@equinor/fusion-framework-cli 12.3.9 → 13.0.0-cli-search-index.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/bin/build/cli.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import{createCommand as e,createOption as t,InvalidOptionArgumentError as r,Command as n}from"commander";import o,{fileURLToPath as i}from"node:url";import{resolve as s,dirname as a,join as c}from"node:path";import{readPackageUpSync as l}from"read-package-up";import{ConsoleLogger as d,buildApplication as u,bundleApp as p,FusionEnv as h,resolveDefaultEnv as f,checkApp as m,initializeFramework as g,uploadApplication as y,publishAppConfig as v,generateApplicationConfig as b,AllowedAppTags as $,tagApplication as w,loadAppManifest as E,startAppDevServer as S,startPortalDevServer as P,loadPortalManifest as L,buildPortal as _,bundlePortal as k,uploadPortalBundle as C,tagPortal as N,AllowedPortalTags as I,publishPortalConfig as O,generatePortalConfig as A}from"@equinor/fusion-framework-cli/bin";import{mkdir as T,writeFile as x}from"node:fs/promises";import{accessSync as D,constants as j,readFileSync as R,writeFileSync as F,rmSync as M,existsSync as G,readdirSync as U,copyFileSync as B,cpSync as z,mkdirSync as H}from"node:fs";import V from"node:assert";import W from"inquirer";import q from"is-path-inside";import{execa as K,ExecaError as Y}from"execa";import{spawn as J,execSync as X}from"node:child_process";import{tmpdir as Z,homedir as Q}from"node:os";import{simpleGit as ee,ResetMode as te}from"simple-git";import{z as re}from"zod";import ne from"url";import oe from"node:module";import ie from"util";import{importConfig as se,importJSON as ae}from"@equinor/fusion-imports";import"deepmerge";const ce=(e=0)=>t=>`[${t+e}m`,le=(e=0)=>t=>`[${38+e};5;${t}m`,de=(e=0)=>(t,r,n)=>`[${38+e};2;${t};${r};${n}m`,ue={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]}};Object.keys(ue.modifier);Object.keys(ue.color),Object.keys(ue.bgColor);const pe=function(){const e=new Map;for(const[t,r]of Object.entries(ue)){for(const[t,n]of Object.entries(r))ue[t]={open:`[${n[0]}m`,close:`[${n[1]}m`},r[t]=ue[t],e.set(n[0],n[1]);Object.defineProperty(ue,t,{value:r,enumerable:!1})}return Object.defineProperty(ue,"codes",{value:e,enumerable:!1}),ue.color.close="",ue.bgColor.close="",ue.color.ansi=ce(),ue.color.ansi256=le(),ue.color.ansi16m=de(),ue.bgColor.ansi=ce(10),ue.bgColor.ansi256=le(10),ue.bgColor.ansi16m=de(10),Object.defineProperties(ue,{rgbToAnsi256:{value:(e,t,r)=>e===t&&t===r?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(r/255*5),enumerable:!1},hexToRgb:{value(e){const t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[r]=t;3===r.length&&(r=[...r].map(e=>e+e).join(""));const n=Number.parseInt(r,16);return[n>>16&255,n>>8&255,255&n]},enumerable:!1},hexToAnsi256:{value:e=>ue.rgbToAnsi256(...ue.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return e-8+90;let t,r,n;if(e>=232)t=(10*(e-232)+8)/255,r=t,n=t;else{const o=(e-=16)%36;t=Math.floor(e/36)/5,r=Math.floor(o/6)/5,n=o%6/5}const o=2*Math.max(t,r,n);if(0===o)return 30;let i=30+(Math.round(n)<<2|Math.round(r)<<1|Math.round(t));return 2===o&&(i+=60),i},enumerable:!1},rgbToAnsi:{value:(e,t,r)=>ue.ansi256ToAnsi(ue.rgbToAnsi256(e,t,r)),enumerable:!1},hexToAnsi:{value:e=>ue.ansi256ToAnsi(ue.hexToAnsi256(e)),enumerable:!1}}),ue}(),he=(()=>{if(!("navigator"in globalThis))return 0;if(globalThis.navigator.userAgentData){const e=navigator.userAgentData.brands.find(({brand:e})=>"Chromium"===e);if(e&&e.version>93)return 3}return/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)?1:0})(),fe=0!==he&&{level:he},me={stdout:fe,stderr:fe};function ge(e,t,r){let n=e.indexOf(t);if(-1===n)return e;const o=t.length;let i=0,s="";do{s+=e.slice(i,n)+t+r,i=n+o,n=e.indexOf(t,i)}while(-1!==n);return s+=e.slice(i),s}const{stdout:ye,stderr:ve}=me,be=Symbol("GENERATOR"),$e=Symbol("STYLER"),we=Symbol("IS_EMPTY"),Ee=["ansi","ansi","ansi256","ansi16m"],Se=Object.create(null),Pe=e=>{const t=(...e)=>e.join(" ");return((e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const r=ye?ye.level:0;e.level=void 0===t.level?r:t.level})(t,e),Object.setPrototypeOf(t,Le.prototype),t};function Le(e){return Pe(e)}Object.setPrototypeOf(Le.prototype,Function.prototype);for(const[e,t]of Object.entries(pe))Se[e]={get(){const r=Ie(this,Ne(t.open,t.close,this[$e]),this[we]);return Object.defineProperty(this,e,{value:r}),r}};Se.visible={get(){const e=Ie(this,this[$e],!0);return Object.defineProperty(this,"visible",{value:e}),e}};const _e=(e,t,r,...n)=>"rgb"===e?"ansi16m"===t?pe[r].ansi16m(...n):"ansi256"===t?pe[r].ansi256(pe.rgbToAnsi256(...n)):pe[r].ansi(pe.rgbToAnsi(...n)):"hex"===e?_e("rgb",t,r,...pe.hexToRgb(...n)):pe[r][e](...n),ke=["rgb","hex","ansi256"];for(const e of ke){Se[e]={get(){const{level:t}=this;return function(...r){const n=Ne(_e(e,Ee[t],"color",...r),pe.color.close,this[$e]);return Ie(this,n,this[we])}}};Se["bg"+e[0].toUpperCase()+e.slice(1)]={get(){const{level:t}=this;return function(...r){const n=Ne(_e(e,Ee[t],"bgColor",...r),pe.bgColor.close,this[$e]);return Ie(this,n,this[we])}}}}const Ce=Object.defineProperties(()=>{},{...Se,level:{enumerable:!0,get(){return this[be].level},set(e){this[be].level=e}}}),Ne=(e,t,r)=>{let n,o;return void 0===r?(n=e,o=t):(n=r.openAll+e,o=t+r.closeAll),{open:e,close:t,openAll:n,closeAll:o,parent:r}},Ie=(e,t,r)=>{const n=(...e)=>Oe(n,1===e.length?""+e[0]:e.join(" "));return Object.setPrototypeOf(n,Ce),n[be]=e,n[$e]=t,n[we]=r,n},Oe=(e,t)=>{if(e.level<=0||!t)return e[we]?"":t;let r=e[$e];if(void 0===r)return t;const{openAll:n,closeAll:o}=r;if(t.includes(""))for(;void 0!==r;)t=ge(t,r.close,r.open),r=r.parent;const i=t.indexOf("\n");return-1!==i&&(t=function(e,t,r,n){let o=0,i="";do{const s="\r"===e[n-1];i+=e.slice(o,s?n-1:n)+t+(s?"\r\n":"\n")+r,o=n+1,n=e.indexOf("\n",o)}while(-1!==n);return i+=e.slice(o),i}(t,o,n,i)),n+t+o};Object.defineProperties(Le.prototype,Se);const Ae=Le();Le({level:ve?ve.level:0});const Te=e("build").description("Build the application").addHelpText("after",["","If no manifest is provided, searches for a default app.manifest(.$ENV)?.[ts|js|json] in the current directory.","example: `ffc app build --env prod` will search for `app.manifest.prod.ts` then fallback to `app.manifest.ts`","","NOTE: app manifest is not required, a default manifest will be generated if not provided","","OUTPUT LOCATION:"," The build output location is determined by the `main` field in your package.json.",' - "main": "dist/index.js" → outputs to dist/index.js',' - "main": "build/app.js" → outputs to build/app.js'," - No main field → defaults to dist/bundle.js"," Output directory cannot be project root, src/, or current working directory.","","Examples:"," $ ffc app build"," $ ffc app build app.manifest.dev.ts --debug"].join("\n")).option("-d, --debug","Enable debug mode for verbose logging",!1).argument("[manifest]","Manifest file to use for building (e.g., app.manifest.ts)").action(async(e,t)=>{const r=new d("app:build",{debug:t.debug});await u({log:r,manifest:e})}),xe="app-bundle.zip",De=e("pack").description("Create a distributable app bundle of the application.").addHelpText("after",["","If no manifest is provided, a default app.manifest(.$ENV)?.[ts|js|json] is used from the current directory.","example: `ffc app pack --env prod` will search for `app.manifest.prod.ts` then fallback to `app.manifest.ts`","","NOTE: app manifest is not required, a default manifest will be generated if not provided","","Examples:"," $ ffc app pack"," $ ffc app pack app.manifest.dev.ts --archive my-app.zip --output ./dist"].join("\n")).option("-a, --archive [string]","Name of the output archive file (default: app-bundle.zip)",xe).option("-o, --output [string]","Directory where the archive will be saved (default: current working directory)",process.cwd()).option("-d, --debug","Enable debug mode for verbose logging",!1).argument("[manifest]","Manifest file to use for bundling (e.g., app.manifest.ts)").action(async(e,t)=>{const r=new d("app:pack",{debug:t.debug});await p({log:r,manifest:e,archive:t.archive}).catch(e=>{r.error("Failed to create package:",e),process.exit(1)})}),je=e=>{const r=Object.values(h).filter(t=>t!==h.Development||e.allowDev);return t("-e, --env <string>",`Set environment [${r.join(", ")}, custom].`).env("FUSION_ENV").default(e.default??f(e.allowDev))};je({allowDev:!0});const Re=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Fe=t("--tenantId <string>","The Azure Active Directory tenant ID").env("FUSION_TENANT_ID").default("3aa4a235-b6e2-48d5-9195-7fcf05b459b0"),Me=t("--clientId <string>","The client ID of the application registered in Azure AD").env("FUSION_CLIENT_ID").default("a318b8e1-0295-4e17-98d5-35f67dfeba14"),Ge=t("--token <string>","The Azure AD access token. If provided, the --tenant and --client options are ignored").env("FUSION_TOKEN").default(void 0),Ue=t("--scope <scopes...>","Azure audience scope, normally the application ID URI of the API you want to access and `.default`").env("FUSION_AUTH_SCOPE").default(["5a842df8-3238-415d-b168-9f16a6a6031b/.default"]),Be=(e,t)=>(e.addOption(Fe),e.addOption(Me),t?.excludeToken||e.addOption(Ge),t?.includeScope&&e.addOption(Ue),e.hook("preAction",e=>{const n=e.opts();if(n.token){if("string"!=typeof n.token||""===n.token.trim())throw new r("Token must be a non-empty string.");return e.setOptionValue("tenantId",void 0),e.setOptionValue("clientId",void 0),void(t?.includeScope&&e.setOptionValue("scope",void 0))}if(!n.tenantId||"string"!=typeof n.tenantId)throw new r("Tenant ID must be a non-empty string.");if(!Re.test(n.tenantId))throw new r("Tenant ID must be a valid UUID.");if(!n.clientId||"string"!=typeof n.clientId)throw new r("Client ID must be a non-empty string.");if(!Re.test(n.clientId))throw new r("Client ID must be a valid UUID.");if(t?.includeScope){if(!Array.isArray(n.scope)||0===n.scope.length)throw new r("Scope must be a non-empty array of strings.");for(const e of n.scope)if("string"!=typeof e||""===e.trim())throw new r("Each scope must be a non-empty string.")}}),e),ze=Be(e("check").description("Check if application is registered in Fusion app store.").addHelpText("after",["","Verifies the registration status of your application in the Fusion app store.","Helps identify issues with app registration or configuration.","","FIRST TIME SETUP:"," Before checking app status, ensure your app is registered in the Fusion App Admin."," The check command will tell you if your app is properly registered.","","Examples:"," $ ffc app check"," $ ffc app check --env prod --debug"].join("\n")).option("-d, --debug","debug mode",!1).addOption(je({allowDev:!1})).action(async e=>{const t=new d("app:check",{debug:!!e.debug});await m({log:t,environment:e.env,auth:"token"in e?{token:e.token}:e})})),He=Be(e("upload").description("Upload a Fusion application bundle to the Fusion App Store.").addHelpText("after",["","Uploads a distributable application bundle (e.g., app-bundle.zip) to the Fusion app store.","","Examples:"," $ ffc app upload"," $ ffc app upload --env ci"," $ ffc app upload my-app-bundle.zip --appKey my-app"," $ ffc app upload --debug"].join("\n")).option("-d, --debug [boolean]","Enable debug mode for verbose logging",!1).option("-k, --appKey <string>","Application key (if not provided, resolved from the build metadata of the bundle)").addOption(je({allowDev:!1})).argument("[bundle]","Application bundle to upload",xe).action(async(e,t)=>{const r=new d("portal:upload",{debug:t.debug});await m({log:r,environment:t.env,auth:"token"in t?{token:t.token}:t})||(r.error("😢 App is not registered / deleted in app store"),process.exit(1)),r?.start("💾 Initializing Fusion Framework...");const n=await g({env:t.env,auth:{token:t.token,tenantId:t.tenantId,clientId:t.clientId}});r?.succeed("💾 Initialized Fusion Framework"),await y({log:r,appKey:t.appKey,framework:n,fileOrBundle:e}).catch(e=>{r.error("😢 Failed to upload bundle:",e),process.exit(1)})})),Ve=Be(e("config").description("Generate or publish the Fusion application configuration object.").addHelpText("after",["","By default, outputs the generated config object to stdout or a file. Use --publish to upload the config to the Fusion app registry.","- Options [--token, --tenantId, --clientId, --manifest] are only relevant when --publish is used.",'- Option [-e, --env] cannot be set to "dev" when --publish is used.',"","Note:","- If not `app.config(.$ENV)?.[ts|js|json]` is found it will fallback to generate a default config (empty object)","- If not `app.manifest(.$ENV)?.[ts|js|json]` is found it will fallback to generate a default manifest","","Examples:"," $ ffc app config app.config.ts"," $ ffc app config app.config.prod.ts --output ./dist/app.config.json"," $ ffc app config app.manifest.prod.ts --silent > ./dist/app.config.json"," $ ffc app config --publish --manifest app.manifest.ts --env prod"," $ ffc app config --env prod my-custom.config.ts"].join("\n")).option("--debug","Enable debug mode for verbose logging").option("--silent","Silent mode, suppresses output except errors").option("--publish","Publish config to Fusion app registry").option("--manifest <path>","Path to the app manifest file (required with --publish)").addOption(je({allowDev:!0})).option("-o, --output <stdout|path>","Output the result to stdout or a file (ignored with --publish, default: stdout)","stdout").argument("[config]","Config build file to use (e.g., app.config[.env]?.[ts,js,json])").action(async(e,t)=>{const r=t.silent?null:new d("app:config",{debug:!!t.debug});if(t.publish)return"dev"===t.env&&(r?.fail("🤪",Ae.blue("--env"),'cannot be "dev" when',Ae.blue("--publish")," is used"),process.exit(1)),v({config:e,manifest:t.manifest,environment:t.env,auth:"token"in t?{token:t.token}:t,debug:t.debug});const{config:n}=await b({log:r,config:e,env:{environment:t.env},output:"stdout"===t.output?void 0:t.output});"stdout"===t.output&&console.log(JSON.stringify(n,null,2))}));const We=Be(e("tag").description("Tag your uploaded Fusion Application build version with a specific tag.").addHelpText("after",["","Note: using --package is preferred over --manifest, since no infered compilation is required.","","Examples:"," $ ffc app tag latest"," $ ffc app tag preview --env prod --manifest app.manifest.prod.ts"," $ ffc app tag stable --package my-app@1.2.3"," $ ffc app tag latest --manifest app.manifest.custom.ts"].join("\n")).addOption(je({allowDev:!1})).option("-p, --package [package@version]","Package to tag in format name@version (e.g., my-app@1.0.0)").option("-m, --manifest <string>","Manifest file to use. Note: ignoring if --package is provided").option("--debug","Enable debug mode for verbose logging").option("--silent","Silent mode, suppresses output except errors").argument("<tag>",`Tag to apply (${Object.values($).join(" | ")})`).action(async(e,t)=>{const r=t.silent?null:new d("app:tag",{debug:t.debug}),n={command:"build",environment:t.env,mode:process.env.NODE_ENV??"production",root:process.cwd()};let o,i;try{({appKey:o,version:i}=await async function(e,t){if(e.package){const[t,r]=e.package.split("@");if(!t||!r)throw new Error("Package must be in format name@version (e.g., my-app@1.0.0). Please verify the package name and version with --package");return{appKey:t,version:r}}const{manifest:r}=await E({manifest:e.manifest,env:t}),n=r.build?.version;if(!n)throw new Error(`Could not determine version from manifest. Please verify manifest ${e.manifest} or provide a package name and version with --package`);return{appKey:r.appKey,version:n}}(t,n))}catch(e){r?.error(`😢 ${e instanceof Error?e.message:"Unknown error occurred"}`),process.exit(1)}r?.info("Tagging application:",Ae.greenBright(`${o}@${i} - ${e}`)),r?.start("Initializing Fusion Framework...");const s=await g({env:t.env,auth:{token:t.token,tenantId:t.tenantId,clientId:t.clientId}});r?.succeed("Initialized Fusion Framework"),r?.start("Tagging application..."),await w({appKey:o,version:i,framework:s,log:r,tag:e}).catch(e=>{r?.error("Failed to tag application:",e),process.exit(1)})})),qe=e("dev").description("Start the application in development mode.").addHelpText("after",["","Configuration:"," dev-server.config.ts Optional configuration file for API mocking, service discovery,"," and development environment customization","","Examples:"," $ ffc app dev"," $ ffc app dev --port 4000"," $ ffc app dev --manifest ./app.manifest.local.ts --config ./app.config.ts"," $ ffc app dev --host 0.0.0.0","","See https://equinor.github.io/fusion-framework/cli/docs/dev-server-config.html for configuration options."].join("\n")).option("--debug","Enable debug mode").option("--manifest <path>","Path to the app manifest file (app.manifest[.env]?.[ts,js,json])").option("--config <path>","Path to the app config file (app.config[.env]?.[ts,js,json])").option("--env <environment>","Runtime environment for the dev server","local").option("--port <port>","Port for the development server","3000").option("--host <host>","Host for the development server").action(async e=>{const t=new d("app:dev",{debug:e.debug});t.start("Starting application in development mode..."),S({log:t,manifest:e.manifest,config:e.config,env:e.env,port:e.port,host:e.host}),t.succeed("Development server started successfully.")}),Ke=(e,t)=>{try{return D(e,j.F_OK),!0}catch(e){return!1}},Ye=e("manifest").description("Build and output the application manifest for Fusion apps.").addHelpText("after",["","By default, outputs the generated manifest object to stdout or a file. Use --output to write to a file.","","Note:","- If not `app.manifest(.$ENV)?.[ts|js|json]` is found it will fallback to generate a default manifest","","Examples:"," $ ffc app manifest"," $ ffc app manifest app.manifest.prod.ts --output ./dist/app.manifest.json",' $ ffc app manifest --silent | jq ".build.entryPoint"'," $ ffc app manifest --debug"].join("\n")).option("-d, --debug","Enable debug mode for verbose logging",!1).option("-o, --output <string>","Output the result to stdout or a file","stdout").option("-s, --silent","Silent mode, suppresses output except errors").argument("[manifest]","Manifest build file to use (e.g., app.manifest[.env]?.[ts,js,json])").action(async(e,t)=>{const r=t.silent?null:new d("app:manifest",{debug:t.debug}),n=await E({log:r,manifest:e});if("stdout"!==t.output){const e=s(process.cwd(),t.output);r?.start("Writing manifest to file",t.output),Ke(a(e))||await T(a(e),{recursive:!0}),await x(e,JSON.stringify(n.manifest,null,2)),r?.succeed("Manifest written to file",e)}else console.log(JSON.stringify(n.manifest,null,2))}),Je=Be(e("publish").description("Deployment: Upload and tag your Fusion application (builds if no bundle provided).").addHelpText("after",["","WHAT THIS COMMAND DOES:"," 1. Builds your application (if no bundle provided)"," 2. Uploads the bundle to Fusion app registry"," 3. Tags the uploaded version for deployment","","If no manifest is provided, a default app.manifest(.$ENV)?.[ts|js|json] is used from the current directory.","example: `ffc app publish --env prod` will search for `app.manifest.prod.ts` then fallback to `app.manifest.ts`","","NOTE: app manifest is not required, a default manifest will be generated if not provided","","FIRST TIME PUBLISHING:"," - Ensure your app is registered in Fusion App Admin"," - Use `ffc app check` first to verify registration status"," - Start with a test environment before production","","Examples:"," $ ffc app publish"," $ ffc app publish --env prod --manifest app.manifest.prod.ts"," $ ffc app publish --tag latest app.bundle.zip"].join("\n")).option("-d, --debug","Enable debug mode for verbose logging",!1).addOption(je({allowDev:!1})).option("-m, --manifest [string]","Manifest file to use for bundling (e.g., app.manifest.ts)").option("-t, --tag [string]",`Tag to apply to the published app (${Object.values($).join(" | ")})`,$.Latest).argument("[bundle]","Path to the app bundle to upload").action(async(e,t)=>{const r=new d("app:publish",{debug:t.debug});let n;if(await m({log:r,environment:t.env,auth:"token"in t?{token:t.token}:t})||(r.error("😢 App is not registered / deleted in app store"),process.exit(1)),e)r.info(`📦 Using provided bundle: ${e}`),n=e;else try{r.start("📦 Bundle application...");n=(await p({log:r,manifest:t.manifest})).archive,r.succeed("📦 Bundle completed")}catch(e){r.error("😢 Failed to bundle application:",e),process.exit(1)}n||(r.error("😢 No bundle provided or created. Please specify a bundle file."),process.exit(1)),r?.start("💾 Initializing Fusion Framework...");const o=await g({env:t.env,auth:{token:t.token,tenantId:t.tenantId,clientId:t.clientId}});r?.succeed("💾 Initialized Fusion Framework"),r.start("🚀 Uploading application...");const i=await y({log:r,framework:o,fileOrBundle:n}).catch(e=>{r.error("😢 Failed to upload bundle:",e),process.exit(1)});r.succeed("🚀 Upload completed"),r.debug("Upload result:",i),r.start("🏷️ Tagging application...");const s=await w({tag:t.tag,appKey:i.name,version:i.version,log:r,framework:o}).catch(e=>{r.error("😢 Failed to tag application:",e),process.exit(1)});r.succeed("Tagging completed"),r.debug("Tagging result:",s)}));async function Xe(e,t="https://registry.npmjs.org"){const r=await async function(e,t="https://registry.npmjs.org"){try{const r=await fetch(`${t}/${e}`);if(!r.ok)throw new Error(`Failed to fetch package info for ${e}: ${r.statusText}`);const n=await r.json();if(!n.name)throw new Error(`Invalid package data received for ${e}`);const o=n["dist-tags"]?.latest;if(!o)throw new Error(`No latest version found for package ${e}`);return{name:n.name,latest:o,versions:Object.keys(n.versions||{}),"dist-tags":n["dist-tags"]||{},description:n.description,homepage:n.homepage,repository:n.repository,author:n.author,license:n.license,keywords:n.keywords,dependencies:n.dependencies,devDependencies:n.devDependencies,peerDependencies:n.peerDependencies}}catch(t){throw new Error(`Failed to fetch package info for ${e}: ${t instanceof Error?t.message:String(t)}`)}}(e,t);return r.latest}async function Ze(e,t){const r=[{key:"dependencies",deps:e.dependencies},{key:"devDependencies",deps:e.devDependencies},{key:"peerDependencies",deps:e.peerDependencies}].filter(e=>void 0!==e.deps&&null!==e.deps);if(0!==r.length){t?.start(`Resolving workspace dependencies for ${r.length} dependency types`);try{const n=await Promise.all(r.map(({key:e,deps:r})=>async function(e,t,r){try{const n=Object.entries(t).filter(e=>{return"string"==typeof(t=e[1])&&t.startsWith("workspace:");var t});if(0===n.length)return r?.debug(`No workspace dependencies found in ${e}`),{key:e,resolved:t};r?.debug(`Resolving ${n.length} workspace dependencies for ${e}`);const o=await Promise.all(n.map(async([e,t])=>{try{const n=await Xe(e);return r?.debug(`Resolved ${e}: ${t} -> ${n}`),[e,n]}catch(n){const o=n instanceof Error?n.message:String(n);return r?.debug(`Failed to resolve ${e}: ${o}`),[e,t]}})),i={...t};for(const[e,t]of o)i[e]=t;return r?.debug(`Successfully processed ${e} with ${o.length} resolved dependencies`),{key:e,resolved:i}}catch(n){const o=n instanceof Error?n.message:String(n);return r?.debug(`Error processing ${e}: ${o}`),{key:e,resolved:t}}}(e,r,t)));for(const{key:t,resolved:r}of n)e[t]=r;const o=n.reduce((e,{resolved:t})=>e+Object.keys(t).length,0);t?.succeed(`Workspace dependencies resolved successfully (${o} total dependencies processed)`)}catch(e){const r=e instanceof Error?e.message:String(e);throw t?.debug(`Error details: ${r}`),new Error(`Failed to resolve workspace dependencies: ${r}`)}}else t?.debug("No dependencies found to resolve")}function Qe(e,t){if("string"!=typeof e||""===e.trim())throw new Error("Target path must be a non-empty string");const r=s(e);if(t){const e=s(t);if(!q(r,e))throw new Error("The target path must be within the specified base directory. Please specify a relative path or ensure the absolute path is within the base directory.")}return r}function et(e,t,r){const n=Qe(e,r);M(n,t)}const tt=["code","cursor"];async function rt(e,t){t.info("By selecting an IDE, it will be opened in a new window."),t.info("👋 please come back to this terminal to continue."),t.info(`You can also open the project in your IDE later by typing e.g. \`code ${e}\` in the terminal.`),t.info("If you do not want to open the project in an IDE, select no.");const{openInIDE:r}=await W.prompt([{type:"list",name:"openInIDE",message:"🚀 Open project in IDE?",default:!1,choices:[{name:"VS Code",value:"code"},{name:"Cursor",value:"cursor"},{name:"No, I will open the project in my IDE later",value:!1}]}]);if(r){if(!function(e){return tt.includes(e)}(r))return void t.error(`Invalid IDE command: ${r}. Only supported IDEs are: ${tt.join(", ")}`);try{const n=K(r,[e],{stdio:"pipe",detached:!0});n.unref(),n.catch(e=>{void 0!==e.exitCode&&0!==e.exitCode?t.error(`IDE process exited with code ${e.exitCode}. The IDE may not have opened successfully.`):t.error(`Failed to open IDE (${r}): ${e.message}`)})}catch(e){t.error(`Failed to spawn IDE process (${r}): ${e instanceof Error?e.message:String(e)}`)}}}const nt=["npm","pnpm"];async function ot(e,t){const{installDeps:r}=await W.prompt([{type:"confirm",name:"installDeps",message:"📦 Install dependencies?",default:!0}]);if(!r)return t.debug("Skipping dependency installation"),{installed:!1};const{packageManager:n}=await W.prompt([{type:"list",name:"packageManager",message:"📦 Which package manager do you want to use?",choices:["pnpm","npm"],default:"pnpm"}]);return await async function(e,t,r){V(nt.includes(t),"Package manager must be npm or pnpm"),r?.start("Installing dependencies...");try{return await K(t,["install"],{cwd:e,stdio:"inherit",shell:!0}),r?.succeed("Dependencies installed successfully!"),t}catch(e){if(e instanceof Y&&0!==e.exitCode)throw r?.error(`${t} install failed with exit code ${e.exitCode}`),new Error(`${t} install failed with exit code ${e.exitCode}`);throw r?.error(`Failed to run ${t} install: ${e instanceof Error?e.message:String(e)}`),e}}(e,n,t),{installed:!0,packageManager:n}}class it{#e;#t;#r;get name(){return this.#e.name}get description(){return this.#e.description}get resources(){return this.#e.resources}constructor(e,t,r){this.#e=e,this.#r=t,this.#t=r.logger}copyTo(e){this.#t?.debug(`Copying template resources to ${e}`);for(const t of this.#e.resources){this.#t?.debug(`Copying resource ${t.path}`,{resource:t});const r=c(this.#r,t.path),n=c(e,t.target??t.path);if(G(r))try{"file"===t.type?(B(r,n),this.#t?.debug(`Copied file: ${t.path} -> ${n}`)):"dir"===t.type?(z(r,n,{recursive:t.recursive??!1}),this.#t?.debug(`Copied directory: ${t.path} -> ${n}`)):this.#t?.debug("Resource is not a file or directory, skipping",{resource:t})}catch(e){throw this.#t?.error(`Failed to copy resource ${t.path}:`,e),e}else this.#t?.warn(`Source resource does not exist, skipping: ${r}`)}}}const st=re.object({type:re.literal("file"),path:re.string(),target:re.string().optional()}),at=re.object({type:re.literal("dir"),path:re.string(),target:re.string().optional(),recursive:re.boolean().optional()}),ct=re.discriminatedUnion("type",[st,at]),lt=re.object({name:re.string(),description:re.string(),resources:re.array(ct)}),dt=re.object({templates:re.array(lt),resources:re.array(ct).optional()});class ut{repo;#n=!1;#o;#i;#s;#a;#c;get protocol(){return this.#a}set protocol(e){V("https"===e||"ssh"===e,"Protocol must be either https or ssh"),this.#a=e}get branch(){return this.#c}get repoUrl(){return"ssh"===this.#a?`git@github.com:${this.repo}.git`:`https://github.com/${this.repo}.git`}set branch(e){this.#c=e,this.#n&&this._checkoutBranch()}constructor(e,t){this.repo=e,this.#i=t.baseDir??c(Z(),"ffc","repo",e),this.#s=t.log,this.#c=t.branch??"main",this.#o=ee(),this.#a=t.protocol??"https"}async initialize(){if(!this.#n)try{if(this.#s?.debug("Checking if repository directory exists...",this.#i),G(this.#i)||(this.#s?.info("Repository directory does not exist, creating..."),H(this.#i,{recursive:!0}),this.#s?.succeed("Repository directory created successfully!")),this.#o=ee({baseDir:this.#i}),this._setupOutputHandler(),!this.#a)try{const e=await this.#o.getConfig("core.sshCommand");this.#a=e?"ssh":"https"}catch{this.#a="https"}this.#s?.debug("Checking if repository is initialized...");await this.#o.checkIsRepo()?(this.#s?.info("Git is initialized, checking out branch..."),await this._checkoutBranch(),this.#s?.succeed("Branch checked out successfully!")):(this.#s?.info("Git is not initialized, cloning repo..."),await this._cloneRepo(),this.#s?.succeed("Repo cloned successfully!")),this.#s?.succeed("Repository initialized successfully!"),this.#n=!0}catch(e){throw this.#s?.fail("Repository initialization failed!"),this.#s?.error(e),e}}async getAvailableTemplates(){let e;try{const t=c(this.#i,"templates.json");this.#s?.debug("Reading template manifest file...",t),e=R(t,"utf8")}catch(e){throw new Error("Failed to read templates.json file from the root of the repository...",{cause:e})}try{this.#s?.debug("Parsing and validating template content...");const t=function(e){try{const t=JSON.parse(e);return dt.parse(t)}catch(e){if(e instanceof re.ZodError)throw new Error(`Template manifest validation failed: ${e.message}`);throw new Error(`Failed to parse JSON: ${e instanceof Error?e.message:"Unknown error"}`)}}(e);this.#s?.debug("Parsed template content...",t);return t.templates.map(e=>{const r=[...t.resources??[],...e.resources];return new it({...e,resources:r},this.#i,{logger:this.#s})})}catch(e){throw new Error("Failed to parse templates.json content",{cause:e})}}async cleanup(){try{this.#s?.debug(`Removing repository directory: ${this.#i}`);return et(Qe(this.#i,Z()),{recursive:!0,force:!0},Z()),this.#s?.succeed("Repository directory cleaned up successfully!"),this.#n=!1,!0}catch(e){return this.#s?.error(`Failed to remove repository directory: ${this.#i}`,e),!1}}async _cloneRepo(){try{this.#s?.debug("Cloning repo...",{repo:this.repo,repoUrl:this.repoUrl,baseDir:this.#i,branch:this.#c,protocol:this.#a}),await this.#o.clone(this.repoUrl,this.#i,["--single-branch","--branch",this.#c])}catch(e){throw new Error("Failed to clone repo...",{cause:e})}}async _checkoutBranch(){try{this.#s?.debug("Fetching repo...",{repo:this.repo,repoUrl:this.repoUrl}),await this.#o.fetch(),this.#s?.debug("Checking out branch...",this.#c);(await this.#o.checkout(this.#c)).includes("branch is up to date")?this.#s?.debug("Branch is up to date!"):(this.#s?.info("Branch is not up to date, updating to latest changes..."),await this.#o.reset(te.HARD).pull(),this.#s?.debug("Branch updated successfully!"))}catch(e){throw new Error("Failed to checkout branch...",{cause:e})}}_setupOutputHandler(){this.#o.outputHandler((e,t,r)=>{t.on("data",e=>{this.#s?.debug("🐙",String(e))}),r.on("data",e=>{this.#s?.error("🐙",String(e))})})}}const pt=[".rsa",".ed25519",".ecdsa",".dsa"],ht=/(_rsa|_ed25519|_ecdsa|_dsa)$/,ft=new Set(["known_hosts","config","authorized_keys","authorized_keys2","ssh_config","ssh_known_hosts"]);function mt(e){if(e.endsWith(".pub"))return!1;if(ft.has(e))return!1;const t=e.startsWith("id_"),r=pt.some(t=>e.endsWith(t)),n=ht.test(e);return t||r||n}async function gt(e){e?.debug("Detecting SSH configuration...");const t=function(){try{return X("git config core.sshCommand",{stdio:"ignore"}),!0}catch{return!1}}()||function(e){try{const t=c(Q(),".ssh");if(!G(t))return!1;for(const r of U(t,{withFileTypes:!0}))if(r.isFile()&&mt(r.name))return e?.debug("SSH private key detected in .ssh directory"),!0;return!1}catch{return!1}}(e);t&&e?.debug("SSH configuration detected");const r=t?void 0:"SSH not configured (no SSH keys or git config found)",{selectedProtocol:n}=await W.prompt([{type:"list",name:"selectedProtocol",message:"🔐 Which Git protocol would you like to use for cloning?",choices:[{name:"HTTPS - Works with personal access tokens and is generally more compatible",value:"https",short:"HTTPS"},{name:"SSH - Faster and more secure, but requires SSH key setup",value:"ssh",short:"SSH",disabled:r}],default:t?"ssh":"https",pageSize:5,loop:!1}]);return e?.debug(`Selected protocol: ${n}`),n}async function yt(e,t,r){V(!!e,"App name is required"),V(G(t.directory),`Directory '${t.directory}' does not exist, use -d to specify a different directory`);const n=s(t.directory,e);r.debug(`Target dir: ${n}`);const o=await async function(e,t,r=!1,n=process.cwd()){let o;V("string"==typeof e,"Target directory must be a string");try{o=Qe(e,n)}catch(e){const r=e instanceof Error?e.message:String(e);return t.error(`❌ Invalid target directory path: ${r}`),t.info('💡 Try using a relative path like "my-app" or ensure the absolute path is within the specified directory.'),!1}if(!G(o))return t.debug(`Target directory does not exist: ${o}`),!0;try{const e=U(o);if(0===e.length)return t.debug(`Target directory is empty: ${o}`),!0;if(t.warn(`Target directory '${o}' is not empty and contains ${e.length} item(s).`),t.info("Contents:",e.slice(0,10).join(", ")+(e.length>10?"...":"")),r){t.info("Cleaning target directory (--clean flag)...");try{et(o,{recursive:!0,force:!0},n),t.succeed("Target directory cleaned successfully!")}catch(e){throw t.error(`Failed to clean target directory: ${e}`),t.info("Check directory permissions and ensure you have write access to the directory."),t.info("You may need to run the command with elevated privileges or manually remove the files."),e}}else{const{action:e}=await W.prompt([{type:"list",name:"action",message:"What would you like to do?",choices:[{name:"Continue - Add files to existing directory",value:"continue"},{name:"Clean - Remove all existing files and continue",value:"clean"},{name:"Abort - Cancel the operation",value:"abort"}],default:"abort"}]);if("abort"===e)return t.info("Operation cancelled by user."),!1;if("clean"===e){t.info("Cleaning target directory...");try{et(o,{recursive:!0,force:!0},n),t.succeed("Target directory cleaned successfully!")}catch(e){throw t.error(`Failed to clean target directory: ${e}`),t.info("Check directory permissions and ensure you have write access to the directory."),t.info("You may need to run the command with elevated privileges or manually remove the files."),e}}else t.info("Continuing with existing directory...")}return!0}catch(e){throw t.error(`Failed to check target directory: ${e}`),t.info("Ensure the path is valid and accessible, and that you have read permissions for the directory."),t.info("Check if the directory path contains any invalid characters or if the path is too long."),e}}(n,r,t.clean,t.directory);o||process.exit(0);const i=await async function(e,t,r,n){const o=s(Z(),"ffc","repo",e);if(n.debug(`Repo dir: ${o}`),t){n.debug(`Removing repo dir: ${o}`);try{et(Qe(o,Z()),{recursive:!0,force:!0},Z())}catch(e){n.debug("Cleanup failed:",e)}}const i=await gt(n),a=new ut(e,{baseDir:o,log:n,branch:r,protocol:i});return await a.initialize(),a}("equinor/fusion-app-template",t.clean,t.branch,r),a=await i.getAvailableTemplates(),l=await async function(e,t,r){V(Array.isArray(e),"Templates must be an array"),V(e.length>0,"No templates available");const n=e.map(e=>e.name);if(t){V("string"==typeof t,"Pre-selected template must be a string"),V(n.includes(t),"Pre-selected template must be in the list of available templates"),r?.debug(`Using pre-selected template: ${t}`);const o=e.find(e=>e.name===t);return V(o,"Pre-selected template not found"),o}if(1===e.length)return r?.debug(`Using single template: ${e[0].name}`),e[0];const{selectedTemplate:o}=await W.prompt([{type:"list",name:"selectedTemplate",message:"🎨 Please select a template:",choices:e.map(e=>({name:`${e.name} - ${e.description}`,value:e})),pageSize:10,loop:!1}]);return o}(a,t.template,r);try{await l.copyTo(n),r.succeed("Template resources copied successfully!")}catch(e){r.error(`Failed to copy template resources: ${e instanceof Error?e.message:String(e)}`),r.info("Please check the target directory permissions and try again"),process.exit(1)}try{await(async(e,t,r)=>{const n=c(e,"package.json");try{const e=R(n,"utf-8"),o=JSON.parse(e);let i={...o};if(t?.resolveWorkspaceDependencies){r?.debug("Resolving workspace dependencies");const e=JSON.parse(JSON.stringify(o));await Ze(e,r),i=e}t?.updates&&(r?.debug(`Applying updates: ${Object.keys(t.updates).join(", ")}`),i={...i,...t.updates}),JSON.stringify(o)!==JSON.stringify(i)?(r?.debug("Writing updated package.json to disk"),F(n,`${JSON.stringify(i,null,2)}\n`)):r?.debug("No changes detected, skipping package.json update")}catch(e){throw new Error(`Failed to update package.json: ${e instanceof Error?e.message:String(e)}`)}})(n,{updates:{name:e},resolveWorkspaceDependencies:!0},r),r.succeed(`Updated package.json with app name: ${e}`)}catch(e){r.error(`Failed to update package.json: ${e instanceof Error?e.message:String(e)}`),r.info("Please check the package.json file and try again"),process.exit(1)}await async function(e,t){const{cleanupTempFiles:r}=await W.prompt([{type:"confirm",name:"cleanupTempFiles",message:"🗑️ Clean up temporary template files?",default:!1}]);r?await e.cleanup():t.debug("Skipping cleanup of temporary template files")}(i,r),await rt(n,r);const{installed:d,packageManager:u}=await ot(n,r);if(d&&u){const e=await async function(e,t,r,n=!1){const{startDev:o}=await W.prompt([{type:"confirm",name:"startDev",message:"🚀 Start development server?",default:!0}]);if(o){r.debug(`Starting development server: ${e}`),n&&r.info("Running in persistent mode - server will run until manually stopped (Ctrl+C)");try{const o=J(t,["run","dev"],{cwd:e,stdio:"inherit"});let i=null,s=!1;if(!n){const e=6e4;i=setTimeout(()=>{s=!0,r.error(`Development server did not start within ${e/1e3} seconds and may be hanging. Terminating process.`),o.kill("SIGTERM"),r.info(`You can try running '${t} run dev' manually in the project directory.`)},e)}const a=()=>{i&&clearTimeout(i),o.removeAllListeners("error"),o.removeAllListeners("exit")};return o.on("error",e=>{a(),s||(r.error(`Failed to start development server with ${t}: ${e.message}`),r.info(`Make sure ${t} is installed and the 'dev' script exists in package.json`))}),o.on("exit",e=>{a(),s||0===e||n?n&&0!==e&&r.info(`Development server stopped with exit code ${e}`):(r.error(`Development server process exited with code ${e}. The server may not have started successfully.`),r.info(`Check the output above for error details or try running '${t} run dev' manually`))}),!0}catch(e){r.error(`Failed to spawn development server process with ${t}: ${e instanceof Error?e.message:String(e)}`),r.info(`Make sure ${t} is installed and the 'dev' script exists in package.json`)}}return!1}(n,u,r,!0);e&&r.debug("Development server started successfully")}}const vt=t=>e(t).description("Create a new Fusion application from template").argument("<name>","Name of the application to create").option("-t, --template <type>","Template type to use (will prompt if not specified or not found)").option("-d, --directory <path>","Directory to create the app in",".").option("--branch <branch>","Branch to checkout","main").option("--clean","Clean the repo directory before cloning").option("--debug","Enable debug mode for verbose logging").action(async(e,t)=>{const r=new d("",{debug:t.debug});try{await yt(e,t,r)}catch(e){r.error("❌ An unexpected error occurred:",e instanceof Error?e.message:String(e)),t.debug&&r.error("Stack trace:",e instanceof Error?e.stack:"No stack trace available"),process.exit(1)}});De.alias("build-pack").hook("preAction",e=>{"build-pack"===process.argv[3]&&(console.warn(Ae.bgRedBright.bold('The command "build-pack" is deprecated. Please use "pack" instead.')),e.getOptionValue("archive")||e.setOptionValue("archive",xe))}),He.alias("build-upload").hook("preAction",e=>{if("build-upload"===process.argv[3]){if(console.warn(Ae.bgRedBright.bold('The command "build-upload" is deprecated. Please use "upload" instead.')),e.getOptionValue("service"))throw new Error("The --service option is deprecated. Please use --env instead.");const t=e.getOptionValue("bundle")??xe;process.argv[4]=t}}),Ye.alias("build-manifest").hook("preAction",()=>{"build-manifest"===process.argv[3]&&console.warn(Ae.bgRedBright.bold('The command "build-manifest" is deprecated. Please use "manifest" instead.'))}),Je.alias("build-publish").hook("preAction",e=>{if("build-publish"===process.argv[3]&&console.warn(Ae.bgRedBright.bold('The command "build-publish" is deprecated. Please use "publish" instead.')),e.getOptionValue("service"))throw new Error("The --service option is deprecated. Please use --env instead.")});const bt=e("app").description("Develop, build, configure, and deploy Fusion applications from your workspace root.").addHelpText("after",["",'The "app" command is your main entry point for managing Fusion applications in this workspace.',"","It provides access to subcommands for every stage of the application lifecycle, including development, building, packaging, configuration, deployment, and release management.","","All available subcommands are listed below automatically. For details and options for a specific subcommand, run:"," fusion app <subcommand> --help","","Typical usage:"," - Create new applications from templates with the create subcommand"," - Run and test your app locally with the dev subcommand"," - Build, bundle, and configure your app for deployment"," - Upload, publish, and tag releases to the Fusion App Store"," - Check registration and generate manifests as needed","","This command should be run from your app root directory."].join("\n")).addCommand(Te).addCommand(De).addCommand(ze).addCommand(He).addCommand(Ve).addCommand(We).addCommand(qe).addCommand(Ye).addCommand(Je).addCommand(vt("create")),$t=e("login").description("Authenticate and log in to Fusion Framework using interactive browser-based authentication.").addHelpText("after",["","WHAT HAPPENS WHEN YOU RUN THIS COMMAND:"," 1. Opens a browser window for Azure AD authentication"," 2. Prompts you to sign in with your Fusion credentials"," 3. Securely caches your tokens for future CLI commands"," 4. You only need to log in once per session","","Note: Requires interactive environment (won't work in CI/CD pipelines)","","Examples:"," $ ffc auth login"," $ ffc auth login --tenant my-tenant --client my-client-id --scope api://my-app/.default"].join("\n")).action(async e=>{const t=new d("auth:login",{debug:e.debug}),r="string"==typeof e.scope?[e.scope]:e.scope;t.start("Initializing Fusion Framework...");const n=await g({auth:{tenantId:e.tenantId,clientId:e.clientId,interactive:!0,server:{port:49741}}});t.succeed("Initialized Fusion Framework");try{t.start("Logging in...");const e=await n.auth.login({scopes:r});t.info("username:",Ae.green(e.account?.username)),t.info("tenant: ",Ae.yellow(e.tenantId)),t.info("audience:",Ae.yellow(e.account?.idTokenClaims?.aud));for(const r of e.scopes)t.info("scope: ",Ae.dim(r));t.succeed("Successfully logged in",Ae.greenBright(e.account?.name))}catch(r){throw t.fail("Failed to log in 🥺",JSON.stringify({tenant:e.tenant,client:e.clientId},void 0,2)),r}});Be($t,{includeScope:!0,excludeToken:!0});const wt=e("logout").description("Log out from Fusion Framework and clear your authentication session.").addHelpText("after",["","WHAT THIS COMMAND DOES:"," - Removes your cached authentication tokens from local storage"," - Clears the current session (does not revoke tokens server-side)"," - You will need to run `ffc auth login` again for future commands","","WHEN TO USE THIS COMMAND:"," - When switching between different user accounts"," - When troubleshooting authentication issues"," - When your cached tokens have expired and you want a fresh login","","Examples:"," $ ffc auth logout"," $ ffc auth logout --tenant my-tenant --client my-client-id"].join("\n")).action(async e=>{const t=new d("auth:logout",{debug:e.debug});t.start("Initializing Fusion Framework...");const r=await g({auth:{tenantId:e.tenantId,clientId:e.clientId}});t.succeed("Initialized Fusion Framework");try{t.start("Logging in..."),await r.auth.logout(),t.succeed("Successfully logged out")}catch(r){throw t.fail("Failed to log out 🥺",JSON.stringify({tenant:e.tenant,client:e.clientId},void 0,2)),r}});Be(wt,{excludeToken:!0,includeScope:!1});class Et extends Error{static Name="NoAccountsError";constructor(e,t){super(e,t),this.name=Et.Name}}const St=e("token").description("Acquire and print an access token for Fusion APIs using your current authentication context.").addHelpText("after",["","USAGE NOTES:"," - This command acquires an access token using your current interactive login session."," - It is intended for local development, manual testing, and debugging authentication issues.","","LIMITATIONS:"," - Requires an interactive user session (not suitable for CI/CD or headless environments)."," - Will only work if you have previously logged in using `ffc auth login`."," - Does NOT prompt for login; if no cached credentials are found, you must log in first."," - For automation or CI/CD, set the FUSION_TOKEN environment variable instead.","","BEST PRACTICES:"," - Use this command to quickly fetch a token for manual API calls or local scripts."," - Use the --silent flag to output only the token (useful for scripting or piping)."," - Specify --scope, --tenant, or --client for advanced scenarios.","","EXAMPLES:"," $ ffc auth token"," $ export MY_TOKEN=$(ffc auth token --silent)"," $ ffc auth token --scope api://my-app/.default"," $ ffc auth token --tenant my-tenant --client my-client-id --silent"].join("\n")).option("-d, --debug","Enable debug mode for verbose logging",!1).option("--silent","Only output the token (no extra logging)").action(async e=>{const t=e.silent?null:new d("auth:token",{debug:e.debug}),r="string"==typeof e.scope?[e.scope]:e.scope;t?.info("Using tenant",e.tenantId),t?.info("Using client",e.clientId),t?.info("Using scope",JSON.stringify(r)),t?.start("Initializing Fusion Framework...");const n=await g({auth:{tenantId:e.tenantId,clientId:e.clientId}});t?.succeed("Initialized Fusion Framework");try{t?.start("Getting access token...");const o=await n.auth.acquireAccessToken({scopes:r});t?.succeed("Successfully acquired access token"),e.silent?console.log(o):t?.info("Access token:",o)}catch(r){if(e.silent||!(r instanceof Et))throw r;t?.fail("No accounts found, please login first")}});Be(St,{includeScope:!0});const Pt=new n("auth").description("Authenticate with Fusion Framework CLI").addHelpText("after",["","Authentication commands for Fusion Framework CLI.","","Use these commands to log in, log out, or acquire tokens for Fusion APIs.","","Examples:"," $ fusion-framework-cli auth login"," $ fusion-framework-cli auth logout"," $ fusion-framework-cli auth token --scope api://my-app/.default"].join("\n"));Pt.addCommand($t,{isDefault:!0}),Pt.addCommand(wt),Pt.addCommand(St);const Lt=e("create").description("Create new Fusion applications and components from templates").addHelpText("after",["",'The "create" command helps you bootstrap new Fusion applications and components',"using predefined templates from the Fusion ecosystem.","","Available templates:"," - app: Create a new Fusion application from the official template","","Examples:"," fusion create app my-new-app"," fusion create app my-new-app --template react",""].join("\n")).addCommand(vt("app")),_t=Be(e("resolve").description("Resolve and display information about a service registered in Fusion service discovery.").addHelpText("after",["","This command looks up a service by name and prints its discovery details using the current authentication and environment.","","USEFUL FOR:"," - Finding service endpoints for API calls"," - Debugging service connectivity issues"," - Getting service metadata and configuration","","OUTPUT FORMATS:"," - Normal: Pretty-printed JSON with service details",' - Silent: Raw JSON only (useful for scripts: --silent | jq ".uri")',"","Examples:"," $ ffc disco resolve my-service",' $ ffc disco resolve my-service --silent | jq ".uri"'," $ ffc disco resolve my-service --env prod"," $ ffc disco resolve my-service --env test --tenantId my-tenant --clientId my-client-id"].join("\n")).addOption(je({allowDev:!1})).option("--silent","Silent mode, suppresses output except errors").argument("<service>","Name of the service to resolve in Fusion service discovery").action(async(e,t)=>{const r=t.silent?null:new d("disco:resolve");r?.start("Initializing Fusion Framework...");const n=await g({env:t.environment,auth:{token:t.token,tenantId:t.tenantId,clientId:t.clientId}});r?.succeed("Initialized Fusion Framework"),r?.start(`Resolving service ${e}...`);const o=await n.serviceDiscovery.resolveService(e);r?.succeed(`Resolved service ${e}`),r?.debug(o),t.silent&&console.log(JSON.stringify(o,null,2))})),kt=e("disco").description("Service discovery operations");kt.addCommand(_t);const Ct=e("dev").description("Start a local development server for the Fusion portal.").addHelpText("after",["","Configuration:"," dev-server.config.ts Optional configuration file for API mocking, service discovery,"," and development environment customization","","Examples:"," $ ffc portal dev"," $ ffc portal dev --port 4000"," $ ffc portal dev --debug","","See https://equinor.github.io/fusion-framework/cli/docs/dev-server-config.html for configuration options."].join("\n")).option("--debug","Enable debug mode").option("--env <environment>","Runtime environment for the dev server","local").option("--port <port>","Port for the development server","3000").action(async e=>{const t=new d("portal:dev",{debug:e.debug});t.start("Starting portal in development mode..."),P({server:{port:Number(e.port)},log:t,env:e.env}),t.succeed("Development server started successfully.")});function Nt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var It,Ot,At,Tt;function xt(){if(Ot)return It;Ot=1;const e="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};return It=e}function Dt(){if(Tt)return At;Tt=1;const e=Number.MAX_SAFE_INTEGER||9007199254740991;return At={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:e,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}}var jt,Rt,Ft,Mt,Gt,Ut,Bt,zt,Ht,Vt,Wt,qt,Kt,Yt={exports:{}};function Jt(){return jt||(jt=1,function(e,t){const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:o}=Dt(),i=xt(),s=(t=e.exports={}).re=[],a=t.safeRe=[],c=t.src=[],l=t.safeSrc=[],d=t.t={};let u=0;const p="[a-zA-Z0-9-]",h=[["\\s",1],["\\d",o],[p,n]],f=(e,t,r)=>{const n=(e=>{for(const[t,r]of h)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e})(t),o=u++;i(e,o,t),d[e]=o,c[o]=t,l[o]=n,s[o]=new RegExp(t,r?"g":void 0),a[o]=new RegExp(n,r?"g":void 0)};f("NUMERICIDENTIFIER","0|[1-9]\\d*"),f("NUMERICIDENTIFIERLOOSE","\\d+"),f("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),f("MAINVERSION",`(${c[d.NUMERICIDENTIFIER]})\\.(${c[d.NUMERICIDENTIFIER]})\\.(${c[d.NUMERICIDENTIFIER]})`),f("MAINVERSIONLOOSE",`(${c[d.NUMERICIDENTIFIERLOOSE]})\\.(${c[d.NUMERICIDENTIFIERLOOSE]})\\.(${c[d.NUMERICIDENTIFIERLOOSE]})`),f("PRERELEASEIDENTIFIER",`(?:${c[d.NONNUMERICIDENTIFIER]}|${c[d.NUMERICIDENTIFIER]})`),f("PRERELEASEIDENTIFIERLOOSE",`(?:${c[d.NONNUMERICIDENTIFIER]}|${c[d.NUMERICIDENTIFIERLOOSE]})`),f("PRERELEASE",`(?:-(${c[d.PRERELEASEIDENTIFIER]}(?:\\.${c[d.PRERELEASEIDENTIFIER]})*))`),f("PRERELEASELOOSE",`(?:-?(${c[d.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[d.PRERELEASEIDENTIFIERLOOSE]})*))`),f("BUILDIDENTIFIER",`${p}+`),f("BUILD",`(?:\\+(${c[d.BUILDIDENTIFIER]}(?:\\.${c[d.BUILDIDENTIFIER]})*))`),f("FULLPLAIN",`v?${c[d.MAINVERSION]}${c[d.PRERELEASE]}?${c[d.BUILD]}?`),f("FULL",`^${c[d.FULLPLAIN]}$`),f("LOOSEPLAIN",`[v=\\s]*${c[d.MAINVERSIONLOOSE]}${c[d.PRERELEASELOOSE]}?${c[d.BUILD]}?`),f("LOOSE",`^${c[d.LOOSEPLAIN]}$`),f("GTLT","((?:<|>)?=?)"),f("XRANGEIDENTIFIERLOOSE",`${c[d.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),f("XRANGEIDENTIFIER",`${c[d.NUMERICIDENTIFIER]}|x|X|\\*`),f("XRANGEPLAIN",`[v=\\s]*(${c[d.XRANGEIDENTIFIER]})(?:\\.(${c[d.XRANGEIDENTIFIER]})(?:\\.(${c[d.XRANGEIDENTIFIER]})(?:${c[d.PRERELEASE]})?${c[d.BUILD]}?)?)?`),f("XRANGEPLAINLOOSE",`[v=\\s]*(${c[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[d.XRANGEIDENTIFIERLOOSE]})(?:${c[d.PRERELEASELOOSE]})?${c[d.BUILD]}?)?)?`),f("XRANGE",`^${c[d.GTLT]}\\s*${c[d.XRANGEPLAIN]}$`),f("XRANGELOOSE",`^${c[d.GTLT]}\\s*${c[d.XRANGEPLAINLOOSE]}$`),f("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),f("COERCE",`${c[d.COERCEPLAIN]}(?:$|[^\\d])`),f("COERCEFULL",c[d.COERCEPLAIN]+`(?:${c[d.PRERELEASE]})?`+`(?:${c[d.BUILD]})?(?:$|[^\\d])`),f("COERCERTL",c[d.COERCE],!0),f("COERCERTLFULL",c[d.COERCEFULL],!0),f("LONETILDE","(?:~>?)"),f("TILDETRIM",`(\\s*)${c[d.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",f("TILDE",`^${c[d.LONETILDE]}${c[d.XRANGEPLAIN]}$`),f("TILDELOOSE",`^${c[d.LONETILDE]}${c[d.XRANGEPLAINLOOSE]}$`),f("LONECARET","(?:\\^)"),f("CARETTRIM",`(\\s*)${c[d.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",f("CARET",`^${c[d.LONECARET]}${c[d.XRANGEPLAIN]}$`),f("CARETLOOSE",`^${c[d.LONECARET]}${c[d.XRANGEPLAINLOOSE]}$`),f("COMPARATORLOOSE",`^${c[d.GTLT]}\\s*(${c[d.LOOSEPLAIN]})$|^$`),f("COMPARATOR",`^${c[d.GTLT]}\\s*(${c[d.FULLPLAIN]})$|^$`),f("COMPARATORTRIM",`(\\s*)${c[d.GTLT]}\\s*(${c[d.LOOSEPLAIN]}|${c[d.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",f("HYPHENRANGE",`^\\s*(${c[d.XRANGEPLAIN]})\\s+-\\s+(${c[d.XRANGEPLAIN]})\\s*$`),f("HYPHENRANGELOOSE",`^\\s*(${c[d.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[d.XRANGEPLAINLOOSE]})\\s*$`),f("STAR","(<|>)?=?\\s*\\*"),f("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),f("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}(Yt,Yt.exports)),Yt.exports}function Xt(){if(Bt)return Ut;Bt=1;const e=xt(),{MAX_LENGTH:t,MAX_SAFE_INTEGER:r}=Dt(),{safeRe:n,t:o}=Jt(),i=function(){if(Ft)return Rt;Ft=1;const e=Object.freeze({loose:!0}),t=Object.freeze({});return Rt=r=>r?"object"!=typeof r?e:r:t}(),{compareIdentifiers:s}=function(){if(Gt)return Mt;Gt=1;const e=/^[0-9]+$/,t=(t,r)=>{if("number"==typeof t&&"number"==typeof r)return t===r?0:t<r?-1:1;const n=e.test(t),o=e.test(r);return n&&o&&(t=+t,r=+r),t===r?0:n&&!o?-1:o&&!n?1:t<r?-1:1};return Mt={compareIdentifiers:t,rcompareIdentifiers:(e,r)=>t(r,e)}}();class a{constructor(s,c){if(c=i(c),s instanceof a){if(s.loose===!!c.loose&&s.includePrerelease===!!c.includePrerelease)return s;s=s.version}else if("string"!=typeof s)throw new TypeError(`Invalid version. Must be a string. Got type "${typeof s}".`);if(s.length>t)throw new TypeError(`version is longer than ${t} characters`);e("SemVer",s,c),this.options=c,this.loose=!!c.loose,this.includePrerelease=!!c.includePrerelease;const l=s.trim().match(c.loose?n[o.LOOSE]:n[o.FULL]);if(!l)throw new TypeError(`Invalid Version: ${s}`);if(this.raw=s,this.major=+l[1],this.minor=+l[2],this.patch=+l[3],this.major>r||this.major<0)throw new TypeError("Invalid major version");if(this.minor>r||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>r||this.patch<0)throw new TypeError("Invalid patch version");l[4]?this.prerelease=l[4].split(".").map(e=>{if(/^[0-9]+$/.test(e)){const t=+e;if(t>=0&&t<r)return t}return e}):this.prerelease=[],this.build=l[5]?l[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(e("SemVer.compare",this.version,this.options,t),!(t instanceof a)){if("string"==typeof t&&t===this.version)return 0;t=new a(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(e){return e instanceof a||(e=new a(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(t){if(t instanceof a||(t=new a(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{const n=this.prerelease[r],o=t.prerelease[r];if(e("prerelease compare",r,n,o),void 0===n&&void 0===o)return 0;if(void 0===o)return 1;if(void 0===n)return-1;if(n!==o)return s(n,o)}while(++r)}compareBuild(t){t instanceof a||(t=new a(t,this.options));let r=0;do{const n=this.build[r],o=t.build[r];if(e("build compare",r,n,o),void 0===n&&void 0===o)return 0;if(void 0===o)return 1;if(void 0===n)return-1;if(n!==o)return s(n,o)}while(++r)}inc(e,t,r){if(e.startsWith("pre")){if(!t&&!1===r)throw new Error("invalid increment argument: identifier is empty");if(t){const e=`-${t}`.match(this.options.loose?n[o.PRERELEASELOOSE]:n[o.PRERELEASE]);if(!e||e[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,r),this.inc("pre",t,r);break;case"prerelease":0===this.prerelease.length&&this.inc("patch",t,r),this.inc("pre",t,r);break;case"release":if(0===this.prerelease.length)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":0===this.minor&&0===this.patch&&0!==this.prerelease.length||this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":0===this.patch&&0!==this.prerelease.length||this.minor++,this.patch=0,this.prerelease=[];break;case"patch":0===this.prerelease.length&&this.patch++,this.prerelease=[];break;case"pre":{const e=Number(r)?1:0;if(0===this.prerelease.length)this.prerelease=[e];else{let n=this.prerelease.length;for(;--n>=0;)"number"==typeof this.prerelease[n]&&(this.prerelease[n]++,n=-2);if(-1===n){if(t===this.prerelease.join(".")&&!1===r)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(e)}}if(t){let n=[t,e];!1===r&&(n=[t]),0===s(this.prerelease[0],t)?isNaN(this.prerelease[1])&&(this.prerelease=n):this.prerelease=n}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return Ut=a}function Zt(){if(Ht)return zt;Ht=1;const e=Xt();return zt=(t,r,n=!1)=>{if(t instanceof e)return t;try{return new e(t,r)}catch(e){if(!n)return null;throw e}}}var Qt,er,tr,rr,nr,or,ir,sr,ar,cr,lr=["0BSD","3D-Slicer-1.0","AAL","ADSL","AFL-1.1","AFL-1.2","AFL-2.0","AFL-2.1","AFL-3.0","AGPL-1.0-only","AGPL-1.0-or-later","AGPL-3.0-only","AGPL-3.0-or-later","AMD-newlib","AMDPLPA","AML","AML-glslang","AMPAS","ANTLR-PD","ANTLR-PD-fallback","APAFML","APL-1.0","APSL-1.0","APSL-1.1","APSL-1.2","APSL-2.0","ASWF-Digital-Assets-1.0","ASWF-Digital-Assets-1.1","Abstyles","AdaCore-doc","Adobe-2006","Adobe-Display-PostScript","Adobe-Glyph","Adobe-Utopia","Afmparse","Aladdin","Apache-1.0","Apache-1.1","Apache-2.0","App-s2p","Arphic-1999","Artistic-1.0","Artistic-1.0-Perl","Artistic-1.0-cl8","Artistic-2.0","Artistic-dist","Aspell-RU","BSD-1-Clause","BSD-2-Clause","BSD-2-Clause-Darwin","BSD-2-Clause-Patent","BSD-2-Clause-Views","BSD-2-Clause-first-lines","BSD-2-Clause-pkgconf-disclaimer","BSD-3-Clause","BSD-3-Clause-Attribution","BSD-3-Clause-Clear","BSD-3-Clause-HP","BSD-3-Clause-LBNL","BSD-3-Clause-Modification","BSD-3-Clause-No-Military-License","BSD-3-Clause-No-Nuclear-License","BSD-3-Clause-No-Nuclear-License-2014","BSD-3-Clause-No-Nuclear-Warranty","BSD-3-Clause-Open-MPI","BSD-3-Clause-Sun","BSD-3-Clause-acpica","BSD-3-Clause-flex","BSD-4-Clause","BSD-4-Clause-Shortened","BSD-4-Clause-UC","BSD-4.3RENO","BSD-4.3TAHOE","BSD-Advertising-Acknowledgement","BSD-Attribution-HPND-disclaimer","BSD-Inferno-Nettverk","BSD-Protection","BSD-Source-Code","BSD-Source-beginning-file","BSD-Systemics","BSD-Systemics-W3Works","BSL-1.0","BUSL-1.1","Baekmuk","Bahyph","Barr","Beerware","BitTorrent-1.0","BitTorrent-1.1","Bitstream-Charter","Bitstream-Vera","BlueOak-1.0.0","Boehm-GC","Boehm-GC-without-fee","Borceux","Brian-Gladman-2-Clause","Brian-Gladman-3-Clause","C-UDA-1.0","CAL-1.0","CAL-1.0-Combined-Work-Exception","CATOSL-1.1","CC-BY-1.0","CC-BY-2.0","CC-BY-2.5","CC-BY-2.5-AU","CC-BY-3.0","CC-BY-3.0-AT","CC-BY-3.0-AU","CC-BY-3.0-DE","CC-BY-3.0-IGO","CC-BY-3.0-NL","CC-BY-3.0-US","CC-BY-4.0","CC-BY-NC-1.0","CC-BY-NC-2.0","CC-BY-NC-2.5","CC-BY-NC-3.0","CC-BY-NC-3.0-DE","CC-BY-NC-4.0","CC-BY-NC-ND-1.0","CC-BY-NC-ND-2.0","CC-BY-NC-ND-2.5","CC-BY-NC-ND-3.0","CC-BY-NC-ND-3.0-DE","CC-BY-NC-ND-3.0-IGO","CC-BY-NC-ND-4.0","CC-BY-NC-SA-1.0","CC-BY-NC-SA-2.0","CC-BY-NC-SA-2.0-DE","CC-BY-NC-SA-2.0-FR","CC-BY-NC-SA-2.0-UK","CC-BY-NC-SA-2.5","CC-BY-NC-SA-3.0","CC-BY-NC-SA-3.0-DE","CC-BY-NC-SA-3.0-IGO","CC-BY-NC-SA-4.0","CC-BY-ND-1.0","CC-BY-ND-2.0","CC-BY-ND-2.5","CC-BY-ND-3.0","CC-BY-ND-3.0-DE","CC-BY-ND-4.0","CC-BY-SA-1.0","CC-BY-SA-2.0","CC-BY-SA-2.0-UK","CC-BY-SA-2.1-JP","CC-BY-SA-2.5","CC-BY-SA-3.0","CC-BY-SA-3.0-AT","CC-BY-SA-3.0-DE","CC-BY-SA-3.0-IGO","CC-BY-SA-4.0","CC-PDDC","CC-PDM-1.0","CC-SA-1.0","CC0-1.0","CDDL-1.0","CDDL-1.1","CDL-1.0","CDLA-Permissive-1.0","CDLA-Permissive-2.0","CDLA-Sharing-1.0","CECILL-1.0","CECILL-1.1","CECILL-2.0","CECILL-2.1","CECILL-B","CECILL-C","CERN-OHL-1.1","CERN-OHL-1.2","CERN-OHL-P-2.0","CERN-OHL-S-2.0","CERN-OHL-W-2.0","CFITSIO","CMU-Mach","CMU-Mach-nodoc","CNRI-Jython","CNRI-Python","CNRI-Python-GPL-Compatible","COIL-1.0","CPAL-1.0","CPL-1.0","CPOL-1.02","CUA-OPL-1.0","Caldera","Caldera-no-preamble","Catharon","ClArtistic","Clips","Community-Spec-1.0","Condor-1.1","Cornell-Lossless-JPEG","Cronyx","Crossword","CryptoSwift","CrystalStacker","Cube","D-FSL-1.0","DEC-3-Clause","DL-DE-BY-2.0","DL-DE-ZERO-2.0","DOC","DRL-1.0","DRL-1.1","DSDP","DocBook-DTD","DocBook-Schema","DocBook-Stylesheet","DocBook-XML","Dotseqn","ECL-1.0","ECL-2.0","EFL-1.0","EFL-2.0","EPICS","EPL-1.0","EPL-2.0","EUDatagrid","EUPL-1.0","EUPL-1.1","EUPL-1.2","Elastic-2.0","Entessa","ErlPL-1.1","Eurosym","FBM","FDK-AAC","FSFAP","FSFAP-no-warranty-disclaimer","FSFUL","FSFULLR","FSFULLRSD","FSFULLRWD","FSL-1.1-ALv2","FSL-1.1-MIT","FTL","Fair","Ferguson-Twofish","Frameworx-1.0","FreeBSD-DOC","FreeImage","Furuseth","GCR-docs","GD","GFDL-1.1-invariants-only","GFDL-1.1-invariants-or-later","GFDL-1.1-no-invariants-only","GFDL-1.1-no-invariants-or-later","GFDL-1.1-only","GFDL-1.1-or-later","GFDL-1.2-invariants-only","GFDL-1.2-invariants-or-later","GFDL-1.2-no-invariants-only","GFDL-1.2-no-invariants-or-later","GFDL-1.2-only","GFDL-1.2-or-later","GFDL-1.3-invariants-only","GFDL-1.3-invariants-or-later","GFDL-1.3-no-invariants-only","GFDL-1.3-no-invariants-or-later","GFDL-1.3-only","GFDL-1.3-or-later","GL2PS","GLWTPL","GPL-1.0-only","GPL-1.0-or-later","GPL-2.0-only","GPL-2.0-or-later","GPL-3.0-only","GPL-3.0-or-later","Game-Programming-Gems","Giftware","Glide","Glulxe","Graphics-Gems","Gutmann","HDF5","HIDAPI","HP-1986","HP-1989","HPND","HPND-DEC","HPND-Fenneberg-Livingston","HPND-INRIA-IMAG","HPND-Intel","HPND-Kevlin-Henney","HPND-MIT-disclaimer","HPND-Markus-Kuhn","HPND-Netrek","HPND-Pbmplus","HPND-UC","HPND-UC-export-US","HPND-doc","HPND-doc-sell","HPND-export-US","HPND-export-US-acknowledgement","HPND-export-US-modify","HPND-export2-US","HPND-merchantability-variant","HPND-sell-MIT-disclaimer-xserver","HPND-sell-regexpr","HPND-sell-variant","HPND-sell-variant-MIT-disclaimer","HPND-sell-variant-MIT-disclaimer-rev","HTMLTIDY","HaskellReport","Hippocratic-2.1","IBM-pibs","ICU","IEC-Code-Components-EULA","IJG","IJG-short","IPA","IPL-1.0","ISC","ISC-Veillard","ImageMagick","Imlib2","Info-ZIP","Inner-Net-2.0","InnoSetup","Intel","Intel-ACPI","Interbase-1.0","JPL-image","JPNIC","JSON","Jam","JasPer-2.0","Kastrup","Kazlib","Knuth-CTAN","LAL-1.2","LAL-1.3","LGPL-2.0-only","LGPL-2.0-or-later","LGPL-2.1-only","LGPL-2.1-or-later","LGPL-3.0-only","LGPL-3.0-or-later","LGPLLR","LOOP","LPD-document","LPL-1.0","LPL-1.02","LPPL-1.0","LPPL-1.1","LPPL-1.2","LPPL-1.3a","LPPL-1.3c","LZMA-SDK-9.11-to-9.20","LZMA-SDK-9.22","Latex2e","Latex2e-translated-notice","Leptonica","LiLiQ-P-1.1","LiLiQ-R-1.1","LiLiQ-Rplus-1.1","Libpng","Linux-OpenIB","Linux-man-pages-1-para","Linux-man-pages-copyleft","Linux-man-pages-copyleft-2-para","Linux-man-pages-copyleft-var","Lucida-Bitmap-Fonts","MIPS","MIT","MIT-0","MIT-CMU","MIT-Click","MIT-Festival","MIT-Khronos-old","MIT-Modern-Variant","MIT-Wu","MIT-advertising","MIT-enna","MIT-feh","MIT-open-group","MIT-testregex","MITNFA","MMIXware","MPEG-SSG","MPL-1.0","MPL-1.1","MPL-2.0","MPL-2.0-no-copyleft-exception","MS-LPL","MS-PL","MS-RL","MTLL","Mackerras-3-Clause","Mackerras-3-Clause-acknowledgment","MakeIndex","Martin-Birgmeier","McPhee-slideshow","Minpack","MirOS","Motosoto","MulanPSL-1.0","MulanPSL-2.0","Multics","Mup","NAIST-2003","NASA-1.3","NBPL-1.0","NCBI-PD","NCGL-UK-2.0","NCL","NCSA","NGPL","NICTA-1.0","NIST-PD","NIST-PD-fallback","NIST-Software","NLOD-1.0","NLOD-2.0","NLPL","NOSL","NPL-1.0","NPL-1.1","NPOSL-3.0","NRL","NTIA-PD","NTP","NTP-0","Naumen","NetCDF","Newsletr","Nokia","Noweb","O-UDA-1.0","OAR","OCCT-PL","OCLC-2.0","ODC-By-1.0","ODbL-1.0","OFFIS","OFL-1.0","OFL-1.0-RFN","OFL-1.0-no-RFN","OFL-1.1","OFL-1.1-RFN","OFL-1.1-no-RFN","OGC-1.0","OGDL-Taiwan-1.0","OGL-Canada-2.0","OGL-UK-1.0","OGL-UK-2.0","OGL-UK-3.0","OGTSL","OLDAP-1.1","OLDAP-1.2","OLDAP-1.3","OLDAP-1.4","OLDAP-2.0","OLDAP-2.0.1","OLDAP-2.1","OLDAP-2.2","OLDAP-2.2.1","OLDAP-2.2.2","OLDAP-2.3","OLDAP-2.4","OLDAP-2.5","OLDAP-2.6","OLDAP-2.7","OLDAP-2.8","OLFL-1.3","OML","OPL-1.0","OPL-UK-3.0","OPUBL-1.0","OSET-PL-2.1","OSL-1.0","OSL-1.1","OSL-2.0","OSL-2.1","OSL-3.0","OpenPBS-2.3","OpenSSL","OpenSSL-standalone","OpenVision","PADL","PDDL-1.0","PHP-3.0","PHP-3.01","PPL","PSF-2.0","Parity-6.0.0","Parity-7.0.0","Pixar","Plexus","PolyForm-Noncommercial-1.0.0","PolyForm-Small-Business-1.0.0","PostgreSQL","Python-2.0","Python-2.0.1","QPL-1.0","QPL-1.0-INRIA-2004","Qhull","RHeCos-1.1","RPL-1.1","RPL-1.5","RPSL-1.0","RSA-MD","RSCPL","Rdisc","Ruby","Ruby-pty","SAX-PD","SAX-PD-2.0","SCEA","SGI-B-1.0","SGI-B-1.1","SGI-B-2.0","SGI-OpenGL","SGP4","SHL-0.5","SHL-0.51","SISSL","SISSL-1.2","SL","SMAIL-GPL","SMLNJ","SMPPL","SNIA","SOFA","SPL-1.0","SSH-OpenSSH","SSH-short","SSLeay-standalone","SSPL-1.0","SUL-1.0","SWL","Saxpath","SchemeReport","Sendmail","Sendmail-8.23","Sendmail-Open-Source-1.1","SimPL-2.0","Sleepycat","Soundex","Spencer-86","Spencer-94","Spencer-99","SugarCRM-1.1.3","Sun-PPP","Sun-PPP-2000","SunPro","Symlinks","TAPR-OHL-1.0","TCL","TCP-wrappers","TGPPL-1.0","TMate","TORQUE-1.1","TOSL","TPDL","TPL-1.0","TTWL","TTYP0","TU-Berlin-1.0","TU-Berlin-2.0","TermReadKey","ThirdEye","TrustedQSL","UCAR","UCL-1.0","UMich-Merit","UPL-1.0","URT-RLE","Ubuntu-font-1.0","Unicode-3.0","Unicode-DFS-2015","Unicode-DFS-2016","Unicode-TOU","UnixCrypt","Unlicense","Unlicense-libtelnet","Unlicense-libwhirlpool","VOSTROM","VSL-1.0","Vim","W3C","W3C-19980720","W3C-20150513","WTFPL","Watcom-1.0","Widget-Workshop","Wsuipa","X11","X11-distribute-modifications-variant","X11-swapped","XFree86-1.1","XSkat","Xdebug-1.03","Xerox","Xfig","Xnet","YPL-1.0","YPL-1.1","ZPL-1.1","ZPL-2.0","ZPL-2.1","Zed","Zeeff","Zend-2.0","Zimbra-1.3","Zimbra-1.4","Zlib","any-OSI","any-OSI-perl-modules","bcrypt-Solar-Designer","blessing","bzip2-1.0.6","check-cvs","checkmk","copyleft-next-0.3.0","copyleft-next-0.3.1","curl","cve-tou","diffmark","dtoa","dvipdfm","eGenix","etalab-2.0","fwlw","gSOAP-1.3b","generic-xts","gnuplot","gtkbook","hdparm","iMatix","jove","libpng-1.6.35","libpng-2.0","libselinux-1.0","libtiff","libutil-David-Nugent","lsof","magaz","mailprio","man2html","metamail","mpi-permissive","mpich2","mplus","ngrep","pkgconf","pnmstitch","psfrag","psutils","python-ldap","radvd","snprintf","softSurfer","ssh-keyscan","swrule","threeparttable","ulem","w3m","wwl","xinetd","xkeyboard-config-Zinoviev","xlock","xpp","xzoom","zlib-acknowledgement"],dr=["AGPL-1.0","AGPL-3.0","BSD-2-Clause-FreeBSD","BSD-2-Clause-NetBSD","GFDL-1.1","GFDL-1.2","GFDL-1.3","GPL-1.0","GPL-2.0","GPL-2.0-with-GCC-exception","GPL-2.0-with-autoconf-exception","GPL-2.0-with-bison-exception","GPL-2.0-with-classpath-exception","GPL-2.0-with-font-exception","GPL-3.0","GPL-3.0-with-GCC-exception","GPL-3.0-with-autoconf-exception","LGPL-2.0","LGPL-2.1","LGPL-3.0","Net-SNMP","Nunit","StandardML-NJ","bzip2-1.0.5","eCos-2.0","wxWindows"],ur=["389-exception","Asterisk-exception","Autoconf-exception-2.0","Autoconf-exception-3.0","Autoconf-exception-generic","Autoconf-exception-generic-3.0","Autoconf-exception-macro","Bison-exception-1.24","Bison-exception-2.2","Bootloader-exception","Classpath-exception-2.0","CLISP-exception-2.0","cryptsetup-OpenSSL-exception","DigiRule-FOSS-exception","eCos-exception-2.0","Fawkes-Runtime-exception","FLTK-exception","fmt-exception","Font-exception-2.0","freertos-exception-2.0","GCC-exception-2.0","GCC-exception-2.0-note","GCC-exception-3.1","Gmsh-exception","GNAT-exception","GNOME-examples-exception","GNU-compiler-exception","gnu-javamail-exception","GPL-3.0-interface-exception","GPL-3.0-linking-exception","GPL-3.0-linking-source-exception","GPL-CC-1.0","GStreamer-exception-2005","GStreamer-exception-2008","i2p-gpl-java-exception","KiCad-libraries-exception","LGPL-3.0-linking-exception","libpri-OpenH323-exception","Libtool-exception","Linux-syscall-note","LLGPL","LLVM-exception","LZMA-exception","mif-exception","OCaml-LGPL-linking-exception","OCCT-exception-1.0","OpenJDK-assembly-exception-1.0","openvpn-openssl-exception","PS-or-PDF-font-exception-20170817","QPL-1.0-INRIA-2004-exception","Qt-GPL-exception-1.0","Qt-LGPL-exception-1.1","Qwt-exception-1.0","SANE-exception","SHL-2.0","SHL-2.1","stunnel-exception","SWI-exception","Swift-exception","Texinfo-exception","u-boot-exception-2.0","UBDL-exception","Universal-FOSS-exception-1.0","vsftpd-openssl-exception","WxWindows-exception-3.1","x11vnc-openssl-exception"];function pr(){if(er)return Qt;er=1;var e=[].concat(lr).concat(dr),t=ur;return Qt=function(r){var n=0;function o(){return n<r.length}function i(e){if(e instanceof RegExp){var t=r.slice(n).match(e);if(t)return n+=t[0].length,t[0]}else if(r.indexOf(e,n)===n)return n+=e.length,e}function s(){i(/[ ]*/)}function a(){return i(/[A-Za-z0-9-.]+/)}function c(){var e=a();if(!e)throw new Error("Expected idstring at offset "+n);return e}function l(){return function(){for(var e,t=["WITH","AND","OR","(",")",":","+"],o=0;o<t.length&&!(e=i(t[o]));o++);if("+"===e&&n>1&&" "===r[n-2])throw new Error("Space before `+`");return e&&{type:"OPERATOR",string:e}}()||function(){if(i("DocumentRef-"))return{type:"DOCUMENTREF",string:c()}}()||function(){if(i("LicenseRef-"))return{type:"LICENSEREF",string:c()}}()||(o=n,s=a(),-1!==e.indexOf(s)?{type:"LICENSE",string:s}:-1!==t.indexOf(s)?{type:"EXCEPTION",string:s}:void(n=o));var o,s}for(var d=[];o()&&(s(),o());){var u=l();if(!u)throw new Error("Unexpected `"+r[n]+"` at offset "+n);d.push(u)}return d}}function hr(){return rr||(rr=1,tr=function(e){var t=0;function r(){return t<e.length}function n(){return r()?e[t]:null}function o(){if(!r())throw new Error;t++}function i(e){var t=n();if(t&&"OPERATOR"===t.type&&e===t.string)return o(),t.string}function s(){var e=n();if(e&&"LICENSE"===e.type){o();var t={license:e.string};i("+")&&(t.plus=!0);var r=function(){if(i("WITH")){var e=n();if(e&&"EXCEPTION"===e.type)return o(),e.string;throw new Error("Expected exception after `WITH`")}}();return r&&(t.exception=r),t}}function a(e,t){return function r(){var n=t();if(n){if(!i(e))return n;var o=r();if(!o)throw new Error("Expected expression");return{left:n,conjunction:e.toLowerCase(),right:o}}}}var c=a("AND",function(){return function(){if(i("(")){var e=l();if(!i(")"))throw new Error("Expected `)`");return e}}()||function(){var e=t,r="",s=n();if("DOCUMENTREF"===s.type&&(o(),r+="DocumentRef-"+s.string+":",!i(":")))throw new Error("Expected `:` after `DocumentRef-...`");if("LICENSEREF"===(s=n()).type)return o(),{license:r+="LicenseRef-"+s.string};t=e}()||s()}),l=a("OR",c),d=l();if(!d||r())throw new Error("Syntax error");return d}),tr}function fr(){if(or)return nr;or=1;var e=pr(),t=hr();return nr=function(r){return t(e(r))}}function mr(){if(cr)return ar;cr=1;var e=fr(),t=function(){if(sr)return ir;sr=1;var e=fr(),t=lr;function r(t){try{return e(t),!0}catch(e){return!1}}function n(e,t){var r=t[0].length-e[0].length;return 0!==r?r:e[0].toUpperCase().localeCompare(t[0].toUpperCase())}var o=[["APGL","AGPL"],["Gpl","GPL"],["GLP","GPL"],["APL","Apache"],["ISD","ISC"],["GLP","GPL"],["IST","ISC"],["Claude","Clause"],[" or later","+"],[" International",""],["GNU","GPL"],["GUN","GPL"],["+",""],["GNU GPL","GPL"],["GNU LGPL","LGPL"],["GNU/GPL","GPL"],["GNU GLP","GPL"],["GNU LESSER GENERAL PUBLIC LICENSE","LGPL"],["GNU Lesser General Public License","LGPL"],["GNU LESSER GENERAL PUBLIC LICENSE","LGPL-2.1"],["GNU Lesser General Public License","LGPL-2.1"],["LESSER GENERAL PUBLIC LICENSE","LGPL"],["Lesser General Public License","LGPL"],["LESSER GENERAL PUBLIC LICENSE","LGPL-2.1"],["Lesser General Public License","LGPL-2.1"],["GNU General Public License","GPL"],["Gnu public license","GPL"],["GNU Public License","GPL"],["GNU GENERAL PUBLIC LICENSE","GPL"],["MTI","MIT"],["Mozilla Public License","MPL"],["Universal Permissive License","UPL"],["WTH","WTF"],["WTFGPL","WTFPL"],["-License",""]].sort(n),i=[function(e){return e.toUpperCase()},function(e){return e.trim()},function(e){return e.replace(/\./g,"")},function(e){return e.replace(/\s+/g,"")},function(e){return e.replace(/\s+/g,"-")},function(e){return e.replace("v","-")},function(e){return e.replace(/,?\s*(\d)/,"-$1")},function(e){return e.replace(/,?\s*(\d)/,"-$1.0")},function(e){return e.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/,"-$2")},function(e){return e.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/,"-$2.0")},function(e){return e[0].toUpperCase()+e.slice(1)},function(e){return e.replace("/","-")},function(e){return e.replace(/\s*V\s*(\d)/,"-$1").replace(/(\d)$/,"$1.0")},function(e){return-1!==e.indexOf("3.0")?e+"-or-later":e+"-only"},function(e){return e+"only"},function(e){return e.replace(/(\d)$/,"-$1.0")},function(e){return e.replace(/(-| )?(\d)$/,"-$2-Clause")},function(e){return e.replace(/(-| )clause(-| )(\d)/,"-$3-Clause")},function(e){return e.replace(/\b(Modified|New|Revised)(-| )?BSD((-| )License)?/i,"BSD-3-Clause")},function(e){return e.replace(/\bSimplified(-| )?BSD((-| )License)?/i,"BSD-2-Clause")},function(e){return e.replace(/\b(Free|Net)(-| )?BSD((-| )License)?/i,"BSD-2-Clause-$1BSD")},function(e){return e.replace(/\bClear(-| )?BSD((-| )License)?/i,"BSD-3-Clause-Clear")},function(e){return e.replace(/\b(Old|Original)(-| )?BSD((-| )License)?/i,"BSD-4-Clause")},function(e){return"CC-"+e},function(e){return"CC-"+e+"-4.0"},function(e){return e.replace("Attribution","BY").replace("NonCommercial","NC").replace("NoDerivatives","ND").replace(/ (\d)/,"-$1").replace(/ ?International/,"")},function(e){return"CC-"+e.replace("Attribution","BY").replace("NonCommercial","NC").replace("NoDerivatives","ND").replace(/ (\d)/,"-$1").replace(/ ?International/,"")+"-4.0"}],s=t.map(function(e){var t=/^(.*)-\d+\.\d+$/.exec(e);return t?[t[0],t[1]]:[e,null]}).reduce(function(e,t){var r=t[1];return e[r]=e[r]||[],e[r].push(t[0]),e},{}),a=Object.keys(s).map(function(e){return[e,s[e]]}).filter(function(e){return 1===e[1].length&&null!==e[0]&&"APL"!==e[0]}).map(function(e){return[e[0],e[1][0]]});s=void 0;var c=[["UNLI","Unlicense"],["WTF","WTFPL"],["2 CLAUSE","BSD-2-Clause"],["2-CLAUSE","BSD-2-Clause"],["3 CLAUSE","BSD-3-Clause"],["3-CLAUSE","BSD-3-Clause"],["AFFERO","AGPL-3.0-or-later"],["AGPL","AGPL-3.0-or-later"],["APACHE","Apache-2.0"],["ARTISTIC","Artistic-2.0"],["Affero","AGPL-3.0-or-later"],["BEER","Beerware"],["BOOST","BSL-1.0"],["BSD","BSD-2-Clause"],["CDDL","CDDL-1.1"],["ECLIPSE","EPL-1.0"],["FUCK","WTFPL"],["GNU","GPL-3.0-or-later"],["LGPL","LGPL-3.0-or-later"],["GPLV1","GPL-1.0-only"],["GPL-1","GPL-1.0-only"],["GPLV2","GPL-2.0-only"],["GPL-2","GPL-2.0-only"],["GPL","GPL-3.0-or-later"],["MIT +NO-FALSE-ATTRIBS","MITNFA"],["MIT","MIT"],["MPL","MPL-2.0"],["X11","X11"],["ZLIB","Zlib"]].concat(a).sort(n),l=function(e){for(var t=0;t<i.length;t++){var n=i[t](e).trim();if(n!==e&&r(n))return n}return null},d=function(e){for(var t=e.toUpperCase(),r=0;r<c.length;r++){var n=c[r];if(t.indexOf(n[0])>-1)return n[1]}return null},u=function(e,t){for(var r=0;r<o.length;r++){var n=o[r],i=n[0];if(e.indexOf(i)>-1){var s=t(e.replace(i,n[1]));if(null!==s)return s}}return null};return ir=function(e,t){var n=void 0===(t=t||{}).upgrade||!!t.upgrade;function o(e){return n?function(e){return-1!==["GPL-1.0","LGPL-1.0","AGPL-1.0","GPL-2.0","LGPL-2.0","AGPL-2.0","LGPL-2.1"].indexOf(e)?e+"-only":-1!==["GPL-1.0+","GPL-2.0+","GPL-3.0+","LGPL-2.0+","LGPL-2.1+","LGPL-3.0+","AGPL-1.0+","AGPL-3.0+"].indexOf(e)?e.replace(/\+$/,"-or-later"):-1!==["GPL-3.0","LGPL-3.0","AGPL-3.0"].indexOf(e)?e+"-or-later":e}(e):e}if("string"!=typeof e||0===e.trim().length)throw Error("Invalid argument. Expected non-empty string.");if(r(e=e.trim()))return o(e);var i=e.replace(/\+$/,"").trim();if(r(i))return o(i);var s=l(e);return null!==s||null!==(s=u(e,function(e){return r(e)?e:l(e)}))||null!==(s=d(e))||null!==(s=u(e,d))?o(s):null}}(),r='license should be a valid SPDX license expression (without "LicenseRef"), "UNLICENSED", or "SEE LICENSE IN <filename>"',n=/^SEE LICEN[CS]E IN (.+)$/;function o(e,t){return t.slice(0,e.length)===e}function i(e){if(e.hasOwnProperty("license")){var t=e.license;return o("LicenseRef",t)||o("DocumentRef",t)}return i(e.left)||i(e.right)}return ar=function(o){var s;try{s=e(o)}catch(e){var a;if("UNLICENSED"===o||"UNLICENCED"===o)return{validForOldPackages:!0,validForNewPackages:!0,unlicensed:!0};if(a=n.exec(o))return{validForOldPackages:!0,validForNewPackages:!0,inFile:a[1]};var c={validForOldPackages:!1,validForNewPackages:!1,warnings:[r]};if(0!==o.trim().length){var l=t(o);l&&c.warnings.push('license is similar to the valid expression "'+l+'"')}return c}return i(s)?{validForNewPackages:!1,validForOldPackages:!1,spdx:!0,warnings:[r]}:{validForNewPackages:!0,validForOldPackages:!0,spdx:!0}}}var gr,yr,vr,br,$r,wr,Er,Sr,Pr,Lr,_r,kr={};function Cr(){if(gr)return kr;gr=1,Object.defineProperty(kr,"__esModule",{value:!0}),kr.LRUCache=void 0;const e="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,t=new Set,r="object"==typeof process&&process?process:{},n=(e,t,n,o)=>{"function"==typeof r.emitWarning?r.emitWarning(e,t,n,o):console.error(`[${n}] ${t}: ${e}`)};let o=globalThis.AbortController,i=globalThis.AbortSignal;if(void 0===o){i=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},o=class{constructor(){t()}signal=new i;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(const t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e="1"!==r.env?.LRU_CACHE_IGNORE_AC_WARNING;const t=()=>{e&&(e=!1,n("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}const s=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),a=e=>s(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?c:null:null;class c extends Array{constructor(e){super(e),this.fill(0)}}class l{heap;length;static#l=!1;static create(e){const t=a(e);if(!t)return[];l.#l=!0;const r=new l(e,t);return l.#l=!1,r}constructor(e,t){if(!l.#l)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}}class d{#d;#u;#p;#h;#f;#m;#g;#y;get perf(){return this.#y}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#v;#b;#$;#w;#E;#S;#P;#L;#_;#k;#C;#N;#I;#O;#A;#T;#x;#D;static unsafeExposeInternals(e){return{starts:e.#I,ttls:e.#O,sizes:e.#N,keyMap:e.#$,keyList:e.#w,valList:e.#E,next:e.#S,prev:e.#P,get head(){return e.#L},get tail(){return e.#_},free:e.#k,isBackgroundFetch:t=>e.#j(t),backgroundFetch:(t,r,n,o)=>e.#R(t,r,n,o),moveToTail:t=>e.#F(t),indexes:t=>e.#M(t),rindexes:t=>e.#G(t),isStale:t=>e.#U(t)}}get max(){return this.#d}get maxSize(){return this.#u}get calculatedSize(){return this.#b}get size(){return this.#v}get fetchMethod(){return this.#m}get memoMethod(){return this.#g}get dispose(){return this.#p}get onInsert(){return this.#h}get disposeAfter(){return this.#f}constructor(r){const{max:o=0,ttl:i,ttlResolution:c=1,ttlAutopurge:u,updateAgeOnGet:p,updateAgeOnHas:h,allowStale:f,dispose:m,onInsert:g,disposeAfter:y,noDisposeOnSet:v,noUpdateTTL:b,maxSize:$=0,maxEntrySize:w=0,sizeCalculation:E,fetchMethod:S,memoMethod:P,noDeleteOnFetchRejection:L,noDeleteOnStaleGet:_,allowStaleOnFetchRejection:k,allowStaleOnFetchAbort:C,ignoreFetchAbort:N,perf:I}=r;if(void 0!==I&&"function"!=typeof I?.now)throw new TypeError("perf option must have a now() method if specified");if(this.#y=I??e,0!==o&&!s(o))throw new TypeError("max option must be a nonnegative integer");const O=o?a(o):Array;if(!O)throw new Error("invalid max value: "+o);if(this.#d=o,this.#u=$,this.maxEntrySize=w||this.#u,this.sizeCalculation=E,this.sizeCalculation){if(!this.#u&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if("function"!=typeof this.sizeCalculation)throw new TypeError("sizeCalculation set to non-function")}if(void 0!==P&&"function"!=typeof P)throw new TypeError("memoMethod must be a function if defined");if(this.#g=P,void 0!==S&&"function"!=typeof S)throw new TypeError("fetchMethod must be a function if specified");if(this.#m=S,this.#T=!!S,this.#$=new Map,this.#w=new Array(o).fill(void 0),this.#E=new Array(o).fill(void 0),this.#S=new O(o),this.#P=new O(o),this.#L=0,this.#_=0,this.#k=l.create(o),this.#v=0,this.#b=0,"function"==typeof m&&(this.#p=m),"function"==typeof g&&(this.#h=g),"function"==typeof y?(this.#f=y,this.#C=[]):(this.#f=void 0,this.#C=void 0),this.#A=!!this.#p,this.#D=!!this.#h,this.#x=!!this.#f,this.noDisposeOnSet=!!v,this.noUpdateTTL=!!b,this.noDeleteOnFetchRejection=!!L,this.allowStaleOnFetchRejection=!!k,this.allowStaleOnFetchAbort=!!C,this.ignoreFetchAbort=!!N,0!==this.maxEntrySize){if(0!==this.#u&&!s(this.#u))throw new TypeError("maxSize must be a positive integer if specified");if(!s(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#B()}if(this.allowStale=!!f,this.noDeleteOnStaleGet=!!_,this.updateAgeOnGet=!!p,this.updateAgeOnHas=!!h,this.ttlResolution=s(c)||0===c?c:1,this.ttlAutopurge=!!u,this.ttl=i||0,this.ttl){if(!s(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#z()}if(0===this.#d&&0===this.ttl&&0===this.#u)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#d&&!this.#u){const e="LRU_CACHE_UNBOUNDED";if((e=>!t.has(e))(e)){t.add(e);n("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",e,d)}}}getRemainingTTL(e){return this.#$.has(e)?1/0:0}#z(){const e=new c(this.#d),t=new c(this.#d);this.#O=e,this.#I=t,this.#H=(r,n,o=this.#y.now())=>{if(t[r]=0!==n?o:0,e[r]=n,0!==n&&this.ttlAutopurge){const e=setTimeout(()=>{this.#U(r)&&this.#V(this.#w[r],"expire")},n+1);e.unref&&e.unref()}},this.#W=r=>{t[r]=0!==e[r]?this.#y.now():0},this.#q=(o,i)=>{if(e[i]){const s=e[i],a=t[i];if(!s||!a)return;o.ttl=s,o.start=a,o.now=r||n();const c=o.now-a;o.remainingTTL=s-c}};let r=0;const n=()=>{const e=this.#y.now();if(this.ttlResolution>0){r=e;const t=setTimeout(()=>r=0,this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=o=>{const i=this.#$.get(o);if(void 0===i)return 0;const s=e[i],a=t[i];if(!s||!a)return 1/0;return s-((r||n())-a)},this.#U=o=>{const i=t[o],s=e[o];return!!s&&!!i&&(r||n())-i>s}}#W=()=>{};#q=()=>{};#H=()=>{};#U=()=>!1;#B(){const e=new c(this.#d);this.#b=0,this.#N=e,this.#K=t=>{this.#b-=e[t],e[t]=0},this.#Y=(e,t,r,n)=>{if(this.#j(t))return 0;if(!s(r)){if(!n)throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");if("function"!=typeof n)throw new TypeError("sizeCalculation must be a function");if(r=n(t,e),!s(r))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return r},this.#J=(t,r,n)=>{if(e[t]=r,this.#u){const r=this.#u-e[t];for(;this.#b>r;)this.#X(!0)}this.#b+=e[t],n&&(n.entrySize=r,n.totalCalculatedSize=this.#b)}}#K=e=>{};#J=(e,t,r)=>{};#Y=(e,t,r,n)=>{if(r||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#M({allowStale:e=this.allowStale}={}){if(this.#v)for(let t=this.#_;this.#Z(t)&&(!e&&this.#U(t)||(yield t),t!==this.#L);)t=this.#P[t]}*#G({allowStale:e=this.allowStale}={}){if(this.#v)for(let t=this.#L;this.#Z(t)&&(!e&&this.#U(t)||(yield t),t!==this.#_);)t=this.#S[t]}#Z(e){return void 0!==e&&this.#$.get(this.#w[e])===e}*entries(){for(const e of this.#M())void 0===this.#E[e]||void 0===this.#w[e]||this.#j(this.#E[e])||(yield[this.#w[e],this.#E[e]])}*rentries(){for(const e of this.#G())void 0===this.#E[e]||void 0===this.#w[e]||this.#j(this.#E[e])||(yield[this.#w[e],this.#E[e]])}*keys(){for(const e of this.#M()){const t=this.#w[e];void 0===t||this.#j(this.#E[e])||(yield t)}}*rkeys(){for(const e of this.#G()){const t=this.#w[e];void 0===t||this.#j(this.#E[e])||(yield t)}}*values(){for(const e of this.#M()){void 0===this.#E[e]||this.#j(this.#E[e])||(yield this.#E[e])}}*rvalues(){for(const e of this.#G()){void 0===this.#E[e]||this.#j(this.#E[e])||(yield this.#E[e])}}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(const r of this.#M()){const n=this.#E[r],o=this.#j(n)?n.__staleWhileFetching:n;if(void 0!==o&&e(o,this.#w[r],this))return this.get(this.#w[r],t)}}forEach(e,t=this){for(const r of this.#M()){const n=this.#E[r],o=this.#j(n)?n.__staleWhileFetching:n;void 0!==o&&e.call(t,o,this.#w[r],this)}}rforEach(e,t=this){for(const r of this.#G()){const n=this.#E[r],o=this.#j(n)?n.__staleWhileFetching:n;void 0!==o&&e.call(t,o,this.#w[r],this)}}purgeStale(){let e=!1;for(const t of this.#G({allowStale:!0}))this.#U(t)&&(this.#V(this.#w[t],"expire"),e=!0);return e}info(e){const t=this.#$.get(e);if(void 0===t)return;const r=this.#E[t],n=this.#j(r)?r.__staleWhileFetching:r;if(void 0===n)return;const o={value:n};if(this.#O&&this.#I){const e=this.#O[t],r=this.#I[t];if(e&&r){const t=e-(this.#y.now()-r);o.ttl=t,o.start=Date.now()}}return this.#N&&(o.size=this.#N[t]),o}dump(){const e=[];for(const t of this.#M({allowStale:!0})){const r=this.#w[t],n=this.#E[t],o=this.#j(n)?n.__staleWhileFetching:n;if(void 0===o||void 0===r)continue;const i={value:o};if(this.#O&&this.#I){i.ttl=this.#O[t];const e=this.#y.now()-this.#I[t];i.start=Math.floor(Date.now()-e)}this.#N&&(i.size=this.#N[t]),e.unshift([r,i])}return e}load(e){this.clear();for(const[t,r]of e){if(r.start){const e=Date.now()-r.start;r.start=this.#y.now()-e}this.set(t,r.value,r)}}set(e,t,r={}){if(void 0===t)return this.delete(e),this;const{ttl:n=this.ttl,start:o,noDisposeOnSet:i=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:a}=r;let{noUpdateTTL:c=this.noUpdateTTL}=r;const l=this.#Y(e,t,r.size||0,s);if(this.maxEntrySize&&l>this.maxEntrySize)return a&&(a.set="miss",a.maxEntrySizeExceeded=!0),this.#V(e,"set"),this;let d=0===this.#v?void 0:this.#$.get(e);if(void 0===d)d=0===this.#v?this.#_:0!==this.#k.length?this.#k.pop():this.#v===this.#d?this.#X(!1):this.#v,this.#w[d]=e,this.#E[d]=t,this.#$.set(e,d),this.#S[this.#_]=d,this.#P[d]=this.#_,this.#_=d,this.#v++,this.#J(d,l,a),a&&(a.set="add"),c=!1,this.#D&&this.#h?.(t,e,"add");else{this.#F(d);const r=this.#E[d];if(t!==r){if(this.#T&&this.#j(r)){r.__abortController.abort(new Error("replaced"));const{__staleWhileFetching:t}=r;void 0===t||i||(this.#A&&this.#p?.(t,e,"set"),this.#x&&this.#C?.push([t,e,"set"]))}else i||(this.#A&&this.#p?.(r,e,"set"),this.#x&&this.#C?.push([r,e,"set"]));if(this.#K(d),this.#J(d,l,a),this.#E[d]=t,a){a.set="replace";const e=r&&this.#j(r)?r.__staleWhileFetching:r;void 0!==e&&(a.oldValue=e)}}else a&&(a.set="update");this.#D&&this.onInsert?.(t,e,t===r?"update":"replace")}if(0===n||this.#O||this.#z(),this.#O&&(c||this.#H(d,n,o),a&&this.#q(a,d)),!i&&this.#x&&this.#C){const e=this.#C;let t;for(;t=e?.shift();)this.#f?.(...t)}return this}pop(){try{for(;this.#v;){const e=this.#E[this.#L];if(this.#X(!0),this.#j(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(void 0!==e)return e}}finally{if(this.#x&&this.#C){const e=this.#C;let t;for(;t=e?.shift();)this.#f?.(...t)}}}#X(e){const t=this.#L,r=this.#w[t],n=this.#E[t];return this.#T&&this.#j(n)?n.__abortController.abort(new Error("evicted")):(this.#A||this.#x)&&(this.#A&&this.#p?.(n,r,"evict"),this.#x&&this.#C?.push([n,r,"evict"])),this.#K(t),e&&(this.#w[t]=void 0,this.#E[t]=void 0,this.#k.push(t)),1===this.#v?(this.#L=this.#_=0,this.#k.length=0):this.#L=this.#S[t],this.#$.delete(r),this.#v--,t}has(e,t={}){const{updateAgeOnHas:r=this.updateAgeOnHas,status:n}=t,o=this.#$.get(e);if(void 0!==o){const e=this.#E[o];if(this.#j(e)&&void 0===e.__staleWhileFetching)return!1;if(!this.#U(o))return r&&this.#W(o),n&&(n.has="hit",this.#q(n,o)),!0;n&&(n.has="stale",this.#q(n,o))}else n&&(n.has="miss");return!1}peek(e,t={}){const{allowStale:r=this.allowStale}=t,n=this.#$.get(e);if(void 0===n||!r&&this.#U(n))return;const o=this.#E[n];return this.#j(o)?o.__staleWhileFetching:o}#R(e,t,r,n){const i=void 0===t?void 0:this.#E[t];if(this.#j(i))return i;const s=new o,{signal:a}=r;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});const c={signal:s.signal,options:r,context:n},l=(n,o=!1)=>{const{aborted:i}=s.signal,a=r.ignoreFetchAbort&&void 0!==n;if(r.status&&(i&&!o?(r.status.fetchAborted=!0,r.status.fetchError=s.signal.reason,a&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),i&&!a&&!o)return d(s.signal.reason);const l=u;return this.#E[t]===u&&(void 0===n?void 0!==l.__staleWhileFetching?this.#E[t]=l.__staleWhileFetching:this.#V(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,n,c.options))),n},d=n=>{const{aborted:o}=s.signal,i=o&&r.allowStaleOnFetchAbort,a=i||r.allowStaleOnFetchRejection,c=a||r.noDeleteOnFetchRejection,l=u;if(this.#E[t]===u){!c||void 0===l.__staleWhileFetching?this.#V(e,"fetch"):i||(this.#E[t]=l.__staleWhileFetching)}if(a)return r.status&&void 0!==l.__staleWhileFetching&&(r.status.returnedStale=!0),l.__staleWhileFetching;if(l.__returned===l)throw n};r.status&&(r.status.fetchDispatched=!0);const u=new Promise((t,n)=>{const o=this.#m?.(e,i,c);o&&o instanceof Promise&&o.then(e=>t(void 0===e?void 0:e),n),s.signal.addEventListener("abort",()=>{r.ignoreFetchAbort&&!r.allowStaleOnFetchAbort||(t(void 0),r.allowStaleOnFetchAbort&&(t=e=>l(e,!0)))})}).then(l,e=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=e),d(e))),p=Object.assign(u,{__abortController:s,__staleWhileFetching:i,__returned:void 0});return void 0===t?(this.set(e,p,{...c.options,status:void 0}),t=this.#$.get(e)):this.#E[t]=p,p}#j(e){if(!this.#T)return!1;const t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof o}async fetch(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:s=this.noDisposeOnSet,size:a=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:u=this.allowStaleOnFetchRejection,ignoreFetchAbort:p=this.ignoreFetchAbort,allowStaleOnFetchAbort:h=this.allowStaleOnFetchAbort,context:f,forceRefresh:m=!1,status:g,signal:y}=t;if(!this.#T)return g&&(g.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:o,status:g});const v={allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:o,ttl:i,noDisposeOnSet:s,size:a,sizeCalculation:c,noUpdateTTL:l,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:u,allowStaleOnFetchAbort:h,ignoreFetchAbort:p,status:g,signal:y};let b=this.#$.get(e);if(void 0===b){g&&(g.fetch="miss");const t=this.#R(e,b,v,f);return t.__returned=t}{const t=this.#E[b];if(this.#j(t)){const e=r&&void 0!==t.__staleWhileFetching;return g&&(g.fetch="inflight",e&&(g.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}const o=this.#U(b);if(!m&&!o)return g&&(g.fetch="hit"),this.#F(b),n&&this.#W(b),g&&this.#q(g,b),t;const i=this.#R(e,b,v,f),s=void 0!==i.__staleWhileFetching&&r;return g&&(g.fetch=o?"stale":"refresh",s&&o&&(g.returnedStale=!0)),s?i.__staleWhileFetching:i.__returned=i}}async forceFetch(e,t={}){const r=await this.fetch(e,t);if(void 0===r)throw new Error("fetch() returned undefined");return r}memo(e,t={}){const r=this.#g;if(!r)throw new Error("no memoMethod provided to constructor");const{context:n,forceRefresh:o,...i}=t,s=this.get(e,i);if(!o&&void 0!==s)return s;const a=r(e,s,{options:i,context:n});return this.set(e,a,i),a}get(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:i}=t,s=this.#$.get(e);if(void 0!==s){const t=this.#E[s],a=this.#j(t);return i&&this.#q(i,s),this.#U(s)?(i&&(i.get="stale"),a?(i&&r&&void 0!==t.__staleWhileFetching&&(i.returnedStale=!0),r?t.__staleWhileFetching:void 0):(o||this.#V(e,"expire"),i&&r&&(i.returnedStale=!0),r?t:void 0)):(i&&(i.get="hit"),a?t.__staleWhileFetching:(this.#F(s),n&&this.#W(s),t))}i&&(i.get="miss")}#Q(e,t){this.#P[t]=e,this.#S[e]=t}#F(e){e!==this.#_&&(e===this.#L?this.#L=this.#S[e]:this.#Q(this.#P[e],this.#S[e]),this.#Q(this.#_,e),this.#_=e)}delete(e){return this.#V(e,"delete")}#V(e,t){let r=!1;if(0!==this.#v){const n=this.#$.get(e);if(void 0!==n)if(r=!0,1===this.#v)this.#ee(t);else{this.#K(n);const r=this.#E[n];if(this.#j(r)?r.__abortController.abort(new Error("deleted")):(this.#A||this.#x)&&(this.#A&&this.#p?.(r,e,t),this.#x&&this.#C?.push([r,e,t])),this.#$.delete(e),this.#w[n]=void 0,this.#E[n]=void 0,n===this.#_)this.#_=this.#P[n];else if(n===this.#L)this.#L=this.#S[n];else{const e=this.#P[n];this.#S[e]=this.#S[n];const t=this.#S[n];this.#P[t]=this.#P[n]}this.#v--,this.#k.push(n)}}if(this.#x&&this.#C?.length){const e=this.#C;let t;for(;t=e?.shift();)this.#f?.(...t)}return r}clear(){return this.#ee("delete")}#ee(e){for(const t of this.#G({allowStale:!0})){const r=this.#E[t];if(this.#j(r))r.__abortController.abort(new Error("deleted"));else{const n=this.#w[t];this.#A&&this.#p?.(r,n,e),this.#x&&this.#C?.push([r,n,e])}}if(this.#$.clear(),this.#E.fill(void 0),this.#w.fill(void 0),this.#O&&this.#I&&(this.#O.fill(0),this.#I.fill(0)),this.#N&&this.#N.fill(0),this.#L=0,this.#_=0,this.#k.length=0,this.#b=0,this.#v=0,this.#x&&this.#C){const e=this.#C;let t;for(;t=e?.shift();)this.#f?.(...t)}}}return kr.LRUCache=d,kr}function Nr(){if($r)return br;$r=1;const e=ne,t=(e,t,r)=>{const n=e.indexOf(r);return e.lastIndexOf(t,n>-1?n:1/0)},r=t=>{try{return new e.URL(t)}catch{}};return br=(e,n)=>{const o=n?((e,t)=>{const r=e.indexOf(":"),n=e.slice(0,r+1);if(Object.prototype.hasOwnProperty.call(t,n))return e;const o=e.indexOf("@");return o>-1?o>r?`git+ssh://${e}`:e:e.indexOf("//")===r+1?e:`${e.slice(0,r+1)}//${e.slice(r+1)}`})(e,n):e;return r(o)||r((e=>{const r=t(e,"@","#"),n=t(e,":","#");return n>r&&(e=e.slice(0,n)+"/"+e.slice(n+1)),-1===t(e,":","#")&&-1===e.indexOf("//")&&(e=`git+ssh://${e}`),e})(o))},br}function Ir(){if(Er)return wr;Er=1;const e=Nr();return wr=(t,r,{gitHosts:n,protocols:o})=>{if(!t)return;const i=(e=>{const t=e.indexOf("#"),r=e.indexOf("/"),n=e.indexOf("/",r+1),o=e.indexOf(":"),i=/\s/.exec(e),s=e.indexOf("@"),a=!i||t>-1&&i.index>t,c=-1===s||t>-1&&s>t,l=-1===o||t>-1&&o>t,d=-1===n||t>-1&&n>t,u=r>0,p=t>-1?"/"!==e[t-1]:!e.endsWith("/"),h=!e.startsWith(".");return a&&u&&p&&h&&c&&l&&d})(t)?`github:${t}`:t,s=e(i,o);if(!s)return;const a=n.byShortcut[s.protocol],c=n.byDomain[s.hostname.startsWith("www.")?s.hostname.slice(4):s.hostname],l=a||c;if(!l)return;const d=n[a||c];let u=null;o[s.protocol]?.auth&&(s.username||s.password)&&(u=`${s.username}${s.password?":"+s.password:""}`);let p=null,h=null,f=null,m=null;try{if(a){let e=s.pathname.startsWith("/")?s.pathname.slice(1):s.pathname;const t=e.indexOf("@");t>-1&&(e=e.slice(t+1));const r=e.lastIndexOf("/");r>-1?(h=decodeURIComponent(e.slice(0,r)),h||(h=null),f=decodeURIComponent(e.slice(r+1))):f=decodeURIComponent(e),f.endsWith(".git")&&(f=f.slice(0,-4)),s.hash&&(p=decodeURIComponent(s.hash.slice(1))),m="shortcut"}else{if(!d.protocols.includes(s.protocol))return;const e=d.extract(s);if(!e)return;h=e.user&&decodeURIComponent(e.user),f=decodeURIComponent(e.project),p=decodeURIComponent(e.committish),m=o[s.protocol]?.name||s.protocol.slice(0,-1)}}catch(e){if(e instanceof URIError)return;throw e}return[l,h,u,f,p,m,r]}}function Or(){if(Pr)return Sr;Pr=1;const{LRUCache:e}=Cr(),t=function(){if(vr)return yr;vr=1;const e=(...e)=>e.every(e=>e)?e.join(""):"",t=e=>e?encodeURIComponent(e):"",r=e=>e.toLowerCase().replace(/^\W+/g,"").replace(/(?<!\W)\W+$/,"").replace(/\//g,"").replace(/\W+/g,"-"),n={sshtemplate:({domain:t,user:r,project:n,committish:o})=>`git@${t}:${r}/${n}.git${e("#",o)}`,sshurltemplate:({domain:t,user:r,project:n,committish:o})=>`git+ssh://git@${t}/${r}/${n}.git${e("#",o)}`,edittemplate:({domain:r,user:n,project:o,committish:i,editpath:s,path:a})=>`https://${r}/${n}/${o}${e("/",s,"/",t(i||"HEAD"),"/",a)}`,browsetemplate:({domain:r,user:n,project:o,committish:i,treepath:s})=>`https://${r}/${n}/${o}${e("/",s,"/",t(i))}`,browsetreetemplate:({domain:r,user:n,project:o,committish:i,treepath:s,path:a,fragment:c,hashformat:l})=>`https://${r}/${n}/${o}/${s}/${t(i||"HEAD")}/${a}${e("#",l(c||""))}`,browseblobtemplate:({domain:r,user:n,project:o,committish:i,blobpath:s,path:a,fragment:c,hashformat:l})=>`https://${r}/${n}/${o}/${s}/${t(i||"HEAD")}/${a}${e("#",l(c||""))}`,docstemplate:({domain:r,user:n,project:o,treepath:i,committish:s})=>`https://${r}/${n}/${o}${e("/",i,"/",t(s))}#readme`,httpstemplate:({auth:t,domain:r,user:n,project:o,committish:i})=>`git+https://${e(t,"@")}${r}/${n}/${o}.git${e("#",i)}`,filetemplate:({domain:e,user:r,project:n,committish:o,path:i})=>`https://${e}/${r}/${n}/raw/${t(o||"HEAD")}/${i}`,shortcuttemplate:({type:t,user:r,project:n,committish:o})=>`${t}:${r}/${n}${e("#",o)}`,pathtemplate:({user:t,project:r,committish:n})=>`${t}/${r}${e("#",n)}`,bugstemplate:({domain:e,user:t,project:r})=>`https://${e}/${t}/${r}/issues`,hashformat:r},o={};o.github={protocols:["git:","http:","git+ssh:","git+https:","ssh:","https:"],domain:"github.com",treepath:"tree",blobpath:"blob",editpath:"edit",filetemplate:({auth:r,user:n,project:o,committish:i,path:s})=>`https://${e(r,"@")}raw.githubusercontent.com/${n}/${o}/${t(i||"HEAD")}/${s}`,gittemplate:({auth:t,domain:r,user:n,project:o,committish:i})=>`git://${e(t,"@")}${r}/${n}/${o}.git${e("#",i)}`,tarballtemplate:({domain:e,user:r,project:n,committish:o})=>`https://codeload.${e}/${r}/${n}/tar.gz/${t(o||"HEAD")}`,extract:e=>{let[,t,r,n,o]=e.pathname.split("/",5);if((!n||"tree"===n)&&(n||(o=e.hash.slice(1)),r&&r.endsWith(".git")&&(r=r.slice(0,-4)),t&&r))return{user:t,project:r,committish:o}}},o.bitbucket={protocols:["git+ssh:","git+https:","ssh:","https:"],domain:"bitbucket.org",treepath:"src",blobpath:"src",editpath:"?mode=edit",edittemplate:({domain:r,user:n,project:o,committish:i,treepath:s,path:a,editpath:c})=>`https://${r}/${n}/${o}${e("/",s,"/",t(i||"HEAD"),"/",a,c)}`,tarballtemplate:({domain:e,user:r,project:n,committish:o})=>`https://${e}/${r}/${n}/get/${t(o||"HEAD")}.tar.gz`,extract:e=>{let[,t,r,n]=e.pathname.split("/",4);if(!["get"].includes(n)&&(r&&r.endsWith(".git")&&(r=r.slice(0,-4)),t&&r))return{user:t,project:r,committish:e.hash.slice(1)}}},o.gitlab={protocols:["git+ssh:","git+https:","ssh:","https:"],domain:"gitlab.com",treepath:"tree",blobpath:"tree",editpath:"-/edit",httpstemplate:({auth:t,domain:r,user:n,project:o,committish:i})=>`git+https://${e(t,"@")}${r}/${n}/${o}.git${e("#",i)}`,tarballtemplate:({domain:e,user:r,project:n,committish:o})=>`https://${e}/${r}/${n}/repository/archive.tar.gz?ref=${t(o||"HEAD")}`,extract:e=>{const t=e.pathname.slice(1);if(t.includes("/-/")||t.includes("/archive.tar.gz"))return;const r=t.split("/");let n=r.pop();n.endsWith(".git")&&(n=n.slice(0,-4));const o=r.join("/");return o&&n?{user:o,project:n,committish:e.hash.slice(1)}:void 0}},o.gist={protocols:["git:","git+ssh:","git+https:","ssh:","https:"],domain:"gist.github.com",editpath:"edit",sshtemplate:({domain:t,project:r,committish:n})=>`git@${t}:${r}.git${e("#",n)}`,sshurltemplate:({domain:t,project:r,committish:n})=>`git+ssh://git@${t}/${r}.git${e("#",n)}`,edittemplate:({domain:r,user:n,project:o,committish:i,editpath:s})=>`https://${r}/${n}/${o}${e("/",t(i))}/${s}`,browsetemplate:({domain:r,project:n,committish:o})=>`https://${r}/${n}${e("/",t(o))}`,browsetreetemplate:({domain:r,project:n,committish:o,path:i,hashformat:s})=>`https://${r}/${n}${e("/",t(o))}${e("#",s(i))}`,browseblobtemplate:({domain:r,project:n,committish:o,path:i,hashformat:s})=>`https://${r}/${n}${e("/",t(o))}${e("#",s(i))}`,docstemplate:({domain:r,project:n,committish:o})=>`https://${r}/${n}${e("/",t(o))}`,httpstemplate:({domain:t,project:r,committish:n})=>`git+https://${t}/${r}.git${e("#",n)}`,filetemplate:({user:r,project:n,committish:o,path:i})=>`https://gist.githubusercontent.com/${r}/${n}/raw${e("/",t(o))}/${i}`,shortcuttemplate:({type:t,project:r,committish:n})=>`${t}:${r}${e("#",n)}`,pathtemplate:({project:t,committish:r})=>`${t}${e("#",r)}`,bugstemplate:({domain:e,project:t})=>`https://${e}/${t}`,gittemplate:({domain:t,project:r,committish:n})=>`git://${t}/${r}.git${e("#",n)}`,tarballtemplate:({project:e,committish:r})=>`https://codeload.github.com/gist/${e}/tar.gz/${t(r||"HEAD")}`,extract:e=>{let[,t,r,n]=e.pathname.split("/",4);if("raw"!==n){if(!r){if(!t)return;r=t,t=null}return r.endsWith(".git")&&(r=r.slice(0,-4)),{user:t,project:r,committish:e.hash.slice(1)}}},hashformat:function(e){return e&&"file-"+r(e)}},o.sourcehut={protocols:["git+ssh:","https:"],domain:"git.sr.ht",treepath:"tree",blobpath:"tree",filetemplate:({domain:e,user:r,project:n,committish:o,path:i})=>`https://${e}/${r}/${n}/blob/${t(o)||"HEAD"}/${i}`,httpstemplate:({domain:t,user:r,project:n,committish:o})=>`https://${t}/${r}/${n}.git${e("#",o)}`,tarballtemplate:({domain:e,user:r,project:n,committish:o})=>`https://${e}/${r}/${n}/archive/${t(o)||"HEAD"}.tar.gz`,bugstemplate:()=>null,extract:e=>{let[,t,r,n]=e.pathname.split("/",4);if(!["archive"].includes(n)&&(r&&r.endsWith(".git")&&(r=r.slice(0,-4)),t&&r))return{user:t,project:r,committish:e.hash.slice(1)}}};for(const[e,t]of Object.entries(o))o[e]=Object.assign({},n,t);return yr=o}(),r=Ir(),n=Nr(),o=new e({max:1e3});class i{constructor(e,t,r,n,o,s,a={}){Object.assign(this,i.#te[e],{type:e,user:t,auth:r,project:n,committish:o,default:s,opts:a})}static#te={byShortcut:{},byDomain:{}};static#re={"git+ssh:":{name:"sshurl"},"ssh:":{name:"sshurl"},"git+https:":{name:"https",auth:!0},"git:":{auth:!0},"http:":{auth:!0},"https:":{auth:!0},"git+http:":{auth:!0}};static addHost(e,t){i.#te[e]=t,i.#te.byDomain[t.domain]=e,i.#te.byShortcut[`${e}:`]=e,i.#re[`${e}:`]={name:e}}static fromUrl(e,t){if("string"!=typeof e)return;const n=e+JSON.stringify(t||{});if(!o.has(n)){const s=r(e,t,{gitHosts:i.#te,protocols:i.#re});o.set(n,s?new i(...s):void 0)}return o.get(n)}static fromManifest(e,t={}){if(!e||"object"!=typeof e)return;const r=e.repository,n=r&&("string"==typeof r?r:"object"==typeof r&&"string"==typeof r.url?r.url:null);if(!n)throw new Error("no repository");const o=n&&i.fromUrl(n.replace(/^git\+/,""),t)||null;if(o)return o;const s=function(e){try{const{protocol:t,hostname:r,pathname:n}=new URL(e);if(!r)return null;return`${/(?:git\+)http:$/.test(t)?"http:":"https:"}//${r}${n.replace(/\.git$/,"")}`}catch{return null}}(n);return i.fromUrl(s,t)||s}static parseUrl(e){return n(e)}#ne(e,t){if("function"!=typeof e)return null;const r={...this,...this.opts,...t};r.path||(r.path=""),r.path.startsWith("/")&&(r.path=r.path.slice(1)),r.noCommittish&&(r.committish=null);const n=e(r);return r.noGitPlus&&n.startsWith("git+")?n.slice(4):n}hash(){return this.committish?`#${this.committish}`:""}ssh(e){return this.#ne(this.sshtemplate,e)}sshurl(e){return this.#ne(this.sshurltemplate,e)}browse(e,...t){return"string"!=typeof e?this.#ne(this.browsetemplate,e):"string"!=typeof t[0]?this.#ne(this.browsetreetemplate,{...t[0],path:e}):this.#ne(this.browsetreetemplate,{...t[1],fragment:t[0],path:e})}browseFile(e,...t){return"string"!=typeof t[0]?this.#ne(this.browseblobtemplate,{...t[0],path:e}):this.#ne(this.browseblobtemplate,{...t[1],fragment:t[0],path:e})}docs(e){return this.#ne(this.docstemplate,e)}bugs(e){return this.#ne(this.bugstemplate,e)}https(e){return this.#ne(this.httpstemplate,e)}git(e){return this.#ne(this.gittemplate,e)}shortcut(e){return this.#ne(this.shortcuttemplate,e)}path(e){return this.#ne(this.pathtemplate,e)}tarball(e){return this.#ne(this.tarballtemplate,{...e,noCommittish:!1})}file(e,t){return this.#ne(this.filetemplate,{...t,path:e})}edit(e,t){return this.#ne(this.edittemplate,{...t,path:e})}getDefaultRepresentation(){return this.default}toString(e){return this.default&&"function"==typeof this[this.default]?this[this.default](e):this.sshurl(e)}}for(const[e,r]of Object.entries(t))i.addHost(e,r);return Sr=i}var Ar,Tr,xr={topLevel:{dependancies:"dependencies",dependecies:"dependencies",depdenencies:"dependencies",devEependencies:"devDependencies",depends:"dependencies","dev-dependencies":"devDependencies",devDependences:"devDependencies",devDepenencies:"devDependencies",devdependencies:"devDependencies",repostitory:"repository",repo:"repository",prefereGlobal:"preferGlobal",hompage:"homepage",hampage:"homepage",autohr:"author",autor:"author",contributers:"contributors",publicationConfig:"publishConfig",script:"scripts"},bugs:{web:"url",name:"url"},script:{server:"start",tests:"test"}};function Dr(){if(Tr)return Ar;Tr=1;var{URL:e}=o,t=function(){if(Wt)return Vt;Wt=1;const e=Zt();return Vt=(t,r)=>{const n=e(t,r);return n?n.version:null}}(),r=function(){if(Kt)return qt;Kt=1;const e=Zt();return qt=(t,r)=>{const n=e(t.trim().replace(/^[=v]+/,""),r);return n?n.version:null}}(),n=mr(),i=Or(),{isBuiltin:s}=oe,a=["dependencies","devDependencies","optionalDependencies"],c=_r?Lr:(_r=1,Lr=function(e){if(!e)return;if("ERROR: No README data found!"===e)return;e=e.trim().split("\n");let t=0;for(;e[t]&&e[t].trim().match(/^(#|$)/);)t++;const r=e.length;let n=t+1;for(;n<r&&e[n].trim();)n++;return e.slice(t,n).join(" ").trim()}),l=xr,d=e=>e.includes("@")&&e.indexOf("@")<e.lastIndexOf(".");function u(e,t){return e.author&&(e.author=t(e.author)),["maintainers","contributors"].forEach(function(r){Array.isArray(e[r])&&(e[r]=e[r].map(t))}),e}function p(e){if("string"==typeof e)return e;var t=e.name||"",r=e.url||e.web,n=r?" ("+r+")":"",o=e.email||e.mail;return t+(o?" <"+o+">":"")+n}function h(e){if("string"!=typeof e)return e;var t=e.match(/^([^(<]+)/),r=e.match(/\(([^()]+)\)/),n=e.match(/<([^<>]+)>/),o={};return t&&t[0].trim()&&(o.name=t[0].trim()),n&&(o.email=n[1]),r&&(o.url=r[1]),o}return Ar={warn:function(){},fixRepositoryField:function(e){if(e.repositories&&(this.warn("repositories"),e.repository=e.repositories[0]),!e.repository)return this.warn("missingRepository");"string"==typeof e.repository&&(e.repository={type:"git",url:e.repository});var t=e.repository.url||"";if(t){var r=i.fromUrl(t);r&&(t=e.repository.url="shortcut"===r.getDefaultRepresentation()?r.https():r.toString())}t.match(/github.com\/[^/]+\/[^/]+\.git\.git$/)&&this.warn("brokenGitUrl",t)},fixTypos:function(e){Object.keys(l.topLevel).forEach(function(t){Object.prototype.hasOwnProperty.call(e,t)&&this.warn("typo",t,l.topLevel[t])},this)},fixScriptsField:function(e){if(e.scripts)return"object"!=typeof e.scripts?(this.warn("nonObjectScripts"),void delete e.scripts):void Object.keys(e.scripts).forEach(function(t){"string"!=typeof e.scripts[t]?(this.warn("nonStringScript"),delete e.scripts[t]):l.script[t]&&!e.scripts[l.script[t]]&&this.warn("typo",t,l.script[t],"scripts")},this)},fixFilesField:function(e){var t=e.files;t&&!Array.isArray(t)?(this.warn("nonArrayFiles"),delete e.files):e.files&&(e.files=e.files.filter(function(e){return!(!e||"string"!=typeof e)||(this.warn("invalidFilename",e),!1)},this))},fixBinField:function(e){if(e.bin&&"string"==typeof e.bin){var t,r={};(t=e.name.match(/^@[^/]+[/](.*)$/))?r[t[1]]=e.bin:r[e.name]=e.bin,e.bin=r}},fixManField:function(e){e.man&&"string"==typeof e.man&&(e.man=[e.man])},fixBundleDependenciesField:function(e){var t="bundledDependencies",r="bundleDependencies";e[t]&&!e[r]&&(e[r]=e[t],delete e[t]),e[r]&&!Array.isArray(e[r])?(this.warn("nonArrayBundleDependencies"),delete e[r]):e[r]&&(e[r]=e[r].filter(function(t){return t&&"string"==typeof t?(e.dependencies||(e.dependencies={}),Object.prototype.hasOwnProperty.call(e.dependencies,t)||(this.warn("nonDependencyBundleDependency",t),e.dependencies[t]="*"),!0):(this.warn("nonStringBundleDependency",t),!1)},this))},fixDependencies:function(e){!function(e,t){a.forEach(function(r){e[r]&&(e[r]=function(e,t,r){if(!e)return{};"string"==typeof e&&(e=e.trim().split(/[\n\r\s\t ,]+/));if(!Array.isArray(e))return e;r("deprecatedArrayDependencies",t);var n={};return e.filter(function(e){return"string"==typeof e}).forEach(function(e){var t=(e=e.trim().split(/(:?[@\s><=])/)).shift(),r=e.join("");r=(r=r.trim()).replace(/^@/,""),n[t]=r}),n}(e[r],r,t))})}(e,this.warn),function(e){var t=e.optionalDependencies;if(!t)return;var r=e.dependencies||{};Object.keys(t).forEach(function(e){r[e]=t[e]}),e.dependencies=r}(e,this.warn),this.fixBundleDependenciesField(e),["dependencies","devDependencies"].forEach(function(t){if(t in e)return e[t]&&"object"==typeof e[t]?void Object.keys(e[t]).forEach(function(r){var n=e[t][r];"string"!=typeof n&&(this.warn("nonStringDependency",r,JSON.stringify(n)),delete e[t][r]);var o=i.fromUrl(e[t][r]);o&&(e[t][r]=o.toString())},this):(this.warn("nonObjectDependencies",t),void delete e[t])},this)},fixModulesField:function(e){e.modules&&(this.warn("deprecatedModules"),delete e.modules)},fixKeywordsField:function(e){"string"==typeof e.keywords&&(e.keywords=e.keywords.split(/,\s+/)),e.keywords&&!Array.isArray(e.keywords)?(delete e.keywords,this.warn("nonArrayKeywords")):e.keywords&&(e.keywords=e.keywords.filter(function(e){return!("string"!=typeof e||!e)||(this.warn("nonStringKeyword"),!1)},this))},fixVersionField:function(e,n){var o=!n;if(!e.version)return e.version="",!0;if(!t(e.version,o))throw new Error('Invalid version: "'+e.version+'"');return e.version=r(e.version,o),!0},fixPeople:function(e){u(e,p),u(e,h)},fixNameField:function(e,t){"boolean"==typeof t?t={strict:t}:void 0===t&&(t={});var r=t.strict;if(e.name||r){if("string"!=typeof e.name)throw new Error("name field must be a string.");r||(e.name=e.name.trim()),function(e,t,r){if("."===e.charAt(0)||!function(e){if("@"!==e.charAt(0))return!1;var t=e.slice(1).split("/");if(2!==t.length)return!1;return t[0]&&t[1]&&t[0]===encodeURIComponent(t[0])&&t[1]===encodeURIComponent(t[1])}(e)&&(n=e,n.match(/[/@\s+%:]/)||n!==encodeURIComponent(n))||t&&!r&&e!==e.toLowerCase()||"node_modules"===e.toLowerCase()||"favicon.ico"===e.toLowerCase())throw new Error("Invalid name: "+JSON.stringify(e));var n}(e.name,r,t.allowLegacyCase),s(e.name)&&this.warn("conflictingName",e.name)}else e.name=""},fixDescriptionField:function(e){e.description&&"string"!=typeof e.description&&(this.warn("nonStringDescription"),delete e.description),e.readme&&!e.description&&(e.description=c(e.readme)),void 0===e.description&&delete e.description,e.description||this.warn("missingDescription")},fixReadmeField:function(e){e.readme||(this.warn("missingReadme"),e.readme="ERROR: No README data found!")},fixBugsField:function(t){if(!t.bugs&&t.repository&&t.repository.url){var r=i.fromUrl(t.repository.url);r&&r.bugs()&&(t.bugs={url:r.bugs()})}else if(t.bugs){if("string"==typeof t.bugs)d(t.bugs)?t.bugs={email:t.bugs}:e.canParse(t.bugs)?t.bugs={url:t.bugs}:this.warn("nonEmailUrlBugsString");else{!function(e,t){if(!e)return;Object.keys(e).forEach(function(r){l.bugs[r]&&(t("typo",r,l.bugs[r],"bugs"),e[l.bugs[r]]=e[r],delete e[r])})}(t.bugs,this.warn);var n=t.bugs;t.bugs={},n.url&&(e.canParse(n.url)?t.bugs.url=n.url:this.warn("nonUrlBugsUrlField")),n.email&&("string"==typeof n.email&&d(n.email)?t.bugs.email=n.email:this.warn("nonEmailBugsEmailField"))}t.bugs.email||t.bugs.url||(delete t.bugs,this.warn("emptyNormalizedBugs"))}},fixHomepageField:function(t){if(!t.homepage&&t.repository&&t.repository.url){var r=i.fromUrl(t.repository.url);r&&r.docs()&&(t.homepage=r.docs())}if(t.homepage)return"string"!=typeof t.homepage?(this.warn("nonUrlHomepage"),delete t.homepage):void(e.canParse(t.homepage)||(t.homepage="http://"+t.homepage))},fixLicenseField:function(e){const t=e.license||e.licence;return t?"string"!=typeof t||t.length<1||""===t.trim()?this.warn("invalidLicense"):n(t).validForNewPackages?void 0:this.warn("invalidLicense"):this.warn("missingLicense")}},Ar}var jr,Rr,Fr,Mr,Gr={repositories:"'repositories' (plural) Not supported. Please pick one as the 'repository' field",missingRepository:"No repository field.",brokenGitUrl:"Probably broken git url: %s",nonObjectScripts:"scripts must be an object",nonStringScript:"script values must be string commands",nonArrayFiles:"Invalid 'files' member",invalidFilename:"Invalid filename in 'files' list: %s",nonArrayBundleDependencies:"Invalid 'bundleDependencies' list. Must be array of package names",nonStringBundleDependency:"Invalid bundleDependencies member: %s",nonDependencyBundleDependency:"Non-dependency in bundleDependencies: %s",nonObjectDependencies:"%s field must be an object",nonStringDependency:"Invalid dependency: %s %s",deprecatedArrayDependencies:"specifying %s as array is deprecated",deprecatedModules:"modules field is deprecated",nonArrayKeywords:"keywords should be an array of strings",nonStringKeyword:"keywords should be an array of strings",conflictingName:"%s is also the name of a node core module.",nonStringDescription:"'description' field should be a string",missingDescription:"No description",missingReadme:"No README data",missingLicense:"No license field.",nonEmailUrlBugsString:"Bug string field must be url, email, or {email,url}",nonUrlBugsUrlField:"bugs.url field must be a string url. Deleted.",nonEmailBugsEmailField:"bugs.email field must be a string email. Deleted.",emptyNormalizedBugs:"Normalized value of bugs field is an empty object. Deleted.",nonUrlHomepage:"homepage field must be a string url. Deleted.",invalidLicense:"license should be a valid SPDX license expression",typo:"%s should probably be %s."};function Ur(){if(Rr)return jr;Rr=1;var e=ie,t=Gr;function r(r,n,o){return o&&(r=o+"['"+r+"']",n=o+"['"+n+"']"),e.format(t.typo,r,n)}return jr=function(){var n=Array.prototype.slice.call(arguments,0),o=n.shift();if("typo"===o)return r.apply(null,n);var i=t[o]?t[o]:o+": '%s'";return n.unshift(i),e.format.apply(null,n)},jr}!function(){if(Mr)return Fr;Mr=1,Fr=n;var e=Dr();n.fixer=e;var t=Ur(),r=["name","version","description","repository","modules","scripts","files","bin","man","bugs","keywords","readme","homepage","license"].map(function(e){return o(e)+"Field"});function n(n,i,s){!0===i&&(i=null,s=!0),s||(s=!1),i&&!n.private||(i=function(){}),n.scripts&&"node-gyp rebuild"===n.scripts.install&&!n.scripts.preinstall&&(n.gypfile=!0),e.warn=function(){i(t.apply(null,arguments))},r.forEach(function(t){e["fix"+o(t)](n,s)}),n._id=n.name+"@"+n.version}function o(e){return e.charAt(0).toUpperCase()+e.slice(1)}r=r.concat(["dependencies","people","typos"])}();const Br=e("manifest").description("Generate or validate a Fusion portal manifest file.").addHelpText("after",["","By default, outputs the generated manifest object to stdout or a file. Use --output to write to a file.","","Note:","- If not `portal.manifest(.$ENV)?.[ts|js|json]` is found it will fallback to generate a default manifest","","Examples:"," $ ffc portal manifest"," $ ffc portal manifest portal.manifest.prod.ts --output ./dist/portal.manifest.json",' $ ffc portal manifest --silent | jq ".build.entryPoint"'," $ ffc portal manifest --debug"].join("\n")).option("-d, --debug","Enable debug mode for verbose logging",!1).option("-o, --output <string>","Write manifest to the specified file","stdout").option("-s, --silent","Silent mode, suppresses output except errors").argument("[manifest]","Manifest build file to use (e.g., portal.manifest[.env]?.[ts,js,json])").action(async(e,t)=>{const r=t.silent?null:new d("portal:manifest",{debug:t.debug}),n=await L({log:r,manifest:e});if(t.output){const e=s(process.cwd(),t.output);r?.start("Writing manifest to file",t.output),Ke(a(e))||await T(a(e),{recursive:!0}),await x(e,JSON.stringify(n.manifest,null,2)),r?.succeed("Manifest written to file",e)}else console.log(JSON.stringify(n.manifest,null,2))});var zr,Hr={exports:{}},Vr={},Wr={},qr={},Kr={},Yr={},Jr={};function Xr(){return zr||(zr=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(e){super(),this._items="string"==typeof e?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const e=this._items[0];return""===e||'""'===e}get str(){var e;return null!==(e=this._str)&&void 0!==e?e:this._str=this._items.reduce((e,t)=>`${e}${t}`,"")}get names(){var e;return null!==(e=this._names)&&void 0!==e?e:this._names=this._items.reduce((e,t)=>(t instanceof r&&(e[t.str]=(e[t.str]||0)+1),e),{})}}function o(e,...t){const r=[e[0]];let o=0;for(;o<t.length;)a(r,t[o]),r.push(e[++o]);return new n(r)}e._Code=n,e.nil=new n(""),e._=o;const i=new n("+");function s(e,...t){const r=[l(e[0])];let o=0;for(;o<t.length;)r.push(i),a(r,t[o]),r.push(i,l(e[++o]));return function(e){let t=1;for(;t<e.length-1;){if(e[t]===i){const r=c(e[t-1],e[t+1]);if(void 0!==r){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}(r),new n(r)}function a(e,t){var o;t instanceof n?e.push(...t._items):t instanceof r?e.push(t):e.push("number"==typeof(o=t)||"boolean"==typeof o||null===o?o:l(Array.isArray(o)?o.join(","):o))}function c(e,t){if('""'===t)return e;if('""'===e)return t;if("string"==typeof e){if(t instanceof r||'"'!==e[e.length-1])return;return"string"!=typeof t?`${e.slice(0,-1)}${t}"`:'"'===t[0]?e.slice(0,-1)+t.slice(1):void 0}return"string"!=typeof t||'"'!==t[0]||e instanceof r?void 0:`"${e}${t.slice(1)}`}function l(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.str=s,e.addCodeArg=a,e.strConcat=function(e,t){return t.emptyStr()?e:e.emptyStr()?t:s`${e}${t}`},e.stringify=function(e){return new n(l(e))},e.safeStringify=l,e.getProperty=function(t){return"string"==typeof t&&e.IDENTIFIER.test(t)?new n(`.${t}`):o`[${t}]`},e.getEsmExportName=function(t){if("string"==typeof t&&e.IDENTIFIER.test(t))return new n(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)},e.regexpCode=function(e){return new n(e.toString())}}(Jr)),Jr}var Zr,Qr,en={};function tn(){return Zr||(Zr=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=Xr();class r extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}}var n;!function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"}(n||(e.UsedValueState=n={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class o{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){return`${e}${(this._names[e]||this._nameGroup(e)).index++}`}_nameGroup(e){var t,r;if((null===(r=null===(t=this._parent)||void 0===t?void 0:t._prefixes)||void 0===r?void 0:r.has(e))||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}}e.Scope=o;class i extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=t._`.${new t.Name(r)}[${n}]`}}e.ValueScopeName=i;const s=t._`\n`;e.ValueScope=class extends o{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?s:t.nil}}get(){return this._scope}name(e){return new i(e,this._newName(e))}value(e,t){var r;if(void 0===t.ref)throw new Error("CodeGen: ref must be passed in value");const n=this.toName(e),{prefix:o}=n,i=null!==(r=t.key)&&void 0!==r?r:t.ref;let s=this._values[o];if(s){const e=s.get(i);if(e)return e}else s=this._values[o]=new Map;s.set(i,n);const a=this._scope[o]||(this._scope[o]=[]),c=a.length;return a[c]=t.ref,n.setValue(t,{property:o,itemIndex:c}),n}getValue(e,t){const r=this._values[e];if(r)return r.get(t)}scopeRefs(e,r=this._values){return this._reduceValues(r,r=>{if(void 0===r.scopePath)throw new Error(`CodeGen: name "${r}" has no value`);return t._`${e}${r.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,e=>{if(void 0===e.value)throw new Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,r)}_reduceValues(o,i,s={},a){let c=t.nil;for(const l in o){const d=o[l];if(!d)continue;const u=s[l]=s[l]||new Map;d.forEach(o=>{if(u.has(o))return;u.set(o,n.Started);let s=i(o);if(s){const r=this.opts.es5?e.varKinds.var:e.varKinds.const;c=t._`${c}${r} ${o} = ${s};${this.opts._n}`}else{if(!(s=null==a?void 0:a(o)))throw new r(o);c=t._`${c}${s}${this.opts._n}`}u.set(o,n.Completed)})}return c}}}(en)),en}function rn(){return Qr||(Qr=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=Xr(),r=tn();var n=Xr();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}});var o=tn();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class i{optimizeNodes(){return this}optimizeNames(e,t){return this}}class s extends i{constructor(e,t,r){super(),this.varKind=e,this.name=t,this.rhs=r}render({es5:e,_n:t}){const n=e?r.varKinds.var:this.varKind,o=void 0===this.rhs?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=N(this.rhs,e,t)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class a extends i{constructor(e,t,r){super(),this.lhs=e,this.rhs=t,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof t.Name)||e[this.lhs.str]||this.sideEffects)return this.rhs=N(this.rhs,e,r),this}get names(){return C(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}}class c extends a{constructor(e,t,r,n){super(e,r,n),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class l extends i{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class d extends i{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class u extends i{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class p extends i{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=N(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class h extends i{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){const{nodes:e}=this;let t=e.length;for(;t--;){const r=e[t].optimizeNodes();Array.isArray(r)?e.splice(t,1,...r):r?e[t]=r:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){const{nodes:r}=this;let n=r.length;for(;n--;){const o=r[n];o.optimizeNames(e,t)||(I(e,o.names),r.splice(n,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>k(e,t.names),{})}}class f extends h{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class m extends h{}class g extends f{}g.kind="else";class y extends f{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();const e=this.condition;if(!0===e)return this.nodes;let t=this.else;if(t){const e=t.optimizeNodes();t=this.else=Array.isArray(e)?new g(e):e}return t?!1===e?t instanceof y?t:t.nodes:this.nodes.length?this:new y(O(e),t instanceof y?[t]:t.nodes):!1!==e&&this.nodes.length?this:void 0}optimizeNames(e,t){var r;if(this.else=null===(r=this.else)||void 0===r?void 0:r.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=N(this.condition,e,t),this}get names(){const e=super.names;return C(e,this.condition),this.else&&k(e,this.else.names),e}}y.kind="if";class v extends f{}v.kind="for";class b extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=N(this.iteration,e,t),this}get names(){return k(super.names,this.iteration.names)}}class $ extends v{constructor(e,t,r,n){super(),this.varKind=e,this.name=t,this.from=r,this.to=n}render(e){const t=e.es5?r.varKinds.var:this.varKind,{name:n,from:o,to:i}=this;return`for(${t} ${n}=${o}; ${n}<${i}; ${n}++)`+super.render(e)}get names(){const e=C(super.names,this.from);return C(e,this.to)}}class w extends v{constructor(e,t,r,n){super(),this.loop=e,this.varKind=t,this.name=r,this.iterable=n}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=N(this.iterable,e,t),this}get names(){return k(super.names,this.iterable.names)}}class E extends f{constructor(e,t,r){super(),this.name=e,this.args=t,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}E.kind="func";class S extends h{render(e){return"return "+super.render(e)}}S.kind="return";class P extends f{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),null===(e=this.catch)||void 0===e||e.optimizeNodes(),null===(t=this.finally)||void 0===t||t.optimizeNodes(),this}optimizeNames(e,t){var r,n;return super.optimizeNames(e,t),null===(r=this.catch)||void 0===r||r.optimizeNames(e,t),null===(n=this.finally)||void 0===n||n.optimizeNames(e,t),this}get names(){const e=super.names;return this.catch&&k(e,this.catch.names),this.finally&&k(e,this.finally.names),e}}class L extends f{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}L.kind="catch";class _ extends f{render(e){return"finally"+super.render(e)}}_.kind="finally";function k(e,t){for(const r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function C(e,r){return r instanceof t._CodeOrName?k(e,r.names):e}function N(e,r,n){return e instanceof t.Name?i(e):(o=e)instanceof t._Code&&o._items.some(e=>e instanceof t.Name&&1===r[e.str]&&void 0!==n[e.str])?new t._Code(e._items.reduce((e,r)=>(r instanceof t.Name&&(r=i(r)),r instanceof t._Code?e.push(...r._items):e.push(r),e),[])):e;var o;function i(e){const t=n[e.str];return void 0===t||1!==r[e.str]?e:(delete r[e.str],t)}}function I(e,t){for(const r in t)e[r]=(e[r]||0)-(t[r]||0)}function O(e){return"boolean"==typeof e||"number"==typeof e||null===e?!e:t._`!${D(e)}`}e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?"\n":""},this._extScope=e,this._scope=new r.Scope({parent:e}),this._nodes=[new m]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){const r=this._extScope.value(e,t);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,r,n){const o=this._scope.toName(t);return void 0!==r&&n&&(this._constants[o.str]=r),this._leafNode(new s(e,o,r)),o}const(e,t,n){return this._def(r.varKinds.const,e,t,n)}let(e,t,n){return this._def(r.varKinds.let,e,t,n)}var(e,t,n){return this._def(r.varKinds.var,e,t,n)}assign(e,t,r){return this._leafNode(new a(e,t,r))}add(t,r){return this._leafNode(new c(t,e.operators.ADD,r))}code(e){return"function"==typeof e?e():e!==t.nil&&this._leafNode(new p(e)),this}object(...e){const r=["{"];for(const[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,t.addCodeArg)(r,o));return r.push("}"),new t._Code(r)}if(e,t,r){if(this._blockNode(new y(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new y(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(y,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new b(e),t)}forRange(e,t,n,o,i=(this.opts.es5?r.varKinds.var:r.varKinds.let)){const s=this._scope.toName(e);return this._for(new $(i,s,t,n),()=>o(s))}forOf(e,n,o,i=r.varKinds.const){const s=this._scope.toName(e);if(this.opts.es5){const e=n instanceof t.Name?n:this.var("_arr",n);return this.forRange("_i",0,t._`${e}.length`,r=>{this.var(s,t._`${e}[${r}]`),o(s)})}return this._for(new w("of",i,s,n),()=>o(s))}forIn(e,n,o,i=(this.opts.es5?r.varKinds.var:r.varKinds.const)){if(this.opts.ownProperties)return this.forOf(e,t._`Object.keys(${n})`,o);const s=this._scope.toName(e);return this._for(new w("in",i,s,n),()=>o(s))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new d(e))}return(e){const t=new S;if(this._blockNode(t),this.code(e),1!==t.nodes.length)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(S)}try(e,t,r){if(!t&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');const n=new P;if(this._blockNode(n),this.code(e),t){const e=this.name("e");this._currNode=n.catch=new L(e),t(e)}return r&&(this._currNode=n.finally=new _,this.code(r)),this._endBlockNode(L,_)}throw(e){return this._leafNode(new u(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){const t=this._blockStarts.pop();if(void 0===t)throw new Error("CodeGen: not in self-balancing block");const r=this._nodes.length-t;if(r<0||void 0!==e&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,r=t.nil,n,o){return this._blockNode(new E(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(E)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){const r=this._currNode;if(r instanceof e||t&&r instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){const t=this._currNode;if(!(t instanceof y))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){const e=this._nodes;return e[e.length-1]}set _currNode(e){const t=this._nodes;t[t.length-1]=e}},e.not=O;const A=x(e.operators.AND);e.and=function(...e){return e.reduce(A)};const T=x(e.operators.OR);function x(e){return(r,n)=>r===t.nil?n:n===t.nil?r:t._`${D(r)} ${e} ${D(n)}`}function D(e){return e instanceof t.Name?e:t._`(${e})`}e.or=function(...e){return e.reduce(T)}}(Yr)),Yr}var nn,on={};function sn(){if(nn)return on;nn=1,Object.defineProperty(on,"__esModule",{value:!0}),on.checkStrictMode=on.getErrorPath=on.Type=on.useFunc=on.setEvaluated=on.evaluatedPropsToName=on.mergeEvaluated=on.eachItem=on.unescapeJsonPointer=on.escapeJsonPointer=on.escapeFragment=on.unescapeFragment=on.schemaRefOrVal=on.schemaHasRulesButRef=on.schemaHasRules=on.checkUnknownRules=on.alwaysValidSchema=on.toHash=void 0;const e=rn(),t=Xr();function r(e,t=e.schema){const{opts:r,self:n}=e;if(!r.strictSchema)return;if("boolean"==typeof t)return;const o=n.RULES.keywords;for(const r in t)o[r]||u(e,`unknown keyword: "${r}"`)}function n(e,t){if("boolean"==typeof e)return!e;for(const r in e)if(t[r])return!0;return!1}function o(e){return"number"==typeof e?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}function i(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function s({mergeNames:t,mergeToName:r,mergeValues:n,resultToName:o}){return(i,s,a,c)=>{const l=void 0===a?s:a instanceof e.Name?(s instanceof e.Name?t(i,s,a):r(i,s,a),a):s instanceof e.Name?(r(i,a,s),s):n(s,a);return c!==e.Name||l instanceof e.Name?l:o(i,l)}}function a(t,r){if(!0===r)return t.var("props",!0);const n=t.var("props",e._`{}`);return void 0!==r&&c(t,n,r),n}function c(t,r,n){Object.keys(n).forEach(n=>t.assign(e._`${r}${(0,e.getProperty)(n)}`,!0))}on.toHash=function(e){const t={};for(const r of e)t[r]=!0;return t},on.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(r(e,t),!n(t,e.self.RULES.all))},on.checkUnknownRules=r,on.schemaHasRules=n,on.schemaHasRulesButRef=function(e,t){if("boolean"==typeof e)return!e;for(const r in e)if("$ref"!==r&&t.all[r])return!0;return!1},on.schemaRefOrVal=function({topSchemaRef:t,schemaPath:r},n,o,i){if(!i){if("number"==typeof n||"boolean"==typeof n)return n;if("string"==typeof n)return e._`${n}`}return e._`${t}${r}${(0,e.getProperty)(o)}`},on.unescapeFragment=function(e){return i(decodeURIComponent(e))},on.escapeFragment=function(e){return encodeURIComponent(o(e))},on.escapeJsonPointer=o,on.unescapeJsonPointer=i,on.eachItem=function(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)},on.mergeEvaluated={props:s({mergeNames:(t,r,n)=>t.if(e._`${n} !== true && ${r} !== undefined`,()=>{t.if(e._`${r} === true`,()=>t.assign(n,!0),()=>t.assign(n,e._`${n} || {}`).code(e._`Object.assign(${n}, ${r})`))}),mergeToName:(t,r,n)=>t.if(e._`${n} !== true`,()=>{!0===r?t.assign(n,!0):(t.assign(n,e._`${n} || {}`),c(t,n,r))}),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:a}),items:s({mergeNames:(t,r,n)=>t.if(e._`${n} !== true && ${r} !== undefined`,()=>t.assign(n,e._`${r} === true ? true : ${n} > ${r} ? ${n} : ${r}`)),mergeToName:(t,r,n)=>t.if(e._`${n} !== true`,()=>t.assign(n,!0===r||e._`${n} > ${r} ? ${n} : ${r}`)),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},on.evaluatedPropsToName=a,on.setEvaluated=c;const l={};var d;function u(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,!0===r)throw new Error(t);e.self.logger.warn(t)}}return on.useFunc=function(e,r){return e.scopeValue("func",{ref:r,code:l[r.code]||(l[r.code]=new t._Code(r.code))})},function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"}(d||(on.Type=d={})),on.getErrorPath=function(t,r,n){if(t instanceof e.Name){const o=r===d.Num;return n?o?e._`"[" + ${t} + "]"`:e._`"['" + ${t} + "']"`:o?e._`"/" + ${t}`:e._`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,e.getProperty)(t).toString():"/"+o(t)},on.checkStrictMode=u,on}var an,cn,ln,dn={};function un(){if(an)return dn;an=1,Object.defineProperty(dn,"__esModule",{value:!0});const e=rn(),t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return dn.default=t,dn}function pn(){return cn||(cn=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=rn(),r=sn(),n=un();function o(e,r){const o=e.const("err",r);e.if(t._`${n.default.vErrors} === null`,()=>e.assign(n.default.vErrors,t._`[${o}]`),t._`${n.default.vErrors}.push(${o})`),e.code(t._`${n.default.errors}++`)}function i(e,r){const{gen:n,validateName:o,schemaEnv:i}=e;i.$async?n.throw(t._`new ${e.ValidationError}(${r})`):(n.assign(t._`${o}.errors`,r),n.return(!1))}e.keywordError={message:({keyword:e})=>t.str`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:r})=>r?t.str`"${e}" keyword must be ${r} ($data)`:t.str`"${e}" keyword is invalid ($data)`},e.reportError=function(r,n=e.keywordError,s,c){const{it:l}=r,{gen:d,compositeRule:u,allErrors:p}=l,h=a(r,n,s);(null!=c?c:u||p)?o(d,h):i(l,t._`[${h}]`)},e.reportExtraError=function(t,r=e.keywordError,s){const{it:c}=t,{gen:l,compositeRule:d,allErrors:u}=c;o(l,a(t,r,s)),d||u||i(c,n.default.vErrors)},e.resetErrorsCount=function(e,r){e.assign(n.default.errors,r),e.if(t._`${n.default.vErrors} !== null`,()=>e.if(r,()=>e.assign(t._`${n.default.vErrors}.length`,r),()=>e.assign(n.default.vErrors,null)))},e.extendErrors=function({gen:e,keyword:r,schemaValue:o,data:i,errsCount:s,it:a}){if(void 0===s)throw new Error("ajv implementation error");const c=e.name("err");e.forRange("i",s,n.default.errors,s=>{e.const(c,t._`${n.default.vErrors}[${s}]`),e.if(t._`${c}.instancePath === undefined`,()=>e.assign(t._`${c}.instancePath`,(0,t.strConcat)(n.default.instancePath,a.errorPath))),e.assign(t._`${c}.schemaPath`,t.str`${a.errSchemaPath}/${r}`),a.opts.verbose&&(e.assign(t._`${c}.schema`,o),e.assign(t._`${c}.data`,i))})};const s={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function a(e,r,o){const{createErrors:i}=e.it;return!1===i?t._`{}`:function(e,r,o={}){const{gen:i,it:a}=e,d=[c(a,o),l(e,o)];return function(e,{params:r,message:o},i){const{keyword:a,data:c,schemaValue:l,it:d}=e,{opts:u,propertyName:p,topSchemaRef:h,schemaPath:f}=d;i.push([s.keyword,a],[s.params,"function"==typeof r?r(e):r||t._`{}`]),u.messages&&i.push([s.message,"function"==typeof o?o(e):o]);u.verbose&&i.push([s.schema,l],[s.parentSchema,t._`${h}${f}`],[n.default.data,c]);p&&i.push([s.propertyName,p])}(e,r,d),i.object(...d)}(e,r,o)}function c({errorPath:e},{instancePath:o}){const i=o?t.str`${e}${(0,r.getErrorPath)(o,r.Type.Str)}`:e;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,i)]}function l({keyword:e,it:{errSchemaPath:n}},{schemaPath:o,parentSchema:i}){let a=i?n:t.str`${n}/${e}`;return o&&(a=t.str`${a}${(0,r.getErrorPath)(o,r.Type.Str)}`),[s.schemaPath,a]}}(Kr)),Kr}var hn,fn={},mn={};function gn(){if(hn)return mn;hn=1,Object.defineProperty(mn,"__esModule",{value:!0}),mn.getRules=mn.isJSONType=void 0;const e=new Set(["string","number","integer","boolean","null","object","array"]);return mn.isJSONType=function(t){return"string"==typeof t&&e.has(t)},mn.getRules=function(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}},mn}var yn,vn,bn={};function $n(){if(yn)return bn;function e(e,r){return r.rules.some(r=>t(e,r))}function t(e,t){var r;return void 0!==e[t.keyword]||(null===(r=t.definition.implements)||void 0===r?void 0:r.some(t=>void 0!==e[t]))}return yn=1,Object.defineProperty(bn,"__esModule",{value:!0}),bn.shouldUseRule=bn.shouldUseGroup=bn.schemaHasRulesForType=void 0,bn.schemaHasRulesForType=function({schema:t,self:r},n){const o=r.RULES.types[n];return o&&!0!==o&&e(t,o)},bn.shouldUseGroup=e,bn.shouldUseRule=t,bn}function wn(){if(vn)return fn;vn=1,Object.defineProperty(fn,"__esModule",{value:!0}),fn.reportTypeError=fn.checkDataTypes=fn.checkDataType=fn.coerceAndCheckDataType=fn.getJSONTypes=fn.getSchemaTypes=fn.DataType=void 0;const e=gn(),t=$n(),r=pn(),n=rn(),o=sn();var i;function s(t){const r=Array.isArray(t)?t:t?[t]:[];if(r.every(e.isJSONType))return r;throw new Error("type must be JSONType or JSONType[]: "+r.join(","))}!function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"}(i||(fn.DataType=i={})),fn.getSchemaTypes=function(e){const t=s(e.type);if(t.includes("null")){if(!1===e.nullable)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&void 0!==e.nullable)throw new Error('"nullable" cannot be used without "type"');!0===e.nullable&&t.push("null")}return t},fn.getJSONTypes=s,fn.coerceAndCheckDataType=function(e,r){const{gen:o,data:s,opts:c}=e,d=function(e,t){return t?e.filter(e=>a.has(e)||"array"===t&&"array"===e):[]}(r,c.coerceTypes),p=r.length>0&&!(0===d.length&&1===r.length&&(0,t.schemaHasRulesForType)(e,r[0]));if(p){const t=l(r,s,c.strictNumbers,i.Wrong);o.if(t,()=>{d.length?function(e,t,r){const{gen:o,data:i,opts:s}=e,c=o.let("dataType",n._`typeof ${i}`),d=o.let("coerced",n._`undefined`);"array"===s.coerceTypes&&o.if(n._`${c} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>o.assign(i,n._`${i}[0]`).assign(c,n._`typeof ${i}`).if(l(t,i,s.strictNumbers),()=>o.assign(d,i)));o.if(n._`${d} !== undefined`);for(const e of r)(a.has(e)||"array"===e&&"array"===s.coerceTypes)&&p(e);function p(e){switch(e){case"string":return void o.elseIf(n._`${c} == "number" || ${c} == "boolean"`).assign(d,n._`"" + ${i}`).elseIf(n._`${i} === null`).assign(d,n._`""`);case"number":return void o.elseIf(n._`${c} == "boolean" || ${i} === null
2
- || (${c} == "string" && ${i} && ${i} == +${i})`).assign(d,n._`+${i}`);case"integer":return void o.elseIf(n._`${c} === "boolean" || ${i} === null
3
- || (${c} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(d,n._`+${i}`);case"boolean":return void o.elseIf(n._`${i} === "false" || ${i} === 0 || ${i} === null`).assign(d,!1).elseIf(n._`${i} === "true" || ${i} === 1`).assign(d,!0);case"null":return o.elseIf(n._`${i} === "" || ${i} === 0 || ${i} === false`),void o.assign(d,null);case"array":o.elseIf(n._`${c} === "string" || ${c} === "number"
4
- || ${c} === "boolean" || ${i} === null`).assign(d,n._`[${i}]`)}}o.else(),u(e),o.endIf(),o.if(n._`${d} !== undefined`,()=>{o.assign(i,d),function({gen:e,parentData:t,parentDataProperty:r},o){e.if(n._`${t} !== undefined`,()=>e.assign(n._`${t}[${r}]`,o))}(e,d)})}(e,r,d):u(e)})}return p};const a=new Set(["string","number","integer","boolean","null"]);function c(e,t,r,o=i.Correct){const s=o===i.Correct?n.operators.EQ:n.operators.NEQ;let a;switch(e){case"null":return n._`${t} ${s} null`;case"array":a=n._`Array.isArray(${t})`;break;case"object":a=n._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":a=c(n._`!(${t} % 1) && !isNaN(${t})`);break;case"number":a=c();break;default:return n._`typeof ${t} ${s} ${e}`}return o===i.Correct?a:(0,n.not)(a);function c(e=n.nil){return(0,n.and)(n._`typeof ${t} == "number"`,e,r?n._`isFinite(${t})`:n.nil)}}function l(e,t,r,i){if(1===e.length)return c(e[0],t,r,i);let s;const a=(0,o.toHash)(e);if(a.array&&a.object){const e=n._`typeof ${t} != "object"`;s=a.null?e:n._`!${t} || ${e}`,delete a.null,delete a.array,delete a.object}else s=n.nil;a.number&&delete a.integer;for(const e in a)s=(0,n.and)(s,c(e,t,r,i));return s}fn.checkDataType=c,fn.checkDataTypes=l;const d={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?n._`{type: ${e}}`:n._`{type: ${t}}`};function u(e){const t=function(e){const{gen:t,data:r,schema:n}=e,i=(0,o.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:e}}(e);(0,r.reportError)(t,d)}return fn.reportTypeError=u,fn}var En,Sn={};var Pn,Ln,_n={},kn={};function Cn(){if(Pn)return kn;Pn=1,Object.defineProperty(kn,"__esModule",{value:!0}),kn.validateUnion=kn.validateArray=kn.usePattern=kn.callValidateCode=kn.schemaProperties=kn.allSchemaProperties=kn.noPropertyInData=kn.propertyInData=kn.isOwnProperty=kn.hasPropFunc=kn.reportMissingProp=kn.checkMissingProp=kn.checkReportMissingProp=void 0;const e=rn(),t=sn(),r=un(),n=sn();function o(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:e._`Object.prototype.hasOwnProperty`})}function i(t,r,n){return e._`${o(t)}.call(${r}, ${n})`}function s(t,r,n,o){const s=e._`${r}${(0,e.getProperty)(n)} === undefined`;return o?(0,e.or)(s,(0,e.not)(i(t,r,n))):s}function a(e){return e?Object.keys(e).filter(e=>"__proto__"!==e):[]}kn.checkReportMissingProp=function(t,r){const{gen:n,data:o,it:i}=t;n.if(s(n,o,r,i.opts.ownProperties),()=>{t.setParams({missingProperty:e._`${r}`},!0),t.error()})},kn.checkMissingProp=function({gen:t,data:r,it:{opts:n}},o,i){return(0,e.or)(...o.map(o=>(0,e.and)(s(t,r,o,n.ownProperties),e._`${i} = ${o}`)))},kn.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},kn.hasPropFunc=o,kn.isOwnProperty=i,kn.propertyInData=function(t,r,n,o){const s=e._`${r}${(0,e.getProperty)(n)} !== undefined`;return o?e._`${s} && ${i(t,r,n)}`:s},kn.noPropertyInData=s,kn.allSchemaProperties=a,kn.schemaProperties=function(e,r){return a(r).filter(n=>!(0,t.alwaysValidSchema)(e,r[n]))},kn.callValidateCode=function({schemaCode:t,data:n,it:{gen:o,topSchemaRef:i,schemaPath:s,errorPath:a},it:c},l,d,u){const p=u?e._`${t}, ${n}, ${i}${s}`:n,h=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,a)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&h.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const f=e._`${p}, ${o.object(...h)}`;return d!==e.nil?e._`${l}.call(${d}, ${f})`:e._`${l}(${f})`};const c=e._`new RegExp`;return kn.usePattern=function({gen:t,it:{opts:r}},o){const i=r.unicodeRegExp?"u":"",{regExp:s}=r.code,a=s(o,i);return t.scopeValue("pattern",{key:a.toString(),ref:a,code:e._`${"new RegExp"===s.code?c:(0,n.useFunc)(t,s)}(${o}, ${i})`})},kn.validateArray=function(r){const{gen:n,data:o,keyword:i,it:s}=r,a=n.name("valid");if(s.allErrors){const e=n.let("valid",!0);return c(()=>n.assign(e,!1)),e}return n.var(a,!0),c(()=>n.break()),a;function c(s){const c=n.const("len",e._`${o}.length`);n.forRange("i",0,c,o=>{r.subschema({keyword:i,dataProp:o,dataPropType:t.Type.Num},a),n.if((0,e.not)(a),s)})}},kn.validateUnion=function(r){const{gen:n,schema:o,keyword:i,it:s}=r;if(!Array.isArray(o))throw new Error("ajv implementation error");if(o.some(e=>(0,t.alwaysValidSchema)(s,e))&&!s.opts.unevaluated)return;const a=n.let("valid",!1),c=n.name("_valid");n.block(()=>o.forEach((t,o)=>{const s=r.subschema({keyword:i,schemaProp:o,compositeRule:!0},c);n.assign(a,e._`${a} || ${c}`);r.mergeValidEvaluated(s,c)||n.if((0,e.not)(a))})),r.result(a,()=>r.reset(),()=>r.error(!0))},kn}function Nn(){if(Ln)return _n;Ln=1,Object.defineProperty(_n,"__esModule",{value:!0}),_n.validateKeywordUsage=_n.validSchemaType=_n.funcKeywordCode=_n.macroKeywordCode=void 0;const e=rn(),t=un(),r=Cn(),n=pn();function o(t){const{gen:r,data:n,it:o}=t;r.if(o.parentData,()=>r.assign(n,e._`${o.parentData}[${o.parentDataProperty}]`))}function i(t,r,n){if(void 0===n)throw new Error(`keyword "${r}" failed to compile`);return t.scopeValue("keyword","function"==typeof n?{ref:n}:{ref:n,code:(0,e.stringify)(n)})}return _n.macroKeywordCode=function(t,r){const{gen:n,keyword:o,schema:s,parentSchema:a,it:c}=t,l=r.macro.call(c.self,s,a,c),d=i(n,o,l);!1!==c.opts.validateSchema&&c.self.validateSchema(l,!0);const u=n.name("valid");t.subschema({schema:l,schemaPath:e.nil,errSchemaPath:`${c.errSchemaPath}/${o}`,topSchemaRef:d,compositeRule:!0},u),t.pass(u,()=>t.error(!0))},_n.funcKeywordCode=function(s,a){var c;const{gen:l,keyword:d,schema:u,parentSchema:p,$data:h,it:f}=s;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(f,a);const m=!h&&a.compile?a.compile.call(f.self,u,p,f):a.validate,g=i(l,d,m),y=l.let("valid");function v(n=(a.async?e._`await `:e.nil)){const o=f.opts.passContext?t.default.this:t.default.self,i=!("compile"in a&&!h||!1===a.schema);l.assign(y,e._`${n}${(0,r.callValidateCode)(s,g,o,i)}`,a.modifying)}function b(t){var r;l.if((0,e.not)(null!==(r=a.valid)&&void 0!==r?r:y),t)}s.block$data(y,function(){if(!1===a.errors)v(),a.modifying&&o(s),b(()=>s.error());else{const r=a.async?function(){const t=l.let("ruleErrs",null);return l.try(()=>v(e._`await `),r=>l.assign(y,!1).if(e._`${r} instanceof ${f.ValidationError}`,()=>l.assign(t,e._`${r}.errors`),()=>l.throw(r))),t}():function(){const t=e._`${g}.errors`;return l.assign(t,null),v(e.nil),t}();a.modifying&&o(s),b(()=>function(r,o){const{gen:i}=r;i.if(e._`Array.isArray(${o})`,()=>{i.assign(t.default.vErrors,e._`${t.default.vErrors} === null ? ${o} : ${t.default.vErrors}.concat(${o})`).assign(t.default.errors,e._`${t.default.vErrors}.length`),(0,n.extendErrors)(r)},()=>r.error())}(s,r))}}),s.ok(null!==(c=a.valid)&&void 0!==c?c:y)},_n.validSchemaType=function(e,t,r=!1){return!t.length||t.some(t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||r&&void 0===e)},_n.validateKeywordUsage=function({schema:e,opts:t,self:r,errSchemaPath:n},o,i){if(Array.isArray(o.keyword)?!o.keyword.includes(i):o.keyword!==i)throw new Error("ajv implementation error");const s=o.dependencies;if(null==s?void 0:s.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(o.validateSchema){if(!o.validateSchema(e[i])){const e=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if("log"!==t.validateSchema)throw new Error(e);r.logger.error(e)}}},_n}var In,On={};var An,Tn,xn={};function Dn(){return Tn||(Tn=1,An=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var n,o,i;if(Array.isArray(t)){if((n=t.length)!=r.length)return!1;for(o=n;0!==o--;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((n=(i=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(o=n;0!==o--;)if(!Object.prototype.hasOwnProperty.call(r,i[o]))return!1;for(o=n;0!==o--;){var s=i[o];if(!e(t[s],r[s]))return!1}return!0}return t!=t&&r!=r}),An}var jn,Rn,Fn,Mn={exports:{}};function Gn(){if(jn)return Mn.exports;jn=1;var e=Mn.exports=function(e,r,n){"function"==typeof r&&(n=r,r={}),t(r,"function"==typeof(n=r.cb||n)?n:n.pre||function(){},n.post||function(){},e,"",e)};function t(n,o,i,s,a,c,l,d,u,p){if(s&&"object"==typeof s&&!Array.isArray(s)){for(var h in o(s,a,c,l,d,u,p),s){var f=s[h];if(Array.isArray(f)){if(h in e.arrayKeywords)for(var m=0;m<f.length;m++)t(n,o,i,f[m],a+"/"+h+"/"+m,c,a,h,s,m)}else if(h in e.propsKeywords){if(f&&"object"==typeof f)for(var g in f)t(n,o,i,f[g],a+"/"+h+"/"+r(g),c,a,h,s,g)}else(h in e.keywords||n.allKeys&&!(h in e.skipKeywords))&&t(n,o,i,f,a+"/"+h,c,a,h,s)}i(s,a,c,l,d,u,p)}}function r(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}return e.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},e.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},e.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},e.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},Mn.exports}function Un(){if(Rn)return xn;Rn=1,Object.defineProperty(xn,"__esModule",{value:!0}),xn.getSchemaRefs=xn.resolveUrl=xn.normalizeId=xn._getFullPath=xn.getFullPath=xn.inlineRef=void 0;const e=sn(),t=Dn(),r=Gn(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);xn.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!i(e):!!t&&s(e)<=t)};const o=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function i(e){for(const t in e){if(o.has(t))return!0;const r=e[t];if(Array.isArray(r)&&r.some(i))return!0;if("object"==typeof r&&i(r))return!0}return!1}function s(t){let r=0;for(const o in t){if("$ref"===o)return 1/0;if(r++,!n.has(o)&&("object"==typeof t[o]&&(0,e.eachItem)(t[o],e=>r+=s(e)),r===1/0))return 1/0}return r}function a(e,t="",r){!1!==r&&(t=d(t));const n=e.parse(t);return c(e,n)}function c(e,t){return e.serialize(t).split("#")[0]+"#"}xn.getFullPath=a,xn._getFullPath=c;const l=/#\/?$/;function d(e){return e?e.replace(l,""):""}xn.normalizeId=d,xn.resolveUrl=function(e,t,r){return r=d(r),e.resolve(t,r)};const u=/^[a-z_][-a-z0-9._]*$/i;return xn.getSchemaRefs=function(e,n){if("boolean"==typeof e)return{};const{schemaId:o,uriResolver:i}=this.opts,s=d(e[o]||n),c={"":s},l=a(i,s,!1),p={},h=new Set;return r(e,{allKeys:!0},(e,t,r,n)=>{if(void 0===n)return;const i=l+t;let s=c[n];function a(t){const r=this.opts.uriResolver.resolve;if(t=d(s?r(s,t):t),h.has(t))throw m(t);h.add(t);let n=this.refs[t];return"string"==typeof n&&(n=this.refs[n]),"object"==typeof n?f(e,n.schema,t):t!==d(i)&&("#"===t[0]?(f(e,p[t],t),p[t]=e):this.refs[t]=i),t}function g(e){if("string"==typeof e){if(!u.test(e))throw new Error(`invalid anchor "${e}"`);a.call(this,`#${e}`)}}"string"==typeof e[o]&&(s=a.call(this,e[o])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),c[t]=s}),p;function f(e,r,n){if(void 0!==r&&!t(e,r))throw m(n)}function m(e){return new Error(`reference "${e}" resolves to more than one schema`)}},xn}function Bn(){if(Fn)return Wr;Fn=1,Object.defineProperty(Wr,"__esModule",{value:!0}),Wr.getData=Wr.KeywordCxt=Wr.validateFunctionCode=void 0;const e=function(){if(ln)return qr;ln=1,Object.defineProperty(qr,"__esModule",{value:!0}),qr.boolOrEmptySchema=qr.topBoolOrEmptySchema=void 0;const e=pn(),t=rn(),r=un(),n={message:"boolean schema is false"};function o(t,r){const{gen:o,data:i}=t,s={gen:o,keyword:"false schema",data:i,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,e.reportError)(s,n,void 0,r)}return qr.topBoolOrEmptySchema=function(e){const{gen:n,schema:i,validateName:s}=e;!1===i?o(e,!1):"object"==typeof i&&!0===i.$async?n.return(r.default.data):(n.assign(t._`${s}.errors`,null),n.return(!0))},qr.boolOrEmptySchema=function(e,t){const{gen:r,schema:n}=e;!1===n?(r.var(t,!1),o(e)):r.var(t,!0)},qr}(),t=wn(),r=$n(),n=wn(),o=function(){if(En)return Sn;En=1,Object.defineProperty(Sn,"__esModule",{value:!0}),Sn.assignDefaults=void 0;const e=rn(),t=sn();function r(r,n,o){const{gen:i,compositeRule:s,data:a,opts:c}=r;if(void 0===o)return;const l=e._`${a}${(0,e.getProperty)(n)}`;if(s)return void(0,t.checkStrictMode)(r,`default is ignored for: ${l}`);let d=e._`${l} === undefined`;"empty"===c.useDefaults&&(d=e._`${d} || ${l} === null || ${l} === ""`),i.if(d,e._`${l} = ${(0,e.stringify)(o)}`)}return Sn.assignDefaults=function(e,t){const{properties:n,items:o}=e.schema;if("object"===t&&n)for(const t in n)r(e,t,n[t].default);else"array"===t&&Array.isArray(o)&&o.forEach((t,n)=>r(e,n,t.default))},Sn}(),i=Nn(),s=function(){if(In)return On;In=1,Object.defineProperty(On,"__esModule",{value:!0}),On.extendSubschemaMode=On.extendSubschemaData=On.getSubschema=void 0;const e=rn(),t=sn();return On.getSubschema=function(r,{keyword:n,schemaProp:o,schema:i,schemaPath:s,errSchemaPath:a,topSchemaRef:c}){if(void 0!==n&&void 0!==i)throw new Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==n){const i=r.schema[n];return void 0===o?{schema:i,schemaPath:e._`${r.schemaPath}${(0,e.getProperty)(n)}`,errSchemaPath:`${r.errSchemaPath}/${n}`}:{schema:i[o],schemaPath:e._`${r.schemaPath}${(0,e.getProperty)(n)}${(0,e.getProperty)(o)}`,errSchemaPath:`${r.errSchemaPath}/${n}/${(0,t.escapeFragment)(o)}`}}if(void 0!==i){if(void 0===s||void 0===a||void 0===c)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:i,schemaPath:s,topSchemaRef:c,errSchemaPath:a}}throw new Error('either "keyword" or "schema" must be passed')},On.extendSubschemaData=function(r,n,{dataProp:o,dataPropType:i,data:s,dataTypes:a,propertyName:c}){if(void 0!==s&&void 0!==o)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:l}=n;if(void 0!==o){const{errorPath:s,dataPathArr:a,opts:c}=n;d(l.let("data",e._`${n.data}${(0,e.getProperty)(o)}`,!0)),r.errorPath=e.str`${s}${(0,t.getErrorPath)(o,i,c.jsPropertySyntax)}`,r.parentDataProperty=e._`${o}`,r.dataPathArr=[...a,r.parentDataProperty]}function d(e){r.data=e,r.dataLevel=n.dataLevel+1,r.dataTypes=[],n.definedProperties=new Set,r.parentData=n.data,r.dataNames=[...n.dataNames,e]}void 0!==s&&(d(s instanceof e.Name?s:l.let("data",s,!0)),void 0!==c&&(r.propertyName=c)),a&&(r.dataTypes=a)},On.extendSubschemaMode=function(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:i}){void 0!==n&&(e.compositeRule=n),void 0!==o&&(e.createErrors=o),void 0!==i&&(e.allErrors=i),e.jtdDiscriminator=t,e.jtdMetadata=r},On}(),a=rn(),c=un(),l=Un(),d=sn(),u=pn();function p({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},i){o.code.es5?e.func(t,a._`${c.default.data}, ${c.default.valCxt}`,n.$async,()=>{e.code(a._`"use strict"; ${h(r,o)}`),function(e,t){e.if(c.default.valCxt,()=>{e.var(c.default.instancePath,a._`${c.default.valCxt}.${c.default.instancePath}`),e.var(c.default.parentData,a._`${c.default.valCxt}.${c.default.parentData}`),e.var(c.default.parentDataProperty,a._`${c.default.valCxt}.${c.default.parentDataProperty}`),e.var(c.default.rootData,a._`${c.default.valCxt}.${c.default.rootData}`),t.dynamicRef&&e.var(c.default.dynamicAnchors,a._`${c.default.valCxt}.${c.default.dynamicAnchors}`)},()=>{e.var(c.default.instancePath,a._`""`),e.var(c.default.parentData,a._`undefined`),e.var(c.default.parentDataProperty,a._`undefined`),e.var(c.default.rootData,c.default.data),t.dynamicRef&&e.var(c.default.dynamicAnchors,a._`{}`)})}(e,o),e.code(i)}):e.func(t,a._`${c.default.data}, ${function(e){return a._`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${e.dynamicRef?a._`, ${c.default.dynamicAnchors}={}`:a.nil}}={}`}(o)}`,n.$async,()=>e.code(h(r,o)).code(i))}function h(e,t){const r="object"==typeof e&&e[t.schemaId];return r&&(t.code.source||t.code.process)?a._`/*# sourceURL=${r} */`:a.nil}function f(t,r){g(t)&&(y(t),m(t))?function(e,t){const{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&b(e);(function(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,l.resolveUrl)(e.opts.uriResolver,e.baseId,t))})(e),function(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}(e);const i=n.const("_errs",c.default.errors);v(e,i),n.var(t,a._`${i} === ${c.default.errors}`)}(t,r):(0,e.boolOrEmptySchema)(t,r)}function m({schema:e,self:t}){if("boolean"==typeof e)return!e;for(const r in e)if(t.RULES.all[r])return!0;return!1}function g(e){return"boolean"!=typeof e.schema}function y(e){(0,d.checkUnknownRules)(e),function(e){const{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}(e)}function v(e,r){if(e.opts.jtd)return $(e,[],!1,r);const n=(0,t.getSchemaTypes)(e.schema);$(e,n,!(0,t.coerceAndCheckDataType)(e,n),r)}function b({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){const i=r.$comment;if(!0===o.$comment)e.code(a._`${c.default.self}.logger.log(${i})`);else if("function"==typeof o.$comment){const r=a.str`${n}/$comment`,o=e.scopeValue("root",{ref:t.root});e.code(a._`${c.default.self}.opts.$comment(${i}, ${r}, ${o}.schema)`)}}function $(e,t,o,i){const{gen:s,schema:l,data:u,allErrors:p,opts:h,self:f}=e,{RULES:m}=f;function g(d){(0,r.shouldUseGroup)(l,d)&&(d.type?(s.if((0,n.checkDataType)(d.type,u,h.strictNumbers)),w(e,d),1===t.length&&t[0]===d.type&&o&&(s.else(),(0,n.reportTypeError)(e)),s.endIf()):w(e,d),p||s.if(a._`${c.default.errors} === ${i||0}`))}!l.$ref||!h.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(l,m)?(h.jtd||function(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;(function(e,t){if(!t.length)return;if(!e.dataTypes.length)return void(e.dataTypes=t);t.forEach(t=>{S(e.dataTypes,t)||P(e,`type "${t}" not allowed by context "${e.dataTypes.join(",")}"`)}),function(e,t){const r=[];for(const n of e.dataTypes)S(t,n)?r.push(n):t.includes("integer")&&"number"===n&&r.push("integer");e.dataTypes=r}(e,t)})(e,t),e.opts.allowUnionTypes||function(e,t){t.length>1&&(2!==t.length||!t.includes("null"))&&P(e,"use allowUnionTypes to allow union type keyword")}(e,t);!function(e,t){const n=e.self.RULES.all;for(const o in n){const i=n[o];if("object"==typeof i&&(0,r.shouldUseRule)(e.schema,i)){const{type:r}=i.definition;r.length&&!r.some(e=>E(t,e))&&P(e,`missing type "${r.join(",")}" for keyword "${o}"`)}}}(e,e.dataTypes)}(e,t),s.block(()=>{for(const e of m.rules)g(e);g(m.post)})):s.block(()=>_(e,"$ref",m.all.$ref.definition))}function w(e,t){const{gen:n,schema:i,opts:{useDefaults:s}}=e;s&&(0,o.assignDefaults)(e,t.type),n.block(()=>{for(const n of t.rules)(0,r.shouldUseRule)(i,n)&&_(e,n.keyword,n.definition,t.type)})}function E(e,t){return e.includes(t)||"number"===t&&e.includes("integer")}function S(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function P(e,t){t+=` at "${e.schemaEnv.baseId+e.errSchemaPath}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}Wr.validateFunctionCode=function(t){g(t)&&(y(t),m(t))?function(e){const{schema:t,opts:r,gen:n}=e;p(e,()=>{r.$comment&&t.$comment&&b(e),function(e){const{schema:t,opts:r}=e;void 0!==t.default&&r.useDefaults&&r.strictSchema&&(0,d.checkStrictMode)(e,"default is ignored in the schema root")}(e),n.let(c.default.vErrors,null),n.let(c.default.errors,0),r.unevaluated&&function(e){const{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",a._`${r}.evaluated`),t.if(a._`${e.evaluated}.dynamicProps`,()=>t.assign(a._`${e.evaluated}.props`,a._`undefined`)),t.if(a._`${e.evaluated}.dynamicItems`,()=>t.assign(a._`${e.evaluated}.items`,a._`undefined`))}(e),v(e),function(e){const{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:i}=e;r.$async?t.if(a._`${c.default.errors} === 0`,()=>t.return(c.default.data),()=>t.throw(a._`new ${o}(${c.default.vErrors})`)):(t.assign(a._`${n}.errors`,c.default.vErrors),i.unevaluated&&function({gen:e,evaluated:t,props:r,items:n}){r instanceof a.Name&&e.assign(a._`${t}.props`,r);n instanceof a.Name&&e.assign(a._`${t}.items`,n)}(e),t.return(a._`${c.default.errors} === 0`))}(e)})}(t):p(t,()=>(0,e.topBoolOrEmptySchema)(t))};class L{constructor(e,t,r){if((0,i.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",N(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,i.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:!1!==t.errors)&&(this.errsCount=e.gen.const("_errs",c.default.errors))}result(e,t,r){this.failResult((0,a.not)(e),t,r)}failResult(e,t,r){this.gen.if(e),r?r():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,a.not)(e),void 0,t)}fail(e){if(void 0===e)return this.error(),void(this.allErrors||this.gen.if(!1));this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:t}=this;this.fail(a._`${t} !== undefined && (${(0,a.or)(this.invalid$data(),e)})`)}error(e,t,r){if(t)return this.setParams(t),this._error(e,r),void this.setParams({});this._error(e,r)}_error(e,t){(e?u.reportExtraError:u.reportError)(this,this.def.error,t)}$dataError(){(0,u.reportError)(this,this.def.$dataError||u.keyword$DataError)}reset(){if(void 0===this.errsCount)throw new Error('add "trackErrors" to keyword definition');(0,u.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,r=a.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=a.nil,t=a.nil){if(!this.$data)return;const{gen:r,schemaCode:n,schemaType:o,def:i}=this;r.if((0,a.or)(a._`${n} === undefined`,t)),e!==a.nil&&r.assign(e,!0),(o.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==a.nil&&r.assign(e,!1)),r.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:r,def:o,it:i}=this;return(0,a.or)(function(){if(r.length){if(!(t instanceof a.Name))throw new Error("ajv implementation error");const e=Array.isArray(r)?r:[r];return a._`${(0,n.checkDataTypes)(e,t,i.opts.strictNumbers,n.DataType.Wrong)}`}return a.nil}(),function(){if(o.validateSchema){const r=e.scopeValue("validate$data",{ref:o.validateSchema});return a._`!${r}(${t})`}return a.nil}())}subschema(e,t){const r=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(r,this.it,e),(0,s.extendSubschemaMode)(r,e);const n={...this.it,...r,items:void 0,props:void 0};return f(n,t),n}mergeEvaluated(e,t){const{it:r,gen:n}=this;r.opts.unevaluated&&(!0!==r.props&&void 0!==e.props&&(r.props=d.mergeEvaluated.props(n,e.props,r.props,t)),!0!==r.items&&void 0!==e.items&&(r.items=d.mergeEvaluated.items(n,e.items,r.items,t)))}mergeValidEvaluated(e,t){const{it:r,gen:n}=this;if(r.opts.unevaluated&&(!0!==r.props||!0!==r.items))return n.if(t,()=>this.mergeEvaluated(e,a.Name)),!0}}function _(e,t,r,n){const o=new L(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,i.funcKeywordCode)(o,r):"macro"in r?(0,i.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,i.funcKeywordCode)(o,r)}Wr.KeywordCxt=L;const k=/^\/(?:[^~]|~0|~1)*$/,C=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function N(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,i;if(""===e)return c.default.rootData;if("/"===e[0]){if(!k.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,i=c.default.rootData}else{const s=C.exec(e);if(!s)throw new Error(`Invalid JSON-pointer: ${e}`);const a=+s[1];if(o=s[2],"#"===o){if(a>=t)throw new Error(u("property/index",a));return n[t-a]}if(a>t)throw new Error(u("data",a));if(i=r[t-a],!o)return i}let s=i;const l=o.split("/");for(const e of l)e&&(i=a._`${i}${(0,a.getProperty)((0,d.unescapeJsonPointer)(e))}`,s=a._`${s} && ${i}`);return s;function u(e,r){return`Cannot access ${e} ${r} levels up, current level is ${t}`}}return Wr.getData=N,Wr}var zn,Hn={};function Vn(){if(zn)return Hn;zn=1,Object.defineProperty(Hn,"__esModule",{value:!0});class e extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}return Hn.default=e,Hn}var Wn,qn={};function Kn(){if(Wn)return qn;Wn=1,Object.defineProperty(qn,"__esModule",{value:!0});const e=Un();class t extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,e.resolveUrl)(t,r,n),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(t,this.missingRef))}}return qn.default=t,qn}var Yn,Jn={};function Xn(){if(Yn)return Jn;Yn=1,Object.defineProperty(Jn,"__esModule",{value:!0}),Jn.resolveSchema=Jn.getCompilingSchema=Jn.resolveRef=Jn.compileSchema=Jn.SchemaEnv=void 0;const e=rn(),t=Vn(),r=un(),n=Un(),o=sn(),i=Bn();class s{constructor(e){var t;let r;this.refs={},this.dynamicAnchors={},"object"==typeof e.schema&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=null!==(t=e.baseId)&&void 0!==t?t:(0,n.normalizeId)(null==r?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=null==r?void 0:r.$async,this.refs={}}}function a(o){const s=l.call(this,o);if(s)return s;const a=(0,n.getFullPath)(this.opts.uriResolver,o.root.baseId),{es5:c,lines:d}=this.opts.code,{ownProperties:u}=this.opts,p=new e.CodeGen(this.scope,{es5:c,lines:d,ownProperties:u});let h;o.$async&&(h=p.scopeValue("Error",{ref:t.default,code:e._`require("ajv/dist/runtime/validation_error").default`}));const f=p.scopeName("validate");o.validateName=f;const m={gen:p,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[e.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:p.scopeValue("schema",!0===this.opts.code.source?{ref:o.schema,code:(0,e.stringify)(o.schema)}:{ref:o.schema}),validateName:f,ValidationError:h,schema:o.schema,schemaEnv:o,rootId:a,baseId:o.baseId||a,schemaPath:e.nil,errSchemaPath:o.schemaPath||(this.opts.jtd?"":"#"),errorPath:e._`""`,opts:this.opts,self:this};let g;try{this._compilations.add(o),(0,i.validateFunctionCode)(m),p.optimize(this.opts.code.optimize);const t=p.toString();g=`${p.scopeRefs(r.default.scope)}return ${t}`,this.opts.code.process&&(g=this.opts.code.process(g,o));const n=new Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(f,{ref:n}),n.errors=null,n.schema=o.schema,n.schemaEnv=o,o.$async&&(n.$async=!0),!0===this.opts.code.source&&(n.source={validateName:f,validateCode:t,scopeValues:p._values}),this.opts.unevaluated){const{props:t,items:r}=m;n.evaluated={props:t instanceof e.Name?void 0:t,items:r instanceof e.Name?void 0:r,dynamicProps:t instanceof e.Name,dynamicItems:r instanceof e.Name},n.source&&(n.source.evaluated=(0,e.stringify)(n.evaluated))}return o.validate=n,o}catch(e){throw delete o.validate,delete o.validateName,g&&this.logger.error("Error compiling schema, function code:",g),e}finally{this._compilations.delete(o)}}function c(e){return(0,n.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:a.call(this,e)}function l(e){for(const t of this._compilations)if(d(t,e))return t}function d(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function u(e,t){let r;for(;"string"==typeof(r=this.refs[t]);)t=r;return r||this.schemas[t]||p.call(this,e,t)}function p(e,t){const r=this.opts.uriResolver.parse(t),o=(0,n._getFullPath)(this.opts.uriResolver,r);let i=(0,n.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&o===i)return f.call(this,r,e);const c=(0,n.normalizeId)(o),l=this.refs[c]||this.schemas[c];if("string"==typeof l){const t=p.call(this,e,l);if("object"!=typeof(null==t?void 0:t.schema))return;return f.call(this,r,t)}if("object"==typeof(null==l?void 0:l.schema)){if(l.validate||a.call(this,l),c===(0,n.normalizeId)(t)){const{schema:t}=l,{schemaId:r}=this.opts,o=t[r];return o&&(i=(0,n.resolveUrl)(this.opts.uriResolver,i,o)),new s({schema:t,schemaId:r,root:e,baseId:i})}return f.call(this,r,l)}}Jn.SchemaEnv=s,Jn.compileSchema=a,Jn.resolveRef=function(e,t,r){var o;r=(0,n.resolveUrl)(this.opts.uriResolver,t,r);const i=e.refs[r];if(i)return i;let a=u.call(this,e,r);if(void 0===a){const n=null===(o=e.localRefs)||void 0===o?void 0:o[r],{schemaId:i}=this.opts;n&&(a=new s({schema:n,schemaId:i,root:e,baseId:t}))}return void 0!==a?e.refs[r]=c.call(this,a):void 0},Jn.getCompilingSchema=l,Jn.resolveSchema=p;const h=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function f(e,{baseId:t,schema:r,root:i}){var a;if("/"!==(null===(a=e.fragment)||void 0===a?void 0:a[0]))return;for(const i of e.fragment.slice(1).split("/")){if("boolean"==typeof r)return;const e=r[(0,o.unescapeFragment)(i)];if(void 0===e)return;const s="object"==typeof(r=e)&&r[this.opts.schemaId];!h.has(i)&&s&&(t=(0,n.resolveUrl)(this.opts.uriResolver,t,s))}let c;if("boolean"!=typeof r&&r.$ref&&!(0,o.schemaHasRulesButRef)(r,this.RULES)){const e=(0,n.resolveUrl)(this.opts.uriResolver,t,r.$ref);c=p.call(this,i,e)}const{schemaId:l}=this.opts;return c=c||new s({schema:r,schemaId:l,root:i,baseId:t}),c.schema!==c.root.schema?c:void 0}return Jn}var Zn,Qn,eo,to,ro,no,oo,io={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1},so={},ao={exports:{}};function co(){if(Qn)return Zn;Qn=1;const e=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),t=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function r(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),48!==r){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(e){return e.length=0,!0}function i(e,t,n){if(e.length){const o=r(e);if(""===o)return n.error=!0,!1;t.push(o),e.length=0}return!0}function s(e){if(function(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}(e,":")<2)return{host:e,isIPV6:!1};const t=function(e){let t=0;const n={error:!1,address:"",zone:""},s=[],a=[];let c=!1,l=!1,d=i;for(let r=0;r<e.length;r++){const i=e[r];if("["!==i&&"]"!==i)if(":"!==i)if("%"===i){if(!d(a,s,n))break;d=o}else a.push(i);else{if(!0===c&&(l=!0),!d(a,s,n))break;if(++t>7){n.error=!0;break}r>0&&":"===e[r-1]&&(c=!0),s.push(":")}}return a.length&&(d===o?n.zone=a.join(""):l?s.push(a.join("")):s.push(r(a))),n.address=s.join(""),n}(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,r=t.address;return t.zone&&(e+="%"+t.zone,r+="%25"+t.zone),{host:e,isIPV6:!0,escapedHost:r}}}return Zn={nonSimpleDomain:n,recomposeAuthority:function(e){const r=[];if(void 0!==e.userinfo&&(r.push(e.userinfo),r.push("@")),void 0!==e.host){let n=unescape(e.host);if(!t(n)){const t=s(n);n=!0===t.isIPV6?`[${t.escapedHost}]`:e.host}r.push(n)}return"number"!=typeof e.port&&"string"!=typeof e.port||(r.push(":"),r.push(String(e.port))),r.length?r.join(""):void 0},normalizeComponentEncoding:function(e,t){const r=!0!==t?escape:unescape;return void 0!==e.scheme&&(e.scheme=r(e.scheme)),void 0!==e.userinfo&&(e.userinfo=r(e.userinfo)),void 0!==e.host&&(e.host=r(e.host)),void 0!==e.path&&(e.path=r(e.path)),void 0!==e.query&&(e.query=r(e.query)),void 0!==e.fragment&&(e.fragment=r(e.fragment)),e},removeDotSegments:function(e){let t=e;const r=[];let n=-1,o=0;for(;o=t.length;){if(1===o){if("."===t)break;if("/"===t){r.push("/");break}r.push(t);break}if(2===o){if("."===t[0]){if("."===t[1])break;if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&("."===t[1]||"/"===t[1])){r.push("/");break}}else if(3===o&&"/.."===t){0!==r.length&&r.pop(),r.push("/");break}if("."===t[0]){if("."===t[1]){if("/"===t[2]){t=t.slice(3);continue}}else if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&"."===t[1]){if("/"===t[2]){t=t.slice(2);continue}if("."===t[2]&&"/"===t[3]){t=t.slice(3),0!==r.length&&r.pop();continue}}if(-1===(n=t.indexOf("/",1))){r.push(t);break}r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")},isIPv4:t,isUUID:e,normalizeIPv6:s,stringArrayToHexStripped:r}}function lo(){if(ro)return ao.exports;ro=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:o,nonSimpleDomain:i}=co(),{SCHEMES:s,getSchemeHandler:a}=function(){if(to)return eo;to=1;const{isUUID:e}=co(),t=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(e){return!0===e.secure||!1!==e.secure&&!!e.scheme&&!(3!==e.scheme.length||"w"!==e.scheme[0]&&"W"!==e.scheme[0]||"s"!==e.scheme[1]&&"S"!==e.scheme[1]||"s"!==e.scheme[2]&&"S"!==e.scheme[2])}function o(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function i(e){const t="https"===String(e.scheme).toLowerCase();return e.port!==(t?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}const s={scheme:"http",domainHost:!0,parse:o,serialize:i},a={scheme:"ws",domainHost:!0,parse:function(e){return e.secure=n(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e},serialize:function(e){if(e.port!==(n(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){const[t,r]=e.resourceName.split("?");e.path=t&&"/"!==t?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}},c={http:s,https:{scheme:"https",domainHost:s.domainHost,parse:o,serialize:i},ws:a,wss:{scheme:"wss",domainHost:a.domainHost,parse:a.parse,serialize:a.serialize},urn:{scheme:"urn",parse:function(e,r){if(!e.path)return e.error="URN can not be parsed",e;const n=e.path.match(t);if(n){const t=r.scheme||e.scheme||"urn";e.nid=n[1].toLowerCase(),e.nss=n[2];const o=l(`${t}:${r.nid||e.nid}`);e.path=void 0,o&&(e=o.parse(e,r))}else e.error=e.error||"URN can not be parsed.";return e},serialize:function(e,t){if(void 0===e.nid)throw new Error("URN without nid cannot be serialized");const r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),o=l(`${r}:${t.nid||n}`);o&&(e=o.serialize(e,t));const i=e,s=e.nss;return i.path=`${n||t.nid}:${s}`,t.skipEscape=!0,i},skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:function(t,r){const n=t;return n.uuid=n.nss,n.nss=void 0,r.tolerant||n.uuid&&e(n.uuid)||(n.error=n.error||"UUID is not valid."),n},serialize:function(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t},skipNormalize:!0}};function l(e){return e&&(c[e]||c[e.toLowerCase()])||void 0}return Object.setPrototypeOf(c,null),eo={wsIsSecure:n,SCHEMES:c,isValidSchemeName:function(e){return-1!==r.indexOf(e)},getSchemeHandler:l}}();function c(e,r,n,o){const i={};return o||(e=u(l(e,n),n),r=u(l(r,n),n)),!(n=n||{}).tolerant&&r.scheme?(i.scheme=r.scheme,i.userinfo=r.userinfo,i.host=r.host,i.port=r.port,i.path=t(r.path||""),i.query=r.query):(void 0!==r.userinfo||void 0!==r.host||void 0!==r.port?(i.userinfo=r.userinfo,i.host=r.host,i.port=r.port,i.path=t(r.path||""),i.query=r.query):(r.path?("/"===r.path[0]?i.path=t(r.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?i.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+r.path:i.path=r.path:i.path="/"+r.path,i.path=t(i.path)),i.query=r.query):(i.path=e.path,void 0!==r.query?i.query=r.query:i.query=e.query),i.userinfo=e.userinfo,i.host=e.host,i.port=e.port),i.scheme=e.scheme),i.fragment=r.fragment,i}function l(e,n){const o={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},i=Object.assign({},n),s=[],c=a(i.scheme||o.scheme);c&&c.serialize&&c.serialize(o,i),void 0!==o.path&&(i.skipEscape?o.path=unescape(o.path):(o.path=escape(o.path),void 0!==o.scheme&&(o.path=o.path.split("%3A").join(":")))),"suffix"!==i.reference&&o.scheme&&s.push(o.scheme,":");const l=r(o);if(void 0!==l&&("suffix"!==i.reference&&s.push("//"),s.push(l),o.path&&"/"!==o.path[0]&&s.push("/")),void 0!==o.path){let e=o.path;i.absolutePath||c&&c.absolutePath||(e=t(e)),void 0===l&&"/"===e[0]&&"/"===e[1]&&(e="/%2F"+e.slice(2)),s.push(e)}return void 0!==o.query&&s.push("?",o.query),void 0!==o.fragment&&s.push("#",o.fragment),s.join("")}const d=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function u(t,r){const n=Object.assign({},r),s={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let c=!1;"suffix"===n.reference&&(t=n.scheme?n.scheme+":"+t:"//"+t);const l=t.match(d);if(l){if(s.scheme=l[1],s.userinfo=l[3],s.host=l[4],s.port=parseInt(l[5],10),s.path=l[6]||"",s.query=l[7],s.fragment=l[8],isNaN(s.port)&&(s.port=l[5]),s.host){if(!1===o(s.host)){const t=e(s.host);s.host=t.host.toLowerCase(),c=t.isIPV6}else c=!0}void 0!==s.scheme||void 0!==s.userinfo||void 0!==s.host||void 0!==s.port||void 0!==s.query||s.path?void 0===s.scheme?s.reference="relative":void 0===s.fragment?s.reference="absolute":s.reference="uri":s.reference="same-document",n.reference&&"suffix"!==n.reference&&n.reference!==s.reference&&(s.error=s.error||"URI is not a "+n.reference+" reference.");const r=a(n.scheme||s.scheme);if(!(n.unicodeSupport||r&&r.unicodeSupport)&&s.host&&(n.domainHost||r&&r.domainHost)&&!1===c&&i(s.host))try{s.host=URL.domainToASCII(s.host.toLowerCase())}catch(e){s.error=s.error||"Host's domain name can not be converted to ASCII: "+e}(!r||r&&!r.skipNormalize)&&(-1!==t.indexOf("%")&&(void 0!==s.scheme&&(s.scheme=unescape(s.scheme)),void 0!==s.host&&(s.host=unescape(s.host))),s.path&&(s.path=escape(unescape(s.path))),s.fragment&&(s.fragment=encodeURI(decodeURIComponent(s.fragment)))),r&&r.parse&&r.parse(s,n)}else s.error=s.error||"URI can not be parsed.";return s}const p={SCHEMES:s,normalize:function(e,t){return"string"==typeof e?e=l(u(e,t),t):"object"==typeof e&&(e=u(l(e,t),t)),e},resolve:function(e,t,r){const n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=c(u(e,n),u(t,n),n,!0);return n.skipEscape=!0,l(o,n)},resolveComponent:c,equal:function(e,t,r){return"string"==typeof e?(e=unescape(e),e=l(n(u(e,r),!0),{...r,skipEscape:!0})):"object"==typeof e&&(e=l(n(e,!0),{...r,skipEscape:!0})),"string"==typeof t?(t=unescape(t),t=l(n(u(t,r),!0),{...r,skipEscape:!0})):"object"==typeof t&&(t=l(n(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()},serialize:l,parse:u};return ao.exports=p,ao.exports.default=p,ao.exports.fastUri=p,ao.exports}function uo(){return oo||(oo=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Bn();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=rn();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const n=Vn(),o=Kn(),i=gn(),s=Xn(),a=rn(),c=Un(),l=wn(),d=sn(),u=io,p=function(){if(no)return so;no=1,Object.defineProperty(so,"__esModule",{value:!0});const e=lo();return e.code='require("ajv/dist/runtime/uri").default',so.default=e,so}(),h=(e,t)=>new RegExp(e,t);h.code="new RegExp";const f=["removeAdditional","useDefaults","coerceTypes"],m=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),g={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},y={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};function v(e){var t,r,n,o,i,s,a,c,l,d,u,f,m,g,y,v,b,$,w,E,S,P,L,_,k;const C=e.strict,N=null===(t=e.code)||void 0===t?void 0:t.optimize,I=!0===N||void 0===N?1:N||0,O=null!==(n=null===(r=e.code)||void 0===r?void 0:r.regExp)&&void 0!==n?n:h,A=null!==(o=e.uriResolver)&&void 0!==o?o:p.default;return{strictSchema:null===(s=null!==(i=e.strictSchema)&&void 0!==i?i:C)||void 0===s||s,strictNumbers:null===(c=null!==(a=e.strictNumbers)&&void 0!==a?a:C)||void 0===c||c,strictTypes:null!==(d=null!==(l=e.strictTypes)&&void 0!==l?l:C)&&void 0!==d?d:"log",strictTuples:null!==(f=null!==(u=e.strictTuples)&&void 0!==u?u:C)&&void 0!==f?f:"log",strictRequired:null!==(g=null!==(m=e.strictRequired)&&void 0!==m?m:C)&&void 0!==g&&g,code:e.code?{...e.code,optimize:I,regExp:O}:{optimize:I,regExp:O},loopRequired:null!==(y=e.loopRequired)&&void 0!==y?y:200,loopEnum:null!==(v=e.loopEnum)&&void 0!==v?v:200,meta:null===(b=e.meta)||void 0===b||b,messages:null===($=e.messages)||void 0===$||$,inlineRefs:null===(w=e.inlineRefs)||void 0===w||w,schemaId:null!==(E=e.schemaId)&&void 0!==E?E:"$id",addUsedSchema:null===(S=e.addUsedSchema)||void 0===S||S,validateSchema:null===(P=e.validateSchema)||void 0===P||P,validateFormats:null===(L=e.validateFormats)||void 0===L||L,unicodeRegExp:null===(_=e.unicodeRegExp)||void 0===_||_,int32range:null===(k=e.int32range)||void 0===k||k,uriResolver:A}}class b{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};const{es5:t,lines:r}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:m,es5:t,lines:r}),this.logger=function(e){if(!1===e)return _;if(void 0===e)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}(e.logger);const n=e.validateFormats;e.validateFormats=!1,this.RULES=(0,i.getRules)(),$.call(this,g,e,"NOT SUPPORTED"),$.call(this,y,e,"DEPRECATED","warn"),this._metaOpts=L.call(this),e.formats&&S.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&P.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),E.call(this),e.validateFormats=n}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:e,meta:t,schemaId:r}=this.opts;let n=u;"id"===r&&(n={...u},n.id=n.$id,delete n.$id),t&&e&&this.addMetaSchema(n,n[r],!1)}defaultMeta(){const{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta="object"==typeof e?e[t]||e:void 0}validate(e,t){let r;if("string"==typeof e){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);const n=r(t);return"$async"in r||(this.errors=r.errors),n}compile(e,t){const r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if("function"!=typeof this.opts.loadSchema)throw new Error("options.loadSchema should be a function");const{loadSchema:r}=this.opts;return n.call(this,e,t);async function n(e,t){await i.call(this,e.$schema);const r=this._addSchema(e,t);return r.validate||s.call(this,r)}async function i(e){e&&!this.getSchema(e)&&await n.call(this,{$ref:e},!0)}async function s(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof o.default))throw t;return a.call(this,t),await c.call(this,t.missingSchema),s.call(this,e)}}function a({missingSchema:e,missingRef:t}){if(this.refs[e])throw new Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){const r=await l.call(this,e);this.refs[e]||await i.call(this,r.$schema),this.refs[e]||this.addSchema(r,e,t)}async function l(e){const t=this._loading[e];if(t)return t;try{return await(this._loading[e]=r(e))}finally{delete this._loading[e]}}}addSchema(e,t,r,n=this.opts.validateSchema){if(Array.isArray(e)){for(const t of e)this.addSchema(t,void 0,r,n);return this}let o;if("object"==typeof e){const{schemaId:t}=this.opts;if(o=e[t],void 0!==o&&"string"!=typeof o)throw new Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||o),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,n,!0),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if("boolean"==typeof e)return!0;let r;if(r=e.$schema,void 0!==r&&"string"!=typeof r)throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const n=this.validate(r,e);if(!n&&t){const e="schema is invalid: "+this.errorsText();if("log"!==this.opts.validateSchema)throw new Error(e);this.logger.error(e)}return n}getSchema(e){let t;for(;"string"==typeof(t=w.call(this,e));)e=t;if(void 0===t){const{schemaId:r}=this.opts,n=new s.SchemaEnv({schema:{},schemaId:r});if(t=s.resolveSchema.call(this,n,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const t=w.call(this,e);return"object"==typeof t&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{const t=e;this._cache.delete(t);let r=e[this.opts.schemaId];return r&&(r=(0,c.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(const t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if("string"==typeof e)r=e,"object"==typeof t&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r);else{if("object"!=typeof e||void 0!==t)throw new Error("invalid addKeywords parameters");if(r=(t=e).keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}if(C.call(this,r,t),!t)return(0,d.eachItem)(r,e=>N.call(this,e)),this;O.call(this,t);const n={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,d.eachItem)(r,0===n.type.length?e=>N.call(this,e,n):e=>n.type.forEach(t=>N.call(this,e,n,t))),this}getKeyword(e){const t=this.RULES.all[e];return"object"==typeof t?t.definition:!!t}removeKeyword(e){const{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(const r of t.rules){const t=r.rules.findIndex(t=>t.keyword===e);t>=0&&r.rules.splice(t,1)}return this}addFormat(e,t){return"string"==typeof t&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){return e&&0!==e.length?e.map(e=>`${r}${e.instancePath} ${e.message}`).reduce((e,r)=>e+t+r):"No errors"}$dataMetaSchema(e,t){const r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(const n of t){const t=n.split("/").slice(1);let o=e;for(const e of t)o=o[e];for(const e in r){const t=r[e];if("object"!=typeof t)continue;const{$data:n}=t.definition,i=o[e];n&&i&&(o[e]=T(i))}}return e}_removeAllSchemas(e,t){for(const r in e){const n=e[r];t&&!t.test(r)||("string"==typeof n?delete e[r]:n&&!n.meta&&(this._cache.delete(n.schema),delete e[r]))}}_addSchema(e,t,r,n=this.opts.validateSchema,o=this.opts.addUsedSchema){let i;const{schemaId:a}=this.opts;if("object"==typeof e)i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if("boolean"!=typeof e)throw new Error("schema must be object or boolean")}let l=this._cache.get(e);if(void 0!==l)return l;r=(0,c.normalizeId)(i||r);const d=c.getSchemaRefs.call(this,e,r);return l=new s.SchemaEnv({schema:e,schemaId:a,meta:t,baseId:r,localRefs:d}),this._cache.set(l.schema,l),o&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=l),n&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):s.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){const t=this.opts;this.opts=this._metaOpts;try{s.compileSchema.call(this,e)}finally{this.opts=t}}}function $(e,t,r,n="error"){for(const o in e){const i=o;i in t&&this.logger[n](`${r}: option ${o}. ${e[i]}`)}}function w(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function E(){const e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(const t in e)this.addSchema(e[t],t)}function S(){for(const e in this.opts.formats){const t=this.opts.formats[e];t&&this.addFormat(e,t)}}function P(e){if(Array.isArray(e))this.addVocabulary(e);else{this.logger.warn("keywords option as map is deprecated, pass array");for(const t in e){const r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}}function L(){const e={...this.opts};for(const t of f)delete e[t];return e}b.ValidationError=n.default,b.MissingRefError=o.default,e.default=b;const _={log(){},warn(){},error(){}};const k=/^[a-z_$][a-z0-9_$:-]*$/i;function C(e,t){const{RULES:r}=this;if((0,d.eachItem)(e,e=>{if(r.keywords[e])throw new Error(`Keyword ${e} is already defined`);if(!k.test(e))throw new Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!("code"in t)&&!("validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function N(e,t,r){var n;const o=null==t?void 0:t.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:i}=this;let s=o?i.post:i.rules.find(({type:e})=>e===r);if(s||(s={type:r,rules:[]},i.rules.push(s)),i.keywords[e]=!0,!t)return;const a={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?I.call(this,s,a,t.before):s.rules.push(a),i.all[e]=a,null===(n=t.implements)||void 0===n||n.forEach(e=>this.addKeyword(e))}function I(e,t,r){const n=e.rules.findIndex(e=>e.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function O(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=T(t)),e.validateSchema=this.compile(t,!0))}const A={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function T(e){return{anyOf:[e,A]}}}(Vr)),Vr}var po,ho={},fo={},mo={};var go,yo,vo={};function bo(){if(go)return vo;go=1,Object.defineProperty(vo,"__esModule",{value:!0}),vo.callRef=vo.getValidate=void 0;const e=Kn(),t=Cn(),r=rn(),n=un(),o=Xn(),i=sn(),s={keyword:"$ref",schemaType:"string",code(t){const{gen:n,schema:i,it:s}=t,{baseId:l,schemaEnv:d,validateName:u,opts:p,self:h}=s,{root:f}=d;if(("#"===i||"#/"===i)&&l===f.baseId)return function(){if(d===f)return c(t,u,d,d.$async);const e=n.scopeValue("root",{ref:f});return c(t,r._`${e}.validate`,f,f.$async)}();const m=o.resolveRef.call(h,f,l,i);if(void 0===m)throw new e.default(s.opts.uriResolver,l,i);return m instanceof o.SchemaEnv?function(e){const r=a(t,e);c(t,r,e,e.$async)}(m):function(e){const o=n.scopeValue("schema",!0===p.code.source?{ref:e,code:(0,r.stringify)(e)}:{ref:e}),s=n.name("valid"),a=t.subschema({schema:e,dataTypes:[],schemaPath:r.nil,topSchemaRef:o,errSchemaPath:i},s);t.mergeEvaluated(a),t.ok(s)}(m)}};function a(e,t){const{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):r._`${n.scopeValue("wrapper",{ref:t})}.validate`}function c(e,o,s,a){const{gen:c,it:l}=e,{allErrors:d,schemaEnv:u,opts:p}=l,h=p.passContext?n.default.this:r.nil;function f(e){const t=r._`${e}.errors`;c.assign(n.default.vErrors,r._`${n.default.vErrors} === null ? ${t} : ${n.default.vErrors}.concat(${t})`),c.assign(n.default.errors,r._`${n.default.vErrors}.length`)}function m(e){var t;if(!l.opts.unevaluated)return;const n=null===(t=null==s?void 0:s.validate)||void 0===t?void 0:t.evaluated;if(!0!==l.props)if(n&&!n.dynamicProps)void 0!==n.props&&(l.props=i.mergeEvaluated.props(c,n.props,l.props));else{const t=c.var("props",r._`${e}.evaluated.props`);l.props=i.mergeEvaluated.props(c,t,l.props,r.Name)}if(!0!==l.items)if(n&&!n.dynamicItems)void 0!==n.items&&(l.items=i.mergeEvaluated.items(c,n.items,l.items));else{const t=c.var("items",r._`${e}.evaluated.items`);l.items=i.mergeEvaluated.items(c,t,l.items,r.Name)}}a?function(){if(!u.$async)throw new Error("async schema referenced by sync schema");const n=c.let("valid");c.try(()=>{c.code(r._`await ${(0,t.callValidateCode)(e,o,h)}`),m(o),d||c.assign(n,!0)},e=>{c.if(r._`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),f(e),d||c.assign(n,!1)}),e.ok(n)}():e.result((0,t.callValidateCode)(e,o,h),()=>m(o),()=>f(o))}return vo.getValidate=a,vo.callRef=c,vo.default=s,vo}function $o(){if(yo)return fo;yo=1,Object.defineProperty(fo,"__esModule",{value:!0});const e=function(){if(po)return mo;po=1,Object.defineProperty(mo,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return mo.default=e,mo}(),t=bo(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return fo.default=r,fo}var wo,Eo={},So={};var Po,Lo={};var _o,ko,Co={},No={};function Io(){if(ko)return Co;ko=1,Object.defineProperty(Co,"__esModule",{value:!0});const e=rn(),t=sn(),r=function(){if(_o)return No;function e(e){const t=e.length;let r,n=0,o=0;for(;o<t;)n++,r=e.charCodeAt(o++),r>=55296&&r<=56319&&o<t&&(r=e.charCodeAt(o),56320==(64512&r)&&o++);return n}return _o=1,Object.defineProperty(No,"__esModule",{value:!0}),No.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',No}(),n={message({keyword:t,schemaCode:r}){const n="maxLength"===t?"more":"fewer";return e.str`must NOT have ${n} than ${r} characters`},params:({schemaCode:t})=>e._`{limit: ${t}}`},o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:n,code(n){const{keyword:o,data:i,schemaCode:s,it:a}=n,c="maxLength"===o?e.operators.GT:e.operators.LT,l=!1===a.opts.unicode?e._`${i}.length`:e._`${(0,t.useFunc)(n.gen,r.default)}(${i})`;n.fail$data(e._`${l} ${c} ${s}`)}};return Co.default=o,Co}var Oo,Ao={};var To,xo={};var Do,jo={};function Ro(){if(Do)return jo;Do=1,Object.defineProperty(jo,"__esModule",{value:!0});const e=Cn(),t=rn(),r=sn(),n={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>t.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>t._`{missingProperty: ${e}}`},code(n){const{gen:o,schema:i,schemaCode:s,data:a,$data:c,it:l}=n,{opts:d}=l;if(!c&&0===i.length)return;const u=i.length>=d.loopRequired;if(l.allErrors?function(){if(u||c)n.block$data(t.nil,p);else for(const t of i)(0,e.checkReportMissingProp)(n,t)}():function(){const r=o.let("missing");if(u||c){const i=o.let("valid",!0);n.block$data(i,()=>function(r,i){n.setParams({missingProperty:r}),o.forOf(r,s,()=>{o.assign(i,(0,e.propertyInData)(o,a,r,d.ownProperties)),o.if((0,t.not)(i),()=>{n.error(),o.break()})},t.nil)}(r,i)),n.ok(i)}else o.if((0,e.checkMissingProp)(n,i,r)),(0,e.reportMissingProp)(n,r),o.else()}(),d.strictRequired){const e=n.parentSchema.properties,{definedProperties:t}=n.it;for(const n of i)if(void 0===(null==e?void 0:e[n])&&!t.has(n)){const e=`required property "${n}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,e,l.opts.strictRequired)}}function p(){o.forOf("prop",s,t=>{n.setParams({missingProperty:t}),o.if((0,e.noPropertyInData)(o,a,t,d.ownProperties),()=>n.error())})}}};return jo.default=n,jo}var Fo,Mo={};var Go,Uo,Bo={},zo={};function Ho(){if(Go)return zo;Go=1,Object.defineProperty(zo,"__esModule",{value:!0});const e=Dn();return e.code='require("ajv/dist/runtime/equal").default',zo.default=e,zo}function Vo(){if(Uo)return Bo;Uo=1,Object.defineProperty(Bo,"__esModule",{value:!0});const e=wn(),t=rn(),r=sn(),n=Ho(),o={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:r}})=>t.str`must NOT have duplicate items (items ## ${r} and ${e} are identical)`,params:({params:{i:e,j:r}})=>t._`{i: ${e}, j: ${r}}`},code(o){const{gen:i,data:s,$data:a,schema:c,parentSchema:l,schemaCode:d,it:u}=o;if(!a&&!c)return;const p=i.let("valid"),h=l.items?(0,e.getSchemaTypes)(l.items):[];function f(r,n){const a=i.name("item"),c=(0,e.checkDataTypes)(h,a,u.opts.strictNumbers,e.DataType.Wrong),l=i.const("indices",t._`{}`);i.for(t._`;${r}--;`,()=>{i.let(a,t._`${s}[${r}]`),i.if(c,t._`continue`),h.length>1&&i.if(t._`typeof ${a} == "string"`,t._`${a} += "_"`),i.if(t._`typeof ${l}[${a}] == "number"`,()=>{i.assign(n,t._`${l}[${a}]`),o.error(),i.assign(p,!1).break()}).code(t._`${l}[${a}] = ${r}`)})}function m(e,a){const c=(0,r.useFunc)(i,n.default),l=i.name("outer");i.label(l).for(t._`;${e}--;`,()=>i.for(t._`${a} = ${e}; ${a}--;`,()=>i.if(t._`${c}(${s}[${e}], ${s}[${a}])`,()=>{o.error(),i.assign(p,!1).break(l)})))}o.block$data(p,function(){const e=i.let("i",t._`${s}.length`),r=i.let("j");o.setParams({i:e,j:r}),i.assign(p,!0),i.if(t._`${e} > 1`,()=>(h.length>0&&!h.some(e=>"object"===e||"array"===e)?f:m)(e,r))},t._`${d} === false`),o.ok(p)}};return Bo.default=o,Bo}var Wo,qo={};var Ko,Yo,Jo={};function Xo(){if(Ko)return Jo;Ko=1,Object.defineProperty(Jo,"__esModule",{value:!0});const e=rn(),t=sn(),r=Ho(),n={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:t})=>e._`{allowedValues: ${t}}`},code(n){const{gen:o,data:i,$data:s,schema:a,schemaCode:c,it:l}=n;if(!s&&0===a.length)throw new Error("enum must have non-empty array");const d=a.length>=l.opts.loopEnum;let u;const p=()=>null!=u?u:u=(0,t.useFunc)(o,r.default);let h;if(d||s)h=o.let("valid"),n.block$data(h,function(){o.assign(h,!1),o.forOf("v",c,t=>o.if(e._`${p()}(${i}, ${t})`,()=>o.assign(h,!0).break()))});else{if(!Array.isArray(a))throw new Error("ajv implementation error");const t=o.const("vSchema",c);h=(0,e.or)(...a.map((r,n)=>function(t,r){const n=a[r];return"object"==typeof n&&null!==n?e._`${p()}(${i}, ${t}[${r}])`:e._`${i} === ${n}`}(t,n)))}n.pass(h)}};return Jo.default=n,Jo}function Zo(){if(Yo)return Eo;Yo=1,Object.defineProperty(Eo,"__esModule",{value:!0});const e=function(){if(wo)return So;wo=1,Object.defineProperty(So,"__esModule",{value:!0});const e=rn(),t=e.operators,r={maximum:{okStr:"<=",ok:t.LTE,fail:t.GT},minimum:{okStr:">=",ok:t.GTE,fail:t.LT},exclusiveMaximum:{okStr:"<",ok:t.LT,fail:t.GTE},exclusiveMinimum:{okStr:">",ok:t.GT,fail:t.LTE}},n={message:({keyword:t,schemaCode:n})=>e.str`must be ${r[t].okStr} ${n}`,params:({keyword:t,schemaCode:n})=>e._`{comparison: ${r[t].okStr}, limit: ${n}}`},o={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:n,code(t){const{keyword:n,data:o,schemaCode:i}=t;t.fail$data(e._`${o} ${r[n].fail} ${i} || isNaN(${o})`)}};return So.default=o,So}(),t=function(){if(Po)return Lo;Po=1,Object.defineProperty(Lo,"__esModule",{value:!0});const e=rn(),t={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:t})=>e.str`must be multiple of ${t}`,params:({schemaCode:t})=>e._`{multipleOf: ${t}}`},code(t){const{gen:r,data:n,schemaCode:o,it:i}=t,s=i.opts.multipleOfPrecision,a=r.let("res"),c=s?e._`Math.abs(Math.round(${a}) - ${a}) > 1e-${s}`:e._`${a} !== parseInt(${a})`;t.fail$data(e._`(${o} === 0 || (${a} = ${n}/${o}, ${c}))`)}};return Lo.default=t,Lo}(),r=Io(),n=function(){if(Oo)return Ao;Oo=1,Object.defineProperty(Ao,"__esModule",{value:!0});const e=Cn(),t=rn(),r={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>t.str`must match pattern "${e}"`,params:({schemaCode:e})=>t._`{pattern: ${e}}`},code(r){const{data:n,$data:o,schema:i,schemaCode:s,it:a}=r,c=a.opts.unicodeRegExp?"u":"",l=o?t._`(new RegExp(${s}, ${c}))`:(0,e.usePattern)(r,i);r.fail$data(t._`!${l}.test(${n})`)}};return Ao.default=r,Ao}(),o=function(){if(To)return xo;To=1,Object.defineProperty(xo,"__esModule",{value:!0});const e=rn(),t={message({keyword:t,schemaCode:r}){const n="maxProperties"===t?"more":"fewer";return e.str`must NOT have ${n} than ${r} properties`},params:({schemaCode:t})=>e._`{limit: ${t}}`},r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:t,code(t){const{keyword:r,data:n,schemaCode:o}=t,i="maxProperties"===r?e.operators.GT:e.operators.LT;t.fail$data(e._`Object.keys(${n}).length ${i} ${o}`)}};return xo.default=r,xo}(),i=Ro(),s=function(){if(Fo)return Mo;Fo=1,Object.defineProperty(Mo,"__esModule",{value:!0});const e=rn(),t={message({keyword:t,schemaCode:r}){const n="maxItems"===t?"more":"fewer";return e.str`must NOT have ${n} than ${r} items`},params:({schemaCode:t})=>e._`{limit: ${t}}`},r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:t,code(t){const{keyword:r,data:n,schemaCode:o}=t,i="maxItems"===r?e.operators.GT:e.operators.LT;t.fail$data(e._`${n}.length ${i} ${o}`)}};return Mo.default=r,Mo}(),a=Vo(),c=function(){if(Wo)return qo;Wo=1,Object.defineProperty(qo,"__esModule",{value:!0});const e=rn(),t=sn(),r=Ho(),n={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:t})=>e._`{allowedValue: ${t}}`},code(n){const{gen:o,data:i,$data:s,schemaCode:a,schema:c}=n;s||c&&"object"==typeof c?n.fail$data(e._`!${(0,t.useFunc)(o,r.default)}(${i}, ${a})`):n.fail(e._`${c} !== ${i}`)}};return qo.default=n,qo}(),l=Xo(),d=[e.default,t.default,r.default,n.default,o.default,i.default,s.default,a.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},c.default,l.default];return Eo.default=d,Eo}var Qo,ei={},ti={};function ri(){if(Qo)return ti;Qo=1,Object.defineProperty(ti,"__esModule",{value:!0}),ti.validateAdditionalItems=void 0;const e=rn(),t=sn(),r={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:t}})=>e.str`must NOT have more than ${t} items`,params:({params:{len:t}})=>e._`{limit: ${t}}`},code(e){const{parentSchema:r,it:o}=e,{items:i}=r;Array.isArray(i)?n(e,i):(0,t.checkStrictMode)(o,'"additionalItems" is ignored when "items" is not an array of schemas')}};function n(r,n){const{gen:o,schema:i,data:s,keyword:a,it:c}=r;c.items=!0;const l=o.const("len",e._`${s}.length`);if(!1===i)r.setParams({len:n.length}),r.pass(e._`${l} <= ${n.length}`);else if("object"==typeof i&&!(0,t.alwaysValidSchema)(c,i)){const i=o.var("valid",e._`${l} <= ${n.length}`);o.if((0,e.not)(i),()=>function(i){o.forRange("i",n.length,l,n=>{r.subschema({keyword:a,dataProp:n,dataPropType:t.Type.Num},i),c.allErrors||o.if((0,e.not)(i),()=>o.break())})}(i)),r.ok(i)}}return ti.validateAdditionalItems=n,ti.default=r,ti}var ni,oi,ii={},si={};function ai(){if(ni)return si;ni=1,Object.defineProperty(si,"__esModule",{value:!0}),si.validateTuple=void 0;const e=rn(),t=sn(),r=Cn(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:n,it:i}=e;if(Array.isArray(n))return o(e,"additionalItems",n);i.items=!0,(0,t.alwaysValidSchema)(i,n)||e.ok((0,r.validateArray)(e))}};function o(r,n,o=r.schema){const{gen:i,parentSchema:s,data:a,keyword:c,it:l}=r;!function(e){const{opts:r,errSchemaPath:i}=l,s=o.length,a=s===e.minItems&&(s===e.maxItems||!1===e[n]);if(r.strictTuples&&!a){const e=`"${c}" is ${s}-tuple, but minItems or maxItems/${n} are not specified or different at path "${i}"`;(0,t.checkStrictMode)(l,e,r.strictTuples)}}(s),l.opts.unevaluated&&o.length&&!0!==l.items&&(l.items=t.mergeEvaluated.items(i,o.length,l.items));const d=i.name("valid"),u=i.const("len",e._`${a}.length`);o.forEach((n,o)=>{(0,t.alwaysValidSchema)(l,n)||(i.if(e._`${u} > ${o}`,()=>r.subschema({keyword:c,schemaProp:o,dataProp:o},d)),r.ok(d))})}return si.validateTuple=o,si.default=n,si}var ci,li={};var di,ui={};function pi(){if(di)return ui;di=1,Object.defineProperty(ui,"__esModule",{value:!0});const e=rn(),t=sn(),r={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:t,max:r}})=>void 0===r?e.str`must contain at least ${t} valid item(s)`:e.str`must contain at least ${t} and no more than ${r} valid item(s)`,params:({params:{min:t,max:r}})=>void 0===r?e._`{minContains: ${t}}`:e._`{minContains: ${t}, maxContains: ${r}}`},code(r){const{gen:n,schema:o,parentSchema:i,data:s,it:a}=r;let c,l;const{minContains:d,maxContains:u}=i;a.opts.next?(c=void 0===d?1:d,l=u):c=1;const p=n.const("len",e._`${s}.length`);if(r.setParams({min:c,max:l}),void 0===l&&0===c)return void(0,t.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==l&&c>l)return(0,t.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),void r.fail();if((0,t.alwaysValidSchema)(a,o)){let t=e._`${p} >= ${c}`;return void 0!==l&&(t=e._`${t} && ${p} <= ${l}`),void r.pass(t)}a.items=!0;const h=n.name("valid");function f(){const t=n.name("_valid"),r=n.let("count",0);m(t,()=>n.if(t,()=>function(t){n.code(e._`${t}++`),void 0===l?n.if(e._`${t} >= ${c}`,()=>n.assign(h,!0).break()):(n.if(e._`${t} > ${l}`,()=>n.assign(h,!1).break()),1===c?n.assign(h,!0):n.if(e._`${t} >= ${c}`,()=>n.assign(h,!0)))}(r)))}function m(e,o){n.forRange("i",0,p,n=>{r.subschema({keyword:"contains",dataProp:n,dataPropType:t.Type.Num,compositeRule:!0},e),o()})}void 0===l&&1===c?m(h,()=>n.if(h,()=>n.break())):0===c?(n.let(h,!0),void 0!==l&&n.if(e._`${s}.length > 0`,f)):(n.let(h,!1),f()),r.result(h,()=>r.reset())}};return ui.default=r,ui}var hi,fi={};function mi(){return hi||(hi=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=rn(),r=sn(),n=Cn();e.error={message:({params:{property:e,depsCount:r,deps:n}})=>{const o=1===r?"property":"properties";return t.str`must have ${o} ${n} when property ${e} is present`},params:({params:{property:e,depsCount:r,deps:n,missingProperty:o}})=>t._`{property: ${e},
5
- missingProperty: ${o},
1
+ import{createCommand as e,createOption as t,InvalidOptionArgumentError as r,Command as n}from"commander";import{config as a}from"dotenv";import i,{fileURLToPath as s}from"node:url";import o,{resolve as c,dirname as l,join as u,relative as d}from"node:path";import{readPackageUpSync as p}from"read-package-up";import{ConsoleLogger as m,buildApplication as h,bundleApp as f,FusionEnv as g,resolveDefaultEnv as y,checkApp as v,initializeFramework as b,uploadApplication as _,publishAppConfig as w,generateApplicationConfig as S,AllowedAppTags as N,tagApplication as k,loadAppManifest as x,startAppDevServer as E,startPortalDevServer as P,loadPortalManifest as C,buildPortal as A,bundlePortal as I,uploadPortalBundle as O,tagPortal as T,publishPortalConfig as $,generatePortalConfig as z}from"@equinor/fusion-framework-cli/bin";import{mkdir as R,writeFile as L}from"node:fs/promises";import{accessSync as M,constants as D,readFileSync as j,writeFileSync as F,rmSync as U,existsSync as q,readdirSync as B,copyFileSync as V,cpSync as G,mkdirSync as H}from"node:fs";import K from"node:assert";import W from"inquirer";import Z from"is-path-inside";import{execa as J,ExecaError as Y}from"execa";import{spawn as Q,execSync as X}from"node:child_process";import ee,{tmpdir as te,homedir as re,EOL as ne}from"node:os";import{simpleGit as ae,ResetMode as ie}from"simple-git";import se,{z as oe}from"zod";import{createInterface as ce}from"readline";import le,{inspect as ue}from"node:util";import de from"node:process";import{randomUUID as pe}from"node:crypto";import{Readable as me}from"stream";import he from"net";import fe from"tls";import ge from"assert";import ye from"tty";import ve from"util";import be from"http";import _e from"https";import we from"url";import Se from"events";import Ne from"node:http";import ke from"node:https";import xe from"node:zlib";import{Transform as Ee}from"node:stream";import{enableAuthModule as Pe}from"@equinor/fusion-framework-module-msal-node";import{globbyStream as Ce}from"globby";import Ae from"multimatch";import{importConfig as Ie,importJSON as Oe}from"@equinor/fusion-imports";import{assert as Te}from"node:console";import $e from"gray-matter";import{RecursiveCharacterTextSplitter as ze}from"@langchain/textsplitters";import{SyntaxKind as Re,Project as Le,Node as Me}from"ts-morph";import{findUpSync as De}from"find-up";import je from"node:module";import"deepmerge";const Fe=(e=0)=>t=>`[${t+e}m`,Ue=(e=0)=>t=>`[${38+e};5;${t}m`,qe=(e=0)=>(t,r,n)=>`[${38+e};2;${t};${r};${n}m`,Be={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]}};Object.keys(Be.modifier);Object.keys(Be.color),Object.keys(Be.bgColor);const Ve=function(){const e=new Map;for(const[t,r]of Object.entries(Be)){for(const[t,n]of Object.entries(r))Be[t]={open:`[${n[0]}m`,close:`[${n[1]}m`},r[t]=Be[t],e.set(n[0],n[1]);Object.defineProperty(Be,t,{value:r,enumerable:!1})}return Object.defineProperty(Be,"codes",{value:e,enumerable:!1}),Be.color.close="",Be.bgColor.close="",Be.color.ansi=Fe(),Be.color.ansi256=Ue(),Be.color.ansi16m=qe(),Be.bgColor.ansi=Fe(10),Be.bgColor.ansi256=Ue(10),Be.bgColor.ansi16m=qe(10),Object.defineProperties(Be,{rgbToAnsi256:{value:(e,t,r)=>e===t&&t===r?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(r/255*5),enumerable:!1},hexToRgb:{value(e){const t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[r]=t;3===r.length&&(r=[...r].map(e=>e+e).join(""));const n=Number.parseInt(r,16);return[n>>16&255,n>>8&255,255&n]},enumerable:!1},hexToAnsi256:{value:e=>Be.rgbToAnsi256(...Be.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return e-8+90;let t,r,n;if(e>=232)t=(10*(e-232)+8)/255,r=t,n=t;else{const a=(e-=16)%36;t=Math.floor(e/36)/5,r=Math.floor(a/6)/5,n=a%6/5}const a=2*Math.max(t,r,n);if(0===a)return 30;let i=30+(Math.round(n)<<2|Math.round(r)<<1|Math.round(t));return 2===a&&(i+=60),i},enumerable:!1},rgbToAnsi:{value:(e,t,r)=>Be.ansi256ToAnsi(Be.rgbToAnsi256(e,t,r)),enumerable:!1},hexToAnsi:{value:e=>Be.ansi256ToAnsi(Be.hexToAnsi256(e)),enumerable:!1}}),Be}(),Ge=(()=>{if(!("navigator"in globalThis))return 0;if(globalThis.navigator.userAgentData){const e=navigator.userAgentData.brands.find(({brand:e})=>"Chromium"===e);if(e&&e.version>93)return 3}return/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)?1:0})(),He=0!==Ge&&{level:Ge},Ke={stdout:He,stderr:He};function We(e,t,r){let n=e.indexOf(t);if(-1===n)return e;const a=t.length;let i=0,s="";do{s+=e.slice(i,n)+t+r,i=n+a,n=e.indexOf(t,i)}while(-1!==n);return s+=e.slice(i),s}const{stdout:Ze,stderr:Je}=Ke,Ye=Symbol("GENERATOR"),Qe=Symbol("STYLER"),Xe=Symbol("IS_EMPTY"),et=["ansi","ansi","ansi256","ansi16m"],tt=Object.create(null),rt=e=>{const t=(...e)=>e.join(" ");return((e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const r=Ze?Ze.level:0;e.level=void 0===t.level?r:t.level})(t,e),Object.setPrototypeOf(t,nt.prototype),t};function nt(e){return rt(e)}Object.setPrototypeOf(nt.prototype,Function.prototype);for(const[e,t]of Object.entries(Ve))tt[e]={get(){const r=ct(this,ot(t.open,t.close,this[Qe]),this[Xe]);return Object.defineProperty(this,e,{value:r}),r}};tt.visible={get(){const e=ct(this,this[Qe],!0);return Object.defineProperty(this,"visible",{value:e}),e}};const at=(e,t,r,...n)=>"rgb"===e?"ansi16m"===t?Ve[r].ansi16m(...n):"ansi256"===t?Ve[r].ansi256(Ve.rgbToAnsi256(...n)):Ve[r].ansi(Ve.rgbToAnsi(...n)):"hex"===e?at("rgb",t,r,...Ve.hexToRgb(...n)):Ve[r][e](...n),it=["rgb","hex","ansi256"];for(const e of it){tt[e]={get(){const{level:t}=this;return function(...r){const n=ot(at(e,et[t],"color",...r),Ve.color.close,this[Qe]);return ct(this,n,this[Xe])}}};tt["bg"+e[0].toUpperCase()+e.slice(1)]={get(){const{level:t}=this;return function(...r){const n=ot(at(e,et[t],"bgColor",...r),Ve.bgColor.close,this[Qe]);return ct(this,n,this[Xe])}}}}const st=Object.defineProperties(()=>{},{...tt,level:{enumerable:!0,get(){return this[Ye].level},set(e){this[Ye].level=e}}}),ot=(e,t,r)=>{let n,a;return void 0===r?(n=e,a=t):(n=r.openAll+e,a=t+r.closeAll),{open:e,close:t,openAll:n,closeAll:a,parent:r}},ct=(e,t,r)=>{const n=(...e)=>lt(n,1===e.length?""+e[0]:e.join(" "));return Object.setPrototypeOf(n,st),n[Ye]=e,n[Qe]=t,n[Xe]=r,n},lt=(e,t)=>{if(e.level<=0||!t)return e[Xe]?"":t;let r=e[Qe];if(void 0===r)return t;const{openAll:n,closeAll:a}=r;if(t.includes(""))for(;void 0!==r;)t=We(t,r.close,r.open),r=r.parent;const i=t.indexOf("\n");return-1!==i&&(t=function(e,t,r,n){let a=0,i="";do{const s="\r"===e[n-1];i+=e.slice(a,s?n-1:n)+t+(s?"\r\n":"\n")+r,a=n+1,n=e.indexOf("\n",a)}while(-1!==n);return i+=e.slice(a),i}(t,a,n,i)),n+t+a};Object.defineProperties(nt.prototype,tt);const ut=nt();nt({level:Je?Je.level:0});const dt=e("build").description("Build the application").addHelpText("after",["","If no manifest is provided, searches for a default app.manifest(.$ENV)?.[ts|js|json] in the current directory.","example: `ffc app build --env prod` will search for `app.manifest.prod.ts` then fallback to `app.manifest.ts`","","NOTE: app manifest is not required, a default manifest will be generated if not provided","","OUTPUT LOCATION:"," The build output location is determined by the `main` field in your package.json.",' - "main": "dist/index.js" → outputs to dist/index.js',' - "main": "build/app.js" → outputs to build/app.js'," - No main field → defaults to dist/bundle.js"," Output directory cannot be project root, src/, or current working directory.","","Examples:"," $ ffc app build"," $ ffc app build app.manifest.dev.ts --debug"].join("\n")).option("-d, --debug","Enable debug mode for verbose logging",!1).argument("[manifest]","Manifest file to use for building (e.g., app.manifest.ts)").action(async(e,t)=>{const r=new m("app:build",{debug:t.debug});await h({log:r,manifest:e})}),pt="app-bundle.zip",mt=e("pack").description("Create a distributable app bundle of the application.").addHelpText("after",["","If no manifest is provided, a default app.manifest(.$ENV)?.[ts|js|json] is used from the current directory.","example: `ffc app pack --env prod` will search for `app.manifest.prod.ts` then fallback to `app.manifest.ts`","","NOTE: app manifest is not required, a default manifest will be generated if not provided","","Examples:"," $ ffc app pack"," $ ffc app pack app.manifest.dev.ts --archive my-app.zip --output ./dist"].join("\n")).option("-a, --archive [string]","Name of the output archive file (default: app-bundle.zip)",pt).option("-o, --output [string]","Directory where the archive will be saved (default: current working directory)",process.cwd()).option("-d, --debug","Enable debug mode for verbose logging",!1).argument("[manifest]","Manifest file to use for bundling (e.g., app.manifest.ts)").action(async(e,t)=>{const r=new m("app:pack",{debug:t.debug});await f({log:r,manifest:e,archive:t.archive}).catch(e=>{r.error("Failed to create package:",e),process.exit(1)})}),ht=e=>{const r=Object.values(g).filter(t=>t!==g.Development||e.allowDev);return t("-e, --env <string>",`Set environment [${r.join(", ")}, custom].`).env("FUSION_ENV").default(e.default??y(e.allowDev))};ht({allowDev:!0});const ft=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,gt=t("--tenantId <string>","The Azure Active Directory tenant ID").env("FUSION_TENANT_ID").default("3aa4a235-b6e2-48d5-9195-7fcf05b459b0"),yt=t("--clientId <string>","The client ID of the application registered in Azure AD").env("FUSION_CLIENT_ID").default("a318b8e1-0295-4e17-98d5-35f67dfeba14"),vt=t("--token <string>","The Azure AD access token. If provided, the --tenant and --client options are ignored").env("FUSION_TOKEN").default(void 0),bt=t("--scope <scopes...>","Azure audience scope, normally the application ID URI of the API you want to access and `.default`").env("FUSION_AUTH_SCOPE").default(["5a842df8-3238-415d-b168-9f16a6a6031b/.default"]),_t=(e,t)=>(e.addOption(gt),e.addOption(yt),t?.excludeToken||e.addOption(vt),t?.includeScope&&e.addOption(bt),e.hook("preAction",e=>{const n=e.opts();if(n.token){if("string"!=typeof n.token||""===n.token.trim())throw new r("Token must be a non-empty string.");return e.setOptionValue("tenantId",void 0),e.setOptionValue("clientId",void 0),void(t?.includeScope&&e.setOptionValue("scope",void 0))}if(!n.tenantId||"string"!=typeof n.tenantId)throw new r("Tenant ID must be a non-empty string.");if(!ft.test(n.tenantId))throw new r("Tenant ID must be a valid UUID.");if(!n.clientId||"string"!=typeof n.clientId)throw new r("Client ID must be a non-empty string.");if(!ft.test(n.clientId))throw new r("Client ID must be a valid UUID.");if(t?.includeScope){if(!Array.isArray(n.scope)||0===n.scope.length)throw new r("Scope must be a non-empty array of strings.");for(const e of n.scope)if("string"!=typeof e||""===e.trim())throw new r("Each scope must be a non-empty string.")}}),e),wt=_t(e("check").description("Check if application is registered in Fusion app store.").addHelpText("after",["","Verifies the registration status of your application in the Fusion app store.","Helps identify issues with app registration or configuration.","","FIRST TIME SETUP:"," Before checking app status, ensure your app is registered in the Fusion App Admin."," The check command will tell you if your app is properly registered.","","Examples:"," $ ffc app check"," $ ffc app check --env prod --debug"].join("\n")).option("-d, --debug","debug mode",!1).addOption(ht({allowDev:!1})).action(async e=>{const t=new m("app:check",{debug:!!e.debug});await v({log:t,environment:e.env,auth:"token"in e?{token:e.token}:e})})),St=_t(e("upload").description("Upload a Fusion application bundle to the Fusion App Store.").addHelpText("after",["","Uploads a distributable application bundle (e.g., app-bundle.zip) to the Fusion app store.","","Examples:"," $ ffc app upload"," $ ffc app upload --env ci"," $ ffc app upload my-app-bundle.zip --appKey my-app"," $ ffc app upload --debug"].join("\n")).option("-d, --debug [boolean]","Enable debug mode for verbose logging",!1).option("-k, --appKey <string>","Application key (if not provided, resolved from the build metadata of the bundle)").addOption(ht({allowDev:!1})).argument("[bundle]","Application bundle to upload",pt).action(async(e,t)=>{const r=new m("portal:upload",{debug:t.debug});await v({log:r,environment:t.env,auth:"token"in t?{token:t.token}:t})||(r.error("😢 App is not registered / deleted in app store"),process.exit(1)),r?.start("💾 Initializing Fusion Framework...");const n=await b({env:t.env,auth:{token:t.token,tenantId:t.tenantId,clientId:t.clientId}});r?.succeed("💾 Initialized Fusion Framework"),await _({log:r,appKey:t.appKey,framework:n,fileOrBundle:e}).catch(e=>{r.error("😢 Failed to upload bundle:",e),process.exit(1)})})),Nt=_t(e("config").description("Generate or publish the Fusion application configuration object.").addHelpText("after",["","By default, outputs the generated config object to stdout or a file. Use --publish to upload the config to the Fusion app registry.","- Options [--token, --tenantId, --clientId, --manifest] are only relevant when --publish is used.",'- Option [-e, --env] cannot be set to "dev" when --publish is used.',"","Note:","- If not `app.config(.$ENV)?.[ts|js|json]` is found it will fallback to generate a default config (empty object)","- If not `app.manifest(.$ENV)?.[ts|js|json]` is found it will fallback to generate a default manifest","","Examples:"," $ ffc app config app.config.ts"," $ ffc app config app.config.prod.ts --output ./dist/app.config.json"," $ ffc app config app.manifest.prod.ts --silent > ./dist/app.config.json"," $ ffc app config --publish --manifest app.manifest.ts --env prod"," $ ffc app config --env prod my-custom.config.ts"].join("\n")).option("--debug","Enable debug mode for verbose logging").option("--silent","Silent mode, suppresses output except errors").option("--publish","Publish config to Fusion app registry").option("--manifest <path>","Path to the app manifest file (required with --publish)").addOption(ht({allowDev:!0})).option("-o, --output <stdout|path>","Output the result to stdout or a file (ignored with --publish, default: stdout)","stdout").argument("[config]","Config build file to use (e.g., app.config[.env]?.[ts,js,json])").action(async(e,t)=>{const r=t.silent?null:new m("app:config",{debug:!!t.debug});if(t.publish)return"dev"===t.env&&(r?.fail("🤪",ut.blue("--env"),'cannot be "dev" when',ut.blue("--publish")," is used"),process.exit(1)),w({config:e,manifest:t.manifest,environment:t.env,auth:"token"in t?{token:t.token}:t,debug:t.debug});const{config:n}=await S({log:r,config:e,env:{environment:t.env},output:"stdout"===t.output?void 0:t.output});"stdout"===t.output&&console.log(JSON.stringify(n,null,2))}));const kt=_t(e("tag").description("Tag your uploaded Fusion Application build version with a specific tag.").addHelpText("after",["","Note: using --package is preferred over --manifest, since no infered compilation is required.","","Examples:"," $ ffc app tag latest"," $ ffc app tag preview --env prod --manifest app.manifest.prod.ts"," $ ffc app tag stable --package my-app@1.2.3"," $ ffc app tag latest --manifest app.manifest.custom.ts"].join("\n")).addOption(ht({allowDev:!1})).option("-p, --package [package@version]","Package to tag in format name@version (e.g., my-app@1.0.0)").option("-m, --manifest <string>","Manifest file to use. Note: ignoring if --package is provided").option("--debug","Enable debug mode for verbose logging").option("--silent","Silent mode, suppresses output except errors").argument("<tag>",`Tag to apply (${Object.values(N).join(" | ")})`).action(async(e,t)=>{const r=t.silent?null:new m("app:tag",{debug:t.debug}),n={command:"build",environment:t.env,mode:process.env.NODE_ENV??"production",root:process.cwd()};let a,i;try{({appKey:a,version:i}=await async function(e,t){if(e.package){const[t,r]=e.package.split("@");if(!t||!r)throw new Error("Package must be in format name@version (e.g., my-app@1.0.0). Please verify the package name and version with --package");return{appKey:t,version:r}}const{manifest:r}=await x({manifest:e.manifest,env:t}),n=r.build?.version;if(!n)throw new Error(`Could not determine version from manifest. Please verify manifest ${e.manifest} or provide a package name and version with --package`);return{appKey:r.appKey,version:n}}(t,n))}catch(e){r?.error(`😢 ${e instanceof Error?e.message:"Unknown error occurred"}`),process.exit(1)}r?.info("Tagging application:",ut.greenBright(`${a}@${i} - ${e}`)),r?.start("Initializing Fusion Framework...");const s=await b({env:t.env,auth:{token:t.token,tenantId:t.tenantId,clientId:t.clientId}});r?.succeed("Initialized Fusion Framework"),r?.start("Tagging application..."),await k({appKey:a,version:i,framework:s,log:r,tag:e}).catch(e=>{r?.error("Failed to tag application:",e),process.exit(1)})})),xt=e("dev").description("Start the application in development mode.").addHelpText("after",["","Configuration:"," dev-server.config.ts Optional configuration file for API mocking, service discovery,"," and development environment customization","","Examples:"," $ ffc app dev"," $ ffc app dev --port 4000"," $ ffc app dev --manifest ./app.manifest.local.ts --config ./app.config.ts"," $ ffc app dev --host 0.0.0.0","","See https://equinor.github.io/fusion-framework/cli/docs/dev-server-config.html for configuration options."].join("\n")).option("--debug","Enable debug mode").option("--manifest <path>","Path to the app manifest file (app.manifest[.env]?.[ts,js,json])").option("--config <path>","Path to the app config file (app.config[.env]?.[ts,js,json])").option("--env <environment>","Runtime environment for the dev server","local").option("--port <port>","Port for the development server","3000").option("--host <host>","Host for the development server").action(async e=>{const t=new m("app:dev",{debug:e.debug});t.start("Starting application in development mode..."),E({log:t,manifest:e.manifest,config:e.config,env:e.env,port:e.port,host:e.host}),t.succeed("Development server started successfully.")}),Et=(e,t)=>{try{return M(e,D.F_OK),!0}catch(e){return!1}},Pt=e("manifest").description("Build and output the application manifest for Fusion apps.").addHelpText("after",["","By default, outputs the generated manifest object to stdout or a file. Use --output to write to a file.","","Note:","- If not `app.manifest(.$ENV)?.[ts|js|json]` is found it will fallback to generate a default manifest","","Examples:"," $ ffc app manifest"," $ ffc app manifest app.manifest.prod.ts --output ./dist/app.manifest.json",' $ ffc app manifest --silent | jq ".build.entryPoint"'," $ ffc app manifest --debug"].join("\n")).option("-d, --debug","Enable debug mode for verbose logging",!1).option("-o, --output <string>","Output the result to stdout or a file","stdout").option("-s, --silent","Silent mode, suppresses output except errors").argument("[manifest]","Manifest build file to use (e.g., app.manifest[.env]?.[ts,js,json])").action(async(e,t)=>{const r=t.silent?null:new m("app:manifest",{debug:t.debug}),n=await x({log:r,manifest:e});if("stdout"!==t.output){const e=c(process.cwd(),t.output);r?.start("Writing manifest to file",t.output),Et(l(e))||await R(l(e),{recursive:!0}),await L(e,JSON.stringify(n.manifest,null,2)),r?.succeed("Manifest written to file",e)}else console.log(JSON.stringify(n.manifest,null,2))}),Ct=_t(e("publish").description("Deployment: Upload and tag your Fusion application (builds if no bundle provided).").addHelpText("after",["","WHAT THIS COMMAND DOES:"," 1. Builds your application (if no bundle provided)"," 2. Uploads the bundle to Fusion app registry"," 3. Tags the uploaded version for deployment","","If no manifest is provided, a default app.manifest(.$ENV)?.[ts|js|json] is used from the current directory.","example: `ffc app publish --env prod` will search for `app.manifest.prod.ts` then fallback to `app.manifest.ts`","","NOTE: app manifest is not required, a default manifest will be generated if not provided","","FIRST TIME PUBLISHING:"," - Ensure your app is registered in Fusion App Admin"," - Use `ffc app check` first to verify registration status"," - Start with a test environment before production","","Examples:"," $ ffc app publish"," $ ffc app publish --env prod --manifest app.manifest.prod.ts"," $ ffc app publish --tag latest app.bundle.zip"].join("\n")).option("-d, --debug","Enable debug mode for verbose logging",!1).addOption(ht({allowDev:!1})).option("-m, --manifest [string]","Manifest file to use for bundling (e.g., app.manifest.ts)").option("-t, --tag [string]",`Tag to apply to the published app (${Object.values(N).join(" | ")})`,N.Latest).argument("[bundle]","Path to the app bundle to upload").action(async(e,t)=>{const r=new m("app:publish",{debug:t.debug});let n;if(await v({log:r,environment:t.env,auth:"token"in t?{token:t.token}:t})||(r.error("😢 App is not registered / deleted in app store"),process.exit(1)),e)r.info(`📦 Using provided bundle: ${e}`),n=e;else try{r.start("📦 Bundle application...");n=(await f({log:r,manifest:t.manifest})).archive,r.succeed("📦 Bundle completed")}catch(e){r.error("😢 Failed to bundle application:",e),process.exit(1)}n||(r.error("😢 No bundle provided or created. Please specify a bundle file."),process.exit(1)),r?.start("💾 Initializing Fusion Framework...");const a=await b({env:t.env,auth:{token:t.token,tenantId:t.tenantId,clientId:t.clientId}});r?.succeed("💾 Initialized Fusion Framework"),r.start("🚀 Uploading application...");const i=await _({log:r,framework:a,fileOrBundle:n}).catch(e=>{r.error("😢 Failed to upload bundle:",e),process.exit(1)});r.succeed("🚀 Upload completed"),r.debug("Upload result:",i),r.start("🏷️ Tagging application...");const s=await k({tag:t.tag,appKey:i.name,version:i.version,log:r,framework:a}).catch(e=>{r.error("😢 Failed to tag application:",e),process.exit(1)});r.succeed("Tagging completed"),r.debug("Tagging result:",s)}));async function At(e,t="https://registry.npmjs.org"){const r=await async function(e,t="https://registry.npmjs.org"){try{const r=await fetch(`${t}/${e}`);if(!r.ok)throw new Error(`Failed to fetch package info for ${e}: ${r.statusText}`);const n=await r.json();if(!n.name)throw new Error(`Invalid package data received for ${e}`);const a=n["dist-tags"]?.latest;if(!a)throw new Error(`No latest version found for package ${e}`);return{name:n.name,latest:a,versions:Object.keys(n.versions||{}),"dist-tags":n["dist-tags"]||{},description:n.description,homepage:n.homepage,repository:n.repository,author:n.author,license:n.license,keywords:n.keywords,dependencies:n.dependencies,devDependencies:n.devDependencies,peerDependencies:n.peerDependencies}}catch(t){throw new Error(`Failed to fetch package info for ${e}: ${t instanceof Error?t.message:String(t)}`)}}(e,t);return r.latest}async function It(e,t){const r=[{key:"dependencies",deps:e.dependencies},{key:"devDependencies",deps:e.devDependencies},{key:"peerDependencies",deps:e.peerDependencies}].filter(e=>void 0!==e.deps&&null!==e.deps);if(0!==r.length){t?.start(`Resolving workspace dependencies for ${r.length} dependency types`);try{const n=await Promise.all(r.map(({key:e,deps:r})=>async function(e,t,r){try{const n=Object.entries(t).filter(e=>function(e){return"string"==typeof e&&e.startsWith("workspace:")}(e[1]));if(0===n.length)return r?.debug(`No workspace dependencies found in ${e}`),{key:e,resolved:t};r?.debug(`Resolving ${n.length} workspace dependencies for ${e}`);const a=await Promise.all(n.map(async([e,t])=>{try{const n=await At(e);return r?.debug(`Resolved ${e}: ${t} -> ${n}`),[e,n]}catch(n){const a=n instanceof Error?n.message:String(n);return r?.debug(`Failed to resolve ${e}: ${a}`),[e,t]}})),i={...t};for(const[e,t]of a)i[e]=t;return r?.debug(`Successfully processed ${e} with ${a.length} resolved dependencies`),{key:e,resolved:i}}catch(n){const a=n instanceof Error?n.message:String(n);return r?.debug(`Error processing ${e}: ${a}`),{key:e,resolved:t}}}(e,r,t)));for(const{key:t,resolved:r}of n)e[t]=r;const a=n.reduce((e,{resolved:t})=>e+Object.keys(t).length,0);t?.succeed(`Workspace dependencies resolved successfully (${a} total dependencies processed)`)}catch(e){const r=e instanceof Error?e.message:String(e);throw t?.debug(`Error details: ${r}`),new Error(`Failed to resolve workspace dependencies: ${r}`)}}else t?.debug("No dependencies found to resolve")}function Ot(e,t){if("string"!=typeof e||""===e.trim())throw new Error("Target path must be a non-empty string");const r=c(e);if(t){const e=c(t);if(!Z(r,e))throw new Error("The target path must be within the specified base directory. Please specify a relative path or ensure the absolute path is within the base directory.")}return r}function Tt(e,t,r){const n=Ot(e,r);U(n,t)}const $t=["code","cursor"];async function zt(e,t){t.info("By selecting an IDE, it will be opened in a new window."),t.info("👋 please come back to this terminal to continue."),t.info(`You can also open the project in your IDE later by typing e.g. \`code ${e}\` in the terminal.`),t.info("If you do not want to open the project in an IDE, select no.");const{openInIDE:r}=await W.prompt([{type:"list",name:"openInIDE",message:"🚀 Open project in IDE?",default:!1,choices:[{name:"VS Code",value:"code"},{name:"Cursor",value:"cursor"},{name:"No, I will open the project in my IDE later",value:!1}]}]);if(r){if(!function(e){return $t.includes(e)}(r))return void t.error(`Invalid IDE command: ${r}. Only supported IDEs are: ${$t.join(", ")}`);try{const n=J(r,[e],{stdio:"pipe",detached:!0});n.unref(),n.catch(e=>{void 0!==e.exitCode&&0!==e.exitCode?t.error(`IDE process exited with code ${e.exitCode}. The IDE may not have opened successfully.`):t.error(`Failed to open IDE (${r}): ${e.message}`)})}catch(e){t.error(`Failed to spawn IDE process (${r}): ${e instanceof Error?e.message:String(e)}`)}}}const Rt=["npm","pnpm"];async function Lt(e,t){const{installDeps:r}=await W.prompt([{type:"confirm",name:"installDeps",message:"📦 Install dependencies?",default:!0}]);if(!r)return t.debug("Skipping dependency installation"),{installed:!1};const{packageManager:n}=await W.prompt([{type:"list",name:"packageManager",message:"📦 Which package manager do you want to use?",choices:["pnpm","npm"],default:"pnpm"}]);return await async function(e,t,r){K(Rt.includes(t),"Package manager must be npm or pnpm"),r?.start("Installing dependencies...");try{return await J(t,["install"],{cwd:e,stdio:"inherit",shell:!0}),r?.succeed("Dependencies installed successfully!"),t}catch(e){if(e instanceof Y&&0!==e.exitCode)throw r?.error(`${t} install failed with exit code ${e.exitCode}`),new Error(`${t} install failed with exit code ${e.exitCode}`);throw r?.error(`Failed to run ${t} install: ${e instanceof Error?e.message:String(e)}`),e}}(e,n,t),{installed:!0,packageManager:n}}class Mt{#e;#t;#r;get name(){return this.#e.name}get description(){return this.#e.description}get resources(){return this.#e.resources}constructor(e,t,r){this.#e=e,this.#r=t,this.#t=r.logger}copyTo(e){this.#t?.debug(`Copying template resources to ${e}`);for(const t of this.#e.resources){this.#t?.debug(`Copying resource ${t.path}`,{resource:t});const r=u(this.#r,t.path),n=u(e,t.target??t.path);if(q(r))try{"file"===t.type?(V(r,n),this.#t?.debug(`Copied file: ${t.path} -> ${n}`)):"dir"===t.type?(G(r,n,{recursive:t.recursive??!1}),this.#t?.debug(`Copied directory: ${t.path} -> ${n}`)):this.#t?.debug("Resource is not a file or directory, skipping",{resource:t})}catch(e){throw this.#t?.error(`Failed to copy resource ${t.path}:`,e),e}else this.#t?.warn(`Source resource does not exist, skipping: ${r}`)}}}const Dt=oe.object({type:oe.literal("file"),path:oe.string(),target:oe.string().optional()}),jt=oe.object({type:oe.literal("dir"),path:oe.string(),target:oe.string().optional(),recursive:oe.boolean().optional()}),Ft=oe.discriminatedUnion("type",[Dt,jt]),Ut=oe.object({name:oe.string(),description:oe.string(),resources:oe.array(Ft)}),qt=oe.object({templates:oe.array(Ut),resources:oe.array(Ft).optional()});class Bt{repo;#n=!1;#a;#i;#s;#o;#c;get protocol(){return this.#o}set protocol(e){K("https"===e||"ssh"===e,"Protocol must be either https or ssh"),this.#o=e}get branch(){return this.#c}get repoUrl(){return"ssh"===this.#o?`git@github.com:${this.repo}.git`:`https://github.com/${this.repo}.git`}set branch(e){this.#c=e,this.#n&&this._checkoutBranch()}constructor(e,t){this.repo=e,this.#i=t.baseDir??u(te(),"ffc","repo",e),this.#s=t.log,this.#c=t.branch??"main",this.#a=ae(),this.#o=t.protocol??"https"}async initialize(){if(!this.#n)try{if(this.#s?.debug("Checking if repository directory exists...",this.#i),q(this.#i)||(this.#s?.info("Repository directory does not exist, creating..."),H(this.#i,{recursive:!0}),this.#s?.succeed("Repository directory created successfully!")),this.#a=ae({baseDir:this.#i}),this._setupOutputHandler(),!this.#o)try{const e=await this.#a.getConfig("core.sshCommand");this.#o=e?"ssh":"https"}catch{this.#o="https"}this.#s?.debug("Checking if repository is initialized...");await this.#a.checkIsRepo()?(this.#s?.info("Git is initialized, checking out branch..."),await this._checkoutBranch(),this.#s?.succeed("Branch checked out successfully!")):(this.#s?.info("Git is not initialized, cloning repo..."),await this._cloneRepo(),this.#s?.succeed("Repo cloned successfully!")),this.#s?.succeed("Repository initialized successfully!"),this.#n=!0}catch(e){throw this.#s?.fail("Repository initialization failed!"),this.#s?.error(e),e}}async getAvailableTemplates(){let e;try{const t=u(this.#i,"templates.json");this.#s?.debug("Reading template manifest file...",t),e=j(t,"utf8")}catch(e){throw new Error("Failed to read templates.json file from the root of the repository...",{cause:e})}try{this.#s?.debug("Parsing and validating template content...");const t=function(e){try{const t=JSON.parse(e);return qt.parse(t)}catch(e){if(e instanceof oe.ZodError)throw new Error(`Template manifest validation failed: ${e.message}`);throw new Error(`Failed to parse JSON: ${e instanceof Error?e.message:"Unknown error"}`)}}(e);this.#s?.debug("Parsed template content...",t);return t.templates.map(e=>{const r=[...t.resources??[],...e.resources];return new Mt({...e,resources:r},this.#i,{logger:this.#s})})}catch(e){throw new Error("Failed to parse templates.json content",{cause:e})}}async cleanup(){try{this.#s?.debug(`Removing repository directory: ${this.#i}`);return Tt(Ot(this.#i,te()),{recursive:!0,force:!0},te()),this.#s?.succeed("Repository directory cleaned up successfully!"),this.#n=!1,!0}catch(e){return this.#s?.error(`Failed to remove repository directory: ${this.#i}`,e),!1}}async _cloneRepo(){try{this.#s?.debug("Cloning repo...",{repo:this.repo,repoUrl:this.repoUrl,baseDir:this.#i,branch:this.#c,protocol:this.#o}),await this.#a.clone(this.repoUrl,this.#i,["--single-branch","--branch",this.#c])}catch(e){throw new Error("Failed to clone repo...",{cause:e})}}async _checkoutBranch(){try{this.#s?.debug("Fetching repo...",{repo:this.repo,repoUrl:this.repoUrl}),await this.#a.fetch(),this.#s?.debug("Checking out branch...",this.#c);(await this.#a.checkout(this.#c)).includes("branch is up to date")?this.#s?.debug("Branch is up to date!"):(this.#s?.info("Branch is not up to date, updating to latest changes..."),await this.#a.reset(ie.HARD).pull(),this.#s?.debug("Branch updated successfully!"))}catch(e){throw new Error("Failed to checkout branch...",{cause:e})}}_setupOutputHandler(){this.#a.outputHandler((e,t,r)=>{t.on("data",e=>{this.#s?.debug("🐙",String(e))}),r.on("data",e=>{this.#s?.error("🐙",String(e))})})}}const Vt=[".rsa",".ed25519",".ecdsa",".dsa"],Gt=/(_rsa|_ed25519|_ecdsa|_dsa)$/,Ht=new Set(["known_hosts","config","authorized_keys","authorized_keys2","ssh_config","ssh_known_hosts"]);function Kt(e){if(e.endsWith(".pub"))return!1;if(Ht.has(e))return!1;const t=e.startsWith("id_"),r=Vt.some(t=>e.endsWith(t)),n=Gt.test(e);return t||r||n}async function Wt(e){e?.debug("Detecting SSH configuration...");const t=function(){try{return X("git config core.sshCommand",{stdio:"ignore"}),!0}catch{return!1}}()||function(e){try{const t=u(re(),".ssh");if(!q(t))return!1;for(const r of B(t,{withFileTypes:!0}))if(r.isFile()&&Kt(r.name))return e?.debug("SSH private key detected in .ssh directory"),!0;return!1}catch{return!1}}(e);t&&e?.debug("SSH configuration detected");const r=t?void 0:"SSH not configured (no SSH keys or git config found)",{selectedProtocol:n}=await W.prompt([{type:"list",name:"selectedProtocol",message:"🔐 Which Git protocol would you like to use for cloning?",choices:[{name:"HTTPS - Works with personal access tokens and is generally more compatible",value:"https",short:"HTTPS"},{name:"SSH - Faster and more secure, but requires SSH key setup",value:"ssh",short:"SSH",disabled:r}],default:t?"ssh":"https",pageSize:5,loop:!1}]);return e?.debug(`Selected protocol: ${n}`),n}async function Zt(e,t,r){K(!!e,"App name is required"),K(q(t.directory),`Directory '${t.directory}' does not exist, use -d to specify a different directory`);const n=c(t.directory,e);r.debug(`Target dir: ${n}`);const a=await async function(e,t,r=!1,n=process.cwd()){let a;K("string"==typeof e,"Target directory must be a string");try{a=Ot(e,n)}catch(e){const r=e instanceof Error?e.message:String(e);return t.error(`❌ Invalid target directory path: ${r}`),t.info('💡 Try using a relative path like "my-app" or ensure the absolute path is within the specified directory.'),!1}if(!q(a))return t.debug(`Target directory does not exist: ${a}`),!0;try{const e=B(a);if(0===e.length)return t.debug(`Target directory is empty: ${a}`),!0;if(t.warn(`Target directory '${a}' is not empty and contains ${e.length} item(s).`),t.info("Contents:",e.slice(0,10).join(", ")+(e.length>10?"...":"")),r){t.info("Cleaning target directory (--clean flag)...");try{Tt(a,{recursive:!0,force:!0},n),t.succeed("Target directory cleaned successfully!")}catch(e){throw t.error(`Failed to clean target directory: ${e}`),t.info("Check directory permissions and ensure you have write access to the directory."),t.info("You may need to run the command with elevated privileges or manually remove the files."),e}}else{const{action:e}=await W.prompt([{type:"list",name:"action",message:"What would you like to do?",choices:[{name:"Continue - Add files to existing directory",value:"continue"},{name:"Clean - Remove all existing files and continue",value:"clean"},{name:"Abort - Cancel the operation",value:"abort"}],default:"abort"}]);if("abort"===e)return t.info("Operation cancelled by user."),!1;if("clean"===e){t.info("Cleaning target directory...");try{Tt(a,{recursive:!0,force:!0},n),t.succeed("Target directory cleaned successfully!")}catch(e){throw t.error(`Failed to clean target directory: ${e}`),t.info("Check directory permissions and ensure you have write access to the directory."),t.info("You may need to run the command with elevated privileges or manually remove the files."),e}}else t.info("Continuing with existing directory...")}return!0}catch(e){throw t.error(`Failed to check target directory: ${e}`),t.info("Ensure the path is valid and accessible, and that you have read permissions for the directory."),t.info("Check if the directory path contains any invalid characters or if the path is too long."),e}}(n,r,t.clean,t.directory);a||process.exit(0);const i=await async function(e,t,r,n){const a=c(te(),"ffc","repo",e);if(n.debug(`Repo dir: ${a}`),t){n.debug(`Removing repo dir: ${a}`);try{Tt(Ot(a,te()),{recursive:!0,force:!0},te())}catch(e){n.debug("Cleanup failed:",e)}}const i=await Wt(n),s=new Bt(e,{baseDir:a,log:n,branch:r,protocol:i});return await s.initialize(),s}("equinor/fusion-app-template",t.clean,t.branch,r),s=await i.getAvailableTemplates(),o=await async function(e,t,r){K(Array.isArray(e),"Templates must be an array"),K(e.length>0,"No templates available");const n=e.map(e=>e.name);if(t){K("string"==typeof t,"Pre-selected template must be a string"),K(n.includes(t),"Pre-selected template must be in the list of available templates"),r?.debug(`Using pre-selected template: ${t}`);const a=e.find(e=>e.name===t);return K(a,"Pre-selected template not found"),a}if(1===e.length)return r?.debug(`Using single template: ${e[0].name}`),e[0];const{selectedTemplate:a}=await W.prompt([{type:"list",name:"selectedTemplate",message:"🎨 Please select a template:",choices:e.map(e=>({name:`${e.name} - ${e.description}`,value:e})),pageSize:10,loop:!1}]);return a}(s,t.template,r);try{await o.copyTo(n),r.succeed("Template resources copied successfully!")}catch(e){r.error(`Failed to copy template resources: ${e instanceof Error?e.message:String(e)}`),r.info("Please check the target directory permissions and try again"),process.exit(1)}try{await(async(e,t,r)=>{const n=u(e,"package.json");try{const e=j(n,"utf-8"),a=JSON.parse(e);let i={...a};if(t?.resolveWorkspaceDependencies){r?.debug("Resolving workspace dependencies");const e=JSON.parse(JSON.stringify(a));await It(e,r),i=e}t?.updates&&(r?.debug(`Applying updates: ${Object.keys(t.updates).join(", ")}`),i={...i,...t.updates}),JSON.stringify(a)!==JSON.stringify(i)?(r?.debug("Writing updated package.json to disk"),F(n,`${JSON.stringify(i,null,2)}\n`)):r?.debug("No changes detected, skipping package.json update")}catch(e){throw new Error(`Failed to update package.json: ${e instanceof Error?e.message:String(e)}`)}})(n,{updates:{name:e},resolveWorkspaceDependencies:!0},r),r.succeed(`Updated package.json with app name: ${e}`)}catch(e){r.error(`Failed to update package.json: ${e instanceof Error?e.message:String(e)}`),r.info("Please check the package.json file and try again"),process.exit(1)}await async function(e,t){const{cleanupTempFiles:r}=await W.prompt([{type:"confirm",name:"cleanupTempFiles",message:"🗑️ Clean up temporary template files?",default:!1}]);r?await e.cleanup():t.debug("Skipping cleanup of temporary template files")}(i,r),await zt(n,r);const{installed:l,packageManager:d}=await Lt(n,r);if(l&&d){const e=await async function(e,t,r,n=!1){const{startDev:a}=await W.prompt([{type:"confirm",name:"startDev",message:"🚀 Start development server?",default:!0}]);if(a){r.debug(`Starting development server: ${e}`),n&&r.info("Running in persistent mode - server will run until manually stopped (Ctrl+C)");try{const a=Q(t,["run","dev"],{cwd:e,stdio:"inherit"});let i=null,s=!1;if(!n){const e=6e4;i=setTimeout(()=>{s=!0,r.error(`Development server did not start within ${e/1e3} seconds and may be hanging. Terminating process.`),a.kill("SIGTERM"),r.info(`You can try running '${t} run dev' manually in the project directory.`)},e)}const o=()=>{i&&clearTimeout(i),a.removeAllListeners("error"),a.removeAllListeners("exit")};return a.on("error",e=>{o(),s||(r.error(`Failed to start development server with ${t}: ${e.message}`),r.info(`Make sure ${t} is installed and the 'dev' script exists in package.json`))}),a.on("exit",e=>{o(),s||0===e||n?n&&0!==e&&r.info(`Development server stopped with exit code ${e}`):(r.error(`Development server process exited with code ${e}. The server may not have started successfully.`),r.info(`Check the output above for error details or try running '${t} run dev' manually`))}),!0}catch(e){r.error(`Failed to spawn development server process with ${t}: ${e instanceof Error?e.message:String(e)}`),r.info(`Make sure ${t} is installed and the 'dev' script exists in package.json`)}}return!1}(n,d,r,!0);e&&r.debug("Development server started successfully")}}const Jt=t=>e(t).description("Create a new Fusion application from template").argument("<name>","Name of the application to create").option("-t, --template <type>","Template type to use (will prompt if not specified or not found)").option("-d, --directory <path>","Directory to create the app in",".").option("--branch <branch>","Branch to checkout","main").option("--clean","Clean the repo directory before cloning").option("--debug","Enable debug mode for verbose logging").action(async(e,t)=>{const r=new m("",{debug:t.debug});try{await Zt(e,t,r)}catch(e){r.error("❌ An unexpected error occurred:",e instanceof Error?e.message:String(e)),t.debug&&r.error("Stack trace:",e instanceof Error?e.stack:"No stack trace available"),process.exit(1)}});mt.alias("build-pack").hook("preAction",e=>{"build-pack"===process.argv[3]&&(console.warn(ut.bgRedBright.bold('The command "build-pack" is deprecated. Please use "pack" instead.')),e.getOptionValue("archive")||e.setOptionValue("archive",pt))}),St.alias("build-upload").hook("preAction",e=>{if("build-upload"===process.argv[3]){if(console.warn(ut.bgRedBright.bold('The command "build-upload" is deprecated. Please use "upload" instead.')),e.getOptionValue("service"))throw new Error("The --service option is deprecated. Please use --env instead.");const t=e.getOptionValue("bundle")??pt;process.argv[4]=t}}),Pt.alias("build-manifest").hook("preAction",()=>{"build-manifest"===process.argv[3]&&console.warn(ut.bgRedBright.bold('The command "build-manifest" is deprecated. Please use "manifest" instead.'))}),Ct.alias("build-publish").hook("preAction",e=>{if("build-publish"===process.argv[3]&&console.warn(ut.bgRedBright.bold('The command "build-publish" is deprecated. Please use "publish" instead.')),e.getOptionValue("service"))throw new Error("The --service option is deprecated. Please use --env instead.")});const Yt=e("app").description("Develop, build, configure, and deploy Fusion applications from your workspace root.").addHelpText("after",["",'The "app" command is your main entry point for managing Fusion applications in this workspace.',"","It provides access to subcommands for every stage of the application lifecycle, including development, building, packaging, configuration, deployment, and release management.","","All available subcommands are listed below automatically. For details and options for a specific subcommand, run:"," fusion app <subcommand> --help","","Typical usage:"," - Create new applications from templates with the create subcommand"," - Run and test your app locally with the dev subcommand"," - Build, bundle, and configure your app for deployment"," - Upload, publish, and tag releases to the Fusion App Store"," - Check registration and generate manifests as needed","","This command should be run from your app root directory."].join("\n")).addCommand(dt).addCommand(mt).addCommand(wt).addCommand(St).addCommand(Nt).addCommand(kt).addCommand(xt).addCommand(Pt).addCommand(Ct).addCommand(Jt("create")),Qt=e("login").description("Authenticate and log in to Fusion Framework using interactive browser-based authentication.").addHelpText("after",["","WHAT HAPPENS WHEN YOU RUN THIS COMMAND:"," 1. Opens a browser window for Azure AD authentication"," 2. Prompts you to sign in with your Fusion credentials"," 3. Securely caches your tokens for future CLI commands"," 4. You only need to log in once per session","","Note: Requires interactive environment (won't work in CI/CD pipelines)","","Examples:"," $ ffc auth login"," $ ffc auth login --tenant my-tenant --client my-client-id --scope api://my-app/.default"].join("\n")).action(async e=>{const t=new m("auth:login",{debug:e.debug}),r="string"==typeof e.scope?[e.scope]:e.scope;t.start("Initializing Fusion Framework...");const n=await b({auth:{tenantId:e.tenantId,clientId:e.clientId,interactive:!0,server:{port:49741}}});t.succeed("Initialized Fusion Framework");try{t.start("Logging in...");const e=await n.auth.login({request:{scopes:r}});t.info("username:",ut.green(e.account?.username)),t.info("tenant: ",ut.yellow(e.tenantId)),t.info("audience:",ut.yellow(e.account?.idTokenClaims?.aud));for(const r of e.scopes)t.info("scope: ",ut.dim(r));t.succeed("Successfully logged in",ut.greenBright(e.account?.name))}catch(r){throw t.fail("Failed to log in 🥺",JSON.stringify({tenant:e.tenant,client:e.clientId},void 0,2)),r}});_t(Qt,{includeScope:!0,excludeToken:!0});const Xt=e("logout").description("Log out from Fusion Framework and clear your authentication session.").addHelpText("after",["","WHAT THIS COMMAND DOES:"," - Removes your cached authentication tokens from local storage"," - Clears the current session (does not revoke tokens server-side)"," - You will need to run `ffc auth login` again for future commands","","WHEN TO USE THIS COMMAND:"," - When switching between different user accounts"," - When troubleshooting authentication issues"," - When your cached tokens have expired and you want a fresh login","","Examples:"," $ ffc auth logout"," $ ffc auth logout --tenant my-tenant --client my-client-id"].join("\n")).action(async e=>{const t=new m("auth:logout",{debug:e.debug});t.start("Initializing Fusion Framework...");const r=await b({auth:{tenantId:e.tenantId,clientId:e.clientId}});t.succeed("Initialized Fusion Framework");try{t.start("Logging in..."),await r.auth.logout(),t.succeed("Successfully logged out")}catch(r){throw t.fail("Failed to log out 🥺",JSON.stringify({tenant:e.tenant,client:e.clientId},void 0,2)),r}});_t(Xt,{excludeToken:!0,includeScope:!1});class er extends Error{static Name="NoAccountsError";constructor(e,t){super(e,t),this.name=er.Name}}const tr=e("token").description("Acquire and print an access token for Fusion APIs using your current authentication context.").addHelpText("after",["","USAGE NOTES:"," - This command acquires an access token using your current interactive login session."," - It is intended for local development, manual testing, and debugging authentication issues.","","LIMITATIONS:"," - Requires an interactive user session (not suitable for CI/CD or headless environments)."," - Will only work if you have previously logged in using `ffc auth login`."," - Does NOT prompt for login; if no cached credentials are found, you must log in first."," - For automation or CI/CD, set the FUSION_TOKEN environment variable instead.","","BEST PRACTICES:"," - Use this command to quickly fetch a token for manual API calls or local scripts."," - Use the --silent flag to output only the token (useful for scripting or piping)."," - Specify --scope, --tenant, or --client for advanced scenarios.","","EXAMPLES:"," $ ffc auth token"," $ export MY_TOKEN=$(ffc auth token --silent)"," $ ffc auth token --scope api://my-app/.default"," $ ffc auth token --tenant my-tenant --client my-client-id --silent"].join("\n")).option("-d, --debug","Enable debug mode for verbose logging",!1).option("--silent","Only output the token (no extra logging)").action(async e=>{const t=e.silent?null:new m("auth:token",{debug:e.debug}),r="string"==typeof e.scope?[e.scope]:e.scope;t?.info("Using tenant",e.tenantId),t?.info("Using client",e.clientId),t?.info("Using scope",JSON.stringify(r)),t?.start("Initializing Fusion Framework...");const n=await b({auth:{tenantId:e.tenantId,clientId:e.clientId}});t?.succeed("Initialized Fusion Framework");try{t?.start("Getting access token...");const a=await n.auth.acquireAccessToken({request:{scopes:r}});t?.succeed("Successfully acquired access token"),e.silent?console.log(a):t?.info("Access token:",a)}catch(r){if(e.silent||!(r instanceof er))throw r;t?.fail("No accounts found, please login first")}});_t(tr,{includeScope:!0});const rr=new n("auth").description("Authenticate with Fusion Framework CLI").addHelpText("after",["","Authentication commands for Fusion Framework CLI.","","Use these commands to log in, log out, or acquire tokens for Fusion APIs.","","Examples:"," $ fusion-framework-cli auth login"," $ fusion-framework-cli auth logout"," $ fusion-framework-cli auth token --scope api://my-app/.default"].join("\n"));rr.addCommand(Qt,{isDefault:!0}),rr.addCommand(Xt),rr.addCommand(tr);const nr=e("create").description("Create new Fusion applications and components from templates").addHelpText("after",["",'The "create" command helps you bootstrap new Fusion applications and components',"using predefined templates from the Fusion ecosystem.","","Available templates:"," - app: Create a new Fusion application from the official template","","Examples:"," fusion create app my-new-app"," fusion create app my-new-app --template react",""].join("\n")).addCommand(Jt("app")),ar=_t(e("resolve").description("Resolve and display information about a service registered in Fusion service discovery.").addHelpText("after",["","This command looks up a service by name and prints its discovery details using the current authentication and environment.","","USEFUL FOR:"," - Finding service endpoints for API calls"," - Debugging service connectivity issues"," - Getting service metadata and configuration","","OUTPUT FORMATS:"," - Normal: Pretty-printed JSON with service details",' - Silent: Raw JSON only (useful for scripts: --silent | jq ".uri")',"","Examples:"," $ ffc disco resolve my-service",' $ ffc disco resolve my-service --silent | jq ".uri"'," $ ffc disco resolve my-service --env prod"," $ ffc disco resolve my-service --env test --tenantId my-tenant --clientId my-client-id"].join("\n")).addOption(ht({allowDev:!1})).option("--silent","Silent mode, suppresses output except errors").argument("<service>","Name of the service to resolve in Fusion service discovery").action(async(e,t)=>{const r=t.silent?null:new m("disco:resolve");r?.start("Initializing Fusion Framework...");const n=await b({env:t.environment,auth:{token:t.token,tenantId:t.tenantId,clientId:t.clientId}});r?.succeed("Initialized Fusion Framework"),r?.start(`Resolving service ${e}...`);const a=await n.serviceDiscovery.resolveService(e);r?.succeed(`Resolved service ${e}`),r?.debug(a),t.silent&&console.log(JSON.stringify(a,null,2))})),ir=e("disco").description("Service discovery operations");ir.addCommand(ar);var sr=function(e,t){return sr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},sr(e,t)};function or(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}sr(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var cr=function(){return cr=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var a in t=arguments[r])Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},cr.apply(this,arguments)};function lr(e,t,r,n){return new(r||(r=Promise))(function(a,i){function s(e){try{c(n.next(e))}catch(e){i(e)}}function o(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?a(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,o)}c((n=n.apply(e,t||[])).next())})}function ur(e,t){var r,n,a,i={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=o(0),s.throw=o(1),s.return=o(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(c){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(i=0)),i;)try{if(r=1,n&&(a=2&o[0]?n.return:o[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,o[1])).done)return a;switch(n=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return i.label++,{value:o[1],done:!1};case 5:i.label++,n=o[1],o=[0];continue;case 7:o=i.ops.pop(),i.trys.pop();continue;default:if(!(a=i.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){i=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){i.label=o[1];break}if(6===o[0]&&i.label<a[1]){i.label=a[1],a=o;break}if(a&&i.label<a[2]){i.label=a[2],i.ops.push(o);break}a[2]&&i.ops.pop(),i.trys.pop();continue}o=t.call(e,i)}catch(e){o=[6,e],n=0}finally{r=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,c])}}}function dr(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function pr(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,a,i=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(e){a={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(a)throw a.error}}return s}function mr(e,t,r){if(r||2===arguments.length)for(var n,a=0,i=t.length;a<i;a++)!n&&a in t||(n||(n=Array.prototype.slice.call(t,0,a)),n[a]=t[a]);return e.concat(n||Array.prototype.slice.call(t))}function hr(e){return this instanceof hr?(this.v=e,this):new hr(e)}function fr(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,a=r.apply(e,t||[]),i=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",function(e){return function(t){return Promise.resolve(t).then(e,l)}}),n[Symbol.asyncIterator]=function(){return this},n;function s(e,t){a[e]&&(n[e]=function(t){return new Promise(function(r,n){i.push([e,t,r,n])>1||o(e,t)})},t&&(n[e]=t(n[e])))}function o(e,t){try{(r=a[e](t)).value instanceof hr?Promise.resolve(r.value.v).then(c,l):u(i[0][2],r)}catch(e){u(i[0][3],e)}var r}function c(e){o("next",e)}function l(e){o("throw",e)}function u(e,t){e(t),i.shift(),i.length&&o(i[0][0],i[0][1])}}function gr(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=dr(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise(function(n,a){(function(e,t,r,n){Promise.resolve(n).then(function(t){e({value:t,done:r})},t)})(n,a,(t=e[r](t)).done,t.value)})}}}function yr(e){return"function"==typeof e}function vr(e){var t=e(function(e){Error.call(e),e.stack=(new Error).stack});return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}"function"==typeof SuppressedError&&SuppressedError;var br=vr(function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map(function(e,t){return t+1+") "+e.toString()}).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}});function _r(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var wr=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,r,n,a;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var s=dr(i),o=s.next();!o.done;o=s.next()){o.value.remove(this)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}else i.remove(this);var c=this.initialTeardown;if(yr(c))try{c()}catch(e){a=e instanceof br?e.errors:[e]}var l=this._finalizers;if(l){this._finalizers=null;try{for(var u=dr(l),d=u.next();!d.done;d=u.next()){var p=d.value;try{kr(p)}catch(e){a=null!=a?a:[],e instanceof br?a=mr(mr([],pr(a)),pr(e.errors)):a.push(e)}}}catch(e){r={error:e}}finally{try{d&&!d.done&&(n=u.return)&&n.call(u)}finally{if(r)throw r.error}}}if(a)throw new br(a)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)kr(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(r=this._finalizers)&&void 0!==r?r:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&_r(t,e)},e.prototype.remove=function(t){var r=this._finalizers;r&&_r(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}(),Sr=wr.EMPTY;function Nr(e){return e instanceof wr||e&&"closed"in e&&yr(e.remove)&&yr(e.add)&&yr(e.unsubscribe)}function kr(e){yr(e)?e():e.unsubscribe()}var xr={Promise:void 0},Er=function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setTimeout.apply(void 0,mr([e,t],pr(r)))};function Pr(e){Er(function(){throw e})}function Cr(){}function Ar(e){e()}var Ir=function(e){function t(t){var r=e.call(this)||this;return r.isStopped=!1,t?(r.destination=t,Nr(t)&&t.add(r)):r.destination=zr,r}return or(t,e),t.create=function(e,t,r){return new Tr(e,t,r)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(wr),Or=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){$r(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){$r(e)}else $r(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){$r(e)}},e}(),Tr=function(e){function t(t,r,n){var a,i=e.call(this)||this;return a=yr(t)||!t?{next:null!=t?t:void 0,error:null!=r?r:void 0,complete:null!=n?n:void 0}:t,i.destination=new Or(a),i}return or(t,e),t}(Ir);function $r(e){Pr(e)}var zr={closed:!0,next:Cr,error:function(e){throw e},complete:Cr},Rr="function"==typeof Symbol&&Symbol.observable||"@@observable";function Lr(e){return e}var Mr=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var r=new e;return r.source=this,r.operator=t,r},e.prototype.subscribe=function(e,t,r){var n,a=this,i=(n=e)&&n instanceof Ir||function(e){return e&&yr(e.next)&&yr(e.error)&&yr(e.complete)}(n)&&Nr(n)?e:new Tr(e,t,r);return Ar(function(){var e=a,t=e.operator,r=e.source;i.add(t?t.call(i,r):r?a._subscribe(i):a._trySubscribe(i))}),i},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var r=this;return new(t=Dr(t))(function(t,n){var a=new Tr({next:function(t){try{e(t)}catch(e){n(e),a.unsubscribe()}},error:n,complete:t});r.subscribe(a)})},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[Rr]=function(){return this},e.prototype.pipe=function(){for(var e,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return(0===(e=t).length?Lr:1===e.length?e[0]:function(t){return e.reduce(function(e,t){return t(e)},t)})(this)},e.prototype.toPromise=function(e){var t=this;return new(e=Dr(e))(function(e,r){var n;t.subscribe(function(e){return n=e},function(e){return r(e)},function(){return e(n)})})},e.create=function(t){return new e(t)},e}();function Dr(e){var t;return null!==(t=null!=e?e:xr.Promise)&&void 0!==t?t:Promise}function jr(e){return function(t){if(function(e){return yr(null==e?void 0:e.lift)}(t))return t.lift(function(t){try{return e(t,this)}catch(e){this.error(e)}});throw new TypeError("Unable to lift unknown Observable type")}}function Fr(e,t,r,n,a){return new Ur(e,t,r,n,a)}var Ur=function(e){function t(t,r,n,a,i,s){var o=e.call(this,t)||this;return o.onFinalize=i,o.shouldUnsubscribe=s,o._next=r?function(e){try{r(e)}catch(e){t.error(e)}}:e.prototype._next,o._error=a?function(e){try{a(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,o._complete=n?function(){try{n()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,o}return or(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;e.prototype.unsubscribe.call(this),!r&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(Ir),qr=vr(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Br=function(e){function t(){var t=e.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return or(t,e),t.prototype.lift=function(e){var t=new Vr(this,this);return t.operator=e,t},t.prototype._throwIfClosed=function(){if(this.closed)throw new qr},t.prototype.next=function(e){var t=this;Ar(function(){var r,n;if(t._throwIfClosed(),!t.isStopped){t.currentObservers||(t.currentObservers=Array.from(t.observers));try{for(var a=dr(t.currentObservers),i=a.next();!i.done;i=a.next()){i.value.next(e)}}catch(e){r={error:e}}finally{try{i&&!i.done&&(n=a.return)&&n.call(a)}finally{if(r)throw r.error}}}})},t.prototype.error=function(e){var t=this;Ar(function(){if(t._throwIfClosed(),!t.isStopped){t.hasError=t.isStopped=!0,t.thrownError=e;for(var r=t.observers;r.length;)r.shift().error(e)}})},t.prototype.complete=function(){var e=this;Ar(function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var t=e.observers;t.length;)t.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var e;return(null===(e=this.observers)||void 0===e?void 0:e.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,r=this,n=r.hasError,a=r.isStopped,i=r.observers;return n||a?Sr:(this.currentObservers=null,i.push(e),new wr(function(){t.currentObservers=null,_r(i,e)}))},t.prototype._checkFinalizedStatuses=function(e){var t=this,r=t.hasError,n=t.thrownError,a=t.isStopped;r?e.error(n):a&&e.complete()},t.prototype.asObservable=function(){var e=new Mr;return e.source=this,e},t.create=function(e,t){return new Vr(e,t)},t}(Mr),Vr=function(e){function t(t,r){var n=e.call(this)||this;return n.destination=t,n.source=r,n}return or(t,e),t.prototype.next=function(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===r||r.call(t,e)},t.prototype.error=function(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===r||r.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,r;return null!==(r=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==r?r:Sr},t}(Br),Gr=function(e){function t(t){var r=e.call(this)||this;return r._value=t,r}return or(t,e),Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(t){var r=e.prototype._subscribe.call(this,t);return!r.closed&&t.next(this._value),r},t.prototype.getValue=function(){var e=this,t=e.hasError,r=e.thrownError,n=e._value;if(t)throw r;return this._throwIfClosed(),n},t.prototype.next=function(t){e.prototype.next.call(this,this._value=t)},t}(Br),Hr={now:function(){return(Hr.delegate||Date).now()},delegate:void 0},Kr=function(e){function t(t,r,n){void 0===t&&(t=1/0),void 0===r&&(r=1/0),void 0===n&&(n=Hr);var a=e.call(this)||this;return a._bufferSize=t,a._windowTime=r,a._timestampProvider=n,a._buffer=[],a._infiniteTimeWindow=!0,a._infiniteTimeWindow=r===1/0,a._bufferSize=Math.max(1,t),a._windowTime=Math.max(1,r),a}return or(t,e),t.prototype.next=function(t){var r=this,n=r.isStopped,a=r._buffer,i=r._infiniteTimeWindow,s=r._timestampProvider,o=r._windowTime;n||(a.push(t),!i&&a.push(s.now()+o)),this._trimBuffer(),e.prototype.next.call(this,t)},t.prototype._subscribe=function(e){this._throwIfClosed(),this._trimBuffer();for(var t=this._innerSubscribe(e),r=this._infiniteTimeWindow,n=this._buffer.slice(),a=0;a<n.length&&!e.closed;a+=r?1:2)e.next(n[a]);return this._checkFinalizedStatuses(e),t},t.prototype._trimBuffer=function(){var e=this,t=e._bufferSize,r=e._timestampProvider,n=e._buffer,a=e._infiniteTimeWindow,i=(a?1:2)*t;if(t<1/0&&i<n.length&&n.splice(0,n.length-i),!a){for(var s=r.now(),o=0,c=1;c<n.length&&n[c]<=s;c+=2)o=c;o&&n.splice(0,o+1)}},t}(Br),Wr=function(e){function t(t,r){return e.call(this)||this}return or(t,e),t.prototype.schedule=function(e,t){return this},t}(wr),Zr=function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setInterval.apply(void 0,mr([e,t],pr(r)))},Jr=function(e){return clearInterval(e)},Yr=function(e){function t(t,r){var n=e.call(this,t,r)||this;return n.scheduler=t,n.work=r,n.pending=!1,n}return or(t,e),t.prototype.schedule=function(e,t){var r;if(void 0===t&&(t=0),this.closed)return this;this.state=e;var n=this.id,a=this.scheduler;return null!=n&&(this.id=this.recycleAsyncId(a,n,t)),this.pending=!0,this.delay=t,this.id=null!==(r=this.id)&&void 0!==r?r:this.requestAsyncId(a,this.id,t),this},t.prototype.requestAsyncId=function(e,t,r){return void 0===r&&(r=0),Zr(e.flush.bind(e,this),r)},t.prototype.recycleAsyncId=function(e,t,r){if(void 0===r&&(r=0),null!=r&&this.delay===r&&!1===this.pending)return t;null!=t&&Jr(t)},t.prototype.execute=function(e,t){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var r=this._execute(e,t);if(r)return r;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,t){var r,n=!1;try{this.work(e)}catch(e){n=!0,r=e||new Error("Scheduled action threw falsy error")}if(n)return this.unsubscribe(),r},t.prototype.unsubscribe=function(){if(!this.closed){var t=this.id,r=this.scheduler,n=r.actions;this.work=this.state=this.scheduler=null,this.pending=!1,_r(n,this),null!=t&&(this.id=this.recycleAsyncId(r,t,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(Wr),Qr=function(){function e(t,r){void 0===r&&(r=e.now),this.schedulerActionCtor=t,this.now=r}return e.prototype.schedule=function(e,t,r){return void 0===t&&(t=0),new this.schedulerActionCtor(this,e).schedule(r,t)},e.now=Hr.now,e}(),Xr=function(e){function t(t,r){void 0===r&&(r=Qr.now);var n=e.call(this,t,r)||this;return n.actions=[],n._active=!1,n}return or(t,e),t.prototype.flush=function(e){var t=this.actions;if(this._active)t.push(e);else{var r;this._active=!0;do{if(r=e.execute(e.state,e.delay))break}while(e=t.shift());if(this._active=!1,r){for(;e=t.shift();)e.unsubscribe();throw r}}},t}(Qr),en=new Xr(Yr),tn=en,rn=new Mr(function(e){return e.complete()});function nn(e){return e&&yr(e.schedule)}function an(e){return e[e.length-1]}function sn(e){return nn(an(e))?e.pop():void 0}var on=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function cn(e){return yr(null==e?void 0:e.then)}function ln(e){return yr(e[Rr])}function un(e){return Symbol.asyncIterator&&yr(null==e?void 0:e[Symbol.asyncIterator])}function dn(e){return new TypeError("You provided "+(null!==e&&"object"==typeof e?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}var pn="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function mn(e){return yr(null==e?void 0:e[pn])}function hn(e){return fr(this,arguments,function(){var t,r,n;return ur(this,function(a){switch(a.label){case 0:t=e.getReader(),a.label=1;case 1:a.trys.push([1,,9,10]),a.label=2;case 2:return[4,hr(t.read())];case 3:return r=a.sent(),n=r.value,r.done?[4,hr(void 0)]:[3,5];case 4:return[2,a.sent()];case 5:return[4,hr(n)];case 6:return[4,a.sent()];case 7:return a.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function fn(e){return yr(null==e?void 0:e.getReader)}function gn(e){if(e instanceof Mr)return e;if(null!=e){if(ln(e))return a=e,new Mr(function(e){var t=a[Rr]();if(yr(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")});if(on(e))return n=e,new Mr(function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()});if(cn(e))return r=e,new Mr(function(e){r.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,Pr)});if(un(e))return yn(e);if(mn(e))return t=e,new Mr(function(e){var r,n;try{for(var a=dr(t),i=a.next();!i.done;i=a.next()){var s=i.value;if(e.next(s),e.closed)return}}catch(e){r={error:e}}finally{try{i&&!i.done&&(n=a.return)&&n.call(a)}finally{if(r)throw r.error}}e.complete()});if(fn(e))return yn(hn(e))}var t,r,n,a;throw dn(e)}function yn(e){return new Mr(function(t){(function(e,t){var r,n,a,i;return lr(this,void 0,void 0,function(){var s,o;return ur(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),r=gr(e),c.label=1;case 1:return[4,r.next()];case 2:if((n=c.sent()).done)return[3,4];if(s=n.value,t.next(s),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return o=c.sent(),a={error:o},[3,11];case 6:return c.trys.push([6,,9,10]),n&&!n.done&&(i=r.return)?[4,i.call(r)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(a)throw a.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})})(e,t).catch(function(e){return t.error(e)})})}function vn(e,t,r,n,a){void 0===n&&(n=0),void 0===a&&(a=!1);var i=t.schedule(function(){r(),a?e.add(this.schedule(null,n)):this.unsubscribe()},n);if(e.add(i),!a)return i}function bn(e,t){return void 0===t&&(t=0),jr(function(r,n){r.subscribe(Fr(n,function(r){return vn(n,e,function(){return n.next(r)},t)},function(){return vn(n,e,function(){return n.complete()},t)},function(r){return vn(n,e,function(){return n.error(r)},t)}))})}function _n(e,t){return void 0===t&&(t=0),jr(function(r,n){n.add(e.schedule(function(){return r.subscribe(n)},t))})}function wn(e,t){if(!e)throw new Error("Iterable cannot be null");return new Mr(function(r){vn(r,t,function(){var n=e[Symbol.asyncIterator]();vn(r,t,function(){n.next().then(function(e){e.done?r.complete():r.next(e.value)})},0,!0)})})}function Sn(e,t){if(null!=e){if(ln(e))return function(e,t){return gn(e).pipe(_n(t),bn(t))}(e,t);if(on(e))return function(e,t){return new Mr(function(r){var n=0;return t.schedule(function(){n===e.length?r.complete():(r.next(e[n++]),r.closed||this.schedule())})})}(e,t);if(cn(e))return function(e,t){return gn(e).pipe(_n(t),bn(t))}(e,t);if(un(e))return wn(e,t);if(mn(e))return function(e,t){return new Mr(function(r){var n;return vn(r,t,function(){n=e[pn](),vn(r,t,function(){var e,t,a;try{t=(e=n.next()).value,a=e.done}catch(e){return void r.error(e)}a?r.complete():r.next(t)},0,!0)}),function(){return yr(null==n?void 0:n.return)&&n.return()}})}(e,t);if(fn(e))return function(e,t){return wn(hn(e),t)}(e,t)}throw dn(e)}function Nn(e,t){return t?Sn(e,t):gn(e)}function kn(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Nn(e,sn(e))}var xn=vr(function(e){return function(){e(this),this.name="EmptyError",this.message="no elements in sequence"}});function En(e,t){var r="object"==typeof t;return new Promise(function(n,a){var i,s=!1;e.subscribe({next:function(e){i=e,s=!0},error:a,complete:function(){s?n(i):r?n(t.defaultValue):a(new xn)}})})}function Pn(e,t){var r="object"==typeof t;return new Promise(function(n,a){var i=new Tr({next:function(e){n(e),i.unsubscribe()},error:a,complete:function(){r?n(t.defaultValue):a(new xn)}});e.subscribe(i)})}function Cn(e){return e instanceof Date&&!isNaN(e)}var An=vr(function(e){return function(t){void 0===t&&(t=null),e(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function In(e){throw new An(e)}function On(e,t){return jr(function(r,n){var a=0;r.subscribe(Fr(n,function(r){n.next(e.call(t,r,a++))}))})}var Tn=Array.isArray;function $n(e){return On(function(t){return function(e,t){return Tn(t)?e.apply(void 0,mr([],pr(t))):e(t)}(e,t)})}function zn(e,t,r,n,a,i,s,o){var c=[],l=0,u=0,d=!1,p=function(){!d||c.length||l||t.complete()},m=function(e){return l<n?h(e):c.push(e)},h=function(e){i&&t.next(e),l++;var o=!1;gn(r(e,u++)).subscribe(Fr(t,function(e){null==a||a(e),i?m(e):t.next(e)},function(){o=!0},void 0,function(){if(o)try{l--;for(var e=function(){var e=c.shift();s||h(e)};c.length&&l<n;)e();p()}catch(e){t.error(e)}}))};return e.subscribe(Fr(t,m,function(){d=!0,p()})),function(){null==o||o()}}function Rn(e,t,r){return void 0===r&&(r=1/0),yr(t)?Rn(function(r,n){return On(function(e,a){return t(r,e,n,a)})(gn(e(r,n)))},r):("number"==typeof t&&(r=t),jr(function(t,n){return zn(t,n,e,r)}))}var Ln=["addListener","removeListener"],Mn=["addEventListener","removeEventListener"],Dn=["on","off"];function jn(e,t,r,n){if(yr(r)&&(n=r,r=void 0),n)return jn(e,t,r).pipe($n(n));var a=pr(function(e){return yr(e.addEventListener)&&yr(e.removeEventListener)}(e)?Mn.map(function(n){return function(a){return e[n](t,a,r)}}):function(e){return yr(e.addListener)&&yr(e.removeListener)}(e)?Ln.map(Fn(e,t)):function(e){return yr(e.on)&&yr(e.off)}(e)?Dn.map(Fn(e,t)):[],2),i=a[0],s=a[1];if(!i&&on(e))return Rn(function(e){return jn(e,t,r)})(gn(e));if(!i)throw new TypeError("Invalid event target");return new Mr(function(e){var t=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return e.next(1<t.length?t:t[0])};return i(t),function(){return s(t)}})}function Fn(e,t){return function(r){return function(n){return e[r](t,n)}}}function Un(e,t,r){void 0===e&&(e=0),void 0===r&&(r=tn);var n=-1;return null!=t&&(nn(t)?r=t:n=t),new Mr(function(t){var a=Cn(e)?+e-r.now():e;a<0&&(a=0);var i=0;return r.schedule(function(){t.closed||(t.next(i++),0<=n?this.schedule(void 0,n):t.complete())},a)})}function qn(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=sn(e),n=function(e,t){return"number"==typeof an(e)?e.pop():t}(e,1/0),a=e;return a.length?1===a.length?gn(a[0]):function(e){return void 0===e&&(e=1/0),Rn(Lr,e)}(n)(Nn(a,r)):rn}function Bn(e,t){return jr(function(r,n){var a=0;r.subscribe(Fr(n,function(r){return e.call(t,r,a++)&&n.next(r)}))})}function Vn(e){return jr(function(t,r){var n,a=null,i=!1;a=t.subscribe(Fr(r,void 0,void 0,function(s){n=gn(e(s,Vn(e)(t))),a?(a.unsubscribe(),a=null,n.subscribe(r)):i=!0})),i&&(a.unsubscribe(),a=null,n.subscribe(r))})}function Gn(e,t,r,n,a){return function(i,s){var o=r,c=t,l=0;i.subscribe(Fr(s,function(t){var r=l++;c=o?e(c,t,r):(o=!0,t),n&&s.next(c)},a&&function(){o&&s.next(c),s.complete()}))}}function Hn(e,t){return jr(Gn(e,t,arguments.length>=2,!1,!0))}var Kn=function(e,t){return e.push(t),e};function Wn(){return jr(function(e,t){Hn(Kn,[])(e).subscribe(t)})}function Zn(e,t){return yr(t)?Rn(e,t,1):Rn(e,1)}function Jn(e){return jr(function(t,r){var n=!1;t.subscribe(Fr(r,function(e){n=!0,r.next(e)},function(){n||r.next(e),r.complete()}))})}function Yn(e,t){return void 0===t&&(t=Lr),e=null!=e?e:Qn,jr(function(r,n){var a,i=!0;r.subscribe(Fr(n,function(r){var s=t(r);!i&&e(a,s)||(i=!1,a=s,n.next(r))}))})}function Qn(e,t){return e===t}function Xn(e){return void 0===e&&(e=ea),jr(function(t,r){var n=!1;t.subscribe(Fr(r,function(e){n=!0,r.next(e)},function(){return n?r.complete():r.error(e())}))})}function ea(){return new xn}function ta(e){return jr(function(t,r){try{t.subscribe(r)}finally{r.add(e)}})}function ra(e,t){var r=arguments.length>=2;return function(e){return e.pipe(Lr,(n=1)<=0?function(){return rn}:jr(function(e,t){var r=[];e.subscribe(Fr(t,function(e){r.push(e),n<r.length&&r.shift()},function(){var e,n;try{for(var a=dr(r),i=a.next();!i.done;i=a.next()){var s=i.value;t.next(s)}}catch(t){e={error:t}}finally{try{i&&!i.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}t.complete()},void 0,function(){r=null}))}),r?Jn(t):Xn(function(){return new xn}));var n}}function na(e,t){return jr(Gn(e,t,arguments.length>=2,!0))}function aa(e){void 0===e&&(e={});var t=e.connector,r=void 0===t?function(){return new Br}:t,n=e.resetOnError,a=void 0===n||n,i=e.resetOnComplete,s=void 0===i||i,o=e.resetOnRefCountZero,c=void 0===o||o;return function(e){var t,n,i,o=0,l=!1,u=!1,d=function(){null==n||n.unsubscribe(),n=void 0},p=function(){d(),t=i=void 0,l=u=!1},m=function(){var e=t;p(),null==e||e.unsubscribe()};return jr(function(e,h){o++,u||l||d();var f=i=null!=i?i:r();h.add(function(){0!==--o||u||l||(n=ia(m,c))}),f.subscribe(h),!t&&o>0&&(t=new Tr({next:function(e){return f.next(e)},error:function(e){u=!0,d(),n=ia(p,a,e),f.error(e)},complete:function(){l=!0,d(),n=ia(p,s),f.complete()}}),gn(e).subscribe(t))})(e)}}function ia(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];if(!0!==t){if(!1!==t){var a=new Tr({next:function(){a.unsubscribe(),e()}});return gn(t.apply(void 0,mr([],pr(r)))).subscribe(a)}}else e()}function sa(e,t){return jr(function(r,n){var a=null,i=0,s=!1,o=function(){return s&&!a&&n.complete()};r.subscribe(Fr(n,function(r){null==a||a.unsubscribe();var s=0,c=i++;gn(e(r,c)).subscribe(a=Fr(n,function(e){return n.next(t?t(r,e,c,s++):e)},function(){a=null,o()}))},function(){s=!0,o()}))})}function oa(e){return jr(function(t,r){gn(e).subscribe(Fr(r,function(){return r.complete()},Cr)),!r.closed&&t.subscribe(r)})}function ca(e,t,r){var n=yr(e)||t||r?{next:e,error:t,complete:r}:e;return n?jr(function(e,t){var r;null===(r=n.subscribe)||void 0===r||r.call(n);var a=!0;e.subscribe(Fr(t,function(e){var r;null===(r=n.next)||void 0===r||r.call(n,e),t.next(e)},function(){var e;a=!1,null===(e=n.complete)||void 0===e||e.call(n),t.complete()},function(e){var r;a=!1,null===(r=n.error)||void 0===r||r.call(n,e),t.error(e)},function(){var e,t;a&&(null===(e=n.unsubscribe)||void 0===e||e.call(n)),null===(t=n.finalize)||void 0===t||t.call(n)}))}):Lr}function la(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r,n=yr(an(r=e))?r.pop():void 0;return jr(function(t,r){for(var a=e.length,i=new Array(a),s=e.map(function(){return!1}),o=!1,c=function(t){gn(e[t]).subscribe(Fr(r,function(e){i[t]=e,o||s[t]||(s[t]=!0,(o=s.every(Lr))&&(s=null))},Cr))},l=0;l<a;l++)c(l);t.subscribe(Fr(r,function(e){if(o){var t=mr([e],pr(i));r.next(n?n.apply(void 0,mr([],pr(t))):t)}}))})}const ua=t("--openai-api-key <key>","API key for Azure OpenAI services").env("AZURE_OPENAI_API_KEY"),da=t("--openai-api-version <version>","Azure OpenAI API version").env("AZURE_OPENAI_API_VERSION").default("2024-02-15-preview"),pa=t("--openai-instance <name>","Azure OpenAI instance name").env("AZURE_OPENAI_INSTANCE_NAME"),ma=t("--openai-chat-deployment <name>","Azure OpenAI chat deployment name").env("AZURE_OPENAI_CHAT_DEPLOYMENT_NAME"),ha=t("--openai-embedding-deployment <name>","Azure OpenAI embedding deployment name").env("AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME"),fa=t("--azure-search-endpoint <url>","Azure Search endpoint URL").env("AZURE_SEARCH_ENDPOINT"),ga=t("--azure-search-api-key <key>","Azure Search API key").env("AZURE_SEARCH_API_KEY"),ya=t("--azure-search-index-name <name>","Azure Search index name").env("AZURE_SEARCH_INDEX_NAME"),va=(e,t)=>(e.addOption(ua),e.addOption(da),e.addOption(pa),!0===t?.includeChat&&e.addOption(ma),!0===t?.includeEmbedding&&e.addOption(ha),!0===t?.includeSearch&&(e.addOption(fa),e.addOption(ga),e.addOption(ya)),e.hook("preAction",e=>{const n=e.opts();if(!n.openaiApiKey||"string"!=typeof n.openaiApiKey||""===n.openaiApiKey.trim())throw new r("API key is required and must be a non-empty string.");if(!n.openaiApiVersion||"string"!=typeof n.openaiApiVersion)throw new r("API version must be a non-empty string.");if(!n.openaiInstance||"string"!=typeof n.openaiInstance||""===n.openaiInstance.trim())throw new r("API instance name is required and must be a non-empty string.");if(!0===t?.includeChat&&(!n.openaiChatDeployment||"string"!=typeof n.openaiChatDeployment||""===n.openaiChatDeployment.trim()))throw new r("Chat deployment name is required and must be a non-empty string.");if(!0===t?.includeEmbedding&&(!n.openaiEmbeddingDeployment||"string"!=typeof n.openaiEmbeddingDeployment||""===n.openaiEmbeddingDeployment.trim()))throw new r("Embedding deployment name is required and must be a non-empty string.");if(!0===t?.includeSearch){if(!n.azureSearchEndpoint||"string"!=typeof n.azureSearchEndpoint||""===n.azureSearchEndpoint.trim())throw new r("Azure Search endpoint is required and must be a non-empty string.");if(!n.azureSearchApiKey||"string"!=typeof n.azureSearchApiKey||""===n.azureSearchApiKey.trim())throw new r("Azure Search API key is required and must be a non-empty string.");if(!n.azureSearchIndexName||"string"!=typeof n.azureSearchIndexName||""===n.azureSearchIndexName.trim())throw new r("Azure Search index name is required and must be a non-empty string.")}}),e);function ba(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var _a,wa,Sa,Na,ka,xa,Ea,Pa,Ca,Aa,Ia,Oa,Ta,$a,za,Ra,La,Ma,Da,ja,Fa,Ua,qa,Ba,Va,Ga,Ha,Ka,Wa,Za,Ja,Ya,Qa,Xa,ei,ti,ri,ni,ai,ii,si,oi,ci,li,ui,di,pi,mi,hi,fi,gi,yi,vi,bi,_i,wi,Si,Ni,ki,xi,Ei,Pi,Ci,Ai,Ii,Oi,Ti,$i,zi,Ri,Li,Mi,Di,ji,Fi,Ui,qi,Bi,Vi,Gi,Hi,Ki,Wi,Zi,Ji,Yi,Qi,Xi,es,ts={exports:{}};function rs(){if(wa)return _a;wa=1;const e=Number.MAX_SAFE_INTEGER||9007199254740991;return _a={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:e,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}}function ns(){if(Na)return Sa;Na=1;const e="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};return Sa=e}function as(){return ka||(ka=1,function(e,t){const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:a}=rs(),i=ns(),s=(t=e.exports={}).re=[],o=t.safeRe=[],c=t.src=[],l=t.safeSrc=[],u=t.t={};let d=0;const p="[a-zA-Z0-9-]",m=[["\\s",1],["\\d",a],[p,n]],h=(e,t,r)=>{const n=(e=>{for(const[t,r]of m)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e})(t),a=d++;i(e,a,t),u[e]=a,c[a]=t,l[a]=n,s[a]=new RegExp(t,r?"g":void 0),o[a]=new RegExp(n,r?"g":void 0)};h("NUMERICIDENTIFIER","0|[1-9]\\d*"),h("NUMERICIDENTIFIERLOOSE","\\d+"),h("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),h("MAINVERSION",`(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})`),h("MAINVERSIONLOOSE",`(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASEIDENTIFIER",`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIER]})`),h("PRERELEASEIDENTIFIERLOOSE",`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASE",`(?:-(${c[u.PRERELEASEIDENTIFIER]}(?:\\.${c[u.PRERELEASEIDENTIFIER]})*))`),h("PRERELEASELOOSE",`(?:-?(${c[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[u.PRERELEASEIDENTIFIERLOOSE]})*))`),h("BUILDIDENTIFIER",`${p}+`),h("BUILD",`(?:\\+(${c[u.BUILDIDENTIFIER]}(?:\\.${c[u.BUILDIDENTIFIER]})*))`),h("FULLPLAIN",`v?${c[u.MAINVERSION]}${c[u.PRERELEASE]}?${c[u.BUILD]}?`),h("FULL",`^${c[u.FULLPLAIN]}$`),h("LOOSEPLAIN",`[v=\\s]*${c[u.MAINVERSIONLOOSE]}${c[u.PRERELEASELOOSE]}?${c[u.BUILD]}?`),h("LOOSE",`^${c[u.LOOSEPLAIN]}$`),h("GTLT","((?:<|>)?=?)"),h("XRANGEIDENTIFIERLOOSE",`${c[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h("XRANGEIDENTIFIER",`${c[u.NUMERICIDENTIFIER]}|x|X|\\*`),h("XRANGEPLAIN",`[v=\\s]*(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:${c[u.PRERELEASE]})?${c[u.BUILD]}?)?)?`),h("XRANGEPLAINLOOSE",`[v=\\s]*(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:${c[u.PRERELEASELOOSE]})?${c[u.BUILD]}?)?)?`),h("XRANGE",`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAIN]}$`),h("XRANGELOOSE",`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAINLOOSE]}$`),h("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),h("COERCE",`${c[u.COERCEPLAIN]}(?:$|[^\\d])`),h("COERCEFULL",c[u.COERCEPLAIN]+`(?:${c[u.PRERELEASE]})?`+`(?:${c[u.BUILD]})?(?:$|[^\\d])`),h("COERCERTL",c[u.COERCE],!0),h("COERCERTLFULL",c[u.COERCEFULL],!0),h("LONETILDE","(?:~>?)"),h("TILDETRIM",`(\\s*)${c[u.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",h("TILDE",`^${c[u.LONETILDE]}${c[u.XRANGEPLAIN]}$`),h("TILDELOOSE",`^${c[u.LONETILDE]}${c[u.XRANGEPLAINLOOSE]}$`),h("LONECARET","(?:\\^)"),h("CARETTRIM",`(\\s*)${c[u.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",h("CARET",`^${c[u.LONECARET]}${c[u.XRANGEPLAIN]}$`),h("CARETLOOSE",`^${c[u.LONECARET]}${c[u.XRANGEPLAINLOOSE]}$`),h("COMPARATORLOOSE",`^${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]})$|^$`),h("COMPARATOR",`^${c[u.GTLT]}\\s*(${c[u.FULLPLAIN]})$|^$`),h("COMPARATORTRIM",`(\\s*)${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]}|${c[u.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",h("HYPHENRANGE",`^\\s*(${c[u.XRANGEPLAIN]})\\s+-\\s+(${c[u.XRANGEPLAIN]})\\s*$`),h("HYPHENRANGELOOSE",`^\\s*(${c[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[u.XRANGEPLAINLOOSE]})\\s*$`),h("STAR","(<|>)?=?\\s*\\*"),h("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),h("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}(ts,ts.exports)),ts.exports}function is(){if(Ea)return xa;Ea=1;const e=Object.freeze({loose:!0}),t=Object.freeze({});return xa=r=>r?"object"!=typeof r?e:r:t}function ss(){if(Ca)return Pa;Ca=1;const e=/^[0-9]+$/,t=(t,r)=>{if("number"==typeof t&&"number"==typeof r)return t===r?0:t<r?-1:1;const n=e.test(t),a=e.test(r);return n&&a&&(t=+t,r=+r),t===r?0:n&&!a?-1:a&&!n?1:t<r?-1:1};return Pa={compareIdentifiers:t,rcompareIdentifiers:(e,r)=>t(r,e)}}function os(){if(Ia)return Aa;Ia=1;const e=ns(),{MAX_LENGTH:t,MAX_SAFE_INTEGER:r}=rs(),{safeRe:n,t:a}=as(),i=is(),{compareIdentifiers:s}=ss();class o{constructor(s,c){if(c=i(c),s instanceof o){if(s.loose===!!c.loose&&s.includePrerelease===!!c.includePrerelease)return s;s=s.version}else if("string"!=typeof s)throw new TypeError(`Invalid version. Must be a string. Got type "${typeof s}".`);if(s.length>t)throw new TypeError(`version is longer than ${t} characters`);e("SemVer",s,c),this.options=c,this.loose=!!c.loose,this.includePrerelease=!!c.includePrerelease;const l=s.trim().match(c.loose?n[a.LOOSE]:n[a.FULL]);if(!l)throw new TypeError(`Invalid Version: ${s}`);if(this.raw=s,this.major=+l[1],this.minor=+l[2],this.patch=+l[3],this.major>r||this.major<0)throw new TypeError("Invalid major version");if(this.minor>r||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>r||this.patch<0)throw new TypeError("Invalid patch version");l[4]?this.prerelease=l[4].split(".").map(e=>{if(/^[0-9]+$/.test(e)){const t=+e;if(t>=0&&t<r)return t}return e}):this.prerelease=[],this.build=l[5]?l[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(e("SemVer.compare",this.version,this.options,t),!(t instanceof o)){if("string"==typeof t&&t===this.version)return 0;t=new o(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(e){return e instanceof o||(e=new o(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(t){if(t instanceof o||(t=new o(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{const n=this.prerelease[r],a=t.prerelease[r];if(e("prerelease compare",r,n,a),void 0===n&&void 0===a)return 0;if(void 0===a)return 1;if(void 0===n)return-1;if(n!==a)return s(n,a)}while(++r)}compareBuild(t){t instanceof o||(t=new o(t,this.options));let r=0;do{const n=this.build[r],a=t.build[r];if(e("build compare",r,n,a),void 0===n&&void 0===a)return 0;if(void 0===a)return 1;if(void 0===n)return-1;if(n!==a)return s(n,a)}while(++r)}inc(e,t,r){if(e.startsWith("pre")){if(!t&&!1===r)throw new Error("invalid increment argument: identifier is empty");if(t){const e=`-${t}`.match(this.options.loose?n[a.PRERELEASELOOSE]:n[a.PRERELEASE]);if(!e||e[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,r),this.inc("pre",t,r);break;case"prerelease":0===this.prerelease.length&&this.inc("patch",t,r),this.inc("pre",t,r);break;case"release":if(0===this.prerelease.length)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":0===this.minor&&0===this.patch&&0!==this.prerelease.length||this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":0===this.patch&&0!==this.prerelease.length||this.minor++,this.patch=0,this.prerelease=[];break;case"patch":0===this.prerelease.length&&this.patch++,this.prerelease=[];break;case"pre":{const e=Number(r)?1:0;if(0===this.prerelease.length)this.prerelease=[e];else{let n=this.prerelease.length;for(;--n>=0;)"number"==typeof this.prerelease[n]&&(this.prerelease[n]++,n=-2);if(-1===n){if(t===this.prerelease.join(".")&&!1===r)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(e)}}if(t){let n=[t,e];!1===r&&(n=[t]),0===s(this.prerelease[0],t)?isNaN(this.prerelease[1])&&(this.prerelease=n):this.prerelease=n}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return Aa=o}function cs(){if(Ta)return Oa;Ta=1;const e=os();return Oa=(t,r,n=!1)=>{if(t instanceof e)return t;try{return new e(t,r)}catch(e){if(!n)return null;throw e}},Oa}function ls(){if(za)return $a;za=1;const e=cs();return $a=(t,r)=>{const n=e(t,r);return n?n.version:null},$a}function us(){if(La)return Ra;La=1;const e=cs();return Ra=(t,r)=>{const n=e(t.trim().replace(/^[=v]+/,""),r);return n?n.version:null},Ra}function ds(){if(Ja)return Za;Ja=1;const e=os();return Za=(t,r,n)=>new e(t,n).compare(new e(r,n))}function ps(){if(ri)return ti;ri=1;const e=os();return ti=(t,r,n)=>{const a=new e(t,n),i=new e(r,n);return a.compare(i)||a.compareBuild(i)}}function ms(){if(ci)return oi;ci=1;const e=ds();return oi=(t,r,n)=>e(t,r,n)>0}function hs(){if(ui)return li;ui=1;const e=ds();return li=(t,r,n)=>e(t,r,n)<0}function fs(){if(pi)return di;pi=1;const e=ds();return di=(t,r,n)=>0===e(t,r,n)}function gs(){if(hi)return mi;hi=1;const e=ds();return mi=(t,r,n)=>0!==e(t,r,n)}function ys(){if(gi)return fi;gi=1;const e=ds();return fi=(t,r,n)=>e(t,r,n)>=0}function vs(){if(vi)return yi;vi=1;const e=ds();return yi=(t,r,n)=>e(t,r,n)<=0}function bs(){if(_i)return bi;_i=1;const e=fs(),t=gs(),r=ms(),n=ys(),a=hs(),i=vs();return bi=(s,o,c,l)=>{switch(o){case"===":return"object"==typeof s&&(s=s.version),"object"==typeof c&&(c=c.version),s===c;case"!==":return"object"==typeof s&&(s=s.version),"object"==typeof c&&(c=c.version),s!==c;case"":case"=":case"==":return e(s,c,l);case"!=":return t(s,c,l);case">":return r(s,c,l);case">=":return n(s,c,l);case"<":return a(s,c,l);case"<=":return i(s,c,l);default:throw new TypeError(`Invalid operator: ${o}`)}}}function _s(){if(Ei)return xi;Ei=1;const e=/\s+/g;class t{constructor(r,n){if(n=a(n),r instanceof t)return r.loose===!!n.loose&&r.includePrerelease===!!n.includePrerelease?r:new t(r.raw,n);if(r instanceof i)return this.raw=r.value,this.set=[[r]],this.formatted=void 0,this;if(this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease,this.raw=r.trim().replace(e," "),this.set=this.raw.split("||").map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const e=this.set[0];if(this.set=this.set.filter(e=>!f(e[0])),0===this.set.length)this.set=[e];else if(this.set.length>1)for(const e of this.set)if(1===e.length&&g(e[0])){this.set=[e];break}}this.formatted=void 0}get range(){if(void 0===this.formatted){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");const t=this.set[e];for(let e=0;e<t.length;e++)e>0&&(this.formatted+=" "),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){const t=((this.options.includePrerelease&&m)|(this.options.loose&&h))+":"+e,r=n.get(t);if(r)return r;const a=this.options.loose,o=a?c[l.HYPHENRANGELOOSE]:c[l.HYPHENRANGE];e=e.replace(o,C(this.options.includePrerelease)),s("hyphen replace",e),e=e.replace(c[l.COMPARATORTRIM],u),s("comparator trim",e),e=e.replace(c[l.TILDETRIM],d),s("tilde trim",e),e=e.replace(c[l.CARETTRIM],p),s("caret trim",e);let g=e.split(" ").map(e=>v(e,this.options)).join(" ").split(/\s+/).map(e=>P(e,this.options));a&&(g=g.filter(e=>(s("loose invalid filter",e,this.options),!!e.match(c[l.COMPARATORLOOSE])))),s("range list",g);const y=new Map,b=g.map(e=>new i(e,this.options));for(const e of b){if(f(e))return[e];y.set(e.value,e)}y.size>1&&y.has("")&&y.delete("");const _=[...y.values()];return n.set(t,_),_}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some(t=>y(t,r)&&e.set.some(e=>y(e,r)&&t.every(t=>e.every(e=>t.intersects(e,r)))))}test(e){if(!e)return!1;if("string"==typeof e)try{e=new o(e,this.options)}catch(e){return!1}for(let t=0;t<this.set.length;t++)if(A(this.set[t],e,this.options))return!0;return!1}}xi=t;const r=(ki||(ki=1,Ni=class{constructor(){this.max=1e3,this.map=new Map}get(e){const t=this.map.get(e);return void 0===t?void 0:(this.map.delete(e),this.map.set(e,t),t)}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&void 0!==t){if(this.map.size>=this.max){const e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}),Ni),n=new r,a=is(),i=ws(),s=ns(),o=os(),{safeRe:c,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:p}=as(),{FLAG_INCLUDE_PRERELEASE:m,FLAG_LOOSE:h}=rs(),f=e=>"<0.0.0-0"===e.value,g=e=>""===e.value,y=(e,t)=>{let r=!0;const n=e.slice();let a=n.pop();for(;r&&n.length;)r=n.every(e=>a.intersects(e,t)),a=n.pop();return r},v=(e,t)=>(e=e.replace(c[l.BUILD],""),s("comp",e,t),e=S(e,t),s("caret",e),e=_(e,t),s("tildes",e),e=k(e,t),s("xrange",e),e=E(e,t),s("stars",e),e),b=e=>!e||"x"===e.toLowerCase()||"*"===e,_=(e,t)=>e.trim().split(/\s+/).map(e=>w(e,t)).join(" "),w=(e,t)=>{const r=t.loose?c[l.TILDELOOSE]:c[l.TILDE];return e.replace(r,(t,r,n,a,i)=>{let o;return s("tilde",e,t,r,n,a,i),b(r)?o="":b(n)?o=`>=${r}.0.0 <${+r+1}.0.0-0`:b(a)?o=`>=${r}.${n}.0 <${r}.${+n+1}.0-0`:i?(s("replaceTilde pr",i),o=`>=${r}.${n}.${a}-${i} <${r}.${+n+1}.0-0`):o=`>=${r}.${n}.${a} <${r}.${+n+1}.0-0`,s("tilde return",o),o})},S=(e,t)=>e.trim().split(/\s+/).map(e=>N(e,t)).join(" "),N=(e,t)=>{s("caret",e,t);const r=t.loose?c[l.CARETLOOSE]:c[l.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(t,r,a,i,o)=>{let c;return s("caret",e,t,r,a,i,o),b(r)?c="":b(a)?c=`>=${r}.0.0${n} <${+r+1}.0.0-0`:b(i)?c="0"===r?`>=${r}.${a}.0${n} <${r}.${+a+1}.0-0`:`>=${r}.${a}.0${n} <${+r+1}.0.0-0`:o?(s("replaceCaret pr",o),c="0"===r?"0"===a?`>=${r}.${a}.${i}-${o} <${r}.${a}.${+i+1}-0`:`>=${r}.${a}.${i}-${o} <${r}.${+a+1}.0-0`:`>=${r}.${a}.${i}-${o} <${+r+1}.0.0-0`):(s("no pr"),c="0"===r?"0"===a?`>=${r}.${a}.${i}${n} <${r}.${a}.${+i+1}-0`:`>=${r}.${a}.${i}${n} <${r}.${+a+1}.0-0`:`>=${r}.${a}.${i} <${+r+1}.0.0-0`),s("caret return",c),c})},k=(e,t)=>(s("replaceXRanges",e,t),e.split(/\s+/).map(e=>x(e,t)).join(" ")),x=(e,t)=>{e=e.trim();const r=t.loose?c[l.XRANGELOOSE]:c[l.XRANGE];return e.replace(r,(r,n,a,i,o,c)=>{s("xRange",e,r,n,a,i,o,c);const l=b(a),u=l||b(i),d=u||b(o),p=d;return"="===n&&p&&(n=""),c=t.includePrerelease?"-0":"",l?r=">"===n||"<"===n?"<0.0.0-0":"*":n&&p?(u&&(i=0),o=0,">"===n?(n=">=",u?(a=+a+1,i=0,o=0):(i=+i+1,o=0)):"<="===n&&(n="<",u?a=+a+1:i=+i+1),"<"===n&&(c="-0"),r=`${n+a}.${i}.${o}${c}`):u?r=`>=${a}.0.0${c} <${+a+1}.0.0-0`:d&&(r=`>=${a}.${i}.0${c} <${a}.${+i+1}.0-0`),s("xRange return",r),r})},E=(e,t)=>(s("replaceStars",e,t),e.trim().replace(c[l.STAR],"")),P=(e,t)=>(s("replaceGTE0",e,t),e.trim().replace(c[t.includePrerelease?l.GTE0PRE:l.GTE0],"")),C=e=>(t,r,n,a,i,s,o,c,l,u,d,p)=>`${r=b(n)?"":b(a)?`>=${n}.0.0${e?"-0":""}`:b(i)?`>=${n}.${a}.0${e?"-0":""}`:s?`>=${r}`:`>=${r}${e?"-0":""}`} ${c=b(l)?"":b(u)?`<${+l+1}.0.0-0`:b(d)?`<${l}.${+u+1}.0-0`:p?`<=${l}.${u}.${d}-${p}`:e?`<${l}.${u}.${+d+1}-0`:`<=${c}`}`.trim(),A=(e,t,r)=>{for(let r=0;r<e.length;r++)if(!e[r].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let r=0;r<e.length;r++)if(s(e[r].semver),e[r].semver!==i.ANY&&e[r].semver.prerelease.length>0){const n=e[r].semver;if(n.major===t.major&&n.minor===t.minor&&n.patch===t.patch)return!0}return!1}return!0};return xi}function ws(){if(Ci)return Pi;Ci=1;const e=Symbol("SemVer ANY");class t{static get ANY(){return e}constructor(n,a){if(a=r(a),n instanceof t){if(n.loose===!!a.loose)return n;n=n.value}n=n.trim().split(/\s+/).join(" "),s("comparator",n,a),this.options=a,this.loose=!!a.loose,this.parse(n),this.semver===e?this.value="":this.value=this.operator+this.semver.version,s("comp",this)}parse(t){const r=this.options.loose?n[a.COMPARATORLOOSE]:n[a.COMPARATOR],i=t.match(r);if(!i)throw new TypeError(`Invalid comparator: ${t}`);this.operator=void 0!==i[1]?i[1]:"","="===this.operator&&(this.operator=""),i[2]?this.semver=new o(i[2],this.options.loose):this.semver=e}toString(){return this.value}test(t){if(s("Comparator.test",t,this.options.loose),this.semver===e||t===e)return!0;if("string"==typeof t)try{t=new o(t,this.options)}catch(e){return!1}return i(t,this.operator,this.semver,this.options)}intersects(e,n){if(!(e instanceof t))throw new TypeError("a Comparator is required");return""===this.operator?""===this.value||new c(e.value,n).test(this.value):""===e.operator?""===e.value||new c(this.value,n).test(e.semver):(!(n=r(n)).includePrerelease||"<0.0.0-0"!==this.value&&"<0.0.0-0"!==e.value)&&(!(!n.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0")))&&(!(!this.operator.startsWith(">")||!e.operator.startsWith(">"))||(!(!this.operator.startsWith("<")||!e.operator.startsWith("<"))||(!(this.semver.version!==e.semver.version||!this.operator.includes("=")||!e.operator.includes("="))||(!!(i(this.semver,"<",e.semver,n)&&this.operator.startsWith(">")&&e.operator.startsWith("<"))||!!(i(this.semver,">",e.semver,n)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))))))}}Pi=t;const r=is(),{safeRe:n,t:a}=as(),i=bs(),s=ns(),o=os(),c=_s();return Pi}function Ss(){if(Ii)return Ai;Ii=1;const e=_s();return Ai=(t,r,n)=>{try{r=new e(r,n)}catch(e){return!1}return r.test(t)},Ai}function Ns(){if(Fi)return ji;Fi=1;const e=_s();return ji=(t,r)=>{try{return new e(t,r).range||"*"}catch(e){return null}},ji}function ks(){if(qi)return Ui;qi=1;const e=os(),t=ws(),{ANY:r}=t,n=_s(),a=Ss(),i=ms(),s=hs(),o=vs(),c=ys();return Ui=(l,u,d,p)=>{let m,h,f,g,y;switch(l=new e(l,p),u=new n(u,p),d){case">":m=i,h=o,f=s,g=">",y=">=";break;case"<":m=s,h=c,f=i,g="<",y="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(a(l,u,p))return!1;for(let e=0;e<u.set.length;++e){const n=u.set[e];let a=null,i=null;if(n.forEach(e=>{e.semver===r&&(e=new t(">=0.0.0")),a=a||e,i=i||e,m(e.semver,a.semver,p)?a=e:f(e.semver,i.semver,p)&&(i=e)}),a.operator===g||a.operator===y)return!1;if((!i.operator||i.operator===g)&&h(l,i.semver))return!1;if(i.operator===y&&f(l,i.semver))return!1}return!0},Ui}var xs=function(){if(es)return Xi;es=1;const e=as(),t=rs(),r=os(),n=ss(),a=cs(),i=ls(),s=us(),o=function(){if(Da)return Ma;Da=1;const e=os();return Ma=(t,r,n,a,i)=>{"string"==typeof n&&(i=a,a=n,n=void 0);try{return new e(t instanceof e?t.version:t,n).inc(r,a,i).version}catch(e){return null}},Ma}(),c=function(){if(Fa)return ja;Fa=1;const e=cs();return ja=(t,r)=>{const n=e(t,null,!0),a=e(r,null,!0),i=n.compare(a);if(0===i)return null;const s=i>0,o=s?n:a,c=s?a:n,l=!!o.prerelease.length;if(c.prerelease.length&&!l){if(!c.patch&&!c.minor)return"major";if(0===c.compareMain(o))return c.minor&&!c.patch?"minor":"patch"}const u=l?"pre":"";return n.major!==a.major?u+"major":n.minor!==a.minor?u+"minor":n.patch!==a.patch?u+"patch":"prerelease"}}(),l=function(){if(qa)return Ua;qa=1;const e=os();return Ua=(t,r)=>new e(t,r).major}(),u=function(){if(Va)return Ba;Va=1;const e=os();return Ba=(t,r)=>new e(t,r).minor}(),d=function(){if(Ha)return Ga;Ha=1;const e=os();return Ga=(t,r)=>new e(t,r).patch}(),p=function(){if(Wa)return Ka;Wa=1;const e=cs();return Ka=(t,r)=>{const n=e(t,r);return n&&n.prerelease.length?n.prerelease:null},Ka}(),m=ds(),h=function(){if(Qa)return Ya;Qa=1;const e=ds();return Ya=(t,r,n)=>e(r,t,n)}(),f=function(){if(ei)return Xa;ei=1;const e=ds();return Xa=(t,r)=>e(t,r,!0)}(),g=ps(),y=function(){if(ai)return ni;ai=1;const e=ps();return ni=(t,r)=>t.sort((t,n)=>e(t,n,r))}(),v=function(){if(si)return ii;si=1;const e=ps();return ii=(t,r)=>t.sort((t,n)=>e(n,t,r))}(),b=ms(),_=hs(),w=fs(),S=gs(),N=ys(),k=vs(),x=bs(),E=function(){if(Si)return wi;Si=1;const e=os(),t=cs(),{safeRe:r,t:n}=as();return wi=(a,i)=>{if(a instanceof e)return a;if("number"==typeof a&&(a=String(a)),"string"!=typeof a)return null;let s=null;if((i=i||{}).rtl){const e=i.includePrerelease?r[n.COERCERTLFULL]:r[n.COERCERTL];let t;for(;(t=e.exec(a))&&(!s||s.index+s[0].length!==a.length);)s&&t.index+t[0].length===s.index+s[0].length||(s=t),e.lastIndex=t.index+t[1].length+t[2].length;e.lastIndex=-1}else s=a.match(i.includePrerelease?r[n.COERCEFULL]:r[n.COERCE]);if(null===s)return null;const o=s[2],c=s[3]||"0",l=s[4]||"0",u=i.includePrerelease&&s[5]?`-${s[5]}`:"",d=i.includePrerelease&&s[6]?`+${s[6]}`:"";return t(`${o}.${c}.${l}${u}${d}`,i)},wi}(),P=ws(),C=_s(),A=Ss(),I=function(){if(Ti)return Oi;Ti=1;const e=_s();return Oi=(t,r)=>new e(t,r).set.map(e=>e.map(e=>e.value).join(" ").trim().split(" ")),Oi}(),O=function(){if(zi)return $i;zi=1;const e=os(),t=_s();return $i=(r,n,a)=>{let i=null,s=null,o=null;try{o=new t(n,a)}catch(e){return null}return r.forEach(t=>{o.test(t)&&(i&&-1!==s.compare(t)||(i=t,s=new e(i,a)))}),i},$i}(),T=function(){if(Li)return Ri;Li=1;const e=os(),t=_s();return Ri=(r,n,a)=>{let i=null,s=null,o=null;try{o=new t(n,a)}catch(e){return null}return r.forEach(t=>{o.test(t)&&(i&&1!==s.compare(t)||(i=t,s=new e(i,a)))}),i},Ri}(),$=function(){if(Di)return Mi;Di=1;const e=os(),t=_s(),r=ms();return Mi=(n,a)=>{n=new t(n,a);let i=new e("0.0.0");if(n.test(i))return i;if(i=new e("0.0.0-0"),n.test(i))return i;i=null;for(let t=0;t<n.set.length;++t){const a=n.set[t];let s=null;a.forEach(t=>{const n=new e(t.semver.version);switch(t.operator){case">":0===n.prerelease.length?n.patch++:n.prerelease.push(0),n.raw=n.format();case"":case">=":s&&!r(n,s)||(s=n);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${t.operator}`)}}),!s||i&&!r(i,s)||(i=s)}return i&&n.test(i)?i:null},Mi}(),z=Ns(),R=ks(),L=function(){if(Vi)return Bi;Vi=1;const e=ks();return Bi=(t,r,n)=>e(t,r,">",n),Bi}(),M=function(){if(Hi)return Gi;Hi=1;const e=ks();return Gi=(t,r,n)=>e(t,r,"<",n),Gi}(),D=function(){if(Wi)return Ki;Wi=1;const e=_s();return Ki=(t,r,n)=>(t=new e(t,n),r=new e(r,n),t.intersects(r,n))}(),j=function(){if(Ji)return Zi;Ji=1;const e=Ss(),t=ds();return Zi=(r,n,a)=>{const i=[];let s=null,o=null;const c=r.sort((e,r)=>t(e,r,a));for(const t of c)e(t,n,a)?(o=t,s||(s=t)):(o&&i.push([s,o]),o=null,s=null);s&&i.push([s,null]);const l=[];for(const[e,t]of i)e===t?l.push(e):t||e!==c[0]?t?e===c[0]?l.push(`<=${t}`):l.push(`${e} - ${t}`):l.push(`>=${e}`):l.push("*");const u=l.join(" || "),d="string"==typeof n.raw?n.raw:String(n);return u.length<d.length?u:n},Zi}(),F=function(){if(Qi)return Yi;Qi=1;const e=_s(),t=ws(),{ANY:r}=t,n=Ss(),a=ds(),i=[new t(">=0.0.0-0")],s=[new t(">=0.0.0")],o=(e,t,o)=>{if(e===t)return!0;if(1===e.length&&e[0].semver===r){if(1===t.length&&t[0].semver===r)return!0;e=o.includePrerelease?i:s}if(1===t.length&&t[0].semver===r){if(o.includePrerelease)return!0;t=s}const u=new Set;let d,p,m,h,f,g,y;for(const t of e)">"===t.operator||">="===t.operator?d=c(d,t,o):"<"===t.operator||"<="===t.operator?p=l(p,t,o):u.add(t.semver);if(u.size>1)return null;if(d&&p){if(m=a(d.semver,p.semver,o),m>0)return null;if(0===m&&(">="!==d.operator||"<="!==p.operator))return null}for(const e of u){if(d&&!n(e,String(d),o))return null;if(p&&!n(e,String(p),o))return null;for(const r of t)if(!n(e,String(r),o))return!1;return!0}let v=!(!p||o.includePrerelease||!p.semver.prerelease.length)&&p.semver,b=!(!d||o.includePrerelease||!d.semver.prerelease.length)&&d.semver;v&&1===v.prerelease.length&&"<"===p.operator&&0===v.prerelease[0]&&(v=!1);for(const e of t){if(y=y||">"===e.operator||">="===e.operator,g=g||"<"===e.operator||"<="===e.operator,d)if(b&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===b.major&&e.semver.minor===b.minor&&e.semver.patch===b.patch&&(b=!1),">"===e.operator||">="===e.operator){if(h=c(d,e,o),h===e&&h!==d)return!1}else if(">="===d.operator&&!n(d.semver,String(e),o))return!1;if(p)if(v&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===v.major&&e.semver.minor===v.minor&&e.semver.patch===v.patch&&(v=!1),"<"===e.operator||"<="===e.operator){if(f=l(p,e,o),f===e&&f!==p)return!1}else if("<="===p.operator&&!n(p.semver,String(e),o))return!1;if(!e.operator&&(p||d)&&0!==m)return!1}return!(d&&g&&!p&&0!==m||p&&y&&!d&&0!==m||b||v)},c=(e,t,r)=>{if(!e)return t;const n=a(e.semver,t.semver,r);return n>0?e:n<0||">"===t.operator&&">="===e.operator?t:e},l=(e,t,r)=>{if(!e)return t;const n=a(e.semver,t.semver,r);return n<0?e:n>0||"<"===t.operator&&"<="===e.operator?t:e};return Yi=(t,r,n={})=>{if(t===r)return!0;t=new e(t,n),r=new e(r,n);let a=!1;e:for(const e of t.set){for(const t of r.set){const r=o(e,t,n);if(a=a||null!==r,r)continue e}if(a)return!1}return!0}}();return Xi={parse:a,valid:i,clean:s,inc:o,diff:c,major:l,minor:u,patch:d,prerelease:p,compare:m,rcompare:h,compareLoose:f,compareBuild:g,sort:y,rsort:v,gt:b,lt:_,eq:w,neq:S,gte:N,lte:k,cmp:x,coerce:E,Comparator:P,Range:C,satisfies:A,toComparators:I,maxSatisfying:O,minSatisfying:T,minVersion:$,validRange:z,outside:R,gtr:L,ltr:M,intersects:D,simplifyRange:j,subset:F,SemVer:r,re:e.re,src:e.src,tokens:e.t,SEMVER_SPEC_VERSION:t.SEMVER_SPEC_VERSION,RELEASE_TYPES:t.RELEASE_TYPES,compareIdentifiers:n.compareIdentifiers,rcompareIdentifiers:n.rcompareIdentifiers}}();class Es extends xs.SemVer{satisfies(e){return xs.satisfies(this,e)}}const Ps=(e,t,r)=>{const n="string"==typeof t?t.split("."):t,a=n.shift();return a&&(e[a]??={},n.length?Ps(e[a],n,r):Object.assign(e,{[a]:r})),e};class Cs{#l={};createConfig(e,t){return Nn(this._createConfig(e,t))}async createConfigAsync(e,t){return En(this.createConfig(e,t))}_set(e,t){const r="function"==typeof t?t:async()=>t;this.#l[e]=r}_get(e){return this.#l[e]}_has(e){return e in this.#l}_createConfig(e,t){return Nn(this._buildConfig(e,t)).pipe(sa(t=>this._processConfig(t,e)))}_buildConfig(e,t){return Nn(Object.entries(this.#l)).pipe(Rn(([t,r])=>Nn(r(e)).pipe(Bn(e=>void 0!==e),On(e=>({target:t,value:e})),Vn(e=>(console.error(`Failed to execute config callback: ${r.name} for attribute: '${t}'`,e),rn)))),Hn((e,{target:t,value:r})=>Ps(e,t,r),t??{}))}_processConfig(e,t){return kn(e)}}var As;!function(e){e[e.Debug=0]="Debug",e[e.Information=1]="Information",e[e.Warning=2]="Warning",e[e.Error=3]="Error",e[e.Critical=4]="Critical"}(As||(As={}));class Is{static[Symbol.hasInstance](e){if(null!==e&&"object"==typeof e&&"version"in e&&"dispose"in e){const t=e,r=xs.coerce(String(t.version)),n=t.dispose;return!!r&&"function"==typeof n}return!1}#u;#d;get version(){return this.#u}constructor(e){const{version:t}=e;this.#u=new Es(t),this.#d=new wr}_addTeardown(e){return this.#d.add(e),()=>this.#d.remove(e)}dispose(){this.#d.unsubscribe()}}class Os extends Error{constructor(){super("Module initialization timed out"),this.name="RequiredModuleTimeoutError"}}class Ts{static className="ModulesConfigurator";get version(){return"5.0.6-cli-search-index.0"}#p=new Kr(100);get event$(){return this.#p.asObservable()}_configs=[];_afterConfiguration=[];_afterInit=[];_modules;constructor(e){this._modules=new Set(e)}get modules(){return[...this._modules]}configure(...e){for(const t of e)this.addConfig(t)}addConfig(e){const{module:t,afterConfig:r,afterInit:n,configure:a}=e;this._modules.add(t),this._registerEvent({level:As.Debug,name:"moduleConfigAdded",message:`Module configurator added for ${t.name}`,properties:{moduleName:t.name,moduleVersion:t.version?.toString()||"unknown",configure:!!a,afterConfig:!!r,afterInit:!!n}}),a&&this._configs.push((e,r)=>a(e[t.name],r)),r&&this._afterConfiguration.push(e=>r(e[t.name])),n&&this._afterInit.push(e=>n(e[t.name]))}onConfigured(e){this._afterConfiguration.push(e),this._registerEvent({level:As.Debug,name:"addOnConfigured",message:"Added onConfigured callback",properties:{count:this._afterConfiguration.length,name:e.name||"anonymous"}})}onInitialized(e){this._afterInit.push(e),this._registerEvent({level:As.Debug,name:"addOnInitialized",message:"Added onInitialized callback",properties:{count:this._afterInit.length,name:e.name||"anonymous"}})}async initialize(e){const t=performance.now(),r=await this._configure(e),n=Math.round(performance.now()-t);this._registerEvent({level:As.Debug,name:"initialize.configLoaded",message:`Modules configured in ${n}ms`,properties:{modules:this.modules.map(e=>e.name).join(", "),count:this.modules.length,loadTime:n},metric:n});const a=performance.now(),i=await this._initialize(r,e),s=Math.round(performance.now()-a);this._registerEvent({level:As.Debug,name:"initialize.instanceInitialized",message:`Modules initialized in ${s}ms`,properties:{modules:this.modules.map(e=>e.name).join(", "),count:this.modules.length,loadTime:s},metric:s});const o=n+s;return this._registerEvent({level:As.Information,name:"initialize",message:`initialize in ${o}ms`,properties:{modules:this.modules.map(e=>e.name).join(", "),configLoadTime:n,instanceLoadTime:s,totalLoadTime:o},metric:o}),await this._postInitialize(i,e),Object.seal(Object.assign({},i,{dispose:()=>this.dispose(i)}))}_registerEvent(e){const t=e.name.split("::");this.#p.next({...e,name:`${this.constructor.className}::${t[t.length-1]}`})}async _configure(e){const t=await this._createConfig(e);return await Promise.all(this._configs.map(r=>Promise.resolve(r(t,e)))),await this._postConfigure(t),t}_createConfig(e){const{modules:t,_afterConfiguration:r,_afterInit:n}=this,a=Nn(t).pipe(Rn(async t=>{const r=performance.now();try{const n=await(t.configure?.(e)),a=Math.round(performance.now()-r);return this._registerEvent({level:As.Debug,name:"_createConfig.configuratorCreated",message:`Configurator created for ${t.name} in ${a}ms`,properties:{moduleName:t.name,moduleVersion:t.version?.toString()||"unknown",configLoadTime:a},metric:a}),{[t.name]:n}}catch(e){throw this._registerEvent({level:As.Error,name:"_createConfig.configuratorFailed",message:`Failed to create configurator for ${t.name}`,properties:{moduleName:t.name,moduleVersion:t.version?.toString()||"unknown"},metric:Math.round(performance.now()-r),error:e}),e}}),Hn((e,t)=>Object.assign(e,t),{onAfterConfiguration(e){r.push(e)},onAfterInit(e){n.push(e)}}));return En(a)}async _postConfigure(e){const{modules:t,_afterConfiguration:r}=this;if(await Promise.allSettled(t.filter(e=>!!e.postConfigure).map(async t=>{try{const r=performance.now();await(t.postConfigure?.(e)),this._registerEvent({level:As.Debug,name:"_postConfigure.modulePostConfigured",message:`Module ${t.name} post-configured successfully`,properties:{moduleName:t.name,moduleVersion:t.version?.toString()||"unknown",postConfigTime:Math.round(performance.now()-r)}})}catch(e){this._registerEvent({level:As.Warning,name:"_postConfigure.modulePostConfigureError",message:`Module ${t.name} post-configure failed`,properties:{moduleName:t.name,moduleVersion:t.version?.toString()||"unknown"},error:e})}})),r.length)try{this._registerEvent({level:As.Debug,name:"_postConfigure.hooks",message:`Post configure hooks [${r.length}] called`});const t=performance.now();await Promise.allSettled(r.map(t=>Promise.resolve(t(e))));const n=Math.round(performance.now()-t);this._registerEvent({level:As.Debug,name:"_postConfigure.hooksComplete",message:"Post configure hooks complete",properties:{count:r.length,postConfigHooksTime:n},metric:n})}catch(e){this._registerEvent({level:As.Warning,name:"_postConfigure.hooksError",message:"Post configure hook failed",error:e})}}async _initialize(e,t){const r=this.modules.map(e=>e.name),n=new Gr({}),a=e=>r.includes(e),i=(e,t=60)=>{if(!r.includes(e)){const r=new Error(`Cannot require [${String(e)}] since module is not defined!`);throw r.name="ModuleNotDefinedError",this._registerEvent({level:As.Error,name:"_initialize.requireInstance.moduleNotDefined",message:r.message,properties:{moduleName:String(e),wait:t},error:r}),r}if(n.value[e])return this._registerEvent({level:As.Debug,name:"_initialize.requireInstance.moduleAlreadyInitialized",message:`Module [${String(e)}] is already initialized, skipping queue`,properties:{moduleName:String(e),wait:t}}),Promise.resolve(n.value[e]);const a=performance.now();return this._registerEvent({level:As.Debug,name:"_initialize.requireInstance.awaiting",message:`Awaiting module [${String(e)}] initialization, timeout ${t}s`,properties:{moduleName:String(e),wait:t}}),Pn(n.pipe(Bn(t=>!!t[e]),On(t=>t[e]),function(e){var t=Cn(e)?{first:e}:"number"==typeof e?{each:e}:e,r=t.first,n=t.each,a=t.with,i=void 0===a?In:a,s=t.scheduler,o=void 0===s?en:s,c=t.meta,l=void 0===c?null:c;if(null==r&&null==n)throw new TypeError("No timeout provided.");return jr(function(e,t){var a,s,c=null,u=0,d=function(e){s=vn(t,o,function(){try{a.unsubscribe(),gn(i({meta:l,lastValue:c,seen:u})).subscribe(t)}catch(e){t.error(e)}},e)};a=e.subscribe(Fr(t,function(e){null==s||s.unsubscribe(),u++,t.next(c=e),n>0&&d(n)},void 0,void 0,function(){(null==s?void 0:s.closed)||null==s||s.unsubscribe(),c=null})),!u&&d(null!=r?"number"==typeof r?r:+r-o.now():n)})}({each:1e3*t,with:()=>{return n=yr(r=()=>{const r=new Os;return this._registerEvent({level:As.Error,name:"_initialize.requireInstance.timeout",message:`Module [${String(e)}] initialization timed out after ${t}s`,properties:{moduleName:String(e),wait:t},error:r}),r})?r:function(){return r},new Mr(function(e){return e.error(n())});var r,n}}),ca(()=>{const r=Math.round(performance.now()-a);this._registerEvent({level:As.Debug,name:"_initialize.requireInstance.moduleResolved",message:`Module [${String(e)}] required in ${r}ms`,properties:{moduleName:String(e),wait:t,requireTime:r},metric:r})})))},s=Nn(this.modules).pipe(Rn(r=>{const n=r.name;if(!r.initialize){const e=new Error(`Module ${r.name} does not have initialize method`);throw e.name="ModuleInitializeError",this._registerEvent({level:As.Error,name:"_initialize.moduleInitializeError",message:e.message,properties:{moduleName:r.name,moduleVersion:r.version?.toString()||"unknown"},error:e}),e}this._registerEvent({level:As.Debug,name:"_initialize.moduleInitializing",message:`Initializing module ${r.name}`,properties:{moduleName:r.name,moduleVersion:r.version?.toString()||"unknown"}});const s=performance.now();return Nn(Promise.resolve(r.initialize({ref:t,config:e[n],requireInstance:i,hasModule:a}))).pipe(On(e=>{e instanceof Is||this._registerEvent({level:As.Warning,name:"_initialize.providerNotBaseModuleProvider",message:`Provider for module ${r.name} does not extend BaseModuleProvider`,properties:{moduleName:r.name,moduleVersion:r.version?.toString()||"unknown"}}),e.version||this._registerEvent({level:As.Warning,name:"_initialize.providerVersionWarning",message:`Provider for module ${r.name} does not expose version`,properties:{moduleName:r.name,moduleVersion:r.version?.toString()||"unknown"}});const t=Math.round(performance.now()-s);return this._registerEvent({level:As.Debug,name:"_initialize.moduleInitialized",message:`Module ${r.name} initialized in ${t}ms`,properties:{moduleName:r.name,moduleVersion:r.version?.toString()||"unknown",providerName:typeof e,providerVersion:e.version?.toString()||"unknown",moduleInitTime:t},metric:t}),[n,e]}))})),o=performance.now();s.pipe(Jn([])).subscribe({next:([e,t])=>{n.next(Object.assign(n.value,{[e]:t}))},error:e=>{this._registerEvent({level:As.Error,name:"_initialize.moduleInitializationError",message:`Failed to initialize module ${e.name||"unknown"}`,error:e}),n.error(e)},complete:()=>{const e=Math.round(performance.now()-o);return this._registerEvent({level:As.Debug,name:"_initialize.moduleInitializationComplete",message:`All modules initialized in ${e}ms`,properties:{modules:Object.keys(n.value).join(", "),loadTime:e},metric:e}),n.complete()}});const c=performance.now(),l=await En(n),u=Math.round(performance.now()-c);return this._registerEvent({level:As.Debug,name:"_initialize.complete",message:`Modules instance created in ${u}ms`,properties:{modules:Object.keys(l).join(", "),initTime:u},metric:u}),Object.seal(l),l}async _postInitialize(e,t){const{modules:r,_afterInit:n}=this,a=Nn(r).pipe(Bn(e=>!!e.postInitialize),ca(e=>{this._registerEvent({level:As.Debug,name:"_postInitialize.modulePostInitializing",message:`Module ${e.name} is being post-initialized`,properties:{moduleName:e.name,moduleVersion:e.version?.toString()||"unknown"}})}),Rn(r=>{const n=performance.now();return Nn(r.postInitialize({ref:t,modules:e,instance:e[r.name]})).pipe(ca(()=>{const e=Math.round(performance.now()-n);this._registerEvent({level:As.Debug,name:"_postInitialize.modulePostInitialized",message:`Module ${r.name} has been post-initialized in ${e}ms`,metric:e,properties:{moduleName:r.name,moduleVersion:r.version?.toString()||"unknown",postInitTime:e}})}),Jn(null),Vn(e=>(this._registerEvent({level:As.Warning,name:"_postInitialize.modulePostInitializeError",message:`Module ${r.name} post-initialize failed`,properties:{moduleName:r.name,moduleVersion:r.version?.toString()||"unknown"},error:e}),rn)))}),Jn(null));this._registerEvent({level:As.Debug,name:"_postInitialize.modulesPostInitializing",message:`Post-initializing all modules [${Object.keys(e).length}]`,properties:{modules:Object.keys(e).join(", ")}});const i=performance.now();await En(a);const s=Math.round(performance.now()-i);if(this._registerEvent({level:As.Debug,name:"_postInitialize.modulesPostInitializeComplete",message:`Post-initialization of all modules completed in ${s}ms`,properties:{modules:Object.keys(e).join(", "),postInitTime:s},metric:s}),n.length)try{this._registerEvent({level:As.Debug,name:"_postInitialize.afterInitHooks",message:`Executing post-initialize hooks [${n.length}]`,properties:{hooks:n.map(e=>e.name||"anonymous").join(", ")}});const t=performance.now();await Promise.allSettled(n.map(t=>Promise.resolve(t(e))));const r=Math.round(performance.now()-t);this._registerEvent({level:As.Debug,name:"_postInitialize.afterInitHooksComplete",message:`Post-initialize hooks completed in ${r}ms`,properties:{hooks:n.map(e=>e.name||"anonymous").join(", "),afterInitTime:r},metric:r})}catch(e){this._registerEvent({level:As.Warning,name:"_postInitialize.afterInitHooksError",message:"Post-initialize hooks failed",properties:{hooks:n.map(e=>e.name||"anonymous").join(", ")},error:e})}const o=Math.round(performance.now()-i);this._registerEvent({level:As.Debug,name:"_postInitialize.complete",message:"Post-initialization complete",properties:{modules:Object.keys(e).join(", "),postInitCompleteTime:o}})}async dispose(e,t){this._registerEvent({level:As.Debug,name:"dispose",message:"Disposing modules instance",properties:{modules:Object.keys(e).join(", ")}}),await Promise.allSettled(this.modules.filter(e=>!!e.dispose).map(async r=>{if(r.dispose)try{await r.dispose({ref:t,modules:e,instance:e[r.name]}),this._registerEvent({level:As.Debug,name:"dispose.moduleDisposed",message:`Module ${r.name} disposed successfully`,properties:{moduleName:r.name,moduleVersion:r.version?.toString()||"unknown"}})}catch(e){this._registerEvent({level:As.Warning,name:"dispose.moduleDisposeError",message:`Module ${r.name} dispose failed`,properties:{moduleName:r.name,moduleVersion:r.version?.toString()||"unknown"},error:e})}})),this.#p.complete()}}function $s(e){return t=>Nn(Object.entries(e)).pipe(Rn(([e,r])=>"function"==typeof r?Nn(r(t)).pipe(Bn(e=>!!e),On(t=>[e,t])):kn([e,r])),na((e,[t,r])=>(e[t]=r,e),{}),Jn({}),function(e,t,r){var n,a,i,s,o=!1;return e&&"object"==typeof e?(n=e.bufferSize,s=void 0===n?1/0:n,a=e.windowTime,t=void 0===a?1/0:a,o=void 0!==(i=e.refCount)&&i,r=e.scheduler):s=null!=e?e:1/0,aa({connector:function(){return new Kr(s,t,r)},resetOnError:!0,resetOnComplete:!1,resetOnRefCountZero:o})}({bufferSize:1,refCount:!0}))}class zs extends Cs{#m={};#h={};#f={};constructor(){super(),this._set("models",$s(this.#m)),this._set("embeddings",$s(this.#h)),this._set("vectorStores",$s(this.#f))}setModel(e,t){return this.#m[e]=t,this}setEmbedding(e,t){return this.#h[e]=t,this}setVectorStore(e,t){return this.#f[e]=t,this}getService(e,t){switch(e){case"models":return this.#m[t];case"embeddings":return this.#h[t];case"vectorStores":return this.#f[t];default:throw new Error(`Unknown service type: ${e}`)}}}class Rs extends Is{#m;#h;#f;constructor(e){super({version:"1.1.0-cli-search-index.0",config:e}),this.#m=e.models||{},this.#h=e.embeddings||{},this.#f=e.vectorStores||{}}getService(e,t){switch(e){case"chat":{const e=this.#m[t];if(!e)throw new Error(`Chat service with identifier '${t}' not found`);return e}case"embeddings":{const e=this.#h[t];if(!e)throw new Error(`Embedding service with identifier '${t}' not found`);return e}case"search":{const e=this.#f[t];if(!e)throw new Error(`Search service with identifier '${t}' not found`);return e}default:throw new Error(`Unknown service type: ${e}`)}}}const Ls={name:"ai",configure:()=>new zs,initialize:async e=>{const t=await e.config.createConfigAsync(e);return new Rs(t)}};class Ms extends Error{code;statusCode;details;constructor(e,t,r,n){super(e),this.code=t,this.statusCode=r,this.details=n,this.name="AIError"}}class Ds{_key;get key(){return this._key}constructor(e){if(!e)throw new Error("key must be a non-empty string");this._key=e}update(e){this._key=e}}function js(e,t){const r=t.retryDelayInMs*Math.pow(2,e),n=Math.min(t.maxRetryDelayInMs,r);var a,i;return{retryAfterInMs:n/2+(a=0,i=n/2,a=Math.ceil(a),i=Math.floor(i),Math.floor(Math.random()*(i-a+1))+a)}}function Fs(e){return!("object"!=typeof e||null===e||Array.isArray(e)||e instanceof RegExp||e instanceof Date)}function Us(e){if(Fs(e)){const t="string"==typeof e.name,r="string"==typeof e.message;return t&&r}return!1}const qs="function"==typeof globalThis?.crypto?.randomUUID?globalThis.crypto.randomUUID.bind(globalThis.crypto):pe;function Bs(){return qs()}"undefined"!=typeof Deno&&void 0!==Deno.version&&Deno.version.deno,"undefined"!=typeof Bun&&Bun.version;const Vs=void 0!==globalThis.process&&Boolean(globalThis.process.version)&&Boolean(globalThis.process.versions?.node);function Gs(e,t){return Buffer.from(e,t)}const Hs="REDACTED",Ks=["x-ms-client-request-id","x-ms-return-client-request-id","x-ms-useragent","x-ms-correlation-request-id","x-ms-request-id","client-request-id","ms-cv","return-client-request-id","traceparent","Access-Control-Allow-Credentials","Access-Control-Allow-Headers","Access-Control-Allow-Methods","Access-Control-Allow-Origin","Access-Control-Expose-Headers","Access-Control-Max-Age","Access-Control-Request-Headers","Access-Control-Request-Method","Origin","Accept","Accept-Encoding","Cache-Control","Connection","Content-Length","Content-Type","Date","ETag","Expires","If-Match","If-Modified-Since","If-None-Match","If-Unmodified-Since","Last-Modified","Pragma","Request-Id","Retry-After","Server","Transfer-Encoding","User-Agent","WWW-Authenticate"],Ws=["api-version"];class Zs{allowedHeaderNames;allowedQueryParameters;constructor({additionalAllowedHeaderNames:e=[],additionalAllowedQueryParameters:t=[]}={}){e=Ks.concat(e),t=Ws.concat(t),this.allowedHeaderNames=new Set(e.map(e=>e.toLowerCase())),this.allowedQueryParameters=new Set(t.map(e=>e.toLowerCase()))}sanitize(e){const t=new Set;return JSON.stringify(e,(e,r)=>{if(r instanceof Error)return{...r,name:r.name,message:r.message};if("headers"===e)return this.sanitizeHeaders(r);if("url"===e)return this.sanitizeUrl(r);if("query"===e)return this.sanitizeQuery(r);if("body"!==e&&"response"!==e&&"operationSpec"!==e){if(Array.isArray(r)||Fs(r)){if(t.has(r))return"[Circular]";t.add(r)}return r}},2)}sanitizeUrl(e){if("string"!=typeof e||null===e||""===e)return e;const t=new URL(e);if(!t.search)return e;for(const[e]of t.searchParams)this.allowedQueryParameters.has(e.toLowerCase())||t.searchParams.set(e,Hs);return t.toString()}sanitizeHeaders(e){const t={};for(const r of Object.keys(e))this.allowedHeaderNames.has(r.toLowerCase())?t[r]=e[r]:t[r]=Hs;return t}sanitizeQuery(e){if("object"!=typeof e||null===e)return e;const t={};for(const r of Object.keys(e))this.allowedQueryParameters.has(r.toLowerCase())?t[r]=e[r]:t[r]=Hs;return t}}let Js=class extends Error{constructor(e){super(e),this.name="AbortError"}};function Ys(e,t){let r;const{abortSignal:n,abortErrorMsg:a}={};return function(e,t){const{cleanupBeforeAbort:r,abortSignal:n,abortErrorMsg:a}=t??{};return new Promise((t,i)=>{function s(){i(new Js(a??"The operation was aborted."))}function o(){n?.removeEventListener("abort",c)}function c(){r?.(),o(),s()}if(n?.aborted)return s();try{e(e=>{o(),t(e)},e=>{o(),i(e)})}catch(e){i(e)}n?.addEventListener("abort",c)})}(t=>{r=setTimeout(t,e)},{cleanupBeforeAbort:()=>clearTimeout(r),abortSignal:n,abortErrorMsg:a??"The delay was aborted."})}function Qs(e){if(Us(e))return e.message;{let t;try{t="object"==typeof e&&e?JSON.stringify(e):String(e)}catch(e){t="[unable to stringify input]"}return`Unknown error ${t}`}}function Xs(e){return Us(e)}const eo=Vs;function to(e){const t=e;return t&&"function"==typeof t.getToken&&(void 0===t.signRequest||t.getToken.length>0)}class ro{latitude;longitude;constructor(e){this.longitude=e.longitude,this.latitude=e.latitude}toJSON(){return{type:"Point",coordinates:[this.longitude,this.latitude],crs:{type:"name",properties:{name:"EPSG:4326"}}}}}class no{actions;constructor(e=[]){this.actions=e}upload(e){const t=e.map(e=>({...e,__actionType:"upload"}));this.actions.push(...t)}merge(e){const t=e.map(e=>({...e,__actionType:"merge"}));this.actions.push(...t)}mergeOrUpload(e){const t=e.map(e=>({...e,__actionType:"mergeOrUpload"}));this.actions.push(...t)}delete(e,t){if(t){const r=e,n=t.map(e=>({__actionType:"delete",[r]:e}));this.actions.push(...n)}else{const t=e.map(e=>({__actionType:"delete",...e}));this.actions.push(...t)}}}var ao;!function(e){e.AzureChina="https://search.azure.cn",e.AzureGovernment="https://search.azure.us",e.AzurePublicCloud="https://search.azure.com"}(ao||(ao={}));class io extends Error{constructor(e){super(e),this.name="AbortError"}}const so="undefined"!=typeof process&&process.env&&process.env.DEBUG||void 0;let oo,co=[],lo=[];const uo=[];so&&mo(so);const po=Object.assign(e=>go(e),{enable:mo,enabled:ho,disable:function(){const e=oo||"";return mo(""),e},log:function(e,...t){de.stderr.write(`${le.format(e,...t)}${ne}`)}});function mo(e){oo=e,co=[],lo=[];const t=e.split(",").map(e=>e.trim());for(const e of t)e.startsWith("-")?lo.push(e.substring(1)):co.push(e);for(const e of uo)e.enabled=ho(e.namespace)}function ho(e){if(e.endsWith("*"))return!0;for(const t of lo)if(fo(e,t))return!1;for(const t of co)if(fo(e,t))return!0;return!1}function fo(e,t){if(-1===t.indexOf("*"))return e===t;let r=t;if(-1!==t.indexOf("**")){const e=[];let n="";for(const r of t)"*"===r&&"*"===n||(n=r,e.push(r));r=e.join("")}let n=0,a=0;const i=r.length,s=e.length;let o=-1,c=-1;for(;n<s&&a<i;)if("*"!==r[a]){if(r[a]!==e[n]){if(o>=0){if(a=o+1,n=c+1,n===s)return!1;for(;e[n]!==r[a];)if(n++,n===s)return!1;c=n,n++,a++;continue}return!1}a++,n++}else{if(o=a,a++,a===i)return!0;for(;e[n]!==r[a];)if(n++,n===s)return!1;c=n,n++,a++}const l=n===e.length,u=a===r.length,d=a===r.length-1&&"*"===r[a];return l&&(u||d)}function go(e){const t=Object.assign(function(...r){if(!t.enabled)return;r.length>0&&(r[0]=`${e} ${r[0]}`);t.log(...r)},{enabled:ho(e),destroy:yo,log:po.log,namespace:e,extend:vo});return uo.push(t),t}function yo(){const e=uo.indexOf(this);return e>=0&&(uo.splice(e,1),!0)}function vo(e){const t=go(`${this.namespace}:${e}`);return t.log=this.log,t}const bo=["verbose","info","warning","error"],_o={verbose:400,info:300,warning:200,error:100};function wo(e,t){t.log=(...t)=>{e.log(...t)}}function So(e){return bo.includes(e)}function No(e){const t=new Set,r="undefined"!=typeof process&&process.env&&process.env[e.logLevelEnvVarName]||void 0;let n;const a=po(e.namespace);function i(e){if(e&&!So(e))throw new Error(`Unknown log level '${e}'. Acceptable values: ${bo.join(",")}`);n=e;const r=[];for(const e of t)s(e)&&r.push(e.namespace);po.enable(r.join(","))}function s(e){return Boolean(n&&_o[e.level]<=_o[n])}function o(e,r){const n=Object.assign(e.extend(r),{level:r});if(wo(e,n),s(n)){const e=po.disable();po.enable(e+","+n.namespace)}return t.add(n),n}return a.log=(...e)=>{po.log(...e)},r&&(So(r)?i(r):console.error(`${e.logLevelEnvVarName} set to unknown log level '${r}'; logging is not enabled. Acceptable values: ${bo.join(", ")}.`)),{setLogLevel:i,getLogLevel:function(){return n},createClientLogger:function(e){const t=a.extend(e);return wo(a,t),{error:o(t,"error"),warning:o(t,"warning"),info:o(t,"info"),verbose:o(t,"verbose")}},logger:a}}const ko=No({logLevelEnvVarName:"TYPESPEC_RUNTIME_LOG_LEVEL",namespace:"typeSpecRuntime"});function xo(e){return ko.createClientLogger(e)}function Eo(e){return e.toLowerCase()}class Po{_headersMap;constructor(e){if(this._headersMap=new Map,e)for(const t of Object.keys(e))this.set(t,e[t])}set(e,t){this._headersMap.set(Eo(e),{name:e,value:String(t).trim()})}get(e){return this._headersMap.get(Eo(e))?.value}has(e){return this._headersMap.has(Eo(e))}delete(e){this._headersMap.delete(Eo(e))}toJSON(e={}){const t={};if(e.preserveCase)for(const e of this._headersMap.values())t[e.name]=e.value;else for(const[e,r]of this._headersMap)t[e]=r.value;return t}toString(){return JSON.stringify(this.toJSON({preserveCase:!0}))}[Symbol.iterator](){return function*(e){for(const t of e.values())yield[t.name,t.value]}(this._headersMap)}}function Co(e){return new Po(e)}class Ao{url;method;headers;timeout;withCredentials;body;multipartBody;formData;streamResponseStatusCodes;enableBrowserStreams;proxySettings;disableKeepAlive;abortSignal;requestId;allowInsecureConnection;onUploadProgress;onDownloadProgress;requestOverrides;authSchemes;constructor(e){this.url=e.url,this.body=e.body,this.headers=e.headers??Co(),this.method=e.method??"GET",this.timeout=e.timeout??0,this.multipartBody=e.multipartBody,this.formData=e.formData,this.disableKeepAlive=e.disableKeepAlive??!1,this.proxySettings=e.proxySettings,this.streamResponseStatusCodes=e.streamResponseStatusCodes,this.withCredentials=e.withCredentials??!1,this.abortSignal=e.abortSignal,this.onUploadProgress=e.onUploadProgress,this.onDownloadProgress=e.onDownloadProgress,this.requestId=e.requestId||Bs(),this.allowInsecureConnection=e.allowInsecureConnection??!1,this.enableBrowserStreams=e.enableBrowserStreams??!1,this.requestOverrides=e.requestOverrides,this.authSchemes=e.authSchemes}}const Io=new Set(["Deserialize","Serialize","Retry","Sign"]);class Oo{_policies=[];_orderedPolicies;constructor(e){this._policies=e?.slice(0)??[],this._orderedPolicies=void 0}addPolicy(e,t={}){if(t.phase&&t.afterPhase)throw new Error("Policies inside a phase cannot specify afterPhase.");if(t.phase&&!Io.has(t.phase))throw new Error(`Invalid phase name: ${t.phase}`);if(t.afterPhase&&!Io.has(t.afterPhase))throw new Error(`Invalid afterPhase name: ${t.afterPhase}`);this._policies.push({policy:e,options:t}),this._orderedPolicies=void 0}removePolicy(e){const t=[];return this._policies=this._policies.filter(r=>!(e.name&&r.policy.name===e.name||e.phase&&r.options.phase===e.phase)||(t.push(r.policy),!1)),this._orderedPolicies=void 0,t}sendRequest(e,t){const r=this.getOrderedPolicies().reduceRight((e,t)=>r=>t.sendRequest(r,e),t=>e.sendRequest(t));return r(t)}getOrderedPolicies(){return this._orderedPolicies||(this._orderedPolicies=this.orderPolicies()),this._orderedPolicies}clone(){return new Oo(this._policies)}static create(){return new Oo}orderPolicies(){const e=[],t=new Map;function r(e){return{name:e,policies:new Set,hasRun:!1,hasAfterPolicies:!1}}const n=r("Serialize"),a=r("None"),i=r("Deserialize"),s=r("Retry"),o=r("Sign"),c=[n,a,i,s,o];function l(e){return"Retry"===e?s:"Serialize"===e?n:"Deserialize"===e?i:"Sign"===e?o:a}for(const e of this._policies){const r=e.policy,n=e.options,a=r.name;if(t.has(a))throw new Error("Duplicate policy names not allowed in pipeline");const i={policy:r,dependsOn:new Set,dependants:new Set};n.afterPhase&&(i.afterPhase=l(n.afterPhase),i.afterPhase.hasAfterPolicies=!0),t.set(a,i);l(n.phase).policies.add(i)}for(const e of this._policies){const{policy:r,options:n}=e,a=r.name,i=t.get(a);if(!i)throw new Error(`Missing node for policy ${a}`);if(n.afterPolicies)for(const e of n.afterPolicies){const r=t.get(e);r&&(i.dependsOn.add(r),r.dependants.add(i))}if(n.beforePolicies)for(const e of n.beforePolicies){const r=t.get(e);r&&(r.dependsOn.add(i),i.dependants.add(r))}}function u(r){r.hasRun=!0;for(const n of r.policies)if((!n.afterPhase||n.afterPhase.hasRun&&!n.afterPhase.policies.size)&&0===n.dependsOn.size){e.push(n.policy);for(const e of n.dependants)e.dependsOn.delete(n);t.delete(n.policy.name),r.policies.delete(n)}}function d(){for(const e of c){if(u(e),e.policies.size>0&&e!==a)return void(a.hasRun||u(a));e.hasAfterPolicies&&u(a)}}let p=0;for(;t.size>0;){p++;const t=e.length;if(d(),e.length<=t&&p>1)throw new Error("Cannot satisfy policy dependencies due to requirements cycle.")}return e}}const To=ue.custom,$o=new Zs;let zo=class e extends Error{static REQUEST_SEND_ERROR="REQUEST_SEND_ERROR";static PARSE_ERROR="PARSE_ERROR";code;statusCode;request;response;details;constructor(t,r={}){super(t),this.name="RestError",this.code=r.code,this.statusCode=r.statusCode,Object.defineProperty(this,"request",{value:r.request,enumerable:!1}),Object.defineProperty(this,"response",{value:r.response,enumerable:!1});const n=this.request?.agent?{maxFreeSockets:this.request.agent.maxFreeSockets,maxSockets:this.request.agent.maxSockets}:void 0;Object.defineProperty(this,To,{value:()=>`RestError: ${this.message} \n ${$o.sanitize({...this,request:{...this.request,agent:n},response:this.response})}`,enumerable:!1}),Object.setPrototypeOf(this,e.prototype)}};const Ro=xo("ts-http-runtime"),Lo={};function Mo(e){return e&&"function"==typeof e.pipe}function Do(e){return!1===e.readable?Promise.resolve():new Promise(t=>{const r=()=>{t(),e.removeListener("close",r),e.removeListener("end",r),e.removeListener("error",r)};e.on("close",r),e.on("end",r),e.on("error",r)})}function jo(e){return e&&"number"==typeof e.byteLength}class Fo extends Ee{loadedBytes=0;progressCallback;_transform(e,t,r){this.push(e),this.loadedBytes+=e.length;try{this.progressCallback({loadedBytes:this.loadedBytes}),r()}catch(e){r(e)}}constructor(e){super(),this.progressCallback=e}}class Uo{cachedHttpAgent;cachedHttpsAgents=new WeakMap;async sendRequest(e){const t=new AbortController;let r,n;if(e.abortSignal){if(e.abortSignal.aborted)throw new io("The operation was aborted. Request has already been canceled.");r=e=>{"abort"===e.type&&t.abort()},e.abortSignal.addEventListener("abort",r)}e.timeout>0&&(n=setTimeout(()=>{const r=new Zs;Ro.info(`request to '${r.sanitizeUrl(e.url)}' timed out. canceling...`),t.abort()},e.timeout));const a=e.headers.get("Accept-Encoding"),i=a?.includes("gzip")||a?.includes("deflate");let s,o="function"==typeof e.body?e.body():e.body;if(o&&!e.headers.has("Content-Length")){const t=function(e){return e?Buffer.isBuffer(e)?e.length:Mo(e)?null:jo(e)?e.byteLength:"string"==typeof e?Buffer.from(e).length:null:0}(o);null!==t&&e.headers.set("Content-Length",t)}try{if(o&&e.onUploadProgress){const t=e.onUploadProgress,r=new Fo(t);r.on("error",e=>{Ro.error("Error in upload progress",e)}),Mo(o)?o.pipe(r):r.end(o),o=r}const r=await this.makeRequest(e,t,o);void 0!==n&&clearTimeout(n);const a=function(e){const t=Co();for(const r of Object.keys(e.headers)){const n=e.headers[r];Array.isArray(n)?n.length>0&&t.set(r,n[0]):n&&t.set(r,n)}return t}(r),l={status:r.statusCode??0,headers:a,request:e};if("HEAD"===e.method)return r.resume(),l;s=i?function(e,t){const r=t.get("Content-Encoding");if("gzip"===r){const t=xe.createGunzip();return e.pipe(t),t}if("deflate"===r){const t=xe.createInflate();return e.pipe(t),t}return e}(r,a):r;const u=e.onDownloadProgress;if(u){const e=new Fo(u);e.on("error",e=>{Ro.error("Error in download progress",e)}),s.pipe(e),s=e}return e.streamResponseStatusCodes?.has(Number.POSITIVE_INFINITY)||e.streamResponseStatusCodes?.has(l.status)?l.readableStreamBody=s:l.bodyAsText=await(c=s,new Promise((e,t)=>{const r=[];c.on("data",e=>{Buffer.isBuffer(e)?r.push(e):r.push(Buffer.from(e))}),c.on("end",()=>{e(Buffer.concat(r).toString("utf8"))}),c.on("error",e=>{t(e&&"AbortError"===e?.name?e:new zo(`Error reading response as text: ${e.message}`,{code:zo.PARSE_ERROR}))})})),l}finally{if(e.abortSignal&&r){let t=Promise.resolve();Mo(o)&&(t=Do(o));let n=Promise.resolve();Mo(s)&&(n=Do(s)),Promise.all([t,n]).then(()=>{r&&e.abortSignal?.removeEventListener("abort",r)}).catch(e=>{Ro.warning("Error when cleaning up abortListener on httpRequest",e)})}}var c}makeRequest(e,t,r){const n=new URL(e.url),a="https:"!==n.protocol;if(a&&!e.allowInsecureConnection)throw new Error(`Cannot connect to ${e.url} while allowInsecureConnection is false.`);const i={agent:e.agent??this.getOrCreateAgent(e,a),hostname:n.hostname,path:`${n.pathname}${n.search}`,port:n.port,method:e.method,headers:e.headers.toJSON({preserveCase:!0}),...e.requestOverrides};return new Promise((n,s)=>{const o=a?Ne.request(i,n):ke.request(i,n);o.once("error",t=>{s(new zo(t.message,{code:t.code??zo.REQUEST_SEND_ERROR,request:e}))}),t.signal.addEventListener("abort",()=>{const e=new io("The operation was aborted. Rejecting from abort signal callback while making request.");o.destroy(e),s(e)}),r&&Mo(r)?r.pipe(o):r?"string"==typeof r||Buffer.isBuffer(r)?o.end(r):jo(r)?o.end(ArrayBuffer.isView(r)?Buffer.from(r.buffer):Buffer.from(r)):(Ro.error("Unrecognized body type",r),s(new zo("Unrecognized body type"))):o.end()})}getOrCreateAgent(e,t){const r=e.disableKeepAlive;if(t)return r?Ne.globalAgent:(this.cachedHttpAgent||(this.cachedHttpAgent=new Ne.Agent({keepAlive:!0})),this.cachedHttpAgent);{if(r&&!e.tlsSettings)return ke.globalAgent;const t=e.tlsSettings??Lo;let n=this.cachedHttpsAgents.get(t);return n&&n.options.keepAlive===!r||(Ro.info("No cached TLS Agent exist, creating a new Agent"),n=new ke.Agent({keepAlive:!r,...t}),this.cachedHttpsAgents.set(t,n)),n}}}function qo(){return new Uo}const Bo="redirectPolicy",Vo=["GET","HEAD"];function Go(e={}){const{maxRetries:t=20}=e;return{name:Bo,async sendRequest(e,r){const n=await r(e);return Ho(r,n,t)}}}async function Ho(e,t,r,n=0){const{request:a,status:i,headers:s}=t,o=s.get("location");if(o&&(300===i||301===i&&Vo.includes(a.method)||302===i&&Vo.includes(a.method)||303===i&&"POST"===a.method||307===i)&&n<r){const t=new URL(o,a.url);a.url=t.toString(),303===i&&(a.method="GET",a.headers.delete("Content-Length"),delete a.body),a.headers.delete("Authorization");const s=await e(a);return Ho(e,s,r,n+1)}return t}function Ko(e,t,r){return new Promise((n,a)=>{let i,s;const o=()=>a(new io(r?.abortErrorMsg?r?.abortErrorMsg:"The operation was aborted.")),c=()=>{r?.abortSignal&&s&&r.abortSignal.removeEventListener("abort",s)};if(s=()=>(i&&clearTimeout(i),c(),o()),r?.abortSignal&&r.abortSignal.aborted)return o();i=setTimeout(()=>{c(),n(t)},e),r?.abortSignal&&r.abortSignal.addEventListener("abort",s)})}function Wo(e,t){const r=e.headers.get(t);if(!r)return;const n=Number(r);return Number.isNaN(n)?void 0:n}const Zo="Retry-After",Jo=["retry-after-ms","x-ms-retry-after-ms",Zo];function Yo(e){if(e&&[429,503].includes(e.status))try{for(const t of Jo){const r=Wo(e,t);if(0===r||r){return r*(t===Zo?1e3:1)}}const t=e.headers.get(Zo);if(!t)return;const r=Date.parse(t)-Date.now();return Number.isFinite(r)?Math.max(0,r):void 0}catch{return}}function Qo(e={}){const t=e.retryDelayInMs??1e3,r=e.maxRetryDelayInMs??64e3;return{name:"exponentialRetryStrategy",retry({retryCount:n,response:a,responseError:i}){const s=function(e){if(!e)return!1;return"ETIMEDOUT"===e.code||"ESOCKETTIMEDOUT"===e.code||"ECONNREFUSED"===e.code||"ECONNRESET"===e.code||"ENOENT"===e.code||"ENOTFOUND"===e.code}(i),o=s&&e.ignoreSystemErrors,c=function(e){return Boolean(e&&void 0!==e.status&&(e.status>=500||408===e.status)&&501!==e.status&&505!==e.status)}(a),l=c&&e.ignoreHttpStatusCodes,u=a&&(function(e){return Number.isFinite(Yo(e))}(a)||!c);return u||l||o?{skipStrategy:!0}:!i||s||c?js(n,{retryDelayInMs:t,maxRetryDelayInMs:r}):{errorToThrow:i}}}}const Xo=xo("ts-http-runtime retryPolicy");function ec(e,t={maxRetries:3}){const r=t.logger||Xo;return{name:"retryPolicy",async sendRequest(n,a){let i,s,o=-1;e:for(;;){o+=1,i=void 0,s=void 0;try{r.info(`Retry ${o}: Attempting to send request`,n.requestId),i=await a(n),r.info(`Retry ${o}: Received a response from request`,n.requestId)}catch(e){if(r.error(`Retry ${o}: Received an error from request`,n.requestId),s=e,!e||"RestError"!==s.name)throw e;i=s.response}if(n.abortSignal?.aborted){r.error(`Retry ${o}: Request aborted.`);throw new io}if(o>=(t.maxRetries??3)){if(r.info(`Retry ${o}: Maximum retries reached. Returning the last received response, or throwing the last received error.`),s)throw s;if(i)return i;throw new Error("Maximum retries reached with no response or error to throw")}r.info(`Retry ${o}: Processing ${e.length} retry strategies.`);t:for(const t of e){const e=t.logger||r;e.info(`Retry ${o}: Processing retry strategy ${t.name}.`);const a=t.retry({retryCount:o,response:i,responseError:s});if(a.skipStrategy){e.info(`Retry ${o}: Skipped.`);continue t}const{errorToThrow:c,retryAfterInMs:l,redirectTo:u}=a;if(c)throw e.error(`Retry ${o}: Retry strategy ${t.name} throws error:`,c),c;if(l||0===l){e.info(`Retry ${o}: Retry strategy ${t.name} retries after ${l}`),await Ko(l,void 0,{abortSignal:n.abortSignal});continue e}if(u){e.info(`Retry ${o}: Retry strategy ${t.name} redirects to ${u}`),n.url=u;continue e}}if(s)throw r.info("None of the retry strategies could work with the received error. Throwing it."),s;if(i)return r.info("None of the retry strategies could work with the received response. Returning it."),i}}}}function tc(){return{name:"formDataPolicy",async sendRequest(e,t){if(Vs&&"undefined"!=typeof FormData&&e.body instanceof FormData&&(e.formData=function(e){const t={};for(const[r,n]of e.entries())t[r]??=[],t[r].push(n);return t}(e.body),e.body=void 0),e.formData){const t=e.headers.get("Content-Type");t&&-1!==t.indexOf("application/x-www-form-urlencoded")?e.body=function(e){const t=new URLSearchParams;for(const[r,n]of Object.entries(e))if(Array.isArray(n))for(const e of n)t.append(r,e.toString());else t.append(r,n.toString());return t.toString()}(e.formData):await async function(e,t){const r=t.headers.get("Content-Type");if(r&&!r.startsWith("multipart/form-data"))return;t.headers.set("Content-Type",r??"multipart/form-data");const n=[];for(const[t,r]of Object.entries(e))for(const e of Array.isArray(r)?r:[r])if("string"==typeof e)n.push({headers:Co({"Content-Disposition":`form-data; name="${t}"`}),body:Gs(e,"utf-8")});else{if(null==e||"object"!=typeof e)throw new Error(`Unexpected value for key ${t}: ${e}. Value should be serialized to string first.`);{const r=e.name||"blob",a=Co();a.set("Content-Disposition",`form-data; name="${t}"; filename="${r}"`),a.set("Content-Type",e.type||"application/octet-stream"),n.push({headers:a,body:e})}}t.multipartBody={parts:n}}(e.formData,e),e.formData=void 0}return t(e)}}}var rc,nc,ac,ic,sc,oc={},cc={exports:{}},lc={exports:{}};function uc(){if(nc)return rc;nc=1;var e=1e3,t=60*e,r=60*t,n=24*r,a=7*n,i=365.25*n;function s(e,t,r,n){var a=t>=1.5*r;return Math.round(e/r)+" "+n+(a?"s":"")}return rc=function(o,c){c=c||{};var l=typeof o;if("string"===l&&o.length>0)return function(s){if(s=String(s),s.length>100)return;var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(s);if(!o)return;var c=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*i;case"weeks":case"week":case"w":return c*a;case"days":case"day":case"d":return c*n;case"hours":case"hour":case"hrs":case"hr":case"h":return c*r;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(o);if("number"===l&&isFinite(o))return c.long?function(a){var i=Math.abs(a);if(i>=n)return s(a,i,n,"day");if(i>=r)return s(a,i,r,"hour");if(i>=t)return s(a,i,t,"minute");if(i>=e)return s(a,i,e,"second");return a+" ms"}(o):function(a){var i=Math.abs(a);if(i>=n)return Math.round(a/n)+"d";if(i>=r)return Math.round(a/r)+"h";if(i>=t)return Math.round(a/t)+"m";if(i>=e)return Math.round(a/e)+"s";return a+"ms"}(o);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(o))},rc}function dc(){if(ic)return ac;return ic=1,ac=function(e){function t(e){let n,a,i,s=null;function o(...e){if(!o.enabled)return;const r=o,a=Number(new Date),i=a-(n||a);r.diff=i,r.prev=n,r.curr=a,n=a,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let s=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(n,a)=>{if("%%"===n)return"%";s++;const i=t.formatters[a];if("function"==typeof i){const t=e[s];n=i.call(r,t),e.splice(s,1),s--}return n}),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return o.namespace=e,o.useColors=t.useColors(),o.color=t.selectColor(e),o.extend=r,o.destroy=t.destroy,Object.defineProperty(o,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(a!==t.namespaces&&(a=t.namespaces,i=t.enabled(e)),i),set:e=>{s=e}}),"function"==typeof t.init&&t.init(o),o}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e,t){let r=0,n=0,a=-1,i=0;for(;r<e.length;)if(n<t.length&&(t[n]===e[r]||"*"===t[n]))"*"===t[n]?(a=n,i=r,n++):(r++,n++);else{if(-1===a)return!1;n=a+1,i++,r=i}for(;n<t.length&&"*"===t[n];)n++;return n===t.length}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(n(e,r))return!1;for(const r of t.names)if(n(e,r))return!0;return!1},t.humanize=uc(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(r=>{t[r]=e[r]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t},ac}var pc,mc,hc,fc,gc={exports:{}};function yc(){return hc||(hc=1,function(e,t){const r=ye,n=ve;t.init=function(e){e.inspectOpts={};const r=Object.keys(t.inspectOpts);for(let n=0;n<r.length;n++)e.inspectOpts[r[n]]=t.inspectOpts[r[n]]},t.log=function(...e){return process.stderr.write(n.formatWithOptions(t.inspectOpts,...e)+"\n")},t.formatArgs=function(r){const{namespace:n,useColors:a}=this;if(a){const t=this.color,a="[3"+(t<8?t:"8;5;"+t),i=` ${a};1m${n} `;r[0]=i+r[0].split("\n").join("\n"+i),r.push(a+"m+"+e.exports.humanize(this.diff)+"")}else r[0]=function(){if(t.inspectOpts.hideDate)return"";return(new Date).toISOString()+" "}()+n+" "+r[0]},t.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},t.load=function(){return process.env.DEBUG},t.useColors=function(){return"colors"in t.inspectOpts?Boolean(t.inspectOpts.colors):r.isatty(process.stderr.fd)},t.destroy=n.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{const e=function(){if(mc)return pc;mc=1;const e=function(){const e=/(Chrome|Chromium)\/(?<chromeVersion>\d+)\./.exec(navigator.userAgent);if(e)return Number.parseInt(e.groups.chromeVersion,10)}()>=69&&{level:1,hasBasic:!0,has256:!1,has16m:!1};return pc={stdout:e,stderr:e}}();e&&(e.stderr||e).level>=2&&(t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(e){}t.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{const r=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase());let n=process.env[t];return n=!!/^(yes|on|true|enabled)$/i.test(n)||!/^(no|off|false|disabled)$/i.test(n)&&("null"===n?null:Number(n)),e[r]=n,e},{}),e.exports=dc()(t);const{formatters:a}=e.exports;a.o=function(e){return this.inspectOpts.colors=this.useColors,n.inspect(e,this.inspectOpts).split("\n").map(e=>e.trim()).join(" ")},a.O=function(e){return this.inspectOpts.colors=this.useColors,n.inspect(e,this.inspectOpts)}}(gc,gc.exports)),gc.exports}function vc(){return fc||(fc=1,"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?cc.exports=(sc||(sc=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,a=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(n++,"%c"===e&&(a=n))}),t.splice(a,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=dc()(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(lc,lc.exports)),lc.exports):cc.exports=yc()),cc.exports}var bc,_c,wc={},Sc={};function Nc(){return _c||(_c=1,function(e){var t=wc&&wc.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var a=Object.getOwnPropertyDescriptor(t,r);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,a)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=wc&&wc.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=wc&&wc.__importStar||function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var a in e)"default"!==a&&Object.prototype.hasOwnProperty.call(e,a)&&t(n,e,a);return r(n,e),n},a=wc&&wc.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||t(r,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),e.Agent=void 0;const i=n(he),s=n(be),o=_e;a(function(){if(bc)return Sc;bc=1;var e=Sc&&Sc.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var a=Object.getOwnPropertyDescriptor(t,r);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,a)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),t=Sc&&Sc.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=Sc&&Sc.__importStar||function(r){if(r&&r.__esModule)return r;var n={};if(null!=r)for(var a in r)"default"!==a&&Object.prototype.hasOwnProperty.call(r,a)&&e(n,r,a);return t(n,r),n};Object.defineProperty(Sc,"__esModule",{value:!0}),Sc.req=Sc.json=Sc.toBuffer=void 0;const n=r(be),a=r(_e);async function i(e){let t=0;const r=[];for await(const n of e)t+=n.length,r.push(n);return Buffer.concat(r,t)}return Sc.toBuffer=i,Sc.json=async function(e){const t=(await i(e)).toString("utf8");try{return JSON.parse(t)}catch(e){const r=e;throw r.message+=` (input: ${t})`,r}},Sc.req=function(e,t={}){const r=(("string"==typeof e?e:e.href).startsWith("https:")?a:n).request(e,t),i=new Promise((e,t)=>{r.once("response",e).once("error",t).end()});return r.then=i.then.bind(i),r},Sc}(),e);const c=Symbol("AgentBaseInternalState");class l extends s.Agent{constructor(e){super(e),this[c]={}}isSecureEndpoint(e){if(e){if("boolean"==typeof e.secureEndpoint)return e.secureEndpoint;if("string"==typeof e.protocol)return"https:"===e.protocol}const{stack:t}=new Error;return"string"==typeof t&&t.split("\n").some(e=>-1!==e.indexOf("(https.js:")||-1!==e.indexOf("node:https:"))}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);const t=new i.Socket({writable:!1});return this.sockets[e].push(t),this.totalSocketCount++,t}decrementSockets(e,t){if(!this.sockets[e]||null===t)return;const r=this.sockets[e],n=r.indexOf(t);-1!==n&&(r.splice(n,1),this.totalSocketCount--,0===r.length&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?o.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,t,r){const n={...t,secureEndpoint:this.isSecureEndpoint(t)},a=this.getName(n),i=this.incrementSockets(a);Promise.resolve().then(()=>this.connect(e,n)).then(o=>{if(this.decrementSockets(a,i),o instanceof s.Agent)try{return o.addRequest(e,n)}catch(e){return r(e)}this[c].currentSocket=o,super.createSocket(e,t,r)},e=>{this.decrementSockets(a,i),r(e)})}createConnection(){const e=this[c].currentSocket;if(this[c].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[c].defaultPort??("https:"===this.protocol?443:80)}set defaultPort(e){this[c]&&(this[c].defaultPort=e)}get protocol(){return this[c].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[c]&&(this[c].protocol=e)}}e.Agent=l}(wc)),wc}var kc,xc,Ec={};function Pc(){if(kc)return Ec;kc=1;var e=Ec&&Ec.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ec,"__esModule",{value:!0}),Ec.parseProxyResponse=void 0;const t=(0,e(vc()).default)("https-proxy-agent:parse-proxy-response");return Ec.parseProxyResponse=function(e){return new Promise((r,n)=>{let a=0;const i=[];function s(){const c=e.read();c?function(c){i.push(c),a+=c.length;const l=Buffer.concat(i,a),u=l.indexOf("\r\n\r\n");if(-1===u)return t("have not received end of HTTP headers yet..."),void s();const d=l.slice(0,u).toString("ascii").split("\r\n"),p=d.shift();if(!p)return e.destroy(),n(new Error("No header received from proxy CONNECT response"));const m=p.split(" "),h=+m[1],f=m.slice(2).join(" "),g={};for(const t of d){if(!t)continue;const r=t.indexOf(":");if(-1===r)return e.destroy(),n(new Error(`Invalid header from proxy CONNECT response: "${t}"`));const a=t.slice(0,r).toLowerCase(),i=t.slice(r+1).trimStart(),s=g[a];"string"==typeof s?g[a]=[s,i]:Array.isArray(s)?s.push(i):g[a]=i}t("got proxy server response: %o %o",p,g),o(),r({connect:{statusCode:h,statusText:f,headers:g},buffered:l})}(c):e.once("readable",s)}function o(){e.removeListener("end",c),e.removeListener("error",l),e.removeListener("readable",s)}function c(){o(),t("onend"),n(new Error("Proxy connection ended before receiving CONNECT response"))}function l(e){o(),t("onerror %o",e),n(e)}e.on("error",l),e.on("end",c),s()})},Ec}var Cc,Ac=function(){if(xc)return oc;xc=1;var e=oc&&oc.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var a=Object.getOwnPropertyDescriptor(t,r);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,a)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),t=oc&&oc.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=oc&&oc.__importStar||function(r){if(r&&r.__esModule)return r;var n={};if(null!=r)for(var a in r)"default"!==a&&Object.prototype.hasOwnProperty.call(r,a)&&e(n,r,a);return t(n,r),n},n=oc&&oc.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(oc,"__esModule",{value:!0}),oc.HttpsProxyAgent=void 0;const a=r(he),i=r(fe),s=n(ge),o=n(vc()),c=Nc(),l=we,u=Pc(),d=(0,o.default)("https-proxy-agent"),p=e=>void 0===e.servername&&e.host&&!a.isIP(e.host)?{...e,servername:e.host}:e;class m extends c.Agent{constructor(e,t){super(t),this.options={path:void 0},this.proxy="string"==typeof e?new l.URL(e):e,this.proxyHeaders=t?.headers??{},d("Creating new HttpsProxyAgent instance: %o",this.proxy.href);const r=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),n=this.proxy.port?parseInt(this.proxy.port,10):"https:"===this.proxy.protocol?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...t?f(t,"headers"):null,host:r,port:n}}async connect(e,t){const{proxy:r}=this;if(!t.host)throw new TypeError('No "host" provided');let n;"https:"===r.protocol?(d("Creating `tls.Socket`: %o",this.connectOpts),n=i.connect(p(this.connectOpts))):(d("Creating `net.Socket`: %o",this.connectOpts),n=a.connect(this.connectOpts));const o="function"==typeof this.proxyHeaders?this.proxyHeaders():{...this.proxyHeaders},c=a.isIPv6(t.host)?`[${t.host}]`:t.host;let l=`CONNECT ${c}:${t.port} HTTP/1.1\r\n`;if(r.username||r.password){const e=`${decodeURIComponent(r.username)}:${decodeURIComponent(r.password)}`;o["Proxy-Authorization"]=`Basic ${Buffer.from(e).toString("base64")}`}o.Host=`${c}:${t.port}`,o["Proxy-Connection"]||(o["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(const e of Object.keys(o))l+=`${e}: ${o[e]}\r\n`;const m=(0,u.parseProxyResponse)(n);n.write(`${l}\r\n`);const{connect:g,buffered:y}=await m;if(e.emit("proxyConnect",g),this.emit("proxyConnect",g,e),200===g.statusCode)return e.once("socket",h),t.secureEndpoint?(d("Upgrading socket connection to TLS"),i.connect({...f(p(t),"host","path","port"),socket:n})):n;n.destroy();const v=new a.Socket({writable:!1});return v.readable=!0,e.once("socket",e=>{d("Replaying proxy buffer for failed request"),(0,s.default)(e.listenerCount("data")>0),e.push(y),e.push(null)}),v}}function h(e){e.resume()}function f(e,...t){const r={};let n;for(n in e)t.includes(n)||(r[n]=e[n]);return r}return m.protocols=["http","https"],oc.HttpsProxyAgent=m,oc}(),Ic={};var Oc=function(){if(Cc)return Ic;Cc=1;var e=Ic&&Ic.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var a=Object.getOwnPropertyDescriptor(t,r);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,a)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),t=Ic&&Ic.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=Ic&&Ic.__importStar||function(r){if(r&&r.__esModule)return r;var n={};if(null!=r)for(var a in r)"default"!==a&&Object.prototype.hasOwnProperty.call(r,a)&&e(n,r,a);return t(n,r),n},n=Ic&&Ic.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ic,"__esModule",{value:!0}),Ic.HttpProxyAgent=void 0;const a=r(he),i=r(fe),s=n(vc()),o=Se,c=Nc(),l=we,u=(0,s.default)("http-proxy-agent");class d extends c.Agent{constructor(e,t){super(t),this.proxy="string"==typeof e?new l.URL(e):e,this.proxyHeaders=t?.headers??{},u("Creating new HttpProxyAgent instance: %o",this.proxy.href);const r=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),n=this.proxy.port?parseInt(this.proxy.port,10):"https:"===this.proxy.protocol?443:80;this.connectOpts={...t?p(t,"headers"):null,host:r,port:n}}addRequest(e,t){e._header=null,this.setRequestProps(e,t),super.addRequest(e,t)}setRequestProps(e,t){const{proxy:r}=this,n=`${t.secureEndpoint?"https:":"http:"}//${e.getHeader("host")||"localhost"}`,a=new l.URL(e.path,n);80!==t.port&&(a.port=String(t.port)),e.path=String(a);const i="function"==typeof this.proxyHeaders?this.proxyHeaders():{...this.proxyHeaders};if(r.username||r.password){const e=`${decodeURIComponent(r.username)}:${decodeURIComponent(r.password)}`;i["Proxy-Authorization"]=`Basic ${Buffer.from(e).toString("base64")}`}i["Proxy-Connection"]||(i["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(const t of Object.keys(i)){const r=i[t];r&&e.setHeader(t,r)}}async connect(e,t){let r,n,s;return e._header=null,e.path.includes("://")||this.setRequestProps(e,t),u("Regenerating stored HTTP header string for request"),e._implicitHeader(),e.outputData&&e.outputData.length>0&&(u("Patching connection write() output buffer with updated header"),r=e.outputData[0].data,n=r.indexOf("\r\n\r\n")+4,e.outputData[0].data=e._header+r.substring(n),u("Output buffer: %o",e.outputData[0].data)),"https:"===this.proxy.protocol?(u("Creating `tls.Socket`: %o",this.connectOpts),s=i.connect(this.connectOpts)):(u("Creating `net.Socket`: %o",this.connectOpts),s=a.connect(this.connectOpts)),await(0,o.once)(s,"connect"),s}}function p(e,...t){const r={};let n;for(n in e)t.includes(n)||(r[n]=e[n]);return r}return d.protocols=["http","https"],Ic.HttpProxyAgent=d,Ic}();const Tc=[];let $c=!1;const zc=new Map;function Rc(e){return process.env[e]?process.env[e]:process.env[e.toLowerCase()]?process.env[e.toLowerCase()]:void 0}function Lc(){const e=function(){if(!process)return;const e=Rc("HTTPS_PROXY"),t=Rc("ALL_PROXY"),r=Rc("HTTP_PROXY");return e||t||r}();return e?new URL(e):void 0}function Mc(e){let t;try{t=new URL(e.host)}catch{throw new Error(`Expecting a valid host string in proxy settings, but found "${e.host}".`)}return t.port=String(e.port),e.username&&(t.username=e.username),e.password&&(t.password=e.password),t}function Dc(e,t,r){if(e.agent)return;const n="https:"!==new URL(e.url).protocol;e.tlsSettings&&Ro.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored.");const a=e.headers.toJSON();n?(t.httpProxyAgent||(t.httpProxyAgent=new Oc.HttpProxyAgent(r,{headers:a})),e.agent=t.httpProxyAgent):(t.httpsProxyAgent||(t.httpsProxyAgent=new Ac.HttpsProxyAgent(r,{headers:a})),e.agent=t.httpsProxyAgent)}function jc(e,t){$c||Tc.push(...function(){const e=Rc("NO_PROXY");return $c=!0,e?e.split(",").map(e=>e.trim()).filter(e=>e.length):[]}());const r=e?Mc(e):Lc(),n={};return{name:"proxyPolicy",sendRequest:async(e,t)=>(e.proxySettings||!r||function(e,t,r){if(0===t.length)return!1;const n=new URL(e).hostname;if(r?.has(n))return r.get(n);let a=!1;for(const e of t)"."===e[0]?(n.endsWith(e)||n.length===e.length-1&&n===e.slice(1))&&(a=!0):n===e&&(a=!0);return r?.set(n,a),a}(e.url,Tc,zc)?e.proxySettings&&Dc(e,n,Mc(e.proxySettings)):Dc(e,n,r),t(e))}}function Fc(e){return"function"==typeof e.stream}async function*Uc(){const e=this.getReader();try{for(;;){const{done:t,value:r}=await e.read();if(t)return;yield r}}finally{e.releaseLock()}}function qc(e){return e instanceof ReadableStream?((t=e)[Symbol.asyncIterator]||(t[Symbol.asyncIterator]=Uc.bind(t)),t.values||(t.values=Uc.bind(t)),me.fromWeb(e)):e;var t}function Bc(e){return e instanceof Uint8Array?me.from(Buffer.from(e)):Fc(e)?qc(e.stream()):qc(e)}function Vc(e){let t="";for(const[r,n]of e)t+=`${r}: ${n}\r\n`;return t}function Gc(e){return e instanceof Uint8Array?e.byteLength:Fc(e)?-1===e.size?void 0:e.size:void 0}async function Hc(e,t,r){const n=[Gs(`--${r}`,"utf-8"),...t.flatMap(e=>[Gs("\r\n","utf-8"),Gs(Vc(e.headers),"utf-8"),Gs("\r\n","utf-8"),e.body,Gs(`\r\n--${r}`,"utf-8")]),Gs("--\r\n\r\n","utf-8")],a=function(e){let t=0;for(const r of e){const e=Gc(r);if(void 0===e)return;t+=e}return t}(n);a&&e.headers.set("Content-Length",a),e.body=await async function(e){return function(){const t=e.map(e=>"function"==typeof e?e():e).map(Bc);return me.from(async function*(){for(const e of t)for await(const t of e)yield t}())}}(n)}const Kc="multipartPolicy",Wc=new Set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?");function Zc(){return{name:Kc,async sendRequest(e,t){if(!e.multipartBody)return t(e);if(e.body)throw new Error("multipartBody and regular body cannot be set at the same time");let r=e.multipartBody.boundary;const n=e.headers.get("Content-Type")??"multipart/mixed",a=n.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/);if(!a)throw new Error(`Got multipart request body, but content-type header was not multipart: ${n}`);const[,i,s]=a;if(s&&r&&s!==r)throw new Error(`Multipart boundary was specified as ${s} in the header, but got ${r} in the request body`);return r??=s,r?function(e){if(e.length>70)throw new Error(`Multipart boundary "${e}" exceeds maximum length of 70 characters`);if(Array.from(e).some(e=>!Wc.has(e)))throw new Error(`Multipart boundary "${e}" contains invalid characters`)}(r):r=`----AzSDKFormBoundary${Bs()}`,e.headers.set("Content-Type",`${i}; boundary=${r}`),await Hc(e,e.multipartBody.parts,r),e.multipartBody=void 0,t(e)}}}function Jc(){return Oo.create()}const Yc=No({logLevelEnvVarName:"AZURE_LOG_LEVEL",namespace:"azure"});function Qc(e){return Yc.createClientLogger(e)}const Xc=Qc("core-rest-pipeline");function el(e={}){return function(e={}){const t=e.logger??Ro.info,r=new Zs({additionalAllowedHeaderNames:e.additionalAllowedHeaderNames,additionalAllowedQueryParameters:e.additionalAllowedQueryParameters});return{name:"logPolicy",async sendRequest(e,n){if(!t.enabled)return n(e);t(`Request: ${r.sanitize(e)}`);const a=await n(e);return t(`Response status code: ${a.status}`),t(`Headers: ${r.sanitize(a.headers)}`),a}}}({logger:Xc.info,...e})}const tl=Bo;const rl="1.22.1";async function nl(e){const t=new Map;t.set("core-rest-pipeline",rl),await async function(e){if(de&&de.versions){const t=de.versions;t.bun?e.set("Bun",t.bun):t.deno?e.set("Deno",t.deno):t.node&&e.set("Node",t.node)}e.set("OS",`(${ee.arch()}-${ee.type()}-${ee.release()})`)}(t);const r=function(e){const t=[];for(const[r,n]of e){const e=n?`${r}/${n}`:r;t.push(e)}return t.join(" ")}(t);return e?`${e} ${r}`:r}const al="User-Agent";const il=Symbol("rawContent");function sl(e){return"function"==typeof e[il]}function ol(e){return sl(e)?e[il]():e}const cl=Kc;function ll(e={}){return function(e={}){return{name:"defaultRetryPolicy",sendRequest:ec([{name:"throttlingRetryStrategy",retry({response:e}){const t=Yo(e);return Number.isFinite(t)?{retryAfterInMs:t}:{skipStrategy:!0}}},Qo(e)],{maxRetries:e.maxRetries??3}).sendRequest}}(e)}const ul={span:Symbol.for("@azure/core-tracing span"),namespace:Symbol.for("@azure/core-tracing namespace")};function dl(e={}){let t=new pl(e.parentContext);return e.span&&(t=t.setValue(ul.span,e.span)),e.namespace&&(t=t.setValue(ul.namespace,e.namespace)),t}class pl{_contextMap;constructor(e){this._contextMap=e instanceof pl?new Map(e._contextMap):new Map}setValue(e,t){const r=new pl(this);return r._contextMap.set(e,t),r}getValue(e){return this._contextMap.get(e)}deleteValue(e){const t=new pl(this);return t._contextMap.delete(e),t}}var ml,hl={};const fl=(ml||(ml=1,Object.defineProperty(hl,"__esModule",{value:!0}),hl.state=void 0,hl.state={instrumenterImplementation:void 0}),hl).state;function gl(){return fl.instrumenterImplementation||(fl.instrumenterImplementation={createRequestHeaders:()=>({}),parseTraceparentHeader:()=>{},startSpan:(e,t)=>({span:{end:()=>{},isRecording:()=>!1,recordException:()=>{},setAttribute:()=>{},setStatus:()=>{},addEvent:()=>{}},tracingContext:dl({parentContext:t.tracingContext})}),withContext:(e,t,...r)=>t(...r)}),fl.instrumenterImplementation}function yl(e){const{namespace:t,packageName:r,packageVersion:n}=e;function a(e,a,i){const s=gl().startSpan(e,{...i,packageName:r,packageVersion:n,tracingContext:a?.tracingOptions?.tracingContext});let o=s.tracingContext;const c=s.span;o.getValue(ul.namespace)||(o=o.setValue(ul.namespace,t)),c.setAttribute("az.namespace",o.getValue(ul.namespace));return{span:c,updatedOptions:Object.assign({},a,{tracingOptions:{...a?.tracingOptions,tracingContext:o}})}}function i(e,t,...r){return gl().withContext(e,t,...r)}return{startSpan:a,withSpan:async function(e,t,r,n){const{span:s,updatedOptions:o}=a(e,t,n);try{const e=await i(o.tracingOptions.tracingContext,()=>Promise.resolve(r(o,s)));return s.setStatus({status:"success"}),e}catch(e){throw s.setStatus({status:"error",error:e}),e}finally{s.end()}},withContext:i,parseTraceparentHeader:function(e){return gl().parseTraceparentHeader(e)},createRequestHeaders:function(e){return gl().createRequestHeaders(e)}}}const vl=zo;function bl(e){return function(e){return e instanceof zo||Us(e)&&"RestError"===e.name}(e)}function _l(e={}){const t=nl(e.userAgentPrefix),r=new Zs({additionalAllowedQueryParameters:e.additionalAllowedQueryParameters}),n=function(){try{return yl({namespace:"",packageName:"@azure/core-rest-pipeline",packageVersion:rl})}catch(e){return void Xc.warning(`Error when creating the TracingClient: ${Qs(e)}`)}}();return{name:"tracingPolicy",async sendRequest(e,a){if(!n)return a(e);const i=await t,s={"http.url":r.sanitizeUrl(e.url),"http.method":e.method,"http.user_agent":i,requestId:e.requestId};i&&(s["http.user_agent"]=i);const{span:o,tracingContext:c}=function(e,t,r){try{const{span:n,updatedOptions:a}=e.startSpan(`HTTP ${t.method}`,{tracingOptions:t.tracingOptions},{spanKind:"client",spanAttributes:r});if(!n.isRecording())return void n.end();const i=e.createRequestHeaders(a.tracingOptions.tracingContext);for(const[e,r]of Object.entries(i))t.headers.set(e,r);return{span:n,tracingContext:a.tracingOptions.tracingContext}}catch(e){return void Xc.warning(`Skipping creating a tracing span due to an error: ${Qs(e)}`)}}(n,e,s)??{};if(!o||!c)return a(e);try{const t=await n.withContext(c,a,e);return function(e,t){try{e.setAttribute("http.status_code",t.status);const r=t.headers.get("x-ms-request-id");r&&e.setAttribute("serviceRequestId",r),t.status>=400&&e.setStatus({status:"error"}),e.end()}catch(e){Xc.warning(`Skipping tracing span processing due to an error: ${Qs(e)}`)}}(o,t),t}catch(e){throw function(e,t){try{e.setStatus({status:"error",error:Xs(t)?t:void 0}),bl(t)&&t.statusCode&&e.setAttribute("http.status_code",t.statusCode),e.end()}catch(e){Xc.warning(`Skipping tracing span processing due to an error: ${Qs(e)}`)}}(o,e),e}}}}function wl(e){if(e instanceof AbortSignal)return{abortSignal:e};if(e.aborted)return{abortSignal:AbortSignal.abort(e.reason)};const t=new AbortController;let r=!0;function n(){r&&(e.removeEventListener("abort",a),r=!1)}function a(){t.abort(e.reason),n()}return e.addEventListener("abort",a),{abortSignal:t.signal,cleanup:n}}function Sl(e){const t=Jc();return eo&&(e.agent&&t.addPolicy(function(e){return{name:"agentPolicy",sendRequest:async(t,r)=>(t.agent||(t.agent=e),r(t))}}(e.agent)),e.tlsOptions&&t.addPolicy(function(e){return{name:"tlsPolicy",sendRequest:async(t,r)=>(t.tlsSettings||(t.tlsSettings=e),r(t))}}(e.tlsOptions)),t.addPolicy(jc(e.proxyOptions)),t.addPolicy({name:"decompressResponsePolicy",sendRequest:async(e,t)=>("HEAD"!==e.method&&e.headers.set("Accept-Encoding","gzip,deflate"),t(e))})),t.addPolicy({name:"wrapAbortSignalLikePolicy",sendRequest:async(e,t)=>{if(!e.abortSignal)return t(e);const{abortSignal:r,cleanup:n}=wl(e.abortSignal);e.abortSignal=r;try{return await t(e)}finally{n?.()}}}),t.addPolicy(tc(),{beforePolicies:[cl]}),t.addPolicy(function(e={}){const t=nl(e.userAgentPrefix);return{name:"userAgentPolicy",sendRequest:async(e,r)=>(e.headers.has(al)||e.headers.set(al,await t),r(e))}}(e.userAgentOptions)),t.addPolicy(function(e="x-ms-client-request-id"){return{name:"setClientRequestIdPolicy",sendRequest:async(t,r)=>(t.headers.has(e)||t.headers.set(e,t.requestId),r(t))}}(e.telemetryOptions?.clientRequestIdHeaderName)),t.addPolicy(function(){const e=Zc();return{name:cl,sendRequest:async(t,r)=>{if(t.multipartBody)for(const e of t.multipartBody.parts)sl(e.body)&&(e.body=ol(e.body));return e.sendRequest(t,r)}}}(),{afterPhase:"Deserialize"}),t.addPolicy(ll(e.retryOptions),{phase:"Retry"}),t.addPolicy(_l({...e.userAgentOptions,...e.loggingOptions}),{afterPhase:"Retry"}),eo&&t.addPolicy(function(e={}){return Go(e)}(e.redirectOptions),{afterPhase:"Retry"}),t.addPolicy(el(e.loggingOptions),{afterPhase:"Sign"}),t}function Nl(e){return function(e){return new Ao(e)}(e)}const kl={forcedRefreshWindowInMs:1e3,retryIntervalInMs:3e3,refreshWindowInMs:12e4};function xl(e,t){let r,n=null,a=null;const i={...kl,...t},s={get isRefreshing(){return null!==n},get shouldRefresh(){return!s.isRefreshing&&(!!(a?.refreshAfterTimestamp&&a.refreshAfterTimestamp<Date.now())||(a?.expiresOnTimestamp??0)-i.refreshWindowInMs<Date.now())},get mustRefresh(){return null===a||a.expiresOnTimestamp-i.forcedRefreshWindowInMs<Date.now()}};function o(t,o){if(!s.isRefreshing){n=async function(e,t,r){async function n(){if(!(Date.now()<r)){const t=await e();if(null===t)throw new Error("Failed to refresh access token.");return t}try{return await e()}catch{return null}}let a=await n();for(;null===a;)await Ys(t),a=await n();return a}(()=>e.getToken(t,o),i.retryIntervalInMs,a?.expiresOnTimestamp??Date.now()).then(e=>(n=null,a=e,r=o.tenantId,a)).catch(e=>{throw n=null,a=null,r=void 0,e})}return n}return async(e,t)=>{const n=Boolean(t.claims),i=r!==t.tenantId;n&&(a=null);return i||n||s.mustRefresh?o(e,t):(s.shouldRefresh&&o(e,t),a)}}async function El(e,t){try{return[await t(e),void 0]}catch(e){if(bl(e)&&e.response)return[e.response,e];throw e}}async function Pl(e){const{scopes:t,getAccessToken:r,request:n}=e,a={abortSignal:n.abortSignal,tracingOptions:n.tracingOptions,enableCae:!0},i=await r(t,a);i&&e.request.headers.set("Authorization",`Bearer ${i.token}`)}function Cl(e){return 401===e.status&&e.headers.has("WWW-Authenticate")}async function Al(e,t){const{scopes:r}=e,n=await e.getAccessToken(r,{enableCae:!0,claims:t});return!!n&&(e.request.headers.set("Authorization",`${n.tokenType??"Bearer"} ${n.token}`),!0)}function Il(e){const{credential:t,scopes:r,challengeCallbacks:n}=e,a=e.logger||Xc,i={authorizeRequest:n?.authorizeRequest?.bind(n)??Pl,authorizeRequestOnChallenge:n?.authorizeRequestOnChallenge?.bind(n)},s=t?xl(t):()=>Promise.resolve(null);return{name:"bearerTokenAuthenticationPolicy",async sendRequest(e,t){if(!e.url.toLowerCase().startsWith("https://"))throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs.");let n,o,c;if(await i.authorizeRequest({scopes:Array.isArray(r)?r:[r],request:e,getAccessToken:s,logger:a}),[n,o]=await El(e,t),Cl(n)){let l=Ol(n.headers.get("WWW-Authenticate"));if(l){let i;try{i=atob(l)}catch(e){return a.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${l}`),n}c=await Al({scopes:Array.isArray(r)?r:[r],response:n,request:e,getAccessToken:s,logger:a},i),c&&([n,o]=await El(e,t))}else if(i.authorizeRequestOnChallenge&&(c=await i.authorizeRequestOnChallenge({scopes:Array.isArray(r)?r:[r],request:e,response:n,getAccessToken:s,logger:a}),c&&([n,o]=await El(e,t)),Cl(n)&&(l=Ol(n.headers.get("WWW-Authenticate")),l))){let i;try{i=atob(l)}catch(e){return a.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${l}`),n}c=await Al({scopes:Array.isArray(r)?r:[r],response:n,request:e,getAccessToken:s,logger:a},i),c&&([n,o]=await El(e,t))}}if(o)throw o;return n}}}function Ol(e){if(!e)return;const t=function(e){const t=/(\w+)\s+((?:\w+=(?:"[^"]*"|[^,]*),?\s*)+)/g,r=/(\w+)="([^"]*)"/g,n=[];let a;for(;null!==(a=t.exec(e));){const e=a[1],t=a[2],i={};let s;for(;null!==(s=r.exec(t));)i[s[1]]=s[2];n.push({scheme:e,params:i})}return n}(e);return t.find(e=>"Bearer"===e.scheme&&e.params.claims&&"insufficient_claims"===e.params.error)?.params.claims}const Tl="DisableKeepAlivePolicy";function $l(e){return(e instanceof Buffer?e:Buffer.from(e.buffer)).toString("base64")}function zl(e){return Buffer.from(e,"base64")}const Rl="$",Ll="_";const Ml=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;const Dl=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i;function jl(e,t){const r=e.parsedHeaders;if("HEAD"===e.request.method)return{...r,body:e.parsedBody};const n=t&&t.bodyMapper,a=Boolean(n?.nullable),i=n?.type.name;if("Stream"===i)return{...r,blobBody:e.blobBody,readableStreamBody:e.readableStreamBody};const s="Composite"===i&&n.type.modelProperties||{},o=Object.keys(s).some(e=>""===s[e].serializedName);if("Sequence"===i||o){const t=e.parsedBody??[];for(const r of Object.keys(s))s[r].serializedName&&(t[r]=e.parsedBody?.[r]);if(r)for(const e of Object.keys(r))t[e]=r[e];return!a||e.parsedBody||r||0!==Object.getOwnPropertyNames(s).length?t:null}return function(e){const t={...e.headers,...e.body};return e.hasNullableType&&0===Object.getOwnPropertyNames(t).length?e.shouldWrapBody?{body:null}:null:e.shouldWrapBody?{...e.headers,body:e.body}:t}({body:e.parsedBody,headers:r,hasNullableType:a,shouldWrapBody:(c=e.parsedBody,l=i,"Composite"!==l&&"Dictionary"!==l&&("string"==typeof c||"number"==typeof c||"boolean"==typeof c||null!==l?.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i)||null==c))});var c,l}class Fl{modelMappers;isXML;constructor(e={},t=!1){this.modelMappers=e,this.isXML=t}validateConstraints(e,t,r){const n=(e,n)=>{throw new Error(`"${r}" with value "${t}" should satisfy the constraint "${e}": ${n}.`)};if(e.constraints&&null!=t){const{ExclusiveMaximum:r,ExclusiveMinimum:a,InclusiveMaximum:i,InclusiveMinimum:s,MaxItems:o,MaxLength:c,MinItems:l,MinLength:u,MultipleOf:d,Pattern:p,UniqueItems:m}=e.constraints;if(void 0!==r&&t>=r&&n("ExclusiveMaximum",r),void 0!==a&&t<=a&&n("ExclusiveMinimum",a),void 0!==i&&t>i&&n("InclusiveMaximum",i),void 0!==s&&t<s&&n("InclusiveMinimum",s),void 0!==o&&t.length>o&&n("MaxItems",o),void 0!==c&&t.length>c&&n("MaxLength",c),void 0!==l&&t.length<l&&n("MinItems",l),void 0!==u&&t.length<u&&n("MinLength",u),void 0!==d&&t%d!==0&&n("MultipleOf",d),p){const e="string"==typeof p?new RegExp(p):p;"string"==typeof t&&null!==t.match(e)||n("Pattern",p)}m&&t.some((e,t,r)=>r.indexOf(e)!==t)&&n("UniqueItems",m)}}serialize(e,t,r,n={xml:{}}){const a={xml:{rootName:n.xml.rootName??"",includeRoot:n.xml.includeRoot??!1,xmlCharKey:n.xml.xmlCharKey??Ll}};let i={};const s=e.type.name;r||(r=e.serializedName),null!==s.match(/^Sequence$/i)&&(i=[]),e.isConstant&&(t=e.defaultValue);const{required:o,nullable:c}=e;if(o&&c&&void 0===t)throw new Error(`${r} cannot be undefined.`);if(o&&!c&&null==t)throw new Error(`${r} cannot be null or undefined.`);if(!o&&!1===c&&null===t)throw new Error(`${r} cannot be null.`);if(null==t)i=t;else if(null!==s.match(/^any$/i))i=t;else if(null!==s.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i))i=function(e,t,r){if(null!=r)if(null!==e.match(/^Number$/i)){if("number"!=typeof r)throw new Error(`${t} with value ${r} must be of type number.`)}else if(null!==e.match(/^String$/i)){if("string"!=typeof r.valueOf())throw new Error(`${t} with value "${r}" must be of type string.`)}else if(null!==e.match(/^Uuid$/i)){if("string"!=typeof r.valueOf()||(n=r,!Dl.test(n)))throw new Error(`${t} with value "${r}" must be of type string and a valid uuid.`)}else if(null!==e.match(/^Boolean$/i)){if("boolean"!=typeof r)throw new Error(`${t} with value ${r} must be of type boolean.`)}else if(null!==e.match(/^Stream$/i)){const e=typeof r;if(!("string"===e||"function"==typeof r.pipe||"function"==typeof r.tee||r instanceof ArrayBuffer||ArrayBuffer.isView(r)||("function"==typeof Blob||"object"==typeof Blob)&&r instanceof Blob||"function"===e))throw new Error(`${t} must be a string, Blob, ArrayBuffer, ArrayBufferView, ReadableStream, or () => ReadableStream.`)}var n;return r}(s,r,t);else if(null!==s.match(/^Enum$/i)){i=function(e,t,r){if(!t)throw new Error(`Please provide a set of allowedValues to validate ${e} as an Enum Type.`);if(!t.some(e=>"string"==typeof e.valueOf()?e.toLowerCase()===r.toLowerCase():e===r))throw new Error(`${r} is not a valid value for ${e}. The valid values are: ${JSON.stringify(t)}.`);return r}(r,e.type.allowedValues,t)}else null!==s.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i)?i=function(e,t,r){if(null!=t)if(null!==e.match(/^Date$/i)){if(!(t instanceof Date||"string"==typeof t.valueOf()&&!isNaN(Date.parse(t))))throw new Error(`${r} must be an instanceof Date or a string in ISO8601 format.`);t=t instanceof Date?t.toISOString().substring(0,10):new Date(t).toISOString().substring(0,10)}else if(null!==e.match(/^DateTime$/i)){if(!(t instanceof Date||"string"==typeof t.valueOf()&&!isNaN(Date.parse(t))))throw new Error(`${r} must be an instanceof Date or a string in ISO8601 format.`);t=t instanceof Date?t.toISOString():new Date(t).toISOString()}else if(null!==e.match(/^DateTimeRfc1123$/i)){if(!(t instanceof Date||"string"==typeof t.valueOf()&&!isNaN(Date.parse(t))))throw new Error(`${r} must be an instanceof Date or a string in RFC-1123 format.`);t=t instanceof Date?t.toUTCString():new Date(t).toUTCString()}else if(null!==e.match(/^UnixTime$/i)){if(!(t instanceof Date||"string"==typeof t.valueOf()&&!isNaN(Date.parse(t))))throw new Error(`${r} must be an instanceof Date or a string in RFC-1123/ISO8601 format for it to be serialized in UnixTime/Epoch format.`);t=function(e){if(!e)return;"string"==typeof e.valueOf()&&(e=new Date(e));return Math.floor(e.getTime()/1e3)}(t)}else if(null!==e.match(/^TimeSpan$/i)&&!function(e){return Ml.test(e)}(t))throw new Error(`${r} must be a string in ISO 8601 format. Instead was "${t}".`);return t}(s,t,r):null!==s.match(/^ByteArray$/i)?i=function(e,t){if(null!=t){if(!(t instanceof Uint8Array))throw new Error(`${e} must be of type Uint8Array.`);t=$l(t)}return t}(r,t):null!==s.match(/^Base64Url$/i)?i=function(e,t){if(null!=t){if(!(t instanceof Uint8Array))throw new Error(`${e} must be of type Uint8Array.`);t=function(e){if(!e)return;if(!(e instanceof Uint8Array))throw new Error("Please provide an input of type Uint8Array for converting to Base64Url.");const t=$l(e);return function(e,t){let r=e.length;for(;r-1>=0&&e[r-1]===t;)--r;return e.substr(0,r)}(t,"=").replace(/\+/g,"-").replace(/\//g,"_")}(t)}return t}(r,t):null!==s.match(/^Sequence$/i)?i=function(e,t,r,n,a,i){if(!Array.isArray(r))throw new Error(`${n} must be of type Array.`);let s=t.type.element;if(!s||"object"!=typeof s)throw new Error(`element" metadata for an Array must be defined in the mapper and it must of type "object" in ${n}.`);"Composite"===s.type.name&&s.type.className&&(s=e.modelMappers[s.type.className]??s);const o=[];for(let t=0;t<r.length;t++){const c=e.serialize(s,r[t],n,i);if(a&&s.xmlNamespace){const e=s.xmlNamespacePrefix?`xmlns:${s.xmlNamespacePrefix}`:"xmlns";"Composite"===s.type.name?(o[t]={...c},o[t][Rl]={[e]:s.xmlNamespace}):(o[t]={},o[t][i.xml.xmlCharKey]=c,o[t][Rl]={[e]:s.xmlNamespace})}else o[t]=c}return o}(this,e,t,r,Boolean(this.isXML),a):null!==s.match(/^Dictionary$/i)?i=function(e,t,r,n,a,i){if("object"!=typeof r)throw new Error(`${n} must be of type object.`);const s=t.type.value;if(!s||"object"!=typeof s)throw new Error(`"value" metadata for a Dictionary must be defined in the mapper and it must of type "object" in ${n}.`);const o={};for(const t of Object.keys(r)){const c=e.serialize(s,r[t],n,i);o[t]=Gl(s,c,a,i)}if(a&&t.xmlNamespace){const e=t.xmlNamespacePrefix?`xmlns:${t.xmlNamespacePrefix}`:"xmlns",r=o;return r[Rl]={[e]:t.xmlNamespace},r}return o}(this,e,t,r,Boolean(this.isXML),a):null!==s.match(/^Composite$/i)&&(i=function(e,t,r,n,a,i){Wl(e,t)&&(t=Kl(e,t,r,"clientName"));if(null!=r){const s={},o=Vl(e,t,n);for(const c of Object.keys(o)){const l=o[c];if(l.readOnly)continue;let u,d=s;if(e.isXML)u=l.xmlIsWrapped?l.xmlName:l.xmlElementName||l.xmlName;else{const e=ql(l.serializedName);u=e.pop();for(const t of e){const e=d[t];null==e&&(void 0!==r[c]&&null!==r[c]||void 0!==l.defaultValue)&&(d[t]={}),d=d[t]}}if(null!=d){if(a&&t.xmlNamespace){const e=t.xmlNamespacePrefix?`xmlns:${t.xmlNamespacePrefix}`:"xmlns";d[Rl]={...d[Rl],[e]:t.xmlNamespace}}const s=""!==l.serializedName?n+"."+l.serializedName:n;let o=r[c];const p=Wl(e,t);p&&p.clientName===c&&null==o&&(o=t.serializedName);const m=e.serialize(l,o,s,i);if(void 0!==m&&null!=u){const e=Gl(l,m,a,i);a&&l.xmlIsAttribute?(d[Rl]=d[Rl]||{},d[Rl][u]=m):a&&l.xmlIsWrapped?d[u]={[l.xmlElementName]:e}:d[u]=e}}}const c=function(e,t,r){const n=t.type.additionalProperties;if(!n&&t.type.className){const n=Bl(e,t,r);return n?.type.additionalProperties}return n}(e,t,n);if(c){const t=Object.keys(o);for(const a in r){t.every(e=>e!==a)&&(s[a]=e.serialize(c,r[a],n+'["'+a+'"]',i))}}return s}return r}(this,e,t,r,Boolean(this.isXML),a));return i}deserialize(e,t,r,n={xml:{}}){const a={xml:{rootName:n.xml.rootName??"",includeRoot:n.xml.includeRoot??!1,xmlCharKey:n.xml.xmlCharKey??Ll},ignoreUnknownProperties:n.ignoreUnknownProperties??!1};if(null==t)return this.isXML&&"Sequence"===e.type.name&&!e.xmlIsWrapped&&(t=[]),void 0!==e.defaultValue&&(t=e.defaultValue),t;let i;const s=e.type.name;if(r||(r=e.serializedName),null!==s.match(/^Composite$/i))i=function(e,t,r,n,a){const i=a.xml.xmlCharKey??Ll;Wl(e,t)&&(t=Kl(e,t,r,"serializedName"));const s=Vl(e,t,n);let o={};const c=[];for(const l of Object.keys(s)){const u=s[l],d=ql(s[l].serializedName);c.push(d[0]);const{serializedName:p,xmlName:m,xmlElementName:h}=u;let f=n;""!==p&&void 0!==p&&(f=n+"."+p);const g=u.headerCollectionPrefix;if(g){const t={};for(const n of Object.keys(r))n.startsWith(g)&&(t[n.substring(g.length)]=e.deserialize(u.type.value,r[n],f,a)),c.push(n);o[l]=t}else if(e.isXML)if(u.xmlIsAttribute&&r[Rl])o[l]=e.deserialize(u,r[Rl][m],f,a);else if(u.xmlIsMsText)void 0!==r[i]?o[l]=r[i]:"string"==typeof r&&(o[l]=r);else{const t=h||m||p;if(u.xmlIsWrapped){const t=r[m],n=t?.[h]??[];o[l]=e.deserialize(u,n,f,a),c.push(m)}else{const n=r[t];o[l]=e.deserialize(u,n,f,a),c.push(t)}}else{let n,i=r,c=0;for(const e of d){if(!i)break;c++,i=i[e]}null===i&&c<d.length&&(i=void 0),n=i;const p=t.type.polymorphicDiscriminator;let m;if(p&&l===p.clientName&&null==n&&(n=t.serializedName),Array.isArray(r[l])&&""===s[l].serializedName){n=r[l];const t=e.deserialize(u,n,f,a);for(const[e,r]of Object.entries(o))Object.prototype.hasOwnProperty.call(t,e)||(t[e]=r);o=t}else void 0===n&&void 0===u.defaultValue||(m=e.deserialize(u,n,f,a),o[l]=m)}}const l=t.type.additionalProperties;if(l){const t=e=>{for(const t in s){if(ql(s[t].serializedName)[0]===e)return!1}return!0};for(const i in r)t(i)&&(o[i]=e.deserialize(l,r[i],n+'["'+i+'"]',a))}else if(r&&!a.ignoreUnknownProperties)for(const e of Object.keys(r))void 0!==o[e]||c.includes(e)||Hl(e,a)||(o[e]=r[e]);return o}(this,e,t,r,a);else{if(this.isXML){const e=a.xml.xmlCharKey;void 0!==t[Rl]&&void 0!==t[e]&&(t=t[e])}null!==s.match(/^Number$/i)?(i=parseFloat(t),isNaN(i)&&(i=t)):null!==s.match(/^Boolean$/i)?i="true"===t||"false"!==t&&t:null!==s.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i)?i=t:null!==s.match(/^(Date|DateTime|DateTimeRfc1123)$/i)?i=new Date(t):null!==s.match(/^UnixTime$/i)?i=function(e){if(!e)return;return new Date(1e3*e)}(t):null!==s.match(/^ByteArray$/i)?i=zl(t):null!==s.match(/^Base64Url$/i)?i=function(e){if(!e)return;if(e&&"string"!=typeof e.valueOf())throw new Error("Please provide an input of type string for converting to Uint8Array");return e=e.replace(/-/g,"+").replace(/_/g,"/"),zl(e)}(t):null!==s.match(/^Sequence$/i)?i=function(e,t,r,n,a){let i=t.type.element;if(!i||"object"!=typeof i)throw new Error(`element" metadata for an Array must be defined in the mapper and it must of type "object" in ${n}`);if(r){Array.isArray(r)||(r=[r]),"Composite"===i.type.name&&i.type.className&&(i=e.modelMappers[i.type.className]??i);const t=[];for(let s=0;s<r.length;s++)t[s]=e.deserialize(i,r[s],`${n}[${s}]`,a);return t}return r}(this,e,t,r,a):null!==s.match(/^Dictionary$/i)&&(i=function(e,t,r,n,a){const i=t.type.value;if(!i||"object"!=typeof i)throw new Error(`"value" metadata for a Dictionary must be defined in the mapper and it must of type "object" in ${n}`);if(r){const t={};for(const s of Object.keys(r))t[s]=e.deserialize(i,r[s],n,a);return t}return r}(this,e,t,r,a))}return e.isConstant&&(i=e.defaultValue),i}}function Ul(e={},t=!1){return new Fl(e,t)}function ql(e){const t=[];let r="";if(e){const n=e.split(".");for(const e of n)"\\"===e.charAt(e.length-1)?r+=e.substr(0,e.length-1)+".":(r+=e,t.push(r),r="")}return t}function Bl(e,t,r){const n=t.type.className;if(!n)throw new Error(`Class name for model "${r}" is not provided in the mapper "${JSON.stringify(t,void 0,2)}".`);return e.modelMappers[n]}function Vl(e,t,r){let n=t.type.modelProperties;if(!n){const a=Bl(e,t,r);if(!a)throw new Error(`mapper() cannot be null or undefined for model "${t.type.className}".`);if(n=a?.type.modelProperties,!n)throw new Error(`modelProperties cannot be null or undefined in the mapper "${JSON.stringify(a)}" of type "${t.type.className}" for object "${r}".`)}return n}function Gl(e,t,r,n){if(!r||!e.xmlNamespace)return t;const a=e.xmlNamespacePrefix?`xmlns:${e.xmlNamespacePrefix}`:"xmlns",i={[a]:e.xmlNamespace};if(["Composite"].includes(e.type.name)){if(t[Rl])return t;{const e={...t};return e[Rl]=i,e}}const s={};return s[n.xml.xmlCharKey]=t,s[Rl]=i,s}function Hl(e,t){return[Rl,t.xml.xmlCharKey].includes(e)}function Kl(e,t,r,n){const a=Wl(e,t);if(a){let i=a[n];if(i){"serializedName"===n&&(i=i.replace(/\\/gi,""));const a=r[i],s=t.type.uberParent??t.type.className;if("string"==typeof a&&s){const r=function(e,t,r){const n=[r];for(;n.length;){const r=n.shift(),a=t===r?t:r+"."+t;if(Object.prototype.hasOwnProperty.call(e,a))return e[a];for(const[t,a]of Object.entries(e))t.startsWith(r+".")&&a.type.uberParent===r&&a.type.className&&n.push(a.type.className)}}(e.modelMappers.discriminators,a,s);r&&(t=r)}}}return t}function Wl(e,t){return t.type.polymorphicDiscriminator||Zl(e,t.type.uberParent)||Zl(e,t.type.className)}function Zl(e,t){return t&&e.modelMappers[t]&&e.modelMappers[t].type.polymorphicDiscriminator}const Jl="Sequence",Yl="String",Ql="Stream";var Xl,eu={};const tu=(Xl||(Xl=1,Object.defineProperty(eu,"__esModule",{value:!0}),eu.state=void 0,eu.state={operationRequestMap:new WeakMap}),eu).state;function ru(e,t,r){let n=t.parameterPath;const a=t.mapper;let i;if("string"==typeof n&&(n=[n]),Array.isArray(n)){if(n.length>0)if(a.isConstant)i=a.defaultValue;else{let t=nu(e,n);!t.propertyFound&&r&&(t=nu(r,n));let s=!1;t.propertyFound||(s=a.required||"options"===n[0]&&2===n.length),i=s?a.defaultValue:t.propertyValue}}else{a.required&&(i={});for(const t in n){const s=a.type.modelProperties[t],o=ru(e,{parameterPath:n[t],mapper:s},r);void 0!==o&&(i||(i={}),i[t]=o)}}return i}function nu(e,t){const r={propertyFound:!1};let n=0;for(;n<t.length;++n){const r=t[n];if(!e||!(r in e))break;e=e[r]}return n===t.length&&(r.propertyValue=e,r.propertyFound=!0),r}const au=Symbol.for("@azure/core-client original request");function iu(e){if(function(e){return au in e}(e))return iu(e[au]);let t=tu.operationRequestMap.get(e);return t||(t={},tu.operationRequestMap.set(e,t)),t}const su=["application/json","text/json"],ou=["application/xml","application/atom+xml"];function cu(e={}){const t=e.expectedContentTypes?.json??su,r=e.expectedContentTypes?.xml??ou,n=e.parseXML,a=e.serializerOptions,i={xml:{rootName:a?.xml.rootName??"",includeRoot:a?.xml.includeRoot??!1,xmlCharKey:a?.xml.xmlCharKey??Ll}};return{name:"deserializationPolicy",async sendRequest(e,a){const s=await a(e);return async function(e,t,r,n,a){const i=await async function(e,t,r,n,a){if(!r.request.streamResponseStatusCodes?.has(r.status)&&r.bodyAsText){const i=r.bodyAsText,s=r.headers.get("Content-Type")||"",o=s?s.split(";").map(e=>e.toLowerCase()):[];try{if(0===o.length||o.some(t=>-1!==e.indexOf(t)))return r.parsedBody=JSON.parse(i),r;if(o.some(e=>-1!==t.indexOf(e))){if(!a)throw new Error("Parsing XML not supported.");const e=await a(i,n.xml);return r.parsedBody=e,r}}catch(e){const t=`Error "${e}" occurred while parsing the response body - ${r.bodyAsText}.`,n=e.code||vl.PARSE_ERROR;throw new vl(t,{code:n,statusCode:r.status,request:r.request,response:r})}}return r}(e,t,r,n,a);if(!function(e){const t=e.request,r=iu(t),n=r?.shouldDeserialize;let a;a=void 0===n||("boolean"==typeof n?n:n(e));return a}(i))return i;const s=iu(i.request),o=s?.operationSpec;if(!o||!o.responses)return i;const c=function(e){let t;const r=e.request,n=iu(r),a=n?.operationSpec;a&&(t=n?.operationResponseGetter?n?.operationResponseGetter(a,e):a.responses[e.status]);return t}(i),{error:l,shouldReturnResponse:u}=function(e,t,r,n){const a=200<=e.status&&e.status<300,i=function(e){const t=Object.keys(e.responses);return 0===t.length||1===t.length&&"default"===t[0]}(t)?a:!!r;if(i){if(!r)return{error:null,shouldReturnResponse:!1};if(!r.isError)return{error:null,shouldReturnResponse:!1}}const s=r??t.responses.default,o=e.request.streamResponseStatusCodes?.has(e.status)?`Unexpected status code: ${e.status}`:e.bodyAsText,c=new vl(o,{statusCode:e.status,request:e.request,response:e});if(!(s||e.parsedBody?.error?.code&&e.parsedBody?.error?.message))throw c;const l=s?.bodyMapper,u=s?.headersMapper;try{if(e.parsedBody){const r=e.parsedBody;let a;if(l){let e=r;if(t.isXML&&l.type.name===Jl){e=[];const t=l.xmlElementName;"object"==typeof r&&t&&(e=r[t])}a=t.serializer.deserialize(l,e,"error.response.parsedBody",n)}const i=r.error||a||r;c.code=i.code,i.message&&(c.message=i.message),l&&(c.response.parsedBody=a)}e.headers&&u&&(c.response.parsedHeaders=t.serializer.deserialize(u,e.headers.toJSON(),"operationRes.parsedHeaders"))}catch(t){c.message=`Error "${t.message}" occurred in deserializing the responseBody - "${e.bodyAsText}" for the default response.`}return{error:c,shouldReturnResponse:!1}}(i,o,c,n);if(l)throw l;if(u)return i;if(c){if(c.bodyMapper){let e=i.parsedBody;o.isXML&&c.bodyMapper.type.name===Jl&&(e="object"==typeof e?e[c.bodyMapper.xmlElementName]:[]);try{i.parsedBody=o.serializer.deserialize(c.bodyMapper,e,"operationRes.parsedBody",n)}catch(e){throw new vl(`Error ${e} occurred in deserializing the responseBody - ${i.bodyAsText}`,{statusCode:i.status,request:i.request,response:i})}}else"HEAD"===o.httpMethod&&(i.parsedBody=r.status>=200&&r.status<300);c.headersMapper&&(i.parsedHeaders=o.serializer.deserialize(c.headersMapper,i.headers.toJSON(),"operationRes.parsedHeaders",{xml:{},ignoreUnknownProperties:!0}))}return i}(t,r,s,i,n)}}}function lu(e){const{parameterPath:t,mapper:r}=e;let n;return n="string"==typeof t?t:Array.isArray(t)?t.join("."):r.serializedName,n}function uu(e={}){const t=e.stringifyXML;return{name:"serializationPolicy",async sendRequest(e,r){const n=iu(e),a=n?.operationSpec,i=n?.operationArguments;return a&&i&&(function(e,t,r){if(r.headerParameters)for(const n of r.headerParameters){let a=ru(t,n);if(null!=a||n.mapper.required){a=r.serializer.serialize(n.mapper,a,lu(n));const t=n.mapper.headerCollectionPrefix;if(t)for(const r of Object.keys(a))e.headers.set(t+r,a[r]);else e.headers.set(n.mapper.serializedName||lu(n),a)}}const n=t.options?.requestOptions?.customHeaders;if(n)for(const t of Object.keys(n))e.headers.set(t,n[t])}(e,i,a),function(e,t,r,n=function(){throw new Error("XML serialization unsupported!")}){const a=t.options?.serializerOptions,i={xml:{rootName:a?.xml.rootName??"",includeRoot:a?.xml.includeRoot??!1,xmlCharKey:a?.xml.xmlCharKey??Ll}},s=i.xml.xmlCharKey;if(r.requestBody&&r.requestBody.mapper){e.body=ru(t,r.requestBody);const a=r.requestBody.mapper,{required:o,serializedName:c,xmlName:l,xmlElementName:u,xmlNamespace:d,xmlNamespacePrefix:p,nullable:m}=a,h=a.type.name;try{if(void 0!==e.body&&null!==e.body||m&&null===e.body||o){const t=lu(r.requestBody);e.body=r.serializer.serialize(a,e.body,t,i);const o=h===Ql;if(r.isXML){const t=p?`xmlns:${p}`:"xmlns",r=function(e,t,r,n,a){if(e&&!["Composite","Sequence","Dictionary"].includes(r)){const r={};return r[a.xml.xmlCharKey]=n,r[Rl]={[t]:e},r}return n}(d,t,h,e.body,i);h===Jl?e.body=n(function(e,t,r,n){Array.isArray(e)||(e=[e]);if(!r||!n)return{[t]:e};const a={[t]:e};return a[Rl]={[r]:n},a}(r,u||l||c,t,d),{rootName:l||c,xmlCharKey:s}):o||(e.body=n(r,{rootName:l||c,xmlCharKey:s}))}else{if(h===Yl&&(r.contentType?.match("text/plain")||"text"===r.mediaType))return;o||(e.body=JSON.stringify(e.body))}}}catch(e){throw new Error(`Error "${e.message}" occurred in serializing the payload - ${JSON.stringify(c,void 0," ")}.`)}}else if(r.formDataParameters&&r.formDataParameters.length>0){e.formData={};for(const n of r.formDataParameters){const a=ru(t,n);if(null!=a){const t=n.mapper.serializedName||lu(n);e.formData[t]=r.serializer.serialize(n.mapper,a,lu(n),i)}}}}(e,i,a,t)),r(e)}}}let du;function pu(){return du||(du=function(){const e=qo();return{async sendRequest(t){const{abortSignal:r,cleanup:n}=t.abortSignal?wl(t.abortSignal):{};try{return t.abortSignal=r,await e.sendRequest(t)}finally{n?.()}}}}()),du}const mu={CSV:",",SSV:" ",Multi:"Multi",TSV:"\t",Pipes:"|"};function hu(e,t,r,n){const a=function(e,t,r){const n=new Map;if(e.urlParameters?.length)for(const a of e.urlParameters){let i=ru(t,a,r);const s=lu(a);i=e.serializer.serialize(a.mapper,i,s),a.skipEncoding||(i=encodeURIComponent(i)),n.set(`{${a.mapper.serializedName||s}}`,i)}return n}(t,r,n);let i=!1,s=fu(e,a);if(t.path){let e=fu(t.path,a);"/{nextLink}"===t.path&&e.startsWith("/")&&(e=e.substring(1)),e.includes("://")?(s=e,i=!0):s=function(e,t){if(!t)return e;const r=new URL(e);let n=r.pathname;n.endsWith("/")||(n=`${n}/`);t.startsWith("/")&&(t=t.substring(1));const a=t.indexOf("?");if(-1!==a){const e=t.substring(0,a),i=t.substring(a+1);n+=e,i&&(r.search=r.search?`${r.search}&${i}`:i)}else n+=t;return r.pathname=n,r.toString()}(s,e)}const{queryParams:o,sequenceParams:c}=function(e,t,r){const n=new Map,a=new Set;if(e.queryParameters?.length)for(const i of e.queryParameters){"Sequence"===i.mapper.type.name&&i.mapper.serializedName&&a.add(i.mapper.serializedName);let s=ru(t,i,r);if(null!=s||i.mapper.required){s=e.serializer.serialize(i.mapper,s,lu(i));const t=i.collectionFormat?mu[i.collectionFormat]:"";if(Array.isArray(s)&&(s=s.map(e=>null==e?"":e)),"Multi"===i.collectionFormat&&0===s.length)continue;!Array.isArray(s)||"SSV"!==i.collectionFormat&&"TSV"!==i.collectionFormat||(s=s.join(t)),i.skipEncoding||(s=Array.isArray(s)?s.map(e=>encodeURIComponent(e)):encodeURIComponent(s)),!Array.isArray(s)||"CSV"!==i.collectionFormat&&"Pipes"!==i.collectionFormat||(s=s.join(t)),n.set(i.mapper.serializedName||lu(i),s)}}return{queryParams:n,sequenceParams:a}}(t,r,n);return s=function(e,t,r,n=!1){if(0===t.size)return e;const a=new URL(e),i=function(e){const t=new Map;if(!e||"?"!==e[0])return t;const r=(e=e.slice(1)).split("&");for(const e of r){const[r,n]=e.split("=",2),a=t.get(r);a?Array.isArray(a)?a.push(n):t.set(r,[a,n]):t.set(r,n)}return t}(a.search);for(const[e,a]of t){const t=i.get(e);if(Array.isArray(t))if(Array.isArray(a)){t.push(...a);const r=new Set(t);i.set(e,Array.from(r))}else t.push(a);else t?(Array.isArray(a)?a.unshift(t):r.has(e)&&i.set(e,[t,a]),n||i.set(e,a)):i.set(e,a)}const s=[];for(const[e,t]of i)if("string"==typeof t)s.push(`${e}=${t}`);else if(Array.isArray(t))for(const r of t)s.push(`${e}=${r}`);else s.push(`${e}=${t}`);return a.search=s.length?`?${s.join("&")}`:"",a.toString()}(s,o,c,i),s}function fu(e,t){let r=e;for(const[e,n]of t)r=r.split(e).join(n);return r}const gu=Qc("core-client");class yu{_endpoint;_requestContentType;_allowInsecureConnection;_httpClient;pipeline;constructor(e={}){if(this._requestContentType=e.requestContentType,this._endpoint=e.endpoint??e.baseUri,e.baseUri&&gu.warning("The baseUri option for SDK Clients has been deprecated, please use endpoint instead."),this._allowInsecureConnection=e.allowInsecureConnection,this._httpClient=e.httpClient||pu(),this.pipeline=e.pipeline||function(e){const t=function(e){if(e.credentialScopes)return e.credentialScopes;if(e.endpoint)return`${e.endpoint}/.default`;if(e.baseUri)return`${e.baseUri}/.default`;if(e.credential&&!e.credentialScopes)throw new Error("When using credentials, the ServiceClientOptions must contain either a endpoint or a credentialScopes. Unable to create a bearerTokenAuthenticationPolicy");return}(e),r=e.credential&&t?{credentialScopes:t,credential:e.credential}:void 0;return function(e={}){const t=Sl(e??{});return e.credentialOptions&&t.addPolicy(Il({credential:e.credentialOptions.credential,scopes:e.credentialOptions.credentialScopes})),t.addPolicy(uu(e.serializationOptions),{phase:"Serialize"}),t.addPolicy(cu(e.deserializationOptions),{phase:"Deserialize"}),t}({...e,credentialOptions:r})}(e),e.additionalPolicies?.length)for(const{policy:t,position:r}of e.additionalPolicies){const e="perRetry"===r?"Sign":void 0;this.pipeline.addPolicy(t,{afterPhase:e})}}async sendRequest(e){return this.pipeline.sendRequest(this._httpClient,e)}async sendOperationRequest(e,t){const r=t.baseUrl||this._endpoint;if(!r)throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a endpoint string property that contains the base URL to use.");const n=Nl({url:hu(r,t,e,this)});n.method=t.httpMethod;const a=iu(n);a.operationSpec=t,a.operationArguments=e;const i=t.contentType||this._requestContentType;i&&t.requestBody&&n.headers.set("Content-Type",i);const s=e.options;if(s){const e=s.requestOptions;e&&(e.timeout&&(n.timeout=e.timeout),e.onUploadProgress&&(n.onUploadProgress=e.onUploadProgress),e.onDownloadProgress&&(n.onDownloadProgress=e.onDownloadProgress),void 0!==e.shouldDeserialize&&(a.shouldDeserialize=e.shouldDeserialize),e.allowInsecureConnection&&(n.allowInsecureConnection=!0)),s.abortSignal&&(n.abortSignal=s.abortSignal),s.tracingOptions&&(n.tracingOptions=s.tracingOptions)}this._allowInsecureConnection&&(n.allowInsecureConnection=!0),void 0===n.streamResponseStatusCodes&&(n.streamResponseStatusCodes=function(e){const t=new Set;for(const r in e.responses){const n=e.responses[r];n.bodyMapper&&n.bodyMapper.type.name===Ql&&t.add(Number(r))}return t}(t));try{const e=await this.sendRequest(n),r=jl(e,t.responses[e.status]);return s?.onResponse&&s.onResponse(e,r),r}catch(e){if("object"==typeof e&&e?.response){const r=e.response,n=jl(r,t.responses[e.statusCode]||t.responses.default);e.details=n,s?.onResponse&&s.onResponse(r,n,e)}throw e}}}function vu(e){return new _u(e.toJSON({preserveCase:!0}))}function bu(e){return e.toLowerCase()}class _u{_headersMap;constructor(e){if(this._headersMap={},e)for(const t in e)this.set(t,e[t])}set(e,t){this._headersMap[bu(e)]={name:e,value:t.toString()}}get(e){const t=this._headersMap[bu(e)];return t?t.value:void 0}contains(e){return!!this._headersMap[bu(e)]}remove(e){const t=this.contains(e);return delete this._headersMap[bu(e)],t}rawHeaders(){return this.toJson({preserveCase:!0})}headersArray(){const e=[];for(const t in this._headersMap)e.push(this._headersMap[t]);return e}headerNames(){const e=[],t=this.headersArray();for(let r=0;r<t.length;++r)e.push(t[r].name);return e}headerValues(){const e=[],t=this.headersArray();for(let r=0;r<t.length;++r)e.push(t[r].value);return e}toJson(e={}){const t={};if(e.preserveCase)for(const e in this._headersMap){const r=this._headersMap[e];t[r.name]=r.value}else for(const e in this._headersMap){const r=this._headersMap[e];t[bu(r.name)]=r.value}return t}toString(){return JSON.stringify(this.toJson({preserveCase:!0}))}clone(){const e={};for(const t in this._headersMap){const r=this._headersMap[t];e[r.name]=r.value}return new _u(e)}}function wu(e,t){let r=function(e){return{url:e.url,method:e.method,headers:vu(e.headers),withCredentials:e.withCredentials,timeout:e.timeout,requestId:e.headers.get("x-ms-client-request-id")||e.requestId,abortSignal:e.abortSignal,body:e.body,formData:e.formData,keepAlive:!!e.disableKeepAlive,onDownloadProgress:e.onDownloadProgress,onUploadProgress:e.onUploadProgress,proxySettings:e.proxySettings,streamResponseStatusCodes:e.streamResponseStatusCodes,agent:e.agent,requestOverrides:e.requestOverrides,clone(){throw new Error("Cannot clone a non-proxied WebResourceLike")},prepare(){throw new Error("WebResourceLike.prepare() is not supported by @azure/core-http-compat")},validateRequestProperties(){}}}(e.request),n=vu(e.headers);return{...e,request:r,headers:n}}class Su extends yu{constructor(e){super(e),!1!==e.keepAliveOptions?.enable||this.pipeline.getOrderedPolicies().some(e=>e.name===Tl)||this.pipeline.addPolicy({name:Tl,sendRequest:async(e,t)=>(e.disableKeepAlive=!0,t(e))}),!1===e.redirectOptions?.handleRedirects&&this.pipeline.removePolicy({name:tl})}async sendOperationRequest(e,t){const r=e?.options?.onResponse;let n;e.options={...e.options,onResponse:function(e,t,a){n=e,r&&r(e,t,a)}};const a=await super.sendOperationRequest(e,t);return n&&Object.defineProperty(a,"_response",{value:wu(n)}),a}}const Nu={type:{name:"Composite",className:"ErrorResponse",modelProperties:{error:{serializedName:"error",type:{name:"Composite",className:"ErrorDetail"}}}}},ku={type:{name:"Composite",className:"SearchDocumentsResult",modelProperties:{count:{serializedName:"@odata\\.count",readOnly:!0,type:{name:"Number"}},coverage:{serializedName:"@search\\.coverage",readOnly:!0,type:{name:"Number"}},facets:{serializedName:"@search\\.facets",readOnly:!0,type:{name:"Dictionary",value:{type:{name:"Sequence",element:{type:{name:"Composite",className:"FacetResult"}}}}}},answers:{serializedName:"@search\\.answers",readOnly:!0,nullable:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"QueryAnswerResult"}}}},nextPageParameters:{serializedName:"@search\\.nextPageParameters",type:{name:"Composite",className:"SearchRequest"}},results:{serializedName:"value",required:!0,readOnly:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"SearchResult"}}}},nextLink:{serializedName:"@odata\\.nextLink",readOnly:!0,type:{name:"String"}},semanticPartialResponseReason:{serializedName:"@search\\.semanticPartialResponseReason",readOnly:!0,type:{name:"String"}},semanticPartialResponseType:{serializedName:"@search\\.semanticPartialResponseType",readOnly:!0,type:{name:"String"}}}}},xu={type:{name:"Composite",className:"SearchRequest",modelProperties:{includeTotalResultCount:{serializedName:"count",type:{name:"Boolean"}},facets:{serializedName:"facets",type:{name:"Sequence",element:{type:{name:"String"}}}},filter:{serializedName:"filter",type:{name:"String"}},highlightFields:{serializedName:"highlight",type:{name:"String"}},highlightPostTag:{serializedName:"highlightPostTag",type:{name:"String"}},highlightPreTag:{serializedName:"highlightPreTag",type:{name:"String"}},minimumCoverage:{serializedName:"minimumCoverage",type:{name:"Number"}},orderBy:{serializedName:"orderby",type:{name:"String"}},queryType:{serializedName:"queryType",type:{name:"Enum",allowedValues:["simple","full","semantic"]}},scoringStatistics:{serializedName:"scoringStatistics",type:{name:"Enum",allowedValues:["local","global"]}},sessionId:{serializedName:"sessionId",type:{name:"String"}},scoringParameters:{serializedName:"scoringParameters",type:{name:"Sequence",element:{type:{name:"String"}}}},scoringProfile:{serializedName:"scoringProfile",type:{name:"String"}},debug:{serializedName:"debug",type:{name:"String"}},searchText:{serializedName:"search",type:{name:"String"}},searchFields:{serializedName:"searchFields",type:{name:"String"}},searchMode:{serializedName:"searchMode",type:{name:"Enum",allowedValues:["any","all"]}},select:{serializedName:"select",type:{name:"String"}},skip:{serializedName:"skip",type:{name:"Number"}},top:{serializedName:"top",type:{name:"Number"}},semanticConfigurationName:{serializedName:"semanticConfiguration",type:{name:"String"}},semanticErrorHandling:{serializedName:"semanticErrorHandling",type:{name:"String"}},semanticMaxWaitInMilliseconds:{constraints:{InclusiveMinimum:700},serializedName:"semanticMaxWaitInMilliseconds",nullable:!0,type:{name:"Number"}},semanticQuery:{serializedName:"semanticQuery",type:{name:"String"}},answers:{serializedName:"answers",type:{name:"String"}},captions:{serializedName:"captions",type:{name:"String"}},vectorQueries:{serializedName:"vectorQueries",type:{name:"Sequence",element:{type:{name:"Composite",className:"VectorQuery"}}}},vectorFilterMode:{serializedName:"vectorFilterMode",type:{name:"String"}}}}},Eu={type:{name:"Composite",className:"VectorQuery",uberParent:"VectorQuery",polymorphicDiscriminator:{serializedName:"kind",clientName:"kind"},modelProperties:{kind:{serializedName:"kind",required:!0,type:{name:"String"}},kNearestNeighborsCount:{serializedName:"k",type:{name:"Number"}},fields:{serializedName:"fields",type:{name:"String"}},exhaustive:{serializedName:"exhaustive",type:{name:"Boolean"}},oversampling:{serializedName:"oversampling",type:{name:"Number"}},weight:{serializedName:"weight",type:{name:"Number"}}}}},Pu={type:{name:"Composite",className:"SuggestDocumentsResult",modelProperties:{results:{serializedName:"value",required:!0,readOnly:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"SuggestResult"}}}},coverage:{serializedName:"@search\\.coverage",readOnly:!0,type:{name:"Number"}}}}},Cu={type:{name:"Composite",className:"SuggestRequest",modelProperties:{filter:{serializedName:"filter",type:{name:"String"}},useFuzzyMatching:{serializedName:"fuzzy",type:{name:"Boolean"}},highlightPostTag:{serializedName:"highlightPostTag",type:{name:"String"}},highlightPreTag:{serializedName:"highlightPreTag",type:{name:"String"}},minimumCoverage:{serializedName:"minimumCoverage",type:{name:"Number"}},orderBy:{serializedName:"orderby",type:{name:"String"}},searchText:{serializedName:"search",required:!0,type:{name:"String"}},searchFields:{serializedName:"searchFields",type:{name:"String"}},select:{serializedName:"select",type:{name:"String"}},suggesterName:{serializedName:"suggesterName",required:!0,type:{name:"String"}},top:{serializedName:"top",type:{name:"Number"}}}}},Au={type:{name:"Composite",className:"IndexBatch",modelProperties:{actions:{serializedName:"value",required:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"IndexAction"}}}}}}},Iu={type:{name:"Composite",className:"IndexDocumentsResult",modelProperties:{results:{serializedName:"value",required:!0,readOnly:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"IndexingResult"}}}}}}},Ou={type:{name:"Composite",className:"AutocompleteResult",modelProperties:{coverage:{serializedName:"@search\\.coverage",readOnly:!0,type:{name:"Number"}},results:{serializedName:"value",required:!0,readOnly:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"AutocompleteItem"}}}}}}},Tu={type:{name:"Composite",className:"AutocompleteRequest",modelProperties:{searchText:{serializedName:"search",required:!0,type:{name:"String"}},autocompleteMode:{serializedName:"autocompleteMode",type:{name:"Enum",allowedValues:["oneTerm","twoTerms","oneTermWithContext"]}},filter:{serializedName:"filter",type:{name:"String"}},useFuzzyMatching:{serializedName:"fuzzy",type:{name:"Boolean"}},highlightPostTag:{serializedName:"highlightPostTag",type:{name:"String"}},highlightPreTag:{serializedName:"highlightPreTag",type:{name:"String"}},minimumCoverage:{serializedName:"minimumCoverage",type:{name:"Number"}},searchFields:{serializedName:"searchFields",type:{name:"String"}},suggesterName:{serializedName:"suggesterName",required:!0,type:{name:"String"}},top:{serializedName:"top",type:{name:"Number"}}}}},$u={serializedName:"vector",type:{name:"Composite",className:"VectorizedQuery",uberParent:"VectorQuery",polymorphicDiscriminator:Eu.type.polymorphicDiscriminator,modelProperties:{...Eu.type.modelProperties,vector:{serializedName:"vector",required:!0,type:{name:"Sequence",element:{type:{name:"Number"}}}}}}},zu={serializedName:"text",type:{name:"Composite",className:"VectorizableTextQuery",uberParent:"VectorQuery",polymorphicDiscriminator:Eu.type.polymorphicDiscriminator,modelProperties:{...Eu.type.modelProperties,text:{serializedName:"text",required:!0,type:{name:"String"}}}}};let Ru={VectorQuery:Eu,"VectorQuery.vector":$u,"VectorQuery.text":zu};var Lu=Object.freeze({__proto__:null,AutocompleteItem:{type:{name:"Composite",className:"AutocompleteItem",modelProperties:{text:{serializedName:"text",required:!0,readOnly:!0,type:{name:"String"}},queryPlusText:{serializedName:"queryPlusText",required:!0,readOnly:!0,type:{name:"String"}}}}},AutocompleteRequest:Tu,AutocompleteResult:Ou,DocumentDebugInfo:{type:{name:"Composite",className:"DocumentDebugInfo",modelProperties:{vectors:{serializedName:"vectors",type:{name:"Composite",className:"VectorsDebugInfo"}}}}},ErrorAdditionalInfo:{type:{name:"Composite",className:"ErrorAdditionalInfo",modelProperties:{type:{serializedName:"type",readOnly:!0,type:{name:"String"}},info:{serializedName:"info",readOnly:!0,type:{name:"Dictionary",value:{type:{name:"any"}}}}}}},ErrorDetail:{type:{name:"Composite",className:"ErrorDetail",modelProperties:{code:{serializedName:"code",readOnly:!0,type:{name:"String"}},message:{serializedName:"message",readOnly:!0,type:{name:"String"}},target:{serializedName:"target",readOnly:!0,type:{name:"String"}},details:{serializedName:"details",readOnly:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"ErrorDetail"}}}},additionalInfo:{serializedName:"additionalInfo",readOnly:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"ErrorAdditionalInfo"}}}}}}},ErrorResponse:Nu,FacetResult:{type:{name:"Composite",className:"FacetResult",additionalProperties:{type:{name:"Object"}},modelProperties:{count:{serializedName:"count",readOnly:!0,type:{name:"Number"}}}}},IndexAction:{type:{name:"Composite",className:"IndexAction",additionalProperties:{type:{name:"Object"}},modelProperties:{__actionType:{serializedName:"@search\\.action",required:!0,type:{name:"Enum",allowedValues:["upload","merge","mergeOrUpload","delete"]}}}}},IndexBatch:Au,IndexDocumentsResult:Iu,IndexingResult:{type:{name:"Composite",className:"IndexingResult",modelProperties:{key:{serializedName:"key",required:!0,readOnly:!0,type:{name:"String"}},errorMessage:{serializedName:"errorMessage",readOnly:!0,type:{name:"String"}},succeeded:{serializedName:"status",required:!0,readOnly:!0,type:{name:"Boolean"}},statusCode:{serializedName:"statusCode",required:!0,readOnly:!0,type:{name:"Number"}}}}},QueryAnswerResult:{type:{name:"Composite",className:"QueryAnswerResult",additionalProperties:{type:{name:"Object"}},modelProperties:{score:{serializedName:"score",required:!0,readOnly:!0,type:{name:"Number"}},key:{serializedName:"key",required:!0,readOnly:!0,type:{name:"String"}},text:{serializedName:"text",required:!0,readOnly:!0,type:{name:"String"}},highlights:{serializedName:"highlights",readOnly:!0,nullable:!0,type:{name:"String"}}}}},QueryCaptionResult:{type:{name:"Composite",className:"QueryCaptionResult",additionalProperties:{type:{name:"Object"}},modelProperties:{text:{serializedName:"text",readOnly:!0,type:{name:"String"}},highlights:{serializedName:"highlights",readOnly:!0,nullable:!0,type:{name:"String"}}}}},QueryResultDocumentSubscores:{type:{name:"Composite",className:"QueryResultDocumentSubscores",modelProperties:{text:{serializedName:"text",type:{name:"Composite",className:"TextResult"}},vectors:{serializedName:"vectors",readOnly:!0,type:{name:"Sequence",element:{type:{name:"Dictionary",value:{type:{name:"Composite",className:"SingleVectorFieldResult"}}}}}},documentBoost:{serializedName:"documentBoost",readOnly:!0,type:{name:"Number"}}}}},SearchDocumentsResult:ku,SearchRequest:xu,SearchResult:{type:{name:"Composite",className:"SearchResult",additionalProperties:{type:{name:"Object"}},modelProperties:{_score:{serializedName:"@search\\.score",required:!0,readOnly:!0,type:{name:"Number"}},_rerankerScore:{serializedName:"@search\\.rerankerScore",readOnly:!0,nullable:!0,type:{name:"Number"}},rerankerBoostedScore:{serializedName:"@search\\.rerankerBoostedScore",readOnly:!0,nullable:!0,type:{name:"Number"}},_highlights:{serializedName:"@search\\.highlights",readOnly:!0,type:{name:"Dictionary",value:{type:{name:"Sequence",element:{type:{name:"String"}}}}}},_captions:{serializedName:"@search\\.captions",readOnly:!0,nullable:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"QueryCaptionResult"}}}},documentDebugInfo:{serializedName:"@search\\.documentDebugInfo",type:{name:"Composite",className:"DocumentDebugInfo"}}}}},SingleVectorFieldResult:{type:{name:"Composite",className:"SingleVectorFieldResult",modelProperties:{searchScore:{serializedName:"searchScore",readOnly:!0,type:{name:"Number"}},vectorSimilarity:{serializedName:"vectorSimilarity",readOnly:!0,type:{name:"Number"}}}}},SuggestDocumentsResult:Pu,SuggestRequest:Cu,SuggestResult:{type:{name:"Composite",className:"SuggestResult",additionalProperties:{type:{name:"Object"}},modelProperties:{_text:{serializedName:"@search\\.text",required:!0,readOnly:!0,type:{name:"String"}}}}},TextResult:{type:{name:"Composite",className:"TextResult",modelProperties:{searchScore:{serializedName:"searchScore",readOnly:!0,type:{name:"Number"}}}}},VectorQuery:Eu,VectorizableTextQuery:zu,VectorizedQuery:$u,VectorsDebugInfo:{type:{name:"Composite",className:"VectorsDebugInfo",modelProperties:{subscores:{serializedName:"subscores",type:{name:"Composite",className:"QueryResultDocumentSubscores"}}}}},discriminators:Ru});const Mu={parameterPath:"accept",mapper:{defaultValue:"application/json",isConstant:!0,serializedName:"Accept",type:{name:"String"}}},Du={parameterPath:"endpoint",mapper:{serializedName:"endpoint",required:!0,type:{name:"String"}},skipEncoding:!0},ju={parameterPath:"indexName",mapper:{serializedName:"indexName",required:!0,type:{name:"String"}}},Fu={parameterPath:"apiVersion",mapper:{serializedName:"api-version",required:!0,type:{name:"String"}}},Uu={parameterPath:["options","contentType"],mapper:{defaultValue:"application/json",isConstant:!0,serializedName:"Content-Type",type:{name:"String"}}},qu={parameterPath:"searchRequest",mapper:xu},Bu={parameterPath:"searchText",mapper:{serializedName:"search",required:!0,type:{name:"String"}}},Vu={parameterPath:"suggesterName",mapper:{serializedName:"suggesterName",required:!0,type:{name:"String"}}},Gu={parameterPath:"suggestRequest",mapper:Cu},Hu={parameterPath:"batch",mapper:Au},Ku={parameterPath:"autocompleteRequest",mapper:Tu};class Wu{client;constructor(e){this.client=e}count(e){return this.client.sendOperationRequest({options:e},Ju)}searchGet(e){return this.client.sendOperationRequest({options:e},Yu)}searchPost(e,t){return this.client.sendOperationRequest({searchRequest:e,options:t},Qu)}get(e,t){return this.client.sendOperationRequest({key:e,options:t},Xu)}suggestGet(e,t,r){return this.client.sendOperationRequest({searchText:e,suggesterName:t,options:r},ed)}suggestPost(e,t){return this.client.sendOperationRequest({suggestRequest:e,options:t},td)}index(e,t){return this.client.sendOperationRequest({batch:e,options:t},rd)}autocompleteGet(e,t,r){return this.client.sendOperationRequest({searchText:e,suggesterName:t,options:r},nd)}autocompletePost(e,t){return this.client.sendOperationRequest({autocompleteRequest:e,options:t},ad)}}const Zu=Ul(Lu,!1),Ju={path:"/docs/$count",httpMethod:"GET",responses:{200:{bodyMapper:{type:{name:"Number"}}},default:{bodyMapper:Nu}},queryParameters:[Fu],urlParameters:[Du,ju],headerParameters:[Mu],serializer:Zu},Yu={path:"/docs",httpMethod:"GET",responses:{200:{bodyMapper:ku},206:{bodyMapper:ku},default:{bodyMapper:Nu}},queryParameters:[Fu,{parameterPath:["options","searchText"],mapper:{serializedName:"search",type:{name:"String"}}},{parameterPath:["options","searchOptions","includeTotalResultCount"],mapper:{serializedName:"$count",type:{name:"Boolean"}}},{parameterPath:["options","searchOptions","facets"],mapper:{serializedName:"facet",type:{name:"Sequence",element:{type:{name:"String"}}}},collectionFormat:"Multi"},{parameterPath:["options","searchOptions","filter"],mapper:{serializedName:"$filter",type:{name:"String"}}},{parameterPath:["options","searchOptions","highlightFields"],mapper:{serializedName:"highlight",type:{name:"Sequence",element:{type:{name:"String"}}}},collectionFormat:"CSV"},{parameterPath:["options","searchOptions","highlightPostTag"],mapper:{serializedName:"highlightPostTag",type:{name:"String"}}},{parameterPath:["options","searchOptions","highlightPreTag"],mapper:{serializedName:"highlightPreTag",type:{name:"String"}}},{parameterPath:["options","searchOptions","minimumCoverage"],mapper:{serializedName:"minimumCoverage",type:{name:"Number"}}},{parameterPath:["options","searchOptions","orderBy"],mapper:{serializedName:"$orderby",type:{name:"Sequence",element:{type:{name:"String"}}}},collectionFormat:"CSV"},{parameterPath:["options","searchOptions","queryType"],mapper:{serializedName:"queryType",type:{name:"Enum",allowedValues:["simple","full","semantic"]}}},{parameterPath:["options","searchOptions","scoringParameters"],mapper:{serializedName:"scoringParameter",type:{name:"Sequence",element:{type:{name:"String"}}}},collectionFormat:"Multi"},{parameterPath:["options","searchOptions","scoringProfile"],mapper:{serializedName:"scoringProfile",type:{name:"String"}}},{parameterPath:["options","searchOptions","searchFields"],mapper:{serializedName:"searchFields",type:{name:"Sequence",element:{type:{name:"String"}}}},collectionFormat:"CSV"},{parameterPath:["options","searchOptions","searchMode"],mapper:{serializedName:"searchMode",type:{name:"Enum",allowedValues:["any","all"]}}},{parameterPath:["options","searchOptions","scoringStatistics"],mapper:{serializedName:"scoringStatistics",type:{name:"Enum",allowedValues:["local","global"]}}},{parameterPath:["options","searchOptions","sessionId"],mapper:{serializedName:"sessionId",type:{name:"String"}}},{parameterPath:["options","searchOptions","select"],mapper:{serializedName:"$select",type:{name:"Sequence",element:{type:{name:"String"}}}},collectionFormat:"CSV"},{parameterPath:["options","searchOptions","skip"],mapper:{serializedName:"$skip",type:{name:"Number"}}},{parameterPath:["options","searchOptions","top"],mapper:{serializedName:"$top",type:{name:"Number"}}},{parameterPath:["options","searchOptions","semanticConfiguration"],mapper:{serializedName:"semanticConfiguration",type:{name:"String"}}},{parameterPath:["options","searchOptions","semanticErrorHandling"],mapper:{serializedName:"semanticErrorHandling",type:{name:"String"}}},{parameterPath:["options","searchOptions","semanticMaxWaitInMilliseconds"],mapper:{constraints:{InclusiveMinimum:700},serializedName:"semanticMaxWaitInMilliseconds",type:{name:"Number"}}},{parameterPath:["options","searchOptions","answers"],mapper:{serializedName:"answers",type:{name:"String"}}},{parameterPath:["options","searchOptions","captions"],mapper:{serializedName:"captions",type:{name:"String"}}},{parameterPath:["options","searchOptions","semanticQuery"],mapper:{serializedName:"semanticQuery",type:{name:"String"}}},{parameterPath:["options","searchOptions","debug"],mapper:{serializedName:"debug",type:{name:"String"}}}],urlParameters:[Du,ju],headerParameters:[Mu],serializer:Zu},Qu={path:"/docs/search.post.search",httpMethod:"POST",responses:{200:{bodyMapper:ku},206:{bodyMapper:ku},default:{bodyMapper:Nu}},requestBody:qu,queryParameters:[Fu],urlParameters:[Du,ju],headerParameters:[Mu,Uu],mediaType:"json",serializer:Zu},Xu={path:"/docs('{key}')",httpMethod:"GET",responses:{200:{bodyMapper:{type:{name:"Dictionary",value:{type:{name:"any"}}}}},default:{bodyMapper:Nu}},queryParameters:[Fu,{parameterPath:["options","selectedFields"],mapper:{serializedName:"$select",type:{name:"Sequence",element:{type:{name:"String"}}}},collectionFormat:"CSV"}],urlParameters:[Du,ju,{parameterPath:"key",mapper:{serializedName:"key",required:!0,type:{name:"String"}}}],headerParameters:[Mu],serializer:Zu},ed={path:"/docs/search.suggest",httpMethod:"GET",responses:{200:{bodyMapper:Pu},default:{bodyMapper:Nu}},queryParameters:[Fu,Bu,Vu,{parameterPath:["options","suggestOptions","filter"],mapper:{serializedName:"$filter",type:{name:"String"}}},{parameterPath:["options","suggestOptions","useFuzzyMatching"],mapper:{serializedName:"fuzzy",type:{name:"Boolean"}}},{parameterPath:["options","suggestOptions","highlightPostTag"],mapper:{serializedName:"highlightPostTag",type:{name:"String"}}},{parameterPath:["options","suggestOptions","highlightPreTag"],mapper:{serializedName:"highlightPreTag",type:{name:"String"}}},{parameterPath:["options","suggestOptions","minimumCoverage"],mapper:{serializedName:"minimumCoverage",type:{name:"Number"}}},{parameterPath:["options","suggestOptions","orderBy"],mapper:{serializedName:"$orderby",type:{name:"Sequence",element:{type:{name:"String"}}}},collectionFormat:"CSV"},{parameterPath:["options","suggestOptions","searchFields"],mapper:{serializedName:"searchFields",type:{name:"Sequence",element:{type:{name:"String"}}}},collectionFormat:"CSV"},{parameterPath:["options","suggestOptions","select"],mapper:{serializedName:"$select",type:{name:"Sequence",element:{type:{name:"String"}}}},collectionFormat:"CSV"},{parameterPath:["options","suggestOptions","top"],mapper:{serializedName:"$top",type:{name:"Number"}}}],urlParameters:[Du,ju],headerParameters:[Mu],serializer:Zu},td={path:"/docs/search.post.suggest",httpMethod:"POST",responses:{200:{bodyMapper:Pu},default:{bodyMapper:Nu}},requestBody:Gu,queryParameters:[Fu],urlParameters:[Du,ju],headerParameters:[Mu,Uu],mediaType:"json",serializer:Zu},rd={path:"/docs/search.index",httpMethod:"POST",responses:{200:{bodyMapper:Iu},207:{bodyMapper:Iu},default:{bodyMapper:Nu}},requestBody:Hu,queryParameters:[Fu],urlParameters:[Du,ju],headerParameters:[Mu,Uu],mediaType:"json",serializer:Zu},nd={path:"/docs/search.autocomplete",httpMethod:"GET",responses:{200:{bodyMapper:Ou},default:{bodyMapper:Nu}},queryParameters:[Fu,Bu,Vu,{parameterPath:["options","autocompleteOptions","autocompleteMode"],mapper:{serializedName:"autocompleteMode",type:{name:"Enum",allowedValues:["oneTerm","twoTerms","oneTermWithContext"]}}},{parameterPath:["options","autocompleteOptions","filter"],mapper:{serializedName:"$filter",type:{name:"String"}}},{parameterPath:["options","autocompleteOptions","useFuzzyMatching"],mapper:{serializedName:"fuzzy",type:{name:"Boolean"}}},{parameterPath:["options","autocompleteOptions","highlightPostTag"],mapper:{serializedName:"highlightPostTag",type:{name:"String"}}},{parameterPath:["options","autocompleteOptions","highlightPreTag"],mapper:{serializedName:"highlightPreTag",type:{name:"String"}}},{parameterPath:["options","autocompleteOptions","minimumCoverage"],mapper:{serializedName:"minimumCoverage",type:{name:"Number"}}},{parameterPath:["options","autocompleteOptions","searchFields"],mapper:{serializedName:"searchFields",type:{name:"Sequence",element:{type:{name:"String"}}}},collectionFormat:"CSV"},{parameterPath:["options","autocompleteOptions","top"],mapper:{serializedName:"$top",type:{name:"Number"}}}],urlParameters:[Du,ju],headerParameters:[Mu],serializer:Zu},ad={path:"/docs/search.post.autocomplete",httpMethod:"POST",responses:{200:{bodyMapper:Ou},default:{bodyMapper:Nu}},requestBody:Ku,queryParameters:[Fu],urlParameters:[Du,ju],headerParameters:[Mu,Uu],mediaType:"json",serializer:Zu};let id=class extends Su{endpoint;indexName;apiVersion;constructor(e,t,r,n){if(void 0===e)throw new Error("'endpoint' cannot be null");if(void 0===t)throw new Error("'indexName' cannot be null");if(void 0===r)throw new Error("'apiVersion' cannot be null");n||(n={});const a="azsdk-js-search-documents/12.2.0",i=n.userAgentOptions&&n.userAgentOptions.userAgentPrefix?`${n.userAgentOptions.userAgentPrefix} ${a}`:`${a}`;super({requestContentType:"application/json; charset=utf-8",...n,userAgentOptions:{userAgentPrefix:i},endpoint:n.endpoint??n.baseUri??"{endpoint}/indexes('{indexName}')"}),this.endpoint=e,this.indexName=t,this.apiVersion=r,this.documents=new Wu(this),this.addCustomApiVersionPolicy(r)}addCustomApiVersionPolicy(e){if(!e)return;const t={name:"CustomApiVersionPolicy",async sendRequest(t,r){const n=t.url.split("?");if(n.length>1){const r=n[1].split("&").map(t=>t.indexOf("api-version")>-1?"api-version="+e:t);t.url=n[0]+"?"+r.join("&")}return r(t)}};this.pipeline.addPolicy(t)}documents};const sd=Qc("search");function od(e){return{name:"OdataMetadataPolicy",sendRequest:async(t,r)=>(t.headers.set("Accept",`application/json;odata.metadata=${e}`),r(t))}}const cd="api-key";function ld(e){return{name:"SearchApiKeyCredentialPolicy",sendRequest:async(t,r)=>(t.headers.has(cd)||t.headers.set(cd,e.key),r(t))}}function ud(e,t){const r=new Set,n=new Map;!function e(a){if(r.has(a))return;r.add(a);const i=function(e){if(!dd(e))return;if(Array.isArray(e))return e;return Object.values(e)}(function(e){const r=n.get(e);if(a=r,null!=a)return r;var a;const i=t(e);e!==i&&n.set(e,i);return n.get(e)}(a)??a);i?.forEach(e),i?.some(e=>n.has(e))&&n.set(a,n.get(a)??function(e){const t=Array.isArray(e)?e.map(e=>e):"object"==typeof e&&null!==e?{...e}:e;return e===t?e:Object.setPrototypeOf(t,Object.getPrototypeOf(e))}(a))}(e);for(const e of n.values())a(e);return n.get(e)??e;function a(e){dd(e)&&(Array.isArray(e)?e.forEach((t,r)=>{e[r]=n.get(t)??t}):"object"==typeof e&&null!==e&&Object.keys(e).forEach(t=>{e[t]=n.get(e[t])??e[t]}))}}function dd(e){return Array.isArray(e)?dd(e[0]):"object"==typeof e&&null!==e}const pd=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/i,md="Point",hd="EPSG:4326",[fd,gd]=[[function(e){return"number"==typeof e&&isNaN(e)?"NaN":e===1/0?"INF":e===-1/0?"-INF":e},function(e){return e instanceof Date?e.toISOString():e},function(e){return e instanceof ro?e.toJSON():e}],[function(e){switch(e){case"NaN":return NaN;case"-INF":return-1/0;case"INF":return 1/0;default:return e}},function(e){return"string"==typeof e&&pd.test(e)?new Date(e):e},function(e){if(t=e,vd(t,{requiredKeys:["type","coordinates"],propertyValidator:e=>{switch(e){case"type":return t.type===md;case"coordinates":return r=t.coordinates,!!Array.isArray(r)&&2===r.length&&"number"==typeof r[0]&&"number"==typeof r[1];case"crs":return vd(n=t.crs,{requiredKeys:["type","properties"],propertyValidator:e=>{switch(e){case"type":return"name"===n.type;case"properties":return vd(t=n.properties,{requiredKeys:["name"],propertyValidator:e=>"name"===e&&t.name===hd});default:return!1}var t}});default:return!1}var r,n}})){const[t,r]=e.coordinates;return new ro({longitude:t,latitude:r})}var t;return e}]].map(e=>t=>e.reduceRight((e,t)=>t(e),t));function yd(e){return ud(e,gd)}function vd(e,t={}){if("object"!=typeof e||null===e)return!1;const r=Object.keys(e);if(t.requiredKeys)for(const e of t.requiredKeys)if(!r.includes(e))return!1;if(t.propertyValidator)for(const e of r)if(!t.propertyValidator(e))return!1;return!0}var bd,_d,wd,Sd;!function(e){e.Classic="classic",e.EdgeNGram="edgeNGram",e.Keyword="keyword_v2",e.Letter="letter",e.Lowercase="lowercase",e.MicrosoftLanguageTokenizer="microsoft_language_tokenizer",e.MicrosoftLanguageStemmingTokenizer="microsoft_language_stemming_tokenizer",e.NGram="nGram",e.PathHierarchy="path_hierarchy_v2",e.Pattern="pattern",e.Standard="standard_v2",e.UaxUrlEmail="uax_url_email",e.Whitespace="whitespace"}(bd||(bd={})),function(e){e.ArabicNormalization="arabic_normalization",e.Apostrophe="apostrophe",e.AsciiFolding="asciifolding",e.CjkBigram="cjk_bigram",e.CjkWidth="cjk_width",e.Classic="classic",e.CommonGram="common_grams",e.EdgeNGram="edgeNGram_v2",e.Elision="elision",e.GermanNormalization="german_normalization",e.HindiNormalization="hindi_normalization",e.IndicNormalization="indic_normalization",e.KeywordRepeat="keyword_repeat",e.KStem="kstem",e.Length="length",e.Limit="limit",e.Lowercase="lowercase",e.NGram="nGram_v2",e.PersianNormalization="persian_normalization",e.Phonetic="phonetic",e.PorterStem="porter_stem",e.Reverse="reverse",e.ScandinavianNormalization="scandinavian_normalization",e.ScandinavianFoldingNormalization="scandinavian_folding",e.Shingle="shingle",e.Snowball="snowball",e.SoraniNormalization="sorani_normalization",e.Stemmer="stemmer",e.Stopwords="stopwords",e.Trim="trim",e.Truncate="truncate",e.Unique="unique",e.Uppercase="uppercase",e.WordDelimiter="word_delimiter"}(_d||(_d={})),function(e){e.HtmlStrip="html_strip"}(wd||(wd={})),function(e){e.ArMicrosoft="ar.microsoft",e.ArLucene="ar.lucene",e.HyLucene="hy.lucene",e.BnMicrosoft="bn.microsoft",e.EuLucene="eu.lucene",e.BgMicrosoft="bg.microsoft",e.BgLucene="bg.lucene",e.CaMicrosoft="ca.microsoft",e.CaLucene="ca.lucene",e.ZhHansMicrosoft="zh-Hans.microsoft",e.ZhHansLucene="zh-Hans.lucene",e.ZhHantMicrosoft="zh-Hant.microsoft",e.ZhHantLucene="zh-Hant.lucene",e.HrMicrosoft="hr.microsoft",e.CsMicrosoft="cs.microsoft",e.CsLucene="cs.lucene",e.DaMicrosoft="da.microsoft",e.DaLucene="da.lucene",e.NlMicrosoft="nl.microsoft",e.NlLucene="nl.lucene",e.EnMicrosoft="en.microsoft",e.EnLucene="en.lucene",e.EtMicrosoft="et.microsoft",e.FiMicrosoft="fi.microsoft",e.FiLucene="fi.lucene",e.FrMicrosoft="fr.microsoft",e.FrLucene="fr.lucene",e.GlLucene="gl.lucene",e.DeMicrosoft="de.microsoft",e.DeLucene="de.lucene",e.ElMicrosoft="el.microsoft",e.ElLucene="el.lucene",e.GuMicrosoft="gu.microsoft",e.HeMicrosoft="he.microsoft",e.HiMicrosoft="hi.microsoft",e.HiLucene="hi.lucene",e.HuMicrosoft="hu.microsoft",e.HuLucene="hu.lucene",e.IsMicrosoft="is.microsoft",e.IdMicrosoft="id.microsoft",e.IdLucene="id.lucene",e.GaLucene="ga.lucene",e.ItMicrosoft="it.microsoft",e.ItLucene="it.lucene",e.JaMicrosoft="ja.microsoft",e.JaLucene="ja.lucene",e.KnMicrosoft="kn.microsoft",e.KoMicrosoft="ko.microsoft",e.KoLucene="ko.lucene",e.LvMicrosoft="lv.microsoft",e.LvLucene="lv.lucene",e.LtMicrosoft="lt.microsoft",e.MlMicrosoft="ml.microsoft",e.MsMicrosoft="ms.microsoft",e.MrMicrosoft="mr.microsoft",e.NbMicrosoft="nb.microsoft",e.NoLucene="no.lucene",e.FaLucene="fa.lucene",e.PlMicrosoft="pl.microsoft",e.PlLucene="pl.lucene",e.PtBRMicrosoft="pt-BR.microsoft",e.PtBRLucene="pt-BR.lucene",e.PtPTMicrosoft="pt-PT.microsoft",e.PtPTLucene="pt-PT.lucene",e.PaMicrosoft="pa.microsoft",e.RoMicrosoft="ro.microsoft",e.RoLucene="ro.lucene",e.RuMicrosoft="ru.microsoft",e.RuLucene="ru.lucene",e.SrCyrillicMicrosoft="sr-cyrillic.microsoft",e.SrLatinMicrosoft="sr-latin.microsoft",e.SkMicrosoft="sk.microsoft",e.SlMicrosoft="sl.microsoft",e.EsMicrosoft="es.microsoft",e.EsLucene="es.lucene",e.SvMicrosoft="sv.microsoft",e.SvLucene="sv.lucene",e.TaMicrosoft="ta.microsoft",e.TeMicrosoft="te.microsoft",e.ThMicrosoft="th.microsoft",e.ThLucene="th.lucene",e.TrMicrosoft="tr.microsoft",e.TrLucene="tr.lucene",e.UkMicrosoft="uk.microsoft",e.UrMicrosoft="ur.microsoft",e.ViMicrosoft="vi.microsoft",e.StandardLucene="standard.lucene",e.StandardAsciiFoldingLucene="standardasciifolding.lucene",e.Keyword="keyword",e.Pattern="pattern",e.Simple="simple",e.Stop="stop",e.Whitespace="whitespace"}(Sd||(Sd={}));const Nd="2025-09-01";function kd(e){if(!e)return e;const t=[];for(const r of e)t.push(r);return t}function xd(e){if(!e)return e;const t=[];for(const r of e)switch(r.odatatype){case"#Microsoft.Azure.Search.StandardAnalyzer":case"#Microsoft.Azure.Search.StopAnalyzer":t.push(r);break;case"#Microsoft.Azure.Search.PatternAnalyzer":t.push({...r,flags:r.flags?r.flags.join("|"):void 0});break;case"#Microsoft.Azure.Search.CustomAnalyzer":t.push({...r,tokenizerName:r.tokenizerName})}return t}function Ed(e){if(!e)return e;const t=[];for(const r of e)switch(r.odatatype){case"#Microsoft.Azure.Search.StandardAnalyzer":case"#Microsoft.Azure.Search.StopAnalyzer":case"#Microsoft.Azure.Search.CustomAnalyzer":t.push(r);break;case"#Microsoft.Azure.Search.PatternAnalyzer":t.push({...r,flags:r.flags?r.flags.split("|"):void 0})}return t}function Pd(e){return e?e.map(e=>{if("Collection(Edm.ComplexType)"===e.type||"Edm.ComplexType"===e.type){return{name:e.name,type:e.type,fields:Pd(e.fields)}}{const t=e.type,r=e.synonymMaps,{retrievable:n,analyzer:a,searchAnalyzer:i,indexAnalyzer:s,normalizer:o,...c}=e;return{...c,type:t,hidden:"boolean"==typeof n?!n:n,analyzerName:a,normalizerName:o,searchAnalyzerName:i,indexAnalyzerName:s,synonymMapNames:r}}}):e}function Cd(e){return e.map(e=>{if(function(e){return"Edm.ComplexType"===e.type||"Collection(Edm.ComplexType)"===e.type}(e))return{name:e.name,type:e.type,fields:e.fields?Cd(e.fields):e.fields};{const{hidden:t,...r}=e;return{...r,retrievable:"boolean"==typeof t?!t:t,searchable:e.searchable??!1,filterable:e.filterable??!1,facetable:e.facetable??!1,sortable:e.sortable??!1,analyzer:e.analyzerName,normalizer:e.normalizerName,searchAnalyzer:e.searchAnalyzerName,indexAnalyzer:e.indexAnalyzerName,synonymMaps:e.synonymMapNames}}})}function Ad(e){if(!e)return e;const t=[];for(const r of e)"#Microsoft.Azure.Search.PatternTokenizer"===r.odatatype?t.push({...r,flags:r.flags?r.flags.join("|"):void 0}):t.push(r);return t}function Id(e){if(!e)return e;const t=[];for(const r of e)if("#Microsoft.Azure.Search.PatternTokenizer"===r.odatatype){const e=r,n=e.flags?.split("|");t.push({...r,flags:n})}else t.push(r);return t}function Od(e){return e||e}function Td(e){if(!e)return e;const t={keyName:e.keyName,keyVersion:e.keyVersion,vaultUrl:e.vaultUri};return e.accessCredentials&&(t.applicationId=e.accessCredentials.applicationId,t.applicationSecret=e.accessCredentials.applicationSecret),t}function $d(e){if(!e)return e;const t={keyName:e.keyName,keyVersion:e.keyVersion,vaultUri:e.vaultUrl};return e.applicationId&&(t.accessCredentials={applicationId:e.applicationId,applicationSecret:e.applicationSecret}),t}function zd(e){return{name:e.name,description:e.description,defaultScoringProfile:e.defaultScoringProfile,corsOptions:e.corsOptions,suggesters:e.suggesters,encryptionKey:Td(e.encryptionKey),etag:e.etag,analyzers:Ed(e.analyzers),tokenizers:Id(e.tokenizers),tokenFilters:e.tokenFilters,normalizers:e.normalizers,charFilters:e.charFilters,scoringProfiles:e.scoringProfiles,fields:Pd(e.fields),similarity:(t=e.similarity,t?(t.odatatype,t):t),semanticSearch:e.semanticSearch,vectorSearch:Md(e.vectorSearch)};var t}function Rd(e){if(!e)return e;switch(e.kind){case"azureOpenAI":{const{parameters:t}=e,r=Ud(t?.authIdentity);return{...e,parameters:{...t,authIdentity:r}}}case"customWebApi":{const{parameters:t}=e,r=Ud(t?.authIdentity);return{...e,parameters:{...t,authIdentity:r}}}}return sd.warning(`Unsupported vectorizer kind: ${e.kind}`),e}function Ld(e){if(!e)return e;if(["hnsw","exhaustiveKnn"].includes(e.kind)){const t=e,r=t.parameters?.metric;return{...t,parameters:{...t.parameters,metric:r}}}throw Error("Unsupported algorithm configuration")}function Md(e){return e?{...e,algorithms:e.algorithms?.map(Ld),vectorizers:e.vectorizers?.map(Rd)}:e}function Dd(e){const{encryptionKey:t,tokenFilters:r,analyzers:n,tokenizers:a,fields:i,similarity:s}=e;return{...e,encryptionKey:$d(t),tokenFilters:kd(r),analyzers:xd(n),tokenizers:Ad(a),fields:Cd(i),similarity:Od(s)}}function jd(e){const t={name:e.name,encryptionKey:Td(e.encryptionKey),etag:e.etag,synonyms:[]};return e.synonyms&&(t.synonyms=e.synonyms.split("\n")),t}function Fd(e){const t={name:e.name,format:"solr",encryptionKey:$d(e.encryptionKey),etag:e.etag,synonyms:e.synonyms.join("\n")};return t.encryptionKey=$d(e.encryptionKey),t}function Ud(e){return e?(e.odatatype,e):e}const qd=yl({namespace:"Microsoft.Search",packageName:"Azure.Search"}).startSpan;class Bd{serviceVersion=Nd;apiVersion=Nd;endpoint;indexName;client;constructor(e,t,r,n={}){this.endpoint=e,this.indexName=t;const a={...n,loggingOptions:{logger:sd.info,additionalAllowedHeaderNames:["elapsed-time","Location","OData-MaxVersion","OData-Version","Prefer","throttle-reason"]}};if(this.serviceVersion=n.serviceVersion??n.apiVersion??Nd,this.apiVersion=this.serviceVersion,this.client=new id(this.endpoint,this.indexName,this.serviceVersion,a),to(r)){const e=n.audience?`${n.audience}/.default`:`${ao.AzurePublicCloud}/.default`;this.client.pipeline.addPolicy(Il({credential:r,scopes:e}))}else this.client.pipeline.addPolicy(ld(r));this.client.pipeline.addPolicy(od("none"))}async getDocumentsCount(e={}){const{span:t,updatedOptions:r}=qd("SearchClient-getDocumentsCount",e);try{let e=0;return await this.client.documents.count({...r,onResponse:(t,n)=>{e=Number(t.bodyAsText),r.onResponse&&r.onResponse(t,n)}}),e}catch(e){throw t.setStatus({status:"error",error:e.message}),e}finally{t.end()}}async autocomplete(e,t,r={}){const{searchFields:n,...a}=r,i={searchText:e,suggesterName:t,searchFields:this.convertSearchFields(n),...a};if(!i.searchText)throw new RangeError("searchText must be provided.");if(!i.suggesterName)throw new RangeError("suggesterName must be provided.");const{span:s,updatedOptions:o}=qd("SearchClient-autocomplete",r);try{return await this.client.documents.autocompletePost(i,o)}catch(e){throw s.setStatus({status:"error",error:e.message}),e}finally{s.end()}}async searchDocuments(e,t={},r={}){const{includeTotalCount:n,orderBy:a,searchFields:i,select:s,vectorSearchOptions:o,semanticSearchOptions:c,...l}=t,{configurationName:u,errorMode:d,answers:p,captions:m,...h}=c??{},{queries:f,filterMode:g,...y}=o??{},v={...h,...y,...l,...r,searchFields:this.convertSearchFields(i),select:this.convertSelect(s)||"*",orderBy:this.convertOrderBy(a),includeTotalResultCount:n,vectorQueries:f?.map(this.convertVectorQuery.bind(this)),answers:this.convertQueryAnswers(p),captions:this.convertQueryCaptions(m),semanticErrorHandling:d,semanticConfigurationName:u,vectorFilterMode:g},{span:b,updatedOptions:_}=qd("SearchClient-searchDocuments",t);try{const t=await this.client.documents.searchPost({...v,searchText:e},_),{results:r,nextLink:n,nextPageParameters:a,semanticPartialResponseReason:i,semanticPartialResponseType:s,...o}=t,c=function(e){const t=e.map(e=>{const{_score:t,_highlights:r,_rerankerScore:n,_captions:a,rerankerBoostedScore:i,...s}=e;return{score:t,highlights:r,rerankerScore:n,rerankerBoostedScore:i,captions:a,document:s}});return t}(r);return yd({...o,results:c,semanticErrorReason:i,semanticSearchResultsType:s,continuationToken:this.encodeContinuationToken(n,a)})}catch(e){throw b.setStatus({status:"error",error:e.message}),e}finally{b.end()}}async*listSearchResultsPage(e,t={},r={}){let n=this.decodeContinuationToken(r.continuationToken),a=await this.searchDocuments(e,t,n?.nextPageParameters);for(yield a;a.continuationToken;)n=this.decodeContinuationToken(a.continuationToken),a=await this.searchDocuments(e,t,n?.nextPageParameters),yield a}async*listSearchResultsAll(e,t,r={}){if(yield*e.results,e.continuationToken)for await(const n of this.listSearchResultsPage(t,r,{continuationToken:e.continuationToken}))yield*n.results}listSearchResults(e,t,r={}){const n=this.listSearchResultsAll(e,t,r);return{next:()=>n.next(),[Symbol.asyncIterator](){return this},byPage:(e={})=>this.listSearchResultsPage(t,r,e)}}async search(e,t){const{span:r,updatedOptions:n}=qd("SearchClient-search",t);try{const t=await this.searchDocuments(e,n);return{...t,results:this.listSearchResults(t,e,n)}}catch(e){throw r.setStatus({status:"error",error:e.message}),e}finally{r.end()}}async suggest(e,t,r={}){const{select:n,searchFields:a,orderBy:i,...s}=r,o={searchText:e,suggesterName:t,searchFields:this.convertSearchFields(a),select:this.convertSelect(n),orderBy:this.convertOrderBy(i),...s};if(!o.searchText)throw new RangeError("searchText must be provided.");if(!o.suggesterName)throw new RangeError("suggesterName must be provided.");const{span:c,updatedOptions:l}=qd("SearchClient-suggest",r);try{const e=await this.client.documents.suggestPost(o,l);return yd({results:(u=e).results.map(e=>{const{_text:t,...r}=e;return{text:t,document:r}}),coverage:u.coverage})}catch(e){throw c.setStatus({status:"error",error:e.message}),e}finally{c.end()}var u}async getDocument(e,t={}){const{span:r,updatedOptions:n}=qd("SearchClient-getDocument",t);try{return yd(await this.client.documents.get(e,{...n,selectedFields:n.selectedFields}))}catch(e){throw r.setStatus({status:"error",error:e.message}),e}finally{r.end()}}async indexDocuments(e,t={}){const{span:r,updatedOptions:n}=qd("SearchClient-indexDocuments",t);try{let r=0;const i=await this.client.documents.index({actions:(a=e.actions,ud(a,fd))},{...n,onResponse:(e,t)=>{r=e.status,n.onResponse&&n.onResponse(e,t)}});if(t.throwOnAnyFailure&&207===r)throw i;return i}catch(e){throw r.setStatus({status:"error",error:e.message}),e}finally{r.end()}var a}async uploadDocuments(e,t={}){const{span:r,updatedOptions:n}=qd("SearchClient-uploadDocuments",t),a=new no;a.upload(e);try{return await this.indexDocuments(a,n)}catch(e){throw r.setStatus({status:"error",error:e.message}),e}finally{r.end()}}async mergeDocuments(e,t={}){const{span:r,updatedOptions:n}=qd("SearchClient-mergeDocuments",t),a=new no;a.merge(e);try{return await this.indexDocuments(a,n)}catch(e){throw r.setStatus({status:"error",error:e.message}),e}finally{r.end()}}async mergeOrUploadDocuments(e,t={}){const{span:r,updatedOptions:n}=qd("SearchClient-mergeDocuments",t),a=new no;a.mergeOrUpload(e);try{return await this.indexDocuments(a,n)}catch(e){throw r.setStatus({status:"error",error:e.message}),e}finally{r.end()}}async deleteDocuments(e,t,r={}){const{span:n,updatedOptions:a}=qd("SearchClient-deleteDocuments",r),i=new no;"string"==typeof e?i.delete(e,t):i.delete(e);try{return await this.indexDocuments(i,a)}catch(e){throw n.setStatus({status:"error",error:e.message}),e}finally{n.end()}}encodeContinuationToken(e,t){if(!e||!t)return;const r=JSON.stringify({apiVersion:this.apiVersion,nextLink:e,nextPageParameters:t});return n=r,Buffer.from(n).toString("base64");var n}decodeContinuationToken(e){if(!e)return;const t=(r=e,Buffer.from(r,"base64").toString());var r;try{const e=JSON.parse(t);if(e.apiVersion!==this.apiVersion)throw new RangeError(`Continuation token uses unsupported apiVersion "${this.apiVersion}"`);return{nextLink:e.nextLink,nextPageParameters:e.nextPageParameters}}catch(e){throw new Error(`Corrupted or invalid continuation token: ${t}`)}}convertSelect(e){return e?e.join(","):e}convertVectorQueryFields(e){return e?e.join(","):e}convertSearchFields(e){return e?e.join(","):e}convertOrderBy(e){return e?e.join(","):e}convertQueryAnswers(e){if(!e)return e;const t=[],{answerType:r,count:n,threshold:a}=e;return n&&t.push(`count-${n}`),a&&t.push(`threshold-${a}`),t.length?r+`|${t.join(",")}`:r}convertQueryCaptions(e){if(!e)return e;const t=[],{captionType:r,highlight:n}=e;return void 0!==n&&t.push(`highlight-${n}`),t.length?r+`|${t.join(",")}`:r}convertVectorQuery(e){return{...e,fields:this.convertVectorQueryFields(e?.fields)}}}const Vd={type:{name:"Composite",className:"SearchIndexerDataSource",modelProperties:{name:{serializedName:"name",required:!0,type:{name:"String"}},description:{serializedName:"description",type:{name:"String"}},type:{serializedName:"type",required:!0,type:{name:"String"}},credentials:{serializedName:"credentials",type:{name:"Composite",className:"DataSourceCredentials"}},container:{serializedName:"container",type:{name:"Composite",className:"SearchIndexerDataContainer"}},dataChangeDetectionPolicy:{serializedName:"dataChangeDetectionPolicy",type:{name:"Composite",className:"DataChangeDetectionPolicy"}},dataDeletionDetectionPolicy:{serializedName:"dataDeletionDetectionPolicy",type:{name:"Composite",className:"DataDeletionDetectionPolicy"}},etag:{serializedName:"@odata\\.etag",type:{name:"String"}},encryptionKey:{serializedName:"encryptionKey",type:{name:"Composite",className:"SearchResourceEncryptionKey"}}}}},Gd={type:{name:"Composite",className:"DataChangeDetectionPolicy",uberParent:"DataChangeDetectionPolicy",polymorphicDiscriminator:{serializedName:"@odata\\.type",clientName:"odatatype"},modelProperties:{odatatype:{serializedName:"@odata\\.type",required:!0,type:{name:"String"}}}}},Hd={type:{name:"Composite",className:"DataDeletionDetectionPolicy",uberParent:"DataDeletionDetectionPolicy",polymorphicDiscriminator:{serializedName:"@odata\\.type",clientName:"odatatype"},modelProperties:{odatatype:{serializedName:"@odata\\.type",required:!0,type:{name:"String"}}}}},Kd={type:{name:"Composite",className:"ErrorResponse",modelProperties:{error:{serializedName:"error",type:{name:"Composite",className:"ErrorDetail"}}}}},Wd={type:{name:"Composite",className:"ListDataSourcesResult",modelProperties:{dataSources:{serializedName:"value",required:!0,readOnly:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"SearchIndexerDataSource"}}}}}}},Zd={type:{name:"Composite",className:"SearchIndexer",modelProperties:{name:{serializedName:"name",required:!0,type:{name:"String"}},description:{serializedName:"description",type:{name:"String"}},dataSourceName:{serializedName:"dataSourceName",required:!0,type:{name:"String"}},skillsetName:{serializedName:"skillsetName",type:{name:"String"}},targetIndexName:{serializedName:"targetIndexName",required:!0,type:{name:"String"}},schedule:{serializedName:"schedule",type:{name:"Composite",className:"IndexingSchedule"}},parameters:{serializedName:"parameters",type:{name:"Composite",className:"IndexingParameters"}},fieldMappings:{serializedName:"fieldMappings",type:{name:"Sequence",element:{type:{name:"Composite",className:"FieldMapping"}}}},outputFieldMappings:{serializedName:"outputFieldMappings",type:{name:"Sequence",element:{type:{name:"Composite",className:"FieldMapping"}}}},isDisabled:{defaultValue:!1,serializedName:"disabled",nullable:!0,type:{name:"Boolean"}},etag:{serializedName:"@odata\\.etag",type:{name:"String"}},encryptionKey:{serializedName:"encryptionKey",type:{name:"Composite",className:"SearchResourceEncryptionKey"}}}}},Jd={type:{name:"Composite",className:"ListIndexersResult",modelProperties:{indexers:{serializedName:"value",required:!0,readOnly:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"SearchIndexer"}}}}}}},Yd={type:{name:"Composite",className:"SearchIndexerStatus",modelProperties:{name:{serializedName:"name",required:!0,readOnly:!0,type:{name:"String"}},status:{serializedName:"status",required:!0,readOnly:!0,type:{name:"Enum",allowedValues:["unknown","error","running"]}},lastResult:{serializedName:"lastResult",type:{name:"Composite",className:"IndexerExecutionResult"}},executionHistory:{serializedName:"executionHistory",required:!0,readOnly:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"IndexerExecutionResult"}}}},limits:{serializedName:"limits",type:{name:"Composite",className:"SearchIndexerLimits"}}}}},Qd={type:{name:"Composite",className:"SearchIndexerSkillset",modelProperties:{name:{serializedName:"name",required:!0,type:{name:"String"}},description:{serializedName:"description",type:{name:"String"}},skills:{serializedName:"skills",required:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"SearchIndexerSkill"}}}},cognitiveServicesAccount:{serializedName:"cognitiveServices",type:{name:"Composite",className:"CognitiveServicesAccount"}},knowledgeStore:{serializedName:"knowledgeStore",type:{name:"Composite",className:"SearchIndexerKnowledgeStore"}},indexProjection:{serializedName:"indexProjections",type:{name:"Composite",className:"SearchIndexerIndexProjection"}},etag:{serializedName:"@odata\\.etag",type:{name:"String"}},encryptionKey:{serializedName:"encryptionKey",type:{name:"Composite",className:"SearchResourceEncryptionKey"}}}}},Xd={type:{name:"Composite",className:"SearchIndexerSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:{serializedName:"@odata\\.type",clientName:"odatatype"},modelProperties:{odatatype:{serializedName:"@odata\\.type",required:!0,type:{name:"String"}},name:{serializedName:"name",type:{name:"String"}},description:{serializedName:"description",type:{name:"String"}},context:{serializedName:"context",type:{name:"String"}},inputs:{serializedName:"inputs",required:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"InputFieldMappingEntry"}}}},outputs:{serializedName:"outputs",required:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"OutputFieldMappingEntry"}}}}}}},ep={type:{name:"Composite",className:"CognitiveServicesAccount",uberParent:"CognitiveServicesAccount",polymorphicDiscriminator:{serializedName:"@odata\\.type",clientName:"odatatype"},modelProperties:{odatatype:{serializedName:"@odata\\.type",required:!0,type:{name:"String"}},description:{serializedName:"description",type:{name:"String"}}}}},tp={type:{name:"Composite",className:"SearchIndexerKnowledgeStoreProjectionSelector",modelProperties:{referenceKeyName:{serializedName:"referenceKeyName",type:{name:"String"}},generatedKeyName:{serializedName:"generatedKeyName",type:{name:"String"}},source:{serializedName:"source",type:{name:"String"}},sourceContext:{serializedName:"sourceContext",type:{name:"String"}},inputs:{serializedName:"inputs",type:{name:"Sequence",element:{type:{name:"Composite",className:"InputFieldMappingEntry"}}}}}}},rp={type:{name:"Composite",className:"ListSkillsetsResult",modelProperties:{skillsets:{serializedName:"value",required:!0,readOnly:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"SearchIndexerSkillset"}}}}}}},np={type:{name:"Composite",className:"SynonymMap",modelProperties:{name:{serializedName:"name",required:!0,type:{name:"String"}},format:{defaultValue:"solr",isConstant:!0,serializedName:"format",type:{name:"String"}},synonyms:{serializedName:"synonyms",required:!0,type:{name:"String"}},encryptionKey:{serializedName:"encryptionKey",type:{name:"Composite",className:"SearchResourceEncryptionKey"}},etag:{serializedName:"@odata\\.etag",type:{name:"String"}}}}},ap={type:{name:"Composite",className:"ListSynonymMapsResult",modelProperties:{synonymMaps:{serializedName:"value",required:!0,readOnly:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"SynonymMap"}}}}}}},ip={type:{name:"Composite",className:"SearchIndex",modelProperties:{name:{serializedName:"name",required:!0,type:{name:"String"}},description:{serializedName:"description",type:{name:"String"}},fields:{serializedName:"fields",required:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"SearchField"}}}},scoringProfiles:{serializedName:"scoringProfiles",type:{name:"Sequence",element:{type:{name:"Composite",className:"ScoringProfile"}}}},defaultScoringProfile:{serializedName:"defaultScoringProfile",type:{name:"String"}},corsOptions:{serializedName:"corsOptions",type:{name:"Composite",className:"CorsOptions"}},suggesters:{serializedName:"suggesters",type:{name:"Sequence",element:{type:{name:"Composite",className:"Suggester"}}}},analyzers:{serializedName:"analyzers",type:{name:"Sequence",element:{type:{name:"Composite",className:"LexicalAnalyzer"}}}},tokenizers:{serializedName:"tokenizers",type:{name:"Sequence",element:{type:{name:"Composite",className:"LexicalTokenizer"}}}},tokenFilters:{serializedName:"tokenFilters",type:{name:"Sequence",element:{type:{name:"Composite",className:"TokenFilter"}}}},charFilters:{serializedName:"charFilters",type:{name:"Sequence",element:{type:{name:"Composite",className:"CharFilter"}}}},normalizers:{serializedName:"normalizers",type:{name:"Sequence",element:{type:{name:"Composite",className:"BaseLexicalNormalizer"}}}},encryptionKey:{serializedName:"encryptionKey",type:{name:"Composite",className:"SearchResourceEncryptionKey"}},similarity:{serializedName:"similarity",type:{name:"Composite",className:"Similarity"}},semanticSearch:{serializedName:"semantic",type:{name:"Composite",className:"SemanticSearch"}},vectorSearch:{serializedName:"vectorSearch",type:{name:"Composite",className:"VectorSearch"}},etag:{serializedName:"@odata\\.etag",type:{name:"String"}}}}},sp={type:{name:"Composite",className:"ScoringFunction",uberParent:"ScoringFunction",polymorphicDiscriminator:{serializedName:"type",clientName:"type"},modelProperties:{type:{serializedName:"type",required:!0,type:{name:"String"}},fieldName:{serializedName:"fieldName",required:!0,type:{name:"String"}},boost:{serializedName:"boost",required:!0,type:{name:"Number"}},interpolation:{serializedName:"interpolation",type:{name:"Enum",allowedValues:["linear","constant","quadratic","logarithmic"]}}}}},op={type:{name:"Composite",className:"LexicalAnalyzer",uberParent:"LexicalAnalyzer",polymorphicDiscriminator:{serializedName:"@odata\\.type",clientName:"odatatype"},modelProperties:{odatatype:{serializedName:"@odata\\.type",required:!0,type:{name:"String"}},name:{serializedName:"name",required:!0,type:{name:"String"}}}}},cp={type:{name:"Composite",className:"LexicalTokenizer",uberParent:"LexicalTokenizer",polymorphicDiscriminator:{serializedName:"@odata\\.type",clientName:"odatatype"},modelProperties:{odatatype:{serializedName:"@odata\\.type",required:!0,type:{name:"String"}},name:{serializedName:"name",required:!0,type:{name:"String"}}}}},lp={type:{name:"Composite",className:"TokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:{serializedName:"@odata\\.type",clientName:"odatatype"},modelProperties:{odatatype:{serializedName:"@odata\\.type",required:!0,type:{name:"String"}},name:{serializedName:"name",required:!0,type:{name:"String"}}}}},up={type:{name:"Composite",className:"CharFilter",uberParent:"CharFilter",polymorphicDiscriminator:{serializedName:"@odata\\.type",clientName:"odatatype"},modelProperties:{odatatype:{serializedName:"@odata\\.type",required:!0,type:{name:"String"}},name:{serializedName:"name",required:!0,type:{name:"String"}}}}},dp={type:{name:"Composite",className:"BaseLexicalNormalizer",uberParent:"BaseLexicalNormalizer",polymorphicDiscriminator:{serializedName:"@odata\\.type",clientName:"odatatype"},modelProperties:{odatatype:{serializedName:"@odata\\.type",required:!0,type:{name:"String"}},name:{serializedName:"name",required:!0,type:{name:"String"}}}}},pp={type:{name:"Composite",className:"Similarity",uberParent:"Similarity",polymorphicDiscriminator:{serializedName:"@odata\\.type",clientName:"odatatype"},modelProperties:{odatatype:{serializedName:"@odata\\.type",required:!0,type:{name:"String"}}}}},mp={type:{name:"Composite",className:"VectorSearchAlgorithmConfiguration",uberParent:"VectorSearchAlgorithmConfiguration",polymorphicDiscriminator:{serializedName:"kind",clientName:"kind"},modelProperties:{name:{serializedName:"name",required:!0,type:{name:"String"}},kind:{serializedName:"kind",required:!0,type:{name:"String"}}}}},hp={type:{name:"Composite",className:"VectorSearchVectorizer",uberParent:"VectorSearchVectorizer",polymorphicDiscriminator:{serializedName:"kind",clientName:"kind"},modelProperties:{vectorizerName:{serializedName:"name",required:!0,type:{name:"String"}},kind:{serializedName:"kind",required:!0,type:{name:"String"}}}}},fp={type:{name:"Composite",className:"VectorSearchCompression",uberParent:"VectorSearchCompression",polymorphicDiscriminator:{serializedName:"kind",clientName:"kind"},modelProperties:{compressionName:{serializedName:"name",required:!0,type:{name:"String"}},kind:{serializedName:"kind",required:!0,type:{name:"String"}},rescoringOptions:{serializedName:"rescoringOptions",type:{name:"Composite",className:"RescoringOptions"}},truncationDimension:{serializedName:"truncationDimension",nullable:!0,type:{name:"Number"}},rerankWithOriginalVectors:{serializedName:"rerankWithOriginalVectors",nullable:!0,type:{name:"Boolean"}},defaultOversampling:{serializedName:"defaultOversampling",nullable:!0,type:{name:"Number"}}}}},gp={type:{name:"Composite",className:"ListIndexesResult",modelProperties:{indexes:{serializedName:"value",required:!0,readOnly:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"SearchIndex"}}}}}}},yp={type:{name:"Composite",className:"GetIndexStatisticsResult",modelProperties:{documentCount:{serializedName:"documentCount",required:!0,readOnly:!0,type:{name:"Number"}},storageSize:{serializedName:"storageSize",required:!0,readOnly:!0,type:{name:"Number"}},vectorIndexSize:{serializedName:"vectorIndexSize",required:!0,readOnly:!0,type:{name:"Number"}}}}},vp={type:{name:"Composite",className:"AnalyzeRequest",modelProperties:{text:{serializedName:"text",required:!0,type:{name:"String"}},analyzer:{serializedName:"analyzer",type:{name:"String"}},tokenizer:{serializedName:"tokenizer",type:{name:"String"}},normalizer:{serializedName:"normalizer",type:{name:"String"}},tokenFilters:{serializedName:"tokenFilters",type:{name:"Sequence",element:{type:{name:"String"}}}},charFilters:{serializedName:"charFilters",type:{name:"Sequence",element:{type:{name:"String"}}}}}}},bp={type:{name:"Composite",className:"AnalyzeResult",modelProperties:{tokens:{serializedName:"tokens",required:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"AnalyzedTokenInfo"}}}}}}},_p={type:{name:"Composite",className:"ServiceStatistics",modelProperties:{counters:{serializedName:"counters",type:{name:"Composite",className:"ServiceCounters"}},limits:{serializedName:"limits",type:{name:"Composite",className:"ServiceLimits"}}}}},wp={type:{name:"Composite",className:"AzureOpenAIParameters",modelProperties:{resourceUrl:{serializedName:"resourceUri",type:{name:"String"}},deploymentId:{serializedName:"deploymentId",type:{name:"String"}},apiKey:{serializedName:"apiKey",type:{name:"String"}},authIdentity:{serializedName:"authIdentity",type:{name:"Composite",className:"SearchIndexerDataIdentity"}},modelName:{serializedName:"modelName",type:{name:"String"}}}}},Sp={type:{name:"Composite",className:"SearchIndexerDataIdentity",uberParent:"SearchIndexerDataIdentity",polymorphicDiscriminator:{serializedName:"@odata\\.type",clientName:"odatatype"},modelProperties:{odatatype:{serializedName:"@odata\\.type",required:!0,type:{name:"String"}}}}},Np={serializedName:"#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy",type:{name:"Composite",className:"HighWaterMarkChangeDetectionPolicy",uberParent:"DataChangeDetectionPolicy",polymorphicDiscriminator:Gd.type.polymorphicDiscriminator,modelProperties:{...Gd.type.modelProperties,highWaterMarkColumnName:{serializedName:"highWaterMarkColumnName",required:!0,type:{name:"String"}}}}},kp={serializedName:"#Microsoft.Azure.Search.SqlIntegratedChangeTrackingPolicy",type:{name:"Composite",className:"SqlIntegratedChangeTrackingPolicy",uberParent:"DataChangeDetectionPolicy",polymorphicDiscriminator:Gd.type.polymorphicDiscriminator,modelProperties:{...Gd.type.modelProperties}}},xp={serializedName:"#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy",type:{name:"Composite",className:"SoftDeleteColumnDeletionDetectionPolicy",uberParent:"DataDeletionDetectionPolicy",polymorphicDiscriminator:Hd.type.polymorphicDiscriminator,modelProperties:{...Hd.type.modelProperties,softDeleteColumnName:{serializedName:"softDeleteColumnName",type:{name:"String"}},softDeleteMarkerValue:{serializedName:"softDeleteMarkerValue",type:{name:"String"}}}}},Ep={serializedName:"#Microsoft.Skills.Util.ConditionalSkill",type:{name:"Composite",className:"ConditionalSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Xd.type.polymorphicDiscriminator,modelProperties:{...Xd.type.modelProperties}}},Pp={serializedName:"#Microsoft.Skills.Text.KeyPhraseExtractionSkill",type:{name:"Composite",className:"KeyPhraseExtractionSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Xd.type.polymorphicDiscriminator,modelProperties:{...Xd.type.modelProperties,defaultLanguageCode:{serializedName:"defaultLanguageCode",type:{name:"String"}},maxKeyPhraseCount:{serializedName:"maxKeyPhraseCount",nullable:!0,type:{name:"Number"}},modelVersion:{serializedName:"modelVersion",nullable:!0,type:{name:"String"}}}}},Cp={serializedName:"#Microsoft.Skills.Vision.OcrSkill",type:{name:"Composite",className:"OcrSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Xd.type.polymorphicDiscriminator,modelProperties:{...Xd.type.modelProperties,defaultLanguageCode:{serializedName:"defaultLanguageCode",type:{name:"String"}},shouldDetectOrientation:{defaultValue:!1,serializedName:"detectOrientation",type:{name:"Boolean"}},lineEnding:{serializedName:"lineEnding",type:{name:"String"}}}}},Ap={serializedName:"#Microsoft.Skills.Vision.ImageAnalysisSkill",type:{name:"Composite",className:"ImageAnalysisSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Xd.type.polymorphicDiscriminator,modelProperties:{...Xd.type.modelProperties,defaultLanguageCode:{serializedName:"defaultLanguageCode",type:{name:"String"}},visualFeatures:{serializedName:"visualFeatures",type:{name:"Sequence",element:{type:{name:"String"}}}},details:{serializedName:"details",type:{name:"Sequence",element:{type:{name:"String"}}}}}}},Ip={serializedName:"#Microsoft.Skills.Text.LanguageDetectionSkill",type:{name:"Composite",className:"LanguageDetectionSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Xd.type.polymorphicDiscriminator,modelProperties:{...Xd.type.modelProperties,defaultCountryHint:{serializedName:"defaultCountryHint",nullable:!0,type:{name:"String"}},modelVersion:{serializedName:"modelVersion",nullable:!0,type:{name:"String"}}}}},Op={serializedName:"#Microsoft.Skills.Util.ShaperSkill",type:{name:"Composite",className:"ShaperSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Xd.type.polymorphicDiscriminator,modelProperties:{...Xd.type.modelProperties}}},Tp={serializedName:"#Microsoft.Skills.Text.MergeSkill",type:{name:"Composite",className:"MergeSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Xd.type.polymorphicDiscriminator,modelProperties:{...Xd.type.modelProperties,insertPreTag:{defaultValue:" ",serializedName:"insertPreTag",type:{name:"String"}},insertPostTag:{defaultValue:" ",serializedName:"insertPostTag",type:{name:"String"}}}}},$p={serializedName:"#Microsoft.Skills.Text.EntityRecognitionSkill",type:{name:"Composite",className:"EntityRecognitionSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Xd.type.polymorphicDiscriminator,modelProperties:{...Xd.type.modelProperties,categories:{serializedName:"categories",type:{name:"Sequence",element:{type:{name:"String"}}}},defaultLanguageCode:{serializedName:"defaultLanguageCode",type:{name:"String"}},includeTypelessEntities:{serializedName:"includeTypelessEntities",nullable:!0,type:{name:"Boolean"}},minimumPrecision:{serializedName:"minimumPrecision",nullable:!0,type:{name:"Number"}}}}},zp={serializedName:"#Microsoft.Skills.Text.SentimentSkill",type:{name:"Composite",className:"SentimentSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Xd.type.polymorphicDiscriminator,modelProperties:{...Xd.type.modelProperties,defaultLanguageCode:{serializedName:"defaultLanguageCode",type:{name:"String"}}}}},Rp={serializedName:"#Microsoft.Skills.Text.V3.SentimentSkill",type:{name:"Composite",className:"SentimentSkillV3",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Xd.type.polymorphicDiscriminator,modelProperties:{...Xd.type.modelProperties,defaultLanguageCode:{serializedName:"defaultLanguageCode",nullable:!0,type:{name:"String"}},includeOpinionMining:{defaultValue:!1,serializedName:"includeOpinionMining",type:{name:"Boolean"}},modelVersion:{serializedName:"modelVersion",nullable:!0,type:{name:"String"}}}}},Lp={serializedName:"#Microsoft.Skills.Text.V3.EntityLinkingSkill",type:{name:"Composite",className:"EntityLinkingSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Xd.type.polymorphicDiscriminator,modelProperties:{...Xd.type.modelProperties,defaultLanguageCode:{serializedName:"defaultLanguageCode",nullable:!0,type:{name:"String"}},minimumPrecision:{constraints:{InclusiveMaximum:1,InclusiveMinimum:0},serializedName:"minimumPrecision",nullable:!0,type:{name:"Number"}},modelVersion:{serializedName:"modelVersion",nullable:!0,type:{name:"String"}}}}},Mp={serializedName:"#Microsoft.Skills.Text.V3.EntityRecognitionSkill",type:{name:"Composite",className:"EntityRecognitionSkillV3",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Xd.type.polymorphicDiscriminator,modelProperties:{...Xd.type.modelProperties,categories:{serializedName:"categories",type:{name:"Sequence",element:{type:{name:"String"}}}},defaultLanguageCode:{serializedName:"defaultLanguageCode",nullable:!0,type:{name:"String"}},minimumPrecision:{constraints:{InclusiveMaximum:1,InclusiveMinimum:0},serializedName:"minimumPrecision",nullable:!0,type:{name:"Number"}},modelVersion:{serializedName:"modelVersion",nullable:!0,type:{name:"String"}}}}},Dp={serializedName:"#Microsoft.Skills.Text.PIIDetectionSkill",type:{name:"Composite",className:"PIIDetectionSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Xd.type.polymorphicDiscriminator,modelProperties:{...Xd.type.modelProperties,defaultLanguageCode:{serializedName:"defaultLanguageCode",nullable:!0,type:{name:"String"}},minimumPrecision:{constraints:{InclusiveMaximum:1,InclusiveMinimum:0},serializedName:"minimumPrecision",nullable:!0,type:{name:"Number"}},maskingMode:{serializedName:"maskingMode",type:{name:"String"}},maskingCharacter:{constraints:{MaxLength:1},serializedName:"maskingCharacter",nullable:!0,type:{name:"String"}},modelVersion:{serializedName:"modelVersion",nullable:!0,type:{name:"String"}},categories:{serializedName:"piiCategories",type:{name:"Sequence",element:{type:{name:"String"}}}},domain:{serializedName:"domain",nullable:!0,type:{name:"String"}}}}},jp={serializedName:"#Microsoft.Skills.Text.SplitSkill",type:{name:"Composite",className:"SplitSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Xd.type.polymorphicDiscriminator,modelProperties:{...Xd.type.modelProperties,defaultLanguageCode:{serializedName:"defaultLanguageCode",type:{name:"String"}},textSplitMode:{serializedName:"textSplitMode",type:{name:"String"}},maxPageLength:{serializedName:"maximumPageLength",nullable:!0,type:{name:"Number"}},pageOverlapLength:{serializedName:"pageOverlapLength",nullable:!0,type:{name:"Number"}},maximumPagesToTake:{serializedName:"maximumPagesToTake",nullable:!0,type:{name:"Number"}}}}},Fp={serializedName:"#Microsoft.Skills.Text.CustomEntityLookupSkill",type:{name:"Composite",className:"CustomEntityLookupSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Xd.type.polymorphicDiscriminator,modelProperties:{...Xd.type.modelProperties,defaultLanguageCode:{serializedName:"defaultLanguageCode",nullable:!0,type:{name:"String"}},entitiesDefinitionUri:{serializedName:"entitiesDefinitionUri",nullable:!0,type:{name:"String"}},inlineEntitiesDefinition:{serializedName:"inlineEntitiesDefinition",nullable:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"CustomEntity"}}}},globalDefaultCaseSensitive:{serializedName:"globalDefaultCaseSensitive",nullable:!0,type:{name:"Boolean"}},globalDefaultAccentSensitive:{serializedName:"globalDefaultAccentSensitive",nullable:!0,type:{name:"Boolean"}},globalDefaultFuzzyEditDistance:{serializedName:"globalDefaultFuzzyEditDistance",nullable:!0,type:{name:"Number"}}}}},Up={serializedName:"#Microsoft.Skills.Text.TranslationSkill",type:{name:"Composite",className:"TextTranslationSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Xd.type.polymorphicDiscriminator,modelProperties:{...Xd.type.modelProperties,defaultToLanguageCode:{serializedName:"defaultToLanguageCode",required:!0,type:{name:"String"}},defaultFromLanguageCode:{serializedName:"defaultFromLanguageCode",type:{name:"String"}},suggestedFrom:{serializedName:"suggestedFrom",nullable:!0,type:{name:"String"}}}}},qp={serializedName:"#Microsoft.Skills.Util.DocumentExtractionSkill",type:{name:"Composite",className:"DocumentExtractionSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Xd.type.polymorphicDiscriminator,modelProperties:{...Xd.type.modelProperties,parsingMode:{serializedName:"parsingMode",nullable:!0,type:{name:"String"}},dataToExtract:{serializedName:"dataToExtract",nullable:!0,type:{name:"String"}},configuration:{serializedName:"configuration",nullable:!0,type:{name:"Dictionary",value:{type:{name:"any"}}}}}}},Bp={serializedName:"#Microsoft.Skills.Util.DocumentIntelligenceLayoutSkill",type:{name:"Composite",className:"DocumentIntelligenceLayoutSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Xd.type.polymorphicDiscriminator,modelProperties:{...Xd.type.modelProperties,outputFormat:{defaultValue:"markdown",serializedName:"outputFormat",nullable:!0,type:{name:"String"}},outputMode:{defaultValue:"oneToMany",serializedName:"outputMode",nullable:!0,type:{name:"String"}},markdownHeaderDepth:{defaultValue:"h6",serializedName:"markdownHeaderDepth",nullable:!0,type:{name:"String"}},extractionOptions:{serializedName:"extractionOptions",nullable:!0,type:{name:"Sequence",element:{type:{name:"String"}}}},chunkingProperties:{serializedName:"chunkingProperties",type:{name:"Composite",className:"DocumentIntelligenceLayoutSkillChunkingProperties"}}}}},Vp={serializedName:"#Microsoft.Skills.Custom.WebApiSkill",type:{name:"Composite",className:"WebApiSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Xd.type.polymorphicDiscriminator,modelProperties:{...Xd.type.modelProperties,uri:{serializedName:"uri",required:!0,type:{name:"String"}},httpHeaders:{serializedName:"httpHeaders",type:{name:"Dictionary",value:{type:{name:"String"}}}},httpMethod:{serializedName:"httpMethod",type:{name:"String"}},timeout:{serializedName:"timeout",type:{name:"TimeSpan"}},batchSize:{serializedName:"batchSize",nullable:!0,type:{name:"Number"}},degreeOfParallelism:{serializedName:"degreeOfParallelism",nullable:!0,type:{name:"Number"}},authResourceId:{serializedName:"authResourceId",nullable:!0,type:{name:"String"}},authIdentity:{serializedName:"authIdentity",type:{name:"Composite",className:"SearchIndexerDataIdentity"}}}}},Gp={serializedName:"#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill",type:{name:"Composite",className:"AzureOpenAIEmbeddingSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Xd.type.polymorphicDiscriminator,modelProperties:{...Xd.type.modelProperties,...wp.type.modelProperties,dimensions:{serializedName:"dimensions",nullable:!0,type:{name:"Number"}}}}},Hp={serializedName:"#Microsoft.Azure.Search.DefaultCognitiveServices",type:{name:"Composite",className:"DefaultCognitiveServicesAccount",uberParent:"CognitiveServicesAccount",polymorphicDiscriminator:ep.type.polymorphicDiscriminator,modelProperties:{...ep.type.modelProperties}}},Kp={serializedName:"#Microsoft.Azure.Search.CognitiveServicesByKey",type:{name:"Composite",className:"CognitiveServicesAccountKey",uberParent:"CognitiveServicesAccount",polymorphicDiscriminator:ep.type.polymorphicDiscriminator,modelProperties:{...ep.type.modelProperties,key:{serializedName:"key",required:!0,type:{name:"String"}}}}},Wp={type:{name:"Composite",className:"SearchIndexerKnowledgeStoreTableProjectionSelector",modelProperties:{...tp.type.modelProperties,tableName:{serializedName:"tableName",required:!0,type:{name:"String"}}}}},Zp={type:{name:"Composite",className:"SearchIndexerKnowledgeStoreBlobProjectionSelector",modelProperties:{...tp.type.modelProperties,storageContainer:{serializedName:"storageContainer",required:!0,type:{name:"String"}}}}},Jp={serializedName:"distance",type:{name:"Composite",className:"DistanceScoringFunction",uberParent:"ScoringFunction",polymorphicDiscriminator:sp.type.polymorphicDiscriminator,modelProperties:{...sp.type.modelProperties,parameters:{serializedName:"distance",type:{name:"Composite",className:"DistanceScoringParameters"}}}}},Yp={serializedName:"freshness",type:{name:"Composite",className:"FreshnessScoringFunction",uberParent:"ScoringFunction",polymorphicDiscriminator:sp.type.polymorphicDiscriminator,modelProperties:{...sp.type.modelProperties,parameters:{serializedName:"freshness",type:{name:"Composite",className:"FreshnessScoringParameters"}}}}},Qp={serializedName:"magnitude",type:{name:"Composite",className:"MagnitudeScoringFunction",uberParent:"ScoringFunction",polymorphicDiscriminator:sp.type.polymorphicDiscriminator,modelProperties:{...sp.type.modelProperties,parameters:{serializedName:"magnitude",type:{name:"Composite",className:"MagnitudeScoringParameters"}}}}},Xp={serializedName:"tag",type:{name:"Composite",className:"TagScoringFunction",uberParent:"ScoringFunction",polymorphicDiscriminator:sp.type.polymorphicDiscriminator,modelProperties:{...sp.type.modelProperties,parameters:{serializedName:"tag",type:{name:"Composite",className:"TagScoringParameters"}}}}},em={serializedName:"#Microsoft.Azure.Search.CustomAnalyzer",type:{name:"Composite",className:"CustomAnalyzer",uberParent:"LexicalAnalyzer",polymorphicDiscriminator:op.type.polymorphicDiscriminator,modelProperties:{...op.type.modelProperties,tokenizerName:{serializedName:"tokenizer",required:!0,type:{name:"String"}},tokenFilters:{serializedName:"tokenFilters",type:{name:"Sequence",element:{type:{name:"String"}}}},charFilters:{serializedName:"charFilters",type:{name:"Sequence",element:{type:{name:"String"}}}}}}},tm={serializedName:"#Microsoft.Azure.Search.PatternAnalyzer",type:{name:"Composite",className:"PatternAnalyzer",uberParent:"LexicalAnalyzer",polymorphicDiscriminator:op.type.polymorphicDiscriminator,modelProperties:{...op.type.modelProperties,lowerCaseTerms:{defaultValue:!0,serializedName:"lowercase",type:{name:"Boolean"}},pattern:{defaultValue:"W+",serializedName:"pattern",type:{name:"String"}},flags:{serializedName:"flags",type:{name:"String"}},stopwords:{serializedName:"stopwords",type:{name:"Sequence",element:{type:{name:"String"}}}}}}},rm={serializedName:"#Microsoft.Azure.Search.StandardAnalyzer",type:{name:"Composite",className:"LuceneStandardAnalyzer",uberParent:"LexicalAnalyzer",polymorphicDiscriminator:op.type.polymorphicDiscriminator,modelProperties:{...op.type.modelProperties,maxTokenLength:{defaultValue:255,constraints:{InclusiveMaximum:300},serializedName:"maxTokenLength",type:{name:"Number"}},stopwords:{serializedName:"stopwords",type:{name:"Sequence",element:{type:{name:"String"}}}}}}},nm={serializedName:"#Microsoft.Azure.Search.StopAnalyzer",type:{name:"Composite",className:"StopAnalyzer",uberParent:"LexicalAnalyzer",polymorphicDiscriminator:op.type.polymorphicDiscriminator,modelProperties:{...op.type.modelProperties,stopwords:{serializedName:"stopwords",type:{name:"Sequence",element:{type:{name:"String"}}}}}}},am={serializedName:"#Microsoft.Azure.Search.ClassicTokenizer",type:{name:"Composite",className:"ClassicTokenizer",uberParent:"LexicalTokenizer",polymorphicDiscriminator:cp.type.polymorphicDiscriminator,modelProperties:{...cp.type.modelProperties,maxTokenLength:{defaultValue:255,constraints:{InclusiveMaximum:300},serializedName:"maxTokenLength",type:{name:"Number"}}}}},im={serializedName:"#Microsoft.Azure.Search.EdgeNGramTokenizer",type:{name:"Composite",className:"EdgeNGramTokenizer",uberParent:"LexicalTokenizer",polymorphicDiscriminator:cp.type.polymorphicDiscriminator,modelProperties:{...cp.type.modelProperties,minGram:{defaultValue:1,constraints:{InclusiveMaximum:300},serializedName:"minGram",type:{name:"Number"}},maxGram:{defaultValue:2,constraints:{InclusiveMaximum:300},serializedName:"maxGram",type:{name:"Number"}},tokenChars:{serializedName:"tokenChars",type:{name:"Sequence",element:{type:{name:"Enum",allowedValues:["letter","digit","whitespace","punctuation","symbol"]}}}}}}},sm={serializedName:"#Microsoft.Azure.Search.KeywordTokenizer",type:{name:"Composite",className:"KeywordTokenizer",uberParent:"LexicalTokenizer",polymorphicDiscriminator:cp.type.polymorphicDiscriminator,modelProperties:{...cp.type.modelProperties,bufferSize:{defaultValue:256,serializedName:"bufferSize",type:{name:"Number"}}}}},om={serializedName:"#Microsoft.Azure.Search.KeywordTokenizerV2",type:{name:"Composite",className:"KeywordTokenizerV2",uberParent:"LexicalTokenizer",polymorphicDiscriminator:cp.type.polymorphicDiscriminator,modelProperties:{...cp.type.modelProperties,maxTokenLength:{defaultValue:256,constraints:{InclusiveMaximum:300},serializedName:"maxTokenLength",type:{name:"Number"}}}}},cm={serializedName:"#Microsoft.Azure.Search.MicrosoftLanguageTokenizer",type:{name:"Composite",className:"MicrosoftLanguageTokenizer",uberParent:"LexicalTokenizer",polymorphicDiscriminator:cp.type.polymorphicDiscriminator,modelProperties:{...cp.type.modelProperties,maxTokenLength:{defaultValue:255,constraints:{InclusiveMaximum:300},serializedName:"maxTokenLength",type:{name:"Number"}},isSearchTokenizer:{defaultValue:!1,serializedName:"isSearchTokenizer",type:{name:"Boolean"}},language:{serializedName:"language",type:{name:"Enum",allowedValues:["bangla","bulgarian","catalan","chineseSimplified","chineseTraditional","croatian","czech","danish","dutch","english","french","german","greek","gujarati","hindi","icelandic","indonesian","italian","japanese","kannada","korean","malay","malayalam","marathi","norwegianBokmaal","polish","portuguese","portugueseBrazilian","punjabi","romanian","russian","serbianCyrillic","serbianLatin","slovenian","spanish","swedish","tamil","telugu","thai","ukrainian","urdu","vietnamese"]}}}}},lm={serializedName:"#Microsoft.Azure.Search.MicrosoftLanguageStemmingTokenizer",type:{name:"Composite",className:"MicrosoftLanguageStemmingTokenizer",uberParent:"LexicalTokenizer",polymorphicDiscriminator:cp.type.polymorphicDiscriminator,modelProperties:{...cp.type.modelProperties,maxTokenLength:{defaultValue:255,constraints:{InclusiveMaximum:300},serializedName:"maxTokenLength",type:{name:"Number"}},isSearchTokenizer:{defaultValue:!1,serializedName:"isSearchTokenizer",type:{name:"Boolean"}},language:{serializedName:"language",type:{name:"Enum",allowedValues:["arabic","bangla","bulgarian","catalan","croatian","czech","danish","dutch","english","estonian","finnish","french","german","greek","gujarati","hebrew","hindi","hungarian","icelandic","indonesian","italian","kannada","latvian","lithuanian","malay","malayalam","marathi","norwegianBokmaal","polish","portuguese","portugueseBrazilian","punjabi","romanian","russian","serbianCyrillic","serbianLatin","slovak","slovenian","spanish","swedish","tamil","telugu","turkish","ukrainian","urdu"]}}}}},um={serializedName:"#Microsoft.Azure.Search.NGramTokenizer",type:{name:"Composite",className:"NGramTokenizer",uberParent:"LexicalTokenizer",polymorphicDiscriminator:cp.type.polymorphicDiscriminator,modelProperties:{...cp.type.modelProperties,minGram:{defaultValue:1,constraints:{InclusiveMaximum:300},serializedName:"minGram",type:{name:"Number"}},maxGram:{defaultValue:2,constraints:{InclusiveMaximum:300},serializedName:"maxGram",type:{name:"Number"}},tokenChars:{serializedName:"tokenChars",type:{name:"Sequence",element:{type:{name:"Enum",allowedValues:["letter","digit","whitespace","punctuation","symbol"]}}}}}}},dm={serializedName:"#Microsoft.Azure.Search.PathHierarchyTokenizerV2",type:{name:"Composite",className:"PathHierarchyTokenizerV2",uberParent:"LexicalTokenizer",polymorphicDiscriminator:cp.type.polymorphicDiscriminator,modelProperties:{...cp.type.modelProperties,delimiter:{defaultValue:"/",serializedName:"delimiter",type:{name:"String"}},replacement:{defaultValue:"/",serializedName:"replacement",type:{name:"String"}},maxTokenLength:{defaultValue:300,constraints:{InclusiveMaximum:300},serializedName:"maxTokenLength",type:{name:"Number"}},reverseTokenOrder:{defaultValue:!1,serializedName:"reverse",type:{name:"Boolean"}},numberOfTokensToSkip:{defaultValue:0,serializedName:"skip",type:{name:"Number"}}}}},pm={serializedName:"#Microsoft.Azure.Search.PatternTokenizer",type:{name:"Composite",className:"PatternTokenizer",uberParent:"LexicalTokenizer",polymorphicDiscriminator:cp.type.polymorphicDiscriminator,modelProperties:{...cp.type.modelProperties,pattern:{defaultValue:"W+",serializedName:"pattern",type:{name:"String"}},flags:{serializedName:"flags",type:{name:"String"}},group:{defaultValue:-1,serializedName:"group",type:{name:"Number"}}}}},mm={serializedName:"#Microsoft.Azure.Search.StandardTokenizer",type:{name:"Composite",className:"LuceneStandardTokenizer",uberParent:"LexicalTokenizer",polymorphicDiscriminator:cp.type.polymorphicDiscriminator,modelProperties:{...cp.type.modelProperties,maxTokenLength:{defaultValue:255,serializedName:"maxTokenLength",type:{name:"Number"}}}}},hm={serializedName:"#Microsoft.Azure.Search.StandardTokenizerV2",type:{name:"Composite",className:"LuceneStandardTokenizerV2",uberParent:"LexicalTokenizer",polymorphicDiscriminator:cp.type.polymorphicDiscriminator,modelProperties:{...cp.type.modelProperties,maxTokenLength:{defaultValue:255,constraints:{InclusiveMaximum:300},serializedName:"maxTokenLength",type:{name:"Number"}}}}},fm={serializedName:"#Microsoft.Azure.Search.UaxUrlEmailTokenizer",type:{name:"Composite",className:"UaxUrlEmailTokenizer",uberParent:"LexicalTokenizer",polymorphicDiscriminator:cp.type.polymorphicDiscriminator,modelProperties:{...cp.type.modelProperties,maxTokenLength:{defaultValue:255,constraints:{InclusiveMaximum:300},serializedName:"maxTokenLength",type:{name:"Number"}}}}},gm={serializedName:"#Microsoft.Azure.Search.AsciiFoldingTokenFilter",type:{name:"Composite",className:"AsciiFoldingTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,preserveOriginal:{defaultValue:!1,serializedName:"preserveOriginal",type:{name:"Boolean"}}}}},ym={serializedName:"#Microsoft.Azure.Search.CjkBigramTokenFilter",type:{name:"Composite",className:"CjkBigramTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,ignoreScripts:{serializedName:"ignoreScripts",type:{name:"Sequence",element:{type:{name:"Enum",allowedValues:["han","hiragana","katakana","hangul"]}}}},outputUnigrams:{defaultValue:!1,serializedName:"outputUnigrams",type:{name:"Boolean"}}}}},vm={serializedName:"#Microsoft.Azure.Search.CommonGramTokenFilter",type:{name:"Composite",className:"CommonGramTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,commonWords:{serializedName:"commonWords",required:!0,type:{name:"Sequence",element:{type:{name:"String"}}}},ignoreCase:{defaultValue:!1,serializedName:"ignoreCase",type:{name:"Boolean"}},useQueryMode:{defaultValue:!1,serializedName:"queryMode",type:{name:"Boolean"}}}}},bm={serializedName:"#Microsoft.Azure.Search.DictionaryDecompounderTokenFilter",type:{name:"Composite",className:"DictionaryDecompounderTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,wordList:{serializedName:"wordList",required:!0,type:{name:"Sequence",element:{type:{name:"String"}}}},minWordSize:{defaultValue:5,constraints:{InclusiveMaximum:300},serializedName:"minWordSize",type:{name:"Number"}},minSubwordSize:{defaultValue:2,constraints:{InclusiveMaximum:300},serializedName:"minSubwordSize",type:{name:"Number"}},maxSubwordSize:{defaultValue:15,constraints:{InclusiveMaximum:300},serializedName:"maxSubwordSize",type:{name:"Number"}},onlyLongestMatch:{defaultValue:!1,serializedName:"onlyLongestMatch",type:{name:"Boolean"}}}}},_m={serializedName:"#Microsoft.Azure.Search.EdgeNGramTokenFilter",type:{name:"Composite",className:"EdgeNGramTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,minGram:{defaultValue:1,serializedName:"minGram",type:{name:"Number"}},maxGram:{defaultValue:2,serializedName:"maxGram",type:{name:"Number"}},side:{serializedName:"side",type:{name:"Enum",allowedValues:["front","back"]}}}}},wm={serializedName:"#Microsoft.Azure.Search.EdgeNGramTokenFilterV2",type:{name:"Composite",className:"EdgeNGramTokenFilterV2",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,minGram:{defaultValue:1,constraints:{InclusiveMaximum:300},serializedName:"minGram",type:{name:"Number"}},maxGram:{defaultValue:2,constraints:{InclusiveMaximum:300},serializedName:"maxGram",type:{name:"Number"}},side:{serializedName:"side",type:{name:"Enum",allowedValues:["front","back"]}}}}},Sm={serializedName:"#Microsoft.Azure.Search.ElisionTokenFilter",type:{name:"Composite",className:"ElisionTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,articles:{serializedName:"articles",type:{name:"Sequence",element:{type:{name:"String"}}}}}}},Nm={serializedName:"#Microsoft.Azure.Search.KeepTokenFilter",type:{name:"Composite",className:"KeepTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,keepWords:{serializedName:"keepWords",required:!0,type:{name:"Sequence",element:{type:{name:"String"}}}},lowerCaseKeepWords:{defaultValue:!1,serializedName:"keepWordsCase",type:{name:"Boolean"}}}}},km={serializedName:"#Microsoft.Azure.Search.KeywordMarkerTokenFilter",type:{name:"Composite",className:"KeywordMarkerTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,keywords:{serializedName:"keywords",required:!0,type:{name:"Sequence",element:{type:{name:"String"}}}},ignoreCase:{defaultValue:!1,serializedName:"ignoreCase",type:{name:"Boolean"}}}}},xm={serializedName:"#Microsoft.Azure.Search.LengthTokenFilter",type:{name:"Composite",className:"LengthTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,minLength:{defaultValue:0,constraints:{InclusiveMaximum:300},serializedName:"min",type:{name:"Number"}},maxLength:{defaultValue:300,constraints:{InclusiveMaximum:300},serializedName:"max",type:{name:"Number"}}}}},Em={serializedName:"#Microsoft.Azure.Search.LimitTokenFilter",type:{name:"Composite",className:"LimitTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,maxTokenCount:{defaultValue:1,serializedName:"maxTokenCount",type:{name:"Number"}},consumeAllTokens:{defaultValue:!1,serializedName:"consumeAllTokens",type:{name:"Boolean"}}}}},Pm={serializedName:"#Microsoft.Azure.Search.NGramTokenFilter",type:{name:"Composite",className:"NGramTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,minGram:{defaultValue:1,serializedName:"minGram",type:{name:"Number"}},maxGram:{defaultValue:2,serializedName:"maxGram",type:{name:"Number"}}}}},Cm={serializedName:"#Microsoft.Azure.Search.NGramTokenFilterV2",type:{name:"Composite",className:"NGramTokenFilterV2",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,minGram:{defaultValue:1,constraints:{InclusiveMaximum:300},serializedName:"minGram",type:{name:"Number"}},maxGram:{defaultValue:2,constraints:{InclusiveMaximum:300},serializedName:"maxGram",type:{name:"Number"}}}}},Am={serializedName:"#Microsoft.Azure.Search.PatternCaptureTokenFilter",type:{name:"Composite",className:"PatternCaptureTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,patterns:{serializedName:"patterns",required:!0,type:{name:"Sequence",element:{type:{name:"String"}}}},preserveOriginal:{defaultValue:!0,serializedName:"preserveOriginal",type:{name:"Boolean"}}}}},Im={serializedName:"#Microsoft.Azure.Search.PatternReplaceTokenFilter",type:{name:"Composite",className:"PatternReplaceTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,pattern:{serializedName:"pattern",required:!0,type:{name:"String"}},replacement:{serializedName:"replacement",required:!0,type:{name:"String"}}}}},Om={serializedName:"#Microsoft.Azure.Search.PhoneticTokenFilter",type:{name:"Composite",className:"PhoneticTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,encoder:{serializedName:"encoder",type:{name:"Enum",allowedValues:["metaphone","doubleMetaphone","soundex","refinedSoundex","caverphone1","caverphone2","cologne","nysiis","koelnerPhonetik","haasePhonetik","beiderMorse"]}},replaceOriginalTokens:{defaultValue:!0,serializedName:"replace",type:{name:"Boolean"}}}}},Tm={serializedName:"#Microsoft.Azure.Search.ShingleTokenFilter",type:{name:"Composite",className:"ShingleTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,maxShingleSize:{defaultValue:2,constraints:{InclusiveMinimum:2},serializedName:"maxShingleSize",type:{name:"Number"}},minShingleSize:{defaultValue:2,constraints:{InclusiveMinimum:2},serializedName:"minShingleSize",type:{name:"Number"}},outputUnigrams:{defaultValue:!0,serializedName:"outputUnigrams",type:{name:"Boolean"}},outputUnigramsIfNoShingles:{defaultValue:!1,serializedName:"outputUnigramsIfNoShingles",type:{name:"Boolean"}},tokenSeparator:{defaultValue:" ",serializedName:"tokenSeparator",type:{name:"String"}},filterToken:{defaultValue:"_",serializedName:"filterToken",type:{name:"String"}}}}},$m={serializedName:"#Microsoft.Azure.Search.SnowballTokenFilter",type:{name:"Composite",className:"SnowballTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,language:{serializedName:"language",required:!0,type:{name:"Enum",allowedValues:["armenian","basque","catalan","danish","dutch","english","finnish","french","german","german2","hungarian","italian","kp","lovins","norwegian","porter","portuguese","romanian","russian","spanish","swedish","turkish"]}}}}},zm={serializedName:"#Microsoft.Azure.Search.StemmerTokenFilter",type:{name:"Composite",className:"StemmerTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,language:{serializedName:"language",required:!0,type:{name:"Enum",allowedValues:["arabic","armenian","basque","brazilian","bulgarian","catalan","czech","danish","dutch","dutchKp","english","lightEnglish","minimalEnglish","possessiveEnglish","porter2","lovins","finnish","lightFinnish","french","lightFrench","minimalFrench","galician","minimalGalician","german","german2","lightGerman","minimalGerman","greek","hindi","hungarian","lightHungarian","indonesian","irish","italian","lightItalian","sorani","latvian","norwegian","lightNorwegian","minimalNorwegian","lightNynorsk","minimalNynorsk","portuguese","lightPortuguese","minimalPortuguese","portugueseRslp","romanian","russian","lightRussian","spanish","lightSpanish","swedish","lightSwedish","turkish"]}}}}},Rm={serializedName:"#Microsoft.Azure.Search.StemmerOverrideTokenFilter",type:{name:"Composite",className:"StemmerOverrideTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,rules:{serializedName:"rules",required:!0,type:{name:"Sequence",element:{type:{name:"String"}}}}}}},Lm={serializedName:"#Microsoft.Azure.Search.StopwordsTokenFilter",type:{name:"Composite",className:"StopwordsTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,stopwords:{serializedName:"stopwords",type:{name:"Sequence",element:{type:{name:"String"}}}},stopwordsList:{serializedName:"stopwordsList",type:{name:"Enum",allowedValues:["arabic","armenian","basque","brazilian","bulgarian","catalan","czech","danish","dutch","english","finnish","french","galician","german","greek","hindi","hungarian","indonesian","irish","italian","latvian","norwegian","persian","portuguese","romanian","russian","sorani","spanish","swedish","thai","turkish"]}},ignoreCase:{defaultValue:!1,serializedName:"ignoreCase",type:{name:"Boolean"}},removeTrailingStopWords:{defaultValue:!0,serializedName:"removeTrailing",type:{name:"Boolean"}}}}},Mm={serializedName:"#Microsoft.Azure.Search.SynonymTokenFilter",type:{name:"Composite",className:"SynonymTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,synonyms:{serializedName:"synonyms",required:!0,type:{name:"Sequence",element:{type:{name:"String"}}}},ignoreCase:{defaultValue:!1,serializedName:"ignoreCase",type:{name:"Boolean"}},expand:{defaultValue:!0,serializedName:"expand",type:{name:"Boolean"}}}}},Dm={serializedName:"#Microsoft.Azure.Search.TruncateTokenFilter",type:{name:"Composite",className:"TruncateTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,length:{defaultValue:300,constraints:{InclusiveMaximum:300},serializedName:"length",type:{name:"Number"}}}}},jm={serializedName:"#Microsoft.Azure.Search.UniqueTokenFilter",type:{name:"Composite",className:"UniqueTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,onlyOnSamePosition:{defaultValue:!1,serializedName:"onlyOnSamePosition",type:{name:"Boolean"}}}}},Fm={serializedName:"#Microsoft.Azure.Search.WordDelimiterTokenFilter",type:{name:"Composite",className:"WordDelimiterTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:lp.type.polymorphicDiscriminator,modelProperties:{...lp.type.modelProperties,generateWordParts:{defaultValue:!0,serializedName:"generateWordParts",type:{name:"Boolean"}},generateNumberParts:{defaultValue:!0,serializedName:"generateNumberParts",type:{name:"Boolean"}},catenateWords:{defaultValue:!1,serializedName:"catenateWords",type:{name:"Boolean"}},catenateNumbers:{defaultValue:!1,serializedName:"catenateNumbers",type:{name:"Boolean"}},catenateAll:{defaultValue:!1,serializedName:"catenateAll",type:{name:"Boolean"}},splitOnCaseChange:{defaultValue:!0,serializedName:"splitOnCaseChange",type:{name:"Boolean"}},preserveOriginal:{defaultValue:!1,serializedName:"preserveOriginal",type:{name:"Boolean"}},splitOnNumerics:{defaultValue:!0,serializedName:"splitOnNumerics",type:{name:"Boolean"}},stemEnglishPossessive:{defaultValue:!0,serializedName:"stemEnglishPossessive",type:{name:"Boolean"}},protectedWords:{serializedName:"protectedWords",type:{name:"Sequence",element:{type:{name:"String"}}}}}}},Um={serializedName:"#Microsoft.Azure.Search.MappingCharFilter",type:{name:"Composite",className:"MappingCharFilter",uberParent:"CharFilter",polymorphicDiscriminator:up.type.polymorphicDiscriminator,modelProperties:{...up.type.modelProperties,mappings:{serializedName:"mappings",required:!0,type:{name:"Sequence",element:{type:{name:"String"}}}}}}},qm={serializedName:"#Microsoft.Azure.Search.PatternReplaceCharFilter",type:{name:"Composite",className:"PatternReplaceCharFilter",uberParent:"CharFilter",polymorphicDiscriminator:up.type.polymorphicDiscriminator,modelProperties:{...up.type.modelProperties,pattern:{serializedName:"pattern",required:!0,type:{name:"String"}},replacement:{serializedName:"replacement",required:!0,type:{name:"String"}}}}},Bm={serializedName:"#Microsoft.Azure.Search.CustomNormalizer",type:{name:"Composite",className:"CustomLexicalNormalizer",uberParent:"BaseLexicalNormalizer",polymorphicDiscriminator:dp.type.polymorphicDiscriminator,modelProperties:{...dp.type.modelProperties,tokenFilters:{serializedName:"tokenFilters",type:{name:"Sequence",element:{type:{name:"String"}}}},charFilters:{serializedName:"charFilters",type:{name:"Sequence",element:{type:{name:"String"}}}}}}},Vm={serializedName:"#Microsoft.Azure.Search.ClassicSimilarity",type:{name:"Composite",className:"ClassicSimilarity",uberParent:"Similarity",polymorphicDiscriminator:pp.type.polymorphicDiscriminator,modelProperties:{...pp.type.modelProperties}}},Gm={serializedName:"#Microsoft.Azure.Search.BM25Similarity",type:{name:"Composite",className:"BM25Similarity",uberParent:"Similarity",polymorphicDiscriminator:pp.type.polymorphicDiscriminator,modelProperties:{...pp.type.modelProperties,k1:{serializedName:"k1",nullable:!0,type:{name:"Number"}},b:{serializedName:"b",nullable:!0,type:{name:"Number"}}}}},Hm={serializedName:"hnsw",type:{name:"Composite",className:"HnswAlgorithmConfiguration",uberParent:"VectorSearchAlgorithmConfiguration",polymorphicDiscriminator:mp.type.polymorphicDiscriminator,modelProperties:{...mp.type.modelProperties,parameters:{serializedName:"hnswParameters",type:{name:"Composite",className:"HnswParameters"}}}}},Km={serializedName:"exhaustiveKnn",type:{name:"Composite",className:"ExhaustiveKnnAlgorithmConfiguration",uberParent:"VectorSearchAlgorithmConfiguration",polymorphicDiscriminator:mp.type.polymorphicDiscriminator,modelProperties:{...mp.type.modelProperties,parameters:{serializedName:"exhaustiveKnnParameters",type:{name:"Composite",className:"ExhaustiveKnnParameters"}}}}},Wm={serializedName:"azureOpenAI",type:{name:"Composite",className:"AzureOpenAIVectorizer",uberParent:"VectorSearchVectorizer",polymorphicDiscriminator:hp.type.polymorphicDiscriminator,modelProperties:{...hp.type.modelProperties,parameters:{serializedName:"azureOpenAIParameters",type:{name:"Composite",className:"AzureOpenAIParameters"}}}}},Zm={serializedName:"customWebApi",type:{name:"Composite",className:"WebApiVectorizer",uberParent:"VectorSearchVectorizer",polymorphicDiscriminator:hp.type.polymorphicDiscriminator,modelProperties:{...hp.type.modelProperties,parameters:{serializedName:"customWebApiParameters",type:{name:"Composite",className:"WebApiParameters"}}}}},Jm={serializedName:"scalarQuantization",type:{name:"Composite",className:"ScalarQuantizationCompression",uberParent:"VectorSearchCompression",polymorphicDiscriminator:fp.type.polymorphicDiscriminator,modelProperties:{...fp.type.modelProperties,parameters:{serializedName:"scalarQuantizationParameters",type:{name:"Composite",className:"ScalarQuantizationParameters"}}}}},Ym={serializedName:"binaryQuantization",type:{name:"Composite",className:"BinaryQuantizationCompression",uberParent:"VectorSearchCompression",polymorphicDiscriminator:fp.type.polymorphicDiscriminator,modelProperties:{...fp.type.modelProperties}}},Qm={serializedName:"#Microsoft.Azure.Search.DataNoneIdentity",type:{name:"Composite",className:"SearchIndexerDataNoneIdentity",uberParent:"SearchIndexerDataIdentity",polymorphicDiscriminator:Sp.type.polymorphicDiscriminator,modelProperties:{...Sp.type.modelProperties}}},Xm={serializedName:"#Microsoft.Azure.Search.DataUserAssignedIdentity",type:{name:"Composite",className:"SearchIndexerDataUserAssignedIdentity",uberParent:"SearchIndexerDataIdentity",polymorphicDiscriminator:Sp.type.polymorphicDiscriminator,modelProperties:{...Sp.type.modelProperties,resourceId:{serializedName:"userAssignedIdentity",required:!0,type:{name:"String"}}}}},eh={type:{name:"Composite",className:"SearchIndexerKnowledgeStoreObjectProjectionSelector",modelProperties:{...Zp.type.modelProperties}}},th={type:{name:"Composite",className:"SearchIndexerKnowledgeStoreFileProjectionSelector",modelProperties:{...Zp.type.modelProperties}}};let rh={DataChangeDetectionPolicy:Gd,DataDeletionDetectionPolicy:Hd,SearchIndexerSkill:Xd,CognitiveServicesAccount:ep,ScoringFunction:sp,LexicalAnalyzer:op,LexicalTokenizer:cp,TokenFilter:lp,CharFilter:up,BaseLexicalNormalizer:dp,Similarity:pp,VectorSearchAlgorithmConfiguration:mp,VectorSearchVectorizer:hp,VectorSearchCompression:fp,SearchIndexerDataIdentity:Sp,"DataChangeDetectionPolicy.#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy":Np,"DataChangeDetectionPolicy.#Microsoft.Azure.Search.SqlIntegratedChangeTrackingPolicy":kp,"DataDeletionDetectionPolicy.#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy":xp,"SearchIndexerSkill.#Microsoft.Skills.Util.ConditionalSkill":Ep,"SearchIndexerSkill.#Microsoft.Skills.Text.KeyPhraseExtractionSkill":Pp,"SearchIndexerSkill.#Microsoft.Skills.Vision.OcrSkill":Cp,"SearchIndexerSkill.#Microsoft.Skills.Vision.ImageAnalysisSkill":Ap,"SearchIndexerSkill.#Microsoft.Skills.Text.LanguageDetectionSkill":Ip,"SearchIndexerSkill.#Microsoft.Skills.Util.ShaperSkill":Op,"SearchIndexerSkill.#Microsoft.Skills.Text.MergeSkill":Tp,"SearchIndexerSkill.#Microsoft.Skills.Text.EntityRecognitionSkill":$p,"SearchIndexerSkill.#Microsoft.Skills.Text.SentimentSkill":zp,"SearchIndexerSkill.#Microsoft.Skills.Text.V3.SentimentSkill":Rp,"SearchIndexerSkill.#Microsoft.Skills.Text.V3.EntityLinkingSkill":Lp,"SearchIndexerSkill.#Microsoft.Skills.Text.V3.EntityRecognitionSkill":Mp,"SearchIndexerSkill.#Microsoft.Skills.Text.PIIDetectionSkill":Dp,"SearchIndexerSkill.#Microsoft.Skills.Text.SplitSkill":jp,"SearchIndexerSkill.#Microsoft.Skills.Text.CustomEntityLookupSkill":Fp,"SearchIndexerSkill.#Microsoft.Skills.Text.TranslationSkill":Up,"SearchIndexerSkill.#Microsoft.Skills.Util.DocumentExtractionSkill":qp,"SearchIndexerSkill.#Microsoft.Skills.Util.DocumentIntelligenceLayoutSkill":Bp,"SearchIndexerSkill.#Microsoft.Skills.Custom.WebApiSkill":Vp,"SearchIndexerSkill.#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill":Gp,"CognitiveServicesAccount.#Microsoft.Azure.Search.DefaultCognitiveServices":Hp,"CognitiveServicesAccount.#Microsoft.Azure.Search.CognitiveServicesByKey":Kp,"ScoringFunction.distance":Jp,"ScoringFunction.freshness":Yp,"ScoringFunction.magnitude":Qp,"ScoringFunction.tag":Xp,"LexicalAnalyzer.#Microsoft.Azure.Search.CustomAnalyzer":em,"LexicalAnalyzer.#Microsoft.Azure.Search.PatternAnalyzer":tm,"LexicalAnalyzer.#Microsoft.Azure.Search.StandardAnalyzer":rm,"LexicalAnalyzer.#Microsoft.Azure.Search.StopAnalyzer":nm,"LexicalTokenizer.#Microsoft.Azure.Search.ClassicTokenizer":am,"LexicalTokenizer.#Microsoft.Azure.Search.EdgeNGramTokenizer":im,"LexicalTokenizer.#Microsoft.Azure.Search.KeywordTokenizer":sm,"LexicalTokenizer.#Microsoft.Azure.Search.KeywordTokenizerV2":om,"LexicalTokenizer.#Microsoft.Azure.Search.MicrosoftLanguageTokenizer":cm,"LexicalTokenizer.#Microsoft.Azure.Search.MicrosoftLanguageStemmingTokenizer":lm,"LexicalTokenizer.#Microsoft.Azure.Search.NGramTokenizer":um,"LexicalTokenizer.#Microsoft.Azure.Search.PathHierarchyTokenizerV2":dm,"LexicalTokenizer.#Microsoft.Azure.Search.PatternTokenizer":pm,"LexicalTokenizer.#Microsoft.Azure.Search.StandardTokenizer":mm,"LexicalTokenizer.#Microsoft.Azure.Search.StandardTokenizerV2":hm,"LexicalTokenizer.#Microsoft.Azure.Search.UaxUrlEmailTokenizer":fm,"TokenFilter.#Microsoft.Azure.Search.AsciiFoldingTokenFilter":gm,"TokenFilter.#Microsoft.Azure.Search.CjkBigramTokenFilter":ym,"TokenFilter.#Microsoft.Azure.Search.CommonGramTokenFilter":vm,"TokenFilter.#Microsoft.Azure.Search.DictionaryDecompounderTokenFilter":bm,"TokenFilter.#Microsoft.Azure.Search.EdgeNGramTokenFilter":_m,"TokenFilter.#Microsoft.Azure.Search.EdgeNGramTokenFilterV2":wm,"TokenFilter.#Microsoft.Azure.Search.ElisionTokenFilter":Sm,"TokenFilter.#Microsoft.Azure.Search.KeepTokenFilter":Nm,"TokenFilter.#Microsoft.Azure.Search.KeywordMarkerTokenFilter":km,"TokenFilter.#Microsoft.Azure.Search.LengthTokenFilter":xm,"TokenFilter.#Microsoft.Azure.Search.LimitTokenFilter":Em,"TokenFilter.#Microsoft.Azure.Search.NGramTokenFilter":Pm,"TokenFilter.#Microsoft.Azure.Search.NGramTokenFilterV2":Cm,"TokenFilter.#Microsoft.Azure.Search.PatternCaptureTokenFilter":Am,"TokenFilter.#Microsoft.Azure.Search.PatternReplaceTokenFilter":Im,"TokenFilter.#Microsoft.Azure.Search.PhoneticTokenFilter":Om,"TokenFilter.#Microsoft.Azure.Search.ShingleTokenFilter":Tm,"TokenFilter.#Microsoft.Azure.Search.SnowballTokenFilter":$m,"TokenFilter.#Microsoft.Azure.Search.StemmerTokenFilter":zm,"TokenFilter.#Microsoft.Azure.Search.StemmerOverrideTokenFilter":Rm,"TokenFilter.#Microsoft.Azure.Search.StopwordsTokenFilter":Lm,"TokenFilter.#Microsoft.Azure.Search.SynonymTokenFilter":Mm,"TokenFilter.#Microsoft.Azure.Search.TruncateTokenFilter":Dm,"TokenFilter.#Microsoft.Azure.Search.UniqueTokenFilter":jm,"TokenFilter.#Microsoft.Azure.Search.WordDelimiterTokenFilter":Fm,"CharFilter.#Microsoft.Azure.Search.MappingCharFilter":Um,"CharFilter.#Microsoft.Azure.Search.PatternReplaceCharFilter":qm,"BaseLexicalNormalizer.#Microsoft.Azure.Search.CustomNormalizer":Bm,"Similarity.#Microsoft.Azure.Search.ClassicSimilarity":Vm,"Similarity.#Microsoft.Azure.Search.BM25Similarity":Gm,"VectorSearchAlgorithmConfiguration.hnsw":Hm,"VectorSearchAlgorithmConfiguration.exhaustiveKnn":Km,"VectorSearchVectorizer.azureOpenAI":Wm,"VectorSearchVectorizer.customWebApi":Zm,"VectorSearchCompression.scalarQuantization":Jm,"VectorSearchCompression.binaryQuantization":Ym,"SearchIndexerDataIdentity.#Microsoft.Azure.Search.DataNoneIdentity":Qm,"SearchIndexerDataIdentity.#Microsoft.Azure.Search.DataUserAssignedIdentity":Xm};var nh=Object.freeze({__proto__:null,AnalyzeRequest:vp,AnalyzeResult:bp,AnalyzedTokenInfo:{type:{name:"Composite",className:"AnalyzedTokenInfo",modelProperties:{token:{serializedName:"token",required:!0,readOnly:!0,type:{name:"String"}},startOffset:{serializedName:"startOffset",required:!0,readOnly:!0,type:{name:"Number"}},endOffset:{serializedName:"endOffset",required:!0,readOnly:!0,type:{name:"Number"}},position:{serializedName:"position",required:!0,readOnly:!0,type:{name:"Number"}}}}},AsciiFoldingTokenFilter:gm,AzureActiveDirectoryApplicationCredentials:{type:{name:"Composite",className:"AzureActiveDirectoryApplicationCredentials",modelProperties:{applicationId:{serializedName:"applicationId",required:!0,type:{name:"String"}},applicationSecret:{serializedName:"applicationSecret",type:{name:"String"}}}}},AzureOpenAIEmbeddingSkill:Gp,AzureOpenAIParameters:wp,AzureOpenAIVectorizer:Wm,BM25Similarity:Gm,BaseLexicalNormalizer:dp,BinaryQuantizationCompression:Ym,CharFilter:up,CjkBigramTokenFilter:ym,ClassicSimilarity:Vm,ClassicTokenizer:am,CognitiveServicesAccount:ep,CognitiveServicesAccountKey:Kp,CommonGramTokenFilter:vm,ConditionalSkill:Ep,CorsOptions:{type:{name:"Composite",className:"CorsOptions",modelProperties:{allowedOrigins:{serializedName:"allowedOrigins",required:!0,type:{name:"Sequence",element:{type:{name:"String"}}}},maxAgeInSeconds:{serializedName:"maxAgeInSeconds",nullable:!0,type:{name:"Number"}}}}},CustomAnalyzer:em,CustomEntity:{type:{name:"Composite",className:"CustomEntity",modelProperties:{name:{serializedName:"name",required:!0,type:{name:"String"}},description:{serializedName:"description",nullable:!0,type:{name:"String"}},type:{serializedName:"type",nullable:!0,type:{name:"String"}},subtype:{serializedName:"subtype",nullable:!0,type:{name:"String"}},id:{serializedName:"id",nullable:!0,type:{name:"String"}},caseSensitive:{serializedName:"caseSensitive",nullable:!0,type:{name:"Boolean"}},accentSensitive:{serializedName:"accentSensitive",nullable:!0,type:{name:"Boolean"}},fuzzyEditDistance:{serializedName:"fuzzyEditDistance",nullable:!0,type:{name:"Number"}},defaultCaseSensitive:{serializedName:"defaultCaseSensitive",nullable:!0,type:{name:"Boolean"}},defaultAccentSensitive:{serializedName:"defaultAccentSensitive",nullable:!0,type:{name:"Boolean"}},defaultFuzzyEditDistance:{serializedName:"defaultFuzzyEditDistance",nullable:!0,type:{name:"Number"}},aliases:{serializedName:"aliases",nullable:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"CustomEntityAlias"}}}}}}},CustomEntityAlias:{type:{name:"Composite",className:"CustomEntityAlias",modelProperties:{text:{serializedName:"text",required:!0,type:{name:"String"}},caseSensitive:{serializedName:"caseSensitive",nullable:!0,type:{name:"Boolean"}},accentSensitive:{serializedName:"accentSensitive",nullable:!0,type:{name:"Boolean"}},fuzzyEditDistance:{serializedName:"fuzzyEditDistance",nullable:!0,type:{name:"Number"}}}}},CustomEntityLookupSkill:Fp,CustomLexicalNormalizer:Bm,DataChangeDetectionPolicy:Gd,DataDeletionDetectionPolicy:Hd,DataSourceCredentials:{type:{name:"Composite",className:"DataSourceCredentials",modelProperties:{connectionString:{serializedName:"connectionString",type:{name:"String"}}}}},DefaultCognitiveServicesAccount:Hp,DictionaryDecompounderTokenFilter:bm,DistanceScoringFunction:Jp,DistanceScoringParameters:{type:{name:"Composite",className:"DistanceScoringParameters",modelProperties:{referencePointParameter:{serializedName:"referencePointParameter",required:!0,type:{name:"String"}},boostingDistance:{serializedName:"boostingDistance",required:!0,type:{name:"Number"}}}}},DocumentExtractionSkill:qp,DocumentIntelligenceLayoutSkill:Bp,DocumentIntelligenceLayoutSkillChunkingProperties:{type:{name:"Composite",className:"DocumentIntelligenceLayoutSkillChunkingProperties",modelProperties:{unit:{defaultValue:"characters",serializedName:"unit",nullable:!0,type:{name:"String"}},maximumLength:{serializedName:"maximumLength",nullable:!0,type:{name:"Number"}},overlapLength:{serializedName:"overlapLength",nullable:!0,type:{name:"Number"}}}}},EdgeNGramTokenFilter:_m,EdgeNGramTokenFilterV2:wm,EdgeNGramTokenizer:im,ElisionTokenFilter:Sm,EntityLinkingSkill:Lp,EntityRecognitionSkill:$p,EntityRecognitionSkillV3:Mp,ErrorAdditionalInfo:{type:{name:"Composite",className:"ErrorAdditionalInfo",modelProperties:{type:{serializedName:"type",readOnly:!0,type:{name:"String"}},info:{serializedName:"info",readOnly:!0,type:{name:"Dictionary",value:{type:{name:"any"}}}}}}},ErrorDetail:{type:{name:"Composite",className:"ErrorDetail",modelProperties:{code:{serializedName:"code",readOnly:!0,type:{name:"String"}},message:{serializedName:"message",readOnly:!0,type:{name:"String"}},target:{serializedName:"target",readOnly:!0,type:{name:"String"}},details:{serializedName:"details",readOnly:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"ErrorDetail"}}}},additionalInfo:{serializedName:"additionalInfo",readOnly:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"ErrorAdditionalInfo"}}}}}}},ErrorResponse:Kd,ExhaustiveKnnAlgorithmConfiguration:Km,ExhaustiveKnnParameters:{type:{name:"Composite",className:"ExhaustiveKnnParameters",modelProperties:{metric:{serializedName:"metric",nullable:!0,type:{name:"String"}}}}},FieldMapping:{type:{name:"Composite",className:"FieldMapping",modelProperties:{sourceFieldName:{serializedName:"sourceFieldName",required:!0,type:{name:"String"}},targetFieldName:{serializedName:"targetFieldName",type:{name:"String"}},mappingFunction:{serializedName:"mappingFunction",type:{name:"Composite",className:"FieldMappingFunction"}}}}},FieldMappingFunction:{type:{name:"Composite",className:"FieldMappingFunction",modelProperties:{name:{serializedName:"name",required:!0,type:{name:"String"}},parameters:{serializedName:"parameters",nullable:!0,type:{name:"Dictionary",value:{type:{name:"any"}}}}}}},FreshnessScoringFunction:Yp,FreshnessScoringParameters:{type:{name:"Composite",className:"FreshnessScoringParameters",modelProperties:{boostingDuration:{serializedName:"boostingDuration",required:!0,type:{name:"TimeSpan"}}}}},GetIndexStatisticsResult:yp,HighWaterMarkChangeDetectionPolicy:Np,HnswAlgorithmConfiguration:Hm,HnswParameters:{type:{name:"Composite",className:"HnswParameters",modelProperties:{m:{defaultValue:4,constraints:{InclusiveMaximum:10,InclusiveMinimum:4},serializedName:"m",nullable:!0,type:{name:"Number"}},efConstruction:{defaultValue:400,constraints:{InclusiveMaximum:1e3,InclusiveMinimum:100},serializedName:"efConstruction",nullable:!0,type:{name:"Number"}},efSearch:{defaultValue:500,constraints:{InclusiveMaximum:1e3,InclusiveMinimum:100},serializedName:"efSearch",nullable:!0,type:{name:"Number"}},metric:{serializedName:"metric",nullable:!0,type:{name:"String"}}}}},ImageAnalysisSkill:Ap,IndexerExecutionResult:{type:{name:"Composite",className:"IndexerExecutionResult",modelProperties:{status:{serializedName:"status",required:!0,readOnly:!0,type:{name:"Enum",allowedValues:["transientFailure","success","inProgress","reset"]}},errorMessage:{serializedName:"errorMessage",readOnly:!0,type:{name:"String"}},startTime:{serializedName:"startTime",readOnly:!0,type:{name:"DateTime"}},endTime:{serializedName:"endTime",readOnly:!0,nullable:!0,type:{name:"DateTime"}},errors:{serializedName:"errors",required:!0,readOnly:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"SearchIndexerError"}}}},warnings:{serializedName:"warnings",required:!0,readOnly:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"SearchIndexerWarning"}}}},itemCount:{serializedName:"itemsProcessed",required:!0,readOnly:!0,type:{name:"Number"}},failedItemCount:{serializedName:"itemsFailed",required:!0,readOnly:!0,type:{name:"Number"}},initialTrackingState:{serializedName:"initialTrackingState",readOnly:!0,type:{name:"String"}},finalTrackingState:{serializedName:"finalTrackingState",readOnly:!0,type:{name:"String"}}}}},IndexingParameters:{type:{name:"Composite",className:"IndexingParameters",modelProperties:{batchSize:{serializedName:"batchSize",nullable:!0,type:{name:"Number"}},maxFailedItems:{defaultValue:0,serializedName:"maxFailedItems",nullable:!0,type:{name:"Number"}},maxFailedItemsPerBatch:{defaultValue:0,serializedName:"maxFailedItemsPerBatch",nullable:!0,type:{name:"Number"}},configuration:{serializedName:"configuration",type:{name:"Composite",className:"IndexingParametersConfiguration"}}}}},IndexingParametersConfiguration:{type:{name:"Composite",className:"IndexingParametersConfiguration",additionalProperties:{type:{name:"Object"}},modelProperties:{parsingMode:{defaultValue:"default",serializedName:"parsingMode",type:{name:"String"}},excludedFileNameExtensions:{defaultValue:"",serializedName:"excludedFileNameExtensions",type:{name:"String"}},indexedFileNameExtensions:{defaultValue:"",serializedName:"indexedFileNameExtensions",type:{name:"String"}},failOnUnsupportedContentType:{defaultValue:!1,serializedName:"failOnUnsupportedContentType",type:{name:"Boolean"}},failOnUnprocessableDocument:{defaultValue:!1,serializedName:"failOnUnprocessableDocument",type:{name:"Boolean"}},indexStorageMetadataOnlyForOversizedDocuments:{defaultValue:!1,serializedName:"indexStorageMetadataOnlyForOversizedDocuments",type:{name:"Boolean"}},delimitedTextHeaders:{serializedName:"delimitedTextHeaders",type:{name:"String"}},delimitedTextDelimiter:{serializedName:"delimitedTextDelimiter",type:{name:"String"}},firstLineContainsHeaders:{defaultValue:!0,serializedName:"firstLineContainsHeaders",type:{name:"Boolean"}},documentRoot:{serializedName:"documentRoot",type:{name:"String"}},dataToExtract:{defaultValue:"contentAndMetadata",serializedName:"dataToExtract",type:{name:"String"}},imageAction:{defaultValue:"none",serializedName:"imageAction",type:{name:"String"}},allowSkillsetToReadFileData:{defaultValue:!1,serializedName:"allowSkillsetToReadFileData",type:{name:"Boolean"}},pdfTextRotationAlgorithm:{defaultValue:"none",serializedName:"pdfTextRotationAlgorithm",type:{name:"String"}},executionEnvironment:{defaultValue:"standard",serializedName:"executionEnvironment",type:{name:"String"}},queryTimeout:{defaultValue:"00:05:00",serializedName:"queryTimeout",type:{name:"String"}}}}},IndexingSchedule:{type:{name:"Composite",className:"IndexingSchedule",modelProperties:{interval:{serializedName:"interval",required:!0,type:{name:"TimeSpan"}},startTime:{serializedName:"startTime",type:{name:"DateTime"}}}}},InputFieldMappingEntry:{type:{name:"Composite",className:"InputFieldMappingEntry",modelProperties:{name:{serializedName:"name",required:!0,type:{name:"String"}},source:{serializedName:"source",type:{name:"String"}},sourceContext:{serializedName:"sourceContext",type:{name:"String"}},inputs:{serializedName:"inputs",type:{name:"Sequence",element:{type:{name:"Composite",className:"InputFieldMappingEntry"}}}}}}},KeepTokenFilter:Nm,KeyPhraseExtractionSkill:Pp,KeywordMarkerTokenFilter:km,KeywordTokenizer:sm,KeywordTokenizerV2:om,LanguageDetectionSkill:Ip,LengthTokenFilter:xm,LexicalAnalyzer:op,LexicalTokenizer:cp,LimitTokenFilter:Em,ListDataSourcesResult:Wd,ListIndexersResult:Jd,ListIndexesResult:gp,ListSkillsetsResult:rp,ListSynonymMapsResult:ap,LuceneStandardAnalyzer:rm,LuceneStandardTokenizer:mm,LuceneStandardTokenizerV2:hm,MagnitudeScoringFunction:Qp,MagnitudeScoringParameters:{type:{name:"Composite",className:"MagnitudeScoringParameters",modelProperties:{boostingRangeStart:{serializedName:"boostingRangeStart",required:!0,type:{name:"Number"}},boostingRangeEnd:{serializedName:"boostingRangeEnd",required:!0,type:{name:"Number"}},shouldBoostBeyondRangeByConstant:{serializedName:"constantBoostBeyondRange",type:{name:"Boolean"}}}}},MappingCharFilter:Um,MergeSkill:Tp,MicrosoftLanguageStemmingTokenizer:lm,MicrosoftLanguageTokenizer:cm,NGramTokenFilter:Pm,NGramTokenFilterV2:Cm,NGramTokenizer:um,OcrSkill:Cp,OutputFieldMappingEntry:{type:{name:"Composite",className:"OutputFieldMappingEntry",modelProperties:{name:{serializedName:"name",required:!0,type:{name:"String"}},targetName:{serializedName:"targetName",type:{name:"String"}}}}},PIIDetectionSkill:Dp,PathHierarchyTokenizerV2:dm,PatternAnalyzer:tm,PatternCaptureTokenFilter:Am,PatternReplaceCharFilter:qm,PatternReplaceTokenFilter:Im,PatternTokenizer:pm,PhoneticTokenFilter:Om,RescoringOptions:{type:{name:"Composite",className:"RescoringOptions",modelProperties:{enableRescoring:{defaultValue:!0,serializedName:"enableRescoring",nullable:!0,type:{name:"Boolean"}},defaultOversampling:{serializedName:"defaultOversampling",nullable:!0,type:{name:"Number"}},rescoreStorageMethod:{serializedName:"rescoreStorageMethod",nullable:!0,type:{name:"String"}}}}},ResourceCounter:{type:{name:"Composite",className:"ResourceCounter",modelProperties:{usage:{serializedName:"usage",required:!0,type:{name:"Number"}},quota:{serializedName:"quota",nullable:!0,type:{name:"Number"}}}}},ScalarQuantizationCompression:Jm,ScalarQuantizationParameters:{type:{name:"Composite",className:"ScalarQuantizationParameters",modelProperties:{quantizedDataType:{serializedName:"quantizedDataType",nullable:!0,type:{name:"String"}}}}},ScoringFunction:sp,ScoringProfile:{type:{name:"Composite",className:"ScoringProfile",modelProperties:{name:{serializedName:"name",required:!0,type:{name:"String"}},textWeights:{serializedName:"text",type:{name:"Composite",className:"TextWeights"}},functions:{serializedName:"functions",type:{name:"Sequence",element:{type:{name:"Composite",className:"ScoringFunction"}}}},functionAggregation:{serializedName:"functionAggregation",type:{name:"Enum",allowedValues:["sum","average","minimum","maximum","firstMatching"]}}}}},SearchField:{type:{name:"Composite",className:"SearchField",modelProperties:{name:{serializedName:"name",required:!0,type:{name:"String"}},type:{serializedName:"type",required:!0,type:{name:"String"}},key:{serializedName:"key",type:{name:"Boolean"}},retrievable:{serializedName:"retrievable",type:{name:"Boolean"}},stored:{serializedName:"stored",type:{name:"Boolean"}},searchable:{serializedName:"searchable",type:{name:"Boolean"}},filterable:{serializedName:"filterable",type:{name:"Boolean"}},sortable:{serializedName:"sortable",type:{name:"Boolean"}},facetable:{serializedName:"facetable",type:{name:"Boolean"}},analyzer:{serializedName:"analyzer",nullable:!0,type:{name:"String"}},searchAnalyzer:{serializedName:"searchAnalyzer",nullable:!0,type:{name:"String"}},indexAnalyzer:{serializedName:"indexAnalyzer",nullable:!0,type:{name:"String"}},normalizer:{serializedName:"normalizer",nullable:!0,type:{name:"String"}},vectorSearchDimensions:{constraints:{InclusiveMaximum:4096,InclusiveMinimum:2},serializedName:"dimensions",nullable:!0,type:{name:"Number"}},vectorSearchProfileName:{serializedName:"vectorSearchProfile",nullable:!0,type:{name:"String"}},vectorEncodingFormat:{serializedName:"vectorEncoding",nullable:!0,type:{name:"String"}},synonymMaps:{serializedName:"synonymMaps",type:{name:"Sequence",element:{type:{name:"String"}}}},fields:{serializedName:"fields",type:{name:"Sequence",element:{type:{name:"Composite",className:"SearchField"}}}}}}},SearchIndex:ip,SearchIndexer:Zd,SearchIndexerDataContainer:{type:{name:"Composite",className:"SearchIndexerDataContainer",modelProperties:{name:{serializedName:"name",required:!0,type:{name:"String"}},query:{serializedName:"query",type:{name:"String"}}}}},SearchIndexerDataIdentity:Sp,SearchIndexerDataNoneIdentity:Qm,SearchIndexerDataSource:Vd,SearchIndexerDataUserAssignedIdentity:Xm,SearchIndexerError:{type:{name:"Composite",className:"SearchIndexerError",modelProperties:{key:{serializedName:"key",readOnly:!0,type:{name:"String"}},errorMessage:{serializedName:"errorMessage",required:!0,readOnly:!0,type:{name:"String"}},statusCode:{serializedName:"statusCode",required:!0,readOnly:!0,type:{name:"Number"}},name:{serializedName:"name",readOnly:!0,type:{name:"String"}},details:{serializedName:"details",readOnly:!0,type:{name:"String"}},documentationLink:{serializedName:"documentationLink",readOnly:!0,type:{name:"String"}}}}},SearchIndexerIndexProjection:{type:{name:"Composite",className:"SearchIndexerIndexProjection",modelProperties:{selectors:{serializedName:"selectors",required:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"SearchIndexerIndexProjectionSelector"}}}},parameters:{serializedName:"parameters",type:{name:"Composite",className:"SearchIndexerIndexProjectionParameters"}}}}},SearchIndexerIndexProjectionParameters:{type:{name:"Composite",className:"SearchIndexerIndexProjectionParameters",additionalProperties:{type:{name:"Object"}},modelProperties:{projectionMode:{serializedName:"projectionMode",type:{name:"String"}}}}},SearchIndexerIndexProjectionSelector:{type:{name:"Composite",className:"SearchIndexerIndexProjectionSelector",modelProperties:{targetIndexName:{serializedName:"targetIndexName",required:!0,type:{name:"String"}},parentKeyFieldName:{serializedName:"parentKeyFieldName",required:!0,type:{name:"String"}},sourceContext:{serializedName:"sourceContext",required:!0,type:{name:"String"}},mappings:{serializedName:"mappings",required:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"InputFieldMappingEntry"}}}}}}},SearchIndexerKnowledgeStore:{type:{name:"Composite",className:"SearchIndexerKnowledgeStore",modelProperties:{storageConnectionString:{serializedName:"storageConnectionString",required:!0,type:{name:"String"}},projections:{serializedName:"projections",required:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"SearchIndexerKnowledgeStoreProjection"}}}}}}},SearchIndexerKnowledgeStoreBlobProjectionSelector:Zp,SearchIndexerKnowledgeStoreFileProjectionSelector:th,SearchIndexerKnowledgeStoreObjectProjectionSelector:eh,SearchIndexerKnowledgeStoreParameters:{type:{name:"Composite",className:"SearchIndexerKnowledgeStoreParameters",additionalProperties:{type:{name:"Object"}},modelProperties:{synthesizeGeneratedKeyName:{defaultValue:!1,serializedName:"synthesizeGeneratedKeyName",type:{name:"Boolean"}}}}},SearchIndexerKnowledgeStoreProjection:{type:{name:"Composite",className:"SearchIndexerKnowledgeStoreProjection",modelProperties:{tables:{serializedName:"tables",type:{name:"Sequence",element:{type:{name:"Composite",className:"SearchIndexerKnowledgeStoreTableProjectionSelector"}}}},objects:{serializedName:"objects",type:{name:"Sequence",element:{type:{name:"Composite",className:"SearchIndexerKnowledgeStoreObjectProjectionSelector"}}}},files:{serializedName:"files",type:{name:"Sequence",element:{type:{name:"Composite",className:"SearchIndexerKnowledgeStoreFileProjectionSelector"}}}}}}},SearchIndexerKnowledgeStoreProjectionSelector:tp,SearchIndexerKnowledgeStoreTableProjectionSelector:Wp,SearchIndexerLimits:{type:{name:"Composite",className:"SearchIndexerLimits",modelProperties:{maxRunTime:{serializedName:"maxRunTime",readOnly:!0,type:{name:"TimeSpan"}},maxDocumentExtractionSize:{serializedName:"maxDocumentExtractionSize",readOnly:!0,type:{name:"Number"}},maxDocumentContentCharactersToExtract:{serializedName:"maxDocumentContentCharactersToExtract",readOnly:!0,type:{name:"Number"}}}}},SearchIndexerSkill:Xd,SearchIndexerSkillset:Qd,SearchIndexerStatus:Yd,SearchIndexerWarning:{type:{name:"Composite",className:"SearchIndexerWarning",modelProperties:{key:{serializedName:"key",readOnly:!0,type:{name:"String"}},message:{serializedName:"message",required:!0,readOnly:!0,type:{name:"String"}},name:{serializedName:"name",readOnly:!0,type:{name:"String"}},details:{serializedName:"details",readOnly:!0,type:{name:"String"}},documentationLink:{serializedName:"documentationLink",readOnly:!0,type:{name:"String"}}}}},SearchResourceEncryptionKey:{type:{name:"Composite",className:"SearchResourceEncryptionKey",modelProperties:{keyName:{serializedName:"keyVaultKeyName",required:!0,type:{name:"String"}},keyVersion:{serializedName:"keyVaultKeyVersion",required:!0,type:{name:"String"}},vaultUri:{serializedName:"keyVaultUri",required:!0,type:{name:"String"}},accessCredentials:{serializedName:"accessCredentials",type:{name:"Composite",className:"AzureActiveDirectoryApplicationCredentials"}}}}},SemanticConfiguration:{type:{name:"Composite",className:"SemanticConfiguration",modelProperties:{name:{serializedName:"name",required:!0,type:{name:"String"}},prioritizedFields:{serializedName:"prioritizedFields",type:{name:"Composite",className:"SemanticPrioritizedFields"}},rankingOrder:{serializedName:"rankingOrder",nullable:!0,type:{name:"String"}}}}},SemanticField:{type:{name:"Composite",className:"SemanticField",modelProperties:{name:{serializedName:"fieldName",required:!0,type:{name:"String"}}}}},SemanticPrioritizedFields:{type:{name:"Composite",className:"SemanticPrioritizedFields",modelProperties:{titleField:{serializedName:"titleField",type:{name:"Composite",className:"SemanticField"}},contentFields:{serializedName:"prioritizedContentFields",type:{name:"Sequence",element:{type:{name:"Composite",className:"SemanticField"}}}},keywordsFields:{serializedName:"prioritizedKeywordsFields",type:{name:"Sequence",element:{type:{name:"Composite",className:"SemanticField"}}}}}}},SemanticSearch:{type:{name:"Composite",className:"SemanticSearch",modelProperties:{defaultConfigurationName:{serializedName:"defaultConfiguration",type:{name:"String"}},configurations:{serializedName:"configurations",type:{name:"Sequence",element:{type:{name:"Composite",className:"SemanticConfiguration"}}}}}}},SentimentSkill:zp,SentimentSkillV3:Rp,ServiceCounters:{type:{name:"Composite",className:"ServiceCounters",modelProperties:{documentCounter:{serializedName:"documentCount",type:{name:"Composite",className:"ResourceCounter"}},indexCounter:{serializedName:"indexesCount",type:{name:"Composite",className:"ResourceCounter"}},indexerCounter:{serializedName:"indexersCount",type:{name:"Composite",className:"ResourceCounter"}},dataSourceCounter:{serializedName:"dataSourcesCount",type:{name:"Composite",className:"ResourceCounter"}},storageSizeCounter:{serializedName:"storageSize",type:{name:"Composite",className:"ResourceCounter"}},synonymMapCounter:{serializedName:"synonymMaps",type:{name:"Composite",className:"ResourceCounter"}},skillsetCounter:{serializedName:"skillsetCount",type:{name:"Composite",className:"ResourceCounter"}},vectorIndexSizeCounter:{serializedName:"vectorIndexSize",type:{name:"Composite",className:"ResourceCounter"}}}}},ServiceLimits:{type:{name:"Composite",className:"ServiceLimits",modelProperties:{maxFieldsPerIndex:{serializedName:"maxFieldsPerIndex",nullable:!0,type:{name:"Number"}},maxFieldNestingDepthPerIndex:{serializedName:"maxFieldNestingDepthPerIndex",nullable:!0,type:{name:"Number"}},maxComplexCollectionFieldsPerIndex:{serializedName:"maxComplexCollectionFieldsPerIndex",nullable:!0,type:{name:"Number"}},maxComplexObjectsInCollectionsPerDocument:{serializedName:"maxComplexObjectsInCollectionsPerDocument",nullable:!0,type:{name:"Number"}},maxStoragePerIndexInBytes:{serializedName:"maxStoragePerIndex",nullable:!0,type:{name:"Number"}}}}},ServiceStatistics:_p,ShaperSkill:Op,ShingleTokenFilter:Tm,Similarity:pp,SnowballTokenFilter:$m,SoftDeleteColumnDeletionDetectionPolicy:xp,SplitSkill:jp,SqlIntegratedChangeTrackingPolicy:kp,StemmerOverrideTokenFilter:Rm,StemmerTokenFilter:zm,StopAnalyzer:nm,StopwordsTokenFilter:Lm,Suggester:{type:{name:"Composite",className:"Suggester",modelProperties:{name:{serializedName:"name",required:!0,type:{name:"String"}},searchMode:{defaultValue:"analyzingInfixMatching",isConstant:!0,serializedName:"searchMode",type:{name:"String"}},sourceFields:{serializedName:"sourceFields",required:!0,type:{name:"Sequence",element:{type:{name:"String"}}}}}}},SynonymMap:np,SynonymTokenFilter:Mm,TagScoringFunction:Xp,TagScoringParameters:{type:{name:"Composite",className:"TagScoringParameters",modelProperties:{tagsParameter:{serializedName:"tagsParameter",required:!0,type:{name:"String"}}}}},TextTranslationSkill:Up,TextWeights:{type:{name:"Composite",className:"TextWeights",modelProperties:{weights:{serializedName:"weights",required:!0,type:{name:"Dictionary",value:{type:{name:"Number"}}}}}}},TokenFilter:lp,TruncateTokenFilter:Dm,UaxUrlEmailTokenizer:fm,UniqueTokenFilter:jm,VectorSearch:{type:{name:"Composite",className:"VectorSearch",modelProperties:{profiles:{serializedName:"profiles",type:{name:"Sequence",element:{type:{name:"Composite",className:"VectorSearchProfile"}}}},algorithms:{serializedName:"algorithms",type:{name:"Sequence",element:{type:{name:"Composite",className:"VectorSearchAlgorithmConfiguration"}}}},vectorizers:{serializedName:"vectorizers",type:{name:"Sequence",element:{type:{name:"Composite",className:"VectorSearchVectorizer"}}}},compressions:{serializedName:"compressions",type:{name:"Sequence",element:{type:{name:"Composite",className:"VectorSearchCompression"}}}}}}},VectorSearchAlgorithmConfiguration:mp,VectorSearchCompression:fp,VectorSearchProfile:{type:{name:"Composite",className:"VectorSearchProfile",modelProperties:{name:{serializedName:"name",required:!0,type:{name:"String"}},algorithmConfigurationName:{serializedName:"algorithm",required:!0,type:{name:"String"}},vectorizerName:{serializedName:"vectorizer",type:{name:"String"}},compressionName:{serializedName:"compression",type:{name:"String"}}}}},VectorSearchVectorizer:hp,WebApiParameters:{type:{name:"Composite",className:"WebApiParameters",modelProperties:{uri:{serializedName:"uri",type:{name:"String"}},httpHeaders:{serializedName:"httpHeaders",type:{name:"Dictionary",value:{type:{name:"String"}}}},httpMethod:{serializedName:"httpMethod",type:{name:"String"}},timeout:{serializedName:"timeout",type:{name:"TimeSpan"}},authResourceId:{serializedName:"authResourceId",nullable:!0,type:{name:"String"}},authIdentity:{serializedName:"authIdentity",type:{name:"Composite",className:"SearchIndexerDataIdentity"}}}}},WebApiSkill:Vp,WebApiVectorizer:Zm,WordDelimiterTokenFilter:Fm,discriminators:rh});const ah={parameterPath:["options","contentType"],mapper:{defaultValue:"application/json",isConstant:!0,serializedName:"Content-Type",type:{name:"String"}}},ih={parameterPath:"dataSource",mapper:Vd},sh={parameterPath:"accept",mapper:{defaultValue:"application/json",isConstant:!0,serializedName:"Accept",type:{name:"String"}}},oh={parameterPath:"endpoint",mapper:{serializedName:"endpoint",required:!0,type:{name:"String"}},skipEncoding:!0},ch={parameterPath:"dataSourceName",mapper:{serializedName:"dataSourceName",required:!0,type:{name:"String"}}},lh={parameterPath:["options","ifMatch"],mapper:{serializedName:"If-Match",type:{name:"String"}}},uh={parameterPath:["options","ifNoneMatch"],mapper:{serializedName:"If-None-Match",type:{name:"String"}}},dh={parameterPath:"prefer",mapper:{defaultValue:"return=representation",isConstant:!0,serializedName:"Prefer",type:{name:"String"}}},ph={parameterPath:"apiVersion",mapper:{serializedName:"api-version",required:!0,type:{name:"String"}}},mh={parameterPath:["options","select"],mapper:{serializedName:"$select",type:{name:"String"}}},hh={parameterPath:"indexerName",mapper:{serializedName:"indexerName",required:!0,type:{name:"String"}}},fh={parameterPath:"indexer",mapper:Zd},gh={parameterPath:"skillset",mapper:Qd},yh={parameterPath:"skillsetName",mapper:{serializedName:"skillsetName",required:!0,type:{name:"String"}}},vh={parameterPath:"synonymMap",mapper:np},bh={parameterPath:"synonymMapName",mapper:{serializedName:"synonymMapName",required:!0,type:{name:"String"}}},_h={parameterPath:"index",mapper:ip},wh={parameterPath:"indexName",mapper:{serializedName:"indexName",required:!0,type:{name:"String"}}},Sh={parameterPath:"request",mapper:vp};class Nh{client;constructor(e){this.client=e}createOrUpdate(e,t,r){return this.client.sendOperationRequest({dataSourceName:e,dataSource:t,options:r},xh)}delete(e,t){return this.client.sendOperationRequest({dataSourceName:e,options:t},Eh)}get(e,t){return this.client.sendOperationRequest({dataSourceName:e,options:t},Ph)}list(e){return this.client.sendOperationRequest({options:e},Ch)}create(e,t){return this.client.sendOperationRequest({dataSource:e,options:t},Ah)}}const kh=Ul(nh,!1),xh={path:"/datasources('{dataSourceName}')",httpMethod:"PUT",responses:{200:{bodyMapper:Vd},201:{bodyMapper:Vd},default:{bodyMapper:Kd}},requestBody:ih,queryParameters:[ph],urlParameters:[oh,ch],headerParameters:[ah,sh,lh,uh,dh],mediaType:"json",serializer:kh},Eh={path:"/datasources('{dataSourceName}')",httpMethod:"DELETE",responses:{204:{},404:{},default:{bodyMapper:Kd}},queryParameters:[ph],urlParameters:[oh,ch],headerParameters:[sh,lh,uh],serializer:kh},Ph={path:"/datasources('{dataSourceName}')",httpMethod:"GET",responses:{200:{bodyMapper:Vd},default:{bodyMapper:Kd}},queryParameters:[ph],urlParameters:[oh,ch],headerParameters:[sh],serializer:kh},Ch={path:"/datasources",httpMethod:"GET",responses:{200:{bodyMapper:Wd},default:{bodyMapper:Kd}},queryParameters:[ph,mh],urlParameters:[oh],headerParameters:[sh],serializer:kh},Ah={path:"/datasources",httpMethod:"POST",responses:{201:{bodyMapper:Vd},default:{bodyMapper:Kd}},requestBody:ih,queryParameters:[ph],urlParameters:[oh],headerParameters:[ah,sh],mediaType:"json",serializer:kh};class Ih{client;constructor(e){this.client=e}reset(e,t){return this.client.sendOperationRequest({indexerName:e,options:t},Th)}run(e,t){return this.client.sendOperationRequest({indexerName:e,options:t},$h)}createOrUpdate(e,t,r){return this.client.sendOperationRequest({indexerName:e,indexer:t,options:r},zh)}delete(e,t){return this.client.sendOperationRequest({indexerName:e,options:t},Rh)}get(e,t){return this.client.sendOperationRequest({indexerName:e,options:t},Lh)}list(e){return this.client.sendOperationRequest({options:e},Mh)}create(e,t){return this.client.sendOperationRequest({indexer:e,options:t},Dh)}getStatus(e,t){return this.client.sendOperationRequest({indexerName:e,options:t},jh)}}const Oh=Ul(nh,!1),Th={path:"/indexers('{indexerName}')/search.reset",httpMethod:"POST",responses:{204:{},default:{bodyMapper:Kd}},queryParameters:[ph],urlParameters:[oh,hh],headerParameters:[sh],serializer:Oh},$h={path:"/indexers('{indexerName}')/search.run",httpMethod:"POST",responses:{202:{},default:{bodyMapper:Kd}},queryParameters:[ph],urlParameters:[oh,hh],headerParameters:[sh],serializer:Oh},zh={path:"/indexers('{indexerName}')",httpMethod:"PUT",responses:{200:{bodyMapper:Zd},201:{bodyMapper:Zd},default:{bodyMapper:Kd}},requestBody:fh,queryParameters:[ph],urlParameters:[oh,hh],headerParameters:[ah,sh,lh,uh,dh],mediaType:"json",serializer:Oh},Rh={path:"/indexers('{indexerName}')",httpMethod:"DELETE",responses:{204:{},404:{},default:{bodyMapper:Kd}},queryParameters:[ph],urlParameters:[oh,hh],headerParameters:[sh,lh,uh],serializer:Oh},Lh={path:"/indexers('{indexerName}')",httpMethod:"GET",responses:{200:{bodyMapper:Zd},default:{bodyMapper:Kd}},queryParameters:[ph],urlParameters:[oh,hh],headerParameters:[sh],serializer:Oh},Mh={path:"/indexers",httpMethod:"GET",responses:{200:{bodyMapper:Jd},default:{bodyMapper:Kd}},queryParameters:[ph,mh],urlParameters:[oh],headerParameters:[sh],serializer:Oh},Dh={path:"/indexers",httpMethod:"POST",responses:{201:{bodyMapper:Zd},default:{bodyMapper:Kd}},requestBody:fh,queryParameters:[ph],urlParameters:[oh],headerParameters:[ah,sh],mediaType:"json",serializer:Oh},jh={path:"/indexers('{indexerName}')/search.status",httpMethod:"GET",responses:{200:{bodyMapper:Yd},default:{bodyMapper:Kd}},queryParameters:[ph],urlParameters:[oh,hh],headerParameters:[sh],serializer:Oh};class Fh{client;constructor(e){this.client=e}createOrUpdate(e,t,r){return this.client.sendOperationRequest({skillsetName:e,skillset:t,options:r},qh)}delete(e,t){return this.client.sendOperationRequest({skillsetName:e,options:t},Bh)}get(e,t){return this.client.sendOperationRequest({skillsetName:e,options:t},Vh)}list(e){return this.client.sendOperationRequest({options:e},Gh)}create(e,t){return this.client.sendOperationRequest({skillset:e,options:t},Hh)}}const Uh=Ul(nh,!1),qh={path:"/skillsets('{skillsetName}')",httpMethod:"PUT",responses:{200:{bodyMapper:Qd},201:{bodyMapper:Qd},default:{bodyMapper:Kd}},requestBody:gh,queryParameters:[ph],urlParameters:[oh,yh],headerParameters:[ah,sh,lh,uh,dh],mediaType:"json",serializer:Uh},Bh={path:"/skillsets('{skillsetName}')",httpMethod:"DELETE",responses:{204:{},404:{},default:{bodyMapper:Kd}},queryParameters:[ph],urlParameters:[oh,yh],headerParameters:[sh,lh,uh],serializer:Uh},Vh={path:"/skillsets('{skillsetName}')",httpMethod:"GET",responses:{200:{bodyMapper:Qd},default:{bodyMapper:Kd}},queryParameters:[ph],urlParameters:[oh,yh],headerParameters:[sh],serializer:Uh},Gh={path:"/skillsets",httpMethod:"GET",responses:{200:{bodyMapper:rp},default:{bodyMapper:Kd}},queryParameters:[ph,mh],urlParameters:[oh],headerParameters:[sh],serializer:Uh},Hh={path:"/skillsets",httpMethod:"POST",responses:{201:{bodyMapper:Qd},default:{bodyMapper:Kd}},requestBody:gh,queryParameters:[ph],urlParameters:[oh],headerParameters:[ah,sh],mediaType:"json",serializer:Uh};class Kh{client;constructor(e){this.client=e}createOrUpdate(e,t,r){return this.client.sendOperationRequest({synonymMapName:e,synonymMap:t,options:r},Zh)}delete(e,t){return this.client.sendOperationRequest({synonymMapName:e,options:t},Jh)}get(e,t){return this.client.sendOperationRequest({synonymMapName:e,options:t},Yh)}list(e){return this.client.sendOperationRequest({options:e},Qh)}create(e,t){return this.client.sendOperationRequest({synonymMap:e,options:t},Xh)}}const Wh=Ul(nh,!1),Zh={path:"/synonymmaps('{synonymMapName}')",httpMethod:"PUT",responses:{200:{bodyMapper:np},201:{bodyMapper:np},default:{bodyMapper:Kd}},requestBody:vh,queryParameters:[ph],urlParameters:[oh,bh],headerParameters:[ah,sh,lh,uh,dh],mediaType:"json",serializer:Wh},Jh={path:"/synonymmaps('{synonymMapName}')",httpMethod:"DELETE",responses:{204:{},404:{},default:{bodyMapper:Kd}},queryParameters:[ph],urlParameters:[oh,bh],headerParameters:[sh,lh,uh],serializer:Wh},Yh={path:"/synonymmaps('{synonymMapName}')",httpMethod:"GET",responses:{200:{bodyMapper:np},default:{bodyMapper:Kd}},queryParameters:[ph],urlParameters:[oh,bh],headerParameters:[sh],serializer:Wh},Qh={path:"/synonymmaps",httpMethod:"GET",responses:{200:{bodyMapper:ap},default:{bodyMapper:Kd}},queryParameters:[ph,mh],urlParameters:[oh],headerParameters:[sh],serializer:Wh},Xh={path:"/synonymmaps",httpMethod:"POST",responses:{201:{bodyMapper:np},default:{bodyMapper:Kd}},requestBody:vh,queryParameters:[ph],urlParameters:[oh],headerParameters:[ah,sh],mediaType:"json",serializer:Wh};class ef{client;constructor(e){this.client=e}create(e,t){return this.client.sendOperationRequest({index:e,options:t},rf)}list(e){return this.client.sendOperationRequest({options:e},nf)}createOrUpdate(e,t,r){return this.client.sendOperationRequest({indexName:e,index:t,options:r},af)}delete(e,t){return this.client.sendOperationRequest({indexName:e,options:t},sf)}get(e,t){return this.client.sendOperationRequest({indexName:e,options:t},of)}getStatistics(e,t){return this.client.sendOperationRequest({indexName:e,options:t},cf)}analyze(e,t,r){return this.client.sendOperationRequest({indexName:e,request:t,options:r},lf)}}const tf=Ul(nh,!1),rf={path:"/indexes",httpMethod:"POST",responses:{201:{bodyMapper:ip},default:{bodyMapper:Kd}},requestBody:_h,queryParameters:[ph],urlParameters:[oh],headerParameters:[ah,sh],mediaType:"json",serializer:tf},nf={path:"/indexes",httpMethod:"GET",responses:{200:{bodyMapper:gp},default:{bodyMapper:Kd}},queryParameters:[ph,mh],urlParameters:[oh],headerParameters:[sh],serializer:tf},af={path:"/indexes('{indexName}')",httpMethod:"PUT",responses:{200:{bodyMapper:ip},201:{bodyMapper:ip},default:{bodyMapper:Kd}},requestBody:_h,queryParameters:[ph,{parameterPath:["options","allowIndexDowntime"],mapper:{serializedName:"allowIndexDowntime",type:{name:"Boolean"}}}],urlParameters:[oh,wh],headerParameters:[ah,sh,lh,uh,dh],mediaType:"json",serializer:tf},sf={path:"/indexes('{indexName}')",httpMethod:"DELETE",responses:{204:{},404:{},default:{bodyMapper:Kd}},queryParameters:[ph],urlParameters:[oh,wh],headerParameters:[sh,lh,uh],serializer:tf},of={path:"/indexes('{indexName}')",httpMethod:"GET",responses:{200:{bodyMapper:ip},default:{bodyMapper:Kd}},queryParameters:[ph],urlParameters:[oh,wh],headerParameters:[sh],serializer:tf},cf={path:"/indexes('{indexName}')/search.stats",httpMethod:"GET",responses:{200:{bodyMapper:yp},default:{bodyMapper:Kd}},queryParameters:[ph],urlParameters:[oh,wh],headerParameters:[sh],serializer:tf},lf={path:"/indexes('{indexName}')/search.analyze",httpMethod:"POST",responses:{200:{bodyMapper:bp},default:{bodyMapper:Kd}},requestBody:Sh,queryParameters:[ph],urlParameters:[oh,wh],headerParameters:[ah,sh],mediaType:"json",serializer:tf};class uf extends Su{endpoint;apiVersion;constructor(e,t,r){if(void 0===e)throw new Error("'endpoint' cannot be null");if(void 0===t)throw new Error("'apiVersion' cannot be null");r||(r={});const n="azsdk-js-search-documents/12.2.0",a=r.userAgentOptions&&r.userAgentOptions.userAgentPrefix?`${r.userAgentOptions.userAgentPrefix} ${n}`:`${n}`;super({requestContentType:"application/json; charset=utf-8",...r,userAgentOptions:{userAgentPrefix:a},endpoint:r.endpoint??r.baseUri??"{endpoint}"}),this.endpoint=e,this.apiVersion=t,this.dataSources=new Nh(this),this.indexers=new Ih(this),this.skillsets=new Fh(this),this.synonymMaps=new Kh(this),this.indexes=new ef(this),this.addCustomApiVersionPolicy(t)}addCustomApiVersionPolicy(e){if(!e)return;const t={name:"CustomApiVersionPolicy",async sendRequest(t,r){const n=t.url.split("?");if(n.length>1){const r=n[1].split("&").map(t=>t.indexOf("api-version")>-1?"api-version="+e:t);t.url=n[0]+"?"+r.join("&")}return r(t)}};this.pipeline.addPolicy(t)}getServiceStatistics(e){return this.sendOperationRequest({options:e},df)}dataSources;indexers;skillsets;synonymMaps;indexes}const df={path:"/servicestats",httpMethod:"GET",responses:{200:{bodyMapper:_p},default:{bodyMapper:Kd}},queryParameters:[ph],urlParameters:[oh],headerParameters:[sh],serializer:Ul(nh,!1)};class pf{serviceVersion=Nd;apiVersion=Nd;endpoint;client;credential;options;constructor(e,t,r={}){this.endpoint=e,this.credential=t,this.options=r;const n={...this.options,loggingOptions:{logger:sd.info,additionalAllowedHeaderNames:["elapsed-time","Location","OData-MaxVersion","OData-Version","Prefer","throttle-reason"]}};if(this.serviceVersion=this.options.serviceVersion??this.options.apiVersion??Nd,this.apiVersion=this.serviceVersion,this.client=new uf(this.endpoint,this.serviceVersion,n),to(t)){const e=this.options.audience?`${this.options.audience}/.default`:`${ao.AzurePublicCloud}/.default`;this.client.pipeline.addPolicy(Il({credential:t,scopes:e}))}else this.client.pipeline.addPolicy(ld(t));this.client.pipeline.addPolicy(od("minimal"))}async*listIndexesPage(e={}){const{span:t,updatedOptions:r}=qd("SearchIndexClient-listIndexesPage",e);try{const e=(await this.client.indexes.list(r)).indexes.map(zd);yield e}catch(e){throw t.setStatus({status:"error",error:e.message}),e}finally{t.end()}}async*listIndexesAll(e={}){for await(const t of this.listIndexesPage(e))yield*t}listIndexes(e={}){const t=this.listIndexesAll(e);return{next:()=>t.next(),[Symbol.asyncIterator](){return this},byPage:()=>this.listIndexesPage(e)}}async*listIndexesNamesPage(e={}){const{span:t,updatedOptions:r}=qd("SearchIndexClient-listIndexesNamesPage",e);try{const e=(await this.client.indexes.list({...r,select:"name"})).indexes.map(e=>e.name);yield e}catch(e){throw t.setStatus({status:"error",error:e.message}),e}finally{t.end()}}async*listIndexesNamesAll(e={}){for await(const t of this.listIndexesNamesPage(e))yield*t}listIndexesNames(e={}){const t=this.listIndexesNamesAll(e);return{next:()=>t.next(),[Symbol.asyncIterator](){return this},byPage:()=>this.listIndexesNamesPage(e)}}async listSynonymMaps(e={}){const{span:t,updatedOptions:r}=qd("SearchIndexClient-listSynonymMaps",e);try{return(await this.client.synonymMaps.list(r)).synonymMaps.map(jd)}catch(e){throw t.setStatus({status:"error",error:e.message}),e}finally{t.end()}}async listSynonymMapsNames(e={}){const{span:t,updatedOptions:r}=qd("SearchIndexClient-listSynonymMapsNames",e);try{return(await this.client.synonymMaps.list({...r,select:"name"})).synonymMaps.map(e=>e.name)}catch(e){throw t.setStatus({status:"error",error:e.message}),e}finally{t.end()}}async getIndex(e,t={}){const{span:r,updatedOptions:n}=qd("SearchIndexClient-getIndex",t);try{return zd(await this.client.indexes.get(e,n))}catch(e){throw r.setStatus({status:"error",error:e.message}),e}finally{r.end()}}async getSynonymMap(e,t={}){const{span:r,updatedOptions:n}=qd("SearchIndexClient-getSynonymMaps",t);try{return jd(await this.client.synonymMaps.get(e,n))}catch(e){throw r.setStatus({status:"error",error:e.message}),e}finally{r.end()}}async createIndex(e,t={}){const{span:r,updatedOptions:n}=qd("SearchIndexClient-createIndex",t);try{return zd(await this.client.indexes.create(Dd(e),n))}catch(e){throw r.setStatus({status:"error",error:e.message}),e}finally{r.end()}}async createSynonymMap(e,t={}){const{span:r,updatedOptions:n}=qd("SearchIndexClient-createSynonymMaps",t);try{return jd(await this.client.synonymMaps.create(Fd(e),n))}catch(e){throw r.setStatus({status:"error",error:e.message}),e}finally{r.end()}}async createOrUpdateIndex(e,t={}){const{span:r,updatedOptions:n}=qd("SearchIndexClient-createOrUpdateIndex",t);try{const r=t.onlyIfUnchanged?e.etag:void 0;return zd(await this.client.indexes.createOrUpdate(e.name,Dd(e),{...n,ifMatch:r}))}catch(e){throw r.setStatus({status:"error",error:e.message}),e}finally{r.end()}}async createOrUpdateSynonymMap(e,t={}){const{span:r,updatedOptions:n}=qd("SearchIndexClient-createOrUpdateSynonymMap",t);try{const r=t.onlyIfUnchanged?e.etag:void 0;return jd(await this.client.synonymMaps.createOrUpdate(e.name,Fd(e),{...n,ifMatch:r}))}catch(e){throw r.setStatus({status:"error",error:e.message}),e}finally{r.end()}}async deleteIndex(e,t={}){const{span:r,updatedOptions:n}=qd("SearchIndexClient-deleteIndex",t);try{const r="string"==typeof e?e:e.name,a="string"==typeof e?void 0:t.onlyIfUnchanged?e.etag:void 0;await this.client.indexes.delete(r,{...n,ifMatch:a})}catch(e){throw r.setStatus({status:"error",error:e.message}),e}finally{r.end()}}async deleteSynonymMap(e,t={}){const{span:r,updatedOptions:n}=qd("SearchIndexClient-deleteSynonymMap",t);try{const r="string"==typeof e?e:e.name,a="string"==typeof e?void 0:t.onlyIfUnchanged?e.etag:void 0;await this.client.synonymMaps.delete(r,{...n,ifMatch:a})}catch(e){throw r.setStatus({status:"error",error:e.message}),e}finally{r.end()}}async getIndexStatistics(e,t={}){const{span:r,updatedOptions:n}=qd("SearchIndexClient-getIndexStatistics",t);try{return await this.client.indexes.getStatistics(e,n)}catch(e){throw r.setStatus({status:"error",error:e.message}),e}finally{r.end()}}async analyzeText(e,t){const{abortSignal:r,requestOptions:n,tracingOptions:a,analyzerName:i,tokenizerName:s,...o}=t,c={abortSignal:r,requestOptions:n,tracingOptions:a},{span:l,updatedOptions:u}=qd("SearchIndexClient-analyzeText",c);try{return await this.client.indexes.analyze(e,{...o,analyzer:i,tokenizer:s},u)}catch(e){throw l.setStatus({status:"error",error:e.message}),e}finally{l.end()}}async getServiceStatistics(e={}){const{span:t,updatedOptions:r}=qd("SearchIndexClient-getServiceStatistics",e);try{return await this.client.getServiceStatistics(r)}catch(e){throw t.setStatus({status:"error",error:e.message}),e}finally{t.end()}}getSearchClient(e,t){return new Bd(this.endpoint,e,this.credential,t||this.options)}}class mf{client;autoFlush;flushWindowInMs;throttlingDelayInMs;maxRetriesPerAction;maxThrottlingDelayInMs;initialBatchActionCount;batchObject;cleanupTimer;emitter=new Se;documentKeyRetriever;constructor(e,t,r={}){if(this.client=e,this.documentKeyRetriever=t,this.autoFlush=r.autoFlush??!0,this.initialBatchActionCount=r.initialBatchActionCount??512,this.flushWindowInMs=r.flushWindowInMs??6e4,this.throttlingDelayInMs=r.throttlingDelayInMs??6e4,this.maxRetriesPerAction=r.maxRetriesPerAction??3,this.maxThrottlingDelayInMs=r.maxThrottlingDelayInMs??6e4,this.batchObject=new no,this.autoFlush){const e=setInterval(()=>this.flush(),this.flushWindowInMs);e?.unref(),this.cleanupTimer=()=>{clearInterval(e)}}}async uploadDocuments(e,t={}){const{span:r,updatedOptions:n}=qd("SearchIndexingBufferedSender-uploadDocuments",t);try{return this.batchObject.upload(e),this.emitter.emit("batchAdded",{action:"upload",documents:e}),this.internalFlush(!1,n)}catch(e){throw r.setStatus({status:"error",error:e.message}),e}finally{r.end()}}async mergeDocuments(e,t={}){const{span:r,updatedOptions:n}=qd("SearchIndexingBufferedSender-mergeDocuments",t);try{return this.batchObject.merge(e),this.emitter.emit("batchAdded",{action:"merge",documents:e}),this.internalFlush(!1,n)}catch(e){throw r.setStatus({status:"error",error:e.message}),e}finally{r.end()}}async mergeOrUploadDocuments(e,t={}){const{span:r,updatedOptions:n}=qd("SearchIndexingBufferedSender-mergeOrUploadDocuments",t);try{return this.batchObject.mergeOrUpload(e),this.emitter.emit("batchAdded",{action:"mergeOrUpload",documents:e}),this.internalFlush(!1,n)}catch(e){throw r.setStatus({status:"error",error:e.message}),e}finally{r.end()}}async deleteDocuments(e,t={}){const{span:r,updatedOptions:n}=qd("SearchIndexingBufferedSender-deleteDocuments",t);try{return this.batchObject.delete(e),this.emitter.emit("batchAdded",{action:"delete",documents:e}),this.internalFlush(!1,n)}catch(e){throw r.setStatus({status:"error",error:e.message}),e}finally{r.end()}}async flush(e={}){const{span:t,updatedOptions:r}=qd("SearchIndexingBufferedSender-flush",e);try{if(this.batchObject.actions.length>0)return this.internalFlush(!0,r)}catch(e){throw t.setStatus({status:"error",error:e.message}),e}finally{t.end()}}async dispose(){this.batchObject.actions.length>0&&await this.internalFlush(!0),this.cleanupTimer&&this.cleanupTimer()}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.removeListener(e,t)}isBatchReady(){return this.batchObject.actions.length>=this.initialBatchActionCount}async internalFlush(e,t={}){if(e||this.autoFlush&&this.isBatchReady()){const e=this.batchObject.actions;for(this.batchObject=new no;e.length>0;){const r=e.splice(0,this.initialBatchActionCount),{batchToSubmit:n,submitLater:a}=this.pruneActions(r);e.unshift(...a),await this.submitDocuments(n,t)}}}pruneActions(e){const t=new Set,r=[],n=[];for(const a of e){const e=this.documentKeyRetriever(a);t.has(e)?n.push(a):(t.add(e),r.push(a))}return{batchToSubmit:r,submitLater:n}}async submitDocuments(e,t,r=1){try{for(const t of e)this.emitter.emit("beforeDocumentSent",t);const r=await this.client.indexDocuments(new no(e),t);this.emitter.emit("batchSucceeded",r)}catch(i){if(i.statusCode&&413===i.statusCode&&e.length>1){const r=[e.slice(0,e.length/2),e.slice(e.length/2,e.length)];this.initialBatchActionCount=r[0].length;for(const e of r)await this.submitDocuments(e,t)}else{if(!(this.isRetryAbleError(i)&&r<=this.maxRetriesPerAction))throw this.emitter.emit("batchFailed",i),i;{const i=this.throttlingDelayInMs*Math.pow(2,r),s=Math.min(this.maxThrottlingDelayInMs,i),o=s/2+(n=0,a=s/2,n=Math.ceil(n),a=Math.floor(a),Math.floor(Math.random()*(a-n+1))+n);await Ys(o),await this.submitDocuments(e,t,r+1)}}}var n,a}isRetryAbleError(e){return e.statusCode&&(422===e.statusCode||409===e.statusCode||503===e.statusCode)}}var hf,ff,gf=Object.defineProperty,yf=(e,t)=>{for(var r in t)gf(e,r,{get:t[r],enumerable:!0})};function vf(e){return"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type&&"source_type"in e&&("url"===e.source_type||"base64"===e.source_type||"text"===e.source_type||"id"===e.source_type)}function bf(e){return vf(e)&&"url"===e.source_type&&"url"in e&&"string"==typeof e.url}function _f(e){return vf(e)&&"base64"===e.source_type&&"data"in e&&"string"==typeof e.data}function wf(e){return vf(e)&&"text"===e.source_type&&"text"in e&&"string"==typeof e.text}function Sf(e){return vf(e)&&"id"===e.source_type&&"id"in e&&"string"==typeof e.id}function Nf(e){if(vf(e)){if("url"===e.source_type)return{type:"image_url",image_url:{url:e.url}};if("base64"===e.source_type){if(!e.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function kf(e){const t=e.split(";")[0].split("/");if(2!==t.length)throw new Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);const r=t[0].trim(),n=t[1].trim();if(""===r||""===n)throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);const a={};for(const t of e.split(";").slice(1)){const r=t.split("=");if(2!==r.length)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);const n=r[0].trim(),i=r[1].trim();if(""===n)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);a[n]=i}return{type:r,subtype:n,parameters:a}}function xf({dataUrl:e,asTypedArray:t=!1}){const r=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let n;if(r){n=r[1].toLowerCase();return{mime_type:n,data:t?Uint8Array.from(atob(r[2]),e=>e.charCodeAt(0)):r[2]}}}function Ef(e,t){if("text"===e.type){if(!t.fromStandardTextBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if("image"===e.type){if(!t.fromStandardImageBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if("audio"===e.type){if(!t.fromStandardAudioBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if("file"===e.type){if(!t.fromStandardFileBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw new Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function Pf(e){return"object"==typeof e&&null!==e&&"type"in e&&"content"in e&&("string"==typeof e.content||Array.isArray(e.content))}var Cf,Af=(ff||(ff=1,hf=function(e,t){if("string"!=typeof e)throw new TypeError("Expected a string");return t=void 0===t?"_":t,e.replace(/([a-z\d])([A-Z])/g,"$1"+t+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+t+"$2").toLowerCase()}),hf),If=ba(Af),Of={exports:{}};function Tf(e,t){return t?.[e]||If(e)}function $f(e,t,r){const n={};for(const a in e)Object.hasOwn(e,a)&&(n[t(a,r)]=e[a]);return n}!function(){if(Cf)return Of.exports;Cf=1;const e=/[\p{Lu}]/u,t=/[\p{Ll}]/u,r=/^[\p{Lu}](?![\p{Lu}])/gu,n=/([\p{Alpha}\p{N}_]|$)/u,a=/[_.\- ]+/,i=new RegExp("^"+a.source),s=new RegExp(a.source+n.source,"gu"),o=new RegExp("\\d+"+n.source,"gu"),c=(n,a)=>{if("string"!=typeof n&&!Array.isArray(n))throw new TypeError("Expected the input to be `string | string[]`");if(a={pascalCase:!1,preserveConsecutiveUppercase:!1,...a},0===(n=Array.isArray(n)?n.map(e=>e.trim()).filter(e=>e.length).join("-"):n.trim()).length)return"";const c=!1===a.locale?e=>e.toLowerCase():e=>e.toLocaleLowerCase(a.locale),l=!1===a.locale?e=>e.toUpperCase():e=>e.toLocaleUpperCase(a.locale);if(1===n.length)return a.pascalCase?l(n):c(n);return n!==c(n)&&(n=((r,n,a)=>{let i=!1,s=!1,o=!1;for(let c=0;c<r.length;c++){const l=r[c];i&&e.test(l)?(r=r.slice(0,c)+"-"+r.slice(c),i=!1,o=s,s=!0,c++):s&&o&&t.test(l)?(r=r.slice(0,c-1)+"-"+r.slice(c-1),o=s,s=!1,i=!0):(i=n(l)===l&&a(l)!==l,o=s,s=a(l)===l&&n(l)!==l)}return r})(n,c,l)),n=n.replace(i,""),n=a.preserveConsecutiveUppercase?((e,t)=>(r.lastIndex=0,e.replace(r,e=>t(e))))(n,c):c(n),a.pascalCase&&(n=l(n.charAt(0))+n.slice(1)),((e,t)=>(s.lastIndex=0,o.lastIndex=0,e.replace(s,(e,r)=>t(r)).replace(o,e=>t(e))))(n,l)};Of.exports=c,Of.exports.default=c,Of.exports}();function zf(e){return Array.isArray(e)?[...e]:{...e}}function Rf(e,t){const r=zf(e);for(const[e,n]of Object.entries(t)){const[t,...a]=e.split(".").reverse();let i=r;for(const e of a.reverse()){if(void 0===i[e])break;i[e]=zf(i[e]),i=i[e]}void 0!==i[t]&&(i[t]={lc:1,type:"secret",id:[n]})}return r}function Lf(e){const t=Object.getPrototypeOf(e);return"function"==typeof e.lc_name&&("function"!=typeof t.lc_name||e.lc_name()!==t.lc_name())?e.lc_name():e.name}yf({},{Serializable:()=>Mf,get_lc_unique_name:()=>Lf});var Mf=class e{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Lf(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...t){void 0!==this.lc_serializable_keys?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([e])=>this.lc_serializable_keys?.includes(e))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof e||"object"!=typeof this.lc_kwargs||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const t={},r={},n=Object.keys(this.lc_kwargs).reduce((e,t)=>(e[t]=t in this?this[t]:this.lc_kwargs[t],e),{});for(let e=Object.getPrototypeOf(this);e;e=Object.getPrototypeOf(e))Object.assign(t,Reflect.get(e,"lc_aliases",this)),Object.assign(r,Reflect.get(e,"lc_secrets",this)),Object.assign(n,Reflect.get(e,"lc_attributes",this));return Object.keys(r).forEach(e=>{let t=this,r=n;const[a,...i]=e.split(".").reverse();for(const e of i.reverse()){if(!(e in t)||void 0===t[e])return;e in r&&void 0!==r[e]||("object"==typeof t[e]&&null!=t[e]?r[e]={}:Array.isArray(t[e])&&(r[e]=[])),t=t[e],r=r[e]}a in t&&void 0!==t[a]&&(r[a]=r[a]||t[a])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:$f(Object.keys(r).length?Rf(n,r):n,Tf,t)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function Df(e,t){return jf(e)&&e.type===t}function jf(e){return"object"==typeof e&&null!==e}function Ff(e){return Array.isArray(e)}function Uf(e){return"string"==typeof e}function qf(e){return"number"==typeof e}function Bf(e){return e instanceof Uint8Array}function Vf(e){try{return JSON.parse(e)}catch{return}}const Gf=e=>e();function Hf(e){if("char_location"===e.type&&Uf(e.document_title)&&qf(e.start_char_index)&&qf(e.end_char_index)&&Uf(e.cited_text)){const{document_title:t,start_char_index:r,end_char_index:n,cited_text:a,...i}=e;return{...i,type:"citation",source:"char",title:t??void 0,startIndex:r,endIndex:n,citedText:a}}if("page_location"===e.type&&Uf(e.document_title)&&qf(e.start_page_number)&&qf(e.end_page_number)&&Uf(e.cited_text)){const{document_title:t,start_page_number:r,end_page_number:n,cited_text:a,...i}=e;return{...i,type:"citation",source:"page",title:t??void 0,startIndex:r,endIndex:n,citedText:a}}if("content_block_location"===e.type&&Uf(e.document_title)&&qf(e.start_block_index)&&qf(e.end_block_index)&&Uf(e.cited_text)){const{document_title:t,start_block_index:r,end_block_index:n,cited_text:a,...i}=e;return{...i,type:"citation",source:"block",title:t??void 0,startIndex:r,endIndex:n,citedText:a}}if("web_search_result_location"===e.type&&Uf(e.url)&&Uf(e.title)&&Uf(e.encrypted_index)&&Uf(e.cited_text)){const{url:t,title:r,encrypted_index:n,cited_text:a,...i}=e;return{...i,type:"citation",source:"url",url:t,title:r,startIndex:Number(n),endIndex:Number(n),citedText:a}}if("search_result_location"===e.type&&Uf(e.source)&&Uf(e.title)&&qf(e.start_block_index)&&qf(e.end_block_index)&&Uf(e.cited_text)){const{source:t,title:r,start_block_index:n,end_block_index:a,cited_text:i,...s}=e;return{...s,type:"citation",source:"search",url:t,title:r??void 0,startIndex:n,endIndex:a,citedText:i}}}function Kf(e){if(Df(e,"document")&&jf(e.source)&&"type"in e.source){if("base64"===e.source.type&&Uf(e.source.media_type)&&Uf(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if("url"===e.source.type&&Uf(e.source.url))return{type:"file",url:e.source.url};if("file"===e.source.type&&Uf(e.source.file_id))return{type:"file",fileId:e.source.file_id};if("text"===e.source.type&&Uf(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(Df(e,"image")&&jf(e.source)&&"type"in e.source){if("base64"===e.source.type&&Uf(e.source.media_type)&&Uf(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if("url"===e.source.type&&Uf(e.source.url))return{type:"image",url:e.source.url};if("file"===e.source.type&&Uf(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function Wf(e){return Array.from(function*(){for(const t of e){const e=Kf(t);e?yield e:yield t}}())}function Zf(e){return Array.from(function*(){const t="string"==typeof e.content?[{type:"text",text:e.content}]:e.content;for(const r of t){if(Df(r,"text")&&Uf(r.text)){const{text:e,citations:t,...n}=r;if(Ff(t)&&t.length){const r=t.reduce((e,t)=>{const r=Hf(t);return r?[...e,r]:e},[]);yield{...n,type:"text",text:e,annotations:r};continue}yield{...n,type:"text",text:e};continue}if(Df(r,"thinking")&&Uf(r.thinking)){const{thinking:e,signature:t,...n}=r;yield{...n,type:"reasoning",reasoning:e,signature:t};continue}if(Df(r,"redacted_thinking"))yield{type:"non_standard",value:r};else if(Df(r,"tool_use")&&Uf(r.name)&&Uf(r.id))yield{type:"tool_call",id:r.id,name:r.name,args:r.input};else{if(Df(r,"input_json_delta")){if(Yf(e)&&e.tool_call_chunks?.length){const t=e.tool_call_chunks[0];yield{type:"tool_call_chunk",id:t.id,name:t.name,args:t.args,index:t.index};continue}}else if(Df(r,"server_tool_use")&&Uf(r.name)&&Uf(r.id)){const{name:e,id:t}=r;if("web_search"===e){const e=Gf(()=>{if("string"==typeof r.input)return r.input;if(jf(r.input)&&Uf(r.input.query))return r.input.query;if(Uf(r.partial_json)){const e=Vf(r.partial_json);if(e?.query)return e.query}return""});yield{id:t,type:"server_tool_call",name:"web_search",args:{query:e}};continue}if("code_execution"===r.name){const e=Gf(()=>{if("string"==typeof r.input)return r.input;if(jf(r.input)&&Uf(r.input.code))return r.input.code;if(Uf(r.partial_json)){const e=Vf(r.partial_json);if(e?.code)return e.code}return""});yield{id:t,type:"server_tool_call",name:"code_execution",args:{code:e}};continue}}else{if(Df(r,"web_search_tool_result")&&Uf(r.tool_use_id)&&Ff(r.content)){const{content:e,tool_use_id:t}=r,n=e.reduce((e,t)=>Df(t,"web_search_result")?[...e,t.url]:e,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:t,status:"success",output:{urls:n}};continue}if(Df(r,"code_execution_tool_result")&&Uf(r.tool_use_id)&&jf(r.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}if(Df(r,"mcp_tool_use")){yield{id:r.id,type:"server_tool_call",name:"mcp_tool_use",args:r.input};continue}if(Df(r,"mcp_tool_result")&&Uf(r.tool_use_id)&&jf(r.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}if(Df(r,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:r.input};continue}if(Df(r,"search_result")){yield{id:r.id,type:"non_standard",value:r};continue}if(Df(r,"tool_result")){yield{id:r.id,type:"non_standard",value:r};continue}{const e=Kf(r);if(e){yield e;continue}}}yield{type:"non_standard",value:r}}}}())}const Jf={translateContent:Zf,translateContentChunk:Zf};function Yf(e){return"function"==typeof e?._getType&&"function"==typeof e.concat&&"ai"===e._getType()}function Qf(e){return bf(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:_f(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:Sf(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function Xf(e){return e.map(Qf)}function eg(e){return!(!Df(e,"image_url")||!jf(e.image_url))||(!(!Df(e,"input_audio")||!jf(e.input_audio))||!(!Df(e,"file")||!jf(e.file)))}function tg(e){if(Df(e,"image_url")&&jf(e.image_url)&&Uf(e.image_url.url)){const t=xf({dataUrl:e.image_url.url});return t?{type:"image",mimeType:t.mime_type,data:t.data}:{type:"image",url:e.image_url.url}}if(Df(e,"input_audio")&&jf(e.input_audio)&&Uf(e.input_audio.data)&&Uf(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(Df(e,"file")&&jf(e.file)&&Uf(e.file.data)){const t=xf({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if(Uf(e.file.file_id))return{type:"file",fileId:e.file.file_id}}return e}function rg(e){const t=[];for(const r of e)eg(r)?t.push(tg(r)):t.push(r);return t}function ng(e){if("url_citation"===e.type){const{url:t,title:r,start_index:n,end_index:a}=e;return{type:"citation",url:t,title:r,startIndex:n,endIndex:a}}if("file_citation"===e.type){const{file_id:t,filename:r,index:n}=e;return{type:"citation",title:r,startIndex:n,endIndex:n,fileId:t}}return e}function ag(e){return Array.from(function*(){if(jf(e.additional_kwargs?.reasoning)&&Ff(e.additional_kwargs.reasoning.summary)){const t=e.additional_kwargs.reasoning.summary.reduce((e,t)=>jf(t)&&Uf(t.text)?`${e}${t.text}`:e,"");yield{type:"reasoning",reasoning:t}}const t="string"==typeof e.content?[{type:"text",text:e.content}]:e.content;for(const e of t)if(Df(e,"text")){const{text:t,annotations:r,...n}=e;Array.isArray(r)?yield{...n,type:"text",text:String(t),annotations:r.map(ng)}:yield{...n,type:"text",text:String(t)}}for(const t of e.tool_calls??[])yield{type:"tool_call",id:t.id,name:t.name,args:t.args};if(jf(e.additional_kwargs)&&Ff(e.additional_kwargs.tool_outputs))for(const t of e.additional_kwargs.tool_outputs)if(Df(t,"web_search_call"))yield{id:t.id,type:"server_tool_call",name:"web_search",args:{query:t.query}};else if(Df(t,"file_search_call"))yield{id:t.id,type:"server_tool_call",name:"file_search",args:{query:t.query}};else if(Df(t,"computer_call"))yield{type:"non_standard",value:t};else if(Df(t,"code_interpreter_call")){if(Uf(t.code)&&(yield{id:t.id,type:"server_tool_call",name:"code_interpreter",args:{code:t.code}}),Ff(t.outputs)){const e=Gf(()=>{if("in_progress"!==t.status){if("completed"===t.status)return 0;if("incomplete"===t.status)return 127;if("interpreting"!==t.status)return"failed"===t.status?1:void 0}});for(const r of t.outputs)if(Df(r,"logs")){yield{type:"server_tool_call_result",toolCallId:t.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:e??0,stderr:[0,void 0].includes(e)?void 0:String(r.logs),stdout:[0,void 0].includes(e)?String(r.logs):void 0}};continue}}}else Df(t,"mcp_call")?yield{id:t.id,type:"server_tool_call",name:"mcp_call",args:t.input}:Df(t,"mcp_list_tools")?yield{id:t.id,type:"server_tool_call",name:"mcp_list_tools",args:t.input}:(Df(t,"mcp_approval_request")||Df(t,"image_generation_call")||jf(t))&&(yield{type:"non_standard",value:t})}())}const ig={translateContent:e=>"string"==typeof e.content?function(e){const t=[];"string"==typeof e.content?t.push({type:"text",text:e.content}):t.push(...rg(e.content));for(const r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}(e):ag(e),translateContentChunk:e=>"string"==typeof e.content?function(e){const t=[];"string"==typeof e.content?t.push({type:"text",text:e.content}):t.push(...rg(e.content));for(const r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}(e):function(e){return Array.from(function*(){yield*ag(e);for(const t of e.tool_call_chunks??[])yield{type:"tool_call_chunk",id:t.id,name:t.name,args:t.args}}())}(e)};function sg(e,t="pretty"){return"pretty"===t?function(e){const t=[],r=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,n=Math.floor((80-r.length)/2),a="=".repeat(n),i=r.length%2==0?a:`${a}=`;if(t.push(`${a}${r}${i}`),"ai"===e.type){const r=e;if(r.tool_calls&&r.tool_calls.length>0){t.push("Tool Calls:");for(const e of r.tool_calls){t.push(` ${e.name} (${e.id})`),t.push(` Call ID: ${e.id}`),t.push(" Args:");for(const[r,n]of Object.entries(e.args))t.push(` ${r}: ${n}`)}}}if("tool"===e.type){const r=e;r.name&&t.push(`Name: ${r.name}`)}"string"==typeof e.content&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content));return t.join("\n")}(e):JSON.stringify(e)}const og=Symbol.for("langchain.message");function cg(e,t){return"string"==typeof e?""===e?t:"string"==typeof t?e+t:Array.isArray(t)&&t.some(e=>vf(e))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t]:Array.isArray(t)?mg(e,t)??[...e,...t]:""===t?e:Array.isArray(e)&&e.some(e=>vf(e))?[...e,{type:"file",source_type:"text",text:t}]:[...e,{type:"text",text:t}]}function lg(e,t){return"error"===e||"error"===t?"error":"success"}var ug=class extends Mf{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[og]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(e){const t="string"==typeof e||Array.isArray(e)?{content:e}:e;t.additional_kwargs||(t.additional_kwargs={}),t.response_metadata||(t.response_metadata={}),super(t),this.name=t.name,void 0===t.content&&void 0!==t.contentBlocks?(this.content=t.contentBlocks,this.response_metadata={output_version:"v1",...t.response_metadata}):void 0!==t.content?(this.content=t.content??[],this.response_metadata=t.response_metadata):(this.content=[],this.response_metadata=t.response_metadata),this.additional_kwargs=t.additional_kwargs,this.id=t.id}get text(){return"string"==typeof this.content?this.content:Array.isArray(this.content)?this.content.map(e=>"string"==typeof e?e:"text"===e.type?e.text:"").join(""):""}get contentBlocks(){const e="string"==typeof this.content?[{type:"text",text:this.content}]:this.content;return[Xf,rg,Wf].reduce((e,t)=>t(e),e)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){return"object"==typeof e&&null!==e&&og in e&&!0===e[og]&&Pf(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(null===e)return this;const t=(r=this._printableFields,n=Math.max(4,e),JSON.stringify(function e(t,r){if("object"!=typeof t||null==t)return t;if(r>=n)return Array.isArray(t)?"[Array]":"[Object]";if(Array.isArray(t))return t.map(t=>e(t,r+1));const a={};for(const n of Object.keys(t))a[n]=e(t[n],r+1);return a}(r,0),null,2));var r,n;return`${this.constructor.lc_name()} ${t}`}toFormattedString(e="pretty"){return sg(this,e)}};function dg(e){return Array.isArray(e)&&e.every(e=>"number"==typeof e.index)}function pg(e={},t={}){const r={...e};for(const[e,n]of Object.entries(t))if(null==r[e])r[e]=n;else{if(null==n)continue;if(typeof r[e]!=typeof n||Array.isArray(r[e])!==Array.isArray(n))throw new Error(`field[${e}] already exists in the message chunk, but with a different type.`);if("string"==typeof r[e]){if("type"===e)continue;["id","name","output_version","model_provider"].includes(e)?r[e]=n:r[e]+=n}else if("object"!=typeof r[e]||Array.isArray(r[e]))if(Array.isArray(r[e]))r[e]=mg(r[e],n);else{if(r[e]===n)continue;console.warn(`field[${e}] already exists in this message chunk and value has unsupported type.`)}else r[e]=pg(r[e],n)}return r}function mg(e,t){if(void 0!==e||void 0!==t){if(void 0===e||void 0===t)return e||t;{const r=[...e];for(const e of t)if("object"==typeof e&&null!==e&&"index"in e&&"number"==typeof e.index){const t=r.findIndex(t=>{const r="object"==typeof t,n="index"in t&&t.index===e.index;return r&&n&&("id"in t&&"id"in e&&t?.id===e?.id||!("id"in t&&t?.id&&"id"in e&&e?.id))});-1!==t&&"object"==typeof r[t]&&null!==r[t]?r[t]=pg(r[t],e):r.push(e)}else{if("object"==typeof e&&null!==e&&"text"in e&&""===e.text)continue;r.push(e)}return r}}}function hg(e,t){if(!e&&!t)throw new Error("Cannot merge two undefined objects.");if(e&&t){if(typeof e!=typeof t)throw new Error(`Cannot merge objects of different types.\nLeft ${typeof e}\nRight ${typeof t}`);if("string"==typeof e&&"string"==typeof t)return e+t;if(Array.isArray(e)&&Array.isArray(t))return mg(e,t);if("object"==typeof e&&"object"==typeof t)return pg(e,t);if(e===t)return e;throw new Error(`Can not merge objects of different types.\nLeft ${e}\nRight ${t}`)}return e||t}var fg=class extends ug{static isInstance(e){return super.isInstance(e)&&"concat"in e&&"function"==typeof e.concat}};function gg(e){return"string"==typeof e.role}function yg(e){return"function"==typeof e?._getType}function vg(e){return yg(e)&&"function"==typeof e.concat}function bg(e,t){return pg(e??{},t??{})}function _g(e,t){const r={};return void 0===e?.audio&&void 0===t?.audio||(r.audio=(e?.audio??0)+(t?.audio??0)),void 0===e?.image&&void 0===t?.image||(r.image=(e?.image??0)+(t?.image??0)),void 0===e?.video&&void 0===t?.video||(r.video=(e?.video??0)+(t?.video??0)),void 0===e?.document&&void 0===t?.document||(r.document=(e?.document??0)+(t?.document??0)),void 0===e?.text&&void 0===t?.text||(r.text=(e?.text??0)+(t?.text??0)),r}function wg(e,t){const r={..._g(e,t)};return void 0===e?.cache_read&&void 0===t?.cache_read||(r.cache_read=(e?.cache_read??0)+(t?.cache_read??0)),void 0===e?.cache_creation&&void 0===t?.cache_creation||(r.cache_creation=(e?.cache_creation??0)+(t?.cache_creation??0)),r}function Sg(e,t){const r={..._g(e,t)};return void 0===e?.reasoning&&void 0===t?.reasoning||(r.reasoning=(e?.reasoning??0)+(t?.reasoning??0)),r}function Ng(e,t){return{input_tokens:(e?.input_tokens??0)+(t?.input_tokens??0),output_tokens:(e?.output_tokens??0)+(t?.output_tokens??0),total_tokens:(e?.total_tokens??0)+(t?.total_tokens??0),input_token_details:wg(e?.input_token_details,t?.input_token_details),output_token_details:Sg(e?.output_token_details,t?.output_token_details)}}function kg(e){return null!=e&&"object"==typeof e&&"lc_direct_tool_output"in e&&!0===e.lc_direct_tool_output}yf({},{ToolMessage:()=>xg,ToolMessageChunk:()=>Eg,defaultToolCallParser:()=>Pg,isDirectToolOutput:()=>kg,isToolMessage:()=>Cg,isToolMessageChunk:()=>Ag});var xg=class extends ug{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}lc_direct_tool_output=!0;type="tool";status;tool_call_id;metadata;artifact;constructor(e,t,r){const n="string"==typeof e||Array.isArray(e)?{content:e,name:r,tool_call_id:t}:e;super(n),this.tool_call_id=n.tool_call_id,this.artifact=n.artifact,this.status=n.status,this.metadata=n.metadata}static isInstance(e){return super.isInstance(e)&&"tool"===e.type}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},Eg=class extends fg{type="tool";tool_call_id;status;artifact;constructor(e){super(e),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}concat(e){return new(0,this.constructor)({content:cg(this.content,e.content),additional_kwargs:pg(this.additional_kwargs,e.additional_kwargs),response_metadata:pg(this.response_metadata,e.response_metadata),artifact:hg(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:lg(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function Pg(e){const t=[],r=[];for(const n of e){if(!n.function)continue;{const e=n.function.name;try{const r=JSON.parse(n.function.arguments);t.push({name:e||"",args:r||{},id:n.id})}catch{r.push({name:e,args:n.function.arguments,id:n.id,error:"Malformed args."})}}}return[t,r]}function Cg(e){return"object"==typeof e&&null!==e&&"getType"in e&&"function"==typeof e.getType&&"tool"===e.getType()}function Ag(e){return"tool"===e._getType()}function Ig(e,t=Og){const r=(e=e.trim()).indexOf("```");if(-1===r)return t(e);let n=e.substring(r+3);n.startsWith("json\n")?n=n.substring(5):n.startsWith("json")?n=n.substring(4):n.startsWith("\n")&&(n=n.substring(1));const a=n.indexOf("```");let i=n;return-1!==a&&(i=n.substring(0,a)),t(i.trim())}function Og(e){if(void 0===e)return null;try{return JSON.parse(e)}catch{}let t="";const r=[];let n=!1,a=!1;for(let i of e){if(n)'"'!==i||a?"\n"!==i||a?a="\\"===i&&!a:i="\\n":n=!1;else if('"'===i)n=!0,a=!1;else if("{"===i)r.push("}");else if("["===i)r.push("]");else if("}"===i||"]"===i){if(!r||r[r.length-1]!==i)return null;r.pop()}t+=i}n&&(t+='"');for(let e=r.length-1;e>=0;e-=1)t+=r[e];try{return JSON.parse(t)}catch{return null}}function Tg(e){switch(e){case"csv":return"text/csv";case"doc":case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}function $g(e){if(jf(e.document)&&jf(e.document.source)){const t=Tg(jf(e.document)&&Uf(e.document.format)?e.document.format:"");if(jf(e.document.source)){if(jf(e.document.source.s3Location)&&Uf(e.document.source.s3Location.uri))return{type:"file",mimeType:t,fileId:e.document.source.s3Location.uri};if(Bf(e.document.source.bytes))return{type:"file",mimeType:t,data:e.document.source.bytes};if(Uf(e.document.source.text))return{type:"file",mimeType:t,data:Buffer.from(e.document.source.text).toString("base64")};if(Ff(e.document.source.content)){return{type:"file",mimeType:t,data:e.document.source.content.reduce((e,t)=>jf(t)&&Uf(t.text)?e+t.text:e,"")}}}}return{type:"non_standard",value:e}}function zg(e){if(Df(e,"image")&&jf(e.image)){const t=Tg(jf(e.image)&&Uf(e.image.format)?e.image.format:"");if(jf(e.image.source)){if(jf(e.image.source.s3Location)&&Uf(e.image.source.s3Location.uri))return{type:"image",mimeType:t,fileId:e.image.source.s3Location.uri};if(Bf(e.image.source.bytes))return{type:"image",mimeType:t,data:e.image.source.bytes}}}return{type:"non_standard",value:e}}function Rg(e){if(Df(e,"video")&&jf(e.video)){const t=Tg(jf(e.video)&&Uf(e.video.format)?e.video.format:"");if(jf(e.video.source)){if(jf(e.video.source.s3Location)&&Uf(e.video.source.s3Location.uri))return{type:"video",mimeType:t,fileId:e.video.source.s3Location.uri};if(Bf(e.video.source.bytes))return{type:"video",mimeType:t,data:e.video.source.bytes}}}return{type:"non_standard",value:e}}function Lg(e){return Array.from(function*(){const t="string"==typeof e.content?[{type:"text",text:e.content}]:e.content;for(const e of t)if(Df(e,"cache_point"))yield{type:"non_standard",value:e};else{if(Df(e,"citations_content")&&jf(e.citationsContent)){const t=Ff(e.citationsContent.content)?e.citationsContent.content.reduce((e,t)=>jf(t)&&Uf(t.text)?e+t.text:e,""):"",r=Ff(e.citationsContent.citations)?e.citationsContent.citations.reduce((e,t)=>{if(jf(t)){const r=Ff(t.sourceContent)?t.sourceContent.reduce((e,t)=>jf(t)&&Uf(t.text)?e+t.text:e,""):"",n=Gf(()=>{if(jf(t.location)){const e=t.location.documentChar||t.location.documentPage||t.location.documentChunk;if(jf(e))return{source:qf(e.documentIndex)?e.documentIndex.toString():void 0,startIndex:qf(e.start)?e.start:void 0,endIndex:qf(e.end)?e.end:void 0}}return{}});e.push({type:"citation",citedText:r,...n})}return e},[]):[];yield{type:"text",text:t,annotations:r};continue}Df(e,"document")&&jf(e.document)?yield $g(e):Df(e,"guard_content")?yield{type:"non_standard",value:e}:Df(e,"image")&&jf(e.image)?yield zg(e):Df(e,"reasoning_content")&&Uf(e.reasoningText)?yield{type:"reasoning",reasoning:e.reasoningText}:Df(e,"text")&&Uf(e.text)?yield{type:"text",text:e.text}:Df(e,"tool_result")?yield{type:"non_standard",value:e}:Df(e,"tool_call")||(Df(e,"video")&&jf(e.video)?yield Rg(e):yield{type:"non_standard",value:e})}}())}const Mg={translateContent:Lg,translateContentChunk:Lg};function Dg(e){return Array.from(function*(){const t="string"==typeof e.content?[{type:"text",text:e.content}]:e.content;for(const r of t)Df(r,"text")&&Uf(r.text)?yield{type:"text",text:r.text}:Df(r,"inlineData")&&jf(r.inlineData)&&Uf(r.inlineData.mimeType)&&Uf(r.inlineData.data)?yield{type:"file",mimeType:r.inlineData.mimeType,data:r.inlineData.data}:Df(r,"functionCall")&&jf(r.functionCall)&&Uf(r.functionCall.name)&&jf(r.functionCall.args)?yield{type:"tool_call",id:e.id,name:r.functionCall.name,args:r.functionCall.args}:Df(r,"functionResponse")?yield{type:"non_standard",value:r}:Df(r,"fileData")&&jf(r.fileData)&&Uf(r.fileData.mimeType)&&Uf(r.fileData.fileUri)?yield{type:"file",mimeType:r.fileData.mimeType,fileId:r.fileData.fileUri}:(Df(r,"executableCode")||Df(r,"codeExecutionResult"),yield{type:"non_standard",value:r})}())}const jg={translateContent:Dg,translateContentChunk:Dg};function Fg(e){return Array.from(function*(){const t="string"==typeof e.content?[{type:"text",text:e.content}]:e.content;for(const r of t){if(Df(r,"reasoning")&&Uf(r.reasoning)){const n=Gf(()=>{const n=t.indexOf(r);if(Ff(e.additional_kwargs?.signatures)&&n>=0)return e.additional_kwargs.signatures.at(n)});Uf(n)?yield{type:"reasoning",reasoning:r.reasoning,signature:n}:yield{type:"reasoning",reasoning:r.reasoning};continue}if(Df(r,"text")&&Uf(r.text))yield{type:"text",text:r.text};else if(Df(r,"image_url")){if(Uf(r.image_url))if(r.image_url.startsWith("data:")){const e=/^data:([^;]+);base64,(.+)$/,t=r.image_url.match(e);t?yield{type:"image",data:t[2],mimeType:t[1]}:yield{type:"image",url:r.image_url}}else yield{type:"image",url:r.image_url}}else Df(r,"media")&&Uf(r.mimeType)&&Uf(r.data)?yield{type:"file",mimeType:r.mimeType,data:r.data}:yield{type:"non_standard",value:r}}}())}const Ug={translateContent:Fg,translateContentChunk:Fg};function qg(e){return globalThis.lc_block_translators_registry.get(e)}globalThis.lc_block_translators_registry??=new Map([["anthropic",Jf],["bedrock-converse",Mg],["google-genai",jg],["google-vertexai",Ug],["openai",ig]]);var Bg=class extends ug{type="ai";tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(e){let t;if("string"==typeof e||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{t=e;const r=t.additional_kwargs?.tool_calls,n=t.tool_calls;null!=r&&r.length>0&&(void 0===n||0===n.length)&&console.warn(["New LangChain packages are available that more efficiently handle","tool calling.\n\nPlease upgrade your packages to versions that set","message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(null!=r&&void 0===n){const[e,n]=Pg(r);t.tool_calls=e??[],t.invalid_tool_calls=n??[]}else t.tool_calls=t.tool_calls??[],t.invalid_tool_calls=t.invalid_tool_calls??[]}catch{t.tool_calls=[],t.invalid_tool_calls=[]}if(void 0!==t.response_metadata&&"output_version"in t.response_metadata&&"v1"===t.response_metadata.output_version&&(t.contentBlocks=t.content,t.content=void 0),void 0!==t.contentBlocks){t.contentBlocks.push(...t.tool_calls.map(e=>({type:"tool_call",id:e.id,name:e.name,args:e.args})));const e=t.contentBlocks.filter(e=>"tool_call"===e.type).filter(e=>!t.tool_calls?.some(t=>t.id===e.id&&t.name===e.name));e.length>0&&(t.tool_calls=e.map(e=>({type:"tool_call",id:e.id,name:e.name,args:e.args})))}}super(t),"string"!=typeof t&&(this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=t.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&"v1"===this.response_metadata.output_version)return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&"string"==typeof this.response_metadata.model_provider){const e=qg(this.response_metadata.model_provider);if(e)return e.translateContent(this)}const e=super.contentBlocks;if(this.tool_calls){const t=this.tool_calls.filter(t=>!e.some(e=>e.id===t.id&&e.name===t.name));e.push(...t.map(e=>({...e,type:"tool_call",id:e.id,name:e.name,args:e.args})))}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(e){return super.isInstance(e)&&"ai"===e.type}};function Vg(e){return"ai"===e._getType()}function Gg(e){return"ai"===e._getType()}var Hg=class extends fg{type="ai";tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(e){let t;if("string"==typeof e||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(void 0===e.tool_call_chunks||0===e.tool_call_chunks.length)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:void 0!==e.usage_metadata?e.usage_metadata:void 0};else{const r=(e.tool_call_chunks??[]).reduce((e,t)=>{const r=e.findIndex(([e])=>"id"in t&&t.id&&"index"in t&&void 0!==t.index?t.id===e.id&&t.index===e.index:"id"in t&&t.id?t.id===e.id:"index"in t&&void 0!==t.index&&t.index===e.index);return-1!==r?e[r].push(t):e.push([t]),e},[]),n=[],a=[];for(const e of r){let t=null;const r=e[0]?.name??"",i=e.map(e=>e.args||"").join(""),s=i.length?i:"{}",o=e[0]?.id;try{if(t=Og(s),!o||null===t||"object"!=typeof t||Array.isArray(t))throw new Error("Malformed tool call chunk args.");n.push({name:r,args:t,id:o,type:"tool_call"})}catch{a.push({name:r,args:s,id:o,error:"Malformed args.",type:"invalid_tool_call"})}}t={...e,tool_calls:n,invalid_tool_calls:a,usage_metadata:void 0!==e.usage_metadata?e.usage_metadata:void 0}}super(t),this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&"v1"===this.response_metadata.output_version)return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&"string"==typeof this.response_metadata.model_provider){const e=qg(this.response_metadata.model_provider);if(e)return e.translateContent(this)}const e=super.contentBlocks;if(this.tool_calls&&"string"!=typeof this.content){const t=this.content.filter(e=>"tool_call"===e.type).map(e=>e.id);for(const r of this.tool_calls)r.id&&!t.includes(r.id)&&e.push({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){const t={content:cg(this.content,e.content),additional_kwargs:pg(this.additional_kwargs,e.additional_kwargs),response_metadata:bg(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};if(void 0!==this.tool_call_chunks||void 0!==e.tool_call_chunks){const r=mg(this.tool_call_chunks,e.tool_call_chunks);void 0!==r&&r.length>0&&(t.tool_call_chunks=r)}void 0===this.usage_metadata&&void 0===e.usage_metadata||(t.usage_metadata=Ng(this.usage_metadata,e.usage_metadata));return new(0,this.constructor)(t)}static isInstance(e){return super.isInstance(e)&&"ai"===e.type}},Kg=class e extends ug{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return e}constructor(e,t){("string"==typeof e||Array.isArray(e))&&(e={content:e,role:t}),super(e),this.role=e.role}static isInstance(e){return super.isInstance(e)&&"generic"===e.type}get _printableFields(){return{...super._printableFields,role:this.role}}},Wg=class extends fg{static lc_name(){return"ChatMessageChunk"}type="generic";role;constructor(e,t){("string"==typeof e||Array.isArray(e))&&(e={content:e,role:t}),super(e),this.role=e.role}concat(e){return new(0,this.constructor)({content:cg(this.content,e.content),additional_kwargs:pg(this.additional_kwargs,e.additional_kwargs),response_metadata:pg(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&"generic"===e.type}get _printableFields(){return{...super._printableFields,role:this.role}}};function Zg(e){return"generic"===e._getType()}function Jg(e){return"generic"===e._getType()}var Yg=class extends ug{static lc_name(){return"FunctionMessage"}type="function";name;constructor(e){super(e),this.name=e.name}},Qg=class extends fg{static lc_name(){return"FunctionMessageChunk"}type="function";concat(e){return new(0,this.constructor)({content:cg(this.content,e.content),additional_kwargs:pg(this.additional_kwargs,e.additional_kwargs),response_metadata:pg(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}};function Xg(e){return"function"===e._getType()}function ey(e){return"function"===e._getType()}var ty=class extends ug{static lc_name(){return"HumanMessage"}type="human";constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&"human"===e.type}},ry=class extends fg{static lc_name(){return"HumanMessageChunk"}type="human";constructor(e){super(e)}concat(e){return new(0,this.constructor)({content:cg(this.content,e.content),additional_kwargs:pg(this.additional_kwargs,e.additional_kwargs),response_metadata:pg(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&"human"===e.type}};function ny(e){return"human"===e.getType()}function ay(e){return"human"===e.getType()}var iy=class extends ug{static lc_name(){return"SystemMessage"}type="system";constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&"system"===e.type}},sy=class extends fg{static lc_name(){return"SystemMessageChunk"}type="system";constructor(e){super(e)}concat(e){return new(0,this.constructor)({content:cg(this.content,e.content),additional_kwargs:pg(this.additional_kwargs,e.additional_kwargs),response_metadata:pg(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&"system"===e.type}};function oy(e){return"system"===e._getType()}function cy(e){return"system"===e._getType()}var ly=class extends ug{type="remove";id;constructor(e){super({...e,content:[]}),this.id=e.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(e){return super.isInstance(e)&&"remove"===e.type}};function uy(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/\n`,e}function dy(e){return!(!e||"object"!=typeof e||!("type"in e)||"tool_call"!==e.type)}var py=class extends Error{output;constructor(e,t){super(e),this.output=t}};const my=e=>e();function hy(e){return dy(e)?e:"string"==typeof e.id&&"function"===e.type&&"object"==typeof e.function&&null!==e.function&&"arguments"in e.function&&"string"==typeof e.function.arguments&&"name"in e.function&&"string"==typeof e.function.name?{id:e.id,args:JSON.parse(e.function.arguments),name:e.function.name,type:"tool_call"}:e}function fy(e){let t,r;if("object"==typeof(n=e)&&null!=n&&1===n.lc&&Array.isArray(n.id)&&null!=n.kwargs&&"object"==typeof n.kwargs){const n=e.id.at(-1);t="HumanMessage"===n||"HumanMessageChunk"===n?"user":"AIMessage"===n||"AIMessageChunk"===n?"assistant":"SystemMessage"===n||"SystemMessageChunk"===n?"system":"FunctionMessage"===n||"FunctionMessageChunk"===n?"function":"ToolMessage"===n||"ToolMessageChunk"===n?"tool":"unknown",r=e.kwargs}else{const{type:n,...a}=e;t=n,r=a}var n;if("human"===t||"user"===t)return new ty(r);if("ai"===t||"assistant"===t){const{tool_calls:e,...t}=r;if(!Array.isArray(e))return new Bg(r);const n=e.map(hy);return new Bg({...t,tool_calls:n})}if("system"===t)return new iy(r);if("developer"===t)return new iy({...r,additional_kwargs:{...r.additional_kwargs,__openai_role__:"developer"}});if("tool"===t&&"tool_call_id"in r)return new xg({...r,content:r.content,tool_call_id:r.tool_call_id,name:r.name});if("remove"===t&&"id"in r&&"string"==typeof r.id)return new ly({...r,id:r.id});throw uy(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.\n\nReceived: ${JSON.stringify(e,null,2)}`),"MESSAGE_COERCION_FAILURE")}function gy(e){if("string"==typeof e)return new ty(e);if(yg(e))return e;if(Array.isArray(e)){const[t,r]=e;return fy({type:t,content:r})}if(gg(e)){const{role:t,...r}=e;return fy({...r,type:t})}return fy(e)}function yy(e,t="Human",r="AI"){const n=[];for(const a of e){let e;if("human"===a._getType())e=t;else if("ai"===a._getType())e=r;else if("system"===a._getType())e="System";else if("tool"===a._getType())e="Tool";else{if("generic"!==a._getType())throw new Error(`Got unsupported message type: ${a._getType()}`);e=a.role}const i=a.name?`${a.name}, `:"",s="string"==typeof a.content?a.content:JSON.stringify(a.content,null,2);n.push(`${e}: ${i}${s}`)}return n.join("\n")}function vy(e){const t=function(e){if(void 0!==e.data)return e;{const t=e;return{type:t.type,data:{content:t.text,role:t.role,name:void 0,tool_call_id:void 0}}}}(e);switch(t.type){case"human":return new ty(t.data);case"ai":return new Bg(t.data);case"system":return new iy(t.data);case"function":if(void 0===t.data.name)throw new Error("Name must be defined for function messages");return new Yg(t.data);case"tool":if(void 0===t.data.tool_call_id)throw new Error("Tool call ID must be defined for tool messages");return new xg(t.data);case"generic":if(void 0===t.data.role)throw new Error("Role must be defined for chat messages");return new Kg(t.data);default:throw new Error(`Got unexpected type: ${t.type}`)}}function by(e){return e.map(vy)}function _y(e){return e.map(e=>e.toDict())}function wy(e){const t=e._getType();if("human"===t)return new ry({...e});if("ai"===t){let t={...e};return"tool_calls"in t&&(t={...t,tool_call_chunks:t.tool_calls?.map(e=>({...e,type:"tool_call_chunk",index:void 0,args:JSON.stringify(e.args)}))}),new Hg({...t})}if("system"===t)return new sy({...e});if("function"===t)return new Qg({...e});if(Kg.isInstance(e))return new Wg({...e});throw new Error("Unknown message type.")}const Sy=Symbol.for("ls:tracing_async_local_storage"),Ny=Symbol.for("lc:context_variables"),ky=()=>globalThis[Sy];yf({},{getEnv:()=>Iy,getEnvironmentVariable:()=>$y,getRuntimeEnvironment:()=>Ty,isBrowser:()=>xy,isDeno:()=>Cy,isJsDom:()=>Py,isNode:()=>Ay,isWebWorker:()=>Ey});const xy=()=>"undefined"!=typeof window&&void 0!==window.document,Ey=()=>"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name,Py=()=>"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&navigator.userAgent.includes("jsdom"),Cy=()=>"undefined"!=typeof Deno,Ay=()=>"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node&&!Cy(),Iy=()=>{let e;return e=xy()?"browser":Ay()?"node":Ey()?"webworker":Py()?"jsdom":Cy()?"deno":"other",e};let Oy;function Ty(){if(void 0===Oy){const e=Iy();Oy={library:"langchain-js",runtime:e}}return Oy}function $y(e){try{return"undefined"!=typeof process?process.env?.[e]:Cy()?Deno?.env.get(e):void 0}catch{return}}var zy=/^(?:[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 Ry(e){return"string"==typeof e&&zy.test(e)}for(var Ly,My=[],Dy=0;Dy<256;++Dy)My.push((Dy+256).toString(16).slice(1));function jy(e,t=0){return(My[e[t+0]]+My[e[t+1]]+My[e[t+2]]+My[e[t+3]]+"-"+My[e[t+4]]+My[e[t+5]]+"-"+My[e[t+6]]+My[e[t+7]]+"-"+My[e[t+8]]+My[e[t+9]]+"-"+My[e[t+10]]+My[e[t+11]]+My[e[t+12]]+My[e[t+13]]+My[e[t+14]]+My[e[t+15]]).toLowerCase()}var Fy=new Uint8Array(16);function Uy(){if(!Ly&&!(Ly="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ly(Fy)}var qy={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function By(e,t,r){if(qy.randomUUID&&!e)return qy.randomUUID();var n=(e=e||{}).random||(e.rng||Uy)();return n[6]=15&n[6]|64,n[8]=63&n[8]|128,jy(n)}function Vy(e,t,r,n){switch(e){case 0:return t&r^~t&n;case 1:case 3:return t^r^n;case 2:return t&r^t&n^r&n}}function Gy(e,t){return e<<t|e>>>32-t}var Hy=function(e,t,r){function n(e,n,a,i){var s;if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));for(var t=[],r=0;r<e.length;++r)t.push(e.charCodeAt(r));return t}(e)),"string"==typeof n&&(n=function(e){if(!Ry(e))throw TypeError("Invalid UUID");var t,r=new Uint8Array(16);return r[0]=(t=parseInt(e.slice(0,8),16))>>>24,r[1]=t>>>16&255,r[2]=t>>>8&255,r[3]=255&t,r[4]=(t=parseInt(e.slice(9,13),16))>>>8,r[5]=255&t,r[6]=(t=parseInt(e.slice(14,18),16))>>>8,r[7]=255&t,r[8]=(t=parseInt(e.slice(19,23),16))>>>8,r[9]=255&t,r[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,r[11]=t/4294967296&255,r[12]=t>>>24&255,r[13]=t>>>16&255,r[14]=t>>>8&255,r[15]=255&t,r}(n)),16!==(null===(s=n)||void 0===s?void 0:s.length))throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var o=new Uint8Array(16+e.length);if(o.set(n),o.set(e,n.length),(o=r(o))[6]=15&o[6]|t,o[8]=63&o[8]|128,a){i=i||0;for(var c=0;c<16;++c)a[i+c]=o[c];return a}return jy(o)}try{n.name=e}catch(e){}return n.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",n.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",n}("v5",80,function(e){var t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){var n=unescape(encodeURIComponent(e));e=[];for(var a=0;a<n.length;++a)e.push(n.charCodeAt(a))}else Array.isArray(e)||(e=Array.prototype.slice.call(e));e.push(128);for(var i=e.length/4+2,s=Math.ceil(i/16),o=new Array(s),c=0;c<s;++c){for(var l=new Uint32Array(16),u=0;u<16;++u)l[u]=e[64*c+4*u]<<24|e[64*c+4*u+1]<<16|e[64*c+4*u+2]<<8|e[64*c+4*u+3];o[c]=l}o[s-1][14]=8*(e.length-1)/Math.pow(2,32),o[s-1][14]=Math.floor(o[s-1][14]),o[s-1][15]=8*(e.length-1)&4294967295;for(var d=0;d<s;++d){for(var p=new Uint32Array(80),m=0;m<16;++m)p[m]=o[d][m];for(var h=16;h<80;++h)p[h]=Gy(p[h-3]^p[h-8]^p[h-14]^p[h-16],1);for(var f=r[0],g=r[1],y=r[2],v=r[3],b=r[4],_=0;_<80;++_){var w=Math.floor(_/20),S=Gy(f,5)+Vy(w,g,y,v)+b+t[w]+p[_]>>>0;b=v,v=y,y=Gy(g,30)>>>0,g=f,f=S}r[0]=r[0]+f>>>0,r[1]=r[1]+g>>>0,r[2]=r[2]+y>>>0,r[3]=r[3]+v>>>0,r[4]=r[4]+b>>>0}return[r[0]>>24&255,r[0]>>16&255,r[0]>>8&255,255&r[0],r[1]>>24&255,r[1]>>16&255,r[1]>>8&255,255&r[1],r[2]>>24&255,r[2]>>16&255,r[2]>>8&255,255&r[2],r[3]>>24&255,r[3]>>16&255,r[3]>>8&255,255&r[3],r[4]>>24&255,r[4]>>16&255,r[4]>>8&255,255&r[4]]});yf({},{BaseCallbackHandler:()=>Zy,callbackHandlerPrefersStreaming:()=>Wy,isBaseCallbackHandler:()=>Jy});var Ky=class{};function Wy(e){return"lc_prefer_streaming"in e&&e.lc_prefer_streaming}var Zy=class extends Ky{lc_serializable=!1;get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Lf(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers="false"===$y("LANGCHAIN_CALLBACKS_BACKGROUND");constructor(e){super(),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return Mf.prototype.toJSON.call(this)}toJSONNotImplemented(){return Mf.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){return new class extends Zy{name=By();constructor(){super(),Object.assign(this,e)}}}};const Jy=e=>{const t=e;return void 0!==t&&"function"==typeof t.copy&&"string"==typeof t.name&&"boolean"==typeof t.awaitHandlers},Yy="gen_ai.request.model",Qy="gen_ai.usage.input_tokens",Xy="gen_ai.usage.output_tokens",ev="gen_ai.usage.total_tokens",tv="langsmith.span.tags",rv=(...e)=>fetch(...e),nv=Symbol.for("ls:fetch_implementation"),av=e=>async(...t)=>{if(e||"true"===fv("DEBUG")){const[e,r]=t;console.log(`→ ${r?.method||"GET"} ${e}`)}const r=await(globalThis[nv]??rv)(...t);return(e||"true"===fv("DEBUG"))&&console.log(`← ${r.status} ${r.statusText} ${r.url}`),r},iv=()=>fv("PROJECT")??hv("LANGCHAIN_SESSION")??"default",sv="0.3.74";let ov;const cv=()=>"undefined"!=typeof Deno,lv=()=>ov||(ov="undefined"!=typeof Bun?"bun":"undefined"!=typeof window&&void 0!==window.document?"browser":"undefined"==typeof process||void 0===process.versions||void 0===process.versions.node||cv()?"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name?"webworker":"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&navigator.userAgent.includes("jsdom")?"jsdom":cv()?"deno":"other":"node",ov);let uv,dv;function pv(){if(void 0===uv){const e=lv(),t=function(){if(void 0!==dv)return dv;const e=["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","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],t={};for(const r of e){const e=hv(r);void 0!==e&&(t[r]=e)}return dv=t,t}();uv={library:"langsmith",runtime:e,sdk:"langsmith-js",sdk_version:sv,...t}}return uv}function mv(){const e=function(){const e={};try{if("undefined"!=typeof process&&process.env)for(const[t,r]of Object.entries(process.env))(t.startsWith("LANGCHAIN_")||t.startsWith("LANGSMITH_"))&&null!=r&&((t.toLowerCase().includes("key")||t.toLowerCase().includes("secret")||t.toLowerCase().includes("token"))&&"string"==typeof r?e[t]=r.slice(0,2)+"*".repeat(r.length-4)+r.slice(-2):e[t]=r)}catch(e){}return e}(),t={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(const[n,a]of Object.entries(e))"string"!=typeof a||r.includes(n)||n.toLowerCase().includes("key")||n.toLowerCase().includes("secret")||n.toLowerCase().includes("token")||("LANGCHAIN_REVISION_ID"===n?t.revision_id=a:t[n]=a);return t}function hv(e){try{return"undefined"!=typeof process?process.env?.[e]:void 0}catch(e){return}}function fv(e){return hv(`LANGSMITH_${e}`)||hv(`LANGCHAIN_${e}`)}function gv(){return"true"===hv("OTEL_ENABLED")||"true"===fv("OTEL_ENABLED")}class yv{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...t){let r;if(!this.hasWarned&&gv()&&(console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0),1===t.length&&"function"==typeof t[0]?r=t[0]:2===t.length&&"function"==typeof t[1]?r=t[1]:3===t.length&&"function"==typeof t[2]&&(r=t[2]),"function"==typeof r)return r()}}const vv=Symbol.for("ls:otel_trace"),bv=Symbol.for("ls:otel_context"),_v=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),wv=new class{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new yv})}getTracer(e,t){return this.mockTracer}getActiveSpan(){}setSpan(e,t){return e}getSpan(e){}setSpanContext(e,t){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},Sv=new class{active(){return{}}with(e,t){return t()}};const Nv=new class{getTraceInstance(){return globalThis[vv]??wv}getContextInstance(){return globalThis[bv]??Sv}initializeGlobalInstances(e){void 0===globalThis[vv]&&(globalThis[vv]=e.trace),void 0===globalThis[bv]&&(globalThis[bv]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[_v]=e}getDefaultOTLPTracerComponents(){return globalThis[_v]??void 0}};function kv(){return Nv.getTraceInstance()}const xv={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};class Ev{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,t){for(const r of e)try{if(!r.run)continue;if("post"===r.operation){const e=this.createSpanForRun(r,r.run,t.get(r.id));e&&!r.run.end_time&&this.spans.set(r.id,e)}else this.updateSpanForRun(r,r.run)}catch(e){console.error(`Error processing operation ${r.id}:`,e)}}createSpanForRun(e,t,r){const n=r&&kv().getSpan(r);if(n)try{return this.finishSpanSetup(n,t,e)}catch(t){return void console.error(`Failed to create span for run ${e.id}:`,t)}}finishSpanSetup(e,t,r){return this.setSpanAttributes(e,t,r),t.error?(e.setStatus({code:2}),e.recordException(new Error(t.error))):e.setStatus({code:1}),t.end_time&&e.end(new Date(t.end_time)),e}updateSpanForRun(e,t){try{const r=this.spans.get(e.id);if(!r)return void console.debug(`No span found for run ${e.id} during update`);this.setSpanAttributes(r,t,e),t.error?(r.setStatus({code:2}),r.recordException(new Error(t.error))):r.setStatus({code:1});const n=t.end_time;n&&(r.end(new Date(n)),this.spans.delete(e.id))}catch(t){console.error(`Failed to update span for run ${e.id}:`,t)}}extractModelName(e){if(e.extra?.metadata){const t=e.extra.metadata;if(t.ls_model_name)return t.ls_model_name;if(t.invocation_params){const e=t.invocation_params;if(e.model)return e.model;if(e.model_name)return e.model_name}}}setSpanAttributes(e,t,r){if("run_type"in t&&t.run_type){e.setAttribute("langsmith.span.kind",t.run_type);const r=(n=t.run_type||"chain",xv[n]||n);e.setAttribute("gen_ai.operation.name",r)}var n;"name"in t&&t.name&&e.setAttribute("langsmith.trace.name",t.name),"session_id"in t&&t.session_id&&e.setAttribute("langsmith.trace.session_id",t.session_id),"session_name"in t&&t.session_name&&e.setAttribute("langsmith.trace.session_name",t.session_name),this.setGenAiSystem(e,t);const a=this.extractModelName(t);a&&e.setAttribute(Yy,a),"prompt_tokens"in t&&"number"==typeof t.prompt_tokens&&e.setAttribute(Qy,t.prompt_tokens),"completion_tokens"in t&&"number"==typeof t.completion_tokens&&e.setAttribute(Xy,t.completion_tokens),"total_tokens"in t&&"number"==typeof t.total_tokens&&e.setAttribute(ev,t.total_tokens),this.setInvocationParameters(e,t);const i=t.extra?.metadata||{};for(const[t,r]of Object.entries(i))null!=r&&e.setAttribute(`langsmith.metadata.${t}`,String(r));const s=t.tags;if(s&&Array.isArray(s)?e.setAttribute(tv,s.join(", ")):s&&e.setAttribute(tv,String(s)),"serialized"in t&&"object"==typeof t.serialized){const r=t.serialized;r.name&&e.setAttribute("gen_ai.serialized.name",String(r.name)),r.signature&&e.setAttribute("gen_ai.serialized.signature",String(r.signature)),r.doc&&e.setAttribute("gen_ai.serialized.doc",String(r.doc))}this.setIOAttributes(e,r)}setGenAiSystem(e,t){let r="langchain";const n=this.extractModelName(t);if(n){const e=n.toLowerCase();e.includes("anthropic")||e.startsWith("claude")?r="anthropic":e.includes("bedrock")?r="aws.bedrock":e.includes("azure")&&e.includes("openai")?r="az.ai.openai":e.includes("azure")&&e.includes("inference")?r="az.ai.inference":e.includes("cohere")?r="cohere":e.includes("deepseek")?r="deepseek":e.includes("gemini")?r="gemini":e.includes("groq")?r="groq":e.includes("watson")||e.includes("ibm")?r="ibm.watsonx.ai":e.includes("mistral")?r="mistral_ai":e.includes("gpt")||e.includes("openai")?r="openai":e.includes("perplexity")||e.includes("sonar")?r="perplexity":e.includes("vertex")?r="vertex_ai":(e.includes("xai")||e.includes("grok"))&&(r="xai")}e.setAttribute("gen_ai.system",r)}setInvocationParameters(e,t){if(!t.extra?.metadata?.invocation_params)return;const r=t.extra.metadata.invocation_params;void 0!==r.max_tokens&&e.setAttribute("gen_ai.request.max_tokens",r.max_tokens),void 0!==r.temperature&&e.setAttribute("gen_ai.request.temperature",r.temperature),void 0!==r.top_p&&e.setAttribute("gen_ai.request.top_p",r.top_p),void 0!==r.frequency_penalty&&e.setAttribute("gen_ai.request.frequency_penalty",r.frequency_penalty),void 0!==r.presence_penalty&&e.setAttribute("gen_ai.request.presence_penalty",r.presence_penalty)}setIOAttributes(e,t){if(t.run.inputs)try{const r=t.run.inputs;"object"==typeof r&&null!==r&&(r.model&&Array.isArray(r.messages)&&e.setAttribute(Yy,r.model),void 0!==r.stream&&e.setAttribute("langsmith.request.streaming",r.stream),r.extra_headers&&e.setAttribute("langsmith.request.headers",JSON.stringify(r.extra_headers)),r.extra_query&&e.setAttribute("gen_ai.request.extra_query",JSON.stringify(r.extra_query)),r.extra_body&&e.setAttribute("gen_ai.request.extra_body",JSON.stringify(r.extra_body))),e.setAttribute("gen_ai.prompt",JSON.stringify(r))}catch(e){console.debug(`Failed to process inputs for run ${t.id}`,e)}if(t.run.outputs)try{const r=t.run.outputs,n=this.getUnifiedRunTokens(r);if(n&&(e.setAttribute(Qy,n[0]),e.setAttribute(Xy,n[1]),e.setAttribute(ev,n[0]+n[1])),r&&"object"==typeof r){if(r.model&&e.setAttribute("gen_ai.response.model",String(r.model)),r.id&&e.setAttribute("gen_ai.response.id",r.id),r.choices&&Array.isArray(r.choices)){const t=r.choices.map(e=>e.finish_reason).filter(e=>e).map(String);t.length>0&&e.setAttribute("gen_ai.response.finish_reasons",t.join(", "))}if(r.service_tier&&e.setAttribute("gen_ai.response.service_tier",r.service_tier),r.system_fingerprint&&e.setAttribute("gen_ai.response.system_fingerprint",r.system_fingerprint),r.usage_metadata&&"object"==typeof r.usage_metadata){const t=r.usage_metadata;t.input_token_details&&e.setAttribute("gen_ai.usage.input_token_details",JSON.stringify(t.input_token_details)),t.output_token_details&&e.setAttribute("gen_ai.usage.output_token_details",JSON.stringify(t.output_token_details))}}e.setAttribute("gen_ai.completion",JSON.stringify(r))}catch(e){console.debug(`Failed to process outputs for run ${t.id}`,e)}}getUnifiedRunTokens(e){if(!e)return null;let t=this.extractUnifiedRunTokens(e.usage_metadata);if(t)return t;const r=Object.keys(e);for(const n of r){const r=e[n];if(r&&"object"==typeof r){if(t=this.extractUnifiedRunTokens(r.usage_metadata),t)return t;if(1===r.lc&&r.kwargs&&"object"==typeof r.kwargs&&(t=this.extractUnifiedRunTokens(r.kwargs.usage_metadata),t))return t}}const n=e.generations||[];if(!Array.isArray(n))return null;const a=Array.isArray(n[0])?n.flat():n;for(const e of a)if("object"==typeof e&&e.message&&"object"==typeof e.message&&e.message.kwargs&&"object"==typeof e.message.kwargs&&(t=this.extractUnifiedRunTokens(e.message.kwargs.usage_metadata),t))return t;return null}extractUnifiedRunTokens(e){return e&&"object"==typeof e?"number"!=typeof e.input_tokens||"number"!=typeof e.output_tokens?null:[e.input_tokens,e.output_tokens]:null}}var Pv,Cv,Av,Iv,Ov,Tv,$v={exports:{}},zv={};function Rv(){return Av||(Av=1,e=zv,t=function(){if(Cv)return Pv;function e(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return Cv=1,Pv=e,e.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},e.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},e.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1)}var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},r),this._options.unref&&this._timer.unref(),!0},e.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},e.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},e.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},e.prototype.start=e.prototype.try,e.prototype.errors=function(){return this._errors},e.prototype.attempts=function(){return this._attempts},e.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,n=0;n<this._errors.length;n++){var a=this._errors[n],i=a.message,s=(e[i]||0)+1;e[i]=s,s>=r&&(t=a,r=s)}return t},Pv}(),e.operation=function(r){var n=e.timeouts(r);return new t(n,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],a=0;a<t.retries;a++)n.push(this.createTimeout(a,t));return e&&e.forever&&!n.length&&n.push(this.createTimeout(a,t)),n.sort(function(e,t){return e-t}),n},e.createTimeout=function(e,t){var r=t.randomize?Math.random()+1:1,n=Math.round(r*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return n=Math.min(n,t.maxTimeout)},e.wrap=function(t,r,n){if(r instanceof Array&&(n=r,r=null),!n)for(var a in n=[],t)"function"==typeof t[a]&&n.push(a);for(var i=0;i<n.length;i++){var s=n[i],o=t[s];t[s]=function(n){var a=e.operation(r),i=Array.prototype.slice.call(arguments,1),s=i.pop();i.push(function(e){a.retry(e)||(e&&(arguments[0]=a.mainError()),s.apply(this,arguments))}),a.attempt(function(){n.apply(t,i)})}.bind(t,o),t[s].options=r}}),zv;var e,t}function Lv(){return Ov?Iv:(Ov=1,Iv=Rv())}var Mv,Dv=function(){if(Tv)return $v.exports;Tv=1;const e=Lv(),t=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class r extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const n=(n,a)=>new Promise((i,s)=>{a={onFailedAttempt:()=>{},retries:10,...a};const o=e.operation(a);o.attempt(async e=>{try{i(await n(e))}catch(n){if(!(n instanceof Error))return void s(new TypeError(`Non-error was thrown: "${n}". You should only throw errors.`));if(n instanceof r)o.stop(),s(n.originalError);else if(n instanceof TypeError&&(c=n.message,!t.includes(c)))o.stop(),s(n);else{((e,t,r)=>{const n=r.retries-(t-1);e.attemptNumber=t,e.retriesLeft=n})(n,e,a);try{await a.onFailedAttempt(n)}catch(e){return void s(e)}o.retry(n)||s(o.mainError())}}var c})});return $v.exports=n,$v.exports.default=n,$v.exports.AbortError=r,$v.exports}(),jv=ba(Dv),Fv={},Uv={exports:{}};var qv,Bv,Vv,Gv={exports:{}};function Hv(){return Bv||(Bv=1,qv=(e,t)=>(t=t||(()=>{}),e.then(e=>new Promise(e=>{e(t())}).then(()=>e),e=>new Promise(e=>{e(t())}).then(()=>{throw e})))),qv}var Kv,Wv,Zv,Jv={},Yv={};function Qv(){if(Wv)return Jv;Wv=1,Object.defineProperty(Jv,"__esModule",{value:!0});const e=(Kv||(Kv=1,Object.defineProperty(Yv,"__esModule",{value:!0}),Yv.default=function(e,t,r){let n=0,a=e.length;for(;a>0;){const i=a/2|0;let s=n+i;r(e[s],t)<=0?(n=++s,a-=i+1):a=i}return n}),Yv);return Jv.default=class{constructor(){this._queue=[]}enqueue(t,r){const n={priority:(r=Object.assign({priority:0},r)).priority,run:t};if(this.size&&this._queue[this.size-1].priority>=r.priority)return void this._queue.push(n);const a=e.default(this._queue,n,(e,t)=>t.priority-e.priority);this._queue.splice(a,0,n)}dequeue(){const e=this._queue.shift();return null==e?void 0:e.run}filter(e){return this._queue.filter(t=>t.priority===e.priority).map(e=>e.run)}get size(){return this._queue.length}},Jv}var Xv=function(){if(Zv)return Fv;Zv=1,Object.defineProperty(Fv,"__esModule",{value:!0});const e=(Mv||(Mv=1,function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}function a(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function i(e,t,n,i,s){if("function"!=typeof n)throw new TypeError("The listener must be a function");var o=new a(n,i||e,s),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],o]:e._events[c].push(o):(e._events[c]=o,e._eventsCount++),e}function s(e,t){0===--e._eventsCount?e._events=new n:delete e._events[t]}function o(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),o.prototype.eventNames=function(){var e,n,a=[];if(0===this._eventsCount)return a;for(n in e=this._events)t.call(e,n)&&a.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?a.concat(Object.getOwnPropertySymbols(e)):a},o.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var a=0,i=n.length,s=new Array(i);a<i;a++)s[a]=n[a].fn;return s},o.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},o.prototype.emit=function(e,t,n,a,i,s){var o=r?r+e:e;if(!this._events[o])return!1;var c,l,u=this._events[o],d=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),d){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,a),!0;case 5:return u.fn.call(u.context,t,n,a,i),!0;case 6:return u.fn.call(u.context,t,n,a,i,s),!0}for(l=1,c=new Array(d-1);l<d;l++)c[l-1]=arguments[l];u.fn.apply(u.context,c)}else{var p,m=u.length;for(l=0;l<m;l++)switch(u[l].once&&this.removeListener(e,u[l].fn,void 0,!0),d){case 1:u[l].fn.call(u[l].context);break;case 2:u[l].fn.call(u[l].context,t);break;case 3:u[l].fn.call(u[l].context,t,n);break;case 4:u[l].fn.call(u[l].context,t,n,a);break;default:if(!c)for(p=1,c=new Array(d-1);p<d;p++)c[p-1]=arguments[p];u[l].fn.apply(u[l].context,c)}}return!0},o.prototype.on=function(e,t,r){return i(this,e,t,r,!1)},o.prototype.once=function(e,t,r){return i(this,e,t,r,!0)},o.prototype.removeListener=function(e,t,n,a){var i=r?r+e:e;if(!this._events[i])return this;if(!t)return s(this,i),this;var o=this._events[i];if(o.fn)o.fn!==t||a&&!o.once||n&&o.context!==n||s(this,i);else{for(var c=0,l=[],u=o.length;c<u;c++)(o[c].fn!==t||a&&!o[c].once||n&&o[c].context!==n)&&l.push(o[c]);l.length?this._events[i]=1===l.length?l[0]:l:s(this,i)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new n,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,e.exports=o}(Uv)),Uv.exports),t=function(){if(Vv)return Gv.exports;Vv=1;const e=Hv();class t extends Error{constructor(e){super(e),this.name="TimeoutError"}}const r=(r,n,a)=>new Promise((i,s)=>{if("number"!=typeof n||n<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(n===1/0)return void i(r);const o=setTimeout(()=>{if("function"==typeof a){try{i(a())}catch(e){s(e)}return}const e=a instanceof Error?a:new t("string"==typeof a?a:`Promise timed out after ${n} milliseconds`);"function"==typeof r.cancel&&r.cancel(),s(e)},n);e(r.then(i,s),()=>{clearTimeout(o)})});return Gv.exports=r,Gv.exports.default=r,Gv.exports.TimeoutError=t,Gv.exports}(),r=Qv(),n=()=>{},a=new t.TimeoutError;return Fv.default=class extends e{constructor(e){var t,a,i,s;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=n,this._resolveIdle=n,!("number"==typeof(e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:r.default},e)).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${null!==(a=null===(t=e.intervalCap)||void 0===t?void 0:t.toString())&&void 0!==a?a:""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${null!==(s=null===(i=e.interval)||void 0===i?void 0:i.toString())&&void 0!==s?s:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||0===e.interval,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=!0===e.throwOnTimeout,this._isPaused=!1===e.autoStart}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=n,0===this._pendingCount&&(this._resolveIdle(),this._resolveIdle=n,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){const e=Date.now();if(void 0===this._intervalId){const t=this._intervalEnd-e;if(!(t<0))return void 0===this._timeoutId&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},t)),!0;this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}return!1}_tryToStartAnother(){if(0===this._queue.size)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const t=this._queue.dequeue();return!!t&&(this.emit("active"),t(),e&&this._initializeIntervalIfNeeded(),!0)}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||void 0!==this._intervalId||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){0===this._intervalCount&&0===this._pendingCount&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,r={}){return new Promise((n,i)=>{this._queue.enqueue(async()=>{this._pendingCount++,this._intervalCount++;try{const s=void 0===this._timeout&&void 0===r.timeout?e():t.default(Promise.resolve(e()),void 0===r.timeout?this._timeout:r.timeout,()=>{(void 0===r.throwOnTimeout?this._throwOnTimeout:r.throwOnTimeout)&&i(a)});n(await s)}catch(e){i(e)}this._next()},r),this._tryToStartAnother(),this.emit("add")})}async addAll(e,t){return Promise.all(e.map(async e=>this.add(e,t)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(0!==this._queue.size)return new Promise(e=>{const t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}})}async onIdle(){if(0!==this._pendingCount||0!==this._queue.size)return new Promise(e=>{const t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}},Fv}(),eb=ba(Xv);const tb=[429,500,502,503,504];let rb=class{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.queue="default"in eb?new eb.default({concurrency:this.maxConcurrency}):new eb({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){const r=this.onFailedResponseHook;return this.queue.add(()=>jv(()=>e(...t).catch(e=>{throw e instanceof Error?e:new Error(e)}),{async onFailedAttempt(e){if(e.message.startsWith("Cancel")||e.message.startsWith("TimeoutError")||"TimeoutError"===e.name||e.message.startsWith("AbortError"))throw e;if("ECONNABORTED"===e?.code)throw e;const t=e?.response;if(r){if(await r(t))return}const n=t?.status??e?.status;if(n&&!tb.includes(+n))throw e},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){return e.signal?Promise.race([this.call(t,...r),new Promise((t,r)=>{e.signal?.addEventListener("abort",()=>{r(new Error("AbortError"))})})]):this.call(t,...r)}};function nb(e){return"function"==typeof e?._getType}function ab(e){const t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}const ib=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function sb(e,t){if(!ib.test(e)){throw new Error(void 0!==t?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`)}return e}const ob={};function cb(e){ob[e]||(console.warn(e),ob[e]=!0)}function lb(e){if(!e||e.split("/").length>2||e.startsWith("/")||e.endsWith("/")||e.split(":").length>2)throw new Error(`Invalid identifier format: ${e}`);const[t,r]=e.split(":"),n=r||"latest";if(t.includes("/")){const[r,a]=t.split("/",2);if(!r||!a)throw new Error(`Invalid identifier format: ${e}`);return[r,a,n]}if(!t)throw new Error(`Invalid identifier format: ${e}`);return["-",t,n]}class ub extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}async function db(e,t,r){let n;if(e.ok)return void(r&&(n=await e.text()));if(403===e.status)try{const t=await e.json(),r=t?.error;"org_scoped_key_requires_workspace"===r&&(n="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch(t){const r=new Error(`${e.status} ${e.statusText}`);throw r.status=e?.status,r}if(void 0===n)try{n=await e.text()}catch(e){n=""}const a=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Message: ${n}`;if(409===e.status)throw new ub(a);const i=new Error(a);throw i.status=e.status,i}const pb="ERR_CONFLICTING_ENDPOINTS";class mb extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:pb}),this.name="ConflictingEndpointsError"}}var hb="[...]",fb={result:"[Circular]"},gb=[],yb=[];const vb=new TextEncoder;function bb(e){return vb.encode(e)}function _b(e){if(e&&"object"==typeof e&&null!==e){if(e instanceof Map)return Object.fromEntries(e);if(e instanceof Set)return Array.from(e);if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return e.toString();if(e instanceof Error)return{name:e.name,message:e.message}}else if("bigint"==typeof e)return e.toString();return e}function wb(e,t,r,n,a){try{return bb(JSON.stringify(e,function(e,t){return _b(t)},n))}catch(i){if(!i.message?.includes("Converting circular structure to JSON"))return console.warn("[WARNING]: LangSmith received unserializable value."+(t?`\nContext: ${t}`:"")),bb("[Unserializable]");let s;"true"!==fv("SUPPRESS_CIRCULAR_JSON_WARNINGS")&&console.warn("[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. "+(t?`\nContext: ${t}`:"")),void 0===a&&(a={depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}),Nb(e,"",0,[],void 0,0,a);try{s=0===yb.length?JSON.stringify(e,r,n):JSON.stringify(e,function(e){return e=void 0!==e?e:function(e,t){return t},function(t,r){if(yb.length>0)for(var n=0;n<yb.length;n++){var a=yb[n];if(a[1]===t&&a[0]===r){r=a[2],yb.splice(n,1);break}}return e.call(this,t,r)}}(r),n)}catch(e){return bb("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==gb.length;){const e=gb.pop();4===e.length?Object.defineProperty(e[0],e[1],e[3]):e[0][e[1]]=e[2]}}return bb(s)}}function Sb(e,t,r,n){var a=Object.getOwnPropertyDescriptor(n,r);void 0!==a.get?a.configurable?(Object.defineProperty(n,r,{value:e}),gb.push([n,r,t,a])):yb.push([t,r,e]):(n[r]=e,gb.push([n,r,t]))}function Nb(e,t,r,n,a,i,s){var o;if(i+=1,"object"==typeof e&&null!==e){for(o=0;o<n.length;o++)if(n[o]===e)return void Sb(fb,e,t,a);if(void 0!==s.depthLimit&&i>s.depthLimit)return void Sb(hb,e,t,a);if(void 0!==s.edgesLimit&&r+1>s.edgesLimit)return void Sb(hb,e,t,a);if(n.push(e),Array.isArray(e))for(o=0;o<e.length;o++)Nb(e[o],o,o,n,e,i,s);else{e=_b(e);var c=Object.keys(e);for(o=0;o<c.length;o++){var l=c[o];Nb(e[l],l,o,n,e,i,s)}}n.pop()}}function kb(e,t){const r=pv(),n=t??mv(),a=e.extra??{},i=a.metadata;return e.extra={...a,runtime:{...r,...a?.runtime},metadata:{...n,...n.revision_id||"revision_id"in e&&e.revision_id?{revision_id:("revision_id"in e?e.revision_id:void 0)??n.revision_id}:{},...i}},e}function xb(e){if(void 0!==e)return e.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const Eb=async e=>{if(429===e?.status){const t=1e3*parseInt(e.headers.get("retry-after")??"10",10);if(t>0)return await new Promise(e=>setTimeout(e,t)),!0}return!1};function Pb(e){return"number"==typeof e?Number(e.toFixed(4)):e}class Cb{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(e){let t;const r=new Promise(e=>{t=e}),n=wb(e.item,`Serializing run with id: ${e.item.id}`).length;return this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:t,itemPromise:r,size:n}),this.sizeBytes+=n,r}pop({upToSizeBytes:e,upToSize:t}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");const r=[];let n=0;for(;n+(this.peek()?.size??0)<e&&this.items.length>0&&r.length<t;){const e=this.items.shift();e&&(r.push(e),n+=e.size,this.sizeBytes-=e.size)}if(0===r.length&&this.items.length>0){const e=this.items.shift();r.push(e),n+=e.size,this.sizeBytes-=e.size}return[r.map(e=>({action:e.action,item:e.payload,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl})),()=>r.forEach(e=>e.itemPromiseResolve())]}}const Ab="https://api.smith.langchain.com";class Ib{get _fetch(){return this.fetchImplementation||av(this.debug)}constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:new Cb}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:"false"===hv("LANGSMITH_TRACING_BACKGROUND")}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:"true"===hv("LANGSMITH_DEBUG")});const t=Ib.getDefaultClientConfig();if(this.tracingSampleRate=(e=>{const t=e?.toString()??fv("TRACING_SAMPLING_RATE");if(void 0===t)return;const r=parseFloat(t);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r})(e.tracingSamplingRate),this.apiUrl=xb(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=xb(e.apiKey??t.apiKey),this.webUrl=xb(e.webUrl??t.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=xb(e.workspaceId??fv("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new rb({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.batchIngestCaller=new rb({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:Eb,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??t.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??t.hideOutputs,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,gv()&&(this.langSmithToOTELTranslator=new Ev),this.cachedLSEnvVarsForMetadata=mv()}static getDefaultClientConfig(){const e=fv("API_KEY");return{apiUrl:fv("ENDPOINT")??Ab,apiKey:e,webUrl:void 0,hideInputs:"true"===fv("HIDE_INPUTS"),hideOutputs:"true"===fv("HIDE_OUTPUTS")}}getHostUrl(){return this.webUrl?this.webUrl:(e=>{const t=e.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return"localhost"===t||"127.0.0.1"===t||"::1"===t})(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){const e={"User-Agent":`langsmith-js/${sv}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}_getPlatformEndpointPath(e){return"/v1"!==this.apiUrl.slice(-3)&&"/v1/"!==this.apiUrl.slice(-4)?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return!1===this.hideInputs?e:!0===this.hideInputs?{}:"function"==typeof this.hideInputs?this.hideInputs(e):e}async processOutputs(e){return!1===this.hideOutputs?e:!0===this.hideOutputs?{}:"function"==typeof this.hideOutputs?this.hideOutputs(e):e}async prepareRunCreateOrUpdateInputs(e){const t={...e};return void 0!==t.inputs&&(t.inputs=await this.processInputs(t.inputs)),void 0!==t.outputs&&(t.outputs=await this.processOutputs(t.outputs)),t}async _getResponse(e,t){const r=t?.toString()??"",n=`${this.apiUrl}${e}?${r}`;return await this.caller.call(async()=>{const t=await this._fetch(n,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(t,`fetch ${e}`),t})}async _get(e,t){return(await this._getResponse(e,t)).json()}async*_getPaginated(e,t=new URLSearchParams,r){let n=Number(t.get("offset"))||0;const a=Number(t.get("limit"))||100;for(;;){t.set("offset",String(n)),t.set("limit",String(a));const i=`${this.apiUrl}${e}?${t}`,s=await this.caller.call(async()=>{const t=await this._fetch(i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(t,`fetch ${e}`),t}),o=r?r(await s.json()):await s.json();if(0===o.length)break;if(yield o,o.length<a)break;n+=o.length}}async*_getCursorPaginatedList(e,t=null,r="POST",n="runs"){const a=t?{...t}:{};for(;;){const t=JSON.stringify(a),i=await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}${e}`,{method:r,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:t});return await db(n,`fetch ${e}`),n}),s=await i.json();if(!s)break;if(!s[n])break;yield s[n];const o=s.cursors;if(!o)break;if(!o.next)break;a.cursor=o.next}}_shouldSample(){return void 0===this.tracingSampleRate||Math.random()<this.tracingSampleRate}_filterForSampling(e,t=!1){if(void 0===this.tracingSampleRate)return e;if(t){const t=[];for(const r of e)this.filteredPostUuids.has(r.trace_id)?r.id===r.trace_id&&this.filteredPostUuids.delete(r.trace_id):t.push(r);return t}{const t=[];for(const r of e){const e=r.trace_id??r.id;this.filteredPostUuids.has(e)||(r.id===e?this._shouldSample()?t.push(r):this.filteredPostUuids.add(e):t.push(r))}return t}}async _getBatchSizeLimitBytes(){const e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e.batch_ingest_config?.size_limit_bytes??25165824}async _getBatchSizeLimit(){const e=await this._ensureServerInfo();return this.batchSizeLimit??e.batch_ingest_config?.size_limit??100}async _getDatasetExamplesMultiPartSupport(){const e=await this._ensureServerInfo();return e.instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t}){const r=[];for(;this.autoBatchQueue.items.length>0;){const[n,a]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:t});if(!n.length){a();break}const i=n.reduce((e,t)=>{const r=t.apiUrl??this.apiUrl,n=t.apiKey??this.apiKey,a=t.apiKey===this.apiKey&&t.apiUrl===this.apiUrl?"default":`${r}|${n}`;return e[a]||(e[a]=[]),e[a].push(t),e},{}),s=[];for(const[e,t]of Object.entries(i)){const r=this._processBatch(t,{apiUrl:"default"===e?void 0:e.split("|")[0],apiKey:"default"===e?void 0:e.split("|")[1]});s.push(r)}const o=Promise.all(s).finally(a);r.push(o)}return Promise.all(r)}async _processBatch(e,t){if(e.length)try{if(void 0!==this.langSmithToOTELTranslator)this._sendBatchToOTELTranslator(e);else{const r={runCreates:e.filter(e=>"create"===e.action).map(e=>e.item),runUpdates:e.filter(e=>"update"===e.action).map(e=>e.item)},n=await this._ensureServerInfo();if(n?.batch_ingest_config?.use_multipart_endpoint){const e=n?.instance_flags?.gzip_body_enabled;await this.multipartIngestRuns(r,{...t,useGzip:e})}else await this.batchIngestRuns(r,t)}}catch(e){console.error("Error exporting batch:",e)}}_sendBatchToOTELTranslator(e){if(void 0!==this.langSmithToOTELTranslator){const t=new Map,r=[];for(const n of e)n.item.id&&n.otelContext&&(t.set(n.item.id,n.otelContext),"create"===n.action?r.push({operation:"post",id:n.item.id,trace_id:n.item.trace_id??n.item.id,run:n.item}):r.push({operation:"patch",id:n.item.id,trace_id:n.item.trace_id??n.item.id,run:n.item}));this.langSmithToOTELTranslator.exportBatch(r,t)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=kb(e.item,this.cachedLSEnvVarsForMetadata);const t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;const r=await this._getBatchSizeLimitBytes(),n=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>r||this.autoBatchQueue.items.length>n)&&this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:n}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:n})},this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){const e=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4),...this.fetchOptions});return await db(e,"get server info"),e}),t=await e.json();return this.debug&&console.log("\n=== LangSmith Server Configuration ===\n"+JSON.stringify(t,null,2)+"\n"),t}async _ensureServerInfo(){return void 0===this._getServerInfoPromise&&(this._getServerInfoPromise=(async()=>{if(void 0===this._serverInfo)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(void 0===this._serverInfo&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){const e=await this._getBatchSizeLimitBytes(),t=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t})}_cloneCurrentOTELContext(){const e=kv(),t=Nv.getContextInstance();if(void 0!==this.langSmithToOTELTranslator){const r=e.getActiveSpan();if(r)return e.setSpan(t.active(),r)}}async createRun(e,t){if(!this._filterForSampling([e]).length)return;const r={...this.headers,"Content-Type":"application/json"},n=e.project_name;delete e.project_name;const a=await this.prepareRunCreateOrUpdateInputs({session_name:n,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&void 0!==a.trace_id&&void 0!==a.dotted_order){const e=this._cloneCurrentOTELContext();return void this.processRunOperation({action:"create",item:a,otelContext:e,apiKey:t?.apiKey,apiUrl:t?.apiUrl}).catch(console.error)}const i=kb(a,this.cachedLSEnvVarsForMetadata);void 0!==t?.apiKey&&(r["x-api-key"]=t.apiKey),void 0!==t?.workspaceId&&(r["x-tenant-id"]=t.workspaceId);const s=wb(i,`Creating run with id: ${i.id}`);await this.caller.call(async()=>{const e=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await db(e,"create run",!0),e})}async batchIngestRuns({runCreates:e,runUpdates:t},r){if(void 0===e&&void 0===t)return;let n=await Promise.all(e?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[]),a=await Promise.all(t?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[]);if(n.length>0&&a.length>0){const e=n.reduce((e,t)=>t.id?(e[t.id]=t,e):e,{}),t=[];for(const r of a)void 0!==r.id&&e[r.id]?e[r.id]={...e[r.id],...r}:t.push(r);n=Object.values(e),a=t}const i={post:n,patch:a};if(!i.post.length&&!i.patch.length)return;const s={post:[],patch:[]};for(const e of["post","patch"]){const t=e,r=i[t].reverse();let n=r.pop();for(;void 0!==n;)s[t].push(n),n=r.pop()}if(s.post.length>0||s.patch.length>0){const e=s.post.map(e=>e.id).concat(s.patch.map(e=>e.id)).join(",");await this._postBatchIngestRuns(wb(s,`Ingesting runs with ids: ${e}`),r)}}async _postBatchIngestRuns(e,t){const r={...this.headers,"Content-Type":"application/json",Accept:"application/json"};void 0!==t?.apiKey&&(r["x-api-key"]=t.apiKey),await this.batchIngestCaller.call(async()=>{const n=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await db(n,"batch create run",!0),n})}async multipartIngestRuns({runCreates:e,runUpdates:t},r){if(void 0===e&&void 0===t)return;const n={};let a=[];for(const t of e??[]){const e=await this.prepareRunCreateOrUpdateInputs(t);void 0!==e.id&&void 0!==e.attachments&&(n[e.id]=e.attachments),delete e.attachments,a.push(e)}let i=[];for(const e of t??[])i.push(await this.prepareRunCreateOrUpdateInputs(e));if(void 0!==a.find(e=>void 0===e.trace_id||void 0===e.dotted_order))throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(void 0!==i.find(e=>void 0===e.trace_id||void 0===e.dotted_order))throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(a.length>0&&i.length>0){const e=a.reduce((e,t)=>t.id?(e[t.id]=t,e):e,{}),t=[];for(const r of i)void 0!==r.id&&e[r.id]?e[r.id]={...e[r.id],...r}:t.push(r);a=Object.values(e),i=t}if(0===a.length&&0===i.length)return;const s=[],o=[];for(const[e,t]of[["post",a],["patch",i]])for(const r of t){const{inputs:t,outputs:a,events:i,extra:c,error:l,serialized:u,attachments:d,...p}=r,m={inputs:t,outputs:a,events:i,extra:c,error:l,serialized:u},h=wb(p,`Serializing for multipart ingestion of run with id: ${p.id}`);o.push({name:`${e}.${p.id}`,payload:new Blob([h],{type:`application/json; length=${h.length}`})});for(const[t,r]of Object.entries(m)){if(void 0===r)continue;const n=wb(r,`Serializing ${t} for multipart ingestion of run with id: ${p.id}`);o.push({name:`${e}.${p.id}.${t}`,payload:new Blob([n],{type:`application/json; length=${n.length}`})})}if(void 0!==p.id){const e=n[p.id];if(e){delete n[p.id];for(const[t,r]of Object.entries(e)){let e,n;Array.isArray(r)?[e,n]=r:(e=r.mimeType,n=r.data),t.includes(".")?console.warn(`Skipping attachment '${t}' for run ${p.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`):o.push({name:`attachment.${p.id}.${t}`,payload:new Blob([n],{type:`${e}; length=${n.byteLength}`})})}}}s.push(`trace=${p.trace_id},id=${p.id}`)}await this._sendMultipartRequest(o,s.join("; "),r)}async _createNodeFetchBody(e,t){const r=[];for(const n of e)r.push(new Blob([`--${t}\r\n`])),r.push(new Blob([`Content-Disposition: form-data; name="${n.name}"\r\n`,`Content-Type: ${n.payload.type}\r\n\r\n`])),r.push(n.payload),r.push(new Blob(["\r\n"]));r.push(new Blob([`--${t}--\r\n`]));const n=new Blob(r);return await n.arrayBuffer()}async _createMultipartStream(e,t){const r=new TextEncoder;return new ReadableStream({async start(n){const a=async e=>{"string"==typeof e?n.enqueue(r.encode(e)):n.enqueue(e)};for(const r of e){await a(`--${t}\r\n`),await a(`Content-Disposition: form-data; name="${r.name}"\r\n`),await a(`Content-Type: ${r.payload.type}\r\n\r\n`);const e=r.payload.stream().getReader();try{let t;for(;!(t=await e.read()).done;)n.enqueue(t.value)}finally{e.releaseLock()}await a("\r\n")}await a(`--${t}--\r\n`),n.close()}})}async _sendMultipartRequest(e,t,r){const n="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),a=(()=>{const e=globalThis[nv];return!!e&&"function"==typeof e&&"Headers"in e&&"Request"in e&&"Response"in e})(),i=()=>this._createNodeFetchBody(e,n),s=()=>this._createMultipartStream(e,n),o=async e=>this.batchIngestCaller.call(async()=>{const t=await e(),a={...this.headers,"Content-Type":`multipart/form-data; boundary=${n}`};void 0!==r?.apiKey&&(a["x-api-key"]=r.apiKey);let i=t;r?.useGzip&&"object"==typeof t&&"pipeThrough"in t&&(i=t.pipeThrough(new CompressionStream("gzip")),a["Content-Encoding"]="gzip");const s=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:a,body:i,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(s,"Failed to send multipart request",!0),s});try{let e,n=!1;a||this.multipartStreamingDisabled||"bun"===lv()?e=await o(i):(n=!0,e=await o(s)),this.multipartStreamingDisabled&&!n||422!==e.status||(r?.apiUrl??this.apiUrl)===Ab||(console.warn(`Streaming multipart upload to ${r?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${t}".`),this.multipartStreamingDisabled=!0,e=await o(i))}catch(e){console.warn(`${e.message.trim()}\n\nContext: ${t}`)}}async updateRun(e,t,r){sb(e),t.inputs&&(t.inputs=await this.processInputs(t.inputs)),t.outputs&&(t.outputs=await this.processOutputs(t.outputs));const n={...t,id:e};if(!this._filterForSampling([n],!0).length)return;if(this.autoBatchTracing&&void 0!==n.trace_id&&void 0!==n.dotted_order){const e=this._cloneCurrentOTELContext();return void 0!==t.end_time&&void 0===n.parent_run_id&&this.blockOnRootRunFinalization&&!this.manualFlushMode?void await this.processRunOperation({action:"update",item:n,otelContext:e,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error):void this.processRunOperation({action:"update",item:n,otelContext:e,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error)}const a={...this.headers,"Content-Type":"application/json"};void 0!==r?.apiKey&&(a["x-api-key"]=r.apiKey),void 0!==r?.workspaceId&&(a["x-tenant-id"]=r.workspaceId);const i=wb(t,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{const t=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:a,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await db(t,"update run",!0),t})}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){sb(e);let r=await this._get(`/runs/${e}`);return t&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:t,projectOpts:r}){if(void 0!==t){let e;if(t.session_id)e=t.session_id;else if(r?.projectName)e=(await this.readProject({projectName:r?.projectName})).id;else if(r?.projectId)e=r?.projectId;else{e=(await this.readProject({projectName:fv("PROJECT")||"default"})).id}const n=await this._getTenantId();return`${this.getHostUrl()}/o/${n}/projects/p/${e}/r/${t.id}?poll=true`}if(void 0!==e){const t=await this.readRun(e);if(!t.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${t.app_path}`}throw new Error("Must provide either runId or run")}async _loadChildRuns(e){const t=await async function(e){const t=[];for await(const r of e)t.push(r);return t}(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),r={},n={};t.sort((e,t)=>(e?.dotted_order??"").localeCompare(t?.dotted_order??""));for(const a of t){if(null===a.parent_run_id||void 0===a.parent_run_id)throw new Error(`Child run ${a.id} has no parent`);a.dotted_order?.startsWith(e.dotted_order??"")&&a.id!==e.id&&(a.parent_run_id in r||(r[a.parent_run_id]=[]),r[a.parent_run_id].push(a),n[a.id]=a)}e.child_runs=r[e.id]||[];for(const t in r)t!==e.id&&(n[t].child_runs=r[t]);return e}async*listRuns(e){const{projectId:t,projectName:r,parentRunId:n,traceId:a,referenceExampleId:i,startTime:s,executionOrder:o,isRoot:c,runType:l,error:u,id:d,query:p,filter:m,traceFilter:h,treeFilter:f,limit:g,select:y,order:v}=e;let b=[];if(t&&(b=Array.isArray(t)?t:[t]),r){const e=Array.isArray(r)?r:[r],t=await Promise.all(e.map(e=>this.readProject({projectName:e}).then(e=>e.id)));b.push(...t)}const _={session:b.length?b:null,run_type:l,reference_example:i,query:p,filter:m,trace_filter:h,tree_filter:f,execution_order:o,parent_run:n,start_time:s?s.toISOString():null,error:u,id:d,limit:g,trace:a,select:y||["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],is_root:c,order:v};_.select.includes("child_run_ids")&&cb("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let w=0;for await(const e of this._getCursorPaginatedList("/runs/query",_))if(g){if(w>=g)break;if(e.length+w>g){const t=e.slice(0,g-w);yield*t;break}w+=e.length,yield*e}else yield*e}async*listGroupRuns(e){const{projectId:t,projectName:r,groupBy:n,filter:a,startTime:i,endTime:s,limit:o,offset:c}=e,l={session_id:t||(await this.readProject({projectName:r})).id,group_by:n,filter:a,start_time:i?i.toISOString():null,end_time:s?s.toISOString():null,limit:Number(o)||100};let u=Number(c)||0;const d="/runs/group",p=`${this.apiUrl}${d}`;for(;;){const e={...l,offset:u},t=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t)),r=JSON.stringify(t),n=await this.caller.call(async()=>{const e=await this._fetch(p,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await db(e,`Failed to fetch ${d}`),e}),a=await n.json(),{groups:i,total:s}=a;if(0===i.length)break;for(const e of i)yield e;if(u+=i.length,u>=s)break}}async getRunStats({id:e,trace:t,parentRun:r,runType:n,projectNames:a,projectIds:i,referenceExampleIds:s,startTime:o,endTime:c,error:l,query:u,filter:d,traceFilter:p,treeFilter:m,isRoot:h,dataSourceType:f}){let g=i||[];a&&(g=[...i||[],...await Promise.all(a.map(e=>this.readProject({projectName:e}).then(e=>e.id)))]);const y={id:e,trace:t,parent_run:r,run_type:n,session:g,reference_example:s,start_time:o,end_time:c,error:l,query:u,filter:d,trace_filter:p,tree_filter:m,is_root:h,data_source_type:f},v=Object.fromEntries(Object.entries(y).filter(([e,t])=>void 0!==t)),b=JSON.stringify(v),_=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:b});return await db(e,"get run stats"),e});return await _.json()}async shareRun(e,{shareId:t}={}){const r={run_id:e,share_token:t||By()};sb(e);const n=JSON.stringify(r),a=await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await db(t,"share run"),t}),i=await a.json();if(null===i||!("share_token"in i))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(e){sb(e),await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(t,"unshare run",!0),t})}async readRunSharedLink(e){sb(e);const t=await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(t,"read run shared link"),t}),r=await t.json();if(null!==r&&"share_token"in r)return`${this.getHostUrl()}/public/${r.share_token}/r`}async listSharedRuns(e,{runIds:t}={}){const r=new URLSearchParams({share_token:e});if(void 0!==t)for(const e of t)r.append("id",e);sb(e);const n=await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/public/${e}/runs${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(t,"list shared runs"),t});return await n.json()}async readDatasetSharedSchema(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");if(!e){const r=await this.readDataset({datasetName:t});e=r.id}sb(e);const r=await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(t,"read dataset shared schema"),t}),n=await r.json();return n.url=`${this.getHostUrl()}/public/${n.share_token}/d`,n}async shareDataset(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");if(!e){const r=await this.readDataset({datasetName:t});e=r.id}const r={dataset_id:e};sb(e);const n=JSON.stringify(r),a=await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await db(t,"share dataset"),t}),i=await a.json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){sb(e),await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(t,"unshare dataset",!0),t})}async readSharedDataset(e){sb(e);const t=await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(t,"read shared dataset"),t});return await t.json()}async listSharedExamples(e,t){const r={};t?.exampleIds&&(r.id=t.exampleIds);const n=new URLSearchParams;Object.entries(r).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>n.append(e,t)):n.append(e,t)});const a=await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/public/${e}/examples?${n.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(t,"list shared examples"),t}),i=await a.json();if(!a.ok){if("detail"in i)throw new Error(`Failed to list shared examples.\nStatus: ${a.status}\nMessage: ${Array.isArray(i.detail)?i.detail.join("\n"):"Unspecified error"}`);throw new Error(`Failed to list shared examples: ${a.status} ${a.statusText}`)}return i.map(e=>({...e,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:t=null,metadata:r=null,upsert:n=!1,projectExtra:a=null,referenceDatasetId:i=null}){const s=n?"?upsert=true":"",o=`${this.apiUrl}/sessions${s}`,c=a||{};r&&(c.metadata=r);const l={name:e,extra:c,description:t};null!==i&&(l.reference_dataset_id=i);const u=JSON.stringify(l),d=await this.caller.call(async()=>{const e=await this._fetch(o,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await db(e,"create project"),e});return await d.json()}async updateProject(e,{name:t=null,description:r=null,metadata:n=null,projectExtra:a=null,endTime:i=null}){const s=`${this.apiUrl}/sessions/${e}`;let o=a;n&&(o={...o||{},metadata:n});const c=JSON.stringify({name:t,extra:o,description:r,end_time:i?new Date(i).toISOString():null}),l=await this.caller.call(async()=>{const e=await this._fetch(s,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await db(e,"update project"),e});return await l.json()}async hasProject({projectId:e,projectName:t}){let r="/sessions";const n=new URLSearchParams;if(void 0!==e&&void 0!==t)throw new Error("Must provide either projectName or projectId, not both");if(void 0!==e)sb(e),r+=`/${e}`;else{if(void 0===t)throw new Error("Must provide projectName or projectId");n.append("name",t)}const a=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}${r}?${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(e,"has project"),e});try{const e=await a.json();return!!a.ok&&(!Array.isArray(e)||e.length>0)}catch(e){return!1}}async readProject({projectId:e,projectName:t,includeStats:r}){let n="/sessions";const a=new URLSearchParams;if(void 0!==e&&void 0!==t)throw new Error("Must provide either projectName or projectId, not both");if(void 0!==e)sb(e),n+=`/${e}`;else{if(void 0===t)throw new Error("Must provide projectName or projectId");a.append("name",t)}void 0!==r&&a.append("include_stats",r.toString());const i=await this._get(n,a);let s;if(Array.isArray(i)){if(0===i.length)throw new Error(`Project[id=${e}, name=${t}] not found`);s=i[0]}else s=i;return s}async getProjectUrl({projectId:e,projectName:t}){if(void 0===e&&void 0===t)throw new Error("Must provide either projectName or projectId");const r=await this.readProject({projectId:e,projectName:t}),n=await this._getTenantId();return`${this.getHostUrl()}/o/${n}/projects/p/${r.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(void 0===e&&void 0===t)throw new Error("Must provide either datasetName or datasetId");const r=await this.readDataset({datasetId:e,datasetName:t}),n=await this._getTenantId();return`${this.getHostUrl()}/o/${n}/datasets/${r.id}`}async _getTenantId(){if(null!==this._tenantId)return this._tenantId;const e=new URLSearchParams({limit:"1"});for await(const t of this._getPaginated("/sessions",e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:t,nameContains:r,referenceDatasetId:n,referenceDatasetName:a,includeStats:i,datasetVersion:s,referenceFree:o,metadata:c}={}){const l=new URLSearchParams;if(void 0!==e)for(const t of e)l.append("id",t);if(void 0!==t&&l.append("name",t),void 0!==r&&l.append("name_contains",r),void 0!==n)l.append("reference_dataset",n);else if(void 0!==a){const e=await this.readDataset({datasetName:a});l.append("reference_dataset",e.id)}void 0!==i&&l.append("include_stats",i.toString()),void 0!==s&&l.append("dataset_version",s),void 0!==o&&l.append("reference_free",o.toString()),void 0!==c&&l.append("metadata",JSON.stringify(c));for await(const e of this._getPaginated("/sessions",l))yield*e}async deleteProject({projectId:e,projectName:t}){let r;if(void 0===e&&void 0===t)throw new Error("Must provide projectName or projectId");if(void 0!==e&&void 0!==t)throw new Error("Must provide either projectName or projectId, not both");r=void 0===e?(await this.readProject({projectName:t})).id:e,sb(r),await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/sessions/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(e,`delete session ${r} (${t})`,!0),e})}async uploadCsv({csvFile:e,fileName:t,inputKeys:r,outputKeys:n,description:a,dataType:i,name:s}){const o=`${this.apiUrl}/datasets/upload`,c=new FormData;c.append("file",e,t),r.forEach(e=>{c.append("input_keys",e)}),n.forEach(e=>{c.append("output_keys",e)}),a&&c.append("description",a),i&&c.append("data_type",i),s&&c.append("name",s);const l=await this.caller.call(async()=>{const e=await this._fetch(o,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await db(e,"upload CSV"),e});return await l.json()}async createDataset(e,{description:t,dataType:r,inputsSchema:n,outputsSchema:a,metadata:i}={}){const s={name:e,description:t,extra:i?{metadata:i}:void 0};r&&(s.data_type=r),n&&(s.inputs_schema_definition=n),a&&(s.outputs_schema_definition=a);const o=JSON.stringify(s),c=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await db(e,"create dataset"),e});return await c.json()}async readDataset({datasetId:e,datasetName:t}){let r="/datasets";const n=new URLSearchParams({limit:"1"});if(e&&t)throw new Error("Must provide either datasetName or datasetId, not both");if(e)sb(e),r+=`/${e}`;else{if(!t)throw new Error("Must provide datasetName or datasetId");n.append("name",t)}const a=await this._get(r,n);let i;if(Array.isArray(a)){if(0===a.length)throw new Error(`Dataset[id=${e}, name=${t}] not found`);i=a[0]}else i=a;return i}async hasDataset({datasetId:e,datasetName:t}){try{return await this.readDataset({datasetId:e,datasetName:t}),!0}catch(e){if(e instanceof Error&&e.message.toLocaleLowerCase().includes("not found"))return!1;throw e}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:r,toVersion:n}){let a=e;if(void 0===a&&void 0===t)throw new Error("Must provide either datasetName or datasetId");if(void 0!==a&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===a){a=(await this.readDataset({datasetName:t})).id}const i=new URLSearchParams({from_version:"string"==typeof r?r:r.toISOString(),to_version:"string"==typeof n?n:n.toISOString()});return await this._get(`/datasets/${a}/versions/diff`,i)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){if(void 0!==e);else{if(void 0===t)throw new Error("Must provide either datasetName or datasetId");e=(await this.readDataset({datasetName:t})).id}const r=await this._getResponse(`/datasets/${e}/openai_ft`);return(await r.text()).trim().split("\n").map(e=>JSON.parse(e))}async*listDatasets({limit:e=100,offset:t=0,datasetIds:r,datasetName:n,datasetNameContains:a,metadata:i}={}){const s=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(void 0!==r)for(const e of r)s.append("id",e);void 0!==n&&s.append("name",n),void 0!==a&&s.append("name_contains",a),void 0!==i&&s.append("metadata",JSON.stringify(i));for await(const e of this._getPaginated("/datasets",s))yield*e}async updateDataset(e){const{datasetId:t,datasetName:r,...n}=e;if(!t&&!r)throw new Error("Must provide either datasetName or datasetId");const a=t??(await this.readDataset({datasetName:r})).id;sb(a);const i=JSON.stringify(n),s=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/datasets/${a}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await db(e,"update dataset"),e});return await s.json()}async updateDatasetTag(e){const{datasetId:t,datasetName:r,asOf:n,tag:a}=e;if(!t&&!r)throw new Error("Must provide either datasetName or datasetId");const i=t??(await this.readDataset({datasetName:r})).id;sb(i);const s=JSON.stringify({as_of:"string"==typeof n?n:n.toISOString(),tag:a});await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/datasets/${i}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await db(e,"update dataset tags",!0),e})}async deleteDataset({datasetId:e,datasetName:t}){let r="/datasets",n=e;if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0!==t){n=(await this.readDataset({datasetName:t})).id}if(void 0===n)throw new Error("Must provide datasetName or datasetId");sb(n),r+=`/${n}`,await this.caller.call(async()=>{const e=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(e,`delete ${r}`,!0),e})}async indexDataset({datasetId:e,datasetName:t,tag:r}){let n=e;if(!n&&!t)throw new Error("Must provide either datasetName or datasetId");if(n&&t)throw new Error("Must provide either datasetName or datasetId, not both");if(!n){const e=await this.readDataset({datasetName:t});n=e.id}sb(n);const a={tag:r},i=JSON.stringify(a),s=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/datasets/${n}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await db(e,"index dataset"),e});await s.json()}async similarExamples(e,t,r,{filter:n}={}){const a={limit:r,inputs:e};void 0!==n&&(a.filter=n),sb(t);const i=JSON.stringify(a),s=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/datasets/${t}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:i});return await db(e,"fetch similar examples"),e});return(await s.json()).examples}async createExample(e,t,r){if(Ob(e)&&(void 0!==t||void 0!==r))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let n=t?r?.datasetId:e.dataset_id;const a=t?r?.datasetName:e.dataset_name;if(void 0===n&&void 0===a)throw new Error("Must provide either datasetName or datasetId");if(void 0!==n&&void 0!==a)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===n){n=(await this.readDataset({datasetName:a})).id}const i=(t?r?.createdAt:e.created_at)||new Date;let s;s=Ob(e)?e:{inputs:e,outputs:t,created_at:i?.toISOString(),id:r?.exampleId,metadata:r?.metadata,split:r?.split,source_run_id:r?.sourceRunId,use_source_run_io:r?.useSourceRunIO,use_source_run_attachments:r?.useSourceRunAttachments,attachments:r?.attachments};const o=await this._uploadExamplesMultipart(n,[s]);return await this.readExample(o.example_ids?.[0]??By())}async createExamples(e){if(Array.isArray(e)){if(0===e.length)return[];const t=e;let r=t[0].dataset_id;const n=t[0].dataset_name;if(void 0===r&&void 0===n)throw new Error("Must provide either datasetName or datasetId");if(void 0!==r&&void 0!==n)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===r){r=(await this.readDataset({datasetName:n})).id}const a=await this._uploadExamplesMultipart(r,t),i=await Promise.all(a.example_ids.map(e=>this.readExample(e)));return i}const{inputs:t,outputs:r,metadata:n,splits:a,sourceRunIds:i,useSourceRunIOs:s,useSourceRunAttachments:o,attachments:c,exampleIds:l,datasetId:u,datasetName:d}=e;if(void 0===t)throw new Error("Must provide inputs when using legacy parameters");let p=u;const m=d;if(void 0===p&&void 0===m)throw new Error("Must provide either datasetName or datasetId");if(void 0!==p&&void 0!==m)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===p){const e=await this.readDataset({datasetName:m});p=e.id}const h=t.map((e,t)=>({dataset_id:p,inputs:e,outputs:r?.[t],metadata:n?.[t],split:a?.[t],id:l?.[t],attachments:c?.[t],source_run_id:i?.[t],use_source_run_io:s?.[t],use_source_run_attachments:o?.[t]})),f=await this._uploadExamplesMultipart(p,h),g=await Promise.all(f.example_ids.map(e=>this.readExample(e)));return g}async createLLMExample(e,t,r){return this.createExample({input:e},{output:t},r)}async createChatExample(e,t,r){const n=e.map(e=>nb(e)?ab(e):e),a=nb(t)?ab(t):t;return this.createExample({input:n},{output:a},r)}async readExample(e){sb(e);const t=`/examples/${e}`,r=await this._get(t),{attachment_urls:n,...a}=r,i=a;return n&&(i.attachments=Object.entries(n).reduce((e,[t,r])=>(e[t.slice(11)]={presigned_url:r.presigned_url,mime_type:r.mime_type},e),{})),i}async*listExamples({datasetId:e,datasetName:t,exampleIds:r,asOf:n,splits:a,inlineS3Urls:i,metadata:s,limit:o,offset:c,filter:l,includeAttachments:u}={}){let d;if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0!==e)d=e;else{if(void 0===t)throw new Error("Must provide a datasetName or datasetId");d=(await this.readDataset({datasetName:t})).id}const p=new URLSearchParams({dataset:d}),m=n?"string"==typeof n?n:n?.toISOString():void 0;m&&p.append("as_of",m);const h=i??!0;if(p.append("inline_s3_urls",h.toString()),void 0!==r)for(const e of r)p.append("id",e);if(void 0!==a)for(const e of a)p.append("splits",e);if(void 0!==s){const e=JSON.stringify(s);p.append("metadata",e)}void 0!==o&&p.append("limit",o.toString()),void 0!==c&&p.append("offset",c.toString()),void 0!==l&&p.append("filter",l),!0===u&&["attachment_urls","outputs","metadata"].forEach(e=>p.append("select",e));let f=0;for await(const e of this._getPaginated("/examples",p)){for(const t of e){const{attachment_urls:e,...r}=t,n=r;e&&(n.attachments=Object.entries(e).reduce((e,[t,r])=>(e[t.slice(11)]={presigned_url:r.presigned_url,mime_type:r.mime_type||void 0},e),{})),yield n,f++}if(void 0!==o&&f>=o)break}}async deleteExample(e){sb(e);const t=`/examples/${e}`;await this.caller.call(async()=>{const e=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(e,`delete ${t}`,!0),e})}async updateExample(e,t){let r,n,a;if(r=t?e:e.id,sb(r),n=t?{id:r,...t}:e,void 0!==n.dataset_id)a=n.dataset_id;else{a=(await this.readExample(r)).dataset_id}return this._updateExamplesMultipart(a,[n])}async updateExamples(e){let t;if(void 0===e[0].dataset_id){t=(await this.readExample(e[0].id)).dataset_id}else t=e[0].dataset_id;return this._updateExamplesMultipart(t,e)}async readDatasetVersion({datasetId:e,datasetName:t,asOf:r,tag:n}){let a;if(e)a=e;else{const e=await this.readDataset({datasetName:t});a=e.id}if(sb(a),r&&n||!r&&!n)throw new Error("Exactly one of asOf and tag must be specified.");const i=new URLSearchParams;void 0!==r&&i.append("as_of","string"==typeof r?r:r.toISOString()),void 0!==n&&i.append("tag",n);const s=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/datasets/${a}/version?${i.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(e,"read dataset version"),e});return await s.json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:r}){let n;if(void 0===e&&void 0===t)throw new Error("Must provide dataset name or ID");if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===e){n=(await this.readDataset({datasetName:t})).id}else n=e;sb(n);const a=new URLSearchParams,i=r?"string"==typeof r?r:r?.toISOString():void 0;i&&a.append("as_of",i);return await this._get(`/datasets/${n}/splits`,a)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:r,exampleIds:n,remove:a=!1}){let i;if(void 0===e&&void 0===t)throw new Error("Must provide dataset name or ID");if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===e){const e=await this.readDataset({datasetName:t});i=e.id}else i=e;sb(i);const s={split_name:r,examples:n.map(e=>(sb(e),e)),remove:a},o=JSON.stringify(s);await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/datasets/${i}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await db(e,"update dataset splits",!0),e})}async evaluateRun(e,t,{sourceInfo:r,loadChildRuns:n,referenceExample:a}={loadChildRuns:!1}){let i;if(cb("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead."),"string"==typeof e)i=await this.readRun(e,{loadChildRuns:n});else{if("object"!=typeof e||!("id"in e))throw new Error("Invalid run type: "+typeof e);i=e}null!==i.reference_example_id&&void 0!==i.reference_example_id&&(a=await this.readExample(i.reference_example_id));const s=await t.evaluateRun(i,a),[o,c]=await this._logEvaluationFeedback(s,i,r);return c[0]}async createFeedback(e,t,{score:r,value:n,correction:a,comment:i,sourceInfo:s,feedbackSourceType:o="api",sourceRunId:c,feedbackId:l,feedbackConfig:u,projectId:d,comparativeExperimentId:p}){if(!e&&!d)throw new Error("One of runId or projectId must be provided");if(e&&d)throw new Error("Only one of runId or projectId can be provided");const m={type:o??"api",metadata:s??{}};void 0===c||void 0===m?.metadata||m.metadata.__run||(m.metadata.__run={run_id:c}),void 0!==m?.metadata&&void 0!==m.metadata.__run?.run_id&&sb(m.metadata.__run.run_id);const h={id:l??By(),run_id:e,key:t,score:Pb(r),value:n,correction:a,comment:i,feedback_source:m,comparative_experiment_id:p,feedbackConfig:u,session_id:d},f=JSON.stringify(h),g=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const e=await this._fetch(g,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:f});return await db(e,"create feedback",!0),e}),h}async updateFeedback(e,{score:t,value:r,correction:n,comment:a}){const i={};null!=t&&(i.score=Pb(t)),null!=r&&(i.value=r),null!=n&&(i.correction=n),null!=a&&(i.comment=a),sb(e);const s=JSON.stringify(i);await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await db(t,"update feedback",!0),t})}async readFeedback(e){sb(e);const t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){sb(e);const t=`/feedback/${e}`;await this.caller.call(async()=>{const e=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(e,`delete ${t}`,!0),e})}async*listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:r}={}){const n=new URLSearchParams;if(e)for(const t of e)sb(t),n.append("run",t);if(t)for(const e of t)n.append("key",e);if(r)for(const e of r)n.append("source",e);for await(const e of this._getPaginated("/feedback",n))yield*e}async createPresignedFeedbackToken(e,t,{expiration:r,feedbackConfig:n}={}){const a={run_id:e,feedback_key:t,feedback_config:n};r?"string"==typeof r?a.expires_at=r:(r?.hours||r?.minutes||r?.days)&&(a.expires_in=r):a.expires_in={hours:3};const i=JSON.stringify(a),s=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await db(e,"create presigned feedback token"),e});return await s.json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:r,createdAt:n,description:a,metadata:i,id:s}){if(0===t.length)throw new Error("At least one experiment is required");if(r||(r=(await this.readProject({projectId:t[0]})).reference_dataset_id),null==!r)throw new Error("A reference dataset is required");const o={id:s,name:e,experiment_ids:t,reference_dataset_id:r,description:a,created_at:(n??new Date)?.toISOString(),extra:{}};i&&(o.extra.metadata=i);const c=JSON.stringify(o);return(await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await db(e,"create comparative experiment"),e})).json()}async*listPresignedFeedbackTokens(e){sb(e);const t=new URLSearchParams({run_id:e});for await(const e of this._getPaginated("/feedback/tokens",t))yield*e}_selectEvalResults(e){let t;return t="results"in e?e.results:Array.isArray(e)?e:[e],t}async _logEvaluationFeedback(e,t,r){const n=this._selectEvalResults(e),a=[];for(const e of n){let n=r||{};e.evaluatorInfo&&(n={...e.evaluatorInfo,...n});let i=null;e.targetRunId?i=e.targetRunId:t&&(i=t.id),a.push(await this.createFeedback(i,e.key,{score:e.score,value:e.value,comment:e.comment,correction:e.correction,sourceInfo:n,sourceRunId:e.sourceRunId,feedbackConfig:e.feedbackConfig,feedbackSourceType:"model"}))}return[n,a]}async logEvaluationFeedback(e,t,r){const[n]=await this._logEvaluationFeedback(e,t,r);return n}async*listAnnotationQueues(e={}){const{queueIds:t,name:r,nameContains:n,limit:a}=e,i=new URLSearchParams;t&&t.forEach((e,t)=>{sb(e,`queueIds[${t}]`),i.append("ids",e)}),r&&i.append("name",r),n&&i.append("name_contains",n),i.append("limit",(void 0!==a?Math.min(a,100):100).toString());let s=0;for await(const e of this._getPaginated("/annotation-queues",i))if(yield*e,s++,void 0!==a&&s>=a)break}async createAnnotationQueue(e){const{name:t,description:r,queueId:n,rubricInstructions:a}=e,i={name:t,description:r,id:n||By(),rubric_instructions:a},s=JSON.stringify(Object.fromEntries(Object.entries(i).filter(([e,t])=>void 0!==t)));return(await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await db(e,"create annotation queue"),e})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/annotation-queues/${sb(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(t,"read annotation queue"),t})).json()}async updateAnnotationQueue(e,t){const{name:r,description:n,rubricInstructions:a}=t,i=JSON.stringify({name:r,description:n,rubric_instructions:a});await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/annotation-queues/${sb(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await db(t,"update annotation queue",!0),t})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/annotation-queues/${sb(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(t,"delete annotation queue",!0),t})}async addRunsToAnnotationQueue(e,t){const r=JSON.stringify(t.map((e,t)=>sb(e,`runIds[${t}]`).toString()));await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/annotation-queues/${sb(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await db(t,"add runs to annotation queue",!0),t})}async getRunFromAnnotationQueue(e,t){const r=`/annotation-queues/${sb(e,"queueId")}/run`;return(await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}${r}/${t}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(e,"get run from annotation queue"),e})).json()}async deleteRunFromAnnotationQueue(e,t){await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${sb(e,"queueId")}/runs/${sb(t,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(r,"delete run from annotation queue",!0),r})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/annotation-queues/${sb(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(t,"get size from annotation queue"),t})).json()}async _currentTenantIsOwner(e){const t=await this._getSettings();return"-"==e||t.tenant_handle===e}async _ownerConflictError(e,t){const r=await this._getSettings();return new Error(`Cannot ${e} for another tenant.\n\n Current tenant: ${r.tenant_handle}\n\n Requested tenant: ${t}`)}async _getLatestCommitHash(e){const t=await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(t,"get latest commit hash"),t}),r=await t.json();if(0!==r.commits.length)return r.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){const[r,n,a]=lb(e),i=JSON.stringify({like:t});return(await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/likes/${r}/${n}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await db(e,(t?"like":"unlike")+" prompt"),e})).json()}async _getPromptUrl(e){const[t,r,n]=lb(e);if(await this._currentTenantIsOwner(t)){const e=await this._getSettings();return"latest"!==n?`${this.getHostUrl()}/prompts/${r}/${n.substring(0,8)}?organizationId=${e.id}`:`${this.getHostUrl()}/prompts/${r}?organizationId=${e.id}`}return"latest"!==n?`${this.getHostUrl()}/hub/${t}/${r}/${n.substring(0,8)}`:`${this.getHostUrl()}/hub/${t}/${r}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){for await(const t of this._getPaginated(`/commits/${e}/`,new URLSearchParams,e=>e.commits))yield*t}async*listPrompts(e){const t=new URLSearchParams;t.append("sort_field",e?.sortField??"updated_at"),t.append("sort_direction","desc"),t.append("is_archived",(!!e?.isArchived).toString()),void 0!==e?.isPublic&&t.append("is_public",e.isPublic.toString()),e?.query&&t.append("query",e.query);for await(const e of this._getPaginated("/repos",t,e=>e.repos))yield*e}async getPrompt(e){const[t,r,n]=lb(e),a=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/repos/${t}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return 404===e?.status?null:(await db(e,"get prompt"),e)}),i=await(a?.json());return i?.repo?i.repo:null}async createPrompt(e,t){const r=await this._getSettings();if(t?.isPublic&&!r.tenant_handle)throw new Error("Cannot create a public prompt without first\n\n creating a LangChain Hub handle.\n You can add a handle by creating a public prompt at:\n\n https://smith.langchain.com/prompts");const[n,a,i]=lb(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("create a prompt",n);const s={repo_handle:a,...t?.description&&{description:t.description},...t?.readme&&{readme:t.readme},...t?.tags&&{tags:t.tags},is_public:!!t?.isPublic},o=JSON.stringify(s),c=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await db(e,"create prompt"),e}),{repo:l}=await c.json();return l}async createCommit(e,t,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[n,a,i]=lb(e),s="latest"!==r?.parentCommitHash&&r?.parentCommitHash?r?.parentCommitHash:await this._getLatestCommitHash(`${n}/${a}`),o={manifest:JSON.parse(JSON.stringify(t)),parent_commit:s},c=JSON.stringify(o),l=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/commits/${n}/${a}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await db(e,"create commit"),e}),u=await l.json();return this._getPromptUrl(`${n}/${a}${u.commit_hash?`:${u.commit_hash}`:""}`)}async updateExamplesMultipart(e,t=[]){return this._updateExamplesMultipart(e,t)}async _updateExamplesMultipart(e,t=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const r=new FormData;for(const e of t){const t=e.id,n=wb({...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split}},`Serializing body for example with id: ${t}`),a=new Blob([n],{type:"application/json"});if(r.append(t,a),e.inputs){const n=wb(e.inputs,`Serializing inputs for example with id: ${t}`),a=new Blob([n],{type:"application/json"});r.append(`${t}.inputs`,a)}if(e.outputs){const n=wb(e.outputs,`Serializing outputs whle updating example with id: ${t}`),a=new Blob([n],{type:"application/json"});r.append(`${t}.outputs`,a)}if(e.attachments)for(const[n,a]of Object.entries(e.attachments)){let e,i;Array.isArray(a)?[e,i]=a:(e=a.mimeType,i=a.data);const s=new Blob([i],{type:`${e}; length=${i.byteLength}`});r.append(`${t}.attachment.${n}`,s)}if(e.attachments_operations){const n=wb(e.attachments_operations,`Serializing attachments while updating example with id: ${t}`),a=new Blob([n],{type:"application/json"});r.append(`${t}.attachments_operations`,a)}}const n=e??t[0]?.dataset_id;return(await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${n}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await db(e,"update examples"),e})).json()}async uploadExamplesMultipart(e,t=[]){return this._uploadExamplesMultipart(e,t)}async _uploadExamplesMultipart(e,t=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const r=new FormData;for(const e of t){const t=(e.id??By()).toString(),n=wb({created_at:e.created_at,...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split},...e.source_run_id&&{source_run_id:e.source_run_id},...e.use_source_run_io&&{use_source_run_io:e.use_source_run_io},...e.use_source_run_attachments&&{use_source_run_attachments:e.use_source_run_attachments}},`Serializing body for uploaded example with id: ${t}`),a=new Blob([n],{type:"application/json"});if(r.append(t,a),e.inputs){const n=wb(e.inputs,`Serializing inputs for uploaded example with id: ${t}`),a=new Blob([n],{type:"application/json"});r.append(`${t}.inputs`,a)}if(e.outputs){const n=wb(e.outputs,`Serializing outputs for uploaded example with id: ${t}`),a=new Blob([n],{type:"application/json"});r.append(`${t}.outputs`,a)}if(e.attachments)for(const[n,a]of Object.entries(e.attachments)){let e,i;Array.isArray(a)?[e,i]=a:(e=a.mimeType,i=a.data);const s=new Blob([i],{type:`${e}; length=${i.byteLength}`});r.append(`${t}.attachment.${n}`,s)}}return(await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await db(t,"upload examples"),t})).json()}async updatePrompt(e,t){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[r,n]=lb(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);const a={};if(void 0!==t?.description&&(a.description=t.description),void 0!==t?.readme&&(a.readme=t.readme),void 0!==t?.tags&&(a.tags=t.tags),void 0!==t?.isPublic&&(a.is_public=t.isPublic),void 0!==t?.isArchived&&(a.is_archived=t.isArchived),0===Object.keys(a).length)throw new Error("No valid update options provided");const i=JSON.stringify(a);return(await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await db(e,"update prompt"),e})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[t,r,n]=lb(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);return(await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/repos/${t}/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(e,"delete prompt"),e})).json()}async pullPromptCommit(e,t){const[r,n,a]=lb(e),i=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/commits/${r}/${n}/${a}${t?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await db(e,"pull prompt commit"),e}),s=await i.json();return{owner:r,repo:n,commit_hash:s.commit_hash,manifest:s.manifest,examples:s.examples}}async _pullPrompt(e,t){const r=await this.pullPromptCommit(e,{includeModel:t?.includeModel});return JSON.stringify(r.manifest)}async pushPrompt(e,t){if(await this.promptExists(e)?t&&Object.keys(t).some(e=>"object"!==e)&&await this.updatePrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}):await this.createPrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}),!t?.object)return await this._getPromptUrl(e);return await this.createCommit(e,t?.object,{parentCommitHash:t?.parentCommitHash})}async clonePublicDataset(e,t={}){const{sourceApiUrl:r=this.apiUrl,datasetName:n}=t,[a,i]=this.parseTokenOrUrl(e,r),s=new Ib({apiUrl:a,apiKey:"placeholder"}),o=await s.readSharedDataset(i),c=n||o.name;try{if(await this.hasDataset({datasetId:c}))return void console.log(`Dataset ${c} already exists in your tenant. Skipping.`)}catch(e){}const l=await s.listSharedExamples(i),u=await this.createDataset(c,{description:o.description,dataType:o.data_type||"kv",inputsSchema:o.inputs_schema_definition??void 0,outputsSchema:o.outputs_schema_definition??void 0});try{await this.createExamples({inputs:l.map(e=>e.inputs),outputs:l.flatMap(e=>e.outputs?[e.outputs]:[]),datasetId:u.id})}catch(e){throw console.error(`An error occurred while creating dataset ${c}. You should delete it manually.`),e}}parseTokenOrUrl(e,t,r=2,n="dataset"){try{return sb(e),[t,e]}catch(e){}try{const a=new URL(e).pathname.split("/").filter(e=>""!==e);if(a.length>=r){return[t,a[a.length-r]]}throw new Error(`Invalid public ${n} URL: ${e}`)}catch(t){throw new Error(`Invalid public ${n} URL or token: ${e}`)}}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),void 0!==this.langSmithToOTELTranslator&&await(Nv.getDefaultOTLPTracerComponents()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush())}}function Ob(e){return"dataset_id"in e||"dataset_name"in e}const Tb=Symbol.for("lc:context_variables");function $b(e,t,r=1){const n=r.toFixed(0).slice(0,3).padStart(3,"0"),a=`${new Date(e).toISOString().slice(0,-1)}${n}Z`;return{dottedOrder:(i=a,i.replace(/[-:.]/g,"")+t),microsecondPrecisionDatestring:a};var i}class zb{constructor(e,t,r,n){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=t,this.project_name=r,this.replicas=n}static fromHeader(e){const t=e.split(",");let r,n,a={},i=[];for(const e of t){const[t,s]=e.split("="),o=decodeURIComponent(s);"langsmith-metadata"===t?a=JSON.parse(o):"langsmith-tags"===t?i=o.split(","):"langsmith-project"===t?r=o:"langsmith-replicas"===t&&(n=JSON.parse(o))}return new zb(a,i,r,n)}toHeader(){const e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}}class Rb{constructor(e){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),null!=(t=e)&&"function"==typeof t.createChild&&"function"==typeof t.postRun)return void Object.assign(this,{...e});var t;const r=Rb.getDefaultConfig(),{metadata:n,...a}=e,i=a.client??Rb.getSharedClient(),s={...n,...a?.extra?.metadata};if(a.extra={...a.extra,metadata:s},Object.assign(this,{...r,...a,client:i}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=function(e){if(e)return e.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e);return function(){const e=hv("LANGSMITH_RUNS_ENDPOINTS");if(!e)return[];try{const t=JSON.parse(e);if(Array.isArray(t)){const e=[];for(const r of t)"object"==typeof r&&null!==r?"string"==typeof r.api_url?"string"==typeof r.api_key?e.push({apiUrl:r.api_url.replace(/\/$/,""),apiKey:r.api_key}):console.warn("Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got "+typeof r.api_key):console.warn("Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got "+typeof r.api_url):console.warn("Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got "+typeof r);return e}if("object"==typeof t&&null!==t){!function(e){if(Object.keys(e).length>0&&fv("ENDPOINT"))throw new mb}(t);const e=[];for(const[r,n]of Object.entries(t)){const t=r.replace(/\/$/,"");"string"==typeof n?e.push({apiUrl:t,apiKey:n}):console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${r}: expected string, got `+typeof n)}return e}return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got "+typeof t),[]}catch(e){if("object"==typeof(t=e)&&null!==t&&t.code===pb)throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}var t}()}(this.replicas),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){const{dottedOrder:e,microsecondPrecisionDatestring:t}=$b(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+e:this.dotted_order=e,this._serialized_start_time=t}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){return{id:By(),run_type:"chain",project_name:iv(),child_runs:[],api_url:hv("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:hv("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return Rb.sharedClient||(Rb.sharedClient=new Ib),Rb.sharedClient}createChild(e){const t=this.child_execution_order+1,r=new Rb({...e,parent_run:this,project_name:this.project_name,replicas:this.replicas,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:t,child_execution_order:t});Tb in this&&(r[Tb]=this[Tb]);const n=Symbol.for("lc:child_config"),a=e.extra?.[n]??this.extra[n];if(null!=(i=a)&&"object"==typeof i.callbacks&&(Mb(i.callbacks?.handlers)||Mb(i.callbacks))){const e={...a},t=function(e){return"object"==typeof e&&null!=e&&Array.isArray(e.handlers)}(e.callbacks)?e.callbacks.copy?.():void 0;t&&(Object.assign(t,{_parentRunId:r.id}),t.handlers?.find(Lb)?.updateFromRunTree?.(r),e.callbacks=t),r.extra[n]=e}var i;const s=new Set;let o=this;for(;null!=o&&!s.has(o.id);)s.add(o.id),o.child_execution_order=Math.max(o.child_execution_order,t),o=o.parent_run;return this.child_runs.push(r),r}async end(e,t,r=Date.now(),n){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??r,n&&Object.keys(n).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...n}}:{metadata:n})}_convertToCreate(e,t,r=!0){const n=e.extra??{};if(void 0===n?.runtime?.library&&(n.runtime||(n.runtime={}),t))for(const[e,r]of Object.entries(t))n.runtime[e]||(n.runtime[e]=r);let a,i;return r?(i=e.parent_run?.id??e.parent_run_id,a=[]):(a=e.child_runs.map(e=>this._convertToCreate(e,t,r)),i=void 0),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:n,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:a,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_remapForProject(e,t,r=!0){const n=this._convertToCreate(this,t,r);if(e===this.project_name)return n;const a=t=>Hy(`${t}:${e}`,Hy.DNS),i=a(n.id),s=n.trace_id?a(n.trace_id):void 0,o=n.parent_run_id?a(n.parent_run_id):void 0;let c;if(n.dotted_order){const e=n.dotted_order.split(".").map(e=>{const t=e.slice(0,-36),r=e.slice(-36),n=parseInt(t.slice(0,4)),a=parseInt(t.slice(4,6))-1,i=parseInt(t.slice(6,8)),s=parseInt(t.slice(9,11)),o=parseInt(t.slice(11,13)),c=parseInt(t.slice(13,15)),l=parseInt(t.slice(15,21));return[new Date(n,a,i,s,o,c,l/1e3),r]}),t=[];for(let r=0;r<e.length-1;r++){const[n,i]=e[r],s=a(i);t.push(n.toISOString().replace(/[-:]/g,"").replace(".","")+s)}const[r]=e[e.length-1];t.push(r.toISOString().replace(/[-:]/g,"").replace(".","")+i),c=t.join(".")}else c=void 0;return{...n,id:i,trace_id:s,parent_run_id:o,dotted_order:c,session_name:e}}async postRun(e=!0){try{const t=pv();if(this.replicas&&this.replicas.length>0)for(const{projectName:e,apiKey:r,apiUrl:n,workspaceId:a}of this.replicas){const i=this._remapForProject(e??this.project_name,t,!0);await this.client.createRun(i,{apiKey:r,apiUrl:n,workspaceId:a})}else{const r=this._convertToCreate(this,t,e);await this.client.createRun(r)}if(!e){cb("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const e of this.child_runs)await e.postRun(!1)}}catch(e){console.error(`Error in postRun for run ${this.id}:`,e)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(const{projectName:t,apiKey:r,apiUrl:n,workspaceId:a,updates:i}of this.replicas){const s=this._remapForProject(t??this.project_name),o={id:s.id,outputs:s.outputs,error:s.error,parent_run_id:s.parent_run_id,session_name:s.session_name,reference_example_id:s.reference_example_id,end_time:s.end_time,dotted_order:s.dotted_order,trace_id:s.trace_id,events:s.events,tags:s.tags,extra:s.extra,attachments:this.attachments,...i};e?.excludeInputs||(o.inputs=s.inputs),await this.client.updateRun(s.id,o,{apiKey:r,apiUrl:n,workspaceId:a})}else try{const t={end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};e?.excludeInputs||(t.inputs=this.inputs),await this.client.updateRun(this.id,t)}catch(e){console.error(`Error in patchRun for run ${this.id}`,e)}}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),"string"==typeof e?this.events.push({name:"event",time:(new Date).toISOString(),message:e}):this.events.push({...e,time:e.time??(new Date).toISOString()})}static fromRunnableConfig(e,t){const r=e?.callbacks;let n,a,i,s=!!["TRACING_V2","TRACING"].find(e=>"true"===fv(e));if(r){const e=r?.getParentRunId?.()??"",t=r?.handlers?.find(e=>"langchain_tracer"==e?.name);n=t?.getRun?.(e),a=t?.projectName,i=t?.client,s=s||!!t}if(!n)return new Rb({...t,client:i,tracingEnabled:s,project_name:a});return new Rb({name:n.name,id:n.id,trace_id:n.trace_id,dotted_order:n.dotted_order,client:i,tracingEnabled:s,project_name:a,tags:[...new Set((n?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...n?.extra?.metadata,...e?.metadata}}}).createChild(t)}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){const r="get"in e&&"function"==typeof e.get?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,n=r["langsmith-trace"];if(!n||"string"!=typeof n)return;const a=n.trim(),i=a.split(".").map(e=>{const[t,r]=e.split("Z");return{strTime:t,time:Date.parse(t+"Z"),uuid:r}}),s=i[0].uuid,o={...t,name:t?.name??"parent",run_type:t?.run_type??"chain",start_time:t?.start_time??Date.now(),id:i.at(-1)?.uuid,trace_id:s,dotted_order:a};if(r.baggage&&"string"==typeof r.baggage){const e=zb.fromHeader(r.baggage);o.metadata=e.metadata,o.tags=e.tags,o.project_name=e.project_name,o.replicas=e.replicas}return new Rb(o)}toHeaders(e){const t={"langsmith-trace":this.dotted_order,baggage:new zb(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(const[r,n]of Object.entries(t))e.set(r,n);return t}}function Lb(e){return"object"==typeof e&&null!=e&&"string"==typeof e.name&&"langchain_tracer"===e.name}function Mb(e){return Array.isArray(e)&&e.some(e=>Lb(e))}Object.defineProperty(Rb,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});yf({},{BaseTracer:()=>qb,isBaseTracer:()=>Fb});function Db(e,t){if(e)return new Rb({...e,start_time:e._serialized_start_time??e.start_time,parent_run:Db(t),child_runs:e.child_runs.map(e=>Db(e)).filter(e=>void 0!==e),extra:{...e.extra,runtime:Ty()},tracingEnabled:!1})}function jb(e,t){return e&&!Array.isArray(e)&&"object"==typeof e?e:{[t]:e}}function Fb(e){return"function"==typeof e._addRunToRunMap}var Ub,qb=class extends Zy{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(e){super(...arguments)}copy(){return this}getRunById(e){if(void 0!==e)return this.usesRunTreeMap?(e=>{if(e)return e.events=e.events??[],e.child_runs=e.child_runs??[],e})(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`\n\n${e.stack}`:""):"string"==typeof e?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){const{dottedOrder:t,microsecondPrecisionDatestring:r}=$b(new Date(e.start_time).getTime(),e.id,e.execution_order),n={...e},a=this.getRunById(n.parent_run_id);if(void 0!==n.parent_run_id?a&&(this._addChildRun(a,n),a.child_execution_order=Math.max(a.child_execution_order,n.child_execution_order),n.trace_id=a.trace_id,void 0!==a.dotted_order&&(n.dotted_order=[a.dotted_order,t].join("."),n._serialized_start_time=r)):(n.trace_id=n.id,n.dotted_order=t,n._serialized_start_time=r),this.usesRunTreeMap){const e=Db(n,a);void 0!==e&&this.runTreeMap.set(n.id,e)}else this.runMap.set(n.id,n);return n}async _endTrace(e){const t=void 0!==e.parent_run_id&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await(this.onRunUpdate?.(e)),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){const t=void 0!==e&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,r,n,a,i,s,o){const c=this._getExecutionOrder(n),l=Date.now(),u=s?{...a,metadata:s}:a,d={id:r,name:o??e.id[e.id.length-1],parent_run_id:n,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{prompts:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:u??{},tags:i||[]};return this._addRunToRunMap(d)}async handleLLMStart(e,t,r,n,a,i,s,o){const c=this.getRunById(r)??this._createRunForLLMStart(e,t,r,n,a,i,s,o);return await(this.onRunCreate?.(c)),await(this.onLLMStart?.(c)),c}_createRunForChatModelStart(e,t,r,n,a,i,s,o){const c=this._getExecutionOrder(n),l=Date.now(),u=s?{...a,metadata:s}:a,d={id:r,name:o??e.id[e.id.length-1],parent_run_id:n,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{messages:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:u??{},tags:i||[]};return this._addRunToRunMap(d)}async handleChatModelStart(e,t,r,n,a,i,s,o){const c=this.getRunById(r)??this._createRunForChatModelStart(e,t,r,n,a,i,s,o);return await(this.onRunCreate?.(c)),await(this.onLLMStart?.(c)),c}async handleLLMEnd(e,t,r,n,a){const i=this.getRunById(t);if(!i||"llm"!==i?.run_type)throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.outputs=e,i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...a},await(this.onLLMEnd?.(i)),await this._endTrace(i),i}async handleLLMError(e,t,r,n,a){const i=this.getRunById(t);if(!i||"llm"!==i?.run_type)throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...a},await(this.onLLMError?.(i)),await this._endTrace(i),i}_createRunForChainStart(e,t,r,n,a,i,s,o){const c=this._getExecutionOrder(n),l=Date.now(),u={id:r,name:o??e.id[e.id.length-1],parent_run_id:n,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:t,execution_order:c,child_execution_order:c,run_type:s??"chain",child_runs:[],extra:i?{metadata:i}:{},tags:a||[]};return this._addRunToRunMap(u)}async handleChainStart(e,t,r,n,a,i,s,o){const c=this.getRunById(r)??this._createRunForChainStart(e,t,r,n,a,i,s,o);return await(this.onRunCreate?.(c)),await(this.onChainStart?.(c)),c}async handleChainEnd(e,t,r,n,a){const i=this.getRunById(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.outputs=jb(e,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),void 0!==a?.inputs&&(i.inputs=jb(a.inputs,"input")),await(this.onChainEnd?.(i)),await this._endTrace(i),i}async handleChainError(e,t,r,n,a){const i=this.getRunById(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),void 0!==a?.inputs&&(i.inputs=jb(a.inputs,"input")),await(this.onChainError?.(i)),await this._endTrace(i),i}_createRunForToolStart(e,t,r,n,a,i,s){const o=this._getExecutionOrder(n),c=Date.now(),l={id:r,name:s??e.id[e.id.length-1],parent_run_id:n,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:t},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:i?{metadata:i}:{},tags:a||[]};return this._addRunToRunMap(l)}async handleToolStart(e,t,r,n,a,i,s){const o=this.getRunById(r)??this._createRunForToolStart(e,t,r,n,a,i,s);return await(this.onRunCreate?.(o)),await(this.onToolStart?.(o)),o}async handleToolEnd(e,t){const r=this.getRunById(t);if(!r||"tool"!==r?.run_type)throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await(this.onToolEnd?.(r)),await this._endTrace(r),r}async handleToolError(e,t){const r=this.getRunById(t);if(!r||"tool"!==r?.run_type)throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await(this.onToolError?.(r)),await this._endTrace(r),r}async handleAgentAction(e,t){const r=this.getRunById(t);if(!r||"chain"!==r?.run_type)return;const n=r;n.actions=n.actions||[],n.actions.push(e),n.events.push({name:"agent_action",time:(new Date).toISOString(),kwargs:{action:e}}),await(this.onAgentAction?.(r))}async handleAgentEnd(e,t){const r=this.getRunById(t);r&&"chain"===r?.run_type&&(r.events.push({name:"agent_end",time:(new Date).toISOString(),kwargs:{action:e}}),await(this.onAgentEnd?.(r)))}_createRunForRetrieverStart(e,t,r,n,a,i,s){const o=this._getExecutionOrder(n),c=Date.now(),l={id:r,name:s??e.id[e.id.length-1],parent_run_id:n,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:t},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:i?{metadata:i}:{},tags:a||[]};return this._addRunToRunMap(l)}async handleRetrieverStart(e,t,r,n,a,i,s){const o=this.getRunById(r)??this._createRunForRetrieverStart(e,t,r,n,a,i,s);return await(this.onRunCreate?.(o)),await(this.onRetrieverStart?.(o)),o}async handleRetrieverEnd(e,t){const r=this.getRunById(t);if(!r||"retriever"!==r?.run_type)throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await(this.onRetrieverEnd?.(r)),await this._endTrace(r),r}async handleRetrieverError(e,t){const r=this.getRunById(t);if(!r||"retriever"!==r?.run_type)throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await(this.onRetrieverError?.(r)),await this._endTrace(r),r}async handleText(e,t){const r=this.getRunById(t);r&&"chain"===r?.run_type&&(r.events.push({name:"text",time:(new Date).toISOString(),kwargs:{text:e}}),await(this.onText?.(r)))}async handleLLMNewToken(e,t,r,n,a,i){const s=this.getRunById(r);if(!s||"llm"!==s?.run_type)throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return s.events.push({name:"new_token",time:(new Date).toISOString(),kwargs:{token:e,idx:t,chunk:i?.chunk}}),await(this.onLLMNewToken?.(s,e,{chunk:i?.chunk})),s}},Bb={exports:{}};var Vb=(Ub||(Ub=1,function(e){const t=(e=0)=>t=>`[${38+e};5;${t}m`,r=(e=0)=>(t,r,n)=>`[${38+e};2;${t};${r};${n}m`;Object.defineProperty(e,"exports",{enumerable:!0,get:function(){const e=new Map,n={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],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],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};n.color.gray=n.color.blackBright,n.bgColor.bgGray=n.bgColor.bgBlackBright,n.color.grey=n.color.blackBright,n.bgColor.bgGrey=n.bgColor.bgBlackBright;for(const[t,r]of Object.entries(n)){for(const[t,a]of Object.entries(r))n[t]={open:`[${a[0]}m`,close:`[${a[1]}m`},r[t]=n[t],e.set(a[0],a[1]);Object.defineProperty(n,t,{value:r,enumerable:!1})}return Object.defineProperty(n,"codes",{value:e,enumerable:!1}),n.color.close="",n.bgColor.close="",n.color.ansi256=t(),n.color.ansi16m=r(),n.bgColor.ansi256=t(10),n.bgColor.ansi16m=r(10),Object.defineProperties(n,{rgbToAnsi256:{value:(e,t,r)=>e===t&&t===r?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(r/255*5),enumerable:!1},hexToRgb:{value:e=>{const t=/(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(e.toString(16));if(!t)return[0,0,0];let{colorString:r}=t.groups;3===r.length&&(r=r.split("").map(e=>e+e).join(""));const n=Number.parseInt(r,16);return[n>>16&255,n>>8&255,255&n]},enumerable:!1},hexToAnsi256:{value:e=>n.rgbToAnsi256(...n.hexToRgb(e)),enumerable:!1}}),n}})}(Bb)),Bb.exports),Gb=ba(Vb);function Hb(e,t){return`${e.open}${t}${e.close}`}function Kb(e,t){try{return JSON.stringify(e,null,2)}catch{return t}}function Wb(e){return"string"==typeof e?e.trim():null==e?e:Kb(e,e.toString())}function Zb(e){if(!e.end_time)return"";const t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}yf({},{ConsoleCallbackHandler:()=>Yb});const{color:Jb}=Gb;var Yb=class extends qb{name="console_callback_handler";persistRun(e){return Promise.resolve()}getParents(e){const t=[];let r=e;for(;r.parent_run_id;){const e=this.runMap.get(r.parent_run_id);if(!e)break;t.push(e),r=e}return t}getBreadcrumbs(e){const t=[...this.getParents(e).reverse(),e].map((e,t,r)=>{const n=`${e.execution_order}:${e.run_type}:${e.name}`;return t===r.length-1?Hb(Gb.bold,n):n}).join(" > ");return Hb(Jb.grey,t)}onChainStart(e){const t=this.getBreadcrumbs(e);console.log(`${Hb(Jb.green,"[chain/start]")} [${t}] Entering Chain run with input: ${Kb(e.inputs,"[inputs]")}`)}onChainEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Hb(Jb.cyan,"[chain/end]")} [${t}] [${Zb(e)}] Exiting Chain run with output: ${Kb(e.outputs,"[outputs]")}`)}onChainError(e){const t=this.getBreadcrumbs(e);console.log(`${Hb(Jb.red,"[chain/error]")} [${t}] [${Zb(e)}] Chain run errored with error: ${Kb(e.error,"[error]")}`)}onLLMStart(e){const t=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(e=>e.trim())}:e.inputs;console.log(`${Hb(Jb.green,"[llm/start]")} [${t}] Entering LLM run with input: ${Kb(r,"[inputs]")}`)}onLLMEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Hb(Jb.cyan,"[llm/end]")} [${t}] [${Zb(e)}] Exiting LLM run with output: ${Kb(e.outputs,"[response]")}`)}onLLMError(e){const t=this.getBreadcrumbs(e);console.log(`${Hb(Jb.red,"[llm/error]")} [${t}] [${Zb(e)}] LLM run errored with error: ${Kb(e.error,"[error]")}`)}onToolStart(e){const t=this.getBreadcrumbs(e);console.log(`${Hb(Jb.green,"[tool/start]")} [${t}] Entering Tool run with input: "${Wb(e.inputs.input)}"`)}onToolEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Hb(Jb.cyan,"[tool/end]")} [${t}] [${Zb(e)}] Exiting Tool run with output: "${Wb(e.outputs?.output)}"`)}onToolError(e){const t=this.getBreadcrumbs(e);console.log(`${Hb(Jb.red,"[tool/error]")} [${t}] [${Zb(e)}] Tool run errored with error: ${Kb(e.error,"[error]")}`)}onRetrieverStart(e){const t=this.getBreadcrumbs(e);console.log(`${Hb(Jb.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${Kb(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Hb(Jb.cyan,"[retriever/end]")} [${t}] [${Zb(e)}] Exiting Retriever run with output: ${Kb(e.outputs,"[outputs]")}`)}onRetrieverError(e){const t=this.getBreadcrumbs(e);console.log(`${Hb(Jb.red,"[retriever/error]")} [${t}] [${Zb(e)}] Retriever run errored with error: ${Kb(e.error,"[error]")}`)}onAgentAction(e){const t=e,r=this.getBreadcrumbs(e);console.log(`${Hb(Jb.blue,"[agent/action]")} [${r}] Agent selected action: ${Kb(t.actions[t.actions.length-1],"[action]")}`)}};let Qb;const Xb=()=>{if(void 0===Qb){const e="false"===$y("LANGCHAIN_CALLBACKS_BACKGROUND")?{blockOnRootRunFinalization:!0}:{};Qb=new Ib(e)}return Qb};const e_=Symbol.for("ls:tracing_async_local_storage"),t_=new class{getStore(){}run(e,t){return t()}};const r_=new class{getInstance(){return globalThis[e_]??t_}initializeGlobalInstance(e){void 0===globalThis[e_]&&(globalThis[e_]=e)}};function n_(e){return"function"==typeof e&&"langsmith:traceable"in e}yf({},{LangChainTracer:()=>a_});var a_=class e extends qb{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;constructor(t={}){super(t);const{exampleId:r,projectName:n,client:a,replicas:i}=t;this.projectName=n??iv(),this.replicas=i,this.exampleId=r,this.client=a??Xb();const s=e.getTraceableRunTree();s&&this.updateFromRunTree(s)}async persistRun(e){}async onRunCreate(e){const t=this.getRunTreeWithTracingConfig(e.id);await(t?.postRun())}async onRunUpdate(e){const t=this.getRunTreeWithTracingConfig(e.id);await(t?.patchRun())}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let t=e;const r=new Set;for(;t.parent_run&&!r.has(t.id)&&(r.add(t.id),t.parent_run);)t=t.parent_run;r.clear();const n=[t];for(;n.length>0;){const e=n.shift();e&&!r.has(e.id)&&(r.add(e.id),this.runTreeMap.set(e.id,e),e.child_runs&&n.push(...e.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(e){const t=this.runTreeMap.get(e);if(t)return new Rb({...t,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return function(e=!1){const t=r_.getInstance().getStore();if(!e&&void 0===t)throw new Error("Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function and that tracing is enabled.");return t}(!0)}catch{return}}};let i_;function s_(){return void 0===i_&&(i_=new("default"in eb?eb.default:eb)({autoStart:!0,concurrency:1})),i_}async function o_(e,t){if(!0===t){const t=ky();void 0!==t?await t.run(void 0,async()=>e()):await e()}else i_=s_(),i_.add(async()=>{const t=ky();void 0!==t?await t.run(void 0,async()=>e()):await e()})}async function c_(){const e=Xb();await Promise.allSettled([void 0!==i_?i_.onIdle():Promise.resolve(),e.awaitPendingTraceBatches()])}yf({},{awaitAllCallbacks:()=>c_,consumeCallback:()=>o_});function l_(e){const t=ky();if(void 0===t)return;const r=t.getStore();return r?.[Ny]?.[e]}const u_=Symbol("lc:configure_hooks");function d_(e){return e?Array.isArray(e)||"name"in e?{callbacks:e}:e:{}}yf({},{BaseCallbackManager:()=>p_,BaseRunManager:()=>m_,CallbackManager:()=>v_,CallbackManagerForChainRun:()=>g_,CallbackManagerForLLMRun:()=>f_,CallbackManagerForRetrieverRun:()=>h_,CallbackManagerForToolRun:()=>y_,ensureHandler:()=>b_,parseCallbackConfigArg:()=>d_});var p_=class{setHandler(e){return this.setHandlers([e])}},m_=class{constructor(e,t,r,n,a,i,s,o){this.runId=e,this.handlers=t,this.inheritableHandlers=r,this.tags=n,this.inheritableTags=a,this.metadata=i,this.inheritableMetadata=s,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>o_(async()=>{try{await(t.handleText?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleCustomEvent(e,t,r,n,a){await Promise.all(this.handlers.map(r=>o_(async()=>{try{await(r.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata))}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleCustomEvent: ${e}`),r.raiseError)throw e}},r.awaitHandlers)))}},h_=class extends m_{getChild(e){const t=new v_(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleRetrieverEnd(e){await Promise.all(this.handlers.map(t=>o_(async()=>{if(!t.ignoreRetriever)try{await(t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw e}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>o_(async()=>{if(!t.ignoreRetriever)try{await(t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags))}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${r}`),t.raiseError)throw e}},t.awaitHandlers)))}},f_=class extends m_{async handleLLMNewToken(e,t,r,n,a,i){await Promise.all(this.handlers.map(r=>o_(async()=>{if(!r.ignoreLLM)try{await(r.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,i))}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMNewToken: ${e}`),r.raiseError)throw e}},r.awaitHandlers)))}async handleLLMError(e,t,r,n,a){await Promise.all(this.handlers.map(t=>o_(async()=>{if(!t.ignoreLLM)try{await(t.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,a))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleLLMEnd(e,t,r,n,a){await Promise.all(this.handlers.map(t=>o_(async()=>{if(!t.ignoreLLM)try{await(t.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,a))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}},g_=class extends m_{getChild(e){const t=new v_(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,r,n,a){await Promise.all(this.handlers.map(t=>o_(async()=>{if(!t.ignoreChain)try{await(t.handleChainError?.(e,this.runId,this._parentRunId,this.tags,a))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleChainEnd(e,t,r,n,a){await Promise.all(this.handlers.map(t=>o_(async()=>{if(!t.ignoreChain)try{await(t.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,a))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>o_(async()=>{if(!t.ignoreAgent)try{await(t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>o_(async()=>{if(!t.ignoreAgent)try{await(t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}},y_=class extends m_{getChild(e){const t=new v_(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleToolError(e){await Promise.all(this.handlers.map(t=>o_(async()=>{if(!t.ignoreAgent)try{await(t.handleToolError?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>o_(async()=>{if(!t.ignoreAgent)try{await(t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}},v_=class e extends p_{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(e,t){super(),this.handlers=t?.handlers??this.handlers,this.inheritableHandlers=t?.inheritableHandlers??this.inheritableHandlers,this.tags=t?.tags??this.tags,this.inheritableTags=t?.inheritableTags??this.inheritableTags,this.metadata=t?.metadata??this.metadata,this.inheritableMetadata=t?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,t,r=void 0,n=void 0,a=void 0,i=void 0,s=void 0,o=void 0){return Promise.all(t.map(async(t,n)=>{const i=0===n&&r?r:By();return await Promise.all(this.handlers.map(r=>{if(!r.ignoreLLM)return Fb(r)&&r._createRunForLLMStart(e,[t],i,this._parentRunId,a,this.tags,this.metadata,o),o_(async()=>{try{await(r.handleLLMStart?.(e,[t],i,this._parentRunId,a,this.tags,this.metadata,o))}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new f_(i,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,t,r=void 0,n=void 0,a=void 0,i=void 0,s=void 0,o=void 0){return Promise.all(t.map(async(t,n)=>{const i=0===n&&r?r:By();return await Promise.all(this.handlers.map(r=>{if(!r.ignoreLLM)return Fb(r)&&r._createRunForChatModelStart(e,[t],i,this._parentRunId,a,this.tags,this.metadata,o),o_(async()=>{try{if(r.handleChatModelStart)await(r.handleChatModelStart?.(e,[t],i,this._parentRunId,a,this.tags,this.metadata,o));else if(r.handleLLMStart){const n=yy(t);await(r.handleLLMStart?.(e,[n],i,this._parentRunId,a,this.tags,this.metadata,o))}}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new f_(i,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,t,r=By(),n=void 0,a=void 0,i=void 0,s=void 0){return await Promise.all(this.handlers.map(a=>{if(!a.ignoreChain)return Fb(a)&&a._createRunForChainStart(e,t,r,this._parentRunId,this.tags,this.metadata,n,s),o_(async()=>{try{await(a.handleChainStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,n,s))}catch(e){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleChainStart: ${e}`),a.raiseError)throw e}},a.awaitHandlers)})),new g_(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,r=By(),n=void 0,a=void 0,i=void 0,s=void 0){return await Promise.all(this.handlers.map(n=>{if(!n.ignoreAgent)return Fb(n)&&n._createRunForToolStart(e,t,r,this._parentRunId,this.tags,this.metadata,s),o_(async()=>{try{await(n.handleToolStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,s))}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleToolStart: ${e}`),n.raiseError)throw e}},n.awaitHandlers)})),new y_(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,r=By(),n=void 0,a=void 0,i=void 0,s=void 0){return await Promise.all(this.handlers.map(n=>{if(!n.ignoreRetriever)return Fb(n)&&n._createRunForRetrieverStart(e,t,r,this._parentRunId,this.tags,this.metadata,s),o_(async()=>{try{await(n.handleRetrieverStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,s))}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleRetrieverStart: ${e}`),n.raiseError)throw e}},n.awaitHandlers)})),new h_(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,r,n,a){await Promise.all(this.handlers.map(n=>o_(async()=>{if(!n.ignoreCustomEvent)try{await(n.handleCustomEvent?.(e,t,r,this.tags,this.metadata))}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleCustomEvent: ${e}`),n.raiseError)throw e}},n.awaitHandlers)))}addHandler(e,t=!0){this.handlers.push(e),t&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(t=>t!==e),this.inheritableHandlers=this.inheritableHandlers.filter(t=>t!==e)}setHandlers(e,t=!0){this.handlers=[],this.inheritableHandlers=[];for(const r of e)this.addHandler(r,t)}addTags(e,t=!0){this.removeTags(e),this.tags.push(...e),t&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(t=>!e.includes(t)),this.inheritableTags=this.inheritableTags.filter(t=>!e.includes(t))}addMetadata(e,t=!0){this.metadata={...this.metadata,...e},t&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(const t of Object.keys(e))delete this.metadata[t],delete this.inheritableMetadata[t]}copy(t=[],r=!0){const n=new e(this._parentRunId);for(const e of this.handlers){const t=this.inheritableHandlers.includes(e);n.addHandler(e,t)}for(const e of this.tags){const t=this.inheritableTags.includes(e);n.addTags([e],t)}for(const e of Object.keys(this.metadata)){const t=Object.keys(this.inheritableMetadata).includes(e);n.addMetadata({[e]:this.metadata[e]},t)}for(const e of t)n.handlers.filter(e=>"console_callback_handler"===e.name).some(t=>t.name===e.name)||n.addHandler(e,r);return n}static fromHandlers(e){const t=new this;return t.addHandler(new class extends Zy{name=By();constructor(){super(),Object.assign(this,e)}}),t}static configure(e,t,r,n,a,i,s){return this._configureSync(e,t,r,n,a,i,s)}static _configureSync(t,r,n,a,i,s,o){let c;(t||r)&&(Array.isArray(t)||!t?(c=new e,c.setHandlers(t?.map(b_)??[],!0)):c=t,c=c.copy(Array.isArray(r)?r.map(b_):r?.handlers,!1));const l="true"===$y("LANGCHAIN_VERBOSE")||o?.verbose,u=a_.getTraceableRunTree()?.tracingEnabled||!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>"true"===$y(e)),d=u||($y("LANGCHAIN_TRACING")??!1);if(l||d){if(c||(c=new e),l&&!c.handlers.some(e=>e.name===Yb.prototype.name)){const e=new Yb;c.addHandler(e,!0)}if(d&&!c.handlers.some(e=>"langchain_tracer"===e.name)&&u){const e=new a_;c.addHandler(e,!0)}if(u){const e=a_.getTraceableRunTree();if(e&&void 0===c._parentRunId){c._parentRunId=e.id;const t=c.handlers.find(e=>"langchain_tracer"===e.name);t?.updateFromRunTree(e)}}}for(const{contextVar:t,inheritable:r=!0,handlerClass:n,envVar:a}of l_(u_)||[]){const i=a&&"true"===$y(a)&&n;let s;const o=void 0!==t?l_(t):void 0;o&&Jy(o)?s=o:i&&(s=new n({})),void 0!==s&&(c||(c=new e),c.handlers.some(e=>e.name===s.name)||c.addHandler(s,r))}return(n||a)&&c&&(c.addTags(n??[]),c.addTags(a??[],!1)),(i||s)&&c&&(c.addMetadata(i??{}),c.addMetadata(s??{},!1)),c}};function b_(e){return"name"in e?e:Zy.fromMethods(e)}var __=class{getStore(){}run(e,t){return t()}enterWith(e){}};const w_=new __,S_=Symbol.for("lc:child_config");const N_=new class{getInstance(){return ky()??w_}getRunnableConfig(){const e=this.getInstance();return e.getStore()?.extra?.[S_]}runWithConfig(e,t,r){const n=v_._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),a=this.getInstance(),i=a.getStore(),s=n?.getParentRunId(),o=n?.handlers?.find(e=>"langchain_tracer"===e?.name);let c;return o&&s?c=o.getRunTreeWithTracingConfig(s):r||(c=new Rb({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[S_]:e}),void 0!==i&&void 0!==i[Ny]&&(void 0===c&&(c={}),c[Ny]=i[Ny]),a.run(c,t)}initializeGlobalInstance(e){void 0===ky()&&(e=>{globalThis[Sy]=e})(e)}};yf({},{AsyncLocalStorageProviderSingleton:()=>N_,MockAsyncLocalStorage:()=>__,_CONTEXT_VARIABLES_KEY:()=>Ny});async function k_(e){return v_._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function x_(...e){const t={};for(const r of e.filter(e=>!!e))for(const e of Object.keys(r))if("metadata"===e)t[e]={...t[e],...r[e]};else if("tags"===e){const n=t[e]??[];t[e]=[...new Set(n.concat(r[e]??[]))]}else if("configurable"===e)t[e]={...t[e],...r[e]};else if("timeout"===e)void 0===t.timeout?t.timeout=r.timeout:void 0!==r.timeout&&(t.timeout=Math.min(t.timeout,r.timeout));else if("signal"===e)void 0===t.signal?t.signal=r.signal:void 0!==r.signal&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,r.signal]):t.signal=r.signal);else if("callbacks"===e){const e=t.callbacks,n=r.callbacks;if(Array.isArray(n))if(e)if(Array.isArray(e))t.callbacks=e.concat(n);else{const r=e.copy();for(const e of n)r.addHandler(b_(e),!0);t.callbacks=r}else t.callbacks=n;else if(n)if(e)if(Array.isArray(e)){const r=n.copy();for(const t of e)r.addHandler(b_(t),!0);t.callbacks=r}else t.callbacks=new v_(n._parentRunId,{handlers:e.handlers.concat(n.handlers),inheritableHandlers:e.inheritableHandlers.concat(n.inheritableHandlers),tags:Array.from(new Set(e.tags.concat(n.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(n.inheritableTags))),metadata:{...e.metadata,...n.metadata}});else t.callbacks=n}else{const n=e;t[n]=r[n]??t[n]}return t}const E_=new Set(["string","number","boolean"]);function P_(e){const t=N_.getRunnableConfig();let r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){const{runId:e,runName:n,...a}=t;r=Object.entries(a).reduce((e,[t,r])=>(void 0!==r&&(e[t]=r),e),r)}if(e&&(r=Object.entries(e).reduce((e,[t,r])=>(void 0!==r&&(e[t]=r),e),r)),r?.configurable)for(const e of Object.keys(r.configurable))E_.has(typeof r.configurable[e])&&!r.metadata?.[e]&&(r.metadata||(r.metadata={}),r.metadata[e]=r.configurable[e]);if(void 0!==r.timeout){if(r.timeout<=0)throw new Error("Timeout must be a positive number");const e=AbortSignal.timeout(r.timeout);void 0!==r.signal?"any"in AbortSignal&&(r.signal=AbortSignal.any([r.signal,e])):r.signal=e,delete r.timeout}return r}function C_(e={},{callbacks:t,maxConcurrency:r,recursionLimit:n,runName:a,configurable:i,runId:s}={}){const o=P_(e);return void 0!==t&&(delete o.runName,o.callbacks=t),void 0!==n&&(o.recursionLimit=n),void 0!==r&&(o.maxConcurrency=r),void 0!==a&&(o.runName=a),void 0!==i&&(o.configurable={...o.configurable,...i}),void 0!==s&&delete o.runId,o}function A_(e){return e?{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal}:void 0}async function I_(e,t){if(void 0===t)return e;let r;return Promise.race([e.catch(e=>{if(!t?.aborted)throw e}),new Promise((e,n)=>{r=()=>{n(O_(t))},t.addEventListener("abort",r),t.aborted&&n(O_(t))})]).finally(()=>t.removeEventListener("abort",r))}function O_(e){return e?.reason instanceof Error?e.reason:"string"==typeof e?.reason?new Error(e.reason):new Error("Aborted")}yf({},{AsyncGeneratorWithSetup:()=>R_,IterableReadableStream:()=>T_,atee:()=>$_,concat:()=>z_,pipeGeneratorWithSetup:()=>L_});var T_=class e extends ReadableStream{reader;ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const e=await this.reader.read();return e.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){const e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){const e=this.reader.cancel();this.reader.releaseLock(),await e}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(t){const r=t.getReader();return new e({start:e=>function t(){return r.read().then(({done:r,value:n})=>{if(!r)return e.enqueue(n),t();e.close()})}(),cancel(){r.releaseLock()}})}static fromAsyncGenerator(t){return new e({async pull(e){const{value:r,done:n}=await t.next();n&&e.close(),e.enqueue(r)},async cancel(e){await t.return(e)}})}};function $_(e,t=2){const r=Array.from({length:t},()=>[]);return r.map(async function*(t){for(;;)if(0===t.length){const t=await e.next();for(const e of r)e.push(t)}else{if(t[0].done)return;yield t.shift().value}})}function z_(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if("string"==typeof e&&"string"==typeof t)return e+t;if("number"==typeof e&&"number"==typeof t)return e+t;if("concat"in e&&"function"==typeof e.concat)return e.concat(t);if("object"==typeof e&&"object"==typeof t){const r={...e};for(const[e,n]of Object.entries(t))e in r&&!Array.isArray(r[e])?r[e]=z_(r[e],n):r[e]=n;return r}throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}var R_=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(e){this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,r)=>{N_.runWithConfig(A_(e.config),async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,r):this.firstResult.then(e=>t(void 0),r)},!0)})}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?N_.runWithConfig(A_(this.config),this.signal?async()=>I_(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function L_(e,t,r,n,...a){const i=new R_({generator:t,startSetup:r,signal:n}),s=await i.setup;return{output:e(i,s,...a),setup:s}}const M_=Object.prototype.hasOwnProperty;function D_(e,t){return M_.call(e,t)}function j_(e){if(Array.isArray(e)){const t=new Array(e.length);for(let e=0;e<t.length;e++)t[e]=""+e;return t}if(Object.keys)return Object.keys(e);let t=[];for(let r in e)D_(e,r)&&t.push(r);return t}function F_(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function U_(e){let t=0;const r=e.length;let n;for(;t<r;){if(n=e.charCodeAt(t),!(n>=48&&n<=57))return!1;t++}return!0}function q_(e){return-1===e.indexOf("/")&&-1===e.indexOf("~")?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function B_(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function V_(e){if(void 0===e)return!0;if(e)if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(V_(e[t]))return!0}else if("object"==typeof e){const r=j_(e),n=r.length;for(var t=0;t<n;t++)if(V_(e[r[t]]))return!0}return!1}function G_(e,t){const r=[e];for(const e in t){const n="object"==typeof t[e]?JSON.stringify(t[e],null,2):t[e];void 0!==n&&r.push(`${e}: ${n}`)}return r.join("\n")}var H_=class extends Error{constructor(e,t,r,n,a){super(G_(e,{name:t,index:r,operation:n,tree:a})),this.name=t,this.index=r,this.operation=n,this.tree=a,Object.setPrototypeOf(this,new.target.prototype),this.message=G_(e,{name:t,index:r,operation:n,tree:a})}},K_={};yf(K_,{JsonPatchError:()=>W_,_areEquals:()=>aw,applyOperation:()=>X_,applyPatch:()=>ew,applyReducer:()=>tw,deepClone:()=>Z_,getValueByPointer:()=>Q_,validate:()=>nw,validator:()=>rw});const W_=H_,Z_=F_,J_={add:function(e,t,r){return e[t]=this.value,{newDocument:r}},remove:function(e,t,r){var n=e[t];return delete e[t],{newDocument:r,removed:n}},replace:function(e,t,r){var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:function(e,t,r){let n=Q_(r,this.path);n&&(n=F_(n));const a=X_(r,{op:"remove",path:this.from}).removed;return X_(r,{op:"add",path:this.path,value:a}),{newDocument:r,removed:n}},copy:function(e,t,r){const n=Q_(r,this.from);return X_(r,{op:"add",path:this.path,value:F_(n)}),{newDocument:r}},test:function(e,t,r){return{newDocument:r,test:aw(e[t],this.value)}},_get:function(e,t,r){return this.value=e[t],{newDocument:r}}};var Y_={add:function(e,t,r){return U_(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:r,index:t}},remove:function(e,t,r){return{newDocument:r,removed:e.splice(t,1)[0]}},replace:function(e,t,r){var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:J_.move,copy:J_.copy,test:J_.test,_get:J_._get};function Q_(e,t){if(""==t)return e;var r={op:"_get",path:t};return X_(e,r),r.value}function X_(e,t,r=!1,n=!0,a=!0,i=0){if(r&&("function"==typeof r?r(t,0,e,t.path):rw(t,0)),""===t.path){let n={newDocument:e};if("add"===t.op)return n.newDocument=t.value,n;if("replace"===t.op)return n.newDocument=t.value,n.removed=e,n;if("move"===t.op||"copy"===t.op)return n.newDocument=Q_(e,t.from),"move"===t.op&&(n.removed=e),n;if("test"===t.op){if(n.test=aw(e,t.value),!1===n.test)throw new W_("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return n.newDocument=e,n}if("remove"===t.op)return n.removed=e,n.newDocument=null,n;if("_get"===t.op)return t.value=e,n;if(r)throw new W_("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,t,e);return n}{n||(e=F_(e));const s=(t.path||"").split("/");let o,c,l,u=e,d=1,p=s.length;for(l="function"==typeof r?r:rw;;){if(c=s[d],c&&-1!=c.indexOf("~")&&(c=B_(c)),a&&("__proto__"==c||"prototype"==c&&d>0&&"constructor"==s[d-1]))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&void 0===o&&(void 0===u[c]?o=s.slice(0,d).join("/"):d==p-1&&(o=t.path),void 0!==o&&l(t,0,e,o)),d++,Array.isArray(u)){if("-"===c)c=u.length;else{if(r&&!U_(c))throw new W_("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,t,e);U_(c)&&(c=~~c)}if(d>=p){if(r&&"add"===t.op&&c>u.length)throw new W_("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,t,e);const n=Y_[t.op].call(t,u,c,e);if(!1===n.test)throw new W_("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return n}}else if(d>=p){const r=J_[t.op].call(t,u,c,e);if(!1===r.test)throw new W_("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return r}if(u=u[c],r&&d<p&&(!u||"object"!=typeof u))throw new W_("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,t,e)}}}function ew(e,t,r,n=!0,a=!0){if(r&&!Array.isArray(t))throw new W_("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(e=F_(e));const i=new Array(t.length);for(let n=0,s=t.length;n<s;n++)i[n]=X_(e,t[n],r,!0,a,n),e=i[n].newDocument;return i.newDocument=e,i}function tw(e,t,r){const n=X_(e,t);if(!1===n.test)throw new W_("Test operation failed","TEST_OPERATION_FAILED",r,t,e);return n.newDocument}function rw(e,t,r,n){if("object"!=typeof e||null===e||Array.isArray(e))throw new W_("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,r);if(!J_[e.op])throw new W_("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,r);if("string"!=typeof e.path)throw new W_("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,r);if(0!==e.path.indexOf("/")&&e.path.length>0)throw new W_('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);if(("move"===e.op||"copy"===e.op)&&"string"!=typeof e.from)throw new W_("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&void 0===e.value)throw new W_("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,r);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&V_(e.value))throw new W_("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,r);if(r)if("add"==e.op){var a=e.path.split("/").length,i=n.split("/").length;if(a!==i+1&&a!==i)throw new W_("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,r)}else if("replace"===e.op||"remove"===e.op||"_get"===e.op){if(e.path!==n)throw new W_("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,r)}else if("move"===e.op||"copy"===e.op){var s=nw([{op:"_get",path:e.from,value:void 0}],r);if(s&&"OPERATION_PATH_UNRESOLVABLE"===s.name)throw new W_("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,r)}}function nw(e,t,r){try{if(!Array.isArray(e))throw new W_("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)ew(F_(t),F_(e),r||!0);else{r=r||rw;for(var n=0;n<e.length;n++)r(e[n],n,t,void 0)}}catch(e){if(e instanceof W_)return e;throw e}}function aw(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){var r,n,a,i=Array.isArray(e),s=Array.isArray(t);if(i&&s){if((n=e.length)!=t.length)return!1;for(r=n;0!==r--;)if(!aw(e[r],t[r]))return!1;return!0}if(i!=s)return!1;var o=Object.keys(e);if((n=o.length)!==Object.keys(t).length)return!1;for(r=n;0!==r--;)if(!t.hasOwnProperty(o[r]))return!1;for(r=n;0!==r--;)if(!aw(e[a=o[r]],t[a]))return!1;return!0}return e!=e&&t!=t}function iw(e,t,r,n,a){if(t!==e){"function"==typeof t.toJSON&&(t=t.toJSON());for(var i=j_(t),s=j_(e),o=!1,c=s.length-1;c>=0;c--){var l=e[d=s[c]];if(!D_(t,d)||void 0===t[d]&&void 0!==l&&!1===Array.isArray(t))Array.isArray(e)===Array.isArray(t)?(a&&r.push({op:"test",path:n+"/"+q_(d),value:F_(l)}),r.push({op:"remove",path:n+"/"+q_(d)}),o=!0):(a&&r.push({op:"test",path:n,value:e}),r.push({op:"replace",path:n,value:t}));else{var u=t[d];"object"==typeof l&&null!=l&&"object"==typeof u&&null!=u&&Array.isArray(l)===Array.isArray(u)?iw(l,u,r,n+"/"+q_(d),a):l!==u&&(a&&r.push({op:"test",path:n+"/"+q_(d),value:F_(l)}),r.push({op:"replace",path:n+"/"+q_(d),value:F_(u)}))}}if(o||i.length!=s.length)for(c=0;c<i.length;c++){var d;D_(e,d=i[c])||void 0===t[d]||r.push({op:"add",path:n+"/"+q_(d),value:F_(t[d])})}}}function sw(e,t,r=!1){var n=[];return iw(e,t,n,"",r),n}yf({},{LogStreamCallbackHandler:()=>pw,RunLog:()=>cw,RunLogPatch:()=>ow,isLogStreamHandler:()=>lw});var ow=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){const t=this.ops.concat(e.ops),r=ew({},t);return new cw({ops:t,state:r[r.length-1].newDocument})}},cw=class e extends ow{state;constructor(e){super(e),this.state=e.state}concat(t){const r=this.ops.concat(t.ops),n=ew(this.state,t.ops);return new e({ops:r,state:n[n.length-1].newDocument})}static fromRunLogPatch(t){const r=ew({},t.ops);return new e({ops:t.ops,state:r[r.length-1].newDocument})}};const lw=e=>"log_stream_tracer"===e.name;async function uw(e,t){if("original"===t)throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:r}=e;return["retriever","llm","prompt"].includes(e.run_type)?r:1!==Object.keys(r).length||""!==r?.input?r.input:void 0}async function dw(e,t){const{outputs:r}=e;return"original"===t||["retriever","llm","prompt"].includes(e.run_type)?r:void 0!==r&&1===Object.keys(r).length&&void 0!==r?.output?r.output:r}var pw=class extends qb{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat="original";rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name="log_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=T_.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;const t=e.tags??[];let r=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.run_type)),void 0!==this.includeTags&&(r=r||void 0!==t.find(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.run_type)),void 0!==this.excludeTags&&(r=r&&t.every(e=>!this.excludeTags?.includes(e))),r}async*tapOutputIterable(e,t){for await(const r of t){if(e!==this.rootId){const t=this.keyMapByRunId[e];t&&await this.writer.write(new ow({ops:[{op:"add",path:`/logs/${t}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(void 0===this.rootId&&(this.rootId=e.id,await this.writer.write(new ow({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;void 0===this.counterMapByRunName[e.name]&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;const t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=1===t?e.name:`${e.name}:${t}`;const r={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};"streaming_events"===this._schemaFormat&&(r.inputs=await uw(e,this._schemaFormat)),await this.writer.write(new ow({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{const t=this.keyMapByRunId[e.id];if(void 0===t)return;const r=[];"streaming_events"===this._schemaFormat&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await uw(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await dw(e,this._schemaFormat)}),void 0!==e.end_time&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});const n=new ow({ops:r});await this.writer.write(n)}finally{if(e.id===this.rootId){const t=new ow({ops:[{op:"replace",path:"/final_output",value:await dw(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){const n=this.keyMapByRunId[e.id];if(void 0===n)return;let a;var i;void 0!==e.inputs.messages?(i=r?.chunk,a=void 0!==i&&void 0!==i.message?r?.chunk:new Hg({id:`run-${e.id}`,content:t})):a=t;const s=new ow({ops:[{op:"add",path:`/logs/${n}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${n}/streamed_output/-`,value:a}]});await this.writer.write(s)}};yf({},{ChatGenerationChunk:()=>fw,GenerationChunk:()=>hw,RUN_KEY:()=>mw});const mw="__run";var hw=class e{text;generationInfo;constructor(e){this.text=e.text,this.generationInfo=e.generationInfo}concat(t){return new e({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},fw=class e extends hw{message;constructor(e){super(e),this.message=e.message}concat(t){return new e({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};function gw({name:e,serialized:t}){return void 0!==e?e:void 0!==t?.name?t.name:void 0!==t?.id&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}const yw=e=>"event_stream_tracer"===e.name;var vw=class extends qb{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;name="event_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=T_.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){const t=e.tags??[];let r=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.runType)),void 0!==this.includeTags&&(r=r||void 0!==t.find(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.runType)),void 0!==this.excludeTags&&(r=r&&t.every(e=>!this.excludeTags?.includes(e))),r}async*tapOutputIterable(e,t){const r=await t.next();if(r.done)return;const n=this.runInfoMap.get(e);if(void 0===n)return void(yield r.value);function a(e,t){return"llm"===e&&"string"==typeof t?new hw({text:t}):t}let i=this.tappedPromises.get(e);if(void 0===i){let s;i=new Promise(e=>{s=e}),this.tappedPromises.set(e,i);try{const i={event:`on_${n.runType}_stream`,run_id:e,name:n.name,tags:n.tags,metadata:n.metadata,data:{}};await this.send({...i,data:{chunk:a(n.runType,r.value)}},n),yield r.value;for await(const e of t)"tool"!==n.runType&&"retriever"!==n.runType&&await this.send({...i,data:{chunk:a(n.runType,e)}},n),yield e}finally{s?.()}}else{yield r.value;for await(const e of t)yield e}}async send(e,t){this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){const r=this.tappedPromises.get(e.run_id);void 0!==r?r.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){const t=gw(e),r=void 0!==e.inputs.messages?"chat_model":"llm",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,n);const a=`on_${r}_start`;await this.send({event:a,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onLLMNewToken(e,t,r){const n=this.runInfoMap.get(e.id);let a,i;if(void 0===n)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(1!==this.runInfoMap.size){if("chat_model"===n.runType)i="on_chat_model_stream",a=void 0===r?.chunk?new Hg({content:t,id:`run-${e.id}`}):r.chunk.message;else{if("llm"!==n.runType)throw new Error(`Unexpected run type ${n.runType}`);i="on_llm_stream",a=void 0===r?.chunk?new hw({text:t}):r.chunk}await this.send({event:i,data:{chunk:a},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}}async onLLMEnd(e){const t=this.runInfoMap.get(e.id);let r;if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);const n=e.outputs?.generations;let a;if("chat_model"===t.runType){for(const e of n??[]){if(void 0!==a)break;a=e[0]?.message}r="on_chat_model_end"}else{if("llm"!==t.runType)throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);a={generations:n?.map(e=>e.map(e=>({text:e.text,generationInfo:e.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},r="on_llm_end"}await this.sendEndEvent({event:r,data:{output:a,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){const t=gw(e),r=e.run_type??"chain",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type};let a={};""===e.inputs.input&&1===Object.keys(e.inputs).length?(a={},n.inputs={}):void 0!==e.inputs.input?(a.input=e.inputs.input,n.inputs=e.inputs.input):(a.input=e.inputs,n.inputs=e.inputs),this.runInfoMap.set(e.id,n),await this.send({event:`on_${r}_start`,data:a,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onChainEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);const r=`on_${e.run_type}_end`,n=e.inputs??t.inputs??{},a={output:e.outputs?.output??e.outputs,input:n};n.input&&1===Object.keys(n).length&&(a.input=n.input,t.inputs=n.input),await this.sendEndEvent({event:r,data:a,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){const t=gw(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,r),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},r)}async onToolEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(void 0===t.inputs)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);const r=void 0===e.outputs?.output?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){const t=gw(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,r),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onRetrieverEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,r){const n=this.runInfoMap.get(r);if(void 0===n)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:n.tags,metadata:n.metadata,data:t},n)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}};yf({},{AsyncCaller:()=>ww});const bw=[400,401,402,403,404,405,406,407,409],_w=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||"AbortError"===e.name)throw e;if("ECONNABORTED"===e?.code)throw e;const t=e?.response?.status??e?.status;if(t&&bw.includes(+t))throw e;if("insufficient_quota"===e?.error?.code){const t=new Error(e?.message);throw t.name="InsufficientQuotaError",t}};var ww=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??_w;const t="default"in eb?eb.default:eb;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>jv(()=>e(...t).catch(e=>{throw e instanceof Error?e:new Error(e)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){if(e.signal){let n;return Promise.race([this.call(t,...r),new Promise((t,r)=>{n=()=>{r(O_(e.signal))},e.signal?.addEventListener("abort",n)})]).finally(()=>{e.signal&&n&&e.signal.removeEventListener("abort",n)})}return this.call(t,...r)}fetch(...e){return this.call(()=>fetch(...e).then(e=>e.ok?e:Promise.reject(e)))}},Sw=class extends qb{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:e,onStart:t,onEnd:r,onError:n}){super({_awaitHandler:!0}),this.config=e,this.argOnStart=t,this.argOnEnd=r,this.argOnError=n}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}};function Nw(e){return!!e&&e.lc_runnable}var kw=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(e){this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let r=void 0===this.includeNames&&void 0===this.includeTypes&&void 0===this.includeTags;const n=e.tags??[];return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(t)),void 0!==this.includeTags&&(r=r||n.some(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(t)),void 0!==this.excludeTags&&(r=r&&n.every(e=>!this.excludeTags?.includes(e))),r}};function xw(e,t,r){function n(r,n){var a;Object.defineProperty(r,"_zod",{value:r._zod??{},enumerable:!1}),(a=r._zod).traits??(a.traits=new Set),r._zod.traits.add(e),t(r,n);for(const e in s.prototype)e in r||Object.defineProperty(r,e,{value:s.prototype[e].bind(r)});r._zod.constr=s,r._zod.def=n}const a=r?.Parent??Object;class i extends a{}function s(e){var t;const a=r?.Parent?new i:this;n(a,e),(t=a._zod).deferred??(t.deferred=[]);for(const e of a._zod.deferred)e();return a}return Object.defineProperty(i,"name",{value:e}),Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class Ew extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Pw={};function Cw(e){return Pw}function Aw(e,t){return"bigint"==typeof t?t.toString():t}const Iw=Symbol("evaluating");function Ow(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==Iw)return void 0===n&&(n=Iw,n=r()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function Tw(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function $w(...e){const t={};for(const r of e){const e=Object.getOwnPropertyDescriptors(r);Object.assign(t,e)}return Object.defineProperties({},t)}const zw="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Rw(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Lw(e,t,r){const n=new e._zod.constr(t??e._zod.def);return t&&!r?.parent||(n._zod.parent=e),n}function Mw(e,t){if(!function(e){if(!1===Rw(e))return!1;const t=e.constructor;if(void 0===t)return!0;const r=t.prototype;return!1!==Rw(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}(t))throw new Error("Invalid input to extend: expected a plain object");const r=e._zod.def.checks;if(r&&r.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const n=$w(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return Tw(this,"shape",r),r},checks:[]});return Lw(e,n)}function Dw(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(!0!==e.issues[r]?.continue)return!0;return!1}function jw(e){return"string"==typeof e?e:e?.message}function Fw(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const a=jw(e.inst?._zod.def?.error?.(e))??jw(t?.error?.(e))??jw(r.customError?.(e))??jw(r.localeError?.(e))??"Invalid input";n.message=a}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}const Uw=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Aw,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},qw=xw("$ZodError",Uw),Bw=xw("$ZodError",Uw,{Parent:Error});function Vw(e){const t=[],r=e.map(e=>"object"==typeof e?e.key:e);for(const e of r)"number"==typeof e?t.push(`[${e}]`):"symbol"==typeof e?t.push(`[${JSON.stringify(String(e))}]`):/[^\w$]/.test(e)?t.push(`[${JSON.stringify(e)}]`):(t.length&&t.push("."),t.push(e));return t.join("")}const Gw=(e=>(t,r,n,a)=>{const i=n?Object.assign(n,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Ew;if(s.issues.length){const t=new(a?.Err??e)(s.issues.map(e=>Fw(e,i,Cw())));throw zw(t,a?.callee),t}return s.value})(Bw),Hw=(e=>async(t,r,n,a)=>{const i=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){const t=new(a?.Err??e)(s.issues.map(e=>Fw(e,i,Cw())));throw zw(t,a?.callee),t}return s.value})(Bw),Kw=(e=>(t,r,n)=>{const a=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise)throw new Ew;return i.issues.length?{success:!1,error:new(e??qw)(i.issues.map(e=>Fw(e,a,Cw())))}:{success:!0,data:i.value}})(Bw),Ww=(e=>async(t,r,n)=>{const a=n?Object.assign(n,{async:!0}):{async:!0};let i=t._zod.run({value:r,issues:[]},a);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(e=>Fw(e,a,Cw())))}:{success:!0,data:i.value}})(Bw),Zw={major:4,minor:1,patch:12},Jw=xw("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Zw;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const t of n)for(const r of t._zod.onattach)r(e);if(0===n.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,r)=>{let n,a=Dw(e);for(const i of t){if(i._zod.def.when){if(!i._zod.def.when(e))continue}else if(a)continue;const t=e.issues.length,s=i._zod.check(e);if(s instanceof Promise&&!1===r?.async)throw new Ew;if(n||s instanceof Promise)n=(n??Promise.resolve()).then(async()=>{await s;e.issues.length!==t&&(a||(a=Dw(e,t)))});else{if(e.issues.length===t)continue;a||(a=Dw(e,t))}}return n?n.then(()=>e):e},r=(r,a,i)=>{if(Dw(r))return r.aborted=!0,r;const s=t(a,n,i);if(s instanceof Promise){if(!1===i.async)throw new Ew;return s.then(t=>e._zod.parse(t,i))}return e._zod.parse(s,i)};e._zod.run=(a,i)=>{if(i.skipChecks)return e._zod.parse(a,i);if("backward"===i.direction){const t=e._zod.parse({value:a.value,issues:[]},{...i,skipChecks:!0});return t instanceof Promise?t.then(e=>r(e,a,i)):r(t,a,i)}const s=e._zod.parse(a,i);if(s instanceof Promise){if(!1===i.async)throw new Ew;return s.then(e=>t(e,n,i))}return t(s,n,i)}}e["~standard"]={validate:t=>{try{const r=Kw(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return Ww(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),Yw=xw("$ZodUnknown",(e,t)=>{Jw.init(e,t),e._zod.parse=e=>e}),Qw=xw("$ZodNever",(e,t)=>{Jw.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function Xw(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const eS=xw("$ZodOptional",(e,t)=>{Jw.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ow(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ow(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${function(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>{if("optional"===t.innerType._zod.optin){const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(t=>Xw(t,e.value)):Xw(n,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,r)}});class tS{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const r=t[0];if(this._map.set(e,r),r&&"object"==typeof r&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};delete r.id;const n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function rS(){return new tS}const nS=rS();class aS{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??nS,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var r;const n=e._zod.def,a={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i){i.count++;return t.schemaPath.includes(e)&&(i.cycle=t.path),i.schema}const s={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,s);const o=e._zod.toJSONSchema?.();if(o)s.schema=o;else{const r={...t,schemaPath:[...t.schemaPath,e],path:t.path},i=e._zod.parent;if(i)s.ref=i,this.process(i,r),this.seen.get(i).isParent=!0;else{const t=s.schema;switch(n.type){case"string":{const r=t;r.type="string";const{minimum:n,maximum:i,format:o,patterns:c,contentEncoding:l}=e._zod.bag;if("number"==typeof n&&(r.minLength=n),"number"==typeof i&&(r.maxLength=i),o&&(r.format=a[o]??o,""===r.format&&delete r.format),l&&(r.contentEncoding=l),c&&c.size>0){const e=[...c];1===e.length?r.pattern=e[0].source:e.length>1&&(s.schema.allOf=[...e.map(e=>({..."draft-7"===this.target||"draft-4"===this.target||"openapi-3.0"===this.target?{type:"string"}:{},pattern:e.source}))])}break}case"number":{const r=t,{minimum:n,maximum:a,format:i,multipleOf:s,exclusiveMaximum:o,exclusiveMinimum:c}=e._zod.bag;"string"==typeof i&&i.includes("int")?r.type="integer":r.type="number","number"==typeof c&&("draft-4"===this.target||"openapi-3.0"===this.target?(r.minimum=c,r.exclusiveMinimum=!0):r.exclusiveMinimum=c),"number"==typeof n&&(r.minimum=n,"number"==typeof c&&"draft-4"!==this.target&&(c>=n?delete r.minimum:delete r.exclusiveMinimum)),"number"==typeof o&&("draft-4"===this.target||"openapi-3.0"===this.target?(r.maximum=o,r.exclusiveMaximum=!0):r.exclusiveMaximum=o),"number"==typeof a&&(r.maximum=a,"number"==typeof o&&"draft-4"!==this.target&&(o<=a?delete r.maximum:delete r.exclusiveMaximum)),"number"==typeof s&&(r.multipleOf=s);break}case"boolean":t.type="boolean";break;case"bigint":if("throw"===this.unrepresentable)throw new Error("BigInt cannot be represented in JSON Schema");break;case"symbol":if("throw"===this.unrepresentable)throw new Error("Symbols cannot be represented in JSON Schema");break;case"null":"openapi-3.0"===this.target?(t.type="string",t.nullable=!0,t.enum=[null]):t.type="null";break;case"any":case"unknown":break;case"undefined":if("throw"===this.unrepresentable)throw new Error("Undefined cannot be represented in JSON Schema");break;case"void":if("throw"===this.unrepresentable)throw new Error("Void cannot be represented in JSON Schema");break;case"never":t.not={};break;case"date":if("throw"===this.unrepresentable)throw new Error("Date cannot be represented in JSON Schema");break;case"array":{const a=t,{minimum:i,maximum:s}=e._zod.bag;"number"==typeof i&&(a.minItems=i),"number"==typeof s&&(a.maxItems=s),a.type="array",a.items=this.process(n.element,{...r,path:[...r.path,"items"]});break}case"object":{const e=t;e.type="object",e.properties={};const a=n.shape;for(const t in a)e.properties[t]=this.process(a[t],{...r,path:[...r.path,"properties",t]});const i=new Set(Object.keys(a)),s=new Set([...i].filter(e=>{const t=n.shape[e]._zod;return"input"===this.io?void 0===t.optin:void 0===t.optout}));s.size>0&&(e.required=Array.from(s)),"never"===n.catchall?._zod.def.type?e.additionalProperties=!1:n.catchall?n.catchall&&(e.additionalProperties=this.process(n.catchall,{...r,path:[...r.path,"additionalProperties"]})):"output"===this.io&&(e.additionalProperties=!1);break}case"union":{const e=t,a=n.options.map((e,t)=>this.process(e,{...r,path:[...r.path,"anyOf",t]}));e.anyOf=a;break}case"intersection":{const e=t,a=this.process(n.left,{...r,path:[...r.path,"allOf",0]}),i=this.process(n.right,{...r,path:[...r.path,"allOf",1]}),s=e=>"allOf"in e&&1===Object.keys(e).length,o=[...s(a)?a.allOf:[a],...s(i)?i.allOf:[i]];e.allOf=o;break}case"tuple":{const a=t;a.type="array";const i="draft-2020-12"===this.target?"prefixItems":"items",s="draft-2020-12"===this.target||"openapi-3.0"===this.target?"items":"additionalItems",o=n.items.map((e,t)=>this.process(e,{...r,path:[...r.path,i,t]})),c=n.rest?this.process(n.rest,{...r,path:[...r.path,s,..."openapi-3.0"===this.target?[n.items.length]:[]]}):null;"draft-2020-12"===this.target?(a.prefixItems=o,c&&(a.items=c)):"openapi-3.0"===this.target?(a.items={anyOf:o},c&&a.items.anyOf.push(c),a.minItems=o.length,c||(a.maxItems=o.length)):(a.items=o,c&&(a.additionalItems=c));const{minimum:l,maximum:u}=e._zod.bag;"number"==typeof l&&(a.minItems=l),"number"==typeof u&&(a.maxItems=u);break}case"record":{const e=t;e.type="object","draft-7"!==this.target&&"draft-2020-12"!==this.target||(e.propertyNames=this.process(n.keyType,{...r,path:[...r.path,"propertyNames"]})),e.additionalProperties=this.process(n.valueType,{...r,path:[...r.path,"additionalProperties"]});break}case"map":if("throw"===this.unrepresentable)throw new Error("Map cannot be represented in JSON Schema");break;case"set":if("throw"===this.unrepresentable)throw new Error("Set cannot be represented in JSON Schema");break;case"enum":{const e=t,r=function(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t)}(n.entries);r.every(e=>"number"==typeof e)&&(e.type="number"),r.every(e=>"string"==typeof e)&&(e.type="string"),e.enum=r;break}case"literal":{const e=t,r=[];for(const e of n.values)if(void 0===e){if("throw"===this.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof e){if("throw"===this.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");r.push(Number(e))}else r.push(e);if(0===r.length);else if(1===r.length){const t=r[0];e.type=null===t?"null":typeof t,"draft-4"===this.target||"openapi-3.0"===this.target?e.enum=[t]:e.const=t}else r.every(e=>"number"==typeof e)&&(e.type="number"),r.every(e=>"string"==typeof e)&&(e.type="string"),r.every(e=>"boolean"==typeof e)&&(e.type="string"),r.every(e=>null===e)&&(e.type="null"),e.enum=r;break}case"file":{const r=t,n={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:i,mime:s}=e._zod.bag;void 0!==a&&(n.minLength=a),void 0!==i&&(n.maxLength=i),s?1===s.length?(n.contentMediaType=s[0],Object.assign(r,n)):r.anyOf=s.map(e=>({...n,contentMediaType:e})):Object.assign(r,n);break}case"transform":if("throw"===this.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema");break;case"nullable":{const e=this.process(n.innerType,r);"openapi-3.0"===this.target?(s.ref=n.innerType,t.nullable=!0):t.anyOf=[e,{type:"null"}];break}case"nonoptional":case"promise":case"optional":this.process(n.innerType,r),s.ref=n.innerType;break;case"success":t.type="boolean";break;case"default":this.process(n.innerType,r),s.ref=n.innerType,t.default=JSON.parse(JSON.stringify(n.defaultValue));break;case"prefault":this.process(n.innerType,r),s.ref=n.innerType,"input"===this.io&&(t._prefault=JSON.parse(JSON.stringify(n.defaultValue)));break;case"catch":{let e;this.process(n.innerType,r),s.ref=n.innerType;try{e=n.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}t.default=e;break}case"nan":if("throw"===this.unrepresentable)throw new Error("NaN cannot be represented in JSON Schema");break;case"template_literal":{const r=t,n=e._zod.pattern;if(!n)throw new Error("Pattern not found in template literal");r.type="string",r.pattern=n.source;break}case"pipe":{const e="input"===this.io?"transform"===n.in._zod.def.type?n.out:n.in:n.out;this.process(e,r),s.ref=e;break}case"readonly":this.process(n.innerType,r),s.ref=n.innerType,t.readOnly=!0;break;case"lazy":{const t=e._zod.innerType;this.process(t,r),s.ref=t;break}case"custom":if("throw"===this.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema");break;case"function":if("throw"===this.unrepresentable)throw new Error("Function types cannot be represented in JSON Schema")}}}const c=this.metadataRegistry.get(e);c&&Object.assign(s.schema,c),"input"===this.io&&sS(e)&&(delete s.schema.examples,delete s.schema.default),"input"===this.io&&s.schema._prefault&&((r=s.schema).default??(r.default=s.schema._prefault)),delete s.schema._prefault;return this.seen.get(e).schema}emit(e,t){const r={cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0},n=this.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=e=>{const t="draft-2020-12"===this.target?"$defs":"definitions";if(r.external){const n=r.external.registry.get(e[0])?.id,a=r.external.uri??(e=>e);if(n)return{ref:a(n)};const i=e[1].defId??e[1].schema.id??"schema"+this.counter++;return e[1].defId=i,{defId:i,ref:`${a("__shared")}#/${t}/${i}`}}if(e[1]===n)return{ref:"#"};const a=`#/${t}/`,i=e[1].schema.id??"__schema"+this.counter++;return{defId:i,ref:a+i}},i=e=>{if(e[1].schema.$ref)return;const t=e[1],{ref:r,defId:n}=a(e);t.def={...t.schema},n&&(t.defId=n);const i=t.schema;for(const e in i)delete i[e];i.$ref=r};if("throw"===r.cycles)for(const e of this.seen.entries()){const t=e[1];if(t.cycle)throw new Error(`Cycle detected: #/${t.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const t of this.seen.entries()){const n=t[1];if(e===t[0]){i(t);continue}if(r.external){const n=r.external.registry.get(t[0])?.id;if(e!==t[0]&&n){i(t);continue}}const a=this.metadataRegistry.get(t[0])?.id;a?i(t):(n.cycle||n.count>1&&"ref"===r.reused)&&i(t)}const s=(e,t)=>{const r=this.seen.get(e),n=r.def??r.schema,a={...n};if(null===r.ref)return;const i=r.ref;if(r.ref=null,i){s(i,t);const e=this.seen.get(i).schema;!e.$ref||"draft-7"!==t.target&&"draft-4"!==t.target&&"openapi-3.0"!==t.target?(Object.assign(n,e),Object.assign(n,a)):(n.allOf=n.allOf??[],n.allOf.push(e))}r.isParent||this.override({zodSchema:e,jsonSchema:n,path:r.path??[]})};for(const e of[...this.seen.entries()].reverse())s(e[0],{target:this.target});const o={};if("draft-2020-12"===this.target?o.$schema="https://json-schema.org/draft/2020-12/schema":"draft-7"===this.target?o.$schema="http://json-schema.org/draft-07/schema#":"draft-4"===this.target?o.$schema="http://json-schema.org/draft-04/schema#":"openapi-3.0"===this.target||console.warn(`Invalid target: ${this.target}`),r.external?.uri){const t=r.external.registry.get(e)?.id;if(!t)throw new Error("Schema is missing an `id` property");o.$id=r.external.uri(t)}Object.assign(o,n.def);const c=r.external?.defs??{};for(const e of this.seen.entries()){const t=e[1];t.def&&t.defId&&(c[t.defId]=t.def)}r.external||Object.keys(c).length>0&&("draft-2020-12"===this.target?o.$defs=c:o.definitions=c);try{return JSON.parse(JSON.stringify(o))}catch(e){throw new Error("Error converting schema to JSON.")}}}function iS(e,t){if(e instanceof tS){const r=new aS(t),n={};for(const t of e._idmap.entries()){const[e,n]=t;r.process(n)}const a={},i={registry:e,uri:t?.uri,defs:n};for(const n of e._idmap.entries()){const[e,s]=n;a[e]=r.emit(s,{...t,external:i})}if(Object.keys(n).length>0){const e="draft-2020-12"===r.target?"$defs":"definitions";a.__shared={[e]:n}}return{schemas:a}}const r=new aS(t);return r.process(e),r.emit(e,t)}function sS(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const n=e._zod.def;switch(n.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":case"custom":case"success":case"catch":case"function":return!1;case"array":return sS(n.element,r);case"object":for(const e in n.shape)if(sS(n.shape[e],r))return!0;return!1;case"union":for(const e of n.options)if(sS(e,r))return!0;return!1;case"intersection":return sS(n.left,r)||sS(n.right,r);case"tuple":for(const e of n.items)if(sS(e,r))return!0;return!(!n.rest||!sS(n.rest,r));case"record":case"map":return sS(n.keyType,r)||sS(n.valueType,r);case"set":return sS(n.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":case"default":case"prefault":return sS(n.innerType,r);case"lazy":return sS(n.getter(),r);case"transform":return!0;case"pipe":return sS(n.in,r)||sS(n.out,r)}throw new Error(`Unknown schema type: ${n.type}`)}function oS(e){if("object"!=typeof e||null===e)return!1;if(!("_zod"in e))return!1;const t=e._zod;return"object"==typeof t&&null!==t&&"def"in t}function cS(e){if("object"!=typeof e||null===e)return!1;if(!("_def"in e)||"_zod"in e)return!1;const t=e._def;return"object"==typeof t&&null!=t&&"typeName"in t}function lS(e){return oS(e)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),cS(e)}function uS(e){return!!e&&("object"==typeof e&&(!Array.isArray(e)&&!(!oS(e)&&!cS(e))))}function dS(e){return"object"==typeof e&&null!==e&&"_def"in e&&"object"==typeof e._def&&null!==e._def&&"typeName"in e._def&&"ZodLiteral"===e._def.typeName}function pS(e){return!!oS(e)&&("object"==typeof e&&null!==e&&"_zod"in e&&"object"==typeof e._zod&&null!==e._zod&&"def"in e._zod&&"object"==typeof e._zod.def&&null!==e._zod.def&&"type"in e._zod.def&&"literal"===e._zod.def.type)}function mS(e){return!!dS(e)||!!pS(e)}async function hS(e,t){if(oS(e))try{return{success:!0,data:await Hw(e,t)}}catch(e){return{success:!1,error:e}}if(cS(e))return await e.safeParseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function fS(e,t){if(oS(e))return await Hw(e,t);if(cS(e))return await e.parseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function gS(e,t){if(oS(e))try{return{success:!0,data:Gw(e,t)}}catch(e){return{success:!1,error:e}}if(cS(e))return e.safeParse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function yS(e,t){if(oS(e))return Gw(e,t);if(cS(e))return e.parse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function vS(e){return oS(e)?nS.get(e)?.description:cS(e)||"description"in e&&"string"==typeof e.description?e.description:void 0}function bS(e){if(!uS(e))return!1;if(cS(e)){const t=e._def;if("ZodObject"===t.typeName){const t=e;return!t.shape||0===Object.keys(t.shape).length}if("ZodRecord"===t.typeName)return!0}if(oS(e)){const t=e._zod.def;if("object"===t.type){const t=e;return!t.shape||0===Object.keys(t.shape).length}if("record"===t.type)return!0}return"object"==typeof e&&null!==e&&!("shape"in e)}function _S(e){if(!uS(e))return!1;if(cS(e)){return"ZodString"===e._def.typeName}if(oS(e)){return"string"===e._zod.def.type}return!1}function wS(e){return"object"==typeof e&&null!==e&&"_def"in e&&"object"==typeof e._def&&null!==e._def&&"typeName"in e._def&&"ZodObject"===e._def.typeName}function SS(e){return!!oS(e)&&("object"==typeof e&&null!==e&&"_zod"in e&&"object"==typeof e._zod&&null!==e._zod&&"def"in e._zod&&"object"==typeof e._zod.def&&null!==e._zod.def&&"type"in e._zod.def&&"object"===e._zod.def.type)}function NS(e){return!!oS(e)&&("object"==typeof e&&null!==e&&"_zod"in e&&"object"==typeof e._zod&&null!==e._zod&&"def"in e._zod&&"object"==typeof e._zod.def&&null!==e._zod.def&&"type"in e._zod.def&&"array"===e._zod.def.type)}function kS(e){return!!wS(e)||!!SS(e)}function xS(e){if(cS(e))return e.shape;if(oS(e))return e._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function ES(e,t){if(cS(e))return e.extend(t);if(oS(e))return Mw(e,t);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function PS(e){if(cS(e))return e.partial();if(oS(e))return function(e,t){const r=$w(t._zod.def,{get shape(){const r=t._zod.def.shape,n={...r};for(const t in r)n[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return Tw(this,"shape",n),n},checks:[]});return Lw(t,r)}(eS,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function CS(e,t=!1){if(cS(e))return e.strict();if(SS(e)){const n=e._zod.def.shape;if(t)for(const[r,a]of Object.entries(e._zod.def.shape)){if(SS(a)){const e=CS(a,t);n[r]=e}else if(NS(a)){let e=a._zod.def.element;SS(e)&&(e=CS(e,t)),n[r]=Lw(a,{...a._zod.def,element:e})}else n[r]=a;const e=nS.get(a);e&&nS.add(n[r],e)}const a=Lw(e,{...e._zod.def,shape:n,catchall:(r=Qw,new r({type:"never"}))}),i=nS.get(e);return i&&nS.add(a,i),a}var r;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function AS(e,t=!1){if(wS(e))return e.passthrough();if(SS(e)){const n=e._zod.def.shape;if(t)for(const[r,a]of Object.entries(e._zod.def.shape)){if(SS(a)){const e=AS(a,t);n[r]=e}else if(NS(a)){let e=a._zod.def.element;SS(e)&&(e=AS(e,t)),n[r]=Lw(a,{...a._zod.def,element:e})}else n[r]=a;const e=nS.get(a);e&&nS.add(n[r],e)}const a=Lw(e,{...e._zod.def,shape:n,catchall:(r=Yw,new r({type:"unknown"}))}),i=nS.get(e);return i&&nS.add(a,i),a}var r;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function IS(e){if(cS(e))try{const t=e.parse(void 0);return()=>t}catch{return}if(oS(e))try{const t=Gw(e,void 0);return()=>t}catch{return}}function OS(e,t,r){const n=r.get(e);if(void 0!==n)return n;if(cS(e))return function(e){return cS(e)&&"typeName"in e._def&&"ZodEffects"===e._def.typeName}(e)?OS(e._def.schema,t,r):e;if(oS(e)){let n=e;if(function(e){return oS(e)&&"pipe"===e._zod.def.type}(e)&&(n=OS(e._zod.def.in,t,r)),t)if(SS(n)){const e=n._zod.def.shape;for(const[a,i]of Object.entries(n._zod.def.shape))e[a]=OS(i,t,r);n=Lw(n,{...n._zod.def,shape:e})}else if(NS(n)){const e=OS(n._zod.def.element,t,r);n=Lw(n,{...n._zod.def,element:e})}const a=nS.get(e);return a&&nS.add(n,a),r.set(e,n),n}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function TS(e,t=!1){return OS(e,t,new WeakMap)}function $S(e,t){if(cS(e)){const r=xS(e),n={};for(const[e,a]of Object.entries(r))t(e,a)?n[e]=a.optional():n[e]=a;return e.extend(n)}if(oS(e)){const r=xS(e),n={...e._zod.def.shape};for(const[e,a]of Object.entries(r))t(e,a)&&(n[e]=new eS({type:"optional",innerType:a}));const a=Lw(e,{...e._zod.def,shape:n}),i=nS.get(e);return i&&nS.add(a,i),a}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function zS(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}const RS=["*","_","`"];function LS(e,t,r){const{firstNode:n,lastNode:a,nodeColors:i,withStyles:s=!0,curveStyle:o="linear",wrapLabelNWords:c=9}=r??{};let l=s?`%%{init: {'flowchart': {'curve': '${o}'}}}%%\ngraph TD;\n`:"graph TD;\n";if(s){const t="default",r={[t]:"{0}({1})"};void 0!==n&&(r[n]="{0}([{1}]):::first"),void 0!==a&&(r[a]="{0}([{1}]):::last");for(const[n,a]of Object.entries(e)){const e=a.name.split(":").pop()??"";let i=RS.some(t=>e.startsWith(t)&&e.endsWith(t))?`<p>${e}</p>`:e;Object.keys(a.metadata??{}).length&&(i+=`<hr/><small><em>${Object.entries(a.metadata??{}).map(([e,t])=>`${e} = ${t}`).join("\n")}</em></small>`);const s=(r[n]??r[t]).replace("{0}",zS(n)).replace("{1}",i);l+=`\t${s}\n`}}const u={};for(const e of t){const t=e.source.split(":"),r=e.target.split(":"),n=t.filter((e,t)=>e===r[t]).join(":");u[n]||(u[n]=[]),u[n].push(e)}const d=new Set;function p(e,t){const r=1===e.length&&e[0].source===e[0].target;if(t&&!r){const e=t.split(":").pop();if(d.has(e))throw new Error(`Found duplicate subgraph '${e}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(e),l+=`\tsubgraph ${e}\n`}for(const t of e){const{source:e,target:r,data:n,conditional:a}=t;let i="";if(void 0!==n){let e=n;const t=e.split(" ");t.length>c&&(e=Array.from({length:Math.ceil(t.length/c)},(e,r)=>t.slice(r*c,(r+1)*c).join(" ")).join("&nbsp;<br>&nbsp;")),i=a?` -. &nbsp;${e}&nbsp; .-> `:` -- &nbsp;${e}&nbsp; --\x3e `}else i=a?" -.-> ":" --\x3e ";l+=`\t${zS(e)}${i}${zS(r)};\n`}for(const e in u)e.startsWith(`${t}:`)&&e!==t&&p(u[e],e);t&&!r&&(l+="\tend\n")}p(u[""]??[],"");for(const e in u)e.includes(":")||""===e||p(u[e],e);return s&&(l+=function(e){let t="";for(const[r,n]of Object.entries(e))t+=`\tclassDef ${r} ${n};\n`;return t}(i??{})),l}const MS=Symbol("Let zodToJsonSchema decide on which parser to use"),DS={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,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"},jS=e=>{const t=(e=>({...DS,...e}))(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}]))}},FS=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function US(e){if("openAi"!==e.target)return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?FS(t,e.currentPath):t.join("/")}}function qS(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function BS(e,t,r,n,a){e[t]=r,qS(e,t,n,a)}var VS,GS;!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)},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}(VS||(VS={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(GS||(GS={}));const HS=VS.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),KS=e=>{switch(typeof e){case"undefined":return HS.undefined;case"string":return HS.string;case"number":return Number.isNaN(e)?HS.nan:HS.number;case"boolean":return HS.boolean;case"function":return HS.function;case"bigint":return HS.bigint;case"symbol":return HS.symbol;case"object":return Array.isArray(e)?HS.array:null===e?HS.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?HS.promise:"undefined"!=typeof Map&&e instanceof Map?HS.map:"undefined"!=typeof Set&&e instanceof Set?HS.set:"undefined"!=typeof Date&&e instanceof Date?HS.date:HS.object;default:return HS.unknown}},WS=VS.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"]);class ZS 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=>{for(const a of e.issues)if("invalid_union"===a.code)a.unionErrors.map(n);else if("invalid_return_type"===a.code)n(a.returnTypeError);else if("invalid_arguments"===a.code)n(a.argumentsError);else if(0===a.path.length)r._errors.push(t(a));else{let e=r,n=0;for(;n<a.path.length;){const r=a.path[n];n===a.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(a))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}static assert(e){if(!(e instanceof ZS))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,VS.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t=Object.create(null),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()}}ZS.create=e=>new ZS(e);const JS=(e,t)=>{let r;switch(e.code){case WS.invalid_type:r=e.received===HS.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case WS.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,VS.jsonStringifyReplacer)}`;break;case WS.unrecognized_keys:r=`Unrecognized key(s) in object: ${VS.joinValues(e.keys,", ")}`;break;case WS.invalid_union:r="Invalid input";break;case WS.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${VS.joinValues(e.options)}`;break;case WS.invalid_enum_value:r=`Invalid enum value. Expected ${VS.joinValues(e.options)}, received '${e.received}'`;break;case WS.invalid_arguments:r="Invalid function arguments";break;case WS.invalid_return_type:r="Invalid function return type";break;case WS.invalid_date:r="Invalid date";break;case WS.invalid_string:"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}"`:VS.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case WS.too_small: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 WS.too_big: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 WS.custom:r="Invalid input";break;case WS.invalid_intersection_types:r="Intersection results could not be merged";break;case WS.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case WS.not_finite:r="Number must be finite";break;default:r=t.defaultError,VS.assertNever(e)}return{message:r}};let YS=JS;function QS(e,t){const r=YS,n=(e=>{const{data:t,path:r,errorMaps:n,issueData:a}=e,i=[...r,...a.path||[]],s={...a,path:i};if(void 0!==a.message)return{...a,path:i,message:a.message};let o="";const c=n.filter(e=>!!e).slice().reverse();for(const e of c)o=e(s,{data:t,defaultError:o}).message;return{...a,path:i,message:o}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===JS?void 0:JS].filter(e=>!!e)});e.common.issues.push(n)}class XS{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 eN;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,n=await e.value;r.push({key:t,value:n})}return XS.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:a}=n;if("aborted"===t.status)return eN;if("aborted"===a.status)return eN;"dirty"===t.status&&e.dirty(),"dirty"===a.status&&e.dirty(),"__proto__"===t.value||void 0===a.value&&!n.alwaysSet||(r[t.value]=a.value)}return{status:e.value,value:r}}}const eN=Object.freeze({status:"aborted"}),tN=e=>({status:"dirty",value:e}),rN=e=>({status:"valid",value:e}),nN=e=>"aborted"===e.status,aN=e=>"dirty"===e.status,iN=e=>"valid"===e.status,sN=e=>"undefined"!=typeof Promise&&e instanceof Promise;var oN;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(oN||(oN={}));class cN{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 lN=(e,t)=>{if(iN(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 ZS(e.common.issues);return this._error=t,this._error}}};function uN(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:a}=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:a};return{errorMap:(t,a)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??a.defaultError}:void 0===a.data?{message:i??n??a.defaultError}:"invalid_type"!==t.code?{message:a.defaultError}:{message:i??r??a.defaultError}},description:a}}class dN{get description(){return this._def.description}_getType(e){return KS(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:KS(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new XS,ctx:{common:e.parent.common,data:e.data,parsedType:KS(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(sN(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:KS(e)},n=this._parseSync({data:e,path:r.path,parent:r});return lN(r,n)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:KS(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return iN(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>iN(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:KS(e)},n=this._parse({data:e,path:r.path,parent:r}),a=await(sN(n)?n:Promise.resolve(n));return lN(r,a)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,n)=>{const a=e(t),i=()=>n.addIssue({code:WS.custom,...r(t)});return"undefined"!=typeof Promise&&a instanceof Promise?a.then(e=>!!e||(i(),!1)):!!a||(i(),!1)})}refinement(e,t){return this._refinement((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1))}_refinement(e){return new lk({schema:this,typeName:vk.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return uk.create(this,this._def)}nullable(){return dk.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return WN.create(this)}promise(){return ck.create(this,this._def)}or(e){return YN.create([this,e],this._def)}and(e){return XN.create(this,e,this._def)}transform(e){return new lk({...uN(this._def),schema:this,typeName:vk.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new pk({...uN(this._def),innerType:this,defaultValue:t,typeName:vk.ZodDefault})}brand(){return new fk({typeName:vk.ZodBranded,type:this,...uN(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new mk({...uN(this._def),innerType:this,catchValue:t,typeName:vk.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return gk.create(this,e)}readonly(){return yk.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const pN=/^c[^\s-]{8,}$/i,mN=/^[0-9a-z]+$/,hN=/^[0-9A-HJKMNP-TV-Z]{26}$/i,fN=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,gN=/^[a-z0-9_-]{21}$/i,yN=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,vN=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,bN=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let _N;const wN=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,SN=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,NN=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,kN=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,xN=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,EN=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,PN="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",CN=new RegExp(`^${PN}$`);function AN(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function IN(e){return new RegExp(`^${AN(e)}$`)}function ON(e){let t=`${PN}T${AN(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function TN(e,t){return!("v4"!==t&&t||!wN.test(e))||!("v6"!==t&&t||!NN.test(e))}function $N(e,t){if(!yN.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),a=JSON.parse(atob(n));return"object"==typeof a&&null!==a&&((!("typ"in a)||"JWT"===a?.typ)&&(!!a.alg&&(!t||a.alg===t)))}catch{return!1}}function zN(e,t){return!("v4"!==t&&t||!SN.test(e))||!("v6"!==t&&t||!kN.test(e))}class RN extends dN{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==HS.string){const t=this._getOrReturnCtx(e);return QS(t,{code:WS.invalid_type,expected:HS.string,received:t.parsedType}),eN}const t=new XS;let r;for(const n of this._def.checks)if("min"===n.kind)e.data.length<n.value&&(r=this._getOrReturnCtx(e,r),QS(r,{code:WS.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("max"===n.kind)e.data.length>n.value&&(r=this._getOrReturnCtx(e,r),QS(r,{code:WS.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("length"===n.kind){const a=e.data.length>n.value,i=e.data.length<n.value;(a||i)&&(r=this._getOrReturnCtx(e,r),a?QS(r,{code:WS.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):i&&QS(r,{code:WS.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),t.dirty())}else if("email"===n.kind)bN.test(e.data)||(r=this._getOrReturnCtx(e,r),QS(r,{validation:"email",code:WS.invalid_string,message:n.message}),t.dirty());else if("emoji"===n.kind)_N||(_N=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),_N.test(e.data)||(r=this._getOrReturnCtx(e,r),QS(r,{validation:"emoji",code:WS.invalid_string,message:n.message}),t.dirty());else if("uuid"===n.kind)fN.test(e.data)||(r=this._getOrReturnCtx(e,r),QS(r,{validation:"uuid",code:WS.invalid_string,message:n.message}),t.dirty());else if("nanoid"===n.kind)gN.test(e.data)||(r=this._getOrReturnCtx(e,r),QS(r,{validation:"nanoid",code:WS.invalid_string,message:n.message}),t.dirty());else if("cuid"===n.kind)pN.test(e.data)||(r=this._getOrReturnCtx(e,r),QS(r,{validation:"cuid",code:WS.invalid_string,message:n.message}),t.dirty());else if("cuid2"===n.kind)mN.test(e.data)||(r=this._getOrReturnCtx(e,r),QS(r,{validation:"cuid2",code:WS.invalid_string,message:n.message}),t.dirty());else if("ulid"===n.kind)hN.test(e.data)||(r=this._getOrReturnCtx(e,r),QS(r,{validation:"ulid",code:WS.invalid_string,message:n.message}),t.dirty());else if("url"===n.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),QS(r,{validation:"url",code:WS.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),QS(r,{validation:"regex",code:WS.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),QS(r,{code:WS.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),QS(r,{code:WS.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),QS(r,{code:WS.invalid_string,validation:{endsWith:n.value},message:n.message}),t.dirty());else if("datetime"===n.kind){ON(n).test(e.data)||(r=this._getOrReturnCtx(e,r),QS(r,{code:WS.invalid_string,validation:"datetime",message:n.message}),t.dirty())}else if("date"===n.kind){CN.test(e.data)||(r=this._getOrReturnCtx(e,r),QS(r,{code:WS.invalid_string,validation:"date",message:n.message}),t.dirty())}else if("time"===n.kind){IN(n).test(e.data)||(r=this._getOrReturnCtx(e,r),QS(r,{code:WS.invalid_string,validation:"time",message:n.message}),t.dirty())}else"duration"===n.kind?vN.test(e.data)||(r=this._getOrReturnCtx(e,r),QS(r,{validation:"duration",code:WS.invalid_string,message:n.message}),t.dirty()):"ip"===n.kind?TN(e.data,n.version)||(r=this._getOrReturnCtx(e,r),QS(r,{validation:"ip",code:WS.invalid_string,message:n.message}),t.dirty()):"jwt"===n.kind?$N(e.data,n.alg)||(r=this._getOrReturnCtx(e,r),QS(r,{validation:"jwt",code:WS.invalid_string,message:n.message}),t.dirty()):"cidr"===n.kind?zN(e.data,n.version)||(r=this._getOrReturnCtx(e,r),QS(r,{validation:"cidr",code:WS.invalid_string,message:n.message}),t.dirty()):"base64"===n.kind?xN.test(e.data)||(r=this._getOrReturnCtx(e,r),QS(r,{validation:"base64",code:WS.invalid_string,message:n.message}),t.dirty()):"base64url"===n.kind?EN.test(e.data)||(r=this._getOrReturnCtx(e,r),QS(r,{validation:"base64url",code:WS.invalid_string,message:n.message}),t.dirty()):VS.assertNever(n);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:WS.invalid_string,...oN.errToObj(r)})}_addCheck(e){return new RN({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...oN.errToObj(e)})}url(e){return this._addCheck({kind:"url",...oN.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...oN.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...oN.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...oN.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...oN.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...oN.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...oN.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...oN.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...oN.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...oN.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...oN.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...oN.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...oN.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,...oN.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...oN.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...oN.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...oN.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...oN.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...oN.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...oN.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...oN.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...oN.errToObj(t)})}nonempty(e){return this.min(1,oN.errToObj(e))}trim(){return new RN({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new RN({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new RN({...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(){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 LN(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,a=r>n?r:n;return Number.parseInt(e.toFixed(a).replace(".",""))%Number.parseInt(t.toFixed(a).replace(".",""))/10**a}RN.create=e=>new RN({checks:[],typeName:vk.ZodString,coerce:e?.coerce??!1,...uN(e)});class MN extends dN{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)!==HS.number){const t=this._getOrReturnCtx(e);return QS(t,{code:WS.invalid_type,expected:HS.number,received:t.parsedType}),eN}let t;const r=new XS;for(const n of this._def.checks)if("int"===n.kind)VS.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),QS(t,{code:WS.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),QS(t,{code:WS.too_small,minimum:n.value,type:"number",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),QS(t,{code:WS.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else"multipleOf"===n.kind?0!==LN(e.data,n.value)&&(t=this._getOrReturnCtx(e,t),QS(t,{code:WS.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),QS(t,{code:WS.not_finite,message:n.message}),r.dirty()):VS.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,oN.toString(t))}gt(e,t){return this.setLimit("min",e,!1,oN.toString(t))}lte(e,t){return this.setLimit("max",e,!0,oN.toString(t))}lt(e,t){return this.setLimit("max",e,!1,oN.toString(t))}setLimit(e,t,r,n){return new MN({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:oN.toString(n)}]})}_addCheck(e){return new MN({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:oN.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:oN.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:oN.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:oN.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:oN.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:oN.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:oN.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:oN.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:oN.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&&VS.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)}}MN.create=e=>new MN({checks:[],typeName:vk.ZodNumber,coerce:e?.coerce||!1,...uN(e)});class DN extends dN{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==HS.bigint)return this._getInvalidInput(e);let t;const r=new XS;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),QS(t,{code:WS.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),QS(t,{code:WS.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),QS(t,{code:WS.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):VS.assertNever(n);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return QS(t,{code:WS.invalid_type,expected:HS.bigint,received:t.parsedType}),eN}gte(e,t){return this.setLimit("min",e,!0,oN.toString(t))}gt(e,t){return this.setLimit("min",e,!1,oN.toString(t))}lte(e,t){return this.setLimit("max",e,!0,oN.toString(t))}lt(e,t){return this.setLimit("max",e,!1,oN.toString(t))}setLimit(e,t,r,n){return new DN({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:oN.toString(n)}]})}_addCheck(e){return new DN({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:oN.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:oN.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:oN.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:oN.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:oN.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}}DN.create=e=>new DN({checks:[],typeName:vk.ZodBigInt,coerce:e?.coerce??!1,...uN(e)});class jN extends dN{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==HS.boolean){const t=this._getOrReturnCtx(e);return QS(t,{code:WS.invalid_type,expected:HS.boolean,received:t.parsedType}),eN}return rN(e.data)}}jN.create=e=>new jN({typeName:vk.ZodBoolean,coerce:e?.coerce||!1,...uN(e)});class FN extends dN{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==HS.date){const t=this._getOrReturnCtx(e);return QS(t,{code:WS.invalid_type,expected:HS.date,received:t.parsedType}),eN}if(Number.isNaN(e.data.getTime())){return QS(this._getOrReturnCtx(e),{code:WS.invalid_date}),eN}const t=new XS;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),QS(r,{code:WS.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),QS(r,{code:WS.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):VS.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new FN({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:oN.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:oN.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}}FN.create=e=>new FN({checks:[],coerce:e?.coerce||!1,typeName:vk.ZodDate,...uN(e)});class UN extends dN{_parse(e){if(this._getType(e)!==HS.symbol){const t=this._getOrReturnCtx(e);return QS(t,{code:WS.invalid_type,expected:HS.symbol,received:t.parsedType}),eN}return rN(e.data)}}UN.create=e=>new UN({typeName:vk.ZodSymbol,...uN(e)});class qN extends dN{_parse(e){if(this._getType(e)!==HS.undefined){const t=this._getOrReturnCtx(e);return QS(t,{code:WS.invalid_type,expected:HS.undefined,received:t.parsedType}),eN}return rN(e.data)}}qN.create=e=>new qN({typeName:vk.ZodUndefined,...uN(e)});class BN extends dN{_parse(e){if(this._getType(e)!==HS.null){const t=this._getOrReturnCtx(e);return QS(t,{code:WS.invalid_type,expected:HS.null,received:t.parsedType}),eN}return rN(e.data)}}BN.create=e=>new BN({typeName:vk.ZodNull,...uN(e)});class VN extends dN{constructor(){super(...arguments),this._any=!0}_parse(e){return rN(e.data)}}VN.create=e=>new VN({typeName:vk.ZodAny,...uN(e)});class GN extends dN{constructor(){super(...arguments),this._unknown=!0}_parse(e){return rN(e.data)}}GN.create=e=>new GN({typeName:vk.ZodUnknown,...uN(e)});class HN extends dN{_parse(e){const t=this._getOrReturnCtx(e);return QS(t,{code:WS.invalid_type,expected:HS.never,received:t.parsedType}),eN}}HN.create=e=>new HN({typeName:vk.ZodNever,...uN(e)});class KN extends dN{_parse(e){if(this._getType(e)!==HS.undefined){const t=this._getOrReturnCtx(e);return QS(t,{code:WS.invalid_type,expected:HS.void,received:t.parsedType}),eN}return rN(e.data)}}KN.create=e=>new KN({typeName:vk.ZodVoid,...uN(e)});class WN extends dN{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==HS.array)return QS(t,{code:WS.invalid_type,expected:HS.array,received:t.parsedType}),eN;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,a=t.data.length<n.exactLength.value;(e||a)&&(QS(t,{code:e?WS.too_big:WS.too_small,minimum:a?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&&(QS(t,{code:WS.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&&(QS(t,{code:WS.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 cN(t,e,t.path,r)))).then(e=>XS.mergeArray(r,e));const a=[...t.data].map((e,r)=>n.type._parseSync(new cN(t,e,t.path,r)));return XS.mergeArray(r,a)}get element(){return this._def.type}min(e,t){return new WN({...this._def,minLength:{value:e,message:oN.toString(t)}})}max(e,t){return new WN({...this._def,maxLength:{value:e,message:oN.toString(t)}})}length(e,t){return new WN({...this._def,exactLength:{value:e,message:oN.toString(t)}})}nonempty(e){return this.min(1,e)}}function ZN(e){if(e instanceof JN){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=uk.create(ZN(n))}return new JN({...e._def,shape:()=>t})}return e instanceof WN?new WN({...e._def,type:ZN(e.element)}):e instanceof uk?uk.create(ZN(e.unwrap())):e instanceof dk?dk.create(ZN(e.unwrap())):e instanceof ek?ek.create(e.items.map(e=>ZN(e))):e}WN.create=(e,t)=>new WN({type:e,minLength:null,maxLength:null,exactLength:null,typeName:vk.ZodArray,...uN(t)});class JN extends dN{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=VS.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==HS.object){const t=this._getOrReturnCtx(e);return QS(t,{code:WS.invalid_type,expected:HS.object,received:t.parsedType}),eN}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof HN&&"strip"===this._def.unknownKeys))for(const e in r.data)a.includes(e)||i.push(e);const s=[];for(const e of a){const t=n[e],a=r.data[e];s.push({key:{status:"valid",value:e},value:t._parse(new cN(r,a,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof HN){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of i)s.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)i.length>0&&(QS(r,{code:WS.unrecognized_keys,keys:i}),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 i){const n=r.data[t];s.push({key:{status:"valid",value:t},value:e._parse(new cN(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of s){const r=await t.key,n=await t.value;e.push({key:r,value:n,alwaysSet:t.alwaysSet})}return e}).then(e=>XS.mergeObjectSync(t,e)):XS.mergeObjectSync(t,s)}get shape(){return this._def.shape()}strict(e){return oN.errToObj,new JN({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const n=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:oN.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new JN({...this._def,unknownKeys:"strip"})}passthrough(){return new JN({...this._def,unknownKeys:"passthrough"})}extend(e){return new JN({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new JN({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:vk.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new JN({...this._def,catchall:e})}pick(e){const t={};for(const r of VS.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new JN({...this._def,shape:()=>t})}omit(e){const t={};for(const r of VS.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new JN({...this._def,shape:()=>t})}deepPartial(){return ZN(this)}partial(e){const t={};for(const r of VS.objectKeys(this.shape)){const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}return new JN({...this._def,shape:()=>t})}required(e){const t={};for(const r of VS.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof uk;)e=e._def.innerType;t[r]=e}return new JN({...this._def,shape:()=>t})}keyof(){return ik(VS.objectKeys(this.shape))}}JN.create=(e,t)=>new JN({shape:()=>e,unknownKeys:"strip",catchall:HN.create(),typeName:vk.ZodObject,...uN(t)}),JN.strictCreate=(e,t)=>new JN({shape:()=>e,unknownKeys:"strict",catchall:HN.create(),typeName:vk.ZodObject,...uN(t)}),JN.lazycreate=(e,t)=>new JN({shape:e,unknownKeys:"strip",catchall:HN.create(),typeName:vk.ZodObject,...uN(t)});class YN extends dN{_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 ZS(e.ctx.common.issues));return QS(t,{code:WS.invalid_union,unionErrors:r}),eN});{let e;const n=[];for(const a of r){const r={...t,common:{...t.common,issues:[]},parent:null},i=a._parseSync({data:t.data,path:t.path,parent:r});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,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 a=n.map(e=>new ZS(e));return QS(t,{code:WS.invalid_union,unionErrors:a}),eN}}get options(){return this._def.options}}function QN(e,t){const r=KS(e),n=KS(t);if(e===t)return{valid:!0,data:e};if(r===HS.object&&n===HS.object){const r=VS.objectKeys(t),n=VS.objectKeys(e).filter(e=>-1!==r.indexOf(e)),a={...e,...t};for(const r of n){const n=QN(e[r],t[r]);if(!n.valid)return{valid:!1};a[r]=n.data}return{valid:!0,data:a}}if(r===HS.array&&n===HS.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n<e.length;n++){const a=QN(e[n],t[n]);if(!a.valid)return{valid:!1};r.push(a.data)}return{valid:!0,data:r}}return r===HS.date&&n===HS.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}YN.create=(e,t)=>new YN({options:e,typeName:vk.ZodUnion,...uN(t)});class XN extends dN{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(nN(e)||nN(n))return eN;const a=QN(e.value,n.value);return a.valid?((aN(e)||aN(n))&&t.dirty(),{status:t.value,value:a.data}):(QS(r,{code:WS.invalid_intersection_types}),eN)};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}))}}XN.create=(e,t,r)=>new XN({left:e,right:t,typeName:vk.ZodIntersection,...uN(r)});class ek extends dN{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==HS.array)return QS(r,{code:WS.invalid_type,expected:HS.array,received:r.parsedType}),eN;if(r.data.length<this._def.items.length)return QS(r,{code:WS.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),eN;!this._def.rest&&r.data.length>this._def.items.length&&(QS(r,{code:WS.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 cN(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(n).then(e=>XS.mergeArray(t,e)):XS.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new ek({...this._def,rest:e})}}ek.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ek({items:e,typeName:vk.ZodTuple,rest:null,...uN(t)})};class tk extends dN{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==HS.map)return QS(r,{code:WS.invalid_type,expected:HS.map,received:r.parsedType}),eN;const n=this._def.keyType,a=this._def.valueType,i=[...r.data.entries()].map(([e,t],i)=>({key:n._parse(new cN(r,e,r.path,[i,"key"])),value:a._parse(new cN(r,t,r.path,[i,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of i){const n=await r.key,a=await r.value;if("aborted"===n.status||"aborted"===a.status)return eN;"dirty"!==n.status&&"dirty"!==a.status||t.dirty(),e.set(n.value,a.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of i){const n=r.key,a=r.value;if("aborted"===n.status||"aborted"===a.status)return eN;"dirty"!==n.status&&"dirty"!==a.status||t.dirty(),e.set(n.value,a.value)}return{status:t.value,value:e}}}}tk.create=(e,t,r)=>new tk({valueType:t,keyType:e,typeName:vk.ZodMap,...uN(r)});class rk extends dN{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==HS.set)return QS(r,{code:WS.invalid_type,expected:HS.set,received:r.parsedType}),eN;const n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(QS(r,{code:WS.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&r.data.size>n.maxSize.value&&(QS(r,{code:WS.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const a=this._def.valueType;function i(e){const r=new Set;for(const n of e){if("aborted"===n.status)return eN;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const s=[...r.data.values()].map((e,t)=>a._parse(new cN(r,e,r.path,t)));return r.common.async?Promise.all(s).then(e=>i(e)):i(s)}min(e,t){return new rk({...this._def,minSize:{value:e,message:oN.toString(t)}})}max(e,t){return new rk({...this._def,maxSize:{value:e,message:oN.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}rk.create=(e,t)=>new rk({valueType:e,minSize:null,maxSize:null,typeName:vk.ZodSet,...uN(t)});class nk extends dN{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})}}nk.create=(e,t)=>new nk({getter:e,typeName:vk.ZodLazy,...uN(t)});class ak extends dN{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return QS(t,{received:t.data,code:WS.invalid_literal,expected:this._def.value}),eN}return{status:"valid",value:e.data}}get value(){return this._def.value}}function ik(e,t){return new sk({values:e,typeName:vk.ZodEnum,...uN(t)})}ak.create=(e,t)=>new ak({value:e,typeName:vk.ZodLiteral,...uN(t)});class sk extends dN{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return QS(t,{expected:VS.joinValues(r),received:t.parsedType,code:WS.invalid_type}),eN}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 QS(t,{received:t.data,code:WS.invalid_enum_value,options:r}),eN}return rN(e.data)}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(e,t=this._def){return sk.create(e,{...this._def,...t})}exclude(e,t=this._def){return sk.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}sk.create=ik;class ok extends dN{_parse(e){const t=VS.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==HS.string&&r.parsedType!==HS.number){const e=VS.objectValues(t);return QS(r,{expected:VS.joinValues(e),received:r.parsedType,code:WS.invalid_type}),eN}if(this._cache||(this._cache=new Set(VS.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=VS.objectValues(t);return QS(r,{received:r.data,code:WS.invalid_enum_value,options:e}),eN}return rN(e.data)}get enum(){return this._def.values}}ok.create=(e,t)=>new ok({values:e,typeName:vk.ZodNativeEnum,...uN(t)});class ck extends dN{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==HS.promise&&!1===t.common.async)return QS(t,{code:WS.invalid_type,expected:HS.promise,received:t.parsedType}),eN;const r=t.parsedType===HS.promise?t.data:Promise.resolve(t.data);return rN(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ck.create=(e,t)=>new ck({type:e,typeName:vk.ZodPromise,...uN(t)});class lk extends dN{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===vk.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,a={addIssue:e=>{QS(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),"preprocess"===n.type){const e=n.transform(r.data,a);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return eN;const n=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===n.status?eN:"dirty"===n.status||"dirty"===t.value?tN(n.value):n});{if("aborted"===t.value)return eN;const n=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===n.status?eN:"dirty"===n.status||"dirty"===t.value?tN(n.value):n}}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,a);if(r.common.async)return Promise.resolve(t);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?eN:("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?eN:("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(!iN(e))return eN;const i=n.transform(e.value,a);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>iN(e)?Promise.resolve(n.transform(e.value,a)).then(e=>({status:t.value,value:e})):eN)}VS.assertNever(n)}}lk.create=(e,t,r)=>new lk({schema:e,typeName:vk.ZodEffects,effect:t,...uN(r)}),lk.createWithPreprocess=(e,t,r)=>new lk({schema:t,effect:{type:"preprocess",transform:e},typeName:vk.ZodEffects,...uN(r)});class uk extends dN{_parse(e){return this._getType(e)===HS.undefined?rN(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}uk.create=(e,t)=>new uk({innerType:e,typeName:vk.ZodOptional,...uN(t)});class dk extends dN{_parse(e){return this._getType(e)===HS.null?rN(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}dk.create=(e,t)=>new dk({innerType:e,typeName:vk.ZodNullable,...uN(t)});class pk extends dN{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===HS.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}pk.create=(e,t)=>new pk({innerType:e,typeName:vk.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...uN(t)});class mk extends dN{_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 sN(n)?n.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new ZS(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new ZS(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}mk.create=(e,t)=>new mk({innerType:e,typeName:vk.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...uN(t)});class hk extends dN{_parse(e){if(this._getType(e)!==HS.nan){const t=this._getOrReturnCtx(e);return QS(t,{code:WS.invalid_type,expected:HS.nan,received:t.parsedType}),eN}return{status:"valid",value:e.data}}}hk.create=e=>new hk({typeName:vk.ZodNaN,...uN(e)});class fk extends dN{_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}}class gk extends dN{_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?eN:"dirty"===e.status?(t.dirty(),tN(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?eN:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new gk({in:e,out:t,typeName:vk.ZodPipeline})}}class yk extends dN{_parse(e){const t=this._def.innerType._parse(e),r=e=>(iN(e)&&(e.value=Object.freeze(e.value)),e);return sN(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}var vk;yk.create=(e,t)=>new yk({innerType:e,typeName:vk.ZodReadonly,...uN(t)}),function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(vk||(vk={}));const bk=RN.create,_k=VN.create;HN.create,WN.create;const wk=JN.create;function Sk(e,t){return Zk(e.type._def,t)}YN.create,XN.create,ek.create,sk.create,ck.create,uk.create,dk.create;function Nk(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(r=>Nk(e,t,r))};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 kk(e,t)}}const kk=(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":BS(r,"minimum",n.value,n.message,t);break;case"max":BS(r,"maximum",n.value,n.message,t)}return r};let xk;const Ek=/^[cC][^\s-]{8,}$/,Pk=/^[0-9a-z]+$/,Ck=/^[0-9A-HJKMNP-TV-Z]{26}$/,Ak=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,Ik=()=>(void 0===xk&&(xk=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),xk),Ok=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Tk=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,$k=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,zk=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Rk=/^[a-zA-Z0-9_-]{21}$/,Lk=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function Mk(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":BS(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":BS(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":Fk(r,"email",n.message,t);break;case"format:idn-email":Fk(r,"idn-email",n.message,t);break;case"pattern:zod":Uk(r,Ak,n.message,t)}break;case"url":Fk(r,"uri",n.message,t);break;case"uuid":Fk(r,"uuid",n.message,t);break;case"regex":Uk(r,n.regex,n.message,t);break;case"cuid":Uk(r,Ek,n.message,t);break;case"cuid2":Uk(r,Pk,n.message,t);break;case"startsWith":Uk(r,RegExp(`^${Dk(n.value,t)}`),n.message,t);break;case"endsWith":Uk(r,RegExp(`${Dk(n.value,t)}$`),n.message,t);break;case"datetime":Fk(r,"date-time",n.message,t);break;case"date":Fk(r,"date",n.message,t);break;case"time":Fk(r,"time",n.message,t);break;case"duration":Fk(r,"duration",n.message,t);break;case"length":BS(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t),BS(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":Uk(r,RegExp(Dk(n.value,t)),n.message,t);break;case"ip":"v6"!==n.version&&Fk(r,"ipv4",n.message,t),"v4"!==n.version&&Fk(r,"ipv6",n.message,t);break;case"base64url":Uk(r,zk,n.message,t);break;case"jwt":Uk(r,Lk,n.message,t);break;case"cidr":"v6"!==n.version&&Uk(r,Ok,n.message,t),"v4"!==n.version&&Uk(r,Tk,n.message,t);break;case"emoji":Uk(r,Ik(),n.message,t);break;case"ulid":Uk(r,Ck,n.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":Fk(r,"binary",n.message,t);break;case"contentEncoding:base64":BS(r,"contentEncoding","base64",n.message,t);break;case"pattern:zod":Uk(r,$k,n.message,t)}break;case"nanoid":Uk(r,Rk,n.message,t)}return r}function Dk(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let r=0;r<e.length;r++)jk.has(e[r])||(t+="\\"),t+=e[r];return t}(e):e}const jk=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Fk(e,t,r,n){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):BS(e,"format",t,r,n)}function Uk(e,t,r,n){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:qk(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):BS(e,"pattern",qk(t,n),r,n)}function qk(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const r=e.flags.includes("i"),n=e.flags.includes("m"),a=e.flags.includes("s"),i=r?e.source.toLowerCase():e.source;let s="",o=!1,c=!1,l=!1;for(let e=0;e<i.length;e++)if(o)s+=i[e],o=!1;else{if(r)if(c){if(i[e].match(/[a-z]/)){l?(s+=i[e],s+=`${i[e-2]}-${i[e]}`.toUpperCase(),l=!1):"-"===i[e+1]&&i[e+2]?.match(/[a-z]/)?(s+=i[e],l=!0):s+=`${i[e]}${i[e].toUpperCase()}`;continue}}else if(i[e].match(/[a-z]/)){s+=`[${i[e]}${i[e].toUpperCase()}]`;continue}if(n){if("^"===i[e]){s+="(^|(?<=[\r\n]))";continue}if("$"===i[e]){s+="($|(?=[\r\n]))";continue}}a&&"."===i[e]?s+=c?`${i[e]}\r\n`:`[${i[e]}\r\n]`:(s+=i[e],"\\"===i[e]?o=!0:c&&"]"===i[e]?c=!1:c||"["!==i[e]||(c=!0))}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return s}function Bk(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===vk.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,n)=>({...r,[n]:Zk(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??US(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:Zk(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===vk.ZodString&&e.keyType._def.checks?.length){const{type:n,...a}=Mk(e.keyType._def,t);return{...r,propertyNames:a}}if(e.keyType?._def.typeName===vk.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===vk.ZodBranded&&e.keyType._def.type._def.typeName===vk.ZodString&&e.keyType._def.type._def.checks?.length){const{type:n,...a}=Sk(e.keyType._def,t);return{...r,propertyNames:a}}return r}const Vk={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};const Gk=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,r)=>Zk(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return r.length?{anyOf:r}:void 0};function Hk(e,t){const r="openAi"===t.target,n={type:"object",properties:{}},a=[],i=e.shape();for(const e in i){let s=i[e];if(void 0===s||void 0===s._def)continue;let o=Kk(s);o&&r&&("ZodOptional"===s._def.typeName&&(s=s._def.innerType),s.isNullable()||(s=s.nullable()),o=!1);const c=Zk(s._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==c&&(n.properties[e]=c,o||a.push(e))}a.length&&(n.required=a);const s=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return Zk(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==s&&(n.additionalProperties=s),n}function Kk(e){try{return e.isOptional()}catch{return!0}}const Wk=(e,t,r)=>{switch(t){case vk.ZodString:return Mk(e,r);case vk.ZodNumber:return function(e,t){const r={type:"number"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"int":r.type="integer",qS(r,"type",n.message,t);break;case"min":"jsonSchema7"===t.target?n.inclusive?BS(r,"minimum",n.value,n.message,t):BS(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),BS(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?BS(r,"maximum",n.value,n.message,t):BS(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),BS(r,"maximum",n.value,n.message,t));break;case"multipleOf":BS(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case vk.ZodObject:return Hk(e,r);case vk.ZodBigInt:return function(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"min":"jsonSchema7"===t.target?n.inclusive?BS(r,"minimum",n.value,n.message,t):BS(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),BS(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?BS(r,"maximum",n.value,n.message,t):BS(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),BS(r,"maximum",n.value,n.message,t));break;case"multipleOf":BS(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case vk.ZodBoolean:return{type:"boolean"};case vk.ZodDate:return Nk(e,r);case vk.ZodUndefined:return function(e){return{not:US(e)}}(r);case vk.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(r);case vk.ZodArray:return function(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==vk.ZodAny&&(r.items=Zk(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&BS(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&BS(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(BS(r,"minItems",e.exactLength.value,e.exactLength.message,t),BS(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}(e,r);case vk.ZodUnion:case vk.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return Gk(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(e=>e._def.typeName in Vk&&(!e._def.checks||!e._def.checks.length))){const e=r.reduce((e,t)=>{const r=Vk[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e},[]);return{type:e.length>1?e:e[0]}}if(r.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){const e=r.reduce((e,t)=>{const r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":return null===t._def.value?[...e,"null"]:e;default:return e}},[]);if(e.length===r.length){const t=e.filter((e,t,r)=>r.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:r.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(r.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:r.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return Gk(e,t)}(e,r);case vk.ZodIntersection:return function(e,t){const r=[Zk(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Zk(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(e=>!!e);let n="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const a=[];return r.forEach(e=>{if((e=>(!("type"in e)||"string"!==e.type)&&"allOf"in e)(e))a.push(...e.allOf),void 0===e.unevaluatedProperties&&(n=void 0);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:r,...n}=e;t=n}else n=void 0;a.push(t)}}),a.length?{allOf:a,...n}:void 0}(e,r);case vk.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,r)=>Zk(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:Zk(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,r)=>Zk(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])}}(e,r);case vk.ZodRecord:return Bk(e,r);case vk.ZodLiteral:return function(e,t){const r=typeof e.value;return"bigint"!==r&&"number"!==r&&"boolean"!==r&&"string"!==r?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===r?"integer":r,enum:[e.value]}:{type:"bigint"===r?"integer":r,const:e.value}}(e,r);case vk.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case vk.ZodNativeEnum:return function(e){const t=e.values,r=Object.keys(e.values).filter(e=>"number"!=typeof t[t[e]]),n=r.map(e=>t[e]),a=Array.from(new Set(n.map(e=>typeof e)));return{type:1===a.length?"string"===a[0]?"string":"number":["string","number"],enum:n}}(e);case vk.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:Vk[e.innerType._def.typeName],nullable:!0}:{type:[Vk[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const r=Zk(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const r=Zk(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}(e,r);case vk.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Zk(e.innerType._def,t);const r=Zk(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:US(t)},r]}:US(t)})(e,r);case vk.ZodMap:return function(e,t){return"record"===t.mapStrategy?Bk(e,t):{type:"array",maxItems:125,items:{type:"array",items:[Zk(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||US(t),Zk(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||US(t)],minItems:2,maxItems:2}}}(e,r);case vk.ZodSet:return function(e,t){const r={type:"array",uniqueItems:!0,items:Zk(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&BS(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&BS(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}(e,r);case vk.ZodLazy:return()=>e.getter()._def;case vk.ZodPromise:return function(e,t){return Zk(e.type._def,t)}(e,r);case vk.ZodNaN:case vk.ZodNever:return function(e){return"openAi"===e.target?void 0:{not:US({...e,currentPath:[...e.currentPath,"not"]})}}(r);case vk.ZodEffects:return function(e,t){return"input"===t.effectStrategy?Zk(e.schema._def,t):US(t)}(e,r);case vk.ZodAny:return US(r);case vk.ZodUnknown:return function(e){return US(e)}(r);case vk.ZodDefault:return function(e,t){return{...Zk(e.innerType._def,t),default:e.defaultValue()}}(e,r);case vk.ZodBranded:return Sk(e,r);case vk.ZodReadonly:case vk.ZodCatch:return((e,t)=>Zk(e.innerType._def,t))(e,r);case vk.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return Zk(e.in._def,t);if("output"===t.pipeStrategy)return Zk(e.out._def,t);const r=Zk(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[r,Zk(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]})].filter(e=>void 0!==e)}})(e,r);case vk.ZodFunction:case vk.ZodVoid:case vk.ZodSymbol:default:return}};function Zk(e,t,r=!1){const n=t.seen.get(e);if(t.override){const a=t.override?.(e,t,n,r);if(a!==MS)return a}if(n&&!r){const e=Jk(n,t);if(void 0!==e)return e}const a={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,a);const i=Wk(e,e.typeName,t),s="function"==typeof i?Zk(i(),t):i;if(s&&Yk(e,t,s),t.postProcess){const r=t.postProcess(s,e,t);return a.jsonSchema=s,r}return a.jsonSchema=s,s}const Jk=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:FS(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`),US(t)):"seen"===t.$refStrategy?US(t):void 0}},Yk=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);function Qk(e,t){const r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;const r=e.length;if(r!==t.length)return!1;for(let n=0;n<r;n++)if(!Qk(e[n],t[n]))return!1;return!0}if("object"===r){if(!e||!t)return e===t;const r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(const n of r)if(!Qk(e[n],t[n]))return!1;return!0}return e===t}function Xk(e){return encodeURI(function(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}(e))}const ex={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},tx={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},rx={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};let nx="undefined"!=typeof self&&self.location&&"null"!==self.location.origin?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function ax(e,t=Object.create(null),r=nx,n=""){if(e&&"object"==typeof e&&!Array.isArray(e)){const a=e.$id||e.id;if(a){const i=new URL(a,r.href);i.hash.length>1?t[i.href]=e:(i.hash="",""===n?r=i:ax(e,t,r))}}else if(!0!==e&&!1!==e)return t;const a=r.href+(n?"#"+n:"");if(void 0!==t[a])throw new Error(`Duplicate schema URI "${a}".`);if(t[a]=e,!0===e||!1===e)return t;if(void 0===e.__absolute_uri__&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:a}),e.$ref&&void 0===e.__absolute_ref__){const t=new URL(e.$ref,r.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:t.href})}if(e.$recursiveRef&&void 0===e.__absolute_recursive_ref__){const t=new URL(e.$recursiveRef,r.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:t.href})}if(e.$anchor){t[new URL("#"+e.$anchor,r.href).href]=e}for(let a in e){if(rx[a])continue;const i=`${n}/${Xk(a)}`,s=e[a];if(Array.isArray(s)){if(ex[a]){const e=s.length;for(let n=0;n<e;n++)ax(s[n],t,r,`${i}/${n}`)}}else if(tx[a])for(let e in s)ax(s[e],t,r,`${i}/${Xk(e)}`);else ax(s,t,r,i)}return t}const ix=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,sx=[0,31,28,31,30,31,30,31,31,30,31,30,31],ox=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;function cx(e){return e.test.bind(e)}const lx={date:ux,time:dx.bind(void 0,!1),"date-time":function(e){const t=e.split(px);return 2==t.length&&ux(t[0])&&dx(!0,t[1])},duration:e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),uri:function(e){return mx.test(e)&&hx.test(e)},"uri-reference":cx(/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i),"uri-template":cx(/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i),url:cx(/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu),email:e=>{if('"'===e[0])return!1;const[t,r,...n]=e.split("@");return!(!t||!r||0!==n.length||t.length>64||r.length>253)&&("."!==t[0]&&!t.endsWith(".")&&!t.includes("..")&&(!(!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t))&&r.split(".").every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))))},hostname:cx(/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i),ipv4:cx(/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/),ipv6:cx(/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i),regex:function(e){if(fx.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(e){return!1}},uuid:cx(/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i),"json-pointer":cx(/^(?:\/(?:[^~/]|~0|~1)*)*$/),"json-pointer-uri-fragment":cx(/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i),"relative-json-pointer":cx(/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/)};function ux(e){const t=e.match(ix);if(!t)return!1;const r=+t[1],n=+t[2],a=+t[3];return n>=1&&n<=12&&a>=1&&a<=(2==n&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(r)?29:sx[n])}function dx(e,t){const r=t.match(ox);if(!r)return!1;const n=+r[1],a=+r[2],i=+r[3],s=!!r[5];return(n<=23&&a<=59&&i<=59||23==n&&59==a&&60==i)&&(!e||s)}const px=/t|\s/i;const mx=/\/|:/,hx=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;const fx=/[^\\]\\Z/;function gx(e,t,r="2019-09",n=ax(t),a=!0,i=null,s="#",o="#",c=Object.create(null)){if(!0===t)return{valid:!0,errors:[]};if(!1===t)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};const l=typeof e;let u;switch(l){case"boolean":case"number":case"string":u=l;break;case"object":u=null===e?"null":Array.isArray(e)?"array":"object";break;default:throw new Error(`Instances of "${l}" type are not supported.`)}const{$ref:d,$recursiveRef:p,$recursiveAnchor:m,type:h,const:f,enum:g,required:y,not:v,anyOf:b,allOf:_,oneOf:w,if:S,then:N,else:k,format:x,properties:E,patternProperties:P,additionalProperties:C,unevaluatedProperties:A,minProperties:I,maxProperties:O,propertyNames:T,dependentRequired:$,dependentSchemas:z,dependencies:R,prefixItems:L,items:M,additionalItems:D,unevaluatedItems:j,contains:F,minContains:U,maxContains:q,minItems:B,maxItems:V,uniqueItems:G,minimum:H,maximum:K,exclusiveMinimum:W,exclusiveMaximum:Z,multipleOf:J,minLength:Y,maxLength:Q,pattern:X,__absolute_ref__:ee,__absolute_recursive_ref__:te}=t,re=[];if(!0===m&&null===i&&(i=t),"#"===p){const l=null===i?n[te]:i,u=`${o}/$recursiveRef`,d=gx(e,null===i?t:i,r,n,a,l,s,u,c);d.valid||re.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:u,error:"A subschema had errors."},...d.errors)}if(void 0!==d){const t=n[ee||d];if(void 0===t){let e=`Unresolved $ref "${d}".`;throw ee&&ee!==d&&(e+=` Absolute URI "${ee}".`),e+=`\nKnown schemas:\n- ${Object.keys(n).join("\n- ")}`,new Error(e)}const l=`${o}/$ref`,u=gx(e,t,r,n,a,i,s,l,c);if(u.valid||re.push({instanceLocation:s,keyword:"$ref",keywordLocation:l,error:"A subschema had errors."},...u.errors),"4"===r||"7"===r)return{valid:0===re.length,errors:re}}if(Array.isArray(h)){let t=h.length,r=!1;for(let n=0;n<t;n++)if(u===h[n]||"integer"===h[n]&&"number"===u&&e%1==0&&e==e){r=!0;break}r||re.push({instanceLocation:s,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${u}" is invalid. Expected "${h.join('", "')}".`})}else"integer"===h?("number"!==u||e%1||e!=e)&&re.push({instanceLocation:s,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${u}" is invalid. Expected "${h}".`}):void 0!==h&&u!==h&&re.push({instanceLocation:s,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${u}" is invalid. Expected "${h}".`});if(void 0!==f&&("object"===u||"array"===u?Qk(e,f)||re.push({instanceLocation:s,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(f)}.`}):e!==f&&re.push({instanceLocation:s,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(f)}.`})),void 0!==g&&("object"===u||"array"===u?g.some(t=>Qk(e,t))||re.push({instanceLocation:s,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||re.push({instanceLocation:s,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),void 0!==v){const t=`${o}/not`;gx(e,v,r,n,a,i,s,t).valid&&re.push({instanceLocation:s,keyword:"not",keywordLocation:t,error:'Instance matched "not" schema.'})}let ne=[];if(void 0!==b){const t=`${o}/anyOf`,l=re.length;let u=!1;for(let o=0;o<b.length;o++){const l=b[o],d=Object.create(c),p=gx(e,l,r,n,a,!0===m?i:null,s,`${t}/${o}`,d);re.push(...p.errors),u=u||p.valid,p.valid&&ne.push(d)}u?re.length=l:re.splice(l,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:t,error:"Instance does not match any subschemas."})}if(void 0!==_){const t=`${o}/allOf`,l=re.length;let u=!0;for(let o=0;o<_.length;o++){const l=_[o],d=Object.create(c),p=gx(e,l,r,n,a,!0===m?i:null,s,`${t}/${o}`,d);re.push(...p.errors),u=u&&p.valid,p.valid&&ne.push(d)}u?re.length=l:re.splice(l,0,{instanceLocation:s,keyword:"allOf",keywordLocation:t,error:"Instance does not match every subschema."})}if(void 0!==w){const t=`${o}/oneOf`,l=re.length,u=w.filter((o,l)=>{const u=Object.create(c),d=gx(e,o,r,n,a,!0===m?i:null,s,`${t}/${l}`,u);return re.push(...d.errors),d.valid&&ne.push(u),d.valid}).length;1===u?re.length=l:re.splice(l,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if("object"!==u&&"array"!==u||Object.assign(c,...ne),void 0!==S){const t=`${o}/if`;if(gx(e,S,r,n,a,i,s,t,c).valid){if(void 0!==N){const l=gx(e,N,r,n,a,i,s,`${o}/then`,c);l.valid||re.push({instanceLocation:s,keyword:"if",keywordLocation:t,error:'Instance does not match "then" schema.'},...l.errors)}}else if(void 0!==k){const l=gx(e,k,r,n,a,i,s,`${o}/else`,c);l.valid||re.push({instanceLocation:s,keyword:"if",keywordLocation:t,error:'Instance does not match "else" schema.'},...l.errors)}}if("object"===u){if(void 0!==y)for(const t of y)t in e||re.push({instanceLocation:s,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${t}".`});const t=Object.keys(e);if(void 0!==I&&t.length<I&&re.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${o}/minProperties`,error:`Instance does not have at least ${I} properties.`}),void 0!==O&&t.length>O&&re.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${O} properties.`}),void 0!==T){const t=`${o}/propertyNames`;for(const o in e){const e=`${s}/${Xk(o)}`,c=gx(o,T,r,n,a,i,e,t);c.valid||re.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:t,error:`Property name "${o}" does not match schema.`},...c.errors)}}if(void 0!==$){const t=`${o}/dependantRequired`;for(const r in $)if(r in e){const n=$[r];for(const a of n)a in e||re.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:t,error:`Instance has "${r}" but does not have "${a}".`})}}if(void 0!==z)for(const t in z){const l=`${o}/dependentSchemas`;if(t in e){const o=gx(e,z[t],r,n,a,i,s,`${l}/${Xk(t)}`,c);o.valid||re.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...o.errors)}}if(void 0!==R){const t=`${o}/dependencies`;for(const o in R)if(o in e){const c=R[o];if(Array.isArray(c))for(const r of c)r in e||re.push({instanceLocation:s,keyword:"dependencies",keywordLocation:t,error:`Instance has "${o}" but does not have "${r}".`});else{const l=gx(e,c,r,n,a,i,s,`${t}/${Xk(o)}`);l.valid||re.push({instanceLocation:s,keyword:"dependencies",keywordLocation:t,error:`Instance has "${o}" but does not match dependant schema.`},...l.errors)}}}const l=Object.create(null);let u=!1;if(void 0!==E){const t=`${o}/properties`;for(const o in E){if(!(o in e))continue;const d=`${s}/${Xk(o)}`,p=gx(e[o],E[o],r,n,a,i,d,`${t}/${Xk(o)}`);if(p.valid)c[o]=l[o]=!0;else if(u=a,re.push({instanceLocation:s,keyword:"properties",keywordLocation:t,error:`Property "${o}" does not match schema.`},...p.errors),u)break}}if(!u&&void 0!==P){const t=`${o}/patternProperties`;for(const o in P){const d=new RegExp(o,"u"),p=P[o];for(const m in e){if(!d.test(m))continue;const h=`${s}/${Xk(m)}`,f=gx(e[m],p,r,n,a,i,h,`${t}/${Xk(o)}`);f.valid?c[m]=l[m]=!0:(u=a,re.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:t,error:`Property "${m}" matches pattern "${o}" but does not match associated schema.`},...f.errors))}}}if(u||void 0===C){if(!u&&void 0!==A){const t=`${o}/unevaluatedProperties`;for(const o in e)if(!c[o]){const l=`${s}/${Xk(o)}`,u=gx(e[o],A,r,n,a,i,l,t);u.valid?c[o]=!0:re.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:t,error:`Property "${o}" does not match unevaluated properties schema.`},...u.errors)}}}else{const t=`${o}/additionalProperties`;for(const o in e){if(l[o])continue;const d=`${s}/${Xk(o)}`,p=gx(e[o],C,r,n,a,i,d,t);p.valid?c[o]=!0:(u=a,re.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:t,error:`Property "${o}" does not match additional properties schema.`},...p.errors))}}}else if("array"===u){void 0!==V&&e.length>V&&re.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${e.length} > ${V}).`}),void 0!==B&&e.length<B&&re.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${o}/minItems`,error:`Array has too few items (${e.length} < ${B}).`});const t=e.length;let l=0,u=!1;if(void 0!==L){const d=`${o}/prefixItems`,p=Math.min(L.length,t);for(;l<p;l++){const t=gx(e[l],L[l],r,n,a,i,`${s}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=a,re.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:d,error:"Items did not match schema."},...t.errors),u))break}}if(void 0!==M){const d=`${o}/items`;if(Array.isArray(M)){const o=Math.min(M.length,t);for(;l<o;l++){const t=gx(e[l],M[l],r,n,a,i,`${s}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=a,re.push({instanceLocation:s,keyword:"items",keywordLocation:d,error:"Items did not match schema."},...t.errors),u))break}}else for(;l<t;l++){const t=gx(e[l],M,r,n,a,i,`${s}/${l}`,d);if(c[l]=!0,!t.valid&&(u=a,re.push({instanceLocation:s,keyword:"items",keywordLocation:d,error:"Items did not match schema."},...t.errors),u))break}if(!u&&void 0!==D){const d=`${o}/additionalItems`;for(;l<t;l++){const t=gx(e[l],D,r,n,a,i,`${s}/${l}`,d);c[l]=!0,t.valid||(u=a,re.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:d,error:"Items did not match additional items schema."},...t.errors))}}}if(void 0!==F)if(0===t&&void 0===U)re.push({instanceLocation:s,keyword:"contains",keywordLocation:`${o}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(void 0!==U&&t<U)re.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array has less items (${t}) than minContains (${U}).`});else{const l=`${o}/contains`,u=re.length;let d=0;for(let o=0;o<t;o++){const t=gx(e[o],F,r,n,a,i,`${s}/${o}`,l);t.valid?(c[o]=!0,d++):re.push(...t.errors)}d>=(U||0)&&(re.length=u),void 0===U&&void 0===q&&0===d?re.splice(u,0,{instanceLocation:s,keyword:"contains",keywordLocation:l,error:"Array does not contain item matching schema."}):void 0!==U&&d<U?re.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array must contain at least ${U} items matching schema. Only ${d} items were found.`}):void 0!==q&&d>q&&re.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${q} items matching schema. ${d} items were found.`})}if(!u&&void 0!==j){const u=`${o}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;const t=gx(e[l],j,r,n,a,i,`${s}/${l}`,u);c[l]=!0,t.valid||re.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:u,error:"Items did not match unevaluated items schema."},...t.errors)}}if(G)for(let r=0;r<t;r++){const n=e[r],a="object"==typeof n&&null!==n;for(let i=0;i<t;i++){if(r===i)continue;const t=e[i];(n===t||a&&("object"==typeof t&&null!==t)&&Qk(n,t))&&(re.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${o}/uniqueItems`,error:`Duplicate items at indexes ${r} and ${i}.`}),r=Number.MAX_SAFE_INTEGER,i=Number.MAX_SAFE_INTEGER)}}}else if("number"===u){if("4"===r?(void 0!==H&&(!0===W&&e<=H||e<H)&&re.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${e} is less than ${W?"or equal to ":""} ${H}.`}),void 0!==K&&(!0===Z&&e>=K||e>K)&&re.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${Z?"or equal to ":""} ${K}.`})):(void 0!==H&&e<H&&re.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${e} is less than ${H}.`}),void 0!==K&&e>K&&re.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${K}.`}),void 0!==W&&e<=W&&re.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${e} is less than ${W}.`}),void 0!==Z&&e>=Z&&re.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Z}.`})),void 0!==J){const t=e%J;Math.abs(0-t)>=1.1920929e-7&&Math.abs(J-t)>=1.1920929e-7&&re.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${e} is not a multiple of ${J}.`})}}else if("string"===u){const t=void 0===Y&&void 0===Q?0:function(e){let t,r=0,n=e.length,a=0;for(;a<n;)r++,t=e.charCodeAt(a++),t>=55296&&t<=56319&&a<n&&(t=e.charCodeAt(a),56320==(64512&t)&&a++);return r}(e);void 0!==Y&&t<Y&&re.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${o}/minLength`,error:`String is too short (${t} < ${Y}).`}),void 0!==Q&&t>Q&&re.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${t} > ${Q}).`}),void 0===X||new RegExp(X,"u").test(e)||re.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),void 0!==x&&lx[x]&&!lx[x](e)&&re.push({instanceLocation:s,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${x}".`})}return{valid:0===re.length,errors:re}}class yx{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",r=!0){this.schema=e,this.draft=t,this.shortCircuit=r,this.lookup=ax(e)}validate(e){return gx(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),ax(e,this.lookup)}}function vx(e){if(oS(e)){const t=TS(e,!0);if(SS(t)){return iS(CS(t,!0))}return iS(e)}return cS(e)?((e,t)=>{const r=jS(t);let n;const a=Zk(e._def,r,!1)??US(r);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 i=n?{...a,[r.definitionPath]:n}:a;return"jsonSchema7"===r.target?i.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==r.target&&"openAi"!==r.target||(i.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===r.target&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i})(e):e}function bx(e){if(!e||"object"!=typeof e||0===Object.keys(e).length||Array.isArray(e))return!1;if("type"in e)return"string"==typeof e.type?"string"===e.type:!!Array.isArray(e.type)&&e.type.every(e=>"string"===e);if("enum"in e)return Array.isArray(e.enum)&&e.enum.length>0&&e.enum.every(e=>"string"==typeof e);if("const"in e)return"string"==typeof e.const;if("allOf"in e&&Array.isArray(e.allOf))return e.allOf.some(e=>bx(e));if("anyOf"in e&&Array.isArray(e.anyOf)||"oneOf"in e&&Array.isArray(e.oneOf)){const t="anyOf"in e?e.anyOf:e.oneOf;return t.length>0&&t.every(e=>bx(e))}if("not"in e)return!1;if("$ref"in e&&"string"==typeof e.$ref){const t=e.$ref,r=ax(e);return!!r[t]&&bx(r[t])}return!1}yf({},{Validator:()=>yx,deepCompareStrict:()=>Qk,toJsonSchema:()=>vx,validatesOnlyStrings:()=>bx});function _x(e,t){if(void 0!==e&&!Ry(e))return e;if(!Nw(t))return t.name??"UnknownSchema";try{let e=t.getName();return e=e.startsWith("Runnable")?e.slice(8):e,e}catch{return t.getName()}}function wx(e){return Nw(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...vx(e.data.schema),title:e.data.name}}}yf({},{Graph:()=>Sx});var Sx=class e{nodes={};edges=[];constructor(e){this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach((t,r)=>{e[t.id]=Ry(t.id)?r:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...wx(t)})),edges:this.edges.map(t=>{const r={source:e[t.source],target:e[t.target]};return void 0!==t.data&&(r.data=t.data),void 0!==t.conditional&&(r.conditional=t.conditional),r})}}addNode(e,t,r){if(void 0!==t&&void 0!==this.nodes[t])throw new Error(`Node with id ${t} already exists`);const n=t??By(),a={id:n,data:e,name:_x(t,e),metadata:r};return this.nodes[n]=a,a}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(t=>t.source!==e.id&&t.target!==e.id)}addEdge(e,t,r,n){if(void 0===this.nodes[e.id])throw new Error(`Source node ${e.id} not in graph`);if(void 0===this.nodes[t.id])throw new Error(`Target node ${t.id} not in graph`);const a={source:e.id,target:t.id,data:r,conditional:n};return this.edges.push(a),a}firstNode(){return Nx(this)}lastNode(){return kx(this)}extend(e,t=""){let r=t;const n=Object.values(e.nodes).map(e=>e.id);n.every(Ry)&&(r="");const a=e=>r?`${r}:${e}`:e;Object.entries(e.nodes).forEach(([e,t])=>{this.nodes[a(e)]={...t,id:a(e)}});const i=e.edges.map(e=>({...e,source:a(e.source),target:a(e.target)}));this.edges=[...this.edges,...i];const s=e.firstNode(),o=e.lastNode();return[s?{id:a(s.id),data:s.data}:void 0,o?{id:a(o.id),data:o.data}:void 0]}trimFirstNode(){const e=this.firstNode();e&&Nx(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&kx(this,[e.id])&&this.removeNode(e)}reid(){const t=Object.fromEntries(Object.values(this.nodes).map(e=>[e.id,e.name])),r=new Map;Object.values(t).forEach(e=>{r.set(e,(r.get(e)||0)+1)});const n=e=>{const n=t[e];return Ry(e)&&1===r.get(n)?n:e};return new e({nodes:Object.fromEntries(Object.entries(this.nodes).map(([e,t])=>[n(e),{...t,id:n(e)}])),edges:this.edges.map(e=>({...e,source:n(e.source),target:n(e.target)}))})}drawMermaid(e){const{withStyles:t,curveStyle:r,nodeColors:n={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:a}=e??{},i=this.reid(),s=i.firstNode(),o=i.lastNode();return LS(i.nodes,i.edges,{firstNode:s?.id,lastNode:o?.id,withStyles:t,curveStyle:r,nodeColors:n,wrapLabelNWords:a})}async drawMermaidPng(e){return async function(e,t){let r=t?.backgroundColor??"white";const n=t?.imageType??"png",a=btoa(e);void 0!==r&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));const i=`https://mermaid.ink/img/${a}?bgColor=${r}&type=${n}`,s=await fetch(i);if(!s.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${s.status}`,`Status text: ${s.statusText}`].join("\n"));return await s.blob()}(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}};function Nx(e,t=[]){const r=new Set(e.edges.filter(e=>!t.includes(e.source)).map(e=>e.target)),n=[];for(const a of Object.values(e.nodes))t.includes(a.id)||r.has(a.id)||n.push(a);return 1===n.length?n[0]:void 0}function kx(e,t=[]){const r=new Set(e.edges.filter(e=>!t.includes(e.target)).map(e=>e.source)),n=[];for(const a of Object.values(e.nodes))t.includes(a.id)||r.has(a.id)||n.push(a);return 1===n.length?n[0]:void 0}function xx(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.iterator]&&"function"==typeof e.next}function Ex(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.asyncIterator]}function*Px(e,t){for(;;){const{value:r,done:n}=N_.runWithConfig(A_(e),t.next.bind(t),!0);if(n)break;yield r}}async function*Cx(e,t){const r=t[Symbol.asyncIterator]();for(;;){const{value:n,done:a}=await N_.runWithConfig(A_(e),r.next.bind(t),!0);if(a)break;yield n}}function Ax(e,t){return!e||Array.isArray(e)||e instanceof Date||"object"!=typeof e?{[t]:e}:e}var Ix=class extends Mf{lc_runnable=!0;name;getName(e){const t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}withRetry(e){return new $x({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new Ox({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new jx({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(P_);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");const r=Object.fromEntries(Object.entries(e).filter(([e])=>"runId"!==e));return Array.from({length:t},(t,n)=>P_(0===n?e:r))}return Array.from({length:t},()=>P_(e))}async batch(e,t,r){const n=this._getOptionsList(t??{},e.length),a=n[0]?.maxConcurrency??r?.maxConcurrency,i=new ww({maxConcurrency:a,onFailedAttempt:e=>{throw e}}),s=e.map((e,t)=>i.call(async()=>{try{return await this.invoke(e,n[t])}catch(e){if(r?.returnExceptions)return e;throw e}}));return Promise.all(s)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){const r=P_(t),n=new R_({generator:this._streamIterator(e,r),config:r});return await n.setup,T_.fromAsyncGenerator(n)}_separateRunnableConfigFromCallOptions(e){let t;t=P_(void 0===e?e:{callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});const r={...e};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[t,r]}async _callWithConfig(e,t,r){const n=P_(r),a=await k_(n),i=await(a?.handleChainStart(this.toJSON(),Ax(t,"input"),n.runId,n?.runType,void 0,void 0,n?.runName??this.getName()));let s;delete n.runId;try{const a=e.call(this,t,n,i);s=await I_(a,r?.signal)}catch(e){throw await(i?.handleChainError(e)),e}return await(i?.handleChainEnd(Ax(s,"output"))),s}async _batchWithConfig(e,t,r,n){const a=this._getOptionsList(r??{},t.length),i=await Promise.all(a.map(k_)),s=await Promise.all(i.map(async(e,r)=>{const n=await(e?.handleChainStart(this.toJSON(),Ax(t[r],"input"),a[r].runId,a[r].runType,void 0,void 0,a[r].runName??this.getName()));return delete a[r].runId,n}));let o;try{const r=e.call(this,t,a,s,n);o=await I_(r,a?.[0]?.signal)}catch(e){throw await Promise.all(s.map(t=>t?.handleChainError(e))),e}return await Promise.all(s.map(e=>e?.handleChainEnd(Ax(o,"output")))),o}_concatOutputChunks(e,t){return z_(e,t)}async*_transformStreamWithConfig(e,t,r){let n,a,i=!0,s=!0;const o=P_(r),c=await k_(o),l=this;let u;try{const d=await L_(t.bind(this),async function*(){for await(const t of e){if(i)if(void 0===n)n=t;else try{n=l._concatOutputChunks(n,t)}catch{n=void 0,i=!1}yield t}}(),async()=>c?.handleChainStart(this.toJSON(),{input:""},o.runId,o.runType,void 0,void 0,o.runName??this.getName()),r?.signal,o);delete o.runId,u=d.setup;const p=u?.handlers.find(yw);let m=d.output;void 0!==p&&void 0!==u&&(m=p.tapOutputIterable(u.runId,m));const h=u?.handlers.find(lw);void 0!==h&&void 0!==u&&(m=h.tapOutputIterable(u.runId,m));for await(const e of m)if(yield e,s)if(void 0===a)a=e;else try{a=this._concatOutputChunks(a,e)}catch{a=void 0,s=!1}}catch(e){throw await(u?.handleChainError(e,void 0,void 0,void 0,{inputs:Ax(n,"input")})),e}await(u?.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:Ax(n,"input")}))}getGraph(e){const t=new Sx,r=t.addNode({name:`${this.getName()}Input`,schema:_k()}),n=t.addNode(this),a=t.addNode({name:`${this.getName()}Output`,schema:_k()});return t.addEdge(r,n),t.addEdge(n,a),t}pipe(e){return new zx({first:this,last:Fx(e)})}pick(e){return this.pipe(new qx(e))}assign(e){return this.pipe(new Ux(new Rx({steps:e})))}async*transform(e,t){let r;for await(const t of e)r=void 0===r?t:this._concatOutputChunks(r,t);yield*this._streamIterator(r,P_(t))}async*streamLog(e,t,r){const n=new pw({...r,autoClose:!1,_schemaFormat:"original"}),a=P_(t);yield*this._streamLog(e,n,a)}async*_streamLog(e,t,r){const{callbacks:n}=r;if(void 0===n)r.callbacks=[t];else if(Array.isArray(n))r.callbacks=n.concat([t]);else{const e=n.copy();e.addHandler(t,!0),r.callbacks=e}const a=this.stream(e,r);const i=async function(){try{const e=await a;for await(const r of e){const e=new ow({ops:[{op:"add",path:"/streamed_output/-",value:r}]});await t.writer.write(e)}}finally{await t.writer.close()}}();try{for await(const e of t)yield e}finally{await i}}streamEvents(e,t,r){let n;if("v1"===t.version)n=this._streamEventsV1(e,t,r);else{if("v2"!==t.version)throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');n=this._streamEventsV2(e,t,r)}return"text/event-stream"===t.encoding?function(e){const t=new TextEncoder,r=new ReadableStream({async start(r){for await(const n of e)r.enqueue(t.encode(`event: data\ndata: ${JSON.stringify(n)}\n\n`));r.enqueue(t.encode("event: end\n\n")),r.close()}});return T_.fromReadableStream(r)}(n):T_.fromAsyncGenerator(n)}async*_streamEventsV2(e,t,r){const n=new vw({...r,autoClose:!1}),a=P_(t),i=a.runId??By();a.runId=i;const s=a.callbacks;if(void 0===s)a.callbacks=[n];else if(Array.isArray(s))a.callbacks=s.concat(n);else{const e=s.copy();e.addHandler(n,!0),a.callbacks=e}const o=new AbortController,c=this;const l=async function(){let r,s=null;try{t?.signal?"any"in AbortSignal?r=AbortSignal.any([o.signal,t.signal]):(r=t.signal,s=()=>{o.abort()},t.signal.addEventListener("abort",s,{once:!0})):r=o.signal;const l=await c.stream(e,{...a,signal:r}),u=n.tapOutputIterable(i,l);for await(const e of u)if(o.signal.aborted)break}finally{await n.finish(),r&&s&&r.removeEventListener("abort",s)}}();let u,d=!1;try{for await(const t of n)d?(t.run_id===u&&t.event.endsWith("_end")&&t.data?.input&&delete t.data.input,yield t):(t.data.input=e,d=!0,u=t.run_id,yield t)}finally{o.abort(),await l}}async*_streamEventsV1(e,t,r){let n,a=!1;const i=P_(t),s=i.tags??[],o=i.metadata??{},c=i.runName??this.getName(),l=new pw({...r,autoClose:!1,_schemaFormat:"streaming_events"}),u=new kw({...r}),d=this._streamLog(e,l,i);for await(const t of d){if(n=n?n.concat(t):cw.fromRunLogPatch(t),void 0===n.state)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!a){a=!0;const t={...n.state},r={run_id:t.id,event:`on_${t.type}_start`,name:c,tags:s,metadata:o,data:{input:e}};u.includeEvent(r,t.type)&&(yield r)}const r=t.ops.filter(e=>e.path.startsWith("/logs/")).map(e=>e.path.split("/")[2]),i=[...new Set(r)];for(const e of i){let t,r={};const a=n.state.logs[e];if(t=void 0===a.end_time?a.streamed_output.length>0?"stream":"start":"end","start"===t)void 0!==a.inputs&&(r.input=a.inputs);else if("end"===t)void 0!==a.inputs&&(r.input=a.inputs),r.output=a.final_output;else if("stream"===t){const e=a.streamed_output.length;if(1!==e)throw new Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${a.name}"`);r={chunk:a.streamed_output[0]},a.streamed_output=[]}yield{event:`on_${a.type}_${t}`,name:a.name,run_id:a.id,tags:a.tags,metadata:a.metadata,data:r}}const{state:l}=n;if(l.streamed_output.length>0){const e=l.streamed_output.length;if(1!==e)throw new Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${l.name}"`);const t={chunk:l.streamed_output[0]};l.streamed_output=[];const r={event:`on_${l.type}_stream`,run_id:l.id,tags:s,metadata:o,name:c,data:t};u.includeEvent(r,l.type)&&(yield r)}}const p=n?.state;if(void 0!==p){const e={event:`on_${p.type}_end`,name:c,run_id:p.id,tags:s,metadata:o,data:{output:p.final_output}};u.includeEvent(e,p.type)&&(yield e)}}static isRunnable(e){return Nw(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new Ox({bound:this,config:{},configFactories:[n=>({callbacks:[new Sw({config:n,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return function(e,t){const r=t.name??e.getName(),n=t.description??vS(t.schema);return _S(t.schema)?new Bx({name:r,description:n,schema:wk({input:bk()}).transform(e=>e.input),bound:e}):new Bx({name:r,description:n,schema:t.schema,bound:e})}(this,e)}},Ox=class e extends Ix{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(e){super(e),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){const t=x_(this.config,...e);return x_(t,...this.configFactories?await Promise.all(this.configFactories.map(async e=>await e(t))):[])}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new $x({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e?.stopAfterAttempt,...e})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig(t,this.kwargs))}async batch(e,t,r){const n=Array.isArray(t)?await Promise.all(t.map(async e=>this._mergeConfig(P_(e),this.kwargs))):await this._mergeConfig(P_(t),this.kwargs);return this.bound.batch(e,n,r)}_concatOutputChunks(e,t){return this.bound._concatOutputChunks(e,t)}async*_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig(P_(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(P_(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(P_(t),this.kwargs))}streamEvents(e,t,r){const n=this;return T_.fromAsyncGenerator(async function*(){yield*n.bound.streamEvents(e,{...await n._mergeConfig(P_(t),n.kwargs),version:t.version},r)}())}static isRunnableBinding(e){return e.bound&&Ix.isRunnable(e.bound)}withListeners({onStart:t,onEnd:r,onError:n}){return new e({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[e=>({callbacks:[new Sw({config:e,onStart:t,onEnd:r,onError:n})]})]})}},Tx=class e extends Ix{static lc_name(){return"RunnableEach"}lc_serializable=!0;lc_namespace=["langchain_core","runnables"];bound;constructor(e){super(e),this.bound=e.bound}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _invoke(e,t,r){return this.bound.batch(e,C_(t,{callbacks:r?.getChild()}))}withListeners({onStart:t,onEnd:r,onError:n}){return new e({bound:this.bound.withListeners({onStart:t,onEnd:r,onError:n})})}},$x=class extends Ox{static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(e){super(e),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,r){const n=e>1?`retry:attempt:${e}`:void 0;return C_(t,{callbacks:r?.getChild(n)})}async _invoke(e,t,r){return jv(n=>super.invoke(e,this._patchConfigForRetry(n,t,r)),{onFailedAttempt:t=>this.onFailedAttempt(t,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,r,n){const a={};try{await jv(async i=>{const s=e.map((e,t)=>t).filter(e=>void 0===a[e.toString()]||a[e.toString()]instanceof Error),o=s.map(t=>e[t]),c=s.map(e=>this._patchConfigForRetry(i,t?.[e],r?.[e])),l=await super.batch(o,c,{...n,returnExceptions:!0});let u;for(let e=0;e<l.length;e+=1){const t=l[e],r=s[e];t instanceof Error&&void 0===u&&(u=t,u.input=o[e]),a[r.toString()]=t}if(u)throw u;return l},{onFailedAttempt:e=>this.onFailedAttempt(e,e.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(e){if(!0!==n?.returnExceptions)throw e}return Object.keys(a).sort((e,t)=>parseInt(e,10)-parseInt(t,10)).map(e=>a[parseInt(e,10)])}async batch(e,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}},zx=class e extends Ix{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(e){super(e),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,t){const r=P_(t),n=await k_(r),a=await(n?.handleChainStart(this.toJSON(),Ax(e,"input"),r.runId,void 0,void 0,void 0,r?.runName));delete r.runId;let i,s=e;try{const e=[this.first,...this.middle];for(let n=0;n<e.length;n+=1){const i=e[n].invoke(s,C_(r,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${n+1}`)}));s=await I_(i,t?.signal)}if(t?.signal?.aborted)throw O_(t.signal);i=await this.last.invoke(s,C_(r,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(e){throw await(a?.handleChainError(e)),e}return await(a?.handleChainEnd(Ax(i,"output"))),i}async batch(e,t,r){const n=this._getOptionsList(t??{},e.length),a=await Promise.all(n.map(k_)),i=await Promise.all(a.map(async(t,r)=>{const a=await(t?.handleChainStart(this.toJSON(),Ax(e[r],"input"),n[r].runId,void 0,void 0,void 0,n[r].runName));return delete n[r].runId,a}));let s=e;try{for(let e=0;e<this.steps.length;e+=1){const t=this.steps[e].batch(s,i.map((t,r)=>{const a=t?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`);return C_(n[r],{callbacks:a})}),r);s=await I_(t,n[0]?.signal)}}catch(e){throw await Promise.all(i.map(t=>t?.handleChainError(e))),e}return await Promise.all(i.map(e=>e?.handleChainEnd(Ax(s,"output")))),s}_concatOutputChunks(e,t){return this.last._concatOutputChunks(e,t)}async*_streamIterator(e,t){const r=await k_(t),{runId:n,...a}=t??{},i=await(r?.handleChainStart(this.toJSON(),Ax(e,"input"),n,void 0,void 0,void 0,a?.runName)),s=[this.first,...this.middle,this.last];let o,c=!0;try{let r=s[0].transform(async function*(){yield e}(),C_(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let e=1;e<s.length;e+=1){const t=s[e];r=await t.transform(r,C_(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`)}))}for await(const e of r)if(t?.signal?.throwIfAborted(),yield e,c)if(void 0===o)o=e;else try{o=this._concatOutputChunks(o,e)}catch{o=void 0,c=!1}}catch(e){throw await(i?.handleChainError(e)),e}await(i?.handleChainEnd(Ax(o,"output")))}getGraph(e){const t=new Sx;let r=null;return this.steps.forEach((n,a)=>{const i=n.getGraph(e);0!==a&&i.trimFirstNode(),a!==this.steps.length-1&&i.trimLastNode(),t.extend(i);const s=i.firstNode();if(!s)throw new Error(`Runnable ${n} has no first node`);r&&t.addEdge(r,s),r=i.lastNode()}),t}pipe(t){return e.isRunnableSequence(t)?new e({first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}):new e({first:this.first,middle:[...this.middle,this.last],last:Fx(t),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&Ix.isRunnable(e)}static from([t,...r],n){let a={};return"string"==typeof n?a.name=n:void 0!==n&&(a=n),new e({...a,first:Fx(t),middle:r.slice(0,-1).map(Fx),last:Fx(r[r.length-1])})}},Rx=class e extends Ix{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),this.steps={};for(const[t,r]of Object.entries(e.steps))this.steps[t]=Fx(r)}static from(t){return new e({steps:t})}async invoke(e,t){const r=P_(t),n=await k_(r),a=await(n?.handleChainStart(this.toJSON(),{input:e},r.runId,void 0,void 0,void 0,r?.runName));delete r.runId;const i={};try{const n=Object.entries(this.steps).map(async([t,n])=>{i[t]=await n.invoke(e,C_(r,{callbacks:a?.getChild(`map:key:${t}`)}))});await I_(Promise.all(n),t?.signal)}catch(e){throw await(a?.handleChainError(e)),e}return await(a?.handleChainEnd(i)),i}async*_transform(e,t,r){const n={...this.steps},a=$_(e,Object.keys(n).length),i=new Map(Object.entries(n).map(([e,n],i)=>{const s=n.transform(a[i],C_(r,{callbacks:t?.getChild(`map:key:${e}`)}));return[e,s.next().then(t=>({key:e,gen:s,result:t}))]}));for(;i.size;){const e=Promise.race(i.values()),{key:t,result:n,gen:a}=await I_(e,r?.signal);i.delete(t),n.done||(yield{[t]:n.value},i.set(t,a.next().then(e=>({key:t,gen:a,result:e}))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=P_(t),n=new R_({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,T_.fromAsyncGenerator(n)}},Lx=class e extends Ix{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(e){if(super(e),!n_(e.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,t){const[r]=this._getOptionsList(t??{},1),n=await k_(r);return I_(this.func(C_(r,{callbacks:n}),e),r?.signal)}async*_streamIterator(e,t){const[r]=this._getOptionsList(t??{},1),n=await this.invoke(e,t);var a;if(Ex(n))for await(const e of n)r?.signal?.throwIfAborted(),yield e;else if(null!=(a=n)&&"object"==typeof a&&"next"in a&&"function"==typeof a.next)for(;;){r?.signal?.throwIfAborted();const e=n.next();if(e.done)break;yield e.value}else yield n}static from(t){return new e({func:t})}};var Mx=class e extends Ix{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(e){if(n_(e.func))return Lx.from(e.func);super(e),function(e){if(n_(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}(e.func),this.func=e.func}static from(t){return new e({func:t})}async _invoke(e,t,r){return new Promise((n,a)=>{const i=C_(t,{callbacks:r?.getChild(),recursionLimit:(t?.recursionLimit??25)-1});N_.runWithConfig(A_(i),async()=>{try{let r=await this.func(e,{...i});if(r&&Ix.isRunnable(r)){if(0===t?.recursionLimit)throw new Error("Recursion limit reached.");r=await r.invoke(e,{...i,recursionLimit:(i.recursionLimit??25)-1})}else if(Ex(r)){let e;for await(const n of Cx(i,r))if(t?.signal?.throwIfAborted(),void 0===e)e=n;else try{e=this._concatOutputChunks(e,n)}catch{e=n}r=e}else if(xx(r)){let e;for(const n of Px(i,r))if(t?.signal?.throwIfAborted(),void 0===e)e=n;else try{e=this._concatOutputChunks(e,n)}catch{e=n}r=e}n(r)}catch(e){a(e)}})})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async*_transform(e,t,r){let n;for await(const t of e)if(void 0===n)n=t;else try{n=this._concatOutputChunks(n,t)}catch{n=t}const a=C_(r,{callbacks:t?.getChild(),recursionLimit:(r?.recursionLimit??25)-1}),i=await new Promise((e,t)=>{N_.runWithConfig(A_(a),async()=>{try{const t=await this.func(n,{...a,config:a});e(t)}catch(e){t(e)}})});if(i&&Ix.isRunnable(i)){if(0===r?.recursionLimit)throw new Error("Recursion limit reached.");const e=await i.stream(n,a);for await(const t of e)yield t}else if(Ex(i))for await(const e of Cx(a,i))r?.signal?.throwIfAborted(),yield e;else if(xx(i))for(const e of Px(a,i))r?.signal?.throwIfAborted(),yield e;else yield i}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=P_(t),n=new R_({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,T_.fromAsyncGenerator(n)}},Dx=class extends Rx{},jx=class extends Ix{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(e){super(e),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,t){const r=P_(t),n=await k_(r),{runId:a,...i}=r,s=await(n?.handleChainStart(this.toJSON(),Ax(e,"input"),a,void 0,void 0,void 0,i?.runName)),o=C_(i,{callbacks:s?.getChild()});return await N_.runWithConfig(o,async()=>{let t;for(const n of this.runnables()){r?.signal?.throwIfAborted();try{const t=await n.invoke(e,o);return await(s?.handleChainEnd(Ax(t,"output"))),t}catch(e){void 0===t&&(t=e)}}if(void 0===t)throw new Error("No error stored at end of fallback.");throw await(s?.handleChainError(t)),t})}async*_streamIterator(e,t){const r=P_(t),n=await k_(r),{runId:a,...i}=r,s=await(n?.handleChainStart(this.toJSON(),Ax(e,"input"),a,void 0,void 0,void 0,i?.runName));let o,c,l;for(const t of this.runnables()){r?.signal?.throwIfAborted();const n=C_(i,{callbacks:s?.getChild()});try{c=Cx(n,await t.stream(e,n));break}catch(e){void 0===o&&(o=e)}}if(void 0===c){const e=o??new Error("No error stored at end of fallback.");throw await(s?.handleChainError(e)),e}try{for await(const e of c){yield e;try{l=void 0===l?l:this._concatOutputChunks(l,e)}catch{l=void 0}}}catch(e){throw await(s?.handleChainError(e)),e}await(s?.handleChainEnd(Ax(l,"output")))}async batch(e,t,r){if(r?.returnExceptions)throw new Error("Not implemented.");const n=this._getOptionsList(t??{},e.length),a=await Promise.all(n.map(e=>k_(e))),i=await Promise.all(a.map(async(t,r)=>{const a=await(t?.handleChainStart(this.toJSON(),Ax(e[r],"input"),n[r].runId,void 0,void 0,void 0,n[r].runName));return delete n[r].runId,a}));let s;for(const t of this.runnables()){n[0].signal?.throwIfAborted();try{const a=await t.batch(e,i.map((e,t)=>C_(n[t],{callbacks:e?.getChild()})),r);return await Promise.all(i.map((e,t)=>e?.handleChainEnd(Ax(a[t],"output")))),a}catch(e){void 0===s&&(s=e)}}if(!s)throw new Error("No error stored at end of fallbacks.");throw await Promise.all(i.map(e=>e?.handleChainError(s))),s}};function Fx(e){if("function"==typeof e)return new Mx({func:e});if(Ix.isRunnable(e))return e;if(Array.isArray(e)||"object"!=typeof e)throw new Error("Expected a Runnable, function or object.\nInstead got an unsupported type.");{const t={};for(const[r,n]of Object.entries(e))t[r]=Fx(n);return new Rx({steps:t})}}var Ux=class extends Ix{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(e){e instanceof Rx&&(e={mapper:e}),super(e),this.mapper=e.mapper}async invoke(e,t){const r=await this.mapper.invoke(e,t);return{...e,...r}}async*_transform(e,t,r){const n=this.mapper.getStepsKeys(),[a,i]=$_(e),s=this.mapper.transform(i,C_(r,{callbacks:t?.getChild()})),o=s.next();for await(const e of a){if("object"!=typeof e||Array.isArray(e))throw new Error("RunnableAssign can only be used with objects as input, got "+typeof e);const t=Object.fromEntries(Object.entries(e).filter(([e])=>!n.includes(e)));Object.keys(t).length>0&&(yield t)}yield(await o).value;for await(const e of s)yield e}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=P_(t),n=new R_({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,T_.fromAsyncGenerator(n)}},qx=class extends Ix{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(e){("string"==typeof e||Array.isArray(e))&&(e={keys:e}),super(e),this.keys=e.keys}async _pick(e){if("string"==typeof this.keys)return e[this.keys];{const t=this.keys.map(t=>[t,e[t]]).filter(e=>void 0!==e[1]);return 0===t.length?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(const t of e){const e=await this._pick(t);void 0!==e&&(yield e)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=P_(t),n=new R_({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,T_.fromAsyncGenerator(n)}},Bx=class extends Ox{name;description;schema;constructor(e){super({bound:zx.from([Mx.from(async e=>{let t;if(dy(e))try{t=await fS(this.schema,e.args)}catch{throw new py("Received tool input did not match expected schema",JSON.stringify(e.args))}else t=e;return t}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name}),config:e.config??{}}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}};const Vx=(e,t)=>{const r=[...new Set(t?.map(e=>{if("string"==typeof e)return e;const t=new e({});if(!("getType"in t)||"function"!=typeof t.getType)throw new Error("Invalid type provided.");return t.getType()}))],n=e.getType();return r.some(e=>e===n)};function Gx(e,t){return Array.isArray(e)?Hx(e,t):Mx.from(t=>Hx(t,e))}function Hx(e,t={}){const{includeNames:r,excludeNames:n,includeTypes:a,excludeTypes:i,includeIds:s,excludeIds:o}=t,c=[];for(const t of e)n&&t.name&&n.includes(t.name)||i&&Vx(t,i)||o&&t.id&&o.includes(t.id)||(a||s||r?(r&&t.name&&r.some(e=>e===t.name)||a&&Vx(t,a)||s&&t.id&&s.some(e=>e===t.id))&&c.push(t):c.push(t));return c}function Kx(e){return Array.isArray(e)?Wx(e):Mx.from(Wx)}function Wx(e){if(!e.length)return[];const t=[];for(const r of e){const e=r,n=t.pop();if(n)if("tool"===e.getType()||e.getType()!==n.getType())t.push(n,e);else{const r=wy(n),a=wy(e),i=r.concat(a);"string"==typeof r.content&&"string"==typeof a.content&&(i.content=`${r.content}\n${a.content}`),t.push(eE(i))}else t.push(e)}return t}function Zx(e,t){if(Array.isArray(e)){const r=e;if(!t)throw new Error("Options parameter is required when providing messages.");return Jx(r,t)}{const t=e;return Mx.from(e=>Jx(e,t)).withConfig({runName:"trim_messages"})}}async function Jx(e,t){const{maxTokens:r,tokenCounter:n,strategy:a="last",allowPartial:i=!1,endOn:s,startOn:o,includeSystem:c=!1,textSplitter:l}=t;if(o&&"first"===a)throw new Error("`startOn` should only be specified if `strategy` is 'last'.");if(c&&"first"===a)throw new Error("`includeSystem` should only be specified if `strategy` is 'last'.");let u;u="getNumTokens"in n?async e=>(await Promise.all(e.map(e=>n.getNumTokens(e.content)))).reduce((e,t)=>e+t,0):async e=>n(e);let d=tE;if(l&&(d="splitText"in l?l.splitText:async e=>l(e)),"first"===a)return Yx(e,{maxTokens:r,tokenCounter:u,textSplitter:d,partialStrategy:i?"first":void 0,endOn:s});if("last"===a)return async function(e,t){const{allowPartial:r=!1,includeSystem:n=!1,endOn:a,startOn:i,...s}=t;let o=e.map(e=>{const t=Object.fromEntries(Object.entries(e).filter(([e])=>"type"!==e&&!e.startsWith("lc_")));return Xx(e.getType(),t,vg(e))});if(a){const e=Array.isArray(a)?a:[a];for(;o.length>0&&!Vx(o[o.length-1],e);)o=o.slice(0,-1)}const c=n&&"system"===o[0]?.getType();let l=c?o.slice(0,1).concat(o.slice(1).reverse()):o.reverse();return l=await Yx(l,{...s,partialStrategy:r?"last":void 0,endOn:i}),c?[l[0],...l.slice(1).reverse()]:l.reverse()}(e,{maxTokens:r,tokenCounter:u,textSplitter:d,allowPartial:i,includeSystem:c,startOn:o,endOn:s});throw new Error(`Unrecognized strategy: '${a}'. Must be one of 'first' or 'last'.`)}async function Yx(e,t){const{maxTokens:r,tokenCounter:n,textSplitter:a,partialStrategy:i,endOn:s}=t;let o=[...e],c=0;for(let e=0;e<o.length;e+=1){const t=e>0?o.slice(0,-e):o;if(await n(t)<=r){c=o.length-e;break}}if(c<o.length&&i){let e=!1;if(Array.isArray(o[c].content)){const t=o[c];if("string"==typeof t.content)throw new Error("Expected content to be an array.");const a=t.content.length,s="last"===i?[...t.content].reverse():t.content;for(let l=1;l<=a;l+=1){const a="first"===i?s.slice(0,l):s.slice(-l),u=Object.fromEntries(Object.entries(t).filter(([e])=>"type"!==e&&!e.startsWith("lc_"))),d=Xx(t.getType(),{...u,content:a}),p=[...o.slice(0,c),d];if(!(await n(p)<=r))break;o=p,c+=1,e=!0}e&&"last"===i&&(t.content=[...s].reverse())}if(!e){const e=o[c];let t;if(Array.isArray(e.content)&&e.content.some(e=>"string"==typeof e||"text"===e.type)){const r=e.content.find(e=>"text"===e.type&&e.text);t=r?.text}else"string"==typeof e.content&&(t=e.content);if(t){const s=await a(t),l=s.length;"last"===i&&s.reverse();for(let t=0;t<l-1;t+=1)if(s.pop(),e.content=s.join(""),await n([...o.slice(0,c),e])<=r){"last"===i&&(e.content=[...s].reverse().join("")),o=[...o.slice(0,c),e],c+=1;break}}}}if(s){const e=Array.isArray(s)?s:[s];for(;c>0&&!Vx(o[c-1],e);)c-=1}return o.slice(0,c)}const Qx={human:{message:ty,messageChunk:ry},ai:{message:Bg,messageChunk:Hg},system:{message:iy,messageChunk:sy},developer:{message:iy,messageChunk:sy},tool:{message:xg,messageChunk:Eg},function:{message:Yg,messageChunk:Qg},generic:{message:Kg,messageChunk:Wg},remove:{message:ly,messageChunk:ly}};function Xx(e,t,r){let n,a;switch(e){case"human":r?n=new ry(t):a=new ty(t);break;case"ai":if(r){let e={...t};"tool_calls"in e&&(e={...e,tool_call_chunks:e.tool_calls?.map(e=>({...e,type:"tool_call_chunk",index:void 0,args:JSON.stringify(e.args)}))}),n=new Hg(e)}else a=new Bg(t);break;case"system":r?n=new sy(t):a=new iy(t);break;case"developer":r?n=new sy({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}}):a=new iy({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if(!("tool_call_id"in t))throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");r?n=new Eg(t):a=new xg(t);break;case"function":if(r)n=new Qg(t);else{if(!t.name)throw new Error("FunctionMessage must have a 'name' field");a=new Yg(t)}break;case"generic":if(!("role"in t))throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");r?n=new Wg(t):a=new Kg(t);break;default:throw new Error(`Unrecognized message type ${e}`)}if(r&&n)return n;if(a)return a;throw new Error(`Unrecognized message type ${e}`)}function eE(e){const t=e.getType();let r;const n=Object.fromEntries(Object.entries(e).filter(([e])=>!["type","tool_call_chunks"].includes(e)&&!e.startsWith("lc_")));if(t in Qx&&(r=Xx(t,n)),!r)throw new Error(`Unrecognized message chunk class ${t}. Supported classes are ${Object.keys(Qx)}`);return r}function tE(e){const t=e.split("\n");return Promise.resolve([...t.slice(0,-1).map(e=>`${e}\n`),t[t.length-1]])}const rE=["text","reasoning","tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result","image","video","audio","text-plain","file"];yf({},{AIMessage:()=>Bg,AIMessageChunk:()=>Hg,BaseMessage:()=>ug,BaseMessageChunk:()=>fg,ChatMessage:()=>Kg,ChatMessageChunk:()=>Wg,FunctionMessage:()=>Yg,FunctionMessageChunk:()=>Qg,HumanMessage:()=>ty,HumanMessageChunk:()=>ry,KNOWN_BLOCK_TYPES:()=>rE,RemoveMessage:()=>ly,SystemMessage:()=>iy,SystemMessageChunk:()=>sy,ToolMessage:()=>xg,ToolMessageChunk:()=>Eg,_isMessageFieldWithRole:()=>gg,_mergeDicts:()=>pg,_mergeLists:()=>mg,_mergeObj:()=>hg,_mergeStatus:()=>lg,coerceMessageLikeToMessage:()=>gy,convertToChunk:()=>wy,convertToOpenAIImageBlock:()=>Nf,convertToProviderContentBlock:()=>Ef,defaultTextSplitter:()=>tE,defaultToolCallParser:()=>Pg,filterMessages:()=>Gx,getBufferString:()=>yy,iife:()=>my,isAIMessage:()=>Vg,isAIMessageChunk:()=>Gg,isBase64ContentBlock:()=>_f,isBaseMessage:()=>yg,isBaseMessageChunk:()=>vg,isChatMessage:()=>Zg,isChatMessageChunk:()=>Jg,isDataContentBlock:()=>vf,isDirectToolOutput:()=>kg,isFunctionMessage:()=>Xg,isFunctionMessageChunk:()=>ey,isHumanMessage:()=>ny,isHumanMessageChunk:()=>ay,isIDContentBlock:()=>Sf,isMessage:()=>Pf,isOpenAIToolCallArray:()=>dg,isPlainTextContentBlock:()=>wf,isSystemMessage:()=>oy,isSystemMessageChunk:()=>cy,isToolMessage:()=>Cg,isToolMessageChunk:()=>Ag,isURLContentBlock:()=>bf,mapChatMessagesToStoredMessages:()=>_y,mapStoredMessageToChatMessage:()=>vy,mapStoredMessagesToChatMessages:()=>by,mergeContent:()=>cg,mergeMessageRuns:()=>Kx,mergeResponseMetadata:()=>bg,mergeUsageMetadata:()=>Ng,parseBase64DataUrl:()=>xf,parseMimeType:()=>kf,trimMessages:()=>Zx});const nE=e=>e();function aE(e){return!!e&&(!!/^o\d/.test(e??"")||!(!e.startsWith("gpt-5")||e.startsWith("gpt-5-chat")))}function iE(e){const t=e._getType();switch(t){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!Kg.isInstance(e))throw new Error("Invalid generic chat message");return function(e){return"system"!==e.role&&"developer"!==e.role&&"assistant"!==e.role&&"user"!==e.role&&"function"!==e.role&&"tool"!==e.role&&console.warn(`Unknown message role: ${e.role}`),e.role}(e);default:throw new Error(`Unknown message type: ${t}`)}}function sE(e){const{azureOpenAIApiDeploymentName:t,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:n,azureOpenAIBasePath:a,baseURL:i,azureADTokenProvider:s,azureOpenAIEndpoint:o}=e;if((n||s)&&a&&t)return`${a}/${t}`;if((n||s)&&o&&t)return`${o}/openai/deployments/${t}`;if(n||s){if(!r)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!t)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${r}.openai.azure.com/openai/deployments/${t}`}return i}function oE(e){return"undefined"!=typeof Headers&&null!==e&&"object"==typeof e&&"[object Headers]"===Object.prototype.toString.call(e)}function cE(e){const t=nE(()=>{if(oE(e))return e;if(Array.isArray(e))return new Headers(e);if("object"==typeof e&&null!==e&&"values"in e&&oE(e.values))return e.values;if("object"==typeof e&&null!==e){const t=Object.entries(e).filter(([,e])=>"string"==typeof e).map(([e,t])=>[e,t]);return new Headers(t)}return new Headers});return Object.fromEntries(t.entries())}function lE(e){return void 0!==e&&Array.isArray(e.lc_namespace)}function uE(e){return void 0!==e&&Ix.isRunnable(e)&&"lc_name"in e.constructor&&"function"==typeof e.constructor.lc_name&&"RunnableToolLike"===e.constructor.lc_name()}function dE(e){return!!e&&"object"==typeof e&&"name"in e&&"schema"in e&&(uS(e.schema)||null!=e.schema&&"object"==typeof e.schema&&"type"in e.schema&&"string"==typeof e.schema.type&&["null","boolean","object","array","number","string"].includes(e.schema.type))}function pE(e){return dE(e)||uE(e)||lE(e)}yf({},{extendInteropZodObject:()=>ES,getInteropZodDefaultGetter:()=>IS,getInteropZodObjectShape:()=>xS,getSchemaDescription:()=>vS,interopParse:()=>yS,interopParseAsync:()=>fS,interopSafeParse:()=>gS,interopSafeParseAsync:()=>hS,interopZodObjectMakeFieldsOptional:()=>$S,interopZodObjectPartial:()=>PS,interopZodObjectPassthrough:()=>AS,interopZodObjectStrict:()=>CS,interopZodTransformInputSchema:()=>TS,isInteropZodLiteral:()=>mS,isInteropZodObject:()=>kS,isInteropZodSchema:()=>uS,isShapelessZodSchema:()=>bS,isSimpleStringZodSchema:()=>_S,isZodArrayV4:()=>NS,isZodLiteralV3:()=>dS,isZodLiteralV4:()=>pS,isZodObjectV3:()=>wS,isZodObjectV4:()=>SS,isZodSchema:()=>lS,isZodSchemaV3:()=>cS,isZodSchemaV4:()=>oS});function mE(e,t){const r="number"==typeof t?void 0:t;return{name:e.name,description:e.description,parameters:vx(e.schema),...void 0!==r?.strict?{strict:r.strict}:{}}}function hE(e,t){const r="number"==typeof t?void 0:t;let n;return n=pE(e)?{type:"function",function:mE(e)}:e,void 0!==r?.strict&&(n.function.strict=r.strict),n}function fE(e,t){const r=[];for(const[n,a]of Object.entries(e.properties??{}))a.description&&t<2&&r.push(`// ${a.description}`),e.required?.includes(n)?r.push(`${n}: ${gE(a,t)},`):r.push(`${n}?: ${gE(a,t)},`);return r.map(e=>" ".repeat(t)+e).join("\n")}function gE(e,t){if(void 0!==(r=e).anyOf&&Array.isArray(r.anyOf))return e.anyOf.map(e=>gE(e,t)).join(" | ");var r;switch(e.type){case"string":return e.enum?e.enum.map(e=>`"${e}"`).join(" | "):"string";case"number":case"integer":return e.enum?e.enum.map(e=>`${e}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",fE(e,t+2),"}"].join("\n");case"array":return e.items?`${gE(e.items,t)}[]`:"any[]";default:return""}}function yE(e){return e?"any"===e||"required"===e?"required":"auto"===e?"auto":"none"===e?"none":"string"==typeof e?{type:"function",function:{name:e}}:e:void 0}function vE(e){return"type"in e&&"function"!==e.type}function bE(e){return"object"==typeof e&&null!==e&&"metadata"in e&&"object"==typeof e.metadata&&null!==e.metadata&&"customTool"in e.metadata&&"object"==typeof e.metadata.customTool&&null!==e.metadata.customTool}function _E(e){return"type"in e&&"custom"===e.type&&"custom"in e&&"object"==typeof e.custom&&null!==e.custom}function wE(e){if("custom_tool_call"===e.type)return{...e,type:"tool_call",call_id:e.id,id:e.call_id,name:e.name,isCustomTool:!0,args:{input:e.input}}}function SE(e){return{type:"custom",name:e.custom.name,description:e.custom.description,format:(()=>{if(e.custom.format)return"grammar"===e.custom.format.type?{type:"grammar",definition:e.custom.format.grammar.definition,syntax:e.custom.format.grammar.syntax}:"text"===e.custom.format.type?{type:"text"}:void 0})()}}function NE(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}yf({},{convertToOpenAIFunction:()=>mE,convertToOpenAITool:()=>hE,isLangChainTool:()=>pE,isRunnableToolLike:()=>uE,isStructuredTool:()=>lE,isStructuredToolParams:()=>dE});const kE=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{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};class xE extends Error{}class EE extends xE{constructor(e,t,r,n){super(`${EE.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=t;const a=t;this.code=a?.code,this.param=a?.param,this.type=a?.type}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 CE({message:r,cause:kE(t)});const a=t?.error;return 400===e?new IE(e,a,r,n):401===e?new OE(e,a,r,n):403===e?new TE(e,a,r,n):404===e?new $E(e,a,r,n):409===e?new zE(e,a,r,n):422===e?new RE(e,a,r,n):429===e?new LE(e,a,r,n):e>=500?new ME(e,a,r,n):new EE(e,a,r,n)}}class PE extends EE{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class CE extends EE{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class AE extends CE{constructor({message:e}={}){super({message:e??"Request timed out."})}}class IE extends EE{}class OE extends EE{}class TE extends EE{}class $E extends EE{}class zE extends EE{}class RE extends EE{}class LE extends EE{}class ME extends EE{}class DE extends xE{constructor(){super("Could not parse response content as the length limit was reached")}}class jE extends xE{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class FE extends Error{constructor(e){super(e)}}function UE(e){return void 0!==e&&"function"in e&&void 0!==e.function}function qE(e){return"auto-parseable-response-format"===e?.$brand}function BE(e){return"auto-parseable-tool"===e?.$brand}function VE(e,t){const r=e.choices.map(e=>{if("length"===e.finish_reason)throw new DE;if("content_filter"===e.finish_reason)throw new jE;return WE(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>function(e,t){const r=e.tools?.find(e=>UE(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:BE(r)?r.$parseRaw(t.function.arguments):r?.function.strict?JSON.parse(t.function.arguments):null}}}(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?GE(t,e.message.content):null}}});return{...e,choices:r}}function GE(e,t){if("json_schema"!==e.response_format?.type)return null;if("json_schema"===e.response_format?.type){if("$parseRaw"in e.response_format){return e.response_format.$parseRaw(t)}return JSON.parse(t)}return null}function HE(e,t){if(!e||!("tools"in e)||!e.tools)return!1;const r=e.tools?.find(e=>UE(e)&&e.function?.name===t.function.name);return UE(r)&&(BE(r)||r?.function.strict||!1)}function KE(e){return!!qE(e.response_format)||(e.tools?.some(e=>BE(e)||"function"===e.type&&!0===e.function.strict)??!1)}function WE(e){for(const t of e||[])if("function"!==t.type)throw new xE(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}const ZE=Symbol("Let zodToJsonSchema decide on which parser to use"),JE={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},YE=e=>"_def"in e?e._def:e;const QE=e=>{const t=(e=>"string"==typeof e?{...JE,basePath:["#"],definitions:{},name:e}:{...JE,basePath:["#"],definitions:{},...e})(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(t.definitions).map(([e,r])=>[YE(r),{def:YE(r),path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function XE(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function eP(e,t,r,n,a){e[t]=r,XE(e,t,n,a)}function tP(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((r,n)=>tP(e,t,r))};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 rP(e,t)}}const rP=(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":eP(r,"minimum",n.value,n.message,t);break;case"max":eP(r,"maximum",n.value,n.message,t)}return r};let nP;const aP=/^[cC][^\s-]{8,}$/,iP=/^[0-9a-z]+$/,sP=/^[0-9A-HJKMNP-TV-Z]{26}$/,oP=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,cP=()=>(void 0===nP&&(nP=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),nP),lP=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,uP=/^[a-zA-Z0-9_-]{21}$/;function dP(e,t){const r={type:"string"};function n(e){return"escape"===t.patternStrategy?pP(e):e}if(e.checks)for(const a of e.checks)switch(a.kind){case"min":eP(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,a.value):a.value,a.message,t);break;case"max":eP(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,a.value):a.value,a.message,t);break;case"email":switch(t.emailStrategy){case"format:email":mP(r,"email",a.message,t);break;case"format:idn-email":mP(r,"idn-email",a.message,t);break;case"pattern:zod":hP(r,oP,a.message,t)}break;case"url":mP(r,"uri",a.message,t);break;case"uuid":mP(r,"uuid",a.message,t);break;case"regex":hP(r,a.regex,a.message,t);break;case"cuid":hP(r,aP,a.message,t);break;case"cuid2":hP(r,iP,a.message,t);break;case"startsWith":hP(r,RegExp(`^${n(a.value)}`),a.message,t);break;case"endsWith":hP(r,RegExp(`${n(a.value)}$`),a.message,t);break;case"datetime":mP(r,"date-time",a.message,t);break;case"date":mP(r,"date",a.message,t);break;case"time":mP(r,"time",a.message,t);break;case"duration":mP(r,"duration",a.message,t);break;case"length":eP(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,a.value):a.value,a.message,t),eP(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,a.value):a.value,a.message,t);break;case"includes":hP(r,RegExp(n(a.value)),a.message,t);break;case"ip":"v6"!==a.version&&mP(r,"ipv4",a.message,t),"v4"!==a.version&&mP(r,"ipv6",a.message,t);break;case"emoji":hP(r,cP,a.message,t);break;case"ulid":hP(r,sP,a.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":mP(r,"binary",a.message,t);break;case"contentEncoding:base64":eP(r,"contentEncoding","base64",a.message,t);break;case"pattern:zod":hP(r,lP,a.message,t)}break;case"nanoid":hP(r,uP,a.message,t)}return r}const pP=e=>Array.from(e).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),mP=(e,t,r,n)=>{e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):eP(e,"format",t,r,n)},hP=(e,t,r,n)=>{e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:fP(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):eP(e,"pattern",fP(t,n),r,n)},fP=(e,t)=>{const r="function"==typeof e?e():e;if(!t.applyRegexFlags||!r.flags)return r.source;const n=r.flags.includes("i"),a=r.flags.includes("m"),i=r.flags.includes("s"),s=n?r.source.toLowerCase():r.source;let o="",c=!1,l=!1,u=!1;for(let e=0;e<s.length;e++)if(c)o+=s[e],c=!1;else{if(n)if(l){if(s[e].match(/[a-z]/)){u?(o+=s[e],o+=`${s[e-2]}-${s[e]}`.toUpperCase(),u=!1):"-"===s[e+1]&&s[e+2]?.match(/[a-z]/)?(o+=s[e],u=!0):o+=`${s[e]}${s[e].toUpperCase()}`;continue}}else if(s[e].match(/[a-z]/)){o+=`[${s[e]}${s[e].toUpperCase()}]`;continue}if(a){if("^"===s[e]){o+="(^|(?<=[\r\n]))";continue}if("$"===s[e]){o+="($|(?=[\r\n]))";continue}}i&&"."===s[e]?o+=l?`${s[e]}\r\n`:`[${s[e]}\r\n]`:(o+=s[e],"\\"===s[e]?c=!0:l&&"]"===s[e]?l=!1:l||"["!==s[e]||(l=!0))}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return o};function gP(e,t){if("openApi3"===t.target&&e.keyType?._def.typeName===vk.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,n)=>({...r,[n]:_P(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??{}}),{}),additionalProperties:!1};const r={type:"object",additionalProperties:_P(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??{}};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===vk.ZodString&&e.keyType._def.checks?.length){const n=Object.entries(dP(e.keyType._def,t)).reduce((e,[t,r])=>"type"===t?e:{...e,[t]:r},{});return{...r,propertyNames:n}}return e.keyType?._def.typeName===vk.ZodEnum?{...r,propertyNames:{enum:e.keyType._def.values}}:r}const yP={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};const vP=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,r)=>_P(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return r.length?{anyOf:r}:void 0};function bP(e,t){return"strict"===t.removeAdditionalStrategy?"ZodNever"===e.catchall._def.typeName?"strict"!==e.unknownKeys:_P(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0:"ZodNever"===e.catchall._def.typeName?"passthrough"===e.unknownKeys:_P(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0}function _P(e,t,r=!1){const n=t.seen.get(e);if(t.override){const a=t.override?.(e,t,n,r);if(a!==ZE)return a}if(n&&!r){const e=wP(n,t);if(void 0!==e)return"$ref"in e&&t.seenRefs.add(e.$ref),e}const a={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,a);const i=NP(e,e.typeName,t,r);return i&&kP(e,t,i),a.jsonSchema=i,i}const wP=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"extract-to-root":const r=e.path.slice(t.basePath.length+1).join("_");return r!==t.name&&"duplicate-ref"===t.nameStrategy&&(t.definitions[r]=e.def),{$ref:[...t.basePath,t.definitionPath,r].join("/")};case"relative":return{$ref:SP(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`),{}):"seen"===t.$refStrategy?{}:void 0}},SP=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")},NP=(e,t,r,n)=>{switch(t){case vk.ZodString:return dP(e,r);case vk.ZodNumber:return function(e,t){const r={type:"number"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"int":r.type="integer",XE(r,"type",n.message,t);break;case"min":"jsonSchema7"===t.target?n.inclusive?eP(r,"minimum",n.value,n.message,t):eP(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),eP(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?eP(r,"maximum",n.value,n.message,t):eP(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),eP(r,"maximum",n.value,n.message,t));break;case"multipleOf":eP(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case vk.ZodObject:return function(e,t){const r={type:"object",...Object.entries(e.shape()).reduce((e,[r,n])=>{if(void 0===n||void 0===n._def)return e;const a=[...t.currentPath,"properties",r],i=_P(n._def,{...t,currentPath:a,propertyPath:a});if(void 0===i)return e;if(t.openaiStrictMode&&n.isOptional()&&!n.isNullable()&&void 0===n._def?.defaultValue)throw new Error(`Zod field at \`${a.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...e.properties,[r]:i},required:n.isOptional()&&!t.openaiStrictMode?e.required:[...e.required,r]}},{properties:{},required:[]}),additionalProperties:bP(e,t)};return r.required.length||delete r.required,r}(e,r);case vk.ZodBigInt:return function(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"min":"jsonSchema7"===t.target?n.inclusive?eP(r,"minimum",n.value,n.message,t):eP(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),eP(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?eP(r,"maximum",n.value,n.message,t):eP(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),eP(r,"maximum",n.value,n.message,t));break;case"multipleOf":eP(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case vk.ZodBoolean:return{type:"boolean"};case vk.ZodDate:return tP(e,r);case vk.ZodUndefined:return{not:{}};case vk.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(r);case vk.ZodArray:return function(e,t){const r={type:"array"};return e.type?._def?.typeName!==vk.ZodAny&&(r.items=_P(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&eP(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&eP(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(eP(r,"minItems",e.exactLength.value,e.exactLength.message,t),eP(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}(e,r);case vk.ZodUnion:case vk.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return vP(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(e=>e._def.typeName in yP&&(!e._def.checks||!e._def.checks.length))){const e=r.reduce((e,t)=>{const r=yP[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e},[]);return{type:e.length>1?e:e[0]}}if(r.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){const e=r.reduce((e,t)=>{const r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===r.length){const t=e.filter((e,t,r)=>r.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:r.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(r.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:r.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return vP(e,t)}(e,r);case vk.ZodIntersection:return function(e,t){const r=[_P(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),_P(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(e=>!!e);let n="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const a=[];return r.forEach(e=>{if((e=>(!("type"in e)||"string"!==e.type)&&"allOf"in e)(e))a.push(...e.allOf),void 0===e.unevaluatedProperties&&(n=void 0);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:r,...n}=e;t=n}else n=void 0;a.push(t)}}),a.length?{allOf:a,...n}:void 0}(e,r);case vk.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,r)=>_P(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:_P(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,r)=>_P(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])}}(e,r);case vk.ZodRecord:return gP(e,r);case vk.ZodLiteral:return function(e,t){const r=typeof e.value;return"bigint"!==r&&"number"!==r&&"boolean"!==r&&"string"!==r?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===r?"integer":r,enum:[e.value]}:{type:"bigint"===r?"integer":r,const:e.value}}(e,r);case vk.ZodEnum:return function(e){return{type:"string",enum:[...e.values]}}(e);case vk.ZodNativeEnum:return function(e){const t=e.values,r=Object.keys(e.values).filter(e=>"number"!=typeof t[t[e]]),n=r.map(e=>t[e]),a=Array.from(new Set(n.map(e=>typeof e)));return{type:1===a.length?"string"===a[0]?"string":"number":["string","number"],enum:n}}(e);case vk.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target||"property"===t.nullableStrategy?{type:yP[e.innerType._def.typeName],nullable:!0}:{type:[yP[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const r=_P(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const r=_P(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}(e,r);case vk.ZodOptional:return((e,t)=>{if(t.propertyPath&&t.currentPath.slice(0,t.propertyPath.length).toString()===t.propertyPath.toString())return _P(e.innerType._def,{...t,currentPath:t.currentPath});const r=_P(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}})(e,r);case vk.ZodMap:return function(e,t){return"record"===t.mapStrategy?gP(e,t):{type:"array",maxItems:125,items:{type:"array",items:[_P(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},_P(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}}}(e,r);case vk.ZodSet:return function(e,t){const r={type:"array",uniqueItems:!0,items:_P(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&eP(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&eP(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}(e,r);case vk.ZodLazy:return _P(e.getter()._def,r);case vk.ZodPromise:return function(e,t){return _P(e.type._def,t)}(e,r);case vk.ZodNaN:case vk.ZodNever:return{not:{}};case vk.ZodEffects:return function(e,t,r){return"input"===t.effectStrategy?_P(e.schema._def,t,r):{}}(e,r,n);case vk.ZodAny:case vk.ZodUnknown:return{};case vk.ZodDefault:return function(e,t){return{..._P(e.innerType._def,t),default:e.defaultValue()}}(e,r);case vk.ZodBranded:return function(e,t){return _P(e.type._def,t)}(e,r);case vk.ZodReadonly:case vk.ZodCatch:return((e,t)=>_P(e.innerType._def,t))(e,r);case vk.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return _P(e.in._def,t);if("output"===t.pipeStrategy)return _P(e.out._def,t);const r=_P(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[r,_P(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]})].filter(e=>void 0!==e)}})(e,r);case vk.ZodFunction:case vk.ZodVoid:case vk.ZodSymbol:default:return}},kP=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);function xP(e,t){return t&&function(e){if(qE(e.text?.format))return!0;return!1}(t)?EP(e,t):{...e,output_parsed:null,output:e.output.map(e=>"function_call"===e.type?{...e,parsed_arguments:null}:"message"===e.type?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)}}function EP(e,t){const r=e.output.map(e=>{if("function_call"===e.type)return{...e,parsed_arguments:AP(t,e)};if("message"===e.type){const r=e.content.map(e=>"output_text"===e.type?{...e,parsed:PP(t,e.text)}:e);return{...e,content:r}}return e}),n=Object.assign({},e,{output:r});return Object.getOwnPropertyDescriptor(e,"output_text")||IP(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(const e of n.output)if("message"===e.type)for(const t of e.content)if("output_text"===t.type&&null!==t.parsed)return t.parsed;return null}}),n}function PP(e,t){if("json_schema"!==e.text?.format?.type)return null;if("$parseRaw"in e.text?.format){const r=e.text?.format;return r.$parseRaw(t)}return JSON.parse(t)}function CP(e){return"auto-parseable-tool"===e?.$brand}function AP(e,t){const r=(n=e.tools??[],a=t.name,n.find(e=>"function"===e.type&&e.name===a));var n,a;return{...t,...t,parsed_arguments:CP(r)?r.$parseRaw(t.arguments):r?.strict?JSON.parse(t.arguments):null}}function IP(e){const t=[];for(const r of e.output)if("message"===r.type)for(const e of r.content)"output_text"===e.type&&t.push(e.text);e.output_text=t.join("")}function OP(e,t){return((e,t)=>{const r=QE(t),n="string"==typeof t?t:"title"===t?.nameStrategy?void 0:t?.name,a=_P(e._def,void 0===n?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},i="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==i&&(a.title=i);const s=(()=>{if(function(e){if(!e)return!0;for(const t in e)return!1;return!0}(r.definitions))return;const e={},t=new Set;for(let n=0;n<500;n++){const n=Object.entries(r.definitions).filter(([e])=>!t.has(e));if(0===n.length)break;for(const[a,i]of n)e[a]=_P(YE(i),{...r,currentPath:[...r.basePath,r.definitionPath,a]},!0)??{},t.add(a)}return e})(),o=void 0===n?s?{...a,[r.definitionPath]:s}:a:"duplicate-ref"===r.nameStrategy?{...a,...s||r.seenRefs.size?{[r.definitionPath]:{...s,...r.seenRefs.size?{[n]:a}:void 0}}:void 0}:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...s,[n]:a}};return"jsonSchema7"===r.target?o.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"===r.target&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),o})(e,{openaiStrictMode:!0,name:t.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function TP(e,t,r){return function(e,t){const r={...e};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),r}({type:"json_schema",json_schema:{...r,name:t,strict:!0,schema:OP(e,{name:t})}},t=>e.parse(JSON.parse(t)))}const $P=["jsonSchema","functionCalling","jsonMode"];function zP(e,t,r){if(cS(e))return TP(e,t,r);if(oS(e))return function(e,t){const r={...e};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),r}({type:"json_schema",json_schema:{...r,name:t,strict:!0,schema:iS(e,{cycles:"ref",reused:"ref",override(e){e.jsonSchema.title=t}})}},t=>Gw(e,JSON.parse(t)));throw new Error("Unsupported schema response format")}function RP(e){const t={...null!=e?.input_tokens_details?.cached_tokens&&{cache_read:e?.input_tokens_details?.cached_tokens}},r={...null!=e?.output_tokens_details?.reasoning_tokens&&{reasoning:e?.output_tokens_details?.reasoning_tokens}};return{input_tokens:e?.input_tokens??0,output_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,input_token_details:t,output_token_details:r}}function LP(e,t,r,n,a){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 MP(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");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 DP=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return DP=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))};const jP=/^[a-z][a-z0-9+.-]*:/i;let FP=e=>(FP=Array.isArray,FP(e)),UP=FP;function qP(e){return"object"!=typeof e?{}:e??{}}function BP(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}const VP=e=>new Promise(t=>setTimeout(t,e)),GP="6.6.0";const HP=()=>{const e="undefined"!=typeof Deno&&null!=Deno.build?"deno":"undefined"!=typeof EdgeRuntime?"edge":"[object process]"===Object.prototype.toString.call(void 0!==globalThis.process?globalThis.process:0)?"node":"unknown";if("deno"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":GP,"X-Stainless-OS":WP(Deno.build.os),"X-Stainless-Arch":KP(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":GP,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if("node"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":GP,"X-Stainless-OS":WP(globalThis.process.platform??"unknown"),"X-Stainless-Arch":KP(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:r}of e){const e=r.exec(navigator.userAgent);if(e){return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}}return null}();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":GP,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":GP,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const KP=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",WP=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let ZP;function JP(...e){const t=globalThis.ReadableStream;if(void 0===t)throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function YP(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return JP({start(){},async pull(e){const{done:r,value:n}=await t.next();r?e.close():e.enqueue(n)},async cancel(){await(t.return?.())}})}function QP(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}const XP=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),eC="RFC3986",tC=e=>String(e),rC={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:tC};let nC=(e,t)=>(nC=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),nC(e,t));const aC=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),iC=1024;function sC(e,t){if(FP(e)){const r=[];for(let n=0;n<e.length;n+=1)r.push(t(e[n]));return r}return t(e)}const oC={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},cC=function(e,t){Array.prototype.push.apply(e,FP(t)?t:[t])};let lC;const uC={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,r,n,a)=>{if(0===e.length)return e;let i=e;if("symbol"==typeof e?i=Symbol.prototype.toString.call(e):"string"!=typeof e&&(i=String(e)),"iso-8859-1"===r)return escape(i).replace(/%u[0-9a-f]{4}/gi,function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"});let s="";for(let e=0;e<i.length;e+=iC){const t=i.length>=iC?i.slice(e,e+iC):i,r=[];for(let e=0;e<t.length;++e){let n=t.charCodeAt(e);45===n||46===n||95===n||126===n||n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||"RFC1738"===a&&(40===n||41===n)?r[r.length]=t.charAt(e):n<128?r[r.length]=aC[n]:n<2048?r[r.length]=aC[192|n>>6]+aC[128|63&n]:n<55296||n>=57344?r[r.length]=aC[224|n>>12]+aC[128|n>>6&63]+aC[128|63&n]:(e+=1,n=65536+((1023&n)<<10|1023&t.charCodeAt(e)),r[r.length]=aC[240|n>>18]+aC[128|n>>12&63]+aC[128|n>>6&63]+aC[128|63&n])}s+=r.join("")}return s},encodeValuesOnly:!1,format:eC,formatter:tC,indices:!1,serializeDate:e=>(lC??(lC=Function.prototype.call.bind(Date.prototype.toISOString)))(e),skipNulls:!1,strictNullHandling:!1};const dC={};function pC(e,t,r,n,a,i,s,o,c,l,u,d,p,m,h,f,g,y){let v=e,b=y,_=0,w=!1;for(;void 0!==(b=b.get(dC))&&!w;){const t=b.get(e);if(_+=1,void 0!==t){if(t===_)throw new RangeError("Cyclic object value");w=!0}void 0===b.get(dC)&&(_=0)}if("function"==typeof l?v=l(t,v):v instanceof Date?v=p?.(v):"comma"===r&&FP(v)&&(v=sC(v,function(e){return e instanceof Date?p?.(e):e})),null===v){if(i)return c&&!f?c(t,uC.encoder,g,"key",m):t;v=""}if("string"==typeof(S=v)||"number"==typeof S||"boolean"==typeof S||"symbol"==typeof S||"bigint"==typeof S||function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))}(v)){if(c){const e=f?t:c(t,uC.encoder,g,"key",m);return[h?.(e)+"="+h?.(c(v,uC.encoder,g,"value",m))]}return[h?.(t)+"="+h?.(String(v))]}var S;const N=[];if(void 0===v)return N;let k;if("comma"===r&&FP(v))f&&c&&(v=sC(v,c)),k=[{value:v.length>0?v.join(",")||null:void 0}];else if(FP(l))k=l;else{const e=Object.keys(v);k=u?e.sort(u):e}const x=o?String(t).replace(/\./g,"%2E"):String(t),E=n&&FP(v)&&1===v.length?x+"[]":x;if(a&&FP(v)&&0===v.length)return E+"[]";for(let t=0;t<k.length;++t){const b=k[t],w="object"==typeof b&&void 0!==b.value?b.value:v[b];if(s&&null===w)continue;const S=d&&o?b.replace(/\./g,"%2E"):b,x=FP(v)?"function"==typeof r?r(E,S):E:E+(d?"."+S:"["+S+"]");y.set(e,_);const P=new WeakMap;P.set(dC,y),cC(N,pC(w,x,r,n,a,i,s,o,"comma"===r&&f&&FP(v)?null:c,l,u,d,p,m,h,f,g,P))}return N}function mC(e,t={}){let r=e;const n=function(e=uC){if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.encodeDotInKeys&&"boolean"!=typeof e.encodeDotInKeys)throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");const t=e.charset||uC.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=eC;if(void 0!==e.format){if(!nC(rC,e.format))throw new TypeError("Unknown format option provided.");r=e.format}const n=rC[r];let a,i=uC.filter;if(("function"==typeof e.filter||FP(e.filter))&&(i=e.filter),a=e.arrayFormat&&e.arrayFormat in oC?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":uC.arrayFormat,"commaRoundTrip"in e&&"boolean"!=typeof e.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const s=void 0===e.allowDots?1==!!e.encodeDotInKeys||uC.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:uC.addQueryPrefix,allowDots:s,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:uC.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:uC.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?uC.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:uC.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:uC.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:uC.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:uC.encodeValuesOnly,filter:i,format:r,formatter:n,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:uC.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:uC.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:uC.strictNullHandling}}(t);let a,i;"function"==typeof n.filter?(i=n.filter,r=i("",r)):FP(n.filter)&&(i=n.filter,a=i);const s=[];if("object"!=typeof r||null===r)return"";const o=oC[n.arrayFormat],c="comma"===o&&n.commaRoundTrip;a||(a=Object.keys(r)),n.sort&&a.sort(n.sort);const l=new WeakMap;for(let e=0;e<a.length;++e){const t=a[e];n.skipNulls&&null===r[t]||cC(s,pC(r[t],t,o,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,l))}const u=s.join(n.delimiter);let d=!0===n.addQueryPrefix?"?":"";return n.charsetSentinel&&("iso-8859-1"===n.charset?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}let hC,fC;function gC(e){let t;return(hC??(t=new globalThis.TextEncoder,hC=t.encode.bind(t)))(e)}function yC(e){let t;return(fC??(t=new globalThis.TextDecoder,fC=t.decode.bind(t)))(e)}var vC,bC;class _C{constructor(){vC.set(this,void 0),bC.set(this,void 0),LP(this,vC,new Uint8Array),LP(this,bC,null)}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?gC(e):e;LP(this,vC,function(e){let t=0;for(const r of e)t+=r.length;const r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}([MP(this,vC,"f"),t]));const r=[];let n;for(;null!=(n=wC(MP(this,vC,"f"),MP(this,bC,"f")));){if(n.carriage&&null==MP(this,bC,"f")){LP(this,bC,n.index);continue}if(null!=MP(this,bC,"f")&&(n.index!==MP(this,bC,"f")+1||n.carriage)){r.push(yC(MP(this,vC,"f").subarray(0,MP(this,bC,"f")-1))),LP(this,vC,MP(this,vC,"f").subarray(MP(this,bC,"f"))),LP(this,bC,null);continue}const e=null!==MP(this,bC,"f")?n.preceding-1:n.preceding,t=yC(MP(this,vC,"f").subarray(0,e));r.push(t),LP(this,vC,MP(this,vC,"f").subarray(n.index)),LP(this,bC,null)}return r}flush(){return MP(this,vC,"f").length?this.decode("\n"):[]}}function wC(e,t){for(let r=t??0;r<e.length;r++){if(10===e[r])return{preceding:r,index:r+1,carriage:!1};if(13===e[r])return{preceding:r,index:r+1,carriage:!0}}return null}function SC(e){for(let t=0;t<e.length-1;t++){if(10===e[t]&&10===e[t+1])return t+2;if(13===e[t]&&13===e[t+1])return t+2;if(13===e[t]&&10===e[t+1]&&t+3<e.length&&13===e[t+2]&&10===e[t+3])return t+4}return-1}vC=new WeakMap,bC=new WeakMap,_C.NEWLINE_CHARS=new Set(["\n","\r"]),_C.NEWLINE_REGEXP=/\r\n|[\n\r]/g;const NC={off:0,error:200,warn:300,info:400,debug:500},kC=(e,t,r)=>{if(e)return function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(NC,e)?e:void AC(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(NC))}`)};function xC(){}function EC(e,t,r){return!t||NC[e]>NC[r]?xC:t[e].bind(t)}const PC={error:xC,warn:xC,info:xC,debug:xC};let CC=new WeakMap;function AC(e){const t=e.logger,r=e.logLevel??"off";if(!t)return PC;const n=CC.get(t);if(n&&n[0]===r)return n[1];const a={error:EC("error",t,r),warn:EC("warn",t,r),info:EC("info",t,r),debug:EC("debug",t,r)};return CC.set(t,[r,a]),a}const IC=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,"authorization"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var OC,TC,$C;class zC{constructor(e,t,r){this.iterator=e,OC.set(this,void 0),this.controller=t,LP(this,OC,r)}static fromSSEResponse(e,t,r){let n=!1;const a=r?AC(r):console;return new zC(async function*(){if(n)throw new xE("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let r=!1;try{for await(const n of async function*(e,t){if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new xE("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new xE("Attempted to iterate over a response with no body")}const r=new RC,n=new _C,a=QP(e.body);for await(const e of async function*(e){let t=new Uint8Array;for await(const r of e){if(null==r)continue;const e=r instanceof ArrayBuffer?new Uint8Array(r):"string"==typeof r?gC(r):r;let n,a=new Uint8Array(t.length+e.length);for(a.set(t),a.set(e,t.length),t=a;-1!==(n=SC(t));)yield t.slice(0,n),t=t.slice(n)}t.length>0&&(yield t)}(a))for(const t of n.decode(e)){const e=r.decode(t);e&&(yield e)}for(const e of n.flush()){const t=r.decode(e);t&&(yield t)}}(e,t))if(!r)if(n.data.startsWith("[DONE]"))r=!0;else if(null!==n.event&&n.event.startsWith("thread.")){let e;try{e=JSON.parse(n.data)}catch(e){throw console.error("Could not parse message into JSON:",n.data),console.error("From chunk:",n.raw),e}if("error"==n.event)throw new EE(void 0,e.error,e.message,void 0);yield{event:n.event,data:e}}else{let t;try{t=JSON.parse(n.data)}catch(e){throw a.error("Could not parse message into JSON:",n.data),a.error("From chunk:",n.raw),e}if(t&&t.error)throw new EE(void 0,t.error,void 0,e.headers);yield t}r=!0}catch(e){if(NE(e))return;throw e}finally{r||t.abort()}},t,r)}static fromReadableStream(e,t,r){let n=!1;return new zC(async function*(){if(n)throw new xE("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let r=!1;try{for await(const t of async function*(){const t=new _C,r=QP(e);for await(const e of r)for(const r of t.decode(e))yield r;for(const e of t.flush())yield e}())r||t&&(yield JSON.parse(t));r=!0}catch(e){if(NE(e))return;throw e}finally{r||t.abort()}},t,r)}[(OC=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],r=this.iterator(),n=n=>({next:()=>{if(0===n.length){const n=r.next();e.push(n),t.push(n)}return n.shift()}});return[new zC(()=>n(e),this.controller,MP(this,OC,"f")),new zC(()=>n(t),this.controller,MP(this,OC,"f"))]}toReadableStream(){const e=this;let t;return JP({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:r,done:n}=await t.next();if(n)return e.close();const a=gC(JSON.stringify(r)+"\n");e.enqueue(a)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}class RC{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=function(e,t){const r=e.indexOf(t);if(-1!==r)return[e.substring(0,r),t,e.substring(r+t.length)];return[e,"",""]}(e,":");return n.startsWith(" ")&&(n=n.substring(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}}async function LC(e,t){const{response:r,requestLogID:n,retryOfRequestLogID:a,startTime:i}=t,s=await(async()=>{if(t.options.stream)return AC(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(r,t.controller,e):zC.fromSSEResponse(r,t.controller,e);if(204===r.status)return null;if(t.options.__binaryResponse)return r;const n=r.headers.get("content-type"),a=n?.split(";")[0]?.trim();if(a?.includes("application/json")||a?.endsWith("+json")){return MC(await r.json(),r)}return await r.text()})();return AC(e).debug(`[${n}] response parsed`,IC({retryOfRequestLogID:a,url:r.url,status:r.status,body:s,durationMs:Date.now()-i})),s}function MC(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}class DC extends Promise{constructor(e,t,r=LC){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=r,TC.set(this,void 0),LP(this,TC,e)}_thenUnwrap(e){return new DC(MP(this,TC,"f"),this.responsePromise,async(t,r)=>MC(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(MP(this,TC,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}TC=new WeakMap;class jC{constructor(e,t,r,n){$C.set(this,void 0),LP(this,$C,e),this.options=n,this.response=t,this.body=r}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageRequestOptions()}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new xE("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await MP(this,$C,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[($C=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class FC extends DC{constructor(e,t,r){super(e,t,async(e,t)=>new r(e,t.response,await LC(e,t),t.options))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}class UC extends jC{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class qC extends jC{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){const e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...qP(this.options.query),after:t}}:null}}class BC extends jC{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){const e=this.last_id;return e?{...this.options,query:{...qP(this.options.query),after:e}}:null}}const VC=()=>{if("undefined"==typeof File){const{process:e}=globalThis,t="string"==typeof e?.versions?.node&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function GC(e,t,r){return VC(),new File(e,t??"unknown_file",r)}function HC(e){return("object"==typeof e&&null!==e&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}const KC=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],WC=async(e,t)=>XC(e.body)?{...e,body:await YC(e.body,t)}:e,ZC=async(e,t)=>({...e,body:await YC(e.body,t)}),JC=new WeakMap;const YC=async(e,t)=>{if(!await function(e){const t="function"==typeof e?e:e.fetch,r=JC.get(t);if(r)return r;const n=(async()=>{try{const e="Response"in t?t.Response:(await t("data:,")).constructor,r=new FormData;return r.toString()!==await new e(r).text()}catch{return!0}})();return JC.set(t,n),n}(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const r=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>eA(r,e,t))),r},QC=e=>e instanceof Blob&&"name"in e,XC=e=>{if((e=>"object"==typeof e&&null!==e&&(e instanceof Response||KC(e)||QC(e)))(e))return!0;if(Array.isArray(e))return e.some(XC);if(e&&"object"==typeof e)for(const t in e)if(XC(e[t]))return!0;return!1},eA=async(e,t,r)=>{if(void 0!==r){if(null==r)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof r||"number"==typeof r||"boolean"==typeof r)e.append(t,String(r));else if(r instanceof Response)e.append(t,GC([await r.blob()],HC(r)));else if(KC(r))e.append(t,GC([await new Response(YP(r)).blob()],HC(r)));else if(QC(r))e.append(t,r,HC(r));else if(Array.isArray(r))await Promise.all(r.map(r=>eA(e,t+"[]",r)));else{if("object"!=typeof r)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`);await Promise.all(Object.entries(r).map(([r,n])=>eA(e,`${t}[${r}]`,n)))}}},tA=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function rA(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(tA(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else{if(!KC(e)){const t=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){if("object"!=typeof e||null===e)return"";const t=Object.getOwnPropertyNames(e);return`; props: [${t.map(e=>`"${e}"`).join(", ")}]`}(e)}`)}for await(const r of e)t.push(...await rA(r))}return t}class nA{constructor(e){this._client=e}}function aA(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const iA=Object.freeze(Object.create(null)),sA=(e=aA)=>function(t,...r){if(1===t.length)return t[0];let n=!1;const a=[],i=t.reduce((t,i,s)=>{/[?#]/.test(i)&&(n=!0);const o=r[s];let c=(n?encodeURIComponent:e)(""+o);return s!==r.length&&(null==o||"object"==typeof o&&o.toString===Object.getPrototypeOf(Object.getPrototypeOf(o.hasOwnProperty??iA)??iA)?.toString)&&(c=o+"",a.push({start:t.length+i.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(o).slice(8,-1)} is not a valid path parameter`})),t+i+(s===r.length?"":c)},""),s=i.split(/[?#]/,1)[0],o=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let c;for(;null!==(c=o.exec(s));)a.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(a.sort((e,t)=>e.start-t.start),a.length>0){let e=0;const t=a.reduce((t,r)=>{const n=" ".repeat(r.start-e),a="^".repeat(r.length);return e=r.start+r.length,t+n+a},"");throw new xE(`Path parameters result in path with invalid segments:\n${a.map(e=>e.error).join("\n")}\n${i}\n${t}`)}return i},oA=sA(aA);let cA=class extends nA{list(e,t={},r){return this._client.getAPIList(oA`/chat/completions/${e}/messages`,qC,{query:t,...r})}};const lA=e=>"assistant"===e?.role,uA=e=>"tool"===e?.role;var dA,pA,mA,hA,fA,gA,yA,vA,bA,_A,wA,SA,NA,kA,xA,EA,PA,CA,AA,IA,OA;class TA{constructor(){dA.add(this),this.controller=new AbortController,pA.set(this,void 0),mA.set(this,()=>{}),hA.set(this,()=>{}),fA.set(this,void 0),gA.set(this,()=>{}),yA.set(this,()=>{}),vA.set(this,{}),bA.set(this,!1),_A.set(this,!1),wA.set(this,!1),SA.set(this,!1),LP(this,pA,new Promise((e,t)=>{LP(this,mA,e),LP(this,hA,t)})),LP(this,fA,new Promise((e,t)=>{LP(this,gA,e),LP(this,yA,t)})),MP(this,pA,"f").catch(()=>{}),MP(this,fA,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},MP(this,dA,"m",NA).bind(this))},0)}_connected(){this.ended||(MP(this,mA,"f").call(this),this._emit("connect"))}get ended(){return MP(this,bA,"f")}get errored(){return MP(this,_A,"f")}get aborted(){return MP(this,wA,"f")}abort(){this.controller.abort()}on(e,t){return(MP(this,vA,"f")[e]||(MP(this,vA,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=MP(this,vA,"f")[e];if(!r)return this;const n=r.findIndex(e=>e.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(MP(this,vA,"f")[e]||(MP(this,vA,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{LP(this,SA,!0),"error"!==e&&this.once("error",r),this.once(e,t)})}async done(){LP(this,SA,!0),await MP(this,fA,"f")}_emit(e,...t){if(MP(this,bA,"f"))return;"end"===e&&(LP(this,bA,!0),MP(this,gA,"f").call(this));const r=MP(this,vA,"f")[e];if(r&&(MP(this,vA,"f")[e]=r.filter(e=>!e.once),r.forEach(({listener:e})=>e(...t))),"abort"===e){const e=t[0];return MP(this,SA,"f")||r?.length||Promise.reject(e),MP(this,hA,"f").call(this,e),MP(this,yA,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];MP(this,SA,"f")||r?.length||Promise.reject(e),MP(this,hA,"f").call(this,e),MP(this,yA,"f").call(this,e),this._emit("end")}}_emitFinal(){}}function $A(e){return"function"==typeof e.parse}pA=new WeakMap,mA=new WeakMap,hA=new WeakMap,fA=new WeakMap,gA=new WeakMap,yA=new WeakMap,vA=new WeakMap,bA=new WeakMap,_A=new WeakMap,wA=new WeakMap,SA=new WeakMap,dA=new WeakSet,NA=function(e){if(LP(this,_A,!0),e instanceof Error&&"AbortError"===e.name&&(e=new PE),e instanceof PE)return LP(this,wA,!0),this._emit("abort",e);if(e instanceof xE)return this._emit("error",e);if(e instanceof Error){const t=new xE(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new xE(String(e)))};const zA=10;class RA extends TA{constructor(){super(...arguments),kA.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t)if(this._emit("message",e),uA(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(lA(e)&&e.tool_calls)for(const t of e.tool_calls)"function"===t.type&&this._emit("functionToolCall",t.function)}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new xE("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),MP(this,kA,"m",xA).call(this)}async finalMessage(){return await this.done(),MP(this,kA,"m",EA).call(this)}async finalFunctionToolCall(){return await this.done(),MP(this,kA,"m",PA).call(this)}async finalFunctionToolCallResult(){return await this.done(),MP(this,kA,"m",CA).call(this)}async totalUsage(){return await this.done(),MP(this,kA,"m",AA).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=MP(this,kA,"m",EA).call(this);t&&this._emit("finalMessage",t);const r=MP(this,kA,"m",xA).call(this);r&&this._emit("finalContent",r);const n=MP(this,kA,"m",PA).call(this);n&&this._emit("finalFunctionToolCall",n);const a=MP(this,kA,"m",CA).call(this);null!=a&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(e=>e.usage)&&this._emit("totalUsage",MP(this,kA,"m",AA).call(this))}async _createChatCompletion(e,t,r){const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),MP(this,kA,"m",IA).call(this,t);const a=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(VE(a,t))}async _runChatCompletion(e,t,r){for(const e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){const n="tool",{tool_choice:a="auto",stream:i,...s}=t,o="string"!=typeof a&&"function"===a.type&&a?.function?.name,{maxChatCompletions:c=zA}=r||{},l=t.tools.map(e=>{if(BE(e)){if(!e.$callback)throw new xE("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:e.$callback,name:e.function.name,description:e.function.description||"",parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),u={};for(const e of l)"function"===e.type&&(u[e.function.name||e.function.function.name]=e.function);const d="tools"in t?l.map(e=>"function"===e.type?{type:"function",function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(const e of t.messages)this._addMessage(e,!1);for(let t=0;t<c;++t){const t=await this._createChatCompletion(e,{...s,tool_choice:a,tools:d,messages:[...this.messages]},r),i=t.choices[0]?.message;if(!i)throw new xE("missing message in ChatCompletion response");if(!i.tool_calls?.length)return;for(const e of i.tool_calls){if("function"!==e.type)continue;const t=e.id,{name:r,arguments:a}=e.function,i=u[r];if(!i){const e=`Invalid tool_call: ${JSON.stringify(r)}. Available options are: ${Object.keys(u).map(e=>JSON.stringify(e)).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:t,content:e});continue}if(o&&o!==r){const e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(o)} requested. Please try again`;this._addMessage({role:n,tool_call_id:t,content:e});continue}let s;try{s=$A(i)?await i.parse(a):a}catch(e){const r=e instanceof Error?e.message:String(e);this._addMessage({role:n,tool_call_id:t,content:r});continue}const c=await i.function(s,this),l=MP(this,kA,"m",OA).call(this,c);if(this._addMessage({role:n,tool_call_id:t,content:l}),o)return}}}}kA=new WeakSet,xA=function(){return MP(this,kA,"m",EA).call(this).content??null},EA=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(lA(t)){return{...t,content:t.content??null,refusal:t.refusal??null}}}throw new xE("stream ended without producing a ChatCompletionMessage with role=assistant")},PA=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(lA(t)&&t?.tool_calls?.length)return t.tool_calls.filter(e=>"function"===e.type).at(-1)?.function}},CA=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(uA(t)&&null!=t.content&&"string"==typeof t.content&&this.messages.some(e=>"assistant"===e.role&&e.tool_calls?.some(e=>"function"===e.type&&e.id===t.tool_call_id)))return t.content}},AA=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},IA=function(e){if(null!=e.n&&e.n>1)throw new xE("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},OA=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class LA extends RA{static runTools(e,t,r){const n=new LA,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,a)),n}_addMessage(e,t=!0){super._addMessage(e,t),lA(e)&&e.content&&this._emit("content",e.content)}}const MA=1,DA=2,jA=4,FA=8,UA=16,qA=32,BA=64,VA=128,GA=256,HA=511;class KA extends Error{}class WA extends Error{}const ZA=(e,t)=>{const r=e.length;let n=0;const a=e=>{throw new KA(`${e} at position ${n}`)},i=e=>{throw new WA(`${e} at position ${n}`)},s=()=>(d(),n>=r&&a("Unexpected end of input"),'"'===e[n]?o():"{"===e[n]?c():"["===e[n]?l():"null"===e.substring(n,n+4)||UA&t&&r-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):"true"===e.substring(n,n+4)||qA&t&&r-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):"false"===e.substring(n,n+5)||qA&t&&r-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):"Infinity"===e.substring(n,n+8)||VA&t&&r-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):"-Infinity"===e.substring(n,n+9)||GA&t&&1<r-n&&r-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):"NaN"===e.substring(n,n+3)||BA&t&&r-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):u()),o=()=>{const s=n;let o=!1;for(n++;n<r&&('"'!==e[n]||o&&"\\"===e[n-1]);)o="\\"===e[n]&&!o,n++;if('"'==e.charAt(n))try{return JSON.parse(e.substring(s,++n-Number(o)))}catch(e){i(String(e))}else if(MA&t)try{return JSON.parse(e.substring(s,n-Number(o))+'"')}catch(t){return JSON.parse(e.substring(s,e.lastIndexOf("\\"))+'"')}a("Unterminated string literal")},c=()=>{n++,d();const i={};try{for(;"}"!==e[n];){if(d(),n>=r&&FA&t)return i;const a=o();d(),n++;try{const e=s();Object.defineProperty(i,a,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(FA&t)return i;throw e}d(),","===e[n]&&n++}}catch(e){if(FA&t)return i;a("Expected '}' at end of object")}return n++,i},l=()=>{n++;const r=[];try{for(;"]"!==e[n];)r.push(s()),d(),","===e[n]&&n++}catch(e){if(jA&t)return r;a("Expected ']' at end of array")}return n++,r},u=()=>{if(0===n){"-"===e&&DA&t&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(r){if(DA&t)try{return"."===e[e.length-1]?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(e){}i(String(r))}}const s=n;for("-"===e[n]&&n++;e[n]&&!",]}".includes(e[n]);)n++;n!=r||DA&t||a("Unterminated number literal");try{return JSON.parse(e.substring(s,n))}catch(r){"-"===e.substring(s,n)&&DA&t&&a("Not sure what '-' is");try{return JSON.parse(e.substring(s,e.lastIndexOf("e")))}catch(e){i(String(e))}}},d=()=>{for(;n<r&&" \n\r\t".includes(e[n]);)n++};return s()},JA=e=>function(e,t=HA){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return ZA(e.trim(),t)}(e,HA^DA);var YA,QA,XA,eI,tI,rI,nI,aI,iI,sI,oI,cI;class lI extends RA{constructor(e){super(),YA.add(this),QA.set(this,void 0),XA.set(this,void 0),eI.set(this,void 0),LP(this,QA,e),LP(this,XA,[])}get currentChatCompletionSnapshot(){return MP(this,eI,"f")}static fromReadableStream(e){const t=new lI(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){const n=new lI(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,t,r){super._createChatCompletion;const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),MP(this,YA,"m",tI).call(this);const a=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const e of a)MP(this,YA,"m",nI).call(this,e);if(a.controller.signal?.aborted)throw new PE;return this._addChatCompletion(MP(this,YA,"m",sI).call(this))}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),MP(this,YA,"m",tI).call(this),this._connected();const n=zC.fromReadableStream(e,this.controller);let a;for await(const e of n)a&&a!==e.id&&this._addChatCompletion(MP(this,YA,"m",sI).call(this)),MP(this,YA,"m",nI).call(this,e),a=e.id;if(n.controller.signal?.aborted)throw new PE;return this._addChatCompletion(MP(this,YA,"m",sI).call(this))}[(QA=new WeakMap,XA=new WeakMap,eI=new WeakMap,YA=new WeakSet,tI=function(){this.ended||LP(this,eI,void 0)},rI=function(e){let t=MP(this,XA,"f")[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},MP(this,XA,"f")[e.index]=t,t)},nI=function(e){if(this.ended)return;const t=MP(this,YA,"m",cI).call(this,e);this._emit("chunk",e,t);for(const r of e.choices){const e=t.choices[r.index];null!=r.delta.content&&"assistant"===e.message?.role&&e.message?.content&&(this._emit("content",r.delta.content,e.message.content),this._emit("content.delta",{delta:r.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),null!=r.delta.refusal&&"assistant"===e.message?.role&&e.message?.refusal&&this._emit("refusal.delta",{delta:r.delta.refusal,snapshot:e.message.refusal}),null!=r.logprobs?.content&&"assistant"===e.message?.role&&this._emit("logprobs.content.delta",{content:r.logprobs?.content,snapshot:e.logprobs?.content??[]}),null!=r.logprobs?.refusal&&"assistant"===e.message?.role&&this._emit("logprobs.refusal.delta",{refusal:r.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});const n=MP(this,YA,"m",rI).call(this,e);e.finish_reason&&(MP(this,YA,"m",iI).call(this,e),null!=n.current_tool_call_index&&MP(this,YA,"m",aI).call(this,e,n.current_tool_call_index));for(const t of r.delta.tool_calls??[])n.current_tool_call_index!==t.index&&(MP(this,YA,"m",iI).call(this,e),null!=n.current_tool_call_index&&MP(this,YA,"m",aI).call(this,e,n.current_tool_call_index)),n.current_tool_call_index=t.index;for(const t of r.delta.tool_calls??[]){const r=e.message.tool_calls?.[t.index];r?.type&&("function"===r?.type?this._emit("tool_calls.function.arguments.delta",{name:r.function?.name,index:t.index,arguments:r.function.arguments,parsed_arguments:r.function.parsed_arguments,arguments_delta:t.function?.arguments??""}):dI(r?.type))}}},aI=function(e,t){if(MP(this,YA,"m",rI).call(this,e).done_tool_calls.has(t))return;const r=e.message.tool_calls?.[t];if(!r)throw new Error("no tool call snapshot");if(!r.type)throw new Error("tool call snapshot missing `type`");if("function"===r.type){const e=MP(this,QA,"f")?.tools?.find(e=>UE(e)&&e.function.name===r.function.name);this._emit("tool_calls.function.arguments.done",{name:r.function.name,index:t,arguments:r.function.arguments,parsed_arguments:BE(e)?e.$parseRaw(r.function.arguments):e?.function.strict?JSON.parse(r.function.arguments):null})}else r.type},iI=function(e){const t=MP(this,YA,"m",rI).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;const r=MP(this,YA,"m",oI).call(this);this._emit("content.done",{content:e.message.content,parsed:r?r.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit("refusal.done",{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:e.logprobs.refusal}))},sI=function(){if(this.ended)throw new xE("stream has ended, this shouldn't happen");const e=MP(this,eI,"f");if(!e)throw new xE("request ended without sending any chunks");return LP(this,eI,void 0),LP(this,XA,[]),function(e,t){const{id:r,choices:n,created:a,model:i,system_fingerprint:s,...o}=e,c={...o,id:r,choices:n.map(({message:t,finish_reason:r,index:n,logprobs:a,...i})=>{if(!r)throw new xE(`missing finish_reason for choice ${n}`);const{content:s=null,function_call:o,tool_calls:c,...l}=t,u=t.role;if(!u)throw new xE(`missing role for choice ${n}`);if(o){const{arguments:e,name:c}=o;if(null==e)throw new xE(`missing function_call.arguments for choice ${n}`);if(!c)throw new xE(`missing function_call.name for choice ${n}`);return{...i,message:{content:s,function_call:{arguments:e,name:c},role:u,refusal:t.refusal??null},finish_reason:r,index:n,logprobs:a}}return c?{...i,index:n,finish_reason:r,logprobs:a,message:{...l,role:u,content:s,refusal:t.refusal??null,tool_calls:c.map((t,r)=>{const{function:a,type:i,id:s,...o}=t,{arguments:c,name:l,...u}=a||{};if(null==s)throw new xE(`missing choices[${n}].tool_calls[${r}].id\n${uI(e)}`);if(null==i)throw new xE(`missing choices[${n}].tool_calls[${r}].type\n${uI(e)}`);if(null==l)throw new xE(`missing choices[${n}].tool_calls[${r}].function.name\n${uI(e)}`);if(null==c)throw new xE(`missing choices[${n}].tool_calls[${r}].function.arguments\n${uI(e)}`);return{...o,id:s,type:i,function:{...u,name:l,arguments:c}}})}}:{...i,message:{...l,content:s,role:u,refusal:t.refusal??null},finish_reason:r,index:n,logprobs:a}}),created:a,model:i,object:"chat.completion",...s?{system_fingerprint:s}:{}};return function(e,t){return t&&KE(t)?VE(e,t):{...e,choices:e.choices.map(e=>(WE(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}}(c,t)}(e,MP(this,QA,"f"))},oI=function(){const e=MP(this,QA,"f")?.response_format;return qE(e)?e:null},cI=function(e){var t,r,n,a;let i=MP(this,eI,"f");const{choices:s,...o}=e;i?Object.assign(i,o):i=LP(this,eI,{...o,choices:[]});for(const{delta:s,finish_reason:o,index:c,logprobs:l=null,...u}of e.choices){let e=i.choices[c];if(e||(e=i.choices[c]={finish_reason:o,index:c,message:{},logprobs:l,...u}),l)if(e.logprobs){const{content:n,refusal:a,...i}=l;Object.assign(e.logprobs,i),n&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...n)),a&&((r=e.logprobs).refusal??(r.refusal=[]),e.logprobs.refusal.push(...a))}else e.logprobs=Object.assign({},l);if(o&&(e.finish_reason=o,MP(this,QA,"f")&&KE(MP(this,QA,"f")))){if("length"===o)throw new DE;if("content_filter"===o)throw new jE}if(Object.assign(e,u),!s)continue;const{content:d,refusal:p,function_call:m,role:h,tool_calls:f,...g}=s;if(Object.assign(e.message,g),p&&(e.message.refusal=(e.message.refusal||"")+p),h&&(e.message.role=h),m&&(e.message.function_call?(m.name&&(e.message.function_call.name=m.name),m.arguments&&((n=e.message.function_call).arguments??(n.arguments=""),e.message.function_call.arguments+=m.arguments)):e.message.function_call=m),d&&(e.message.content=(e.message.content||"")+d,!e.message.refusal&&MP(this,YA,"m",oI).call(this)&&(e.message.parsed=JA(e.message.content))),f){e.message.tool_calls||(e.message.tool_calls=[]);for(const{index:t,id:r,type:n,function:i,...s}of f){const o=(a=e.message.tool_calls)[t]??(a[t]={});Object.assign(o,s),r&&(o.id=r),n&&(o.type=n),i&&(o.function??(o.function={name:i.name??"",arguments:""})),i?.name&&(o.function.name=i.name),i?.arguments&&(o.function.arguments+=i.arguments,HE(MP(this,QA,"f"),o)&&(o.function.parsed_arguments=JA(o.function.arguments)))}}}return i},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("chunk",r=>{const n=t.shift();n?n.resolve(r):e.push(r)}),this.on("end",()=>{r=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{r=!0;for(const r of t)r.reject(e);t.length=0}),this.on("error",e=>{r=!0;for(const r of t)r.reject(e);t.length=0}),{next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise((e,r)=>t.push({resolve:e,reject:r})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new zC(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function uI(e){return JSON.stringify(e)}function dI(e){}class pI extends lI{static fromReadableStream(e){const t=new pI(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){const n=new pI(t),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,a)),n}}let mI=class extends nA{constructor(){super(...arguments),this.messages=new cA(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(oA`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(oA`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",qC,{query:e,...t})}delete(e,t){return this._client.delete(oA`/chat/completions/${e}`,t)}parse(e,t){return function(e){for(const t of e??[]){if("function"!==t.type)throw new xE(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new xE(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(t=>VE(t,e))}runTools(e,t){return e.stream?pI.runTools(this._client,e,t):LA.runTools(this._client,e,t)}stream(e,t){return lI.createChatCompletion(this._client,e,t)}};mI.Messages=cA;class hI extends nA{constructor(){super(...arguments),this.completions=new mI(this._client)}}hI.Completions=mI;const fI=Symbol("brand.privateNullableHeaders");function*gI(e){if(!e)return;if(fI in e){const{values:t,nulls:r}=e;yield*t.entries();for(const e of r)yield[e,null];return}let t,r=!1;e instanceof Headers?t=e.entries():UP(e)?t=e:(r=!0,t=Object.entries(e??{}));for(let e of t){const t=e[0];if("string"!=typeof t)throw new TypeError("expected header name to be a string");const n=UP(e[1])?e[1]:[e[1]];let a=!1;for(const e of n)void 0!==e&&(r&&!a&&(a=!0,yield[t,null]),yield[t,e])}}const yI=e=>{const t=new Headers,r=new Set;for(const n of e){const e=new Set;for(const[a,i]of gI(n)){const n=a.toLowerCase();e.has(n)||(t.delete(a),e.add(n)),null===i?(t.delete(a),r.add(n)):(t.append(a,i),r.delete(n))}}return{[fI]:!0,values:t,nulls:r}};class vI extends nA{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:yI([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class bI extends nA{create(e,t){return this._client.post("/audio/transcriptions",ZC({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class _I extends nA{create(e,t){return this._client.post("/audio/translations",ZC({body:e,...t,__metadata:{model:e.model}},this._client))}}class wI extends nA{constructor(){super(...arguments),this.transcriptions=new bI(this._client),this.translations=new _I(this._client),this.speech=new vI(this._client)}}wI.Transcriptions=bI,wI.Translations=_I,wI.Speech=vI;class SI extends nA{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(oA`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",qC,{query:e,...t})}cancel(e,t){return this._client.post(oA`/batches/${e}/cancel`,t)}}class NI extends nA{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:yI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(oA`/assistants/${e}`,{...t,headers:yI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(oA`/assistants/${e}`,{body:t,...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",qC,{query:e,...t,headers:yI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(oA`/assistants/${e}`,{...t,headers:yI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}let kI=class extends nA{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:yI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};class xI extends nA{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:yI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}let EI=class extends nA{constructor(){super(...arguments),this.sessions=new kI(this._client),this.transcriptionSessions=new xI(this._client)}};EI.Sessions=kI,EI.TranscriptionSessions=xI;class PI extends nA{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:yI([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(oA`/chatkit/sessions/${e}/cancel`,{...t,headers:yI([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}}let CI=class extends nA{retrieve(e,t){return this._client.get(oA`/chatkit/threads/${e}`,{...t,headers:yI([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",BC,{query:e,...t,headers:yI([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(oA`/chatkit/threads/${e}`,{...t,headers:yI([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},r){return this._client.getAPIList(oA`/chatkit/threads/${e}/items`,BC,{query:t,...r,headers:yI([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}};class AI extends nA{constructor(){super(...arguments),this.sessions=new PI(this._client),this.threads=new CI(this._client)}}AI.Sessions=PI,AI.Threads=CI;class II extends nA{create(e,t,r){return this._client.post(oA`/threads/${e}/messages`,{body:t,...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){const{thread_id:n}=t;return this._client.get(oA`/threads/${n}/messages/${e}`,{...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){const{thread_id:n,...a}=t;return this._client.post(oA`/threads/${n}/messages/${e}`,{body:a,...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(oA`/threads/${e}/messages`,qC,{query:t,...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){const{thread_id:n}=t;return this._client.delete(oA`/threads/${n}/messages/${e}`,{...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class OI extends nA{retrieve(e,t,r){const{thread_id:n,run_id:a,...i}=t;return this._client.get(oA`/threads/${n}/runs/${a}/steps/${e}`,{query:i,...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){const{thread_id:n,...a}=t;return this._client.getAPIList(oA`/threads/${n}/runs/${e}/steps`,qC,{query:a,...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}const TI=e=>void 0!==globalThis.process?globalThis.process.env?.[e]?.trim()??void 0:void 0!==globalThis.Deno?globalThis.Deno.env?.get?.(e)?.trim():void 0;var $I,zI,RI,LI,MI,DI,jI,FI,UI,qI,BI,VI,GI,HI,KI,WI,ZI,JI,YI,QI,XI,eO,tO;class rO extends TA{constructor(){super(...arguments),$I.add(this),RI.set(this,[]),LI.set(this,{}),MI.set(this,{}),DI.set(this,void 0),jI.set(this,void 0),FI.set(this,void 0),UI.set(this,void 0),qI.set(this,void 0),BI.set(this,void 0),VI.set(this,void 0),GI.set(this,void 0),HI.set(this,void 0)}[(RI=new WeakMap,LI=new WeakMap,MI=new WeakMap,DI=new WeakMap,jI=new WeakMap,FI=new WeakMap,UI=new WeakMap,qI=new WeakMap,BI=new WeakMap,VI=new WeakMap,GI=new WeakMap,HI=new WeakMap,$I=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("event",r=>{const n=t.shift();n?n.resolve(r):e.push(r)}),this.on("end",()=>{r=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{r=!0;for(const r of t)r.reject(e);t.length=0}),this.on("error",e=>{r=!0;for(const r of t)r.reject(e);t.length=0}),{next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise((e,r)=>t.push({resolve:e,reject:r})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new zI;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();const n=zC.fromReadableStream(e,this.controller);for await(const e of n)MP(this,$I,"m",KI).call(this,e);if(n.controller.signal?.aborted)throw new PE;return this._addRun(MP(this,$I,"m",WI).call(this))}toReadableStream(){return new zC(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n){const a=new zI;return a._run(()=>a._runToolAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,t,r,n){const a=n?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...r,stream:!0},s=await e.submitToolOutputs(t,i,{...n,signal:this.controller.signal});this._connected();for await(const e of s)MP(this,$I,"m",KI).call(this,e);if(s.controller.signal?.aborted)throw new PE;return this._addRun(MP(this,$I,"m",WI).call(this))}static createThreadAssistantStream(e,t,r){const n=new zI;return n._run(()=>n._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,r,n){const a=new zI;return a._run(()=>a._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return MP(this,VI,"f")}currentRun(){return MP(this,GI,"f")}currentMessageSnapshot(){return MP(this,DI,"f")}currentRunStepSnapshot(){return MP(this,HI,"f")}async finalRunSteps(){return await this.done(),Object.values(MP(this,LI,"f"))}async finalMessages(){return await this.done(),Object.values(MP(this,MI,"f"))}async finalRun(){if(await this.done(),!MP(this,jI,"f"))throw Error("Final run was not received.");return MP(this,jI,"f")}async _createThreadAssistantStream(e,t,r){const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort()));const a={...t,stream:!0},i=await e.createAndRun(a,{...r,signal:this.controller.signal});this._connected();for await(const e of i)MP(this,$I,"m",KI).call(this,e);if(i.controller.signal?.aborted)throw new PE;return this._addRun(MP(this,$I,"m",WI).call(this))}async _createAssistantStream(e,t,r,n){const a=n?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...r,stream:!0},s=await e.create(t,i,{...n,signal:this.controller.signal});this._connected();for await(const e of s)MP(this,$I,"m",KI).call(this,e);if(s.controller.signal?.aborted)throw new PE;return this._addRun(MP(this,$I,"m",WI).call(this))}static accumulateDelta(e,t){for(const[r,n]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=n;continue}let t=e[r];if(null!=t)if("index"!==r&&"type"!==r){if("string"==typeof t&&"string"==typeof n)t+=n;else if("number"==typeof t&&"number"==typeof n)t+=n;else{if(!BP(t)||!BP(n)){if(Array.isArray(t)&&Array.isArray(n)){if(t.every(e=>"string"==typeof e||"number"==typeof e)){t.push(...n);continue}for(const e of n){if(!BP(e))throw new Error(`Expected array delta entry to be an object but got: ${e}`);const r=e.index;if(null==r)throw console.error(e),new Error("Expected array delta entry to have an `index` property");if("number"!=typeof r)throw new Error(`Expected array delta entry \`index\` property to be a number but got ${r}`);const n=t[r];null==n?t.push(e):t[r]=this.accumulateDelta(n,e)}continue}throw Error(`Unhandled record type: ${r}, deltaValue: ${n}, accValue: ${t}`)}t=this.accumulateDelta(t,n)}e[r]=t}else e[r]=n;else e[r]=n}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,n){return await this._createAssistantStream(t,e,r,n)}async _runToolAssistantStream(e,t,r,n){return await this._createToolAssistantStream(t,e,r,n)}}zI=rO,KI=function(e){if(!this.ended)switch(LP(this,VI,e),MP(this,$I,"m",YI).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":MP(this,$I,"m",tO).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":MP(this,$I,"m",JI).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":MP(this,$I,"m",ZI).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},WI=function(){if(this.ended)throw new xE("stream has ended, this shouldn't happen");if(!MP(this,jI,"f"))throw Error("Final run has not been received");return MP(this,jI,"f")},ZI=function(e){const[t,r]=MP(this,$I,"m",XI).call(this,e,MP(this,DI,"f"));LP(this,DI,t),MP(this,MI,"f")[t.id]=t;for(const e of r){const r=t.content[e.index];"text"==r?.type&&this._emit("textCreated",r.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const r of e.data.delta.content){if("text"==r.type&&r.text){let e=r.text,n=t.content[r.index];if(!n||"text"!=n.type)throw Error("The snapshot associated with this text delta is not text or missing");this._emit("textDelta",e,n.text)}if(r.index!=MP(this,FI,"f")){if(MP(this,UI,"f"))switch(MP(this,UI,"f").type){case"text":this._emit("textDone",MP(this,UI,"f").text,MP(this,DI,"f"));break;case"image_file":this._emit("imageFileDone",MP(this,UI,"f").image_file,MP(this,DI,"f"))}LP(this,FI,r.index)}LP(this,UI,t.content[r.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==MP(this,FI,"f")){const t=e.data.content[MP(this,FI,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,MP(this,DI,"f"));break;case"text":this._emit("textDone",t.text,MP(this,DI,"f"))}}MP(this,DI,"f")&&this._emit("messageDone",e.data),LP(this,DI,void 0)}},JI=function(e){const t=MP(this,$I,"m",QI).call(this,e);switch(LP(this,HI,t),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const r=e.data.delta;if(r.step_details&&"tool_calls"==r.step_details.type&&r.step_details.tool_calls&&"tool_calls"==t.step_details.type)for(const e of r.step_details.tool_calls)e.index==MP(this,qI,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(MP(this,BI,"f")&&this._emit("toolCallDone",MP(this,BI,"f")),LP(this,qI,e.index),LP(this,BI,t.step_details.tool_calls[e.index]),MP(this,BI,"f")&&this._emit("toolCallCreated",MP(this,BI,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":LP(this,HI,void 0);"tool_calls"==e.data.step_details.type&&MP(this,BI,"f")&&(this._emit("toolCallDone",MP(this,BI,"f")),LP(this,BI,void 0)),this._emit("runStepDone",e.data,t)}},YI=function(e){MP(this,RI,"f").push(e),this._emit("event",e)},QI=function(e){switch(e.event){case"thread.run.step.created":return MP(this,LI,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=MP(this,LI,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){const n=zI.accumulateDelta(t,r.delta);MP(this,LI,"f")[e.data.id]=n}return MP(this,LI,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":MP(this,LI,"f")[e.data.id]=e.data}if(MP(this,LI,"f")[e.data.id])return MP(this,LI,"f")[e.data.id];throw new Error("No snapshot available")},XI=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(const e of n.delta.content)if(e.index in t.content){let r=t.content[e.index];t.content[e.index]=MP(this,$I,"m",eO).call(this,e,r)}else t.content[e.index]=e,r.push(e);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},eO=function(e,t){return zI.accumulateDelta(t,e)},tO=function(e){switch(LP(this,GI,e.data),e.event){case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":LP(this,jI,e.data),MP(this,BI,"f")&&(this._emit("toolCallDone",MP(this,BI,"f")),LP(this,BI,void 0))}};let nO=class extends nA{constructor(){super(...arguments),this.steps=new OI(this._client)}create(e,t,r){const{include:n,...a}=t;return this._client.post(oA`/threads/${e}/runs`,{query:{include:n},body:a,...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}retrieve(e,t,r){const{thread_id:n}=t;return this._client.get(oA`/threads/${n}/runs/${e}`,{...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){const{thread_id:n,...a}=t;return this._client.post(oA`/threads/${n}/runs/${e}`,{body:a,...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(oA`/threads/${e}/runs`,qC,{query:t,...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){const{thread_id:n}=t;return this._client.post(oA`/threads/${n}/runs/${e}/cancel`,{...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){const n=await this.create(e,t,r);return await this.poll(n.id,{thread_id:e},r)}createAndStream(e,t,r){return rO.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){const n=yI([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:a,response:i}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...n}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let e=5e3;if(r?.pollIntervalMs)e=r.pollIntervalMs;else{const t=i.headers.get("openai-poll-after-ms");if(t){const r=parseInt(t);isNaN(r)||(e=r)}}await VP(e);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,t,r){return rO.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){const{thread_id:n,...a}=t;return this._client.post(oA`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:a,...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,r){const n=await this.submitToolOutputs(e,t,r);return await this.poll(n.id,t,r)}submitToolOutputsStream(e,t,r){return rO.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};nO.Steps=OI;class aO extends nA{constructor(){super(...arguments),this.runs=new nO(this._client),this.messages=new II(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:yI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(oA`/threads/${e}`,{...t,headers:yI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(oA`/threads/${e}`,{body:t,...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(oA`/threads/${e}`,{...t,headers:yI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:yI([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){const r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return rO.createThreadAssistantStream(e,this._client.beta.threads,t)}}aO.Runs=nO,aO.Messages=II;class iO extends nA{constructor(){super(...arguments),this.realtime=new EI(this._client),this.chatkit=new AI(this._client),this.assistants=new NI(this._client),this.threads=new aO(this._client)}}iO.Realtime=EI,iO.ChatKit=AI,iO.Assistants=NI,iO.Threads=aO;class sO extends nA{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class oO extends nA{retrieve(e,t,r){const{container_id:n}=t;return this._client.get(oA`/containers/${n}/files/${e}/content`,{...r,headers:yI([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}let cO=class extends nA{constructor(){super(...arguments),this.content=new oO(this._client)}create(e,t,r){return this._client.post(oA`/containers/${e}/files`,ZC({body:t,...r},this._client))}retrieve(e,t,r){const{container_id:n}=t;return this._client.get(oA`/containers/${n}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(oA`/containers/${e}/files`,qC,{query:t,...r})}delete(e,t,r){const{container_id:n}=t;return this._client.delete(oA`/containers/${n}/files/${e}`,{...r,headers:yI([{Accept:"*/*"},r?.headers])})}};cO.Content=oO;class lO extends nA{constructor(){super(...arguments),this.files=new cO(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(oA`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",qC,{query:e,...t})}delete(e,t){return this._client.delete(oA`/containers/${e}`,{...t,headers:yI([{Accept:"*/*"},t?.headers])})}}lO.Files=cO;class uO extends nA{create(e,t,r){const{include:n,...a}=t;return this._client.post(oA`/conversations/${e}/items`,{query:{include:n},body:a,...r})}retrieve(e,t,r){const{conversation_id:n,...a}=t;return this._client.get(oA`/conversations/${n}/items/${e}`,{query:a,...r})}list(e,t={},r){return this._client.getAPIList(oA`/conversations/${e}/items`,BC,{query:t,...r})}delete(e,t,r){const{conversation_id:n}=t;return this._client.delete(oA`/conversations/${n}/items/${e}`,r)}}class dO extends nA{constructor(){super(...arguments),this.items=new uO(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(oA`/conversations/${e}`,t)}update(e,t,r){return this._client.post(oA`/conversations/${e}`,{body:t,...r})}delete(e,t){return this._client.delete(oA`/conversations/${e}`,t)}}dO.Items=uO;let pO=class extends nA{create(e,t){const r=!!e.encoding_format;let n=r?e.encoding_format:"base64";r&&AC(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const a=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t});return r?a:(AC(this._client).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{const t=e.embedding;e.embedding=(e=>{if("undefined"!=typeof Buffer){const t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}{const t=atob(e),r=t.length,n=new Uint8Array(r);for(let e=0;e<r;e++)n[e]=t.charCodeAt(e);return Array.from(new Float32Array(n.buffer))}})(t)}),e)))}};class mO extends nA{retrieve(e,t,r){const{eval_id:n,run_id:a}=t;return this._client.get(oA`/evals/${n}/runs/${a}/output_items/${e}`,r)}list(e,t,r){const{eval_id:n,...a}=t;return this._client.getAPIList(oA`/evals/${n}/runs/${e}/output_items`,qC,{query:a,...r})}}class hO extends nA{constructor(){super(...arguments),this.outputItems=new mO(this._client)}create(e,t,r){return this._client.post(oA`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){const{eval_id:n}=t;return this._client.get(oA`/evals/${n}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(oA`/evals/${e}/runs`,qC,{query:t,...r})}delete(e,t,r){const{eval_id:n}=t;return this._client.delete(oA`/evals/${n}/runs/${e}`,r)}cancel(e,t,r){const{eval_id:n}=t;return this._client.post(oA`/evals/${n}/runs/${e}`,r)}}hO.OutputItems=mO;class fO extends nA{constructor(){super(...arguments),this.runs=new hO(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(oA`/evals/${e}`,t)}update(e,t,r){return this._client.post(oA`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",qC,{query:e,...t})}delete(e,t){return this._client.delete(oA`/evals/${e}`,t)}}fO.Runs=hO;let gO=class extends nA{create(e,t){return this._client.post("/files",ZC({body:e,...t},this._client))}retrieve(e,t){return this._client.get(oA`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",qC,{query:e,...t})}delete(e,t){return this._client.delete(oA`/files/${e}`,t)}content(e,t){return this._client.get(oA`/files/${e}/content`,{...t,headers:yI([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=18e5}={}){const n=new Set(["processed","error","deleted"]),a=Date.now();let i=await this.retrieve(e);for(;!i.status||!n.has(i.status);)if(await VP(t),i=await this.retrieve(e),Date.now()-a>r)throw new AE({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};class yO extends nA{}let vO=class extends nA{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};class bO extends nA{constructor(){super(...arguments),this.graders=new vO(this._client)}}bO.Graders=vO;class _O extends nA{create(e,t,r){return this._client.getAPIList(oA`/fine_tuning/checkpoints/${e}/permissions`,UC,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(oA`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}delete(e,t,r){const{fine_tuned_model_checkpoint:n}=t;return this._client.delete(oA`/fine_tuning/checkpoints/${n}/permissions/${e}`,r)}}let wO=class extends nA{constructor(){super(...arguments),this.permissions=new _O(this._client)}};wO.Permissions=_O;class SO extends nA{list(e,t={},r){return this._client.getAPIList(oA`/fine_tuning/jobs/${e}/checkpoints`,qC,{query:t,...r})}}class NO extends nA{constructor(){super(...arguments),this.checkpoints=new SO(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(oA`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",qC,{query:e,...t})}cancel(e,t){return this._client.post(oA`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(oA`/fine_tuning/jobs/${e}/events`,qC,{query:t,...r})}pause(e,t){return this._client.post(oA`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(oA`/fine_tuning/jobs/${e}/resume`,t)}}NO.Checkpoints=SO;class kO extends nA{constructor(){super(...arguments),this.methods=new yO(this._client),this.jobs=new NO(this._client),this.checkpoints=new wO(this._client),this.alpha=new bO(this._client)}}kO.Methods=yO,kO.Jobs=NO,kO.Checkpoints=wO,kO.Alpha=bO;class xO extends nA{}class EO extends nA{constructor(){super(...arguments),this.graderModels=new xO(this._client)}}EO.GraderModels=xO;class PO extends nA{createVariation(e,t){return this._client.post("/images/variations",ZC({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",ZC({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}}class CO extends nA{retrieve(e,t){return this._client.get(oA`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",UC,e)}delete(e,t){return this._client.delete(oA`/models/${e}`,t)}}class AO extends nA{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class IO extends nA{accept(e,t,r){return this._client.post(oA`/realtime/calls/${e}/accept`,{body:t,...r,headers:yI([{Accept:"*/*"},r?.headers])})}hangup(e,t){return this._client.post(oA`/realtime/calls/${e}/hangup`,{...t,headers:yI([{Accept:"*/*"},t?.headers])})}refer(e,t,r){return this._client.post(oA`/realtime/calls/${e}/refer`,{body:t,...r,headers:yI([{Accept:"*/*"},r?.headers])})}reject(e,t={},r){return this._client.post(oA`/realtime/calls/${e}/reject`,{body:t,...r,headers:yI([{Accept:"*/*"},r?.headers])})}}class OO extends nA{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class TO extends nA{constructor(){super(...arguments),this.clientSecrets=new OO(this._client),this.calls=new IO(this._client)}}var $O,zO,RO,LO,MO,DO,jO,FO;TO.ClientSecrets=OO,TO.Calls=IO;class UO extends TA{constructor(e){super(),$O.add(this),zO.set(this,void 0),RO.set(this,void 0),LO.set(this,void 0),LP(this,zO,e)}static createResponse(e,t,r){const n=new UO(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,t,r){const n=r?.signal;let a;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),MP(this,$O,"m",MO).call(this);let i=null;"response_id"in t?(a=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):a=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(const e of a)MP(this,$O,"m",DO).call(this,e,i);if(a.controller.signal?.aborted)throw new PE;return MP(this,$O,"m",jO).call(this)}[(zO=new WeakMap,RO=new WeakMap,LO=new WeakMap,$O=new WeakSet,MO=function(){this.ended||LP(this,RO,void 0)},DO=function(e,t){if(this.ended)return;const r=(e,r)=>{(null==t||r.sequence_number>t)&&this._emit(e,r)},n=MP(this,$O,"m",FO).call(this,e);switch(r("event",e),e.type){case"response.output_text.delta":{const t=n.output[e.output_index];if(!t)throw new xE(`missing output at index ${e.output_index}`);if("message"===t.type){const n=t.content[e.content_index];if(!n)throw new xE(`missing content at index ${e.content_index}`);if("output_text"!==n.type)throw new xE(`expected content to be 'output_text', got ${n.type}`);r("response.output_text.delta",{...e,snapshot:n.text})}break}case"response.function_call_arguments.delta":{const t=n.output[e.output_index];if(!t)throw new xE(`missing output at index ${e.output_index}`);"function_call"===t.type&&r("response.function_call_arguments.delta",{...e,snapshot:t.arguments});break}default:r(e.type,e)}},jO=function(){if(this.ended)throw new xE("stream has ended, this shouldn't happen");const e=MP(this,RO,"f");if(!e)throw new xE("request ended without sending any events");LP(this,RO,void 0);const t=function(e,t){return xP(e,t)}(e,MP(this,zO,"f"));return LP(this,LO,t),t},FO=function(e){let t=MP(this,RO,"f");if(!t){if("response.created"!==e.type)throw new xE(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return t=LP(this,RO,e.response),t}switch(e.type){case"response.output_item.added":t.output.push(e.item);break;case"response.content_part.added":{const r=t.output[e.output_index];if(!r)throw new xE(`missing output at index ${e.output_index}`);const n=r.type,a=e.part;"message"===n&&"reasoning_text"!==a.type?r.content.push(a):"reasoning"===n&&"reasoning_text"===a.type&&(r.content||(r.content=[]),r.content.push(a));break}case"response.output_text.delta":{const r=t.output[e.output_index];if(!r)throw new xE(`missing output at index ${e.output_index}`);if("message"===r.type){const t=r.content[e.content_index];if(!t)throw new xE(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new xE(`expected content to be 'output_text', got ${t.type}`);t.text+=e.delta}break}case"response.function_call_arguments.delta":{const r=t.output[e.output_index];if(!r)throw new xE(`missing output at index ${e.output_index}`);"function_call"===r.type&&(r.arguments+=e.delta);break}case"response.reasoning_text.delta":{const r=t.output[e.output_index];if(!r)throw new xE(`missing output at index ${e.output_index}`);if("reasoning"===r.type){const t=r.content?.[e.content_index];if(!t)throw new xE(`missing content at index ${e.content_index}`);if("reasoning_text"!==t.type)throw new xE(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}break}case"response.completed":LP(this,RO,e.response)}return t},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("event",r=>{const n=t.shift();n?n.resolve(r):e.push(r)}),this.on("end",()=>{r=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{r=!0;for(const r of t)r.reject(e);t.length=0}),this.on("error",e=>{r=!0;for(const r of t)r.reject(e);t.length=0}),{next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise((e,r)=>t.push({resolve:e,reject:r})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=MP(this,LO,"f");if(!e)throw new xE("stream ended without producing a ChatCompletion");return e}}class qO extends nA{list(e,t={},r){return this._client.getAPIList(oA`/responses/${e}/input_items`,qC,{query:t,...r})}}class BO extends nA{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}}class VO extends nA{constructor(){super(...arguments),this.inputItems=new qO(this._client),this.inputTokens=new BO(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(e=>("object"in e&&"response"===e.object&&IP(e),e))}retrieve(e,t={},r){return this._client.get(oA`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap(e=>("object"in e&&"response"===e.object&&IP(e),e))}delete(e,t){return this._client.delete(oA`/responses/${e}`,{...t,headers:yI([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>EP(t,e))}stream(e,t){return UO.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(oA`/responses/${e}/cancel`,t)}}VO.InputItems=qO,VO.InputTokens=BO;class GO extends nA{create(e,t,r){return this._client.post(oA`/uploads/${e}/parts`,ZC({body:t,...r},this._client))}}class HO extends nA{constructor(){super(...arguments),this.parts=new GO(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(oA`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(oA`/uploads/${e}/complete`,{body:t,...r})}}HO.Parts=GO;class KO extends nA{create(e,t,r){return this._client.post(oA`/vector_stores/${e}/file_batches`,{body:t,...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){const{vector_store_id:n}=t;return this._client.get(oA`/vector_stores/${n}/file_batches/${e}`,{...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){const{vector_store_id:n}=t;return this._client.post(oA`/vector_stores/${n}/file_batches/${e}/cancel`,{...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){const n=await this.create(e,t);return await this.poll(e,n.id,r)}listFiles(e,t,r){const{vector_store_id:n,...a}=t;return this._client.getAPIList(oA`/vector_stores/${n}/file_batches/${e}/files`,qC,{query:a,...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){const n=yI([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:a,response:i}=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse();switch(a.status){case"in_progress":let e=5e3;if(r?.pollIntervalMs)e=r.pollIntervalMs;else{const t=i.headers.get("openai-poll-after-ms");if(t){const r=parseInt(t);isNaN(r)||(e=r)}}await VP(e);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},n){if(null==t||0==t.length)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const a=n?.maxConcurrency??5,i=Math.min(a,t.length),s=this._client,o=t.values(),c=[...r];const l=Array(i).fill(o).map(async function(e){for(let t of e){const e=await s.files.create({file:t,purpose:"assistants"},n);c.push(e.id)}});return await(async e=>{const t=await Promise.allSettled(e),r=t.filter(e=>"rejected"===e.status);if(r.length){for(const e of r)console.error(e.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}const n=[];for(const e of t)"fulfilled"===e.status&&n.push(e.value);return n})(l),await this.createAndPoll(e,{file_ids:c})}}class WO extends nA{create(e,t,r){return this._client.post(oA`/vector_stores/${e}/files`,{body:t,...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){const{vector_store_id:n}=t;return this._client.get(oA`/vector_stores/${n}/files/${e}`,{...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){const{vector_store_id:n,...a}=t;return this._client.post(oA`/vector_stores/${n}/files/${e}`,{body:a,...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(oA`/vector_stores/${e}/files`,qC,{query:t,...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){const{vector_store_id:n}=t;return this._client.delete(oA`/vector_stores/${n}/files/${e}`,{...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){const n=await this.create(e,t,r);return await this.poll(e,n.id,r)}async poll(e,t,r){const n=yI([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){const a=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse(),i=a.data;switch(i.status){case"in_progress":let e=5e3;if(r?.pollIntervalMs)e=r.pollIntervalMs;else{const t=a.response.headers.get("openai-poll-after-ms");if(t){const r=parseInt(t);isNaN(r)||(e=r)}}await VP(e);break;case"failed":case"completed":return i}}}async upload(e,t,r){const n=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:n.id},r)}async uploadAndPoll(e,t,r){const n=await this.upload(e,t,r);return await this.poll(e,n.id,r)}content(e,t,r){const{vector_store_id:n}=t;return this._client.getAPIList(oA`/vector_stores/${n}/files/${e}/content`,UC,{...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class ZO extends nA{constructor(){super(...arguments),this.files=new WO(this._client),this.fileBatches=new KO(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:yI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(oA`/vector_stores/${e}`,{...t,headers:yI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(oA`/vector_stores/${e}`,{body:t,...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",qC,{query:e,...t,headers:yI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(oA`/vector_stores/${e}`,{...t,headers:yI([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(oA`/vector_stores/${e}/search`,UC,{body:t,method:"post",...r,headers:yI([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}ZO.Files=WO,ZO.FileBatches=KO;class JO extends nA{create(e,t){return this._client.post("/videos",WC({body:e,...t},this._client))}retrieve(e,t){return this._client.get(oA`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",BC,{query:e,...t})}delete(e,t){return this._client.delete(oA`/videos/${e}`,t)}downloadContent(e,t={},r){return this._client.get(oA`/videos/${e}/content`,{query:t,...r,headers:yI([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}remix(e,t,r){return this._client.post(oA`/videos/${e}/remix`,WC({body:t,...r},this._client))}}var YO,QO,XO,eT,tT,rT,nT;class aT extends nA{constructor(){super(...arguments),YO.add(this)}async unwrap(e,t,r=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,r,n),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,n=300){if("undefined"==typeof crypto||"function"!=typeof crypto.subtle.importKey||"function"!=typeof crypto.subtle.verify)throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");MP(this,YO,"m",QO).call(this,r);const a=yI([t]).values,i=MP(this,YO,"m",XO).call(this,a,"webhook-signature"),s=MP(this,YO,"m",XO).call(this,a,"webhook-timestamp"),o=MP(this,YO,"m",XO).call(this,a,"webhook-id"),c=parseInt(s,10);if(isNaN(c))throw new FE("Invalid webhook timestamp format");const l=Math.floor(Date.now()/1e3);if(l-c>n)throw new FE("Webhook timestamp is too old");if(c>l+n)throw new FE("Webhook timestamp is too new");const u=i.split(" ").map(e=>e.startsWith("v1,")?e.substring(3):e),d=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),p=o?`${o}.${s}.${e}`:`${s}.${e}`,m=await crypto.subtle.importKey("raw",d,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const e of u)try{const t=Buffer.from(e,"base64");if(await crypto.subtle.verify("HMAC",m,t,(new TextEncoder).encode(p)))return}catch{continue}throw new FE("The given webhook signature does not match the expected signature")}}YO=new WeakSet,QO=function(e){if("string"!=typeof e||0===e.length)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},XO=function(e,t){if(!e)throw new Error("Headers are required");const r=e.get(t);if(null==r)throw new Error(`Missing required header: ${t}`);return r};class iT{constructor({baseURL:e=TI("OPENAI_BASE_URL"),apiKey:t=TI("OPENAI_API_KEY"),organization:r=TI("OPENAI_ORG_ID")??null,project:n=TI("OPENAI_PROJECT_ID")??null,webhookSecret:a=TI("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(eT.add(this),rT.set(this,void 0),this.completions=new sO(this),this.chat=new hI(this),this.embeddings=new pO(this),this.files=new gO(this),this.images=new PO(this),this.audio=new wI(this),this.moderations=new AO(this),this.models=new CO(this),this.fineTuning=new kO(this),this.graders=new EO(this),this.vectorStores=new ZO(this),this.webhooks=new aT(this),this.beta=new iO(this),this.batches=new SI(this),this.uploads=new HO(this),this.responses=new VO(this),this.realtime=new TO(this),this.conversations=new dO(this),this.evals=new fO(this),this.containers=new lO(this),this.videos=new JO(this),void 0===t)throw new xE("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");const s={apiKey:t,organization:r,project:n,webhookSecret:a,...i,baseURL:e||"https://api.openai.com/v1"};if(!s.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new xE("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");this.baseURL=s.baseURL,this.timeout=s.timeout??tT.DEFAULT_TIMEOUT,this.logger=s.logger??console;const o="warn";this.logLevel=o,this.logLevel=kC(s.logLevel,"ClientOptions.logLevel",this)??kC(TI("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??o,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??function(){if("undefined"!=typeof fetch)return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}(),LP(this,rT,XP),this._options=s,this.apiKey="string"==typeof t?t:"Missing Key",this.organization=r,this.project=n,this.webhookSecret=a}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return yI([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return mC(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${GP}`}defaultIdempotencyKey(){return`stainless-node-retry-${DP()}`}makeStatusError(e,t,r,n){return EE.generate(e,t,r,n)}async _callApiKey(){const e=this._options.apiKey;if("function"!=typeof e)return!1;let t;try{t=await e()}catch(e){if(e instanceof xE)throw e;throw new xE(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if("string"!=typeof t||!t)throw new xE(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){const n=!MP(this,eT,"m",nT).call(this)&&r||this.baseURL,a=(e=>jP.test(e))(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return function(e){if(!e)return!0;for(const t in e)return!1;return!0}(i)||(t={...i,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(a.search=this.stringifyQuery(t)),a.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(r=>({method:e,path:t,...r})))}request(e,t=null){return new DC(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){const n=await e,a=n.maxRetries??this.maxRetries;null==t&&(t=a),await this.prepareOptions(n);const{req:i,url:s,timeout:o}=await this.buildRequest(n,{retryCount:a-t});await this.prepareRequest(i,{url:s,options:n});const c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=void 0===r?"":`, retryOf: ${r}`,u=Date.now();if(AC(this).debug(`[${c}] sending request`,IC({retryOfRequestLogID:r,method:n.method,url:s,options:n,headers:i.headers})),n.signal?.aborted)throw new PE;const d=new AbortController,p=await this.fetchWithTimeout(s,i,o,d).catch(kE),m=Date.now();if(p instanceof globalThis.Error){const e=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new PE;const a=NE(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(t)return AC(this).info(`[${c}] connection ${a?"timed out":"failed"} - ${e}`),AC(this).debug(`[${c}] connection ${a?"timed out":"failed"} (${e})`,IC({retryOfRequestLogID:r,url:s,durationMs:m-u,message:p.message})),this.retryRequest(n,t,r??c);if(AC(this).info(`[${c}] connection ${a?"timed out":"failed"} - error; no more retries left`),AC(this).debug(`[${c}] connection ${a?"timed out":"failed"} (error; no more retries left)`,IC({retryOfRequestLogID:r,url:s,durationMs:m-u,message:p.message})),a)throw new AE;throw new CE({cause:p})}const h=`[${c}${l}${[...p.headers.entries()].filter(([e])=>"x-request-id"===e).map(([e,t])=>", "+e+": "+JSON.stringify(t)).join("")}] ${i.method} ${s} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${m-u}ms`;if(!p.ok){const e=await this.shouldRetry(p);if(t&&e){const e=`retrying, ${t} attempts remaining`;return await async function(e){if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator])return void await(e[Symbol.asyncIterator]().return?.());const t=e.getReader(),r=t.cancel();t.releaseLock(),await r}(p.body),AC(this).info(`${h} - ${e}`),AC(this).debug(`[${c}] response error (${e})`,IC({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,durationMs:m-u})),this.retryRequest(n,t,r??c,p.headers)}const a=e?"error; no more retries left":"error; not retryable";AC(this).info(`${h} - ${a}`);const i=await p.text().catch(e=>kE(e).message),s=(e=>{try{return JSON.parse(e)}catch(e){return}})(i),o=s?void 0:i;AC(this).debug(`[${c}] response error (${a})`,IC({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,message:o,durationMs:Date.now()-u}));throw this.makeStatusError(p.status,s,o,p.headers)}return AC(this).info(h),AC(this).debug(`[${c}] response start`,IC({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,durationMs:m-u})),{response:p,options:n,controller:d,requestLogID:c,retryOfRequestLogID:r,startTime:u}}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}requestAPIList(e,t){const r=this.makeRequest(t,null,void 0);return new FC(this,r,e)}async fetchWithTimeout(e,t,r,n){const{signal:a,method:i,...s}=t||{};a&&a.addEventListener("abort",()=>n.abort());const o=setTimeout(()=>n.abort(),r),c=globalThis.ReadableStream&&s.body instanceof globalThis.ReadableStream||"object"==typeof s.body&&null!==s.body&&Symbol.asyncIterator in s.body,l={signal:n.signal,...c?{duplex:"half"}:{},method:"GET",...s};i&&(l.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,l)}finally{clearTimeout(o)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,r,n){let a;const i=n?.get("retry-after-ms");if(i){const e=parseFloat(i);Number.isNaN(e)||(a=e)}const s=n?.get("retry-after");if(s&&!a){const e=parseFloat(s);a=Number.isNaN(e)?Date.parse(s)-Date.now():1e3*e}if(!(a&&0<=a&&a<6e4)){const r=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(t,r)}return await VP(a),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){const r=t-e;return Math.min(.5*Math.pow(2,r),8)*(1-.25*Math.random())*1e3}async buildRequest(e,{retryCount:t=0}={}){const r={...e},{method:n,path:a,query:i,defaultBaseURL:s}=r,o=this.buildURL(a,i,s);"timeout"in r&&((e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new xE(`${e} must be an integer`);if(t<0)throw new xE(`${e} must be a positive integer`)})("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:c,body:l}=this.buildBody({options:r});return{req:{method:n,headers:await this.buildHeaders({options:e,method:n,bodyHeaders:c,retryCount:t}),...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...r.fetchOptions??{}},url:o,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let a={};this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);const i=yI([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...ZP??(ZP=HP()),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const r=yI([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{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:YP(e)}:MP(this,rT,"f").call(this,{body:e,headers:r})}}tT=iT,rT=new WeakMap,eT=new WeakSet,nT=function(){return"https://api.openai.com/v1"!==this.baseURL},iT.OpenAI=tT,iT.DEFAULT_TIMEOUT=6e5,iT.OpenAIError=xE,iT.APIError=EE,iT.APIConnectionError=CE,iT.APIConnectionTimeoutError=AE,iT.APIUserAbortError=PE,iT.NotFoundError=$E,iT.ConflictError=zE,iT.RateLimitError=LE,iT.BadRequestError=IE,iT.AuthenticationError=OE,iT.InternalServerError=ME,iT.PermissionDeniedError=TE,iT.UnprocessableEntityError=RE,iT.InvalidWebhookSignatureError=FE,iT.toFile=async function(e,t,r){if(VC(),(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&tA(e))(e=await e))return e instanceof File?e:GC([await e.arrayBuffer()],e.name);if((e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob)(e)){const n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),GC(await rA(n),t,r)}const n=await rA(e);if(t||(t=HC(e)),!r?.type){const e=n.find(e=>"object"==typeof e&&"type"in e&&e.type);"string"==typeof e&&(r={...r,type:e})}return GC(n,t,r)},iT.Completions=sO,iT.Chat=hI,iT.Embeddings=pO,iT.Files=gO,iT.Images=PO,iT.Audio=wI,iT.Moderations=AO,iT.Models=CO,iT.FineTuning=kO,iT.Graders=EO,iT.VectorStores=ZO,iT.Webhooks=aT,iT.Beta=iO,iT.Batches=SI,iT.Uploads=HO,iT.Responses=VO,iT.Realtime=TO,iT.Conversations=dO,iT.Evals=fO,iT.Containers=lO,iT.Videos=JO;class sT extends iT{constructor({baseURL:e=TI("OPENAI_BASE_URL"),apiKey:t=TI("AZURE_OPENAI_API_KEY"),apiVersion:r=TI("OPENAI_API_VERSION"),endpoint:n,deployment:a,azureADTokenProvider:i,dangerouslyAllowBrowser:s,...o}={}){if(!r)throw new xE("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if("function"==typeof i&&(s=!0),!i&&!t)throw new xE("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(i&&t)throw new xE("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(o.defaultQuery={...o.defaultQuery,"api-version":r},e){if(n)throw new xE("baseURL and endpoint are mutually exclusive")}else{if(n||(n=process.env.AZURE_OPENAI_ENDPOINT),!n)throw new xE("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${n}/openai`}super({apiKey:i??t,baseURL:e,...o,...void 0!==s?{dangerouslyAllowBrowser:s}:{}}),this.apiVersion="",this.apiVersion=r,this.deploymentName=a}async buildRequest(e,t={}){if(oT.has(e.path)&&"post"===e.method&&void 0!==e.body){if(!BP(e.body))throw new Error("Expected request body to be an object");const t=this.deploymentName||e.body.model||e.__metadata?.model;void 0===t||this.baseURL.includes("/deployments")||(e.path=`/deployments/${t}${e.path}`)}return super.buildRequest(e,t)}async authHeaders(e){return"string"==typeof this._options.apiKey?yI([{"api-key":this.apiKey}]):super.authHeaders(e)}}const oT=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);yf({},{BasePromptValue:()=>cT,ChatPromptValue:()=>uT,ImagePromptValue:()=>dT,StringPromptValue:()=>lT});var cT=class extends Mf{},lT=class extends cT{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new ty(this.value)]}},uT=class extends cT{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return yy(this.messages)}toChatMessages(){return this.messages}},dT=class extends cT{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new ty({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},pT="0123456789abcdef".split(""),mT=[-2147483648,8388608,32768,128],hT=[24,16,8,0],fT=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],gT=[];function yT(e,t){t?(gT[0]=gT[16]=gT[1]=gT[2]=gT[3]=gT[4]=gT[5]=gT[6]=gT[7]=gT[8]=gT[9]=gT[10]=gT[11]=gT[12]=gT[13]=gT[14]=gT[15]=0,this.blocks=gT):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}yT.prototype.update=function(e){if(!this.finalized){var t,r=typeof e;if("string"!==r){if("object"!==r)throw new Error(ERROR);if(null===e)throw new Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!(Array.isArray(e)||ARRAY_BUFFER&&ArrayBuffer.isView(e)))throw new Error(ERROR);t=!0}for(var n,a,i=0,s=e.length,o=this.blocks;i<s;){if(this.hashed&&(this.hashed=!1,o[0]=this.block,this.block=o[16]=o[1]=o[2]=o[3]=o[4]=o[5]=o[6]=o[7]=o[8]=o[9]=o[10]=o[11]=o[12]=o[13]=o[14]=o[15]=0),t)for(a=this.start;i<s&&a<64;++i)o[a>>>2]|=e[i]<<hT[3&a++];else for(a=this.start;i<s&&a<64;++i)(n=e.charCodeAt(i))<128?o[a>>>2]|=n<<hT[3&a++]:n<2048?(o[a>>>2]|=(192|n>>>6)<<hT[3&a++],o[a>>>2]|=(128|63&n)<<hT[3&a++]):n<55296||n>=57344?(o[a>>>2]|=(224|n>>>12)<<hT[3&a++],o[a>>>2]|=(128|n>>>6&63)<<hT[3&a++],o[a>>>2]|=(128|63&n)<<hT[3&a++]):(n=65536+((1023&n)<<10|1023&e.charCodeAt(++i)),o[a>>>2]|=(240|n>>>18)<<hT[3&a++],o[a>>>2]|=(128|n>>>12&63)<<hT[3&a++],o[a>>>2]|=(128|n>>>6&63)<<hT[3&a++],o[a>>>2]|=(128|63&n)<<hT[3&a++]);this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=o[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this}},yT.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=mT[3&t],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}},yT.prototype.hash=function(){var e,t,r,n,a,i,s,o,c,l=this.h0,u=this.h1,d=this.h2,p=this.h3,m=this.h4,h=this.h5,f=this.h6,g=this.h7,y=this.blocks;for(e=16;e<64;++e)t=((a=y[e-15])>>>7|a<<25)^(a>>>18|a<<14)^a>>>3,r=((a=y[e-2])>>>17|a<<15)^(a>>>19|a<<13)^a>>>10,y[e]=y[e-16]+t+y[e-7]+r|0;for(c=u&d,e=0;e<64;e+=4)this.first?(this.is224?(i=300032,g=(a=y[0]-1413257819)-150054599|0,p=a+24177077|0):(i=704751109,g=(a=y[0]-210244248)-1521486534|0,p=a+143694565|0),this.first=!1):(t=(l>>>2|l<<30)^(l>>>13|l<<19)^(l>>>22|l<<10),n=(i=l&u)^l&d^c,g=p+(a=g+(r=(m>>>6|m<<26)^(m>>>11|m<<21)^(m>>>25|m<<7))+(m&h^~m&f)+fT[e]+y[e])|0,p=a+(t+n)|0),t=(p>>>2|p<<30)^(p>>>13|p<<19)^(p>>>22|p<<10),n=(s=p&l)^p&u^i,f=d+(a=h+(r=(g>>>6|g<<26)^(g>>>11|g<<21)^(g>>>25|g<<7))+(f&g^~f&m)+fT[e+1]+y[e+1])|0,t=((d=a+(t+n)|0)>>>2|d<<30)^(d>>>13|d<<19)^(d>>>22|d<<10),n=(o=d&p)^d&l^s,h=u+(a=m+(r=(f>>>6|f<<26)^(f>>>11|f<<21)^(f>>>25|f<<7))+(h&f^~h&g)+fT[e+2]+y[e+2])|0,t=((u=a+(t+n)|0)>>>2|u<<30)^(u>>>13|u<<19)^(u>>>22|u<<10),n=(c=u&d)^u&p^o,m=l+(a=m+(r=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7))+(h&f^~h&g)+fT[e+3]+y[e+3])|0,l=a+(t+n)|0,this.chromeBugWorkAround=!0;this.h0=this.h0+l|0,this.h1=this.h1+u|0,this.h2=this.h2+d|0,this.h3=this.h3+p|0,this.h4=this.h4+m|0,this.h5=this.h5+h|0,this.h6=this.h6+f|0,this.h7=this.h7+g|0},yT.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,n=this.h3,a=this.h4,i=this.h5,s=this.h6,o=this.h7,c=pT[e>>>28&15]+pT[e>>>24&15]+pT[e>>>20&15]+pT[e>>>16&15]+pT[e>>>12&15]+pT[e>>>8&15]+pT[e>>>4&15]+pT[15&e]+pT[t>>>28&15]+pT[t>>>24&15]+pT[t>>>20&15]+pT[t>>>16&15]+pT[t>>>12&15]+pT[t>>>8&15]+pT[t>>>4&15]+pT[15&t]+pT[r>>>28&15]+pT[r>>>24&15]+pT[r>>>20&15]+pT[r>>>16&15]+pT[r>>>12&15]+pT[r>>>8&15]+pT[r>>>4&15]+pT[15&r]+pT[n>>>28&15]+pT[n>>>24&15]+pT[n>>>20&15]+pT[n>>>16&15]+pT[n>>>12&15]+pT[n>>>8&15]+pT[n>>>4&15]+pT[15&n]+pT[a>>>28&15]+pT[a>>>24&15]+pT[a>>>20&15]+pT[a>>>16&15]+pT[a>>>12&15]+pT[a>>>8&15]+pT[a>>>4&15]+pT[15&a]+pT[i>>>28&15]+pT[i>>>24&15]+pT[i>>>20&15]+pT[i>>>16&15]+pT[i>>>12&15]+pT[i>>>8&15]+pT[i>>>4&15]+pT[15&i]+pT[s>>>28&15]+pT[s>>>24&15]+pT[s>>>20&15]+pT[s>>>16&15]+pT[s>>>12&15]+pT[s>>>8&15]+pT[s>>>4&15]+pT[15&s];return this.is224||(c+=pT[o>>>28&15]+pT[o>>>24&15]+pT[o>>>20&15]+pT[o>>>16&15]+pT[o>>>12&15]+pT[o>>>8&15]+pT[o>>>4&15]+pT[15&o]),c},yT.prototype.toString=yT.prototype.hex,yT.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,n=this.h3,a=this.h4,i=this.h5,s=this.h6,o=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,255&e,t>>>24&255,t>>>16&255,t>>>8&255,255&t,r>>>24&255,r>>>16&255,r>>>8&255,255&r,n>>>24&255,n>>>16&255,n>>>8&255,255&n,a>>>24&255,a>>>16&255,a>>>8&255,255&a,i>>>24&255,i>>>16&255,i>>>8&255,255&i,s>>>24&255,s>>>16&255,s>>>8&255,255&s];return this.is224||c.push(o>>>24&255,o>>>16&255,o>>>8&255,255&o),c},yT.prototype.array=yT.prototype.digest,yT.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};const vT=(...e)=>new yT(!1,!0).update(e.join("")).hex();yf({},{sha256:()=>vT});yf({},{BaseCache:()=>ST,InMemoryCache:()=>xT,defaultHashKeyEncoder:()=>bT,deserializeStoredGeneration:()=>_T,serializeGeneration:()=>wT});const bT=(...e)=>vT(e.join("_"));function _T(e){return void 0!==e.message?{text:e.text,message:vy(e.message)}:{text:e.text}}function wT(e){const t={text:e.text};return void 0!==e.message&&(t.message=e.message.toDict()),t}var ST=class{keyEncoder=bT;makeDefaultKeyEncoder(e){this.keyEncoder=e}};const NT=new Map;var kT,xT=class e extends ST{cache;constructor(e){super(),this.cache=e??new Map}lookup(e,t){return Promise.resolve(this.cache.get(this.keyEncoder(e,t))??null)}async update(e,t,r){this.cache.set(this.keyEncoder(e,t),r)}static global(){return new e(NT)}},ET={};var PT=function(){if(kT)return ET;kT=1,ET.byteLength=function(e){var t=i(e),r=t[0],n=t[1];return 3*(r+n)/4-n},ET.toByteArray=function(e){var n,a,s=i(e),o=s[0],c=s[1],l=new r(function(e,t,r){return 3*(t+r)/4-r}(0,o,c)),u=0,d=c>0?o-4:o;for(a=0;a<d;a+=4)n=t[e.charCodeAt(a)]<<18|t[e.charCodeAt(a+1)]<<12|t[e.charCodeAt(a+2)]<<6|t[e.charCodeAt(a+3)],l[u++]=n>>16&255,l[u++]=n>>8&255,l[u++]=255&n;2===c&&(n=t[e.charCodeAt(a)]<<2|t[e.charCodeAt(a+1)]>>4,l[u++]=255&n);1===c&&(n=t[e.charCodeAt(a)]<<10|t[e.charCodeAt(a+1)]<<4|t[e.charCodeAt(a+2)]>>2,l[u++]=n>>8&255,l[u++]=255&n);return l},ET.fromByteArray=function(t){for(var r,n=t.length,a=n%3,i=[],s=16383,c=0,l=n-a;c<l;c+=s)i.push(o(t,c,c+s>l?l:c+s));1===a?(r=t[n-1],i.push(e[r>>2]+e[r<<4&63]+"==")):2===a&&(r=(t[n-2]<<8)+t[n-1],i.push(e[r>>10]+e[r>>4&63]+e[r<<2&63]+"="));return i.join("")};for(var e=[],t=[],r="undefined"!=typeof Uint8Array?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0;a<64;++a)e[a]=n[a],t[n.charCodeAt(a)]=a;function i(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function s(t){return e[t>>18&63]+e[t>>12&63]+e[t>>6&63]+e[63&t]}function o(e,t,r){for(var n,a=[],i=t;i<r;i+=3)n=(e[i]<<16&16711680)+(e[i+1]<<8&65280)+(255&e[i+2]),a.push(s(n));return a.join("")}return t["-".charCodeAt(0)]=62,t["_".charCodeAt(0)]=63,ET}(),CT=ba(PT),AT=Object.defineProperty;function IT(e,t){return 1===e.length?[t.get(e.join(","))]:function(e,t){let r=Array.from({length:e.length},(e,t)=>({start:t,end:t+1}));for(;r.length>1;){let n=null;for(let a=0;a<r.length-1;a++){const i=e.slice(r[a].start,r[a+1].end),s=t.get(i.join(","));null!=s&&(null==n||s<n[0])&&(n=[s,a])}if(null==n)break;{const e=n[1];r[e]={start:r[e].start,end:r[e+1].end},r.splice(e+1,1)}}return r}(e,t).map(r=>t.get(e.slice(r.start,r.end).join(","))).filter(e=>null!=e)}var OT=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,t){this.patStr=e.pat_str;const r=e.bpe_ranks.split("\n").filter(Boolean).reduce((e,t)=>{const[r,n,...a]=t.split(" "),i=Number.parseInt(n,10);return a.forEach((t,r)=>e[t]=i+r),e},{});for(const[e,t]of Object.entries(r)){const r=CT.toByteArray(e);this.rankMap.set(r.join(","),t),this.textMap.set(t,r)}this.specialTokens={...e.special_tokens,...t},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((e,[t,r])=>(e[r]=this.textEncoder.encode(t),e),{})}encode(e,t=[],r="all"){const n=new RegExp(this.patStr,"ug"),a=OT.specialTokenRegex(Object.keys(this.specialTokens)),i=[],s=new Set("all"===t?Object.keys(this.specialTokens):t),o=new Set("all"===r?Object.keys(this.specialTokens).filter(e=>!s.has(e)):r);if(o.size>0){const t=OT.specialTokenRegex([...o]),r=e.match(t);if(null!=r)throw new Error(`The text contains a special token that is not allowed: ${r[0]}`)}let c=0;for(;;){let t=null,r=c;for(;a.lastIndex=r,t=a.exec(e),null!=t&&!s.has(t[0]);)r=t.index+1;const o=t?.index??e.length;for(const t of e.substring(c,o).matchAll(n)){const e=this.textEncoder.encode(t[0]),r=this.rankMap.get(e.join(","));null==r?i.push(...IT(e,this.rankMap)):i.push(r)}if(null==t)break;let l=this.specialTokens[t[0]];i.push(l),c=t.index+t[0].length}return i}decode(e){const t=[];let r=0;for(let n=0;n<e.length;++n){const a=e[n],i=this.textMap.get(a)??this.inverseSpecialTokens[a];null!=i&&(t.push(i),r+=i.length)}const n=new Uint8Array(r);let a=0;for(const e of t)n.set(e,a),a+=e.length;return this.textDecoder.decode(n)}},TT=OT;((e,t,r)=>{((e,t,r)=>{t in e?AT(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r})(e,t+"",r)})(TT,"specialTokenRegex",e=>new RegExp(e.map(e=>function(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}(e)).join("|"),"g"));yf({},{encodingForModel:()=>LT,getEncoding:()=>RT});const $T={},zT=new ww({});async function RT(e){return e in $T||($T[e]=zT.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(e=>e.json()).then(e=>new TT(e)).catch(t=>{throw delete $T[e],t})),await $T[e]}async function LT(e){return RT(function(e){switch(e){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":case"gpt-5":case"gpt-5-2025-08-07":case"gpt-5-nano":case"gpt-5-nano-2025-08-07":case"gpt-5-mini":case"gpt-5-mini-2025-08-07":case"gpt-5-chat-latest":return"o200k_base";default:throw new Error("Unknown model")}}(e))}yf({},{BaseLangChain:()=>qT,BaseLanguageModel:()=>BT,calculateMaxTokens:()=>UT,getEmbeddingContextSize:()=>DT,getModelContextSize:()=>jT,getModelNameForTiktoken:()=>MT,isOpenAITool:()=>FT});const MT=e=>e.startsWith("gpt-5")?"gpt-5":e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e.startsWith("gpt-4o")?"gpt-4o":e,DT=e=>"text-embedding-ada-002"===e?8191:2046,jT=e=>{switch(MT(e)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 4e5;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128e3;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":case"gemini-pro":case"gemini-pro-vision":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":default:return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":case"code-cushman-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8e3;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 2e5;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6}};function FT(e){return!("object"!=typeof e||!e)&&!!("type"in e&&"function"===e.type&&"function"in e&&"object"==typeof e.function&&e.function&&"name"in e.function&&"parameters"in e.function)}const UT=async({prompt:e,modelName:t})=>{let r;try{r=(await LT(MT(t))).encode(e).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),r=Math.ceil(e.length/4)}return jT(t)-r};var qT=class extends Ix{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??!1,this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},BT=class extends qT{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:e,callbackManager:t,...r}){const{cache:n,...a}=r;super({callbacks:e??t,...a}),this.cache="object"==typeof n?n:n?xT.global():void 0,this.caller=new ww(r??{})}_encoding;async getNumTokens(e){let t;t="string"==typeof e?e:e.map(e=>"string"==typeof e?e:"text"===e.type&&"text"in e?e.text:"").join("");let r=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await LT("modelName"in this?MT(this.modelName):"gpt2")}catch(e){console.warn("Failed to calculate number of tokens, falling back to approximate count",e)}if(this._encoding)try{r=this._encoding.encode(t).length}catch(e){console.warn("Failed to calculate number of tokens, falling back to approximate count",e)}return r}static _convertInputToPromptValue(e){return"string"==typeof e?new lT(e):Array.isArray(e)?new uT(e.map(gy)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){const r={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()},n=Object.entries(r).filter(([e,t])=>void 0!==t).map(([e,t])=>`${e}:${JSON.stringify(t)}`).sort().join(",");return n}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}get profile(){return{}}},VT=class extends Ix{static lc_name(){return"RunnablePassthrough"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;func;constructor(e){super(e),e&&(this.func=e.func)}async invoke(e,t){const r=P_(t);return this.func&&await this.func(e,r),this._callWithConfig(e=>Promise.resolve(e),e,r)}async*transform(e,t){const r=P_(t);let n,a=!0;for await(const t of this._transformStreamWithConfig(e,e=>e,r))if(yield t,a)if(void 0===n)n=t;else try{n=z_(n,t)}catch{n=void 0,a=!1}this.func&&void 0!==n&&await this.func(n,r)}static assign(e){return new Ux(new Rx({steps:e}))}};function GT(e){return new(0,e.constructor)({...e,content:e.contentBlocks,response_metadata:{...e.response_metadata,output_version:"v1"}})}function HT(e){const t=[];for(const r of e){let e=r;if(Array.isArray(r.content))for(let t=0;t<r.content.length;t++){const n=r.content[t];(bf(n)||_f(n))&&e===r&&(e=new r.constructor({...e,content:[...r.content.slice(0,t),Nf(n),...r.content.slice(t+1)]}))}t.push(e)}return t}yf({},{BaseChatModel:()=>KT,SimpleChatModel:()=>WT});var KT=class e extends BT{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(e){super(e),this.outputVersion=(()=>{const t=e.outputVersion??$y("LC_OUTPUT_VERSION");return t&&["v0","v1"].includes(t)?t:"v0"})()}_separateRunnableConfigFromCallOptionsCompat(e){const[t,r]=super._separateRunnableConfigFromCallOptions(e);return r.signal=t.signal,[t,r]}async invoke(t,r){const n=e._convertInputToPromptValue(t);return(await this.generatePrompt([n],r,r?.callbacks)).generations[0][0].message}async*_streamResponseChunks(e,t,r){throw new Error("Not implemented.")}async*_streamIterator(t,r){if(this._streamResponseChunks===e.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(t,r);else{const n=e._convertInputToPromptValue(t).toChatMessages(),[a,i]=this._separateRunnableConfigFromCallOptionsCompat(r),s={...a.metadata,...this.getLsParams(i)},o=await v_.configure(a.callbacks,this.callbacks,a.tags,this.tags,s,this.metadata,{verbose:this.verbose}),c={options:i,invocation_params:this?.invocationParams(i),batch_size:1},l=i.outputVersion??this.outputVersion,u=await(o?.handleChatModelStart(this.toJSON(),[HT(n)],a.runId,void 0,c,void 0,void 0,a.runName));let d,p;try{for await(const e of this._streamResponseChunks(n,i,u?.[0])){if(null==e.message.id){const t=u?.at(0)?.runId;null!=t&&e.message._updateId(`run-${t}`)}e.message.response_metadata={...e.generationInfo,...e.message.response_metadata},"v1"===l?yield GT(e.message):yield e.message,d=d?d.concat(e):e,Gg(e.message)&&void 0!==e.message.usage_metadata&&(p={tokenUsage:{promptTokens:e.message.usage_metadata.input_tokens,completionTokens:e.message.usage_metadata.output_tokens,totalTokens:e.message.usage_metadata.total_tokens}})}}catch(e){throw await Promise.all((u??[]).map(t=>t?.handleLLMError(e))),e}await Promise.all((u??[]).map(e=>e?.handleLLMEnd({generations:[[d]],llmOutput:p})))}}getLsParams(e){const t=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:e.stop,ls_provider:t}}async _generateUncached(t,r,n,a){const i=t.map(e=>e.map(gy));let s;if(void 0!==a&&a.length===i.length)s=a;else{const e={...n.metadata,...this.getLsParams(r)},t=await v_.configure(n.callbacks,this.callbacks,n.tags,this.tags,e,this.metadata,{verbose:this.verbose}),a={options:r,invocation_params:this?.invocationParams(r),batch_size:1};s=await(t?.handleChatModelStart(this.toJSON(),i.map(HT),n.runId,void 0,a,void 0,void 0,n.runName))}const o=r.outputVersion??this.outputVersion,c=[],l=[];if(!!s?.[0].handlers.find(Wy)&&!this.disableStreaming&&1===i.length&&this._streamResponseChunks!==e.prototype._streamResponseChunks)try{const e=await this._streamResponseChunks(i[0],r,s?.[0]);let t,n;for await(const r of e){if(null==r.message.id){const e=s?.at(0)?.runId;null!=e&&r.message._updateId(`run-${e}`)}t=void 0===t?r:z_(t,r),Gg(r.message)&&void 0!==r.message.usage_metadata&&(n={tokenUsage:{promptTokens:r.message.usage_metadata.input_tokens,completionTokens:r.message.usage_metadata.output_tokens,totalTokens:r.message.usage_metadata.total_tokens}})}if(void 0===t)throw new Error("Received empty response from chat model call.");c.push([t]),await(s?.[0].handleLLMEnd({generations:c,llmOutput:n}))}catch(e){throw await(s?.[0].handleLLMError(e)),e}else{const e=await Promise.allSettled(i.map(async(e,t)=>{const n=await this._generate(e,{...r,promptIndex:t},s?.[t]);if("v1"===o)for(const e of n.generations)e.message=GT(e.message);return n}));await Promise.all(e.map(async(e,t)=>{if("fulfilled"===e.status){const r=e.value;for(const e of r.generations){if(null==e.message.id){const t=s?.at(0)?.runId;null!=t&&e.message._updateId(`run-${t}`)}e.message.response_metadata={...e.generationInfo,...e.message.response_metadata}}return 1===r.generations.length&&(r.generations[0].message.response_metadata={...r.llmOutput,...r.generations[0].message.response_metadata}),c[t]=r.generations,l[t]=r.llmOutput,s?.[t]?.handleLLMEnd({generations:[r.generations],llmOutput:r.llmOutput})}return await(s?.[t]?.handleLLMError(e.reason)),Promise.reject(e.reason)}))}const u={generations:c,llmOutput:l.length?this._combineLLMOutput?.(...l):void 0};return Object.defineProperty(u,mw,{value:s?{runIds:s?.map(e=>e.runId)}:void 0,configurable:!0}),u}async _generateCached({messages:t,cache:r,llmStringKey:n,parsedOptions:a,handledOptions:i}){const s=t.map(e=>e.map(gy)),o={...i.metadata,...this.getLsParams(a)},c=await v_.configure(i.callbacks,this.callbacks,i.tags,this.tags,o,this.metadata,{verbose:this.verbose}),l={options:a,invocation_params:this?.invocationParams(a),batch_size:1},u=await(c?.handleChatModelStart(this.toJSON(),s.map(HT),i.runId,void 0,l,void 0,void 0,i.runName)),d=[],p=await Promise.allSettled(s.map(async(t,a)=>{const i=e._convertInputToPromptValue(t).toString(),s=await r.lookup(i,n);return null==s&&d.push(a),s})),m=p.map((e,t)=>({result:e,runManager:u?.[t]})).filter(({result:e})=>"fulfilled"===e.status&&null!=e.value||"rejected"===e.status),h=a.outputVersion??this.outputVersion,f=[];await Promise.all(m.map(async({result:e,runManager:t},r)=>{if("fulfilled"===e.status){const n=e.value;return f[r]=n.map(e=>("message"in e&&yg(e.message)&&Vg(e.message)&&(e.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},"v1"===h&&(e.message=GT(e.message))),e.generationInfo={...e.generationInfo,tokenUsage:{}},e)),n.length&&await(t?.handleLLMNewToken(n[0].text)),t?.handleLLMEnd({generations:[n]},void 0,void 0,void 0,{cached:!0})}return await(t?.handleLLMError(e.reason,void 0,void 0,void 0,{cached:!0})),Promise.reject(e.reason)}));const g={generations:f,missingPromptIndices:d,startedRunManagers:u};return Object.defineProperty(g,mw,{value:u?{runIds:u?.map(e=>e.runId)}:void 0,configurable:!0}),g}async generate(t,r,n){let a;a=Array.isArray(r)?{stop:r}:r;const i=t.map(e=>e.map(gy)),[s,o]=this._separateRunnableConfigFromCallOptionsCompat(a);if(s.callbacks=s.callbacks??n,!this.cache)return this._generateUncached(i,o,s);const{cache:c}=this,l=this._getSerializedCacheKeyParametersForCall(o),{generations:u,missingPromptIndices:d,startedRunManagers:p}=await this._generateCached({messages:i,cache:c,llmStringKey:l,parsedOptions:o,handledOptions:s});let m={};if(d.length>0){const t=await this._generateUncached(d.map(e=>i[e]),o,s,void 0!==p?d.map(e=>p?.[e]):void 0);await Promise.all(t.generations.map(async(t,r)=>{const n=d[r];u[n]=t;const a=e._convertInputToPromptValue(i[n]).toString();return c.update(a,l,t)})),m=t.llmOutput??{}}return{generations:u,llmOutput:m}}invocationParams(e){return{}}_modelType(){return"base_chat_model"}async generatePrompt(e,t,r){const n=e.map(e=>e.toChatMessages());return this.generate(n,t,r)}withStructuredOutput(e,t){if("function"!=typeof this.bindTools)throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(t?.strict)throw new Error('"strict" mode is not supported for this model by default.');const r=e,n=t?.name,a=vS(r)??"A function available to call.",i=t?.method,s=t?.includeRaw;if("jsonMode"===i)throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let o,c=n??"extract";uS(r)?o=[{type:"function",function:{name:c,description:a,parameters:vx(r)}}]:("name"in r&&(c=r.name),o=[{type:"function",function:{name:c,description:a,parameters:r}}]);const l=this.bindTools(o),u=Mx.from(e=>{if(!Hg.isInstance(e))throw new Error("Input is not an AIMessageChunk.");if(!e.tool_calls||0===e.tool_calls.length)throw new Error("No tool calls found in the response.");const t=e.tool_calls.find(e=>e.name===c);if(!t)throw new Error(`No tool call found with name ${c}.`);return t.args});if(!s)return l.pipe(u).withConfig({runName:"StructuredOutput"});const d=VT.assign({parsed:(e,t)=>u.invoke(e.raw,t)}),p=VT.assign({parsed:()=>null}),m=d.withFallbacks({fallbacks:[p]});return zx.from([{raw:l},m]).withConfig({runName:"StructuredOutputRunnable"})}},WT=class extends KT{async _generate(e,t,r){const n=await this._call(e,t,r),a=new Bg(n);if("string"!=typeof a.content)throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:a.content,message:a}]}}},ZT=class extends Ix{static lc_name(){return"RouterRunnable"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnables;constructor(e){super(e),this.runnables=e.runnables}async invoke(e,t){const{key:r,input:n}=e,a=this.runnables[r];if(void 0===a)throw new Error(`No runnable associated with key "${r}".`);return a.invoke(n,P_(t))}async batch(e,t,r){const n=e.map(e=>e.key),a=e.map(e=>e.input),i=n.find(e=>void 0===this.runnables[e]);if(void 0!==i)throw new Error("One or more keys do not have a corresponding runnable.");const s=n.map(e=>this.runnables[e]),o=this._getOptionsList(t??{},e.length),c=o[0]?.maxConcurrency??r?.maxConcurrency,l=c&&c>0?c:e.length,u=[];for(let e=0;e<a.length;e+=l){const t=a.slice(e,e+l).map((e,t)=>s[t].invoke(e,o[t])),r=await Promise.all(t);u.push(r)}return u.flat()}async stream(e,t){const{key:r,input:n}=e,a=this.runnables[r];if(void 0===a)throw new Error(`No runnable associated with key "${r}".`);return a.stream(n,t)}},JT=class extends Ix{static lc_name(){return"RunnableBranch"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;default;branches;constructor(e){super(e),this.branches=e.branches,this.default=e.default}static from(e){if(e.length<1)throw new Error("RunnableBranch requires at least one branch");return new this({branches:e.slice(0,-1).map(([e,t])=>[Fx(e),Fx(t)]),default:Fx(e[e.length-1])})}async _invoke(e,t,r){let n;for(let a=0;a<this.branches.length;a+=1){const[i,s]=this.branches[a];if(await i.invoke(e,C_(t,{callbacks:r?.getChild(`condition:${a+1}`)}))){n=await s.invoke(e,C_(t,{callbacks:r?.getChild(`branch:${a+1}`)}));break}}return n||(n=await this.default.invoke(e,C_(t,{callbacks:r?.getChild("branch:default")}))),n}async invoke(e,t={}){return this._callWithConfig(this._invoke,e,t)}async*_streamIterator(e,t){const r=await k_(t),n=await(r?.handleChainStart(this.toJSON(),Ax(e,"input"),t?.runId,void 0,void 0,void 0,t?.runName));let a,i,s=!0;try{for(let r=0;r<this.branches.length;r+=1){const[o,c]=this.branches[r];if(await o.invoke(e,C_(t,{callbacks:n?.getChild(`condition:${r+1}`)}))){i=await c.stream(e,C_(t,{callbacks:n?.getChild(`branch:${r+1}`)}));for await(const e of i)if(yield e,s)if(void 0===a)a=e;else try{a=z_(a,e)}catch{a=void 0,s=!1}break}}if(void 0===i){i=await this.default.stream(e,C_(t,{callbacks:n?.getChild("branch:default")}));for await(const e of i)if(yield e,s)if(void 0===a)a=e;else try{a=z_(a,e)}catch{a=void 0,s=!1}}}catch(e){throw await(n?.handleChainError(e)),e}await(n?.handleChainEnd(a??{}))}},YT=class extends Ox{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(e){let t=Mx.from((e,t)=>this._enterHistory(e,t??{})).withConfig({runName:"loadHistory"});const r=e.historyMessagesKey??e.inputMessagesKey;r&&(t=VT.assign({[r]:t}).withConfig({runName:"insertHistory"}));const n=t.pipe(e.runnable.withListeners({onEnd:(e,t)=>this._exitHistory(e,t??{})})).withConfig({runName:"RunnableWithMessageHistory"}),a=e.config??{};super({...e,config:a,bound:n}),this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let t;if("object"!=typeof e||Array.isArray(e)||yg(e))t=e;else{let r;r=this.inputMessagesKey?this.inputMessagesKey:1===Object.keys(e).length?Object.keys(e)[0]:"input",t=Array.isArray(e[r])&&Array.isArray(e[r][0])?e[r][0]:e[r]}if("string"==typeof t)return[new ty(t)];if(Array.isArray(t))return t;if(yg(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.\nGot ${JSON.stringify(t,null,2)}`)}_getOutputMessages(e){let t;if(Array.isArray(e)||yg(e)||"string"==typeof e)t=e;else{let r;r=void 0!==this.outputMessagesKey?this.outputMessagesKey:1===Object.keys(e).length?Object.keys(e)[0]:"output",t=void 0!==e.generations?e.generations[0][0].message:e[r]}if("string"==typeof t)return[new Bg(t)];if(Array.isArray(t))return t;if(yg(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(t,null,2)}`)}async _enterHistory(e,t){const r=t?.configurable?.messageHistory,n=await r.getMessages();return void 0===this.historyMessagesKey?n.concat(this._getInputMessages(e)):n}async _exitHistory(e,t){const r=t.configurable?.messageHistory;let n;n=Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?e.inputs[0]:e.inputs;let a=this._getInputMessages(n);if(void 0===this.historyMessagesKey){const e=await r.getMessages();a=a.slice(e.length)}const i=e.outputs;if(!i)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);const s=this._getOutputMessages(i);await r.addMessages([...a,...s])}async _mergeConfig(...e){const t=await super._mergeConfig(...e);if(!t.configurable||!t.configurable.sessionId){const e={[this.inputMessagesKey??"input"]:"foo"},t={configurable:{sessionId:"123"}};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()\neg. chain.invoke(${JSON.stringify(e)}, ${JSON.stringify(t)})`)}const{sessionId:r}=t.configurable;return t.configurable.messageHistory=await this.getMessageHistory(r),t}};yf({},{RouterRunnable:()=>ZT,Runnable:()=>Ix,RunnableAssign:()=>Ux,RunnableBinding:()=>Ox,RunnableBranch:()=>JT,RunnableEach:()=>Tx,RunnableLambda:()=>Mx,RunnableMap:()=>Rx,RunnableParallel:()=>Dx,RunnablePassthrough:()=>VT,RunnablePick:()=>qx,RunnableRetry:()=>$x,RunnableSequence:()=>zx,RunnableToolLike:()=>Bx,RunnableWithFallbacks:()=>jx,RunnableWithMessageHistory:()=>YT,_coerceToRunnable:()=>Fx,ensureConfig:()=>P_,getCallbackManagerForConfig:()=>k_,mergeConfigs:()=>x_,patchConfig:()=>C_,pickRunnableConfigKeys:()=>A_});var QT=class extends Ix{parseResultWithPrompt(e,t,r){return this.parseResult(e,r)}_baseMessageToString(e){return"string"==typeof e.content?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return"string"==typeof e?this._callWithConfig(async(e,t)=>this.parseResult([{text:e}],t?.callbacks),e,{...t,runType:"parser"}):this._callWithConfig(async(e,t)=>this.parseResult([{message:e,text:this._baseMessageToString(e)}],t?.callbacks),e,{...t,runType:"parser"})}},XT=class extends QT{parseResult(e,t){return this.parse(e[0].text,t)}async parseWithPrompt(e,t,r){return this.parse(e,r)}_type(){throw new Error("_type not implemented")}},e$=class extends Error{llmOutput;observation;sendToLLM;constructor(e,t,r,n=!1){if(super(e),this.llmOutput=t,this.observation=r,this.sendToLLM=n,n&&(void 0===r||void 0===t))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");uy(this,"OUTPUT_PARSING_FAILURE")}},t$=class extends XT{async*_transform(e){for await(const t of e)"string"==typeof t?yield this.parseResult([{text:t}]):yield this.parseResult([{message:t,text:this._baseMessageToString(t)}])}async*transform(e,t){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...t,runType:"parser"})}},r$=class extends t${diff=!1;constructor(e){super(e),this.diff=e?.diff??this.diff}async*_transform(e){let t,r;for await(const n of e){if("string"!=typeof n&&"string"!=typeof n.content)throw new Error("Cannot handle non-string output.");let e;if(vg(n)){if("string"!=typeof n.content)throw new Error("Cannot handle non-string message output.");e=new fw({message:n,text:n.content})}else if(yg(n)){if("string"!=typeof n.content)throw new Error("Cannot handle non-string message output.");e=new fw({message:wy(n),text:n.content})}else e=new hw({text:n});r=void 0===r?e:r.concat(e);const a=await this.parsePartialResult([r]);null==a||Qk(a,t)||(this.diff?yield this._diff(t,a):yield a,t=a)}}getFormatInstructions(){return""}},n$=class extends t${static lc_name(){return"BytesOutputParser"}lc_namespace=["langchain_core","output_parsers","bytes"];lc_serializable=!0;textEncoder=new TextEncoder;parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}},a$=class extends t${re;async*_transform(e){let t="";for await(const r of e)if(t+="string"==typeof r?r:r.content,this.re){const e=[...t.matchAll(this.re)];if(e.length>1){let r=0;for(const t of e.slice(0,-1))yield[t[1]],r+=(t.index??0)+t[0].length;t=t.slice(r)}}else{const e=await this.parse(t);if(e.length>1){for(const t of e.slice(0,-1))yield[t];t=e[e.length-1]}}for(const e of await this.parse(t))yield[e]}},i$=class extends a${static lc_name(){return"CommaSeparatedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;async parse(e){try{return e.trim().split(",").map(e=>e.trim())}catch{throw new e$(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},s$=class extends a${lc_namespace=["langchain_core","output_parsers","list"];length;separator;constructor({length:e,separator:t}){super(...arguments),this.length=e,this.separator=t||","}async parse(e){try{const t=e.trim().split(this.separator).map(e=>e.trim());if(void 0!==this.length&&t.length!==this.length)throw new e$(`Incorrect number of items. Expected ${this.length}, got ${t.length}.`);return t}catch(t){if(Object.getPrototypeOf(t)===e$.prototype)throw t;throw new e$(`Could not parse output: ${e}`)}}getFormatInstructions(){return`Your response should be a list of ${void 0===this.length?"":`${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`}},o$=class extends a${static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return"Your response should be a numbered list with each item on a new line. For example: \n\n1. foo\n\n2. bar\n\n3. baz"}re=/\d+\.\s([^\n]+)/g;async parse(e){return[...e.matchAll(this.re)??[]].map(e=>e[1])}},c$=class extends a${static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return"Your response should be a numbered list with each item on a new line. For example: \n\n1. foo\n\n2. bar\n\n3. baz"}re=/^\s*[-*]\s([^\n]+)$/gm;async parse(e){return[...e.matchAll(this.re)??[]].map(e=>e[1])}},l$=class extends t${static lc_name(){return"StrOutputParser"}lc_namespace=["langchain_core","output_parsers","string"];lc_serializable=!0;parse(e){return Promise.resolve(e)}getFormatInstructions(){return""}_textContentToString(e){return e.text}_imageUrlContentToString(e){throw new Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentToString(e){switch(e.type){case"text":case"text_delta":if("text"in e)return this._textContentToString(e);break;case"image_url":if("image_url"in e)return this._imageUrlContentToString(e);break;default:throw new Error(`Cannot coerce "${e.type}" message part into a string.`)}throw new Error(`Invalid content type: ${e.type}`)}_baseMessageContentToString(e){return e.reduce((e,t)=>e+this._messageContentToString(t),"")}},u$=class extends XT{static lc_name(){return"StructuredOutputParser"}lc_namespace=["langchain","output_parsers","structured"];toJSON(){return this.toJSONNotImplemented()}constructor(e){super(e),this.schema=e}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){const t=wk(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,bk().describe(t)])));return new this(t)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.\n\n"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.\n\nFor example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}\nwould match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.\nThus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.\n\nYour output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!\n\nHere is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:\n\`\`\`json\n${JSON.stringify(vx(this.schema))}\n\`\`\`\n`}async parse(e){try{const t=e.trim(),r=(t.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||t.match(/```json\s*([\s\S]*?)```/)?.[1]||t).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(e,t)=>`"${t.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await fS(this.schema,JSON.parse(r))}catch(t){throw new e$(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}},d$=class extends u${static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(e){const t=e?.interpolationDepth??1;if(t<1)throw new Error("f string interpolation depth must be at least 1");return`Return a markdown code snippet with a JSON object formatted to look like:\n\`\`\`json\n${this._schemaToInstruction(vx(this.schema)).replaceAll("{","{".repeat(t)).replaceAll("}","}".repeat(t))}\n\`\`\``}_schemaToInstruction(e,t=2){const r=e;if("type"in r){let e,n=!1;if(Array.isArray(r.type)){const t=r.type.findIndex(e=>"null"===e);-1!==t&&(n=!0,r.type.splice(t,1)),e=r.type.join(" | ")}else e=r.type;if("object"===r.type&&r.properties){const e=r.description?` // ${r.description}`:"",n=Object.entries(r.properties).map(([e,n])=>{const a=r.required?.includes(e)?"":" (optional)";return`${" ".repeat(t)}"${e}": ${this._schemaToInstruction(n,t+2)}${a}`}).join("\n");return`{\n${n}\n${" ".repeat(t-2)}}${e}`}if("array"===r.type&&r.items){const e=r.description?` // ${r.description}`:"";return`array[\n${" ".repeat(t)}${this._schemaToInstruction(r.items,t+2)}\n${" ".repeat(t-2)}] ${e}`}const a=n?" (nullable)":"";return`${e}${r.description?` // ${r.description}`:""}${a}`}if("anyOf"in r)return r.anyOf.map(e=>this._schemaToInstruction(e,t)).join(`\n${" ".repeat(t-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){const t=wk(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,bk().describe(t)])));return new this(t)}},p$=class extends XT{structuredInputParser;constructor({inputSchema:e}){super(...arguments),this.structuredInputParser=new d$(e)}async parse(e){let t;try{t=await this.structuredInputParser.parse(e)}catch(t){throw new e$(`Failed to parse. Text: "${e}". Error: ${t}`,e)}return this.outputProcessor(t)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}};yf({},{applyPatch:()=>ew,compare:()=>sw});var m$=class extends r${static lc_name(){return"JsonOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_concatOutputChunks(e,t){return this.diff?super._concatOutputChunks(e,t):t}_diff(e,t){if(t)return e?sw(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return Ig(e[0].text)}async parse(e){return Ig(e,JSON.parse)}getFormatInstructions(){return""}};const h$=function(){const e={parser:function(e,t){return new r(e,t)}};e.SAXParser=r,e.SAXStream=i,e.createStream=function(e,t){return new i(e,t)},e.MAX_BUFFER_LENGTH=65536;const t=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];function r(n,a){if(!(this instanceof r))return new r(n,a);var i=this;!function(e){for(var r=0,n=t.length;r<n;r++)e[t[r]]=""}(i),i.q=i.c="",i.bufferCheckPosition=e.MAX_BUFFER_LENGTH,i.opt=a||{},i.opt.lowercase=i.opt.lowercase||i.opt.lowercasetags,i.looseCase=i.opt.lowercase?"toLowerCase":"toUpperCase",i.tags=[],i.closed=i.closedRoot=i.sawRoot=!1,i.tag=i.error=null,i.strict=!!n,i.noscript=!(!n&&!i.opt.noscript),i.state=N.BEGIN,i.strictEntities=i.opt.strictEntities,i.ENTITIES=i.strictEntities?Object.create(e.XML_ENTITIES):Object.create(e.ENTITIES),i.attribList=[],i.opt.xmlns&&(i.ns=Object.create(u)),i.trackPosition=!1!==i.opt.position,i.trackPosition&&(i.position=i.line=i.column=0),x(i,"onready")}e.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"],Object.create||(Object.create=function(e){function t(){}return t.prototype=e,new t}),Object.keys||(Object.keys=function(e){var t=[];for(var r in e)e.hasOwnProperty(r)&&t.push(r);return t}),r.prototype={end:function(){I(this)},write:function(r){var n=this;if(this.error)throw this.error;if(n.closed)return A(n,"Cannot write after close. Assign an onready handler.");if(null===r)return I(n);"object"==typeof r&&(r=r.toString());var a=0,i="";for(;i=j(r,a++),n.c=i,i;)switch(n.trackPosition&&(n.position++,"\n"===i?(n.line++,n.column=0):n.column++),n.state){case N.BEGIN:if(n.state=N.BEGIN_WHITESPACE,"\ufeff"===i)continue;D(n,i);continue;case N.BEGIN_WHITESPACE:D(n,i);continue;case N.TEXT:if(n.sawRoot&&!n.closedRoot){for(var c=a-1;i&&"<"!==i&&"&"!==i;)(i=j(r,a++))&&n.trackPosition&&(n.position++,"\n"===i?(n.line++,n.column=0):n.column++);n.textNode+=r.substring(c,a-1)}"<"!==i||n.sawRoot&&n.closedRoot&&!n.strict?(f(i)||n.sawRoot&&!n.closedRoot||O(n,"Text data outside of root node."),"&"===i?n.state=N.TEXT_ENTITY:n.textNode+=i):(n.state=N.OPEN_WAKA,n.startTagPosition=n.position);continue;case N.SCRIPT:"<"===i?n.state=N.SCRIPT_ENDING:n.script+=i;continue;case N.SCRIPT_ENDING:"/"===i?n.state=N.CLOSE_TAG:(n.script+="<"+i,n.state=N.SCRIPT);continue;case N.OPEN_WAKA:if("!"===i)n.state=N.SGML_DECL,n.sgmlDecl="";else if(f(i));else if(v(d,i))n.state=N.OPEN_TAG,n.tagName=i;else if("/"===i)n.state=N.CLOSE_TAG,n.tagName="";else if("?"===i)n.state=N.PROC_INST,n.procInstName=n.procInstBody="";else{if(O(n,"Unencoded <"),n.startTagPosition+1<n.position){var l=n.position-n.startTagPosition;i=new Array(l).join(" ")+i}n.textNode+="<"+i,n.state=N.TEXT}continue;case N.SGML_DECL:(n.sgmlDecl+i).toUpperCase()===s?(E(n,"onopencdata"),n.state=N.CDATA,n.sgmlDecl="",n.cdata=""):n.sgmlDecl+i==="--"?(n.state=N.COMMENT,n.comment="",n.sgmlDecl=""):(n.sgmlDecl+i).toUpperCase()===o?(n.state=N.DOCTYPE,(n.doctype||n.sawRoot)&&O(n,"Inappropriately located doctype declaration"),n.doctype="",n.sgmlDecl=""):">"===i?(E(n,"onsgmldeclaration",n.sgmlDecl),n.sgmlDecl="",n.state=N.TEXT):g(i)?(n.state=N.SGML_DECL_QUOTED,n.sgmlDecl+=i):n.sgmlDecl+=i;continue;case N.SGML_DECL_QUOTED:i===n.q&&(n.state=N.SGML_DECL,n.q=""),n.sgmlDecl+=i;continue;case N.DOCTYPE:">"===i?(n.state=N.TEXT,E(n,"ondoctype",n.doctype),n.doctype=!0):(n.doctype+=i,"["===i?n.state=N.DOCTYPE_DTD:g(i)&&(n.state=N.DOCTYPE_QUOTED,n.q=i));continue;case N.DOCTYPE_QUOTED:n.doctype+=i,i===n.q&&(n.q="",n.state=N.DOCTYPE);continue;case N.DOCTYPE_DTD:n.doctype+=i,"]"===i?n.state=N.DOCTYPE:g(i)&&(n.state=N.DOCTYPE_DTD_QUOTED,n.q=i);continue;case N.DOCTYPE_DTD_QUOTED:n.doctype+=i,i===n.q&&(n.state=N.DOCTYPE_DTD,n.q="");continue;case N.COMMENT:"-"===i?n.state=N.COMMENT_ENDING:n.comment+=i;continue;case N.COMMENT_ENDING:"-"===i?(n.state=N.COMMENT_ENDED,n.comment=C(n.opt,n.comment),n.comment&&E(n,"oncomment",n.comment),n.comment=""):(n.comment+="-"+i,n.state=N.COMMENT);continue;case N.COMMENT_ENDED:">"!==i?(O(n,"Malformed comment"),n.comment+="--"+i,n.state=N.COMMENT):n.state=N.TEXT;continue;case N.CDATA:"]"===i?n.state=N.CDATA_ENDING:n.cdata+=i;continue;case N.CDATA_ENDING:"]"===i?n.state=N.CDATA_ENDING_2:(n.cdata+="]"+i,n.state=N.CDATA);continue;case N.CDATA_ENDING_2:">"===i?(n.cdata&&E(n,"oncdata",n.cdata),E(n,"onclosecdata"),n.cdata="",n.state=N.TEXT):"]"===i?n.cdata+="]":(n.cdata+="]]"+i,n.state=N.CDATA);continue;case N.PROC_INST:"?"===i?n.state=N.PROC_INST_ENDING:f(i)?n.state=N.PROC_INST_BODY:n.procInstName+=i;continue;case N.PROC_INST_BODY:if(!n.procInstBody&&f(i))continue;"?"===i?n.state=N.PROC_INST_ENDING:n.procInstBody+=i;continue;case N.PROC_INST_ENDING:">"===i?(E(n,"onprocessinginstruction",{name:n.procInstName,body:n.procInstBody}),n.procInstName=n.procInstBody="",n.state=N.TEXT):(n.procInstBody+="?"+i,n.state=N.PROC_INST_BODY);continue;case N.OPEN_TAG:v(p,i)?n.tagName+=i:(T(n),">"===i?R(n):"/"===i?n.state=N.OPEN_TAG_SLASH:(f(i)||O(n,"Invalid character in tag name"),n.state=N.ATTRIB));continue;case N.OPEN_TAG_SLASH:">"===i?(R(n,!0),L(n)):(O(n,"Forward-slash in opening tag not followed by >"),n.state=N.ATTRIB);continue;case N.ATTRIB:if(f(i))continue;">"===i?R(n):"/"===i?n.state=N.OPEN_TAG_SLASH:v(d,i)?(n.attribName=i,n.attribValue="",n.state=N.ATTRIB_NAME):O(n,"Invalid attribute name");continue;case N.ATTRIB_NAME:"="===i?n.state=N.ATTRIB_VALUE:">"===i?(O(n,"Attribute without value"),n.attribValue=n.attribName,z(n),R(n)):f(i)?n.state=N.ATTRIB_NAME_SAW_WHITE:v(p,i)?n.attribName+=i:O(n,"Invalid attribute name");continue;case N.ATTRIB_NAME_SAW_WHITE:if("="===i)n.state=N.ATTRIB_VALUE;else{if(f(i))continue;O(n,"Attribute without value"),n.tag.attributes[n.attribName]="",n.attribValue="",E(n,"onattribute",{name:n.attribName,value:""}),n.attribName="",">"===i?R(n):v(d,i)?(n.attribName=i,n.state=N.ATTRIB_NAME):(O(n,"Invalid attribute name"),n.state=N.ATTRIB)}continue;case N.ATTRIB_VALUE:if(f(i))continue;g(i)?(n.q=i,n.state=N.ATTRIB_VALUE_QUOTED):(O(n,"Unquoted attribute value"),n.state=N.ATTRIB_VALUE_UNQUOTED,n.attribValue=i);continue;case N.ATTRIB_VALUE_QUOTED:if(i!==n.q){"&"===i?n.state=N.ATTRIB_VALUE_ENTITY_Q:n.attribValue+=i;continue}z(n),n.q="",n.state=N.ATTRIB_VALUE_CLOSED;continue;case N.ATTRIB_VALUE_CLOSED:f(i)?n.state=N.ATTRIB:">"===i?R(n):"/"===i?n.state=N.OPEN_TAG_SLASH:v(d,i)?(O(n,"No whitespace between attributes"),n.attribName=i,n.attribValue="",n.state=N.ATTRIB_NAME):O(n,"Invalid attribute name");continue;case N.ATTRIB_VALUE_UNQUOTED:if(!y(i)){"&"===i?n.state=N.ATTRIB_VALUE_ENTITY_U:n.attribValue+=i;continue}z(n),">"===i?R(n):n.state=N.ATTRIB;continue;case N.CLOSE_TAG:if(n.tagName)">"===i?L(n):v(p,i)?n.tagName+=i:n.script?(n.script+="</"+n.tagName,n.tagName="",n.state=N.SCRIPT):(f(i)||O(n,"Invalid tagname in closing tag"),n.state=N.CLOSE_TAG_SAW_WHITE);else{if(f(i))continue;b(d,i)?n.script?(n.script+="</"+i,n.state=N.SCRIPT):O(n,"Invalid tagname in closing tag."):n.tagName=i}continue;case N.CLOSE_TAG_SAW_WHITE:if(f(i))continue;">"===i?L(n):O(n,"Invalid characters in closing tag");continue;case N.TEXT_ENTITY:case N.ATTRIB_VALUE_ENTITY_Q:case N.ATTRIB_VALUE_ENTITY_U:var u,_;switch(n.state){case N.TEXT_ENTITY:u=N.TEXT,_="textNode";break;case N.ATTRIB_VALUE_ENTITY_Q:u=N.ATTRIB_VALUE_QUOTED,_="attribValue";break;case N.ATTRIB_VALUE_ENTITY_U:u=N.ATTRIB_VALUE_UNQUOTED,_="attribValue"}if(";"===i)if(n.opt.unparsedEntities){var w=M(n);n.entity="",n.state=u,n.write(w)}else n[_]+=M(n),n.entity="",n.state=u;else v(n.entity.length?h:m,i)?n.entity+=i:(O(n,"Invalid character in entity name"),n[_]+="&"+n.entity+i,n.entity="",n.state=u);continue;default:throw new Error(n,"Unknown state: "+n.state)}n.position>=n.bufferCheckPosition&&function(r){for(var n=Math.max(e.MAX_BUFFER_LENGTH,10),a=0,i=0,s=t.length;i<s;i++){var o=r[t[i]].length;if(o>n)switch(t[i]){case"textNode":P(r);break;case"cdata":E(r,"oncdata",r.cdata),r.cdata="";break;case"script":E(r,"onscript",r.script),r.script="";break;default:A(r,"Max buffer length exceeded: "+t[i])}a=Math.max(a,o)}var c=e.MAX_BUFFER_LENGTH-a;r.bufferCheckPosition=c+r.position}(n);return n},resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){var e;P(e=this),""!==e.cdata&&(E(e,"oncdata",e.cdata),e.cdata=""),""!==e.script&&(E(e,"onscript",e.script),e.script="")}};var n=ReadableStream;n||(n=function(){});var a=e.EVENTS.filter(function(e){return"error"!==e&&"end"!==e});function i(e,t){if(!(this instanceof i))return new i(e,t);n.apply(this),this._parser=new r(e,t),this.writable=!0,this.readable=!0;var s=this;this._parser.onend=function(){s.emit("end")},this._parser.onerror=function(e){s.emit("error",e),s._parser.error=null},this._decoder=null,a.forEach(function(e){Object.defineProperty(s,"on"+e,{get:function(){return s._parser["on"+e]},set:function(t){if(!t)return s.removeAllListeners(e),s._parser["on"+e]=t,t;s.on(e,t)},enumerable:!0,configurable:!1})})}i.prototype=Object.create(n.prototype,{constructor:{value:i}}),i.prototype.write=function(e){return this._parser.write(e.toString()),this.emit("data",e),!0},i.prototype.end=function(e){return e&&e.length&&this.write(e),this._parser.end(),!0},i.prototype.on=function(e,t){var r=this;return r._parser["on"+e]||-1===a.indexOf(e)||(r._parser["on"+e]=function(){var t=1===arguments.length?[arguments[0]]:Array.apply(null,arguments);t.splice(0,0,e),r.emit.apply(r,t)}),n.prototype.on.call(r,e,t)};var s="[CDATA[",o="DOCTYPE",c="http://www.w3.org/XML/1998/namespace",l="http://www.w3.org/2000/xmlns/",u={xml:c,xmlns:l},d=/[:_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]/,p=/[:_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\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,m=/[#:_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]/,h=/[#:_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\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function f(e){return" "===e||"\n"===e||"\r"===e||"\t"===e}function g(e){return'"'===e||"'"===e}function y(e){return">"===e||f(e)}function v(e,t){return e.test(t)}function b(e,t){return!v(e,t)}var _,w,S,N=0;for(var k in e.STATE={BEGIN:N++,BEGIN_WHITESPACE:N++,TEXT:N++,TEXT_ENTITY:N++,OPEN_WAKA:N++,SGML_DECL:N++,SGML_DECL_QUOTED:N++,DOCTYPE:N++,DOCTYPE_QUOTED:N++,DOCTYPE_DTD:N++,DOCTYPE_DTD_QUOTED:N++,COMMENT_STARTING:N++,COMMENT:N++,COMMENT_ENDING:N++,COMMENT_ENDED:N++,CDATA:N++,CDATA_ENDING:N++,CDATA_ENDING_2:N++,PROC_INST:N++,PROC_INST_BODY:N++,PROC_INST_ENDING:N++,OPEN_TAG:N++,OPEN_TAG_SLASH:N++,ATTRIB:N++,ATTRIB_NAME:N++,ATTRIB_NAME_SAW_WHITE:N++,ATTRIB_VALUE:N++,ATTRIB_VALUE_QUOTED:N++,ATTRIB_VALUE_CLOSED:N++,ATTRIB_VALUE_UNQUOTED:N++,ATTRIB_VALUE_ENTITY_Q:N++,ATTRIB_VALUE_ENTITY_U:N++,CLOSE_TAG:N++,CLOSE_TAG_SAW_WHITE:N++,SCRIPT:N++,SCRIPT_ENDING:N++},e.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},e.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(e.ENTITIES).forEach(function(t){var r=e.ENTITIES[t],n="number"==typeof r?String.fromCharCode(r):r;e.ENTITIES[t]=n}),e.STATE)e.STATE[e.STATE[k]]=k;function x(e,t,r){e[t]&&e[t](r)}function E(e,t,r){e.textNode&&P(e),x(e,t,r)}function P(e){e.textNode=C(e.opt,e.textNode),e.textNode&&x(e,"ontext",e.textNode),e.textNode=""}function C(e,t){return e.trim&&(t=t.trim()),e.normalize&&(t=t.replace(/\s+/g," ")),t}function A(e,t){return P(e),e.trackPosition&&(t+="\nLine: "+e.line+"\nColumn: "+e.column+"\nChar: "+e.c),t=new Error(t),e.error=t,x(e,"onerror",t),e}function I(e){return e.sawRoot&&!e.closedRoot&&O(e,"Unclosed root tag"),e.state!==N.BEGIN&&e.state!==N.BEGIN_WHITESPACE&&e.state!==N.TEXT&&A(e,"Unexpected end"),P(e),e.c="",e.closed=!0,x(e,"onend"),r.call(e,e.strict,e.opt),e}function O(e,t){if("object"!=typeof e||!(e instanceof r))throw new Error("bad call to strictFail");e.strict&&A(e,t)}function T(e){e.strict||(e.tagName=e.tagName[e.looseCase]());var t=e.tags[e.tags.length-1]||e,r=e.tag={name:e.tagName,attributes:{}};e.opt.xmlns&&(r.ns=t.ns),e.attribList.length=0,E(e,"onopentagstart",r)}function $(e,t){var r=e.indexOf(":")<0?["",e]:e.split(":"),n=r[0],a=r[1];return t&&"xmlns"===e&&(n="xmlns",a=""),{prefix:n,local:a}}function z(e){if(e.strict||(e.attribName=e.attribName[e.looseCase]()),-1!==e.attribList.indexOf(e.attribName)||e.tag.attributes.hasOwnProperty(e.attribName))e.attribName=e.attribValue="";else{if(e.opt.xmlns){var t=$(e.attribName,!0),r=t.prefix,n=t.local;if("xmlns"===r)if("xml"===n&&e.attribValue!==c)O(e,"xml: prefix must be bound to "+c+"\nActual: "+e.attribValue);else if("xmlns"===n&&e.attribValue!==l)O(e,"xmlns: prefix must be bound to "+l+"\nActual: "+e.attribValue);else{var a=e.tag,i=e.tags[e.tags.length-1]||e;a.ns===i.ns&&(a.ns=Object.create(i.ns)),a.ns[n]=e.attribValue}e.attribList.push([e.attribName,e.attribValue])}else e.tag.attributes[e.attribName]=e.attribValue,E(e,"onattribute",{name:e.attribName,value:e.attribValue});e.attribName=e.attribValue=""}}function R(e,t){if(e.opt.xmlns){var r=e.tag,n=$(e.tagName);r.prefix=n.prefix,r.local=n.local,r.uri=r.ns[n.prefix]||"",r.prefix&&!r.uri&&(O(e,"Unbound namespace prefix: "+JSON.stringify(e.tagName)),r.uri=n.prefix);var a=e.tags[e.tags.length-1]||e;r.ns&&a.ns!==r.ns&&Object.keys(r.ns).forEach(function(t){E(e,"onopennamespace",{prefix:t,uri:r.ns[t]})});for(var i=0,s=e.attribList.length;i<s;i++){var o=e.attribList[i],c=o[0],l=o[1],u=$(c,!0),d=u.prefix,p=u.local,m=""===d?"":r.ns[d]||"",h={name:c,value:l,prefix:d,local:p,uri:m};d&&"xmlns"!==d&&!m&&(O(e,"Unbound namespace prefix: "+JSON.stringify(d)),h.uri=d),e.tag.attributes[c]=h,E(e,"onattribute",h)}e.attribList.length=0}e.tag.isSelfClosing=!!t,e.sawRoot=!0,e.tags.push(e.tag),E(e,"onopentag",e.tag),t||(e.noscript||"script"!==e.tagName.toLowerCase()?e.state=N.TEXT:e.state=N.SCRIPT,e.tag=null,e.tagName=""),e.attribName=e.attribValue="",e.attribList.length=0}function L(e){if(!e.tagName)return O(e,"Weird empty close tag."),e.textNode+="</>",void(e.state=N.TEXT);if(e.script){if("script"!==e.tagName)return e.script+="</"+e.tagName+">",e.tagName="",void(e.state=N.SCRIPT);E(e,"onscript",e.script),e.script=""}var t=e.tags.length,r=e.tagName;e.strict||(r=r[e.looseCase]());for(var n=r;t--;){if(e.tags[t].name===n)break;O(e,"Unexpected close tag")}if(t<0)return O(e,"Unmatched closing tag: "+e.tagName),e.textNode+="</"+e.tagName+">",void(e.state=N.TEXT);e.tagName=r;for(var a=e.tags.length;a-- >t;){var i=e.tag=e.tags.pop();e.tagName=e.tag.name,E(e,"onclosetag",e.tagName);var s={};for(var o in i.ns)s[o]=i.ns[o];var c=e.tags[e.tags.length-1]||e;e.opt.xmlns&&i.ns!==c.ns&&Object.keys(i.ns).forEach(function(t){var r=i.ns[t];E(e,"onclosenamespace",{prefix:t,uri:r})})}0===t&&(e.closedRoot=!0),e.tagName=e.attribValue=e.attribName="",e.attribList.length=0,e.state=N.TEXT}function M(e){var t,r=e.entity,n=r.toLowerCase(),a="";return e.ENTITIES[r]?e.ENTITIES[r]:e.ENTITIES[n]?e.ENTITIES[n]:("#"===(r=n).charAt(0)&&("x"===r.charAt(1)?(r=r.slice(2),a=(t=parseInt(r,16)).toString(16)):(r=r.slice(1),a=(t=parseInt(r,10)).toString(10))),r=r.replace(/^0+/,""),isNaN(t)||a.toLowerCase()!==r?(O(e,"Invalid character entity"),"&"+e.entity+";"):String.fromCodePoint(t))}function D(e,t){"<"===t?(e.state=N.OPEN_WAKA,e.startTagPosition=e.position):f(t)||(O(e,"Non-whitespace before first tag."),e.textNode=t,e.state=N.TEXT)}function j(e,t){var r="";return t<e.length&&(r=e.charAt(t)),r}return N=e.STATE,String.fromCodePoint||(_=String.fromCharCode,w=Math.floor,S=function(){var e,t,r=[],n=-1,a=arguments.length;if(!a)return"";for(var i="";++n<a;){var s=Number(arguments[n]);if(!isFinite(s)||s<0||s>1114111||w(s)!==s)throw RangeError("Invalid code point: "+s);s<=65535?r.push(s):(e=55296+((s-=65536)>>10),t=s%1024+56320,r.push(e,t)),(n+1===a||r.length>16384)&&(i+=_.apply(null,r),r.length=0)}return i},Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:S,configurable:!0,writable:!0}):String.fromCodePoint=S),e}(),f$='The output should be formatted as a XML file.\n1. Output should conform to the tags below. \n2. If tags are not given, make them on your own.\n3. Remember to always open and close all the tags.\n\nAs an example, for the tags ["foo", "bar", "baz"]:\n1. String "<foo>\n <bar>\n <baz></baz>\n </bar>\n</foo>" is a well-formatted instance of the schema. \n2. String "<foo>\n <bar>\n </foo>" is a badly-formatted instance.\n3. String "<foo>\n <tag>\n </tag>\n</foo>" is a badly-formatted instance.\n\nHere are the output tags:\n```\n{tags}\n```';var g$=class extends r${tags;constructor(e){super(e),this.tags=e?.tags}static lc_name(){return"XMLOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_diff(e,t){if(t)return e?sw(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return b$(e[0].text)}async parse(e){return b$(e)}getFormatInstructions(){return!!(this.tags&&this.tags.length>0)?f$.replace("{tags}",this.tags?.join(", ")??""):f$}};const y$=e=>e.split("\n").map(e=>e.replace(/^\s+/,"")).join("\n").trim(),v$=e=>{if(0===Object.keys(e).length)return{};const t={};return e.children.length>0?(t[e.name]=e.children.map(v$),t):(t[e.name]=e.text??void 0,t)};function b$(e){const t=y$(e),r=h$.parser(!0);let n={};const a=[];r.onopentag=e=>{const t={name:e.name,attributes:e.attributes,children:[],text:"",isSelfClosing:e.isSelfClosing};if(a.length>0){a[a.length-1].children.push(t)}else n=t;e.isSelfClosing||a.push(t)},r.onclosetag=()=>{if(a.length>0){const e=a.pop();0===a.length&&e&&(n=e)}},r.ontext=e=>{if(a.length>0){a[a.length-1].text+=e}},r.onattribute=e=>{if(a.length>0){a[a.length-1].attributes[e.name]=e.value}};const i=/```(xml)?(.*)```/s.exec(t),s=i?i[2]:t;return r.write(s).close(),n&&"?xml"===n.name&&(n=n.children[0]),v$(n)}function _$(e,t){if(void 0===e.function)return;let r;if(t?.partial)try{r=Og(e.function.arguments??"{}")}catch{return}else try{r=JSON.parse(e.function.arguments)}catch(t){throw new e$([`Function "${e.function.name}" arguments:`,"",e.function.arguments,"","are not valid JSON.",`Error: ${t.message}`].join("\n"))}const n={name:e.function.name,args:r,type:"tool_call"};return t?.returnId&&(n.id=e.id),n}function w$(e){if(void 0===e.id)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}}}function S$(e,t){return{name:e.function?.name,args:e.function?.arguments,id:e.id,error:t,type:"invalid_tool_call"}}yf({},{AsymmetricStructuredOutputParser:()=>p$,BaseCumulativeTransformOutputParser:()=>r$,BaseLLMOutputParser:()=>QT,BaseOutputParser:()=>XT,BaseTransformOutputParser:()=>t$,BytesOutputParser:()=>n$,CommaSeparatedListOutputParser:()=>i$,CustomListOutputParser:()=>s$,JsonMarkdownStructuredOutputParser:()=>d$,JsonOutputParser:()=>m$,ListOutputParser:()=>a$,MarkdownListOutputParser:()=>c$,NumberedListOutputParser:()=>o$,OutputParserException:()=>e$,StringOutputParser:()=>l$,StructuredOutputParser:()=>u$,XMLOutputParser:()=>g$,XML_FORMAT_INSTRUCTIONS:()=>f$,parseJsonMarkdown:()=>Ig,parsePartialJson:()=>Og,parseXMLMarkdown:()=>b$});var N$=class extends r${static lc_name(){return"JsonOutputToolsParser"}returnId=!1;lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;constructor(e){super(e),this.returnId=e?.returnId??this.returnId}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,t=!0){const r=e[0].message;let n;if(Vg(r)&&r.tool_calls?.length)n=r.tool_calls.map(e=>{const{id:t,...r}=e;return this.returnId?{id:t,...r}:r});else if(void 0!==r.additional_kwargs.tool_calls){n=JSON.parse(JSON.stringify(r.additional_kwargs.tool_calls)).map(e=>_$(e,{returnId:this.returnId,partial:t}))}if(!n)return[];const a=[];for(const e of n)if(void 0!==e){const t={type:e.name,args:e.args,id:e.id};a.push(t)}return a}},k$=class extends N${static lc_name(){return"JsonOutputKeyToolsParser"}lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(void 0===this.zodSchema)return e;const t=await hS(this.zodSchema,e);if(t.success)return t.data;throw new e$(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error?.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){const t=(await super.parsePartialResult(e)).filter(e=>e.type===this.keyName);let r=t;if(t.length)return this.returnId||(r=t.map(e=>e.args)),this.returnSingle?r[0]:r}async parseResult(e){const t=(await super.parsePartialResult(e,!1)).filter(e=>e.type===this.keyName);let r=t;if(!t.length)return;if(this.returnId||(r=t.map(e=>e.args)),this.returnSingle)return this._validateResult(r[0]);return await Promise.all(r.map(e=>this._validateResult(e)))}};yf({},{JsonOutputKeyToolsParser:()=>k$,JsonOutputToolsParser:()=>N$,convertLangChainToolCallToOpenAI:()=>w$,makeInvalidToolCall:()=>S$,parseToolCall:()=>_$});var x$=class extends KT{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","verbosity"]}getLsParams(e){const t=this.invocationParams(e);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(e){super(e??{});const t="string"==typeof e?.configuration?.apiKey?e?.configuration?.apiKey:void 0;this.apiKey=e?.apiKey??t??$y("OPENAI_API_KEY"),this.organization=e?.configuration?.organization??$y("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelKwargs=e?.modelKwargs??{},this.timeout=e?.timeout,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.frequencyPenalty=e?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=e?.presencePenalty??this.presencePenalty,this.logprobs=e?.logprobs,this.topLogprobs=e?.topLogprobs,this.n=e?.n??this.n,this.logitBias=e?.logitBias,this.stop=e?.stopSequences??e?.stop,this.stopSequences=this.stop,this.user=e?.user,this.__includeRawResponse=e?.__includeRawResponse,this.audio=e?.audio,this.modalities=e?.modalities,this.reasoning=e?.reasoning,this.maxTokens=e?.maxCompletionTokens??e?.maxTokens,this.promptCacheKey=e?.promptCacheKey??this.promptCacheKey,this.verbosity=e?.verbosity??this.verbosity,this.disableStreaming=!0===e?.disableStreaming,this.streaming=!0===e?.streaming,this.disableStreaming&&(this.streaming=!1),!1===e?.streaming&&(this.disableStreaming=!0),this.streamUsage=e?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration},void 0!==e?.supportsStrictToolCalling&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),void 0!==e?.service_tier&&(this.service_tier=e.service_tier),this.zdrEnabled=e?.zdrEnabled??!1}_getReasoningParams(e){if(!aE(this.model))return;let t;return void 0!==this.reasoning&&(t={...t,...this.reasoning}),void 0!==e?.reasoning&&(t={...t,...e.reasoning}),t}_getResponseFormat(e){return e&&"json_schema"===e.type&&e.json_schema.schema&&uS(e.json_schema.schema)?zP(e.json_schema.schema,e.json_schema.name,{description:e.json_schema.description}):e}_combineCallOptions(e){return{...this.defaultOptions,...e??{}}}_getClientOptions(e){if(!this.client){const e=sE({baseURL:this.clientConfig.baseURL}),t={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};t.baseURL||delete t.baseURL,this.client=new iT(t)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,t){return bE(e)?function(e){return{type:"custom",custom:{name:e.name,description:e.description,format:(()=>{if(e.format)return"grammar"===e.format.type?{type:"grammar",grammar:{definition:e.format.definition,syntax:e.format.syntax}}:"text"===e.format.type?{type:"text"}:void 0})()}}}(e.metadata.customTool):FT(e)?void 0!==t?.strict?{...e,function:{...e.function,strict:t.strict}}:e:function(e,t){let r;return r=pE(e)?hE(e):e,void 0!==t?.strict&&(r.function.strict=t.strict),r}(e,t)}bindTools(e,t){let r;return void 0!==t?.strict?r=t.strict:void 0!==this.supportsStrictToolCalling&&(r=this.supportsStrictToolCalling),this.withConfig({tools:e.map(e=>vE(e)||bE(e)?e:this._convertChatOpenAIToolToCompletionsTool(e,{strict:r})),...t})}async stream(e,t){return super.stream(e,this._combineCallOptions(t))}async invoke(e,t){return super.invoke(e,this._combineCallOptions(t))}_combineLLMOutput(...e){return e.reduce((e,t)=>(t&&t.tokenUsage&&(e.tokenUsage.completionTokens+=t.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=t.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=t.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let t=0,r=0,n=0;"gpt-3.5-turbo-0301"===this.model?(r=4,n=-1):(r=3,n=1);const a=await Promise.all(e.map(async e=>{const a=await this.getNumTokens(e.content),i=await this.getNumTokens(iE(e)),s=void 0!==e.name?n+await this.getNumTokens(e.name):0;let o=a+r+i+s;const c=e;if("function"===c._getType()&&(o-=2),c.additional_kwargs?.function_call&&(o+=3),c?.additional_kwargs.function_call?.name&&(o+=await this.getNumTokens(c.additional_kwargs.function_call?.name)),c.additional_kwargs.function_call?.arguments)try{o+=await this.getNumTokens(JSON.stringify(JSON.parse(c.additional_kwargs.function_call?.arguments)))}catch(e){console.error("Error parsing function arguments",e,JSON.stringify(c.additional_kwargs.function_call)),o+=await this.getNumTokens(c.additional_kwargs.function_call?.arguments)}return t+=o,o}));return t+=3,{totalCount:t,countPerMessage:a}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,t)=>e+t,0)}async _getEstimatedTokenCountFromPrompt(e,t,r){let n=(await this.getNumTokensFromMessages(e)).totalCount;if(t&&"auto"!==r){const e=function(e){const t=["namespace functions {",""];for(const r of e)r.description&&t.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(t.push(`type ${r.name} = (_: {`),t.push(fE(r.parameters,0)),t.push("}) => any;")):t.push(`type ${r.name} = () => any;`),t.push("");return t.push("} // namespace functions"),t.join("\n")}(t);n+=await this.getNumTokens(e),n+=9}return t&&e.find(e=>"system"===e._getType())&&(n-=4),"none"===r?n+=1:"object"==typeof r&&(n+=await this.getNumTokens(r.name)+4),n}_getStructuredOutputMethod(e){const t={...e};if(this.model.startsWith("gpt-3")||this.model.startsWith("gpt-4-")||"gpt-4"===this.model)"jsonSchema"===t.method&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);else if(void 0===t?.method)return"jsonSchema";return t.method}withStructuredOutput(e,t){let r,n;const{schema:a,name:i,includeRaw:s}={...t,schema:e};if(void 0!==t?.strict&&"jsonMode"===t.method)throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");const o=function(e,t){if(void 0!==t&&!$P.includes(t))throw new Error(`Invalid method: ${t}. Supported methods are: ${$P.join(", ")}`);const r=!e.startsWith("gpt-3")&&!e.startsWith("gpt-4-")&&"gpt-4"!==e;if(r&&!t)return"jsonSchema";if(!r&&"jsonSchema"===t)throw new Error(`JSON Schema is not supported for model "${e}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return t??"functionCalling"}(this.model,t?.method);if("jsonMode"===o){n=uS(a)?u$.fromZodSchema(a):new m$;const e=vx(a);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:i??"extract",...e}}})}else if("jsonSchema"===o){const e={name:i??"extract",description:vS(a),schema:a,strict:t?.strict},s=vx(e.schema);if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:e},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:e.name,description:e.description,...s}}}),uS(a)){const e=u$.fromZodSchema(a);n=Mx.from(t=>"parsed"in t.additional_kwargs?t.additional_kwargs.parsed:e)}else n=new m$}else{let e=i??"extract";if(uS(a)){const i=vx(a);r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:{name:e,description:i.description,parameters:i}}],tool_choice:{type:"function",function:{name:e}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:e,...i}},...void 0!==t?.strict?{strict:t.strict}:{}}),n=new k$({returnSingle:!0,keyName:e,zodSchema:a})}else{let i;"string"==typeof a.name&&"object"==typeof a.parameters&&null!=a.parameters?(i=a,e=a.name):(e=a.title??e,i={name:e,description:a.description??"",parameters:a});const s=vx(a);r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:i}],tool_choice:{type:"function",function:{name:e}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:e,...s}},...void 0!==t?.strict?{strict:t.strict}:{}}),n=new k$({returnSingle:!0,keyName:e})}}if(!s)return r.pipe(n);const c=VT.assign({parsed:(e,t)=>n.invoke(e.raw,t)}),l=VT.assign({parsed:()=>null}),u=c.withFallbacks({fallbacks:[l]});return zx.from([{raw:r},u])}};function E$(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${t}/\n`,e}function P$(e){if(!e||"object"!=typeof e)return e;let t;return e.constructor.name===AE.name&&"message"in e&&"string"==typeof e.message?(t=new Error(e.message),t.name="TimeoutError"):e.constructor.name===PE.name&&"message"in e&&"string"==typeof e.message?(t=new Error(e.message),t.name="AbortError"):t="status"in e&&400===e.status&&"message"in e&&"string"==typeof e.message&&e.message.includes("tool_calls")?E$(e,"INVALID_TOOL_RESULTS"):"status"in e&&401===e.status?E$(e,"MODEL_AUTHENTICATION"):"status"in e&&429===e.status?E$(e,"MODEL_RATE_LIMIT"):"status"in e&&404===e.status?E$(e,"MODEL_NOT_FOUND"):e,t}function C$(e){if("image"===e.type){if(e.url)return{type:"image_url",image_url:{url:e.url}};if(e.data)return{type:"image_url",image_url:{url:`data:${e.mimeType};base64,${e.data}`}}}if("audio"===e.type&&e.data){const t=nE(()=>{const[,t]=e.mimeType.split("/");return"wav"===t||"mp3"===t?t:"wav"});return{type:"input_audio",input_audio:{data:e.data.toString(),format:t}}}if("file"===e.type){if(e.data)return{type:"file",file:{file_data:e.data.toString()}};if(e.fileId)return{type:"file",file:{file_id:e.fileId}}}}const A$={providerName:"ChatOpenAI",fromStandardTextBlock:e=>({type:"text",text:e.text}),fromStandardImageBlock(e){if("url"===e.source_type)return{type:"image_url",image_url:{url:e.url,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};if("base64"===e.source_type){return{type:"image_url",image_url:{url:`data:${e.mime_type??""};base64,${e.data}`,...e.metadata?.detail?{detail:e.metadata.detail}:{}}}}throw new Error(`Image content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(e){if("url"===e.source_type){const t=xf({dataUrl:e.url});if(!t)throw new Error(`URL audio blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);const r=t.mime_type||e.mime_type||"";let n;try{n=kf(r)}catch{throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if("audio"!==n.type||"wav"!==n.subtype&&"mp3"!==n.subtype)throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:n.subtype,data:t.data}}}if("base64"===e.source_type){let t;try{t=kf(e.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if("audio"!==t.type||"wav"!==t.subtype&&"mp3"!==t.subtype)throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:t.subtype,data:e.data}}}throw new Error(`Audio content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(e){if("url"===e.source_type){if(!xf({dataUrl:e.url}))throw new Error(`URL file blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:e.url,...e.metadata?.filename||e.metadata?.name?{filename:e.metadata?.filename||e.metadata?.name}:{}}}}if("base64"===e.source_type)return{type:"file",file:{file_data:`data:${e.mime_type??""};base64,${e.data}`,...e.metadata?.filename||e.metadata?.name||e.metadata?.title?{filename:e.metadata?.filename||e.metadata?.name||e.metadata?.title}:{}}};if("id"===e.source_type)return{type:"file",file:{file_id:e.id}};throw new Error(`File content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)}};function I$(e,t){return e.flatMap(e=>{if("output_version"in e.response_metadata&&"v1"===e.response_metadata?.output_version)return function(e,t){let r=iE(e);return"system"===r&&aE(t)&&(r="developer"),"developer"===r?{role:"developer",content:e.contentBlocks.filter(e=>"text"===e.type)}:"system"===r?{role:"system",content:e.contentBlocks.filter(e=>"text"===e.type)}:"assistant"===r?{role:"assistant",content:e.contentBlocks.filter(e=>"text"===e.type)}:"tool"===r&&xg.isInstance(e)?{role:"tool",tool_call_id:e.tool_call_id,content:e.contentBlocks.filter(e=>"text"===e.type)}:"function"===r?{role:"function",name:e.name??"",content:e.contentBlocks.filter(e=>"text"===e.type).join("")}:{role:"user",content:Array.from(function*(e){for(const t of e){"text"===t.type&&(yield{type:"text",text:t.text});const e=C$(t);e&&(yield e)}}(e.contentBlocks))}}(e);let r=iE(e);"system"===r&&aE(t)&&(r="developer");const n={role:r,content:"string"==typeof e.content?e.content:e.content.map(e=>vf(e)?Ef(e,A$):e)};if(null!=e.name&&(n.name=e.name),null!=e.additional_kwargs.function_call&&(n.function_call=e.additional_kwargs.function_call,n.content=""),Vg(e)&&e.tool_calls?.length?(n.tool_calls=e.tool_calls.map(w$),n.content=""):(null!=e.additional_kwargs.tool_calls&&(n.tool_calls=e.additional_kwargs.tool_calls),null!=e.tool_call_id&&(n.tool_call_id=e.tool_call_id)),e.additional_kwargs.audio&&"object"==typeof e.additional_kwargs.audio&&"id"in e.additional_kwargs.audio){return[n,{role:"assistant",audio:{id:e.additional_kwargs.audio.id}}]}return n})}const O$="__openai_function_call_ids__";var T$=class extends x${invocationParams(e){let t;void 0!==e?.strict?t=e.strict:void 0!==this.supportsStrictToolCalling&&(t=this.supportsStrictToolCalling);const r={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,stream:this.streaming,previous_response_id:e?.previous_response_id,truncation:e?.truncation,include:e?.include,tools:e?.tools?.length?this._reduceChatOpenAITools(e.tools,{stream:this.streaming,strict:t}):void 0,tool_choice:(n=e?.tool_choice,null!=n&&"object"==typeof n&&"type"in n&&"function"!==n.type?e?.tool_choice:(()=>{const t=yE(e?.tool_choice);if("object"==typeof t&&"type"in t){if("function"===t.type)return{type:"function",name:t.function.name};if("allowed_tools"===t.type)return{type:"allowed_tools",mode:t.allowed_tools.mode,tools:t.allowed_tools.tools};if("custom"===t.type)return{type:"custom",name:t.custom.name}}})()),text:(()=>{if(e?.text)return e.text;const t=this._getResponseFormat(e?.response_format);return"json_schema"===t?.type?null!=t.json_schema.schema?{format:{type:"json_schema",schema:t.json_schema.schema,description:t.json_schema.description,name:t.json_schema.name,strict:t.json_schema.strict},verbosity:e?.verbosity}:void 0:{format:t,verbosity:e?.verbosity}})(),parallel_tool_calls:e?.parallel_tool_calls,max_output_tokens:-1===this.maxTokens?void 0:this.maxTokens,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs};var n;const a=this._getReasoningParams(e);return void 0!==a&&(r.reasoning=a),r}async _generate(e,t){const r=this.invocationParams(t);if(r.stream){const r=this._streamResponseChunks(e,t);let n;for await(const e of r)e.message.response_metadata={...e.generationInfo,...e.message.response_metadata},n=n?.concat(e)??e;return{generations:n?[n]:[],llmOutput:{estimatedTokenUsage:(n?.message)?.usage_metadata}}}{const n=this._convertMessagesToResponsesParams(e),a=await this.completionWithRetry({input:n,...r,stream:!1},{signal:t?.signal,...t?.options});return{generations:[{text:a.output_text,message:this._convertResponsesMessageToBaseMessage(a)}],llmOutput:{id:a.id,estimatedTokenUsage:a.usage?{promptTokens:a.usage.input_tokens,completionTokens:a.usage.output_tokens,totalTokens:a.usage.total_tokens}:void 0}}}}async*_streamResponseChunks(e,t,r){const n=await this.completionWithRetry({...this.invocationParams(t),input:this._convertMessagesToResponsesParams(e),stream:!0},t);for await(const e of n){const n=this._convertResponsesDeltaToBaseMessageChunk(e);null!=n&&(yield n,await(r?.handleLLMNewToken(n.text||"",{prompt:t.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:n})))}}async completionWithRetry(e,t){return this.caller.call(async()=>{const r=this._getClientOptions(t);try{return"json_schema"!==e.text?.format?.type||e.stream?await this.client.responses.create(e,r):await this.client.responses.parse(e,r)}catch(e){throw P$(e)}})}_convertResponsesMessageToBaseMessage(e){if(e.error){const t=new Error(e.error.message);throw t.name=e.error.code,t}let t;const r=[],n=[],a=[],i={model_provider:"openai",model:e.model,created_at:e.created_at,id:e.id,incomplete_details:e.incomplete_details,metadata:e.metadata,object:e.object,status:e.status,user:e.user,service_tier:e.service_tier,model_name:e.model},s={};for(const i of e.output)if("message"===i.type)t=i.id,r.push(...i.content.flatMap(e=>"output_text"===e.type?("parsed"in e&&null!=e.parsed&&(s.parsed=e.parsed),{type:"text",text:e.text,annotations:e.annotations}):"refusal"===e.type?(s.refusal=e.refusal,[]):e));else if("function_call"===i.type){const e={function:{name:i.name,arguments:i.arguments},id:i.call_id};try{n.push(_$(e,{returnId:!0}))}catch(t){let r;"object"==typeof t&&null!=t&&"message"in t&&"string"==typeof t.message&&(r=t.message),a.push(S$(e,r))}s[O$]??={},i.id&&(s[O$][i.call_id]=i.id)}else if("reasoning"===i.type)s.reasoning=i;else if("custom_tool_call"===i.type){const e=wE(i);e?n.push(e):a.push(S$(i,"Malformed custom tool call"))}else s.tool_outputs??=[],s.tool_outputs.push(i);return new Bg({id:t,content:r,tool_calls:n,invalid_tool_calls:a,usage_metadata:RP(e.usage),additional_kwargs:s,response_metadata:i})}_convertResponsesDeltaToBaseMessageChunk(e){const t=[];let r,n={};const a=[],i={model_provider:"openai"},s={};let o;if("response.output_text.delta"===e.type)t.push({type:"text",text:e.delta,index:e.content_index});else if("response.output_text.annotation.added"===e.type)t.push({type:"text",text:"",annotations:[e.annotation],index:e.content_index});else if("response.output_item.added"===e.type&&"message"===e.item.type)o=e.item.id;else if("response.output_item.added"===e.type&&"function_call"===e.item.type)a.push({type:"tool_call_chunk",name:e.item.name,args:e.item.arguments,id:e.item.call_id,index:e.output_index}),s[O$]={[e.item.call_id]:e.item.id};else if("response.output_item.done"===e.type&&["web_search_call","file_search_call","computer_call","code_interpreter_call","mcp_call","mcp_list_tools","mcp_approval_request","image_generation_call","custom_tool_call"].includes(e.item.type))s.tool_outputs=[e.item];else if("response.created"===e.type)i.id=e.response.id,i.model_name=e.response.model,i.model=e.response.model;else if("response.completed"===e.type){const t=this._convertResponsesMessageToBaseMessage(e.response);r=RP(e.response.usage),"json_schema"===e.response.text?.format?.type&&(s.parsed??=JSON.parse(t.text));for(const[t,r]of Object.entries(e.response))"id"!==t&&(i[t]=r)}else if("response.function_call_arguments.delta"===e.type||"response.custom_tool_call_input.delta"===e.type)a.push({type:"tool_call_chunk",args:e.delta,index:e.output_index});else if("response.web_search_call.completed"===e.type||"response.file_search_call.completed"===e.type)n={tool_outputs:{id:e.item_id,type:e.type.replace("response.","").replace(".completed",""),status:"completed"}};else if("response.refusal.done"===e.type)s.refusal=e.refusal;else if("response.output_item.added"===e.type&&"item"in e&&"reasoning"===e.item.type){const t=e.item.summary?e.item.summary.map((e,t)=>({...e,index:t})):void 0;s.reasoning={id:e.item.id,type:e.item.type,...t?{summary:t}:{}}}else if("response.reasoning_summary_part.added"===e.type)s.reasoning={type:"reasoning",summary:[{...e.part,index:e.summary_index}]};else{if("response.reasoning_summary_text.delta"!==e.type)return e.type,null;s.reasoning={type:"reasoning",summary:[{text:e.delta,type:"summary_text",index:e.summary_index}]}}return new fw({text:t.map(e=>e.text).join(""),message:new Hg({id:o,content:t,tool_call_chunks:a,usage_metadata:r,additional_kwargs:s,response_metadata:i}),generationInfo:n})}_convertMessagesToResponsesParams(e){return e.flatMap(e=>{const t=e.response_metadata;if("v1"===t?.output_version)return function(e){const t=Vg(e)&&"openai"===e.response_metadata?.model_provider;return Array.from(function*(){const r=nE(()=>{try{const t=iE(e);return"system"===t||"developer"===t||"assistant"===t||"user"===t?t:"assistant"}catch{return"assistant"}});let n;const a=new Set,i=new Set,s=new Map,o=new Map;function*c(){if(!n)return;const e=n.content;("string"==typeof e&&e.length>0||Array.isArray(e)&&e.length>0)&&(yield n),n=void 0}const l=e=>{n||(n={type:"message",role:r,content:[]}),"string"==typeof n.content?n.content=n.content.length>0?[{type:"input_text",text:n.content},...e]:[...e]:n.content.push(...e)},u=e=>{if("string"==typeof e)return e;try{return JSON.stringify(e??{})}catch{return"{}"}},d=e=>{const t=nE(()=>{const t=e.metadata?.detail;return"low"===t||"high"===t||"auto"===t?t:"auto"});if(e.fileId)return{type:"input_image",detail:t,file_id:e.fileId};if(e.url)return{type:"input_image",detail:t,image_url:e.url};if(e.data){const r="string"==typeof e.data?e.data:Buffer.from(e.data).toString("base64");return{type:"input_image",detail:t,image_url:`data:${e.mimeType??"image/png"};base64,${r}`}}},p=e=>{const t=e.metadata?.filename??e.metadata?.name??e.metadata?.title;if(e.fileId&&"string"==typeof t)return{type:"input_file",file_id:e.fileId,...t?{filename:t}:{}};if(e.url&&"string"==typeof t)return{type:"input_file",file_url:e.url,...t?{filename:t}:{}};if(e.data&&"string"==typeof t){const r="string"==typeof e.data?e.data:Buffer.from(e.data).toString("base64");return{type:"input_file",file_data:`data:${e.mimeType??"application/octet-stream"};base64,${r}`,...t?{filename:t}:{}}}},m=e=>{const t=nE(()=>{if(Array.isArray(e.summary)){const t=e.summary,r=t?.map(e=>e?.text).filter(e=>"string"==typeof e)??[];if(r.length>0)return r}return e.reasoning?[e.reasoning]:[]}),r=t.length>0?t.map(e=>({type:"summary_text",text:e})):[{type:"summary_text",text:""}],n={type:"reasoning",id:e.id??"",summary:r};return e.reasoning&&(n.content=[{type:"reasoning_text",text:e.reasoning}]),n},h=e=>({type:"function_call",name:e.name??"",call_id:e.id??"",arguments:u(e.args)}),f=e=>{const t=u(e.output),r="success"===e.status?"completed":"error"===e.status?"incomplete":void 0;return{type:"function_call_output",call_id:e.toolCallId??"",output:t,...r?{status:r}:{}}};for(const r of e.contentBlocks)if("text"===r.type)l([{type:"input_text",text:r.text}]);else if("invalid_tool_call"===r.type);else if("reasoning"===r.type)yield*c(),yield m(r);else if("tool_call"===r.type){yield*c();const e=r.id??"";e&&(a.add(e),s.delete(e)),yield h(r)}else if("tool_call_chunk"===r.type){if(r.id){const e=s.get(r.id)??{name:r.name,args:[]};r.name&&(e.name=r.name),r.args&&e.args.push(r.args),s.set(r.id,e)}}else if("server_tool_call"===r.type){yield*c();const e=r.id??"";e&&(i.add(e),o.delete(e)),yield h(r)}else if("server_tool_call_chunk"===r.type){if(r.id){const e=o.get(r.id)??{name:r.name,args:[]};r.name&&(e.name=r.name),r.args&&e.args.push(r.args),o.set(r.id,e)}}else if("server_tool_call_result"===r.type)yield*c(),yield f(r);else if("audio"===r.type);else if("file"===r.type){const e=p(r);e&&l([e])}else if("image"===r.type){const e=d(r);e&&l([e])}else if("video"===r.type){const e=p(r);e&&l([e])}else"text-plain"===r.type?r.text&&l([{type:"input_text",text:r.text}]):"non_standard"===r.type&&t&&(yield*c(),yield r.value);yield*c();for(const[e,t]of s){if(!e||a.has(e))continue;const r=t.args.join("");(t.name||r)&&(yield{type:"function_call",call_id:e,name:t.name??"",arguments:r})}for(const[e,t]of o){if(!e||i.has(e))continue;const r=t.args.join("");(t.name||r)&&(yield{type:"function_call",call_id:e,name:t.name??"",arguments:r})}}())}(e);const r=e.additional_kwargs;let n=iE(e);if("system"===n&&aE(this.model)&&(n="developer"),"function"===n)throw new Error("Function messages are not supported in Responses API");if("tool"===n){const t=e;if("computer_call_output"===r?.type){const e=(()=>{if("string"==typeof t.content)return{type:"computer_screenshot",image_url:t.content};if(Array.isArray(t.content)){const e=t.content.find(e=>"computer_screenshot"===e.type);if(e)return e;const r=t.content.find(e=>"image_url"===e.type);if(r)return{type:"computer_screenshot",image_url:"string"==typeof r.image_url?r.image_url:r.image_url.url}}throw new Error("Invalid computer call output")})();return{type:"computer_call_output",output:e,call_id:t.tool_call_id}}return t.additional_kwargs?.customTool?{type:"custom_tool_call_output",call_id:t.tool_call_id,output:t.content}:{type:"function_call_output",call_id:t.tool_call_id,id:t.id?.startsWith("fc_")?t.id:void 0,output:"string"!=typeof t.content?JSON.stringify(t.content):t.content}}if("assistant"===n){if(!this.zdrEnabled&&null!=t?.output&&Array.isArray(t?.output)&&t?.output.length>0&&t?.output.every(e=>"type"in e))return t?.output;const n=[];if(r?.reasoning&&!this.zdrEnabled){const e=this._convertReasoningSummary(r.reasoning);n.push(e)}let{content:a}=e;r?.refusal&&("string"==typeof a&&(a=[{type:"output_text",text:a,annotations:[]}]),a=[...a,{type:"refusal",refusal:r.refusal}]),("string"==typeof a||a.length>0)&&n.push({type:"message",role:"assistant",...e.id&&!this.zdrEnabled&&e.id.startsWith("msg_")?{id:e.id}:{},content:nE(()=>"string"==typeof a?a:a.flatMap(e=>"text"===e.type?{type:"output_text",text:e.text,annotations:e.annotations??[]}:"output_text"===e.type||"refusal"===e.type?e:[]))});const i=r?.[O$];Vg(e)&&e.tool_calls?.length?n.push(...e.tool_calls.map(e=>function(e){return"tool_call"===e.type&&"isCustomTool"in e&&!0===e.isCustomTool}(e)?{type:"custom_tool_call",id:e.call_id,call_id:e.id??"",input:e.args.input,name:e.name}:{type:"function_call",name:e.name,arguments:JSON.stringify(e.args),call_id:e.id,...this.zdrEnabled?{id:i?.[e.id]}:{}})):r?.tool_calls&&n.push(...r.tool_calls.map(e=>({type:"function_call",name:e.function.name,call_id:e.id,arguments:e.function.arguments,...this.zdrEnabled?{id:i?.[e.id]}:{}})));const s=(t?.output)?.length?t?.output:r.tool_outputs,o=["computer_call","mcp_call","code_interpreter_call","image_generation_call"];if(null!=s){const e=s,t=e?.filter(e=>o.includes(e.type));t.length>0&&n.push(...t)}return n}if("user"===n||"system"===n||"developer"===n){if("string"==typeof e.content)return{type:"message",role:n,content:e.content};const t=[],r=e.content.flatMap(e=>{if("mcp_approval_response"===e.type&&t.push({type:"mcp_approval_response",approval_request_id:e.approval_request_id,approve:e.approve}),vf(e))return Ef(e,A$);if("text"===e.type)return{type:"input_text",text:e.text};if("image_url"===e.type){return{type:"input_image",image_url:nE(()=>"string"==typeof e.image_url?e.image_url:"object"==typeof e.image_url&&null!==e.image_url&&"url"in e.image_url?e.image_url.url:void 0),detail:nE(()=>"string"==typeof e.image_url?"auto":"object"==typeof e.image_url&&null!==e.image_url&&"detail"in e.image_url?e.image_url.detail:void 0)}}return"input_text"===e.type||"input_image"===e.type||"input_file"===e.type?e:[]});return r.length>0&&t.push({type:"message",role:n,content:r}),t}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${n}`),[]})}_convertReasoningSummary(e){const t=(e.summary.length>1?e.summary.reduce((e,t)=>{const r=e[e.length-1];return r.index===t.index?r.text+=t.text:e.push(t),e},[{...e.summary[0]}]):e.summary).map(e=>Object.fromEntries(Object.entries(e).filter(([e])=>"index"!==e)));return{...e,summary:t}}_reduceChatOpenAITools(e,t){const r=[];for(const n of e)if(vE(n))"image_generation"===n.type&&t?.stream&&(n.partial_images=1),r.push(n);else if(bE(n)){const e=n.metadata.customTool;r.push({type:"custom",name:e.name,description:e.description,format:e.format})}else FT(n)?r.push({type:"function",name:n.function.name,parameters:n.function.parameters,description:n.function.description,strict:t?.strict??null}):_E(n)&&r.push(SE(n));return r}},$$=class extends x${invocationParams(e,t){let r;void 0!==e?.strict?r=e.strict:void 0!==this.supportsStrictToolCalling&&(r=this.supportsStrictToolCalling);let n={};void 0!==e?.stream_options?n={stream_options:e.stream_options}:this.streamUsage&&(this.streaming||t?.streaming)&&(n={stream_options:{include_usage:!0}});const a={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:e?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:e?.functions,function_call:e?.function_call,tools:e?.tools?.length?e.tools.map(e=>this._convertChatOpenAIToolToCompletionsTool(e,{strict:r})):void 0,tool_choice:yE(e?.tool_choice),response_format:this._getResponseFormat(e?.response_format),seed:e?.seed,...n,parallel_tool_calls:e?.parallel_tool_calls,...this.audio||e?.audio?{audio:this.audio||e?.audio}:{},...this.modalities||e?.modalities?{modalities:this.modalities||e?.modalities}:{},...this.modelKwargs,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,verbosity:e?.verbosity??this.verbosity};void 0!==e?.prediction&&(a.prediction=e.prediction),void 0!==this.service_tier&&(a.service_tier=this.service_tier),void 0!==e?.service_tier&&(a.service_tier=e.service_tier);const i=this._getReasoningParams(e);return void 0!==i&&void 0!==i.effort&&(a.reasoning_effort=i.effort),aE(a.model)?a.max_completion_tokens=-1===this.maxTokens?void 0:this.maxTokens:a.max_tokens=-1===this.maxTokens?void 0:this.maxTokens,a}async _generate(e,t,r){const n={},a=this.invocationParams(t),i=I$(e,this.model);if(a.stream){const a=this._streamResponseChunks(e,t,r),i={};for await(const e of a){e.message.response_metadata={...e.generationInfo,...e.message.response_metadata};const t=e.generationInfo?.completion??0;void 0===i[t]?i[t]=e:i[t]=i[t].concat(e)}const s=Object.entries(i).sort(([e],[t])=>parseInt(e,10)-parseInt(t,10)).map(([e,t])=>t),{functions:o,function_call:c}=this.invocationParams(t),l=await this._getEstimatedTokenCountFromPrompt(e,o,c),u=await this._getNumTokensFromGenerations(s);return n.input_tokens=l,n.output_tokens=u,n.total_tokens=l+u,{generations:s,llmOutput:{estimatedTokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}{const e=await this.completionWithRetry({...a,stream:!1,messages:i},{signal:t?.signal,...t?.options}),{completion_tokens:r,prompt_tokens:s,total_tokens:o,prompt_tokens_details:c,completion_tokens_details:l}=e?.usage??{};r&&(n.output_tokens=(n.output_tokens??0)+r),s&&(n.input_tokens=(n.input_tokens??0)+s),o&&(n.total_tokens=(n.total_tokens??0)+o),null===c?.audio_tokens&&null===c?.cached_tokens||(n.input_token_details={...null!==c?.audio_tokens&&{audio:c?.audio_tokens},...null!==c?.cached_tokens&&{cache_read:c?.cached_tokens}}),null===l?.audio_tokens&&null===l?.reasoning_tokens||(n.output_token_details={...null!==l?.audio_tokens&&{audio:l?.audio_tokens},...null!==l?.reasoning_tokens&&{reasoning:l?.reasoning_tokens}});const u=[];for(const t of e?.choices??[]){const r={text:t.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(t.message??{role:"assistant"},e)};r.generationInfo={...t.finish_reason?{finish_reason:t.finish_reason}:{},...t.logprobs?{logprobs:t.logprobs}:{}},Vg(r.message)&&(r.message.usage_metadata=n),r.message=new Bg(Object.fromEntries(Object.entries(r.message).filter(([e])=>!e.startsWith("lc_")))),u.push(r)}return{generations:u,llmOutput:{tokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}}async*_streamResponseChunks(e,t,r){const n=I$(e,this.model),a={...this.invocationParams(t,{streaming:!0}),messages:n,stream:!0};let i;const s=await this.completionWithRetry(a,t);let o;for await(const e of s){const n=e?.choices?.[0];if(e.usage&&(o=e.usage),!n)continue;const{delta:a}=n;if(!a)continue;const s=this._convertCompletionsDeltaToBaseMessageChunk(a,e,i);i=a.role??i;const c={prompt:t.promptIndex??0,completion:n.index??0};if("string"!=typeof s.content){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}const l={...c};null!=n.finish_reason&&(l.finish_reason=n.finish_reason,l.system_fingerprint=e.system_fingerprint,l.model_name=e.model,l.service_tier=e.service_tier),this.logprobs&&(l.logprobs=n.logprobs);const u=new fw({message:s,text:s.content,generationInfo:l});yield u,await(r?.handleLLMNewToken(u.text??"",c,void 0,void 0,void 0,{chunk:u}))}if(o){const e={...null!==o.prompt_tokens_details?.audio_tokens&&{audio:o.prompt_tokens_details?.audio_tokens},...null!==o.prompt_tokens_details?.cached_tokens&&{cache_read:o.prompt_tokens_details?.cached_tokens}},t={...null!==o.completion_tokens_details?.audio_tokens&&{audio:o.completion_tokens_details?.audio_tokens},...null!==o.completion_tokens_details?.reasoning_tokens&&{reasoning:o.completion_tokens_details?.reasoning_tokens}},r=new fw({message:new Hg({content:"",response_metadata:{usage:{...o}},usage_metadata:{input_tokens:o.prompt_tokens,output_tokens:o.completion_tokens,total_tokens:o.total_tokens,...Object.keys(e).length>0&&{input_token_details:e},...Object.keys(t).length>0&&{output_token_details:t}}}),text:""});yield r}if(t.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(e,t){const r=this._getClientOptions(t),n=e.response_format&&"json_schema"===e.response_format.type;return this.caller.call(async()=>{try{return n&&!e.stream?await this.client.chat.completions.parse(e,r):await this.client.chat.completions.create(e,r)}catch(e){throw P$(e)}})}_convertCompletionsMessageToBaseMessage(e,t){const r=e.tool_calls;if("assistant"===e.role){const n=[],a=[];for(const e of r??[])try{n.push(_$(e,{returnId:!0}))}catch(t){a.push(S$(e,t.message))}const i={function_call:e.function_call,tool_calls:r};void 0!==this.__includeRawResponse&&(i.__raw_response=t);const s={model_provider:"openai",model_name:t.model,...t.system_fingerprint?{usage:{...t.usage},system_fingerprint:t.system_fingerprint}:{}};e.audio&&(i.audio=e.audio);const o=function(e,t){if(t&&"object"==typeof t&&"images"in t&&Array.isArray(t.images))return[{type:"text",text:e},...t.images.filter(e=>"string"==typeof e?.image_url?.url).map(e=>({type:"image",url:e.image_url.url}))];return e}(e.content||"",t.choices?.[0]?.message);return new Bg({content:o,tool_calls:n,invalid_tool_calls:a,additional_kwargs:i,response_metadata:s,id:t.id})}return new Kg(e.content||"",e.role??"unknown")}_convertCompletionsDeltaToBaseMessageChunk(e,t,r){const n=e.role??r,a=e.content??"";let i;i=e.function_call?{function_call:e.function_call}:e.tool_calls?{tool_calls:e.tool_calls}:{},this.__includeRawResponse&&(i.__raw_response=t),e.audio&&(i.audio={...e.audio,index:t.choices[0].index});const s={model_provider:"openai",usage:{...t.usage}};if("user"===n)return new ry({content:a,response_metadata:s});if("assistant"===n){const r=[];if(Array.isArray(e.tool_calls))for(const t of e.tool_calls)r.push({name:t.function?.name,args:t.function?.arguments,id:t.id,index:t.index,type:"tool_call_chunk"});return new Hg({content:a,tool_call_chunks:r,additional_kwargs:i,id:t.id,response_metadata:s})}return"system"===n?new sy({content:a,response_metadata:s}):"developer"===n?new sy({content:a,response_metadata:s,additional_kwargs:{__openai_role__:"developer"}}):"function"===n?new Qg({content:a,additional_kwargs:i,name:e.name,response_metadata:s}):"tool"===n?new Eg({content:a,additional_kwargs:i,tool_call_id:e.tool_call_id,response_metadata:s}):new Wg({content:a,role:n,response_metadata:s})}},z$=class e extends x${useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}constructor(e){super(e),this.fields=e,this.useResponsesApi=e?.useResponsesApi??!1,this.responses=e?.responses??new T$(e),this.completions=e?.completions??new $$(e)}_useResponsesApi(e){const t=e?.tools?.some(vE),r=null!=e?.previous_response_id||null!=e?.text||null!=e?.truncation||null!=e?.include||null!=e?.reasoning?.summary||null!=this.reasoning?.summary,n=e?.tools?.some(_E)||e?.tools?.some(bE);return this.useResponsesApi||t||r||n}getLsParams(e){const t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(t):this.completions.getLsParams(t)}invocationParams(e){const t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(t):this.completions.invocationParams(t)}async _generate(e,t,r){return this._useResponsesApi(t)?this.responses._generate(e,t):this.completions._generate(e,t,r)}async*_streamResponseChunks(e,t,r){this._useResponsesApi(t)?yield*this.responses._streamResponseChunks(e,this._combineCallOptions(t),r):yield*this.completions._streamResponseChunks(e,this._combineCallOptions(t),r)}withConfig(t){const r=new e(this.fields);return r.defaultOptions={...this.defaultOptions,...t},r}};const R$={openAIApiKey:"openai_api_key",openAIApiVersion:"openai_api_version",openAIBasePath:"openai_api_base",deploymentName:"deployment_name",azureOpenAIEndpoint:"azure_endpoint",azureOpenAIApiVersion:"openai_api_version",azureOpenAIBasePath:"openai_api_base",azureOpenAIApiDeploymentName:"deployment_name"},L$={azureOpenAIApiKey:"AZURE_OPENAI_API_KEY"},M$=["azureOpenAIApiKey","azureOpenAIApiVersion","azureOpenAIBasePath","azureOpenAIEndpoint","azureOpenAIApiInstanceName","azureOpenAIApiDeploymentName","deploymentName","openAIApiKey","openAIApiVersion"];function D$(e){if(this.azureOpenAIApiKey=e?.azureOpenAIApiKey??e?.openAIApiKey??e?.apiKey??$y("AZURE_OPENAI_API_KEY"),this.azureOpenAIApiInstanceName=e?.azureOpenAIApiInstanceName??$y("AZURE_OPENAI_API_INSTANCE_NAME"),this.azureOpenAIApiDeploymentName=e?.azureOpenAIApiDeploymentName??e?.deploymentName??$y("AZURE_OPENAI_API_DEPLOYMENT_NAME"),this.azureOpenAIApiVersion=e?.azureOpenAIApiVersion??e?.openAIApiVersion??$y("AZURE_OPENAI_API_VERSION"),this.azureOpenAIBasePath=e?.azureOpenAIBasePath??$y("AZURE_OPENAI_BASE_PATH"),this.azureOpenAIEndpoint=e?.azureOpenAIEndpoint??$y("AZURE_OPENAI_ENDPOINT"),this.azureADTokenProvider=e?.azureADTokenProvider,!this.azureOpenAIApiKey&&!this.apiKey&&!this.azureADTokenProvider)throw new Error("Azure OpenAI API key or Token Provider not found")}function j$(e){if(!this.client){const e={azureOpenAIApiDeploymentName:this.azureOpenAIApiDeploymentName,azureOpenAIApiInstanceName:this.azureOpenAIApiInstanceName,azureOpenAIApiKey:this.azureOpenAIApiKey,azureOpenAIBasePath:this.azureOpenAIBasePath,azureADTokenProvider:this.azureADTokenProvider,baseURL:this.clientConfig.baseURL,azureOpenAIEndpoint:this.azureOpenAIEndpoint},t=sE(e),r={...this.clientConfig,baseURL:t,timeout:this.timeout,maxRetries:0};this.azureADTokenProvider||(r.apiKey=e.azureOpenAIApiKey),r.baseURL||delete r.baseURL;let n=Iy();"node"!==n&&"deno"!==n||(n=`(${n}/${process.version}; ${process.platform}; ${process.arch})`);const a=cE(r.defaultHeaders);r.defaultHeaders={...r.defaultHeaders,"User-Agent":a["User-Agent"]?`langchainjs-azure-openai/2.0.0 (${n})${a["User-Agent"]}`:`langchainjs-azure-openai/2.0.0 (${n})`},this.client=new sT({apiVersion:this.azureOpenAIApiVersion,azureADTokenProvider:this.azureADTokenProvider,deployment:this.azureOpenAIApiDeploymentName,...r})}const t={...this.clientConfig,...e};return this.azureOpenAIApiKey&&(t.headers={"api-key":this.azureOpenAIApiKey,...t.headers},t.query={"api-version":this.azureOpenAIApiVersion,...t.query}),t}function F$(e){const t=e;function r(e){return"object"==typeof e&&null!=e}if(r(t)&&r(t.kwargs)){if(delete t.kwargs.azure_openai_base_path,delete t.kwargs.azure_openai_api_deployment_name,delete t.kwargs.azure_openai_api_key,delete t.kwargs.azure_openai_api_version,delete t.kwargs.azure_open_ai_base_path,!t.kwargs.azure_endpoint&&this.azureOpenAIEndpoint&&(t.kwargs.azure_endpoint=this.azureOpenAIEndpoint),!t.kwargs.azure_endpoint&&this.azureOpenAIBasePath){const e=this.azureOpenAIBasePath.split("/openai/deployments/");if(2===e.length&&e[0].startsWith("http")){const[r]=e;t.kwargs.azure_endpoint=r}}if(!t.kwargs.azure_endpoint&&this.azureOpenAIApiInstanceName&&(t.kwargs.azure_endpoint=`https://${this.azureOpenAIApiInstanceName}.openai.azure.com/`),!t.kwargs.deployment_name&&this.azureOpenAIApiDeploymentName&&(t.kwargs.deployment_name=this.azureOpenAIApiDeploymentName),!t.kwargs.deployment_name&&this.azureOpenAIBasePath){const e=this.azureOpenAIBasePath.split("/openai/deployments/");if(2===e.length){const[,r]=e;t.kwargs.deployment_name=r}}t.kwargs.azure_endpoint&&t.kwargs.deployment_name&&t.kwargs.openai_api_base&&delete t.kwargs.openai_api_base,t.kwargs.azure_openai_api_instance_name&&t.kwargs.azure_endpoint&&delete t.kwargs.azure_openai_api_instance_name}return t}var U$=class extends $${azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return"azure_openai"}get lc_aliases(){return{...super.lc_aliases,...R$}}get lc_secrets(){return{...super.lc_secrets,...L$}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...M$]}getLsParams(e){const t=super.getLsParams(e);return t.ls_provider="azure",t}constructor(e){super(e),D$.call(this,e)}_getClientOptions(e){return j$.call(this,e)}toJSON(){return F$.call(this,super.toJSON())}},q$=class extends T${azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return"azure_openai"}get lc_aliases(){return{...super.lc_aliases,...R$}}get lc_secrets(){return{...super.lc_secrets,...L$}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...M$]}getLsParams(e){const t=super.getLsParams(e);return t.ls_provider="azure",t}constructor(e){super(e),D$.call(this,e)}_getClientOptions(e){return j$.call(this,e)}toJSON(){return F$.call(this,super.toJSON())}},B$=class extends z${azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return"azure_openai"}get lc_aliases(){return{...super.lc_aliases,...R$}}get lc_secrets(){return{...super.lc_secrets,...L$}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...M$]}getLsParams(e){const t=super.getLsParams(e);return t.ls_provider="azure",t}constructor(e){super({...e,completions:new U$(e),responses:new q$(e)}),D$.call(this,e)}_getStructuredOutputMethod(e){const t={...e};return this.model.startsWith("gpt-4o")&&void 0===t?.method?"functionCalling":super._getStructuredOutputMethod(t)}toJSON(){return F$.call(this,super.toJSON())}};yf({},{BaseLLM:()=>V$,LLM:()=>G$});var V$=class e extends BT{lc_namespace=["langchain","llms",this._llmType()];async invoke(t,r){const n=e._convertInputToPromptValue(t);return(await this.generatePrompt([n],r,r?.callbacks)).generations[0][0].text}async*_streamResponseChunks(e,t,r){throw new Error("Not implemented.")}_separateRunnableConfigFromCallOptionsCompat(e){const[t,r]=super._separateRunnableConfigFromCallOptions(e);return r.signal=t.signal,[t,r]}async*_streamIterator(t,r){if(this._streamResponseChunks===e.prototype._streamResponseChunks)yield this.invoke(t,r);else{const n=e._convertInputToPromptValue(t),[a,i]=this._separateRunnableConfigFromCallOptionsCompat(r),s=await v_.configure(a.callbacks,this.callbacks,a.tags,this.tags,a.metadata,this.metadata,{verbose:this.verbose}),o={options:i,invocation_params:this?.invocationParams(i),batch_size:1},c=await(s?.handleLLMStart(this.toJSON(),[n.toString()],a.runId,void 0,o,void 0,void 0,a.runName));let l=new hw({text:""});try{for await(const e of this._streamResponseChunks(n.toString(),i,c?.[0]))l=l?l.concat(e):e,"string"==typeof e.text&&(yield e.text)}catch(e){throw await Promise.all((c??[]).map(t=>t?.handleLLMError(e))),e}await Promise.all((c??[]).map(e=>e?.handleLLMEnd({generations:[[l]]})))}}async generatePrompt(e,t,r){const n=e.map(e=>e.toString());return this.generate(n,t,r)}invocationParams(e){return{}}_flattenLLMResult(e){const t=[];for(let r=0;r<e.generations.length;r+=1){const n=e.generations[r];if(0===r)t.push({generations:[n],llmOutput:e.llmOutput});else{const r=e.llmOutput?{...e.llmOutput,tokenUsage:{}}:void 0;t.push({generations:[n],llmOutput:r})}}return t}async _generateUncached(t,r,n,a){let i;if(void 0!==a&&a.length===t.length)i=a;else{const e=await v_.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}),a={options:r,invocation_params:this?.invocationParams(r),batch_size:t.length};i=await(e?.handleLLMStart(this.toJSON(),t,n.runId,void 0,a,void 0,void 0,n?.runName))}let s;if(!!i?.[0].handlers.find(Wy)&&1===t.length&&this._streamResponseChunks!==e.prototype._streamResponseChunks)try{const e=await this._streamResponseChunks(t[0],r,i?.[0]);let n;for await(const t of e)n=void 0===n?t:z_(n,t);if(void 0===n)throw new Error("Received empty response from chat model call.");s={generations:[[n]],llmOutput:{}},await(i?.[0].handleLLMEnd(s))}catch(e){throw await(i?.[0].handleLLMError(e)),e}else{try{s=await this._generate(t,r,i?.[0])}catch(e){throw await Promise.all((i??[]).map(t=>t?.handleLLMError(e))),e}const e=this._flattenLLMResult(s);await Promise.all((i??[]).map((t,r)=>t?.handleLLMEnd(e[r])))}const o=i?.map(e=>e.runId)||void 0;return Object.defineProperty(s,mw,{value:o?{runIds:o}:void 0,configurable:!0}),s}async _generateCached({prompts:e,cache:t,llmStringKey:r,parsedOptions:n,handledOptions:a,runId:i}){const s=await v_.configure(a.callbacks,this.callbacks,a.tags,this.tags,a.metadata,this.metadata,{verbose:this.verbose}),o={options:n,invocation_params:this?.invocationParams(n),batch_size:e.length},c=await(s?.handleLLMStart(this.toJSON(),e,i,void 0,o,void 0,void 0,a?.runName)),l=[],u=await Promise.allSettled(e.map(async(e,n)=>{const a=await t.lookup(e,r);return null==a&&l.push(n),a})),d=u.map((e,t)=>({result:e,runManager:c?.[t]})).filter(({result:e})=>"fulfilled"===e.status&&null!=e.value||"rejected"===e.status),p=[];await Promise.all(d.map(async({result:e,runManager:t},r)=>{if("fulfilled"===e.status){const n=e.value;return p[r]=n.map(e=>(e.generationInfo={...e.generationInfo,tokenUsage:{}},e)),n.length&&await(t?.handleLLMNewToken(n[0].text)),t?.handleLLMEnd({generations:[n]},void 0,void 0,void 0,{cached:!0})}return await(t?.handleLLMError(e.reason,void 0,void 0,void 0,{cached:!0})),Promise.reject(e.reason)}));const m={generations:p,missingPromptIndices:l,startedRunManagers:c};return Object.defineProperty(m,mw,{value:c?{runIds:c?.map(e=>e.runId)}:void 0,configurable:!0}),m}async generate(e,t,r){if(!Array.isArray(e))throw new Error("Argument 'prompts' is expected to be a string[]");let n;n=Array.isArray(t)?{stop:t}:t;const[a,i]=this._separateRunnableConfigFromCallOptionsCompat(n);if(a.callbacks=a.callbacks??r,!this.cache)return this._generateUncached(e,i,a);const{cache:s}=this,o=this._getSerializedCacheKeyParametersForCall(i),{generations:c,missingPromptIndices:l,startedRunManagers:u}=await this._generateCached({prompts:e,cache:s,llmStringKey:o,parsedOptions:i,handledOptions:a,runId:a.runId});let d={};if(l.length>0){const t=await this._generateUncached(l.map(t=>e[t]),i,a,void 0!==u?l.map(e=>u?.[e]):void 0);await Promise.all(t.generations.map(async(t,r)=>{const n=l[r];return c[n]=t,s.update(e[n],o,t)})),d=t.llmOutput??{}}return{generations:c,llmOutput:d}}_identifyingParams(){return{}}_modelType(){return"base_llm"}},G$=class extends V${async _generate(e,t,r){return{generations:await Promise.all(e.map((e,n)=>this._call(e,{...t,promptIndex:n},r).then(e=>[{text:e}])))}}};yf({},{chunkArray:()=>H$});const H$=(e,t)=>e.reduce((e,r,n)=>{const a=Math.floor(n/t),i=e[a]||[];return e[a]=i.concat([r]),e},[]);yf({},{Embeddings:()=>K$});var K$=class{caller;constructor(e){this.caller=new ww(e??{})}},W$=class extends K${model="text-embedding-ada-002";modelName;batchSize=512;stripNewLines=!0;dimensions;timeout;organization;encodingFormat;client;clientConfig;constructor(e){const t={maxConcurrency:2,...e};super(t);const r=t?.apiKey??t?.openAIApiKey??$y("OPENAI_API_KEY");this.organization=t?.configuration?.organization??$y("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelName=this.model,this.batchSize=t?.batchSize??this.batchSize,this.stripNewLines=t?.stripNewLines??this.stripNewLines,this.timeout=t?.timeout,this.dimensions=t?.dimensions,this.encodingFormat=t?.encodingFormat,this.clientConfig={apiKey:r,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration}}async embedDocuments(e){const t=H$(this.stripNewLines?e.map(e=>e.replace(/\n/g," ")):e,this.batchSize),r=t.map(e=>{const t={model:this.model,input:e};return this.dimensions&&(t.dimensions=this.dimensions),this.encodingFormat&&(t.encoding_format=this.encodingFormat),this.embeddingWithRetry(t)}),n=await Promise.all(r),a=[];for(let e=0;e<n.length;e+=1){const r=t[e],{data:i}=n[e];for(let e=0;e<r.length;e+=1)a.push(i[e].embedding)}return a}async embedQuery(e){const t={model:this.model,input:this.stripNewLines?e.replace(/\n/g," "):e};this.dimensions&&(t.dimensions=this.dimensions),this.encodingFormat&&(t.encoding_format=this.encodingFormat);const{data:r}=await this.embeddingWithRetry(t);return r[0].embedding}async embeddingWithRetry(e){if(!this.client){const e=sE({baseURL:this.clientConfig.baseURL}),t={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};t.baseURL||delete t.baseURL,this.client=new iT(t)}const t={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(e,t)}catch(e){throw P$(e)}})}},Z$=class extends W${azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;constructor(e){super(e),this.batchSize=e?.batchSize??1,this.azureOpenAIApiKey=e?.azureOpenAIApiKey??e?.apiKey??$y("AZURE_OPENAI_API_KEY"),this.azureOpenAIApiVersion=e?.azureOpenAIApiVersion??e?.openAIApiVersion??$y("AZURE_OPENAI_API_VERSION"),this.azureOpenAIBasePath=e?.azureOpenAIBasePath??$y("AZURE_OPENAI_BASE_PATH"),this.azureOpenAIApiInstanceName=e?.azureOpenAIApiInstanceName??$y("AZURE_OPENAI_API_INSTANCE_NAME"),this.azureOpenAIApiDeploymentName=(e?.azureOpenAIApiEmbeddingsDeploymentName||e?.azureOpenAIApiDeploymentName)??($y("AZURE_OPENAI_API_EMBEDDINGS_DEPLOYMENT_NAME")||$y("AZURE_OPENAI_API_DEPLOYMENT_NAME")),this.azureADTokenProvider=e?.azureADTokenProvider}async embeddingWithRetry(e){if(!this.client){const e={azureOpenAIApiDeploymentName:this.azureOpenAIApiDeploymentName,azureOpenAIApiInstanceName:this.azureOpenAIApiInstanceName,azureOpenAIApiKey:this.azureOpenAIApiKey,azureOpenAIBasePath:this.azureOpenAIBasePath,azureADTokenProvider:this.azureADTokenProvider,baseURL:this.clientConfig.baseURL},t=sE(e),r={...this.clientConfig,baseURL:t,timeout:this.timeout,maxRetries:0};this.azureADTokenProvider||(r.apiKey=e.azureOpenAIApiKey),r.baseURL||delete r.baseURL;const n=cE(r.defaultHeaders);r.defaultHeaders={...r.defaultHeaders,"User-Agent":n["User-Agent"]?`${n["User-Agent"]}: langchainjs-azure-openai-v2`:"langchainjs-azure-openai-v2"},this.client=new sT({apiVersion:this.azureOpenAIApiVersion,azureADTokenProvider:this.azureADTokenProvider,deployment:this.azureOpenAIApiDeploymentName,...r})}const t={};return this.azureOpenAIApiKey&&(t.headers={"api-key":this.azureOpenAIApiKey,...t.headers},t.query={"api-version":this.azureOpenAIApiVersion,...t.query}),this.caller.call(async()=>{try{return await this.client.embeddings.create(e,t)}catch(e){throw P$(e)}})}};yf({},{BaseToolkit:()=>ez,DynamicStructuredTool:()=>X$,DynamicTool:()=>Q$,StructuredTool:()=>J$,Tool:()=>Y$,ToolInputParsingException:()=>py,isLangChainTool:()=>pE,isRunnableToolLike:()=>uE,isStructuredTool:()=>lE,isStructuredToolParams:()=>dE,tool:()=>tz});var J$=class extends qT{returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return["langchain","tools"]}responseFormat="content";defaultConfig;constructor(e){super(e??{}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat,this.defaultConfig=e?.defaultConfig??this.defaultConfig,this.metadata=e?.metadata??this.metadata}async invoke(e,t){let r,n=P_(x_(this.defaultConfig,t));return dy(e)?(r=e.args,n={...n,toolCall:e}):r=e,this.call(r,n)}async call(e,t,r){const n=dy(e)?e.args:e;let a;if(uS(this.schema))try{a=await fS(this.schema,n)}catch(t){let r="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(r=`${r}\nDetails: ${t.message}`),t instanceof Error&&"ZodError"===t.constructor.name&&(r=`${r}\n\n${function(e){const t=[],r=[...e.issues].sort((e,t)=>(e.path??[]).length-(t.path??[]).length);for(const e of r)t.push(`✖ ${e.message}`),e.path?.length&&t.push(` → at ${Vw(e.path)}`);return t.join("\n")}(t)}`),new py(r,JSON.stringify(e))}else{const t=gx(n,this.schema);if(!t.valid){let r="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(r=`${r}\nDetails: ${t.errors.map(e=>`${e.keywordLocation}: ${e.error}`).join("\n")}`),new py(r,JSON.stringify(e))}a=n}const i=d_(t),s=v_.configure(i.callbacks,this.callbacks,i.tags||r,this.tags,i.metadata,this.metadata,{verbose:this.verbose}),o=await(s?.handleToolStart(this.toJSON(),"string"==typeof e?e:JSON.stringify(e),i.runId,void 0,void 0,void 0,i.runName));let c,l,u,d;delete i.runId;try{c=await this._call(a,o,i)}catch(e){throw await(o?.handleToolError(e)),e}if("content_and_artifact"===this.responseFormat){if(!Array.isArray(c)||2!==c.length)throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.\nResult: ${JSON.stringify(c)}`);[l,u]=c}else l=c;dy(e)&&(d=e.id),!d&&function(e){return!!(e&&"object"==typeof e&&"toolCall"in e&&null!=e.toolCall&&"object"==typeof e.toolCall&&"id"in e.toolCall&&"string"==typeof e.toolCall.id)}(i)&&(d=i.toolCall.id);const p=function(e){const{content:t,artifact:r,toolCallId:n,metadata:a}=e;return n&&!kg(t)?"string"==typeof t||Array.isArray(t)&&t.every(e=>"object"==typeof e)?new xg({status:"success",content:t,artifact:r,tool_call_id:n,name:e.name,metadata:a}):new xg({status:"success",content:rz(t),artifact:r,tool_call_id:n,name:e.name,metadata:a}):t}({content:l,artifact:u,toolCallId:d,name:this.name,metadata:this.metadata});return await(o?.handleToolEnd(p)),p}},Y$=class extends J${schema=wk({input:bk().optional()}).transform(e=>e.input);constructor(e){super(e)}call(e,t){const r="string"==typeof e||null==e?{input:e}:e;return super.call(r,t)}},Q$=class extends Y${static lc_name(){return"DynamicTool"}name;description;func;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}async call(e,t){const r=d_(t);return void 0===r.runName&&(r.runName=this.name),super.call(e,r)}async _call(e,t,r){return this.func(e,t,r)}},X$=class extends J${static lc_name(){return"DynamicStructuredTool"}name;description;func;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}async call(e,t,r){const n=d_(t);return void 0===n.runName&&(n.runName=this.name),super.call(e,n,r)}_call(e,t,r){return this.func(e,t,r)}},ez=class{getTools(){return this.tools}};function tz(e,t){const r=_S(t.schema),n=bx(t.schema);if(!t.schema||r||n)return new Q$({...t,description:t.description??t.schema?.description??`${t.name} tool`,func:async(t,r,n)=>new Promise((a,i)=>{const s=C_(n,{callbacks:r?.getChild()});N_.runWithConfig(A_(s),async()=>{try{a(e(t,s))}catch(e){i(e)}})})});const a=t.schema,i=t.description??t.schema.description??`${t.name} tool`;return new X$({...t,description:i,schema:a,func:async(t,r,n)=>new Promise((a,i)=>{let s;const o=()=>{n?.signal&&s&&n.signal.removeEventListener("abort",s)};n?.signal&&(s=()=>{o(),i(O_(n.signal))},n.signal.addEventListener("abort",s));const c=C_(n,{callbacks:r?.getChild()});N_.runWithConfig(A_(c),async()=>{try{const r=await e(t,c);if(n?.signal?.aborted)return void o();o(),a(r)}catch(e){o(),i(e)}})})})}function rz(e){try{return JSON.stringify(e,null,2)??""}catch(t){return`${e}`}}class nz extends Ix{lc_namespace=["@equinor","fusion-framework-module-ai"];async invoke(e,t){return En(this.invoke$(e,t))}async*_streamIterator(e,t){yield*function(e){return{[Symbol.asyncIterator](){const t=[];let r=!1,n=null,a=null;const i=e.subscribe({next(e){n?(n({value:e,done:!1}),n=null):t.push({value:e,done:!1})},error(e){r=!0,a&&(a(e),a=null)},complete(){r=!0,n?(n({value:void 0,done:!0}),n=null):t.push({value:void 0,done:!0})}});return{next:async()=>t.length>0?t.shift():r?{value:void 0,done:!0}:new Promise((e,t)=>{n=e,a=t}),return:()=>(i.unsubscribe(),Promise.resolve({value:void 0,done:!0})),throw:e=>(i.unsubscribe(),Promise.reject(e))}}}}(this.invoke$(e,t))}asRunnable(){return this}}class az extends nz{#g;get llm(){return this.#g}bindTools(e,t){return this.#g.bindTools(e,t)}constructor(e){super(),this.#g=new B$(e)}async invoke(e,t){return this.#g.invoke(e,t)}invoke$(e){return Nn(this.#g.stream(e)).pipe(Zn(e=>Nn(e)))}_prepareMessages(e){return e.map(e=>new Kg(e))}}class iz extends Error{constructor(e,t){super(e,t),this.name="ServiceError"}}class sz extends nz{client;constructor(e){super(),this.client=new Z$(e)}embedQuery(e){return this.client.embedQuery(e)}embedDocuments(e){return this.client.embedDocuments(e)}invoke$(e){return Nn(this.client.embedDocuments(e)).pipe(Vn(e=>{throw new iz("Azure OpenAI embedding request failed",{cause:e})}))}}yf({},{BaseRetriever:()=>oz});var oz=class extends Ix{callbacks;tags;metadata;verbose;constructor(e){super(e),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,t){throw new Error("Not implemented!")}async invoke(e,t){const r=P_(d_(t)),n=await v_.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}),a=await(n?.handleRetrieverStart(this.toJSON(),e,r.runId,void 0,void 0,void 0,r.runName));try{const t=await this._getRelevantDocuments(e,a);return await(a?.handleRetrieverEnd(t)),t}catch(e){throw await(a?.handleRetrieverError(e)),e}}};yf({},{SaveableVectorStore:()=>uz,VectorStore:()=>lz,VectorStoreRetriever:()=>cz});var cz=class extends oz{static lc_name(){return"VectorStoreRetriever"}get lc_namespace(){return["langchain_core","vectorstores"]}vectorStore;k=4;searchType="similarity";searchKwargs;filter;_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(e){super(e),this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,"mmr"===e.searchType&&(this.searchKwargs=e.searchKwargs)}async _getRelevantDocuments(e,t){if("mmr"===this.searchType){if("function"!=typeof this.vectorStore.maxMarginalRelevanceSearch)throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(e,{k:this.k,filter:this.filter,...this.searchKwargs},t?.getChild("vectorstore"))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t?.getChild("vectorstore"))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}},lz=class extends Mf{lc_namespace=["langchain","vectorstores",this._vectorstoreType()];embeddings;constructor(e,t){super(t),this.embeddings=e}async delete(e){throw new Error("Not implemented.")}async similaritySearch(e,t=4,r=void 0,n=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r)).map(e=>e[0])}async similaritySearchWithScore(e,t=4,r=void 0,n=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r)}static fromTexts(e,t,r,n){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(e,t,r){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(e,t,r,n,a,i){if("number"==typeof e)return new cz({vectorStore:this,k:e,filter:t,tags:[...n??[],this._vectorstoreType()],metadata:a,verbose:i,callbacks:r});{const t={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return new cz("mmr"===e?.searchType?{...t,searchKwargs:e.searchKwargs}:{...t})}}},uz=class extends lz{static load(e,t){throw new Error("Not implemented")}},dz=class{pageContent;metadata;id;constructor(e){this.pageContent=void 0!==e.pageContent?e.pageContent.toString():"",this.metadata=e.metadata??{},this.id=e.id}},pz=class extends Ix{lc_namespace=["langchain_core","documents","transformers"];invoke(e,t){return this.transformDocuments(e)}},mz=class extends pz{async transformDocuments(e){const t=[];for(const r of e){const e=await this._transformDocument(r);t.push(e)}return t}};function hz(e,t){let r=0,n=0,a=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i],n+=e[i]*e[i],a+=t[i]*t[i];return r/(Math.sqrt(n)*Math.sqrt(a))}function fz(e,t){let r=0;for(let n=0;n<e.length;n++)r+=e[n]*t[n];return r}function gz(e,t){return Math.sqrt(function(e,t){let r=0;for(let n=0;n<e.length;n++)r+=(e[n]-t[n])*(e[n]-t[n]);return r}(e,t))}yf({},{BaseDocumentTransformer:()=>pz,Document:()=>dz,MappingDocumentTransformer:()=>mz});function yz(e,t,r){if(0===e.length||0===e[0].length||0===t.length||0===t[0].length)return[[]];if(e[0].length!==t[0].length)throw new Error(`Number of columns in X and Y must be the same. X has shape ${[e.length,e[0].length]} and Y has shape ${[t.length,t[0].length]}.`);return e.map(e=>t.map(t=>r(e,t)).map(e=>Number.isNaN(e)?0:e))}function vz(e,t=!1){const r=e.reduce((e,t)=>Math.max(e,Nz(t).maxValue),0);return e.map(e=>e.map(e=>t?1-e/r:e/r))}function bz(e,t){return yz(e,t,hz)}function _z(e,t){return yz(e,t,fz)}function wz(e,t){return yz(e,t,gz)}function Sz(e,t,r=.5,n=4){if(Math.min(n,t.length)<=0)return[];const a=bz(Array.isArray(e[0])?e:[e],t)[0],i=Nz(a).maxIndex,s=[t[i]],o=[i];for(;o.length<Math.min(n,t.length);){let e=-1/0,n=-1;const i=bz(t,s);a.forEach((t,a)=>{if(o.includes(a))return;const s=Math.max(...i[a]),c=r*t-(1-r)*s;c>e&&(e=c,n=a)}),s.push(t[n]),o.push(n)}return o}function Nz(e){if(0===e.length)return{maxIndex:-1,maxValue:NaN};let t=e[0],r=0;for(let n=1;n<e.length;n+=1)e[n]>t&&(r=n,t=e[n]);return{maxIndex:r,maxValue:t}}yf({},{cosineSimilarity:()=>bz,euclideanDistance:()=>wz,innerProduct:()=>_z,matrixFunc:()=>yz,maximalMarginalRelevance:()=>Sz,normalize:()=>vz});const kz="similarity",xz="similarity_hybrid",Ez="semantic_hybrid",Pz="langchainjs-azure-aisearch",Cz="content",Az="content_vector",Iz="metadata";class Oz extends lz{get lc_secrets(){return{endpoint:"AZURE_AISEARCH_ENDPOINT",key:"AZURE_AISEARCH_KEY"}}_vectorstoreType(){return"azure_aisearch"}constructor(e,t){super(e,t),Object.defineProperty(this,"initPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"indexName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const r=t.endpoint??$y("AZURE_AISEARCH_ENDPOINT"),n=t.key??$y("AZURE_AISEARCH_KEY");let{credentials:a}=t;if(!(t.client||r&&(n||a)))throw new Error("Azure AI Search client or endpoint and key/credentials must be set.");if(this.indexName=t.indexName??"vectorsearch",t.client)this.client=t.client;else{a??=new Ds(n),this.client=new Bd(r,this.indexName,a,{userAgentOptions:{userAgentPrefix:Pz}});const e=new pf(r,a,{userAgentOptions:{userAgentPrefix:Pz}});this.initPromise=this.ensureIndexExists(e).catch(e=>{console.error("Error during Azure AI Search index initialization:",e)})}this.options=t.search??{},this.embeddings=e}async delete(e){if(!e.ids&&!e.filter)throw new Error('Azure AI Search delete requires either "ids" or "filter" to be set in the params object');await this.initPromise,e.ids&&await this.deleteById(e.ids),e.filter&&await this.deleteMany(e.filter)}async deleteMany(e){if(!e.filterExpression)throw new Error('Azure AI Search deleteMany requires "filterExpression" to be set in the filter object');const{results:t}=await this.client.search("*",{filter:e.filterExpression}),r=[];for await(const e of t)r.push(e.document);const n=[],a=new mf(this.client,e=>e.id);return a.on("batchSucceeded",e=>{n.push(...e.results)}),a.on("batchFailed",e=>{throw new Error(`Azure AI Search deleteDocuments batch failed: ${e}`)}),await a.deleteDocuments(r),await a.flush(),await a.dispose(),n}async deleteById(e){const t=(Array.isArray(e)?e:[e]).map(e=>({id:e})),r=[],n=new mf(this.client,e=>e.id);return n.on("batchSucceeded",e=>{r.push(...e.results)}),n.on("batchFailed",e=>{throw new Error(`Azure AI Search deleteDocuments batch failed: ${e}`)}),await n.deleteDocuments(t),await n.flush(),await n.dispose(),r}async addDocuments(e,t){const r=e.map(({pageContent:e})=>e),n=await this.embeddings.embedDocuments(r);return await this.addVectors(n,e,t)}async addVectors(e,t,r){const n=r?.ids??t.map(()=>By()),a=t.map((t,r)=>({id:n[r],content:t.pageContent,content_vector:e[r],metadata:{source:t.metadata?.source,attributes:t.metadata?.attributes??[]}}));await this.initPromise;const i=new mf(this.client,e=>e.id);return i.on("batchFailed",e=>{throw new Error(`Azure AI Search uploadDocuments batch failed: ${e}`)}),await i.uploadDocuments(a),await i.flush(),await i.dispose(),n}async similaritySearch(e,t=4,r=void 0){return(await this.similaritySearchWithScore(e,t,r)).map(e=>e[0])}async similaritySearchWithScore(e,t=4,r=void 0){const n=this.options.type??xz;if(n===kz)return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r);if(n===xz)return this.hybridSearchVectorWithScore(e,await this.embeddings.embedQuery(e),t,r);if(n===Ez)return this.semanticHybridSearchVectorWithScore(e,await this.embeddings.embedQuery(e),t,r);throw new Error(`Unrecognized search type '${n}'`)}async hybridSearchVectorWithScore(e,t,r=4,n=void 0){const a=t??await this.embeddings.embedQuery(e);await this.initPromise;const{results:i}=await this.client.search(e,{vectorSearchOptions:{queries:[{kind:"vector",vector:a,kNearestNeighborsCount:r,fields:[Az]}],filterMode:n?.vectorFilterMode},filter:n?.filterExpression,top:r}),s=[];for await(const e of i){const t=new dz({pageContent:e.document[Cz],metadata:{...e.document[Iz]}});n?.includeEmbeddings&&(t.metadata.embedding=e.document[Az]),s.push([t,e.score])}return s}async semanticHybridSearchVectorWithScore(e,t,r=4,n=void 0){const a=t??await this.embeddings.embedQuery(e);await this.initPromise;const{results:i}=await this.client.search(e,{vectorSearchOptions:{queries:[{kind:"vector",vector:a,kNearestNeighborsCount:r,fields:[Az]}],filterMode:n?.vectorFilterMode},filter:n?.filterExpression,top:r,queryType:"semantic",semanticSearchOptions:{configurationName:this.options.semanticConfigurationName??"semantic-search-config"}}),s=[];for await(const e of i){const t=new dz({pageContent:e.document[Cz],metadata:{...e.document[Iz]}});n?.includeEmbeddings&&(t.metadata.embedding=e.document[Az]),s.push([t,e.score])}return s}async similaritySearchVectorWithScore(e,t,r){await this.initPromise;const{results:n}=await this.client.search("*",{vectorSearchOptions:{queries:[{kind:"vector",vector:e,kNearestNeighborsCount:t,fields:[Az]}],filterMode:r?.vectorFilterMode},filter:r?.filterExpression}),a=[];for await(const e of n){const t=new dz({pageContent:e.document[Cz],metadata:{...e.document[Iz]}});r?.includeEmbeddings&&(t.metadata.embedding=e.document[Az]),a.push([t,e.score])}return a}async maxMarginalRelevanceSearch(e,t){const{k:r,fetchK:n=20,lambda:a=.5}=t,i=t.filter?.includeEmbeddings||!1,s=await this.embeddings.embedQuery(e),o=await this.similaritySearchVectorWithScore(s,n,{...t.filter,includeEmbeddings:!0});return Sz(s,o.map(e=>e[0].metadata.embedding),a,r).map(e=>{const t=o[e][0];return i||delete t.metadata.embedding,t})}async ensureIndexExists(e){try{await e.getIndex(this.indexName)}catch(t){const r=await this.createSearchIndexDefinition(this.indexName);await e.createIndex(r)}}async createSearchIndexDefinition(e){const t=(await this.embeddings.embedQuery("test")).length;return{name:e,vectorSearch:{algorithms:[{name:"vector-search-algorithm",kind:"hnsw",parameters:{m:4,efSearch:500,metric:"cosine",efConstruction:400}}],profiles:[{name:"vector-search-profile",algorithmConfigurationName:"vector-search-algorithm"}]},semanticSearch:{defaultConfigurationName:"semantic-search-config",configurations:[{name:"semantic-search-config",prioritizedFields:{contentFields:[{name:Cz}],keywordsFields:[{name:Cz}]}}]},fields:[{name:"id",filterable:!0,key:!0,type:"Edm.String"},{name:Cz,searchable:!0,filterable:!0,type:"Edm.String"},{name:Az,searchable:!0,type:"Collection(Edm.Single)",vectorSearchDimensions:t,vectorSearchProfileName:"vector-search-profile"},{name:Iz,type:"Edm.ComplexType",fields:[{name:"source",type:"Edm.String",filterable:!0},{name:"attributes",type:"Collection(Edm.ComplexType)",fields:[{name:"key",type:"Edm.String",filterable:!0},{name:"value",type:"Edm.String",filterable:!0}]}]}]}}static async fromTexts(e,t,r,n){const a=[];for(let r=0;r<e.length;r+=1){const n=Array.isArray(t)?t[r]:t,i=new dz({pageContent:e[r],metadata:n});a.push(i)}return Oz.fromDocuments(a,r,n)}static async fromDocuments(e,t,r,n){const a=new this(t,r);return await a.addDocuments(e,n),a}}class Tz extends nz{vectorStore;constructor(e,t){super();try{this.vectorStore=new Oz(e,t)}catch(e){throw new Ms(`Failed to initialize Azure Vector Store: ${e instanceof Error?e.message:String(e)}`,"INITIALIZATION_ERROR")}}addDocuments(e){const t={ids:e.map(e=>e.id??"")},r=e.map(e=>{const t=e.metadata.attributes?(r=e.metadata.attributes,Object.entries(r).map(([e,t])=>({key:e,value:"string"==typeof t?t:JSON.stringify(t)}))):void 0;var r;return{...e,metadata:{...e.metadata,attributes:t}}});return this.vectorStore.addDocuments(r,t)}deleteDocuments(e){return this.vectorStore.delete(e)}async invoke(e){try{return await this.vectorStore.similaritySearch(e,10)}catch(e){throw new Ms(`Azure Vector Store search failed: ${e instanceof Error?e.message:String(e)}`,"SEARCH_ERROR")}}invoke$(e){return Nn(this.invoke(e)).pipe(Zn(e=>Nn(e)),On(e=>[e]))}asRetriever(e){return this.vectorStore.asRetriever(e)}}class $z{_operators;get operators(){return this._operators}constructor(e){this._operators=e&&"operators"in e?{...e.operators}:e??{}}add(e,t){if(Object.keys(this._operators).includes(e))throw Error(`Operator [${e}] already defined`);return this.set(e,t)}set(e,t){return this._operators[e]=t,this}remove(e){return delete this._operators[e],this}get(e){return this._operators[e]}process(e){return Object.values(this._operators).length?Nn(Object.values(this._operators)).pipe((t=(e,t)=>Promise.resolve(t(e)).then(t=>t??e),r=e,n=1,jr(function(e,a){var i=r;return zn(e,a,function(e,r){return t(i,e,r)},n,function(e){i=e},!1,void 0,function(){return i=null})})),ra()):kn(e);var t,r,n}}class zz extends $z{setHeader(e,t){const r=((e,t)=>r=>{const n=new Headers(r.headers);return n.append(e,t),{...r,headers:n}})(e,t);return this.set("header-"+e,r)}}class Rz extends $z{}const Lz=oe.object({attributionReporting:oe.object({eventSourceEligible:oe.boolean().optional(),triggerEligible:oe.boolean().optional()}).optional(),body:oe.union([oe.string(),oe.instanceof(Blob),oe.instanceof(ArrayBuffer),oe.instanceof(FormData),oe.instanceof(URLSearchParams),oe.instanceof(ReadableStream)]).optional(),browsingTopics:oe.boolean().optional(),cache:oe.enum(["default","no-store","reload","no-cache","force-cache","only-if-cached"]).optional(),credentials:oe.enum(["omit","same-origin","include"]).optional(),headers:oe.record(oe.string(),oe.string()).optional().or(oe.instanceof(Headers)),integrity:oe.string().optional(),keepalive:oe.boolean().optional(),method:oe.enum(["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD","CONNECT","TRACE"],{message:"Invalid request method. Expected one of: GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD, CONNECT, TRACE. See RFC 2615 Section 9 for more information: https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html"}).optional().optional(),mode:oe.enum(["same-origin","cors","no-cors","navigate","websocket"]).optional(),priority:oe.enum(["low","high","auto"]).optional(),redirect:oe.enum(["follow","error","manual"]).optional(),referrer:oe.string().optional(),referrerPolicy:oe.enum(["no-referrer","no-referrer-when-downgrade","origin","origin-when-cross-origin","same-origin","strict-origin","strict-origin-when-cross-origin","unsafe-url"]).optional(),signal:oe.instanceof(AbortSignal).optional()}).extend({uri:oe.string(),path:oe.string().optional()}),Mz=e=>e=>{const{error:t,success:r,data:n}=oe.string().optional().refine(e=>void 0===e||e===e?.toUpperCase(),{message:["Provided HTTP method must be in uppercase.","See RFC 7231 Section 4.1 for more information","https://www.rfc-editor.org/rfc/rfc7231#section-4.1"].join(" ")}).safeParse(e.method);if(e.method=r?n:e.method?.toUpperCase(),t)for(const e of t.issues)console.warn(e.message);return e},Dz=e=>e=>{const{strict:t,parse:r}={},n=t?Lz:Lz.passthrough();try{const t=n.parse(e);return r?t:void 0}catch(e){if(r)throw e;console.error("Invalid request options",e.message)}};class jz{_clients={};get clients(){return{...this._clients}}defaultHttpClientCtor;defaultHttpRequestHandler=new zz({"capitalize-method":Mz(),"request-validation":Dz()});constructor(e){this.defaultHttpClientCtor=e}hasClient(e){return Object.keys(this._clients).includes(e)}configureClient(e,t){const r="string"==typeof t?{baseUri:t}:t,n="function"==typeof r?{onCreate:r}:r;return this._clients[e]={...this._clients[e],...n},this}}class Fz extends Error{}class Uz extends Is{config;get defaultHttpRequestHandler(){return this.config.defaultHttpRequestHandler}constructor(e){super({version:"7.0.6-cli-search-index.0",config:e}),this.config=e}hasClient(e){return Object.keys(this.config.clients).includes(e)}createClient(e){const t=this._resolveConfig(e),{baseUri:r,defaultScopes:n=[],onCreate:a,ctor:i=this.config.defaultHttpClientCtor,requestHandler:s=this.defaultHttpRequestHandler}=t,o=new i(r||"",{requestHandler:s});return Object.assign(o,{defaultScopes:n}),a?.(o),o}createCustomClient(e){return this.createClient(e)}_resolveConfig(e){if("string"==typeof e){const r=this.config.clients[e];if(!r&&(t=e,new RegExp("^(https?:\\/\\/)?((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*(\\?[;&a-z\\d%_.~+=-]*)?(\\#[-a-z\\d_]*)?$","i").test(t)))return{baseUri:e};if(!r)throw new Fz(`No registered http client for key [${e}]`);return r}var t;return e}}function qz(e,t){void 0===t&&(t={});var r=t.selector,n=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var a=0;for(n=Object.getOwnPropertySymbols(e);a<n.length;a++)t.indexOf(n[a])<0&&Object.prototype.propertyIsEnumerable.call(e,n[a])&&(r[n[a]]=e[n[a]])}return r}(t,["selector"]);return new Mr(function(t){var a=new AbortController,i=a.signal,s=!0,o=n.signal;if(o)if(o.aborted)a.abort();else{var c=function(){i.aborted||a.abort()};o.addEventListener("abort",c),t.add(function(){return o.removeEventListener("abort",c)})}var l=cr(cr({},n),{signal:i}),u=function(e){s=!1,t.error(e)};return fetch(e,l).then(function(e){r?gn(r(e)).subscribe(Fr(t,void 0,function(){s=!1,t.complete()},u)):(s=!1,t.next(e),t.complete())}).catch(u),function(){s&&a.abort()}})}class Bz extends Error{response;static Name="HttpResponseError";constructor(e,t,r){super(e,r),this.response=t}}class Vz extends Bz{static Name="HttpJsonResponseError";data;constructor(e,t,r){super(e,t,r),this.name=Vz.Name,this.data=r?.data}}class Gz extends Bz{static Name="ServerSentEventResponseError";constructor(e,t,r){super(e,t,r),this.name=Gz.Name}}const Hz=async e=>{if(204===e.status)return Promise.resolve();try{const t=await e.json();if(!e.ok)throw new Vz("network response was not OK",e,{data:t});return t}catch(t){if(t instanceof Vz)throw t;throw new Vz("failed to parse response",e,{cause:t})}},Kz=async e=>{if(!e.ok)throw new Error("network response was not OK");if(204===e.status)throw new Error("no content");const t=e.headers.get("content-disposition")?.split(";").find(e=>e.includes("filename="))?.replace("filename=","")?.trim();try{return{filename:t,blob:await e.blob()}}catch(e){throw Error("failed to parse response")}},Wz=e=>{try{return JSON.parse(e)}catch{return e}};function*Zz(e,t){const r=e.split("\n\n"),n=t?.dataParser||Wz;for(const e of r){if(!e.trim())continue;const t=e.split("\n").reduce((e,t)=>{if(!t)return e;const r=t.indexOf(":");if(-1===r)return e;const a=t.slice(0,r).trim(),i=t.slice(r+1).trim();return"data"===a?e.data=n(i):e[a]=i,e},{});Object.keys(t).length&&(yield t)}}const Jz=e=>t=>{if(!t.ok)throw new Gz(`HTTP error! Status: ${t.status}`,t);if(!t.body)throw new Gz("Response body is not readable",t);if(!t.headers.get("Content-Type")?.includes("text/event-stream"))throw new Gz("Response is not a text/event-stream",t);const r=t.body.getReader();return Nn(async function*(e,t){const r=!!t?.skipHeartbeats,n=t?.eventFilter?Array.isArray(t.eventFilter)?t.eventFilter:[t.eventFilter]:null,a=new TextDecoder;for(;;){const{done:i,value:s}=await e.read();if(i)break;const o=Zz(a.decode(s,{stream:!0}),{dataParser:t?.dataParser});for(const e of o)if(e.retry)await new Promise(t=>setTimeout(t,Number.parseInt(e.retry??"300",10)));else{if(r){if(!e.event&&!e.data&&!e.id)continue;if(e.event&&["heartbeat","ping"].includes(e.event))continue}(!n||e.event&&n.includes(e.event))&&(yield e)}}}(r,{dataParser:e?.dataParser,skipHeartbeats:e?.skipHeartbeats,eventFilter:e?.eventFilter})).pipe(oa(e?.abortSignal?jn(e.abortSignal,"abort"):rn),ta(async()=>{await r.cancel().catch(()=>{}),r.releaseLock()}))};class Yz{uri;requestHandler;responseHandler;_request$=new Br;_response$=new Br;_abort$=new Br;get request$(){return this._request$.asObservable()}get response$(){return this._response$.asObservable()}constructor(e,t){this.uri=e,this.requestHandler=new zz(t?.requestHandler),this.responseHandler=new Rz(t?.responseHandler),this._init()}_init(){}fetch$(e,t){return this._fetch$(e,t)}fetch(e,t){return Pn(this.fetch$(e,t))}fetchAsync(e,t){return this.fetch(e,t)}json$(e,t){const r="object"==typeof t?.body?JSON.stringify(t?.body):t?.body,n=t?.selector??Hz,a=new Headers(t?.headers);return a.append("Accept","application/json"),a.append("Content-Type","application/json"),this.fetch$(e,{...t,body:r,selector:n,headers:a})}json(e,t){return Pn(this.json$(e,t))}blob$(e,t){const r=t?.selector??Kz,n={...t,selector:r};return this.fetch$(e,n)}blob(e,t){return Pn(this.blob$(e,t))}sse$(e,t,r){const n=new Headers(t?.headers);n.append("Accept","text/event-stream"),n.append("Content-Type","text/event-stream"),n.append("Cache-Control","no-cache"),n.append("Connection","keep-alive");const a=Jz({...r,abortSignal:t?.signal});return this._fetch$(e,{selector:a,...t,headers:n})}jsonAsync(e,t){return this.json(e,t)}execute(e,t,r){return this[e](t,r)}abort(){this._abort$.next()}_fetch$(e,t){const{selector:r,...n}=t||{},a=kn({...n,uri:this._resolveUrl(e)}).pipe(sa(e=>this._prepareRequest(e)),ca(e=>this._request$.next(e)),sa(({uri:e,path:t,...r})=>qz(e,r)),sa(e=>this._prepareResponse(e)),ca(e=>this._response$.next(e)),sa(e=>{if(r)try{return r(e)}catch(t){throw new Bz("failed to execute response selector",e,{cause:t})}return kn(e)}),oa(this._abort$));return a}_prepareRequest(e){return this.requestHandler.process(e)}_prepareResponse(e){return this.responseHandler.process(e)}_resolveUrl(e){const{origin:t,pathname:r}=new URL(this.uri,this.uri.startsWith("http")?void 0:window.location.origin),n=[r,e].join("/").replace(/\/{2,}/g,"/");return new URL(n,t).href}}class Qz extends Yz{defaultScopes=[];fetch$(e,t){const r=Object.assign(t||{},{scopes:this.defaultScopes.concat(t?.scopes||[])});return super._fetch$(e,r)}}const Xz={name:"http",configure:()=>new jz(Qz),initialize:async({config:e,hasModule:t,requireInstance:r})=>{const n=new Uz(e);if(t("auth")){const e=await r("auth");n.defaultHttpRequestHandler.set("MSAL",async t=>{const{scopes:r=[]}=t;if(r.length){const n=await e.acquireAccessToken({request:{scopes:r}});if(n){const e=new Headers(t.headers);return e.set("Authorization",`Bearer ${n}`),{...t,headers:e}}}})}return n}},eR=(...e)=>t=>t.pipe(Zn(...e)),tR=(...e)=>t=>t.pipe(Rn(...e)),rR=(...e)=>t=>t.pipe(sa(...e)),nR=e=>e.pipe(On(e=>e.value));var aR=/^(?:[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 iR(e){if(!function(e){return"string"==typeof e&&aR.test(e)}(e))throw TypeError("Invalid UUID");let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,255&t,(t=parseInt(e.slice(9,13),16))>>>8,255&t,(t=parseInt(e.slice(14,18),16))>>>8,255&t,(t=parseInt(e.slice(19,23),16))>>>8,255&t,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,255&t)}const sR=[];for(let e=0;e<256;++e)sR.push((e+256).toString(16).slice(1));function oR(e,t=0){return(sR[e[t+0]]+sR[e[t+1]]+sR[e[t+2]]+sR[e[t+3]]+"-"+sR[e[t+4]]+sR[e[t+5]]+"-"+sR[e[t+6]]+sR[e[t+7]]+"-"+sR[e[t+8]]+sR[e[t+9]]+"-"+sR[e[t+10]]+sR[e[t+11]]+sR[e[t+12]]+sR[e[t+13]]+sR[e[t+14]]+sR[e[t+15]]).toLowerCase()}let cR;const lR=new Uint8Array(16);function uR(e,t,r,n,a,i){const s="string"==typeof r?function(e){e=unescape(encodeURIComponent(e));const t=new Uint8Array(e.length);for(let r=0;r<e.length;++r)t[r]=e.charCodeAt(r);return t}(r):r,o="string"==typeof n?iR(n):n;if("string"==typeof n&&(n=iR(n)),16!==n?.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+s.length);if(c.set(o),c.set(s,o.length),c=t(c),c[6]=15&c[6]|e,c[8]=63&c[8]|128,a){i=i||0;for(let e=0;e<16;++e)a[i+e]=c[e];return a}return oR(c)}var dR={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function pR(e,t,r){const n=(e=e||{}).random??e.rng?.()??function(){if(!cR){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");cR=crypto.getRandomValues.bind(crypto)}return cR(lR)}();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,oR(n)}function mR(e,t,r){return dR.randomUUID&&!e?dR.randomUUID():pR(e)}function hR(e,t,r,n){switch(e){case 0:return t&r^~t&n;case 1:case 3:return t^r^n;case 2:return t&r^t&n^r&n}}function fR(e,t){return e<<t|e>>>32-t}function gR(e){const t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520],n=new Uint8Array(e.length+1);n.set(e),n[e.length]=128;const a=(e=n).length/4+2,i=Math.ceil(a/16),s=new Array(i);for(let t=0;t<i;++t){const r=new Uint32Array(16);for(let n=0;n<16;++n)r[n]=e[64*t+4*n]<<24|e[64*t+4*n+1]<<16|e[64*t+4*n+2]<<8|e[64*t+4*n+3];s[t]=r}s[i-1][14]=8*(e.length-1)/Math.pow(2,32),s[i-1][14]=Math.floor(s[i-1][14]),s[i-1][15]=8*(e.length-1)&4294967295;for(let e=0;e<i;++e){const n=new Uint32Array(80);for(let t=0;t<16;++t)n[t]=s[e][t];for(let e=16;e<80;++e)n[e]=fR(n[e-3]^n[e-8]^n[e-14]^n[e-16],1);let a=r[0],i=r[1],o=r[2],c=r[3],l=r[4];for(let e=0;e<80;++e){const r=Math.floor(e/20),s=fR(a,5)+hR(r,i,o,c)+l+t[r]+n[e]>>>0;l=c,c=o,o=fR(i,30)>>>0,i=a,a=s}r[0]=r[0]+a>>>0,r[1]=r[1]+i>>>0,r[2]=r[2]+o>>>0,r[3]=r[3]+c>>>0,r[4]=r[4]+l>>>0}return Uint8Array.of(r[0]>>24,r[0]>>16,r[0]>>8,r[0],r[1]>>24,r[1]>>16,r[1]>>8,r[1],r[2]>>24,r[2]>>16,r[2]>>8,r[2],r[3]>>24,r[3]>>16,r[3]>>8,r[3],r[4]>>24,r[4]>>16,r[4]>>8,r[4])}function yR(e,t,r,n){return uR(80,gR,e,t,r,n)}yR.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",yR.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";class vR extends Error{type;request;constructor(e,t){super(t.message,{cause:t.cause}),this.type=e,this.name="QueryClientError",this.request=t.request}}var bR=Symbol.for("immer-nothing"),_R=Symbol.for("immer-draftable"),wR=Symbol.for("immer-state"),SR="production"!==process.env.NODE_ENV?[function(e){return`The plugin for '${e}' has not been loaded into Immer. To enable the plugin, import and call \`enable${e}()\` when initializing your application.`},function(e){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${e}'`},"This object has been frozen and should not be mutated",function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(e){return`'current' expects a draft, got: ${e}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(e){return`'original' expects a draft, got: ${e}`}]:[];function NR(e,...t){if("production"!==process.env.NODE_ENV){const r=SR[e],n="function"==typeof r?r.apply(null,t):r;throw new Error(`[Immer] ${n}`)}throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var kR=Object.getPrototypeOf;function xR(e){return!!e&&!!e[wR]}function ER(e){return!!e&&(AR(e)||Array.isArray(e)||!!e[_R]||!!e.constructor?.[_R]||zR(e)||RR(e))}var PR=Object.prototype.constructor.toString(),CR=new WeakMap;function AR(e){if(!e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);if(null===t||t===Object.prototype)return!0;const r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;if(r===Object)return!0;if("function"!=typeof r)return!1;let n=CR.get(r);return void 0===n&&(n=Function.toString.call(r),CR.set(r,n)),n===PR}function IR(e,t,r=!0){if(0===OR(e)){(r?Reflect.ownKeys(e):Object.keys(e)).forEach(r=>{t(r,e[r],e)})}else e.forEach((r,n)=>t(n,r,e))}function OR(e){const t=e[wR];return t?t.type_:Array.isArray(e)?1:zR(e)?2:RR(e)?3:0}function TR(e,t){return 2===OR(e)?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function $R(e,t,r){const n=OR(e);2===n?e.set(t,r):3===n?e.add(r):e[t]=r}function zR(e){return e instanceof Map}function RR(e){return e instanceof Set}function LR(e){return e.copy_||e.base_}function MR(e,t){if(zR(e))return new Map(e);if(RR(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const r=AR(e);if(!0===t||"class_only"===t&&!r){const t=Object.getOwnPropertyDescriptors(e);delete t[wR];let r=Reflect.ownKeys(t);for(let n=0;n<r.length;n++){const a=r[n],i=t[a];!1===i.writable&&(i.writable=!0,i.configurable=!0),(i.get||i.set)&&(t[a]={configurable:!0,writable:!0,enumerable:i.enumerable,value:e[a]})}return Object.create(kR(e),t)}{const t=kR(e);if(null!==t&&r)return{...e};const n=Object.create(t);return Object.assign(n,e)}}function DR(e,t=!1){return FR(e)||xR(e)||!ER(e)||(OR(e)>1&&Object.defineProperties(e,{set:jR,add:jR,clear:jR,delete:jR}),Object.freeze(e),t&&Object.values(e).forEach(e=>DR(e,!0))),e}var jR={value:function(){NR(2)}};function FR(e){return null===e||"object"!=typeof e||Object.isFrozen(e)}var UR,qR={};function BR(e){const t=qR[e];return t||NR(0,e),t}function VR(){return UR}function GR(e,t){t&&(BR("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function HR(e){KR(e),e.drafts_.forEach(ZR),e.drafts_=null}function KR(e){e===UR&&(UR=e.parent_)}function WR(e){return UR={drafts_:[],parent_:UR,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function ZR(e){const t=e[wR];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function JR(e,t){t.unfinalizedDrafts_=t.drafts_.length;const r=t.drafts_[0];return void 0!==e&&e!==r?(r[wR].modified_&&(HR(t),NR(4)),ER(e)&&(e=YR(t,e),t.parent_||XR(t,e)),t.patches_&&BR("Patches").generateReplacementPatches_(r[wR].base_,e,t.patches_,t.inversePatches_)):e=YR(t,r,[]),HR(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==bR?e:void 0}function YR(e,t,r){if(FR(t))return t;const n=e.immer_.shouldUseStrictIteration(),a=t[wR];if(!a)return IR(t,(n,i)=>QR(e,a,t,n,i,r),n),t;if(a.scope_!==e)return t;if(!a.modified_)return XR(e,a.base_,!0),a.base_;if(!a.finalized_){a.finalized_=!0,a.scope_.unfinalizedDrafts_--;const t=a.copy_;let i=t,s=!1;3===a.type_&&(i=new Set(t),t.clear(),s=!0),IR(i,(n,i)=>QR(e,a,t,n,i,r,s),n),XR(e,t,!1),r&&e.patches_&&BR("Patches").generatePatches_(a,r,e.patches_,e.inversePatches_)}return a.copy_}function QR(e,t,r,n,a,i,s){if(null==a)return;if("object"!=typeof a&&!s)return;const o=FR(a);if(!o||s){if("production"!==process.env.NODE_ENV&&a===r&&NR(5),xR(a)){const s=YR(e,a,i&&t&&3!==t.type_&&!TR(t.assigned_,n)?i.concat(n):void 0);if($R(r,n,s),!xR(s))return;e.canAutoFreeze_=!1}else s&&r.add(a);if(ER(a)&&!o){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;if(t&&t.base_&&t.base_[n]===a&&o)return;YR(e,a),t&&t.scope_.parent_||"symbol"==typeof n||!(zR(r)?r.has(n):Object.prototype.propertyIsEnumerable.call(r,n))||XR(e,a)}}}function XR(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&DR(t,r)}var eL={get(e,t){if(t===wR)return e;const r=LR(e);if(!TR(r,t))return function(e,t,r){const n=nL(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}(e,r,t);const n=r[t];return e.finalized_||!ER(n)?n:n===rL(e.base_,t)?(iL(e),e.copy_[t]=sL(n,e)):n},has:(e,t)=>t in LR(e),ownKeys:e=>Reflect.ownKeys(LR(e)),set(e,t,r){const n=nL(LR(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){const n=rL(LR(e),t),s=n?.[wR];if(s&&s.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(((a=r)===(i=n)?0!==a||1/a==1/i:a!=a&&i!=i)&&(void 0!==r||TR(e.base_,t)))return!0;iL(e),aL(e)}var a,i;return e.copy_[t]===r&&(void 0!==r||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty:(e,t)=>(void 0!==rL(e.base_,t)||t in e.base_?(e.assigned_[t]=!1,iL(e),aL(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const r=LR(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n?{writable:!0,configurable:1!==e.type_||"length"!==t,enumerable:n.enumerable,value:r[t]}:n},defineProperty(){NR(11)},getPrototypeOf:e=>kR(e.base_),setPrototypeOf(){NR(12)}},tL={};function rL(e,t){const r=e[wR];return(r?LR(r):e)[t]}function nL(e,t){if(!(t in e))return;let r=kR(e);for(;r;){const e=Object.getOwnPropertyDescriptor(r,t);if(e)return e;r=kR(r)}}function aL(e){e.modified_||(e.modified_=!0,e.parent_&&aL(e.parent_))}function iL(e){e.copy_||(e.copy_=MR(e.base_,e.scope_.immer_.useStrictShallowCopy_))}IR(eL,(e,t)=>{tL[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}}),tL.deleteProperty=function(e,t){return"production"!==process.env.NODE_ENV&&isNaN(parseInt(t))&&NR(13),tL.set.call(this,e,t,void 0)},tL.set=function(e,t,r){return"production"!==process.env.NODE_ENV&&"length"!==t&&isNaN(parseInt(t))&&NR(14),eL.set.call(this,e[0],t,r,e[0])};function sL(e,t){const r=zR(e)?BR("MapSet").proxyMap_(e,t):RR(e)?BR("MapSet").proxySet_(e,t):function(e,t){const r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:VR(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let a=n,i=eL;r&&(a=[n],i=tL);const{revoke:s,proxy:o}=Proxy.revocable(a,i);return n.draft_=o,n.revoke_=s,o}(e,t);return(t?t.scope_:VR()).drafts_.push(r),r}function oL(e){if(!ER(e)||FR(e))return e;const t=e[wR];let r,n=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=MR(e,t.scope_.immer_.useStrictShallowCopy_),n=t.scope_.immer_.shouldUseStrictIteration()}else r=MR(e,!0);return IR(r,(e,t)=>{$R(r,e,oL(t))},n),t&&(t.finalized_=!1),r}var cL=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(e,t,r)=>{if("function"==typeof e&&"function"!=typeof t){const r=t;t=e;const n=this;return function(e=r,...a){return n.produce(e,e=>t.call(this,e,...a))}}let n;if("function"!=typeof t&&NR(6),void 0!==r&&"function"!=typeof r&&NR(7),ER(e)){const a=WR(this),i=sL(e,void 0);let s=!0;try{n=t(i),s=!1}finally{s?HR(a):KR(a)}return GR(a,r),JR(n,a)}if(!e||"object"!=typeof e){if(n=t(e),void 0===n&&(n=e),n===bR&&(n=void 0),this.autoFreeze_&&DR(n,!0),r){const t=[],a=[];BR("Patches").generateReplacementPatches_(e,n,t,a),r(t,a)}return n}NR(1,e)},this.produceWithPatches=(e,t)=>{if("function"==typeof e)return(t,...r)=>this.produceWithPatches(t,t=>e(t,...r));let r,n;return[this.produce(e,t,(e,t)=>{r=e,n=t}),r,n]},"boolean"==typeof e?.autoFreeze&&this.setAutoFreeze(e.autoFreeze),"boolean"==typeof e?.useStrictShallowCopy&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),"boolean"==typeof e?.useStrictIteration&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){ER(e)||NR(8),xR(e)&&(e=function(e){xR(e)||NR(10,e);return oL(e)}(e));const t=WR(this),r=sL(e,void 0);return r[wR].isManual_=!0,KR(t),r}finishDraft(e,t){const r=e&&e[wR];r&&r.isManual_||NR(9);const{scope_:n}=r;return GR(n,t),JR(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){const n=t[r];if(0===n.path.length&&"replace"===n.op){e=n.value;break}}r>-1&&(t=t.slice(r+1));const n=BR("Patches").applyPatches_;return xR(e)?n(e,t):this.produce(e,e=>n(e,t))}},lL=cL.produce;const uL=(...e)=>Bn(t=>e.includes(t.type));class dL extends Mr{#y=new Br;#v;get action$(){return this.#y.asObservable()}get value(){return this.#v.value}get closed(){return this.#v.closed||this.#y.closed}constructor(e,t){super(e=>this.#v.subscribe(e));const r="getInitialState"in e?e.getInitialState():t;this.#v=new Gr(r),this.#y.pipe(na(e,r),Yn()).subscribe(this.#v),this.reset=()=>this.#v.next(r)}reset;next(e){this.#y.next(e)}select(e,t){return this.#v.pipe(On(e),Yn(t))}addEffect(e,t){const r="function"==typeof e?this.action$:Array.isArray(e)?this.action$.pipe(uL(...e)):this.action$.pipe(uL(e)),n=t||e;return r.pipe(Rn(e=>Nn(new Promise((t,r)=>{try{t(n(e,this.value))}catch(e){r(e)}})).pipe(Vn(e=>(console.warn("unhandled effect",e),rn)))),Bn(e=>!!e),bn(en)).subscribe(this.#y)}addEpic(e){return this.addFlow(e)}addFlow(e){const t=e(this.action$,this);if(!t)throw new TypeError(`addEpic: one of the provided effects "${e.name||"<anonymous>"}" does not return a stream. Double check you're not missing a return statement!`);return t.pipe(Vn(e=>(console.trace("unhandled exception, epic closed!",e),rn)),bn(en)).subscribe(this.#y)}unsubscribe(){this.#y.unsubscribe(),this.#v.unsubscribe()}complete(){this.#y.complete(),this.#v.complete()}asObservable(){return this.#v.asObservable()}}function pL(e,t){function r(...r){if(t){const n=t(...r);if(!n)throw new Error("prepareAction did not return an object");return{type:e,payload:n.payload,..."meta"in n&&{meta:n.meta},..."error"in n&&{error:n.error}}}return{type:e,payload:r[0]}}return r.toString=()=>`${e}`,r.type=e,r.match=t=>t.type===e,r}const mL="::";function hL(e,t,r,n){const a=pL([e,"request"].join(mL),t);return r&&Object.assign(a,{success:pL([e,"success"].join(mL),r)}),n&&Object.assign(a,{failure:pL([e,"failure"].join(mL),n)}),a}function fL(e){return ER(e)?lL(e,()=>{}):e}function gL(e,t){const[r,n,a]=function(e){const t={},r=[];let n;const a={addCase(e,i){if("production"!==process.env.NODE_ENV){if(r.length>0)throw new Error("`builder.addCase` should only be called before calling `builder.addMatcher`");if(n)throw new Error("`builder.addCase` should only be called before calling `builder.addDefaultCase`")}const s="string"==typeof e?e:e.type;if(s in t)throw new Error("addCase cannot be called with two reducers for the same action type");return t[s]=i,a},addMatcher(e,t){if("production"!==process.env.NODE_ENV&&n)throw new Error("`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");return r.push({matcher:e,reducer:t}),a},addDefaultCase(e){if("production"!==process.env.NODE_ENV&&n)throw new Error("`builder.addDefaultCase` can only be called once");return n=e,a}};return e(a),[t,r,n]}(t);let i;if("function"==typeof e)i=()=>fL(e());else{const t=fL(e);i=()=>t}function s(e,t){let s=[r[t.type],...n.filter(({matcher:e})=>e(t)).map(({reducer:e})=>e)];return a&&0===s.filter(e=>!!e).length&&(s=[a]),s.reduce((e,r)=>{if(r){if(xR(e)){const n=r(e,t);return void 0===n?e:n}if(ER(e))return lL(e,e=>r(e,t));{const n=r(e,t);if(void 0===n){if(null===e)return e;throw Error("A case reducer on a non-draftable value must not return undefined")}return n}}return e},e??i())}return s.getInitialState=i,s}const yL={request:pL("client/request",(e,t)=>({payload:{args:e,options:t},meta:{transaction:mR(),created:Date.now()}})),execute:hL("client/execute",e=>({payload:e,meta:{transaction:e,created:Date.now()}}),e=>({payload:e,meta:{transaction:e.transaction,created:Date.now()}}),(e,t)=>({payload:{error:e},meta:{transaction:t,created:Date.now()}})),cancel:pL("client/cancel",(e,t)=>({payload:{transaction:e,reason:t},meta:{transaction:e,created:Date.now()}})),error:pL("client/error",(e,t)=>({payload:{transaction:e,error:t},meta:{transaction:e,created:Date.now()}}))},vL=e=>e.pipe(Bn(yL.request.match),On(e=>yL.execute(e.meta.transaction)));class bL extends Mr{#b=new Gr("idle");get status(){return this.#b.value}get status$(){return this.#b.asObservable()}#g;#_;get transaction(){return this.#_}created=Date.now();get closed(){return"complete"===this.status||"error"===this.status||"canceled"===this.status}constructor(e,t,r){super(t=>{const{transaction:n}=this,a=e.action$.pipe(Bn(e=>e.meta.transaction===n));t.add(e.state$.pipe(Bn(e=>!!e[n]),On(e=>e[n])).subscribe(e=>{this.#b.next(e.status)})),t.add(a.pipe(Bn(yL.execute.success.match),On(({payload:e})=>e)).subscribe(e=>{this.#b.next("complete"),t.next(e),t.complete()})),t.add(a.pipe(Bn(yL.error.match),On(({payload:e})=>e)).subscribe(e=>{this.#b.next("error"),t.error(e.error)})),t.add(a.pipe(Bn(yL.cancel.match)).subscribe(e=>{this.#b.next("canceled"),t.error(new vR("abort",{message:e.payload.reason||`job: ${n} was canceled`,request:this.#g.getRequest(e.meta.transaction)}))})),r?.signal&&t.add(jn(r?.signal,"abort").pipe(On(()=>yL.cancel(n,`job: ${n} was aborted on signal from caller: ${r?.ref}`))).subscribe(t=>e.next(t))),t.add(()=>{this.complete()})}),this.#g=e;const n=yL.request(t,{ref:r?.ref,retry:r?.retry});this.#_=n.meta.transaction,this.#g.next(n)}complete(e){this.closed||this.cancel(e??`job: ${this.transaction} was completed`)}cancel(e){const t=this.transaction;this.#g.cancel(t,e??`job: ${t} was canceled`)}[Symbol.dispose](){this.complete()}}class _L{type;transaction;data;constructor(e,t,r){this.type=e,this.transaction=t,this.data=r}}class wL extends Mr{#v;#w;#S;_registerEvent(e,t,r){this.#S.next(new _L(e,t,r))}get closed(){return this.#v.closed}get state$(){return this.#v.asObservable()}get action$(){return this.#v.action$}get event$(){return this.#S.asObservable()}get success$(){return this.action$.pipe(Bn(yL.execute.success.match),On(({payload:e})=>e))}get error$(){return this.action$.pipe(uL("client/error"),la(this.#v),On(([e,t])=>{const{payload:r,meta:{transaction:n}}=e,a=t[n];return new vR("error",{request:a,message:`job: ${n} failed`,cause:r})}))}constructor(e,t){super(e=>this.#v.subscribe(e)),this.#v=new dL(((e={})=>gL(e,e=>{e.addCase(yL.request,(e,t)=>{e[t.meta.transaction]={...t.payload,...t.meta,execution:[],errors:[],status:"idle"}}),e.addCase(yL.execute,(e,t)=>{const r=e[t.payload];r&&(r.execution.push(Date.now()),r.status="active")}),e.addCase(yL.execute.success,(e,t)=>{delete e[t.payload.transaction]}),e.addCase(yL.execute.failure,(e,t)=>{const r=e[t.meta.transaction];r&&(r.errors.push(t.payload.error),r.status="failed")}),e.addCase(yL.error,(e,t)=>{delete e[t.meta.transaction]}),e.addCase(yL.cancel,(e,t)=>{delete e[t.meta.transaction]})}))({})),this.#w=new wr(()=>{this.#v.complete(),this.#S.complete()}),this.#S=new Br,this.#w.add(this.#v.addFlow(vL)),this.#w.add(this.#v.addFlow((e=>(t,r)=>t.pipe(Bn(yL.execute.match),la(r),Rn(([r,n])=>{const a=r.payload,i=n[a],s=new AbortController,o=t.pipe(Bn(yL.cancel.match),Bn(e=>e.payload.transaction===a),ca(()=>{s.signal.aborted||s.abort()}));try{return Nn(e(i.args,s.signal)).pipe(On(e=>yL.execute.success({...i,status:"complete",completed:Date.now(),value:e})),Vn(e=>kn(yL.execute.failure(e,a))),oa(o))}catch(e){return kn(yL.execute.failure(e,a))}})))(e))),this.#w.add(this.#v.addFlow((e=>(t,r)=>t.pipe(Bn(yL.execute.failure.match),la(r),Rn(([t,n])=>{const{transaction:a}=t.meta,i=n[a];if(!i)return kn(yL.error(a,new vR("error",{message:"request not found, cannot retry request, most likely removed while scheduled for retry!"})));const s=i.execution.length,o=Object.assign({},e,i.options?.retry),c=i.errors?.slice(-1)[0]??new vR("error",{message:"no errors registered for request!",request:i});if(s>o.count){const e=0===o.count?c:new vR("error",{message:"maximum retries executed!",cause:i.errors,request:i});return kn(yL.error(a,e))}return("function"==typeof o.delay?Nn(o.delay(c)).pipe(Vn(e=>kn(yL.error(a,new vR("error",{message:"retry delay callback failed!",cause:[...i.errors??[],e],request:i}))))):Un(o.delay)).pipe(la(r),Bn(([e,t])=>!!t[a]),ca(([,e])=>{if(!e[a])throw new vR("error",{message:"request not found, most likely removed while scheduled for retry",cause:i.errors,request:i})}),On(()=>yL.execute(a)))})))(Object.assign({count:0,delay:0},t?.retry)))),this.#v.addEffect(yL.request.type,({payload:e,meta:{transaction:t}})=>{this._registerEvent("query_client_job_requested",t,e)}),this.#v.addEffect(yL.execute.type,({meta:{transaction:e}})=>{this._registerEvent("query_client_job_executing",e)}),this.#v.addEffect(yL.execute.success.type,({payload:e,meta:{transaction:t}})=>{this._registerEvent("query_client_job_completed",t,{payload:e})}),this.#v.addEffect(yL.execute.failure.type,({payload:e,meta:{transaction:t}})=>{const r=e.error instanceof Error?e.error:new Error(String(e.error));this._registerEvent("query_client_job_failed",t,{error:r})}),this.#v.addEffect(yL.cancel.type,({payload:{reason:e},meta:{transaction:t}})=>{this._registerEvent("query_client_job_canceled",t,{reason:e||"no reason provided"})}),this.#v.addEffect(yL.error.type,({payload:e,meta:{transaction:t}})=>{const r=e.error instanceof Error?e.error:new Error(String(e.error));this._registerEvent("query_client_job_error",t,{error:r})})}next(e){this.#v.next(e)}query(e,t){const r=new bL(this,e,t),n=r.pipe(aa({connector:()=>new Kr,resetOnRefCountZero:!1}));return Object.defineProperties(n,{transaction:{get:()=>r.transaction},created:{get:()=>r.created},status:{get:()=>r.status},closed:{get:()=>r.closed},cancel:{value:e=>r.cancel(e)},complete:{value:()=>r.complete()}}),n}async nextAsync(e,t){return Pn(this.query(e,t))}getRequest(e){return this.#v.value[e]}getRequestByRef(e){return Object.values(this.#v.value).find(t=>t.ref===e)}cancelTaskByRef(e,t){const r=this.getRequestByRef(e);r?.ref&&this.cancel(r.transaction,t)}cancel(e,t){if(e)this.#v.value[e]&&(t??=`cancelation requested for job: ${e}`,this.#v.next(yL.cancel(e,t)));else for(const e of Object.keys(this.#v.value))this.cancel(e,"all transactions requested canceled")}on(e,t){return this.#v.addEffect(yL[e].type,e=>{t(e,this)})}complete(){this.#w.unsubscribe()}}const SL={set:pL("cache/set",(e,t)=>({payload:{key:e,record:t}})),insert:pL("cache/insert",(e,t)=>({payload:{key:e,entry:t}})),remove:pL("cache/remove",e=>({payload:e})),invalidate:pL("cache/invalidate",(e,t)=>({payload:e,meta:{item:t}})),mutate:pL("cache/mutate",(e,t,r)=>({payload:{...t,key:e},meta:{item:r}})),trim:pL("cache/trim",e=>({payload:e}))},NL=(e,t)=>(t.updated??0)-(e.updated??0);class kL{type;key;data;constructor(e,t,r){this.type=e,this.key=t,this.data=r}}class xL{#v;#S;get state(){return this.#v.value}get state$(){return this.#v.asObservable()}get action$(){return this.#v.action$}_registerEvent(e,t){this.#S.next(new kL(e,t?.key,t?.data))}get event$(){return this.#S.asObservable()}constructor(e){const{trimming:t,initial:r}=e??{};this.#v=new dL(function(e,t={}){return gL(t,t=>t.addCase(e.set,(e,t)=>{const{key:r,record:n}=t.payload;e[r]=n}).addCase(e.insert,(e,t)=>{const{key:r,entry:n}=t.payload,a=e[r];if(a)a.updated=Date.now(),a.updates??=0,a.updates++,a.value=n.value,a.transaction=n.transaction,a.mutated=void 0;else{const t=Date.now();e[r]={...n,created:t,updated:t}}}).addCase(e.remove,(e,t)=>{delete e[t.payload]}).addCase(e.invalidate,(e,t)=>{const r=t.payload?[t.payload]:Object.keys(e);for(const t of r){const r=e[t];r&&(r.updated=void 0)}}).addCase(e.mutate,(e,t)=>{const{key:r,value:n,updated:a}=t.payload,i=e[r];i&&(i.value=n,i.updated=a,i.mutated=Date.now(),i.updates??=0,i.updates++)}).addCase(e.trim,(e,t)=>{const{payload:r}=t,n=r.sort??NL,a=Object.keys(e),i=Object.entries(e).filter(([e,t])=>!r.validate||r.validate(t)).sort((e,t)=>n(e[1],t[1])).slice(0,r.size??Number.MAX_SAFE_INTEGER).map(([e])=>e);if(a.length!==i.length)for(const t of a){const r=i.indexOf(t);-1!==r?i.splice(r,1):delete e[t]}}))}(SL,r)),t&&this.#v.addEffect("cache/set",()=>this.#v.next(SL.trim(t))),this.#S=new Br}has(e){return e in this.#v.value}setItem(e,t){const{args:r,transaction:n,value:a}=t;this.#v.next(SL.insert(e,{args:r,transaction:n,value:a})),this._registerEvent("query_cache_entry_inserted",{key:e,data:{value:a,args:r,transaction:n}})}getItem(e){return this.#v.value[e]}removeItem(e){this.#v.next(SL.remove(e)),this._registerEvent("query_cache_entry_removed",{key:e})}invalidate(e){const t=e?this.#v.value[e]:void 0;this.#v.next(SL.invalidate(e,t)),e&&this._registerEvent("query_cache_entry_invalidated",{key:e,data:{previousValue:t?.value}})}mutate(e,t){const r=e in this.#v.value?this.#v.value[e]:void 0;if(!r)throw new Error(`Cannot mutate cache item with key ${e}: item not found`);const n="function"==typeof t?t(r?.value):t;return this.#v.next(SL.mutate(e,n,r)),this._registerEvent("query_cache_entry_mutated",{key:e,data:{previousValue:r.value,newValue:n,mutation:n}}),()=>this.#v.next(SL.set(e,r))}trim(e){const t=new Set(Object.keys(this.#v.value));this.#v.next(SL.trim(e));const r=new Set(Object.keys(this.#v.value)),n=Array.from(t).filter(e=>!r.has(e));this._registerEvent("query_cache_trimmed",{data:{removedKeys:n,criteria:e}})}reset(){this.#v.reset(),this._registerEvent("query_cache_reset")}complete(){this.#v.complete(),this.#S.complete()}}class EL extends Br{key;args;options;#N=Date.now();get created(){return this.#N}#k=mR();get uuid(){return this.#k}constructor(e,t,r){super(),this.key=e,this.args=t,this.options=r}processJob(e){return e.pipe(On(t=>{const{key:r,uuid:n,created:a}=this;return{key:r,uuid:n,created:a,status:"complete",transaction:e.transaction,complete:t.completed,value:t.value}}),ta(()=>{e.complete()})).subscribe(this)}}class PL{type;key;data;constructor(e,t,r){this.type=e,this.key=t,this.data=r}}class CL{static extractQueryValue=nR;#w=new wr;#g;#x;#E=new Br;#P={};#C;#A;#I=mR();#p;get client(){return this.#g}_registerEvent(e,t,r){this.#p.next(new PL(e,t,r))}get cache(){return this.#x}get event$(){return this.#p.asObservable()}constructor(e){this.#p=new Br,this.#C=t=>yR(e.key(t),this.#I),this.#A=e?.validate??((e=0)=>t=>(t.updated??0)+e>Date.now())(e?.expire),e.client instanceof wL?this.#g=e.client:(this.#g=new wL(e.client.fn,{...e.client.options}),this.#w.add(()=>this.#g.complete())),this.#w.add(this.#g.event$.subscribe({next:e=>this.#p.next(e)})),e.cache instanceof xL?this.#x=e.cache:(this.#x=new xL(e.cache||{}),this.#w.add(()=>this.#x.complete())),this.#w.add(this.#x.event$.subscribe({next:e=>this.#p.next(e)}));const t=((e="switch")=>"function"==typeof e?e:(()=>{switch(e){case"concat":return eR;case"merge":return tR;case"switch":return rR;default:throw new Error(`Invalid queue operator: ${e}`)}})())(e.queueOperator);var r,n;this.#w.add(()=>this.#E.complete()),this.#w.add(this.#E.pipe(ca(e=>{this._registerEvent("query_queued",e)}),Bn(e=>!!(e in this.#P)),t(e=>{const t=this.#P[e],{args:r,options:n,uuid:a}=t;if(this._registerEvent("query_job_selected",e,{taskId:a,args:r,options:n}),!t?.observed)return this._registerEvent("query_job_skipped",e,{taskId:a,args:r,options:n}),delete this.#P[e],rn;const i=this.#g.query(r,{...n,ref:t.uuid});return new Mr(s=>{const{transaction:o}=i;var c,l;this._registerEvent("query_job_started",e,{taskId:a,transaction:o,args:r,options:n}),s.add(()=>{this._registerEvent("query_job_closed",e,{taskId:a,transaction:o,args:r,options:n}),i.complete("task closed"),delete this.#P[e]}),s.add((c=10,void 0===l&&(l=en),Un(c,c,l)).pipe(Bn(()=>!t.observed)).subscribe(()=>{i.cancel(`task: ${t.uuid} is not observed`),s.complete()})),s.add(t.processJob(i).add(()=>{this._registerEvent("query_job_completed",e,{taskId:a,transaction:o,args:r,options:n})})),i.pipe(On(e=>({result:e,task:t})),Vn(()=>rn)).subscribe(s)})}),(r=()=>!this.#g.closed,void 0===n&&(n=!1),jr(function(e,t){var a=0;e.subscribe(Fr(t,function(e){var i=r(e,a++);(i||n)&&t.next(e),!i&&t.complete()}))}))).subscribe(e=>{const{value:t,transaction:r}=e.result,{args:n,key:a,uuid:i}=e.task;this._registerEvent("query_cache_added",a,{data:t,taskId:i,args:n,transaction:r}),this._registerEvent("query_completed",a,{data:t,hasValidCache:!0}),this.#x.setItem(a,{value:t,args:n,transaction:r})}))}query(e,t){return this._query(e,t)}queryAsync(e,t){const{skipResolve:r,...n}=t||{},a=r?Pn:En;return new Promise((r,i)=>{t?.signal&&t.signal.addEventListener("abort",()=>i(new Error("Query aborted"))),a(this._query(e,n).pipe(Xn())).then(r,i)})}persistentQuery(e,t){const r=this.#C(e),n=this._query(e,t);return new Mr(a=>{a.add(n.subscribe({next:a.next.bind(a),error:a.error.bind(a)}));const i=t?.cache?.validate||this.#A;a.add(this.cache.state$.pipe(Bn(e=>r in e),On(t=>({...t[r],key:r,status:"cache",hasValidCache:i(t[r],e)}))).subscribe(a))}).pipe(Yn((e,t)=>e.transaction===t.transaction&&e.mutated===t.mutated))}generateCacheKey(e){return this.#C(e)}mutate(e,t,r){const n=this.#C(e);if(n in this.cache.state==!1){if(void 0===r?.allowCreation)throw new Error(`Cannot mutate cache item with key ${n}: item not found and option "allowCreation" is false`);if(!1===r.allowCreation)return()=>{};const{value:a}="function"==typeof t?t():t;this.cache.setItem(n,{args:e,transaction:mR(),value:a})}return this.#x.mutate(n,t)}invalidate(e){this.#x.invalidate(e&&this.#C(e))}complete(){this.#w.unsubscribe(),this.#p?.complete()}onInvalidate(e){const t=this.#x.action$.pipe(uL("cache/invalidate")).subscribe(t=>e({detail:{item:t.meta.item}}));return()=>t.unsubscribe()}onMutate(e){const t=this.#x.action$.pipe(uL("cache/mutate")).subscribe(t=>e({detail:{changes:t.payload,current:t.meta.item}}));return()=>t.unsubscribe()}_query(e,t){const r=this.#C(e),n=this._createTask(r,e,t);return this._registerEvent("query_created",r,{args:e,options:t}),n}_createTask(e,t,r){return new Mr(n=>{if(r?.signal){if(r?.signal.aborted)return this._registerEvent("query_aborted",e),n.complete();n.add(jn(r?.signal,"abort").subscribe(()=>{this._registerEvent("query_aborted",e),n.complete()}))}const a=this.#x.getItem(e);if(a){this._registerEvent("query_cache_hit",e,{cacheEntry:a});const i=r?.cache?.suppressInvalid??!1,s=(r?.cache?.validate||this.#A)(a,t),o={...a,key:e,status:"cache",hasValidCache:s};if(n.next(o),s||i)return this._registerEvent("query_completed",e,{data:a.value,hasValidCache:s}),n.complete();this._registerEvent("query_cache_miss",e)}const i=e in this.#P;i?this._registerEvent("query_connected",e,{isExistingTask:!0}):(this.#P[e]=new EL(e,t,r),this._registerEvent("query_job_created",e,{taskId:this.#P[e].uuid,args:t,options:r}));const s=this.#P[e];n.add(s.subscribe(n)),i||this.#E.next(e)})}}const AL=se.object({key:se.string().describe("The key used to identify the service"),uri:se.string().describe("The URI of the service"),id:se.string().optional().describe("The ID of the service"),environment:se.string().optional().describe("The environment of the service"),name:se.string().optional().describe("The name of the service"),scopes:se.array(se.string()).optional().default([]).describe("Endpoint authentication scopes"),tags:se.array(se.string()).optional().describe("Tags for the service")}).describe("A service from the service discovery API").transform(e=>({...e,get defaultScopes(){return e.scopes??[]}})),IL=se.array(AL).describe("A list of services from the service discovery API"),OL=e=>Nn(Hz(e)).pipe(On(e=>IL.default([]).parse(e)));class TL{#O;endpoint;http;constructor({http:e,endpoint:t}){this.http=e,this.endpoint=t,this.#O=new CL({client:{fn:()=>e.fetch$(t??"",{selector:OL})},key:()=>"services",expire:3e5})}resolveServices(e){return(e?Pn:En)(CL.extractQueryValue(this.#O.query()))}async resolveService(e,t){const r=(await this.resolveServices(t)).find(t=>t.key===e);if(!r)throw Error(`Failed to resolve service, invalid key [${e}]`);return r}}class $L extends Cs{async _createConfig(e,t){if(!e.hasModule("http"))throw new Error("http module is required");if(!this._has("discoveryClient")){(await e.requireInstance("http")).hasClient("service_discovery")&&this.configureServiceDiscoveryClientByClientKey("service_discovery")}return En(Nn(super._createConfig(e,t)))}_processConfig(e,t){if(!e.discoveryClient)throw new Error("discoveryClient is required, please configure it");return super._processConfig(e,t)}setServiceDiscoveryClient(e){this._set("discoveryClient","function"==typeof e?e:async()=>e)}configureServiceDiscoveryClient(e){this.setServiceDiscoveryClient(async t=>{const{httpClient:r,endpoint:n}=await En(Nn(e(t)))??{};if(r)return new TL({http:r,endpoint:n});throw Error("httpClient is required")})}configureServiceDiscoveryClientByClientKey(e,t){this.configureServiceDiscoveryClient(async({requireInstance:r})=>({httpClient:(await r("http")).createClient(e),endpoint:t}))}}class zL extends Is{config;_http;constructor(e,t){super({version:"9.0.5-cli-search-index.0",config:e}),this.config=e,this._http=t}resolveServices(){return this.config.discoveryClient.resolveServices()}async resolveService(e){return this.config.discoveryClient.resolveService(e)}async createClient(e,t){const r=await this.resolveService(e);if(!r)throw Error(`Could not load configuration of service [${e}]`);return this._http.createClient({...t,baseUri:r.uri,defaultScopes:r.scopes})}async configureClient(e,t){const{key:r,alias:n}="string"==typeof e?{key:e,alias:e}:e,{uri:a,scopes:i}=await this.resolveService(r);var s,o;t.addConfig((s=n,o={baseUri:a,defaultScopes:i},{module:Xz,configure:e=>{e.configureClient(s,o)}}))}}const RL={name:"serviceDiscovery",configure:()=>new $L,initialize:async e=>{const{requireInstance:t,ref:r}=e,n=await e.config.createConfigAsync(e,{...r?.serviceDiscovery?.config}),a=await t("http");return new zL(n,a)}},LL=(e,t)=>{e.addConfig((e=>({module:RL,configure:t=>e(t)}))(()=>Promise.resolve()))};var ML,DL,jL={},FL=[{name:"Agola CI",constant:"AGOLA",env:"AGOLA_GIT_REF",pr:"AGOLA_PULL_REQUEST_ID"},{name:"Appcircle",constant:"APPCIRCLE",env:"AC_APPCIRCLE",pr:{env:"AC_GIT_PR",ne:"false"}},{name:"AppVeyor",constant:"APPVEYOR",env:"APPVEYOR",pr:"APPVEYOR_PULL_REQUEST_NUMBER"},{name:"AWS CodeBuild",constant:"CODEBUILD",env:"CODEBUILD_BUILD_ARN",pr:{env:"CODEBUILD_WEBHOOK_EVENT",any:["PULL_REQUEST_CREATED","PULL_REQUEST_UPDATED","PULL_REQUEST_REOPENED"]}},{name:"Azure Pipelines",constant:"AZURE_PIPELINES",env:"TF_BUILD",pr:{BUILD_REASON:"PullRequest"}},{name:"Bamboo",constant:"BAMBOO",env:"bamboo_planKey"},{name:"Bitbucket Pipelines",constant:"BITBUCKET",env:"BITBUCKET_COMMIT",pr:"BITBUCKET_PR_ID"},{name:"Bitrise",constant:"BITRISE",env:"BITRISE_IO",pr:"BITRISE_PULL_REQUEST"},{name:"Buddy",constant:"BUDDY",env:"BUDDY_WORKSPACE_ID",pr:"BUDDY_EXECUTION_PULL_REQUEST_ID"},{name:"Buildkite",constant:"BUILDKITE",env:"BUILDKITE",pr:{env:"BUILDKITE_PULL_REQUEST",ne:"false"}},{name:"CircleCI",constant:"CIRCLE",env:"CIRCLECI",pr:"CIRCLE_PULL_REQUEST"},{name:"Cirrus CI",constant:"CIRRUS",env:"CIRRUS_CI",pr:"CIRRUS_PR"},{name:"Cloudflare Pages",constant:"CLOUDFLARE_PAGES",env:"CF_PAGES"},{name:"Cloudflare Workers",constant:"CLOUDFLARE_WORKERS",env:"WORKERS_CI"},{name:"Codefresh",constant:"CODEFRESH",env:"CF_BUILD_ID",pr:{any:["CF_PULL_REQUEST_NUMBER","CF_PULL_REQUEST_ID"]}},{name:"Codemagic",constant:"CODEMAGIC",env:"CM_BUILD_ID",pr:"CM_PULL_REQUEST"},{name:"Codeship",constant:"CODESHIP",env:{CI_NAME:"codeship"}},{name:"Drone",constant:"DRONE",env:"DRONE",pr:{DRONE_BUILD_EVENT:"pull_request"}},{name:"dsari",constant:"DSARI",env:"DSARI"},{name:"Earthly",constant:"EARTHLY",env:"EARTHLY_CI"},{name:"Expo Application Services",constant:"EAS",env:"EAS_BUILD"},{name:"Gerrit",constant:"GERRIT",env:"GERRIT_PROJECT"},{name:"Gitea Actions",constant:"GITEA_ACTIONS",env:"GITEA_ACTIONS"},{name:"GitHub Actions",constant:"GITHUB_ACTIONS",env:"GITHUB_ACTIONS",pr:{GITHUB_EVENT_NAME:"pull_request"}},{name:"GitLab CI",constant:"GITLAB",env:"GITLAB_CI",pr:"CI_MERGE_REQUEST_ID"},{name:"GoCD",constant:"GOCD",env:"GO_PIPELINE_LABEL"},{name:"Google Cloud Build",constant:"GOOGLE_CLOUD_BUILD",env:"BUILDER_OUTPUT"},{name:"Harness CI",constant:"HARNESS",env:"HARNESS_BUILD_ID"},{name:"Heroku",constant:"HEROKU",env:{env:"NODE",includes:"/app/.heroku/node/bin/node"}},{name:"Hudson",constant:"HUDSON",env:"HUDSON_URL"},{name:"Jenkins",constant:"JENKINS",env:["JENKINS_URL","BUILD_ID"],pr:{any:["ghprbPullId","CHANGE_ID"]}},{name:"LayerCI",constant:"LAYERCI",env:"LAYERCI",pr:"LAYERCI_PULL_REQUEST"},{name:"Magnum CI",constant:"MAGNUM",env:"MAGNUM"},{name:"Netlify CI",constant:"NETLIFY",env:"NETLIFY",pr:{env:"PULL_REQUEST",ne:"false"}},{name:"Nevercode",constant:"NEVERCODE",env:"NEVERCODE",pr:{env:"NEVERCODE_PULL_REQUEST",ne:"false"}},{name:"Prow",constant:"PROW",env:"PROW_JOB_ID"},{name:"ReleaseHub",constant:"RELEASEHUB",env:"RELEASE_BUILD_ID"},{name:"Render",constant:"RENDER",env:"RENDER",pr:{IS_PULL_REQUEST:"true"}},{name:"Sail CI",constant:"SAIL",env:"SAILCI",pr:"SAIL_PULL_REQUEST_NUMBER"},{name:"Screwdriver",constant:"SCREWDRIVER",env:"SCREWDRIVER",pr:{env:"SD_PULL_REQUEST",ne:"false"}},{name:"Semaphore",constant:"SEMAPHORE",env:"SEMAPHORE",pr:"PULL_REQUEST_NUMBER"},{name:"Sourcehut",constant:"SOURCEHUT",env:{CI_NAME:"sourcehut"}},{name:"Strider CD",constant:"STRIDER",env:"STRIDER"},{name:"TaskCluster",constant:"TASKCLUSTER",env:["TASK_ID","RUN_ID"]},{name:"TeamCity",constant:"TEAMCITY",env:"TEAMCITY_VERSION"},{name:"Travis CI",constant:"TRAVIS",env:"TRAVIS",pr:{env:"TRAVIS_PULL_REQUEST",ne:"false"}},{name:"Vela",constant:"VELA",env:"VELA",pr:{VELA_PULL_REQUEST:"1"}},{name:"Vercel",constant:"VERCEL",env:{any:["NOW_BUILDER","VERCEL"]},pr:"VERCEL_GIT_PULL_REQUEST_ID"},{name:"Visual Studio App Center",constant:"APPCENTER",env:"APPCENTER_BUILD_ID"},{name:"Woodpecker",constant:"WOODPECKER",env:{CI:"woodpecker"},pr:{CI_BUILD_EVENT:"pull_request"}},{name:"Xcode Cloud",constant:"XCODE_CLOUD",env:"CI_XCODE_PROJECT",pr:"CI_PULL_REQUEST_NUMBER"},{name:"Xcode Server",constant:"XCODE_SERVER",env:"XCS"}];function UL(){return ML||(ML=1,function(e){const t=FL,r=process.env;function n(e){return"string"==typeof e?!!r[e]:"env"in e?r[e.env]&&r[e.env].includes(e.includes):"any"in e?e.any.some(function(e){return!!r[e]}):Object.keys(e).every(function(t){return r[t]===e[t]})}Object.defineProperty(e,"_vendors",{value:t.map(function(e){return e.constant})}),e.name=null,e.isPR=null,e.id=null,t.forEach(function(t){const a=(Array.isArray(t.env)?t.env:[t.env]).every(function(e){return n(e)});e[t.constant]=a,a&&(e.name=t.name,e.isPR=function(e){switch(typeof e.pr){case"string":return!!r[e.pr];case"object":return"env"in e.pr?"any"in e.pr?e.pr.any.some(function(t){return r[e.pr.env]===t}):e.pr.env in r&&r[e.pr.env]!==e.pr.ne:"any"in e.pr?e.pr.any.some(function(e){return!!r[e]}):n(e.pr);default:return null}}(t),e.id=t.constant)}),e.isCI=!("false"===r.CI||!(r.BUILD_ID||r.BUILD_NUMBER||r.CI||r.CI_APP_ID||r.CI_BUILD_ID||r.CI_BUILD_NUMBER||r.CI_NAME||r.CONTINUOUS_INTEGRATION||r.RUN_ID||e.name))}(jL)),jL}DL||(DL=1,UL().isCI);const qL=["5a842df8-3238-415d-b168-9f16a6a6031b/.default"];var BL;!function(e){e.ContinuesIntegration="ci",e.QualityAssurance="fqa",e.Training="tr",e.Production="fprd",e.Development="dev"}(BL||(BL={}));const VL=async e=>{const t=(e=>{const t=new Ts,r=e.env??BL.ContinuesIntegration;return t.addConfig({module:Xz,configure:t=>{const n=r===BL.Development?BL.ContinuesIntegration:r,a=e.serviceDiscovery?.url??new URL(`/service-registry/environments/${n}/services`,"https://discovery.fusion.equinor.com").toString(),i=e.serviceDiscovery?.scope??qL;t.configureClient("service_discovery",{baseUri:a,defaultScopes:i})}}),LL(t),Pe(t,t=>{const{auth:r}=e;if("token"in r&&r.token){const{token:e}=r;return t.setMode("token_only"),void t.setAccessToken(e)}const{clientId:n,tenantId:a,interactive:i}=r;if(!n||!a)throw new Error("clientId and tenantId are required for auth module");if(t.setClientConfig(a,n),t.setMode(i?"interactive":"silent"),i){const{server:e}=r;if(!e.port)throw new Error("server.port is required for interactive mode");t.setServerPort(e.port),t.setServerOnOpen(e.onOpen)}}),t})({auth:{clientId:"dummy",tenantId:"dummy"}});((e,t)=>{e.addConfig({module:Ls,configure:t})})(t,t=>{if(e.openaiChatDeployment&&t.setModel(e.openaiChatDeployment,new az({azureOpenAIApiKey:e.openaiApiKey,azureOpenAIApiDeploymentName:e.openaiChatDeployment,azureOpenAIApiInstanceName:e.openaiInstance,azureOpenAIApiVersion:e.openaiApiVersion})),e.openaiEmbeddingDeployment&&(console.log("Setting embedding deployment",`\nazureOpenAIApiKey: ${e.openaiApiKey}`,`\nazureOpenAIApiDeploymentName: ${e.openaiEmbeddingDeployment}`,`\nazureOpenAIApiInstanceName: ${e.openaiInstance}`,`\nazureOpenAIApiVersion: ${e.openaiApiVersion}`),t.setEmbedding(e.openaiEmbeddingDeployment,new sz({azureOpenAIApiKey:e.openaiApiKey,azureOpenAIApiDeploymentName:e.openaiEmbeddingDeployment,azureOpenAIApiInstanceName:e.openaiInstance,azureOpenAIApiVersion:e.openaiApiVersion}))),e.azureSearchEndpoint&&e.azureSearchApiKey&&e.azureSearchIndexName){if(!e.openaiEmbeddingDeployment)throw new Error("Embedding deployment is required to configure the vector store");const r=t.getService("embeddings",e.openaiEmbeddingDeployment);t.setVectorStore(e.azureSearchIndexName,new Tz(r,{endpoint:e.azureSearchEndpoint,key:e.azureSearchApiKey,indexName:e.azureSearchIndexName}))}});return await t.initialize()},GL=e("chat").description("Interactive chat with Large Language Models").addOption(t("--verbose","Enable verbose output").default(!1)).addOption(t("--context-limit <number>","Maximum number of context documents to retrieve").default(5).argParser(parseInt)).addOption(t("--history-limit <number>","Maximum number of messages to keep in conversation history").default(20).argParser(parseInt)).action(async e=>{const t=await VL(e),r=t.ai;if(e.verbose&&(console.log("✅ Framework initialized successfully"),console.log("💬 Starting interactive chat..."),console.log("🔍 Context retrieval enabled"),console.log(`📝 Message history limit: ${e.historyLimit||20} messages`),e.azureSearchEndpoint?console.log(`📚 Using vector store: ${e.azureSearchIndexName}`):console.log("⚠️ No vector store configured - context retrieval will be skipped"),console.log('Type "exit" or "quit" to end the conversation'),console.log('Type "clear" to clear the conversation history'),console.log("Press Ctrl+C to exit immediately"),console.log("")),!e.openaiChatDeployment)throw new Error("Chat deployment name is required");if(!e.azureSearchIndexName)throw new Error("Azure Search index name is required");const n=t.ai.getService("chat",e.openaiChatDeployment),a=r.getService("search",e.azureSearchIndexName);e.verbose&&console.log("🔧 Configuring retriever with options:",{k:e.contextLimit||5,searchType:"similarity"});const i=a.asRetriever({k:e.contextLimit||5,searchType:"similarity"}),s=(new VT).pipe(async t=>{const r=await(async t=>{try{e.verbose&&console.log("🔍 Retrieving context for query:",t);const r=await i.invoke(t);return e.verbose&&console.log("📄 Retrieved documents:",r?.length||0),r&&0!==r.length?r.map(e=>e.pageContent).join("\n"):"No relevant context found."}catch(t){return console.error("❌ Error retrieving context:",t),e.verbose&&console.error("Full error details:",t),"Error retrieving context."}})(t.userMessage);return[{role:"system",content:`You are a helpful assistant. Use the following context to provide accurate and relevant responses. If the context doesn't contain relevant information, say so clearly.\n \n Context:\n${r}`},...t.messageHistory,{role:"user",content:t.userMessage}]}),o=zx.from([s,n,new l$]),c=[],l=async(t,r,a)=>{if(t.push(r),t.length>=10){e.verbose&&console.log("🔄 Compressing conversation history with AI summarization...");const r=t.splice(0,5),a=await(async e=>{const t=`Please provide a concise summary of the following conversation history. Focus on key topics, decisions, and important context that should be remembered for the ongoing conversation:\n\n${e.map(e=>`${e.role}: ${e.content}`).join("\n")}\n\nSummary:`;try{return{role:"assistant",content:`[Previous conversation summary: ${await n.invoke([{role:"user",content:t}])}]`}}catch(t){return console.error("❌ Error summarizing conversation:",t),{role:"assistant",content:`[Previous conversation summary: ${e.length} messages about various topics]`}}})(r);t.unshift(a),e.verbose&&console.log(`📝 Compressed 5 messages into 1 summary. History now has ${t.length} messages.`)}if(t.length>a){const e=t.length-a,r=Math.min(e,Math.max(0,t.length-2));t.splice(0,r)}return t};console.log("💬 Chat ready! Start typing your message...\n"),console.log("💡 Press Ctrl+C to exit at any time\n");const u=ce({input:process.stdin,output:process.stdout}),d=()=>{console.log("\n\n👋 Goodbye!"),u.close(),process.exit(0)};for(process.on("SIGINT",d),process.on("SIGTERM",d);;)try{const t=await new Promise(e=>{u.question("You: ",t=>{e(t.trim())})});if(!t){console.log("Please enter a message\n");continue}if("clear"===t.toLowerCase()){c.length=0,console.log("\n🧹 Conversation history cleared!\n");continue}await l(c,{role:"user",content:t},e.historyLimit||20),console.log("\n🤖 AI Response:");try{e.verbose&&(console.log("🔍 Using LangChain chain with context retrieval..."),console.log(`📝 Message history contains ${c.length} messages`));const r=await o.stream({userMessage:t,messageHistory:c}),n=await new Promise((e,t)=>{let n="";Nn(r).subscribe({next:e=>{process.stdout.write(String(e)),n+=e},error:e=>{t(e)},complete:()=>{e(n)}})});await l(c,{role:"assistant",content:n},e.historyLimit||20)}catch(e){console.error("\n❌ Chain error:",e),console.log("Falling back to basic chat...")}console.log("")}catch(e){console.error("\n❌ Error during chat:",e),console.log("")}}),HL=va(GL,{includeChat:!0,includeEmbedding:!0,includeSearch:!0}),KL=(e,t)=>{const r=Buffer.from(e).toString("base64").replace(/[^a-zA-Z0-9]/g,"");return t?`${r}-${t}`:r},WL={chunkSize:2e3,chunkOverlap:200,separators:["\n# ","\n## ","\n```"]},ZL=e=>e.endsWith(".md"),JL=async e=>{Te(ZL(e.path),`File ${e.path} is not a markdown file`);const t=j(e.path,"utf8"),r=await(async(e,t)=>{const{content:r,data:n}=$e(e),a=Object.entries(n).reduce((e,[t,r])=>(e[`md_${t}`]=r,e),{type:"markdown"}),i=new ze(WL);return(await i.splitText(r)).map((e,r)=>({id:KL(t,r),pageContent:e,metadata:{source:t,attributes:a}}))})(t,e.relativePath??e.path);return r.map(t=>({...t,metadata:{...t.metadata,rootPath:e.projectRoot}}))},YL=[Re.FunctionDeclaration,Re.ClassDeclaration,Re.InterfaceDeclaration,Re.TypeAliasDeclaration,Re.VariableStatement,Re.EnumDeclaration],QL=e=>e.endsWith(".ts")||e.endsWith(".tsx"),XL=(e,t,r,n)=>{const a=e.getKind();if(!YL.includes(a))return null;if(a===Re.ClassDeclaration)return((e,t)=>{const r=e.getLeadingCommentRanges().find(e=>e.getText().startsWith("/**"));if(!r)return null;const n=r.getText(),a=e.getName()||"AnonymousClass";let i=`${n}\n${e.getText({includeJsDocComments:!1}).split("{")[0].trim()} {`;const s=e.getConstructors()[0];if(s){const e=s.getLeadingCommentRanges().find(e=>e.getText().startsWith("/**"));if(e){const t=e.getText(),r=s.getText({includeJsDocComments:!1}).split("{")[0].trim();i+=`\n ${t}\n ${r}`}}[...e.getMethods().filter(e=>e.hasModifier(Re.PublicKeyword)),...e.getProperties().filter(e=>e.hasModifier(Re.PublicKeyword))].forEach(e=>{const t=e.getLeadingCommentRanges().find(e=>e.getText().startsWith("/**"));if(t){const r=t.getText();let n="";e.getKind()===Re.MethodDeclaration?n=e.getText({includeJsDocComments:!1}).split("{")[0].trim():e.getKind()===Re.PropertyDeclaration&&(n=e.getText({includeJsDocComments:!1}).trim()),i+=`\n ${r}\n ${n}`}}),i+="\n}";const o=t.getFilePath();return{id:KL(o),pageContent:i,metadata:{source:o,attributes:{type:"tsdoc",ts_kind:e.getKindName(),ts_name:a}}}})(e,t);if(a===Re.VariableStatement){const n=e.getDeclarations().find(e=>e.getKind()===Re.VariableDeclaration);if(!n)return null;const a=n.getInitializer();if(!a||a.getKind()!==Re.ArrowFunction&&a.getKind()!==Re.FunctionExpression)return null;const i=e.getLeadingCommentRanges().find(e=>e.getText().startsWith("/**"));if(!i)return null;const s=n.getName()||"missing_name_of_node",o=i.getText(),c=t.getFilePath();return{id:KL(c),pageContent:o,metadata:{source:c,rootPath:r?.projectRoot,attributes:{type:"tsdoc",ts_kind:a.getKindName(),ts_name:s}}}}const i=Me.hasName(e)?e.getName():"missing_name_of_node",s=e.getLeadingCommentRanges().find(e=>e.getText().startsWith("/**"));if(!s)return null;const o=s.getText();let c=o;const l=t.getFilePath();if(a===Re.InterfaceDeclaration||a===Re.TypeAliasDeclaration)c=`${o}\n${e.getText()}`;else if(a!==Re.FunctionDeclaration)return null;return{id:KL(l),pageContent:c,metadata:{source:l,rootPath:r?.projectRoot,attributes:{type:"tsdoc",ts_kind:e.getKindName(),ts_name:i}}}},eM=(e,t)=>{const r=[];return e.forEachDescendant(n=>{const a=XL(n,e,t);a&&r.push(a)}),r},tM=new Map,rM=e=>{if(q(u(e,".git")))return e;const t=De(".git",{cwd:l(e),type:"both"}),r=t?.replace(/\.git$/,"");return r},nM=e=>{const t=rM(e);if(t)return tM.has(t)||tM.set(t,ae(t)),{git:tM.get(t),gitRepoPath:t}},aM=e("embeddings").description("Document embedding utilities for Large Language Model processing").addOption(t("--dry-run","Show what would be processed without actually doing it").default(!1)).addOption(t("--config <config>","Path to a config file").default("fusion-ai.config.ts")).addOption(t("--diff","Process only changed files (workflow mode)").default(!1)).addOption(t("--base-ref <ref>","Git reference to compare against").default("HEAD~1")).argument("[glob-patterns...]","Glob patterns to match files (optional when using --diff)").action(async(e,t)=>{const r=await Ie(t.config,{baseDir:process.cwd()}).then(e=>e.config()),n=e.length?e:r.patterns??["**/*.ts","**/*.md"];t.diff||n||(console.error("❌ Error: Glob patterns are required when not using --diff"),process.exit(1));const a=await VL(t),i=a.ai.getService("embeddings",t.openaiEmbeddingDeployment),s=[];if(t.diff)try{const r=await(async(e=process.cwd())=>{if(!rM(e))throw new Error("Not in a git repository");const{git:t}=nM(e)??{};if(!t)throw new Error("Failed to initialize git client");try{const e=await t.revparse(["--abbrev-ref","HEAD"]),r=await t.revparse(["--short","HEAD"]),n=await t.status(),a=n.staged.length,i=n.modified.length+n.deleted.length+n.not_added.length;return{branch:e.trim(),commit:r.trim(),hasChanges:a>0||i>0,stagedFiles:a,unstagedFiles:i}}catch(e){throw new Error(`Failed to get git status: ${e instanceof Error?e.message:String(e)}`)}})();console.log(`🔍 Git status: ${r.branch}@${r.commit}`),console.log(`📊 Changes: ${r.stagedFiles} staged, ${r.unstagedFiles} unstaged`),await(async e=>{const{diff:t,baseRef:r="HEAD~1",cwd:n=process.cwd()}=e;if(!t)return[];const a=rM(n);if(!a)throw new Error("Not in a git repository. Cannot use --diff option.");const{git:i}=nM(n)??{};if(!i)throw new Error("Failed to initialize git client");try{try{return(await i.diff([`${r}`,"--name-only"])).split("\n").filter(e=>""!==e.trim()).map(e=>`${a}/${e}`)}catch{return console.warn(`⚠️ Warning: Git reference '${r}' not found. Processing all files.`),[]}}catch(e){throw new Error(`Git diff failed: ${e instanceof Error?e.message:String(e)}`)}})({diff:t.diff,baseRef:t.baseRef}).then(t=>e&&e.length>0?(console.log(`🎯 Filtering with patterns: ${e.join(", ")}`),Ae(t,e)):t).then(e=>{s.push(...e)}),0===s.length&&(console.log("✅ No changed files match the provided patterns. Nothing to process."),process.exit(0)),console.log(`📝 Found ${s.length} changed files matching patterns`),t.dryRun&&console.log("Changed files:",s.map(e=>e.replace(process.cwd(),".")).join("\n "))}catch(e){console.error(`❌ Git diff error: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}const c=(t.diff?Nn(s):Nn(Ce(n,{onlyFiles:!0,gitignore:!0,absolute:!0}))).pipe(On(e=>{const t=rM(e);return{path:e,projectRoot:t,relativePath:t?d(t,e):e}}),aa({connector:()=>new Br})),l=c.pipe(Bn(e=>ZL(e.path)),Rn(async e=>await JL(e))),u=c.pipe(Bn(e=>QL(e.path)),On(e=>((e,t)=>{Te(QL(e.path),`File ${e.path} is not a TypeScript file`);const r=new Le({useInMemoryFileSystem:!0}).createSourceFile(e.relativePath??e.path,j(e.path,"utf8"));return eM(r,t)})(e))),p=qn(l,u).pipe(Rn(e=>Nn(e).pipe(Rn(async e=>{const t=e.metadata.source?await(async e=>{const{git:t,gitRepoPath:r}=nM(e)??{};if(!t||!r)return void console.log(444,"no git repo root",e);const n=d(r,e),{latest:a}=await t.log({file:n,maxCount:1}),i=await t.getConfig("remote.origin.url").then(({value:e})=>e??void 0);return{git_link:i?((e,t)=>{const r=e.match(/github\.com[:/]([^/]+)\/([^/.]+)(?:\.git)?$/);if(r){const[,e,n]=r;return`https://github.com/${e}/${n}/blob/main/${t}`}})(i,n):void 0,git_commit_hash:a?.hash,git_commit_date:a?.date}})(o.join(e.metadata.rootPath??process.cwd(),e.metadata.source)):{};return{...e,metadata:{...e.metadata,attributes:{...e.metadata.attributes,...t}}}}),On(e=>{const t=r.metadata?.attributeProcessor||((e,t)=>e),n=t(e.metadata.attributes??{},e);return{...e,metadata:{...e.metadata,attributes:n}}}),Wn()))),m=p.pipe(Rn(e=>Nn(e).pipe(Rn(async e=>{console.log("embedding document",e.metadata.source);const t=await i.embedQuery(e.pageContent),r={...e.metadata,embedding:t};return{...e,metadata:r}}),Wn()))),h=m.pipe(Rn(async e=>{const r=a.ai.getService("search",t.azureSearchIndexName);if(0===e.length)return[];if(e.length>1){const t=e.map(e=>e.metadata.source).reduce((e,t)=>e.add(t),new Set),n=Array.from(t).map(e=>`metadata/source eq '${e}'`).join(" or ");r.deleteDocuments({filter:{filterExpression:n}})}console.log("Adding documents to vector store",e.length);for(const t of e)console.log("source:",t?.metadata?.source);return await r.addDocuments(e)}));if(t.dryRun){let e=0;console.log("Dry run mode enabled"),p.subscribe({next:t=>{t.forEach(e=>{console.log("\n--------------------------------"),console.log("id",e.id),console.log("pageContent",e.pageContent.slice(0,100),"..."),console.log("attributes",e?.metadata?.attributes),console.log("source",e?.metadata?.source),console.log("--------------------------------\n")}),e+=t.length},error:e=>{console.error(`❌ Error: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)},complete:()=>{console.log(`✅ ${e} documents would be processed`),process.exit(0)}})}else h.subscribe({next:e=>{console.log(e)},error:e=>{console.error(`❌ Error: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)},complete:()=>{console.log("✅ Embeddings generation completed!"),process.exit(0)}})}),iM=va(aM,{includeEmbedding:!0,includeSearch:!0}),sM=e("ai").description("Manage Large Language Model (ai) integrations and configurations").addHelpText("after",["",'The "ai" command provides tools for managing Large Language Model integrations',"and document processing within the Fusion Framework ecosystem.","","Available subcommands:"," chat Interactive chat with AI models"," embeddings Document embedding utilities for ai processing","","For details and options for a specific subcommand, run:"," fusion ai <subcommand> --help","","Examples:"," $ ffc ai chat"," $ ffc ai chat --model gpt-4 --api-key sk-..."," $ ffc ai embeddings --dry-run ./src"," $ ffc ai embeddings --chunk-size 1000 ./docs/readme.md"].join("\n")).addCommand(HL).addCommand(iM),oM=e("dev").description("Start a local development server for the Fusion portal.").addHelpText("after",["","Configuration:"," dev-server.config.ts Optional configuration file for API mocking, service discovery,"," and development environment customization","","Examples:"," $ ffc portal dev"," $ ffc portal dev --port 4000"," $ ffc portal dev --debug","","See https://equinor.github.io/fusion-framework/cli/docs/dev-server-config.html for configuration options."].join("\n")).option("--debug","Enable debug mode").option("--env <environment>","Runtime environment for the dev server","local").option("--port <port>","Port for the development server","3000").action(async e=>{const t=new m("portal:dev",{debug:e.debug});t.start("Starting portal in development mode..."),P({server:{port:Number(e.port)},log:t,env:e.env}),t.succeed("Development server started successfully.")});var cM,lM,uM,dM,pM,mM,hM,fM,gM,yM,vM=["0BSD","3D-Slicer-1.0","AAL","ADSL","AFL-1.1","AFL-1.2","AFL-2.0","AFL-2.1","AFL-3.0","AGPL-1.0-only","AGPL-1.0-or-later","AGPL-3.0-only","AGPL-3.0-or-later","AMD-newlib","AMDPLPA","AML","AML-glslang","AMPAS","ANTLR-PD","ANTLR-PD-fallback","APAFML","APL-1.0","APSL-1.0","APSL-1.1","APSL-1.2","APSL-2.0","ASWF-Digital-Assets-1.0","ASWF-Digital-Assets-1.1","Abstyles","AdaCore-doc","Adobe-2006","Adobe-Display-PostScript","Adobe-Glyph","Adobe-Utopia","Afmparse","Aladdin","Apache-1.0","Apache-1.1","Apache-2.0","App-s2p","Arphic-1999","Artistic-1.0","Artistic-1.0-Perl","Artistic-1.0-cl8","Artistic-2.0","Artistic-dist","Aspell-RU","BSD-1-Clause","BSD-2-Clause","BSD-2-Clause-Darwin","BSD-2-Clause-Patent","BSD-2-Clause-Views","BSD-2-Clause-first-lines","BSD-2-Clause-pkgconf-disclaimer","BSD-3-Clause","BSD-3-Clause-Attribution","BSD-3-Clause-Clear","BSD-3-Clause-HP","BSD-3-Clause-LBNL","BSD-3-Clause-Modification","BSD-3-Clause-No-Military-License","BSD-3-Clause-No-Nuclear-License","BSD-3-Clause-No-Nuclear-License-2014","BSD-3-Clause-No-Nuclear-Warranty","BSD-3-Clause-Open-MPI","BSD-3-Clause-Sun","BSD-3-Clause-acpica","BSD-3-Clause-flex","BSD-4-Clause","BSD-4-Clause-Shortened","BSD-4-Clause-UC","BSD-4.3RENO","BSD-4.3TAHOE","BSD-Advertising-Acknowledgement","BSD-Attribution-HPND-disclaimer","BSD-Inferno-Nettverk","BSD-Protection","BSD-Source-Code","BSD-Source-beginning-file","BSD-Systemics","BSD-Systemics-W3Works","BSL-1.0","BUSL-1.1","Baekmuk","Bahyph","Barr","Beerware","BitTorrent-1.0","BitTorrent-1.1","Bitstream-Charter","Bitstream-Vera","BlueOak-1.0.0","Boehm-GC","Boehm-GC-without-fee","Borceux","Brian-Gladman-2-Clause","Brian-Gladman-3-Clause","C-UDA-1.0","CAL-1.0","CAL-1.0-Combined-Work-Exception","CATOSL-1.1","CC-BY-1.0","CC-BY-2.0","CC-BY-2.5","CC-BY-2.5-AU","CC-BY-3.0","CC-BY-3.0-AT","CC-BY-3.0-AU","CC-BY-3.0-DE","CC-BY-3.0-IGO","CC-BY-3.0-NL","CC-BY-3.0-US","CC-BY-4.0","CC-BY-NC-1.0","CC-BY-NC-2.0","CC-BY-NC-2.5","CC-BY-NC-3.0","CC-BY-NC-3.0-DE","CC-BY-NC-4.0","CC-BY-NC-ND-1.0","CC-BY-NC-ND-2.0","CC-BY-NC-ND-2.5","CC-BY-NC-ND-3.0","CC-BY-NC-ND-3.0-DE","CC-BY-NC-ND-3.0-IGO","CC-BY-NC-ND-4.0","CC-BY-NC-SA-1.0","CC-BY-NC-SA-2.0","CC-BY-NC-SA-2.0-DE","CC-BY-NC-SA-2.0-FR","CC-BY-NC-SA-2.0-UK","CC-BY-NC-SA-2.5","CC-BY-NC-SA-3.0","CC-BY-NC-SA-3.0-DE","CC-BY-NC-SA-3.0-IGO","CC-BY-NC-SA-4.0","CC-BY-ND-1.0","CC-BY-ND-2.0","CC-BY-ND-2.5","CC-BY-ND-3.0","CC-BY-ND-3.0-DE","CC-BY-ND-4.0","CC-BY-SA-1.0","CC-BY-SA-2.0","CC-BY-SA-2.0-UK","CC-BY-SA-2.1-JP","CC-BY-SA-2.5","CC-BY-SA-3.0","CC-BY-SA-3.0-AT","CC-BY-SA-3.0-DE","CC-BY-SA-3.0-IGO","CC-BY-SA-4.0","CC-PDDC","CC-PDM-1.0","CC-SA-1.0","CC0-1.0","CDDL-1.0","CDDL-1.1","CDL-1.0","CDLA-Permissive-1.0","CDLA-Permissive-2.0","CDLA-Sharing-1.0","CECILL-1.0","CECILL-1.1","CECILL-2.0","CECILL-2.1","CECILL-B","CECILL-C","CERN-OHL-1.1","CERN-OHL-1.2","CERN-OHL-P-2.0","CERN-OHL-S-2.0","CERN-OHL-W-2.0","CFITSIO","CMU-Mach","CMU-Mach-nodoc","CNRI-Jython","CNRI-Python","CNRI-Python-GPL-Compatible","COIL-1.0","CPAL-1.0","CPL-1.0","CPOL-1.02","CUA-OPL-1.0","Caldera","Caldera-no-preamble","Catharon","ClArtistic","Clips","Community-Spec-1.0","Condor-1.1","Cornell-Lossless-JPEG","Cronyx","Crossword","CryptoSwift","CrystalStacker","Cube","D-FSL-1.0","DEC-3-Clause","DL-DE-BY-2.0","DL-DE-ZERO-2.0","DOC","DRL-1.0","DRL-1.1","DSDP","DocBook-DTD","DocBook-Schema","DocBook-Stylesheet","DocBook-XML","Dotseqn","ECL-1.0","ECL-2.0","EFL-1.0","EFL-2.0","EPICS","EPL-1.0","EPL-2.0","EUDatagrid","EUPL-1.0","EUPL-1.1","EUPL-1.2","Elastic-2.0","Entessa","ErlPL-1.1","Eurosym","FBM","FDK-AAC","FSFAP","FSFAP-no-warranty-disclaimer","FSFUL","FSFULLR","FSFULLRSD","FSFULLRWD","FSL-1.1-ALv2","FSL-1.1-MIT","FTL","Fair","Ferguson-Twofish","Frameworx-1.0","FreeBSD-DOC","FreeImage","Furuseth","GCR-docs","GD","GFDL-1.1-invariants-only","GFDL-1.1-invariants-or-later","GFDL-1.1-no-invariants-only","GFDL-1.1-no-invariants-or-later","GFDL-1.1-only","GFDL-1.1-or-later","GFDL-1.2-invariants-only","GFDL-1.2-invariants-or-later","GFDL-1.2-no-invariants-only","GFDL-1.2-no-invariants-or-later","GFDL-1.2-only","GFDL-1.2-or-later","GFDL-1.3-invariants-only","GFDL-1.3-invariants-or-later","GFDL-1.3-no-invariants-only","GFDL-1.3-no-invariants-or-later","GFDL-1.3-only","GFDL-1.3-or-later","GL2PS","GLWTPL","GPL-1.0-only","GPL-1.0-or-later","GPL-2.0-only","GPL-2.0-or-later","GPL-3.0-only","GPL-3.0-or-later","Game-Programming-Gems","Giftware","Glide","Glulxe","Graphics-Gems","Gutmann","HDF5","HIDAPI","HP-1986","HP-1989","HPND","HPND-DEC","HPND-Fenneberg-Livingston","HPND-INRIA-IMAG","HPND-Intel","HPND-Kevlin-Henney","HPND-MIT-disclaimer","HPND-Markus-Kuhn","HPND-Netrek","HPND-Pbmplus","HPND-UC","HPND-UC-export-US","HPND-doc","HPND-doc-sell","HPND-export-US","HPND-export-US-acknowledgement","HPND-export-US-modify","HPND-export2-US","HPND-merchantability-variant","HPND-sell-MIT-disclaimer-xserver","HPND-sell-regexpr","HPND-sell-variant","HPND-sell-variant-MIT-disclaimer","HPND-sell-variant-MIT-disclaimer-rev","HTMLTIDY","HaskellReport","Hippocratic-2.1","IBM-pibs","ICU","IEC-Code-Components-EULA","IJG","IJG-short","IPA","IPL-1.0","ISC","ISC-Veillard","ImageMagick","Imlib2","Info-ZIP","Inner-Net-2.0","InnoSetup","Intel","Intel-ACPI","Interbase-1.0","JPL-image","JPNIC","JSON","Jam","JasPer-2.0","Kastrup","Kazlib","Knuth-CTAN","LAL-1.2","LAL-1.3","LGPL-2.0-only","LGPL-2.0-or-later","LGPL-2.1-only","LGPL-2.1-or-later","LGPL-3.0-only","LGPL-3.0-or-later","LGPLLR","LOOP","LPD-document","LPL-1.0","LPL-1.02","LPPL-1.0","LPPL-1.1","LPPL-1.2","LPPL-1.3a","LPPL-1.3c","LZMA-SDK-9.11-to-9.20","LZMA-SDK-9.22","Latex2e","Latex2e-translated-notice","Leptonica","LiLiQ-P-1.1","LiLiQ-R-1.1","LiLiQ-Rplus-1.1","Libpng","Linux-OpenIB","Linux-man-pages-1-para","Linux-man-pages-copyleft","Linux-man-pages-copyleft-2-para","Linux-man-pages-copyleft-var","Lucida-Bitmap-Fonts","MIPS","MIT","MIT-0","MIT-CMU","MIT-Click","MIT-Festival","MIT-Khronos-old","MIT-Modern-Variant","MIT-Wu","MIT-advertising","MIT-enna","MIT-feh","MIT-open-group","MIT-testregex","MITNFA","MMIXware","MPEG-SSG","MPL-1.0","MPL-1.1","MPL-2.0","MPL-2.0-no-copyleft-exception","MS-LPL","MS-PL","MS-RL","MTLL","Mackerras-3-Clause","Mackerras-3-Clause-acknowledgment","MakeIndex","Martin-Birgmeier","McPhee-slideshow","Minpack","MirOS","Motosoto","MulanPSL-1.0","MulanPSL-2.0","Multics","Mup","NAIST-2003","NASA-1.3","NBPL-1.0","NCBI-PD","NCGL-UK-2.0","NCL","NCSA","NGPL","NICTA-1.0","NIST-PD","NIST-PD-fallback","NIST-Software","NLOD-1.0","NLOD-2.0","NLPL","NOSL","NPL-1.0","NPL-1.1","NPOSL-3.0","NRL","NTIA-PD","NTP","NTP-0","Naumen","NetCDF","Newsletr","Nokia","Noweb","O-UDA-1.0","OAR","OCCT-PL","OCLC-2.0","ODC-By-1.0","ODbL-1.0","OFFIS","OFL-1.0","OFL-1.0-RFN","OFL-1.0-no-RFN","OFL-1.1","OFL-1.1-RFN","OFL-1.1-no-RFN","OGC-1.0","OGDL-Taiwan-1.0","OGL-Canada-2.0","OGL-UK-1.0","OGL-UK-2.0","OGL-UK-3.0","OGTSL","OLDAP-1.1","OLDAP-1.2","OLDAP-1.3","OLDAP-1.4","OLDAP-2.0","OLDAP-2.0.1","OLDAP-2.1","OLDAP-2.2","OLDAP-2.2.1","OLDAP-2.2.2","OLDAP-2.3","OLDAP-2.4","OLDAP-2.5","OLDAP-2.6","OLDAP-2.7","OLDAP-2.8","OLFL-1.3","OML","OPL-1.0","OPL-UK-3.0","OPUBL-1.0","OSET-PL-2.1","OSL-1.0","OSL-1.1","OSL-2.0","OSL-2.1","OSL-3.0","OpenPBS-2.3","OpenSSL","OpenSSL-standalone","OpenVision","PADL","PDDL-1.0","PHP-3.0","PHP-3.01","PPL","PSF-2.0","Parity-6.0.0","Parity-7.0.0","Pixar","Plexus","PolyForm-Noncommercial-1.0.0","PolyForm-Small-Business-1.0.0","PostgreSQL","Python-2.0","Python-2.0.1","QPL-1.0","QPL-1.0-INRIA-2004","Qhull","RHeCos-1.1","RPL-1.1","RPL-1.5","RPSL-1.0","RSA-MD","RSCPL","Rdisc","Ruby","Ruby-pty","SAX-PD","SAX-PD-2.0","SCEA","SGI-B-1.0","SGI-B-1.1","SGI-B-2.0","SGI-OpenGL","SGP4","SHL-0.5","SHL-0.51","SISSL","SISSL-1.2","SL","SMAIL-GPL","SMLNJ","SMPPL","SNIA","SOFA","SPL-1.0","SSH-OpenSSH","SSH-short","SSLeay-standalone","SSPL-1.0","SUL-1.0","SWL","Saxpath","SchemeReport","Sendmail","Sendmail-8.23","Sendmail-Open-Source-1.1","SimPL-2.0","Sleepycat","Soundex","Spencer-86","Spencer-94","Spencer-99","SugarCRM-1.1.3","Sun-PPP","Sun-PPP-2000","SunPro","Symlinks","TAPR-OHL-1.0","TCL","TCP-wrappers","TGPPL-1.0","TMate","TORQUE-1.1","TOSL","TPDL","TPL-1.0","TTWL","TTYP0","TU-Berlin-1.0","TU-Berlin-2.0","TermReadKey","ThirdEye","TrustedQSL","UCAR","UCL-1.0","UMich-Merit","UPL-1.0","URT-RLE","Ubuntu-font-1.0","Unicode-3.0","Unicode-DFS-2015","Unicode-DFS-2016","Unicode-TOU","UnixCrypt","Unlicense","Unlicense-libtelnet","Unlicense-libwhirlpool","VOSTROM","VSL-1.0","Vim","W3C","W3C-19980720","W3C-20150513","WTFPL","Watcom-1.0","Widget-Workshop","Wsuipa","X11","X11-distribute-modifications-variant","X11-swapped","XFree86-1.1","XSkat","Xdebug-1.03","Xerox","Xfig","Xnet","YPL-1.0","YPL-1.1","ZPL-1.1","ZPL-2.0","ZPL-2.1","Zed","Zeeff","Zend-2.0","Zimbra-1.3","Zimbra-1.4","Zlib","any-OSI","any-OSI-perl-modules","bcrypt-Solar-Designer","blessing","bzip2-1.0.6","check-cvs","checkmk","copyleft-next-0.3.0","copyleft-next-0.3.1","curl","cve-tou","diffmark","dtoa","dvipdfm","eGenix","etalab-2.0","fwlw","gSOAP-1.3b","generic-xts","gnuplot","gtkbook","hdparm","iMatix","jove","libpng-1.6.35","libpng-2.0","libselinux-1.0","libtiff","libutil-David-Nugent","lsof","magaz","mailprio","man2html","metamail","mpi-permissive","mpich2","mplus","ngrep","pkgconf","pnmstitch","psfrag","psutils","python-ldap","radvd","snprintf","softSurfer","ssh-keyscan","swrule","threeparttable","ulem","w3m","wwl","xinetd","xkeyboard-config-Zinoviev","xlock","xpp","xzoom","zlib-acknowledgement"],bM=["AGPL-1.0","AGPL-3.0","BSD-2-Clause-FreeBSD","BSD-2-Clause-NetBSD","GFDL-1.1","GFDL-1.2","GFDL-1.3","GPL-1.0","GPL-2.0","GPL-2.0-with-GCC-exception","GPL-2.0-with-autoconf-exception","GPL-2.0-with-bison-exception","GPL-2.0-with-classpath-exception","GPL-2.0-with-font-exception","GPL-3.0","GPL-3.0-with-GCC-exception","GPL-3.0-with-autoconf-exception","LGPL-2.0","LGPL-2.1","LGPL-3.0","Net-SNMP","Nunit","StandardML-NJ","bzip2-1.0.5","eCos-2.0","wxWindows"],_M=["389-exception","Asterisk-exception","Autoconf-exception-2.0","Autoconf-exception-3.0","Autoconf-exception-generic","Autoconf-exception-generic-3.0","Autoconf-exception-macro","Bison-exception-1.24","Bison-exception-2.2","Bootloader-exception","Classpath-exception-2.0","CLISP-exception-2.0","cryptsetup-OpenSSL-exception","DigiRule-FOSS-exception","eCos-exception-2.0","Fawkes-Runtime-exception","FLTK-exception","fmt-exception","Font-exception-2.0","freertos-exception-2.0","GCC-exception-2.0","GCC-exception-2.0-note","GCC-exception-3.1","Gmsh-exception","GNAT-exception","GNOME-examples-exception","GNU-compiler-exception","gnu-javamail-exception","GPL-3.0-interface-exception","GPL-3.0-linking-exception","GPL-3.0-linking-source-exception","GPL-CC-1.0","GStreamer-exception-2005","GStreamer-exception-2008","i2p-gpl-java-exception","KiCad-libraries-exception","LGPL-3.0-linking-exception","libpri-OpenH323-exception","Libtool-exception","Linux-syscall-note","LLGPL","LLVM-exception","LZMA-exception","mif-exception","OCaml-LGPL-linking-exception","OCCT-exception-1.0","OpenJDK-assembly-exception-1.0","openvpn-openssl-exception","PS-or-PDF-font-exception-20170817","QPL-1.0-INRIA-2004-exception","Qt-GPL-exception-1.0","Qt-LGPL-exception-1.1","Qwt-exception-1.0","SANE-exception","SHL-2.0","SHL-2.1","stunnel-exception","SWI-exception","Swift-exception","Texinfo-exception","u-boot-exception-2.0","UBDL-exception","Universal-FOSS-exception-1.0","vsftpd-openssl-exception","WxWindows-exception-3.1","x11vnc-openssl-exception"];function wM(){if(lM)return cM;lM=1;var e=[].concat(vM).concat(bM),t=_M;return cM=function(r){var n=0;function a(){return n<r.length}function i(e){if(e instanceof RegExp){var t=r.slice(n).match(e);if(t)return n+=t[0].length,t[0]}else if(r.indexOf(e,n)===n)return n+=e.length,e}function s(){i(/[ ]*/)}function o(){return i(/[A-Za-z0-9-.]+/)}function c(){var e=o();if(!e)throw new Error("Expected idstring at offset "+n);return e}function l(){return function(){for(var e,t=["WITH","AND","OR","(",")",":","+"],a=0;a<t.length&&!(e=i(t[a]));a++);if("+"===e&&n>1&&" "===r[n-2])throw new Error("Space before `+`");return e&&{type:"OPERATOR",string:e}}()||function(){if(i("DocumentRef-"))return{type:"DOCUMENTREF",string:c()}}()||function(){if(i("LicenseRef-"))return{type:"LICENSEREF",string:c()}}()||(a=n,s=o(),-1!==e.indexOf(s)?{type:"LICENSE",string:s}:-1!==t.indexOf(s)?{type:"EXCEPTION",string:s}:void(n=a));var a,s}for(var u=[];a()&&(s(),a());){var d=l();if(!d)throw new Error("Unexpected `"+r[n]+"` at offset "+n);u.push(d)}return u},cM}function SM(){return dM||(dM=1,uM=function(e){var t=0;function r(){return t<e.length}function n(){return r()?e[t]:null}function a(){if(!r())throw new Error;t++}function i(e){var t=n();if(t&&"OPERATOR"===t.type&&e===t.string)return a(),t.string}function s(){var e=n();if(e&&"LICENSE"===e.type){a();var t={license:e.string};i("+")&&(t.plus=!0);var r=function(){if(i("WITH")){var e=n();if(e&&"EXCEPTION"===e.type)return a(),e.string;throw new Error("Expected exception after `WITH`")}}();return r&&(t.exception=r),t}}function o(e,t){return function r(){var n=t();if(n){if(!i(e))return n;var a=r();if(!a)throw new Error("Expected expression");return{left:n,conjunction:e.toLowerCase(),right:a}}}}var c=o("AND",function(){return function(){if(i("(")){var e=l();if(!i(")"))throw new Error("Expected `)`");return e}}()||function(){var e=t,r="",s=n();if("DOCUMENTREF"===s.type&&(a(),r+="DocumentRef-"+s.string+":",!i(":")))throw new Error("Expected `:` after `DocumentRef-...`");if("LICENSEREF"===(s=n()).type)return a(),{license:r+="LicenseRef-"+s.string};t=e}()||s()}),l=o("OR",c),u=l();if(!u||r())throw new Error("Syntax error");return u}),uM}function NM(){if(mM)return pM;mM=1;var e=wM(),t=SM();return pM=function(r){return t(e(r))}}function kM(){if(yM)return gM;yM=1;var e=NM(),t=function(){if(fM)return hM;fM=1;var e=NM(),t=vM;function r(t){try{return e(t),!0}catch(e){return!1}}function n(e,t){var r=t[0].length-e[0].length;return 0!==r?r:e[0].toUpperCase().localeCompare(t[0].toUpperCase())}var a=[["APGL","AGPL"],["Gpl","GPL"],["GLP","GPL"],["APL","Apache"],["ISD","ISC"],["GLP","GPL"],["IST","ISC"],["Claude","Clause"],[" or later","+"],[" International",""],["GNU","GPL"],["GUN","GPL"],["+",""],["GNU GPL","GPL"],["GNU LGPL","LGPL"],["GNU/GPL","GPL"],["GNU GLP","GPL"],["GNU LESSER GENERAL PUBLIC LICENSE","LGPL"],["GNU Lesser General Public License","LGPL"],["GNU LESSER GENERAL PUBLIC LICENSE","LGPL-2.1"],["GNU Lesser General Public License","LGPL-2.1"],["LESSER GENERAL PUBLIC LICENSE","LGPL"],["Lesser General Public License","LGPL"],["LESSER GENERAL PUBLIC LICENSE","LGPL-2.1"],["Lesser General Public License","LGPL-2.1"],["GNU General Public License","GPL"],["Gnu public license","GPL"],["GNU Public License","GPL"],["GNU GENERAL PUBLIC LICENSE","GPL"],["MTI","MIT"],["Mozilla Public License","MPL"],["Universal Permissive License","UPL"],["WTH","WTF"],["WTFGPL","WTFPL"],["-License",""]].sort(n),i=[function(e){return e.toUpperCase()},function(e){return e.trim()},function(e){return e.replace(/\./g,"")},function(e){return e.replace(/\s+/g,"")},function(e){return e.replace(/\s+/g,"-")},function(e){return e.replace("v","-")},function(e){return e.replace(/,?\s*(\d)/,"-$1")},function(e){return e.replace(/,?\s*(\d)/,"-$1.0")},function(e){return e.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/,"-$2")},function(e){return e.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/,"-$2.0")},function(e){return e[0].toUpperCase()+e.slice(1)},function(e){return e.replace("/","-")},function(e){return e.replace(/\s*V\s*(\d)/,"-$1").replace(/(\d)$/,"$1.0")},function(e){return-1!==e.indexOf("3.0")?e+"-or-later":e+"-only"},function(e){return e+"only"},function(e){return e.replace(/(\d)$/,"-$1.0")},function(e){return e.replace(/(-| )?(\d)$/,"-$2-Clause")},function(e){return e.replace(/(-| )clause(-| )(\d)/,"-$3-Clause")},function(e){return e.replace(/\b(Modified|New|Revised)(-| )?BSD((-| )License)?/i,"BSD-3-Clause")},function(e){return e.replace(/\bSimplified(-| )?BSD((-| )License)?/i,"BSD-2-Clause")},function(e){return e.replace(/\b(Free|Net)(-| )?BSD((-| )License)?/i,"BSD-2-Clause-$1BSD")},function(e){return e.replace(/\bClear(-| )?BSD((-| )License)?/i,"BSD-3-Clause-Clear")},function(e){return e.replace(/\b(Old|Original)(-| )?BSD((-| )License)?/i,"BSD-4-Clause")},function(e){return"CC-"+e},function(e){return"CC-"+e+"-4.0"},function(e){return e.replace("Attribution","BY").replace("NonCommercial","NC").replace("NoDerivatives","ND").replace(/ (\d)/,"-$1").replace(/ ?International/,"")},function(e){return"CC-"+e.replace("Attribution","BY").replace("NonCommercial","NC").replace("NoDerivatives","ND").replace(/ (\d)/,"-$1").replace(/ ?International/,"")+"-4.0"}],s=t.map(function(e){var t=/^(.*)-\d+\.\d+$/.exec(e);return t?[t[0],t[1]]:[e,null]}).reduce(function(e,t){var r=t[1];return e[r]=e[r]||[],e[r].push(t[0]),e},{}),o=Object.keys(s).map(function(e){return[e,s[e]]}).filter(function(e){return 1===e[1].length&&null!==e[0]&&"APL"!==e[0]}).map(function(e){return[e[0],e[1][0]]});s=void 0;var c=[["UNLI","Unlicense"],["WTF","WTFPL"],["2 CLAUSE","BSD-2-Clause"],["2-CLAUSE","BSD-2-Clause"],["3 CLAUSE","BSD-3-Clause"],["3-CLAUSE","BSD-3-Clause"],["AFFERO","AGPL-3.0-or-later"],["AGPL","AGPL-3.0-or-later"],["APACHE","Apache-2.0"],["ARTISTIC","Artistic-2.0"],["Affero","AGPL-3.0-or-later"],["BEER","Beerware"],["BOOST","BSL-1.0"],["BSD","BSD-2-Clause"],["CDDL","CDDL-1.1"],["ECLIPSE","EPL-1.0"],["FUCK","WTFPL"],["GNU","GPL-3.0-or-later"],["LGPL","LGPL-3.0-or-later"],["GPLV1","GPL-1.0-only"],["GPL-1","GPL-1.0-only"],["GPLV2","GPL-2.0-only"],["GPL-2","GPL-2.0-only"],["GPL","GPL-3.0-or-later"],["MIT +NO-FALSE-ATTRIBS","MITNFA"],["MIT","MIT"],["MPL","MPL-2.0"],["X11","X11"],["ZLIB","Zlib"]].concat(o).sort(n),l=function(e){for(var t=0;t<i.length;t++){var n=i[t](e).trim();if(n!==e&&r(n))return n}return null},u=function(e){for(var t=e.toUpperCase(),r=0;r<c.length;r++){var n=c[r];if(t.indexOf(n[0])>-1)return n[1]}return null},d=function(e,t){for(var r=0;r<a.length;r++){var n=a[r],i=n[0];if(e.indexOf(i)>-1){var s=t(e.replace(i,n[1]));if(null!==s)return s}}return null};return hM=function(e,t){var n=void 0===(t=t||{}).upgrade||!!t.upgrade;function a(e){return n?function(e){return-1!==["GPL-1.0","LGPL-1.0","AGPL-1.0","GPL-2.0","LGPL-2.0","AGPL-2.0","LGPL-2.1"].indexOf(e)?e+"-only":-1!==["GPL-1.0+","GPL-2.0+","GPL-3.0+","LGPL-2.0+","LGPL-2.1+","LGPL-3.0+","AGPL-1.0+","AGPL-3.0+"].indexOf(e)?e.replace(/\+$/,"-or-later"):-1!==["GPL-3.0","LGPL-3.0","AGPL-3.0"].indexOf(e)?e+"-or-later":e}(e):e}if("string"!=typeof e||0===e.trim().length)throw Error("Invalid argument. Expected non-empty string.");if(r(e=e.trim()))return a(e);var i=e.replace(/\+$/,"").trim();if(r(i))return a(i);var s=l(e);return null!==s||null!==(s=d(e,function(e){return r(e)?e:l(e)}))||null!==(s=u(e))||null!==(s=d(e,u))?a(s):null}}(),r='license should be a valid SPDX license expression (without "LicenseRef"), "UNLICENSED", or "SEE LICENSE IN <filename>"',n=/^SEE LICEN[CS]E IN (.+)$/;function a(e,t){return t.slice(0,e.length)===e}function i(e){if(e.hasOwnProperty("license")){var t=e.license;return a("LicenseRef",t)||a("DocumentRef",t)}return i(e.left)||i(e.right)}return gM=function(a){var s;try{s=e(a)}catch(e){var o;if("UNLICENSED"===a||"UNLICENCED"===a)return{validForOldPackages:!0,validForNewPackages:!0,unlicensed:!0};if(o=n.exec(a))return{validForOldPackages:!0,validForNewPackages:!0,inFile:o[1]};var c={validForOldPackages:!1,validForNewPackages:!1,warnings:[r]};if(0!==a.trim().length){var l=t(a);l&&c.warnings.push('license is similar to the valid expression "'+l+'"')}return c}return i(s)?{validForNewPackages:!1,validForOldPackages:!1,spdx:!0,warnings:[r]}:{validForNewPackages:!0,validForOldPackages:!0,spdx:!0}}}var xM,EM,PM,CM,AM,IM,OM,TM,$M,zM,RM,LM={};function MM(){if(xM)return LM;xM=1,Object.defineProperty(LM,"__esModule",{value:!0}),LM.LRUCache=void 0;const e="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,t=new Set,r="object"==typeof process&&process?process:{},n=(e,t,n,a)=>{"function"==typeof r.emitWarning?r.emitWarning(e,t,n,a):console.error(`[${n}] ${t}: ${e}`)};let a=globalThis.AbortController,i=globalThis.AbortSignal;if(void 0===a){i=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},a=class{constructor(){t()}signal=new i;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(const t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e="1"!==r.env?.LRU_CACHE_IGNORE_AC_WARNING;const t=()=>{e&&(e=!1,n("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}const s=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),o=e=>s(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?c:null:null;class c extends Array{constructor(e){super(e),this.fill(0)}}class l{heap;length;static#T=!1;static create(e){const t=o(e);if(!t)return[];l.#T=!0;const r=new l(e,t);return l.#T=!1,r}constructor(e,t){if(!l.#T)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}}class u{#$;#z;#R;#L;#M;#D;#j;#F;get perf(){return this.#F}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#U;#q;#B;#V;#G;#H;#K;#W;#Z;#J;#Y;#Q;#X;#ee;#te;#re;#ne;#ae;static unsafeExposeInternals(e){return{starts:e.#X,ttls:e.#ee,sizes:e.#Q,keyMap:e.#B,keyList:e.#V,valList:e.#G,next:e.#H,prev:e.#K,get head(){return e.#W},get tail(){return e.#Z},free:e.#J,isBackgroundFetch:t=>e.#ie(t),backgroundFetch:(t,r,n,a)=>e.#se(t,r,n,a),moveToTail:t=>e.#oe(t),indexes:t=>e.#ce(t),rindexes:t=>e.#le(t),isStale:t=>e.#ue(t)}}get max(){return this.#$}get maxSize(){return this.#z}get calculatedSize(){return this.#q}get size(){return this.#U}get fetchMethod(){return this.#D}get memoMethod(){return this.#j}get dispose(){return this.#R}get onInsert(){return this.#L}get disposeAfter(){return this.#M}constructor(r){const{max:a=0,ttl:i,ttlResolution:c=1,ttlAutopurge:d,updateAgeOnGet:p,updateAgeOnHas:m,allowStale:h,dispose:f,onInsert:g,disposeAfter:y,noDisposeOnSet:v,noUpdateTTL:b,maxSize:_=0,maxEntrySize:w=0,sizeCalculation:S,fetchMethod:N,memoMethod:k,noDeleteOnFetchRejection:x,noDeleteOnStaleGet:E,allowStaleOnFetchRejection:P,allowStaleOnFetchAbort:C,ignoreFetchAbort:A,perf:I}=r;if(void 0!==I&&"function"!=typeof I?.now)throw new TypeError("perf option must have a now() method if specified");if(this.#F=I??e,0!==a&&!s(a))throw new TypeError("max option must be a nonnegative integer");const O=a?o(a):Array;if(!O)throw new Error("invalid max value: "+a);if(this.#$=a,this.#z=_,this.maxEntrySize=w||this.#z,this.sizeCalculation=S,this.sizeCalculation){if(!this.#z&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if("function"!=typeof this.sizeCalculation)throw new TypeError("sizeCalculation set to non-function")}if(void 0!==k&&"function"!=typeof k)throw new TypeError("memoMethod must be a function if defined");if(this.#j=k,void 0!==N&&"function"!=typeof N)throw new TypeError("fetchMethod must be a function if specified");if(this.#D=N,this.#re=!!N,this.#B=new Map,this.#V=new Array(a).fill(void 0),this.#G=new Array(a).fill(void 0),this.#H=new O(a),this.#K=new O(a),this.#W=0,this.#Z=0,this.#J=l.create(a),this.#U=0,this.#q=0,"function"==typeof f&&(this.#R=f),"function"==typeof g&&(this.#L=g),"function"==typeof y?(this.#M=y,this.#Y=[]):(this.#M=void 0,this.#Y=void 0),this.#te=!!this.#R,this.#ae=!!this.#L,this.#ne=!!this.#M,this.noDisposeOnSet=!!v,this.noUpdateTTL=!!b,this.noDeleteOnFetchRejection=!!x,this.allowStaleOnFetchRejection=!!P,this.allowStaleOnFetchAbort=!!C,this.ignoreFetchAbort=!!A,0!==this.maxEntrySize){if(0!==this.#z&&!s(this.#z))throw new TypeError("maxSize must be a positive integer if specified");if(!s(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#de()}if(this.allowStale=!!h,this.noDeleteOnStaleGet=!!E,this.updateAgeOnGet=!!p,this.updateAgeOnHas=!!m,this.ttlResolution=s(c)||0===c?c:1,this.ttlAutopurge=!!d,this.ttl=i||0,this.ttl){if(!s(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#pe()}if(0===this.#$&&0===this.ttl&&0===this.#z)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#$&&!this.#z){const e="LRU_CACHE_UNBOUNDED";if((e=>!t.has(e))(e)){t.add(e);n("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",e,u)}}}getRemainingTTL(e){return this.#B.has(e)?1/0:0}#pe(){const e=new c(this.#$),t=new c(this.#$);this.#ee=e,this.#X=t,this.#me=(r,n,a=this.#F.now())=>{if(t[r]=0!==n?a:0,e[r]=n,0!==n&&this.ttlAutopurge){const e=setTimeout(()=>{this.#ue(r)&&this.#he(this.#V[r],"expire")},n+1);e.unref&&e.unref()}},this.#fe=r=>{t[r]=0!==e[r]?this.#F.now():0},this.#ge=(a,i)=>{if(e[i]){const s=e[i],o=t[i];if(!s||!o)return;a.ttl=s,a.start=o,a.now=r||n();const c=a.now-o;a.remainingTTL=s-c}};let r=0;const n=()=>{const e=this.#F.now();if(this.ttlResolution>0){r=e;const t=setTimeout(()=>r=0,this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=a=>{const i=this.#B.get(a);if(void 0===i)return 0;const s=e[i],o=t[i];if(!s||!o)return 1/0;return s-((r||n())-o)},this.#ue=a=>{const i=t[a],s=e[a];return!!s&&!!i&&(r||n())-i>s}}#fe=()=>{};#ge=()=>{};#me=()=>{};#ue=()=>!1;#de(){const e=new c(this.#$);this.#q=0,this.#Q=e,this.#ye=t=>{this.#q-=e[t],e[t]=0},this.#ve=(e,t,r,n)=>{if(this.#ie(t))return 0;if(!s(r)){if(!n)throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");if("function"!=typeof n)throw new TypeError("sizeCalculation must be a function");if(r=n(t,e),!s(r))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return r},this.#be=(t,r,n)=>{if(e[t]=r,this.#z){const r=this.#z-e[t];for(;this.#q>r;)this.#_e(!0)}this.#q+=e[t],n&&(n.entrySize=r,n.totalCalculatedSize=this.#q)}}#ye=e=>{};#be=(e,t,r)=>{};#ve=(e,t,r,n)=>{if(r||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#ce({allowStale:e=this.allowStale}={}){if(this.#U)for(let t=this.#Z;this.#we(t)&&(!e&&this.#ue(t)||(yield t),t!==this.#W);)t=this.#K[t]}*#le({allowStale:e=this.allowStale}={}){if(this.#U)for(let t=this.#W;this.#we(t)&&(!e&&this.#ue(t)||(yield t),t!==this.#Z);)t=this.#H[t]}#we(e){return void 0!==e&&this.#B.get(this.#V[e])===e}*entries(){for(const e of this.#ce())void 0===this.#G[e]||void 0===this.#V[e]||this.#ie(this.#G[e])||(yield[this.#V[e],this.#G[e]])}*rentries(){for(const e of this.#le())void 0===this.#G[e]||void 0===this.#V[e]||this.#ie(this.#G[e])||(yield[this.#V[e],this.#G[e]])}*keys(){for(const e of this.#ce()){const t=this.#V[e];void 0===t||this.#ie(this.#G[e])||(yield t)}}*rkeys(){for(const e of this.#le()){const t=this.#V[e];void 0===t||this.#ie(this.#G[e])||(yield t)}}*values(){for(const e of this.#ce()){void 0===this.#G[e]||this.#ie(this.#G[e])||(yield this.#G[e])}}*rvalues(){for(const e of this.#le()){void 0===this.#G[e]||this.#ie(this.#G[e])||(yield this.#G[e])}}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(const r of this.#ce()){const n=this.#G[r],a=this.#ie(n)?n.__staleWhileFetching:n;if(void 0!==a&&e(a,this.#V[r],this))return this.get(this.#V[r],t)}}forEach(e,t=this){for(const r of this.#ce()){const n=this.#G[r],a=this.#ie(n)?n.__staleWhileFetching:n;void 0!==a&&e.call(t,a,this.#V[r],this)}}rforEach(e,t=this){for(const r of this.#le()){const n=this.#G[r],a=this.#ie(n)?n.__staleWhileFetching:n;void 0!==a&&e.call(t,a,this.#V[r],this)}}purgeStale(){let e=!1;for(const t of this.#le({allowStale:!0}))this.#ue(t)&&(this.#he(this.#V[t],"expire"),e=!0);return e}info(e){const t=this.#B.get(e);if(void 0===t)return;const r=this.#G[t],n=this.#ie(r)?r.__staleWhileFetching:r;if(void 0===n)return;const a={value:n};if(this.#ee&&this.#X){const e=this.#ee[t],r=this.#X[t];if(e&&r){const t=e-(this.#F.now()-r);a.ttl=t,a.start=Date.now()}}return this.#Q&&(a.size=this.#Q[t]),a}dump(){const e=[];for(const t of this.#ce({allowStale:!0})){const r=this.#V[t],n=this.#G[t],a=this.#ie(n)?n.__staleWhileFetching:n;if(void 0===a||void 0===r)continue;const i={value:a};if(this.#ee&&this.#X){i.ttl=this.#ee[t];const e=this.#F.now()-this.#X[t];i.start=Math.floor(Date.now()-e)}this.#Q&&(i.size=this.#Q[t]),e.unshift([r,i])}return e}load(e){this.clear();for(const[t,r]of e){if(r.start){const e=Date.now()-r.start;r.start=this.#F.now()-e}this.set(t,r.value,r)}}set(e,t,r={}){if(void 0===t)return this.delete(e),this;const{ttl:n=this.ttl,start:a,noDisposeOnSet:i=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:o}=r;let{noUpdateTTL:c=this.noUpdateTTL}=r;const l=this.#ve(e,t,r.size||0,s);if(this.maxEntrySize&&l>this.maxEntrySize)return o&&(o.set="miss",o.maxEntrySizeExceeded=!0),this.#he(e,"set"),this;let u=0===this.#U?void 0:this.#B.get(e);if(void 0===u)u=0===this.#U?this.#Z:0!==this.#J.length?this.#J.pop():this.#U===this.#$?this.#_e(!1):this.#U,this.#V[u]=e,this.#G[u]=t,this.#B.set(e,u),this.#H[this.#Z]=u,this.#K[u]=this.#Z,this.#Z=u,this.#U++,this.#be(u,l,o),o&&(o.set="add"),c=!1,this.#ae&&this.#L?.(t,e,"add");else{this.#oe(u);const r=this.#G[u];if(t!==r){if(this.#re&&this.#ie(r)){r.__abortController.abort(new Error("replaced"));const{__staleWhileFetching:t}=r;void 0===t||i||(this.#te&&this.#R?.(t,e,"set"),this.#ne&&this.#Y?.push([t,e,"set"]))}else i||(this.#te&&this.#R?.(r,e,"set"),this.#ne&&this.#Y?.push([r,e,"set"]));if(this.#ye(u),this.#be(u,l,o),this.#G[u]=t,o){o.set="replace";const e=r&&this.#ie(r)?r.__staleWhileFetching:r;void 0!==e&&(o.oldValue=e)}}else o&&(o.set="update");this.#ae&&this.onInsert?.(t,e,t===r?"update":"replace")}if(0===n||this.#ee||this.#pe(),this.#ee&&(c||this.#me(u,n,a),o&&this.#ge(o,u)),!i&&this.#ne&&this.#Y){const e=this.#Y;let t;for(;t=e?.shift();)this.#M?.(...t)}return this}pop(){try{for(;this.#U;){const e=this.#G[this.#W];if(this.#_e(!0),this.#ie(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(void 0!==e)return e}}finally{if(this.#ne&&this.#Y){const e=this.#Y;let t;for(;t=e?.shift();)this.#M?.(...t)}}}#_e(e){const t=this.#W,r=this.#V[t],n=this.#G[t];return this.#re&&this.#ie(n)?n.__abortController.abort(new Error("evicted")):(this.#te||this.#ne)&&(this.#te&&this.#R?.(n,r,"evict"),this.#ne&&this.#Y?.push([n,r,"evict"])),this.#ye(t),e&&(this.#V[t]=void 0,this.#G[t]=void 0,this.#J.push(t)),1===this.#U?(this.#W=this.#Z=0,this.#J.length=0):this.#W=this.#H[t],this.#B.delete(r),this.#U--,t}has(e,t={}){const{updateAgeOnHas:r=this.updateAgeOnHas,status:n}=t,a=this.#B.get(e);if(void 0!==a){const e=this.#G[a];if(this.#ie(e)&&void 0===e.__staleWhileFetching)return!1;if(!this.#ue(a))return r&&this.#fe(a),n&&(n.has="hit",this.#ge(n,a)),!0;n&&(n.has="stale",this.#ge(n,a))}else n&&(n.has="miss");return!1}peek(e,t={}){const{allowStale:r=this.allowStale}=t,n=this.#B.get(e);if(void 0===n||!r&&this.#ue(n))return;const a=this.#G[n];return this.#ie(a)?a.__staleWhileFetching:a}#se(e,t,r,n){const i=void 0===t?void 0:this.#G[t];if(this.#ie(i))return i;const s=new a,{signal:o}=r;o?.addEventListener("abort",()=>s.abort(o.reason),{signal:s.signal});const c={signal:s.signal,options:r,context:n},l=(n,a=!1)=>{const{aborted:i}=s.signal,o=r.ignoreFetchAbort&&void 0!==n;if(r.status&&(i&&!a?(r.status.fetchAborted=!0,r.status.fetchError=s.signal.reason,o&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),i&&!o&&!a)return u(s.signal.reason);const l=d;return this.#G[t]===d&&(void 0===n?void 0!==l.__staleWhileFetching?this.#G[t]=l.__staleWhileFetching:this.#he(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,n,c.options))),n},u=n=>{const{aborted:a}=s.signal,i=a&&r.allowStaleOnFetchAbort,o=i||r.allowStaleOnFetchRejection,c=o||r.noDeleteOnFetchRejection,l=d;if(this.#G[t]===d){!c||void 0===l.__staleWhileFetching?this.#he(e,"fetch"):i||(this.#G[t]=l.__staleWhileFetching)}if(o)return r.status&&void 0!==l.__staleWhileFetching&&(r.status.returnedStale=!0),l.__staleWhileFetching;if(l.__returned===l)throw n};r.status&&(r.status.fetchDispatched=!0);const d=new Promise((t,n)=>{const a=this.#D?.(e,i,c);a&&a instanceof Promise&&a.then(e=>t(void 0===e?void 0:e),n),s.signal.addEventListener("abort",()=>{r.ignoreFetchAbort&&!r.allowStaleOnFetchAbort||(t(void 0),r.allowStaleOnFetchAbort&&(t=e=>l(e,!0)))})}).then(l,e=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=e),u(e))),p=Object.assign(d,{__abortController:s,__staleWhileFetching:i,__returned:void 0});return void 0===t?(this.set(e,p,{...c.options,status:void 0}),t=this.#B.get(e)):this.#G[t]=p,p}#ie(e){if(!this.#re)return!1;const t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof a}async fetch(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:s=this.noDisposeOnSet,size:o=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:u=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:p=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:h,forceRefresh:f=!1,status:g,signal:y}=t;if(!this.#re)return g&&(g.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:a,status:g});const v={allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:a,ttl:i,noDisposeOnSet:s,size:o,sizeCalculation:c,noUpdateTTL:l,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:m,ignoreFetchAbort:p,status:g,signal:y};let b=this.#B.get(e);if(void 0===b){g&&(g.fetch="miss");const t=this.#se(e,b,v,h);return t.__returned=t}{const t=this.#G[b];if(this.#ie(t)){const e=r&&void 0!==t.__staleWhileFetching;return g&&(g.fetch="inflight",e&&(g.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}const a=this.#ue(b);if(!f&&!a)return g&&(g.fetch="hit"),this.#oe(b),n&&this.#fe(b),g&&this.#ge(g,b),t;const i=this.#se(e,b,v,h),s=void 0!==i.__staleWhileFetching&&r;return g&&(g.fetch=a?"stale":"refresh",s&&a&&(g.returnedStale=!0)),s?i.__staleWhileFetching:i.__returned=i}}async forceFetch(e,t={}){const r=await this.fetch(e,t);if(void 0===r)throw new Error("fetch() returned undefined");return r}memo(e,t={}){const r=this.#j;if(!r)throw new Error("no memoMethod provided to constructor");const{context:n,forceRefresh:a,...i}=t,s=this.get(e,i);if(!a&&void 0!==s)return s;const o=r(e,s,{options:i,context:n});return this.set(e,o,i),o}get(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,status:i}=t,s=this.#B.get(e);if(void 0!==s){const t=this.#G[s],o=this.#ie(t);return i&&this.#ge(i,s),this.#ue(s)?(i&&(i.get="stale"),o?(i&&r&&void 0!==t.__staleWhileFetching&&(i.returnedStale=!0),r?t.__staleWhileFetching:void 0):(a||this.#he(e,"expire"),i&&r&&(i.returnedStale=!0),r?t:void 0)):(i&&(i.get="hit"),o?t.__staleWhileFetching:(this.#oe(s),n&&this.#fe(s),t))}i&&(i.get="miss")}#Se(e,t){this.#K[t]=e,this.#H[e]=t}#oe(e){e!==this.#Z&&(e===this.#W?this.#W=this.#H[e]:this.#Se(this.#K[e],this.#H[e]),this.#Se(this.#Z,e),this.#Z=e)}delete(e){return this.#he(e,"delete")}#he(e,t){let r=!1;if(0!==this.#U){const n=this.#B.get(e);if(void 0!==n)if(r=!0,1===this.#U)this.#Ne(t);else{this.#ye(n);const r=this.#G[n];if(this.#ie(r)?r.__abortController.abort(new Error("deleted")):(this.#te||this.#ne)&&(this.#te&&this.#R?.(r,e,t),this.#ne&&this.#Y?.push([r,e,t])),this.#B.delete(e),this.#V[n]=void 0,this.#G[n]=void 0,n===this.#Z)this.#Z=this.#K[n];else if(n===this.#W)this.#W=this.#H[n];else{const e=this.#K[n];this.#H[e]=this.#H[n];const t=this.#H[n];this.#K[t]=this.#K[n]}this.#U--,this.#J.push(n)}}if(this.#ne&&this.#Y?.length){const e=this.#Y;let t;for(;t=e?.shift();)this.#M?.(...t)}return r}clear(){return this.#Ne("delete")}#Ne(e){for(const t of this.#le({allowStale:!0})){const r=this.#G[t];if(this.#ie(r))r.__abortController.abort(new Error("deleted"));else{const n=this.#V[t];this.#te&&this.#R?.(r,n,e),this.#ne&&this.#Y?.push([r,n,e])}}if(this.#B.clear(),this.#G.fill(void 0),this.#V.fill(void 0),this.#ee&&this.#X&&(this.#ee.fill(0),this.#X.fill(0)),this.#Q&&this.#Q.fill(0),this.#W=0,this.#Z=0,this.#J.length=0,this.#q=0,this.#U=0,this.#ne&&this.#Y){const e=this.#Y;let t;for(;t=e?.shift();)this.#M?.(...t)}}}return LM.LRUCache=u,LM}function DM(){if(AM)return CM;AM=1;const e=we,t=(e,t,r)=>{const n=e.indexOf(r);return e.lastIndexOf(t,n>-1?n:1/0)},r=t=>{try{return new e.URL(t)}catch{}};return CM=(e,n)=>{const a=n?((e,t)=>{const r=e.indexOf(":"),n=e.slice(0,r+1);if(Object.prototype.hasOwnProperty.call(t,n))return e;const a=e.indexOf("@");return a>-1?a>r?`git+ssh://${e}`:e:e.indexOf("//")===r+1?e:`${e.slice(0,r+1)}//${e.slice(r+1)}`})(e,n):e;return r(a)||r((e=>{const r=t(e,"@","#"),n=t(e,":","#");return n>r&&(e=e.slice(0,n)+"/"+e.slice(n+1)),-1===t(e,":","#")&&-1===e.indexOf("//")&&(e=`git+ssh://${e}`),e})(a))},CM}function jM(){if(OM)return IM;OM=1;const e=DM();return IM=(t,r,{gitHosts:n,protocols:a})=>{if(!t)return;const i=(e=>{const t=e.indexOf("#"),r=e.indexOf("/"),n=e.indexOf("/",r+1),a=e.indexOf(":"),i=/\s/.exec(e),s=e.indexOf("@"),o=!i||t>-1&&i.index>t,c=-1===s||t>-1&&s>t,l=-1===a||t>-1&&a>t,u=-1===n||t>-1&&n>t,d=r>0,p=t>-1?"/"!==e[t-1]:!e.endsWith("/"),m=!e.startsWith(".");return o&&d&&p&&m&&c&&l&&u})(t)?`github:${t}`:t,s=e(i,a);if(!s)return;const o=n.byShortcut[s.protocol],c=n.byDomain[s.hostname.startsWith("www.")?s.hostname.slice(4):s.hostname],l=o||c;if(!l)return;const u=n[o||c];let d=null;a[s.protocol]?.auth&&(s.username||s.password)&&(d=`${s.username}${s.password?":"+s.password:""}`);let p=null,m=null,h=null,f=null;try{if(o){let e=s.pathname.startsWith("/")?s.pathname.slice(1):s.pathname;const t=e.indexOf("@");t>-1&&(e=e.slice(t+1));const r=e.lastIndexOf("/");r>-1?(m=decodeURIComponent(e.slice(0,r)),m||(m=null),h=decodeURIComponent(e.slice(r+1))):h=decodeURIComponent(e),h.endsWith(".git")&&(h=h.slice(0,-4)),s.hash&&(p=decodeURIComponent(s.hash.slice(1))),f="shortcut"}else{if(!u.protocols.includes(s.protocol))return;const e=u.extract(s);if(!e)return;m=e.user&&decodeURIComponent(e.user),h=decodeURIComponent(e.project),p=decodeURIComponent(e.committish),f=a[s.protocol]?.name||s.protocol.slice(0,-1)}}catch(e){if(e instanceof URIError)return;throw e}return[l,m,d,h,p,f,r]}}function FM(){if($M)return TM;$M=1;const{LRUCache:e}=MM(),t=function(){if(PM)return EM;PM=1;const e=(...e)=>e.every(e=>e)?e.join(""):"",t=e=>e?encodeURIComponent(e):"",r=e=>e.toLowerCase().replace(/^\W+/g,"").replace(/(?<!\W)\W+$/,"").replace(/\//g,"").replace(/\W+/g,"-"),n={sshtemplate:({domain:t,user:r,project:n,committish:a})=>`git@${t}:${r}/${n}.git${e("#",a)}`,sshurltemplate:({domain:t,user:r,project:n,committish:a})=>`git+ssh://git@${t}/${r}/${n}.git${e("#",a)}`,edittemplate:({domain:r,user:n,project:a,committish:i,editpath:s,path:o})=>`https://${r}/${n}/${a}${e("/",s,"/",t(i||"HEAD"),"/",o)}`,browsetemplate:({domain:r,user:n,project:a,committish:i,treepath:s})=>`https://${r}/${n}/${a}${e("/",s,"/",t(i))}`,browsetreetemplate:({domain:r,user:n,project:a,committish:i,treepath:s,path:o,fragment:c,hashformat:l})=>`https://${r}/${n}/${a}/${s}/${t(i||"HEAD")}/${o}${e("#",l(c||""))}`,browseblobtemplate:({domain:r,user:n,project:a,committish:i,blobpath:s,path:o,fragment:c,hashformat:l})=>`https://${r}/${n}/${a}/${s}/${t(i||"HEAD")}/${o}${e("#",l(c||""))}`,docstemplate:({domain:r,user:n,project:a,treepath:i,committish:s})=>`https://${r}/${n}/${a}${e("/",i,"/",t(s))}#readme`,httpstemplate:({auth:t,domain:r,user:n,project:a,committish:i})=>`git+https://${e(t,"@")}${r}/${n}/${a}.git${e("#",i)}`,filetemplate:({domain:e,user:r,project:n,committish:a,path:i})=>`https://${e}/${r}/${n}/raw/${t(a||"HEAD")}/${i}`,shortcuttemplate:({type:t,user:r,project:n,committish:a})=>`${t}:${r}/${n}${e("#",a)}`,pathtemplate:({user:t,project:r,committish:n})=>`${t}/${r}${e("#",n)}`,bugstemplate:({domain:e,user:t,project:r})=>`https://${e}/${t}/${r}/issues`,hashformat:r},a={};a.github={protocols:["git:","http:","git+ssh:","git+https:","ssh:","https:"],domain:"github.com",treepath:"tree",blobpath:"blob",editpath:"edit",filetemplate:({auth:r,user:n,project:a,committish:i,path:s})=>`https://${e(r,"@")}raw.githubusercontent.com/${n}/${a}/${t(i||"HEAD")}/${s}`,gittemplate:({auth:t,domain:r,user:n,project:a,committish:i})=>`git://${e(t,"@")}${r}/${n}/${a}.git${e("#",i)}`,tarballtemplate:({domain:e,user:r,project:n,committish:a})=>`https://codeload.${e}/${r}/${n}/tar.gz/${t(a||"HEAD")}`,extract:e=>{let[,t,r,n,a]=e.pathname.split("/",5);if((!n||"tree"===n)&&(n||(a=e.hash.slice(1)),r&&r.endsWith(".git")&&(r=r.slice(0,-4)),t&&r))return{user:t,project:r,committish:a}}},a.bitbucket={protocols:["git+ssh:","git+https:","ssh:","https:"],domain:"bitbucket.org",treepath:"src",blobpath:"src",editpath:"?mode=edit",edittemplate:({domain:r,user:n,project:a,committish:i,treepath:s,path:o,editpath:c})=>`https://${r}/${n}/${a}${e("/",s,"/",t(i||"HEAD"),"/",o,c)}`,tarballtemplate:({domain:e,user:r,project:n,committish:a})=>`https://${e}/${r}/${n}/get/${t(a||"HEAD")}.tar.gz`,extract:e=>{let[,t,r,n]=e.pathname.split("/",4);if(!["get"].includes(n)&&(r&&r.endsWith(".git")&&(r=r.slice(0,-4)),t&&r))return{user:t,project:r,committish:e.hash.slice(1)}}},a.gitlab={protocols:["git+ssh:","git+https:","ssh:","https:"],domain:"gitlab.com",treepath:"tree",blobpath:"tree",editpath:"-/edit",httpstemplate:({auth:t,domain:r,user:n,project:a,committish:i})=>`git+https://${e(t,"@")}${r}/${n}/${a}.git${e("#",i)}`,tarballtemplate:({domain:e,user:r,project:n,committish:a})=>`https://${e}/${r}/${n}/repository/archive.tar.gz?ref=${t(a||"HEAD")}`,extract:e=>{const t=e.pathname.slice(1);if(t.includes("/-/")||t.includes("/archive.tar.gz"))return;const r=t.split("/");let n=r.pop();n.endsWith(".git")&&(n=n.slice(0,-4));const a=r.join("/");return a&&n?{user:a,project:n,committish:e.hash.slice(1)}:void 0}},a.gist={protocols:["git:","git+ssh:","git+https:","ssh:","https:"],domain:"gist.github.com",editpath:"edit",sshtemplate:({domain:t,project:r,committish:n})=>`git@${t}:${r}.git${e("#",n)}`,sshurltemplate:({domain:t,project:r,committish:n})=>`git+ssh://git@${t}/${r}.git${e("#",n)}`,edittemplate:({domain:r,user:n,project:a,committish:i,editpath:s})=>`https://${r}/${n}/${a}${e("/",t(i))}/${s}`,browsetemplate:({domain:r,project:n,committish:a})=>`https://${r}/${n}${e("/",t(a))}`,browsetreetemplate:({domain:r,project:n,committish:a,path:i,hashformat:s})=>`https://${r}/${n}${e("/",t(a))}${e("#",s(i))}`,browseblobtemplate:({domain:r,project:n,committish:a,path:i,hashformat:s})=>`https://${r}/${n}${e("/",t(a))}${e("#",s(i))}`,docstemplate:({domain:r,project:n,committish:a})=>`https://${r}/${n}${e("/",t(a))}`,httpstemplate:({domain:t,project:r,committish:n})=>`git+https://${t}/${r}.git${e("#",n)}`,filetemplate:({user:r,project:n,committish:a,path:i})=>`https://gist.githubusercontent.com/${r}/${n}/raw${e("/",t(a))}/${i}`,shortcuttemplate:({type:t,project:r,committish:n})=>`${t}:${r}${e("#",n)}`,pathtemplate:({project:t,committish:r})=>`${t}${e("#",r)}`,bugstemplate:({domain:e,project:t})=>`https://${e}/${t}`,gittemplate:({domain:t,project:r,committish:n})=>`git://${t}/${r}.git${e("#",n)}`,tarballtemplate:({project:e,committish:r})=>`https://codeload.github.com/gist/${e}/tar.gz/${t(r||"HEAD")}`,extract:e=>{let[,t,r,n]=e.pathname.split("/",4);if("raw"!==n){if(!r){if(!t)return;r=t,t=null}return r.endsWith(".git")&&(r=r.slice(0,-4)),{user:t,project:r,committish:e.hash.slice(1)}}},hashformat:function(e){return e&&"file-"+r(e)}},a.sourcehut={protocols:["git+ssh:","https:"],domain:"git.sr.ht",treepath:"tree",blobpath:"tree",filetemplate:({domain:e,user:r,project:n,committish:a,path:i})=>`https://${e}/${r}/${n}/blob/${t(a)||"HEAD"}/${i}`,httpstemplate:({domain:t,user:r,project:n,committish:a})=>`https://${t}/${r}/${n}.git${e("#",a)}`,tarballtemplate:({domain:e,user:r,project:n,committish:a})=>`https://${e}/${r}/${n}/archive/${t(a)||"HEAD"}.tar.gz`,bugstemplate:()=>null,extract:e=>{let[,t,r,n]=e.pathname.split("/",4);if(!["archive"].includes(n)&&(r&&r.endsWith(".git")&&(r=r.slice(0,-4)),t&&r))return{user:t,project:r,committish:e.hash.slice(1)}}};for(const[e,t]of Object.entries(a))a[e]=Object.assign({},n,t);return EM=a}(),r=jM(),n=DM(),a=new e({max:1e3});class i{constructor(e,t,r,n,a,s,o={}){Object.assign(this,i.#ke[e],{type:e,user:t,auth:r,project:n,committish:a,default:s,opts:o})}static#ke={byShortcut:{},byDomain:{}};static#xe={"git+ssh:":{name:"sshurl"},"ssh:":{name:"sshurl"},"git+https:":{name:"https",auth:!0},"git:":{auth:!0},"http:":{auth:!0},"https:":{auth:!0},"git+http:":{auth:!0}};static addHost(e,t){i.#ke[e]=t,i.#ke.byDomain[t.domain]=e,i.#ke.byShortcut[`${e}:`]=e,i.#xe[`${e}:`]={name:e}}static fromUrl(e,t){if("string"!=typeof e)return;const n=e+JSON.stringify(t||{});if(!a.has(n)){const s=r(e,t,{gitHosts:i.#ke,protocols:i.#xe});a.set(n,s?new i(...s):void 0)}return a.get(n)}static fromManifest(e,t={}){if(!e||"object"!=typeof e)return;const r=e.repository,n=r&&("string"==typeof r?r:"object"==typeof r&&"string"==typeof r.url?r.url:null);if(!n)throw new Error("no repository");const a=n&&i.fromUrl(n.replace(/^git\+/,""),t)||null;if(a)return a;const s=function(e){try{const{protocol:t,hostname:r,pathname:n}=new URL(e);if(!r)return null;return`${/(?:git\+)http:$/.test(t)?"http:":"https:"}//${r}${n.replace(/\.git$/,"")}`}catch{return null}}(n);return i.fromUrl(s,t)||s}static parseUrl(e){return n(e)}#Ee(e,t){if("function"!=typeof e)return null;const r={...this,...this.opts,...t};r.path||(r.path=""),r.path.startsWith("/")&&(r.path=r.path.slice(1)),r.noCommittish&&(r.committish=null);const n=e(r);return r.noGitPlus&&n.startsWith("git+")?n.slice(4):n}hash(){return this.committish?`#${this.committish}`:""}ssh(e){return this.#Ee(this.sshtemplate,e)}sshurl(e){return this.#Ee(this.sshurltemplate,e)}browse(e,...t){return"string"!=typeof e?this.#Ee(this.browsetemplate,e):"string"!=typeof t[0]?this.#Ee(this.browsetreetemplate,{...t[0],path:e}):this.#Ee(this.browsetreetemplate,{...t[1],fragment:t[0],path:e})}browseFile(e,...t){return"string"!=typeof t[0]?this.#Ee(this.browseblobtemplate,{...t[0],path:e}):this.#Ee(this.browseblobtemplate,{...t[1],fragment:t[0],path:e})}docs(e){return this.#Ee(this.docstemplate,e)}bugs(e){return this.#Ee(this.bugstemplate,e)}https(e){return this.#Ee(this.httpstemplate,e)}git(e){return this.#Ee(this.gittemplate,e)}shortcut(e){return this.#Ee(this.shortcuttemplate,e)}path(e){return this.#Ee(this.pathtemplate,e)}tarball(e){return this.#Ee(this.tarballtemplate,{...e,noCommittish:!1})}file(e,t){return this.#Ee(this.filetemplate,{...t,path:e})}edit(e,t){return this.#Ee(this.edittemplate,{...t,path:e})}getDefaultRepresentation(){return this.default}toString(e){return this.default&&"function"==typeof this[this.default]?this[this.default](e):this.sshurl(e)}}for(const[e,r]of Object.entries(t))i.addHost(e,r);return TM=i}var UM,qM,BM={topLevel:{dependancies:"dependencies",dependecies:"dependencies",depdenencies:"dependencies",devEependencies:"devDependencies",depends:"dependencies","dev-dependencies":"devDependencies",devDependences:"devDependencies",devDepenencies:"devDependencies",devdependencies:"devDependencies",repostitory:"repository",repo:"repository",prefereGlobal:"preferGlobal",hompage:"homepage",hampage:"homepage",autohr:"author",autor:"author",contributers:"contributors",publicationConfig:"publishConfig",script:"scripts"},bugs:{web:"url",name:"url"},script:{server:"start",tests:"test"}};function VM(){if(qM)return UM;qM=1;var{URL:e}=i,t=ls(),r=us(),n=kM(),a=FM(),{isBuiltin:s}=je,o=["dependencies","devDependencies","optionalDependencies"],c=RM?zM:(RM=1,zM=function(e){if(!e)return;if("ERROR: No README data found!"===e)return;e=e.trim().split("\n");let t=0;for(;e[t]&&e[t].trim().match(/^(#|$)/);)t++;const r=e.length;let n=t+1;for(;n<r&&e[n].trim();)n++;return e.slice(t,n).join(" ").trim()}),l=BM,u=e=>e.includes("@")&&e.indexOf("@")<e.lastIndexOf(".");function d(e,t){return e.author&&(e.author=t(e.author)),["maintainers","contributors"].forEach(function(r){Array.isArray(e[r])&&(e[r]=e[r].map(t))}),e}function p(e){if("string"==typeof e)return e;var t=e.name||"",r=e.url||e.web,n=r?" ("+r+")":"",a=e.email||e.mail;return t+(a?" <"+a+">":"")+n}function m(e){if("string"!=typeof e)return e;var t=e.match(/^([^(<]+)/),r=e.match(/\(([^()]+)\)/),n=e.match(/<([^<>]+)>/),a={};return t&&t[0].trim()&&(a.name=t[0].trim()),n&&(a.email=n[1]),r&&(a.url=r[1]),a}return UM={warn:function(){},fixRepositoryField:function(e){if(e.repositories&&(this.warn("repositories"),e.repository=e.repositories[0]),!e.repository)return this.warn("missingRepository");"string"==typeof e.repository&&(e.repository={type:"git",url:e.repository});var t=e.repository.url||"";if(t){var r=a.fromUrl(t);r&&(t=e.repository.url="shortcut"===r.getDefaultRepresentation()?r.https():r.toString())}t.match(/github.com\/[^/]+\/[^/]+\.git\.git$/)&&this.warn("brokenGitUrl",t)},fixTypos:function(e){Object.keys(l.topLevel).forEach(function(t){Object.prototype.hasOwnProperty.call(e,t)&&this.warn("typo",t,l.topLevel[t])},this)},fixScriptsField:function(e){if(e.scripts)return"object"!=typeof e.scripts?(this.warn("nonObjectScripts"),void delete e.scripts):void Object.keys(e.scripts).forEach(function(t){"string"!=typeof e.scripts[t]?(this.warn("nonStringScript"),delete e.scripts[t]):l.script[t]&&!e.scripts[l.script[t]]&&this.warn("typo",t,l.script[t],"scripts")},this)},fixFilesField:function(e){var t=e.files;t&&!Array.isArray(t)?(this.warn("nonArrayFiles"),delete e.files):e.files&&(e.files=e.files.filter(function(e){return!(!e||"string"!=typeof e)||(this.warn("invalidFilename",e),!1)},this))},fixBinField:function(e){if(e.bin&&"string"==typeof e.bin){var t,r={};(t=e.name.match(/^@[^/]+[/](.*)$/))?r[t[1]]=e.bin:r[e.name]=e.bin,e.bin=r}},fixManField:function(e){e.man&&"string"==typeof e.man&&(e.man=[e.man])},fixBundleDependenciesField:function(e){var t="bundledDependencies",r="bundleDependencies";e[t]&&!e[r]&&(e[r]=e[t],delete e[t]),e[r]&&!Array.isArray(e[r])?(this.warn("nonArrayBundleDependencies"),delete e[r]):e[r]&&(e[r]=e[r].filter(function(t){return t&&"string"==typeof t?(e.dependencies||(e.dependencies={}),Object.prototype.hasOwnProperty.call(e.dependencies,t)||(this.warn("nonDependencyBundleDependency",t),e.dependencies[t]="*"),!0):(this.warn("nonStringBundleDependency",t),!1)},this))},fixDependencies:function(e){!function(e,t){o.forEach(function(r){e[r]&&(e[r]=function(e,t,r){if(!e)return{};"string"==typeof e&&(e=e.trim().split(/[\n\r\s\t ,]+/));if(!Array.isArray(e))return e;r("deprecatedArrayDependencies",t);var n={};return e.filter(function(e){return"string"==typeof e}).forEach(function(e){var t=(e=e.trim().split(/(:?[@\s><=])/)).shift(),r=e.join("");r=(r=r.trim()).replace(/^@/,""),n[t]=r}),n}(e[r],r,t))})}(e,this.warn),function(e){var t=e.optionalDependencies;if(!t)return;var r=e.dependencies||{};Object.keys(t).forEach(function(e){r[e]=t[e]}),e.dependencies=r}(e,this.warn),this.fixBundleDependenciesField(e),["dependencies","devDependencies"].forEach(function(t){if(t in e)return e[t]&&"object"==typeof e[t]?void Object.keys(e[t]).forEach(function(r){var n=e[t][r];"string"!=typeof n&&(this.warn("nonStringDependency",r,JSON.stringify(n)),delete e[t][r]);var i=a.fromUrl(e[t][r]);i&&(e[t][r]=i.toString())},this):(this.warn("nonObjectDependencies",t),void delete e[t])},this)},fixModulesField:function(e){e.modules&&(this.warn("deprecatedModules"),delete e.modules)},fixKeywordsField:function(e){"string"==typeof e.keywords&&(e.keywords=e.keywords.split(/,\s+/)),e.keywords&&!Array.isArray(e.keywords)?(delete e.keywords,this.warn("nonArrayKeywords")):e.keywords&&(e.keywords=e.keywords.filter(function(e){return!("string"!=typeof e||!e)||(this.warn("nonStringKeyword"),!1)},this))},fixVersionField:function(e,n){var a=!n;if(!e.version)return e.version="",!0;if(!t(e.version,a))throw new Error('Invalid version: "'+e.version+'"');return e.version=r(e.version,a),!0},fixPeople:function(e){d(e,p),d(e,m)},fixNameField:function(e,t){"boolean"==typeof t?t={strict:t}:void 0===t&&(t={});var r=t.strict;if(e.name||r){if("string"!=typeof e.name)throw new Error("name field must be a string.");r||(e.name=e.name.trim()),function(e,t,r){if("."===e.charAt(0)||!function(e){if("@"!==e.charAt(0))return!1;var t=e.slice(1).split("/");if(2!==t.length)return!1;return t[0]&&t[1]&&t[0]===encodeURIComponent(t[0])&&t[1]===encodeURIComponent(t[1])}(e)&&(n=e,n.match(/[/@\s+%:]/)||n!==encodeURIComponent(n))||t&&!r&&e!==e.toLowerCase()||"node_modules"===e.toLowerCase()||"favicon.ico"===e.toLowerCase())throw new Error("Invalid name: "+JSON.stringify(e));var n}(e.name,r,t.allowLegacyCase),s(e.name)&&this.warn("conflictingName",e.name)}else e.name=""},fixDescriptionField:function(e){e.description&&"string"!=typeof e.description&&(this.warn("nonStringDescription"),delete e.description),e.readme&&!e.description&&(e.description=c(e.readme)),void 0===e.description&&delete e.description,e.description||this.warn("missingDescription")},fixReadmeField:function(e){e.readme||(this.warn("missingReadme"),e.readme="ERROR: No README data found!")},fixBugsField:function(t){if(!t.bugs&&t.repository&&t.repository.url){var r=a.fromUrl(t.repository.url);r&&r.bugs()&&(t.bugs={url:r.bugs()})}else if(t.bugs){if("string"==typeof t.bugs)u(t.bugs)?t.bugs={email:t.bugs}:e.canParse(t.bugs)?t.bugs={url:t.bugs}:this.warn("nonEmailUrlBugsString");else{!function(e,t){if(!e)return;Object.keys(e).forEach(function(r){l.bugs[r]&&(t("typo",r,l.bugs[r],"bugs"),e[l.bugs[r]]=e[r],delete e[r])})}(t.bugs,this.warn);var n=t.bugs;t.bugs={},n.url&&(e.canParse(n.url)?t.bugs.url=n.url:this.warn("nonUrlBugsUrlField")),n.email&&("string"==typeof n.email&&u(n.email)?t.bugs.email=n.email:this.warn("nonEmailBugsEmailField"))}t.bugs.email||t.bugs.url||(delete t.bugs,this.warn("emptyNormalizedBugs"))}},fixHomepageField:function(t){if(!t.homepage&&t.repository&&t.repository.url){var r=a.fromUrl(t.repository.url);r&&r.docs()&&(t.homepage=r.docs())}if(t.homepage)return"string"!=typeof t.homepage?(this.warn("nonUrlHomepage"),delete t.homepage):void(e.canParse(t.homepage)||(t.homepage="http://"+t.homepage))},fixLicenseField:function(e){const t=e.license||e.licence;return t?"string"!=typeof t||t.length<1||""===t.trim()?this.warn("invalidLicense"):n(t).validForNewPackages?void 0:this.warn("invalidLicense"):this.warn("missingLicense")}},UM}var GM,HM,KM,WM,ZM={repositories:"'repositories' (plural) Not supported. Please pick one as the 'repository' field",missingRepository:"No repository field.",brokenGitUrl:"Probably broken git url: %s",nonObjectScripts:"scripts must be an object",nonStringScript:"script values must be string commands",nonArrayFiles:"Invalid 'files' member",invalidFilename:"Invalid filename in 'files' list: %s",nonArrayBundleDependencies:"Invalid 'bundleDependencies' list. Must be array of package names",nonStringBundleDependency:"Invalid bundleDependencies member: %s",nonDependencyBundleDependency:"Non-dependency in bundleDependencies: %s",nonObjectDependencies:"%s field must be an object",nonStringDependency:"Invalid dependency: %s %s",deprecatedArrayDependencies:"specifying %s as array is deprecated",deprecatedModules:"modules field is deprecated",nonArrayKeywords:"keywords should be an array of strings",nonStringKeyword:"keywords should be an array of strings",conflictingName:"%s is also the name of a node core module.",nonStringDescription:"'description' field should be a string",missingDescription:"No description",missingReadme:"No README data",missingLicense:"No license field.",nonEmailUrlBugsString:"Bug string field must be url, email, or {email,url}",nonUrlBugsUrlField:"bugs.url field must be a string url. Deleted.",nonEmailBugsEmailField:"bugs.email field must be a string email. Deleted.",emptyNormalizedBugs:"Normalized value of bugs field is an empty object. Deleted.",nonUrlHomepage:"homepage field must be a string url. Deleted.",invalidLicense:"license should be a valid SPDX license expression",typo:"%s should probably be %s."};function JM(){if(HM)return GM;HM=1;var e=ve,t=ZM;function r(r,n,a){return a&&(r=a+"['"+r+"']",n=a+"['"+n+"']"),e.format(t.typo,r,n)}return GM=function(){var n=Array.prototype.slice.call(arguments,0),a=n.shift();if("typo"===a)return r.apply(null,n);var i=t[a]?t[a]:a+": '%s'";return n.unshift(i),e.format.apply(null,n)},GM}!function(){if(WM)return KM;WM=1,KM=n;var e=VM();n.fixer=e;var t=JM(),r=["name","version","description","repository","modules","scripts","files","bin","man","bugs","keywords","readme","homepage","license"].map(function(e){return a(e)+"Field"});function n(n,i,s){!0===i&&(i=null,s=!0),s||(s=!1),i&&!n.private||(i=function(){}),n.scripts&&"node-gyp rebuild"===n.scripts.install&&!n.scripts.preinstall&&(n.gypfile=!0),e.warn=function(){i(t.apply(null,arguments))},r.forEach(function(t){e["fix"+a(t)](n,s)}),n._id=n.name+"@"+n.version}function a(e){return e.charAt(0).toUpperCase()+e.slice(1)}r=r.concat(["dependencies","people","typos"])}();const YM=e("manifest").description("Generate or validate a Fusion portal manifest file.").addHelpText("after",["","By default, outputs the generated manifest object to stdout or a file. Use --output to write to a file.","","Note:","- If not `portal.manifest(.$ENV)?.[ts|js|json]` is found it will fallback to generate a default manifest","","Examples:"," $ ffc portal manifest"," $ ffc portal manifest portal.manifest.prod.ts --output ./dist/portal.manifest.json",' $ ffc portal manifest --silent | jq ".build.entryPoint"'," $ ffc portal manifest --debug"].join("\n")).option("-d, --debug","Enable debug mode for verbose logging",!1).option("-o, --output <string>","Write manifest to the specified file","stdout").option("-s, --silent","Silent mode, suppresses output except errors").argument("[manifest]","Manifest build file to use (e.g., portal.manifest[.env]?.[ts,js,json])").action(async(e,t)=>{const r=t.silent?null:new m("portal:manifest",{debug:t.debug}),n=await C({log:r,manifest:e});if(t.output){const e=c(process.cwd(),t.output);r?.start("Writing manifest to file",t.output),Et(l(e))||await R(l(e),{recursive:!0}),await L(e,JSON.stringify(n.manifest,null,2)),r?.succeed("Manifest written to file",e)}else console.log(JSON.stringify(n.manifest,null,2))});var QM,XM={exports:{}},eD={},tD={},rD={},nD={},aD={},iD={};function sD(){return QM||(QM=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(e){super(),this._items="string"==typeof e?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const e=this._items[0];return""===e||'""'===e}get str(){var e;return null!==(e=this._str)&&void 0!==e?e:this._str=this._items.reduce((e,t)=>`${e}${t}`,"")}get names(){var e;return null!==(e=this._names)&&void 0!==e?e:this._names=this._items.reduce((e,t)=>(t instanceof r&&(e[t.str]=(e[t.str]||0)+1),e),{})}}function a(e,...t){const r=[e[0]];let a=0;for(;a<t.length;)o(r,t[a]),r.push(e[++a]);return new n(r)}e._Code=n,e.nil=new n(""),e._=a;const i=new n("+");function s(e,...t){const r=[l(e[0])];let a=0;for(;a<t.length;)r.push(i),o(r,t[a]),r.push(i,l(e[++a]));return function(e){let t=1;for(;t<e.length-1;){if(e[t]===i){const r=c(e[t-1],e[t+1]);if(void 0!==r){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}(r),new n(r)}function o(e,t){var a;t instanceof n?e.push(...t._items):t instanceof r?e.push(t):e.push("number"==typeof(a=t)||"boolean"==typeof a||null===a?a:l(Array.isArray(a)?a.join(","):a))}function c(e,t){if('""'===t)return e;if('""'===e)return t;if("string"==typeof e){if(t instanceof r||'"'!==e[e.length-1])return;return"string"!=typeof t?`${e.slice(0,-1)}${t}"`:'"'===t[0]?e.slice(0,-1)+t.slice(1):void 0}return"string"!=typeof t||'"'!==t[0]||e instanceof r?void 0:`"${e}${t.slice(1)}`}function l(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.str=s,e.addCodeArg=o,e.strConcat=function(e,t){return t.emptyStr()?e:e.emptyStr()?t:s`${e}${t}`},e.stringify=function(e){return new n(l(e))},e.safeStringify=l,e.getProperty=function(t){return"string"==typeof t&&e.IDENTIFIER.test(t)?new n(`.${t}`):a`[${t}]`},e.getEsmExportName=function(t){if("string"==typeof t&&e.IDENTIFIER.test(t))return new n(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)},e.regexpCode=function(e){return new n(e.toString())}}(iD)),iD}var oD,cD,lD={};function uD(){return oD||(oD=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=sD();class r extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}}var n;!function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"}(n||(e.UsedValueState=n={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class a{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){return`${e}${(this._names[e]||this._nameGroup(e)).index++}`}_nameGroup(e){var t,r;if((null===(r=null===(t=this._parent)||void 0===t?void 0:t._prefixes)||void 0===r?void 0:r.has(e))||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}}e.Scope=a;class i extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=t._`.${new t.Name(r)}[${n}]`}}e.ValueScopeName=i;const s=t._`\n`;e.ValueScope=class extends a{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?s:t.nil}}get(){return this._scope}name(e){return new i(e,this._newName(e))}value(e,t){var r;if(void 0===t.ref)throw new Error("CodeGen: ref must be passed in value");const n=this.toName(e),{prefix:a}=n,i=null!==(r=t.key)&&void 0!==r?r:t.ref;let s=this._values[a];if(s){const e=s.get(i);if(e)return e}else s=this._values[a]=new Map;s.set(i,n);const o=this._scope[a]||(this._scope[a]=[]),c=o.length;return o[c]=t.ref,n.setValue(t,{property:a,itemIndex:c}),n}getValue(e,t){const r=this._values[e];if(r)return r.get(t)}scopeRefs(e,r=this._values){return this._reduceValues(r,r=>{if(void 0===r.scopePath)throw new Error(`CodeGen: name "${r}" has no value`);return t._`${e}${r.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,e=>{if(void 0===e.value)throw new Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,r)}_reduceValues(a,i,s={},o){let c=t.nil;for(const l in a){const u=a[l];if(!u)continue;const d=s[l]=s[l]||new Map;u.forEach(a=>{if(d.has(a))return;d.set(a,n.Started);let s=i(a);if(s){const r=this.opts.es5?e.varKinds.var:e.varKinds.const;c=t._`${c}${r} ${a} = ${s};${this.opts._n}`}else{if(!(s=null==o?void 0:o(a)))throw new r(a);c=t._`${c}${s}${this.opts._n}`}d.set(a,n.Completed)})}return c}}}(lD)),lD}function dD(){return cD||(cD=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=sD(),r=uD();var n=sD();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}});var a=uD();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return a.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return a.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return a.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return a.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class i{optimizeNodes(){return this}optimizeNames(e,t){return this}}class s extends i{constructor(e,t,r){super(),this.varKind=e,this.name=t,this.rhs=r}render({es5:e,_n:t}){const n=e?r.varKinds.var:this.varKind,a=void 0===this.rhs?"":` = ${this.rhs}`;return`${n} ${this.name}${a};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=A(this.rhs,e,t)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class o extends i{constructor(e,t,r){super(),this.lhs=e,this.rhs=t,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof t.Name)||e[this.lhs.str]||this.sideEffects)return this.rhs=A(this.rhs,e,r),this}get names(){return C(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}}class c extends o{constructor(e,t,r,n){super(e,r,n),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class l extends i{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class u extends i{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class d extends i{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class p extends i{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=A(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class m extends i{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){const{nodes:e}=this;let t=e.length;for(;t--;){const r=e[t].optimizeNodes();Array.isArray(r)?e.splice(t,1,...r):r?e[t]=r:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){const{nodes:r}=this;let n=r.length;for(;n--;){const a=r[n];a.optimizeNames(e,t)||(I(e,a.names),r.splice(n,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>P(e,t.names),{})}}class h extends m{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class f extends m{}class g extends h{}g.kind="else";class y extends h{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();const e=this.condition;if(!0===e)return this.nodes;let t=this.else;if(t){const e=t.optimizeNodes();t=this.else=Array.isArray(e)?new g(e):e}return t?!1===e?t instanceof y?t:t.nodes:this.nodes.length?this:new y(O(e),t instanceof y?[t]:t.nodes):!1!==e&&this.nodes.length?this:void 0}optimizeNames(e,t){var r;if(this.else=null===(r=this.else)||void 0===r?void 0:r.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=A(this.condition,e,t),this}get names(){const e=super.names;return C(e,this.condition),this.else&&P(e,this.else.names),e}}y.kind="if";class v extends h{}v.kind="for";class b extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=A(this.iteration,e,t),this}get names(){return P(super.names,this.iteration.names)}}class _ extends v{constructor(e,t,r,n){super(),this.varKind=e,this.name=t,this.from=r,this.to=n}render(e){const t=e.es5?r.varKinds.var:this.varKind,{name:n,from:a,to:i}=this;return`for(${t} ${n}=${a}; ${n}<${i}; ${n}++)`+super.render(e)}get names(){const e=C(super.names,this.from);return C(e,this.to)}}class w extends v{constructor(e,t,r,n){super(),this.loop=e,this.varKind=t,this.name=r,this.iterable=n}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=A(this.iterable,e,t),this}get names(){return P(super.names,this.iterable.names)}}class S extends h{constructor(e,t,r){super(),this.name=e,this.args=t,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}S.kind="func";class N extends m{render(e){return"return "+super.render(e)}}N.kind="return";class k extends h{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),null===(e=this.catch)||void 0===e||e.optimizeNodes(),null===(t=this.finally)||void 0===t||t.optimizeNodes(),this}optimizeNames(e,t){var r,n;return super.optimizeNames(e,t),null===(r=this.catch)||void 0===r||r.optimizeNames(e,t),null===(n=this.finally)||void 0===n||n.optimizeNames(e,t),this}get names(){const e=super.names;return this.catch&&P(e,this.catch.names),this.finally&&P(e,this.finally.names),e}}class x extends h{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}x.kind="catch";class E extends h{render(e){return"finally"+super.render(e)}}E.kind="finally";function P(e,t){for(const r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function C(e,r){return r instanceof t._CodeOrName?P(e,r.names):e}function A(e,r,n){return e instanceof t.Name?i(e):(a=e)instanceof t._Code&&a._items.some(e=>e instanceof t.Name&&1===r[e.str]&&void 0!==n[e.str])?new t._Code(e._items.reduce((e,r)=>(r instanceof t.Name&&(r=i(r)),r instanceof t._Code?e.push(...r._items):e.push(r),e),[])):e;var a;function i(e){const t=n[e.str];return void 0===t||1!==r[e.str]?e:(delete r[e.str],t)}}function I(e,t){for(const r in t)e[r]=(e[r]||0)-(t[r]||0)}function O(e){return"boolean"==typeof e||"number"==typeof e||null===e?!e:t._`!${R(e)}`}e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?"\n":""},this._extScope=e,this._scope=new r.Scope({parent:e}),this._nodes=[new f]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){const r=this._extScope.value(e,t);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,r,n){const a=this._scope.toName(t);return void 0!==r&&n&&(this._constants[a.str]=r),this._leafNode(new s(e,a,r)),a}const(e,t,n){return this._def(r.varKinds.const,e,t,n)}let(e,t,n){return this._def(r.varKinds.let,e,t,n)}var(e,t,n){return this._def(r.varKinds.var,e,t,n)}assign(e,t,r){return this._leafNode(new o(e,t,r))}add(t,r){return this._leafNode(new c(t,e.operators.ADD,r))}code(e){return"function"==typeof e?e():e!==t.nil&&this._leafNode(new p(e)),this}object(...e){const r=["{"];for(const[n,a]of e)r.length>1&&r.push(","),r.push(n),(n!==a||this.opts.es5)&&(r.push(":"),(0,t.addCodeArg)(r,a));return r.push("}"),new t._Code(r)}if(e,t,r){if(this._blockNode(new y(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new y(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(y,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new b(e),t)}forRange(e,t,n,a,i=(this.opts.es5?r.varKinds.var:r.varKinds.let)){const s=this._scope.toName(e);return this._for(new _(i,s,t,n),()=>a(s))}forOf(e,n,a,i=r.varKinds.const){const s=this._scope.toName(e);if(this.opts.es5){const e=n instanceof t.Name?n:this.var("_arr",n);return this.forRange("_i",0,t._`${e}.length`,r=>{this.var(s,t._`${e}[${r}]`),a(s)})}return this._for(new w("of",i,s,n),()=>a(s))}forIn(e,n,a,i=(this.opts.es5?r.varKinds.var:r.varKinds.const)){if(this.opts.ownProperties)return this.forOf(e,t._`Object.keys(${n})`,a);const s=this._scope.toName(e);return this._for(new w("in",i,s,n),()=>a(s))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){const t=new N;if(this._blockNode(t),this.code(e),1!==t.nodes.length)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(N)}try(e,t,r){if(!t&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');const n=new k;if(this._blockNode(n),this.code(e),t){const e=this.name("e");this._currNode=n.catch=new x(e),t(e)}return r&&(this._currNode=n.finally=new E,this.code(r)),this._endBlockNode(x,E)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){const t=this._blockStarts.pop();if(void 0===t)throw new Error("CodeGen: not in self-balancing block");const r=this._nodes.length-t;if(r<0||void 0!==e&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,r=t.nil,n,a){return this._blockNode(new S(e,r,n)),a&&this.code(a).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){const r=this._currNode;if(r instanceof e||t&&r instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){const t=this._currNode;if(!(t instanceof y))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){const e=this._nodes;return e[e.length-1]}set _currNode(e){const t=this._nodes;t[t.length-1]=e}},e.not=O;const T=z(e.operators.AND);e.and=function(...e){return e.reduce(T)};const $=z(e.operators.OR);function z(e){return(r,n)=>r===t.nil?n:n===t.nil?r:t._`${R(r)} ${e} ${R(n)}`}function R(e){return e instanceof t.Name?e:t._`(${e})`}e.or=function(...e){return e.reduce($)}}(aD)),aD}var pD,mD={};function hD(){if(pD)return mD;pD=1,Object.defineProperty(mD,"__esModule",{value:!0}),mD.checkStrictMode=mD.getErrorPath=mD.Type=mD.useFunc=mD.setEvaluated=mD.evaluatedPropsToName=mD.mergeEvaluated=mD.eachItem=mD.unescapeJsonPointer=mD.escapeJsonPointer=mD.escapeFragment=mD.unescapeFragment=mD.schemaRefOrVal=mD.schemaHasRulesButRef=mD.schemaHasRules=mD.checkUnknownRules=mD.alwaysValidSchema=mD.toHash=void 0;const e=dD(),t=sD();function r(e,t=e.schema){const{opts:r,self:n}=e;if(!r.strictSchema)return;if("boolean"==typeof t)return;const a=n.RULES.keywords;for(const r in t)a[r]||d(e,`unknown keyword: "${r}"`)}function n(e,t){if("boolean"==typeof e)return!e;for(const r in e)if(t[r])return!0;return!1}function a(e){return"number"==typeof e?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}function i(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function s({mergeNames:t,mergeToName:r,mergeValues:n,resultToName:a}){return(i,s,o,c)=>{const l=void 0===o?s:o instanceof e.Name?(s instanceof e.Name?t(i,s,o):r(i,s,o),o):s instanceof e.Name?(r(i,o,s),s):n(s,o);return c!==e.Name||l instanceof e.Name?l:a(i,l)}}function o(t,r){if(!0===r)return t.var("props",!0);const n=t.var("props",e._`{}`);return void 0!==r&&c(t,n,r),n}function c(t,r,n){Object.keys(n).forEach(n=>t.assign(e._`${r}${(0,e.getProperty)(n)}`,!0))}mD.toHash=function(e){const t={};for(const r of e)t[r]=!0;return t},mD.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(r(e,t),!n(t,e.self.RULES.all))},mD.checkUnknownRules=r,mD.schemaHasRules=n,mD.schemaHasRulesButRef=function(e,t){if("boolean"==typeof e)return!e;for(const r in e)if("$ref"!==r&&t.all[r])return!0;return!1},mD.schemaRefOrVal=function({topSchemaRef:t,schemaPath:r},n,a,i){if(!i){if("number"==typeof n||"boolean"==typeof n)return n;if("string"==typeof n)return e._`${n}`}return e._`${t}${r}${(0,e.getProperty)(a)}`},mD.unescapeFragment=function(e){return i(decodeURIComponent(e))},mD.escapeFragment=function(e){return encodeURIComponent(a(e))},mD.escapeJsonPointer=a,mD.unescapeJsonPointer=i,mD.eachItem=function(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)},mD.mergeEvaluated={props:s({mergeNames:(t,r,n)=>t.if(e._`${n} !== true && ${r} !== undefined`,()=>{t.if(e._`${r} === true`,()=>t.assign(n,!0),()=>t.assign(n,e._`${n} || {}`).code(e._`Object.assign(${n}, ${r})`))}),mergeToName:(t,r,n)=>t.if(e._`${n} !== true`,()=>{!0===r?t.assign(n,!0):(t.assign(n,e._`${n} || {}`),c(t,n,r))}),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:o}),items:s({mergeNames:(t,r,n)=>t.if(e._`${n} !== true && ${r} !== undefined`,()=>t.assign(n,e._`${r} === true ? true : ${n} > ${r} ? ${n} : ${r}`)),mergeToName:(t,r,n)=>t.if(e._`${n} !== true`,()=>t.assign(n,!0===r||e._`${n} > ${r} ? ${n} : ${r}`)),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},mD.evaluatedPropsToName=o,mD.setEvaluated=c;const l={};var u;function d(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,!0===r)throw new Error(t);e.self.logger.warn(t)}}return mD.useFunc=function(e,r){return e.scopeValue("func",{ref:r,code:l[r.code]||(l[r.code]=new t._Code(r.code))})},function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"}(u||(mD.Type=u={})),mD.getErrorPath=function(t,r,n){if(t instanceof e.Name){const a=r===u.Num;return n?a?e._`"[" + ${t} + "]"`:e._`"['" + ${t} + "']"`:a?e._`"/" + ${t}`:e._`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,e.getProperty)(t).toString():"/"+a(t)},mD.checkStrictMode=d,mD}var fD,gD,yD,vD={};function bD(){if(fD)return vD;fD=1,Object.defineProperty(vD,"__esModule",{value:!0});const e=dD(),t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return vD.default=t,vD}function _D(){return gD||(gD=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=dD(),r=hD(),n=bD();function a(e,r){const a=e.const("err",r);e.if(t._`${n.default.vErrors} === null`,()=>e.assign(n.default.vErrors,t._`[${a}]`),t._`${n.default.vErrors}.push(${a})`),e.code(t._`${n.default.errors}++`)}function i(e,r){const{gen:n,validateName:a,schemaEnv:i}=e;i.$async?n.throw(t._`new ${e.ValidationError}(${r})`):(n.assign(t._`${a}.errors`,r),n.return(!1))}e.keywordError={message:({keyword:e})=>t.str`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:r})=>r?t.str`"${e}" keyword must be ${r} ($data)`:t.str`"${e}" keyword is invalid ($data)`},e.reportError=function(r,n=e.keywordError,s,c){const{it:l}=r,{gen:u,compositeRule:d,allErrors:p}=l,m=o(r,n,s);(null!=c?c:d||p)?a(u,m):i(l,t._`[${m}]`)},e.reportExtraError=function(t,r=e.keywordError,s){const{it:c}=t,{gen:l,compositeRule:u,allErrors:d}=c;a(l,o(t,r,s)),u||d||i(c,n.default.vErrors)},e.resetErrorsCount=function(e,r){e.assign(n.default.errors,r),e.if(t._`${n.default.vErrors} !== null`,()=>e.if(r,()=>e.assign(t._`${n.default.vErrors}.length`,r),()=>e.assign(n.default.vErrors,null)))},e.extendErrors=function({gen:e,keyword:r,schemaValue:a,data:i,errsCount:s,it:o}){if(void 0===s)throw new Error("ajv implementation error");const c=e.name("err");e.forRange("i",s,n.default.errors,s=>{e.const(c,t._`${n.default.vErrors}[${s}]`),e.if(t._`${c}.instancePath === undefined`,()=>e.assign(t._`${c}.instancePath`,(0,t.strConcat)(n.default.instancePath,o.errorPath))),e.assign(t._`${c}.schemaPath`,t.str`${o.errSchemaPath}/${r}`),o.opts.verbose&&(e.assign(t._`${c}.schema`,a),e.assign(t._`${c}.data`,i))})};const s={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function o(e,r,a){const{createErrors:i}=e.it;return!1===i?t._`{}`:function(e,r,a={}){const{gen:i,it:o}=e,u=[c(o,a),l(e,a)];return function(e,{params:r,message:a},i){const{keyword:o,data:c,schemaValue:l,it:u}=e,{opts:d,propertyName:p,topSchemaRef:m,schemaPath:h}=u;i.push([s.keyword,o],[s.params,"function"==typeof r?r(e):r||t._`{}`]),d.messages&&i.push([s.message,"function"==typeof a?a(e):a]);d.verbose&&i.push([s.schema,l],[s.parentSchema,t._`${m}${h}`],[n.default.data,c]);p&&i.push([s.propertyName,p])}(e,r,u),i.object(...u)}(e,r,a)}function c({errorPath:e},{instancePath:a}){const i=a?t.str`${e}${(0,r.getErrorPath)(a,r.Type.Str)}`:e;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,i)]}function l({keyword:e,it:{errSchemaPath:n}},{schemaPath:a,parentSchema:i}){let o=i?n:t.str`${n}/${e}`;return a&&(o=t.str`${o}${(0,r.getErrorPath)(a,r.Type.Str)}`),[s.schemaPath,o]}}(nD)),nD}var wD,SD={},ND={};function kD(){if(wD)return ND;wD=1,Object.defineProperty(ND,"__esModule",{value:!0}),ND.getRules=ND.isJSONType=void 0;const e=new Set(["string","number","integer","boolean","null","object","array"]);return ND.isJSONType=function(t){return"string"==typeof t&&e.has(t)},ND.getRules=function(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}},ND}var xD,ED,PD={};function CD(){if(xD)return PD;function e(e,r){return r.rules.some(r=>t(e,r))}function t(e,t){var r;return void 0!==e[t.keyword]||(null===(r=t.definition.implements)||void 0===r?void 0:r.some(t=>void 0!==e[t]))}return xD=1,Object.defineProperty(PD,"__esModule",{value:!0}),PD.shouldUseRule=PD.shouldUseGroup=PD.schemaHasRulesForType=void 0,PD.schemaHasRulesForType=function({schema:t,self:r},n){const a=r.RULES.types[n];return a&&!0!==a&&e(t,a)},PD.shouldUseGroup=e,PD.shouldUseRule=t,PD}function AD(){if(ED)return SD;ED=1,Object.defineProperty(SD,"__esModule",{value:!0}),SD.reportTypeError=SD.checkDataTypes=SD.checkDataType=SD.coerceAndCheckDataType=SD.getJSONTypes=SD.getSchemaTypes=SD.DataType=void 0;const e=kD(),t=CD(),r=_D(),n=dD(),a=hD();var i;function s(t){const r=Array.isArray(t)?t:t?[t]:[];if(r.every(e.isJSONType))return r;throw new Error("type must be JSONType or JSONType[]: "+r.join(","))}!function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"}(i||(SD.DataType=i={})),SD.getSchemaTypes=function(e){const t=s(e.type);if(t.includes("null")){if(!1===e.nullable)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&void 0!==e.nullable)throw new Error('"nullable" cannot be used without "type"');!0===e.nullable&&t.push("null")}return t},SD.getJSONTypes=s,SD.coerceAndCheckDataType=function(e,r){const{gen:a,data:s,opts:c}=e,u=function(e,t){return t?e.filter(e=>o.has(e)||"array"===t&&"array"===e):[]}(r,c.coerceTypes),p=r.length>0&&!(0===u.length&&1===r.length&&(0,t.schemaHasRulesForType)(e,r[0]));if(p){const t=l(r,s,c.strictNumbers,i.Wrong);a.if(t,()=>{u.length?function(e,t,r){const{gen:a,data:i,opts:s}=e,c=a.let("dataType",n._`typeof ${i}`),u=a.let("coerced",n._`undefined`);"array"===s.coerceTypes&&a.if(n._`${c} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>a.assign(i,n._`${i}[0]`).assign(c,n._`typeof ${i}`).if(l(t,i,s.strictNumbers),()=>a.assign(u,i)));a.if(n._`${u} !== undefined`);for(const e of r)(o.has(e)||"array"===e&&"array"===s.coerceTypes)&&p(e);function p(e){switch(e){case"string":return void a.elseIf(n._`${c} == "number" || ${c} == "boolean"`).assign(u,n._`"" + ${i}`).elseIf(n._`${i} === null`).assign(u,n._`""`);case"number":return void a.elseIf(n._`${c} == "boolean" || ${i} === null
2
+ || (${c} == "string" && ${i} && ${i} == +${i})`).assign(u,n._`+${i}`);case"integer":return void a.elseIf(n._`${c} === "boolean" || ${i} === null
3
+ || (${c} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(u,n._`+${i}`);case"boolean":return void a.elseIf(n._`${i} === "false" || ${i} === 0 || ${i} === null`).assign(u,!1).elseIf(n._`${i} === "true" || ${i} === 1`).assign(u,!0);case"null":return a.elseIf(n._`${i} === "" || ${i} === 0 || ${i} === false`),void a.assign(u,null);case"array":a.elseIf(n._`${c} === "string" || ${c} === "number"
4
+ || ${c} === "boolean" || ${i} === null`).assign(u,n._`[${i}]`)}}a.else(),d(e),a.endIf(),a.if(n._`${u} !== undefined`,()=>{a.assign(i,u),function({gen:e,parentData:t,parentDataProperty:r},a){e.if(n._`${t} !== undefined`,()=>e.assign(n._`${t}[${r}]`,a))}(e,u)})}(e,r,u):d(e)})}return p};const o=new Set(["string","number","integer","boolean","null"]);function c(e,t,r,a=i.Correct){const s=a===i.Correct?n.operators.EQ:n.operators.NEQ;let o;switch(e){case"null":return n._`${t} ${s} null`;case"array":o=n._`Array.isArray(${t})`;break;case"object":o=n._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":o=c(n._`!(${t} % 1) && !isNaN(${t})`);break;case"number":o=c();break;default:return n._`typeof ${t} ${s} ${e}`}return a===i.Correct?o:(0,n.not)(o);function c(e=n.nil){return(0,n.and)(n._`typeof ${t} == "number"`,e,r?n._`isFinite(${t})`:n.nil)}}function l(e,t,r,i){if(1===e.length)return c(e[0],t,r,i);let s;const o=(0,a.toHash)(e);if(o.array&&o.object){const e=n._`typeof ${t} != "object"`;s=o.null?e:n._`!${t} || ${e}`,delete o.null,delete o.array,delete o.object}else s=n.nil;o.number&&delete o.integer;for(const e in o)s=(0,n.and)(s,c(e,t,r,i));return s}SD.checkDataType=c,SD.checkDataTypes=l;const u={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?n._`{type: ${e}}`:n._`{type: ${t}}`};function d(e){const t=function(e){const{gen:t,data:r,schema:n}=e,i=(0,a.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:e}}(e);(0,r.reportError)(t,u)}return SD.reportTypeError=d,SD}var ID,OD={};var TD,$D,zD={},RD={};function LD(){if(TD)return RD;TD=1,Object.defineProperty(RD,"__esModule",{value:!0}),RD.validateUnion=RD.validateArray=RD.usePattern=RD.callValidateCode=RD.schemaProperties=RD.allSchemaProperties=RD.noPropertyInData=RD.propertyInData=RD.isOwnProperty=RD.hasPropFunc=RD.reportMissingProp=RD.checkMissingProp=RD.checkReportMissingProp=void 0;const e=dD(),t=hD(),r=bD(),n=hD();function a(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:e._`Object.prototype.hasOwnProperty`})}function i(t,r,n){return e._`${a(t)}.call(${r}, ${n})`}function s(t,r,n,a){const s=e._`${r}${(0,e.getProperty)(n)} === undefined`;return a?(0,e.or)(s,(0,e.not)(i(t,r,n))):s}function o(e){return e?Object.keys(e).filter(e=>"__proto__"!==e):[]}RD.checkReportMissingProp=function(t,r){const{gen:n,data:a,it:i}=t;n.if(s(n,a,r,i.opts.ownProperties),()=>{t.setParams({missingProperty:e._`${r}`},!0),t.error()})},RD.checkMissingProp=function({gen:t,data:r,it:{opts:n}},a,i){return(0,e.or)(...a.map(a=>(0,e.and)(s(t,r,a,n.ownProperties),e._`${i} = ${a}`)))},RD.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},RD.hasPropFunc=a,RD.isOwnProperty=i,RD.propertyInData=function(t,r,n,a){const s=e._`${r}${(0,e.getProperty)(n)} !== undefined`;return a?e._`${s} && ${i(t,r,n)}`:s},RD.noPropertyInData=s,RD.allSchemaProperties=o,RD.schemaProperties=function(e,r){return o(r).filter(n=>!(0,t.alwaysValidSchema)(e,r[n]))},RD.callValidateCode=function({schemaCode:t,data:n,it:{gen:a,topSchemaRef:i,schemaPath:s,errorPath:o},it:c},l,u,d){const p=d?e._`${t}, ${n}, ${i}${s}`:n,m=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,o)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&m.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const h=e._`${p}, ${a.object(...m)}`;return u!==e.nil?e._`${l}.call(${u}, ${h})`:e._`${l}(${h})`};const c=e._`new RegExp`;return RD.usePattern=function({gen:t,it:{opts:r}},a){const i=r.unicodeRegExp?"u":"",{regExp:s}=r.code,o=s(a,i);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:e._`${"new RegExp"===s.code?c:(0,n.useFunc)(t,s)}(${a}, ${i})`})},RD.validateArray=function(r){const{gen:n,data:a,keyword:i,it:s}=r,o=n.name("valid");if(s.allErrors){const e=n.let("valid",!0);return c(()=>n.assign(e,!1)),e}return n.var(o,!0),c(()=>n.break()),o;function c(s){const c=n.const("len",e._`${a}.length`);n.forRange("i",0,c,a=>{r.subschema({keyword:i,dataProp:a,dataPropType:t.Type.Num},o),n.if((0,e.not)(o),s)})}},RD.validateUnion=function(r){const{gen:n,schema:a,keyword:i,it:s}=r;if(!Array.isArray(a))throw new Error("ajv implementation error");if(a.some(e=>(0,t.alwaysValidSchema)(s,e))&&!s.opts.unevaluated)return;const o=n.let("valid",!1),c=n.name("_valid");n.block(()=>a.forEach((t,a)=>{const s=r.subschema({keyword:i,schemaProp:a,compositeRule:!0},c);n.assign(o,e._`${o} || ${c}`);r.mergeValidEvaluated(s,c)||n.if((0,e.not)(o))})),r.result(o,()=>r.reset(),()=>r.error(!0))},RD}function MD(){if($D)return zD;$D=1,Object.defineProperty(zD,"__esModule",{value:!0}),zD.validateKeywordUsage=zD.validSchemaType=zD.funcKeywordCode=zD.macroKeywordCode=void 0;const e=dD(),t=bD(),r=LD(),n=_D();function a(t){const{gen:r,data:n,it:a}=t;r.if(a.parentData,()=>r.assign(n,e._`${a.parentData}[${a.parentDataProperty}]`))}function i(t,r,n){if(void 0===n)throw new Error(`keyword "${r}" failed to compile`);return t.scopeValue("keyword","function"==typeof n?{ref:n}:{ref:n,code:(0,e.stringify)(n)})}return zD.macroKeywordCode=function(t,r){const{gen:n,keyword:a,schema:s,parentSchema:o,it:c}=t,l=r.macro.call(c.self,s,o,c),u=i(n,a,l);!1!==c.opts.validateSchema&&c.self.validateSchema(l,!0);const d=n.name("valid");t.subschema({schema:l,schemaPath:e.nil,errSchemaPath:`${c.errSchemaPath}/${a}`,topSchemaRef:u,compositeRule:!0},d),t.pass(d,()=>t.error(!0))},zD.funcKeywordCode=function(s,o){var c;const{gen:l,keyword:u,schema:d,parentSchema:p,$data:m,it:h}=s;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(h,o);const f=!m&&o.compile?o.compile.call(h.self,d,p,h):o.validate,g=i(l,u,f),y=l.let("valid");function v(n=(o.async?e._`await `:e.nil)){const a=h.opts.passContext?t.default.this:t.default.self,i=!("compile"in o&&!m||!1===o.schema);l.assign(y,e._`${n}${(0,r.callValidateCode)(s,g,a,i)}`,o.modifying)}function b(t){var r;l.if((0,e.not)(null!==(r=o.valid)&&void 0!==r?r:y),t)}s.block$data(y,function(){if(!1===o.errors)v(),o.modifying&&a(s),b(()=>s.error());else{const r=o.async?function(){const t=l.let("ruleErrs",null);return l.try(()=>v(e._`await `),r=>l.assign(y,!1).if(e._`${r} instanceof ${h.ValidationError}`,()=>l.assign(t,e._`${r}.errors`),()=>l.throw(r))),t}():function(){const t=e._`${g}.errors`;return l.assign(t,null),v(e.nil),t}();o.modifying&&a(s),b(()=>function(r,a){const{gen:i}=r;i.if(e._`Array.isArray(${a})`,()=>{i.assign(t.default.vErrors,e._`${t.default.vErrors} === null ? ${a} : ${t.default.vErrors}.concat(${a})`).assign(t.default.errors,e._`${t.default.vErrors}.length`),(0,n.extendErrors)(r)},()=>r.error())}(s,r))}}),s.ok(null!==(c=o.valid)&&void 0!==c?c:y)},zD.validSchemaType=function(e,t,r=!1){return!t.length||t.some(t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||r&&void 0===e)},zD.validateKeywordUsage=function({schema:e,opts:t,self:r,errSchemaPath:n},a,i){if(Array.isArray(a.keyword)?!a.keyword.includes(i):a.keyword!==i)throw new Error("ajv implementation error");const s=a.dependencies;if(null==s?void 0:s.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(a.validateSchema){if(!a.validateSchema(e[i])){const e=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(a.validateSchema.errors);if("log"!==t.validateSchema)throw new Error(e);r.logger.error(e)}}},zD}var DD,jD={};var FD,UD,qD={};function BD(){return UD||(UD=1,FD=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var n,a,i;if(Array.isArray(t)){if((n=t.length)!=r.length)return!1;for(a=n;0!==a--;)if(!e(t[a],r[a]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((n=(i=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(a=n;0!==a--;)if(!Object.prototype.hasOwnProperty.call(r,i[a]))return!1;for(a=n;0!==a--;){var s=i[a];if(!e(t[s],r[s]))return!1}return!0}return t!=t&&r!=r}),FD}var VD,GD,HD,KD={exports:{}};function WD(){if(VD)return KD.exports;VD=1;var e=KD.exports=function(e,r,n){"function"==typeof r&&(n=r,r={}),t(r,"function"==typeof(n=r.cb||n)?n:n.pre||function(){},n.post||function(){},e,"",e)};function t(n,a,i,s,o,c,l,u,d,p){if(s&&"object"==typeof s&&!Array.isArray(s)){for(var m in a(s,o,c,l,u,d,p),s){var h=s[m];if(Array.isArray(h)){if(m in e.arrayKeywords)for(var f=0;f<h.length;f++)t(n,a,i,h[f],o+"/"+m+"/"+f,c,o,m,s,f)}else if(m in e.propsKeywords){if(h&&"object"==typeof h)for(var g in h)t(n,a,i,h[g],o+"/"+m+"/"+r(g),c,o,m,s,g)}else(m in e.keywords||n.allKeys&&!(m in e.skipKeywords))&&t(n,a,i,h,o+"/"+m,c,o,m,s)}i(s,o,c,l,u,d,p)}}function r(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}return e.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},e.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},e.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},e.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},KD.exports}function ZD(){if(GD)return qD;GD=1,Object.defineProperty(qD,"__esModule",{value:!0}),qD.getSchemaRefs=qD.resolveUrl=qD.normalizeId=qD._getFullPath=qD.getFullPath=qD.inlineRef=void 0;const e=hD(),t=BD(),r=WD(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);qD.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!i(e):!!t&&s(e)<=t)};const a=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function i(e){for(const t in e){if(a.has(t))return!0;const r=e[t];if(Array.isArray(r)&&r.some(i))return!0;if("object"==typeof r&&i(r))return!0}return!1}function s(t){let r=0;for(const a in t){if("$ref"===a)return 1/0;if(r++,!n.has(a)&&("object"==typeof t[a]&&(0,e.eachItem)(t[a],e=>r+=s(e)),r===1/0))return 1/0}return r}function o(e,t="",r){!1!==r&&(t=u(t));const n=e.parse(t);return c(e,n)}function c(e,t){return e.serialize(t).split("#")[0]+"#"}qD.getFullPath=o,qD._getFullPath=c;const l=/#\/?$/;function u(e){return e?e.replace(l,""):""}qD.normalizeId=u,qD.resolveUrl=function(e,t,r){return r=u(r),e.resolve(t,r)};const d=/^[a-z_][-a-z0-9._]*$/i;return qD.getSchemaRefs=function(e,n){if("boolean"==typeof e)return{};const{schemaId:a,uriResolver:i}=this.opts,s=u(e[a]||n),c={"":s},l=o(i,s,!1),p={},m=new Set;return r(e,{allKeys:!0},(e,t,r,n)=>{if(void 0===n)return;const i=l+t;let s=c[n];function o(t){const r=this.opts.uriResolver.resolve;if(t=u(s?r(s,t):t),m.has(t))throw f(t);m.add(t);let n=this.refs[t];return"string"==typeof n&&(n=this.refs[n]),"object"==typeof n?h(e,n.schema,t):t!==u(i)&&("#"===t[0]?(h(e,p[t],t),p[t]=e):this.refs[t]=i),t}function g(e){if("string"==typeof e){if(!d.test(e))throw new Error(`invalid anchor "${e}"`);o.call(this,`#${e}`)}}"string"==typeof e[a]&&(s=o.call(this,e[a])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),c[t]=s}),p;function h(e,r,n){if(void 0!==r&&!t(e,r))throw f(n)}function f(e){return new Error(`reference "${e}" resolves to more than one schema`)}},qD}function JD(){if(HD)return tD;HD=1,Object.defineProperty(tD,"__esModule",{value:!0}),tD.getData=tD.KeywordCxt=tD.validateFunctionCode=void 0;const e=function(){if(yD)return rD;yD=1,Object.defineProperty(rD,"__esModule",{value:!0}),rD.boolOrEmptySchema=rD.topBoolOrEmptySchema=void 0;const e=_D(),t=dD(),r=bD(),n={message:"boolean schema is false"};function a(t,r){const{gen:a,data:i}=t,s={gen:a,keyword:"false schema",data:i,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,e.reportError)(s,n,void 0,r)}return rD.topBoolOrEmptySchema=function(e){const{gen:n,schema:i,validateName:s}=e;!1===i?a(e,!1):"object"==typeof i&&!0===i.$async?n.return(r.default.data):(n.assign(t._`${s}.errors`,null),n.return(!0))},rD.boolOrEmptySchema=function(e,t){const{gen:r,schema:n}=e;!1===n?(r.var(t,!1),a(e)):r.var(t,!0)},rD}(),t=AD(),r=CD(),n=AD(),a=function(){if(ID)return OD;ID=1,Object.defineProperty(OD,"__esModule",{value:!0}),OD.assignDefaults=void 0;const e=dD(),t=hD();function r(r,n,a){const{gen:i,compositeRule:s,data:o,opts:c}=r;if(void 0===a)return;const l=e._`${o}${(0,e.getProperty)(n)}`;if(s)return void(0,t.checkStrictMode)(r,`default is ignored for: ${l}`);let u=e._`${l} === undefined`;"empty"===c.useDefaults&&(u=e._`${u} || ${l} === null || ${l} === ""`),i.if(u,e._`${l} = ${(0,e.stringify)(a)}`)}return OD.assignDefaults=function(e,t){const{properties:n,items:a}=e.schema;if("object"===t&&n)for(const t in n)r(e,t,n[t].default);else"array"===t&&Array.isArray(a)&&a.forEach((t,n)=>r(e,n,t.default))},OD}(),i=MD(),s=function(){if(DD)return jD;DD=1,Object.defineProperty(jD,"__esModule",{value:!0}),jD.extendSubschemaMode=jD.extendSubschemaData=jD.getSubschema=void 0;const e=dD(),t=hD();return jD.getSubschema=function(r,{keyword:n,schemaProp:a,schema:i,schemaPath:s,errSchemaPath:o,topSchemaRef:c}){if(void 0!==n&&void 0!==i)throw new Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==n){const i=r.schema[n];return void 0===a?{schema:i,schemaPath:e._`${r.schemaPath}${(0,e.getProperty)(n)}`,errSchemaPath:`${r.errSchemaPath}/${n}`}:{schema:i[a],schemaPath:e._`${r.schemaPath}${(0,e.getProperty)(n)}${(0,e.getProperty)(a)}`,errSchemaPath:`${r.errSchemaPath}/${n}/${(0,t.escapeFragment)(a)}`}}if(void 0!==i){if(void 0===s||void 0===o||void 0===c)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:i,schemaPath:s,topSchemaRef:c,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')},jD.extendSubschemaData=function(r,n,{dataProp:a,dataPropType:i,data:s,dataTypes:o,propertyName:c}){if(void 0!==s&&void 0!==a)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:l}=n;if(void 0!==a){const{errorPath:s,dataPathArr:o,opts:c}=n;u(l.let("data",e._`${n.data}${(0,e.getProperty)(a)}`,!0)),r.errorPath=e.str`${s}${(0,t.getErrorPath)(a,i,c.jsPropertySyntax)}`,r.parentDataProperty=e._`${a}`,r.dataPathArr=[...o,r.parentDataProperty]}function u(e){r.data=e,r.dataLevel=n.dataLevel+1,r.dataTypes=[],n.definedProperties=new Set,r.parentData=n.data,r.dataNames=[...n.dataNames,e]}void 0!==s&&(u(s instanceof e.Name?s:l.let("data",s,!0)),void 0!==c&&(r.propertyName=c)),o&&(r.dataTypes=o)},jD.extendSubschemaMode=function(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:a,allErrors:i}){void 0!==n&&(e.compositeRule=n),void 0!==a&&(e.createErrors=a),void 0!==i&&(e.allErrors=i),e.jtdDiscriminator=t,e.jtdMetadata=r},jD}(),o=dD(),c=bD(),l=ZD(),u=hD(),d=_D();function p({gen:e,validateName:t,schema:r,schemaEnv:n,opts:a},i){a.code.es5?e.func(t,o._`${c.default.data}, ${c.default.valCxt}`,n.$async,()=>{e.code(o._`"use strict"; ${m(r,a)}`),function(e,t){e.if(c.default.valCxt,()=>{e.var(c.default.instancePath,o._`${c.default.valCxt}.${c.default.instancePath}`),e.var(c.default.parentData,o._`${c.default.valCxt}.${c.default.parentData}`),e.var(c.default.parentDataProperty,o._`${c.default.valCxt}.${c.default.parentDataProperty}`),e.var(c.default.rootData,o._`${c.default.valCxt}.${c.default.rootData}`),t.dynamicRef&&e.var(c.default.dynamicAnchors,o._`${c.default.valCxt}.${c.default.dynamicAnchors}`)},()=>{e.var(c.default.instancePath,o._`""`),e.var(c.default.parentData,o._`undefined`),e.var(c.default.parentDataProperty,o._`undefined`),e.var(c.default.rootData,c.default.data),t.dynamicRef&&e.var(c.default.dynamicAnchors,o._`{}`)})}(e,a),e.code(i)}):e.func(t,o._`${c.default.data}, ${function(e){return o._`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${e.dynamicRef?o._`, ${c.default.dynamicAnchors}={}`:o.nil}}={}`}(a)}`,n.$async,()=>e.code(m(r,a)).code(i))}function m(e,t){const r="object"==typeof e&&e[t.schemaId];return r&&(t.code.source||t.code.process)?o._`/*# sourceURL=${r} */`:o.nil}function h(t,r){g(t)&&(y(t),f(t))?function(e,t){const{schema:r,gen:n,opts:a}=e;a.$comment&&r.$comment&&b(e);(function(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,l.resolveUrl)(e.opts.uriResolver,e.baseId,t))})(e),function(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}(e);const i=n.const("_errs",c.default.errors);v(e,i),n.var(t,o._`${i} === ${c.default.errors}`)}(t,r):(0,e.boolOrEmptySchema)(t,r)}function f({schema:e,self:t}){if("boolean"==typeof e)return!e;for(const r in e)if(t.RULES.all[r])return!0;return!1}function g(e){return"boolean"!=typeof e.schema}function y(e){(0,u.checkUnknownRules)(e),function(e){const{schema:t,errSchemaPath:r,opts:n,self:a}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(t,a.RULES)&&a.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}(e)}function v(e,r){if(e.opts.jtd)return _(e,[],!1,r);const n=(0,t.getSchemaTypes)(e.schema);_(e,n,!(0,t.coerceAndCheckDataType)(e,n),r)}function b({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:a}){const i=r.$comment;if(!0===a.$comment)e.code(o._`${c.default.self}.logger.log(${i})`);else if("function"==typeof a.$comment){const r=o.str`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code(o._`${c.default.self}.opts.$comment(${i}, ${r}, ${a}.schema)`)}}function _(e,t,a,i){const{gen:s,schema:l,data:d,allErrors:p,opts:m,self:h}=e,{RULES:f}=h;function g(u){(0,r.shouldUseGroup)(l,u)&&(u.type?(s.if((0,n.checkDataType)(u.type,d,m.strictNumbers)),w(e,u),1===t.length&&t[0]===u.type&&a&&(s.else(),(0,n.reportTypeError)(e)),s.endIf()):w(e,u),p||s.if(o._`${c.default.errors} === ${i||0}`))}!l.$ref||!m.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(l,f)?(m.jtd||function(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;(function(e,t){if(!t.length)return;if(!e.dataTypes.length)return void(e.dataTypes=t);t.forEach(t=>{N(e.dataTypes,t)||k(e,`type "${t}" not allowed by context "${e.dataTypes.join(",")}"`)}),function(e,t){const r=[];for(const n of e.dataTypes)N(t,n)?r.push(n):t.includes("integer")&&"number"===n&&r.push("integer");e.dataTypes=r}(e,t)})(e,t),e.opts.allowUnionTypes||function(e,t){t.length>1&&(2!==t.length||!t.includes("null"))&&k(e,"use allowUnionTypes to allow union type keyword")}(e,t);!function(e,t){const n=e.self.RULES.all;for(const a in n){const i=n[a];if("object"==typeof i&&(0,r.shouldUseRule)(e.schema,i)){const{type:r}=i.definition;r.length&&!r.some(e=>S(t,e))&&k(e,`missing type "${r.join(",")}" for keyword "${a}"`)}}}(e,e.dataTypes)}(e,t),s.block(()=>{for(const e of f.rules)g(e);g(f.post)})):s.block(()=>E(e,"$ref",f.all.$ref.definition))}function w(e,t){const{gen:n,schema:i,opts:{useDefaults:s}}=e;s&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(const n of t.rules)(0,r.shouldUseRule)(i,n)&&E(e,n.keyword,n.definition,t.type)})}function S(e,t){return e.includes(t)||"number"===t&&e.includes("integer")}function N(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function k(e,t){t+=` at "${e.schemaEnv.baseId+e.errSchemaPath}" (strictTypes)`,(0,u.checkStrictMode)(e,t,e.opts.strictTypes)}tD.validateFunctionCode=function(t){g(t)&&(y(t),f(t))?function(e){const{schema:t,opts:r,gen:n}=e;p(e,()=>{r.$comment&&t.$comment&&b(e),function(e){const{schema:t,opts:r}=e;void 0!==t.default&&r.useDefaults&&r.strictSchema&&(0,u.checkStrictMode)(e,"default is ignored in the schema root")}(e),n.let(c.default.vErrors,null),n.let(c.default.errors,0),r.unevaluated&&function(e){const{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",o._`${r}.evaluated`),t.if(o._`${e.evaluated}.dynamicProps`,()=>t.assign(o._`${e.evaluated}.props`,o._`undefined`)),t.if(o._`${e.evaluated}.dynamicItems`,()=>t.assign(o._`${e.evaluated}.items`,o._`undefined`))}(e),v(e),function(e){const{gen:t,schemaEnv:r,validateName:n,ValidationError:a,opts:i}=e;r.$async?t.if(o._`${c.default.errors} === 0`,()=>t.return(c.default.data),()=>t.throw(o._`new ${a}(${c.default.vErrors})`)):(t.assign(o._`${n}.errors`,c.default.vErrors),i.unevaluated&&function({gen:e,evaluated:t,props:r,items:n}){r instanceof o.Name&&e.assign(o._`${t}.props`,r);n instanceof o.Name&&e.assign(o._`${t}.items`,n)}(e),t.return(o._`${c.default.errors} === 0`))}(e)})}(t):p(t,()=>(0,e.topBoolOrEmptySchema)(t))};class x{constructor(e,t,r){if((0,i.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",A(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,i.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:!1!==t.errors)&&(this.errsCount=e.gen.const("_errs",c.default.errors))}result(e,t,r){this.failResult((0,o.not)(e),t,r)}failResult(e,t,r){this.gen.if(e),r?r():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,o.not)(e),void 0,t)}fail(e){if(void 0===e)return this.error(),void(this.allErrors||this.gen.if(!1));this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:t}=this;this.fail(o._`${t} !== undefined && (${(0,o.or)(this.invalid$data(),e)})`)}error(e,t,r){if(t)return this.setParams(t),this._error(e,r),void this.setParams({});this._error(e,r)}_error(e,t){(e?d.reportExtraError:d.reportError)(this,this.def.error,t)}$dataError(){(0,d.reportError)(this,this.def.$dataError||d.keyword$DataError)}reset(){if(void 0===this.errsCount)throw new Error('add "trackErrors" to keyword definition');(0,d.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,r=o.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=o.nil,t=o.nil){if(!this.$data)return;const{gen:r,schemaCode:n,schemaType:a,def:i}=this;r.if((0,o.or)(o._`${n} === undefined`,t)),e!==o.nil&&r.assign(e,!0),(a.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==o.nil&&r.assign(e,!1)),r.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:r,def:a,it:i}=this;return(0,o.or)(function(){if(r.length){if(!(t instanceof o.Name))throw new Error("ajv implementation error");const e=Array.isArray(r)?r:[r];return o._`${(0,n.checkDataTypes)(e,t,i.opts.strictNumbers,n.DataType.Wrong)}`}return o.nil}(),function(){if(a.validateSchema){const r=e.scopeValue("validate$data",{ref:a.validateSchema});return o._`!${r}(${t})`}return o.nil}())}subschema(e,t){const r=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(r,this.it,e),(0,s.extendSubschemaMode)(r,e);const n={...this.it,...r,items:void 0,props:void 0};return h(n,t),n}mergeEvaluated(e,t){const{it:r,gen:n}=this;r.opts.unevaluated&&(!0!==r.props&&void 0!==e.props&&(r.props=u.mergeEvaluated.props(n,e.props,r.props,t)),!0!==r.items&&void 0!==e.items&&(r.items=u.mergeEvaluated.items(n,e.items,r.items,t)))}mergeValidEvaluated(e,t){const{it:r,gen:n}=this;if(r.opts.unevaluated&&(!0!==r.props||!0!==r.items))return n.if(t,()=>this.mergeEvaluated(e,o.Name)),!0}}function E(e,t,r,n){const a=new x(e,r,t);"code"in r?r.code(a,n):a.$data&&r.validate?(0,i.funcKeywordCode)(a,r):"macro"in r?(0,i.macroKeywordCode)(a,r):(r.compile||r.validate)&&(0,i.funcKeywordCode)(a,r)}tD.KeywordCxt=x;const P=/^\/(?:[^~]|~0|~1)*$/,C=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function A(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let a,i;if(""===e)return c.default.rootData;if("/"===e[0]){if(!P.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);a=e,i=c.default.rootData}else{const s=C.exec(e);if(!s)throw new Error(`Invalid JSON-pointer: ${e}`);const o=+s[1];if(a=s[2],"#"===a){if(o>=t)throw new Error(d("property/index",o));return n[t-o]}if(o>t)throw new Error(d("data",o));if(i=r[t-o],!a)return i}let s=i;const l=a.split("/");for(const e of l)e&&(i=o._`${i}${(0,o.getProperty)((0,u.unescapeJsonPointer)(e))}`,s=o._`${s} && ${i}`);return s;function d(e,r){return`Cannot access ${e} ${r} levels up, current level is ${t}`}}return tD.getData=A,tD}var YD,QD={};function XD(){if(YD)return QD;YD=1,Object.defineProperty(QD,"__esModule",{value:!0});class e extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}return QD.default=e,QD}var ej,tj={};function rj(){if(ej)return tj;ej=1,Object.defineProperty(tj,"__esModule",{value:!0});const e=ZD();class t extends Error{constructor(t,r,n,a){super(a||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,e.resolveUrl)(t,r,n),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(t,this.missingRef))}}return tj.default=t,tj}var nj,aj={};function ij(){if(nj)return aj;nj=1,Object.defineProperty(aj,"__esModule",{value:!0}),aj.resolveSchema=aj.getCompilingSchema=aj.resolveRef=aj.compileSchema=aj.SchemaEnv=void 0;const e=dD(),t=XD(),r=bD(),n=ZD(),a=hD(),i=JD();class s{constructor(e){var t;let r;this.refs={},this.dynamicAnchors={},"object"==typeof e.schema&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=null!==(t=e.baseId)&&void 0!==t?t:(0,n.normalizeId)(null==r?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=null==r?void 0:r.$async,this.refs={}}}function o(a){const s=l.call(this,a);if(s)return s;const o=(0,n.getFullPath)(this.opts.uriResolver,a.root.baseId),{es5:c,lines:u}=this.opts.code,{ownProperties:d}=this.opts,p=new e.CodeGen(this.scope,{es5:c,lines:u,ownProperties:d});let m;a.$async&&(m=p.scopeValue("Error",{ref:t.default,code:e._`require("ajv/dist/runtime/validation_error").default`}));const h=p.scopeName("validate");a.validateName=h;const f={gen:p,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[e.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:p.scopeValue("schema",!0===this.opts.code.source?{ref:a.schema,code:(0,e.stringify)(a.schema)}:{ref:a.schema}),validateName:h,ValidationError:m,schema:a.schema,schemaEnv:a,rootId:o,baseId:a.baseId||o,schemaPath:e.nil,errSchemaPath:a.schemaPath||(this.opts.jtd?"":"#"),errorPath:e._`""`,opts:this.opts,self:this};let g;try{this._compilations.add(a),(0,i.validateFunctionCode)(f),p.optimize(this.opts.code.optimize);const t=p.toString();g=`${p.scopeRefs(r.default.scope)}return ${t}`,this.opts.code.process&&(g=this.opts.code.process(g,a));const n=new Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(h,{ref:n}),n.errors=null,n.schema=a.schema,n.schemaEnv=a,a.$async&&(n.$async=!0),!0===this.opts.code.source&&(n.source={validateName:h,validateCode:t,scopeValues:p._values}),this.opts.unevaluated){const{props:t,items:r}=f;n.evaluated={props:t instanceof e.Name?void 0:t,items:r instanceof e.Name?void 0:r,dynamicProps:t instanceof e.Name,dynamicItems:r instanceof e.Name},n.source&&(n.source.evaluated=(0,e.stringify)(n.evaluated))}return a.validate=n,a}catch(e){throw delete a.validate,delete a.validateName,g&&this.logger.error("Error compiling schema, function code:",g),e}finally{this._compilations.delete(a)}}function c(e){return(0,n.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:o.call(this,e)}function l(e){for(const t of this._compilations)if(u(t,e))return t}function u(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function d(e,t){let r;for(;"string"==typeof(r=this.refs[t]);)t=r;return r||this.schemas[t]||p.call(this,e,t)}function p(e,t){const r=this.opts.uriResolver.parse(t),a=(0,n._getFullPath)(this.opts.uriResolver,r);let i=(0,n.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&a===i)return h.call(this,r,e);const c=(0,n.normalizeId)(a),l=this.refs[c]||this.schemas[c];if("string"==typeof l){const t=p.call(this,e,l);if("object"!=typeof(null==t?void 0:t.schema))return;return h.call(this,r,t)}if("object"==typeof(null==l?void 0:l.schema)){if(l.validate||o.call(this,l),c===(0,n.normalizeId)(t)){const{schema:t}=l,{schemaId:r}=this.opts,a=t[r];return a&&(i=(0,n.resolveUrl)(this.opts.uriResolver,i,a)),new s({schema:t,schemaId:r,root:e,baseId:i})}return h.call(this,r,l)}}aj.SchemaEnv=s,aj.compileSchema=o,aj.resolveRef=function(e,t,r){var a;r=(0,n.resolveUrl)(this.opts.uriResolver,t,r);const i=e.refs[r];if(i)return i;let o=d.call(this,e,r);if(void 0===o){const n=null===(a=e.localRefs)||void 0===a?void 0:a[r],{schemaId:i}=this.opts;n&&(o=new s({schema:n,schemaId:i,root:e,baseId:t}))}return void 0!==o?e.refs[r]=c.call(this,o):void 0},aj.getCompilingSchema=l,aj.resolveSchema=p;const m=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function h(e,{baseId:t,schema:r,root:i}){var o;if("/"!==(null===(o=e.fragment)||void 0===o?void 0:o[0]))return;for(const i of e.fragment.slice(1).split("/")){if("boolean"==typeof r)return;const e=r[(0,a.unescapeFragment)(i)];if(void 0===e)return;const s="object"==typeof(r=e)&&r[this.opts.schemaId];!m.has(i)&&s&&(t=(0,n.resolveUrl)(this.opts.uriResolver,t,s))}let c;if("boolean"!=typeof r&&r.$ref&&!(0,a.schemaHasRulesButRef)(r,this.RULES)){const e=(0,n.resolveUrl)(this.opts.uriResolver,t,r.$ref);c=p.call(this,i,e)}const{schemaId:l}=this.opts;return c=c||new s({schema:r,schemaId:l,root:i,baseId:t}),c.schema!==c.root.schema?c:void 0}return aj}var sj,oj,cj,lj,uj,dj,pj,mj={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1},hj={},fj={exports:{}};function gj(){if(oj)return sj;oj=1;const e=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),t=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function r(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),48!==r){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function a(e){return e.length=0,!0}function i(e,t,n){if(e.length){const a=r(e);if(""===a)return n.error=!0,!1;t.push(a),e.length=0}return!0}function s(e){if(function(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}(e,":")<2)return{host:e,isIPV6:!1};const t=function(e){let t=0;const n={error:!1,address:"",zone:""},s=[],o=[];let c=!1,l=!1,u=i;for(let r=0;r<e.length;r++){const i=e[r];if("["!==i&&"]"!==i)if(":"!==i)if("%"===i){if(!u(o,s,n))break;u=a}else o.push(i);else{if(!0===c&&(l=!0),!u(o,s,n))break;if(++t>7){n.error=!0;break}r>0&&":"===e[r-1]&&(c=!0),s.push(":")}}return o.length&&(u===a?n.zone=o.join(""):l?s.push(o.join("")):s.push(r(o))),n.address=s.join(""),n}(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,r=t.address;return t.zone&&(e+="%"+t.zone,r+="%25"+t.zone),{host:e,isIPV6:!0,escapedHost:r}}}return sj={nonSimpleDomain:n,recomposeAuthority:function(e){const r=[];if(void 0!==e.userinfo&&(r.push(e.userinfo),r.push("@")),void 0!==e.host){let n=unescape(e.host);if(!t(n)){const t=s(n);n=!0===t.isIPV6?`[${t.escapedHost}]`:e.host}r.push(n)}return"number"!=typeof e.port&&"string"!=typeof e.port||(r.push(":"),r.push(String(e.port))),r.length?r.join(""):void 0},normalizeComponentEncoding:function(e,t){const r=!0!==t?escape:unescape;return void 0!==e.scheme&&(e.scheme=r(e.scheme)),void 0!==e.userinfo&&(e.userinfo=r(e.userinfo)),void 0!==e.host&&(e.host=r(e.host)),void 0!==e.path&&(e.path=r(e.path)),void 0!==e.query&&(e.query=r(e.query)),void 0!==e.fragment&&(e.fragment=r(e.fragment)),e},removeDotSegments:function(e){let t=e;const r=[];let n=-1,a=0;for(;a=t.length;){if(1===a){if("."===t)break;if("/"===t){r.push("/");break}r.push(t);break}if(2===a){if("."===t[0]){if("."===t[1])break;if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&("."===t[1]||"/"===t[1])){r.push("/");break}}else if(3===a&&"/.."===t){0!==r.length&&r.pop(),r.push("/");break}if("."===t[0]){if("."===t[1]){if("/"===t[2]){t=t.slice(3);continue}}else if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&"."===t[1]){if("/"===t[2]){t=t.slice(2);continue}if("."===t[2]&&"/"===t[3]){t=t.slice(3),0!==r.length&&r.pop();continue}}if(-1===(n=t.indexOf("/",1))){r.push(t);break}r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")},isIPv4:t,isUUID:e,normalizeIPv6:s,stringArrayToHexStripped:r},sj}function yj(){if(uj)return fj.exports;uj=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:a,nonSimpleDomain:i}=gj(),{SCHEMES:s,getSchemeHandler:o}=function(){if(lj)return cj;lj=1;const{isUUID:e}=gj(),t=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(e){return!0===e.secure||!1!==e.secure&&!!e.scheme&&!(3!==e.scheme.length||"w"!==e.scheme[0]&&"W"!==e.scheme[0]||"s"!==e.scheme[1]&&"S"!==e.scheme[1]||"s"!==e.scheme[2]&&"S"!==e.scheme[2])}function a(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function i(e){const t="https"===String(e.scheme).toLowerCase();return e.port!==(t?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}const s={scheme:"http",domainHost:!0,parse:a,serialize:i},o={scheme:"ws",domainHost:!0,parse:function(e){return e.secure=n(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e},serialize:function(e){if(e.port!==(n(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){const[t,r]=e.resourceName.split("?");e.path=t&&"/"!==t?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}},c={http:s,https:{scheme:"https",domainHost:s.domainHost,parse:a,serialize:i},ws:o,wss:{scheme:"wss",domainHost:o.domainHost,parse:o.parse,serialize:o.serialize},urn:{scheme:"urn",parse:function(e,r){if(!e.path)return e.error="URN can not be parsed",e;const n=e.path.match(t);if(n){const t=r.scheme||e.scheme||"urn";e.nid=n[1].toLowerCase(),e.nss=n[2];const a=l(`${t}:${r.nid||e.nid}`);e.path=void 0,a&&(e=a.parse(e,r))}else e.error=e.error||"URN can not be parsed.";return e},serialize:function(e,t){if(void 0===e.nid)throw new Error("URN without nid cannot be serialized");const r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),a=l(`${r}:${t.nid||n}`);a&&(e=a.serialize(e,t));const i=e,s=e.nss;return i.path=`${n||t.nid}:${s}`,t.skipEscape=!0,i},skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:function(t,r){const n=t;return n.uuid=n.nss,n.nss=void 0,r.tolerant||n.uuid&&e(n.uuid)||(n.error=n.error||"UUID is not valid."),n},serialize:function(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t},skipNormalize:!0}};function l(e){return e&&(c[e]||c[e.toLowerCase()])||void 0}return Object.setPrototypeOf(c,null),cj={wsIsSecure:n,SCHEMES:c,isValidSchemeName:function(e){return-1!==r.indexOf(e)},getSchemeHandler:l}}();function c(e,r,n,a){const i={};return a||(e=d(l(e,n),n),r=d(l(r,n),n)),!(n=n||{}).tolerant&&r.scheme?(i.scheme=r.scheme,i.userinfo=r.userinfo,i.host=r.host,i.port=r.port,i.path=t(r.path||""),i.query=r.query):(void 0!==r.userinfo||void 0!==r.host||void 0!==r.port?(i.userinfo=r.userinfo,i.host=r.host,i.port=r.port,i.path=t(r.path||""),i.query=r.query):(r.path?("/"===r.path[0]?i.path=t(r.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?i.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+r.path:i.path=r.path:i.path="/"+r.path,i.path=t(i.path)),i.query=r.query):(i.path=e.path,void 0!==r.query?i.query=r.query:i.query=e.query),i.userinfo=e.userinfo,i.host=e.host,i.port=e.port),i.scheme=e.scheme),i.fragment=r.fragment,i}function l(e,n){const a={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},i=Object.assign({},n),s=[],c=o(i.scheme||a.scheme);c&&c.serialize&&c.serialize(a,i),void 0!==a.path&&(i.skipEscape?a.path=unescape(a.path):(a.path=escape(a.path),void 0!==a.scheme&&(a.path=a.path.split("%3A").join(":")))),"suffix"!==i.reference&&a.scheme&&s.push(a.scheme,":");const l=r(a);if(void 0!==l&&("suffix"!==i.reference&&s.push("//"),s.push(l),a.path&&"/"!==a.path[0]&&s.push("/")),void 0!==a.path){let e=a.path;i.absolutePath||c&&c.absolutePath||(e=t(e)),void 0===l&&"/"===e[0]&&"/"===e[1]&&(e="/%2F"+e.slice(2)),s.push(e)}return void 0!==a.query&&s.push("?",a.query),void 0!==a.fragment&&s.push("#",a.fragment),s.join("")}const u=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function d(t,r){const n=Object.assign({},r),s={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let c=!1;"suffix"===n.reference&&(t=n.scheme?n.scheme+":"+t:"//"+t);const l=t.match(u);if(l){if(s.scheme=l[1],s.userinfo=l[3],s.host=l[4],s.port=parseInt(l[5],10),s.path=l[6]||"",s.query=l[7],s.fragment=l[8],isNaN(s.port)&&(s.port=l[5]),s.host){if(!1===a(s.host)){const t=e(s.host);s.host=t.host.toLowerCase(),c=t.isIPV6}else c=!0}void 0!==s.scheme||void 0!==s.userinfo||void 0!==s.host||void 0!==s.port||void 0!==s.query||s.path?void 0===s.scheme?s.reference="relative":void 0===s.fragment?s.reference="absolute":s.reference="uri":s.reference="same-document",n.reference&&"suffix"!==n.reference&&n.reference!==s.reference&&(s.error=s.error||"URI is not a "+n.reference+" reference.");const r=o(n.scheme||s.scheme);if(!(n.unicodeSupport||r&&r.unicodeSupport)&&s.host&&(n.domainHost||r&&r.domainHost)&&!1===c&&i(s.host))try{s.host=URL.domainToASCII(s.host.toLowerCase())}catch(e){s.error=s.error||"Host's domain name can not be converted to ASCII: "+e}(!r||r&&!r.skipNormalize)&&(-1!==t.indexOf("%")&&(void 0!==s.scheme&&(s.scheme=unescape(s.scheme)),void 0!==s.host&&(s.host=unescape(s.host))),s.path&&(s.path=escape(unescape(s.path))),s.fragment&&(s.fragment=encodeURI(decodeURIComponent(s.fragment)))),r&&r.parse&&r.parse(s,n)}else s.error=s.error||"URI can not be parsed.";return s}const p={SCHEMES:s,normalize:function(e,t){return"string"==typeof e?e=l(d(e,t),t):"object"==typeof e&&(e=d(l(e,t),t)),e},resolve:function(e,t,r){const n=r?Object.assign({scheme:"null"},r):{scheme:"null"},a=c(d(e,n),d(t,n),n,!0);return n.skipEscape=!0,l(a,n)},resolveComponent:c,equal:function(e,t,r){return"string"==typeof e?(e=unescape(e),e=l(n(d(e,r),!0),{...r,skipEscape:!0})):"object"==typeof e&&(e=l(n(e,!0),{...r,skipEscape:!0})),"string"==typeof t?(t=unescape(t),t=l(n(d(t,r),!0),{...r,skipEscape:!0})):"object"==typeof t&&(t=l(n(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()},serialize:l,parse:d};return fj.exports=p,fj.exports.default=p,fj.exports.fastUri=p,fj.exports}function vj(){return pj||(pj=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=JD();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=dD();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const n=XD(),a=rj(),i=kD(),s=ij(),o=dD(),c=ZD(),l=AD(),u=hD(),d=mj,p=function(){if(dj)return hj;dj=1,Object.defineProperty(hj,"__esModule",{value:!0});const e=yj();return e.code='require("ajv/dist/runtime/uri").default',hj.default=e,hj}(),m=(e,t)=>new RegExp(e,t);m.code="new RegExp";const h=["removeAdditional","useDefaults","coerceTypes"],f=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),g={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},y={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};function v(e){var t,r,n,a,i,s,o,c,l,u,d,h,f,g,y,v,b,_,w,S,N,k,x,E,P;const C=e.strict,A=null===(t=e.code)||void 0===t?void 0:t.optimize,I=!0===A||void 0===A?1:A||0,O=null!==(n=null===(r=e.code)||void 0===r?void 0:r.regExp)&&void 0!==n?n:m,T=null!==(a=e.uriResolver)&&void 0!==a?a:p.default;return{strictSchema:null===(s=null!==(i=e.strictSchema)&&void 0!==i?i:C)||void 0===s||s,strictNumbers:null===(c=null!==(o=e.strictNumbers)&&void 0!==o?o:C)||void 0===c||c,strictTypes:null!==(u=null!==(l=e.strictTypes)&&void 0!==l?l:C)&&void 0!==u?u:"log",strictTuples:null!==(h=null!==(d=e.strictTuples)&&void 0!==d?d:C)&&void 0!==h?h:"log",strictRequired:null!==(g=null!==(f=e.strictRequired)&&void 0!==f?f:C)&&void 0!==g&&g,code:e.code?{...e.code,optimize:I,regExp:O}:{optimize:I,regExp:O},loopRequired:null!==(y=e.loopRequired)&&void 0!==y?y:200,loopEnum:null!==(v=e.loopEnum)&&void 0!==v?v:200,meta:null===(b=e.meta)||void 0===b||b,messages:null===(_=e.messages)||void 0===_||_,inlineRefs:null===(w=e.inlineRefs)||void 0===w||w,schemaId:null!==(S=e.schemaId)&&void 0!==S?S:"$id",addUsedSchema:null===(N=e.addUsedSchema)||void 0===N||N,validateSchema:null===(k=e.validateSchema)||void 0===k||k,validateFormats:null===(x=e.validateFormats)||void 0===x||x,unicodeRegExp:null===(E=e.unicodeRegExp)||void 0===E||E,int32range:null===(P=e.int32range)||void 0===P||P,uriResolver:T}}class b{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};const{es5:t,lines:r}=this.opts.code;this.scope=new o.ValueScope({scope:{},prefixes:f,es5:t,lines:r}),this.logger=function(e){if(!1===e)return E;if(void 0===e)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}(e.logger);const n=e.validateFormats;e.validateFormats=!1,this.RULES=(0,i.getRules)(),_.call(this,g,e,"NOT SUPPORTED"),_.call(this,y,e,"DEPRECATED","warn"),this._metaOpts=x.call(this),e.formats&&N.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&k.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=n}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:e,meta:t,schemaId:r}=this.opts;let n=d;"id"===r&&(n={...d},n.id=n.$id,delete n.$id),t&&e&&this.addMetaSchema(n,n[r],!1)}defaultMeta(){const{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta="object"==typeof e?e[t]||e:void 0}validate(e,t){let r;if("string"==typeof e){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);const n=r(t);return"$async"in r||(this.errors=r.errors),n}compile(e,t){const r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if("function"!=typeof this.opts.loadSchema)throw new Error("options.loadSchema should be a function");const{loadSchema:r}=this.opts;return n.call(this,e,t);async function n(e,t){await i.call(this,e.$schema);const r=this._addSchema(e,t);return r.validate||s.call(this,r)}async function i(e){e&&!this.getSchema(e)&&await n.call(this,{$ref:e},!0)}async function s(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof a.default))throw t;return o.call(this,t),await c.call(this,t.missingSchema),s.call(this,e)}}function o({missingSchema:e,missingRef:t}){if(this.refs[e])throw new Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){const r=await l.call(this,e);this.refs[e]||await i.call(this,r.$schema),this.refs[e]||this.addSchema(r,e,t)}async function l(e){const t=this._loading[e];if(t)return t;try{return await(this._loading[e]=r(e))}finally{delete this._loading[e]}}}addSchema(e,t,r,n=this.opts.validateSchema){if(Array.isArray(e)){for(const t of e)this.addSchema(t,void 0,r,n);return this}let a;if("object"==typeof e){const{schemaId:t}=this.opts;if(a=e[t],void 0!==a&&"string"!=typeof a)throw new Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||a),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,n,!0),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if("boolean"==typeof e)return!0;let r;if(r=e.$schema,void 0!==r&&"string"!=typeof r)throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const n=this.validate(r,e);if(!n&&t){const e="schema is invalid: "+this.errorsText();if("log"!==this.opts.validateSchema)throw new Error(e);this.logger.error(e)}return n}getSchema(e){let t;for(;"string"==typeof(t=w.call(this,e));)e=t;if(void 0===t){const{schemaId:r}=this.opts,n=new s.SchemaEnv({schema:{},schemaId:r});if(t=s.resolveSchema.call(this,n,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const t=w.call(this,e);return"object"==typeof t&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{const t=e;this._cache.delete(t);let r=e[this.opts.schemaId];return r&&(r=(0,c.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(const t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if("string"==typeof e)r=e,"object"==typeof t&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r);else{if("object"!=typeof e||void 0!==t)throw new Error("invalid addKeywords parameters");if(r=(t=e).keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}if(C.call(this,r,t),!t)return(0,u.eachItem)(r,e=>A.call(this,e)),this;O.call(this,t);const n={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(r,0===n.type.length?e=>A.call(this,e,n):e=>n.type.forEach(t=>A.call(this,e,n,t))),this}getKeyword(e){const t=this.RULES.all[e];return"object"==typeof t?t.definition:!!t}removeKeyword(e){const{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(const r of t.rules){const t=r.rules.findIndex(t=>t.keyword===e);t>=0&&r.rules.splice(t,1)}return this}addFormat(e,t){return"string"==typeof t&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){return e&&0!==e.length?e.map(e=>`${r}${e.instancePath} ${e.message}`).reduce((e,r)=>e+t+r):"No errors"}$dataMetaSchema(e,t){const r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(const n of t){const t=n.split("/").slice(1);let a=e;for(const e of t)a=a[e];for(const e in r){const t=r[e];if("object"!=typeof t)continue;const{$data:n}=t.definition,i=a[e];n&&i&&(a[e]=$(i))}}return e}_removeAllSchemas(e,t){for(const r in e){const n=e[r];t&&!t.test(r)||("string"==typeof n?delete e[r]:n&&!n.meta&&(this._cache.delete(n.schema),delete e[r]))}}_addSchema(e,t,r,n=this.opts.validateSchema,a=this.opts.addUsedSchema){let i;const{schemaId:o}=this.opts;if("object"==typeof e)i=e[o];else{if(this.opts.jtd)throw new Error("schema must be object");if("boolean"!=typeof e)throw new Error("schema must be object or boolean")}let l=this._cache.get(e);if(void 0!==l)return l;r=(0,c.normalizeId)(i||r);const u=c.getSchemaRefs.call(this,e,r);return l=new s.SchemaEnv({schema:e,schemaId:o,meta:t,baseId:r,localRefs:u}),this._cache.set(l.schema,l),a&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=l),n&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):s.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){const t=this.opts;this.opts=this._metaOpts;try{s.compileSchema.call(this,e)}finally{this.opts=t}}}function _(e,t,r,n="error"){for(const a in e){const i=a;i in t&&this.logger[n](`${r}: option ${a}. ${e[i]}`)}}function w(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){const e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(const t in e)this.addSchema(e[t],t)}function N(){for(const e in this.opts.formats){const t=this.opts.formats[e];t&&this.addFormat(e,t)}}function k(e){if(Array.isArray(e))this.addVocabulary(e);else{this.logger.warn("keywords option as map is deprecated, pass array");for(const t in e){const r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}}function x(){const e={...this.opts};for(const t of h)delete e[t];return e}b.ValidationError=n.default,b.MissingRefError=a.default,e.default=b;const E={log(){},warn(){},error(){}};const P=/^[a-z_$][a-z0-9_$:-]*$/i;function C(e,t){const{RULES:r}=this;if((0,u.eachItem)(e,e=>{if(r.keywords[e])throw new Error(`Keyword ${e} is already defined`);if(!P.test(e))throw new Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!("code"in t)&&!("validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function A(e,t,r){var n;const a=null==t?void 0:t.post;if(r&&a)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:i}=this;let s=a?i.post:i.rules.find(({type:e})=>e===r);if(s||(s={type:r,rules:[]},i.rules.push(s)),i.keywords[e]=!0,!t)return;const o={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?I.call(this,s,o,t.before):s.rules.push(o),i.all[e]=o,null===(n=t.implements)||void 0===n||n.forEach(e=>this.addKeyword(e))}function I(e,t,r){const n=e.rules.findIndex(e=>e.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function O(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=$(t)),e.validateSchema=this.compile(t,!0))}const T={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function $(e){return{anyOf:[e,T]}}}(eD)),eD}var bj,_j={},wj={},Sj={};var Nj,kj,xj={};function Ej(){if(Nj)return xj;Nj=1,Object.defineProperty(xj,"__esModule",{value:!0}),xj.callRef=xj.getValidate=void 0;const e=rj(),t=LD(),r=dD(),n=bD(),a=ij(),i=hD(),s={keyword:"$ref",schemaType:"string",code(t){const{gen:n,schema:i,it:s}=t,{baseId:l,schemaEnv:u,validateName:d,opts:p,self:m}=s,{root:h}=u;if(("#"===i||"#/"===i)&&l===h.baseId)return function(){if(u===h)return c(t,d,u,u.$async);const e=n.scopeValue("root",{ref:h});return c(t,r._`${e}.validate`,h,h.$async)}();const f=a.resolveRef.call(m,h,l,i);if(void 0===f)throw new e.default(s.opts.uriResolver,l,i);return f instanceof a.SchemaEnv?function(e){const r=o(t,e);c(t,r,e,e.$async)}(f):function(e){const a=n.scopeValue("schema",!0===p.code.source?{ref:e,code:(0,r.stringify)(e)}:{ref:e}),s=n.name("valid"),o=t.subschema({schema:e,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},s);t.mergeEvaluated(o),t.ok(s)}(f)}};function o(e,t){const{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):r._`${n.scopeValue("wrapper",{ref:t})}.validate`}function c(e,a,s,o){const{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:p}=l,m=p.passContext?n.default.this:r.nil;function h(e){const t=r._`${e}.errors`;c.assign(n.default.vErrors,r._`${n.default.vErrors} === null ? ${t} : ${n.default.vErrors}.concat(${t})`),c.assign(n.default.errors,r._`${n.default.vErrors}.length`)}function f(e){var t;if(!l.opts.unevaluated)return;const n=null===(t=null==s?void 0:s.validate)||void 0===t?void 0:t.evaluated;if(!0!==l.props)if(n&&!n.dynamicProps)void 0!==n.props&&(l.props=i.mergeEvaluated.props(c,n.props,l.props));else{const t=c.var("props",r._`${e}.evaluated.props`);l.props=i.mergeEvaluated.props(c,t,l.props,r.Name)}if(!0!==l.items)if(n&&!n.dynamicItems)void 0!==n.items&&(l.items=i.mergeEvaluated.items(c,n.items,l.items));else{const t=c.var("items",r._`${e}.evaluated.items`);l.items=i.mergeEvaluated.items(c,t,l.items,r.Name)}}o?function(){if(!d.$async)throw new Error("async schema referenced by sync schema");const n=c.let("valid");c.try(()=>{c.code(r._`await ${(0,t.callValidateCode)(e,a,m)}`),f(a),u||c.assign(n,!0)},e=>{c.if(r._`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),h(e),u||c.assign(n,!1)}),e.ok(n)}():e.result((0,t.callValidateCode)(e,a,m),()=>f(a),()=>h(a))}return xj.getValidate=o,xj.callRef=c,xj.default=s,xj}function Pj(){if(kj)return wj;kj=1,Object.defineProperty(wj,"__esModule",{value:!0});const e=function(){if(bj)return Sj;bj=1,Object.defineProperty(Sj,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return Sj.default=e,Sj}(),t=Ej(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return wj.default=r,wj}var Cj,Aj={},Ij={};var Oj,Tj={};var $j,zj,Rj={},Lj={};function Mj(){if(zj)return Rj;zj=1,Object.defineProperty(Rj,"__esModule",{value:!0});const e=dD(),t=hD(),r=function(){if($j)return Lj;function e(e){const t=e.length;let r,n=0,a=0;for(;a<t;)n++,r=e.charCodeAt(a++),r>=55296&&r<=56319&&a<t&&(r=e.charCodeAt(a),56320==(64512&r)&&a++);return n}return $j=1,Object.defineProperty(Lj,"__esModule",{value:!0}),Lj.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',Lj}(),n={message({keyword:t,schemaCode:r}){const n="maxLength"===t?"more":"fewer";return e.str`must NOT have ${n} than ${r} characters`},params:({schemaCode:t})=>e._`{limit: ${t}}`},a={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:n,code(n){const{keyword:a,data:i,schemaCode:s,it:o}=n,c="maxLength"===a?e.operators.GT:e.operators.LT,l=!1===o.opts.unicode?e._`${i}.length`:e._`${(0,t.useFunc)(n.gen,r.default)}(${i})`;n.fail$data(e._`${l} ${c} ${s}`)}};return Rj.default=a,Rj}var Dj,jj={};var Fj,Uj={};var qj,Bj={};function Vj(){if(qj)return Bj;qj=1,Object.defineProperty(Bj,"__esModule",{value:!0});const e=LD(),t=dD(),r=hD(),n={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>t.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>t._`{missingProperty: ${e}}`},code(n){const{gen:a,schema:i,schemaCode:s,data:o,$data:c,it:l}=n,{opts:u}=l;if(!c&&0===i.length)return;const d=i.length>=u.loopRequired;if(l.allErrors?function(){if(d||c)n.block$data(t.nil,p);else for(const t of i)(0,e.checkReportMissingProp)(n,t)}():function(){const r=a.let("missing");if(d||c){const i=a.let("valid",!0);n.block$data(i,()=>function(r,i){n.setParams({missingProperty:r}),a.forOf(r,s,()=>{a.assign(i,(0,e.propertyInData)(a,o,r,u.ownProperties)),a.if((0,t.not)(i),()=>{n.error(),a.break()})},t.nil)}(r,i)),n.ok(i)}else a.if((0,e.checkMissingProp)(n,i,r)),(0,e.reportMissingProp)(n,r),a.else()}(),u.strictRequired){const e=n.parentSchema.properties,{definedProperties:t}=n.it;for(const n of i)if(void 0===(null==e?void 0:e[n])&&!t.has(n)){const e=`required property "${n}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,e,l.opts.strictRequired)}}function p(){a.forOf("prop",s,t=>{n.setParams({missingProperty:t}),a.if((0,e.noPropertyInData)(a,o,t,u.ownProperties),()=>n.error())})}}};return Bj.default=n,Bj}var Gj,Hj={};var Kj,Wj,Zj={},Jj={};function Yj(){if(Kj)return Jj;Kj=1,Object.defineProperty(Jj,"__esModule",{value:!0});const e=BD();return e.code='require("ajv/dist/runtime/equal").default',Jj.default=e,Jj}function Qj(){if(Wj)return Zj;Wj=1,Object.defineProperty(Zj,"__esModule",{value:!0});const e=AD(),t=dD(),r=hD(),n=Yj(),a={message:({params:{i:e,j:r}})=>t.str`must NOT have duplicate items (items ## ${r} and ${e} are identical)`,params:({params:{i:e,j:r}})=>t._`{i: ${e}, j: ${r}}`},i={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:a,code(a){const{gen:i,data:s,$data:o,schema:c,parentSchema:l,schemaCode:u,it:d}=a;if(!o&&!c)return;const p=i.let("valid"),m=l.items?(0,e.getSchemaTypes)(l.items):[];function h(r,n){const o=i.name("item"),c=(0,e.checkDataTypes)(m,o,d.opts.strictNumbers,e.DataType.Wrong),l=i.const("indices",t._`{}`);i.for(t._`;${r}--;`,()=>{i.let(o,t._`${s}[${r}]`),i.if(c,t._`continue`),m.length>1&&i.if(t._`typeof ${o} == "string"`,t._`${o} += "_"`),i.if(t._`typeof ${l}[${o}] == "number"`,()=>{i.assign(n,t._`${l}[${o}]`),a.error(),i.assign(p,!1).break()}).code(t._`${l}[${o}] = ${r}`)})}function f(e,o){const c=(0,r.useFunc)(i,n.default),l=i.name("outer");i.label(l).for(t._`;${e}--;`,()=>i.for(t._`${o} = ${e}; ${o}--;`,()=>i.if(t._`${c}(${s}[${e}], ${s}[${o}])`,()=>{a.error(),i.assign(p,!1).break(l)})))}a.block$data(p,function(){const e=i.let("i",t._`${s}.length`),r=i.let("j");a.setParams({i:e,j:r}),i.assign(p,!0),i.if(t._`${e} > 1`,()=>(m.length>0&&!m.some(e=>"object"===e||"array"===e)?h:f)(e,r))},t._`${u} === false`),a.ok(p)}};return Zj.default=i,Zj}var Xj,eF={};var tF,rF,nF={};function aF(){if(tF)return nF;tF=1,Object.defineProperty(nF,"__esModule",{value:!0});const e=dD(),t=hD(),r=Yj(),n={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:t})=>e._`{allowedValues: ${t}}`},code(n){const{gen:a,data:i,$data:s,schema:o,schemaCode:c,it:l}=n;if(!s&&0===o.length)throw new Error("enum must have non-empty array");const u=o.length>=l.opts.loopEnum;let d;const p=()=>null!=d?d:d=(0,t.useFunc)(a,r.default);let m;if(u||s)m=a.let("valid"),n.block$data(m,function(){a.assign(m,!1),a.forOf("v",c,t=>a.if(e._`${p()}(${i}, ${t})`,()=>a.assign(m,!0).break()))});else{if(!Array.isArray(o))throw new Error("ajv implementation error");const t=a.const("vSchema",c);m=(0,e.or)(...o.map((r,n)=>function(t,r){const n=o[r];return"object"==typeof n&&null!==n?e._`${p()}(${i}, ${t}[${r}])`:e._`${i} === ${n}`}(t,n)))}n.pass(m)}};return nF.default=n,nF}function iF(){if(rF)return Aj;rF=1,Object.defineProperty(Aj,"__esModule",{value:!0});const e=function(){if(Cj)return Ij;Cj=1,Object.defineProperty(Ij,"__esModule",{value:!0});const e=dD(),t=e.operators,r={maximum:{okStr:"<=",ok:t.LTE,fail:t.GT},minimum:{okStr:">=",ok:t.GTE,fail:t.LT},exclusiveMaximum:{okStr:"<",ok:t.LT,fail:t.GTE},exclusiveMinimum:{okStr:">",ok:t.GT,fail:t.LTE}},n={message:({keyword:t,schemaCode:n})=>e.str`must be ${r[t].okStr} ${n}`,params:({keyword:t,schemaCode:n})=>e._`{comparison: ${r[t].okStr}, limit: ${n}}`},a={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:n,code(t){const{keyword:n,data:a,schemaCode:i}=t;t.fail$data(e._`${a} ${r[n].fail} ${i} || isNaN(${a})`)}};return Ij.default=a,Ij}(),t=function(){if(Oj)return Tj;Oj=1,Object.defineProperty(Tj,"__esModule",{value:!0});const e=dD(),t={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:t})=>e.str`must be multiple of ${t}`,params:({schemaCode:t})=>e._`{multipleOf: ${t}}`},code(t){const{gen:r,data:n,schemaCode:a,it:i}=t,s=i.opts.multipleOfPrecision,o=r.let("res"),c=s?e._`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:e._`${o} !== parseInt(${o})`;t.fail$data(e._`(${a} === 0 || (${o} = ${n}/${a}, ${c}))`)}};return Tj.default=t,Tj}(),r=Mj(),n=function(){if(Dj)return jj;Dj=1,Object.defineProperty(jj,"__esModule",{value:!0});const e=LD(),t=dD(),r={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>t.str`must match pattern "${e}"`,params:({schemaCode:e})=>t._`{pattern: ${e}}`},code(r){const{data:n,$data:a,schema:i,schemaCode:s,it:o}=r,c=o.opts.unicodeRegExp?"u":"",l=a?t._`(new RegExp(${s}, ${c}))`:(0,e.usePattern)(r,i);r.fail$data(t._`!${l}.test(${n})`)}};return jj.default=r,jj}(),a=function(){if(Fj)return Uj;Fj=1,Object.defineProperty(Uj,"__esModule",{value:!0});const e=dD(),t={message({keyword:t,schemaCode:r}){const n="maxProperties"===t?"more":"fewer";return e.str`must NOT have ${n} than ${r} properties`},params:({schemaCode:t})=>e._`{limit: ${t}}`},r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:t,code(t){const{keyword:r,data:n,schemaCode:a}=t,i="maxProperties"===r?e.operators.GT:e.operators.LT;t.fail$data(e._`Object.keys(${n}).length ${i} ${a}`)}};return Uj.default=r,Uj}(),i=Vj(),s=function(){if(Gj)return Hj;Gj=1,Object.defineProperty(Hj,"__esModule",{value:!0});const e=dD(),t={message({keyword:t,schemaCode:r}){const n="maxItems"===t?"more":"fewer";return e.str`must NOT have ${n} than ${r} items`},params:({schemaCode:t})=>e._`{limit: ${t}}`},r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:t,code(t){const{keyword:r,data:n,schemaCode:a}=t,i="maxItems"===r?e.operators.GT:e.operators.LT;t.fail$data(e._`${n}.length ${i} ${a}`)}};return Hj.default=r,Hj}(),o=Qj(),c=function(){if(Xj)return eF;Xj=1,Object.defineProperty(eF,"__esModule",{value:!0});const e=dD(),t=hD(),r=Yj(),n={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:t})=>e._`{allowedValue: ${t}}`},code(n){const{gen:a,data:i,$data:s,schemaCode:o,schema:c}=n;s||c&&"object"==typeof c?n.fail$data(e._`!${(0,t.useFunc)(a,r.default)}(${i}, ${o})`):n.fail(e._`${c} !== ${i}`)}};return eF.default=n,eF}(),l=aF(),u=[e.default,t.default,r.default,n.default,a.default,i.default,s.default,o.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},c.default,l.default];return Aj.default=u,Aj}var sF,oF={},cF={};function lF(){if(sF)return cF;sF=1,Object.defineProperty(cF,"__esModule",{value:!0}),cF.validateAdditionalItems=void 0;const e=dD(),t=hD(),r={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:t}})=>e.str`must NOT have more than ${t} items`,params:({params:{len:t}})=>e._`{limit: ${t}}`},code(e){const{parentSchema:r,it:a}=e,{items:i}=r;Array.isArray(i)?n(e,i):(0,t.checkStrictMode)(a,'"additionalItems" is ignored when "items" is not an array of schemas')}};function n(r,n){const{gen:a,schema:i,data:s,keyword:o,it:c}=r;c.items=!0;const l=a.const("len",e._`${s}.length`);if(!1===i)r.setParams({len:n.length}),r.pass(e._`${l} <= ${n.length}`);else if("object"==typeof i&&!(0,t.alwaysValidSchema)(c,i)){const i=a.var("valid",e._`${l} <= ${n.length}`);a.if((0,e.not)(i),()=>function(i){a.forRange("i",n.length,l,n=>{r.subschema({keyword:o,dataProp:n,dataPropType:t.Type.Num},i),c.allErrors||a.if((0,e.not)(i),()=>a.break())})}(i)),r.ok(i)}}return cF.validateAdditionalItems=n,cF.default=r,cF}var uF,dF,pF={},mF={};function hF(){if(uF)return mF;uF=1,Object.defineProperty(mF,"__esModule",{value:!0}),mF.validateTuple=void 0;const e=dD(),t=hD(),r=LD(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:n,it:i}=e;if(Array.isArray(n))return a(e,"additionalItems",n);i.items=!0,(0,t.alwaysValidSchema)(i,n)||e.ok((0,r.validateArray)(e))}};function a(r,n,a=r.schema){const{gen:i,parentSchema:s,data:o,keyword:c,it:l}=r;!function(e){const{opts:r,errSchemaPath:i}=l,s=a.length,o=s===e.minItems&&(s===e.maxItems||!1===e[n]);if(r.strictTuples&&!o){const e=`"${c}" is ${s}-tuple, but minItems or maxItems/${n} are not specified or different at path "${i}"`;(0,t.checkStrictMode)(l,e,r.strictTuples)}}(s),l.opts.unevaluated&&a.length&&!0!==l.items&&(l.items=t.mergeEvaluated.items(i,a.length,l.items));const u=i.name("valid"),d=i.const("len",e._`${o}.length`);a.forEach((n,a)=>{(0,t.alwaysValidSchema)(l,n)||(i.if(e._`${d} > ${a}`,()=>r.subschema({keyword:c,schemaProp:a,dataProp:a},u)),r.ok(u))})}return mF.validateTuple=a,mF.default=n,mF}var fF,gF={};var yF,vF={};function bF(){if(yF)return vF;yF=1,Object.defineProperty(vF,"__esModule",{value:!0});const e=dD(),t=hD(),r={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:t,max:r}})=>void 0===r?e.str`must contain at least ${t} valid item(s)`:e.str`must contain at least ${t} and no more than ${r} valid item(s)`,params:({params:{min:t,max:r}})=>void 0===r?e._`{minContains: ${t}}`:e._`{minContains: ${t}, maxContains: ${r}}`},code(r){const{gen:n,schema:a,parentSchema:i,data:s,it:o}=r;let c,l;const{minContains:u,maxContains:d}=i;o.opts.next?(c=void 0===u?1:u,l=d):c=1;const p=n.const("len",e._`${s}.length`);if(r.setParams({min:c,max:l}),void 0===l&&0===c)return void(0,t.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==l&&c>l)return(0,t.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),void r.fail();if((0,t.alwaysValidSchema)(o,a)){let t=e._`${p} >= ${c}`;return void 0!==l&&(t=e._`${t} && ${p} <= ${l}`),void r.pass(t)}o.items=!0;const m=n.name("valid");function h(){const t=n.name("_valid"),r=n.let("count",0);f(t,()=>n.if(t,()=>function(t){n.code(e._`${t}++`),void 0===l?n.if(e._`${t} >= ${c}`,()=>n.assign(m,!0).break()):(n.if(e._`${t} > ${l}`,()=>n.assign(m,!1).break()),1===c?n.assign(m,!0):n.if(e._`${t} >= ${c}`,()=>n.assign(m,!0)))}(r)))}function f(e,a){n.forRange("i",0,p,n=>{r.subschema({keyword:"contains",dataProp:n,dataPropType:t.Type.Num,compositeRule:!0},e),a()})}void 0===l&&1===c?f(m,()=>n.if(m,()=>n.break())):0===c?(n.let(m,!0),void 0!==l&&n.if(e._`${s}.length > 0`,h)):(n.let(m,!1),h()),r.result(m,()=>r.reset())}};return vF.default=r,vF}var _F,wF={};function SF(){return _F||(_F=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=dD(),r=hD(),n=LD();e.error={message:({params:{property:e,depsCount:r,deps:n}})=>{const a=1===r?"property":"properties";return t.str`must have ${a} ${n} when property ${e} is present`},params:({params:{property:e,depsCount:r,deps:n,missingProperty:a}})=>t._`{property: ${e},
5
+ missingProperty: ${a},
6
6
  depsCount: ${r},
7
- deps: ${n}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(e){const[t,r]=function({schema:e}){const t={},r={};for(const n in e){if("__proto__"===n)continue;(Array.isArray(e[n])?t:r)[n]=e[n]}return[t,r]}(e);i(e,t),s(e,r)}};function i(e,r=e.schema){const{gen:o,data:i,it:s}=e;if(0===Object.keys(r).length)return;const a=o.let("missing");for(const c in r){const l=r[c];if(0===l.length)continue;const d=(0,n.propertyInData)(o,i,c,s.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(", ")}),s.allErrors?o.if(d,()=>{for(const t of l)(0,n.checkReportMissingProp)(e,t)}):(o.if(t._`${d} && (${(0,n.checkMissingProp)(e,l,a)})`),(0,n.reportMissingProp)(e,a),o.else())}}function s(e,t=e.schema){const{gen:o,data:i,keyword:s,it:a}=e,c=o.name("valid");for(const l in t)(0,r.alwaysValidSchema)(a,t[l])||(o.if((0,n.propertyInData)(o,i,l,a.opts.ownProperties),()=>{const t=e.subschema({keyword:s,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>o.var(c,!0)),e.ok(c))}e.validatePropertyDeps=i,e.validateSchemaDeps=s,e.default=o}(fi)),fi}var gi,yi={};var vi,bi={};function $i(){if(vi)return bi;vi=1,Object.defineProperty(bi,"__esModule",{value:!0});const e=Cn(),t=rn(),r=un(),n=sn(),o={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:e})=>t._`{additionalProperty: ${e.additionalProperty}}`},code(o){const{gen:i,schema:s,parentSchema:a,data:c,errsCount:l,it:d}=o;if(!l)throw new Error("ajv implementation error");const{allErrors:u,opts:p}=d;if(d.props=!0,"all"!==p.removeAdditional&&(0,n.alwaysValidSchema)(d,s))return;const h=(0,e.allSchemaProperties)(a.properties),f=(0,e.allSchemaProperties)(a.patternProperties);function m(e){i.code(t._`delete ${c}[${e}]`)}function g(e){if("all"===p.removeAdditional||p.removeAdditional&&!1===s)m(e);else{if(!1===s)return o.setParams({additionalProperty:e}),o.error(),void(u||i.break());if("object"==typeof s&&!(0,n.alwaysValidSchema)(d,s)){const r=i.name("valid");"failing"===p.removeAdditional?(y(e,r,!1),i.if((0,t.not)(r),()=>{o.reset(),m(e)})):(y(e,r),u||i.if((0,t.not)(r),()=>i.break()))}}}function y(e,t,r){const i={keyword:"additionalProperties",dataProp:e,dataPropType:n.Type.Str};!1===r&&Object.assign(i,{compositeRule:!0,createErrors:!1,allErrors:!1}),o.subschema(i,t)}i.forIn("key",c,r=>{h.length||f.length?i.if(function(r){let s;if(h.length>8){const t=(0,n.schemaRefOrVal)(d,a.properties,"properties");s=(0,e.isOwnProperty)(i,t,r)}else s=h.length?(0,t.or)(...h.map(e=>t._`${r} === ${e}`)):t.nil;return f.length&&(s=(0,t.or)(s,...f.map(n=>t._`${(0,e.usePattern)(o,n)}.test(${r})`))),(0,t.not)(s)}(r),()=>g(r)):g(r)}),o.ok(t._`${l} === ${r.default.errors}`)}};return bi.default=o,bi}var wi,Ei={};var Si,Pi={};var Li,_i={};var ki,Ci={};var Ni,Ii={};var Oi,Ai={};var Ti,xi={};var Di,ji,Ri={};function Fi(){if(ji)return ei;ji=1,Object.defineProperty(ei,"__esModule",{value:!0});const e=ri(),t=function(){if(oi)return ii;oi=1,Object.defineProperty(ii,"__esModule",{value:!0});const e=ai(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,e.validateTuple)(t,"items")};return ii.default=t,ii}(),r=ai(),n=function(){if(ci)return li;ci=1,Object.defineProperty(li,"__esModule",{value:!0});const e=rn(),t=sn(),r=Cn(),n=ri(),o={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:t}})=>e.str`must NOT have more than ${t} items`,params:({params:{len:t}})=>e._`{limit: ${t}}`},code(e){const{schema:o,parentSchema:i,it:s}=e,{prefixItems:a}=i;s.items=!0,(0,t.alwaysValidSchema)(s,o)||(a?(0,n.validateAdditionalItems)(e,a):e.ok((0,r.validateArray)(e)))}};return li.default=o,li}(),o=pi(),i=mi(),s=function(){if(gi)return yi;gi=1,Object.defineProperty(yi,"__esModule",{value:!0});const e=rn(),t=sn(),r={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:t})=>e._`{propertyName: ${t.propertyName}}`},code(r){const{gen:n,schema:o,data:i,it:s}=r;if((0,t.alwaysValidSchema)(s,o))return;const a=n.name("valid");n.forIn("key",i,t=>{r.setParams({propertyName:t}),r.subschema({keyword:"propertyNames",data:t,dataTypes:["string"],propertyName:t,compositeRule:!0},a),n.if((0,e.not)(a),()=>{r.error(!0),s.allErrors||n.break()})}),r.ok(a)}};return yi.default=r,yi}(),a=$i(),c=function(){if(wi)return Ei;wi=1,Object.defineProperty(Ei,"__esModule",{value:!0});const e=Bn(),t=Cn(),r=sn(),n=$i(),o={keyword:"properties",type:"object",schemaType:"object",code(o){const{gen:i,schema:s,parentSchema:a,data:c,it:l}=o;"all"===l.opts.removeAdditional&&void 0===a.additionalProperties&&n.default.code(new e.KeywordCxt(l,n.default,"additionalProperties"));const d=(0,t.allSchemaProperties)(s);for(const e of d)l.definedProperties.add(e);l.opts.unevaluated&&d.length&&!0!==l.props&&(l.props=r.mergeEvaluated.props(i,(0,r.toHash)(d),l.props));const u=d.filter(e=>!(0,r.alwaysValidSchema)(l,s[e]));if(0===u.length)return;const p=i.name("valid");for(const e of u)h(e)?f(e):(i.if((0,t.propertyInData)(i,c,e,l.opts.ownProperties)),f(e),l.allErrors||i.else().var(p,!0),i.endIf()),o.it.definedProperties.add(e),o.ok(p);function h(e){return l.opts.useDefaults&&!l.compositeRule&&void 0!==s[e].default}function f(e){o.subschema({keyword:"properties",schemaProp:e,dataProp:e},p)}}};return Ei.default=o,Ei}(),l=function(){if(Si)return Pi;Si=1,Object.defineProperty(Pi,"__esModule",{value:!0});const e=Cn(),t=rn(),r=sn(),n=sn(),o={keyword:"patternProperties",type:"object",schemaType:"object",code(o){const{gen:i,schema:s,data:a,parentSchema:c,it:l}=o,{opts:d}=l,u=(0,e.allSchemaProperties)(s),p=u.filter(e=>(0,r.alwaysValidSchema)(l,s[e]));if(0===u.length||p.length===u.length&&(!l.opts.unevaluated||!0===l.props))return;const h=d.strictSchema&&!d.allowMatchingProperties&&c.properties,f=i.name("valid");!0===l.props||l.props instanceof t.Name||(l.props=(0,n.evaluatedPropsToName)(i,l.props));const{props:m}=l;function g(e){for(const t in h)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function y(r){i.forIn("key",a,s=>{i.if(t._`${(0,e.usePattern)(o,r)}.test(${s})`,()=>{const e=p.includes(r);e||o.subschema({keyword:"patternProperties",schemaProp:r,dataProp:s,dataPropType:n.Type.Str},f),l.opts.unevaluated&&!0!==m?i.assign(t._`${m}[${s}]`,!0):e||l.allErrors||i.if((0,t.not)(f),()=>i.break())})})}!function(){for(const e of u)h&&g(e),l.allErrors?y(e):(i.var(f,!0),y(e),i.if(f))}()}};return Pi.default=o,Pi}(),d=function(){if(Li)return _i;Li=1,Object.defineProperty(_i,"__esModule",{value:!0});const e=sn(),t={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){const{gen:r,schema:n,it:o}=t;if((0,e.alwaysValidSchema)(o,n))return void t.fail();const i=r.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),t.failResult(i,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};return _i.default=t,_i}(),u=function(){if(ki)return Ci;ki=1,Object.defineProperty(Ci,"__esModule",{value:!0});const e={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Cn().validateUnion,error:{message:"must match a schema in anyOf"}};return Ci.default=e,Ci}(),p=function(){if(Ni)return Ii;Ni=1,Object.defineProperty(Ii,"__esModule",{value:!0});const e=rn(),t=sn(),r={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:t})=>e._`{passingSchemas: ${t.passing}}`},code(r){const{gen:n,schema:o,parentSchema:i,it:s}=r;if(!Array.isArray(o))throw new Error("ajv implementation error");if(s.opts.discriminator&&i.discriminator)return;const a=o,c=n.let("valid",!1),l=n.let("passing",null),d=n.name("_valid");r.setParams({passing:l}),n.block(function(){a.forEach((o,i)=>{let a;(0,t.alwaysValidSchema)(s,o)?n.var(d,!0):a=r.subschema({keyword:"oneOf",schemaProp:i,compositeRule:!0},d),i>0&&n.if(e._`${d} && ${c}`).assign(c,!1).assign(l,e._`[${l}, ${i}]`).else(),n.if(d,()=>{n.assign(c,!0),n.assign(l,i),a&&r.mergeEvaluated(a,e.Name)})})}),r.result(c,()=>r.reset(),()=>r.error(!0))}};return Ii.default=r,Ii}(),h=function(){if(Oi)return Ai;Oi=1,Object.defineProperty(Ai,"__esModule",{value:!0});const e=sn(),t={keyword:"allOf",schemaType:"array",code(t){const{gen:r,schema:n,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");const i=r.name("valid");n.forEach((r,n)=>{if((0,e.alwaysValidSchema)(o,r))return;const s=t.subschema({keyword:"allOf",schemaProp:n},i);t.ok(i),t.mergeEvaluated(s)})}};return Ai.default=t,Ai}(),f=function(){if(Ti)return xi;Ti=1,Object.defineProperty(xi,"__esModule",{value:!0});const e=rn(),t=sn(),r={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:t})=>e.str`must match "${t.ifClause}" schema`,params:({params:t})=>e._`{failingKeyword: ${t.ifClause}}`},code(r){const{gen:o,parentSchema:i,it:s}=r;void 0===i.then&&void 0===i.else&&(0,t.checkStrictMode)(s,'"if" without "then" and "else" is ignored');const a=n(s,"then"),c=n(s,"else");if(!a&&!c)return;const l=o.let("valid",!0),d=o.name("_valid");if(function(){const e=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},d);r.mergeEvaluated(e)}(),r.reset(),a&&c){const e=o.let("ifClause");r.setParams({ifClause:e}),o.if(d,u("then",e),u("else",e))}else a?o.if(d,u("then")):o.if((0,e.not)(d),u("else"));function u(t,n){return()=>{const i=r.subschema({keyword:t},d);o.assign(l,d),r.mergeValidEvaluated(i,l),n?o.assign(n,e._`${t}`):r.setParams({ifClause:t})}}r.pass(l,()=>r.error(!0))}};function n(e,r){const n=e.schema[r];return void 0!==n&&!(0,t.alwaysValidSchema)(e,n)}return xi.default=r,xi}(),m=function(){if(Di)return Ri;Di=1,Object.defineProperty(Ri,"__esModule",{value:!0});const e=sn(),t={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:r,it:n}){void 0===r.if&&(0,e.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};return Ri.default=t,Ri}();return ei.default=function(g=!1){const y=[d.default,u.default,p.default,h.default,f.default,m.default,s.default,a.default,i.default,c.default,l.default];return g?y.push(t.default,n.default):y.push(e.default,r.default),y.push(o.default),y},ei}var Mi,Gi={},Ui={};function Bi(){if(Mi)return Ui;Mi=1,Object.defineProperty(Ui,"__esModule",{value:!0}),Ui.dynamicAnchor=void 0;const e=rn(),t=un(),r=Xn(),n=bo(),o={keyword:"$dynamicAnchor",schemaType:"string",code:e=>i(e,e.schema)};function i(o,i){const{gen:s,it:a}=o;a.schemaEnv.root.dynamicAnchors[i]=!0;const c=e._`${t.default.dynamicAnchors}${(0,e.getProperty)(i)}`,l="#"===a.errSchemaPath?a.validateName:function(e){const{schemaEnv:t,schema:o,self:i}=e.it,{root:s,baseId:a,localRefs:c,meta:l}=t.root,{schemaId:d}=i.opts,u=new r.SchemaEnv({schema:o,schemaId:d,root:s,baseId:a,localRefs:c,meta:l});return r.compileSchema.call(i,u),(0,n.getValidate)(e,u)}(o);s.if(e._`!${c}`,()=>s.assign(c,l))}return Ui.dynamicAnchor=i,Ui.default=o,Ui}var zi,Hi={};function Vi(){if(zi)return Hi;zi=1,Object.defineProperty(Hi,"__esModule",{value:!0}),Hi.dynamicRef=void 0;const e=rn(),t=un(),r=bo(),n={keyword:"$dynamicRef",schemaType:"string",code:e=>o(e,e.schema)};function o(n,o){const{gen:i,keyword:s,it:a}=n;if("#"!==o[0])throw new Error(`"${s}" only supports hash fragment reference`);const c=o.slice(1);if(a.allErrors)l();else{const e=i.let("valid",!1);l(e),n.ok(e)}function l(r){if(a.schemaEnv.root.dynamicAnchors[c]){const n=i.let("_v",e._`${t.default.dynamicAnchors}${(0,e.getProperty)(c)}`);i.if(n,d(n,r),d(a.validateName,r))}else d(a.validateName,r)()}function d(e,t){return t?()=>i.block(()=>{(0,r.callRef)(n,e),i.let(t,!0)}):()=>(0,r.callRef)(n,e)}}return Hi.dynamicRef=o,Hi.default=n,Hi}var Wi,qi={};var Ki,Yi,Ji={};function Xi(){if(Yi)return Gi;Yi=1,Object.defineProperty(Gi,"__esModule",{value:!0});const e=Bi(),t=Vi(),r=function(){if(Wi)return qi;Wi=1,Object.defineProperty(qi,"__esModule",{value:!0});const e=Bi(),t=sn(),r={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,e.dynamicAnchor)(r,""):(0,t.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};return qi.default=r,qi}(),n=function(){if(Ki)return Ji;Ki=1,Object.defineProperty(Ji,"__esModule",{value:!0});const e=Vi(),t={keyword:"$recursiveRef",schemaType:"string",code:t=>(0,e.dynamicRef)(t,t.schema)};return Ji.default=t,Ji}(),o=[e.default,t.default,r.default,n.default];return Gi.default=o,Gi}var Zi,Qi={},es={};var ts,rs={};var ns,os,is={};function ss(){if(os)return Qi;os=1,Object.defineProperty(Qi,"__esModule",{value:!0});const e=function(){if(Zi)return es;Zi=1,Object.defineProperty(es,"__esModule",{value:!0});const e=mi(),t={keyword:"dependentRequired",type:"object",schemaType:"object",error:e.error,code:t=>(0,e.validatePropertyDeps)(t)};return es.default=t,es}(),t=function(){if(ts)return rs;ts=1,Object.defineProperty(rs,"__esModule",{value:!0});const e=mi(),t={keyword:"dependentSchemas",type:"object",schemaType:"object",code:t=>(0,e.validateSchemaDeps)(t)};return rs.default=t,rs}(),r=function(){if(ns)return is;ns=1,Object.defineProperty(is,"__esModule",{value:!0});const e=sn(),t={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:t,parentSchema:r,it:n}){void 0===r.contains&&(0,e.checkStrictMode)(n,`"${t}" without "contains" is ignored`)}};return is.default=t,is}(),n=[e.default,t.default,r.default];return Qi.default=n,Qi}var as,cs={},ls={};function ds(){if(as)return ls;as=1,Object.defineProperty(ls,"__esModule",{value:!0});const e=rn(),t=sn(),r=un(),n={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:{message:"must NOT have unevaluated properties",params:({params:t})=>e._`{unevaluatedProperty: ${t.unevaluatedProperty}}`},code(n){const{gen:o,schema:i,data:s,errsCount:a,it:c}=n;if(!a)throw new Error("ajv implementation error");const{allErrors:l,props:d}=c;function u(r){if(!1===i)return n.setParams({unevaluatedProperty:r}),n.error(),void(l||o.break());if(!(0,t.alwaysValidSchema)(c,i)){const i=o.name("valid");n.subschema({keyword:"unevaluatedProperties",dataProp:r,dataPropType:t.Type.Str},i),l||o.if((0,e.not)(i),()=>o.break())}}d instanceof e.Name?o.if(e._`${d} !== true`,()=>o.forIn("key",s,t=>o.if(function(t,r){return e._`!${t} || !${t}[${r}]`}(d,t),()=>u(t)))):!0!==d&&o.forIn("key",s,t=>void 0===d?u(t):o.if(function(t,r){const n=[];for(const o in t)!0===t[o]&&n.push(e._`${r} !== ${o}`);return(0,e.and)(...n)}(d,t),()=>u(t))),c.props=!0,n.ok(e._`${a} === ${r.default.errors}`)}};return ls.default=n,ls}var us,ps,hs={};function fs(){if(us)return hs;us=1,Object.defineProperty(hs,"__esModule",{value:!0});const e=rn(),t=sn(),r={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:{message:({params:{len:t}})=>e.str`must NOT have more than ${t} items`,params:({params:{len:t}})=>e._`{limit: ${t}}`},code(r){const{gen:n,schema:o,data:i,it:s}=r,a=s.items||0;if(!0===a)return;const c=n.const("len",e._`${i}.length`);if(!1===o)r.setParams({len:a}),r.fail(e._`${c} > ${a}`);else if("object"==typeof o&&!(0,t.alwaysValidSchema)(s,o)){const o=n.var("valid",e._`${c} <= ${a}`);n.if((0,e.not)(o),()=>function(o,i){n.forRange("i",i,c,i=>{r.subschema({keyword:"unevaluatedItems",dataProp:i,dataPropType:t.Type.Num},o),s.allErrors||n.if((0,e.not)(o),()=>n.break())})}(o,a)),r.ok(o)}s.items=!0}};return hs.default=r,hs}var ms,gs,ys={},vs={};function bs(){if(ms)return vs;ms=1,Object.defineProperty(vs,"__esModule",{value:!0});const e=rn(),t={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:t})=>e.str`must match format "${t}"`,params:({schemaCode:t})=>e._`{format: ${t}}`},code(t,r){const{gen:n,data:o,$data:i,schema:s,schemaCode:a,it:c}=t,{opts:l,errSchemaPath:d,schemaEnv:u,self:p}=c;l.validateFormats&&(i?function(){const i=n.scopeValue("formats",{ref:p.formats,code:l.code.formats}),s=n.const("fDef",e._`${i}[${a}]`),c=n.let("fType"),d=n.let("format");n.if(e._`typeof ${s} == "object" && !(${s} instanceof RegExp)`,()=>n.assign(c,e._`${s}.type || "string"`).assign(d,e._`${s}.validate`),()=>n.assign(c,e._`"string"`).assign(d,s)),t.fail$data((0,e.or)(!1===l.strictSchema?e.nil:e._`${a} && !${d}`,function(){const t=u.$async?e._`(${s}.async ? await ${d}(${o}) : ${d}(${o}))`:e._`${d}(${o})`,n=e._`(typeof ${d} == "function" ? ${t} : ${d}.test(${o}))`;return e._`${d} && ${d} !== true && ${c} === ${r} && !${n}`}()))}():function(){const i=p.formats[s];if(!i)return void function(){if(!1===l.strictSchema)return void p.logger.warn(e());throw new Error(e());function e(){return`unknown format "${s}" ignored in schema at path "${d}"`}}();if(!0===i)return;const[a,c,h]=function(t){const r=t instanceof RegExp?(0,e.regexpCode)(t):l.code.formats?e._`${l.code.formats}${(0,e.getProperty)(s)}`:void 0,o=n.scopeValue("formats",{key:s,ref:t,code:r});if("object"==typeof t&&!(t instanceof RegExp))return[t.type||"string",t.validate,e._`${o}.validate`];return["string",t,o]}(i);a===r&&t.pass(function(){if("object"==typeof i&&!(i instanceof RegExp)&&i.async){if(!u.$async)throw new Error("async format in sync schema");return e._`await ${h}(${o})`}return"function"==typeof c?e._`${h}(${o})`:e._`${h}.test(${o})`}())}())}};return vs.default=t,vs}var $s,ws,Es={};function Ss(){if(ws)return ho;ws=1,Object.defineProperty(ho,"__esModule",{value:!0});const e=$o(),t=Zo(),r=Fi(),n=Xi(),o=ss(),i=function(){if(ps)return cs;ps=1,Object.defineProperty(cs,"__esModule",{value:!0});const e=ds(),t=fs(),r=[e.default,t.default];return cs.default=r,cs}(),s=function(){if(gs)return ys;gs=1,Object.defineProperty(ys,"__esModule",{value:!0});const e=[bs().default];return ys.default=e,ys}(),a=($s||($s=1,Object.defineProperty(Es,"__esModule",{value:!0}),Es.contentVocabulary=Es.metadataVocabulary=void 0,Es.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Es.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),Es),c=[n.default,e.default,t.default,(0,r.default)(!0),s.default,a.metadataVocabulary,a.contentVocabulary,o.default,i.default];return ho.default=c,ho}var Ps,Ls,_s={},ks={};function Cs(){if(Ls)return _s;Ls=1,Object.defineProperty(_s,"__esModule",{value:!0});const e=rn(),t=(Ps||(Ps=1,Object.defineProperty(ks,"__esModule",{value:!0}),ks.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(r||(ks.DiscrError=r={}))),ks);var r;const n=Xn(),o=Kn(),i=sn(),s={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:r}})=>e===t.DiscrError.Tag?`tag "${r}" must be string`:`value of tag "${r}" must be in oneOf`,params:({params:{discrError:t,tag:r,tagName:n}})=>e._`{error: ${t}, tag: ${n}, tagValue: ${r}}`},code(r){const{gen:s,data:a,schema:c,parentSchema:l,it:d}=r,{oneOf:u}=l;if(!d.opts.discriminator)throw new Error("discriminator: requires discriminator option");const p=c.propertyName;if("string"!=typeof p)throw new Error("discriminator: requires propertyName");if(c.mapping)throw new Error("discriminator: mapping is not supported");if(!u)throw new Error("discriminator: requires oneOf keyword");const h=s.let("valid",!1),f=s.const("tag",e._`${a}${(0,e.getProperty)(p)}`);function m(t){const n=s.name("valid"),o=r.subschema({keyword:"oneOf",schemaProp:t},n);return r.mergeEvaluated(o,e.Name),n}s.if(e._`typeof ${f} == "string"`,()=>function(){const a=function(){var e;const t={},r=a(l);let s=!0;for(let t=0;t<u.length;t++){let l=u[t];if((null==l?void 0:l.$ref)&&!(0,i.schemaHasRulesButRef)(l,d.self.RULES)){const e=l.$ref;if(l=n.resolveRef.call(d.self,d.schemaEnv.root,d.baseId,e),l instanceof n.SchemaEnv&&(l=l.schema),void 0===l)throw new o.default(d.opts.uriResolver,d.baseId,e)}const h=null===(e=null==l?void 0:l.properties)||void 0===e?void 0:e[p];if("object"!=typeof h)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${p}"`);s=s&&(r||a(l)),c(h,t)}if(!s)throw new Error(`discriminator: "${p}" must be required`);return t;function a({required:e}){return Array.isArray(e)&&e.includes(p)}function c(e,t){if(e.const)h(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${p}" must have "const" or "enum"`);for(const r of e.enum)h(r,t)}}function h(e,r){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${p}" values must be unique strings`);t[e]=r}}();s.if(!1);for(const t in a)s.elseIf(e._`${f} === ${t}`),s.assign(h,m(a[t]));s.else(),r.error(!1,{discrError:t.DiscrError.Mapping,tag:f,tagName:p}),s.endIf()}(),()=>r.error(!1,{discrError:t.DiscrError.Tag,tag:f,tagName:p})),r.ok(h)}};return _s.default=s,_s}var Ns,Is,Os={},As={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}},Ts={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}},xs={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}},Ds={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}},js={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}},Rs={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}},Fs={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}},Ms={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}};var Gs=(Is||(Is=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv2020=void 0;const r=uo(),n=Ss(),o=Cs(),i=function(){if(Ns)return Os;Ns=1,Object.defineProperty(Os,"__esModule",{value:!0});const e=As,t=Ts,r=xs,n=Ds,o=js,i=Rs,s=Fs,a=Ms,c=["/properties"];return Os.default=function(l){return[e,t,r,n,o,d(this,i),s,d(this,a)].forEach(e=>this.addMetaSchema(e,void 0,!1)),this;function d(e,t){return l?e.$dataMetaSchema(t,c):t}},Os}(),s="https://json-schema.org/draft/2020-12/schema";class a extends r.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),n.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();const{$data:e,meta:t}=this.opts;t&&(i.default.call(this,e),this.refs["http://json-schema.org/schema"]=s)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}}t.Ajv2020=a,e.exports=t=a,e.exports.Ajv2020=a,Object.defineProperty(t,"__esModule",{value:!0}),t.default=a;var c=Bn();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var l=rn();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var d=Vn();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var u=Kn();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return u.default}})}(Hr,Hr.exports)),Hr.exports),Us=Nt(Gs);const Bs=re.object({templateEntry:re.string({message:"templateEntry must be a string"}).describe("Main entry point for the portal"),schemaEntry:re.string({message:"schemaEntry must be a string"}).describe("Schema file for portal validation"),assetPath:re.string({message:"assetPath must be a string"}).optional().describe("Asset path for dev/preview builds"),githubRepo:re.string({message:"githubRepo must be a string"}).optional().describe("GitHub repo URL or local git remote"),version:re.string({message:"version must be a string"}).describe("Version from package.json"),timestamp:re.string({message:"timestamp must be a string"}).describe("Current build timestamp (ISO8601)"),commitSha:re.string({message:"commitSha must be a string"}).describe("Current git commit SHA"),annotations:re.record(re.string(),re.string()).optional().describe("Optional build annotations"),projectPage:re.string({message:"projectPage must be a string"}).optional().describe("Optional project homepage"),allowedExtensions:re.array(re.string({message:"Each allowed extension must be a string"}),{message:"allowedExtensions must be an array of strings"}).describe("List of allowed asset extensions (with leading dot)"),schema:re.record(re.string(),re.unknown()).optional().describe("Optional schema for the portal"),config:re.record(re.string(),re.unknown()).optional().describe("Optional configuration for the portal")});re.object({name:re.string({message:"name must be a string"}).describe("Short app key (unscoped, derived from package name)"),displayName:re.string({message:"displayName must be a string"}).optional().describe("Full package name, may include scope"),description:re.string({message:"description must be a string"}).optional().describe("Description of the portal"),build:Bs});const zs=e("schema").description("Generate or validate a Fusion portal schema file.").addHelpText("after",["","Examples:"," $ ffc portal schema"," $ ffc portal schema --output portal.schema.json"," $ ffc portal schema --validate my-config.json"].join("\n")).addOption(je({allowDev:!0})).option("-o, --output <string>","Output file name (default: stdout)","stdout").option("-d, --debug","Enable debug mode for verbose logging",!1).option("-v, --validate <file>","Validate the generated schema against a JSON file").argument("[schema]","Schema build file to use (e.g., portal.schema[.env]?.[ts,js,json])").action(async(e,t)=>{const r=new d("portal:schema",{debug:t.debug});r.debug("Manifest file:",e),r.debug("Current working directory:",process.cwd()),r.start("Generating schema for the application...");const n=await(async(e,t)=>{const r=[`portal.schema.${e.environment}`,"portal.schema"],n=await se(r,{baseDir:e.root,extensions:t?.extensions,script:{resolve:async t=>{const r="function"==typeof t.default?await Promise.resolve(t.default(e)):t.default;if(!r)throw new Error("Schema function did not return a valid schema");return r}}});return{schema:n.config,path:n.path,extension:n.extension}})({command:"build",environment:t.environment,mode:"build",root:process.cwd()});if(r.debug("Schema:",JSON.stringify(n,null,2)),r.succeed("Schema generated successfully!"),t.output&&("stdout"===t.output?r.info("Schema:",JSON.stringify(n.schema,null,2)):(r.start(`Writing schema to ${t.output}`),((e,t,r)=>{const n=a(String(e));G(n)||H(n,{recursive:!0}),F(e,t,r)})(t.output,JSON.stringify(n.schema,null,2)),r.succeed(`Schema written to ${t.output}`)),process.exit(0)),t.validate){r.start("Validating schema against JSON file...");const e=new Us({strict:!0}).compile(n.schema),o=await ae(t.validate);r.debug("JSON value:",JSON.stringify(o,null,2));e(o)?r.succeed("Schema validation passed!"):(r.fail("Schema validation failed:",JSON.stringify(e.errors??"Unknown error")),process.exit(1))}}),Hs=e("build").description("Build the Fusion portal from a manifest file with environment-specific settings.").addHelpText("after",["","If no manifest is provided, the command will search for a default portal.manifest.[ts|js|json] in the current directory.","example: `ffc portal build --env prod` will search for `portal.manifest.prod.ts` then fallback to `portal.manifest.ts`","","NOTE: portal manifest is not required, a default manifest will be generated if not provided","","Examples:"," $ ffc portal build"," $ ffc portal build portal.manifest.prod.ts --debug",""].join("\n")).option("-d, --debug","Enable debug mode for verbose logging",!1).argument("[manifest]","Manifest build file to use for building (e.g., portal.manifest[.env]?.[ts|js|json])").action(async(e,t)=>{const r=new d("portal:build",{debug:t.debug});await _({log:r,manifest:e})}),Vs=e("pack").description("Bundle the Fusion portal into a deployable archive.").addHelpText("after",["","If no manifest is provided, a default portal.manifest(.$ENV)?.[ts|js|json] is used from the current directory.","example: `ffc portal pack --env prod` will search for `portal.manifest.prod.ts` then fallback to `portal.manifest.ts`","","NOTE: portal manifest is not required, a default manifest will be generated if not provided","","Examples:"," $ ffc portal pack"," $ ffc portal pack portal.manifest.dev.ts --archive my-portal.zip --output ./dist"].join("\n")).option("-a, --archive [string]","Name of the output archive file (default: out/bundle.zip)","out/bundle.zip").option("-d, --debug [boolean]","Enable debug mode for verbose logging",!1).option("--schema [string]","Schema file to use for validation").argument("[manifest]","Manifest file to use for bundling (e.g., my-portal.manifest.ts)").action(async(e,t)=>{const r=new d("portal:pack",{debug:t.debug});await k({log:r,manifest:e,archive:t.archive,schema:t.schema}).catch(e=>{r.error("Failed to create package:",e),process.exit(1)})}),Ws=Be(e("upload").description("Upload a Fusion portal bundle to the portal registry.").addHelpText("after",["","Uploads a distributable portal bundle (e.g., portal-bundle.zip) to the Fusion portal registry.","","Examples:"," $ ffc portal upload"," $ ffc portal upload my-portal-bundle.zip --name my-portal"," $ ffc portal upload --debug"].join("\n")).option("-d, --debug [boolean]","Enable debug mode for verbose logging",!1).addOption(je({allowDev:!1})).argument("<bundle>","Portal bundle to upload (e.g., out/bundle.zip)").action(async(e,t)=>{const r=new d("portal:upload",{debug:t.debug});r?.start("Initializing Fusion Framework...");const n=await g({env:t.env,auth:{token:t.token,tenantId:t.tenantId,clientId:t.clientId}});r?.succeed("Initialized Fusion Framework"),await C({log:r,framework:n,fileOrBundle:e}).catch(e=>{r.error("Failed to upload bundle:",e),process.exit(1)})}));const qs=Be(e("tag").description("Tag your uploaded Fusion Portal build version with a specific tag.").addHelpText("after",["","Note: using --package is preferred over --manifest, since no infered compilation is required.","","Examples:"," $ ffc portal tag latest"," $ ffc portal tag latest --package my-portal@1.2.3 --env prod"," $ ffc portal tag preview --manifest ./portal.manifest.ts"].join("\n")).addOption(je({allowDev:!1})).option("-m, --manifest <string>","Manifest file to use. Note: ignoring if --package is provided").option("-p, --package [package@version]","Package to tag in format name@version (e.g., my-portal@1.0.0). If not provided, loaded from manifest").option("-d, --debug","Enable debug mode for verbose logging").option("--silent","Silent mode, suppresses output except errors").argument("<tag>","Tag to apply (latest | preview)").action(async(e,t)=>{const r=t.silent?null:new d("app:tag",{debug:t.debug}),n={command:"build",environment:t.env,mode:process.env.NODE_ENV??"production",root:process.cwd()},o=await async function(e,t){if(e.package){const[t,r]=e.package.split("@");if(!t||!r)throw new Error("Package must be in format name@version (e.g., my-portal@1.0.0). Please verify the package name and version with --package");return{name:t,version:r}}const{manifest:r}=await L({manifest:e.manifest,env:t}),n=r.build?.version;if(!n)throw new Error(`Could not determine version from manifest. Please verify manifest ${e.manifest} or provide a package name and version with --package`);return{name:r.name,version:n}}(t,n).catch(e=>{r?.error(`😢 ${e instanceof Error?e.message:"Unknown error occurred"}`),r?.debug(e),process.exit(1)});r?.info("Tagging portal:",Ae.greenBright(`${o.name}@${o.version} - ${e}`)),r?.start("Initializing Fusion Framework...");const i=await g({env:t.env,auth:{token:t.token,tenantId:t.tenantId,clientId:t.clientId}});r?.succeed("Initialized Fusion Framework"),N({tag:e,name:o.name,version:o.version,framework:i,log:r}).catch(e=>{r?.error("😢 Failed to tag application:",e),process.exit(1)})})),Ks=Be(e("publish").description("Build, upload, and tag your Fusion portal bundle for deployment.").addHelpText("after",["","If no manifest is provided, a default portal.manifest(.$ENV)?.[ts|js|json] is used from the current directory.","example: `ffc portal publish --env prod` will search for `portal.manifest.prod.ts` then fallback to `portal.manifest.ts`","","NOTE: portal manifest is not required, a default manifest will be generated if not provided","","Examples:"," $ ffc portal publish"," $ ffc portal publish --env prod --manifest portal.manifest.prod.ts"," $ ffc portal publish --tag preview"].join("\n")).option("-d, --debug","Enable debug mode for verbose logging",!1).addOption(je({allowDev:!1})).option("-m, --manifest [string]","Manifest file to use for bundling (e.g., my-portal.manifest.ts)").option("--schema [string]","Schema file to use for validation").option("-t, --tag [string]",`Tag to apply to the published portal (${Object.values(I).join(" | ")})`,I.Latest).action(async e=>{const t=new d("portal:publish",{debug:e.debug});t?.info("Using environment:",Ae.redBright(e.env)),t.start("📦 Bundling Portal Template...");const r=await k({log:t,manifest:e.manifest,schema:e.schema}).catch(e=>{t.error("😢 Failed to create bundle:",e),process.exit(1)});t.succeed("📦 Bundling completed"),t?.start("💾 Initializing Fusion Framework...");const n=await g({env:e.env,auth:{token:e.token,tenantId:e.tenantId,clientId:e.clientId}});t?.succeed("💾 Initialized Fusion Framework"),t.start("🚀 Uploading Portal Template..."),await C({log:t,framework:n,fileOrBundle:r.archive}).catch(e=>{t.error("😢 Failed to upload bundle:",e),process.exit(1)}),t.succeed("🚀 Upload completed"),t.start("🏷️ Tagging Portal Template..."),await N({tag:e.tag,name:r.manifest.name,version:r.manifest.build.version,framework:n,log:t}).catch(e=>{t.error("😢 Failed to tag Portal Template:",e),process.exit(1)}),t.succeed("🏷️ Tagging completed")})),Ys=Be(e("config").description("Generate or publish the Fusion portal configuration file.").addHelpText("after",["","By default, outputs the generated config object to stdout or a file. Use --publish to upload the config to the Fusion portal registry.","- Options [--token, --tenantId, --clientId, --manifest] are only relevant when --publish is used.",'- Option [-e, --env] cannot be set to "dev" when --publish is used.',"","Note:","- If not `portal.config(.$ENV)?.[ts|js|json]` is found it will fallback to generate a default config (empty object)","- If not `portal.manifest(.$ENV)?.[ts|js|json]` is found it will fallback to generate a default manifest","","Examples:"," $ ffc portal config app.config.ts"," $ ffc portal config portal.config.prod.ts --output ./dist/portal.config.json"," $ ffc portal config portal.manifest.prod.ts --silent > ./dist/portal.config.json"," $ ffc portal config --publish --manifest portal.manifest.ts --env prod"," $ ffc portal config --env prod my-custom.config.ts"].join("\n")).option("--debug","Enable debug mode for verbose logging").option("--silent","Silent mode, suppresses output except errors").option("--publish <name@version>","Publish config to Fusion portal registry, Identifier of the portal, example my-portal@1.2.3").addOption(je({allowDev:!0})).option("-o, --output <stdout|path>","Output the result to stdout or a file (ignored with --publish, default: stdout)","stdout").argument("[config]","Path to the portal config file (e.g., portal.config[.env]?.[ts,js,json])").action(async(e,t)=>{const r=t.silent?null:new d("portal:config",{debug:!!t.debug});if(t.publish){const[e,n]=t.publish.split("@")||[];return e&&n||(r?.fail("🤪","Portal identifier is required when using",Ae.blue("--publish")),r?.info("Example: fusion-framework-cli portal config --publish my-portal@1.2.3"),process.exit(1)),"dev"===t.env&&(r?.fail("🤪",Ae.blue("--env"),'cannot be "dev" when',Ae.blue("--publish")," is used"),process.exit(1)),O({config:t.config,portal:{name:e,version:n},environment:t.env,auth:"token"in t?{token:t.token}:t,debug:t.debug})}const{config:n}=await A({log:r,config:e,env:{environment:t.env},output:"stdout"===t.output?void 0:t.output});"stdout"===t.output&&console.log(JSON.stringify(n,null,2))})),Js=e("portal").description("Develop and deploy portal templates").addCommand(Ct).addCommand(Br).addCommand(zs).addCommand(Hs).addCommand(Vs).addCommand(Ws).addCommand(qs).addCommand(Ks).addCommand(Ys);const[Xs]=process.versions.node.split(".").map(Number);Xs<Number(20)&&(console.error(Ae.red("[ERROR]"),"Fusion Framework CLI requires Node.js 20 or higher."),process.exit(1));Xs!==Number(22)&&console.warn(Ae.yellow("[WARNING]"),"Node.js 22.x (LTS) is recommended for best compatibility. You are using Node.js",process.versions.node);const Zs=l({cwd:i(import.meta.url)});if(!Zs)throw Error("failed to find program root");process.env.CLI_BIN=s(a(Zs.path),String(Zs.packageJson.bin?.["fusion-framework-cli"]));const Qs=new n;Qs.name(Zs.packageJson.name),Qs.description([`${Zs.packageJson.name}@${Zs.packageJson.version}`,"","Fusion Framework CLI","","A toolkit for building, packaging, deploying, and managing Fusion applications and portals.","","• Run fusion <command> --help for details on any command.","• For documentation, issues, and source code, visit:"," https://equinor.github.io/fusion-framework/cli/"].join("\n")),Qs.version(Zs.packageJson.version,"-V, --version","CLI version"),(e=>{e.addCommand(bt),e.addCommand(Pt),e.addCommand(Lt),e.addCommand(kt),e.addCommand(Js)})(Qs),Qs.parse();
7
+ deps: ${n}}`};const a={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(e){const[t,r]=function({schema:e}){const t={},r={};for(const n in e){if("__proto__"===n)continue;(Array.isArray(e[n])?t:r)[n]=e[n]}return[t,r]}(e);i(e,t),s(e,r)}};function i(e,r=e.schema){const{gen:a,data:i,it:s}=e;if(0===Object.keys(r).length)return;const o=a.let("missing");for(const c in r){const l=r[c];if(0===l.length)continue;const u=(0,n.propertyInData)(a,i,c,s.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(", ")}),s.allErrors?a.if(u,()=>{for(const t of l)(0,n.checkReportMissingProp)(e,t)}):(a.if(t._`${u} && (${(0,n.checkMissingProp)(e,l,o)})`),(0,n.reportMissingProp)(e,o),a.else())}}function s(e,t=e.schema){const{gen:a,data:i,keyword:s,it:o}=e,c=a.name("valid");for(const l in t)(0,r.alwaysValidSchema)(o,t[l])||(a.if((0,n.propertyInData)(a,i,l,o.opts.ownProperties),()=>{const t=e.subschema({keyword:s,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>a.var(c,!0)),e.ok(c))}e.validatePropertyDeps=i,e.validateSchemaDeps=s,e.default=a}(wF)),wF}var NF,kF={};var xF,EF={};function PF(){if(xF)return EF;xF=1,Object.defineProperty(EF,"__esModule",{value:!0});const e=LD(),t=dD(),r=bD(),n=hD(),a={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:e})=>t._`{additionalProperty: ${e.additionalProperty}}`},code(a){const{gen:i,schema:s,parentSchema:o,data:c,errsCount:l,it:u}=a;if(!l)throw new Error("ajv implementation error");const{allErrors:d,opts:p}=u;if(u.props=!0,"all"!==p.removeAdditional&&(0,n.alwaysValidSchema)(u,s))return;const m=(0,e.allSchemaProperties)(o.properties),h=(0,e.allSchemaProperties)(o.patternProperties);function f(e){i.code(t._`delete ${c}[${e}]`)}function g(e){if("all"===p.removeAdditional||p.removeAdditional&&!1===s)f(e);else{if(!1===s)return a.setParams({additionalProperty:e}),a.error(),void(d||i.break());if("object"==typeof s&&!(0,n.alwaysValidSchema)(u,s)){const r=i.name("valid");"failing"===p.removeAdditional?(y(e,r,!1),i.if((0,t.not)(r),()=>{a.reset(),f(e)})):(y(e,r),d||i.if((0,t.not)(r),()=>i.break()))}}}function y(e,t,r){const i={keyword:"additionalProperties",dataProp:e,dataPropType:n.Type.Str};!1===r&&Object.assign(i,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(i,t)}i.forIn("key",c,r=>{m.length||h.length?i.if(function(r){let s;if(m.length>8){const t=(0,n.schemaRefOrVal)(u,o.properties,"properties");s=(0,e.isOwnProperty)(i,t,r)}else s=m.length?(0,t.or)(...m.map(e=>t._`${r} === ${e}`)):t.nil;return h.length&&(s=(0,t.or)(s,...h.map(n=>t._`${(0,e.usePattern)(a,n)}.test(${r})`))),(0,t.not)(s)}(r),()=>g(r)):g(r)}),a.ok(t._`${l} === ${r.default.errors}`)}};return EF.default=a,EF}var CF,AF={};var IF,OF={};var TF,$F={};var zF,RF={};var LF,MF={};var DF,jF={};var FF,UF={};var qF,BF,VF={};function GF(){if(BF)return oF;BF=1,Object.defineProperty(oF,"__esModule",{value:!0});const e=lF(),t=function(){if(dF)return pF;dF=1,Object.defineProperty(pF,"__esModule",{value:!0});const e=hF(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,e.validateTuple)(t,"items")};return pF.default=t,pF}(),r=hF(),n=function(){if(fF)return gF;fF=1,Object.defineProperty(gF,"__esModule",{value:!0});const e=dD(),t=hD(),r=LD(),n=lF(),a={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:t}})=>e.str`must NOT have more than ${t} items`,params:({params:{len:t}})=>e._`{limit: ${t}}`},code(e){const{schema:a,parentSchema:i,it:s}=e,{prefixItems:o}=i;s.items=!0,(0,t.alwaysValidSchema)(s,a)||(o?(0,n.validateAdditionalItems)(e,o):e.ok((0,r.validateArray)(e)))}};return gF.default=a,gF}(),a=bF(),i=SF(),s=function(){if(NF)return kF;NF=1,Object.defineProperty(kF,"__esModule",{value:!0});const e=dD(),t=hD(),r={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:t})=>e._`{propertyName: ${t.propertyName}}`},code(r){const{gen:n,schema:a,data:i,it:s}=r;if((0,t.alwaysValidSchema)(s,a))return;const o=n.name("valid");n.forIn("key",i,t=>{r.setParams({propertyName:t}),r.subschema({keyword:"propertyNames",data:t,dataTypes:["string"],propertyName:t,compositeRule:!0},o),n.if((0,e.not)(o),()=>{r.error(!0),s.allErrors||n.break()})}),r.ok(o)}};return kF.default=r,kF}(),o=PF(),c=function(){if(CF)return AF;CF=1,Object.defineProperty(AF,"__esModule",{value:!0});const e=JD(),t=LD(),r=hD(),n=PF(),a={keyword:"properties",type:"object",schemaType:"object",code(a){const{gen:i,schema:s,parentSchema:o,data:c,it:l}=a;"all"===l.opts.removeAdditional&&void 0===o.additionalProperties&&n.default.code(new e.KeywordCxt(l,n.default,"additionalProperties"));const u=(0,t.allSchemaProperties)(s);for(const e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&!0!==l.props&&(l.props=r.mergeEvaluated.props(i,(0,r.toHash)(u),l.props));const d=u.filter(e=>!(0,r.alwaysValidSchema)(l,s[e]));if(0===d.length)return;const p=i.name("valid");for(const e of d)m(e)?h(e):(i.if((0,t.propertyInData)(i,c,e,l.opts.ownProperties)),h(e),l.allErrors||i.else().var(p,!0),i.endIf()),a.it.definedProperties.add(e),a.ok(p);function m(e){return l.opts.useDefaults&&!l.compositeRule&&void 0!==s[e].default}function h(e){a.subschema({keyword:"properties",schemaProp:e,dataProp:e},p)}}};return AF.default=a,AF}(),l=function(){if(IF)return OF;IF=1,Object.defineProperty(OF,"__esModule",{value:!0});const e=LD(),t=dD(),r=hD(),n=hD(),a={keyword:"patternProperties",type:"object",schemaType:"object",code(a){const{gen:i,schema:s,data:o,parentSchema:c,it:l}=a,{opts:u}=l,d=(0,e.allSchemaProperties)(s),p=d.filter(e=>(0,r.alwaysValidSchema)(l,s[e]));if(0===d.length||p.length===d.length&&(!l.opts.unevaluated||!0===l.props))return;const m=u.strictSchema&&!u.allowMatchingProperties&&c.properties,h=i.name("valid");!0===l.props||l.props instanceof t.Name||(l.props=(0,n.evaluatedPropsToName)(i,l.props));const{props:f}=l;function g(e){for(const t in m)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function y(r){i.forIn("key",o,s=>{i.if(t._`${(0,e.usePattern)(a,r)}.test(${s})`,()=>{const e=p.includes(r);e||a.subschema({keyword:"patternProperties",schemaProp:r,dataProp:s,dataPropType:n.Type.Str},h),l.opts.unevaluated&&!0!==f?i.assign(t._`${f}[${s}]`,!0):e||l.allErrors||i.if((0,t.not)(h),()=>i.break())})})}!function(){for(const e of d)m&&g(e),l.allErrors?y(e):(i.var(h,!0),y(e),i.if(h))}()}};return OF.default=a,OF}(),u=function(){if(TF)return $F;TF=1,Object.defineProperty($F,"__esModule",{value:!0});const e=hD(),t={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){const{gen:r,schema:n,it:a}=t;if((0,e.alwaysValidSchema)(a,n))return void t.fail();const i=r.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),t.failResult(i,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};return $F.default=t,$F}(),d=function(){if(zF)return RF;zF=1,Object.defineProperty(RF,"__esModule",{value:!0});const e={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:LD().validateUnion,error:{message:"must match a schema in anyOf"}};return RF.default=e,RF}(),p=function(){if(LF)return MF;LF=1,Object.defineProperty(MF,"__esModule",{value:!0});const e=dD(),t=hD(),r={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:t})=>e._`{passingSchemas: ${t.passing}}`},code(r){const{gen:n,schema:a,parentSchema:i,it:s}=r;if(!Array.isArray(a))throw new Error("ajv implementation error");if(s.opts.discriminator&&i.discriminator)return;const o=a,c=n.let("valid",!1),l=n.let("passing",null),u=n.name("_valid");r.setParams({passing:l}),n.block(function(){o.forEach((a,i)=>{let o;(0,t.alwaysValidSchema)(s,a)?n.var(u,!0):o=r.subschema({keyword:"oneOf",schemaProp:i,compositeRule:!0},u),i>0&&n.if(e._`${u} && ${c}`).assign(c,!1).assign(l,e._`[${l}, ${i}]`).else(),n.if(u,()=>{n.assign(c,!0),n.assign(l,i),o&&r.mergeEvaluated(o,e.Name)})})}),r.result(c,()=>r.reset(),()=>r.error(!0))}};return MF.default=r,MF}(),m=function(){if(DF)return jF;DF=1,Object.defineProperty(jF,"__esModule",{value:!0});const e=hD(),t={keyword:"allOf",schemaType:"array",code(t){const{gen:r,schema:n,it:a}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");const i=r.name("valid");n.forEach((r,n)=>{if((0,e.alwaysValidSchema)(a,r))return;const s=t.subschema({keyword:"allOf",schemaProp:n},i);t.ok(i),t.mergeEvaluated(s)})}};return jF.default=t,jF}(),h=function(){if(FF)return UF;FF=1,Object.defineProperty(UF,"__esModule",{value:!0});const e=dD(),t=hD(),r={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:t})=>e.str`must match "${t.ifClause}" schema`,params:({params:t})=>e._`{failingKeyword: ${t.ifClause}}`},code(r){const{gen:a,parentSchema:i,it:s}=r;void 0===i.then&&void 0===i.else&&(0,t.checkStrictMode)(s,'"if" without "then" and "else" is ignored');const o=n(s,"then"),c=n(s,"else");if(!o&&!c)return;const l=a.let("valid",!0),u=a.name("_valid");if(function(){const e=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},u);r.mergeEvaluated(e)}(),r.reset(),o&&c){const e=a.let("ifClause");r.setParams({ifClause:e}),a.if(u,d("then",e),d("else",e))}else o?a.if(u,d("then")):a.if((0,e.not)(u),d("else"));function d(t,n){return()=>{const i=r.subschema({keyword:t},u);a.assign(l,u),r.mergeValidEvaluated(i,l),n?a.assign(n,e._`${t}`):r.setParams({ifClause:t})}}r.pass(l,()=>r.error(!0))}};function n(e,r){const n=e.schema[r];return void 0!==n&&!(0,t.alwaysValidSchema)(e,n)}return UF.default=r,UF}(),f=function(){if(qF)return VF;qF=1,Object.defineProperty(VF,"__esModule",{value:!0});const e=hD(),t={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:r,it:n}){void 0===r.if&&(0,e.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};return VF.default=t,VF}();return oF.default=function(g=!1){const y=[u.default,d.default,p.default,m.default,h.default,f.default,s.default,o.default,i.default,c.default,l.default];return g?y.push(t.default,n.default):y.push(e.default,r.default),y.push(a.default),y},oF}var HF,KF={},WF={};function ZF(){if(HF)return WF;HF=1,Object.defineProperty(WF,"__esModule",{value:!0}),WF.dynamicAnchor=void 0;const e=dD(),t=bD(),r=ij(),n=Ej(),a={keyword:"$dynamicAnchor",schemaType:"string",code:e=>i(e,e.schema)};function i(a,i){const{gen:s,it:o}=a;o.schemaEnv.root.dynamicAnchors[i]=!0;const c=e._`${t.default.dynamicAnchors}${(0,e.getProperty)(i)}`,l="#"===o.errSchemaPath?o.validateName:function(e){const{schemaEnv:t,schema:a,self:i}=e.it,{root:s,baseId:o,localRefs:c,meta:l}=t.root,{schemaId:u}=i.opts,d=new r.SchemaEnv({schema:a,schemaId:u,root:s,baseId:o,localRefs:c,meta:l});return r.compileSchema.call(i,d),(0,n.getValidate)(e,d)}(a);s.if(e._`!${c}`,()=>s.assign(c,l))}return WF.dynamicAnchor=i,WF.default=a,WF}var JF,YF={};function QF(){if(JF)return YF;JF=1,Object.defineProperty(YF,"__esModule",{value:!0}),YF.dynamicRef=void 0;const e=dD(),t=bD(),r=Ej(),n={keyword:"$dynamicRef",schemaType:"string",code:e=>a(e,e.schema)};function a(n,a){const{gen:i,keyword:s,it:o}=n;if("#"!==a[0])throw new Error(`"${s}" only supports hash fragment reference`);const c=a.slice(1);if(o.allErrors)l();else{const e=i.let("valid",!1);l(e),n.ok(e)}function l(r){if(o.schemaEnv.root.dynamicAnchors[c]){const n=i.let("_v",e._`${t.default.dynamicAnchors}${(0,e.getProperty)(c)}`);i.if(n,u(n,r),u(o.validateName,r))}else u(o.validateName,r)()}function u(e,t){return t?()=>i.block(()=>{(0,r.callRef)(n,e),i.let(t,!0)}):()=>(0,r.callRef)(n,e)}}return YF.dynamicRef=a,YF.default=n,YF}var XF,eU={};var tU,rU,nU={};function aU(){if(rU)return KF;rU=1,Object.defineProperty(KF,"__esModule",{value:!0});const e=ZF(),t=QF(),r=function(){if(XF)return eU;XF=1,Object.defineProperty(eU,"__esModule",{value:!0});const e=ZF(),t=hD(),r={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,e.dynamicAnchor)(r,""):(0,t.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};return eU.default=r,eU}(),n=function(){if(tU)return nU;tU=1,Object.defineProperty(nU,"__esModule",{value:!0});const e=QF(),t={keyword:"$recursiveRef",schemaType:"string",code:t=>(0,e.dynamicRef)(t,t.schema)};return nU.default=t,nU}(),a=[e.default,t.default,r.default,n.default];return KF.default=a,KF}var iU,sU={},oU={};var cU,lU={};var uU,dU,pU={};function mU(){if(dU)return sU;dU=1,Object.defineProperty(sU,"__esModule",{value:!0});const e=function(){if(iU)return oU;iU=1,Object.defineProperty(oU,"__esModule",{value:!0});const e=SF(),t={keyword:"dependentRequired",type:"object",schemaType:"object",error:e.error,code:t=>(0,e.validatePropertyDeps)(t)};return oU.default=t,oU}(),t=function(){if(cU)return lU;cU=1,Object.defineProperty(lU,"__esModule",{value:!0});const e=SF(),t={keyword:"dependentSchemas",type:"object",schemaType:"object",code:t=>(0,e.validateSchemaDeps)(t)};return lU.default=t,lU}(),r=function(){if(uU)return pU;uU=1,Object.defineProperty(pU,"__esModule",{value:!0});const e=hD(),t={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:t,parentSchema:r,it:n}){void 0===r.contains&&(0,e.checkStrictMode)(n,`"${t}" without "contains" is ignored`)}};return pU.default=t,pU}(),n=[e.default,t.default,r.default];return sU.default=n,sU}var hU,fU={},gU={};function yU(){if(hU)return gU;hU=1,Object.defineProperty(gU,"__esModule",{value:!0});const e=dD(),t=hD(),r=bD(),n={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:{message:"must NOT have unevaluated properties",params:({params:t})=>e._`{unevaluatedProperty: ${t.unevaluatedProperty}}`},code(n){const{gen:a,schema:i,data:s,errsCount:o,it:c}=n;if(!o)throw new Error("ajv implementation error");const{allErrors:l,props:u}=c;function d(r){if(!1===i)return n.setParams({unevaluatedProperty:r}),n.error(),void(l||a.break());if(!(0,t.alwaysValidSchema)(c,i)){const i=a.name("valid");n.subschema({keyword:"unevaluatedProperties",dataProp:r,dataPropType:t.Type.Str},i),l||a.if((0,e.not)(i),()=>a.break())}}u instanceof e.Name?a.if(e._`${u} !== true`,()=>a.forIn("key",s,t=>a.if(function(t,r){return e._`!${t} || !${t}[${r}]`}(u,t),()=>d(t)))):!0!==u&&a.forIn("key",s,t=>void 0===u?d(t):a.if(function(t,r){const n=[];for(const a in t)!0===t[a]&&n.push(e._`${r} !== ${a}`);return(0,e.and)(...n)}(u,t),()=>d(t))),c.props=!0,n.ok(e._`${o} === ${r.default.errors}`)}};return gU.default=n,gU}var vU,bU,_U={};function wU(){if(vU)return _U;vU=1,Object.defineProperty(_U,"__esModule",{value:!0});const e=dD(),t=hD(),r={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:{message:({params:{len:t}})=>e.str`must NOT have more than ${t} items`,params:({params:{len:t}})=>e._`{limit: ${t}}`},code(r){const{gen:n,schema:a,data:i,it:s}=r,o=s.items||0;if(!0===o)return;const c=n.const("len",e._`${i}.length`);if(!1===a)r.setParams({len:o}),r.fail(e._`${c} > ${o}`);else if("object"==typeof a&&!(0,t.alwaysValidSchema)(s,a)){const a=n.var("valid",e._`${c} <= ${o}`);n.if((0,e.not)(a),()=>function(a,i){n.forRange("i",i,c,i=>{r.subschema({keyword:"unevaluatedItems",dataProp:i,dataPropType:t.Type.Num},a),s.allErrors||n.if((0,e.not)(a),()=>n.break())})}(a,o)),r.ok(a)}s.items=!0}};return _U.default=r,_U}var SU,NU,kU={},xU={};function EU(){if(SU)return xU;SU=1,Object.defineProperty(xU,"__esModule",{value:!0});const e=dD(),t={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:t})=>e.str`must match format "${t}"`,params:({schemaCode:t})=>e._`{format: ${t}}`},code(t,r){const{gen:n,data:a,$data:i,schema:s,schemaCode:o,it:c}=t,{opts:l,errSchemaPath:u,schemaEnv:d,self:p}=c;l.validateFormats&&(i?function(){const i=n.scopeValue("formats",{ref:p.formats,code:l.code.formats}),s=n.const("fDef",e._`${i}[${o}]`),c=n.let("fType"),u=n.let("format");n.if(e._`typeof ${s} == "object" && !(${s} instanceof RegExp)`,()=>n.assign(c,e._`${s}.type || "string"`).assign(u,e._`${s}.validate`),()=>n.assign(c,e._`"string"`).assign(u,s)),t.fail$data((0,e.or)(!1===l.strictSchema?e.nil:e._`${o} && !${u}`,function(){const t=d.$async?e._`(${s}.async ? await ${u}(${a}) : ${u}(${a}))`:e._`${u}(${a})`,n=e._`(typeof ${u} == "function" ? ${t} : ${u}.test(${a}))`;return e._`${u} && ${u} !== true && ${c} === ${r} && !${n}`}()))}():function(){const i=p.formats[s];if(!i)return void function(){if(!1===l.strictSchema)return void p.logger.warn(e());throw new Error(e());function e(){return`unknown format "${s}" ignored in schema at path "${u}"`}}();if(!0===i)return;const[o,c,m]=function(t){const r=t instanceof RegExp?(0,e.regexpCode)(t):l.code.formats?e._`${l.code.formats}${(0,e.getProperty)(s)}`:void 0,a=n.scopeValue("formats",{key:s,ref:t,code:r});if("object"==typeof t&&!(t instanceof RegExp))return[t.type||"string",t.validate,e._`${a}.validate`];return["string",t,a]}(i);o===r&&t.pass(function(){if("object"==typeof i&&!(i instanceof RegExp)&&i.async){if(!d.$async)throw new Error("async format in sync schema");return e._`await ${m}(${a})`}return"function"==typeof c?e._`${m}(${a})`:e._`${m}.test(${a})`}())}())}};return xU.default=t,xU}var PU,CU,AU={};function IU(){if(CU)return _j;CU=1,Object.defineProperty(_j,"__esModule",{value:!0});const e=Pj(),t=iF(),r=GF(),n=aU(),a=mU(),i=function(){if(bU)return fU;bU=1,Object.defineProperty(fU,"__esModule",{value:!0});const e=yU(),t=wU(),r=[e.default,t.default];return fU.default=r,fU}(),s=function(){if(NU)return kU;NU=1,Object.defineProperty(kU,"__esModule",{value:!0});const e=[EU().default];return kU.default=e,kU}(),o=(PU||(PU=1,Object.defineProperty(AU,"__esModule",{value:!0}),AU.contentVocabulary=AU.metadataVocabulary=void 0,AU.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],AU.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),AU),c=[n.default,e.default,t.default,(0,r.default)(!0),s.default,o.metadataVocabulary,o.contentVocabulary,a.default,i.default];return _j.default=c,_j}var OU,TU,$U={},zU={};function RU(){if(TU)return $U;TU=1,Object.defineProperty($U,"__esModule",{value:!0});const e=dD(),t=(OU||(OU=1,Object.defineProperty(zU,"__esModule",{value:!0}),zU.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(r||(zU.DiscrError=r={}))),zU);var r;const n=ij(),a=rj(),i=hD(),s={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:r}})=>e===t.DiscrError.Tag?`tag "${r}" must be string`:`value of tag "${r}" must be in oneOf`,params:({params:{discrError:t,tag:r,tagName:n}})=>e._`{error: ${t}, tag: ${n}, tagValue: ${r}}`},code(r){const{gen:s,data:o,schema:c,parentSchema:l,it:u}=r,{oneOf:d}=l;if(!u.opts.discriminator)throw new Error("discriminator: requires discriminator option");const p=c.propertyName;if("string"!=typeof p)throw new Error("discriminator: requires propertyName");if(c.mapping)throw new Error("discriminator: mapping is not supported");if(!d)throw new Error("discriminator: requires oneOf keyword");const m=s.let("valid",!1),h=s.const("tag",e._`${o}${(0,e.getProperty)(p)}`);function f(t){const n=s.name("valid"),a=r.subschema({keyword:"oneOf",schemaProp:t},n);return r.mergeEvaluated(a,e.Name),n}s.if(e._`typeof ${h} == "string"`,()=>function(){const o=function(){var e;const t={},r=o(l);let s=!0;for(let t=0;t<d.length;t++){let l=d[t];if((null==l?void 0:l.$ref)&&!(0,i.schemaHasRulesButRef)(l,u.self.RULES)){const e=l.$ref;if(l=n.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),l instanceof n.SchemaEnv&&(l=l.schema),void 0===l)throw new a.default(u.opts.uriResolver,u.baseId,e)}const m=null===(e=null==l?void 0:l.properties)||void 0===e?void 0:e[p];if("object"!=typeof m)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${p}"`);s=s&&(r||o(l)),c(m,t)}if(!s)throw new Error(`discriminator: "${p}" must be required`);return t;function o({required:e}){return Array.isArray(e)&&e.includes(p)}function c(e,t){if(e.const)m(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${p}" must have "const" or "enum"`);for(const r of e.enum)m(r,t)}}function m(e,r){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${p}" values must be unique strings`);t[e]=r}}();s.if(!1);for(const t in o)s.elseIf(e._`${h} === ${t}`),s.assign(m,f(o[t]));s.else(),r.error(!1,{discrError:t.DiscrError.Mapping,tag:h,tagName:p}),s.endIf()}(),()=>r.error(!1,{discrError:t.DiscrError.Tag,tag:h,tagName:p})),r.ok(m)}};return $U.default=s,$U}var LU,MU,DU={},jU={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}},FU={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}},UU={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}},qU={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}},BU={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}},VU={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}},GU={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}},HU={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}};var KU=(MU||(MU=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv2020=void 0;const r=vj(),n=IU(),a=RU(),i=function(){if(LU)return DU;LU=1,Object.defineProperty(DU,"__esModule",{value:!0});const e=jU,t=FU,r=UU,n=qU,a=BU,i=VU,s=GU,o=HU,c=["/properties"];return DU.default=function(l){return[e,t,r,n,a,u(this,i),s,u(this,o)].forEach(e=>this.addMetaSchema(e,void 0,!1)),this;function u(e,t){return l?e.$dataMetaSchema(t,c):t}},DU}(),s="https://json-schema.org/draft/2020-12/schema";class o extends r.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),n.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(a.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();const{$data:e,meta:t}=this.opts;t&&(i.default.call(this,e),this.refs["http://json-schema.org/schema"]=s)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}}t.Ajv2020=o,e.exports=t=o,e.exports.Ajv2020=o,Object.defineProperty(t,"__esModule",{value:!0}),t.default=o;var c=JD();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var l=dD();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var u=XD();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return u.default}});var d=rj();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return d.default}})}(XM,XM.exports)),XM.exports),WU=ba(KU);const ZU=oe.object({templateEntry:oe.string({message:"templateEntry must be a string"}).describe("Main entry point for the portal"),schemaEntry:oe.string({message:"schemaEntry must be a string"}).describe("Schema file for portal validation"),assetPath:oe.string({message:"assetPath must be a string"}).optional().describe("Asset path for dev/preview builds"),githubRepo:oe.string({message:"githubRepo must be a string"}).optional().describe("GitHub repo URL or local git remote"),version:oe.string({message:"version must be a string"}).describe("Version from package.json"),timestamp:oe.string({message:"timestamp must be a string"}).describe("Current build timestamp (ISO8601)"),commitSha:oe.string({message:"commitSha must be a string"}).describe("Current git commit SHA"),annotations:oe.record(oe.string(),oe.string()).optional().describe("Optional build annotations"),projectPage:oe.string({message:"projectPage must be a string"}).optional().describe("Optional project homepage"),allowedExtensions:oe.array(oe.string({message:"Each allowed extension must be a string"}),{message:"allowedExtensions must be an array of strings"}).describe("List of allowed asset extensions (with leading dot)"),schema:oe.record(oe.string(),oe.unknown()).optional().describe("Optional schema for the portal"),config:oe.record(oe.string(),oe.unknown()).optional().describe("Optional configuration for the portal")});oe.object({name:oe.string({message:"name must be a string"}).describe("Short app key (unscoped, derived from package name)"),displayName:oe.string({message:"displayName must be a string"}).optional().describe("Full package name, may include scope"),description:oe.string({message:"description must be a string"}).optional().describe("Description of the portal"),build:ZU});const JU=e("schema").description("Generate or validate a Fusion portal schema file.").addHelpText("after",["","Examples:"," $ ffc portal schema"," $ ffc portal schema --output portal.schema.json"," $ ffc portal schema --validate my-config.json"].join("\n")).addOption(ht({allowDev:!0})).option("-o, --output <string>","Output file name (default: stdout)","stdout").option("-d, --debug","Enable debug mode for verbose logging",!1).option("-v, --validate <file>","Validate the generated schema against a JSON file").argument("[schema]","Schema build file to use (e.g., portal.schema[.env]?.[ts,js,json])").action(async(e,t)=>{const r=new m("portal:schema",{debug:t.debug});r.debug("Manifest file:",e),r.debug("Current working directory:",process.cwd()),r.start("Generating schema for the application...");const n=await(async(e,t)=>{const r=[`portal.schema.${e.environment}`,"portal.schema"],n=await Ie(r,{baseDir:e.root,extensions:t?.extensions,script:{resolve:async t=>{const r="function"==typeof t.default?await Promise.resolve(t.default(e)):t.default;if(!r)throw new Error("Schema function did not return a valid schema");return r}}});return{schema:n.config,path:n.path,extension:n.extension}})({command:"build",environment:t.environment,mode:"build",root:process.cwd()});if(r.debug("Schema:",JSON.stringify(n,null,2)),r.succeed("Schema generated successfully!"),t.output&&("stdout"===t.output?r.info("Schema:",JSON.stringify(n.schema,null,2)):(r.start(`Writing schema to ${t.output}`),((e,t,r)=>{const n=l(String(e));q(n)||H(n,{recursive:!0}),F(e,t,r)})(t.output,JSON.stringify(n.schema,null,2)),r.succeed(`Schema written to ${t.output}`)),process.exit(0)),t.validate){r.start("Validating schema against JSON file...");const e=new WU({strict:!0}).compile(n.schema),a=await Oe(t.validate);r.debug("JSON value:",JSON.stringify(a,null,2));e(a)?r.succeed("Schema validation passed!"):(r.fail("Schema validation failed:",JSON.stringify(e.errors??"Unknown error")),process.exit(1))}}),YU=e("build").description("Build the Fusion portal from a manifest file with environment-specific settings.").addHelpText("after",["","If no manifest is provided, the command will search for a default portal.manifest.[ts|js|json] in the current directory.","example: `ffc portal build --env prod` will search for `portal.manifest.prod.ts` then fallback to `portal.manifest.ts`","","NOTE: portal manifest is not required, a default manifest will be generated if not provided","","Examples:"," $ ffc portal build"," $ ffc portal build portal.manifest.prod.ts --debug",""].join("\n")).option("-d, --debug","Enable debug mode for verbose logging",!1).argument("[manifest]","Manifest build file to use for building (e.g., portal.manifest[.env]?.[ts|js|json])").action(async(e,t)=>{const r=new m("portal:build",{debug:t.debug});await A({log:r,manifest:e})}),QU=e("pack").description("Bundle the Fusion portal into a deployable archive.").addHelpText("after",["","If no manifest is provided, a default portal.manifest(.$ENV)?.[ts|js|json] is used from the current directory.","example: `ffc portal pack --env prod` will search for `portal.manifest.prod.ts` then fallback to `portal.manifest.ts`","","NOTE: portal manifest is not required, a default manifest will be generated if not provided","","Examples:"," $ ffc portal pack"," $ ffc portal pack portal.manifest.dev.ts --archive my-portal.zip --output ./dist"].join("\n")).option("-a, --archive [string]","Name of the output archive file (default: out/bundle.zip)","out/bundle.zip").option("-d, --debug [boolean]","Enable debug mode for verbose logging",!1).option("--schema [string]","Schema file to use for validation").argument("[manifest]","Manifest file to use for bundling (e.g., my-portal.manifest.ts)").action(async(e,t)=>{const r=new m("portal:pack",{debug:t.debug});await I({log:r,manifest:e,archive:t.archive,schema:t.schema}).catch(e=>{r.error("Failed to create package:",e),process.exit(1)})}),XU=_t(e("upload").description("Upload a Fusion portal bundle to the portal registry.").addHelpText("after",["","Uploads a distributable portal bundle (e.g., portal-bundle.zip) to the Fusion portal registry.","","Examples:"," $ ffc portal upload"," $ ffc portal upload my-portal-bundle.zip --name my-portal"," $ ffc portal upload --debug"].join("\n")).option("-d, --debug [boolean]","Enable debug mode for verbose logging",!1).addOption(ht({allowDev:!1})).argument("<bundle>","Portal bundle to upload (e.g., out/bundle.zip)").action(async(e,t)=>{const r=new m("portal:upload",{debug:t.debug});r?.start("Initializing Fusion Framework...");const n=await b({env:t.env,auth:{token:t.token,tenantId:t.tenantId,clientId:t.clientId}});r?.succeed("Initialized Fusion Framework"),await O({log:r,framework:n,fileOrBundle:e}).catch(e=>{r.error("Failed to upload bundle:",e),process.exit(1)})}));const eq=_t(e("tag").description("Tag your uploaded Fusion Portal build version with a specific tag.").addHelpText("after",["","Note: using --package is preferred over --manifest, since no infered compilation is required.","","Examples:"," $ ffc portal tag latest"," $ ffc portal tag latest --package my-portal@1.2.3 --env prod"," $ ffc portal tag preview --manifest ./portal.manifest.ts"," $ ffc portal tag next --package my-portal@2.0.0-alpha"," $ ffc portal tag stable --package my-portal@1.5.0"].join("\n")).addOption(ht({allowDev:!1})).option("-m, --manifest <string>","Manifest file to use. Note: ignoring if --package is provided").option("-p, --package [package@version]","Package to tag in format name@version (e.g., my-portal@1.0.0). If not provided, loaded from manifest").option("-d, --debug","Enable debug mode for verbose logging").option("--silent","Silent mode, suppresses output except errors").argument("<tag>","Tag to apply (e.g., latest, preview, next, or any string value)").action(async(e,t)=>{const r=t.silent?null:new m("app:tag",{debug:t.debug}),n={command:"build",environment:t.env,mode:process.env.NODE_ENV??"production",root:process.cwd()},a=await async function(e,t){if(e.package){const[t,r]=e.package.split("@");if(!t||!r)throw new Error("Package must be in format name@version (e.g., my-portal@1.0.0). Please verify the package name and version with --package");return{name:t,version:r}}const{manifest:r}=await C({manifest:e.manifest,env:t}),n=r.build?.version;if(!n)throw new Error(`Could not determine version from manifest. Please verify manifest ${e.manifest} or provide a package name and version with --package`);return{name:r.name,version:n}}(t,n).catch(e=>{r?.error(`😢 ${e instanceof Error?e.message:"Unknown error occurred"}`),r?.debug(e),process.exit(1)});r?.info("Tagging portal:",ut.greenBright(`${a.name}@${a.version} - ${e}`)),r?.start("Initializing Fusion Framework...");const i=await b({env:t.env,auth:{token:t.token,tenantId:t.tenantId,clientId:t.clientId}});r?.succeed("Initialized Fusion Framework"),T({tag:e,name:a.name,version:a.version,framework:i,log:r}).catch(e=>{r?.error("😢 Failed to tag application:",e),process.exit(1)})})),tq=_t(e("publish").description("Build, upload, and tag your Fusion portal bundle for deployment.").addHelpText("after",["","If no manifest is provided, a default portal.manifest(.$ENV)?.[ts|js|json] is used from the current directory.","example: `ffc portal publish --env prod` will search for `portal.manifest.prod.ts` then fallback to `portal.manifest.ts`","","NOTE: portal manifest is not required, a default manifest will be generated if not provided","","Examples:"," $ ffc portal publish"," $ ffc portal publish --env prod --manifest portal.manifest.prod.ts"," $ ffc portal publish --tag preview"," $ ffc portal publish --tag next"].join("\n")).option("-d, --debug","Enable debug mode for verbose logging",!1).addOption(ht({allowDev:!1})).option("-m, --manifest [string]","Manifest file to use for bundling (e.g., my-portal.manifest.ts)").option("--schema [string]","Schema file to use for validation").option("-t, --tag [string]","Tag to apply to the published portal (e.g., latest, preview, next, or any string value)","latest").action(async e=>{const t=new m("portal:publish",{debug:e.debug});t?.info("Using environment:",ut.redBright(e.env)),t.start("📦 Bundling Portal Template...");const r=await I({log:t,manifest:e.manifest,schema:e.schema}).catch(e=>{t.error("😢 Failed to create bundle:",e),process.exit(1)});t.succeed("📦 Bundling completed"),t?.start("💾 Initializing Fusion Framework...");const n=await b({env:e.env,auth:{token:e.token,tenantId:e.tenantId,clientId:e.clientId}});t?.succeed("💾 Initialized Fusion Framework"),t.start("🚀 Uploading Portal Template..."),await O({log:t,framework:n,fileOrBundle:r.archive}).catch(e=>{t.error("😢 Failed to upload bundle:",e),process.exit(1)}),t.succeed("🚀 Upload completed"),t.start("🏷️ Tagging Portal Template..."),await T({tag:e.tag,name:r.manifest.name,version:r.manifest.build.version,framework:n,log:t}).catch(e=>{t.error("😢 Failed to tag Portal Template:",e),process.exit(1)}),t.succeed("🏷️ Tagging completed")})),rq=_t(e("config").description("Generate or publish the Fusion portal configuration file.").addHelpText("after",["","By default, outputs the generated config object to stdout or a file. Use --publish to upload the config to the Fusion portal registry.","- Options [--token, --tenantId, --clientId, --manifest] are only relevant when --publish is used.",'- Option [-e, --env] cannot be set to "dev" when --publish is used.',"","Note:","- If not `portal.config(.$ENV)?.[ts|js|json]` is found it will fallback to generate a default config (empty object)","- If not `portal.manifest(.$ENV)?.[ts|js|json]` is found it will fallback to generate a default manifest","","Examples:"," $ ffc portal config app.config.ts"," $ ffc portal config portal.config.prod.ts --output ./dist/portal.config.json"," $ ffc portal config portal.manifest.prod.ts --silent > ./dist/portal.config.json"," $ ffc portal config --publish --manifest portal.manifest.ts --env prod"," $ ffc portal config --env prod my-custom.config.ts"].join("\n")).option("--debug","Enable debug mode for verbose logging").option("--silent","Silent mode, suppresses output except errors").option("--publish <name@version>","Publish config to Fusion portal registry, Identifier of the portal, example my-portal@1.2.3").addOption(ht({allowDev:!0})).option("-o, --output <stdout|path>","Output the result to stdout or a file (ignored with --publish, default: stdout)","stdout").argument("[config]","Path to the portal config file (e.g., portal.config[.env]?.[ts,js,json])").action(async(e,t)=>{const r=t.silent?null:new m("portal:config",{debug:!!t.debug});if(t.publish){const[e,n]=t.publish.split("@")||[];return e&&n||(r?.fail("🤪","Portal identifier is required when using",ut.blue("--publish")),r?.info("Example: fusion-framework-cli portal config --publish my-portal@1.2.3"),process.exit(1)),"dev"===t.env&&(r?.fail("🤪",ut.blue("--env"),'cannot be "dev" when',ut.blue("--publish")," is used"),process.exit(1)),$({config:t.config,portal:{name:e,version:n},environment:t.env,auth:"token"in t?{token:t.token}:t,debug:t.debug})}const{config:n}=await z({log:r,config:e,env:{environment:t.env},output:"stdout"===t.output?void 0:t.output});"stdout"===t.output&&console.log(JSON.stringify(n,null,2))})),nq=e("portal").description("Develop and deploy portal templates").addCommand(oM).addCommand(YM).addCommand(JU).addCommand(YU).addCommand(QU).addCommand(XU).addCommand(eq).addCommand(tq).addCommand(rq);a();const[aq]=process.versions.node.split(".").map(Number);aq<Number(20)&&(console.error(ut.red("[ERROR]"),"Fusion Framework CLI requires Node.js 20 or higher."),process.exit(1));aq!==Number(22)&&console.warn(ut.yellow("[WARNING]"),"Node.js 22.x (LTS) is recommended for best compatibility. You are using Node.js",process.versions.node);const iq=p({cwd:s(import.meta.url)});if(!iq)throw Error("failed to find program root");process.env.CLI_BIN=c(l(iq.path),String(iq.packageJson.bin?.["fusion-framework-cli"]));const sq=new n;sq.name(iq.packageJson.name),sq.description([`${iq.packageJson.name}@${iq.packageJson.version}`,"","Fusion Framework CLI","","A toolkit for building, packaging, deploying, and managing Fusion applications and portals.","","• Run fusion <command> --help for details on any command.","• For documentation, issues, and source code, visit:"," https://equinor.github.io/fusion-framework/cli/"].join("\n")),sq.version(iq.packageJson.version,"-V, --version","CLI version"),(e=>{e.addCommand(Yt),e.addCommand(rr),e.addCommand(nr),e.addCommand(ir),e.addCommand(sM),e.addCommand(nq)})(sq),sq.parse();