@equinor/fusion-framework-cli 13.0.0-cli-search-index.4 → 13.0.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.
Files changed (53) hide show
  1. package/CHANGELOG.md +125 -56
  2. package/README.md +24 -0
  3. package/bin/build/bin.mjs +1 -1
  4. package/bin/build/cli.mjs +6 -6
  5. package/dist/esm/lib/dev-server.js +1 -0
  6. package/dist/esm/lib/dev-server.js.map +1 -1
  7. package/dist/esm/lib/fusion-cli-config.js +21 -0
  8. package/dist/esm/lib/fusion-cli-config.js.map +1 -0
  9. package/dist/esm/lib/index.js +1 -0
  10. package/dist/esm/lib/index.js.map +1 -1
  11. package/dist/esm/version.js +1 -1
  12. package/dist/types/cli/commands/create/_helpers/cleanup-template-files.d.ts +4 -2
  13. package/dist/types/cli/commands/create/_helpers/open-in-ide.d.ts +3 -2
  14. package/dist/types/cli/commands/create/_helpers/select-git-protocol.d.ts +7 -2
  15. package/dist/types/cli/commands/create/_helpers/setup-repository.d.ts +6 -2
  16. package/dist/types/cli/commands/create/app.d.ts +4 -1
  17. package/dist/types/cli/commands/index.d.ts +1 -1
  18. package/dist/types/cli/plugins/loader.d.ts +2 -0
  19. package/dist/types/lib/dev-server.d.ts +1 -0
  20. package/dist/types/lib/fusion-cli-config.d.ts +84 -0
  21. package/dist/types/lib/index.d.ts +1 -0
  22. package/dist/types/version.d.ts +1 -1
  23. package/docs/ai-commands.md +28 -24
  24. package/package.json +12 -33
  25. package/dist/esm/lib/ai/fusion-ai.js +0 -2
  26. package/dist/esm/lib/ai/fusion-ai.js.map +0 -1
  27. package/dist/esm/lib/ai/index.js +0 -2
  28. package/dist/esm/lib/ai/index.js.map +0 -1
  29. package/dist/types/cli/commands/ai/chat.d.ts +0 -2
  30. package/dist/types/cli/commands/ai/embeddings.d.ts +0 -2
  31. package/dist/types/cli/commands/ai/index.d.ts +0 -30
  32. package/dist/types/cli/commands/ai/search.d.ts +0 -48
  33. package/dist/types/cli/commands/ai/utils/generate-cunk-id.d.ts +0 -8
  34. package/dist/types/cli/commands/ai/utils/git/file-changes.d.ts +0 -21
  35. package/dist/types/cli/commands/ai/utils/git/git-client.d.ts +0 -17
  36. package/dist/types/cli/commands/ai/utils/git/index.d.ts +0 -5
  37. package/dist/types/cli/commands/ai/utils/git/metadata.d.ts +0 -7
  38. package/dist/types/cli/commands/ai/utils/git/status.d.ts +0 -12
  39. package/dist/types/cli/commands/ai/utils/git/types.d.ts +0 -33
  40. package/dist/types/cli/commands/ai/utils/markdown/index.d.ts +0 -2
  41. package/dist/types/cli/commands/ai/utils/markdown/parser.d.ts +0 -21
  42. package/dist/types/cli/commands/ai/utils/markdown/types.d.ts +0 -11
  43. package/dist/types/cli/commands/ai/utils/setup-framework.d.ts +0 -10
  44. package/dist/types/cli/commands/ai/utils/ts-doc/constants.d.ts +0 -5
  45. package/dist/types/cli/commands/ai/utils/ts-doc/extractors.d.ts +0 -28
  46. package/dist/types/cli/commands/ai/utils/ts-doc/index.d.ts +0 -2
  47. package/dist/types/cli/commands/ai/utils/ts-doc/parser.d.ts +0 -23
  48. package/dist/types/cli/commands/ai/utils/ts-doc/types.d.ts +0 -20
  49. package/dist/types/cli/commands/ai/utils/types.d.ts +0 -7
  50. package/dist/types/cli/commands/create/_helpers/start-dev-server.d.ts +0 -17
  51. package/dist/types/cli/options/ai.d.ts +0 -105
  52. package/dist/types/lib/ai/fusion-ai.d.ts +0 -20
  53. package/dist/types/lib/ai/index.d.ts +0 -1
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{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 P,startPortalDevServer as E,loadPortalManifest as C,buildPortal as A,bundlePortal as O,uploadPortalBundle as I,tagPortal as $,publishPortalConfig as T,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 j,readFileSync as D,writeFileSync as F,rmSync as U,existsSync as B,readdirSync as q,copyFileSync as V,cpSync as G,mkdirSync as H}from"node:fs";import W from"node:assert";import K from"inquirer";import Z from"is-path-inside";import{execa as J,ExecaError as Y}from"execa";import{spawn as X,execSync as Q}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{z as se}from"zod";import{createInterface as oe}from"node:readline";import ce,{inspect as le}from"node:util";import ue from"node:process";import{randomUUID as de}from"node:crypto";import{Readable as pe}from"stream";import me from"net";import he from"tls";import fe from"assert";import ge from"tty";import ye from"util";import ve from"http";import be from"https";import _e from"url";import we from"events";import Se from"node:http";import Ne from"node:https";import ke from"node:zlib";import{Transform as xe}from"node:stream";import{globbyStream as Pe}from"globby";import Ee from"multimatch";import{importConfig as Ce,importJSON as Ae}from"@equinor/fusion-imports";import{assert as Oe}from"node:console";import Ie from"gray-matter";import{RecursiveCharacterTextSplitter as $e}from"@langchain/textsplitters";import{SyntaxKind as Te,Node as ze,Project as Re}from"ts-morph";import{findUpSync as Le}from"find-up";import Me from"node:module";import"deepmerge";const je=(e=0)=>t=>`[${t+e}m`,De=(e=0)=>t=>`[${38+e};5;${t}m`,Fe=(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 Be=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=je(),Ue.color.ansi256=De(),Ue.color.ansi16m=Fe(),Ue.bgColor.ansi=je(10),Ue.bgColor.ansi256=De(10),Ue.bgColor.ansi16m=Fe(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 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)=>Ue.ansi256ToAnsi(Ue.rgbToAnsi256(e,t,r)),enumerable:!1},hexToAnsi:{value:e=>Ue.ansi256ToAnsi(Ue.hexToAnsi256(e)),enumerable:!1}}),Ue}(),qe=(()=>{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})(),Ve=0!==qe&&{level:qe},Ge={stdout:Ve,stderr:Ve};function He(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:We,stderr:Ke}=Ge,Ze=Symbol("GENERATOR"),Je=Symbol("STYLER"),Ye=Symbol("IS_EMPTY"),Xe=["ansi","ansi","ansi256","ansi16m"],Qe=Object.create(null),et=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=We?We.level:0;e.level=void 0===t.level?r:t.level})(t,e),Object.setPrototypeOf(t,tt.prototype),t};function tt(e){return et(e)}Object.setPrototypeOf(tt.prototype,Function.prototype);for(const[e,t]of Object.entries(Be))Qe[e]={get(){const r=st(this,it(t.open,t.close,this[Je]),this[Ye]);return Object.defineProperty(this,e,{value:r}),r}};Qe.visible={get(){const e=st(this,this[Je],!0);return Object.defineProperty(this,"visible",{value:e}),e}};const rt=(e,t,r,...n)=>"rgb"===e?"ansi16m"===t?Be[r].ansi16m(...n):"ansi256"===t?Be[r].ansi256(Be.rgbToAnsi256(...n)):Be[r].ansi(Be.rgbToAnsi(...n)):"hex"===e?rt("rgb",t,r,...Be.hexToRgb(...n)):Be[r][e](...n),nt=["rgb","hex","ansi256"];for(const e of nt){Qe[e]={get(){const{level:t}=this;return function(...r){const n=it(rt(e,Xe[t],"color",...r),Be.color.close,this[Je]);return st(this,n,this[Ye])}}};Qe["bg"+e[0].toUpperCase()+e.slice(1)]={get(){const{level:t}=this;return function(...r){const n=it(rt(e,Xe[t],"bgColor",...r),Be.bgColor.close,this[Je]);return st(this,n,this[Ye])}}}}const at=Object.defineProperties(()=>{},{...Qe,level:{enumerable:!0,get(){return this[Ze].level},set(e){this[Ze].level=e}}}),it=(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}},st=(e,t,r)=>{const n=(...e)=>ot(n,1===e.length?""+e[0]:e.join(" "));return Object.setPrototypeOf(n,at),n[Ze]=e,n[Je]=t,n[Ye]=r,n},ot=(e,t)=>{if(e.level<=0||!t)return e[Ye]?"":t;let r=e[Je];if(void 0===r)return t;const{openAll:n,closeAll:a}=r;if(t.includes(""))for(;void 0!==r;)t=He(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(tt.prototype,Qe);const ct=tt();tt({level:Ke?Ke.level:0});const lt=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})}),ut="app-bundle.zip",dt=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)",ut).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)})}),pt=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))};pt({allowDev:!0});const mt=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ht=t("--tenantId <string>","The Azure Active Directory tenant ID").env("FUSION_TENANT_ID").default("3aa4a235-b6e2-48d5-9195-7fcf05b459b0"),ft=t("--clientId <string>","The client ID of the application registered in Azure AD").env("FUSION_CLIENT_ID").default("a318b8e1-0295-4e17-98d5-35f67dfeba14"),gt=t("--token <string>","The Azure AD access token. If provided, the --tenant and --client options are ignored").env("FUSION_TOKEN").default(void 0),yt=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"]),vt=(e,t)=>(e.addOption(ht),e.addOption(ft),t?.excludeToken||e.addOption(gt),t?.includeScope&&e.addOption(yt),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(!mt.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(!mt.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),bt=vt(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(pt({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})})),_t=vt(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(pt({allowDev:!1})).argument("[bundle]","Application bundle to upload",ut).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)})})),wt=vt(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(pt({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("🤪",ct.blue("--env"),'cannot be "dev" when',ct.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 St=vt(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(pt({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:",ct.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)})})),Nt=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..."),P({log:t,manifest:e.manifest,config:e.config,env:e.env,port:e.port,host:e.host}),t.succeed("Development server started successfully.")}),kt=(e,t)=>{try{return M(e,j.F_OK),!0}catch(e){return!1}},xt=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),kt(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))}),Pt=vt(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(pt({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 Et(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 Ct(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 Et(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 At(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 Ot(e,t,r){const n=At(e,r);U(n,t)}const It=["code","cursor"];async function $t(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 K.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 It.includes(e)}(r))return void t.error(`Invalid IDE command: ${r}. Only supported IDEs are: ${It.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 Tt=["npm","pnpm"];async function zt(e,t){const{installDeps:r}=await K.prompt([{type:"confirm",name:"installDeps",message:"📦 Install dependencies?",default:!0}]);if(!r)return t.debug("Skipping dependency installation"),{installed:!1};const{packageManager:n}=await K.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){W(Tt.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 Rt{#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(B(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 Lt=se.object({type:se.literal("file"),path:se.string(),target:se.string().optional()}),Mt=se.object({type:se.literal("dir"),path:se.string(),target:se.string().optional(),recursive:se.boolean().optional()}),jt=se.discriminatedUnion("type",[Lt,Mt]),Dt=se.object({name:se.string(),description:se.string(),resources:se.array(jt)}),Ft=se.object({templates:se.array(Dt),resources:se.array(jt).optional()});class Ut{repo;#n=!1;#a;#i;#s;#o;#c;get protocol(){return this.#o}set protocol(e){W("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),B(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=D(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 Ft.parse(t)}catch(e){if(e instanceof se.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 Rt({...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 Ot(At(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 Bt=[".rsa",".ed25519",".ecdsa",".dsa"],qt=/(_rsa|_ed25519|_ecdsa|_dsa)$/,Vt=new Set(["known_hosts","config","authorized_keys","authorized_keys2","ssh_config","ssh_known_hosts"]);function Gt(e){if(e.endsWith(".pub"))return!1;if(Vt.has(e))return!1;const t=e.startsWith("id_"),r=Bt.some(t=>e.endsWith(t)),n=qt.test(e);return t||r||n}async function Ht(e){e?.debug("Detecting SSH configuration...");const t=function(){try{return Q("git config core.sshCommand",{stdio:"ignore"}),!0}catch{return!1}}()||function(e){try{const t=u(re(),".ssh");if(!B(t))return!1;for(const r of q(t,{withFileTypes:!0}))if(r.isFile()&&Gt(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 K.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 Wt(e,t,r){W(!!e,"App name is required"),W(B(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;W("string"==typeof e,"Target directory must be a string");try{a=At(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(!B(a))return t.debug(`Target directory does not exist: ${a}`),!0;try{const e=q(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{Ot(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 K.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{Ot(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{Ot(At(a,te()),{recursive:!0,force:!0},te())}catch(e){n.debug("Cleanup failed:",e)}}const i=await Ht(n),s=new Ut(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){W(Array.isArray(e),"Templates must be an array"),W(e.length>0,"No templates available");const n=e.map(e=>e.name);if(t){W("string"==typeof t,"Pre-selected template must be a string"),W(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 W(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 K.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=D(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 Ct(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 K.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 $t(n,r);const{installed:l,packageManager:d}=await zt(n,r);if(l&&d){const e=await async function(e,t,r,n=!1){const{startDev:a}=await K.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=X(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 Kt=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 Wt(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)}});dt.alias("build-pack").hook("preAction",e=>{"build-pack"===process.argv[3]&&(console.warn(ct.bgRedBright.bold('The command "build-pack" is deprecated. Please use "pack" instead.')),e.getOptionValue("archive")||e.setOptionValue("archive",ut))}),_t.alias("build-upload").hook("preAction",e=>{if("build-upload"===process.argv[3]){if(console.warn(ct.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")??ut;process.argv[4]=t}}),xt.alias("build-manifest").hook("preAction",()=>{"build-manifest"===process.argv[3]&&console.warn(ct.bgRedBright.bold('The command "build-manifest" is deprecated. Please use "manifest" instead.'))}),Pt.alias("build-publish").hook("preAction",e=>{if("build-publish"===process.argv[3]&&console.warn(ct.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 Zt=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(lt).addCommand(dt).addCommand(bt).addCommand(_t).addCommand(wt).addCommand(St).addCommand(Nt).addCommand(xt).addCommand(Pt).addCommand(Kt("create")),Jt=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:",ct.green(e.account?.username)),t.info("tenant: ",ct.yellow(e.tenantId)),t.info("audience:",ct.yellow(e.account?.idTokenClaims?.aud));for(const r of e.scopes)t.info("scope: ",ct.dim(r));t.succeed("Successfully logged in",ct.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}});vt(Jt,{includeScope:!0,excludeToken:!0});const Yt=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}});vt(Yt,{excludeToken:!0,includeScope:!1});class Xt extends Error{static Name="NoAccountsError";constructor(e,t){super(e,t),this.name=Xt.Name}}const Qt=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 Xt))throw r;t?.fail("No accounts found, please login first")}});vt(Qt,{includeScope:!0});const er=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"));er.addCommand(Jt,{isDefault:!0}),er.addCommand(Yt),er.addCommand(Qt);const tr=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(Kt("app")),rr=vt(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(pt({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))})),nr=e("disco").description("Service discovery operations");nr.addCommand(rr);var ar=function(e,t){return ar=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])},ar(e,t)};function ir(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}ar(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function sr(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 or(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 cr(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 lr(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 ur(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 dr(e){return this instanceof dr?(this.v=e,this):new dr(e)}function pr(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 dr?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 mr(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=cr(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 hr(e){return"function"==typeof e}function fr(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 gr=fr(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 yr(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var vr=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=cr(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(hr(c))try{c()}catch(e){a=e instanceof gr?e.errors:[e]}var l=this._finalizers;if(l){this._finalizers=null;try{for(var u=cr(l),d=u.next();!d.done;d=u.next()){var p=d.value;try{wr(p)}catch(e){a=null!=a?a:[],e instanceof gr?a=ur(ur([],lr(a)),lr(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 gr(a)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)wr(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)&&yr(t,e)},e.prototype.remove=function(t){var r=this._finalizers;r&&yr(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}(),br=vr.EMPTY;function _r(e){return e instanceof vr||e&&"closed"in e&&hr(e.remove)&&hr(e.add)&&hr(e.unsubscribe)}function wr(e){hr(e)?e():e.unsubscribe()}var Sr={Promise:void 0},Nr=function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setTimeout.apply(void 0,ur([e,t],lr(r)))};function kr(e){Nr(function(){throw e})}function xr(){}function Pr(e){e()}var Er=function(e){function t(t){var r=e.call(this)||this;return r.isStopped=!1,t?(r.destination=t,_r(t)&&t.add(r)):r.destination=Ir,r}return ir(t,e),t.create=function(e,t,r){return new Ar(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}(vr),Cr=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){Or(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){Or(e)}else Or(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){Or(e)}},e}(),Ar=function(e){function t(t,r,n){var a,i=e.call(this)||this;return a=hr(t)||!t?{next:null!=t?t:void 0,error:null!=r?r:void 0,complete:null!=n?n:void 0}:t,i.destination=new Cr(a),i}return ir(t,e),t}(Er);function Or(e){kr(e)}var Ir={closed:!0,next:xr,error:function(e){throw e},complete:xr},$r="function"==typeof Symbol&&Symbol.observable||"@@observable";function Tr(e){return e}var zr=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 Er||function(e){return e&&hr(e.next)&&hr(e.error)&&hr(e.complete)}(n)&&_r(n)?e:new Ar(e,t,r);return Pr(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=Rr(t))(function(t,n){var a=new Ar({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[$r]=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?Tr: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=Rr(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 Rr(e){var t;return null!==(t=null!=e?e:Sr.Promise)&&void 0!==t?t:Promise}function Lr(e){return function(t){if(function(e){return hr(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 Mr(e,t,r,n,a){return new jr(e,t,r,n,a)}var jr=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 ir(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}(Er),Dr=fr(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Fr=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 ir(t,e),t.prototype.lift=function(e){var t=new Ur(this,this);return t.operator=e,t},t.prototype._throwIfClosed=function(){if(this.closed)throw new Dr},t.prototype.next=function(e){var t=this;Pr(function(){var r,n;if(t._throwIfClosed(),!t.isStopped){t.currentObservers||(t.currentObservers=Array.from(t.observers));try{for(var a=cr(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;Pr(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;Pr(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?br:(this.currentObservers=null,i.push(e),new vr(function(){t.currentObservers=null,yr(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 zr;return e.source=this,e},t.create=function(e,t){return new Ur(e,t)},t}(zr),Ur=function(e){function t(t,r){var n=e.call(this)||this;return n.destination=t,n.source=r,n}return ir(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:br},t}(Fr),Br=function(e){function t(t){var r=e.call(this)||this;return r._value=t,r}return ir(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}(Fr),qr={now:function(){return(qr.delegate||Date).now()},delegate:void 0},Vr=function(e){function t(t,r,n){void 0===t&&(t=1/0),void 0===r&&(r=1/0),void 0===n&&(n=qr);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 ir(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}(Fr),Gr=function(e){function t(t,r){return e.call(this)||this}return ir(t,e),t.prototype.schedule=function(e,t){return this},t}(vr),Hr=function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setInterval.apply(void 0,ur([e,t],lr(r)))},Wr=function(e){return clearInterval(e)},Kr=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 ir(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),Hr(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&&Wr(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,yr(n,this),null!=t&&(this.id=this.recycleAsyncId(r,t,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(Gr),Zr=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=qr.now,e}(),Jr=new(function(e){function t(t,r){void 0===r&&(r=Zr.now);var n=e.call(this,t,r)||this;return n.actions=[],n._active=!1,n}return ir(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}(Zr))(Kr),Yr=new zr(function(e){return e.complete()});function Xr(e){return e[e.length-1]}function Qr(e){return(t=Xr(e))&&hr(t.schedule)?e.pop():void 0;var t}var en=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function tn(e){return hr(null==e?void 0:e.then)}function rn(e){return hr(e[$r])}function nn(e){return Symbol.asyncIterator&&hr(null==e?void 0:e[Symbol.asyncIterator])}function an(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 sn="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function on(e){return hr(null==e?void 0:e[sn])}function cn(e){return pr(this,arguments,function(){var t,r,n;return or(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,dr(t.read())];case 3:return r=a.sent(),n=r.value,r.done?[4,dr(void 0)]:[3,5];case 4:return[2,a.sent()];case 5:return[4,dr(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 ln(e){return hr(null==e?void 0:e.getReader)}function un(e){if(e instanceof zr)return e;if(null!=e){if(rn(e))return a=e,new zr(function(e){var t=a[$r]();if(hr(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")});if(en(e))return n=e,new zr(function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()});if(tn(e))return r=e,new zr(function(e){r.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,kr)});if(nn(e))return dn(e);if(on(e))return t=e,new zr(function(e){var r,n;try{for(var a=cr(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(ln(e))return dn(cn(e))}var t,r,n,a;throw an(e)}function dn(e){return new zr(function(t){(function(e,t){var r,n,a,i;return sr(this,void 0,void 0,function(){var s,o;return or(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),r=mr(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 pn(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 mn(e,t){return void 0===t&&(t=0),Lr(function(r,n){r.subscribe(Mr(n,function(r){return pn(n,e,function(){return n.next(r)},t)},function(){return pn(n,e,function(){return n.complete()},t)},function(r){return pn(n,e,function(){return n.error(r)},t)}))})}function hn(e,t){return void 0===t&&(t=0),Lr(function(r,n){n.add(e.schedule(function(){return r.subscribe(n)},t))})}function fn(e,t){if(!e)throw new Error("Iterable cannot be null");return new zr(function(r){pn(r,t,function(){var n=e[Symbol.asyncIterator]();pn(r,t,function(){n.next().then(function(e){e.done?r.complete():r.next(e.value)})},0,!0)})})}function gn(e,t){if(null!=e){if(rn(e))return function(e,t){return un(e).pipe(hn(t),mn(t))}(e,t);if(en(e))return function(e,t){return new zr(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(tn(e))return function(e,t){return un(e).pipe(hn(t),mn(t))}(e,t);if(nn(e))return fn(e,t);if(on(e))return function(e,t){return new zr(function(r){var n;return pn(r,t,function(){n=e[sn](),pn(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 hr(null==n?void 0:n.return)&&n.return()}})}(e,t);if(ln(e))return function(e,t){return fn(cn(e),t)}(e,t)}throw an(e)}function yn(e,t){return t?gn(e,t):un(e)}function vn(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return yn(e,Qr(e))}var bn=fr(function(e){return function(){e(this),this.name="EmptyError",this.message="no elements in sequence"}});function _n(e,t){return new Promise(function(t,r){var n,a=!1;e.subscribe({next:function(e){n=e,a=!0},error:r,complete:function(){a?t(n):r(new bn)}})})}var wn=fr(function(e){return function(t){void 0===t&&(t=null),e(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function Sn(e,t){var r,n=(r=e)instanceof Date&&!isNaN(r)?{first:e}:"number"==typeof e?{each:e}:e,a=n.first,i=n.each,s=n.with,o=void 0===s?Nn:s,c=n.scheduler,l=void 0===c?Jr:c,u=n.meta,d=void 0===u?null:u;if(null==a&&null==i)throw new TypeError("No timeout provided.");return Lr(function(e,t){var r,n,s=null,c=0,u=function(e){n=pn(t,l,function(){try{r.unsubscribe(),un(o({meta:d,lastValue:s,seen:c})).subscribe(t)}catch(e){t.error(e)}},e)};r=e.subscribe(Mr(t,function(e){null==n||n.unsubscribe(),c++,t.next(s=e),i>0&&u(i)},void 0,void 0,function(){(null==n?void 0:n.closed)||null==n||n.unsubscribe(),s=null})),!c&&u(null!=a?"number"==typeof a?a:+a-l.now():i)})}function Nn(e){throw new wn(e)}function kn(e,t){return Lr(function(r,n){var a=0;r.subscribe(Mr(n,function(r){n.next(e.call(t,r,a++))}))})}function xn(e,t,r){return void 0===r&&(r=1/0),hr(t)?xn(function(r,n){return kn(function(e,a){return t(r,e,n,a)})(un(e(r,n)))},r):("number"==typeof t&&(r=t),Lr(function(t,n){return function(e,t,r,n,a,i,s){var o=[],c=0,l=0,u=!1,d=function(){!u||o.length||c||t.complete()},p=function(e){c++;var a=!1;un(r(e,l++)).subscribe(Mr(t,function(e){t.next(e)},function(){a=!0},void 0,function(){if(a)try{c--;for(var e=function(){var e=o.shift();s||p(e)};o.length&&c<n;)e();d()}catch(e){t.error(e)}}))};return e.subscribe(Mr(t,function(e){return c<n?p(e):o.push(e)},function(){u=!0,d()})),function(){}}(t,n,e,r)}))}function Pn(e){return void 0===e&&(e=1/0),xn(Tr,e)}function En(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Pn(1)(yn(e,Qr(e)))}function Cn(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=Qr(e),n=function(e,t){return"number"==typeof Xr(e)?e.pop():t}(e,1/0),a=e;return a.length?1===a.length?un(a[0]):Pn(n)(yn(a,r)):Yr}function An(e,t){return Lr(function(r,n){var a=0;r.subscribe(Mr(n,function(r){return e.call(t,r,a++)&&n.next(r)}))})}function On(e){return Lr(function(t,r){var n,a=null,i=!1;a=t.subscribe(Mr(r,void 0,void 0,function(s){n=un(e(s,On(e)(t))),a?(a.unsubscribe(),a=null,n.subscribe(r)):i=!0})),i&&(a.unsubscribe(),a=null,n.subscribe(r))})}function In(e,t,r,n,a){return function(i,s){var o=r,c=t,l=0;i.subscribe(Mr(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 $n(e,t){return Lr(In(e,t,arguments.length>=2,!1,!0))}var Tn=function(e,t){return e.push(t),e};function zn(){return Lr(function(e,t){$n(Tn,[])(e).subscribe(t)})}function Rn(e,t){return hr(t)?xn(e,t,1):xn(e,1)}function Ln(e){return Lr(function(t,r){var n=!1;t.subscribe(Mr(r,function(e){n=!0,r.next(e)},function(){n||r.next(e),r.complete()}))})}function Mn(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 Ar({next:function(){a.unsubscribe(),e()}});return un(t.apply(void 0,ur([],lr(r)))).subscribe(a)}}else e()}function jn(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,function(e){void 0===e&&(e={});var t=e.connector,r=void 0===t?function(){return new Fr}: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 Lr(function(e,h){o++,u||l||d();var f=i=null!=i?i:r();h.add(function(){0!==--o||u||l||(n=Mn(m,c))}),f.subscribe(h),!t&&o>0&&(t=new Ar({next:function(e){return f.next(e)},error:function(e){u=!0,d(),n=Mn(p,a,e),f.error(e)},complete:function(){l=!0,d(),n=Mn(p,s),f.complete()}}),un(e).subscribe(t))})(e)}}({connector:function(){return new Vr(s,t,r)},resetOnError:!0,resetOnComplete:!1,resetOnRefCountZero:o})}function Dn(e,t,r){var n=hr(e)||t||r?{next:e,error:t,complete:r}:e;return n?Lr(function(e,t){var r;null===(r=n.subscribe)||void 0===r||r.call(n);var a=!0;e.subscribe(Mr(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)}))}):Tr}const Fn=t("--openai-api-key <key>","API key for Azure OpenAI services").env("AZURE_OPENAI_API_KEY"),Un=t("--openai-api-version <version>","Azure OpenAI API version").env("AZURE_OPENAI_API_VERSION").default("2024-02-15-preview"),Bn=t("--openai-instance <name>","Azure OpenAI instance name").env("AZURE_OPENAI_INSTANCE_NAME"),qn=t("--openai-chat-deployment <name>","Azure OpenAI chat deployment name").env("AZURE_OPENAI_CHAT_DEPLOYMENT_NAME"),Vn=t("--openai-embedding-deployment <name>","Azure OpenAI embedding deployment name").env("AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME"),Gn=t("--azure-search-endpoint <url>","Azure Search endpoint URL").env("AZURE_SEARCH_ENDPOINT"),Hn=t("--azure-search-api-key <key>","Azure Search API key").env("AZURE_SEARCH_API_KEY"),Wn=t("--azure-search-index-name <name>","Azure Search index name").env("AZURE_SEARCH_INDEX_NAME"),Kn=(e,t)=>(e.addOption(Fn),e.addOption(Un),e.addOption(Bn),!0===t?.includeChat&&e.addOption(qn),!0===t?.includeEmbedding&&e.addOption(Vn),!0===t?.includeSearch&&(e.addOption(Gn),e.addOption(Hn),e.addOption(Wn)),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 Zn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Jn,Yn,Xn,Qn,ea,ta,ra,na,aa,ia,sa,oa,ca,la,ua,da,pa,ma,ha,fa,ga,ya,va,ba,_a,wa,Sa,Na,ka,xa,Pa,Ea,Ca,Aa,Oa,Ia,$a,Ta,za,Ra,La,Ma,ja,Da,Fa,Ua,Ba,qa,Va,Ga,Ha,Wa,Ka,Za,Ja,Ya,Xa,Qa,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,Pi,Ei,Ci,Ai,Oi,Ii={exports:{}};function $i(){if(Yn)return Jn;Yn=1;const e=Number.MAX_SAFE_INTEGER||9007199254740991;return Jn={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 Ti(){if(Qn)return Xn;Qn=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 Xn=e}function zi(){return ea||(ea=1,function(e,t){const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:a}=$i(),i=Ti(),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*$")}(Ii,Ii.exports)),Ii.exports}function Ri(){if(ra)return ta;ra=1;const e=Object.freeze({loose:!0}),t=Object.freeze({});return ta=r=>r?"object"!=typeof r?e:r:t}function Li(){if(aa)return na;aa=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 na={compareIdentifiers:t,rcompareIdentifiers:(e,r)=>t(r,e)}}function Mi(){if(sa)return ia;sa=1;const e=Ti(),{MAX_LENGTH:t,MAX_SAFE_INTEGER:r}=$i(),{safeRe:n,t:a}=zi(),i=Ri(),{compareIdentifiers:s}=Li();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 ia=o}function ji(){if(ca)return oa;ca=1;const e=Mi();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 Di(){if(ua)return la;ua=1;const e=ji();return la=(t,r)=>{const n=e(t,r);return n?n.version:null},la}function Fi(){if(pa)return da;pa=1;const e=ji();return da=(t,r)=>{const n=e(t.trim().replace(/^[=v]+/,""),r);return n?n.version:null},da}function Ui(){if(Pa)return xa;Pa=1;const e=Mi();return xa=(t,r,n)=>new e(t,n).compare(new e(r,n))}function Bi(){if($a)return Ia;$a=1;const e=Mi();return Ia=(t,r,n)=>{const a=new e(t,n),i=new e(r,n);return a.compare(i)||a.compareBuild(i)}}function qi(){if(ja)return Ma;ja=1;const e=Ui();return Ma=(t,r,n)=>e(t,r,n)>0}function Vi(){if(Fa)return Da;Fa=1;const e=Ui();return Da=(t,r,n)=>e(t,r,n)<0}function Gi(){if(Ba)return Ua;Ba=1;const e=Ui();return Ua=(t,r,n)=>0===e(t,r,n)}function Hi(){if(Va)return qa;Va=1;const e=Ui();return qa=(t,r,n)=>0!==e(t,r,n)}function Wi(){if(Ha)return Ga;Ha=1;const e=Ui();return Ga=(t,r,n)=>e(t,r,n)>=0}function Ki(){if(Ka)return Wa;Ka=1;const e=Ui();return Wa=(t,r,n)=>e(t,r,n)<=0}function Zi(){if(Ja)return Za;Ja=1;const e=Gi(),t=Hi(),r=qi(),n=Wi(),a=Vi(),i=Ki();return Za=(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 Ji(){if(ri)return ti;ri=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=>E(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}}ti=t;const r=(ei||(ei=1,Qa=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}}),Qa),n=new r,a=Ri(),i=Yi(),s=Ti(),o=Mi(),{safeRe:c,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:p}=zi(),{FLAG_INCLUDE_PRERELEASE:m,FLAG_LOOSE:h}=$i(),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=P(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})},P=(e,t)=>(s("replaceStars",e,t),e.trim().replace(c[l.STAR],"")),E=(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 ti}function Yi(){if(ai)return ni;ai=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(">")))))))}}ni=t;const r=Ri(),{safeRe:n,t:a}=zi(),i=Zi(),s=Ti(),o=Mi(),c=Ji();return ni}function Xi(){if(si)return ii;si=1;const e=Ji();return ii=(t,r,n)=>{try{r=new e(r,n)}catch(e){return!1}return r.test(t)},ii}function Qi(){if(gi)return fi;gi=1;const e=Ji();return fi=(t,r)=>{try{return new e(t,r).range||"*"}catch(e){return null}},fi}function es(){if(vi)return yi;vi=1;const e=Mi(),t=Yi(),{ANY:r}=t,n=Ji(),a=Xi(),i=qi(),s=Vi(),o=Ki(),c=Wi();return yi=(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},yi}var ts=function(){if(Oi)return Ai;Oi=1;const e=zi(),t=$i(),r=Mi(),n=Li(),a=ji(),i=Di(),s=Fi(),o=function(){if(ha)return ma;ha=1;const e=Mi();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(ga)return fa;ga=1;const e=ji();return fa=(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(va)return ya;va=1;const e=Mi();return ya=(t,r)=>new e(t,r).major}(),u=function(){if(_a)return ba;_a=1;const e=Mi();return ba=(t,r)=>new e(t,r).minor}(),d=function(){if(Sa)return wa;Sa=1;const e=Mi();return wa=(t,r)=>new e(t,r).patch}(),p=function(){if(ka)return Na;ka=1;const e=ji();return Na=(t,r)=>{const n=e(t,r);return n&&n.prerelease.length?n.prerelease:null},Na}(),m=Ui(),h=function(){if(Ca)return Ea;Ca=1;const e=Ui();return Ea=(t,r,n)=>e(r,t,n)}(),f=function(){if(Oa)return Aa;Oa=1;const e=Ui();return Aa=(t,r)=>e(t,r,!0)}(),g=Bi(),y=function(){if(za)return Ta;za=1;const e=Bi();return Ta=(t,r)=>t.sort((t,n)=>e(t,n,r))}(),v=function(){if(La)return Ra;La=1;const e=Bi();return Ra=(t,r)=>t.sort((t,n)=>e(n,t,r))}(),b=qi(),_=Vi(),w=Gi(),S=Hi(),N=Wi(),k=Ki(),x=Zi(),P=function(){if(Xa)return Ya;Xa=1;const e=Mi(),t=ji(),{safeRe:r,t:n}=zi();return Ya=(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)},Ya}(),E=Yi(),C=Ji(),A=Xi(),O=function(){if(ci)return oi;ci=1;const e=Ji();return oi=(t,r)=>new e(t,r).set.map(e=>e.map(e=>e.value).join(" ").trim().split(" ")),oi}(),I=function(){if(ui)return li;ui=1;const e=Mi(),t=Ji();return li=(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},li}(),$=function(){if(pi)return di;pi=1;const e=Mi(),t=Ji();return di=(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},di}(),T=function(){if(hi)return mi;hi=1;const e=Mi(),t=Ji(),r=qi();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=Qi(),R=es(),L=function(){if(_i)return bi;_i=1;const e=es();return bi=(t,r,n)=>e(t,r,">",n),bi}(),M=function(){if(Si)return wi;Si=1;const e=es();return wi=(t,r,n)=>e(t,r,"<",n),wi}(),j=function(){if(ki)return Ni;ki=1;const e=Ji();return Ni=(t,r,n)=>(t=new e(t,n),r=new e(r,n),t.intersects(r,n))}(),D=function(){if(Pi)return xi;Pi=1;const e=Xi(),t=Ui();return xi=(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},xi}(),F=function(){if(Ci)return Ei;Ci=1;const e=Ji(),t=Yi(),{ANY:r}=t,n=Xi(),a=Ui(),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 Ei=(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 Ai={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:P,Comparator:E,Range:C,satisfies:A,toComparators:O,maxSatisfying:I,minSatisfying:$,minVersion:T,validRange:z,outside:R,gtr:L,ltr:M,intersects:j,simplifyRange:D,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 rs extends ts.SemVer{satisfies(e){return ts.satisfies(this,e)}}const ns=(e,t,r)=>{const n="string"==typeof t?t.split("."):t,a=n.shift();return a&&(e[a]??={},n.length?ns(e[a],n,r):Object.assign(e,{[a]:r})),e};class as{#l={};createConfig(e,t){return yn(this._createConfig(e,t))}async createConfigAsync(e,t){return _n(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 yn(this._buildConfig(e,t)).pipe((r=t=>this._processConfig(t,e),Lr(function(e,t){var a=null,i=0,s=!1,o=function(){return s&&!a&&t.complete()};e.subscribe(Mr(t,function(e){null==a||a.unsubscribe();var s=0,c=i++;un(r(e,c)).subscribe(a=Mr(t,function(r){return t.next(n?n(e,r,c,s++):r)},function(){a=null,o()}))},function(){s=!0,o()}))})));var r,n}_buildConfig(e,t){return yn(Object.entries(this.#l)).pipe(xn(([t,r])=>yn(r(e)).pipe(An(e=>void 0!==e),kn(e=>({target:t,value:e})),On(e=>(console.error(`Failed to execute config callback: ${r.name} for attribute: '${t}'`,e),Yr)))),$n((e,{target:t,value:r})=>ns(e,t,r),t??{}))}_processConfig(e,t){return vn(e)}}var is;!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"}(is||(is={}));class ss{static[Symbol.hasInstance](e){if(null!==e&&"object"==typeof e&&"version"in e&&"dispose"in e){const t=e,r=ts.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 rs(t),this.#d=new vr}_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 cs{static className="ModulesConfigurator";get version(){return"5.0.6-cli-search-index.0"}#p=new Vr(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:is.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:is.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:is.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:is.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:is.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:is.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=yn(t).pipe(xn(async t=>{const r=performance.now();try{const n=await(t.configure?.(e)),a=Math.round(performance.now()-r);return this._registerEvent({level:is.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:is.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}}),$n((e,t)=>Object.assign(e,t),{onAfterConfiguration(e){r.push(e)},onAfterInit(e){n.push(e)}}));return _n(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:is.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:is.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:is.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:is.Debug,name:"_postConfigure.hooksComplete",message:"Post configure hooks complete",properties:{count:r.length,postConfigHooksTime:n},metric:n})}catch(e){this._registerEvent({level:is.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 Br({}),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:is.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:is.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:is.Debug,name:"_initialize.requireInstance.awaiting",message:`Awaiting module [${String(e)}] initialization, timeout ${t}s`,properties:{moduleName:String(e),wait:t}}),i=n.pipe(An(t=>!!t[e]),kn(t=>t[e]),Sn({each:1e3*t,with:()=>{return n=hr(r=()=>{const r=new os;return this._registerEvent({level:is.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 zr(function(e){return e.error(n())});var r,n}}),Dn(()=>{const r=Math.round(performance.now()-a);this._registerEvent({level:is.Debug,name:"_initialize.requireInstance.moduleResolved",message:`Module [${String(e)}] required in ${r}ms`,properties:{moduleName:String(e),wait:t,requireTime:r},metric:r})})),new Promise(function(e,t){var r=new Ar({next:function(t){e(t),r.unsubscribe()},error:t,complete:function(){t(new bn)}});i.subscribe(r)});var i},s=yn(this.modules).pipe(xn(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:is.Error,name:"_initialize.moduleInitializeError",message:e.message,properties:{moduleName:r.name,moduleVersion:r.version?.toString()||"unknown"},error:e}),e}this._registerEvent({level:is.Debug,name:"_initialize.moduleInitializing",message:`Initializing module ${r.name}`,properties:{moduleName:r.name,moduleVersion:r.version?.toString()||"unknown"}});const s=performance.now();return yn(Promise.resolve(r.initialize({ref:t,config:e[n],requireInstance:i,hasModule:a}))).pipe(kn(e=>{e instanceof ss||this._registerEvent({level:is.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:is.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:is.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(Ln([])).subscribe({next:([e,t])=>{n.next(Object.assign(n.value,{[e]:t}))},error:e=>{this._registerEvent({level:is.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:is.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 _n(n),u=Math.round(performance.now()-c);return this._registerEvent({level:is.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=yn(r).pipe(An(e=>!!e.postInitialize),Dn(e=>{this._registerEvent({level:is.Debug,name:"_postInitialize.modulePostInitializing",message:`Module ${e.name} is being post-initialized`,properties:{moduleName:e.name,moduleVersion:e.version?.toString()||"unknown"}})}),xn(r=>{const n=performance.now();return yn(r.postInitialize({ref:t,modules:e,instance:e[r.name]})).pipe(Dn(()=>{const e=Math.round(performance.now()-n);this._registerEvent({level:is.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}})}),Ln(null),On(e=>(this._registerEvent({level:is.Warning,name:"_postInitialize.modulePostInitializeError",message:`Module ${r.name} post-initialize failed`,properties:{moduleName:r.name,moduleVersion:r.version?.toString()||"unknown"},error:e}),Yr)))}),Ln(null));this._registerEvent({level:is.Debug,name:"_postInitialize.modulesPostInitializing",message:`Post-initializing all modules [${Object.keys(e).length}]`,properties:{modules:Object.keys(e).join(", ")}});const i=performance.now();await _n(a);const s=Math.round(performance.now()-i);if(this._registerEvent({level:is.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:is.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:is.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:is.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:is.Debug,name:"_postInitialize.complete",message:"Post-initialization complete",properties:{modules:Object.keys(e).join(", "),postInitCompleteTime:o}})}async dispose(e,t){this._registerEvent({level:is.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:is.Debug,name:"dispose.moduleDisposed",message:`Module ${r.name} disposed successfully`,properties:{moduleName:r.name,moduleVersion:r.version?.toString()||"unknown"}})}catch(e){this._registerEvent({level:is.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 ls(e){return t=>yn(Object.entries(e)).pipe(xn(([e,r])=>"function"==typeof r?yn(r(t)).pipe(An(e=>!!e),kn(t=>[e,t])):vn([e,r])),function(e,t){return Lr(In(e,t,arguments.length>=2,!0))}((e,[t,r])=>(e[t]=r,e),{}),Ln({}),jn({bufferSize:1,refCount:!0}))}class us extends as{#m={};#h={};#f={};constructor(){super(),this._set("models",ls(this.#m)),this._set("embeddings",ls(this.#h)),this._set("vectorStores",ls(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 ds extends ss{#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 ps={name:"ai",configure:()=>new us,initialize:async e=>{const t=await e.config.createConfigAsync(e);return new ds(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 hs{_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 fs(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 gs(e){return!("object"!=typeof e||null===e||Array.isArray(e)||e instanceof RegExp||e instanceof Date)}function ys(e){if(gs(e)){const t="string"==typeof e.name,r="string"==typeof e.message;return t&&r}return!1}const vs="function"==typeof globalThis?.crypto?.randomUUID?globalThis.crypto.randomUUID.bind(globalThis.crypto):de;function bs(){return vs()}"undefined"!=typeof Deno&&void 0!==Deno.version&&Deno.version.deno,"undefined"!=typeof Bun&&Bun.version;const _s=void 0!==globalThis.process&&Boolean(globalThis.process.version)&&Boolean(globalThis.process.versions?.node);function ws(e,t){return Buffer.from(e,t)}const Ss="REDACTED",Ns=["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"],ks=["api-version"];class xs{allowedHeaderNames;allowedQueryParameters;constructor({additionalAllowedHeaderNames:e=[],additionalAllowedQueryParameters:t=[]}={}){e=Ns.concat(e),t=ks.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)||gs(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,Ss);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]=Ss;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]=Ss;return t}}let Ps=class extends Error{constructor(e){super(e),this.name="AbortError"}};function Es(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 Ps(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 Cs(e){if(ys(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 As(e){return ys(e)}const Os=_s;function Is(e){const t=e;return t&&"function"==typeof t.getToken&&(void 0===t.signRequest||t.getToken.length>0)}class $s{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 Ts{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 zs;!function(e){e.AzureChina="https://search.azure.cn",e.AzureGovernment="https://search.azure.us",e.AzurePublicCloud="https://search.azure.com"}(zs||(zs={}));class Rs extends Error{constructor(e){super(e),this.name="AbortError"}}const Ls="undefined"!=typeof process&&process.env&&process.env.DEBUG||void 0;let Ms,js=[],Ds=[];const Fs=[];Ls&&Bs(Ls);const Us=Object.assign(e=>Gs(e),{enable:Bs,enabled:qs,disable:function(){const e=Ms||"";return Bs(""),e},log:function(e,...t){ue.stderr.write(`${ce.format(e,...t)}${ne}`)}});function Bs(e){Ms=e,js=[],Ds=[];const t=e.split(",").map(e=>e.trim());for(const e of t)e.startsWith("-")?Ds.push(e.substring(1)):js.push(e);for(const e of Fs)e.enabled=qs(e.namespace)}function qs(e){if(e.endsWith("*"))return!0;for(const t of Ds)if(Vs(e,t))return!1;for(const t of js)if(Vs(e,t))return!0;return!1}function Vs(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 Gs(e){const t=Object.assign(function(...r){if(!t.enabled)return;r.length>0&&(r[0]=`${e} ${r[0]}`);t.log(...r)},{enabled:qs(e),destroy:Hs,log:Us.log,namespace:e,extend:Ws});return Fs.push(t),t}function Hs(){const e=Fs.indexOf(this);return e>=0&&(Fs.splice(e,1),!0)}function Ws(e){const t=Gs(`${this.namespace}:${e}`);return t.log=this.log,t}const Ks=["verbose","info","warning","error"],Zs={verbose:400,info:300,warning:200,error:100};function Js(e,t){t.log=(...t)=>{e.log(...t)}}function Ys(e){return Ks.includes(e)}function Xs(e){const t=new Set,r="undefined"!=typeof process&&process.env&&process.env[e.logLevelEnvVarName]||void 0;let n;const a=Us(e.namespace);function i(e){if(e&&!Ys(e))throw new Error(`Unknown log level '${e}'. Acceptable values: ${Ks.join(",")}`);n=e;const r=[];for(const e of t)s(e)&&r.push(e.namespace);Us.enable(r.join(","))}function s(e){return Boolean(n&&Zs[e.level]<=Zs[n])}function o(e,r){const n=Object.assign(e.extend(r),{level:r});if(Js(e,n),s(n)){const e=Us.disable();Us.enable(e+","+n.namespace)}return t.add(n),n}return a.log=(...e)=>{Us.log(...e)},r&&(Ys(r)?i(r):console.error(`${e.logLevelEnvVarName} set to unknown log level '${r}'; logging is not enabled. Acceptable values: ${Ks.join(", ")}.`)),{setLogLevel:i,getLogLevel:function(){return n},createClientLogger:function(e){const t=a.extend(e);return Js(a,t),{error:o(t,"error"),warning:o(t,"warning"),info:o(t,"info"),verbose:o(t,"verbose")}},logger:a}}const Qs=Xs({logLevelEnvVarName:"TYPESPEC_RUNTIME_LOG_LEVEL",namespace:"typeSpecRuntime"});function eo(e){return Qs.createClientLogger(e)}function to(e){return e.toLowerCase()}class ro{_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(to(e),{name:e,value:String(t).trim()})}get(e){return this._headersMap.get(to(e))?.value}has(e){return this._headersMap.has(to(e))}delete(e){this._headersMap.delete(to(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 no(e){return new ro(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??no(),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 so{_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 so(this._policies)}static create(){return new so}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 oo=le.custom,co=new xs;let lo=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,oo,{value:()=>`RestError: ${this.message} \n ${co.sanitize({...this,request:{...this.request,agent:n},response:this.response})}`,enumerable:!1}),Object.setPrototypeOf(this,e.prototype)}};const uo=eo("ts-http-runtime"),po={};function mo(e){return e&&"function"==typeof e.pipe}function ho(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 fo(e){return e&&"number"==typeof e.byteLength}class go extends xe{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 yo{cachedHttpAgent;cachedHttpsAgents=new WeakMap;async sendRequest(e){const t=new AbortController;let r,n;if(e.abortSignal){if(e.abortSignal.aborted)throw new Rs("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 xs;uo.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:fo(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 go(t);r.on("error",e=>{uo.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=no();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=ke.createGunzip();return e.pipe(t),t}if("deflate"===r){const t=ke.createInflate();return e.pipe(t),t}return e}(r,a):r;const u=e.onDownloadProgress;if(u){const e=new go(u);e.on("error",e=>{uo.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 lo(`Error reading response as text: ${e.message}`,{code:lo.PARSE_ERROR}))})})),l}finally{if(e.abortSignal&&r){let t=Promise.resolve();mo(o)&&(t=ho(o));let n=Promise.resolve();mo(s)&&(n=ho(s)),Promise.all([t,n]).then(()=>{r&&e.abortSignal?.removeEventListener("abort",r)}).catch(e=>{uo.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?Se.request(i,n):Ne.request(i,n);o.once("error",t=>{s(new lo(t.message,{code:t.code??lo.REQUEST_SEND_ERROR,request:e}))}),t.signal.addEventListener("abort",()=>{const e=new Rs("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):fo(r)?o.end(ArrayBuffer.isView(r)?Buffer.from(r.buffer):Buffer.from(r)):(uo.error("Unrecognized body type",r),s(new lo("Unrecognized body type"))):o.end()})}getOrCreateAgent(e,t){const r=e.disableKeepAlive;if(t)return r?Se.globalAgent:(this.cachedHttpAgent||(this.cachedHttpAgent=new Se.Agent({keepAlive:!0})),this.cachedHttpAgent);{if(r&&!e.tlsSettings)return Ne.globalAgent;const t=e.tlsSettings??po;let n=this.cachedHttpsAgents.get(t);return n&&n.options.keepAlive===!r||(uo.info("No cached TLS Agent exist, creating a new Agent"),n=new Ne.Agent({keepAlive:!r,...t}),this.cachedHttpsAgents.set(t,n)),n}}}function vo(){return new yo}const bo="redirectPolicy",_o=["GET","HEAD"];function wo(e={}){const{maxRetries:t=20}=e;return{name:bo,async sendRequest(e,r){const n=await r(e);return So(r,n,t)}}}async function So(e,t,r,n=0){const{request:a,status:i,headers:s}=t,o=s.get("location");if(o&&(300===i||301===i&&_o.includes(a.method)||302===i&&_o.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 So(e,s,r,n+1)}return t}function No(e,t,r){return new Promise((n,a)=>{let i,s;const o=()=>a(new Rs(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 ko(e,t){const r=e.headers.get(t);if(!r)return;const n=Number(r);return Number.isNaN(n)?void 0:n}const xo="Retry-After",Po=["retry-after-ms","x-ms-retry-after-ms",xo];function Eo(e){if(e&&[429,503].includes(e.status))try{for(const t of Po){const r=ko(e,t);if(0===r||r){return r*(t===xo?1e3:1)}}const t=e.headers.get(xo);if(!t)return;const r=Date.parse(t)-Date.now();return Number.isFinite(r)?Math.max(0,r):void 0}catch{return}}function Co(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(Eo(e))}(a)||!c);return u||l||o?{skipStrategy:!0}:!i||s||c?fs(n,{retryDelayInMs:t,maxRetryDelayInMs:r}):{errorToThrow:i}}}}const Ao=eo("ts-http-runtime retryPolicy");function Oo(e,t={maxRetries:3}){const r=t.logger||Ao;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 Rs}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 No(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 Io(){return{name:"formDataPolicy",async sendRequest(e,t){if(_s&&"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:no({"Content-Disposition":`form-data; name="${t}"`}),body:ws(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=no();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 $o,To,zo,Ro,Lo,Mo={},jo={exports:{}},Do={exports:{}};function Fo(){if(To)return $o;To=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 $o=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))},$o}function Uo(){if(Ro)return zo;return Ro=1,zo=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=Fo(),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},zo}var Bo,qo,Vo,Go,Ho={exports:{}};function Wo(){return Vo||(Vo=1,function(e,t){const r=ge,n=ye;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(qo)return Bo;qo=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 Bo={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=Uo()(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)}}(Ho,Ho.exports)),Ho.exports}function Ko(){return Go||(Go=1,"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?jo.exports=(Lo||(Lo=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=Uo()(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Do,Do.exports)),Do.exports):jo.exports=Wo()),jo.exports}var Zo,Jo,Yo={},Xo={};function Qo(){return Jo||(Jo=1,function(e){var t=Yo&&Yo.__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=Yo&&Yo.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=Yo&&Yo.__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=Yo&&Yo.__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(me),s=n(ve),o=be;a(function(){if(Zo)return Xo;Zo=1;var e=Xo&&Xo.__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=Xo&&Xo.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=Xo&&Xo.__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(Xo,"__esModule",{value:!0}),Xo.req=Xo.json=Xo.toBuffer=void 0;const n=r(ve),a=r(be);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 Xo.toBuffer=i,Xo.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}},Xo.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},Xo}(),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}(Yo)),Yo}var ec,tc,rc={};function nc(){if(ec)return rc;ec=1;var e=rc&&rc.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(rc,"__esModule",{value:!0}),rc.parseProxyResponse=void 0;const t=(0,e(Ko()).default)("https-proxy-agent:parse-proxy-response");return rc.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()})},rc}var ac,ic=function(){if(tc)return Mo;tc=1;var e=Mo&&Mo.__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=Mo&&Mo.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=Mo&&Mo.__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=Mo&&Mo.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Mo,"__esModule",{value:!0}),Mo.HttpsProxyAgent=void 0;const a=r(me),i=r(he),s=n(fe),o=n(Ko()),c=Qo(),l=_e,u=nc(),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"],Mo.HttpsProxyAgent=m,Mo}(),sc={};var oc=function(){if(ac)return sc;ac=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},n=sc&&sc.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(sc,"__esModule",{value:!0}),sc.HttpProxyAgent=void 0;const a=r(me),i=r(he),s=n(Ko()),o=we,c=Qo(),l=_e,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"],sc.HttpProxyAgent=d,sc}();const cc=[];let lc=!1;const uc=new Map;function dc(e){return process.env[e]?process.env[e]:process.env[e.toLowerCase()]?process.env[e.toLowerCase()]:void 0}function pc(){const e=function(){if(!process)return;const e=dc("HTTPS_PROXY"),t=dc("ALL_PROXY"),r=dc("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 hc(e,t,r){if(e.agent)return;const n="https:"!==new URL(e.url).protocol;e.tlsSettings&&uo.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 ic.HttpsProxyAgent(r,{headers:a})),e.agent=t.httpsProxyAgent)}function fc(e,t){lc||cc.push(...function(){const e=dc("NO_PROXY");return lc=!0,e?e.split(",").map(e=>e.trim()).filter(e=>e.length):[]}());const r=e?mc(e):pc(),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,cc,uc)?e.proxySettings&&hc(e,n,mc(e.proxySettings)):hc(e,n,r),t(e))}}function gc(e){return"function"==typeof e.stream}async function*yc(){const e=this.getReader();try{for(;;){const{done:t,value:r}=await e.read();if(t)return;yield r}}finally{e.releaseLock()}}function vc(e){return e instanceof ReadableStream?((t=e)[Symbol.asyncIterator]||(t[Symbol.asyncIterator]=yc.bind(t)),t.values||(t.values=yc.bind(t)),pe.fromWeb(e)):e;var t}function bc(e){return e instanceof Uint8Array?pe.from(Buffer.from(e)):gc(e)?vc(e.stream()):vc(e)}function _c(e){let t="";for(const[r,n]of e)t+=`${r}: ${n}\r\n`;return t}function wc(e){return e instanceof Uint8Array?e.byteLength:gc(e)?-1===e.size?void 0:e.size:void 0}async function Sc(e,t,r){const n=[ws(`--${r}`,"utf-8"),...t.flatMap(e=>[ws("\r\n","utf-8"),ws(_c(e.headers),"utf-8"),ws("\r\n","utf-8"),e.body,ws(`\r\n--${r}`,"utf-8")]),ws("--\r\n\r\n","utf-8")],a=function(e){let t=0;for(const r of e){const e=wc(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 pe.from(async function*(){for(const e of t)for await(const t of e)yield t}())}}(n)}const Nc="multipartPolicy",kc=new Set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?");function xc(){return{name:Nc,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=>!kc.has(e)))throw new Error(`Multipart boundary "${e}" contains invalid characters`)}(r):r=`----AzSDKFormBoundary${bs()}`,e.headers.set("Content-Type",`${i}; boundary=${r}`),await Sc(e,e.multipartBody.parts,r),e.multipartBody=void 0,t(e)}}}function Pc(){return so.create()}const Ec=Xs({logLevelEnvVarName:"AZURE_LOG_LEVEL",namespace:"azure"});function Cc(e){return Ec.createClientLogger(e)}const Ac=Cc("core-rest-pipeline");function Oc(e={}){return function(e={}){const t=e.logger??uo.info,r=new xs({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:Ac.info,...e})}const Ic=bo;const $c="1.22.1";async function Tc(e){const t=new Map;t.set("core-rest-pipeline",$c),await async function(e){if(ue&&ue.versions){const t=ue.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 zc="User-Agent";const Rc=Symbol("rawContent");function Lc(e){return"function"==typeof e[Rc]}function Mc(e){return Lc(e)?e[Rc]():e}const jc=Nc;function Dc(e={}){return function(e={}){return{name:"defaultRetryPolicy",sendRequest:Oo([{name:"throttlingRetryStrategy",retry({response:e}){const t=Eo(e);return Number.isFinite(t)?{retryAfterInMs:t}:{skipStrategy:!0}}},Co(e)],{maxRetries:e.maxRetries??3}).sendRequest}}(e)}const Fc={span:Symbol.for("@azure/core-tracing span"),namespace:Symbol.for("@azure/core-tracing namespace")};function Uc(e={}){let t=new Bc(e.parentContext);return e.span&&(t=t.setValue(Fc.span,e.span)),e.namespace&&(t=t.setValue(Fc.namespace,e.namespace)),t}class Bc{_contextMap;constructor(e){this._contextMap=e instanceof Bc?new Map(e._contextMap):new Map}setValue(e,t){const r=new Bc(this);return r._contextMap.set(e,t),r}getValue(e){return this._contextMap.get(e)}deleteValue(e){const t=new Bc(this);return t._contextMap.delete(e),t}}var qc,Vc={};const Gc=(qc||(qc=1,Object.defineProperty(Vc,"__esModule",{value:!0}),Vc.state=void 0,Vc.state={instrumenterImplementation:void 0}),Vc).state;function Hc(){return Gc.instrumenterImplementation||(Gc.instrumenterImplementation={createRequestHeaders:()=>({}),parseTraceparentHeader:()=>{},startSpan:(e,t)=>({span:{end:()=>{},isRecording:()=>!1,recordException:()=>{},setAttribute:()=>{},setStatus:()=>{},addEvent:()=>{}},tracingContext:Uc({parentContext:t.tracingContext})}),withContext:(e,t,...r)=>t(...r)}),Gc.instrumenterImplementation}function Wc(e){const{namespace:t,packageName:r,packageVersion:n}=e;function a(e,a,i){const s=Hc().startSpan(e,{...i,packageName:r,packageVersion:n,tracingContext:a?.tracingOptions?.tracingContext});let o=s.tracingContext;const c=s.span;o.getValue(Fc.namespace)||(o=o.setValue(Fc.namespace,t)),c.setAttribute("az.namespace",o.getValue(Fc.namespace));return{span:c,updatedOptions:Object.assign({},a,{tracingOptions:{...a?.tracingOptions,tracingContext:o}})}}function i(e,t,...r){return Hc().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 Hc().parseTraceparentHeader(e)},createRequestHeaders:function(e){return Hc().createRequestHeaders(e)}}}const Kc=lo;function Zc(e){return function(e){return e instanceof lo||ys(e)&&"RestError"===e.name}(e)}function Jc(e={}){const t=Tc(e.userAgentPrefix),r=new xs({additionalAllowedQueryParameters:e.additionalAllowedQueryParameters}),n=function(){try{return Wc({namespace:"",packageName:"@azure/core-rest-pipeline",packageVersion:$c})}catch(e){return void Ac.warning(`Error when creating the TracingClient: ${Cs(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 Ac.warning(`Skipping creating a tracing span due to an error: ${Cs(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){Ac.warning(`Skipping tracing span processing due to an error: ${Cs(e)}`)}}(o,t),t}catch(e){throw function(e,t){try{e.setStatus({status:"error",error:As(t)?t:void 0}),Zc(t)&&t.statusCode&&e.setAttribute("http.status_code",t.statusCode),e.end()}catch(e){Ac.warning(`Skipping tracing span processing due to an error: ${Cs(e)}`)}}(o,e),e}}}}function Yc(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 Xc(e){const t=Pc();return Os&&(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(fc(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}=Yc(e.abortSignal);e.abortSignal=r;try{return await t(e)}finally{n?.()}}}),t.addPolicy(Io(),{beforePolicies:[jc]}),t.addPolicy(function(e={}){const t=Tc(e.userAgentPrefix);return{name:"userAgentPolicy",sendRequest:async(e,r)=>(e.headers.has(zc)||e.headers.set(zc,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=xc();return{name:jc,sendRequest:async(t,r)=>{if(t.multipartBody)for(const e of t.multipartBody.parts)Lc(e.body)&&(e.body=Mc(e.body));return e.sendRequest(t,r)}}}(),{afterPhase:"Deserialize"}),t.addPolicy(Dc(e.retryOptions),{phase:"Retry"}),t.addPolicy(Jc({...e.userAgentOptions,...e.loggingOptions}),{afterPhase:"Retry"}),Os&&t.addPolicy(function(e={}){return wo(e)}(e.redirectOptions),{afterPhase:"Retry"}),t.addPolicy(Oc(e.loggingOptions),{afterPhase:"Sign"}),t}function Qc(e){return function(e){return new ao(e)}(e)}const el={forcedRefreshWindowInMs:1e3,retryIntervalInMs:3e3,refreshWindowInMs:12e4};function tl(e,t){let r,n=null,a=null;const i={...el,...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 Es(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 rl(e,t){try{return[await t(e),void 0]}catch(e){if(Zc(e)&&e.response)return[e.response,e];throw e}}async function nl(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 al(e){return 401===e.status&&e.headers.has("WWW-Authenticate")}async function il(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 sl(e){const{credential:t,scopes:r,challengeCallbacks:n}=e,a=e.logger||Ac,i={authorizeRequest:n?.authorizeRequest?.bind(n)??nl,authorizeRequestOnChallenge:n?.authorizeRequestOnChallenge?.bind(n)},s=t?tl(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 rl(e,t),al(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 il({scopes:Array.isArray(r)?r:[r],response:n,request:e,getAccessToken:s,logger:a},i),c&&([n,o]=await rl(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 rl(e,t)),al(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 il({scopes:Array.isArray(r)?r:[r],response:n,request:e,getAccessToken:s,logger:a},i),c&&([n,o]=await rl(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 cl="DisableKeepAlivePolicy";function ll(e){return(e instanceof Buffer?e:Buffer.from(e.buffer)).toString("base64")}function ul(e){return Buffer.from(e,"base64")}const dl="$",pl="_";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 hl=/^[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 fl(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 gl{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??pl}};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,!hl.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=ll(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=ll(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][dl]={[e]:s.xmlNamespace}):(o[t]={},o[t][i.xml.xmlCharKey]=c,o[t][dl]={[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]=wl(s,c,a,i)}if(a&&t.xmlNamespace){const e=t.xmlNamespacePrefix?`xmlns:${t.xmlNamespacePrefix}`:"xmlns",r=o;return r[dl]={[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){kl(e,t)&&(t=Nl(e,t,r,"clientName"));if(null!=r){const s={},o=_l(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=vl(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[dl]={...d[dl],[e]:t.xmlNamespace}}const s=""!==l.serializedName?n+"."+l.serializedName:n;let o=r[c];const p=kl(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=wl(l,m,a,i);a&&l.xmlIsAttribute?(d[dl]=d[dl]||{},d[dl][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??pl},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??pl;kl(e,t)&&(t=Nl(e,t,r,"serializedName"));const s=_l(e,t,n);let o={};const c=[];for(const l of Object.keys(s)){const u=s[l],d=vl(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[dl])o[l]=e.deserialize(u,r[dl][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(vl(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)||Sl(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[dl]&&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=ul(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,"/"),ul(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 yl(e={},t=!1){return new gl(e,t)}function vl(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 _l(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 wl(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[dl])return t;{const e={...t};return e[dl]=i,e}}const s={};return s[n.xml.xmlCharKey]=t,s[dl]=i,s}function Sl(e,t){return[dl,t.xml.xmlCharKey].includes(e)}function Nl(e,t,r,n){const a=kl(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 kl(e,t){return t.type.polymorphicDiscriminator||xl(e,t.type.uberParent)||xl(e,t.type.className)}function xl(e,t){return t&&e.modelMappers[t]&&e.modelMappers[t].type.polymorphicDiscriminator}const Pl="Sequence",El="String",Cl="Stream";var Al,Ol={};const Il=(Al||(Al=1,Object.defineProperty(Ol,"__esModule",{value:!0}),Ol.state=void 0,Ol.state={operationRequestMap:new WeakMap}),Ol).state;function $l(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=Tl(e,n);!t.propertyFound&&r&&(t=Tl(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=$l(e,{parameterPath:n[t],mapper:s},r);void 0!==o&&(i||(i={}),i[t]=o)}}return i}function Tl(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 zl=Symbol.for("@azure/core-client original request");function Rl(e){if(function(e){return zl in e}(e))return Rl(e[zl]);let t=Il.operationRequestMap.get(e);return t||(t={},Il.operationRequestMap.set(e,t)),t}const Ll=["application/json","text/json"],Ml=["application/xml","application/atom+xml"];function jl(e={}){const t=e.expectedContentTypes?.json??Ll,r=e.expectedContentTypes?.xml??Ml,n=e.parseXML,a=e.serializerOptions,i={xml:{rootName:a?.xml.rootName??"",includeRoot:a?.xml.includeRoot??!1,xmlCharKey:a?.xml.xmlCharKey??pl}};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||Kc.PARSE_ERROR;throw new Kc(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=Rl(t),n=r?.shouldDeserialize;let a;a=void 0===n||("boolean"==typeof n?n:n(e));return a}(i))return i;const s=Rl(i.request),o=s?.operationSpec;if(!o||!o.responses)return i;const c=function(e){let t;const r=e.request,n=Rl(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 Kc(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===Pl){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===Pl&&(e="object"==typeof e?e[c.bodyMapper.xmlElementName]:[]);try{i.parsedBody=o.serializer.deserialize(c.bodyMapper,e,"operationRes.parsedBody",n)}catch(e){throw new Kc(`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 Dl(e){const{parameterPath:t,mapper:r}=e;let n;return n="string"==typeof t?t:Array.isArray(t)?t.join("."):r.serializedName,n}function Fl(e={}){const t=e.stringifyXML;return{name:"serializationPolicy",async sendRequest(e,r){const n=Rl(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=$l(t,n);if(null!=a||n.mapper.required){a=r.serializer.serialize(n.mapper,a,Dl(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||Dl(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??pl}},s=i.xml.xmlCharKey;if(r.requestBody&&r.requestBody.mapper){e.body=$l(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=Dl(r.requestBody);e.body=r.serializer.serialize(a,e.body,t,i);const o=h===Cl;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[dl]={[t]:e},r}return n}(d,t,h,e.body,i);h===Pl?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[dl]={[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===El&&(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=$l(t,n);if(null!=a){const t=n.mapper.serializedName||Dl(n);e.formData[t]=r.serializer.serialize(n.mapper,a,Dl(n),i)}}}}(e,i,a,t)),r(e)}}}let Ul;function Bl(){return Ul||(Ul=function(){const e=vo();return{async sendRequest(t){const{abortSignal:r,cleanup:n}=t.abortSignal?Yc(t.abortSignal):{};try{return t.abortSignal=r,await e.sendRequest(t)}finally{n?.()}}}}()),Ul}const ql={CSV:",",SSV:" ",Multi:"Multi",TSV:"\t",Pipes:"|"};function Vl(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=$l(t,a,r);const s=Dl(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=Gl(e,a);if(t.path){let e=Gl(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=$l(t,i,r);if(null!=s||i.mapper.required){s=e.serializer.serialize(i.mapper,s,Dl(i));const t=i.collectionFormat?ql[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||Dl(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 Gl(e,t){let r=e;for(const[e,n]of t)r=r.split(e).join(n);return r}const Hl=Cc("core-client");class Wl{_endpoint;_requestContentType;_allowInsecureConnection;_httpClient;pipeline;constructor(e={}){if(this._requestContentType=e.requestContentType,this._endpoint=e.endpoint??e.baseUri,e.baseUri&&Hl.warning("The baseUri option for SDK Clients has been deprecated, please use endpoint instead."),this._allowInsecureConnection=e.allowInsecureConnection,this._httpClient=e.httpClient||Bl(),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=Xc(e??{});return e.credentialOptions&&t.addPolicy(sl({credential:e.credentialOptions.credential,scopes:e.credentialOptions.credentialScopes})),t.addPolicy(Fl(e.serializationOptions),{phase:"Serialize"}),t.addPolicy(jl(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=Qc({url:Vl(r,t,e,this)});n.method=t.httpMethod;const a=Rl(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===Cl&&t.add(Number(r))}return t}(t));try{const e=await this.sendRequest(n),r=fl(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=fl(r,t.responses[e.statusCode]||t.responses.default);e.details=n,s?.onResponse&&s.onResponse(r,n,e)}throw e}}}function Kl(e){return new Jl(e.toJSON({preserveCase:!0}))}function Zl(e){return e.toLowerCase()}class Jl{_headersMap;constructor(e){if(this._headersMap={},e)for(const t in e)this.set(t,e[t])}set(e,t){this._headersMap[Zl(e)]={name:e,value:t.toString()}}get(e){const t=this._headersMap[Zl(e)];return t?t.value:void 0}contains(e){return!!this._headersMap[Zl(e)]}remove(e){const t=this.contains(e);return delete this._headersMap[Zl(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[Zl(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 Jl(e)}}function Yl(e,t){let r=function(e){return{url:e.url,method:e.method,headers:Kl(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=Kl(e.headers);return{...e,request:r,headers:n}}class Xl extends Wl{constructor(e){super(e),!1!==e.keepAliveOptions?.enable||this.pipeline.getOrderedPolicies().some(e=>e.name===cl)||this.pipeline.addPolicy({name:cl,sendRequest:async(e,t)=>(e.disableKeepAlive=!0,t(e))}),!1===e.redirectOptions?.handleRedirects&&this.pipeline.removePolicy({name:Ic})}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:Yl(n)}),a}}const Ql={type:{name:"Composite",className:"ErrorResponse",modelProperties:{error:{serializedName:"error",type:{name:"Composite",className:"ErrorDetail"}}}}},eu={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"}}}}},tu={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"}}}}},ru={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"}}}}},nu={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"}}}}},au={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"}}}}},iu={type:{name:"Composite",className:"IndexBatch",modelProperties:{actions:{serializedName:"value",required:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"IndexAction"}}}}}}},su={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"}}}}}}},cu={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"}}}}},lu={serializedName:"vector",type:{name:"Composite",className:"VectorizedQuery",uberParent:"VectorQuery",polymorphicDiscriminator:ru.type.polymorphicDiscriminator,modelProperties:{...ru.type.modelProperties,vector:{serializedName:"vector",required:!0,type:{name:"Sequence",element:{type:{name:"Number"}}}}}}},uu={serializedName:"text",type:{name:"Composite",className:"VectorizableTextQuery",uberParent:"VectorQuery",polymorphicDiscriminator:ru.type.polymorphicDiscriminator,modelProperties:{...ru.type.modelProperties,text:{serializedName:"text",required:!0,type:{name:"String"}}}}};let du={VectorQuery:ru,"VectorQuery.vector":lu,"VectorQuery.text":uu};var pu=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:cu,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:Ql,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:iu,IndexDocumentsResult:su,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:eu,SearchRequest:tu,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:nu,SuggestRequest:au,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:ru,VectorizableTextQuery:uu,VectorizedQuery:lu,VectorsDebugInfo:{type:{name:"Composite",className:"VectorsDebugInfo",modelProperties:{subscores:{serializedName:"subscores",type:{name:"Composite",className:"QueryResultDocumentSubscores"}}}}},discriminators:du});const mu={parameterPath:"accept",mapper:{defaultValue:"application/json",isConstant:!0,serializedName:"Accept",type:{name:"String"}}},hu={parameterPath:"endpoint",mapper:{serializedName:"endpoint",required:!0,type:{name:"String"}},skipEncoding:!0},fu={parameterPath:"indexName",mapper:{serializedName:"indexName",required:!0,type:{name:"String"}}},gu={parameterPath:"apiVersion",mapper:{serializedName:"api-version",required:!0,type:{name:"String"}}},yu={parameterPath:["options","contentType"],mapper:{defaultValue:"application/json",isConstant:!0,serializedName:"Content-Type",type:{name:"String"}}},vu={parameterPath:"searchRequest",mapper:tu},bu={parameterPath:"searchText",mapper:{serializedName:"search",required:!0,type:{name:"String"}}},_u={parameterPath:"suggesterName",mapper:{serializedName:"suggesterName",required:!0,type:{name:"String"}}},wu={parameterPath:"suggestRequest",mapper:au},Su={parameterPath:"batch",mapper:iu},Nu={parameterPath:"autocompleteRequest",mapper:cu};class ku{client;constructor(e){this.client=e}count(e){return this.client.sendOperationRequest({options:e},Pu)}searchGet(e){return this.client.sendOperationRequest({options:e},Eu)}searchPost(e,t){return this.client.sendOperationRequest({searchRequest:e,options:t},Cu)}get(e,t){return this.client.sendOperationRequest({key:e,options:t},Au)}suggestGet(e,t,r){return this.client.sendOperationRequest({searchText:e,suggesterName:t,options:r},Ou)}suggestPost(e,t){return this.client.sendOperationRequest({suggestRequest:e,options:t},Iu)}index(e,t){return this.client.sendOperationRequest({batch:e,options:t},$u)}autocompleteGet(e,t,r){return this.client.sendOperationRequest({searchText:e,suggesterName:t,options:r},Tu)}autocompletePost(e,t){return this.client.sendOperationRequest({autocompleteRequest:e,options:t},zu)}}const xu=yl(pu,!1),Pu={path:"/docs/$count",httpMethod:"GET",responses:{200:{bodyMapper:{type:{name:"Number"}}},default:{bodyMapper:Ql}},queryParameters:[gu],urlParameters:[hu,fu],headerParameters:[mu],serializer:xu},Eu={path:"/docs",httpMethod:"GET",responses:{200:{bodyMapper:eu},206:{bodyMapper:eu},default:{bodyMapper:Ql}},queryParameters:[gu,{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:[hu,fu],headerParameters:[mu],serializer:xu},Cu={path:"/docs/search.post.search",httpMethod:"POST",responses:{200:{bodyMapper:eu},206:{bodyMapper:eu},default:{bodyMapper:Ql}},requestBody:vu,queryParameters:[gu],urlParameters:[hu,fu],headerParameters:[mu,yu],mediaType:"json",serializer:xu},Au={path:"/docs('{key}')",httpMethod:"GET",responses:{200:{bodyMapper:{type:{name:"Dictionary",value:{type:{name:"any"}}}}},default:{bodyMapper:Ql}},queryParameters:[gu,{parameterPath:["options","selectedFields"],mapper:{serializedName:"$select",type:{name:"Sequence",element:{type:{name:"String"}}}},collectionFormat:"CSV"}],urlParameters:[hu,fu,{parameterPath:"key",mapper:{serializedName:"key",required:!0,type:{name:"String"}}}],headerParameters:[mu],serializer:xu},Ou={path:"/docs/search.suggest",httpMethod:"GET",responses:{200:{bodyMapper:nu},default:{bodyMapper:Ql}},queryParameters:[gu,bu,_u,{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:[hu,fu],headerParameters:[mu],serializer:xu},Iu={path:"/docs/search.post.suggest",httpMethod:"POST",responses:{200:{bodyMapper:nu},default:{bodyMapper:Ql}},requestBody:wu,queryParameters:[gu],urlParameters:[hu,fu],headerParameters:[mu,yu],mediaType:"json",serializer:xu},$u={path:"/docs/search.index",httpMethod:"POST",responses:{200:{bodyMapper:su},207:{bodyMapper:su},default:{bodyMapper:Ql}},requestBody:Su,queryParameters:[gu],urlParameters:[hu,fu],headerParameters:[mu,yu],mediaType:"json",serializer:xu},Tu={path:"/docs/search.autocomplete",httpMethod:"GET",responses:{200:{bodyMapper:ou},default:{bodyMapper:Ql}},queryParameters:[gu,bu,_u,{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:[hu,fu],headerParameters:[mu],serializer:xu},zu={path:"/docs/search.post.autocomplete",httpMethod:"POST",responses:{200:{bodyMapper:ou},default:{bodyMapper:Ql}},requestBody:Nu,queryParameters:[gu],urlParameters:[hu,fu],headerParameters:[mu,yu],mediaType:"json",serializer:xu};let Ru=class extends Xl{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 ku(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 Lu=Cc("search");function Mu(e){return{name:"OdataMetadataPolicy",sendRequest:async(t,r)=>(t.headers.set("Accept",`application/json;odata.metadata=${e}`),r(t))}}const ju="api-key";function Du(e){return{name:"SearchApiKeyCredentialPolicy",sendRequest:async(t,r)=>(t.headers.has(ju)||t.headers.set(ju,e.key),r(t))}}function Fu(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(!Uu(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){Uu(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 Uu(e){return Array.isArray(e)?Uu(e[0]):"object"==typeof e&&null!==e}const Bu=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/i,qu="Point",Vu="EPSG:4326",[Gu,Hu]=[[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 $s?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&&Bu.test(e)?new Date(e):e},function(e){if(t=e,Ku(t,{requiredKeys:["type","coordinates"],propertyValidator:e=>{switch(e){case"type":return t.type===qu;case"coordinates":return r=t.coordinates,!!Array.isArray(r)&&2===r.length&&"number"==typeof r[0]&&"number"==typeof r[1];case"crs":return Ku(n=t.crs,{requiredKeys:["type","properties"],propertyValidator:e=>{switch(e){case"type":return"name"===n.type;case"properties":return Ku(t=n.properties,{requiredKeys:["name"],propertyValidator:e=>"name"===e&&t.name===Vu});default:return!1}var t}});default:return!1}var r,n}})){const[t,r]=e.coordinates;return new $s({longitude:t,latitude:r})}var t;return e}]].map(e=>t=>e.reduceRight((e,t)=>t(e),t));function Wu(e){return Fu(e,Hu)}function Ku(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 Zu,Ju,Yu,Xu;!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"}(Zu||(Zu={})),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"}(Ju||(Ju={})),function(e){e.HtmlStrip="html_strip"}(Yu||(Yu={})),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"}(Xu||(Xu={}));const Qu="2025-09-01";function ed(e){if(!e)return e;const t=[];for(const r of e)t.push(r);return t}function td(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 rd(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 nd(e){return e?e.map(e=>{if("Collection(Edm.ComplexType)"===e.type||"Edm.ComplexType"===e.type){return{name:e.name,type:e.type,fields:nd(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 ad(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?ad(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 id(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 sd(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 cd(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 ld(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 ud(e){return{name:e.name,description:e.description,defaultScoringProfile:e.defaultScoringProfile,corsOptions:e.corsOptions,suggesters:e.suggesters,encryptionKey:cd(e.encryptionKey),etag:e.etag,analyzers:rd(e.analyzers),tokenizers:sd(e.tokenizers),tokenFilters:e.tokenFilters,normalizers:e.normalizers,charFilters:e.charFilters,scoringProfiles:e.scoringProfiles,fields:nd(e.fields),similarity:(t=e.similarity,t?(t.odatatype,t):t),semanticSearch:e.semanticSearch,vectorSearch:md(e.vectorSearch)};var t}function dd(e){if(!e)return e;switch(e.kind){case"azureOpenAI":{const{parameters:t}=e,r=yd(t?.authIdentity);return{...e,parameters:{...t,authIdentity:r}}}case"customWebApi":{const{parameters:t}=e,r=yd(t?.authIdentity);return{...e,parameters:{...t,authIdentity:r}}}}return Lu.warning(`Unsupported vectorizer kind: ${e.kind}`),e}function pd(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(pd),vectorizers:e.vectorizers?.map(dd)}:e}function hd(e){const{encryptionKey:t,tokenFilters:r,analyzers:n,tokenizers:a,fields:i,similarity:s}=e;return{...e,encryptionKey:ld(t),tokenFilters:ed(r),analyzers:td(n),tokenizers:id(a),fields:ad(i),similarity:od(s)}}function fd(e){const t={name:e.name,encryptionKey:cd(e.encryptionKey),etag:e.etag,synonyms:[]};return e.synonyms&&(t.synonyms=e.synonyms.split("\n")),t}function gd(e){const t={name:e.name,format:"solr",encryptionKey:ld(e.encryptionKey),etag:e.etag,synonyms:e.synonyms.join("\n")};return t.encryptionKey=ld(e.encryptionKey),t}function yd(e){return e?(e.odatatype,e):e}const vd=Wc({namespace:"Microsoft.Search",packageName:"Azure.Search"}).startSpan;class bd{serviceVersion=Qu;apiVersion=Qu;endpoint;indexName;client;constructor(e,t,r,n={}){this.endpoint=e,this.indexName=t;const a={...n,loggingOptions:{logger:Lu.info,additionalAllowedHeaderNames:["elapsed-time","Location","OData-MaxVersion","OData-Version","Prefer","throttle-reason"]}};if(this.serviceVersion=n.serviceVersion??n.apiVersion??Qu,this.apiVersion=this.serviceVersion,this.client=new Ru(this.endpoint,this.indexName,this.serviceVersion,a),Is(r)){const e=n.audience?`${n.audience}/.default`:`${zs.AzurePublicCloud}/.default`;this.client.pipeline.addPolicy(sl({credential:r,scopes:e}))}else this.client.pipeline.addPolicy(Du(r));this.client.pipeline.addPolicy(Mu("none"))}async getDocumentsCount(e={}){const{span:t,updatedOptions:r}=vd("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}=vd("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:_}=vd("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 Wu({...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}=vd("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}=vd("SearchClient-suggest",r);try{const e=await this.client.documents.suggestPost(o,l);return Wu({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}=vd("SearchClient-getDocument",t);try{return Wu(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}=vd("SearchClient-indexDocuments",t);try{let r=0;const i=await this.client.documents.index({actions:(a=e.actions,Fu(a,Gu))},{...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}=vd("SearchClient-uploadDocuments",t),a=new Ts;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}=vd("SearchClient-mergeDocuments",t),a=new Ts;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}=vd("SearchClient-mergeDocuments",t),a=new Ts;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}=vd("SearchClient-deleteDocuments",r),i=new Ts;"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 _d={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"}}}}},wd={type:{name:"Composite",className:"DataChangeDetectionPolicy",uberParent:"DataChangeDetectionPolicy",polymorphicDiscriminator:{serializedName:"@odata\\.type",clientName:"odatatype"},modelProperties:{odatatype:{serializedName:"@odata\\.type",required:!0,type:{name:"String"}}}}},Sd={type:{name:"Composite",className:"DataDeletionDetectionPolicy",uberParent:"DataDeletionDetectionPolicy",polymorphicDiscriminator:{serializedName:"@odata\\.type",clientName:"odatatype"},modelProperties:{odatatype:{serializedName:"@odata\\.type",required:!0,type:{name:"String"}}}}},Nd={type:{name:"Composite",className:"ErrorResponse",modelProperties:{error:{serializedName:"error",type:{name:"Composite",className:"ErrorDetail"}}}}},kd={type:{name:"Composite",className:"ListDataSourcesResult",modelProperties:{dataSources:{serializedName:"value",required:!0,readOnly:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"SearchIndexerDataSource"}}}}}}},xd={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"}}}}},Pd={type:{name:"Composite",className:"ListIndexersResult",modelProperties:{indexers:{serializedName:"value",required:!0,readOnly:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"SearchIndexer"}}}}}}},Ed={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"}}}}},Cd={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"}}}}},Ad={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"}}}}}}},Od={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"}}}}},Id={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"}}}}}}},$d={type:{name:"Composite",className:"ListSkillsetsResult",modelProperties:{skillsets:{serializedName:"value",required:!0,readOnly:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"SearchIndexerSkillset"}}}}}}},Td={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"}}}}},zd={type:{name:"Composite",className:"ListSynonymMapsResult",modelProperties:{synonymMaps:{serializedName:"value",required:!0,readOnly:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"SynonymMap"}}}}}}},Rd={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"}}}}},Ld={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"]}}}}},Md={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"}}}}},jd={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"}}}}},Dd={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"}}}}},Fd={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"}}}}},Ud={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"}}}}},Bd={type:{name:"Composite",className:"Similarity",uberParent:"Similarity",polymorphicDiscriminator:{serializedName:"@odata\\.type",clientName:"odatatype"},modelProperties:{odatatype:{serializedName:"@odata\\.type",required:!0,type:{name:"String"}}}}},qd={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"}}}}},Vd={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"}}}}},Gd={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"}}}}},Hd={type:{name:"Composite",className:"ListIndexesResult",modelProperties:{indexes:{serializedName:"value",required:!0,readOnly:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"SearchIndex"}}}}}}},Wd={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"}}}}},Kd={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"}}}}}}},Zd={type:{name:"Composite",className:"AnalyzeResult",modelProperties:{tokens:{serializedName:"tokens",required:!0,type:{name:"Sequence",element:{type:{name:"Composite",className:"AnalyzedTokenInfo"}}}}}}},Jd={type:{name:"Composite",className:"ServiceStatistics",modelProperties:{counters:{serializedName:"counters",type:{name:"Composite",className:"ServiceCounters"}},limits:{serializedName:"limits",type:{name:"Composite",className:"ServiceLimits"}}}}},Yd={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"}}}}},Xd={type:{name:"Composite",className:"SearchIndexerDataIdentity",uberParent:"SearchIndexerDataIdentity",polymorphicDiscriminator:{serializedName:"@odata\\.type",clientName:"odatatype"},modelProperties:{odatatype:{serializedName:"@odata\\.type",required:!0,type:{name:"String"}}}}},Qd={serializedName:"#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy",type:{name:"Composite",className:"HighWaterMarkChangeDetectionPolicy",uberParent:"DataChangeDetectionPolicy",polymorphicDiscriminator:wd.type.polymorphicDiscriminator,modelProperties:{...wd.type.modelProperties,highWaterMarkColumnName:{serializedName:"highWaterMarkColumnName",required:!0,type:{name:"String"}}}}},ep={serializedName:"#Microsoft.Azure.Search.SqlIntegratedChangeTrackingPolicy",type:{name:"Composite",className:"SqlIntegratedChangeTrackingPolicy",uberParent:"DataChangeDetectionPolicy",polymorphicDiscriminator:wd.type.polymorphicDiscriminator,modelProperties:{...wd.type.modelProperties}}},tp={serializedName:"#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy",type:{name:"Composite",className:"SoftDeleteColumnDeletionDetectionPolicy",uberParent:"DataDeletionDetectionPolicy",polymorphicDiscriminator:Sd.type.polymorphicDiscriminator,modelProperties:{...Sd.type.modelProperties,softDeleteColumnName:{serializedName:"softDeleteColumnName",type:{name:"String"}},softDeleteMarkerValue:{serializedName:"softDeleteMarkerValue",type:{name:"String"}}}}},rp={serializedName:"#Microsoft.Skills.Util.ConditionalSkill",type:{name:"Composite",className:"ConditionalSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Ad.type.polymorphicDiscriminator,modelProperties:{...Ad.type.modelProperties}}},np={serializedName:"#Microsoft.Skills.Text.KeyPhraseExtractionSkill",type:{name:"Composite",className:"KeyPhraseExtractionSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Ad.type.polymorphicDiscriminator,modelProperties:{...Ad.type.modelProperties,defaultLanguageCode:{serializedName:"defaultLanguageCode",type:{name:"String"}},maxKeyPhraseCount:{serializedName:"maxKeyPhraseCount",nullable:!0,type:{name:"Number"}},modelVersion:{serializedName:"modelVersion",nullable:!0,type:{name:"String"}}}}},ap={serializedName:"#Microsoft.Skills.Vision.OcrSkill",type:{name:"Composite",className:"OcrSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Ad.type.polymorphicDiscriminator,modelProperties:{...Ad.type.modelProperties,defaultLanguageCode:{serializedName:"defaultLanguageCode",type:{name:"String"}},shouldDetectOrientation:{defaultValue:!1,serializedName:"detectOrientation",type:{name:"Boolean"}},lineEnding:{serializedName:"lineEnding",type:{name:"String"}}}}},ip={serializedName:"#Microsoft.Skills.Vision.ImageAnalysisSkill",type:{name:"Composite",className:"ImageAnalysisSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Ad.type.polymorphicDiscriminator,modelProperties:{...Ad.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"}}}}}}},sp={serializedName:"#Microsoft.Skills.Text.LanguageDetectionSkill",type:{name:"Composite",className:"LanguageDetectionSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Ad.type.polymorphicDiscriminator,modelProperties:{...Ad.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:Ad.type.polymorphicDiscriminator,modelProperties:{...Ad.type.modelProperties}}},cp={serializedName:"#Microsoft.Skills.Text.MergeSkill",type:{name:"Composite",className:"MergeSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Ad.type.polymorphicDiscriminator,modelProperties:{...Ad.type.modelProperties,insertPreTag:{defaultValue:" ",serializedName:"insertPreTag",type:{name:"String"}},insertPostTag:{defaultValue:" ",serializedName:"insertPostTag",type:{name:"String"}}}}},lp={serializedName:"#Microsoft.Skills.Text.EntityRecognitionSkill",type:{name:"Composite",className:"EntityRecognitionSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Ad.type.polymorphicDiscriminator,modelProperties:{...Ad.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"}}}}},up={serializedName:"#Microsoft.Skills.Text.SentimentSkill",type:{name:"Composite",className:"SentimentSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Ad.type.polymorphicDiscriminator,modelProperties:{...Ad.type.modelProperties,defaultLanguageCode:{serializedName:"defaultLanguageCode",type:{name:"String"}}}}},dp={serializedName:"#Microsoft.Skills.Text.V3.SentimentSkill",type:{name:"Composite",className:"SentimentSkillV3",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Ad.type.polymorphicDiscriminator,modelProperties:{...Ad.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"}}}}},pp={serializedName:"#Microsoft.Skills.Text.V3.EntityLinkingSkill",type:{name:"Composite",className:"EntityLinkingSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Ad.type.polymorphicDiscriminator,modelProperties:{...Ad.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:Ad.type.polymorphicDiscriminator,modelProperties:{...Ad.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"}}}}},hp={serializedName:"#Microsoft.Skills.Text.PIIDetectionSkill",type:{name:"Composite",className:"PIIDetectionSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Ad.type.polymorphicDiscriminator,modelProperties:{...Ad.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"}}}}},fp={serializedName:"#Microsoft.Skills.Text.SplitSkill",type:{name:"Composite",className:"SplitSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Ad.type.polymorphicDiscriminator,modelProperties:{...Ad.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"}}}}},gp={serializedName:"#Microsoft.Skills.Text.CustomEntityLookupSkill",type:{name:"Composite",className:"CustomEntityLookupSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Ad.type.polymorphicDiscriminator,modelProperties:{...Ad.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"}}}}},yp={serializedName:"#Microsoft.Skills.Text.TranslationSkill",type:{name:"Composite",className:"TextTranslationSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Ad.type.polymorphicDiscriminator,modelProperties:{...Ad.type.modelProperties,defaultToLanguageCode:{serializedName:"defaultToLanguageCode",required:!0,type:{name:"String"}},defaultFromLanguageCode:{serializedName:"defaultFromLanguageCode",type:{name:"String"}},suggestedFrom:{serializedName:"suggestedFrom",nullable:!0,type:{name:"String"}}}}},vp={serializedName:"#Microsoft.Skills.Util.DocumentExtractionSkill",type:{name:"Composite",className:"DocumentExtractionSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Ad.type.polymorphicDiscriminator,modelProperties:{...Ad.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:Ad.type.polymorphicDiscriminator,modelProperties:{...Ad.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"}}}}},_p={serializedName:"#Microsoft.Skills.Custom.WebApiSkill",type:{name:"Composite",className:"WebApiSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Ad.type.polymorphicDiscriminator,modelProperties:{...Ad.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"}}}}},wp={serializedName:"#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill",type:{name:"Composite",className:"AzureOpenAIEmbeddingSkill",uberParent:"SearchIndexerSkill",polymorphicDiscriminator:Ad.type.polymorphicDiscriminator,modelProperties:{...Ad.type.modelProperties,...Yd.type.modelProperties,dimensions:{serializedName:"dimensions",nullable:!0,type:{name:"Number"}}}}},Sp={serializedName:"#Microsoft.Azure.Search.DefaultCognitiveServices",type:{name:"Composite",className:"DefaultCognitiveServicesAccount",uberParent:"CognitiveServicesAccount",polymorphicDiscriminator:Od.type.polymorphicDiscriminator,modelProperties:{...Od.type.modelProperties}}},Np={serializedName:"#Microsoft.Azure.Search.CognitiveServicesByKey",type:{name:"Composite",className:"CognitiveServicesAccountKey",uberParent:"CognitiveServicesAccount",polymorphicDiscriminator:Od.type.polymorphicDiscriminator,modelProperties:{...Od.type.modelProperties,key:{serializedName:"key",required:!0,type:{name:"String"}}}}},kp={type:{name:"Composite",className:"SearchIndexerKnowledgeStoreTableProjectionSelector",modelProperties:{...Id.type.modelProperties,tableName:{serializedName:"tableName",required:!0,type:{name:"String"}}}}},xp={type:{name:"Composite",className:"SearchIndexerKnowledgeStoreBlobProjectionSelector",modelProperties:{...Id.type.modelProperties,storageContainer:{serializedName:"storageContainer",required:!0,type:{name:"String"}}}}},Pp={serializedName:"distance",type:{name:"Composite",className:"DistanceScoringFunction",uberParent:"ScoringFunction",polymorphicDiscriminator:Ld.type.polymorphicDiscriminator,modelProperties:{...Ld.type.modelProperties,parameters:{serializedName:"distance",type:{name:"Composite",className:"DistanceScoringParameters"}}}}},Ep={serializedName:"freshness",type:{name:"Composite",className:"FreshnessScoringFunction",uberParent:"ScoringFunction",polymorphicDiscriminator:Ld.type.polymorphicDiscriminator,modelProperties:{...Ld.type.modelProperties,parameters:{serializedName:"freshness",type:{name:"Composite",className:"FreshnessScoringParameters"}}}}},Cp={serializedName:"magnitude",type:{name:"Composite",className:"MagnitudeScoringFunction",uberParent:"ScoringFunction",polymorphicDiscriminator:Ld.type.polymorphicDiscriminator,modelProperties:{...Ld.type.modelProperties,parameters:{serializedName:"magnitude",type:{name:"Composite",className:"MagnitudeScoringParameters"}}}}},Ap={serializedName:"tag",type:{name:"Composite",className:"TagScoringFunction",uberParent:"ScoringFunction",polymorphicDiscriminator:Ld.type.polymorphicDiscriminator,modelProperties:{...Ld.type.modelProperties,parameters:{serializedName:"tag",type:{name:"Composite",className:"TagScoringParameters"}}}}},Op={serializedName:"#Microsoft.Azure.Search.CustomAnalyzer",type:{name:"Composite",className:"CustomAnalyzer",uberParent:"LexicalAnalyzer",polymorphicDiscriminator:Md.type.polymorphicDiscriminator,modelProperties:{...Md.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"}}}}}}},Ip={serializedName:"#Microsoft.Azure.Search.PatternAnalyzer",type:{name:"Composite",className:"PatternAnalyzer",uberParent:"LexicalAnalyzer",polymorphicDiscriminator:Md.type.polymorphicDiscriminator,modelProperties:{...Md.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"}}}}}}},$p={serializedName:"#Microsoft.Azure.Search.StandardAnalyzer",type:{name:"Composite",className:"LuceneStandardAnalyzer",uberParent:"LexicalAnalyzer",polymorphicDiscriminator:Md.type.polymorphicDiscriminator,modelProperties:{...Md.type.modelProperties,maxTokenLength:{defaultValue:255,constraints:{InclusiveMaximum:300},serializedName:"maxTokenLength",type:{name:"Number"}},stopwords:{serializedName:"stopwords",type:{name:"Sequence",element:{type:{name:"String"}}}}}}},Tp={serializedName:"#Microsoft.Azure.Search.StopAnalyzer",type:{name:"Composite",className:"StopAnalyzer",uberParent:"LexicalAnalyzer",polymorphicDiscriminator:Md.type.polymorphicDiscriminator,modelProperties:{...Md.type.modelProperties,stopwords:{serializedName:"stopwords",type:{name:"Sequence",element:{type:{name:"String"}}}}}}},zp={serializedName:"#Microsoft.Azure.Search.ClassicTokenizer",type:{name:"Composite",className:"ClassicTokenizer",uberParent:"LexicalTokenizer",polymorphicDiscriminator:jd.type.polymorphicDiscriminator,modelProperties:{...jd.type.modelProperties,maxTokenLength:{defaultValue:255,constraints:{InclusiveMaximum:300},serializedName:"maxTokenLength",type:{name:"Number"}}}}},Rp={serializedName:"#Microsoft.Azure.Search.EdgeNGramTokenizer",type:{name:"Composite",className:"EdgeNGramTokenizer",uberParent:"LexicalTokenizer",polymorphicDiscriminator:jd.type.polymorphicDiscriminator,modelProperties:{...jd.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"]}}}}}}},Lp={serializedName:"#Microsoft.Azure.Search.KeywordTokenizer",type:{name:"Composite",className:"KeywordTokenizer",uberParent:"LexicalTokenizer",polymorphicDiscriminator:jd.type.polymorphicDiscriminator,modelProperties:{...jd.type.modelProperties,bufferSize:{defaultValue:256,serializedName:"bufferSize",type:{name:"Number"}}}}},Mp={serializedName:"#Microsoft.Azure.Search.KeywordTokenizerV2",type:{name:"Composite",className:"KeywordTokenizerV2",uberParent:"LexicalTokenizer",polymorphicDiscriminator:jd.type.polymorphicDiscriminator,modelProperties:{...jd.type.modelProperties,maxTokenLength:{defaultValue:256,constraints:{InclusiveMaximum:300},serializedName:"maxTokenLength",type:{name:"Number"}}}}},jp={serializedName:"#Microsoft.Azure.Search.MicrosoftLanguageTokenizer",type:{name:"Composite",className:"MicrosoftLanguageTokenizer",uberParent:"LexicalTokenizer",polymorphicDiscriminator:jd.type.polymorphicDiscriminator,modelProperties:{...jd.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"]}}}}},Dp={serializedName:"#Microsoft.Azure.Search.MicrosoftLanguageStemmingTokenizer",type:{name:"Composite",className:"MicrosoftLanguageStemmingTokenizer",uberParent:"LexicalTokenizer",polymorphicDiscriminator:jd.type.polymorphicDiscriminator,modelProperties:{...jd.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"]}}}}},Fp={serializedName:"#Microsoft.Azure.Search.NGramTokenizer",type:{name:"Composite",className:"NGramTokenizer",uberParent:"LexicalTokenizer",polymorphicDiscriminator:jd.type.polymorphicDiscriminator,modelProperties:{...jd.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"]}}}}}}},Up={serializedName:"#Microsoft.Azure.Search.PathHierarchyTokenizerV2",type:{name:"Composite",className:"PathHierarchyTokenizerV2",uberParent:"LexicalTokenizer",polymorphicDiscriminator:jd.type.polymorphicDiscriminator,modelProperties:{...jd.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"}}}}},Bp={serializedName:"#Microsoft.Azure.Search.PatternTokenizer",type:{name:"Composite",className:"PatternTokenizer",uberParent:"LexicalTokenizer",polymorphicDiscriminator:jd.type.polymorphicDiscriminator,modelProperties:{...jd.type.modelProperties,pattern:{defaultValue:"W+",serializedName:"pattern",type:{name:"String"}},flags:{serializedName:"flags",type:{name:"String"}},group:{defaultValue:-1,serializedName:"group",type:{name:"Number"}}}}},qp={serializedName:"#Microsoft.Azure.Search.StandardTokenizer",type:{name:"Composite",className:"LuceneStandardTokenizer",uberParent:"LexicalTokenizer",polymorphicDiscriminator:jd.type.polymorphicDiscriminator,modelProperties:{...jd.type.modelProperties,maxTokenLength:{defaultValue:255,serializedName:"maxTokenLength",type:{name:"Number"}}}}},Vp={serializedName:"#Microsoft.Azure.Search.StandardTokenizerV2",type:{name:"Composite",className:"LuceneStandardTokenizerV2",uberParent:"LexicalTokenizer",polymorphicDiscriminator:jd.type.polymorphicDiscriminator,modelProperties:{...jd.type.modelProperties,maxTokenLength:{defaultValue:255,constraints:{InclusiveMaximum:300},serializedName:"maxTokenLength",type:{name:"Number"}}}}},Gp={serializedName:"#Microsoft.Azure.Search.UaxUrlEmailTokenizer",type:{name:"Composite",className:"UaxUrlEmailTokenizer",uberParent:"LexicalTokenizer",polymorphicDiscriminator:jd.type.polymorphicDiscriminator,modelProperties:{...jd.type.modelProperties,maxTokenLength:{defaultValue:255,constraints:{InclusiveMaximum:300},serializedName:"maxTokenLength",type:{name:"Number"}}}}},Hp={serializedName:"#Microsoft.Azure.Search.AsciiFoldingTokenFilter",type:{name:"Composite",className:"AsciiFoldingTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.type.modelProperties,preserveOriginal:{defaultValue:!1,serializedName:"preserveOriginal",type:{name:"Boolean"}}}}},Wp={serializedName:"#Microsoft.Azure.Search.CjkBigramTokenFilter",type:{name:"Composite",className:"CjkBigramTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.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"}}}}},Kp={serializedName:"#Microsoft.Azure.Search.CommonGramTokenFilter",type:{name:"Composite",className:"CommonGramTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.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"}}}}},Zp={serializedName:"#Microsoft.Azure.Search.DictionaryDecompounderTokenFilter",type:{name:"Composite",className:"DictionaryDecompounderTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.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"}}}}},Jp={serializedName:"#Microsoft.Azure.Search.EdgeNGramTokenFilter",type:{name:"Composite",className:"EdgeNGramTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.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"]}}}}},Yp={serializedName:"#Microsoft.Azure.Search.EdgeNGramTokenFilterV2",type:{name:"Composite",className:"EdgeNGramTokenFilterV2",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.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"]}}}}},Xp={serializedName:"#Microsoft.Azure.Search.ElisionTokenFilter",type:{name:"Composite",className:"ElisionTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.type.modelProperties,articles:{serializedName:"articles",type:{name:"Sequence",element:{type:{name:"String"}}}}}}},Qp={serializedName:"#Microsoft.Azure.Search.KeepTokenFilter",type:{name:"Composite",className:"KeepTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.type.modelProperties,keepWords:{serializedName:"keepWords",required:!0,type:{name:"Sequence",element:{type:{name:"String"}}}},lowerCaseKeepWords:{defaultValue:!1,serializedName:"keepWordsCase",type:{name:"Boolean"}}}}},em={serializedName:"#Microsoft.Azure.Search.KeywordMarkerTokenFilter",type:{name:"Composite",className:"KeywordMarkerTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.type.modelProperties,keywords:{serializedName:"keywords",required:!0,type:{name:"Sequence",element:{type:{name:"String"}}}},ignoreCase:{defaultValue:!1,serializedName:"ignoreCase",type:{name:"Boolean"}}}}},tm={serializedName:"#Microsoft.Azure.Search.LengthTokenFilter",type:{name:"Composite",className:"LengthTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.type.modelProperties,minLength:{defaultValue:0,constraints:{InclusiveMaximum:300},serializedName:"min",type:{name:"Number"}},maxLength:{defaultValue:300,constraints:{InclusiveMaximum:300},serializedName:"max",type:{name:"Number"}}}}},rm={serializedName:"#Microsoft.Azure.Search.LimitTokenFilter",type:{name:"Composite",className:"LimitTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.type.modelProperties,maxTokenCount:{defaultValue:1,serializedName:"maxTokenCount",type:{name:"Number"}},consumeAllTokens:{defaultValue:!1,serializedName:"consumeAllTokens",type:{name:"Boolean"}}}}},nm={serializedName:"#Microsoft.Azure.Search.NGramTokenFilter",type:{name:"Composite",className:"NGramTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.type.modelProperties,minGram:{defaultValue:1,serializedName:"minGram",type:{name:"Number"}},maxGram:{defaultValue:2,serializedName:"maxGram",type:{name:"Number"}}}}},am={serializedName:"#Microsoft.Azure.Search.NGramTokenFilterV2",type:{name:"Composite",className:"NGramTokenFilterV2",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.type.modelProperties,minGram:{defaultValue:1,constraints:{InclusiveMaximum:300},serializedName:"minGram",type:{name:"Number"}},maxGram:{defaultValue:2,constraints:{InclusiveMaximum:300},serializedName:"maxGram",type:{name:"Number"}}}}},im={serializedName:"#Microsoft.Azure.Search.PatternCaptureTokenFilter",type:{name:"Composite",className:"PatternCaptureTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.type.modelProperties,patterns:{serializedName:"patterns",required:!0,type:{name:"Sequence",element:{type:{name:"String"}}}},preserveOriginal:{defaultValue:!0,serializedName:"preserveOriginal",type:{name:"Boolean"}}}}},sm={serializedName:"#Microsoft.Azure.Search.PatternReplaceTokenFilter",type:{name:"Composite",className:"PatternReplaceTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.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:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.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"}}}}},cm={serializedName:"#Microsoft.Azure.Search.ShingleTokenFilter",type:{name:"Composite",className:"ShingleTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.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"}}}}},lm={serializedName:"#Microsoft.Azure.Search.SnowballTokenFilter",type:{name:"Composite",className:"SnowballTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.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"]}}}}},um={serializedName:"#Microsoft.Azure.Search.StemmerTokenFilter",type:{name:"Composite",className:"StemmerTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.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"]}}}}},dm={serializedName:"#Microsoft.Azure.Search.StemmerOverrideTokenFilter",type:{name:"Composite",className:"StemmerOverrideTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.type.modelProperties,rules:{serializedName:"rules",required:!0,type:{name:"Sequence",element:{type:{name:"String"}}}}}}},pm={serializedName:"#Microsoft.Azure.Search.StopwordsTokenFilter",type:{name:"Composite",className:"StopwordsTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.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:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.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"}}}}},hm={serializedName:"#Microsoft.Azure.Search.TruncateTokenFilter",type:{name:"Composite",className:"TruncateTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.type.modelProperties,length:{defaultValue:300,constraints:{InclusiveMaximum:300},serializedName:"length",type:{name:"Number"}}}}},fm={serializedName:"#Microsoft.Azure.Search.UniqueTokenFilter",type:{name:"Composite",className:"UniqueTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.type.modelProperties,onlyOnSamePosition:{defaultValue:!1,serializedName:"onlyOnSamePosition",type:{name:"Boolean"}}}}},gm={serializedName:"#Microsoft.Azure.Search.WordDelimiterTokenFilter",type:{name:"Composite",className:"WordDelimiterTokenFilter",uberParent:"TokenFilter",polymorphicDiscriminator:Dd.type.polymorphicDiscriminator,modelProperties:{...Dd.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"}}}}}}},ym={serializedName:"#Microsoft.Azure.Search.MappingCharFilter",type:{name:"Composite",className:"MappingCharFilter",uberParent:"CharFilter",polymorphicDiscriminator:Fd.type.polymorphicDiscriminator,modelProperties:{...Fd.type.modelProperties,mappings:{serializedName:"mappings",required:!0,type:{name:"Sequence",element:{type:{name:"String"}}}}}}},vm={serializedName:"#Microsoft.Azure.Search.PatternReplaceCharFilter",type:{name:"Composite",className:"PatternReplaceCharFilter",uberParent:"CharFilter",polymorphicDiscriminator:Fd.type.polymorphicDiscriminator,modelProperties:{...Fd.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:Ud.type.polymorphicDiscriminator,modelProperties:{...Ud.type.modelProperties,tokenFilters:{serializedName:"tokenFilters",type:{name:"Sequence",element:{type:{name:"String"}}}},charFilters:{serializedName:"charFilters",type:{name:"Sequence",element:{type:{name:"String"}}}}}}},_m={serializedName:"#Microsoft.Azure.Search.ClassicSimilarity",type:{name:"Composite",className:"ClassicSimilarity",uberParent:"Similarity",polymorphicDiscriminator:Bd.type.polymorphicDiscriminator,modelProperties:{...Bd.type.modelProperties}}},wm={serializedName:"#Microsoft.Azure.Search.BM25Similarity",type:{name:"Composite",className:"BM25Similarity",uberParent:"Similarity",polymorphicDiscriminator:Bd.type.polymorphicDiscriminator,modelProperties:{...Bd.type.modelProperties,k1:{serializedName:"k1",nullable:!0,type:{name:"Number"}},b:{serializedName:"b",nullable:!0,type:{name:"Number"}}}}},Sm={serializedName:"hnsw",type:{name:"Composite",className:"HnswAlgorithmConfiguration",uberParent:"VectorSearchAlgorithmConfiguration",polymorphicDiscriminator:qd.type.polymorphicDiscriminator,modelProperties:{...qd.type.modelProperties,parameters:{serializedName:"hnswParameters",type:{name:"Composite",className:"HnswParameters"}}}}},Nm={serializedName:"exhaustiveKnn",type:{name:"Composite",className:"ExhaustiveKnnAlgorithmConfiguration",uberParent:"VectorSearchAlgorithmConfiguration",polymorphicDiscriminator:qd.type.polymorphicDiscriminator,modelProperties:{...qd.type.modelProperties,parameters:{serializedName:"exhaustiveKnnParameters",type:{name:"Composite",className:"ExhaustiveKnnParameters"}}}}},km={serializedName:"azureOpenAI",type:{name:"Composite",className:"AzureOpenAIVectorizer",uberParent:"VectorSearchVectorizer",polymorphicDiscriminator:Vd.type.polymorphicDiscriminator,modelProperties:{...Vd.type.modelProperties,parameters:{serializedName:"azureOpenAIParameters",type:{name:"Composite",className:"AzureOpenAIParameters"}}}}},xm={serializedName:"customWebApi",type:{name:"Composite",className:"WebApiVectorizer",uberParent:"VectorSearchVectorizer",polymorphicDiscriminator:Vd.type.polymorphicDiscriminator,modelProperties:{...Vd.type.modelProperties,parameters:{serializedName:"customWebApiParameters",type:{name:"Composite",className:"WebApiParameters"}}}}},Pm={serializedName:"scalarQuantization",type:{name:"Composite",className:"ScalarQuantizationCompression",uberParent:"VectorSearchCompression",polymorphicDiscriminator:Gd.type.polymorphicDiscriminator,modelProperties:{...Gd.type.modelProperties,parameters:{serializedName:"scalarQuantizationParameters",type:{name:"Composite",className:"ScalarQuantizationParameters"}}}}},Em={serializedName:"binaryQuantization",type:{name:"Composite",className:"BinaryQuantizationCompression",uberParent:"VectorSearchCompression",polymorphicDiscriminator:Gd.type.polymorphicDiscriminator,modelProperties:{...Gd.type.modelProperties}}},Cm={serializedName:"#Microsoft.Azure.Search.DataNoneIdentity",type:{name:"Composite",className:"SearchIndexerDataNoneIdentity",uberParent:"SearchIndexerDataIdentity",polymorphicDiscriminator:Xd.type.polymorphicDiscriminator,modelProperties:{...Xd.type.modelProperties}}},Am={serializedName:"#Microsoft.Azure.Search.DataUserAssignedIdentity",type:{name:"Composite",className:"SearchIndexerDataUserAssignedIdentity",uberParent:"SearchIndexerDataIdentity",polymorphicDiscriminator:Xd.type.polymorphicDiscriminator,modelProperties:{...Xd.type.modelProperties,resourceId:{serializedName:"userAssignedIdentity",required:!0,type:{name:"String"}}}}},Om={type:{name:"Composite",className:"SearchIndexerKnowledgeStoreObjectProjectionSelector",modelProperties:{...xp.type.modelProperties}}},Im={type:{name:"Composite",className:"SearchIndexerKnowledgeStoreFileProjectionSelector",modelProperties:{...xp.type.modelProperties}}};let $m={DataChangeDetectionPolicy:wd,DataDeletionDetectionPolicy:Sd,SearchIndexerSkill:Ad,CognitiveServicesAccount:Od,ScoringFunction:Ld,LexicalAnalyzer:Md,LexicalTokenizer:jd,TokenFilter:Dd,CharFilter:Fd,BaseLexicalNormalizer:Ud,Similarity:Bd,VectorSearchAlgorithmConfiguration:qd,VectorSearchVectorizer:Vd,VectorSearchCompression:Gd,SearchIndexerDataIdentity:Xd,"DataChangeDetectionPolicy.#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy":Qd,"DataChangeDetectionPolicy.#Microsoft.Azure.Search.SqlIntegratedChangeTrackingPolicy":ep,"DataDeletionDetectionPolicy.#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy":tp,"SearchIndexerSkill.#Microsoft.Skills.Util.ConditionalSkill":rp,"SearchIndexerSkill.#Microsoft.Skills.Text.KeyPhraseExtractionSkill":np,"SearchIndexerSkill.#Microsoft.Skills.Vision.OcrSkill":ap,"SearchIndexerSkill.#Microsoft.Skills.Vision.ImageAnalysisSkill":ip,"SearchIndexerSkill.#Microsoft.Skills.Text.LanguageDetectionSkill":sp,"SearchIndexerSkill.#Microsoft.Skills.Util.ShaperSkill":op,"SearchIndexerSkill.#Microsoft.Skills.Text.MergeSkill":cp,"SearchIndexerSkill.#Microsoft.Skills.Text.EntityRecognitionSkill":lp,"SearchIndexerSkill.#Microsoft.Skills.Text.SentimentSkill":up,"SearchIndexerSkill.#Microsoft.Skills.Text.V3.SentimentSkill":dp,"SearchIndexerSkill.#Microsoft.Skills.Text.V3.EntityLinkingSkill":pp,"SearchIndexerSkill.#Microsoft.Skills.Text.V3.EntityRecognitionSkill":mp,"SearchIndexerSkill.#Microsoft.Skills.Text.PIIDetectionSkill":hp,"SearchIndexerSkill.#Microsoft.Skills.Text.SplitSkill":fp,"SearchIndexerSkill.#Microsoft.Skills.Text.CustomEntityLookupSkill":gp,"SearchIndexerSkill.#Microsoft.Skills.Text.TranslationSkill":yp,"SearchIndexerSkill.#Microsoft.Skills.Util.DocumentExtractionSkill":vp,"SearchIndexerSkill.#Microsoft.Skills.Util.DocumentIntelligenceLayoutSkill":bp,"SearchIndexerSkill.#Microsoft.Skills.Custom.WebApiSkill":_p,"SearchIndexerSkill.#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill":wp,"CognitiveServicesAccount.#Microsoft.Azure.Search.DefaultCognitiveServices":Sp,"CognitiveServicesAccount.#Microsoft.Azure.Search.CognitiveServicesByKey":Np,"ScoringFunction.distance":Pp,"ScoringFunction.freshness":Ep,"ScoringFunction.magnitude":Cp,"ScoringFunction.tag":Ap,"LexicalAnalyzer.#Microsoft.Azure.Search.CustomAnalyzer":Op,"LexicalAnalyzer.#Microsoft.Azure.Search.PatternAnalyzer":Ip,"LexicalAnalyzer.#Microsoft.Azure.Search.StandardAnalyzer":$p,"LexicalAnalyzer.#Microsoft.Azure.Search.StopAnalyzer":Tp,"LexicalTokenizer.#Microsoft.Azure.Search.ClassicTokenizer":zp,"LexicalTokenizer.#Microsoft.Azure.Search.EdgeNGramTokenizer":Rp,"LexicalTokenizer.#Microsoft.Azure.Search.KeywordTokenizer":Lp,"LexicalTokenizer.#Microsoft.Azure.Search.KeywordTokenizerV2":Mp,"LexicalTokenizer.#Microsoft.Azure.Search.MicrosoftLanguageTokenizer":jp,"LexicalTokenizer.#Microsoft.Azure.Search.MicrosoftLanguageStemmingTokenizer":Dp,"LexicalTokenizer.#Microsoft.Azure.Search.NGramTokenizer":Fp,"LexicalTokenizer.#Microsoft.Azure.Search.PathHierarchyTokenizerV2":Up,"LexicalTokenizer.#Microsoft.Azure.Search.PatternTokenizer":Bp,"LexicalTokenizer.#Microsoft.Azure.Search.StandardTokenizer":qp,"LexicalTokenizer.#Microsoft.Azure.Search.StandardTokenizerV2":Vp,"LexicalTokenizer.#Microsoft.Azure.Search.UaxUrlEmailTokenizer":Gp,"TokenFilter.#Microsoft.Azure.Search.AsciiFoldingTokenFilter":Hp,"TokenFilter.#Microsoft.Azure.Search.CjkBigramTokenFilter":Wp,"TokenFilter.#Microsoft.Azure.Search.CommonGramTokenFilter":Kp,"TokenFilter.#Microsoft.Azure.Search.DictionaryDecompounderTokenFilter":Zp,"TokenFilter.#Microsoft.Azure.Search.EdgeNGramTokenFilter":Jp,"TokenFilter.#Microsoft.Azure.Search.EdgeNGramTokenFilterV2":Yp,"TokenFilter.#Microsoft.Azure.Search.ElisionTokenFilter":Xp,"TokenFilter.#Microsoft.Azure.Search.KeepTokenFilter":Qp,"TokenFilter.#Microsoft.Azure.Search.KeywordMarkerTokenFilter":em,"TokenFilter.#Microsoft.Azure.Search.LengthTokenFilter":tm,"TokenFilter.#Microsoft.Azure.Search.LimitTokenFilter":rm,"TokenFilter.#Microsoft.Azure.Search.NGramTokenFilter":nm,"TokenFilter.#Microsoft.Azure.Search.NGramTokenFilterV2":am,"TokenFilter.#Microsoft.Azure.Search.PatternCaptureTokenFilter":im,"TokenFilter.#Microsoft.Azure.Search.PatternReplaceTokenFilter":sm,"TokenFilter.#Microsoft.Azure.Search.PhoneticTokenFilter":om,"TokenFilter.#Microsoft.Azure.Search.ShingleTokenFilter":cm,"TokenFilter.#Microsoft.Azure.Search.SnowballTokenFilter":lm,"TokenFilter.#Microsoft.Azure.Search.StemmerTokenFilter":um,"TokenFilter.#Microsoft.Azure.Search.StemmerOverrideTokenFilter":dm,"TokenFilter.#Microsoft.Azure.Search.StopwordsTokenFilter":pm,"TokenFilter.#Microsoft.Azure.Search.SynonymTokenFilter":mm,"TokenFilter.#Microsoft.Azure.Search.TruncateTokenFilter":hm,"TokenFilter.#Microsoft.Azure.Search.UniqueTokenFilter":fm,"TokenFilter.#Microsoft.Azure.Search.WordDelimiterTokenFilter":gm,"CharFilter.#Microsoft.Azure.Search.MappingCharFilter":ym,"CharFilter.#Microsoft.Azure.Search.PatternReplaceCharFilter":vm,"BaseLexicalNormalizer.#Microsoft.Azure.Search.CustomNormalizer":bm,"Similarity.#Microsoft.Azure.Search.ClassicSimilarity":_m,"Similarity.#Microsoft.Azure.Search.BM25Similarity":wm,"VectorSearchAlgorithmConfiguration.hnsw":Sm,"VectorSearchAlgorithmConfiguration.exhaustiveKnn":Nm,"VectorSearchVectorizer.azureOpenAI":km,"VectorSearchVectorizer.customWebApi":xm,"VectorSearchCompression.scalarQuantization":Pm,"VectorSearchCompression.binaryQuantization":Em,"SearchIndexerDataIdentity.#Microsoft.Azure.Search.DataNoneIdentity":Cm,"SearchIndexerDataIdentity.#Microsoft.Azure.Search.DataUserAssignedIdentity":Am};var Tm=Object.freeze({__proto__:null,AnalyzeRequest:Kd,AnalyzeResult:Zd,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:Hp,AzureActiveDirectoryApplicationCredentials:{type:{name:"Composite",className:"AzureActiveDirectoryApplicationCredentials",modelProperties:{applicationId:{serializedName:"applicationId",required:!0,type:{name:"String"}},applicationSecret:{serializedName:"applicationSecret",type:{name:"String"}}}}},AzureOpenAIEmbeddingSkill:wp,AzureOpenAIParameters:Yd,AzureOpenAIVectorizer:km,BM25Similarity:wm,BaseLexicalNormalizer:Ud,BinaryQuantizationCompression:Em,CharFilter:Fd,CjkBigramTokenFilter:Wp,ClassicSimilarity:_m,ClassicTokenizer:zp,CognitiveServicesAccount:Od,CognitiveServicesAccountKey:Np,CommonGramTokenFilter:Kp,ConditionalSkill:rp,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:Op,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:gp,CustomLexicalNormalizer:bm,DataChangeDetectionPolicy:wd,DataDeletionDetectionPolicy:Sd,DataSourceCredentials:{type:{name:"Composite",className:"DataSourceCredentials",modelProperties:{connectionString:{serializedName:"connectionString",type:{name:"String"}}}}},DefaultCognitiveServicesAccount:Sp,DictionaryDecompounderTokenFilter:Zp,DistanceScoringFunction:Pp,DistanceScoringParameters:{type:{name:"Composite",className:"DistanceScoringParameters",modelProperties:{referencePointParameter:{serializedName:"referencePointParameter",required:!0,type:{name:"String"}},boostingDistance:{serializedName:"boostingDistance",required:!0,type:{name:"Number"}}}}},DocumentExtractionSkill:vp,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:Jp,EdgeNGramTokenFilterV2:Yp,EdgeNGramTokenizer:Rp,ElisionTokenFilter:Xp,EntityLinkingSkill:pp,EntityRecognitionSkill:lp,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:Nd,ExhaustiveKnnAlgorithmConfiguration:Nm,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:Ep,FreshnessScoringParameters:{type:{name:"Composite",className:"FreshnessScoringParameters",modelProperties:{boostingDuration:{serializedName:"boostingDuration",required:!0,type:{name:"TimeSpan"}}}}},GetIndexStatisticsResult:Wd,HighWaterMarkChangeDetectionPolicy:Qd,HnswAlgorithmConfiguration:Sm,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:ip,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:Qp,KeyPhraseExtractionSkill:np,KeywordMarkerTokenFilter:em,KeywordTokenizer:Lp,KeywordTokenizerV2:Mp,LanguageDetectionSkill:sp,LengthTokenFilter:tm,LexicalAnalyzer:Md,LexicalTokenizer:jd,LimitTokenFilter:rm,ListDataSourcesResult:kd,ListIndexersResult:Pd,ListIndexesResult:Hd,ListSkillsetsResult:$d,ListSynonymMapsResult:zd,LuceneStandardAnalyzer:$p,LuceneStandardTokenizer:qp,LuceneStandardTokenizerV2:Vp,MagnitudeScoringFunction:Cp,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:ym,MergeSkill:cp,MicrosoftLanguageStemmingTokenizer:Dp,MicrosoftLanguageTokenizer:jp,NGramTokenFilter:nm,NGramTokenFilterV2:am,NGramTokenizer:Fp,OcrSkill:ap,OutputFieldMappingEntry:{type:{name:"Composite",className:"OutputFieldMappingEntry",modelProperties:{name:{serializedName:"name",required:!0,type:{name:"String"}},targetName:{serializedName:"targetName",type:{name:"String"}}}}},PIIDetectionSkill:hp,PathHierarchyTokenizerV2:Up,PatternAnalyzer:Ip,PatternCaptureTokenFilter:im,PatternReplaceCharFilter:vm,PatternReplaceTokenFilter:sm,PatternTokenizer:Bp,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:Pm,ScalarQuantizationParameters:{type:{name:"Composite",className:"ScalarQuantizationParameters",modelProperties:{quantizedDataType:{serializedName:"quantizedDataType",nullable:!0,type:{name:"String"}}}}},ScoringFunction:Ld,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:Rd,SearchIndexer:xd,SearchIndexerDataContainer:{type:{name:"Composite",className:"SearchIndexerDataContainer",modelProperties:{name:{serializedName:"name",required:!0,type:{name:"String"}},query:{serializedName:"query",type:{name:"String"}}}}},SearchIndexerDataIdentity:Xd,SearchIndexerDataNoneIdentity:Cm,SearchIndexerDataSource:_d,SearchIndexerDataUserAssignedIdentity:Am,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:xp,SearchIndexerKnowledgeStoreFileProjectionSelector:Im,SearchIndexerKnowledgeStoreObjectProjectionSelector:Om,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:Id,SearchIndexerKnowledgeStoreTableProjectionSelector:kp,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:Ad,SearchIndexerSkillset:Cd,SearchIndexerStatus:Ed,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:up,SentimentSkillV3:dp,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:Jd,ShaperSkill:op,ShingleTokenFilter:cm,Similarity:Bd,SnowballTokenFilter:lm,SoftDeleteColumnDeletionDetectionPolicy:tp,SplitSkill:fp,SqlIntegratedChangeTrackingPolicy:ep,StemmerOverrideTokenFilter:dm,StemmerTokenFilter:um,StopAnalyzer:Tp,StopwordsTokenFilter:pm,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:Td,SynonymTokenFilter:mm,TagScoringFunction:Ap,TagScoringParameters:{type:{name:"Composite",className:"TagScoringParameters",modelProperties:{tagsParameter:{serializedName:"tagsParameter",required:!0,type:{name:"String"}}}}},TextTranslationSkill:yp,TextWeights:{type:{name:"Composite",className:"TextWeights",modelProperties:{weights:{serializedName:"weights",required:!0,type:{name:"Dictionary",value:{type:{name:"Number"}}}}}}},TokenFilter:Dd,TruncateTokenFilter:hm,UaxUrlEmailTokenizer:Gp,UniqueTokenFilter:fm,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:qd,VectorSearchCompression:Gd,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:Vd,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:_p,WebApiVectorizer:xm,WordDelimiterTokenFilter:gm,discriminators:$m});const zm={parameterPath:["options","contentType"],mapper:{defaultValue:"application/json",isConstant:!0,serializedName:"Content-Type",type:{name:"String"}}},Rm={parameterPath:"dataSource",mapper:_d},Lm={parameterPath:"accept",mapper:{defaultValue:"application/json",isConstant:!0,serializedName:"Accept",type:{name:"String"}}},Mm={parameterPath:"endpoint",mapper:{serializedName:"endpoint",required:!0,type:{name:"String"}},skipEncoding:!0},jm={parameterPath:"dataSourceName",mapper:{serializedName:"dataSourceName",required:!0,type:{name:"String"}}},Dm={parameterPath:["options","ifMatch"],mapper:{serializedName:"If-Match",type:{name:"String"}}},Fm={parameterPath:["options","ifNoneMatch"],mapper:{serializedName:"If-None-Match",type:{name:"String"}}},Um={parameterPath:"prefer",mapper:{defaultValue:"return=representation",isConstant:!0,serializedName:"Prefer",type:{name:"String"}}},Bm={parameterPath:"apiVersion",mapper:{serializedName:"api-version",required:!0,type:{name:"String"}}},qm={parameterPath:["options","select"],mapper:{serializedName:"$select",type:{name:"String"}}},Vm={parameterPath:"indexerName",mapper:{serializedName:"indexerName",required:!0,type:{name:"String"}}},Gm={parameterPath:"indexer",mapper:xd},Hm={parameterPath:"skillset",mapper:Cd},Wm={parameterPath:"skillsetName",mapper:{serializedName:"skillsetName",required:!0,type:{name:"String"}}},Km={parameterPath:"synonymMap",mapper:Td},Zm={parameterPath:"synonymMapName",mapper:{serializedName:"synonymMapName",required:!0,type:{name:"String"}}},Jm={parameterPath:"index",mapper:Rd},Ym={parameterPath:"indexName",mapper:{serializedName:"indexName",required:!0,type:{name:"String"}}},Xm={parameterPath:"request",mapper:Kd};class Qm{client;constructor(e){this.client=e}createOrUpdate(e,t,r){return this.client.sendOperationRequest({dataSourceName:e,dataSource:t,options:r},th)}delete(e,t){return this.client.sendOperationRequest({dataSourceName:e,options:t},rh)}get(e,t){return this.client.sendOperationRequest({dataSourceName:e,options:t},nh)}list(e){return this.client.sendOperationRequest({options:e},ah)}create(e,t){return this.client.sendOperationRequest({dataSource:e,options:t},ih)}}const eh=yl(Tm,!1),th={path:"/datasources('{dataSourceName}')",httpMethod:"PUT",responses:{200:{bodyMapper:_d},201:{bodyMapper:_d},default:{bodyMapper:Nd}},requestBody:Rm,queryParameters:[Bm],urlParameters:[Mm,jm],headerParameters:[zm,Lm,Dm,Fm,Um],mediaType:"json",serializer:eh},rh={path:"/datasources('{dataSourceName}')",httpMethod:"DELETE",responses:{204:{},404:{},default:{bodyMapper:Nd}},queryParameters:[Bm],urlParameters:[Mm,jm],headerParameters:[Lm,Dm,Fm],serializer:eh},nh={path:"/datasources('{dataSourceName}')",httpMethod:"GET",responses:{200:{bodyMapper:_d},default:{bodyMapper:Nd}},queryParameters:[Bm],urlParameters:[Mm,jm],headerParameters:[Lm],serializer:eh},ah={path:"/datasources",httpMethod:"GET",responses:{200:{bodyMapper:kd},default:{bodyMapper:Nd}},queryParameters:[Bm,qm],urlParameters:[Mm],headerParameters:[Lm],serializer:eh},ih={path:"/datasources",httpMethod:"POST",responses:{201:{bodyMapper:_d},default:{bodyMapper:Nd}},requestBody:Rm,queryParameters:[Bm],urlParameters:[Mm],headerParameters:[zm,Lm],mediaType:"json",serializer:eh};class sh{client;constructor(e){this.client=e}reset(e,t){return this.client.sendOperationRequest({indexerName:e,options:t},ch)}run(e,t){return this.client.sendOperationRequest({indexerName:e,options:t},lh)}createOrUpdate(e,t,r){return this.client.sendOperationRequest({indexerName:e,indexer:t,options:r},uh)}delete(e,t){return this.client.sendOperationRequest({indexerName:e,options:t},dh)}get(e,t){return this.client.sendOperationRequest({indexerName:e,options:t},ph)}list(e){return this.client.sendOperationRequest({options:e},mh)}create(e,t){return this.client.sendOperationRequest({indexer:e,options:t},hh)}getStatus(e,t){return this.client.sendOperationRequest({indexerName:e,options:t},fh)}}const oh=yl(Tm,!1),ch={path:"/indexers('{indexerName}')/search.reset",httpMethod:"POST",responses:{204:{},default:{bodyMapper:Nd}},queryParameters:[Bm],urlParameters:[Mm,Vm],headerParameters:[Lm],serializer:oh},lh={path:"/indexers('{indexerName}')/search.run",httpMethod:"POST",responses:{202:{},default:{bodyMapper:Nd}},queryParameters:[Bm],urlParameters:[Mm,Vm],headerParameters:[Lm],serializer:oh},uh={path:"/indexers('{indexerName}')",httpMethod:"PUT",responses:{200:{bodyMapper:xd},201:{bodyMapper:xd},default:{bodyMapper:Nd}},requestBody:Gm,queryParameters:[Bm],urlParameters:[Mm,Vm],headerParameters:[zm,Lm,Dm,Fm,Um],mediaType:"json",serializer:oh},dh={path:"/indexers('{indexerName}')",httpMethod:"DELETE",responses:{204:{},404:{},default:{bodyMapper:Nd}},queryParameters:[Bm],urlParameters:[Mm,Vm],headerParameters:[Lm,Dm,Fm],serializer:oh},ph={path:"/indexers('{indexerName}')",httpMethod:"GET",responses:{200:{bodyMapper:xd},default:{bodyMapper:Nd}},queryParameters:[Bm],urlParameters:[Mm,Vm],headerParameters:[Lm],serializer:oh},mh={path:"/indexers",httpMethod:"GET",responses:{200:{bodyMapper:Pd},default:{bodyMapper:Nd}},queryParameters:[Bm,qm],urlParameters:[Mm],headerParameters:[Lm],serializer:oh},hh={path:"/indexers",httpMethod:"POST",responses:{201:{bodyMapper:xd},default:{bodyMapper:Nd}},requestBody:Gm,queryParameters:[Bm],urlParameters:[Mm],headerParameters:[zm,Lm],mediaType:"json",serializer:oh},fh={path:"/indexers('{indexerName}')/search.status",httpMethod:"GET",responses:{200:{bodyMapper:Ed},default:{bodyMapper:Nd}},queryParameters:[Bm],urlParameters:[Mm,Vm],headerParameters:[Lm],serializer:oh};class gh{client;constructor(e){this.client=e}createOrUpdate(e,t,r){return this.client.sendOperationRequest({skillsetName:e,skillset:t,options:r},vh)}delete(e,t){return this.client.sendOperationRequest({skillsetName:e,options:t},bh)}get(e,t){return this.client.sendOperationRequest({skillsetName:e,options:t},_h)}list(e){return this.client.sendOperationRequest({options:e},wh)}create(e,t){return this.client.sendOperationRequest({skillset:e,options:t},Sh)}}const yh=yl(Tm,!1),vh={path:"/skillsets('{skillsetName}')",httpMethod:"PUT",responses:{200:{bodyMapper:Cd},201:{bodyMapper:Cd},default:{bodyMapper:Nd}},requestBody:Hm,queryParameters:[Bm],urlParameters:[Mm,Wm],headerParameters:[zm,Lm,Dm,Fm,Um],mediaType:"json",serializer:yh},bh={path:"/skillsets('{skillsetName}')",httpMethod:"DELETE",responses:{204:{},404:{},default:{bodyMapper:Nd}},queryParameters:[Bm],urlParameters:[Mm,Wm],headerParameters:[Lm,Dm,Fm],serializer:yh},_h={path:"/skillsets('{skillsetName}')",httpMethod:"GET",responses:{200:{bodyMapper:Cd},default:{bodyMapper:Nd}},queryParameters:[Bm],urlParameters:[Mm,Wm],headerParameters:[Lm],serializer:yh},wh={path:"/skillsets",httpMethod:"GET",responses:{200:{bodyMapper:$d},default:{bodyMapper:Nd}},queryParameters:[Bm,qm],urlParameters:[Mm],headerParameters:[Lm],serializer:yh},Sh={path:"/skillsets",httpMethod:"POST",responses:{201:{bodyMapper:Cd},default:{bodyMapper:Nd}},requestBody:Hm,queryParameters:[Bm],urlParameters:[Mm],headerParameters:[zm,Lm],mediaType:"json",serializer:yh};class Nh{client;constructor(e){this.client=e}createOrUpdate(e,t,r){return this.client.sendOperationRequest({synonymMapName:e,synonymMap:t,options:r},xh)}delete(e,t){return this.client.sendOperationRequest({synonymMapName:e,options:t},Ph)}get(e,t){return this.client.sendOperationRequest({synonymMapName:e,options:t},Eh)}list(e){return this.client.sendOperationRequest({options:e},Ch)}create(e,t){return this.client.sendOperationRequest({synonymMap:e,options:t},Ah)}}const kh=yl(Tm,!1),xh={path:"/synonymmaps('{synonymMapName}')",httpMethod:"PUT",responses:{200:{bodyMapper:Td},201:{bodyMapper:Td},default:{bodyMapper:Nd}},requestBody:Km,queryParameters:[Bm],urlParameters:[Mm,Zm],headerParameters:[zm,Lm,Dm,Fm,Um],mediaType:"json",serializer:kh},Ph={path:"/synonymmaps('{synonymMapName}')",httpMethod:"DELETE",responses:{204:{},404:{},default:{bodyMapper:Nd}},queryParameters:[Bm],urlParameters:[Mm,Zm],headerParameters:[Lm,Dm,Fm],serializer:kh},Eh={path:"/synonymmaps('{synonymMapName}')",httpMethod:"GET",responses:{200:{bodyMapper:Td},default:{bodyMapper:Nd}},queryParameters:[Bm],urlParameters:[Mm,Zm],headerParameters:[Lm],serializer:kh},Ch={path:"/synonymmaps",httpMethod:"GET",responses:{200:{bodyMapper:zd},default:{bodyMapper:Nd}},queryParameters:[Bm,qm],urlParameters:[Mm],headerParameters:[Lm],serializer:kh},Ah={path:"/synonymmaps",httpMethod:"POST",responses:{201:{bodyMapper:Td},default:{bodyMapper:Nd}},requestBody:Km,queryParameters:[Bm],urlParameters:[Mm],headerParameters:[zm,Lm],mediaType:"json",serializer:kh};class Oh{client;constructor(e){this.client=e}create(e,t){return this.client.sendOperationRequest({index:e,options:t},$h)}list(e){return this.client.sendOperationRequest({options:e},Th)}createOrUpdate(e,t,r){return this.client.sendOperationRequest({indexName:e,index:t,options:r},zh)}delete(e,t){return this.client.sendOperationRequest({indexName:e,options:t},Rh)}get(e,t){return this.client.sendOperationRequest({indexName:e,options:t},Lh)}getStatistics(e,t){return this.client.sendOperationRequest({indexName:e,options:t},Mh)}analyze(e,t,r){return this.client.sendOperationRequest({indexName:e,request:t,options:r},jh)}}const Ih=yl(Tm,!1),$h={path:"/indexes",httpMethod:"POST",responses:{201:{bodyMapper:Rd},default:{bodyMapper:Nd}},requestBody:Jm,queryParameters:[Bm],urlParameters:[Mm],headerParameters:[zm,Lm],mediaType:"json",serializer:Ih},Th={path:"/indexes",httpMethod:"GET",responses:{200:{bodyMapper:Hd},default:{bodyMapper:Nd}},queryParameters:[Bm,qm],urlParameters:[Mm],headerParameters:[Lm],serializer:Ih},zh={path:"/indexes('{indexName}')",httpMethod:"PUT",responses:{200:{bodyMapper:Rd},201:{bodyMapper:Rd},default:{bodyMapper:Nd}},requestBody:Jm,queryParameters:[Bm,{parameterPath:["options","allowIndexDowntime"],mapper:{serializedName:"allowIndexDowntime",type:{name:"Boolean"}}}],urlParameters:[Mm,Ym],headerParameters:[zm,Lm,Dm,Fm,Um],mediaType:"json",serializer:Ih},Rh={path:"/indexes('{indexName}')",httpMethod:"DELETE",responses:{204:{},404:{},default:{bodyMapper:Nd}},queryParameters:[Bm],urlParameters:[Mm,Ym],headerParameters:[Lm,Dm,Fm],serializer:Ih},Lh={path:"/indexes('{indexName}')",httpMethod:"GET",responses:{200:{bodyMapper:Rd},default:{bodyMapper:Nd}},queryParameters:[Bm],urlParameters:[Mm,Ym],headerParameters:[Lm],serializer:Ih},Mh={path:"/indexes('{indexName}')/search.stats",httpMethod:"GET",responses:{200:{bodyMapper:Wd},default:{bodyMapper:Nd}},queryParameters:[Bm],urlParameters:[Mm,Ym],headerParameters:[Lm],serializer:Ih},jh={path:"/indexes('{indexName}')/search.analyze",httpMethod:"POST",responses:{200:{bodyMapper:Zd},default:{bodyMapper:Nd}},requestBody:Xm,queryParameters:[Bm],urlParameters:[Mm,Ym],headerParameters:[zm,Lm],mediaType:"json",serializer:Ih};class Dh extends Xl{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 Qm(this),this.indexers=new sh(this),this.skillsets=new gh(this),this.synonymMaps=new Nh(this),this.indexes=new Oh(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},Fh)}dataSources;indexers;skillsets;synonymMaps;indexes}const Fh={path:"/servicestats",httpMethod:"GET",responses:{200:{bodyMapper:Jd},default:{bodyMapper:Nd}},queryParameters:[Bm],urlParameters:[Mm],headerParameters:[Lm],serializer:yl(Tm,!1)};class Uh{serviceVersion=Qu;apiVersion=Qu;endpoint;client;credential;options;constructor(e,t,r={}){this.endpoint=e,this.credential=t,this.options=r;const n={...this.options,loggingOptions:{logger:Lu.info,additionalAllowedHeaderNames:["elapsed-time","Location","OData-MaxVersion","OData-Version","Prefer","throttle-reason"]}};if(this.serviceVersion=this.options.serviceVersion??this.options.apiVersion??Qu,this.apiVersion=this.serviceVersion,this.client=new Dh(this.endpoint,this.serviceVersion,n),Is(t)){const e=this.options.audience?`${this.options.audience}/.default`:`${zs.AzurePublicCloud}/.default`;this.client.pipeline.addPolicy(sl({credential:t,scopes:e}))}else this.client.pipeline.addPolicy(Du(t));this.client.pipeline.addPolicy(Mu("minimal"))}async*listIndexesPage(e={}){const{span:t,updatedOptions:r}=vd("SearchIndexClient-listIndexesPage",e);try{const e=(await this.client.indexes.list(r)).indexes.map(ud);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}=vd("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}=vd("SearchIndexClient-listSynonymMaps",e);try{return(await this.client.synonymMaps.list(r)).synonymMaps.map(fd)}catch(e){throw t.setStatus({status:"error",error:e.message}),e}finally{t.end()}}async listSynonymMapsNames(e={}){const{span:t,updatedOptions:r}=vd("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}=vd("SearchIndexClient-getIndex",t);try{return ud(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}=vd("SearchIndexClient-getSynonymMaps",t);try{return fd(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}=vd("SearchIndexClient-createIndex",t);try{return ud(await this.client.indexes.create(hd(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}=vd("SearchIndexClient-createSynonymMaps",t);try{return fd(await this.client.synonymMaps.create(gd(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}=vd("SearchIndexClient-createOrUpdateIndex",t);try{const r=t.onlyIfUnchanged?e.etag:void 0;return ud(await this.client.indexes.createOrUpdate(e.name,hd(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}=vd("SearchIndexClient-createOrUpdateSynonymMap",t);try{const r=t.onlyIfUnchanged?e.etag:void 0;return fd(await this.client.synonymMaps.createOrUpdate(e.name,gd(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}=vd("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}=vd("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}=vd("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}=vd("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}=vd("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 Bh{client;autoFlush;flushWindowInMs;throttlingDelayInMs;maxRetriesPerAction;maxThrottlingDelayInMs;initialBatchActionCount;batchObject;cleanupTimer;emitter=new we;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 Ts,this.autoFlush){const e=setInterval(()=>this.flush(),this.flushWindowInMs);e?.unref(),this.cleanupTimer=()=>{clearInterval(e)}}}async uploadDocuments(e,t={}){const{span:r,updatedOptions:n}=vd("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}=vd("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}=vd("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}=vd("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}=vd("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 Ts;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 Ts(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 Es(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 qh,Vh,Gh=Object.defineProperty,Hh=(e,t)=>{for(var r in t)Gh(e,r,{get:t[r],enumerable:!0})};function Wh(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 Kh(e){return Wh(e)&&"url"===e.source_type&&"url"in e&&"string"==typeof e.url}function Zh(e){return Wh(e)&&"base64"===e.source_type&&"data"in e&&"string"==typeof e.data}function Jh(e){return Wh(e)&&"text"===e.source_type&&"text"in e&&"string"==typeof e.text}function Yh(e){return Wh(e)&&"id"===e.source_type&&"id"in e&&"string"==typeof e.id}function Xh(e){if(Wh(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 Qh(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 ef({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 tf(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 rf(e){return"object"==typeof e&&null!==e&&"type"in e&&"content"in e&&("string"==typeof e.content||Array.isArray(e.content))}var nf,af=(Vh||(Vh=1,qh=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()}),qh),sf=Zn(af),of={exports:{}};function cf(e,t){return t?.[e]||sf(e)}function lf(e,t,r){const n={};for(const a in e)Object.hasOwn(e,a)&&(n[t(a,r)]=e[a]);return n}!function(){if(nf)return of.exports;nf=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 uf(e){return Array.isArray(e)?[...e]:{...e}}function df(e,t){const r=uf(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]=uf(i[e]),i=i[e]}void 0!==i[t]&&(i[t]={lc:1,type:"secret",id:[n]})}return r}function pf(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}Hh({},{Serializable:()=>mf,get_lc_unique_name:()=>pf});var mf=class e{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,pf(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:lf(Object.keys(r).length?df(n,r):n,cf,t)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function hf(e,t){return ff(e)&&e.type===t}function ff(e){return"object"==typeof e&&null!==e}function gf(e){return Array.isArray(e)}function yf(e){return"string"==typeof e}function vf(e){return"number"==typeof e}function bf(e){return e instanceof Uint8Array}function _f(e){try{return JSON.parse(e)}catch{return}}const wf=e=>e();function Sf(e){if("char_location"===e.type&&yf(e.document_title)&&vf(e.start_char_index)&&vf(e.end_char_index)&&yf(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&&yf(e.document_title)&&vf(e.start_page_number)&&vf(e.end_page_number)&&yf(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&&yf(e.document_title)&&vf(e.start_block_index)&&vf(e.end_block_index)&&yf(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&&yf(e.url)&&yf(e.title)&&yf(e.encrypted_index)&&yf(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&&yf(e.source)&&yf(e.title)&&vf(e.start_block_index)&&vf(e.end_block_index)&&yf(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 Nf(e){if(hf(e,"document")&&ff(e.source)&&"type"in e.source){if("base64"===e.source.type&&yf(e.source.media_type)&&yf(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if("url"===e.source.type&&yf(e.source.url))return{type:"file",url:e.source.url};if("file"===e.source.type&&yf(e.source.file_id))return{type:"file",fileId:e.source.file_id};if("text"===e.source.type&&yf(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(hf(e,"image")&&ff(e.source)&&"type"in e.source){if("base64"===e.source.type&&yf(e.source.media_type)&&yf(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if("url"===e.source.type&&yf(e.source.url))return{type:"image",url:e.source.url};if("file"===e.source.type&&yf(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function kf(e){return Array.from(function*(){for(const t of e){const e=Nf(t);e?yield e:yield t}}())}function xf(e){return Array.from(function*(){const t="string"==typeof e.content?[{type:"text",text:e.content}]:e.content;for(const r of t){if(hf(r,"text")&&yf(r.text)){const{text:e,citations:t,...n}=r;if(gf(t)&&t.length){const r=t.reduce((e,t)=>{const r=Sf(t);return r?[...e,r]:e},[]);yield{...n,type:"text",text:e,annotations:r};continue}yield{...n,type:"text",text:e};continue}if(hf(r,"thinking")&&yf(r.thinking)){const{thinking:e,signature:t,...n}=r;yield{...n,type:"reasoning",reasoning:e,signature:t};continue}if(hf(r,"redacted_thinking"))yield{type:"non_standard",value:r};else if(hf(r,"tool_use")&&yf(r.name)&&yf(r.id))yield{type:"tool_call",id:r.id,name:r.name,args:r.input};else{if(hf(r,"input_json_delta")){if(Ef(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(hf(r,"server_tool_use")&&yf(r.name)&&yf(r.id)){const{name:e,id:t}=r;if("web_search"===e){const e=wf(()=>{if("string"==typeof r.input)return r.input;if(ff(r.input)&&yf(r.input.query))return r.input.query;if(yf(r.partial_json)){const e=_f(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=wf(()=>{if("string"==typeof r.input)return r.input;if(ff(r.input)&&yf(r.input.code))return r.input.code;if(yf(r.partial_json)){const e=_f(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(hf(r,"web_search_tool_result")&&yf(r.tool_use_id)&&gf(r.content)){const{content:e,tool_use_id:t}=r,n=e.reduce((e,t)=>hf(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(hf(r,"code_execution_tool_result")&&yf(r.tool_use_id)&&ff(r.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}if(hf(r,"mcp_tool_use")){yield{id:r.id,type:"server_tool_call",name:"mcp_tool_use",args:r.input};continue}if(hf(r,"mcp_tool_result")&&yf(r.tool_use_id)&&ff(r.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}if(hf(r,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:r.input};continue}if(hf(r,"search_result")){yield{id:r.id,type:"non_standard",value:r};continue}if(hf(r,"tool_result")){yield{id:r.id,type:"non_standard",value:r};continue}{const e=Nf(r);if(e){yield e;continue}}}yield{type:"non_standard",value:r}}}}())}const Pf={translateContent:xf,translateContentChunk:xf};function Ef(e){return"function"==typeof e?._getType&&"function"==typeof e.concat&&"ai"===e._getType()}function Cf(e){return Kh(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:Zh(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:Yh(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function Af(e){return e.map(Cf)}function Of(e){return!(!hf(e,"image_url")||!ff(e.image_url))||(!(!hf(e,"input_audio")||!ff(e.input_audio))||!(!hf(e,"file")||!ff(e.file)))}function If(e){if(hf(e,"image_url")&&ff(e.image_url)&&yf(e.image_url.url)){const t=ef({dataUrl:e.image_url.url});return t?{type:"image",mimeType:t.mime_type,data:t.data}:{type:"image",url:e.image_url.url}}if(hf(e,"input_audio")&&ff(e.input_audio)&&yf(e.input_audio.data)&&yf(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(hf(e,"file")&&ff(e.file)&&yf(e.file.data)){const t=ef({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if(yf(e.file.file_id))return{type:"file",fileId:e.file.file_id}}return e}function $f(e){const t=[];for(const r of e)Of(r)?t.push(If(r)):t.push(r);return t}function Tf(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 zf(e){return Array.from(function*(){if(ff(e.additional_kwargs?.reasoning)&&gf(e.additional_kwargs.reasoning.summary)){const t=e.additional_kwargs.reasoning.summary.reduce((e,t)=>ff(t)&&yf(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(hf(e,"text")){const{text:t,annotations:r,...n}=e;Array.isArray(r)?yield{...n,type:"text",text:String(t),annotations:r.map(Tf)}: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(ff(e.additional_kwargs)&&gf(e.additional_kwargs.tool_outputs))for(const t of e.additional_kwargs.tool_outputs)if(hf(t,"web_search_call"))yield{id:t.id,type:"server_tool_call",name:"web_search",args:{query:t.query}};else if(hf(t,"file_search_call"))yield{id:t.id,type:"server_tool_call",name:"file_search",args:{query:t.query}};else if(hf(t,"computer_call"))yield{type:"non_standard",value:t};else if(hf(t,"code_interpreter_call")){if(yf(t.code)&&(yield{id:t.id,type:"server_tool_call",name:"code_interpreter",args:{code:t.code}}),gf(t.outputs)){const e=wf(()=>{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(hf(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 hf(t,"mcp_call")?yield{id:t.id,type:"server_tool_call",name:"mcp_call",args:t.input}:hf(t,"mcp_list_tools")?yield{id:t.id,type:"server_tool_call",name:"mcp_list_tools",args:t.input}:(hf(t,"mcp_approval_request")||hf(t,"image_generation_call")||ff(t))&&(yield{type:"non_standard",value:t})}())}const Rf={translateContent:e=>"string"==typeof e.content?function(e){const t=[];"string"==typeof e.content?t.push({type:"text",text:e.content}):t.push(...$f(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):zf(e),translateContentChunk:e=>"string"==typeof e.content?function(e){const t=[];"string"==typeof e.content?t.push({type:"text",text:e.content}):t.push(...$f(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*zf(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 Lf(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 Mf=Symbol.for("langchain.message");function jf(e,t){return"string"==typeof e?""===e?t:"string"==typeof t?e+t:Array.isArray(t)&&t.some(e=>Wh(e))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t]:Array.isArray(t)?qf(e,t)??[...e,...t]:""===t?e:Array.isArray(e)&&e.some(e=>Wh(e))?[...e,{type:"file",source_type:"text",text:t}]:[...e,{type:"text",text:t}]}function Df(e,t){return"error"===e||"error"===t?"error":"success"}var Ff=class extends mf{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[Mf]=!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[Af,$f,kf].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&&Mf in e&&!0===e[Mf]&&rf(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 Lf(this,e)}};function Uf(e){return Array.isArray(e)&&e.every(e=>"number"==typeof e.index)}function Bf(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]=qf(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]=Bf(r[e],n)}return r}function qf(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]=Bf(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 Vf(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 qf(e,t);if("object"==typeof e&&"object"==typeof t)return Bf(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 Gf=class extends Ff{static isInstance(e){return super.isInstance(e)&&"concat"in e&&"function"==typeof e.concat}};function Hf(e){return"string"==typeof e.role}function Wf(e){return"function"==typeof e?._getType}function Kf(e){return Wf(e)&&"function"==typeof e.concat}function Zf(e,t){return Bf(e??{},t??{})}function Jf(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 Yf(e,t){const r={...Jf(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 Xf(e,t){const r={...Jf(e,t)};return void 0===e?.reasoning&&void 0===t?.reasoning||(r.reasoning=(e?.reasoning??0)+(t?.reasoning??0)),r}function Qf(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:Yf(e?.input_token_details,t?.input_token_details),output_token_details:Xf(e?.output_token_details,t?.output_token_details)}}function eg(e){return null!=e&&"object"==typeof e&&"lc_direct_tool_output"in e&&!0===e.lc_direct_tool_output}Hh({},{ToolMessage:()=>tg,ToolMessageChunk:()=>rg,defaultToolCallParser:()=>ng,isDirectToolOutput:()=>eg,isToolMessage:()=>ag,isToolMessageChunk:()=>ig});var tg=class extends Ff{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}}},rg=class extends Gf{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:jf(this.content,e.content),additional_kwargs:Bf(this.additional_kwargs,e.additional_kwargs),response_metadata:Bf(this.response_metadata,e.response_metadata),artifact:Vf(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:Df(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function ng(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 ag(e){return"object"==typeof e&&null!==e&&"getType"in e&&"function"==typeof e.getType&&"tool"===e.getType()}function ig(e){return"tool"===e._getType()}function sg(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 cg(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 lg(e){if(ff(e.document)&&ff(e.document.source)){const t=cg(ff(e.document)&&yf(e.document.format)?e.document.format:"");if(ff(e.document.source)){if(ff(e.document.source.s3Location)&&yf(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(yf(e.document.source.text))return{type:"file",mimeType:t,data:Buffer.from(e.document.source.text).toString("base64")};if(gf(e.document.source.content)){return{type:"file",mimeType:t,data:e.document.source.content.reduce((e,t)=>ff(t)&&yf(t.text)?e+t.text:e,"")}}}}return{type:"non_standard",value:e}}function ug(e){if(hf(e,"image")&&ff(e.image)){const t=cg(ff(e.image)&&yf(e.image.format)?e.image.format:"");if(ff(e.image.source)){if(ff(e.image.source.s3Location)&&yf(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 dg(e){if(hf(e,"video")&&ff(e.video)){const t=cg(ff(e.video)&&yf(e.video.format)?e.video.format:"");if(ff(e.video.source)){if(ff(e.video.source.s3Location)&&yf(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 pg(e){return Array.from(function*(){const t="string"==typeof e.content?[{type:"text",text:e.content}]:e.content;for(const e of t)if(hf(e,"cache_point"))yield{type:"non_standard",value:e};else{if(hf(e,"citations_content")&&ff(e.citationsContent)){const t=gf(e.citationsContent.content)?e.citationsContent.content.reduce((e,t)=>ff(t)&&yf(t.text)?e+t.text:e,""):"",r=gf(e.citationsContent.citations)?e.citationsContent.citations.reduce((e,t)=>{if(ff(t)){const r=gf(t.sourceContent)?t.sourceContent.reduce((e,t)=>ff(t)&&yf(t.text)?e+t.text:e,""):"",n=wf(()=>{if(ff(t.location)){const e=t.location.documentChar||t.location.documentPage||t.location.documentChunk;if(ff(e))return{source:vf(e.documentIndex)?e.documentIndex.toString():void 0,startIndex:vf(e.start)?e.start:void 0,endIndex:vf(e.end)?e.end:void 0}}return{}});e.push({type:"citation",citedText:r,...n})}return e},[]):[];yield{type:"text",text:t,annotations:r};continue}hf(e,"document")&&ff(e.document)?yield lg(e):hf(e,"guard_content")?yield{type:"non_standard",value:e}:hf(e,"image")&&ff(e.image)?yield ug(e):hf(e,"reasoning_content")&&yf(e.reasoningText)?yield{type:"reasoning",reasoning:e.reasoningText}:hf(e,"text")&&yf(e.text)?yield{type:"text",text:e.text}:hf(e,"tool_result")?yield{type:"non_standard",value:e}:hf(e,"tool_call")||(hf(e,"video")&&ff(e.video)?yield dg(e):yield{type:"non_standard",value:e})}}())}const mg={translateContent:pg,translateContentChunk:pg};function hg(e){return Array.from(function*(){const t="string"==typeof e.content?[{type:"text",text:e.content}]:e.content;for(const r of t)hf(r,"text")&&yf(r.text)?yield{type:"text",text:r.text}:hf(r,"inlineData")&&ff(r.inlineData)&&yf(r.inlineData.mimeType)&&yf(r.inlineData.data)?yield{type:"file",mimeType:r.inlineData.mimeType,data:r.inlineData.data}:hf(r,"functionCall")&&ff(r.functionCall)&&yf(r.functionCall.name)&&ff(r.functionCall.args)?yield{type:"tool_call",id:e.id,name:r.functionCall.name,args:r.functionCall.args}:hf(r,"functionResponse")?yield{type:"non_standard",value:r}:hf(r,"fileData")&&ff(r.fileData)&&yf(r.fileData.mimeType)&&yf(r.fileData.fileUri)?yield{type:"file",mimeType:r.fileData.mimeType,fileId:r.fileData.fileUri}:(hf(r,"executableCode")||hf(r,"codeExecutionResult"),yield{type:"non_standard",value:r})}())}const fg={translateContent:hg,translateContentChunk:hg};function gg(e){return Array.from(function*(){const t="string"==typeof e.content?[{type:"text",text:e.content}]:e.content;for(const r of t){if(hf(r,"reasoning")&&yf(r.reasoning)){const n=wf(()=>{const n=t.indexOf(r);if(gf(e.additional_kwargs?.signatures)&&n>=0)return e.additional_kwargs.signatures.at(n)});yf(n)?yield{type:"reasoning",reasoning:r.reasoning,signature:n}:yield{type:"reasoning",reasoning:r.reasoning};continue}if(hf(r,"text")&&yf(r.text))yield{type:"text",text:r.text};else if(hf(r,"image_url")){if(yf(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 hf(r,"media")&&yf(r.mimeType)&&yf(r.data)?yield{type:"file",mimeType:r.mimeType,data:r.data}:yield{type:"non_standard",value:r}}}())}const yg={translateContent:gg,translateContentChunk:gg};function vg(e){return globalThis.lc_block_translators_registry.get(e)}globalThis.lc_block_translators_registry??=new Map([["anthropic",Pf],["bedrock-converse",mg],["google-genai",fg],["google-vertexai",yg],["openai",Rf]]);var bg=class extends Ff{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]=ng(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=vg(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 _g(e){return"ai"===e._getType()}function wg(e){return"ai"===e._getType()}var Sg=class extends Gf{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=vg(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:jf(this.content,e.content),additional_kwargs:Bf(this.additional_kwargs,e.additional_kwargs),response_metadata:Zf(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=qf(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=Qf(this.usage_metadata,e.usage_metadata));return new(0,this.constructor)(t)}static isInstance(e){return super.isInstance(e)&&"ai"===e.type}},Ng=class e extends Ff{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}}},kg=class extends Gf{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:jf(this.content,e.content),additional_kwargs:Bf(this.additional_kwargs,e.additional_kwargs),response_metadata:Bf(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 xg(e){return"generic"===e._getType()}function Pg(e){return"generic"===e._getType()}var Eg=class extends Ff{static lc_name(){return"FunctionMessage"}type="function";name;constructor(e){super(e),this.name=e.name}},Cg=class extends Gf{static lc_name(){return"FunctionMessageChunk"}type="function";concat(e){return new(0,this.constructor)({content:jf(this.content,e.content),additional_kwargs:Bf(this.additional_kwargs,e.additional_kwargs),response_metadata:Bf(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}};function Ag(e){return"function"===e._getType()}function Og(e){return"function"===e._getType()}var Ig=class extends Ff{static lc_name(){return"HumanMessage"}type="human";constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&"human"===e.type}},$g=class extends Gf{static lc_name(){return"HumanMessageChunk"}type="human";constructor(e){super(e)}concat(e){return new(0,this.constructor)({content:jf(this.content,e.content),additional_kwargs:Bf(this.additional_kwargs,e.additional_kwargs),response_metadata:Bf(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&"human"===e.type}};function Tg(e){return"human"===e.getType()}function zg(e){return"human"===e.getType()}var Rg=class extends Ff{static lc_name(){return"SystemMessage"}type="system";constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&"system"===e.type}},Lg=class extends Gf{static lc_name(){return"SystemMessageChunk"}type="system";constructor(e){super(e)}concat(e){return new(0,this.constructor)({content:jf(this.content,e.content),additional_kwargs:Bf(this.additional_kwargs,e.additional_kwargs),response_metadata:Bf(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&"system"===e.type}};function Mg(e){return"system"===e._getType()}function jg(e){return"system"===e._getType()}var Dg=class extends Ff{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 Fg(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 Ug(e){return!(!e||"object"!=typeof e||!("type"in e)||"tool_call"!==e.type)}var Bg=class extends Error{output;constructor(e,t){super(e),this.output=t}};const qg=e=>e();function Vg(e){return Ug(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 Gg(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 Ig(r);if("ai"===t||"assistant"===t){const{tool_calls:e,...t}=r;if(!Array.isArray(e))return new bg(r);const n=e.map(Vg);return new bg({...t,tool_calls:n})}if("system"===t)return new Rg(r);if("developer"===t)return new Rg({...r,additional_kwargs:{...r.additional_kwargs,__openai_role__:"developer"}});if("tool"===t&&"tool_call_id"in r)return new tg({...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 Dg({...r,id:r.id});throw Fg(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 Hg(e){if("string"==typeof e)return new Ig(e);if(Wf(e))return e;if(Array.isArray(e)){const[t,r]=e;return Gg({type:t,content:r})}if(Hf(e)){const{role:t,...r}=e;return Gg({...r,type:t})}return Gg(e)}function Wg(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 Kg(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 Ig(t.data);case"ai":return new bg(t.data);case"system":return new Rg(t.data);case"function":if(void 0===t.data.name)throw new Error("Name must be defined for function messages");return new Eg(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 tg(t.data);case"generic":if(void 0===t.data.role)throw new Error("Role must be defined for chat messages");return new Ng(t.data);default:throw new Error(`Got unexpected type: ${t.type}`)}}function Zg(e){return e.map(Kg)}function Jg(e){return e.map(e=>e.toDict())}function Yg(e){const t=e._getType();if("human"===t)return new $g({...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 Sg({...t})}if("system"===t)return new Lg({...e});if("function"===t)return new Cg({...e});if(Ng.isInstance(e))return new kg({...e});throw new Error("Unknown message type.")}const Xg=Symbol.for("ls:tracing_async_local_storage"),Qg=Symbol.for("lc:context_variables"),ey=()=>globalThis[Xg];Hh({},{getEnv:()=>sy,getEnvironmentVariable:()=>ly,getRuntimeEnvironment:()=>cy,isBrowser:()=>ty,isDeno:()=>ay,isJsDom:()=>ny,isNode:()=>iy,isWebWorker:()=>ry});const ty=()=>"undefined"!=typeof window&&void 0!==window.document,ry=()=>"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name,ny=()=>"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&navigator.userAgent.includes("jsdom"),ay=()=>"undefined"!=typeof Deno,iy=()=>"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node&&!ay(),sy=()=>{let e;return e=ty()?"browser":iy()?"node":ry()?"webworker":ny()?"jsdom":ay()?"deno":"other",e};let oy;function cy(){if(void 0===oy){const e=sy();oy={library:"langchain-js",runtime:e}}return oy}function ly(e){try{return"undefined"!=typeof process?process.env?.[e]:ay()?Deno?.env.get(e):void 0}catch{return}}var uy=/^(?:[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 dy(e){return"string"==typeof e&&uy.test(e)}for(var py,my=[],hy=0;hy<256;++hy)my.push((hy+256).toString(16).slice(1));function fy(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 gy=new Uint8Array(16);function yy(){if(!py&&!(py="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 py(gy)}var vy={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function by(e,t,r){if(vy.randomUUID&&!e)return vy.randomUUID();var n=(e=e||{}).random||(e.rng||yy)();return n[6]=15&n[6]|64,n[8]=63&n[8]|128,fy(n)}function _y(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 wy(e,t){return e<<t|e>>>32-t}var Sy=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(!dy(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 fy(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]=wy(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=wy(f,5)+_y(w,g,y,v)+b+t[w]+p[_]>>>0;b=v,v=y,y=wy(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]]});Hh({},{BaseCallbackHandler:()=>xy,callbackHandlerPrefersStreaming:()=>ky,isBaseCallbackHandler:()=>Py});var Ny=class{};function ky(e){return"lc_prefer_streaming"in e&&e.lc_prefer_streaming}var xy=class extends Ny{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,pf(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers="false"===ly("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 xy{name=by();constructor(){super(),Object.assign(this,e)}}}};const Py=e=>{const t=e;return void 0!==t&&"function"==typeof t.copy&&"string"==typeof t.name&&"boolean"==typeof t.awaitHandlers},Ey="gen_ai.request.model",Cy="gen_ai.usage.input_tokens",Ay="gen_ai.usage.output_tokens",Oy="gen_ai.usage.total_tokens",Iy="langsmith.span.tags",$y=(...e)=>fetch(...e),Ty=Symbol.for("ls:fetch_implementation"),zy=e=>async(...t)=>{if(e||"true"===Gy("DEBUG")){const[e,r]=t;console.log(`→ ${r?.method||"GET"} ${e}`)}const r=await(globalThis[Ty]??$y)(...t);return(e||"true"===Gy("DEBUG"))&&console.log(`← ${r.status} ${r.statusText} ${r.url}`),r},Ry=()=>Gy("PROJECT")??Vy("LANGCHAIN_SESSION")??"default",Ly="0.3.74";let My;const jy=()=>"undefined"!=typeof Deno,Dy=()=>My||(My="undefined"!=typeof Bun?"bun":"undefined"!=typeof window&&void 0!==window.document?"browser":"undefined"==typeof process||void 0===process.versions||void 0===process.versions.node||jy()?"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name?"webworker":"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&navigator.userAgent.includes("jsdom")?"jsdom":jy()?"deno":"other":"node",My);let Fy,Uy;function By(){if(void 0===Fy){const e=Dy(),t=function(){if(void 0!==Uy)return Uy;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=Vy(r);void 0!==e&&(t[r]=e)}return Uy=t,t}();Fy={library:"langsmith",runtime:e,sdk:"langsmith-js",sdk_version:Ly,...t}}return Fy}function qy(){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 Vy(e){try{return"undefined"!=typeof process?process.env?.[e]:void 0}catch(e){return}}function Gy(e){return Vy(`LANGSMITH_${e}`)||Vy(`LANGCHAIN_${e}`)}function Hy(){return"true"===Vy("OTEL_ENABLED")||"true"===Gy("OTEL_ENABLED")}class Wy{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...t){let r;if(!this.hasWarned&&Hy()&&(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 Ky=Symbol.for("ls:otel_trace"),Zy=Symbol.for("ls:otel_context"),Jy=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),Yy=new class{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new Wy})}getTracer(e,t){return this.mockTracer}getActiveSpan(){}setSpan(e,t){return e}getSpan(e){}setSpanContext(e,t){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},Xy=new class{active(){return{}}with(e,t){return t()}};const Qy=new class{getTraceInstance(){return globalThis[Ky]??Yy}getContextInstance(){return globalThis[Zy]??Xy}initializeGlobalInstances(e){void 0===globalThis[Ky]&&(globalThis[Ky]=e.trace),void 0===globalThis[Zy]&&(globalThis[Zy]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[Jy]=e}getDefaultOTLPTracerComponents(){return globalThis[Jy]??void 0}};function ev(){return Qy.getTraceInstance()}const tv={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};class rv{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&&ev().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",tv[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(Ey,a),"prompt_tokens"in t&&"number"==typeof t.prompt_tokens&&e.setAttribute(Cy,t.prompt_tokens),"completion_tokens"in t&&"number"==typeof t.completion_tokens&&e.setAttribute(Ay,t.completion_tokens),"total_tokens"in t&&"number"==typeof t.total_tokens&&e.setAttribute(Oy,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(Iy,s.join(", ")):s&&e.setAttribute(Iy,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(Ey,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(Cy,n[0]),e.setAttribute(Ay,n[1]),e.setAttribute(Oy,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 nv,av,iv,sv,ov,cv,lv={exports:{}},uv={};function dv(){return iv||(iv=1,e=uv,t=function(){if(av)return nv;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 av=1,nv=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},nv}(),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}}),uv;var e,t}function pv(){return ov?sv:(ov=1,sv=dv())}var mv,hv=function(){if(cv)return lv.exports;cv=1;const e=pv(),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 lv.exports=n,lv.exports.default=n,lv.exports.AbortError=r,lv.exports}(),fv=Zn(hv),gv={},yv={exports:{}};var vv,bv,_v,wv={exports:{}};function Sv(){return bv||(bv=1,vv=(e,t)=>(t=t||(()=>{}),e.then(e=>new Promise(e=>{e(t())}).then(()=>e),e=>new Promise(e=>{e(t())}).then(()=>{throw e})))),vv}var Nv,kv,xv,Pv={},Ev={};function Cv(){if(kv)return Pv;kv=1,Object.defineProperty(Pv,"__esModule",{value:!0});const e=(Nv||(Nv=1,Object.defineProperty(Ev,"__esModule",{value:!0}),Ev.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}),Ev);return Pv.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}},Pv}var Av=function(){if(xv)return gv;xv=1,Object.defineProperty(gv,"__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}(yv)),yv.exports),t=function(){if(_v)return wv.exports;_v=1;const e=Sv();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 wv.exports=r,wv.exports.default=r,wv.exports.TimeoutError=t,wv.exports}(),r=Cv(),n=()=>{},a=new t.TimeoutError;return gv.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}},gv}(),Ov=Zn(Av);const Iv=[429,500,502,503,504];let $v=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 Ov?new Ov.default({concurrency:this.maxConcurrency}):new Ov({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){const r=this.onFailedResponseHook;return this.queue.add(()=>fv(()=>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&&!Iv.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 Tv(e){return"function"==typeof e?._getType}function zv(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 Rv=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Lv(e,t){if(!Rv.test(e)){throw new Error(void 0!==t?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`)}return e}const Mv={};function jv(e){Mv[e]||(console.warn(e),Mv[e]=!0)}function Dv(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 Fv 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 Uv(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 Fv(a);const i=new Error(a);throw i.status=e.status,i}const Bv="ERR_CONFLICTING_ENDPOINTS";class qv 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:Bv}),this.name="ConflictingEndpointsError"}}var Vv="[...]",Gv={result:"[Circular]"},Hv=[],Wv=[];const Kv=new TextEncoder;function Zv(e){return Kv.encode(e)}function Jv(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 Yv(e,t,r,n,a){try{return Zv(JSON.stringify(e,function(e,t){return Jv(t)},n))}catch(i){if(!i.message?.includes("Converting circular structure to JSON"))return console.warn("[WARNING]: LangSmith received unserializable value."+(t?`\nContext: ${t}`:"")),Zv("[Unserializable]");let s;"true"!==Gy("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}),Qv(e,"",0,[],void 0,0,a);try{s=0===Wv.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(Wv.length>0)for(var n=0;n<Wv.length;n++){var a=Wv[n];if(a[1]===t&&a[0]===r){r=a[2],Wv.splice(n,1);break}}return e.call(this,t,r)}}(r),n)}catch(e){return Zv("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Hv.length;){const e=Hv.pop();4===e.length?Object.defineProperty(e[0],e[1],e[3]):e[0][e[1]]=e[2]}}return Zv(s)}}function Xv(e,t,r,n){var a=Object.getOwnPropertyDescriptor(n,r);void 0!==a.get?a.configurable?(Object.defineProperty(n,r,{value:e}),Hv.push([n,r,t,a])):Wv.push([t,r,e]):(n[r]=e,Hv.push([n,r,t]))}function Qv(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 Xv(Gv,e,t,a);if(void 0!==s.depthLimit&&i>s.depthLimit)return void Xv(Vv,e,t,a);if(void 0!==s.edgesLimit&&r+1>s.edgesLimit)return void Xv(Vv,e,t,a);if(n.push(e),Array.isArray(e))for(o=0;o<e.length;o++)Qv(e[o],o,o,n,e,i,s);else{e=Jv(e);var c=Object.keys(e);for(o=0;o<c.length;o++){var l=c[o];Qv(e[l],l,o,n,e,i,s)}}n.pop()}}function eb(e,t){const r=By(),n=t??qy(),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 tb(e){if(void 0!==e)return e.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const rb=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 nb(e){return"number"==typeof e?Number(e.toFixed(4)):e}class ab{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=Yv(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 ib="https://api.smith.langchain.com";class sb{get _fetch(){return this.fetchImplementation||zy(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 ab}),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"===Vy("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"===Vy("LANGSMITH_DEBUG")});const t=sb.getDefaultClientConfig();if(this.tracingSampleRate=(e=>{const t=e?.toString()??Gy("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=tb(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=tb(e.apiKey??t.apiKey),this.webUrl=tb(e.webUrl??t.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=tb(e.workspaceId??Gy("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new $v({...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 $v({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:rb,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,Hy()&&(this.langSmithToOTELTranslator=new rv),this.cachedLSEnvVarsForMetadata=qy()}static getDefaultClientConfig(){const e=Gy("API_KEY");return{apiUrl:Gy("ENDPOINT")??ib,apiKey:e,webUrl:void 0,hideInputs:"true"===Gy("HIDE_INPUTS"),hideOutputs:"true"===Gy("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/${Ly}`};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 Uv(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 Uv(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 Uv(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=eb(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 Uv(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=ev(),t=Qy.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=eb(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=Yv(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 Uv(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(Yv(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 Uv(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=Yv(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=Yv(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[Ty];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 Uv(s,"Failed to send multipart request",!0),s});try{let e,n=!1;a||this.multipartStreamingDisabled||"bun"===Dy()?e=await o(i):(n=!0,e=await o(s)),this.multipartStreamingDisabled&&!n||422!==e.status||(r?.apiUrl??this.apiUrl)===ib||(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){Lv(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=Yv(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 Uv(t,"update run",!0),t})}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){Lv(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:Gy("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")&&jv("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 Uv(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 Uv(e,"get run stats"),e});return await _.json()}async shareRun(e,{shareId:t}={}){const r={run_id:e,share_token:t||by()};Lv(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 Uv(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){Lv(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 Uv(t,"unshare run",!0),t})}async readRunSharedLink(e){Lv(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 Uv(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);Lv(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 Uv(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}Lv(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 Uv(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};Lv(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 Uv(t,"share dataset"),t}),i=await a.json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){Lv(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 Uv(t,"unshare dataset",!0),t})}async readSharedDataset(e){Lv(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 Uv(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 Uv(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 Uv(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 Uv(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)Lv(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 Uv(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)Lv(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,Lv(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 Uv(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 Uv(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 Uv(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)Lv(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;Lv(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 Uv(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;Lv(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 Uv(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");Lv(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 Uv(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}Lv(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 Uv(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),Lv(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 Uv(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=>Tv(e)?zv(e):e),a=Tv(t)?zv(t):t;return this.createExample({input:n},{output:a},r)}async readExample(e){Lv(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){Lv(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 Uv(e,`delete ${t}`,!0),e})}async updateExample(e,t){let r,n,a;if(r=t?e:e.id,Lv(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(Lv(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 Uv(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;Lv(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;Lv(i);const s={split_name:r,examples:n.map(e=>(Lv(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 Uv(e,"update dataset splits",!0),e})}async evaluateRun(e,t,{sourceInfo:r,loadChildRuns:n,referenceExample:a}={loadChildRuns:!1}){let i;if(jv("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&&Lv(m.metadata.__run.run_id);const h={id:l??by(),run_id:e,key:t,score:nb(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 Uv(e,"create feedback",!0),e}),h}async updateFeedback(e,{score:t,value:r,correction:n,comment:a}){const i={};null!=t&&(i.score=nb(t)),null!=r&&(i.value=r),null!=n&&(i.correction=n),null!=a&&(i.comment=a),Lv(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 Uv(t,"update feedback",!0),t})}async readFeedback(e){Lv(e);const t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){Lv(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 Uv(e,`delete ${t}`,!0),e})}async*listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:r}={}){const n=new URLSearchParams;if(e)for(const t of e)Lv(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 Uv(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 Uv(e,"create comparative experiment"),e})).json()}async*listPresignedFeedbackTokens(e){Lv(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)=>{Lv(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 Uv(e,"create annotation queue"),e})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/annotation-queues/${Lv(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Uv(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/${Lv(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await Uv(t,"update annotation queue",!0),t})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/annotation-queues/${Lv(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Uv(t,"delete annotation queue",!0),t})}async addRunsToAnnotationQueue(e,t){const r=JSON.stringify(t.map((e,t)=>Lv(e,`runIds[${t}]`).toString()));await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/annotation-queues/${Lv(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await Uv(t,"add runs to annotation queue",!0),t})}async getRunFromAnnotationQueue(e,t){const r=`/annotation-queues/${Lv(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 Uv(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/${Lv(e,"queueId")}/runs/${Lv(t,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Uv(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/${Lv(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Uv(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 Uv(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]=Dv(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 Uv(e,(t?"like":"unlike")+" prompt"),e})).json()}async _getPromptUrl(e){const[t,r,n]=Dv(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]=Dv(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 Uv(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]=Dv(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 Uv(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]=Dv(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 Uv(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=Yv({...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=Yv(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=Yv(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=Yv(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 Uv(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=Yv({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=Yv(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=Yv(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 Uv(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]=Dv(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 Uv(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]=Dv(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 Uv(e,"delete prompt"),e})).json()}async pullPromptCommit(e,t){const[r,n,a]=Dv(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 Uv(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 sb({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 Lv(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(Qy.getDefaultOTLPTracerComponents()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush())}}function ob(e){return"dataset_id"in e||"dataset_name"in e}const cb=Symbol.for("lc:context_variables");function lb(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 ub{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 ub(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 db{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=db.getDefaultConfig(),{metadata:n,...a}=e,i=a.client??db.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=Vy("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&&Gy("ENDPOINT"))throw new qv}(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===Bv)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}=lb(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:Ry(),child_runs:[],api_url:Vy("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:Vy("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return db.sharedClient||(db.sharedClient=new sb),db.sharedClient}createChild(e){const t=this.child_execution_order+1,r=new db({...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});cb in this&&(r[cb]=this[cb]);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(pb)?.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=>Sy(`${t}:${e}`,Sy.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=By();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){jv("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"===Gy(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 db({...t,client:i,tracingEnabled:s,project_name:a});return new db({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=ub.fromHeader(r.baggage);o.metadata=e.metadata,o.tags=e.tags,o.project_name=e.project_name,o.replicas=e.replicas}return new db(o)}toHeaders(e){const t={"langsmith-trace":this.dotted_order,baggage:new ub(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 pb(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=>pb(e))}Object.defineProperty(db,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});Hh({},{BaseTracer:()=>vb,isBaseTracer:()=>gb});function hb(e,t){if(e)return new db({...e,start_time:e._serialized_start_time??e.start_time,parent_run:hb(t),child_runs:e.child_runs.map(e=>hb(e)).filter(e=>void 0!==e),extra:{...e.extra,runtime:cy()},tracingEnabled:!1})}function fb(e,t){return e&&!Array.isArray(e)&&"object"==typeof e?e:{[t]:e}}function gb(e){return"function"==typeof e._addRunToRunMap}var yb,vb=class extends xy{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}=lb(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=hb(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=fb(e,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),void 0!==a?.inputs&&(i.inputs=fb(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=fb(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 _b=(yb||(yb=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),wb=Zn(_b);function Sb(e,t){return`${e.open}${t}${e.close}`}function Nb(e,t){try{return JSON.stringify(e,null,2)}catch{return t}}function kb(e){return"string"==typeof e?e.trim():null==e?e:Nb(e,e.toString())}function xb(e){if(!e.end_time)return"";const t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}Hh({},{ConsoleCallbackHandler:()=>Eb});const{color:Pb}=wb;var Eb=class extends vb{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?Sb(wb.bold,n):n}).join(" > ");return Sb(Pb.grey,t)}onChainStart(e){const t=this.getBreadcrumbs(e);console.log(`${Sb(Pb.green,"[chain/start]")} [${t}] Entering Chain run with input: ${Nb(e.inputs,"[inputs]")}`)}onChainEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Sb(Pb.cyan,"[chain/end]")} [${t}] [${xb(e)}] Exiting Chain run with output: ${Nb(e.outputs,"[outputs]")}`)}onChainError(e){const t=this.getBreadcrumbs(e);console.log(`${Sb(Pb.red,"[chain/error]")} [${t}] [${xb(e)}] Chain run errored with error: ${Nb(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(`${Sb(Pb.green,"[llm/start]")} [${t}] Entering LLM run with input: ${Nb(r,"[inputs]")}`)}onLLMEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Sb(Pb.cyan,"[llm/end]")} [${t}] [${xb(e)}] Exiting LLM run with output: ${Nb(e.outputs,"[response]")}`)}onLLMError(e){const t=this.getBreadcrumbs(e);console.log(`${Sb(Pb.red,"[llm/error]")} [${t}] [${xb(e)}] LLM run errored with error: ${Nb(e.error,"[error]")}`)}onToolStart(e){const t=this.getBreadcrumbs(e);console.log(`${Sb(Pb.green,"[tool/start]")} [${t}] Entering Tool run with input: "${kb(e.inputs.input)}"`)}onToolEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Sb(Pb.cyan,"[tool/end]")} [${t}] [${xb(e)}] Exiting Tool run with output: "${kb(e.outputs?.output)}"`)}onToolError(e){const t=this.getBreadcrumbs(e);console.log(`${Sb(Pb.red,"[tool/error]")} [${t}] [${xb(e)}] Tool run errored with error: ${Nb(e.error,"[error]")}`)}onRetrieverStart(e){const t=this.getBreadcrumbs(e);console.log(`${Sb(Pb.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${Nb(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Sb(Pb.cyan,"[retriever/end]")} [${t}] [${xb(e)}] Exiting Retriever run with output: ${Nb(e.outputs,"[outputs]")}`)}onRetrieverError(e){const t=this.getBreadcrumbs(e);console.log(`${Sb(Pb.red,"[retriever/error]")} [${t}] [${xb(e)}] Retriever run errored with error: ${Nb(e.error,"[error]")}`)}onAgentAction(e){const t=e,r=this.getBreadcrumbs(e);console.log(`${Sb(Pb.blue,"[agent/action]")} [${r}] Agent selected action: ${Nb(t.actions[t.actions.length-1],"[action]")}`)}};let Cb;const Ab=()=>{if(void 0===Cb){const e="false"===ly("LANGCHAIN_CALLBACKS_BACKGROUND")?{blockOnRootRunFinalization:!0}:{};Cb=new sb(e)}return Cb};const Ob=Symbol.for("ls:tracing_async_local_storage"),Ib=new class{getStore(){}run(e,t){return t()}};const $b=new class{getInstance(){return globalThis[Ob]??Ib}initializeGlobalInstance(e){void 0===globalThis[Ob]&&(globalThis[Ob]=e)}};function Tb(e){return"function"==typeof e&&"langsmith:traceable"in e}Hh({},{LangChainTracer:()=>zb});var zb=class e extends vb{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??Ry(),this.replicas=i,this.exampleId=r,this.client=a??Ab();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 db({...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=$b.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 Rb;function Lb(){return void 0===Rb&&(Rb=new("default"in Ov?Ov.default:Ov)({autoStart:!0,concurrency:1})),Rb}async function Mb(e,t){if(!0===t){const t=ey();void 0!==t?await t.run(void 0,async()=>e()):await e()}else Rb=Lb(),Rb.add(async()=>{const t=ey();void 0!==t?await t.run(void 0,async()=>e()):await e()})}async function jb(){const e=Ab();await Promise.allSettled([void 0!==Rb?Rb.onIdle():Promise.resolve(),e.awaitPendingTraceBatches()])}Hh({},{awaitAllCallbacks:()=>jb,consumeCallback:()=>Mb});function Db(e){const t=ey();if(void 0===t)return;const r=t.getStore();return r?.[Qg]?.[e]}const Fb=Symbol("lc:configure_hooks");function Ub(e){return e?Array.isArray(e)||"name"in e?{callbacks:e}:e:{}}Hh({},{BaseCallbackManager:()=>Bb,BaseRunManager:()=>qb,CallbackManager:()=>Kb,CallbackManagerForChainRun:()=>Hb,CallbackManagerForLLMRun:()=>Gb,CallbackManagerForRetrieverRun:()=>Vb,CallbackManagerForToolRun:()=>Wb,ensureHandler:()=>Zb,parseCallbackConfigArg:()=>Ub});var Bb=class{setHandler(e){return this.setHandlers([e])}},qb=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=>Mb(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=>Mb(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)))}},Vb=class extends qb{getChild(e){const t=new Kb(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=>Mb(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=>Mb(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)))}},Gb=class extends qb{async handleLLMNewToken(e,t,r,n,a,i){await Promise.all(this.handlers.map(r=>Mb(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=>Mb(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=>Mb(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)))}},Hb=class extends qb{getChild(e){const t=new Kb(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=>Mb(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=>Mb(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=>Mb(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=>Mb(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)))}},Wb=class extends qb{getChild(e){const t=new Kb(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=>Mb(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=>Mb(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)))}},Kb=class e extends Bb{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 gb(r)&&r._createRunForLLMStart(e,[t],i,this._parentRunId,a,this.tags,this.metadata,o),Mb(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 Gb(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 gb(r)&&r._createRunForChatModelStart(e,[t],i,this._parentRunId,a,this.tags,this.metadata,o),Mb(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=Wg(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 Gb(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 gb(a)&&a._createRunForChainStart(e,t,r,this._parentRunId,this.tags,this.metadata,n,s),Mb(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 Hb(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 gb(n)&&n._createRunForToolStart(e,t,r,this._parentRunId,this.tags,this.metadata,s),Mb(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 Wb(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 gb(n)&&n._createRunForRetrieverStart(e,t,r,this._parentRunId,this.tags,this.metadata,s),Mb(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 Vb(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=>Mb(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 xy{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(Zb)??[],!0)):c=t,c=c.copy(Array.isArray(r)?r.map(Zb):r?.handlers,!1));const l="true"===ly("LANGCHAIN_VERBOSE")||o?.verbose,u=zb.getTraceableRunTree()?.tracingEnabled||!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>"true"===ly(e)),d=u||(ly("LANGCHAIN_TRACING")??!1);if(l||d){if(c||(c=new e),l&&!c.handlers.some(e=>e.name===Eb.prototype.name)){const e=new Eb;c.addHandler(e,!0)}if(d&&!c.handlers.some(e=>"langchain_tracer"===e.name)&&u){const e=new zb;c.addHandler(e,!0)}if(u){const e=zb.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 Db(Fb)||[]){const i=a&&"true"===ly(a)&&n;let s;const o=void 0!==t?Db(t):void 0;o&&Py(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 Zb(e){return"name"in e?e:xy.fromMethods(e)}var Jb=class{getStore(){}run(e,t){return t()}enterWith(e){}};const Yb=new Jb,Xb=Symbol.for("lc:child_config");const Qb=new class{getInstance(){return ey()??Yb}getRunnableConfig(){const e=this.getInstance();return e.getStore()?.extra?.[Xb]}runWithConfig(e,t,r){const n=Kb._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 db({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[Xb]:e}),void 0!==i&&void 0!==i[Qg]&&(void 0===c&&(c={}),c[Qg]=i[Qg]),a.run(c,t)}initializeGlobalInstance(e){void 0===ey()&&(e=>{globalThis[Xg]=e})(e)}};Hh({},{AsyncLocalStorageProviderSingleton:()=>Qb,MockAsyncLocalStorage:()=>Jb,_CONTEXT_VARIABLES_KEY:()=>Qg});async function e_(e){return Kb._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function t_(...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(Zb(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(Zb(t),!0);t.callbacks=r}else t.callbacks=new Kb(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 r_=new Set(["string","number","boolean"]);function n_(e){const t=Qb.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))r_.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 a_(e={},{callbacks:t,maxConcurrency:r,recursionLimit:n,runName:a,configurable:i,runId:s}={}){const o=n_(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 i_(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 s_(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")}Hh({},{AsyncGeneratorWithSetup:()=>d_,IterableReadableStream:()=>c_,atee:()=>l_,concat:()=>u_,pipeGeneratorWithSetup:()=>p_});var c_=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 l_(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 u_(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]=u_(r[e],n):r[e]=n;return r}throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}var d_=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)=>{Qb.runWithConfig(i_(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?Qb.runWithConfig(i_(this.config),this.signal?async()=>s_(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 p_(e,t,r,n,...a){const i=new d_({generator:t,startSetup:r,signal:n}),s=await i.setup;return{output:e(i,s,...a),setup:s}}const m_=Object.prototype.hasOwnProperty;function h_(e,t){return m_.call(e,t)}function f_(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)h_(e,r)&&t.push(r);return t}function g_(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function y_(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 v_(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 __(e){if(void 0===e)return!0;if(e)if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(__(e[t]))return!0}else if("object"==typeof e){const r=f_(e),n=r.length;for(var t=0;t<n;t++)if(__(e[r[t]]))return!0}return!1}function w_(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 S_=class extends Error{constructor(e,t,r,n,a){super(w_(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=w_(e,{name:t,index:r,operation:n,tree:a})}},N_={};Hh(N_,{JsonPatchError:()=>k_,_areEquals:()=>z_,applyOperation:()=>A_,applyPatch:()=>O_,applyReducer:()=>I_,deepClone:()=>x_,getValueByPointer:()=>C_,validate:()=>T_,validator:()=>$_});const k_=S_,x_=g_,P_={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=C_(r,this.path);n&&(n=g_(n));const a=A_(r,{op:"remove",path:this.from}).removed;return A_(r,{op:"add",path:this.path,value:a}),{newDocument:r,removed:n}},copy:function(e,t,r){const n=C_(r,this.from);return A_(r,{op:"add",path:this.path,value:g_(n)}),{newDocument:r}},test:function(e,t,r){return{newDocument:r,test:z_(e[t],this.value)}},_get:function(e,t,r){return this.value=e[t],{newDocument:r}}};var E_={add:function(e,t,r){return y_(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:P_.move,copy:P_.copy,test:P_.test,_get:P_._get};function C_(e,t){if(""==t)return e;var r={op:"_get",path:t};return A_(e,r),r.value}function A_(e,t,r=!1,n=!0,a=!0,i=0){if(r&&("function"==typeof r?r(t,0,e,t.path):$_(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=C_(e,t.from),"move"===t.op&&(n.removed=e),n;if("test"===t.op){if(n.test=z_(e,t.value),!1===n.test)throw new k_("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 k_("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,t,e);return n}{n||(e=g_(e));const s=(t.path||"").split("/");let o,c,l,u=e,d=1,p=s.length;for(l="function"==typeof r?r:$_;;){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&&!y_(c))throw new k_("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);y_(c)&&(c=~~c)}if(d>=p){if(r&&"add"===t.op&&c>u.length)throw new k_("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=E_[t.op].call(t,u,c,e);if(!1===n.test)throw new k_("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return n}}else if(d>=p){const r=P_[t.op].call(t,u,c,e);if(!1===r.test)throw new k_("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return r}if(u=u[c],r&&d<p&&(!u||"object"!=typeof u))throw new k_("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,t,e)}}}function O_(e,t,r,n=!0,a=!0){if(r&&!Array.isArray(t))throw new k_("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(e=g_(e));const i=new Array(t.length);for(let n=0,s=t.length;n<s;n++)i[n]=A_(e,t[n],r,!0,a,n),e=i[n].newDocument;return i.newDocument=e,i}function I_(e,t,r){const n=A_(e,t);if(!1===n.test)throw new k_("Test operation failed","TEST_OPERATION_FAILED",r,t,e);return n.newDocument}function $_(e,t,r,n){if("object"!=typeof e||null===e||Array.isArray(e))throw new k_("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,r);if(!P_[e.op])throw new k_("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 k_("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,r);if(0!==e.path.indexOf("/")&&e.path.length>0)throw new k_('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 k_("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 k_("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)&&__(e.value))throw new k_("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 k_("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 k_("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=T_([{op:"_get",path:e.from,value:void 0}],r);if(s&&"OPERATION_PATH_UNRESOLVABLE"===s.name)throw new k_("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,r)}}function T_(e,t,r){try{if(!Array.isArray(e))throw new k_("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)O_(g_(t),g_(e),r||!0);else{r=r||$_;for(var n=0;n<e.length;n++)r(e[n],n,t,void 0)}}catch(e){if(e instanceof k_)return e;throw e}}function z_(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(!z_(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(!z_(e[a=o[r]],t[a]))return!1;return!0}return e!=e&&t!=t}function R_(e,t,r,n,a){if(t!==e){"function"==typeof t.toJSON&&(t=t.toJSON());for(var i=f_(t),s=f_(e),o=!1,c=s.length-1;c>=0;c--){var l=e[d=s[c]];if(!h_(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+"/"+v_(d),value:g_(l)}),r.push({op:"remove",path:n+"/"+v_(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)?R_(l,u,r,n+"/"+v_(d),a):l!==u&&(a&&r.push({op:"test",path:n+"/"+v_(d),value:g_(l)}),r.push({op:"replace",path:n+"/"+v_(d),value:g_(u)}))}}if(o||i.length!=s.length)for(c=0;c<i.length;c++){var d;h_(e,d=i[c])||void 0===t[d]||r.push({op:"add",path:n+"/"+v_(d),value:g_(t[d])})}}}function L_(e,t,r=!1){var n=[];return R_(e,t,n,"",r),n}Hh({},{LogStreamCallbackHandler:()=>B_,RunLog:()=>j_,RunLogPatch:()=>M_,isLogStreamHandler:()=>D_});var M_=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){const t=this.ops.concat(e.ops),r=O_({},t);return new j_({ops:t,state:r[r.length-1].newDocument})}},j_=class e extends M_{state;constructor(e){super(e),this.state=e.state}concat(t){const r=this.ops.concat(t.ops),n=O_(this.state,t.ops);return new e({ops:r,state:n[n.length-1].newDocument})}static fromRunLogPatch(t){const r=O_({},t.ops);return new e({ops:t.ops,state:r[r.length-1].newDocument})}};const D_=e=>"log_stream_tracer"===e.name;async function F_(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 U_(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 B_=class extends vb{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=c_.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 M_({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 M_({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 F_(e,this._schemaFormat)),await this.writer.write(new M_({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 F_(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await U_(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 M_({ops:r});await this.writer.write(n)}finally{if(e.id===this.rootId){const t=new M_({ops:[{op:"replace",path:"/final_output",value:await U_(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 Sg({id:`run-${e.id}`,content:t})):a=t;const s=new M_({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)}};Hh({},{ChatGenerationChunk:()=>G_,GenerationChunk:()=>V_,RUN_KEY:()=>q_});const q_="__run";var V_=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}})}},G_=class e extends V_{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 H_({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 W_=e=>"event_stream_tracer"===e.name;var K_=class extends vb{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=c_.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 V_({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=H_(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 Sg({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 V_({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=H_(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=H_(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=H_(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()})}};Hh({},{AsyncCaller:()=>Y_});const Z_=[400,401,402,403,404,405,406,407,409],J_=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&&Z_.includes(+t))throw e;if("insufficient_quota"===e?.error?.code){const t=new Error(e?.message);throw t.name="InsufficientQuotaError",t}};var Y_=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??J_;const t="default"in Ov?Ov.default:Ov;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>fv(()=>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)))}},X_=class extends vb{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 Q_(e){return!!e&&e.lc_runnable}var ew=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 tw(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 rw extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const nw={};function aw(e){return nw}function iw(e,t){return"bigint"==typeof t?t.toString():t}const sw=Symbol("evaluating");function ow(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==sw)return void 0===n&&(n=sw,n=r()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function cw(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function lw(...e){const t={};for(const r of e){const e=Object.getOwnPropertyDescriptors(r);Object.assign(t,e)}return Object.defineProperties({},t)}const uw="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function dw(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function pw(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===dw(e))return!1;const t=e.constructor;if(void 0===t)return!0;const r=t.prototype;return!1!==dw(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=lw(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return cw(this,"shape",r),r},checks:[]});return pw(e,n)}function hw(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 fw(e){return"string"==typeof e?e:e?.message}function gw(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const a=fw(e.inst?._zod.def?.error?.(e))??fw(t?.error?.(e))??fw(r.customError?.(e))??fw(r.localeError?.(e))??"Invalid input";n.message=a}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}const yw=(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,iw,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},vw=tw("$ZodError",yw),bw=tw("$ZodError",yw,{Parent:Error});function _w(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 ww=(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 rw;if(s.issues.length){const t=new(a?.Err??e)(s.issues.map(e=>gw(e,i,aw())));throw uw(t,a?.callee),t}return s.value})(bw),Sw=(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=>gw(e,i,aw())));throw uw(t,a?.callee),t}return s.value})(bw),Nw=(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 rw;return i.issues.length?{success:!1,error:new(e??vw)(i.issues.map(e=>gw(e,a,aw())))}:{success:!0,data:i.value}})(bw),kw=(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=>gw(e,a,aw())))}:{success:!0,data:i.value}})(bw),xw={major:4,minor:1,patch:12},Pw=tw("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=xw;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=hw(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 rw;if(n||s instanceof Promise)n=(n??Promise.resolve()).then(async()=>{await s;e.issues.length!==t&&(a||(a=hw(e,t)))});else{if(e.issues.length===t)continue;a||(a=hw(e,t))}}return n?n.then(()=>e):e},r=(r,a,i)=>{if(hw(r))return r.aborted=!0,r;const s=t(a,n,i);if(s instanceof Promise){if(!1===i.async)throw new rw;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 rw;return s.then(e=>t(e,n,i))}return t(s,n,i)}}e["~standard"]={validate:t=>{try{const r=Nw(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return kw(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),Ew=tw("$ZodUnknown",(e,t)=>{Pw.init(e,t),e._zod.parse=e=>e}),Cw=tw("$ZodNever",(e,t)=>{Pw.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function Aw(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const Ow=tw("$ZodOptional",(e,t)=>{Pw.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=>Aw(t,e.value)):Aw(n,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,r)}});class Iw{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 $w(){return new Iw}const Tw=$w();class zw{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Tw,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&&Lw(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 Rw(e,t){if(e instanceof Iw){const r=new zw(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 zw(t);return r.process(e),r.emit(e,t)}function Lw(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 Lw(n.element,r);case"object":for(const e in n.shape)if(Lw(n.shape[e],r))return!0;return!1;case"union":for(const e of n.options)if(Lw(e,r))return!0;return!1;case"intersection":return Lw(n.left,r)||Lw(n.right,r);case"tuple":for(const e of n.items)if(Lw(e,r))return!0;return!(!n.rest||!Lw(n.rest,r));case"record":case"map":return Lw(n.keyType,r)||Lw(n.valueType,r);case"set":return Lw(n.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":case"default":case"prefault":return Lw(n.innerType,r);case"lazy":return Lw(n.getter(),r);case"transform":return!0;case"pipe":return Lw(n.in,r)||Lw(n.out,r)}throw new Error(`Unknown schema type: ${n.type}`)}function Mw(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 jw(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 Dw(e){return Mw(e)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),jw(e)}function Fw(e){return!!e&&("object"==typeof e&&(!Array.isArray(e)&&!(!Mw(e)&&!jw(e))))}function Uw(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 Bw(e){return!!Mw(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 qw(e){return!!Uw(e)||!!Bw(e)}async function Vw(e,t){if(Mw(e))try{return{success:!0,data:await Sw(e,t)}}catch(e){return{success:!1,error:e}}if(jw(e))return await e.safeParseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function Gw(e,t){if(Mw(e))return await Sw(e,t);if(jw(e))return await e.parseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Hw(e,t){if(Mw(e))try{return{success:!0,data:ww(e,t)}}catch(e){return{success:!1,error:e}}if(jw(e))return e.safeParse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Ww(e,t){if(Mw(e))return ww(e,t);if(jw(e))return e.parse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Kw(e){return Mw(e)?Tw.get(e)?.description:jw(e)||"description"in e&&"string"==typeof e.description?e.description:void 0}function Zw(e){if(!Fw(e))return!1;if(jw(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(Mw(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 Jw(e){if(!Fw(e))return!1;if(jw(e)){return"ZodString"===e._def.typeName}if(Mw(e)){return"string"===e._zod.def.type}return!1}function Yw(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 Xw(e){return!!Mw(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 Qw(e){return!!Mw(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 eS(e){return!!Yw(e)||!!Xw(e)}function tS(e){if(jw(e))return e.shape;if(Mw(e))return e._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function rS(e,t){if(jw(e))return e.extend(t);if(Mw(e))return mw(e,t);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function nS(e){if(jw(e))return e.partial();if(Mw(e))return function(e,t){const r=lw(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 cw(this,"shape",n),n},checks:[]});return pw(t,r)}(Ow,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function aS(e,t=!1){if(jw(e))return e.strict();if(Xw(e)){const n=e._zod.def.shape;if(t)for(const[r,a]of Object.entries(e._zod.def.shape)){if(Xw(a)){const e=aS(a,t);n[r]=e}else if(Qw(a)){let e=a._zod.def.element;Xw(e)&&(e=aS(e,t)),n[r]=pw(a,{...a._zod.def,element:e})}else n[r]=a;const e=Tw.get(a);e&&Tw.add(n[r],e)}const a=pw(e,{...e._zod.def,shape:n,catchall:(r=Cw,new r({type:"never"}))}),i=Tw.get(e);return i&&Tw.add(a,i),a}var r;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function iS(e,t=!1){if(Yw(e))return e.passthrough();if(Xw(e)){const n=e._zod.def.shape;if(t)for(const[r,a]of Object.entries(e._zod.def.shape)){if(Xw(a)){const e=iS(a,t);n[r]=e}else if(Qw(a)){let e=a._zod.def.element;Xw(e)&&(e=iS(e,t)),n[r]=pw(a,{...a._zod.def,element:e})}else n[r]=a;const e=Tw.get(a);e&&Tw.add(n[r],e)}const a=pw(e,{...e._zod.def,shape:n,catchall:(r=Ew,new r({type:"unknown"}))}),i=Tw.get(e);return i&&Tw.add(a,i),a}var r;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function sS(e){if(jw(e))try{const t=e.parse(void 0);return()=>t}catch{return}if(Mw(e))try{const t=ww(e,void 0);return()=>t}catch{return}}function oS(e,t,r){const n=r.get(e);if(void 0!==n)return n;if(jw(e))return function(e){return jw(e)&&"typeName"in e._def&&"ZodEffects"===e._def.typeName}(e)?oS(e._def.schema,t,r):e;if(Mw(e)){let n=e;if(function(e){return Mw(e)&&"pipe"===e._zod.def.type}(e)&&(n=oS(e._zod.def.in,t,r)),t)if(Xw(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=pw(n,{...n._zod.def,shape:e})}else if(Qw(n)){const e=oS(n._zod.def.element,t,r);n=pw(n,{...n._zod.def,element:e})}const a=Tw.get(e);return a&&Tw.add(n,a),r.set(e,n),n}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function cS(e,t=!1){return oS(e,t,new WeakMap)}function lS(e,t){if(jw(e)){const r=tS(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(Mw(e)){const r=tS(e),n={...e._zod.def.shape};for(const[e,a]of Object.entries(r))t(e,a)&&(n[e]=new Ow({type:"optional",innerType:a}));const a=pw(e,{...e._zod.def,shape:n}),i=Tw.get(e);return i&&Tw.add(a,i),a}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function uS(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}const dS=["*","_","`"];function pS(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=dS.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}",uS(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${uS(e)}${i}${uS(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"),hS={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"},fS=e=>{const t=(e=>({...hS,...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}]))}},gS=(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 yS(e){if("openAi"!==e.target)return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?gS(t,e.currentPath):t.join("/")}}function vS(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function bS(e,t,r,n,a){e[t]=r,vS(e,t,n,a)}var _S,wS;!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}(_S||(_S={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(wS||(wS={}));const SS=_S.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),NS=e=>{switch(typeof e){case"undefined":return SS.undefined;case"string":return SS.string;case"number":return Number.isNaN(e)?SS.nan:SS.number;case"boolean":return SS.boolean;case"function":return SS.function;case"bigint":return SS.bigint;case"symbol":return SS.symbol;case"object":return Array.isArray(e)?SS.array:null===e?SS.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?SS.promise:"undefined"!=typeof Map&&e instanceof Map?SS.map:"undefined"!=typeof Set&&e instanceof Set?SS.set:"undefined"!=typeof Date&&e instanceof Date?SS.date:SS.object;default:return SS.unknown}},kS=_S.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 xS 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 xS))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,_S.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()}}xS.create=e=>new xS(e);const PS=(e,t)=>{let r;switch(e.code){case kS.invalid_type:r=e.received===SS.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case kS.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,_S.jsonStringifyReplacer)}`;break;case kS.unrecognized_keys:r=`Unrecognized key(s) in object: ${_S.joinValues(e.keys,", ")}`;break;case kS.invalid_union:r="Invalid input";break;case kS.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${_S.joinValues(e.options)}`;break;case kS.invalid_enum_value:r=`Invalid enum value. Expected ${_S.joinValues(e.options)}, received '${e.received}'`;break;case kS.invalid_arguments:r="Invalid function arguments";break;case kS.invalid_return_type:r="Invalid function return type";break;case kS.invalid_date:r="Invalid date";break;case kS.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}"`:_S.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case kS.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 kS.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 kS.custom:r="Invalid input";break;case kS.invalid_intersection_types:r="Intersection results could not be merged";break;case kS.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case kS.not_finite:r="Number must be finite";break;default:r=t.defaultError,_S.assertNever(e)}return{message:r}};let ES=PS;function CS(e,t){const r=ES,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===PS?void 0:PS].filter(e=>!!e)});e.common.issues.push(n)}class AS{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 OS;"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 AS.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 OS;if("aborted"===a.status)return OS;"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 OS=Object.freeze({status:"aborted"}),IS=e=>({status:"dirty",value:e}),$S=e=>({status:"valid",value:e}),TS=e=>"aborted"===e.status,zS=e=>"dirty"===e.status,RS=e=>"valid"===e.status,LS=e=>"undefined"!=typeof Promise&&e instanceof Promise;var MS;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(MS||(MS={}));class jS{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 DS=(e,t)=>{if(RS(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 xS(e.common.issues);return this._error=t,this._error}}};function FS(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 US{get description(){return this._def.description}_getType(e){return NS(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:NS(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new AS,ctx:{common:e.parent.common,data:e.data,parsedType:NS(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(LS(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:NS(e)},n=this._parseSync({data:e,path:r.path,parent:r});return DS(r,n)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:NS(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return RS(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=>RS(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:NS(e)},n=this._parse({data:e,path:r.path,parent:r}),a=await(LS(n)?n:Promise.resolve(n));return DS(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:kS.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 DN({schema:this,typeName:KN.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 FN.create(this,this._def)}nullable(){return UN.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return kN.create(this)}promise(){return jN.create(this,this._def)}or(e){return EN.create([this,e],this._def)}and(e){return AN.create(this,e,this._def)}transform(e){return new DN({...FS(this._def),schema:this,typeName:KN.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new BN({...FS(this._def),innerType:this,defaultValue:t,typeName:KN.ZodDefault})}brand(){return new GN({typeName:KN.ZodBranded,type:this,...FS(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new qN({...FS(this._def),innerType:this,catchValue:t,typeName:KN.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return HN.create(this,e)}readonly(){return WN.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const BS=/^c[^\s-]{8,}$/i,qS=/^[0-9a-z]+$/,VS=/^[0-9A-HJKMNP-TV-Z]{26}$/i,GS=/^[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,HS=/^[a-z0-9_-]{21}$/i,WS=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,KS=/^[-+]?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)?)??$/,ZS=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let JS;const YS=/^(?:(?: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])$/,XS=/^(?:(?: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])$/,QS=/^(([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]))$/,eN=/^(([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])$/,tN=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,rN=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nN="((\\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])))",aN=new RegExp(`^${nN}$`);function iN(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 sN(e){return new RegExp(`^${iN(e)}$`)}function oN(e){let t=`${nN}T${iN(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 cN(e,t){return!("v4"!==t&&t||!YS.test(e))||!("v6"!==t&&t||!QS.test(e))}function lN(e,t){if(!WS.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 uN(e,t){return!("v4"!==t&&t||!XS.test(e))||!("v6"!==t&&t||!eN.test(e))}class dN extends US{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==SS.string){const t=this._getOrReturnCtx(e);return CS(t,{code:kS.invalid_type,expected:SS.string,received:t.parsedType}),OS}const t=new AS;let r;for(const n of this._def.checks)if("min"===n.kind)e.data.length<n.value&&(r=this._getOrReturnCtx(e,r),CS(r,{code:kS.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),CS(r,{code:kS.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?CS(r,{code:kS.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):i&&CS(r,{code:kS.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),t.dirty())}else if("email"===n.kind)ZS.test(e.data)||(r=this._getOrReturnCtx(e,r),CS(r,{validation:"email",code:kS.invalid_string,message:n.message}),t.dirty());else if("emoji"===n.kind)JS||(JS=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),JS.test(e.data)||(r=this._getOrReturnCtx(e,r),CS(r,{validation:"emoji",code:kS.invalid_string,message:n.message}),t.dirty());else if("uuid"===n.kind)GS.test(e.data)||(r=this._getOrReturnCtx(e,r),CS(r,{validation:"uuid",code:kS.invalid_string,message:n.message}),t.dirty());else if("nanoid"===n.kind)HS.test(e.data)||(r=this._getOrReturnCtx(e,r),CS(r,{validation:"nanoid",code:kS.invalid_string,message:n.message}),t.dirty());else if("cuid"===n.kind)BS.test(e.data)||(r=this._getOrReturnCtx(e,r),CS(r,{validation:"cuid",code:kS.invalid_string,message:n.message}),t.dirty());else if("cuid2"===n.kind)qS.test(e.data)||(r=this._getOrReturnCtx(e,r),CS(r,{validation:"cuid2",code:kS.invalid_string,message:n.message}),t.dirty());else if("ulid"===n.kind)VS.test(e.data)||(r=this._getOrReturnCtx(e,r),CS(r,{validation:"ulid",code:kS.invalid_string,message:n.message}),t.dirty());else if("url"===n.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),CS(r,{validation:"url",code:kS.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),CS(r,{validation:"regex",code:kS.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),CS(r,{code:kS.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),CS(r,{code:kS.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),CS(r,{code:kS.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),CS(r,{code:kS.invalid_string,validation:"datetime",message:n.message}),t.dirty())}else if("date"===n.kind){aN.test(e.data)||(r=this._getOrReturnCtx(e,r),CS(r,{code:kS.invalid_string,validation:"date",message:n.message}),t.dirty())}else if("time"===n.kind){sN(n).test(e.data)||(r=this._getOrReturnCtx(e,r),CS(r,{code:kS.invalid_string,validation:"time",message:n.message}),t.dirty())}else"duration"===n.kind?KS.test(e.data)||(r=this._getOrReturnCtx(e,r),CS(r,{validation:"duration",code:kS.invalid_string,message:n.message}),t.dirty()):"ip"===n.kind?cN(e.data,n.version)||(r=this._getOrReturnCtx(e,r),CS(r,{validation:"ip",code:kS.invalid_string,message:n.message}),t.dirty()):"jwt"===n.kind?lN(e.data,n.alg)||(r=this._getOrReturnCtx(e,r),CS(r,{validation:"jwt",code:kS.invalid_string,message:n.message}),t.dirty()):"cidr"===n.kind?uN(e.data,n.version)||(r=this._getOrReturnCtx(e,r),CS(r,{validation:"cidr",code:kS.invalid_string,message:n.message}),t.dirty()):"base64"===n.kind?tN.test(e.data)||(r=this._getOrReturnCtx(e,r),CS(r,{validation:"base64",code:kS.invalid_string,message:n.message}),t.dirty()):"base64url"===n.kind?rN.test(e.data)||(r=this._getOrReturnCtx(e,r),CS(r,{validation:"base64url",code:kS.invalid_string,message:n.message}),t.dirty()):_S.assertNever(n);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:kS.invalid_string,...MS.errToObj(r)})}_addCheck(e){return new dN({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...MS.errToObj(e)})}url(e){return this._addCheck({kind:"url",...MS.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...MS.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...MS.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...MS.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...MS.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...MS.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...MS.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...MS.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...MS.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...MS.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...MS.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...MS.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,...MS.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,...MS.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...MS.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...MS.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...MS.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...MS.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...MS.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...MS.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...MS.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...MS.errToObj(t)})}nonempty(e){return this.min(1,MS.errToObj(e))}trim(){return new dN({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new dN({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new dN({...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 pN(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}dN.create=e=>new dN({checks:[],typeName:KN.ZodString,coerce:e?.coerce??!1,...FS(e)});class mN extends US{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)!==SS.number){const t=this._getOrReturnCtx(e);return CS(t,{code:kS.invalid_type,expected:SS.number,received:t.parsedType}),OS}let t;const r=new AS;for(const n of this._def.checks)if("int"===n.kind)_S.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),CS(t,{code:kS.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),CS(t,{code:kS.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),CS(t,{code:kS.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else"multipleOf"===n.kind?0!==pN(e.data,n.value)&&(t=this._getOrReturnCtx(e,t),CS(t,{code:kS.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),CS(t,{code:kS.not_finite,message:n.message}),r.dirty()):_S.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,MS.toString(t))}gt(e,t){return this.setLimit("min",e,!1,MS.toString(t))}lte(e,t){return this.setLimit("max",e,!0,MS.toString(t))}lt(e,t){return this.setLimit("max",e,!1,MS.toString(t))}setLimit(e,t,r,n){return new mN({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:MS.toString(n)}]})}_addCheck(e){return new mN({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:MS.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:MS.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:MS.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:MS.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:MS.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:MS.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:MS.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:MS.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:MS.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&&_S.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:KN.ZodNumber,coerce:e?.coerce||!1,...FS(e)});class hN extends US{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)!==SS.bigint)return this._getInvalidInput(e);let t;const r=new AS;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),CS(t,{code:kS.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),CS(t,{code:kS.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),CS(t,{code:kS.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):_S.assertNever(n);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return CS(t,{code:kS.invalid_type,expected:SS.bigint,received:t.parsedType}),OS}gte(e,t){return this.setLimit("min",e,!0,MS.toString(t))}gt(e,t){return this.setLimit("min",e,!1,MS.toString(t))}lte(e,t){return this.setLimit("max",e,!0,MS.toString(t))}lt(e,t){return this.setLimit("max",e,!1,MS.toString(t))}setLimit(e,t,r,n){return new hN({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:MS.toString(n)}]})}_addCheck(e){return new hN({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:MS.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:MS.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:MS.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:MS.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:MS.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}}hN.create=e=>new hN({checks:[],typeName:KN.ZodBigInt,coerce:e?.coerce??!1,...FS(e)});class fN extends US{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==SS.boolean){const t=this._getOrReturnCtx(e);return CS(t,{code:kS.invalid_type,expected:SS.boolean,received:t.parsedType}),OS}return $S(e.data)}}fN.create=e=>new fN({typeName:KN.ZodBoolean,coerce:e?.coerce||!1,...FS(e)});class gN extends US{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==SS.date){const t=this._getOrReturnCtx(e);return CS(t,{code:kS.invalid_type,expected:SS.date,received:t.parsedType}),OS}if(Number.isNaN(e.data.getTime())){return CS(this._getOrReturnCtx(e),{code:kS.invalid_date}),OS}const t=new AS;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),CS(r,{code:kS.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),CS(r,{code:kS.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):_S.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new gN({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:MS.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:MS.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}}gN.create=e=>new gN({checks:[],coerce:e?.coerce||!1,typeName:KN.ZodDate,...FS(e)});class yN extends US{_parse(e){if(this._getType(e)!==SS.symbol){const t=this._getOrReturnCtx(e);return CS(t,{code:kS.invalid_type,expected:SS.symbol,received:t.parsedType}),OS}return $S(e.data)}}yN.create=e=>new yN({typeName:KN.ZodSymbol,...FS(e)});class vN extends US{_parse(e){if(this._getType(e)!==SS.undefined){const t=this._getOrReturnCtx(e);return CS(t,{code:kS.invalid_type,expected:SS.undefined,received:t.parsedType}),OS}return $S(e.data)}}vN.create=e=>new vN({typeName:KN.ZodUndefined,...FS(e)});class bN extends US{_parse(e){if(this._getType(e)!==SS.null){const t=this._getOrReturnCtx(e);return CS(t,{code:kS.invalid_type,expected:SS.null,received:t.parsedType}),OS}return $S(e.data)}}bN.create=e=>new bN({typeName:KN.ZodNull,...FS(e)});class _N extends US{constructor(){super(...arguments),this._any=!0}_parse(e){return $S(e.data)}}_N.create=e=>new _N({typeName:KN.ZodAny,...FS(e)});class wN extends US{constructor(){super(...arguments),this._unknown=!0}_parse(e){return $S(e.data)}}wN.create=e=>new wN({typeName:KN.ZodUnknown,...FS(e)});class SN extends US{_parse(e){const t=this._getOrReturnCtx(e);return CS(t,{code:kS.invalid_type,expected:SS.never,received:t.parsedType}),OS}}SN.create=e=>new SN({typeName:KN.ZodNever,...FS(e)});class NN extends US{_parse(e){if(this._getType(e)!==SS.undefined){const t=this._getOrReturnCtx(e);return CS(t,{code:kS.invalid_type,expected:SS.void,received:t.parsedType}),OS}return $S(e.data)}}NN.create=e=>new NN({typeName:KN.ZodVoid,...FS(e)});class kN extends US{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==SS.array)return CS(t,{code:kS.invalid_type,expected:SS.array,received:t.parsedType}),OS;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,a=t.data.length<n.exactLength.value;(e||a)&&(CS(t,{code:e?kS.too_big:kS.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&&(CS(t,{code:kS.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&&(CS(t,{code:kS.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 jS(t,e,t.path,r)))).then(e=>AS.mergeArray(r,e));const a=[...t.data].map((e,r)=>n.type._parseSync(new jS(t,e,t.path,r)));return AS.mergeArray(r,a)}get element(){return this._def.type}min(e,t){return new kN({...this._def,minLength:{value:e,message:MS.toString(t)}})}max(e,t){return new kN({...this._def,maxLength:{value:e,message:MS.toString(t)}})}length(e,t){return new kN({...this._def,exactLength:{value:e,message:MS.toString(t)}})}nonempty(e){return this.min(1,e)}}function xN(e){if(e instanceof PN){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=FN.create(xN(n))}return new PN({...e._def,shape:()=>t})}return e instanceof kN?new kN({...e._def,type:xN(e.element)}):e instanceof FN?FN.create(xN(e.unwrap())):e instanceof UN?UN.create(xN(e.unwrap())):e instanceof ON?ON.create(e.items.map(e=>xN(e))):e}kN.create=(e,t)=>new kN({type:e,minLength:null,maxLength:null,exactLength:null,typeName:KN.ZodArray,...FS(t)});class PN extends US{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=_S.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==SS.object){const t=this._getOrReturnCtx(e);return CS(t,{code:kS.invalid_type,expected:SS.object,received:t.parsedType}),OS}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof SN&&"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 jS(r,a,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof SN){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&&(CS(r,{code:kS.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 jS(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=>AS.mergeObjectSync(t,e)):AS.mergeObjectSync(t,s)}get shape(){return this._def.shape()}strict(e){return MS.errToObj,new PN({...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:MS.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new PN({...this._def,unknownKeys:"strip"})}passthrough(){return new PN({...this._def,unknownKeys:"passthrough"})}extend(e){return new PN({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new PN({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:KN.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new PN({...this._def,catchall:e})}pick(e){const t={};for(const r of _S.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new PN({...this._def,shape:()=>t})}omit(e){const t={};for(const r of _S.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new PN({...this._def,shape:()=>t})}deepPartial(){return xN(this)}partial(e){const t={};for(const r of _S.objectKeys(this.shape)){const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}return new PN({...this._def,shape:()=>t})}required(e){const t={};for(const r of _S.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof FN;)e=e._def.innerType;t[r]=e}return new PN({...this._def,shape:()=>t})}keyof(){return RN(_S.objectKeys(this.shape))}}PN.create=(e,t)=>new PN({shape:()=>e,unknownKeys:"strip",catchall:SN.create(),typeName:KN.ZodObject,...FS(t)}),PN.strictCreate=(e,t)=>new PN({shape:()=>e,unknownKeys:"strict",catchall:SN.create(),typeName:KN.ZodObject,...FS(t)}),PN.lazycreate=(e,t)=>new PN({shape:e,unknownKeys:"strip",catchall:SN.create(),typeName:KN.ZodObject,...FS(t)});class EN extends US{_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 xS(e.ctx.common.issues));return CS(t,{code:kS.invalid_union,unionErrors:r}),OS});{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 xS(e));return CS(t,{code:kS.invalid_union,unionErrors:a}),OS}}get options(){return this._def.options}}function CN(e,t){const r=NS(e),n=NS(t);if(e===t)return{valid:!0,data:e};if(r===SS.object&&n===SS.object){const r=_S.objectKeys(t),n=_S.objectKeys(e).filter(e=>-1!==r.indexOf(e)),a={...e,...t};for(const r of n){const n=CN(e[r],t[r]);if(!n.valid)return{valid:!1};a[r]=n.data}return{valid:!0,data:a}}if(r===SS.array&&n===SS.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n<e.length;n++){const a=CN(e[n],t[n]);if(!a.valid)return{valid:!1};r.push(a.data)}return{valid:!0,data:r}}return r===SS.date&&n===SS.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}EN.create=(e,t)=>new EN({options:e,typeName:KN.ZodUnion,...FS(t)});class AN extends US{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(TS(e)||TS(n))return OS;const a=CN(e.value,n.value);return a.valid?((zS(e)||zS(n))&&t.dirty(),{status:t.value,value:a.data}):(CS(r,{code:kS.invalid_intersection_types}),OS)};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}))}}AN.create=(e,t,r)=>new AN({left:e,right:t,typeName:KN.ZodIntersection,...FS(r)});class ON extends US{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==SS.array)return CS(r,{code:kS.invalid_type,expected:SS.array,received:r.parsedType}),OS;if(r.data.length<this._def.items.length)return CS(r,{code:kS.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),OS;!this._def.rest&&r.data.length>this._def.items.length&&(CS(r,{code:kS.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 jS(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(n).then(e=>AS.mergeArray(t,e)):AS.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new ON({...this._def,rest:e})}}ON.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ON({items:e,typeName:KN.ZodTuple,rest:null,...FS(t)})};class IN extends US{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!==SS.map)return CS(r,{code:kS.invalid_type,expected:SS.map,received:r.parsedType}),OS;const n=this._def.keyType,a=this._def.valueType,i=[...r.data.entries()].map(([e,t],i)=>({key:n._parse(new jS(r,e,r.path,[i,"key"])),value:a._parse(new jS(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 OS;"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 OS;"dirty"!==n.status&&"dirty"!==a.status||t.dirty(),e.set(n.value,a.value)}return{status:t.value,value:e}}}}IN.create=(e,t,r)=>new IN({valueType:t,keyType:e,typeName:KN.ZodMap,...FS(r)});class $N extends US{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==SS.set)return CS(r,{code:kS.invalid_type,expected:SS.set,received:r.parsedType}),OS;const n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(CS(r,{code:kS.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&&(CS(r,{code:kS.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 OS;"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 jS(r,e,r.path,t)));return r.common.async?Promise.all(s).then(e=>i(e)):i(s)}min(e,t){return new $N({...this._def,minSize:{value:e,message:MS.toString(t)}})}max(e,t){return new $N({...this._def,maxSize:{value:e,message:MS.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}$N.create=(e,t)=>new $N({valueType:e,minSize:null,maxSize:null,typeName:KN.ZodSet,...FS(t)});class TN extends US{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})}}TN.create=(e,t)=>new TN({getter:e,typeName:KN.ZodLazy,...FS(t)});class zN extends US{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return CS(t,{received:t.data,code:kS.invalid_literal,expected:this._def.value}),OS}return{status:"valid",value:e.data}}get value(){return this._def.value}}function RN(e,t){return new LN({values:e,typeName:KN.ZodEnum,...FS(t)})}zN.create=(e,t)=>new zN({value:e,typeName:KN.ZodLiteral,...FS(t)});class LN extends US{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return CS(t,{expected:_S.joinValues(r),received:t.parsedType,code:kS.invalid_type}),OS}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 CS(t,{received:t.data,code:kS.invalid_enum_value,options:r}),OS}return $S(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 LN.create(e,{...this._def,...t})}exclude(e,t=this._def){return LN.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}LN.create=RN;class MN extends US{_parse(e){const t=_S.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==SS.string&&r.parsedType!==SS.number){const e=_S.objectValues(t);return CS(r,{expected:_S.joinValues(e),received:r.parsedType,code:kS.invalid_type}),OS}if(this._cache||(this._cache=new Set(_S.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=_S.objectValues(t);return CS(r,{received:r.data,code:kS.invalid_enum_value,options:e}),OS}return $S(e.data)}get enum(){return this._def.values}}MN.create=(e,t)=>new MN({values:e,typeName:KN.ZodNativeEnum,...FS(t)});class jN extends US{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==SS.promise&&!1===t.common.async)return CS(t,{code:kS.invalid_type,expected:SS.promise,received:t.parsedType}),OS;const r=t.parsedType===SS.promise?t.data:Promise.resolve(t.data);return $S(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}jN.create=(e,t)=>new jN({type:e,typeName:KN.ZodPromise,...FS(t)});class DN extends US{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===KN.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=>{CS(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 OS;const n=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===n.status?OS:"dirty"===n.status||"dirty"===t.value?IS(n.value):n});{if("aborted"===t.value)return OS;const n=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===n.status?OS:"dirty"===n.status||"dirty"===t.value?IS(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?OS:("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?OS:("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(!RS(e))return OS;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=>RS(e)?Promise.resolve(n.transform(e.value,a)).then(e=>({status:t.value,value:e})):OS)}_S.assertNever(n)}}DN.create=(e,t,r)=>new DN({schema:e,typeName:KN.ZodEffects,effect:t,...FS(r)}),DN.createWithPreprocess=(e,t,r)=>new DN({schema:t,effect:{type:"preprocess",transform:e},typeName:KN.ZodEffects,...FS(r)});class FN extends US{_parse(e){return this._getType(e)===SS.undefined?$S(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}FN.create=(e,t)=>new FN({innerType:e,typeName:KN.ZodOptional,...FS(t)});class UN extends US{_parse(e){return this._getType(e)===SS.null?$S(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}UN.create=(e,t)=>new UN({innerType:e,typeName:KN.ZodNullable,...FS(t)});class BN extends US{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===SS.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}BN.create=(e,t)=>new BN({innerType:e,typeName:KN.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...FS(t)});class qN extends US{_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 LS(n)?n.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new xS(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new xS(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}qN.create=(e,t)=>new qN({innerType:e,typeName:KN.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...FS(t)});class VN extends US{_parse(e){if(this._getType(e)!==SS.nan){const t=this._getOrReturnCtx(e);return CS(t,{code:kS.invalid_type,expected:SS.nan,received:t.parsedType}),OS}return{status:"valid",value:e.data}}}VN.create=e=>new VN({typeName:KN.ZodNaN,...FS(e)});class GN extends US{_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 HN extends US{_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?OS:"dirty"===e.status?(t.dirty(),IS(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?OS:"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 HN({in:e,out:t,typeName:KN.ZodPipeline})}}class WN extends US{_parse(e){const t=this._def.innerType._parse(e),r=e=>(RS(e)&&(e.value=Object.freeze(e.value)),e);return LS(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}var KN;WN.create=(e,t)=>new WN({innerType:e,typeName:KN.ZodReadonly,...FS(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"}(KN||(KN={}));const ZN=dN.create,JN=_N.create;SN.create,kN.create;const YN=PN.create;function XN(e,t){return xk(e.type._def,t)}EN.create,AN.create,ON.create,LN.create,jN.create,FN.create,UN.create;function QN(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(r=>QN(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 ek(e,t)}}const ek=(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 tk;const rk=/^[cC][^\s-]{8,}$/,nk=/^[0-9a-z]+$/,ak=/^[0-9A-HJKMNP-TV-Z]{26}$/,ik=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,sk=()=>(void 0===tk&&(tk=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),tk),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])$/,ck=/^(([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])$/,lk=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,uk=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dk=/^[a-zA-Z0-9_-]{21}$/,pk=/^[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":gk(r,"email",n.message,t);break;case"format:idn-email":gk(r,"idn-email",n.message,t);break;case"pattern:zod":yk(r,ik,n.message,t)}break;case"url":gk(r,"uri",n.message,t);break;case"uuid":gk(r,"uuid",n.message,t);break;case"regex":yk(r,n.regex,n.message,t);break;case"cuid":yk(r,rk,n.message,t);break;case"cuid2":yk(r,nk,n.message,t);break;case"startsWith":yk(r,RegExp(`^${hk(n.value,t)}`),n.message,t);break;case"endsWith":yk(r,RegExp(`${hk(n.value,t)}$`),n.message,t);break;case"datetime":gk(r,"date-time",n.message,t);break;case"date":gk(r,"date",n.message,t);break;case"time":gk(r,"time",n.message,t);break;case"duration":gk(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":yk(r,RegExp(hk(n.value,t)),n.message,t);break;case"ip":"v6"!==n.version&&gk(r,"ipv4",n.message,t),"v4"!==n.version&&gk(r,"ipv6",n.message,t);break;case"base64url":yk(r,uk,n.message,t);break;case"jwt":yk(r,pk,n.message,t);break;case"cidr":"v6"!==n.version&&yk(r,ok,n.message,t),"v4"!==n.version&&yk(r,ck,n.message,t);break;case"emoji":yk(r,sk(),n.message,t);break;case"ulid":yk(r,ak,n.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":gk(r,"binary",n.message,t);break;case"contentEncoding:base64":bS(r,"contentEncoding","base64",n.message,t);break;case"pattern:zod":yk(r,lk,n.message,t)}break;case"nanoid":yk(r,dk,n.message,t)}return r}function hk(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let r=0;r<e.length;r++)fk.has(e[r])||(t+="\\"),t+=e[r];return t}(e):e}const fk=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function gk(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 yk(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:vk(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):bS(e,"pattern",vk(t,n),r,n)}function vk(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===KN.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,n)=>({...r,[n]:xk(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??yS(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:xk(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===KN.ZodString&&e.keyType._def.checks?.length){const{type:n,...a}=mk(e.keyType._def,t);return{...r,propertyNames:a}}if(e.keyType?._def.typeName===KN.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===KN.ZodBranded&&e.keyType._def.type._def.typeName===KN.ZodString&&e.keyType._def.type._def.checks?.length){const{type:n,...a}=XN(e.keyType._def,t);return{...r,propertyNames:a}}return r}const _k={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};const wk=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,r)=>xk(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 Sk(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=Nk(s);o&&r&&("ZodOptional"===s._def.typeName&&(s=s._def.innerType),s.isNullable()||(s=s.nullable()),o=!1);const c=xk(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 xk(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 Nk(e){try{return e.isOptional()}catch{return!0}}const kk=(e,t,r)=>{switch(t){case KN.ZodString:return mk(e,r);case KN.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",vS(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 KN.ZodObject:return Sk(e,r);case KN.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 KN.ZodBoolean:return{type:"boolean"};case KN.ZodDate:return QN(e,r);case KN.ZodUndefined:return function(e){return{not:yS(e)}}(r);case KN.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(r);case KN.ZodArray:return function(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==KN.ZodAny&&(r.items=xk(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 KN.ZodUnion:case KN.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return wk(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(e=>e._def.typeName in _k&&(!e._def.checks||!e._def.checks.length))){const e=r.reduce((e,t)=>{const r=_k[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 wk(e,t)}(e,r);case KN.ZodIntersection:return function(e,t){const r=[xk(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),xk(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 KN.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,r)=>xk(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:xk(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,r)=>xk(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])}}(e,r);case KN.ZodRecord:return bk(e,r);case KN.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 KN.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case KN.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 KN.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:_k[e.innerType._def.typeName],nullable:!0}:{type:[_k[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const r=xk(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const r=xk(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}(e,r);case KN.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return xk(e.innerType._def,t);const r=xk(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:yS(t)},r]}:yS(t)})(e,r);case KN.ZodMap:return function(e,t){return"record"===t.mapStrategy?bk(e,t):{type:"array",maxItems:125,items:{type:"array",items:[xk(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||yS(t),xk(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||yS(t)],minItems:2,maxItems:2}}}(e,r);case KN.ZodSet:return function(e,t){const r={type:"array",uniqueItems:!0,items:xk(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 KN.ZodLazy:return()=>e.getter()._def;case KN.ZodPromise:return function(e,t){return xk(e.type._def,t)}(e,r);case KN.ZodNaN:case KN.ZodNever:return function(e){return"openAi"===e.target?void 0:{not:yS({...e,currentPath:[...e.currentPath,"not"]})}}(r);case KN.ZodEffects:return function(e,t){return"input"===t.effectStrategy?xk(e.schema._def,t):yS(t)}(e,r);case KN.ZodAny:return yS(r);case KN.ZodUnknown:return function(e){return yS(e)}(r);case KN.ZodDefault:return function(e,t){return{...xk(e.innerType._def,t),default:e.defaultValue()}}(e,r);case KN.ZodBranded:return XN(e,r);case KN.ZodReadonly:case KN.ZodCatch:return((e,t)=>xk(e.innerType._def,t))(e,r);case KN.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return xk(e.in._def,t);if("output"===t.pipeStrategy)return xk(e.out._def,t);const r=xk(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[r,xk(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]})].filter(e=>void 0!==e)}})(e,r);case KN.ZodFunction:case KN.ZodVoid:case KN.ZodSymbol:default:return}};function xk(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=Pk(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=kk(e,e.typeName,t),s="function"==typeof i?xk(i(),t):i;if(s&&Ek(e,t,s),t.postProcess){const r=t.postProcess(s,e,t);return a.jsonSchema=s,r}return a.jsonSchema=s,s}const Pk=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:gS(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`),yS(t)):"seen"===t.$refStrategy?yS(t):void 0}},Ek=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);function Ck(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(!Ck(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(!Ck(e[n],t[n]))return!1;return!0}return e===t}function Ak(e){return encodeURI(function(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}(e))}const Ok={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Ik={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},$k={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 Tk="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 zk(e,t=Object.create(null),r=Tk,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:zk(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($k[a])continue;const i=`${n}/${Ak(a)}`,s=e[a];if(Array.isArray(s)){if(Ok[a]){const e=s.length;for(let n=0;n<e;n++)zk(s[n],t,r,`${i}/${n}`)}}else if(Ik[a])for(let e in s)zk(s[e],t,r,`${i}/${Ak(e)}`);else zk(s,t,r,i)}return t}const Rk=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Lk=[0,31,28,31,30,31,30,31,31,30,31,30,31],Mk=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;function jk(e){return e.test.bind(e)}const Dk={date:Fk,time:Uk.bind(void 0,!1),"date-time":function(e){const t=e.split(Bk);return 2==t.length&&Fk(t[0])&&Uk(!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 qk.test(e)&&Vk.test(e)},"uri-reference":jk(/^(?:[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":jk(/^(?:(?:[^\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:jk(/^(?:(?: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:jk(/^(?=.{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:jk(/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/),ipv6:jk(/^((([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(Gk.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(e){return!1}},uuid:jk(/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i),"json-pointer":jk(/^(?:\/(?:[^~/]|~0|~1)*)*$/),"json-pointer-uri-fragment":jk(/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i),"relative-json-pointer":jk(/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/)};function Fk(e){const t=e.match(Rk);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:Lk[n])}function Uk(e,t){const r=t.match(Mk);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 Bk=/t|\s/i;const qk=/\/|:/,Vk=/^(?:[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 Gk=/[^\\]\\Z/;function Hk(e,t,r="2019-09",n=zk(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:P,patternProperties:E,additionalProperties:C,unevaluatedProperties:A,minProperties:O,maxProperties:I,propertyNames:$,dependentRequired:T,dependentSchemas:z,dependencies:R,prefixItems:L,items:M,additionalItems:j,unevaluatedItems:D,contains:F,minContains:U,maxContains:B,minItems:q,maxItems:V,uniqueItems:G,minimum:H,maximum:W,exclusiveMinimum:K,exclusiveMaximum:Z,multipleOf:J,minLength:Y,maxLength:X,pattern:Q,__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=Hk(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=Hk(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?Ck(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=>Ck(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`;Hk(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=Hk(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=Hk(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=Hk(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(Hk(e,S,r,n,a,i,s,t,c).valid){if(void 0!==N){const l=Hk(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=Hk(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!==O&&t.length<O&&re.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${o}/minProperties`,error:`Instance does not have at least ${O} properties.`}),void 0!==I&&t.length>I&&re.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${I} properties.`}),void 0!==$){const t=`${o}/propertyNames`;for(const o in e){const e=`${s}/${Ak(o)}`,c=Hk(o,$,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!==T){const t=`${o}/dependantRequired`;for(const r in T)if(r in e){const n=T[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=Hk(e,z[t],r,n,a,i,s,`${l}/${Ak(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=Hk(e,c,r,n,a,i,s,`${t}/${Ak(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!==P){const t=`${o}/properties`;for(const o in P){if(!(o in e))continue;const d=`${s}/${Ak(o)}`,p=Hk(e[o],P[o],r,n,a,i,d,`${t}/${Ak(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!==E){const t=`${o}/patternProperties`;for(const o in E){const d=new RegExp(o,"u"),p=E[o];for(const m in e){if(!d.test(m))continue;const h=`${s}/${Ak(m)}`,f=Hk(e[m],p,r,n,a,i,h,`${t}/${Ak(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}/${Ak(o)}`,u=Hk(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}/${Ak(o)}`,p=Hk(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!==q&&e.length<q&&re.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${o}/minItems`,error:`Array has too few items (${e.length} < ${q}).`});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=Hk(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=Hk(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=Hk(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!==j){const d=`${o}/additionalItems`;for(;l<t;l++){const t=Hk(e[l],j,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=Hk(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===B&&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!==B&&d>B&&re.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${B} items matching schema. ${d} items were found.`})}if(!u&&void 0!==D){const u=`${o}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;const t=Hk(e[l],D,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)&&Ck(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===K&&e<=H||e<H)&&re.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${e} is less than ${K?"or equal to ":""} ${H}.`}),void 0!==W&&(!0===Z&&e>=W||e>W)&&re.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${Z?"or equal to ":""} ${W}.`})):(void 0!==H&&e<H&&re.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${e} is less than ${H}.`}),void 0!==W&&e>W&&re.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${W}.`}),void 0!==K&&e<=K&&re.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${e} is less than ${K}.`}),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===X?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!==X&&t>X&&re.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${t} > ${X}).`}),void 0===Q||new RegExp(Q,"u").test(e)||re.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),void 0!==x&&Dk[x]&&!Dk[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 Wk{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",r=!0){this.schema=e,this.draft=t,this.shortCircuit=r,this.lookup=zk(e)}validate(e){return Hk(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),zk(e,this.lookup)}}function Kk(e){if(Mw(e)){const t=cS(e,!0);if(Xw(t)){return Rw(aS(t,!0))}return Rw(e)}return jw(e)?((e,t)=>{const r=fS(t);let n;const a=xk(e._def,r,!1)??yS(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 Zk(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=>Zk(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=>Zk(e))}if("not"in e)return!1;if("$ref"in e&&"string"==typeof e.$ref){const t=e.$ref,r=zk(e);return!!r[t]&&Zk(r[t])}return!1}Hh({},{Validator:()=>Wk,deepCompareStrict:()=>Ck,toJsonSchema:()=>Kk,validatesOnlyStrings:()=>Zk});function Jk(e,t){if(void 0!==e&&!dy(e))return e;if(!Q_(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 Yk(e){return Q_(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...Kk(e.data.schema),title:e.data.name}}}Hh({},{Graph:()=>Xk});var Xk=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]=dy(t.id)?r:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...Yk(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:Jk(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 Qk(this)}lastNode(){return ex(this)}extend(e,t=""){let r=t;const n=Object.values(e.nodes).map(e=>e.id);n.every(dy)&&(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&&Qk(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&ex(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 dy(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 pS(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 Qk(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 ex(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 tx(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.iterator]&&"function"==typeof e.next}function rx(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.asyncIterator]}function*nx(e,t){for(;;){const{value:r,done:n}=Qb.runWithConfig(i_(e),t.next.bind(t),!0);if(n)break;yield r}}async function*ax(e,t){const r=t[Symbol.asyncIterator]();for(;;){const{value:n,done:a}=await Qb.runWithConfig(i_(e),r.next.bind(t),!0);if(a)break;yield n}}function ix(e,t){return!e||Array.isArray(e)||e instanceof Date||"object"!=typeof e?{[t]:e}:e}var sx=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 lx({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 fx({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(n_);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)=>n_(0===n?e:r))}return Array.from({length:t},()=>n_(e))}async batch(e,t,r){const n=this._getOptionsList(t??{},e.length),a=n[0]?.maxConcurrency??r?.maxConcurrency,i=new Y_({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=n_(t),n=new d_({generator:this._streamIterator(e,r),config:r});return await n.setup,c_.fromAsyncGenerator(n)}_separateRunnableConfigFromCallOptions(e){let t;t=n_(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=n_(r),a=await e_(n),i=await(a?.handleChainStart(this.toJSON(),ix(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 s_(a,r?.signal)}catch(e){throw await(i?.handleChainError(e)),e}return await(i?.handleChainEnd(ix(s,"output"))),s}async _batchWithConfig(e,t,r,n){const a=this._getOptionsList(r??{},t.length),i=await Promise.all(a.map(e_)),s=await Promise.all(i.map(async(e,r)=>{const n=await(e?.handleChainStart(this.toJSON(),ix(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 s_(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(ix(o,"output")))),o}_concatOutputChunks(e,t){return u_(e,t)}async*_transformStreamWithConfig(e,t,r){let n,a,i=!0,s=!0;const o=n_(r),c=await e_(o),l=this;let u;try{const d=await p_(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(W_);let m=d.output;void 0!==p&&void 0!==u&&(m=p.tapOutputIterable(u.runId,m));const h=u?.handlers.find(D_);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:ix(n,"input")})),e}await(u?.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:ix(n,"input")}))}getGraph(e){const t=new Xk,r=t.addNode({name:`${this.getName()}Input`,schema:JN()}),n=t.addNode(this),a=t.addNode({name:`${this.getName()}Output`,schema:JN()});return t.addEdge(r,n),t.addEdge(n,a),t}pipe(e){return new ux({first:this,last:gx(e)})}pick(e){return this.pipe(new vx(e))}assign(e){return this.pipe(new yx(new dx({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,n_(t))}async*streamLog(e,t,r){const n=new B_({...r,autoClose:!1,_schemaFormat:"original"}),a=n_(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 M_({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 c_.fromReadableStream(r)}(n):c_.fromAsyncGenerator(n)}async*_streamEventsV2(e,t,r){const n=new K_({...r,autoClose:!1}),a=n_(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=n_(t),s=i.tags??[],o=i.metadata??{},c=i.runName??this.getName(),l=new B_({...r,autoClose:!1,_schemaFormat:"streaming_events"}),u=new ew({...r}),d=this._streamLog(e,l,i);for await(const t of d){if(n=n?n.concat(t):j_.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 Q_(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new ox({bound:this,config:{},configFactories:[n=>({callbacks:[new X_({config:n,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return function(e,t){const r=t.name??e.getName(),n=t.description??Kw(t.schema);return Jw(t.schema)?new bx({name:r,description:n,schema:YN({input:ZN()}).transform(e=>e.input),bound:e}):new bx({name:r,description:n,schema:t.schema,bound:e})}(this,e)}},ox=class e extends sx{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=t_(this.config,...e);return t_(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 lx({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(n_(e),this.kwargs))):await this._mergeConfig(n_(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(n_(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(n_(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(n_(t),this.kwargs))}streamEvents(e,t,r){const n=this;return c_.fromAsyncGenerator(async function*(){yield*n.bound.streamEvents(e,{...await n._mergeConfig(n_(t),n.kwargs),version:t.version},r)}())}static isRunnableBinding(e){return e.bound&&sx.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 X_({config:e,onStart:t,onEnd:r,onError:n})]})]})}},cx=class e extends sx{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,a_(t,{callbacks:r?.getChild()}))}withListeners({onStart:t,onEnd:r,onError:n}){return new e({bound:this.bound.withListeners({onStart:t,onEnd:r,onError:n})})}},lx=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 a_(t,{callbacks:r?.getChild(n)})}async _invoke(e,t,r){return fv(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 fv(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)}},ux=class e extends sx{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=n_(t),n=await e_(r),a=await(n?.handleChainStart(this.toJSON(),ix(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,a_(r,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${n+1}`)}));s=await s_(i,t?.signal)}if(t?.signal?.aborted)throw o_(t.signal);i=await this.last.invoke(s,a_(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(ix(i,"output"))),i}async batch(e,t,r){const n=this._getOptionsList(t??{},e.length),a=await Promise.all(n.map(e_)),i=await Promise.all(a.map(async(t,r)=>{const a=await(t?.handleChainStart(this.toJSON(),ix(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 a_(n[r],{callbacks:a})}),r);s=await s_(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(ix(s,"output")))),s}_concatOutputChunks(e,t){return this.last._concatOutputChunks(e,t)}async*_streamIterator(e,t){const r=await e_(t),{runId:n,...a}=t??{},i=await(r?.handleChainStart(this.toJSON(),ix(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}(),a_(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,a_(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(ix(o,"output")))}getGraph(e){const t=new Xk;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:gx(t),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&sx.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:gx(t),middle:r.slice(0,-1).map(gx),last:gx(r[r.length-1])})}},dx=class e extends sx{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]=gx(r)}static from(t){return new e({steps:t})}async invoke(e,t){const r=n_(t),n=await e_(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,a_(r,{callbacks:a?.getChild(`map:key:${t}`)}))});await s_(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=l_(e,Object.keys(n).length),i=new Map(Object.entries(n).map(([e,n],i)=>{const s=n.transform(a[i],a_(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 s_(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=n_(t),n=new d_({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,c_.fromAsyncGenerator(n)}},px=class e extends sx{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(e){if(super(e),!Tb(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 e_(r);return s_(this.func(a_(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(rx(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 sx{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(e){if(Tb(e.func))return px.from(e.func);super(e),function(e){if(Tb(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=a_(t,{callbacks:r?.getChild(),recursionLimit:(t?.recursionLimit??25)-1});Qb.runWithConfig(i_(i),async()=>{try{let r=await this.func(e,{...i});if(r&&sx.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(rx(r)){let e;for await(const n of ax(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(tx(r)){let e;for(const n of nx(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=a_(r,{callbacks:t?.getChild(),recursionLimit:(r?.recursionLimit??25)-1}),i=await new Promise((e,t)=>{Qb.runWithConfig(i_(a),async()=>{try{const t=await this.func(n,{...a,config:a});e(t)}catch(e){t(e)}})});if(i&&sx.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(rx(i))for await(const e of ax(a,i))r?.signal?.throwIfAborted(),yield e;else if(tx(i))for(const e of nx(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=n_(t),n=new d_({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,c_.fromAsyncGenerator(n)}},hx=class extends dx{},fx=class extends sx{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=n_(t),n=await e_(r),{runId:a,...i}=r,s=await(n?.handleChainStart(this.toJSON(),ix(e,"input"),a,void 0,void 0,void 0,i?.runName)),o=a_(i,{callbacks:s?.getChild()});return await Qb.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(ix(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=n_(t),n=await e_(r),{runId:a,...i}=r,s=await(n?.handleChainStart(this.toJSON(),ix(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=a_(i,{callbacks:s?.getChild()});try{c=ax(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(ix(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=>e_(e))),i=await Promise.all(a.map(async(t,r)=>{const a=await(t?.handleChainStart(this.toJSON(),ix(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)=>a_(n[t],{callbacks:e?.getChild()})),r);return await Promise.all(i.map((e,t)=>e?.handleChainEnd(ix(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 gx(e){if("function"==typeof e)return new mx({func:e});if(sx.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]=gx(n);return new dx({steps:t})}}var yx=class extends sx{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(e){e instanceof dx&&(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]=l_(e),s=this.mapper.transform(i,a_(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=n_(t),n=new d_({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,c_.fromAsyncGenerator(n)}},vx=class extends sx{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=n_(t),n=new d_({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,c_.fromAsyncGenerator(n)}},bx=class extends ox{name;description;schema;constructor(e){super({bound:ux.from([mx.from(async e=>{let t;if(Ug(e))try{t=await Gw(this.schema,e.args)}catch{throw new Bg("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 _x=(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 wx(e,t){return Array.isArray(e)?Sx(e,t):mx.from(t=>Sx(t,e))}function Sx(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&&_x(t,i)||o&&t.id&&o.includes(t.id)||(a||s||r?(r&&t.name&&r.some(e=>e===t.name)||a&&_x(t,a)||s&&t.id&&s.some(e=>e===t.id))&&c.push(t):c.push(t));return c}function Nx(e){return Array.isArray(e)?kx(e):mx.from(kx)}function kx(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=Yg(n),a=Yg(e),i=r.concat(a);"string"==typeof r.content&&"string"==typeof a.content&&(i.content=`${r.content}\n${a.content}`),t.push(Ox(i))}else t.push(e)}return t}function xx(e,t){if(Array.isArray(e)){const r=e;if(!t)throw new Error("Options parameter is required when providing messages.");return Px(r,t)}{const t=e;return mx.from(e=>Px(e,t)).withConfig({runName:"trim_messages"})}}async function Px(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=Ix;if(l&&(d="splitText"in l?l.splitText:async e=>l(e)),"first"===a)return Ex(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 Ax(e.getType(),t,Kf(e))});if(a){const e=Array.isArray(a)?a:[a];for(;o.length>0&&!_x(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 Ex(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 Ex(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=Ax(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&&!_x(o[c-1],e);)c-=1}return o.slice(0,c)}const Cx={human:{message:Ig,messageChunk:$g},ai:{message:bg,messageChunk:Sg},system:{message:Rg,messageChunk:Lg},developer:{message:Rg,messageChunk:Lg},tool:{message:tg,messageChunk:rg},function:{message:Eg,messageChunk:Cg},generic:{message:Ng,messageChunk:kg},remove:{message:Dg,messageChunk:Dg}};function Ax(e,t,r){let n,a;switch(e){case"human":r?n=new $g(t):a=new Ig(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 Sg(e)}else a=new bg(t);break;case"system":r?n=new Lg(t):a=new Rg(t);break;case"developer":r?n=new Lg({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}}):a=new Rg({...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 rg(t):a=new tg(t);break;case"function":if(r)n=new Cg(t);else{if(!t.name)throw new Error("FunctionMessage must have a 'name' field");a=new Eg(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 kg(t):a=new Ng(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 Ox(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 Cx&&(r=Ax(t,n)),!r)throw new Error(`Unrecognized message chunk class ${t}. Supported classes are ${Object.keys(Cx)}`);return r}function Ix(e){const t=e.split("\n");return Promise.resolve([...t.slice(0,-1).map(e=>`${e}\n`),t[t.length-1]])}const $x=["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"];Hh({},{AIMessage:()=>bg,AIMessageChunk:()=>Sg,BaseMessage:()=>Ff,BaseMessageChunk:()=>Gf,ChatMessage:()=>Ng,ChatMessageChunk:()=>kg,FunctionMessage:()=>Eg,FunctionMessageChunk:()=>Cg,HumanMessage:()=>Ig,HumanMessageChunk:()=>$g,KNOWN_BLOCK_TYPES:()=>$x,RemoveMessage:()=>Dg,SystemMessage:()=>Rg,SystemMessageChunk:()=>Lg,ToolMessage:()=>tg,ToolMessageChunk:()=>rg,_isMessageFieldWithRole:()=>Hf,_mergeDicts:()=>Bf,_mergeLists:()=>qf,_mergeObj:()=>Vf,_mergeStatus:()=>Df,coerceMessageLikeToMessage:()=>Hg,convertToChunk:()=>Yg,convertToOpenAIImageBlock:()=>Xh,convertToProviderContentBlock:()=>tf,defaultTextSplitter:()=>Ix,defaultToolCallParser:()=>ng,filterMessages:()=>wx,getBufferString:()=>Wg,iife:()=>qg,isAIMessage:()=>_g,isAIMessageChunk:()=>wg,isBase64ContentBlock:()=>Zh,isBaseMessage:()=>Wf,isBaseMessageChunk:()=>Kf,isChatMessage:()=>xg,isChatMessageChunk:()=>Pg,isDataContentBlock:()=>Wh,isDirectToolOutput:()=>eg,isFunctionMessage:()=>Ag,isFunctionMessageChunk:()=>Og,isHumanMessage:()=>Tg,isHumanMessageChunk:()=>zg,isIDContentBlock:()=>Yh,isMessage:()=>rf,isOpenAIToolCallArray:()=>Uf,isPlainTextContentBlock:()=>Jh,isSystemMessage:()=>Mg,isSystemMessageChunk:()=>jg,isToolMessage:()=>ag,isToolMessageChunk:()=>ig,isURLContentBlock:()=>Kh,mapChatMessagesToStoredMessages:()=>Jg,mapStoredMessageToChatMessage:()=>Kg,mapStoredMessagesToChatMessages:()=>Zg,mergeContent:()=>jf,mergeMessageRuns:()=>Nx,mergeResponseMetadata:()=>Zf,mergeUsageMetadata:()=>Qf,parseBase64DataUrl:()=>ef,parseMimeType:()=>Qh,trimMessages:()=>xx});const Tx=e=>e();function zx(e){return!!e&&(!!/^o\d/.test(e??"")||!(!e.startsWith("gpt-5")||e.startsWith("gpt-5-chat")))}function Rx(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(!Ng.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 Lx(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 Mx(e){return"undefined"!=typeof Headers&&null!==e&&"object"==typeof e&&"[object Headers]"===Object.prototype.toString.call(e)}function jx(e){const t=Tx(()=>{if(Mx(e))return e;if(Array.isArray(e))return new Headers(e);if("object"==typeof e&&null!==e&&"values"in e&&Mx(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 Dx(e){return void 0!==e&&Array.isArray(e.lc_namespace)}function Fx(e){return void 0!==e&&sx.isRunnable(e)&&"lc_name"in e.constructor&&"function"==typeof e.constructor.lc_name&&"RunnableToolLike"===e.constructor.lc_name()}function Ux(e){return!!e&&"object"==typeof e&&"name"in e&&"schema"in e&&(Fw(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 Bx(e){return Ux(e)||Fx(e)||Dx(e)}Hh({},{extendInteropZodObject:()=>rS,getInteropZodDefaultGetter:()=>sS,getInteropZodObjectShape:()=>tS,getSchemaDescription:()=>Kw,interopParse:()=>Ww,interopParseAsync:()=>Gw,interopSafeParse:()=>Hw,interopSafeParseAsync:()=>Vw,interopZodObjectMakeFieldsOptional:()=>lS,interopZodObjectPartial:()=>nS,interopZodObjectPassthrough:()=>iS,interopZodObjectStrict:()=>aS,interopZodTransformInputSchema:()=>cS,isInteropZodLiteral:()=>qw,isInteropZodObject:()=>eS,isInteropZodSchema:()=>Fw,isShapelessZodSchema:()=>Zw,isSimpleStringZodSchema:()=>Jw,isZodArrayV4:()=>Qw,isZodLiteralV3:()=>Uw,isZodLiteralV4:()=>Bw,isZodObjectV3:()=>Yw,isZodObjectV4:()=>Xw,isZodSchema:()=>Dw,isZodSchemaV3:()=>jw,isZodSchemaV4:()=>Mw});function qx(e,t){const r="number"==typeof t?void 0:t;return{name:e.name,description:e.description,parameters:Kk(e.schema),...void 0!==r?.strict?{strict:r.strict}:{}}}function Vx(e,t){const r="number"==typeof t?void 0:t;let n;return n=Bx(e)?{type:"function",function:qx(e)}:e,void 0!==r?.strict&&(n.function.strict=r.strict),n}function Gx(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}: ${Hx(a,t)},`):r.push(`${n}?: ${Hx(a,t)},`);return r.map(e=>" ".repeat(t)+e).join("\n")}function Hx(e,t){if(void 0!==(r=e).anyOf&&Array.isArray(r.anyOf))return e.anyOf.map(e=>Hx(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["{",Gx(e,t+2),"}"].join("\n");case"array":return e.items?`${Hx(e.items,t)}[]`:"any[]";default:return""}}function Wx(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 Kx(e){return"type"in e&&"function"!==e.type}function Zx(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 Jx(e){return"type"in e&&"custom"===e.type&&"custom"in e&&"object"==typeof e.custom&&null!==e.custom}function Yx(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 Xx(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 Qx(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}Hh({},{convertToOpenAIFunction:()=>qx,convertToOpenAITool:()=>Vx,isLangChainTool:()=>Bx,isRunnableToolLike:()=>Fx,isStructuredTool:()=>Dx,isStructuredToolParams:()=>Ux});const eP=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 tP extends Error{}class rP extends tP{constructor(e,t,r,n){super(`${rP.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 aP({message:r,cause:eP(t)});const a=t?.error;return 400===e?new sP(e,a,r,n):401===e?new oP(e,a,r,n):403===e?new cP(e,a,r,n):404===e?new lP(e,a,r,n):409===e?new uP(e,a,r,n):422===e?new dP(e,a,r,n):429===e?new pP(e,a,r,n):e>=500?new mP(e,a,r,n):new rP(e,a,r,n)}}class nP extends rP{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class aP extends rP{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class iP extends aP{constructor({message:e}={}){super({message:e??"Request timed out."})}}class sP extends rP{}class oP extends rP{}class cP extends rP{}class lP extends rP{}class uP extends rP{}class dP extends rP{}class pP extends rP{}class mP extends rP{}class hP extends tP{constructor(){super("Could not parse response content as the length limit was reached")}}class fP extends tP{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class gP extends Error{constructor(e){super(e)}}function yP(e){return void 0!==e&&"function"in e&&void 0!==e.function}function vP(e){return"auto-parseable-response-format"===e?.$brand}function bP(e){return"auto-parseable-tool"===e?.$brand}function _P(e,t){const r=e.choices.map(e=>{if("length"===e.finish_reason)throw new hP;if("content_filter"===e.finish_reason)throw new fP;return kP(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=>yP(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:bP(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?wP(t,e.message.content):null}}});return{...e,choices:r}}function wP(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 SP(e,t){if(!e||!("tools"in e)||!e.tools)return!1;const r=e.tools?.find(e=>yP(e)&&e.function?.name===t.function.name);return yP(r)&&(bP(r)||r?.function.strict||!1)}function NP(e){return!!vP(e.response_format)||(e.tools?.some(e=>bP(e)||"function"===e.type&&!0===e.function.strict)??!1)}function kP(e){for(const t of e||[])if("function"!==t.type)throw new tP(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}const xP=Symbol("Let zodToJsonSchema decide on which parser to use"),PP={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"},EP=e=>"_def"in e?e._def:e;const CP=e=>{const t=(e=>"string"==typeof e?{...PP,basePath:["#"],definitions:{},name:e}:{...PP,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])=>[EP(r),{def:EP(r),path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function AP(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function OP(e,t,r,n,a){e[t]=r,AP(e,t,n,a)}function IP(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((r,n)=>IP(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 $P(e,t)}}const $P=(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":OP(r,"minimum",n.value,n.message,t);break;case"max":OP(r,"maximum",n.value,n.message,t)}return r};let TP;const zP=/^[cC][^\s-]{8,}$/,RP=/^[0-9a-z]+$/,LP=/^[0-9A-HJKMNP-TV-Z]{26}$/,MP=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,jP=()=>(void 0===TP&&(TP=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),TP),DP=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,FP=/^[a-zA-Z0-9_-]{21}$/;function UP(e,t){const r={type:"string"};function n(e){return"escape"===t.patternStrategy?BP(e):e}if(e.checks)for(const a of e.checks)switch(a.kind){case"min":OP(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,a.value):a.value,a.message,t);break;case"max":OP(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":qP(r,"email",a.message,t);break;case"format:idn-email":qP(r,"idn-email",a.message,t);break;case"pattern:zod":VP(r,MP,a.message,t)}break;case"url":qP(r,"uri",a.message,t);break;case"uuid":qP(r,"uuid",a.message,t);break;case"regex":VP(r,a.regex,a.message,t);break;case"cuid":VP(r,zP,a.message,t);break;case"cuid2":VP(r,RP,a.message,t);break;case"startsWith":VP(r,RegExp(`^${n(a.value)}`),a.message,t);break;case"endsWith":VP(r,RegExp(`${n(a.value)}$`),a.message,t);break;case"datetime":qP(r,"date-time",a.message,t);break;case"date":qP(r,"date",a.message,t);break;case"time":qP(r,"time",a.message,t);break;case"duration":qP(r,"duration",a.message,t);break;case"length":OP(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,a.value):a.value,a.message,t),OP(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,a.value):a.value,a.message,t);break;case"includes":VP(r,RegExp(n(a.value)),a.message,t);break;case"ip":"v6"!==a.version&&qP(r,"ipv4",a.message,t),"v4"!==a.version&&qP(r,"ipv6",a.message,t);break;case"emoji":VP(r,jP,a.message,t);break;case"ulid":VP(r,LP,a.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":qP(r,"binary",a.message,t);break;case"contentEncoding:base64":OP(r,"contentEncoding","base64",a.message,t);break;case"pattern:zod":VP(r,DP,a.message,t)}break;case"nanoid":VP(r,FP,a.message,t)}return r}const BP=e=>Array.from(e).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),qP=(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}}})):OP(e,"format",t,r,n)},VP=(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:GP(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):OP(e,"pattern",GP(t,n),r,n)},GP=(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 HP(e,t){if("openApi3"===t.target&&e.keyType?._def.typeName===KN.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,n)=>({...r,[n]:JP(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??{}}),{}),additionalProperties:!1};const r={type:"object",additionalProperties:JP(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??{}};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===KN.ZodString&&e.keyType._def.checks?.length){const n=Object.entries(UP(e.keyType._def,t)).reduce((e,[t,r])=>"type"===t?e:{...e,[t]:r},{});return{...r,propertyNames:n}}return e.keyType?._def.typeName===KN.ZodEnum?{...r,propertyNames:{enum:e.keyType._def.values}}:r}const WP={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};const KP=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,r)=>JP(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 ZP(e,t){return"strict"===t.removeAdditionalStrategy?"ZodNever"===e.catchall._def.typeName?"strict"!==e.unknownKeys:JP(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0:"ZodNever"===e.catchall._def.typeName?"passthrough"===e.unknownKeys:JP(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0}function JP(e,t,r=!1){const n=t.seen.get(e);if(t.override){const a=t.override?.(e,t,n,r);if(a!==xP)return a}if(n&&!r){const e=YP(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=QP(e,e.typeName,t,r);return i&&eE(e,t,i),a.jsonSchema=i,i}const YP=(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:XP(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}},XP=(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("/")},QP=(e,t,r,n)=>{switch(t){case KN.ZodString:return UP(e,r);case KN.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",AP(r,"type",n.message,t);break;case"min":"jsonSchema7"===t.target?n.inclusive?OP(r,"minimum",n.value,n.message,t):OP(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),OP(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?OP(r,"maximum",n.value,n.message,t):OP(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),OP(r,"maximum",n.value,n.message,t));break;case"multipleOf":OP(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case KN.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=JP(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:ZP(e,t)};return r.required.length||delete r.required,r}(e,r);case KN.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?OP(r,"minimum",n.value,n.message,t):OP(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),OP(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?OP(r,"maximum",n.value,n.message,t):OP(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),OP(r,"maximum",n.value,n.message,t));break;case"multipleOf":OP(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case KN.ZodBoolean:return{type:"boolean"};case KN.ZodDate:return IP(e,r);case KN.ZodUndefined:return{not:{}};case KN.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(r);case KN.ZodArray:return function(e,t){const r={type:"array"};return e.type?._def?.typeName!==KN.ZodAny&&(r.items=JP(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&OP(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&OP(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(OP(r,"minItems",e.exactLength.value,e.exactLength.message,t),OP(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}(e,r);case KN.ZodUnion:case KN.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return KP(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(e=>e._def.typeName in WP&&(!e._def.checks||!e._def.checks.length))){const e=r.reduce((e,t)=>{const r=WP[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 KP(e,t)}(e,r);case KN.ZodIntersection:return function(e,t){const r=[JP(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),JP(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 KN.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,r)=>JP(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:JP(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,r)=>JP(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])}}(e,r);case KN.ZodRecord:return HP(e,r);case KN.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 KN.ZodEnum:return function(e){return{type:"string",enum:[...e.values]}}(e);case KN.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 KN.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:WP[e.innerType._def.typeName],nullable:!0}:{type:[WP[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const r=JP(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const r=JP(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}(e,r);case KN.ZodOptional:return((e,t)=>{if(t.propertyPath&&t.currentPath.slice(0,t.propertyPath.length).toString()===t.propertyPath.toString())return JP(e.innerType._def,{...t,currentPath:t.currentPath});const r=JP(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}})(e,r);case KN.ZodMap:return function(e,t){return"record"===t.mapStrategy?HP(e,t):{type:"array",maxItems:125,items:{type:"array",items:[JP(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},JP(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}}}(e,r);case KN.ZodSet:return function(e,t){const r={type:"array",uniqueItems:!0,items:JP(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&OP(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&OP(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}(e,r);case KN.ZodLazy:return JP(e.getter()._def,r);case KN.ZodPromise:return function(e,t){return JP(e.type._def,t)}(e,r);case KN.ZodNaN:case KN.ZodNever:return{not:{}};case KN.ZodEffects:return function(e,t,r){return"input"===t.effectStrategy?JP(e.schema._def,t,r):{}}(e,r,n);case KN.ZodAny:case KN.ZodUnknown:return{};case KN.ZodDefault:return function(e,t){return{...JP(e.innerType._def,t),default:e.defaultValue()}}(e,r);case KN.ZodBranded:return function(e,t){return JP(e.type._def,t)}(e,r);case KN.ZodReadonly:case KN.ZodCatch:return((e,t)=>JP(e.innerType._def,t))(e,r);case KN.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return JP(e.in._def,t);if("output"===t.pipeStrategy)return JP(e.out._def,t);const r=JP(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[r,JP(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]})].filter(e=>void 0!==e)}})(e,r);case KN.ZodFunction:case KN.ZodVoid:case KN.ZodSymbol:default:return}},eE=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);function tE(e,t){return t&&function(e){if(vP(e.text?.format))return!0;return!1}(t)?rE(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 rE(e,t){const r=e.output.map(e=>{if("function_call"===e.type)return{...e,parsed_arguments:iE(t,e)};if("message"===e.type){const r=e.content.map(e=>"output_text"===e.type?{...e,parsed:nE(t,e.text)}:e);return{...e,content:r}}return e}),n=Object.assign({},e,{output:r});return Object.getOwnPropertyDescriptor(e,"output_text")||sE(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 nE(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 aE(e){return"auto-parseable-tool"===e?.$brand}function iE(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:aE(r)?r.$parseRaw(t.arguments):r?.strict?JSON.parse(t.arguments):null}}function sE(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 oE(e,t){return((e,t)=>{const r=CP(t),n="string"==typeof t?t:"title"===t?.nameStrategy?void 0:t?.name,a=JP(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]=JP(EP(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 cE(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:oE(e,{name:t})}},t=>e.parse(JSON.parse(t)))}const lE=["jsonSchema","functionCalling","jsonMode"];function uE(e,t,r){if(jw(e))return cE(e,t,r);if(Mw(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:Rw(e,{cycles:"ref",reused:"ref",override(e){e.jsonSchema.title=t}})}},t=>ww(e,JSON.parse(t)));throw new Error("Unsupported schema response format")}function dE(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 pE(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 mE(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 hE=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return hE=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 fE=/^[a-z][a-z0-9+.-]*:/i;let gE=e=>(gE=Array.isArray,gE(e)),yE=gE;function vE(e){return"object"!=typeof e?{}:e??{}}function bE(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}const _E=e=>new Promise(t=>setTimeout(t,e)),wE="6.6.0";const SE=()=>{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":wE,"X-Stainless-OS":kE(Deno.build.os),"X-Stainless-Arch":NE(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":wE,"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":wE,"X-Stainless-OS":kE(globalThis.process.platform??"unknown"),"X-Stainless-Arch":NE(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":wE,"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":wE,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const NE=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",kE=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 xE;function PE(...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 EE(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return PE({start(){},async pull(e){const{done:r,value:n}=await t.next();r?e.close():e.enqueue(n)},async cancel(){await(t.return?.())}})}function CE(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 AE=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),OE="RFC3986",IE=e=>String(e),$E={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:IE};let TE=(e,t)=>(TE=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),TE(e,t));const zE=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),RE=1024;function LE(e,t){if(gE(e)){const r=[];for(let n=0;n<e.length;n+=1)r.push(t(e[n]));return r}return t(e)}const ME={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},jE=function(e,t){Array.prototype.push.apply(e,gE(t)?t:[t])};let DE;const FE={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+=RE){const t=i.length>=RE?i.slice(e,e+RE):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]=zE[n]:n<2048?r[r.length]=zE[192|n>>6]+zE[128|63&n]:n<55296||n>=57344?r[r.length]=zE[224|n>>12]+zE[128|n>>6&63]+zE[128|63&n]:(e+=1,n=65536+((1023&n)<<10|1023&t.charCodeAt(e)),r[r.length]=zE[240|n>>18]+zE[128|n>>12&63]+zE[128|n>>6&63]+zE[128|63&n])}s+=r.join("")}return s},encodeValuesOnly:!1,format:OE,formatter:IE,indices:!1,serializeDate:e=>(DE??(DE=Function.prototype.call.bind(Date.prototype.toISOString)))(e),skipNulls:!1,strictNullHandling:!1};const UE={};function BE(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(UE))&&!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(UE)&&(_=0)}if("function"==typeof l?v=l(t,v):v instanceof Date?v=p?.(v):"comma"===r&&gE(v)&&(v=LE(v,function(e){return e instanceof Date?p?.(e):e})),null===v){if(i)return c&&!f?c(t,FE.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,FE.encoder,g,"key",m);return[h?.(e)+"="+h?.(c(v,FE.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&&gE(v))f&&c&&(v=LE(v,c)),k=[{value:v.length>0?v.join(",")||null:void 0}];else if(gE(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),P=n&&gE(v)&&1===v.length?x+"[]":x;if(a&&gE(v)&&0===v.length)return P+"[]";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=gE(v)?"function"==typeof r?r(P,S):P:P+(d?"."+S:"["+S+"]");y.set(e,_);const E=new WeakMap;E.set(UE,y),jE(N,BE(w,x,r,n,a,i,s,o,"comma"===r&&f&&gE(v)?null:c,l,u,d,p,m,h,f,g,E))}return N}function qE(e,t={}){let r=e;const n=function(e=FE){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||FE.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=OE;if(void 0!==e.format){if(!TE($E,e.format))throw new TypeError("Unknown format option provided.");r=e.format}const n=$E[r];let a,i=FE.filter;if(("function"==typeof e.filter||gE(e.filter))&&(i=e.filter),a=e.arrayFormat&&e.arrayFormat in ME?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":FE.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||FE.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:FE.addQueryPrefix,allowDots:s,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:FE.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:FE.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?FE.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:FE.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:FE.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:FE.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:FE.encodeValuesOnly,filter:i,format:r,formatter:n,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:FE.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:FE.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:FE.strictNullHandling}}(t);let a,i;"function"==typeof n.filter?(i=n.filter,r=i("",r)):gE(n.filter)&&(i=n.filter,a=i);const s=[];if("object"!=typeof r||null===r)return"";const o=ME[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]||jE(s,BE(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 VE,GE;function HE(e){let t;return(VE??(t=new globalThis.TextEncoder,VE=t.encode.bind(t)))(e)}function WE(e){let t;return(GE??(t=new globalThis.TextDecoder,GE=t.decode.bind(t)))(e)}var KE,ZE;class JE{constructor(){KE.set(this,void 0),ZE.set(this,void 0),pE(this,KE,new Uint8Array),pE(this,ZE,null)}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?HE(e):e;pE(this,KE,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}([mE(this,KE,"f"),t]));const r=[];let n;for(;null!=(n=YE(mE(this,KE,"f"),mE(this,ZE,"f")));){if(n.carriage&&null==mE(this,ZE,"f")){pE(this,ZE,n.index);continue}if(null!=mE(this,ZE,"f")&&(n.index!==mE(this,ZE,"f")+1||n.carriage)){r.push(WE(mE(this,KE,"f").subarray(0,mE(this,ZE,"f")-1))),pE(this,KE,mE(this,KE,"f").subarray(mE(this,ZE,"f"))),pE(this,ZE,null);continue}const e=null!==mE(this,ZE,"f")?n.preceding-1:n.preceding,t=WE(mE(this,KE,"f").subarray(0,e));r.push(t),pE(this,KE,mE(this,KE,"f").subarray(n.index)),pE(this,ZE,null)}return r}flush(){return mE(this,KE,"f").length?this.decode("\n"):[]}}function YE(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 XE(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}KE=new WeakMap,ZE=new WeakMap,JE.NEWLINE_CHARS=new Set(["\n","\r"]),JE.NEWLINE_REGEXP=/\r\n|[\n\r]/g;const QE={off:0,error:200,warn:300,info:400,debug:500},eC=(e,t,r)=>{if(e)return function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(QE,e)?e:void iC(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(QE))}`)};function tC(){}function rC(e,t,r){return!t||QE[e]>QE[r]?tC:t[e].bind(t)}const nC={error:tC,warn:tC,info:tC,debug:tC};let aC=new WeakMap;function iC(e){const t=e.logger,r=e.logLevel??"off";if(!t)return nC;const n=aC.get(t);if(n&&n[0]===r)return n[1];const a={error:rC("error",t,r),warn:rC("warn",t,r),info:rC("info",t,r),debug:rC("debug",t,r)};return aC.set(t,[r,a]),a}const sC=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,cC,lC;class uC{constructor(e,t,r){this.iterator=e,oC.set(this,void 0),this.controller=t,pE(this,oC,r)}static fromSSEResponse(e,t,r){let n=!1;const a=r?iC(r):console;return new uC(async function*(){if(n)throw new tP("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 tP("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 tP("Attempted to iterate over a response with no body")}const r=new dC,n=new JE,a=CE(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?HE(r):r;let n,a=new Uint8Array(t.length+e.length);for(a.set(t),a.set(e,t.length),t=a;-1!==(n=XE(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 rP(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 rP(void 0,t.error,void 0,e.headers);yield t}r=!0}catch(e){if(Qx(e))return;throw e}finally{r||t.abort()}},t,r)}static fromReadableStream(e,t,r){let n=!1;return new uC(async function*(){if(n)throw new tP("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 JE,r=CE(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(Qx(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 uC(()=>n(e),this.controller,mE(this,oC,"f")),new uC(()=>n(t),this.controller,mE(this,oC,"f"))]}toReadableStream(){const e=this;let t;return PE({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=HE(JSON.stringify(r)+"\n");e.enqueue(a)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}class dC{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 pC(e,t){const{response:r,requestLogID:n,retryOfRequestLogID:a,startTime:i}=t,s=await(async()=>{if(t.options.stream)return iC(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(r,t.controller,e):uC.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 iC(e).debug(`[${n}] response parsed`,sC({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 hC extends Promise{constructor(e,t,r=pC){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=r,cC.set(this,void 0),pE(this,cC,e)}_thenUnwrap(e){return new hC(mE(this,cC,"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(mE(this,cC,"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)}}cC=new WeakMap;class fC{constructor(e,t,r,n){lC.set(this,void 0),pE(this,lC,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 tP("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await mE(this,lC,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(lC=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class gC extends hC{constructor(e,t,r){super(e,t,async(e,t)=>new r(e,t.response,await pC(e,t),t.options))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}class yC extends fC{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 vC extends fC{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:{...vE(this.options.query),after:t}}:null}}class bC extends fC{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:{...vE(this.options.query),after:e}}:null}}const _C=()=>{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 wC(e,t,r){return _C(),new File(e,t??"unknown_file",r)}function SC(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 NC=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],kC=async(e,t)=>AC(e.body)?{...e,body:await EC(e.body,t)}:e,xC=async(e,t)=>({...e,body:await EC(e.body,t)}),PC=new WeakMap;const EC=async(e,t)=>{if(!await function(e){const t="function"==typeof e?e:e.fetch,r=PC.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 PC.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])=>OC(r,e,t))),r},CC=e=>e instanceof Blob&&"name"in e,AC=e=>{if((e=>"object"==typeof e&&null!==e&&(e instanceof Response||NC(e)||CC(e)))(e))return!0;if(Array.isArray(e))return e.some(AC);if(e&&"object"==typeof e)for(const t in e)if(AC(e[t]))return!0;return!1},OC=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,wC([await r.blob()],SC(r)));else if(NC(r))e.append(t,wC([await new Response(EE(r)).blob()],SC(r)));else if(CC(r))e.append(t,r,SC(r));else if(Array.isArray(r))await Promise.all(r.map(r=>OC(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])=>OC(e,`${t}[${r}]`,n)))}}},IC=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 $C(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(IC(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else{if(!NC(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 $C(r))}return t}class TC{constructor(e){this._client=e}}function zC(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const RC=Object.freeze(Object.create(null)),LC=(e=zC)=>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??RC)??RC)?.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 tP(`Path parameters result in path with invalid segments:\n${a.map(e=>e.error).join("\n")}\n${i}\n${t}`)}return i},MC=LC(zC);let jC=class extends TC{list(e,t={},r){return this._client.getAPIList(MC`/chat/completions/${e}/messages`,vC,{query:t,...r})}};const DC=e=>"assistant"===e?.role,FC=e=>"tool"===e?.role;var UC,BC,qC,VC,GC,HC,WC,KC,ZC,JC,YC,XC,QC,eA,tA,rA,nA,aA,iA,sA,oA;class cA{constructor(){UC.add(this),this.controller=new AbortController,BC.set(this,void 0),qC.set(this,()=>{}),VC.set(this,()=>{}),GC.set(this,void 0),HC.set(this,()=>{}),WC.set(this,()=>{}),KC.set(this,{}),ZC.set(this,!1),JC.set(this,!1),YC.set(this,!1),XC.set(this,!1),pE(this,BC,new Promise((e,t)=>{pE(this,qC,e),pE(this,VC,t)})),pE(this,GC,new Promise((e,t)=>{pE(this,HC,e),pE(this,WC,t)})),mE(this,BC,"f").catch(()=>{}),mE(this,GC,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},mE(this,UC,"m",QC).bind(this))},0)}_connected(){this.ended||(mE(this,qC,"f").call(this),this._emit("connect"))}get ended(){return mE(this,ZC,"f")}get errored(){return mE(this,JC,"f")}get aborted(){return mE(this,YC,"f")}abort(){this.controller.abort()}on(e,t){return(mE(this,KC,"f")[e]||(mE(this,KC,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=mE(this,KC,"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(mE(this,KC,"f")[e]||(mE(this,KC,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{pE(this,XC,!0),"error"!==e&&this.once("error",r),this.once(e,t)})}async done(){pE(this,XC,!0),await mE(this,GC,"f")}_emit(e,...t){if(mE(this,ZC,"f"))return;"end"===e&&(pE(this,ZC,!0),mE(this,HC,"f").call(this));const r=mE(this,KC,"f")[e];if(r&&(mE(this,KC,"f")[e]=r.filter(e=>!e.once),r.forEach(({listener:e})=>e(...t))),"abort"===e){const e=t[0];return mE(this,XC,"f")||r?.length||Promise.reject(e),mE(this,VC,"f").call(this,e),mE(this,WC,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];mE(this,XC,"f")||r?.length||Promise.reject(e),mE(this,VC,"f").call(this,e),mE(this,WC,"f").call(this,e),this._emit("end")}}_emitFinal(){}}function lA(e){return"function"==typeof e.parse}BC=new WeakMap,qC=new WeakMap,VC=new WeakMap,GC=new WeakMap,HC=new WeakMap,WC=new WeakMap,KC=new WeakMap,ZC=new WeakMap,JC=new WeakMap,YC=new WeakMap,XC=new WeakMap,UC=new WeakSet,QC=function(e){if(pE(this,JC,!0),e instanceof Error&&"AbortError"===e.name&&(e=new nP),e instanceof nP)return pE(this,YC,!0),this._emit("abort",e);if(e instanceof tP)return this._emit("error",e);if(e instanceof Error){const t=new tP(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new tP(String(e)))};const uA=10;class dA extends cA{constructor(){super(...arguments),eA.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),FC(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(DC(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 tP("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),mE(this,eA,"m",tA).call(this)}async finalMessage(){return await this.done(),mE(this,eA,"m",rA).call(this)}async finalFunctionToolCall(){return await this.done(),mE(this,eA,"m",nA).call(this)}async finalFunctionToolCallResult(){return await this.done(),mE(this,eA,"m",aA).call(this)}async totalUsage(){return await this.done(),mE(this,eA,"m",iA).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=mE(this,eA,"m",rA).call(this);t&&this._emit("finalMessage",t);const r=mE(this,eA,"m",tA).call(this);r&&this._emit("finalContent",r);const n=mE(this,eA,"m",nA).call(this);n&&this._emit("finalFunctionToolCall",n);const a=mE(this,eA,"m",aA).call(this);null!=a&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(e=>e.usage)&&this._emit("totalUsage",mE(this,eA,"m",iA).call(this))}async _createChatCompletion(e,t,r){const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),mE(this,eA,"m",sA).call(this,t);const a=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(_P(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=uA}=r||{},l=t.tools.map(e=>{if(bP(e)){if(!e.$callback)throw new tP("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 tP("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=lA(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=mE(this,eA,"m",oA).call(this,c);if(this._addMessage({role:n,tool_call_id:t,content:l}),o)return}}}}eA=new WeakSet,tA=function(){return mE(this,eA,"m",rA).call(this).content??null},rA=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(DC(t)){return{...t,content:t.content??null,refusal:t.refusal??null}}}throw new tP("stream ended without producing a ChatCompletionMessage with role=assistant")},nA=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(DC(t)&&t?.tool_calls?.length)return t.tool_calls.filter(e=>"function"===e.type).at(-1)?.function}},aA=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(FC(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}},iA=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},sA=function(e){if(null!=e.n&&e.n>1)throw new tP("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 pA extends dA{static runTools(e,t,r){const n=new pA,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),DC(e)&&e.content&&this._emit("content",e.content)}}const mA=1,hA=2,fA=4,gA=8,yA=16,vA=32,bA=64,_A=128,wA=256,SA=511;class NA extends Error{}class kA extends Error{}const xA=(e,t)=>{const r=e.length;let n=0;const a=e=>{throw new NA(`${e} at position ${n}`)},i=e=>{throw new kA(`${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)||yA&t&&r-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):"true"===e.substring(n,n+4)||vA&t&&r-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):"false"===e.substring(n,n+5)||vA&t&&r-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):"Infinity"===e.substring(n,n+8)||_A&t&&r-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):"-Infinity"===e.substring(n,n+9)||wA&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&&gA&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(gA&t)return i;throw e}d(),","===e[n]&&n++}}catch(e){if(gA&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(fA&t)return r;a("Expected ']' at end of array")}return n++,r},u=()=>{if(0===n){"-"===e&&hA&t&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(r){if(hA&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||hA&t||a("Unterminated number literal");try{return JSON.parse(e.substring(s,n))}catch(r){"-"===e.substring(s,n)&&hA&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()},PA=e=>function(e,t=SA){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return xA(e.trim(),t)}(e,SA^hA);var EA,CA,AA,OA,IA,$A,TA,zA,RA,LA,MA,jA;class DA extends dA{constructor(e){super(),EA.add(this),CA.set(this,void 0),AA.set(this,void 0),OA.set(this,void 0),pE(this,CA,e),pE(this,AA,[])}get currentChatCompletionSnapshot(){return mE(this,OA,"f")}static fromReadableStream(e){const t=new DA(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){const n=new DA(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())),mE(this,EA,"m",IA).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)mE(this,EA,"m",TA).call(this,e);if(a.controller.signal?.aborted)throw new nP;return this._addChatCompletion(mE(this,EA,"m",LA).call(this))}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),mE(this,EA,"m",IA).call(this),this._connected();const n=uC.fromReadableStream(e,this.controller);let a;for await(const e of n)a&&a!==e.id&&this._addChatCompletion(mE(this,EA,"m",LA).call(this)),mE(this,EA,"m",TA).call(this,e),a=e.id;if(n.controller.signal?.aborted)throw new nP;return this._addChatCompletion(mE(this,EA,"m",LA).call(this))}[(CA=new WeakMap,AA=new WeakMap,OA=new WeakMap,EA=new WeakSet,IA=function(){this.ended||pE(this,OA,void 0)},$A=function(e){let t=mE(this,AA,"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},mE(this,AA,"f")[e.index]=t,t)},TA=function(e){if(this.ended)return;const t=mE(this,EA,"m",jA).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=mE(this,EA,"m",$A).call(this,e);e.finish_reason&&(mE(this,EA,"m",RA).call(this,e),null!=n.current_tool_call_index&&mE(this,EA,"m",zA).call(this,e,n.current_tool_call_index));for(const t of r.delta.tool_calls??[])n.current_tool_call_index!==t.index&&(mE(this,EA,"m",RA).call(this,e),null!=n.current_tool_call_index&&mE(this,EA,"m",zA).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??""}):UA(r?.type))}}},zA=function(e,t){if(mE(this,EA,"m",$A).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=mE(this,CA,"f")?.tools?.find(e=>yP(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:bP(e)?e.$parseRaw(r.function.arguments):e?.function.strict?JSON.parse(r.function.arguments):null})}else r.type},RA=function(e){const t=mE(this,EA,"m",$A).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;const r=mE(this,EA,"m",MA).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}))},LA=function(){if(this.ended)throw new tP("stream has ended, this shouldn't happen");const e=mE(this,OA,"f");if(!e)throw new tP("request ended without sending any chunks");return pE(this,OA,void 0),pE(this,AA,[]),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 tP(`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 tP(`missing role for choice ${n}`);if(o){const{arguments:e,name:c}=o;if(null==e)throw new tP(`missing function_call.arguments for choice ${n}`);if(!c)throw new tP(`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 tP(`missing choices[${n}].tool_calls[${r}].id\n${FA(e)}`);if(null==i)throw new tP(`missing choices[${n}].tool_calls[${r}].type\n${FA(e)}`);if(null==l)throw new tP(`missing choices[${n}].tool_calls[${r}].function.name\n${FA(e)}`);if(null==c)throw new tP(`missing choices[${n}].tool_calls[${r}].function.arguments\n${FA(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&&NP(t)?_P(e,t):{...e,choices:e.choices.map(e=>(kP(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,mE(this,CA,"f"))},MA=function(){const e=mE(this,CA,"f")?.response_format;return vP(e)?e:null},jA=function(e){var t,r,n,a;let i=mE(this,OA,"f");const{choices:s,...o}=e;i?Object.assign(i,o):i=pE(this,OA,{...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,mE(this,CA,"f")&&NP(mE(this,CA,"f")))){if("length"===o)throw new hP;if("content_filter"===o)throw new fP}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&&mE(this,EA,"m",MA).call(this)&&(e.message.parsed=PA(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,SP(mE(this,CA,"f"),o)&&(o.function.parsed_arguments=PA(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 uC(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function FA(e){return JSON.stringify(e)}function UA(e){}class BA extends DA{static fromReadableStream(e){const t=new BA(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){const n=new BA(t),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,a)),n}}let qA=class extends TC{constructor(){super(...arguments),this.messages=new jC(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(MC`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(MC`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",vC,{query:e,...t})}delete(e,t){return this._client.delete(MC`/chat/completions/${e}`,t)}parse(e,t){return function(e){for(const t of e??[]){if("function"!==t.type)throw new tP(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new tP(`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=>_P(t,e))}runTools(e,t){return e.stream?BA.runTools(this._client,e,t):pA.runTools(this._client,e,t)}stream(e,t){return DA.createChatCompletion(this._client,e,t)}};qA.Messages=jC;class VA extends TC{constructor(){super(...arguments),this.completions=new qA(this._client)}}VA.Completions=qA;const GA=Symbol("brand.privateNullableHeaders");function*HA(e){if(!e)return;if(GA 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():yE(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=yE(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 WA=e=>{const t=new Headers,r=new Set;for(const n of e){const e=new Set;for(const[a,i]of HA(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{[GA]:!0,values:t,nulls:r}};class KA extends TC{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:WA([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class ZA extends TC{create(e,t){return this._client.post("/audio/transcriptions",xC({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class JA extends TC{create(e,t){return this._client.post("/audio/translations",xC({body:e,...t,__metadata:{model:e.model}},this._client))}}class YA extends TC{constructor(){super(...arguments),this.transcriptions=new ZA(this._client),this.translations=new JA(this._client),this.speech=new KA(this._client)}}YA.Transcriptions=ZA,YA.Translations=JA,YA.Speech=KA;class XA extends TC{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(MC`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",vC,{query:e,...t})}cancel(e,t){return this._client.post(MC`/batches/${e}/cancel`,t)}}class QA extends TC{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:WA([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(MC`/assistants/${e}`,{...t,headers:WA([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(MC`/assistants/${e}`,{body:t,...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",vC,{query:e,...t,headers:WA([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(MC`/assistants/${e}`,{...t,headers:WA([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}let eO=class extends TC{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:WA([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};class tO extends TC{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:WA([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}let rO=class extends TC{constructor(){super(...arguments),this.sessions=new eO(this._client),this.transcriptionSessions=new tO(this._client)}};rO.Sessions=eO,rO.TranscriptionSessions=tO;class nO extends TC{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:WA([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(MC`/chatkit/sessions/${e}/cancel`,{...t,headers:WA([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}}let aO=class extends TC{retrieve(e,t){return this._client.get(MC`/chatkit/threads/${e}`,{...t,headers:WA([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",bC,{query:e,...t,headers:WA([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(MC`/chatkit/threads/${e}`,{...t,headers:WA([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},r){return this._client.getAPIList(MC`/chatkit/threads/${e}/items`,bC,{query:t,...r,headers:WA([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}};class iO extends TC{constructor(){super(...arguments),this.sessions=new nO(this._client),this.threads=new aO(this._client)}}iO.Sessions=nO,iO.Threads=aO;class sO extends TC{create(e,t,r){return this._client.post(MC`/threads/${e}/messages`,{body:t,...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){const{thread_id:n}=t;return this._client.get(MC`/threads/${n}/messages/${e}`,{...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){const{thread_id:n,...a}=t;return this._client.post(MC`/threads/${n}/messages/${e}`,{body:a,...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(MC`/threads/${e}/messages`,vC,{query:t,...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){const{thread_id:n}=t;return this._client.delete(MC`/threads/${n}/messages/${e}`,{...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class oO extends TC{retrieve(e,t,r){const{thread_id:n,run_id:a,...i}=t;return this._client.get(MC`/threads/${n}/runs/${a}/steps/${e}`,{query:i,...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){const{thread_id:n,...a}=t;return this._client.getAPIList(MC`/threads/${n}/runs/${e}/steps`,vC,{query:a,...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}const cO=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 lO,uO,dO,pO,mO,hO,fO,gO,yO,vO,bO,_O,wO,SO,NO,kO,xO,PO,EO,CO,AO,OO,IO;class $O extends cA{constructor(){super(...arguments),lO.add(this),dO.set(this,[]),pO.set(this,{}),mO.set(this,{}),hO.set(this,void 0),fO.set(this,void 0),gO.set(this,void 0),yO.set(this,void 0),vO.set(this,void 0),bO.set(this,void 0),_O.set(this,void 0),wO.set(this,void 0),SO.set(this,void 0)}[(dO=new WeakMap,pO=new WeakMap,mO=new WeakMap,hO=new WeakMap,fO=new WeakMap,gO=new WeakMap,yO=new WeakMap,vO=new WeakMap,bO=new WeakMap,_O=new WeakMap,wO=new WeakMap,SO=new WeakMap,lO=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 uO;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=uC.fromReadableStream(e,this.controller);for await(const e of n)mE(this,lO,"m",NO).call(this,e);if(n.controller.signal?.aborted)throw new nP;return this._addRun(mE(this,lO,"m",kO).call(this))}toReadableStream(){return new uC(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n){const a=new uO;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)mE(this,lO,"m",NO).call(this,e);if(s.controller.signal?.aborted)throw new nP;return this._addRun(mE(this,lO,"m",kO).call(this))}static createThreadAssistantStream(e,t,r){const n=new uO;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 uO;return a._run(()=>a._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return mE(this,_O,"f")}currentRun(){return mE(this,wO,"f")}currentMessageSnapshot(){return mE(this,hO,"f")}currentRunStepSnapshot(){return mE(this,SO,"f")}async finalRunSteps(){return await this.done(),Object.values(mE(this,pO,"f"))}async finalMessages(){return await this.done(),Object.values(mE(this,mO,"f"))}async finalRun(){if(await this.done(),!mE(this,fO,"f"))throw Error("Final run was not received.");return mE(this,fO,"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)mE(this,lO,"m",NO).call(this,e);if(i.controller.signal?.aborted)throw new nP;return this._addRun(mE(this,lO,"m",kO).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)mE(this,lO,"m",NO).call(this,e);if(s.controller.signal?.aborted)throw new nP;return this._addRun(mE(this,lO,"m",kO).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(!bE(t)||!bE(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(!bE(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)}}uO=$O,NO=function(e){if(!this.ended)switch(pE(this,_O,e),mE(this,lO,"m",EO).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":mE(this,lO,"m",IO).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":mE(this,lO,"m",PO).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":mE(this,lO,"m",xO).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},kO=function(){if(this.ended)throw new tP("stream has ended, this shouldn't happen");if(!mE(this,fO,"f"))throw Error("Final run has not been received");return mE(this,fO,"f")},xO=function(e){const[t,r]=mE(this,lO,"m",AO).call(this,e,mE(this,hO,"f"));pE(this,hO,t),mE(this,mO,"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!=mE(this,gO,"f")){if(mE(this,yO,"f"))switch(mE(this,yO,"f").type){case"text":this._emit("textDone",mE(this,yO,"f").text,mE(this,hO,"f"));break;case"image_file":this._emit("imageFileDone",mE(this,yO,"f").image_file,mE(this,hO,"f"))}pE(this,gO,r.index)}pE(this,yO,t.content[r.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==mE(this,gO,"f")){const t=e.data.content[mE(this,gO,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,mE(this,hO,"f"));break;case"text":this._emit("textDone",t.text,mE(this,hO,"f"))}}mE(this,hO,"f")&&this._emit("messageDone",e.data),pE(this,hO,void 0)}},PO=function(e){const t=mE(this,lO,"m",CO).call(this,e);switch(pE(this,SO,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==mE(this,vO,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(mE(this,bO,"f")&&this._emit("toolCallDone",mE(this,bO,"f")),pE(this,vO,e.index),pE(this,bO,t.step_details.tool_calls[e.index]),mE(this,bO,"f")&&this._emit("toolCallCreated",mE(this,bO,"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":pE(this,SO,void 0);"tool_calls"==e.data.step_details.type&&mE(this,bO,"f")&&(this._emit("toolCallDone",mE(this,bO,"f")),pE(this,bO,void 0)),this._emit("runStepDone",e.data,t)}},EO=function(e){mE(this,dO,"f").push(e),this._emit("event",e)},CO=function(e){switch(e.event){case"thread.run.step.created":return mE(this,pO,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=mE(this,pO,"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=uO.accumulateDelta(t,r.delta);mE(this,pO,"f")[e.data.id]=n}return mE(this,pO,"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":mE(this,pO,"f")[e.data.id]=e.data}if(mE(this,pO,"f")[e.data.id])return mE(this,pO,"f")[e.data.id];throw new Error("No snapshot available")},AO=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]=mE(this,lO,"m",OO).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")},OO=function(e,t){return uO.accumulateDelta(t,e)},IO=function(e){switch(pE(this,wO,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":pE(this,fO,e.data),mE(this,bO,"f")&&(this._emit("toolCallDone",mE(this,bO,"f")),pE(this,bO,void 0))}};let TO=class extends TC{constructor(){super(...arguments),this.steps=new oO(this._client)}create(e,t,r){const{include:n,...a}=t;return this._client.post(MC`/threads/${e}/runs`,{query:{include:n},body:a,...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}retrieve(e,t,r){const{thread_id:n}=t;return this._client.get(MC`/threads/${n}/runs/${e}`,{...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){const{thread_id:n,...a}=t;return this._client.post(MC`/threads/${n}/runs/${e}`,{body:a,...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(MC`/threads/${e}/runs`,vC,{query:t,...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){const{thread_id:n}=t;return this._client.post(MC`/threads/${n}/runs/${e}/cancel`,{...r,headers:WA([{"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 $O.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){const n=WA([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 _E(e);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,t,r){return $O.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){const{thread_id:n,...a}=t;return this._client.post(MC`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:a,...r,headers:WA([{"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 $O.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};TO.Steps=oO;class zO extends TC{constructor(){super(...arguments),this.runs=new TO(this._client),this.messages=new sO(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:WA([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(MC`/threads/${e}`,{...t,headers:WA([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(MC`/threads/${e}`,{body:t,...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(MC`/threads/${e}`,{...t,headers:WA([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:WA([{"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 $O.createThreadAssistantStream(e,this._client.beta.threads,t)}}zO.Runs=TO,zO.Messages=sO;class RO extends TC{constructor(){super(...arguments),this.realtime=new rO(this._client),this.chatkit=new iO(this._client),this.assistants=new QA(this._client),this.threads=new zO(this._client)}}RO.Realtime=rO,RO.ChatKit=iO,RO.Assistants=QA,RO.Threads=zO;class LO extends TC{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class MO extends TC{retrieve(e,t,r){const{container_id:n}=t;return this._client.get(MC`/containers/${n}/files/${e}/content`,{...r,headers:WA([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}let jO=class extends TC{constructor(){super(...arguments),this.content=new MO(this._client)}create(e,t,r){return this._client.post(MC`/containers/${e}/files`,xC({body:t,...r},this._client))}retrieve(e,t,r){const{container_id:n}=t;return this._client.get(MC`/containers/${n}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(MC`/containers/${e}/files`,vC,{query:t,...r})}delete(e,t,r){const{container_id:n}=t;return this._client.delete(MC`/containers/${n}/files/${e}`,{...r,headers:WA([{Accept:"*/*"},r?.headers])})}};jO.Content=MO;class DO extends TC{constructor(){super(...arguments),this.files=new jO(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(MC`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",vC,{query:e,...t})}delete(e,t){return this._client.delete(MC`/containers/${e}`,{...t,headers:WA([{Accept:"*/*"},t?.headers])})}}DO.Files=jO;class FO extends TC{create(e,t,r){const{include:n,...a}=t;return this._client.post(MC`/conversations/${e}/items`,{query:{include:n},body:a,...r})}retrieve(e,t,r){const{conversation_id:n,...a}=t;return this._client.get(MC`/conversations/${n}/items/${e}`,{query:a,...r})}list(e,t={},r){return this._client.getAPIList(MC`/conversations/${e}/items`,bC,{query:t,...r})}delete(e,t,r){const{conversation_id:n}=t;return this._client.delete(MC`/conversations/${n}/items/${e}`,r)}}class UO extends TC{constructor(){super(...arguments),this.items=new FO(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(MC`/conversations/${e}`,t)}update(e,t,r){return this._client.post(MC`/conversations/${e}`,{body:t,...r})}delete(e,t){return this._client.delete(MC`/conversations/${e}`,t)}}UO.Items=FO;let BO=class extends TC{create(e,t){const r=!!e.encoding_format;let n=r?e.encoding_format:"base64";r&&iC(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:(iC(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 qO extends TC{retrieve(e,t,r){const{eval_id:n,run_id:a}=t;return this._client.get(MC`/evals/${n}/runs/${a}/output_items/${e}`,r)}list(e,t,r){const{eval_id:n,...a}=t;return this._client.getAPIList(MC`/evals/${n}/runs/${e}/output_items`,vC,{query:a,...r})}}class VO extends TC{constructor(){super(...arguments),this.outputItems=new qO(this._client)}create(e,t,r){return this._client.post(MC`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){const{eval_id:n}=t;return this._client.get(MC`/evals/${n}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(MC`/evals/${e}/runs`,vC,{query:t,...r})}delete(e,t,r){const{eval_id:n}=t;return this._client.delete(MC`/evals/${n}/runs/${e}`,r)}cancel(e,t,r){const{eval_id:n}=t;return this._client.post(MC`/evals/${n}/runs/${e}`,r)}}VO.OutputItems=qO;class GO extends TC{constructor(){super(...arguments),this.runs=new VO(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(MC`/evals/${e}`,t)}update(e,t,r){return this._client.post(MC`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",vC,{query:e,...t})}delete(e,t){return this._client.delete(MC`/evals/${e}`,t)}}GO.Runs=VO;let HO=class extends TC{create(e,t){return this._client.post("/files",xC({body:e,...t},this._client))}retrieve(e,t){return this._client.get(MC`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",vC,{query:e,...t})}delete(e,t){return this._client.delete(MC`/files/${e}`,t)}content(e,t){return this._client.get(MC`/files/${e}/content`,{...t,headers:WA([{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 _E(t),i=await this.retrieve(e),Date.now()-a>r)throw new iP({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};class WO extends TC{}let KO=class extends TC{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 ZO extends TC{constructor(){super(...arguments),this.graders=new KO(this._client)}}ZO.Graders=KO;class JO extends TC{create(e,t,r){return this._client.getAPIList(MC`/fine_tuning/checkpoints/${e}/permissions`,yC,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(MC`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}delete(e,t,r){const{fine_tuned_model_checkpoint:n}=t;return this._client.delete(MC`/fine_tuning/checkpoints/${n}/permissions/${e}`,r)}}let YO=class extends TC{constructor(){super(...arguments),this.permissions=new JO(this._client)}};YO.Permissions=JO;class XO extends TC{list(e,t={},r){return this._client.getAPIList(MC`/fine_tuning/jobs/${e}/checkpoints`,vC,{query:t,...r})}}class QO extends TC{constructor(){super(...arguments),this.checkpoints=new XO(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(MC`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",vC,{query:e,...t})}cancel(e,t){return this._client.post(MC`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(MC`/fine_tuning/jobs/${e}/events`,vC,{query:t,...r})}pause(e,t){return this._client.post(MC`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(MC`/fine_tuning/jobs/${e}/resume`,t)}}QO.Checkpoints=XO;class eI extends TC{constructor(){super(...arguments),this.methods=new WO(this._client),this.jobs=new QO(this._client),this.checkpoints=new YO(this._client),this.alpha=new ZO(this._client)}}eI.Methods=WO,eI.Jobs=QO,eI.Checkpoints=YO,eI.Alpha=ZO;class tI extends TC{}class rI extends TC{constructor(){super(...arguments),this.graderModels=new tI(this._client)}}rI.GraderModels=tI;class nI extends TC{createVariation(e,t){return this._client.post("/images/variations",xC({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",xC({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 aI extends TC{retrieve(e,t){return this._client.get(MC`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",yC,e)}delete(e,t){return this._client.delete(MC`/models/${e}`,t)}}class iI extends TC{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class sI extends TC{accept(e,t,r){return this._client.post(MC`/realtime/calls/${e}/accept`,{body:t,...r,headers:WA([{Accept:"*/*"},r?.headers])})}hangup(e,t){return this._client.post(MC`/realtime/calls/${e}/hangup`,{...t,headers:WA([{Accept:"*/*"},t?.headers])})}refer(e,t,r){return this._client.post(MC`/realtime/calls/${e}/refer`,{body:t,...r,headers:WA([{Accept:"*/*"},r?.headers])})}reject(e,t={},r){return this._client.post(MC`/realtime/calls/${e}/reject`,{body:t,...r,headers:WA([{Accept:"*/*"},r?.headers])})}}class oI extends TC{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class cI extends TC{constructor(){super(...arguments),this.clientSecrets=new oI(this._client),this.calls=new sI(this._client)}}var lI,uI,dI,pI,mI,hI,fI,gI;cI.ClientSecrets=oI,cI.Calls=sI;class yI extends cA{constructor(e){super(),lI.add(this),uI.set(this,void 0),dI.set(this,void 0),pI.set(this,void 0),pE(this,uI,e)}static createResponse(e,t,r){const n=new yI(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())),mE(this,lI,"m",mI).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)mE(this,lI,"m",hI).call(this,e,i);if(a.controller.signal?.aborted)throw new nP;return mE(this,lI,"m",fI).call(this)}[(uI=new WeakMap,dI=new WeakMap,pI=new WeakMap,lI=new WeakSet,mI=function(){this.ended||pE(this,dI,void 0)},hI=function(e,t){if(this.ended)return;const r=(e,r)=>{(null==t||r.sequence_number>t)&&this._emit(e,r)},n=mE(this,lI,"m",gI).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 tP(`missing output at index ${e.output_index}`);if("message"===t.type){const n=t.content[e.content_index];if(!n)throw new tP(`missing content at index ${e.content_index}`);if("output_text"!==n.type)throw new tP(`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 tP(`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)}},fI=function(){if(this.ended)throw new tP("stream has ended, this shouldn't happen");const e=mE(this,dI,"f");if(!e)throw new tP("request ended without sending any events");pE(this,dI,void 0);const t=function(e,t){return tE(e,t)}(e,mE(this,uI,"f"));return pE(this,pI,t),t},gI=function(e){let t=mE(this,dI,"f");if(!t){if("response.created"!==e.type)throw new tP(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return t=pE(this,dI,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 tP(`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 tP(`missing output at index ${e.output_index}`);if("message"===r.type){const t=r.content[e.content_index];if(!t)throw new tP(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new tP(`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 tP(`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 tP(`missing output at index ${e.output_index}`);if("reasoning"===r.type){const t=r.content?.[e.content_index];if(!t)throw new tP(`missing content at index ${e.content_index}`);if("reasoning_text"!==t.type)throw new tP(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}break}case"response.completed":pE(this,dI,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=mE(this,pI,"f");if(!e)throw new tP("stream ended without producing a ChatCompletion");return e}}class vI extends TC{list(e,t={},r){return this._client.getAPIList(MC`/responses/${e}/input_items`,vC,{query:t,...r})}}class bI extends TC{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}}class _I extends TC{constructor(){super(...arguments),this.inputItems=new vI(this._client),this.inputTokens=new bI(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&&sE(e),e))}retrieve(e,t={},r){return this._client.get(MC`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap(e=>("object"in e&&"response"===e.object&&sE(e),e))}delete(e,t){return this._client.delete(MC`/responses/${e}`,{...t,headers:WA([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>rE(t,e))}stream(e,t){return yI.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(MC`/responses/${e}/cancel`,t)}}_I.InputItems=vI,_I.InputTokens=bI;class wI extends TC{create(e,t,r){return this._client.post(MC`/uploads/${e}/parts`,xC({body:t,...r},this._client))}}class SI extends TC{constructor(){super(...arguments),this.parts=new wI(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(MC`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(MC`/uploads/${e}/complete`,{body:t,...r})}}SI.Parts=wI;class NI extends TC{create(e,t,r){return this._client.post(MC`/vector_stores/${e}/file_batches`,{body:t,...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){const{vector_store_id:n}=t;return this._client.get(MC`/vector_stores/${n}/file_batches/${e}`,{...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){const{vector_store_id:n}=t;return this._client.post(MC`/vector_stores/${n}/file_batches/${e}/cancel`,{...r,headers:WA([{"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(MC`/vector_stores/${n}/file_batches/${e}/files`,vC,{query:a,...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){const n=WA([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 _E(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 kI extends TC{create(e,t,r){return this._client.post(MC`/vector_stores/${e}/files`,{body:t,...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){const{vector_store_id:n}=t;return this._client.get(MC`/vector_stores/${n}/files/${e}`,{...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){const{vector_store_id:n,...a}=t;return this._client.post(MC`/vector_stores/${n}/files/${e}`,{body:a,...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(MC`/vector_stores/${e}/files`,vC,{query:t,...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){const{vector_store_id:n}=t;return this._client.delete(MC`/vector_stores/${n}/files/${e}`,{...r,headers:WA([{"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=WA([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 _E(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(MC`/vector_stores/${n}/files/${e}/content`,yC,{...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class xI extends TC{constructor(){super(...arguments),this.files=new kI(this._client),this.fileBatches=new NI(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:WA([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(MC`/vector_stores/${e}`,{...t,headers:WA([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(MC`/vector_stores/${e}`,{body:t,...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",vC,{query:e,...t,headers:WA([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(MC`/vector_stores/${e}`,{...t,headers:WA([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(MC`/vector_stores/${e}/search`,yC,{body:t,method:"post",...r,headers:WA([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}xI.Files=kI,xI.FileBatches=NI;class PI extends TC{create(e,t){return this._client.post("/videos",kC({body:e,...t},this._client))}retrieve(e,t){return this._client.get(MC`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",bC,{query:e,...t})}delete(e,t){return this._client.delete(MC`/videos/${e}`,t)}downloadContent(e,t={},r){return this._client.get(MC`/videos/${e}/content`,{query:t,...r,headers:WA([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}remix(e,t,r){return this._client.post(MC`/videos/${e}/remix`,kC({body:t,...r},this._client))}}var EI,CI,AI,OI,II,$I,TI;class zI extends TC{constructor(){super(...arguments),EI.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");mE(this,EI,"m",CI).call(this,r);const a=WA([t]).values,i=mE(this,EI,"m",AI).call(this,a,"webhook-signature"),s=mE(this,EI,"m",AI).call(this,a,"webhook-timestamp"),o=mE(this,EI,"m",AI).call(this,a,"webhook-id"),c=parseInt(s,10);if(isNaN(c))throw new gP("Invalid webhook timestamp format");const l=Math.floor(Date.now()/1e3);if(l-c>n)throw new gP("Webhook timestamp is too old");if(c>l+n)throw new gP("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 gP("The given webhook signature does not match the expected signature")}}EI=new WeakSet,CI=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")},AI=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 RI{constructor({baseURL:e=cO("OPENAI_BASE_URL"),apiKey:t=cO("OPENAI_API_KEY"),organization:r=cO("OPENAI_ORG_ID")??null,project:n=cO("OPENAI_PROJECT_ID")??null,webhookSecret:a=cO("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(OI.add(this),$I.set(this,void 0),this.completions=new LO(this),this.chat=new VA(this),this.embeddings=new BO(this),this.files=new HO(this),this.images=new nI(this),this.audio=new YA(this),this.moderations=new iI(this),this.models=new aI(this),this.fineTuning=new eI(this),this.graders=new rI(this),this.vectorStores=new xI(this),this.webhooks=new zI(this),this.beta=new RO(this),this.batches=new XA(this),this.uploads=new SI(this),this.responses=new _I(this),this.realtime=new cI(this),this.conversations=new UO(this),this.evals=new GO(this),this.containers=new DO(this),this.videos=new PI(this),void 0===t)throw new tP("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 tP("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??II.DEFAULT_TIMEOUT,this.logger=s.logger??console;const o="warn";this.logLevel=o,this.logLevel=eC(s.logLevel,"ClientOptions.logLevel",this)??eC(cO("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`")}(),pE(this,$I,AE),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 WA([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return qE(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${wE}`}defaultIdempotencyKey(){return`stainless-node-retry-${hE()}`}makeStatusError(e,t,r,n){return rP.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 tP)throw e;throw new tP(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if("string"!=typeof t||!t)throw new tP(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){const n=!mE(this,OI,"m",TI).call(this)&&r||this.baseURL,a=(e=>fE.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 hC(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(iC(this).debug(`[${c}] sending request`,sC({retryOfRequestLogID:r,method:n.method,url:s,options:n,headers:i.headers})),n.signal?.aborted)throw new nP;const d=new AbortController,p=await this.fetchWithTimeout(s,i,o,d).catch(eP),m=Date.now();if(p instanceof globalThis.Error){const e=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new nP;const a=Qx(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(t)return iC(this).info(`[${c}] connection ${a?"timed out":"failed"} - ${e}`),iC(this).debug(`[${c}] connection ${a?"timed out":"failed"} (${e})`,sC({retryOfRequestLogID:r,url:s,durationMs:m-u,message:p.message})),this.retryRequest(n,t,r??c);if(iC(this).info(`[${c}] connection ${a?"timed out":"failed"} - error; no more retries left`),iC(this).debug(`[${c}] connection ${a?"timed out":"failed"} (error; no more retries left)`,sC({retryOfRequestLogID:r,url:s,durationMs:m-u,message:p.message})),a)throw new iP;throw new aP({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),iC(this).info(`${h} - ${e}`),iC(this).debug(`[${c}] response error (${e})`,sC({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";iC(this).info(`${h} - ${a}`);const i=await p.text().catch(e=>eP(e).message),s=(e=>{try{return JSON.parse(e)}catch(e){return}})(i),o=s?void 0:i;iC(this).debug(`[${c}] response error (${a})`,sC({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 iC(this).info(h),iC(this).debug(`[${c}] response start`,sC({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 gC(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 _E(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 tP(`${e} must be an integer`);if(t<0)throw new tP(`${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=WA([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))}:{},...xE??(xE=SE()),"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=WA([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:EE(e)}:mE(this,$I,"f").call(this,{body:e,headers:r})}}II=RI,$I=new WeakMap,OI=new WeakSet,TI=function(){return"https://api.openai.com/v1"!==this.baseURL},RI.OpenAI=II,RI.DEFAULT_TIMEOUT=6e5,RI.OpenAIError=tP,RI.APIError=rP,RI.APIConnectionError=aP,RI.APIConnectionTimeoutError=iP,RI.APIUserAbortError=nP,RI.NotFoundError=lP,RI.ConflictError=uP,RI.RateLimitError=pP,RI.BadRequestError=sP,RI.AuthenticationError=oP,RI.InternalServerError=mP,RI.PermissionDeniedError=cP,RI.UnprocessableEntityError=dP,RI.InvalidWebhookSignatureError=gP,RI.toFile=async function(e,t,r){if(_C(),(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&IC(e))(e=await e))return e instanceof File?e:wC([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()),wC(await $C(n),t,r)}const n=await $C(e);if(t||(t=SC(e)),!r?.type){const e=n.find(e=>"object"==typeof e&&"type"in e&&e.type);"string"==typeof e&&(r={...r,type:e})}return wC(n,t,r)},RI.Completions=LO,RI.Chat=VA,RI.Embeddings=BO,RI.Files=HO,RI.Images=nI,RI.Audio=YA,RI.Moderations=iI,RI.Models=aI,RI.FineTuning=eI,RI.Graders=rI,RI.VectorStores=xI,RI.Webhooks=zI,RI.Beta=RO,RI.Batches=XA,RI.Uploads=SI,RI.Responses=_I,RI.Realtime=cI,RI.Conversations=UO,RI.Evals=GO,RI.Containers=DO,RI.Videos=PI;class LI extends RI{constructor({baseURL:e=cO("OPENAI_BASE_URL"),apiKey:t=cO("AZURE_OPENAI_API_KEY"),apiVersion:r=cO("OPENAI_API_VERSION"),endpoint:n,deployment:a,azureADTokenProvider:i,dangerouslyAllowBrowser:s,...o}={}){if(!r)throw new tP("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 tP("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(i&&t)throw new tP("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 tP("baseURL and endpoint are mutually exclusive")}else{if(n||(n=process.env.AZURE_OPENAI_ENDPOINT),!n)throw new tP("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(MI.has(e.path)&&"post"===e.method&&void 0!==e.body){if(!bE(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?WA([{"api-key":this.apiKey}]):super.authHeaders(e)}}const MI=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);Hh({},{BasePromptValue:()=>jI,ChatPromptValue:()=>FI,ImagePromptValue:()=>UI,StringPromptValue:()=>DI});var jI=class extends mf{},DI=class extends jI{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 Ig(this.value)]}},FI=class extends jI{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 Wg(this.messages)}toChatMessages(){return this.messages}},UI=class extends jI{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 Ig({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},BI="0123456789abcdef".split(""),qI=[-2147483648,8388608,32768,128],VI=[24,16,8,0],GI=[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],HI=[];function WI(e,t){t?(HI[0]=HI[16]=HI[1]=HI[2]=HI[3]=HI[4]=HI[5]=HI[6]=HI[7]=HI[8]=HI[9]=HI[10]=HI[11]=HI[12]=HI[13]=HI[14]=HI[15]=0,this.blocks=HI):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}WI.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]<<VI[3&a++];else for(a=this.start;i<s&&a<64;++i)(n=e.charCodeAt(i))<128?o[a>>>2]|=n<<VI[3&a++]:n<2048?(o[a>>>2]|=(192|n>>>6)<<VI[3&a++],o[a>>>2]|=(128|63&n)<<VI[3&a++]):n<55296||n>=57344?(o[a>>>2]|=(224|n>>>12)<<VI[3&a++],o[a>>>2]|=(128|n>>>6&63)<<VI[3&a++],o[a>>>2]|=(128|63&n)<<VI[3&a++]):(n=65536+((1023&n)<<10|1023&e.charCodeAt(++i)),o[a>>>2]|=(240|n>>>18)<<VI[3&a++],o[a>>>2]|=(128|n>>>12&63)<<VI[3&a++],o[a>>>2]|=(128|n>>>6&63)<<VI[3&a++],o[a>>>2]|=(128|63&n)<<VI[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}},WI.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=qI[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()}},WI.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)+GI[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)+GI[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)+GI[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)+GI[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},WI.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=BI[e>>>28&15]+BI[e>>>24&15]+BI[e>>>20&15]+BI[e>>>16&15]+BI[e>>>12&15]+BI[e>>>8&15]+BI[e>>>4&15]+BI[15&e]+BI[t>>>28&15]+BI[t>>>24&15]+BI[t>>>20&15]+BI[t>>>16&15]+BI[t>>>12&15]+BI[t>>>8&15]+BI[t>>>4&15]+BI[15&t]+BI[r>>>28&15]+BI[r>>>24&15]+BI[r>>>20&15]+BI[r>>>16&15]+BI[r>>>12&15]+BI[r>>>8&15]+BI[r>>>4&15]+BI[15&r]+BI[n>>>28&15]+BI[n>>>24&15]+BI[n>>>20&15]+BI[n>>>16&15]+BI[n>>>12&15]+BI[n>>>8&15]+BI[n>>>4&15]+BI[15&n]+BI[a>>>28&15]+BI[a>>>24&15]+BI[a>>>20&15]+BI[a>>>16&15]+BI[a>>>12&15]+BI[a>>>8&15]+BI[a>>>4&15]+BI[15&a]+BI[i>>>28&15]+BI[i>>>24&15]+BI[i>>>20&15]+BI[i>>>16&15]+BI[i>>>12&15]+BI[i>>>8&15]+BI[i>>>4&15]+BI[15&i]+BI[s>>>28&15]+BI[s>>>24&15]+BI[s>>>20&15]+BI[s>>>16&15]+BI[s>>>12&15]+BI[s>>>8&15]+BI[s>>>4&15]+BI[15&s];return this.is224||(c+=BI[o>>>28&15]+BI[o>>>24&15]+BI[o>>>20&15]+BI[o>>>16&15]+BI[o>>>12&15]+BI[o>>>8&15]+BI[o>>>4&15]+BI[15&o]),c},WI.prototype.toString=WI.prototype.hex,WI.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},WI.prototype.array=WI.prototype.digest,WI.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 KI=(...e)=>new WI(!1,!0).update(e.join("")).hex();Hh({},{sha256:()=>KI});Hh({},{BaseCache:()=>XI,InMemoryCache:()=>t$,defaultHashKeyEncoder:()=>ZI,deserializeStoredGeneration:()=>JI,serializeGeneration:()=>YI});const ZI=(...e)=>KI(e.join("_"));function JI(e){return void 0!==e.message?{text:e.text,message:Kg(e.message)}:{text:e.text}}function YI(e){const t={text:e.text};return void 0!==e.message&&(t.message=e.message.toDict()),t}var XI=class{keyEncoder=ZI;makeDefaultKeyEncoder(e){this.keyEncoder=e}};const QI=new Map;var e$,t$=class e extends XI{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(QI)}},r$={};var n$=function(){if(e$)return r$;e$=1,r$.byteLength=function(e){var t=i(e),r=t[0],n=t[1];return 3*(r+n)/4-n},r$.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},r$.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,r$}(),a$=Zn(n$),i$=Object.defineProperty;function s$(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 o$=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=a$.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=o$.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=o$.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(...s$(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)}},c$=o$;((e,t,r)=>{((e,t,r)=>{t in e?i$(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r})(e,t+"",r)})(c$,"specialTokenRegex",e=>new RegExp(e.map(e=>function(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}(e)).join("|"),"g"));Hh({},{encodingForModel:()=>p$,getEncoding:()=>d$});const l$={},u$=new Y_({});async function d$(e){return e in l$||(l$[e]=u$.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(e=>e.json()).then(e=>new c$(e)).catch(t=>{throw delete l$[e],t})),await l$[e]}async function p$(e){return d$(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))}Hh({},{BaseLangChain:()=>v$,BaseLanguageModel:()=>b$,calculateMaxTokens:()=>y$,getEmbeddingContextSize:()=>h$,getModelContextSize:()=>f$,getModelNameForTiktoken:()=>m$,isOpenAITool:()=>g$});const m$=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,h$=e=>"text-embedding-ada-002"===e?8191:2046,f$=e=>{switch(m$(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 g$(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 y$=async({prompt:e,modelName:t})=>{let r;try{r=(await p$(m$(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 f$(t)-r};var v$=class extends sx{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??{}}},b$=class extends v${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?t$.global():void 0,this.caller=new Y_(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 p$("modelName"in this?m$(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 DI(e):Array.isArray(e)?new FI(e.map(Hg)):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{}}},_$=class extends sx{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=n_(t);return this.func&&await this.func(e,r),this._callWithConfig(e=>Promise.resolve(e),e,r)}async*transform(e,t){const r=n_(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=u_(n,t)}catch{n=void 0,a=!1}this.func&&void 0!==n&&await this.func(n,r)}static assign(e){return new yx(new dx({steps:e}))}};function w$(e){return new(0,e.constructor)({...e,content:e.contentBlocks,response_metadata:{...e.response_metadata,output_version:"v1"}})}function S$(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];(Kh(n)||Zh(n))&&e===r&&(e=new r.constructor({...e,content:[...r.content.slice(0,t),Xh(n),...r.content.slice(t+1)]}))}t.push(e)}return t}Hh({},{BaseChatModel:()=>N$,SimpleChatModel:()=>k$});var N$=class e extends b${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??ly("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 Kb.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(),[S$(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 w$(e.message):yield e.message,d=d?d.concat(e):e,wg(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(Hg));let s;if(void 0!==a&&a.length===i.length)s=a;else{const e={...n.metadata,...this.getLsParams(r)},t=await Kb.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(S$),n.runId,void 0,a,void 0,void 0,n.runName))}const o=r.outputVersion??this.outputVersion,c=[],l=[];if(!!s?.[0].handlers.find(ky)&&!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:u_(t,r),wg(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=w$(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,q_,{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(Hg)),o={...i.metadata,...this.getLsParams(a)},c=await Kb.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(S$),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&&Wf(e.message)&&_g(e.message)&&(e.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},"v1"===h&&(e.message=w$(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,q_,{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(Hg)),[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=Kw(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";Fw(r)?o=[{type:"function",function:{name:c,description:a,parameters:Kk(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(!Sg.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=_$.assign({parsed:(e,t)=>u.invoke(e.raw,t)}),p=_$.assign({parsed:()=>null}),m=d.withFallbacks({fallbacks:[p]});return ux.from([{raw:l},m]).withConfig({runName:"StructuredOutputRunnable"})}},k$=class extends N${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}]}}},x$=class extends sx{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,n_(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)}},P$=class extends sx{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])=>[gx(e),gx(t)]),default:gx(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,a_(t,{callbacks:r?.getChild(`condition:${a+1}`)}))){n=await s.invoke(e,a_(t,{callbacks:r?.getChild(`branch:${a+1}`)}));break}}return n||(n=await this.default.invoke(e,a_(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 e_(t),n=await(r?.handleChainStart(this.toJSON(),ix(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,a_(t,{callbacks:n?.getChild(`condition:${r+1}`)}))){i=await c.stream(e,a_(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=u_(a,e)}catch{a=void 0,s=!1}break}}if(void 0===i){i=await this.default.stream(e,a_(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=u_(a,e)}catch{a=void 0,s=!1}}}catch(e){throw await(n?.handleChainError(e)),e}await(n?.handleChainEnd(a??{}))}},E$=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=_$.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)||Wf(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 Ig(t)];if(Array.isArray(t))return t;if(Wf(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)||Wf(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(Wf(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}};Hh({},{RouterRunnable:()=>x$,Runnable:()=>sx,RunnableAssign:()=>yx,RunnableBinding:()=>ox,RunnableBranch:()=>P$,RunnableEach:()=>cx,RunnableLambda:()=>mx,RunnableMap:()=>dx,RunnableParallel:()=>hx,RunnablePassthrough:()=>_$,RunnablePick:()=>vx,RunnableRetry:()=>lx,RunnableSequence:()=>ux,RunnableToolLike:()=>bx,RunnableWithFallbacks:()=>fx,RunnableWithMessageHistory:()=>E$,_coerceToRunnable:()=>gx,ensureConfig:()=>n_,getCallbackManagerForConfig:()=>e_,mergeConfigs:()=>t_,patchConfig:()=>a_,pickRunnableConfigKeys:()=>i_});var C$=class extends sx{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"})}},A$=class extends C${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")}},O$=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");Fg(this,"OUTPUT_PARSING_FAILURE")}},I$=class extends A${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"})}},$$=class extends I${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(Kf(n)){if("string"!=typeof n.content)throw new Error("Cannot handle non-string message output.");e=new G_({message:n,text:n.content})}else if(Wf(n)){if("string"!=typeof n.content)throw new Error("Cannot handle non-string message output.");e=new G_({message:Yg(n),text:n.content})}else e=new V_({text:n});r=void 0===r?e:r.concat(e);const a=await this.parsePartialResult([r]);null==a||Ck(a,t)||(this.diff?yield this._diff(t,a):yield a,t=a)}}getFormatInstructions(){return""}},T$=class extends I${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""}},z$=class extends I${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]}},R$=class extends z${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 O$(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},L$=class extends z${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 O$(`Incorrect number of items. Expected ${this.length}, got ${t.length}.`);return t}catch(t){if(Object.getPrototypeOf(t)===O$.prototype)throw t;throw new O$(`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\`)`}},M$=class extends z${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])}},j$=class extends z${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])}},D$=class extends I${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),"")}},F$=class extends A${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=YN(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,ZN().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(Kk(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 Gw(this.schema,JSON.parse(r))}catch(t){throw new O$(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}},U$=class extends F${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(Kk(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=YN(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,ZN().describe(t)])));return new this(t)}},B$=class extends A${structuredInputParser;constructor({inputSchema:e}){super(...arguments),this.structuredInputParser=new U$(e)}async parse(e){let t;try{t=await this.structuredInputParser.parse(e)}catch(t){throw new O$(`Failed to parse. Text: "${e}". Error: ${t}`,e)}return this.outputProcessor(t)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}};Hh({},{applyPatch:()=>O_,compare:()=>L_});var q$=class extends $${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?L_(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return sg(e[0].text)}async parse(e){return sg(e,JSON.parse)}getFormatInstructions(){return""}};const V$=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(){O(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 O(n);"object"==typeof r&&(r=r.toString());var a=0,i="";for(;i=D(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;j(n,i);continue;case N.BEGIN_WHITESPACE:j(n,i);continue;case N.TEXT:if(n.sawRoot&&!n.closedRoot){for(var c=a-1;i&&"<"!==i&&"&"!==i;)(i=D(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||I(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(I(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?(P(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)&&I(n,"Inappropriately located doctype declaration"),n.doctype="",n.sgmlDecl=""):">"===i?(P(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,P(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&&P(n,"oncomment",n.comment),n.comment=""):(n.comment+="-"+i,n.state=N.COMMENT);continue;case N.COMMENT_ENDED:">"!==i?(I(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&&P(n,"oncdata",n.cdata),P(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?(P(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:($(n),">"===i?R(n):"/"===i?n.state=N.OPEN_TAG_SLASH:(f(i)||I(n,"Invalid character in tag name"),n.state=N.ATTRIB));continue;case N.OPEN_TAG_SLASH:">"===i?(R(n,!0),L(n)):(I(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):I(n,"Invalid attribute name");continue;case N.ATTRIB_NAME:"="===i?n.state=N.ATTRIB_VALUE:">"===i?(I(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:I(n,"Invalid attribute name");continue;case N.ATTRIB_NAME_SAW_WHITE:if("="===i)n.state=N.ATTRIB_VALUE;else{if(f(i))continue;I(n,"Attribute without value"),n.tag.attributes[n.attribName]="",n.attribValue="",P(n,"onattribute",{name:n.attribName,value:""}),n.attribName="",">"===i?R(n):v(d,i)?(n.attribName=i,n.state=N.ATTRIB_NAME):(I(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):(I(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)?(I(n,"No whitespace between attributes"),n.attribName=i,n.attribValue="",n.state=N.ATTRIB_NAME):I(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)||I(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):I(n,"Invalid tagname in closing tag."):n.tagName=i}continue;case N.CLOSE_TAG_SAW_WHITE:if(f(i))continue;">"===i?L(n):I(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:(I(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":E(r);break;case"cdata":P(r,"oncdata",r.cdata),r.cdata="";break;case"script":P(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;E(e=this),""!==e.cdata&&(P(e,"oncdata",e.cdata),e.cdata=""),""!==e.script&&(P(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 P(e,t,r){e.textNode&&E(e),x(e,t,r)}function E(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 E(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 O(e){return e.sawRoot&&!e.closedRoot&&I(e,"Unclosed root tag"),e.state!==N.BEGIN&&e.state!==N.BEGIN_WHITESPACE&&e.state!==N.TEXT&&A(e,"Unexpected end"),E(e),e.c="",e.closed=!0,x(e,"onend"),r.call(e,e.strict,e.opt),e}function I(e,t){if("object"!=typeof e||!(e instanceof r))throw new Error("bad call to strictFail");e.strict&&A(e,t)}function $(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,P(e,"onopentagstart",r)}function T(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=T(e.attribName,!0),r=t.prefix,n=t.local;if("xmlns"===r)if("xml"===n&&e.attribValue!==c)I(e,"xml: prefix must be bound to "+c+"\nActual: "+e.attribValue);else if("xmlns"===n&&e.attribValue!==l)I(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,P(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=T(e.tagName);r.prefix=n.prefix,r.local=n.local,r.uri=r.ns[n.prefix]||"",r.prefix&&!r.uri&&(I(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){P(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=T(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&&(I(e,"Unbound namespace prefix: "+JSON.stringify(d)),h.uri=d),e.tag.attributes[c]=h,P(e,"onattribute",h)}e.attribList.length=0}e.tag.isSelfClosing=!!t,e.sawRoot=!0,e.tags.push(e.tag),P(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 I(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);P(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;I(e,"Unexpected close tag")}if(t<0)return I(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,P(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];P(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?(I(e,"Invalid character entity"),"&"+e.entity+";"):String.fromCodePoint(t))}function j(e,t){"<"===t?(e.state=N.OPEN_WAKA,e.startTagPosition=e.position):f(t)||(I(e,"Non-whitespace before first tag."),e.textNode=t,e.state=N.TEXT)}function D(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}(),G$='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 H$=class extends $${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?L_(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return Z$(e[0].text)}async parse(e){return Z$(e)}getFormatInstructions(){return!!(this.tags&&this.tags.length>0)?G$.replace("{tags}",this.tags?.join(", ")??""):G$}};const W$=e=>e.split("\n").map(e=>e.replace(/^\s+/,"")).join("\n").trim(),K$=e=>{if(0===Object.keys(e).length)return{};const t={};return e.children.length>0?(t[e.name]=e.children.map(K$),t):(t[e.name]=e.text??void 0,t)};function Z$(e){const t=W$(e),r=V$.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]),K$(n)}function J$(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 O$([`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 Y$(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 X$(e,t){return{name:e.function?.name,args:e.function?.arguments,id:e.id,error:t,type:"invalid_tool_call"}}Hh({},{AsymmetricStructuredOutputParser:()=>B$,BaseCumulativeTransformOutputParser:()=>$$,BaseLLMOutputParser:()=>C$,BaseOutputParser:()=>A$,BaseTransformOutputParser:()=>I$,BytesOutputParser:()=>T$,CommaSeparatedListOutputParser:()=>R$,CustomListOutputParser:()=>L$,JsonMarkdownStructuredOutputParser:()=>U$,JsonOutputParser:()=>q$,ListOutputParser:()=>z$,MarkdownListOutputParser:()=>j$,NumberedListOutputParser:()=>M$,OutputParserException:()=>O$,StringOutputParser:()=>D$,StructuredOutputParser:()=>F$,XMLOutputParser:()=>H$,XML_FORMAT_INSTRUCTIONS:()=>G$,parseJsonMarkdown:()=>sg,parsePartialJson:()=>og,parseXMLMarkdown:()=>Z$});var Q$=class extends $${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(_g(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=>J$(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}},eT=class extends Q${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 Vw(this.zodSchema,e);if(t.success)return t.data;throw new O$(`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)))}};Hh({},{JsonOutputKeyToolsParser:()=>eT,JsonOutputToolsParser:()=>Q$,convertLangChainToolCallToOpenAI:()=>Y$,makeInvalidToolCall:()=>X$,parseToolCall:()=>J$});var tT=class extends N${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??ly("OPENAI_API_KEY"),this.organization=e?.configuration?.organization??ly("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(!zx(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&&Fw(e.json_schema.schema)?uE(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=Lx({baseURL:this.clientConfig.baseURL}),t={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};t.baseURL||delete t.baseURL,this.client=new RI(t)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,t){return Zx(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):g$(e)?void 0!==t?.strict?{...e,function:{...e.function,strict:t.strict}}:e:function(e,t){let r;return r=Bx(e)?Vx(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=>Kx(e)||Zx(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(Rx(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(Gx(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&&!lE.includes(t))throw new Error(`Invalid method: ${t}. Supported methods are: ${lE.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=Fw(a)?F$.fromZodSchema(a):new q$;const e=Kk(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:Kw(a),schema:a,strict:t?.strict},s=Kk(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}}}),Fw(a)){const e=F$.fromZodSchema(a);n=mx.from(t=>"parsed"in t.additional_kwargs?t.additional_kwargs.parsed:e)}else n=new q$}else{let e=i??"extract";if(Fw(a)){const i=Kk(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 eT({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=Kk(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 eT({returnSingle:!0,keyName:e})}}if(!s)return r.pipe(n);const c=_$.assign({parsed:(e,t)=>n.invoke(e.raw,t)}),l=_$.assign({parsed:()=>null}),u=c.withFallbacks({fallbacks:[l]});return ux.from([{raw:r},u])}};function rT(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 nT(e){if(!e||"object"!=typeof e)return e;let t;return e.constructor.name===iP.name&&"message"in e&&"string"==typeof e.message?(t=new Error(e.message),t.name="TimeoutError"):e.constructor.name===nP.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")?rT(e,"INVALID_TOOL_RESULTS"):"status"in e&&401===e.status?rT(e,"MODEL_AUTHENTICATION"):"status"in e&&429===e.status?rT(e,"MODEL_RATE_LIMIT"):"status"in e&&404===e.status?rT(e,"MODEL_NOT_FOUND"):e,t}function aT(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=Tx(()=>{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 iT={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=ef({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=Qh(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=Qh(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(!ef({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 sT(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=Rx(e);return"system"===r&&zx(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&&tg.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=aT(t);e&&(yield e)}}(e.contentBlocks))}}(e);let r=Rx(e);"system"===r&&zx(t)&&(r="developer");const n={role:r,content:"string"==typeof e.content?e.content:e.content.map(e=>Wh(e)?tf(e,iT):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=""),_g(e)&&e.tool_calls?.length?(n.tool_calls=e.tool_calls.map(Y$),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 oT="__openai_function_call_ids__";var cT=class extends tT{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=Wx(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 nT(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(J$(e,{returnId:!0}))}catch(t){let r;"object"==typeof t&&null!=t&&"message"in t&&"string"==typeof t.message&&(r=t.message),a.push(X$(e,r))}s[oT]??={},i.id&&(s[oT][i.call_id]=i.id)}else if("reasoning"===i.type)s.reasoning=i;else if("custom_tool_call"===i.type){const e=Yx(i);e?n.push(e):a.push(X$(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:dE(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[oT]={[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=dE(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 G_({text:t.map(e=>e.text).join(""),message:new Sg({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=_g(e)&&"openai"===e.response_metadata?.model_provider;return Array.from(function*(){const r=Tx(()=>{try{const t=Rx(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=Tx(()=>{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=Tx(()=>{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=Rx(e);if("system"===n&&zx(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:Tx(()=>"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?.[oT];_g(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}),Wh(e))return tf(e,iT);if("text"===e.type)return{type:"input_text",text:e.text};if("image_url"===e.type){return{type:"input_image",image_url:Tx(()=>"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:Tx(()=>"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(Kx(n))"image_generation"===n.type&&t?.stream&&(n.partial_images=1),r.push(n);else if(Zx(n)){const e=n.metadata.customTool;r.push({type:"custom",name:e.name,description:e.description,format:e.format})}else g$(n)?r.push({type:"function",name:n.function.name,parameters:n.function.parameters,description:n.function.description,strict:t?.strict??null}):Jx(n)&&r.push(Xx(n));return r}},lT=class extends tT{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:Wx(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),zx(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=sT(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}:{}},_g(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=sT(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 G_({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 G_({message:new Sg({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 nT(e)}})}_convertCompletionsMessageToBaseMessage(e,t){const r=e.tool_calls;if("assistant"===e.role){const n=[],a=[];for(const e of r??[])try{n.push(J$(e,{returnId:!0}))}catch(t){a.push(X$(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 Ng(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 $g({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 Sg({content:a,tool_call_chunks:r,additional_kwargs:i,id:t.id,response_metadata:s})}return"system"===n?new Lg({content:a,response_metadata:s}):"developer"===n?new Lg({content:a,response_metadata:s,additional_kwargs:{__openai_role__:"developer"}}):"function"===n?new Cg({content:a,additional_kwargs:i,name:e.name,response_metadata:s}):"tool"===n?new rg({content:a,additional_kwargs:i,tool_call_id:e.tool_call_id,response_metadata:s}):new kg({content:a,role:n,response_metadata:s})}},uT=class e extends tT{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 cT(e),this.completions=e?.completions??new lT(e)}_useResponsesApi(e){const t=e?.tools?.some(Kx),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(Jx)||e?.tools?.some(Zx);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 dT={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"},pT={azureOpenAIApiKey:"AZURE_OPENAI_API_KEY"},mT=["azureOpenAIApiKey","azureOpenAIApiVersion","azureOpenAIBasePath","azureOpenAIEndpoint","azureOpenAIApiInstanceName","azureOpenAIApiDeploymentName","deploymentName","openAIApiKey","openAIApiVersion"];function hT(e){if(this.azureOpenAIApiKey=e?.azureOpenAIApiKey??e?.openAIApiKey??e?.apiKey??ly("AZURE_OPENAI_API_KEY"),this.azureOpenAIApiInstanceName=e?.azureOpenAIApiInstanceName??ly("AZURE_OPENAI_API_INSTANCE_NAME"),this.azureOpenAIApiDeploymentName=e?.azureOpenAIApiDeploymentName??e?.deploymentName??ly("AZURE_OPENAI_API_DEPLOYMENT_NAME"),this.azureOpenAIApiVersion=e?.azureOpenAIApiVersion??e?.openAIApiVersion??ly("AZURE_OPENAI_API_VERSION"),this.azureOpenAIBasePath=e?.azureOpenAIBasePath??ly("AZURE_OPENAI_BASE_PATH"),this.azureOpenAIEndpoint=e?.azureOpenAIEndpoint??ly("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 fT(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=Lx(e),r={...this.clientConfig,baseURL:t,timeout:this.timeout,maxRetries:0};this.azureADTokenProvider||(r.apiKey=e.azureOpenAIApiKey),r.baseURL||delete r.baseURL;let n=sy();"node"!==n&&"deno"!==n||(n=`(${n}/${process.version}; ${process.platform}; ${process.arch})`);const a=jx(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 LI({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 gT(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 yT=class extends lT{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return"azure_openai"}get lc_aliases(){return{...super.lc_aliases,...dT}}get lc_secrets(){return{...super.lc_secrets,...pT}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...mT]}getLsParams(e){const t=super.getLsParams(e);return t.ls_provider="azure",t}constructor(e){super(e),hT.call(this,e)}_getClientOptions(e){return fT.call(this,e)}toJSON(){return gT.call(this,super.toJSON())}},vT=class extends cT{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return"azure_openai"}get lc_aliases(){return{...super.lc_aliases,...dT}}get lc_secrets(){return{...super.lc_secrets,...pT}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...mT]}getLsParams(e){const t=super.getLsParams(e);return t.ls_provider="azure",t}constructor(e){super(e),hT.call(this,e)}_getClientOptions(e){return fT.call(this,e)}toJSON(){return gT.call(this,super.toJSON())}},bT=class extends uT{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return"azure_openai"}get lc_aliases(){return{...super.lc_aliases,...dT}}get lc_secrets(){return{...super.lc_secrets,...pT}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...mT]}getLsParams(e){const t=super.getLsParams(e);return t.ls_provider="azure",t}constructor(e){super({...e,completions:new yT(e),responses:new vT(e)}),hT.call(this,e)}_getStructuredOutputMethod(e){const t={...e};return this.model.startsWith("gpt-4o")&&void 0===t?.method?"functionCalling":super._getStructuredOutputMethod(t)}toJSON(){return gT.call(this,super.toJSON())}};Hh({},{BaseLLM:()=>_T,LLM:()=>wT});var _T=class e extends b${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 Kb.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 V_({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 Kb.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(ky)&&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:u_(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,q_,{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 Kb.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,q_,{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"}},wT=class extends _T{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}])))}}};Hh({},{chunkArray:()=>ST});const ST=(e,t)=>e.reduce((e,r,n)=>{const a=Math.floor(n/t),i=e[a]||[];return e[a]=i.concat([r]),e},[]);Hh({},{Embeddings:()=>NT});var NT=class{caller;constructor(e){this.caller=new Y_(e??{})}},kT=class extends NT{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??ly("OPENAI_API_KEY");this.organization=t?.configuration?.organization??ly("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=ST(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=Lx({baseURL:this.clientConfig.baseURL}),t={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};t.baseURL||delete t.baseURL,this.client=new RI(t)}const t={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(e,t)}catch(e){throw nT(e)}})}},xT=class extends kT{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;constructor(e){super(e),this.batchSize=e?.batchSize??1,this.azureOpenAIApiKey=e?.azureOpenAIApiKey??e?.apiKey??ly("AZURE_OPENAI_API_KEY"),this.azureOpenAIApiVersion=e?.azureOpenAIApiVersion??e?.openAIApiVersion??ly("AZURE_OPENAI_API_VERSION"),this.azureOpenAIBasePath=e?.azureOpenAIBasePath??ly("AZURE_OPENAI_BASE_PATH"),this.azureOpenAIApiInstanceName=e?.azureOpenAIApiInstanceName??ly("AZURE_OPENAI_API_INSTANCE_NAME"),this.azureOpenAIApiDeploymentName=(e?.azureOpenAIApiEmbeddingsDeploymentName||e?.azureOpenAIApiDeploymentName)??(ly("AZURE_OPENAI_API_EMBEDDINGS_DEPLOYMENT_NAME")||ly("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=Lx(e),r={...this.clientConfig,baseURL:t,timeout:this.timeout,maxRetries:0};this.azureADTokenProvider||(r.apiKey=e.azureOpenAIApiKey),r.baseURL||delete r.baseURL;const n=jx(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 LI({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 nT(e)}})}};Hh({},{BaseToolkit:()=>OT,DynamicStructuredTool:()=>AT,DynamicTool:()=>CT,StructuredTool:()=>PT,Tool:()=>ET,ToolInputParsingException:()=>Bg,isLangChainTool:()=>Bx,isRunnableToolLike:()=>Fx,isStructuredTool:()=>Dx,isStructuredToolParams:()=>Ux,tool:()=>IT});var PT=class extends v${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=n_(t_(this.defaultConfig,t));return Ug(e)?(r=e.args,n={...n,toolCall:e}):r=e,this.call(r,n)}async call(e,t,r){const n=Ug(e)?e.args:e;let a;if(Fw(this.schema))try{a=await Gw(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 ${_w(e.path)}`);return t.join("\n")}(t)}`),new Bg(r,JSON.stringify(e))}else{const t=Hk(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 Bg(r,JSON.stringify(e))}a=n}const i=Ub(t),s=Kb.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;Ug(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&&!eg(t)?"string"==typeof t||Array.isArray(t)&&t.every(e=>"object"==typeof e)?new tg({status:"success",content:t,artifact:r,tool_call_id:n,name:e.name,metadata:a}):new tg({status:"success",content:$T(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}},ET=class extends PT{schema=YN({input:ZN().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)}},CT=class extends ET{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=Ub(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)}},AT=class extends PT{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=Ub(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)}},OT=class{getTools(){return this.tools}};function IT(e,t){const r=Jw(t.schema),n=Zk(t.schema);if(!t.schema||r||n)return new CT({...t,description:t.description??t.schema?.description??`${t.name} tool`,func:async(t,r,n)=>new Promise((a,i)=>{const s=a_(n,{callbacks:r?.getChild()});Qb.runWithConfig(i_(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 AT({...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=a_(n,{callbacks:r?.getChild()});Qb.runWithConfig(i_(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 $T(e){try{return JSON.stringify(e,null,2)??""}catch(t){return`${e}`}}class TT extends sx{lc_namespace=["@equinor","fusion-framework-module-ai"];async invoke(e,t){return _n(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 zT extends TT{#g;get llm(){return this.#g}bindTools(e,t){return this.#g.bindTools(e,t)}constructor(e){super(),this.#g=new bT(e)}async invoke(e,t){return this.#g.invoke(e,t)}invoke$(e){return yn(this.#g.stream(e)).pipe(Rn(e=>yn(e)))}_prepareMessages(e){return e.map(e=>new Ng(e))}}class RT extends Error{constructor(e,t){super(e,t),this.name="ServiceError"}}class LT extends TT{client;constructor(e){super(),this.client=new xT(e)}embedQuery(e){return this.client.embedQuery(e)}embedDocuments(e){return this.client.embedDocuments(e)}invoke$(e){return yn(this.client.embedDocuments(e)).pipe(On(e=>{throw new RT("Azure OpenAI embedding request failed",{cause:e})}))}}Hh({},{BaseRetriever:()=>MT});var MT=class extends sx{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=n_(Ub(t)),n=await Kb.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}}};Hh({},{SaveableVectorStore:()=>FT,VectorStore:()=>DT,VectorStoreRetriever:()=>jT});var jT=class extends MT{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)}},DT=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 jT({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 jT("mmr"===e?.searchType?{...t,searchKwargs:e.searchKwargs}:{...t})}}},FT=class extends DT{static load(e,t){throw new Error("Not implemented")}},UT=class{pageContent;metadata;id;constructor(e){this.pageContent=void 0!==e.pageContent?e.pageContent.toString():"",this.metadata=e.metadata??{},this.id=e.id}},BT=class extends sx{lc_namespace=["langchain_core","documents","transformers"];invoke(e,t){return this.transformDocuments(e)}},qT=class extends BT{async transformDocuments(e){const t=[];for(const r of e){const e=await this._transformDocument(r);t.push(e)}return t}};function VT(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 GT(e,t){let r=0;for(let n=0;n<e.length;n++)r+=e[n]*t[n];return r}function HT(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))}Hh({},{BaseDocumentTransformer:()=>BT,Document:()=>UT,MappingDocumentTransformer:()=>qT});function WT(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 KT(e,t=!1){const r=e.reduce((e,t)=>Math.max(e,QT(t).maxValue),0);return e.map(e=>e.map(e=>t?1-e/r:e/r))}function ZT(e,t){return WT(e,t,VT)}function JT(e,t){return WT(e,t,GT)}function YT(e,t){return WT(e,t,HT)}function XT(e,t,r=.5,n=4){if(Math.min(n,t.length)<=0)return[];const a=ZT(Array.isArray(e[0])?e:[e],t)[0],i=QT(a).maxIndex,s=[t[i]],o=[i];for(;o.length<Math.min(n,t.length);){let e=-1/0,n=-1;const i=ZT(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 QT(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}}Hh({},{cosineSimilarity:()=>ZT,euclideanDistance:()=>YT,innerProduct:()=>JT,matrixFunc:()=>WT,maximalMarginalRelevance:()=>XT,normalize:()=>KT});const ez="similarity",tz="similarity_hybrid",rz="semantic_hybrid",nz="langchainjs-azure-aisearch",az="content",iz="content_vector",sz="metadata";class oz extends DT{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??ly("AZURE_AISEARCH_ENDPOINT"),n=t.key??ly("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 hs(n),this.client=new bd(r,this.indexName,a,{userAgentOptions:{userAgentPrefix:nz}});const e=new Uh(r,a,{userAgentOptions:{userAgentPrefix:nz}});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 Bh(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 Bh(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 Bh(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??tz;if(n===ez)return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r);if(n===tz)return this.hybridSearchVectorWithScore(e,await this.embeddings.embedQuery(e),t,r);if(n===rz)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:[iz]}],filterMode:n?.vectorFilterMode},filter:n?.filterExpression,top:r}),s=[];for await(const e of i){const t=new UT({pageContent:e.document[az],metadata:{...e.document[sz]}});n?.includeEmbeddings&&(t.metadata.embedding=e.document[iz]),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:[iz]}],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 UT({pageContent:e.document[az],metadata:{...e.document[sz]}});n?.includeEmbeddings&&(t.metadata.embedding=e.document[iz]),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:[iz]}],filterMode:r?.vectorFilterMode},filter:r?.filterExpression}),a=[];for await(const e of n){const t=new UT({pageContent:e.document[az],metadata:{...e.document[sz]}});r?.includeEmbeddings&&(t.metadata.embedding=e.document[iz]),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 XT(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:az}],keywordsFields:[{name:az}]}}]},fields:[{name:"id",filterable:!0,key:!0,type:"Edm.String"},{name:az,searchable:!0,filterable:!0,type:"Edm.String"},{name:iz,searchable:!0,type:"Collection(Edm.Single)",vectorSearchDimensions:t,vectorSearchProfileName:"vector-search-profile"},{name:sz,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 UT({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 cz extends TT{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 yn(this.invoke(e)).pipe(Rn(e=>yn(e)),kn(e=>[e]))}asRetriever(e){return this.vectorStore.asRetriever(e)}}const lz=async e=>{const t=new cs;((e,t)=>{e.addConfig({module:ps,configure:t})})(t,t=>{if(e.openaiChatDeployment&&t.setModel(e.openaiChatDeployment,new zT({azureOpenAIApiKey:e.openaiApiKey,azureOpenAIApiDeploymentName:e.openaiChatDeployment,azureOpenAIApiInstanceName:e.openaiInstance,azureOpenAIApiVersion:e.openaiApiVersion})),e.openaiEmbeddingDeployment&&t.setEmbedding(e.openaiEmbeddingDeployment,new LT({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 cz(r,{endpoint:e.azureSearchEndpoint,key:e.azureSearchApiKey,indexName:e.azureSearchIndexName}))}});return await t.initialize()},uz=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 lz(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 _$).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=ux.from([s,n,new D$]),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=oe({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="";yn(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("")}}),dz=Kn(uz,{includeChat:!0,includeEmbedding:!0,includeSearch:!0}),pz=(e,t)=>{const r=Buffer.from(e).toString("base64").replace(/[^a-zA-Z0-9]/g,"");return t?`${r}-${t}`:r},mz={chunkSize:2e3,chunkOverlap:200,separators:["\n# ","\n## ","\n```"]},hz=e=>e.endsWith(".md"),fz=async e=>{Oe(hz(e.path),`File ${e.path} is not a markdown file`);const t=D(e.path,"utf8"),r=await(async(e,t)=>{const{content:r,data:n}=Ie(e),a=Object.entries(n).reduce((e,[t,r])=>(e[`md_${t}`]=r,e),{type:"markdown"}),i=new $e(mz);return(await i.splitText(r)).map((e,r)=>({id:pz(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}}))},gz=[Te.FunctionDeclaration,Te.ClassDeclaration,Te.InterfaceDeclaration,Te.TypeAliasDeclaration,Te.VariableStatement,Te.EnumDeclaration],yz=(e,t,r,n)=>{const a=e.getKind();if(!gz.includes(a))return null;if(a===Te.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(Te.PublicKeyword)),...e.getProperties().filter(e=>e.hasModifier(Te.PublicKeyword))].forEach(e=>{const t=e.getLeadingCommentRanges().find(e=>e.getText().startsWith("/**"));if(t){const r=t.getText();let n="";e.getKind()===Te.MethodDeclaration?n=e.getText({includeJsDocComments:!1}).split("{")[0].trim():e.getKind()===Te.PropertyDeclaration&&(n=e.getText({includeJsDocComments:!1}).trim()),i+=`\n ${r}\n ${n}`}}),i+="\n}";const o=t.getFilePath();return{id:pz(o),pageContent:i,metadata:{source:o,attributes:{type:"tsdoc",ts_kind:e.getKindName(),ts_name:a}}}})(e,t);if(a===Te.VariableStatement){const n=e.getDeclarations().find(e=>e.getKind()===Te.VariableDeclaration);if(!n)return null;const a=n.getInitializer();if(!a||a.getKind()!==Te.ArrowFunction&&a.getKind()!==Te.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:pz(c),pageContent:o,metadata:{source:c,rootPath:r?.projectRoot,attributes:{type:"tsdoc",ts_kind:a.getKindName(),ts_name:s}}}}const i=ze.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===Te.InterfaceDeclaration||a===Te.TypeAliasDeclaration)c=`${o}\n${e.getText()}`;else if(a!==Te.FunctionDeclaration)return null;return{id:pz(l),pageContent:c,metadata:{source:l,rootPath:r?.projectRoot,attributes:{type:"tsdoc",ts_kind:e.getKindName(),ts_name:i}}}},vz=e=>e.endsWith(".ts")||e.endsWith(".tsx"),bz=(e,t)=>{Oe(vz(e.path),`File ${e.path} is not a TypeScript file`);return((e,t)=>{const r=[];return e.forEachDescendant(n=>{const a=yz(n,e,t);a&&r.push(a)}),r})(new Re({useInMemoryFileSystem:!0}).createSourceFile(e.relativePath??e.path,D(e.path,"utf8")),t)},_z=new Map,wz=e=>{if(B(u(e,".git")))return e;const t=Le(".git",{cwd:l(e),type:"both"}),r=t?.replace(/\.git$/,"");return r},Sz=e=>{const t=wz(e);if(t)return _z.has(t)||_z.set(t,ae(t)),{git:_z.get(t),gitRepoPath:t}},Nz=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")).addOption(t("--clean","Delete all existing documents from the vector store before processing").default(!1)).argument("[glob-patterns...]","Glob patterns to match files (optional when using --diff)").action(async(e,t)=>{const r=await Ce(t.config,{baseDir:process.cwd()}).then(e=>e.config()),n=r.patterns??["**/*.ts","**/*.md"],a=e.length?e:n,i=await lz(t),s=i.ai.getService("embeddings",t.openaiEmbeddingDeployment);if(t.clean){const e=i.ai.getService("search",t.azureSearchIndexName);t.dryRun||(console.log("🧹 Cleaning vector store: deleting all existing documents..."),await e.deleteDocuments({filter:{filterExpression:"metadata/source ne ''"}}),console.log("✅ Vector store cleaned successfully"))}let c=[];if(t.diff)try{const e=await(async(e=process.cwd())=>{if(!wz(e))throw new Error("Not in a git repository");const{git:t}=Sz(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: ${e.branch}@${e.commit}`),console.log(`📊 Changes: ${e.stagedFiles} staged, ${e.unstagedFiles} unstaged`),c=await(async e=>{const{diff:t,baseRef:r="HEAD~1",cwd:n=process.cwd()}=e;if(!t)return[];const a=wz(n);if(!a)throw new Error("Not in a git repository. Cannot use --diff option.");const{git:i}=Sz(n)??{};if(!i)throw new Error("Failed to initialize git client");try{try{const e=(await i.diff([`${r}`,"--name-status"])).split("\n").filter(e=>""!==e.trim()),t=[];for(const r of e){const e=r.match(/^([AMD])\s+(.+)$/);if(e){const[,r,n]=e,i=`${a}/${n}`;let s;if("A"===r)s="new";else if("M"===r)s="modified";else{if("D"!==r)continue;s="removed"}t.push({filepath:i,status:s})}}return t}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}),0===c.length&&(console.log("✅ No changed files match the provided patterns. Nothing to process."),process.exit(0)),console.log(`📝 Found ${c.length} changed files matching patterns`)}catch(e){console.error(`❌ Git diff error: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}const l=t.diff?yn(c):yn(Pe(a,{onlyFiles:!0,gitignore:!0,absolute:!0})).pipe(xn(e=>(async e=>{const{git:t,gitRepoPath:r}=Sz(e)??{};if(!t||!r)return[{filepath:e,status:"new"}];const n=d(r,e).replace(/\\/g,"/");try{if(await t.raw(["ls-files","--error-unmatch",n]).then(()=>!0).catch(()=>!1))return[{filepath:e,status:"modified"}];try{const r=(await t.raw(["status","--porcelain","--",n])).trim();if(r.length>0&&/^\?\?/.test(r))return[{filepath:e,status:"new"}]}catch{}try{const n=(await t.raw(["status","--porcelain"])).split("\n").filter(e=>""!==e.trim());for(const t of n){const n=t.match(/^R\d+\s+(.+?)\s+(.+)$/);if(n){const[,t,a]=n,i=u(r,t),s=u(r,a);if(s===e)return[{filepath:i,status:"removed"},{filepath:s,status:"new"}]}const a=t.match(/^C\d+\s+(.+?)\s+(.+)$/);if(a){const[,,t]=a,n=u(r,t);if(n===e)return[{filepath:n,status:"new"}]}}}catch{}try{return[{filepath:e,status:await t.raw(["log","--all","--full-history","--follow","--oneline","-1","--",n]).then(e=>e.trim().length>0).catch(()=>!1)?"modified":"new"}]}catch{return[{filepath:e,status:"new"}]}}catch{return[{filepath:e,status:"new"}]}})(e)),Rn(e=>yn(e)),jn({refCount:!0})),p=l.pipe(kn(e=>{const{filepath:t,status:r}=e,n=wz(t);return{path:t,status:r,projectRoot:n,relativePath:n?d(n,t):t}}),An(e=>Ee(e.relativePath,n).length>0),Dn(e=>console.log("🔍 processing file",e.relativePath)),jn({refCount:!0})),m=p.pipe(An(e=>"removed"===e.status)),h=p.pipe(An(e=>"new"===e.status||"modified"===e.status),jn({refCount:!0})),f=m.pipe(zn(),kn(e=>{if(0===e.length)return{files:[],filterExpression:null};const t=e.map(e=>`metadata/source eq '${e.relativePath}'`).join(" or ");return{files:e,filterExpression:t}}),xn(async({files:e,filterExpression:r})=>{if(0!==e.length){for(const t of e)console.log("Removing entry from vector store",t.relativePath);if(!t.dryRun){const e=i.ai.getService("search",t.azureSearchIndexName);await e.deleteDocuments({filter:{filterExpression:r}})}return{status:"deleted",files:e}}}),An(e=>Boolean(e))),g=Cn(h.pipe(An(e=>hz(e.path)),xn(async e=>{const t=await fz(e);return{status:e.status,documents:t}})),h.pipe(An(e=>vz(e.path)),kn(e=>{const t=bz(e);return{status:e.status,documents:t}}))).pipe(xn(e=>yn(e.documents).pipe(xn(async e=>{const t=e.metadata.source?await(async e=>{const{git:t,gitRepoPath:r}=Sz(e)??{};if(!t||!r)return;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}}}}),kn(e=>{const t=r.metadata?.attributeProcessor||((e,t)=>e),n=t(e.metadata.attributes??{},e);return{...e,metadata:{...e.metadata,attributes:n}}}),zn()))).pipe(xn(e=>yn(e).pipe(xn(async e=>{console.log("embedding document",e.metadata.source);const t=await s.embedQuery(e.pageContent),r={...e.metadata,embedding:t};return{...e,metadata:r}}),zn()))),y=g.pipe(xn(async e=>{const r=i.ai.getService("search",t.azureSearchIndexName);if(0!==e.length){for(const t of e)console.log(`Adding entry [${t.id}] to vector store`,t.metadata.source);if(!t.dryRun){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}})}await r.addDocuments(e)}return{status:"added",documents:e}}}),An(e=>Boolean(e))),v={deleted:[],added:[]};En(f,y).subscribe({next:e=>{"deleted"===e.status?v.deleted.push(...e.files.map(e=>e.relativePath)):"added"===e.status&&v.added.push(...e.documents.map(e=>({source:e.metadata.source,id:e.id})))},error:e=>{console.error(`❌ Error: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)},complete:()=>{console.log("🗂️ Indexing results:",v),console.log("✅ Embeddings generation completed!"),process.exit(0)}})}),kz=Kn(Nz,{includeEmbedding:!0,includeSearch:!0}),xz=e=>{const t={...e};if(Array.isArray(t.attributes)){const e={};for(const r of t.attributes)if("object"==typeof r&&null!==r&&"key"in r&&"value"in r&&"string"==typeof r.key)try{e[r.key]=JSON.parse(r.value)}catch{e[r.key]=r.value}Object.assign(t,e),delete t.attributes}return t},Pz=Kn(e("search").description("Search the vector store to validate embeddings and retrieve relevant documents").addOption(t("--limit <number>","Maximum number of results to return").default(10).argParser(parseInt)).addOption(t("--filter <expression>","OData filter expression for metadata filtering")).addOption(t("--json","Output results as JSON").default(!1)).addOption(t("--raw","Output raw metadata without normalization").default(!1)).addOption(t("--verbose","Enable verbose output").default(!1)).argument("<query>","Search query string").action(async(e,t)=>{t.verbose&&console.log("🔍 Initializing framework...");const r=await lz(t);if(!t.azureSearchIndexName)throw new Error("Azure Search index name is required");t.verbose&&(console.log("✅ Framework initialized successfully"),console.log(`🔎 Searching for: "${e}"`),console.log(`📊 Limit: ${t.limit}`),t.filter&&console.log(`🔧 Filter: ${t.filter}`),console.log(""));const n=r.ai.getService("search",t.azureSearchIndexName);try{const r={k:t.limit};t.filter&&(r.filter={filterExpression:t.filter});const a=n.asRetriever(r),i=await a.invoke(e);if(t.json)for(const e of i)if(t.raw)console.log(le(e,{depth:null,colors:!0}));else{const t=xz(e.metadata);console.log({content:e.pageContent,metadata:t,score:t?.score})}else{if(0===i.length)return void console.log("❌ No results found");console.log(`✅ Found ${i.length} result${1!==i.length?"s":""}:\n`),i.forEach((e,r)=>{const n=t.raw?e.metadata:xz(e.metadata),a=n.score,i=n.source||"Unknown source";if(console.log(`${"─".repeat(80)}`),console.log(`Result ${r+1}${void 0!==a?` (Score: ${a.toFixed(4)})`:""}`),console.log(`Source: ${i}`),t.verbose){const{source:e,score:t,...r}=n;Object.keys(r).length>0&&console.log("Metadata:",JSON.stringify(r,null,2))}console.log("");const s=e.pageContent;s.length>500?(console.log(`${s.substring(0,500)}...`),console.log(`\n[Content truncated - ${s.length} characters total]`)):console.log(s),console.log("")}),console.log(`${"─".repeat(80)}`)}}catch(e){console.error(`❌ Search failed: ${e instanceof Error?e.message:"Unknown error"}`),t.verbose&&e instanceof Error&&e.stack&&console.error(e.stack),process.exit(1)}}),{includeEmbedding:!0,includeSearch:!0}),Ez=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"," search Search the vector store to validate embeddings","","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",' $ ffc ai search "how to use the framework"'].join("\n")).addCommand(dz).addCommand(kz).addCommand(Pz),Cz=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..."),E({server:{port:Number(e.port)},log:t,env:e.env}),t.succeed("Development server started successfully.")});var Az,Oz,Iz,$z,Tz,zz,Rz,Lz,Mz,jz,Dz=["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"],Fz=["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"],Uz=["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 Bz(){if(Oz)return Az;Oz=1;var e=[].concat(Dz).concat(Fz),t=Uz;return Az=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},Az}function qz(){return $z||($z=1,Iz=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}),Iz}function Vz(){if(zz)return Tz;zz=1;var e=Bz(),t=qz();return Tz=function(r){return t(e(r))}}function Gz(){if(jz)return Mz;jz=1;var e=Vz(),t=function(){if(Lz)return Rz;Lz=1;var e=Vz(),t=Dz;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 Rz=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 Mz=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 Hz,Wz,Kz,Zz,Jz,Yz,Xz,Qz,eR,tR,rR,nR={};function aR(){if(Hz)return nR;Hz=1,Object.defineProperty(nR,"__esModule",{value:!0}),nR.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#y=!1;static create(e){const t=o(e);if(!t)return[];l.#y=!0;const r=new l(e,t);return l.#y=!1,r}constructor(e,t){if(!l.#y)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{#v;#b;#_;#w;#S;#N;#k;#x;get perf(){return this.#x}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#P;#E;#C;#A;#O;#I;#$;#T;#z;#R;#L;#M;#j;#D;#F;#U;#B;#q;static unsafeExposeInternals(e){return{starts:e.#j,ttls:e.#D,sizes:e.#M,keyMap:e.#C,keyList:e.#A,valList:e.#O,next:e.#I,prev:e.#$,get head(){return e.#T},get tail(){return e.#z},free:e.#R,isBackgroundFetch:t=>e.#V(t),backgroundFetch:(t,r,n,a)=>e.#G(t,r,n,a),moveToTail:t=>e.#H(t),indexes:t=>e.#W(t),rindexes:t=>e.#K(t),isStale:t=>e.#Z(t)}}get max(){return this.#v}get maxSize(){return this.#b}get calculatedSize(){return this.#E}get size(){return this.#P}get fetchMethod(){return this.#N}get memoMethod(){return this.#k}get dispose(){return this.#_}get onInsert(){return this.#w}get disposeAfter(){return this.#S}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:P,allowStaleOnFetchRejection:E,allowStaleOnFetchAbort:C,ignoreFetchAbort:A,perf:O}=r;if(void 0!==O&&"function"!=typeof O?.now)throw new TypeError("perf option must have a now() method if specified");if(this.#x=O??e,0!==a&&!s(a))throw new TypeError("max option must be a nonnegative integer");const I=a?o(a):Array;if(!I)throw new Error("invalid max value: "+a);if(this.#v=a,this.#b=_,this.maxEntrySize=w||this.#b,this.sizeCalculation=S,this.sizeCalculation){if(!this.#b&&!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.#k=k,void 0!==N&&"function"!=typeof N)throw new TypeError("fetchMethod must be a function if specified");if(this.#N=N,this.#U=!!N,this.#C=new Map,this.#A=new Array(a).fill(void 0),this.#O=new Array(a).fill(void 0),this.#I=new I(a),this.#$=new I(a),this.#T=0,this.#z=0,this.#R=l.create(a),this.#P=0,this.#E=0,"function"==typeof f&&(this.#_=f),"function"==typeof g&&(this.#w=g),"function"==typeof y?(this.#S=y,this.#L=[]):(this.#S=void 0,this.#L=void 0),this.#F=!!this.#_,this.#q=!!this.#w,this.#B=!!this.#S,this.noDisposeOnSet=!!v,this.noUpdateTTL=!!b,this.noDeleteOnFetchRejection=!!x,this.allowStaleOnFetchRejection=!!E,this.allowStaleOnFetchAbort=!!C,this.ignoreFetchAbort=!!A,0!==this.maxEntrySize){if(0!==this.#b&&!s(this.#b))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.#J()}if(this.allowStale=!!h,this.noDeleteOnStaleGet=!!P,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.#Y()}if(0===this.#v&&0===this.ttl&&0===this.#b)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#v&&!this.#b){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.#C.has(e)?1/0:0}#Y(){const e=new c(this.#v),t=new c(this.#v);this.#D=e,this.#j=t,this.#X=(r,n,a=this.#x.now())=>{if(t[r]=0!==n?a:0,e[r]=n,0!==n&&this.ttlAutopurge){const e=setTimeout(()=>{this.#Z(r)&&this.#Q(this.#A[r],"expire")},n+1);e.unref&&e.unref()}},this.#ee=r=>{t[r]=0!==e[r]?this.#x.now():0},this.#te=(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.#x.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.#C.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.#Z=a=>{const i=t[a],s=e[a];return!!s&&!!i&&(r||n())-i>s}}#ee=()=>{};#te=()=>{};#X=()=>{};#Z=()=>!1;#J(){const e=new c(this.#v);this.#E=0,this.#M=e,this.#re=t=>{this.#E-=e[t],e[t]=0},this.#ne=(e,t,r,n)=>{if(this.#V(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.#ae=(t,r,n)=>{if(e[t]=r,this.#b){const r=this.#b-e[t];for(;this.#E>r;)this.#ie(!0)}this.#E+=e[t],n&&(n.entrySize=r,n.totalCalculatedSize=this.#E)}}#re=e=>{};#ae=(e,t,r)=>{};#ne=(e,t,r,n)=>{if(r||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#W({allowStale:e=this.allowStale}={}){if(this.#P)for(let t=this.#z;this.#se(t)&&(!e&&this.#Z(t)||(yield t),t!==this.#T);)t=this.#$[t]}*#K({allowStale:e=this.allowStale}={}){if(this.#P)for(let t=this.#T;this.#se(t)&&(!e&&this.#Z(t)||(yield t),t!==this.#z);)t=this.#I[t]}#se(e){return void 0!==e&&this.#C.get(this.#A[e])===e}*entries(){for(const e of this.#W())void 0===this.#O[e]||void 0===this.#A[e]||this.#V(this.#O[e])||(yield[this.#A[e],this.#O[e]])}*rentries(){for(const e of this.#K())void 0===this.#O[e]||void 0===this.#A[e]||this.#V(this.#O[e])||(yield[this.#A[e],this.#O[e]])}*keys(){for(const e of this.#W()){const t=this.#A[e];void 0===t||this.#V(this.#O[e])||(yield t)}}*rkeys(){for(const e of this.#K()){const t=this.#A[e];void 0===t||this.#V(this.#O[e])||(yield t)}}*values(){for(const e of this.#W()){void 0===this.#O[e]||this.#V(this.#O[e])||(yield this.#O[e])}}*rvalues(){for(const e of this.#K()){void 0===this.#O[e]||this.#V(this.#O[e])||(yield this.#O[e])}}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(const r of this.#W()){const n=this.#O[r],a=this.#V(n)?n.__staleWhileFetching:n;if(void 0!==a&&e(a,this.#A[r],this))return this.get(this.#A[r],t)}}forEach(e,t=this){for(const r of this.#W()){const n=this.#O[r],a=this.#V(n)?n.__staleWhileFetching:n;void 0!==a&&e.call(t,a,this.#A[r],this)}}rforEach(e,t=this){for(const r of this.#K()){const n=this.#O[r],a=this.#V(n)?n.__staleWhileFetching:n;void 0!==a&&e.call(t,a,this.#A[r],this)}}purgeStale(){let e=!1;for(const t of this.#K({allowStale:!0}))this.#Z(t)&&(this.#Q(this.#A[t],"expire"),e=!0);return e}info(e){const t=this.#C.get(e);if(void 0===t)return;const r=this.#O[t],n=this.#V(r)?r.__staleWhileFetching:r;if(void 0===n)return;const a={value:n};if(this.#D&&this.#j){const e=this.#D[t],r=this.#j[t];if(e&&r){const t=e-(this.#x.now()-r);a.ttl=t,a.start=Date.now()}}return this.#M&&(a.size=this.#M[t]),a}dump(){const e=[];for(const t of this.#W({allowStale:!0})){const r=this.#A[t],n=this.#O[t],a=this.#V(n)?n.__staleWhileFetching:n;if(void 0===a||void 0===r)continue;const i={value:a};if(this.#D&&this.#j){i.ttl=this.#D[t];const e=this.#x.now()-this.#j[t];i.start=Math.floor(Date.now()-e)}this.#M&&(i.size=this.#M[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.#x.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.#ne(e,t,r.size||0,s);if(this.maxEntrySize&&l>this.maxEntrySize)return o&&(o.set="miss",o.maxEntrySizeExceeded=!0),this.#Q(e,"set"),this;let u=0===this.#P?void 0:this.#C.get(e);if(void 0===u)u=0===this.#P?this.#z:0!==this.#R.length?this.#R.pop():this.#P===this.#v?this.#ie(!1):this.#P,this.#A[u]=e,this.#O[u]=t,this.#C.set(e,u),this.#I[this.#z]=u,this.#$[u]=this.#z,this.#z=u,this.#P++,this.#ae(u,l,o),o&&(o.set="add"),c=!1,this.#q&&this.#w?.(t,e,"add");else{this.#H(u);const r=this.#O[u];if(t!==r){if(this.#U&&this.#V(r)){r.__abortController.abort(new Error("replaced"));const{__staleWhileFetching:t}=r;void 0===t||i||(this.#F&&this.#_?.(t,e,"set"),this.#B&&this.#L?.push([t,e,"set"]))}else i||(this.#F&&this.#_?.(r,e,"set"),this.#B&&this.#L?.push([r,e,"set"]));if(this.#re(u),this.#ae(u,l,o),this.#O[u]=t,o){o.set="replace";const e=r&&this.#V(r)?r.__staleWhileFetching:r;void 0!==e&&(o.oldValue=e)}}else o&&(o.set="update");this.#q&&this.onInsert?.(t,e,t===r?"update":"replace")}if(0===n||this.#D||this.#Y(),this.#D&&(c||this.#X(u,n,a),o&&this.#te(o,u)),!i&&this.#B&&this.#L){const e=this.#L;let t;for(;t=e?.shift();)this.#S?.(...t)}return this}pop(){try{for(;this.#P;){const e=this.#O[this.#T];if(this.#ie(!0),this.#V(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(void 0!==e)return e}}finally{if(this.#B&&this.#L){const e=this.#L;let t;for(;t=e?.shift();)this.#S?.(...t)}}}#ie(e){const t=this.#T,r=this.#A[t],n=this.#O[t];return this.#U&&this.#V(n)?n.__abortController.abort(new Error("evicted")):(this.#F||this.#B)&&(this.#F&&this.#_?.(n,r,"evict"),this.#B&&this.#L?.push([n,r,"evict"])),this.#re(t),e&&(this.#A[t]=void 0,this.#O[t]=void 0,this.#R.push(t)),1===this.#P?(this.#T=this.#z=0,this.#R.length=0):this.#T=this.#I[t],this.#C.delete(r),this.#P--,t}has(e,t={}){const{updateAgeOnHas:r=this.updateAgeOnHas,status:n}=t,a=this.#C.get(e);if(void 0!==a){const e=this.#O[a];if(this.#V(e)&&void 0===e.__staleWhileFetching)return!1;if(!this.#Z(a))return r&&this.#ee(a),n&&(n.has="hit",this.#te(n,a)),!0;n&&(n.has="stale",this.#te(n,a))}else n&&(n.has="miss");return!1}peek(e,t={}){const{allowStale:r=this.allowStale}=t,n=this.#C.get(e);if(void 0===n||!r&&this.#Z(n))return;const a=this.#O[n];return this.#V(a)?a.__staleWhileFetching:a}#G(e,t,r,n){const i=void 0===t?void 0:this.#O[t];if(this.#V(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.#O[t]===d&&(void 0===n?void 0!==l.__staleWhileFetching?this.#O[t]=l.__staleWhileFetching:this.#Q(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.#O[t]===d){!c||void 0===l.__staleWhileFetching?this.#Q(e,"fetch"):i||(this.#O[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.#N?.(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.#C.get(e)):this.#O[t]=p,p}#V(e){if(!this.#U)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.#U)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.#C.get(e);if(void 0===b){g&&(g.fetch="miss");const t=this.#G(e,b,v,h);return t.__returned=t}{const t=this.#O[b];if(this.#V(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.#Z(b);if(!f&&!a)return g&&(g.fetch="hit"),this.#H(b),n&&this.#ee(b),g&&this.#te(g,b),t;const i=this.#G(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.#k;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.#C.get(e);if(void 0!==s){const t=this.#O[s],o=this.#V(t);return i&&this.#te(i,s),this.#Z(s)?(i&&(i.get="stale"),o?(i&&r&&void 0!==t.__staleWhileFetching&&(i.returnedStale=!0),r?t.__staleWhileFetching:void 0):(a||this.#Q(e,"expire"),i&&r&&(i.returnedStale=!0),r?t:void 0)):(i&&(i.get="hit"),o?t.__staleWhileFetching:(this.#H(s),n&&this.#ee(s),t))}i&&(i.get="miss")}#oe(e,t){this.#$[t]=e,this.#I[e]=t}#H(e){e!==this.#z&&(e===this.#T?this.#T=this.#I[e]:this.#oe(this.#$[e],this.#I[e]),this.#oe(this.#z,e),this.#z=e)}delete(e){return this.#Q(e,"delete")}#Q(e,t){let r=!1;if(0!==this.#P){const n=this.#C.get(e);if(void 0!==n)if(r=!0,1===this.#P)this.#ce(t);else{this.#re(n);const r=this.#O[n];if(this.#V(r)?r.__abortController.abort(new Error("deleted")):(this.#F||this.#B)&&(this.#F&&this.#_?.(r,e,t),this.#B&&this.#L?.push([r,e,t])),this.#C.delete(e),this.#A[n]=void 0,this.#O[n]=void 0,n===this.#z)this.#z=this.#$[n];else if(n===this.#T)this.#T=this.#I[n];else{const e=this.#$[n];this.#I[e]=this.#I[n];const t=this.#I[n];this.#$[t]=this.#$[n]}this.#P--,this.#R.push(n)}}if(this.#B&&this.#L?.length){const e=this.#L;let t;for(;t=e?.shift();)this.#S?.(...t)}return r}clear(){return this.#ce("delete")}#ce(e){for(const t of this.#K({allowStale:!0})){const r=this.#O[t];if(this.#V(r))r.__abortController.abort(new Error("deleted"));else{const n=this.#A[t];this.#F&&this.#_?.(r,n,e),this.#B&&this.#L?.push([r,n,e])}}if(this.#C.clear(),this.#O.fill(void 0),this.#A.fill(void 0),this.#D&&this.#j&&(this.#D.fill(0),this.#j.fill(0)),this.#M&&this.#M.fill(0),this.#T=0,this.#z=0,this.#R.length=0,this.#E=0,this.#P=0,this.#B&&this.#L){const e=this.#L;let t;for(;t=e?.shift();)this.#S?.(...t)}}}return nR.LRUCache=u,nR}function iR(){if(Jz)return Zz;Jz=1;const e=_e,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 Zz=(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))},Zz}function sR(){if(Xz)return Yz;Xz=1;const e=iR();return Yz=(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 oR(){if(eR)return Qz;eR=1;const{LRUCache:e}=aR(),t=function(){if(Kz)return Wz;Kz=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 Wz=a}(),r=sR(),n=iR(),a=new e({max:1e3});class i{constructor(e,t,r,n,a,s,o={}){Object.assign(this,i.#le[e],{type:e,user:t,auth:r,project:n,committish:a,default:s,opts:o})}static#le={byShortcut:{},byDomain:{}};static#ue={"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.#le[e]=t,i.#le.byDomain[t.domain]=e,i.#le.byShortcut[`${e}:`]=e,i.#ue[`${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.#le,protocols:i.#ue});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)}#de(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.#de(this.sshtemplate,e)}sshurl(e){return this.#de(this.sshurltemplate,e)}browse(e,...t){return"string"!=typeof e?this.#de(this.browsetemplate,e):"string"!=typeof t[0]?this.#de(this.browsetreetemplate,{...t[0],path:e}):this.#de(this.browsetreetemplate,{...t[1],fragment:t[0],path:e})}browseFile(e,...t){return"string"!=typeof t[0]?this.#de(this.browseblobtemplate,{...t[0],path:e}):this.#de(this.browseblobtemplate,{...t[1],fragment:t[0],path:e})}docs(e){return this.#de(this.docstemplate,e)}bugs(e){return this.#de(this.bugstemplate,e)}https(e){return this.#de(this.httpstemplate,e)}git(e){return this.#de(this.gittemplate,e)}shortcut(e){return this.#de(this.shortcuttemplate,e)}path(e){return this.#de(this.pathtemplate,e)}tarball(e){return this.#de(this.tarballtemplate,{...e,noCommittish:!1})}file(e,t){return this.#de(this.filetemplate,{...t,path:e})}edit(e,t){return this.#de(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 Qz=i}var cR,lR,uR={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(lR)return cR;lR=1;var{URL:e}=i,t=Di(),r=Fi(),n=Gz(),a=oR(),{isBuiltin:s}=Me,o=["dependencies","devDependencies","optionalDependencies"],c=rR?tR:(rR=1,tR=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=uR,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 cR={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")}},cR}var pR,mR,hR,fR,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 yR(){if(mR)return pR;mR=1;var e=ye,t=gR;function r(r,n,a){return a&&(r=a+"['"+r+"']",n=a+"['"+n+"']"),e.format(t.typo,r,n)}return pR=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)},pR}!function(){if(fR)return hR;fR=1,hR=n;var e=dR();n.fixer=e;var t=yR(),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 vR=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),kt(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 bR,_R={exports:{}},wR={},SR={},NR={},kR={},xR={},PR={};function ER(){return bR||(bR=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())}}(PR)),PR}var CR,AR,OR={};function IR(){return CR||(CR=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=ER();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}}}(OR)),OR}function $R(){return AR||(AR=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=ER(),r=IR();var n=ER();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=IR();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)||(O(e,a.names),r.splice(n,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>E(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(I(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&&E(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 E(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 E(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&&E(e,this.catch.names),this.finally&&E(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 P extends h{render(e){return"finally"+super.render(e)}}P.kind="finally";function E(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?E(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 O(e,t){for(const r in t)e[r]=(e[r]||0)-(t[r]||0)}function I(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 P,this.code(r)),this._endBlockNode(x,P)}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=I;const $=z(e.operators.AND);e.and=function(...e){return e.reduce($)};const T=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(T)}}(xR)),xR}var TR,zR={};function RR(){if(TR)return zR;TR=1,Object.defineProperty(zR,"__esModule",{value:!0}),zR.checkStrictMode=zR.getErrorPath=zR.Type=zR.useFunc=zR.setEvaluated=zR.evaluatedPropsToName=zR.mergeEvaluated=zR.eachItem=zR.unescapeJsonPointer=zR.escapeJsonPointer=zR.escapeFragment=zR.unescapeFragment=zR.schemaRefOrVal=zR.schemaHasRulesButRef=zR.schemaHasRules=zR.checkUnknownRules=zR.alwaysValidSchema=zR.toHash=void 0;const e=$R(),t=ER();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))}zR.toHash=function(e){const t={};for(const r of e)t[r]=!0;return t},zR.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(r(e,t),!n(t,e.self.RULES.all))},zR.checkUnknownRules=r,zR.schemaHasRules=n,zR.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},zR.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)}`},zR.unescapeFragment=function(e){return i(decodeURIComponent(e))},zR.escapeFragment=function(e){return encodeURIComponent(a(e))},zR.escapeJsonPointer=a,zR.unescapeJsonPointer=i,zR.eachItem=function(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)},zR.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)})},zR.evaluatedPropsToName=o,zR.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 zR.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||(zR.Type=u={})),zR.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)},zR.checkStrictMode=d,zR}var LR,MR,jR,DR={};function FR(){if(LR)return DR;LR=1,Object.defineProperty(DR,"__esModule",{value:!0});const e=$R(),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 DR.default=t,DR}function UR(){return MR||(MR=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=$R(),r=RR(),n=FR();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]}}(kR)),kR}var BR,qR={},VR={};function GR(){if(BR)return VR;BR=1,Object.defineProperty(VR,"__esModule",{value:!0}),VR.getRules=VR.isJSONType=void 0;const e=new Set(["string","number","integer","boolean","null","object","array"]);return VR.isJSONType=function(t){return"string"==typeof t&&e.has(t)},VR.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:{}}},VR}var HR,WR,KR={};function ZR(){if(HR)return KR;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 HR=1,Object.defineProperty(KR,"__esModule",{value:!0}),KR.shouldUseRule=KR.shouldUseGroup=KR.schemaHasRulesForType=void 0,KR.schemaHasRulesForType=function({schema:t,self:r},n){const a=r.RULES.types[n];return a&&!0!==a&&e(t,a)},KR.shouldUseGroup=e,KR.shouldUseRule=t,KR}function JR(){if(WR)return qR;WR=1,Object.defineProperty(qR,"__esModule",{value:!0}),qR.reportTypeError=qR.checkDataTypes=qR.checkDataType=qR.coerceAndCheckDataType=qR.getJSONTypes=qR.getSchemaTypes=qR.DataType=void 0;const e=GR(),t=ZR(),r=UR(),n=$R(),a=RR();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||(qR.DataType=i={})),qR.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},qR.getJSONTypes=s,qR.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}qR.checkDataType=c,qR.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 qR.reportTypeError=d,qR}var YR,XR={};var QR,eL,tL={},rL={};function nL(){if(QR)return rL;QR=1,Object.defineProperty(rL,"__esModule",{value:!0}),rL.validateUnion=rL.validateArray=rL.usePattern=rL.callValidateCode=rL.schemaProperties=rL.allSchemaProperties=rL.noPropertyInData=rL.propertyInData=rL.isOwnProperty=rL.hasPropFunc=rL.reportMissingProp=rL.checkMissingProp=rL.checkReportMissingProp=void 0;const e=$R(),t=RR(),r=FR(),n=RR();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):[]}rL.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()})},rL.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}`)))},rL.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},rL.hasPropFunc=a,rL.isOwnProperty=i,rL.propertyInData=function(t,r,n,a){const s=e._`${r}${(0,e.getProperty)(n)} !== undefined`;return a?e._`${s} && ${i(t,r,n)}`:s},rL.noPropertyInData=s,rL.allSchemaProperties=o,rL.schemaProperties=function(e,r){return o(r).filter(n=>!(0,t.alwaysValidSchema)(e,r[n]))},rL.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 rL.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})`})},rL.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)})}},rL.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))},rL}function aL(){if(eL)return tL;eL=1,Object.defineProperty(tL,"__esModule",{value:!0}),tL.validateKeywordUsage=tL.validSchemaType=tL.funcKeywordCode=tL.macroKeywordCode=void 0;const e=$R(),t=FR(),r=nL(),n=UR();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 tL.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))},tL.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)},tL.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)},tL.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)}}},tL}var iL,sL={};var oL,cL,lL={};function uL(){return cL||(cL=1,oL=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}),oL}var dL,pL,mL,hL={exports:{}};function fL(){if(dL)return hL.exports;dL=1;var e=hL.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},hL.exports}function gL(){if(pL)return lL;pL=1,Object.defineProperty(lL,"__esModule",{value:!0}),lL.getSchemaRefs=lL.resolveUrl=lL.normalizeId=lL._getFullPath=lL.getFullPath=lL.inlineRef=void 0;const e=RR(),t=uL(),r=fL(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);lL.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]+"#"}lL.getFullPath=o,lL._getFullPath=c;const l=/#\/?$/;function u(e){return e?e.replace(l,""):""}lL.normalizeId=u,lL.resolveUrl=function(e,t,r){return r=u(r),e.resolve(t,r)};const d=/^[a-z_][-a-z0-9._]*$/i;return lL.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`)}},lL}function yL(){if(mL)return SR;mL=1,Object.defineProperty(SR,"__esModule",{value:!0}),SR.getData=SR.KeywordCxt=SR.validateFunctionCode=void 0;const e=function(){if(jR)return NR;jR=1,Object.defineProperty(NR,"__esModule",{value:!0}),NR.boolOrEmptySchema=NR.topBoolOrEmptySchema=void 0;const e=UR(),t=$R(),r=FR(),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 NR.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))},NR.boolOrEmptySchema=function(e,t){const{gen:r,schema:n}=e;!1===n?(r.var(t,!1),a(e)):r.var(t,!0)},NR}(),t=JR(),r=ZR(),n=JR(),a=function(){if(YR)return XR;YR=1,Object.defineProperty(XR,"__esModule",{value:!0}),XR.assignDefaults=void 0;const e=$R(),t=RR();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 XR.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))},XR}(),i=aL(),s=function(){if(iL)return sL;iL=1,Object.defineProperty(sL,"__esModule",{value:!0}),sL.extendSubschemaMode=sL.extendSubschemaData=sL.getSubschema=void 0;const e=$R(),t=RR();return sL.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')},sL.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)},sL.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},sL}(),o=$R(),c=FR(),l=gL(),u=RR(),d=UR();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(()=>P(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)&&P(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)}SR.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 P(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)}SR.KeywordCxt=x;const E=/^\/(?:[^~]|~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(!E.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 SR.getData=A,SR}var vL,bL={};function _L(){if(vL)return bL;vL=1,Object.defineProperty(bL,"__esModule",{value:!0});class e extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}return bL.default=e,bL}var wL,SL={};function NL(){if(wL)return SL;wL=1,Object.defineProperty(SL,"__esModule",{value:!0});const e=gL();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 SL.default=t,SL}var kL,xL={};function PL(){if(kL)return xL;kL=1,Object.defineProperty(xL,"__esModule",{value:!0}),xL.resolveSchema=xL.getCompilingSchema=xL.resolveRef=xL.compileSchema=xL.SchemaEnv=void 0;const e=$R(),t=_L(),r=FR(),n=gL(),a=RR(),i=yL();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)}}xL.SchemaEnv=s,xL.compileSchema=o,xL.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},xL.getCompilingSchema=l,xL.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 xL}var EL,CL,AL,OL,IL,$L,TL,zL={$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},RL={},LL={exports:{}};function ML(){if(CL)return EL;CL=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 EL={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},EL}function jL(){if(IL)return LL.exports;IL=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:a,nonSimpleDomain:i}=ML(),{SCHEMES:s,getSchemeHandler:o}=function(){if(OL)return AL;OL=1;const{isUUID:e}=ML(),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),AL={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 LL.exports=p,LL.exports.default=p,LL.exports.fastUri=p,LL.exports}function DL(){return TL||(TL=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=yL();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=$R();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=_L(),a=NL(),i=GR(),s=PL(),o=$R(),c=gL(),l=JR(),u=RR(),d=zL,p=function(){if($L)return RL;$L=1,Object.defineProperty(RL,"__esModule",{value:!0});const e=jL();return e.code='require("ajv/dist/runtime/uri").default',RL.default=e,RL}(),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,P,E;const C=e.strict,A=null===(t=e.code)||void 0===t?void 0:t.optimize,O=!0===A||void 0===A?1:A||0,I=null!==(n=null===(r=e.code)||void 0===r?void 0:r.regExp)&&void 0!==n?n:m,$=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:O,regExp:I}:{optimize:O,regExp:I},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===(P=e.unicodeRegExp)||void 0===P||P,int32range:null===(E=e.int32range)||void 0===E||E,uriResolver:$}}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 P;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;I.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]=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,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 P={log(){},warn(){},error(){}};const E=/^[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(!E.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?O.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 O(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 I(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=T(t)),e.validateSchema=this.compile(t,!0))}const $={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function T(e){return{anyOf:[e,$]}}}(wR)),wR}var FL,UL={},BL={},qL={};var VL,GL,HL={};function WL(){if(VL)return HL;VL=1,Object.defineProperty(HL,"__esModule",{value:!0}),HL.callRef=HL.getValidate=void 0;const e=NL(),t=nL(),r=$R(),n=FR(),a=PL(),i=RR(),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 HL.getValidate=o,HL.callRef=c,HL.default=s,HL}function KL(){if(GL)return BL;GL=1,Object.defineProperty(BL,"__esModule",{value:!0});const e=function(){if(FL)return qL;FL=1,Object.defineProperty(qL,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return qL.default=e,qL}(),t=WL(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return BL.default=r,BL}var ZL,JL={},YL={};var XL,QL={};var eM,tM,rM={},nM={};function aM(){if(tM)return rM;tM=1,Object.defineProperty(rM,"__esModule",{value:!0});const e=$R(),t=RR(),r=function(){if(eM)return nM;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 eM=1,Object.defineProperty(nM,"__esModule",{value:!0}),nM.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',nM}(),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 rM.default=a,rM}var iM,sM={};var oM,cM={};var lM,uM={};function dM(){if(lM)return uM;lM=1,Object.defineProperty(uM,"__esModule",{value:!0});const e=nL(),t=$R(),r=RR(),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 uM.default=n,uM}var pM,mM={};var hM,fM,gM={},yM={};function vM(){if(hM)return yM;hM=1,Object.defineProperty(yM,"__esModule",{value:!0});const e=uL();return e.code='require("ajv/dist/runtime/equal").default',yM.default=e,yM}function bM(){if(fM)return gM;fM=1,Object.defineProperty(gM,"__esModule",{value:!0});const e=JR(),t=$R(),r=RR(),n=vM(),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 gM.default=i,gM}var _M,wM={};var SM,NM,kM={};function xM(){if(SM)return kM;SM=1,Object.defineProperty(kM,"__esModule",{value:!0});const e=$R(),t=RR(),r=vM(),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 kM.default=n,kM}function PM(){if(NM)return JL;NM=1,Object.defineProperty(JL,"__esModule",{value:!0});const e=function(){if(ZL)return YL;ZL=1,Object.defineProperty(YL,"__esModule",{value:!0});const e=$R(),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 YL.default=a,YL}(),t=function(){if(XL)return QL;XL=1,Object.defineProperty(QL,"__esModule",{value:!0});const e=$R(),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 QL.default=t,QL}(),r=aM(),n=function(){if(iM)return sM;iM=1,Object.defineProperty(sM,"__esModule",{value:!0});const e=nL(),t=$R(),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 sM.default=r,sM}(),a=function(){if(oM)return cM;oM=1,Object.defineProperty(cM,"__esModule",{value:!0});const e=$R(),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 cM.default=r,cM}(),i=dM(),s=function(){if(pM)return mM;pM=1,Object.defineProperty(mM,"__esModule",{value:!0});const e=$R(),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 mM.default=r,mM}(),o=bM(),c=function(){if(_M)return wM;_M=1,Object.defineProperty(wM,"__esModule",{value:!0});const e=$R(),t=RR(),r=vM(),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 wM.default=n,wM}(),l=xM(),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 JL.default=u,JL}var EM,CM={},AM={};function OM(){if(EM)return AM;EM=1,Object.defineProperty(AM,"__esModule",{value:!0}),AM.validateAdditionalItems=void 0;const e=$R(),t=RR(),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 AM.validateAdditionalItems=n,AM.default=r,AM}var IM,$M,TM={},zM={};function RM(){if(IM)return zM;IM=1,Object.defineProperty(zM,"__esModule",{value:!0}),zM.validateTuple=void 0;const e=$R(),t=RR(),r=nL(),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 zM.validateTuple=a,zM.default=n,zM}var LM,MM={};var jM,DM={};function FM(){if(jM)return DM;jM=1,Object.defineProperty(DM,"__esModule",{value:!0});const e=$R(),t=RR(),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 DM.default=r,DM}var UM,BM={};function qM(){return UM||(UM=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=$R(),r=RR(),n=nL();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},
1
+ import{createCommand as e,createOption as t,InvalidOptionArgumentError as r,Command as n}from"commander";import{config as o}from"dotenv";import i,{fileURLToPath as s,pathToFileURL as a}from"node:url";import{resolve as c,dirname as l,join as d}from"node:path";import{readPackageUp as u,readPackageUpSync as p}from"read-package-up";import{ConsoleLogger as h,buildApplication as f,bundleApp as m,FusionEnv as g,resolveDefaultEnv as y,checkApp as v,initializeFramework as b,uploadApplication as $,publishAppConfig as w,generateApplicationConfig as E,AllowedAppTags as S,tagApplication as P,loadAppManifest as L,startAppDevServer as _,startPortalDevServer as k,loadPortalManifest as C,buildPortal as N,bundlePortal as I,uploadPortalBundle as O,tagPortal as A,publishPortalConfig as x,generatePortalConfig as T}from"@equinor/fusion-framework-cli/bin";import{mkdir as D,writeFile as j}from"node:fs/promises";import{accessSync as R,constants as F,readFileSync as M,writeFileSync as G,rmSync as U,existsSync as B,readdirSync as z,copyFileSync as H,cpSync as V,mkdirSync as W}from"node:fs";import q from"node:assert";import K from"inquirer";import J from"is-path-inside";import{execa as Y,ExecaError as X}from"execa";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{execSync as ne}from"node:child_process";import oe from"url";import ie from"node:module";import se from"util";import{importConfig as ae,importJSON as ce,FileNotFoundError as le}from"@equinor/fusion-imports";import"deepmerge";import{findUp as de}from"find-up";const ue=(e=0)=>t=>`[${t+e}m`,pe=(e=0)=>t=>`[${38+e};5;${t}m`,he=(e=0)=>(t,r,n)=>`[${38+e};2;${t};${r};${n}m`,fe={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(fe.modifier);Object.keys(fe.color),Object.keys(fe.bgColor);const me=function(){const e=new Map;for(const[t,r]of Object.entries(fe)){for(const[t,n]of Object.entries(r))fe[t]={open:`[${n[0]}m`,close:`[${n[1]}m`},r[t]=fe[t],e.set(n[0],n[1]);Object.defineProperty(fe,t,{value:r,enumerable:!1})}return Object.defineProperty(fe,"codes",{value:e,enumerable:!1}),fe.color.close="",fe.bgColor.close="",fe.color.ansi=ue(),fe.color.ansi256=pe(),fe.color.ansi16m=he(),fe.bgColor.ansi=ue(10),fe.bgColor.ansi256=pe(10),fe.bgColor.ansi16m=he(10),Object.defineProperties(fe,{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=>fe.rgbToAnsi256(...fe.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)=>fe.ansi256ToAnsi(fe.rgbToAnsi256(e,t,r)),enumerable:!1},hexToAnsi:{value:e=>fe.ansi256ToAnsi(fe.hexToAnsi256(e)),enumerable:!1}}),fe}(),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})(),ye=0!==ge&&{level:ge},ve={stdout:ye,stderr:ye};function be(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:$e,stderr:we}=ve,Ee=Symbol("GENERATOR"),Se=Symbol("STYLER"),Pe=Symbol("IS_EMPTY"),Le=["ansi","ansi","ansi256","ansi16m"],_e=Object.create(null),ke=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=$e?$e.level:0;e.level=void 0===t.level?r:t.level})(t,e),Object.setPrototypeOf(t,Ce.prototype),t};function Ce(e){return ke(e)}Object.setPrototypeOf(Ce.prototype,Function.prototype);for(const[e,t]of Object.entries(me))_e[e]={get(){const r=xe(this,Ae(t.open,t.close,this[Se]),this[Pe]);return Object.defineProperty(this,e,{value:r}),r}};_e.visible={get(){const e=xe(this,this[Se],!0);return Object.defineProperty(this,"visible",{value:e}),e}};const Ne=(e,t,r,...n)=>"rgb"===e?"ansi16m"===t?me[r].ansi16m(...n):"ansi256"===t?me[r].ansi256(me.rgbToAnsi256(...n)):me[r].ansi(me.rgbToAnsi(...n)):"hex"===e?Ne("rgb",t,r,...me.hexToRgb(...n)):me[r][e](...n),Ie=["rgb","hex","ansi256"];for(const e of Ie){_e[e]={get(){const{level:t}=this;return function(...r){const n=Ae(Ne(e,Le[t],"color",...r),me.color.close,this[Se]);return xe(this,n,this[Pe])}}};_e["bg"+e[0].toUpperCase()+e.slice(1)]={get(){const{level:t}=this;return function(...r){const n=Ae(Ne(e,Le[t],"bgColor",...r),me.bgColor.close,this[Se]);return xe(this,n,this[Pe])}}}}const Oe=Object.defineProperties(()=>{},{..._e,level:{enumerable:!0,get(){return this[Ee].level},set(e){this[Ee].level=e}}}),Ae=(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}},xe=(e,t,r)=>{const n=(...e)=>Te(n,1===e.length?""+e[0]:e.join(" "));return Object.setPrototypeOf(n,Oe),n[Ee]=e,n[Se]=t,n[Pe]=r,n},Te=(e,t)=>{if(e.level<=0||!t)return e[Pe]?"":t;let r=e[Se];if(void 0===r)return t;const{openAll:n,closeAll:o}=r;if(t.includes(""))for(;void 0!==r;)t=be(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(Ce.prototype,_e);const De=Ce();Ce({level:we?we.level:0});const je=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 h("app:build",{debug:t.debug});await f({log:r,manifest:e})}),Re="app-bundle.zip",Fe=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)",Re).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 h("app:pack",{debug:t.debug});await m({log:r,manifest:e,archive:t.archive}).catch(e=>{r.error("Failed to create package:",e),process.exit(1)})}),Me=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))};Me({allowDev:!0});const Ge=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Ue=t("--tenantId <string>","The Azure Active Directory tenant ID").env("FUSION_TENANT_ID").default("3aa4a235-b6e2-48d5-9195-7fcf05b459b0"),Be=t("--clientId <string>","The client ID of the application registered in Azure AD").env("FUSION_CLIENT_ID").default("a318b8e1-0295-4e17-98d5-35f67dfeba14"),ze=t("--token <string>","The Azure AD access token. If provided, the --tenant and --client options are ignored").env("FUSION_TOKEN").default(void 0),He=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"]),Ve=(e,t)=>(e.addOption(Ue),e.addOption(Be),t?.excludeToken||e.addOption(ze),t?.includeScope&&e.addOption(He),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(!Ge.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(!Ge.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),We=Ve(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(Me({allowDev:!1})).action(async e=>{const t=new h("app:check",{debug:!!e.debug});await v({log:t,environment:e.env,auth:"token"in e?{token:e.token}:e})})),qe=Ve(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(Me({allowDev:!1})).argument("[bundle]","Application bundle to upload",Re).action(async(e,t)=>{const r=new h("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)})})),Ke=Ve(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(Me({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 h("app:config",{debug:!!t.debug});if(t.publish)return"dev"===t.env&&(r?.fail("🤪",De.blue("--env"),'cannot be "dev" when',De.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 E({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 Je=Ve(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(Me({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(S).join(" | ")})`).action(async(e,t)=>{const r=t.silent?null:new h("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 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{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:",De.greenBright(`${o}@${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 P({appKey:o,version:i,framework:s,log:r,tag:e}).catch(e=>{r?.error("Failed to tag application:",e),process.exit(1)})})),Ye=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 h("app:dev",{debug:e.debug});t.start("Starting application in development mode..."),_({log:t,manifest:e.manifest,config:e.config,env:e.env,port:e.port,host:e.host}),t.succeed("Development server started successfully.")}),Xe=(e,t)=>{try{return R(e,F.F_OK),!0}catch(e){return!1}},Ze=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 h("app:manifest",{debug:t.debug}),n=await L({log:r,manifest:e});if("stdout"!==t.output){const e=c(process.cwd(),t.output);r?.start("Writing manifest to file",t.output),Xe(l(e))||await D(l(e),{recursive:!0}),await j(e,JSON.stringify(n.manifest,null,2)),r?.succeed("Manifest written to file",e)}else console.log(JSON.stringify(n.manifest,null,2))}),Qe=Ve(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(Me({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(S).join(" | ")})`,S.Latest).argument("[bundle]","Path to the app bundle to upload").action(async(e,t)=>{const r=new h("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 m({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 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: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 P({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 et(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 tt(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 et(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 rt(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(!J(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 nt(e,t,r){const n=rt(e,r);U(n,t)}const ot=["code","cursor"];async function it(e,t,r=!1){if(r)return void t.debug("Skipping IDE opening");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:n}=await K.prompt([{type:"select",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(n){if(!function(e){return ot.includes(e)}(n))return void t.error(`Invalid IDE command: ${n}. Only supported IDEs are: ${ot.join(", ")}`);try{const r=Y(n,[e],{stdio:"pipe",detached:!0});r.unref(),r.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 (${n}): ${e.message}`)})}catch(e){t.error(`Failed to spawn IDE process (${n}): ${e instanceof Error?e.message:String(e)}`)}}}const st=["npm","pnpm"];async function at(e,t){const{installDeps:r}=await K.prompt([{type:"confirm",name:"installDeps",message:"📦 Install dependencies?",default:!0}]);if(!r)return t.debug("Skipping dependency installation"),{installed:!1};const{packageManager:n}=await K.prompt([{type:"select",name:"packageManager",message:"📦 Which package manager do you want to use?",choices:["pnpm","npm"],default:"pnpm"}]);return await async function(e,t,r){q(st.includes(t),"Package manager must be npm or pnpm"),r?.start("Installing dependencies...");try{return await Y(t,["install"],{cwd:e,stdio:"inherit",shell:!0}),r?.succeed("Dependencies installed successfully!"),t}catch(e){if(e instanceof X&&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 ct{#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=d(this.#r,t.path),n=d(e,t.target??t.path);if(B(r))try{"file"===t.type?(H(r,n),this.#t?.debug(`Copied file: ${t.path} -> ${n}`)):"dir"===t.type?(V(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 lt=re.object({type:re.literal("file"),path:re.string(),target:re.string().optional()}),dt=re.object({type:re.literal("dir"),path:re.string(),target:re.string().optional(),recursive:re.boolean().optional()}),ut=re.discriminatedUnion("type",[lt,dt]),pt=re.object({name:re.string(),description:re.string(),resources:re.array(ut)}),ht=re.object({templates:re.array(pt),resources:re.array(ut).optional()});class ft{repo;#n=!1;#o;#i;#s;#a;#c;get protocol(){return this.#a}set protocol(e){q("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??d(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),B(this.#i)||(this.#s?.info("Repository directory does not exist, creating..."),W(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=d(this.#i,"templates.json");this.#s?.debug("Reading template manifest file...",t),e=M(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 ht.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 ct({...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 nt(rt(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 mt=[".rsa",".ed25519",".ecdsa",".dsa"],gt=/(_rsa|_ed25519|_ecdsa|_dsa)$/,yt=new Set(["known_hosts","config","authorized_keys","authorized_keys2","ssh_config","ssh_known_hosts"]);function vt(e){if(e.endsWith(".pub"))return!1;if(yt.has(e))return!1;const t=e.startsWith("id_"),r=mt.some(t=>e.endsWith(t)),n=gt.test(e);return t||r||n}async function bt(e,t){if(t)return e?.debug(`Using provided protocol: ${t}`),t;e?.debug("Detecting SSH configuration...");const r=function(){try{return ne("git config core.sshCommand",{stdio:"ignore"}),!0}catch{return!1}}()||function(e){try{const t=d(Q(),".ssh");if(!B(t))return!1;for(const r of z(t,{withFileTypes:!0}))if(r.isFile()&&vt(r.name))return e?.debug("SSH private key detected in .ssh directory"),!0;return!1}catch{return!1}}(e);r&&e?.debug("SSH configuration detected");const n=r?void 0:"SSH not configured (no SSH keys or git config found)",{selectedProtocol:o}=await K.prompt([{type:"select",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:n}],default:r?"ssh":"https",pageSize:5,loop:!1}]);return e?.debug(`Selected protocol: ${o}`),o}async function $t(e,t,r){q(!!e,"App name is required"),q(B(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 o=await async function(e,t,r=!1,n=process.cwd()){let o;q("string"==typeof e,"Target directory must be a string");try{o=rt(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(!B(o))return t.debug(`Target directory does not exist: ${o}`),!0;try{const e=z(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{nt(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 K.prompt([{type:"select",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{nt(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,o){const i=c(Z(),"ffc","repo",e);if(n.debug(`Repo dir: ${i}`),t){n.debug(`Removing repo dir: ${i}`);try{nt(rt(i,Z()),{recursive:!0,force:!0},Z())}catch(e){n.debug("Cleanup failed:",e)}}const s=await bt(n,o),a=new ft(e,{baseDir:i,log:n,branch:r,protocol:s});return await a.initialize(),a}("equinor/fusion-app-template",t.clean,t.branch,r,t.gitProtocol),s=await i.getAvailableTemplates(),a=await async function(e,t,r){q(Array.isArray(e),"Templates must be an array"),q(e.length>0,"No templates available");const n=e.map(e=>e.name);if(t){q("string"==typeof t,"Pre-selected template must be a string"),q(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 q(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 K.prompt([{type:"select",name:"selectedTemplate",message:"🎨 Please select a template:",choices:e.map(e=>({name:`${e.name} - ${e.description}`,value:e})),pageSize:10,loop:!1}]);return o}(s,t.template,r);try{await a.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=d(e,"package.json");try{const e=M(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 tt(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"),G(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,r){if(void 0!==r)return void(r?await e.cleanup():t.debug("Skipping cleanup of temporary template files"));const{cleanupTempFiles:n}=await K.prompt([{type:"confirm",name:"cleanupTempFiles",message:"🗑️ Clean up temporary template files?",default:!1}]);n?await e.cleanup():t.debug("Skipping cleanup of temporary template files")}(i,r,t.cleanup),t.noOpen||await it(n,r),await at(n,r)}const wt=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").option("--git-protocol <protocol>","Git protocol to use for cloning (https or ssh) - skips prompt if provided").option("--cleanup","Clean up temporary template files after creation - skips prompt if provided").option("--no-cleanup","Do not clean up temporary template files - skips prompt if provided").option("--no-open","Skip opening the project in IDE").action(async(e,t)=>{const r=new h("",{debug:t.debug});t.gitProtocol&&"https"!==t.gitProtocol&&"ssh"!==t.gitProtocol&&(r.error(`Invalid git-protocol: ${t.gitProtocol}. Must be 'https' or 'ssh'`),process.exit(1));try{await $t(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)}});Fe.alias("build-pack").hook("preAction",e=>{"build-pack"===process.argv[3]&&(console.warn(De.bgRedBright.bold('The command "build-pack" is deprecated. Please use "pack" instead.')),e.getOptionValue("archive")||e.setOptionValue("archive",Re))}),qe.alias("build-upload").hook("preAction",e=>{if("build-upload"===process.argv[3]){if(console.warn(De.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")??Re;process.argv[4]=t}}),Ze.alias("build-manifest").hook("preAction",()=>{"build-manifest"===process.argv[3]&&console.warn(De.bgRedBright.bold('The command "build-manifest" is deprecated. Please use "manifest" instead.'))}),Qe.alias("build-publish").hook("preAction",e=>{if("build-publish"===process.argv[3]&&console.warn(De.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 Et=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(je).addCommand(Fe).addCommand(We).addCommand(qe).addCommand(Ke).addCommand(Je).addCommand(Ye).addCommand(Ze).addCommand(Qe).addCommand(wt("create")),St=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 h("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:",De.green(e.account?.username)),t.info("tenant: ",De.yellow(e.tenantId)),t.info("audience:",De.yellow(e.account?.idTokenClaims?.aud));for(const r of e.scopes)t.info("scope: ",De.dim(r));t.succeed("Successfully logged in",De.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}});Ve(St,{includeScope:!0,excludeToken:!0});const Pt=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 h("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}});Ve(Pt,{excludeToken:!0,includeScope:!1});class Lt extends Error{static Name="NoAccountsError";constructor(e,t){super(e,t),this.name=Lt.Name}}const _t=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 h("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 o=await n.auth.acquireAccessToken({request:{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 Lt))throw r;t?.fail("No accounts found, please login first")}});Ve(_t,{includeScope:!0});const kt=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"));kt.addCommand(St,{isDefault:!0}),kt.addCommand(Pt),kt.addCommand(_t);const Ct=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(wt("app")),Nt=Ve(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(Me({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 h("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 o=await n.serviceDiscovery.resolveService(e);r?.succeed(`Resolved service ${e}`),r?.debug(o),t.silent&&console.log(JSON.stringify(o,null,2))})),It=e("disco").description("Service discovery operations");It.addCommand(Nt);const Ot=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 h("portal:dev",{debug:e.debug});t.start("Starting portal in development mode..."),k({server:{port:Number(e.port)},log:t,env:e.env}),t.succeed("Development server started successfully.")});function At(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var xt,Tt,Dt,jt;function Rt(){if(Tt)return xt;Tt=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 xt=e}function Ft(){if(jt)return Dt;jt=1;const e=Number.MAX_SAFE_INTEGER||9007199254740991;return Dt={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 Mt,Gt,Ut,Bt,zt,Ht,Vt,Wt,qt,Kt,Jt,Yt,Xt,Zt={exports:{}};function Qt(){return Mt||(Mt=1,function(e,t){const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:o}=Ft(),i=Rt(),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*$")}(Zt,Zt.exports)),Zt.exports}function er(){if(Vt)return Ht;Vt=1;const e=Rt(),{MAX_LENGTH:t,MAX_SAFE_INTEGER:r}=Ft(),{safeRe:n,t:o}=Qt(),i=function(){if(Ut)return Gt;Ut=1;const e=Object.freeze({loose:!0}),t=Object.freeze({});return Gt=r=>r?"object"!=typeof r?e:r:t}(),{compareIdentifiers:s}=function(){if(zt)return Bt;zt=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 Bt={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 Ht=a}function tr(){if(qt)return Wt;qt=1;const e=er();return Wt=(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 rr,nr,or,ir,sr,ar,cr,lr,dr,ur,pr=["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"],hr=["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"],fr=["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 mr(){if(nr)return rr;nr=1;var e=[].concat(pr).concat(hr),t=fr;return rr=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 gr(){return ir||(ir=1,or=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}),or}function yr(){if(ar)return sr;ar=1;var e=mr(),t=gr();return sr=function(r){return t(e(r))}}function vr(){if(ur)return dr;ur=1;var e=yr(),t=function(){if(lr)return cr;lr=1;var e=yr(),t=pr;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 cr=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 dr=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 br,$r,wr,Er,Sr,Pr,Lr,_r,kr,Cr,Nr,Ir={};function Or(){if(br)return Ir;br=1,Object.defineProperty(Ir,"__esModule",{value:!0}),Ir.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;#x;#T;#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.#x=!!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.#T=!!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.#J=(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.#Y=(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=>{};#Y=(e,t,r)=>{};#J=(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.#J(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.#Y(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.#x&&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.#T&&this.#C?.push([t,e,"set"]))}else i||(this.#A&&this.#p?.(r,e,"set"),this.#T&&this.#C?.push([r,e,"set"]));if(this.#K(d),this.#Y(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.#T&&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.#T&&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.#x&&this.#j(n)?n.__abortController.abort(new Error("evicted")):(this.#A||this.#T)&&(this.#A&&this.#p?.(n,r,"evict"),this.#T&&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.#x)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.#x)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.#T)&&(this.#A&&this.#p?.(r,e,t),this.#T&&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.#T&&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.#T&&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.#T&&this.#C){const e=this.#C;let t;for(;t=e?.shift();)this.#f?.(...t)}}}return Ir.LRUCache=d,Ir}function Ar(){if(Sr)return Er;Sr=1;const e=oe,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 Er=(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))},Er}function xr(){if(Lr)return Pr;Lr=1;const e=Ar();return Pr=(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 Tr(){if(kr)return _r;kr=1;const{LRUCache:e}=Or(),t=function(){if(wr)return $r;wr=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 $r=o}(),r=xr(),n=Ar(),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 _r=i}var Dr,jr,Rr={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 Fr(){if(jr)return Dr;jr=1;var{URL:e}=i,t=function(){if(Jt)return Kt;Jt=1;const e=tr();return Kt=(t,r)=>{const n=e(t,r);return n?n.version:null}}(),r=function(){if(Xt)return Yt;Xt=1;const e=tr();return Yt=(t,r)=>{const n=e(t.trim().replace(/^[=v]+/,""),r);return n?n.version:null}}(),n=vr(),o=Tr(),{isBuiltin:s}=ie,a=["dependencies","devDependencies","optionalDependencies"],c=Nr?Cr:(Nr=1,Cr=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=Rr,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 Dr={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=o.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 i=o.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 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=o.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=o.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")}},Dr}var Mr,Gr,Ur,Br,zr={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 Hr(){if(Gr)return Mr;Gr=1;var e=se,t=zr;function r(r,n,o){return o&&(r=o+"['"+r+"']",n=o+"['"+n+"']"),e.format(t.typo,r,n)}return Mr=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)},Mr}!function(){if(Br)return Ur;Br=1,Ur=n;var e=Fr();n.fixer=e;var t=Hr(),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 Vr=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 h("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),Xe(l(e))||await D(l(e),{recursive:!0}),await j(e,JSON.stringify(n.manifest,null,2)),r?.succeed("Manifest written to file",e)}else console.log(JSON.stringify(n.manifest,null,2))});var Wr,qr={exports:{}},Kr={},Jr={},Yr={},Xr={},Zr={},Qr={};function en(){return Wr||(Wr=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())}}(Qr)),Qr}var tn,rn,nn={};function on(){return tn||(tn=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=en();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}}}(nn)),nn}function sn(){return rn||(rn=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=en(),r=on();var n=en();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=on();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=T(e.operators.AND);e.and=function(...e){return e.reduce(A)};const x=T(e.operators.OR);function T(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(x)}}(Zr)),Zr}var an,cn={};function ln(){if(an)return cn;an=1,Object.defineProperty(cn,"__esModule",{value:!0}),cn.checkStrictMode=cn.getErrorPath=cn.Type=cn.useFunc=cn.setEvaluated=cn.evaluatedPropsToName=cn.mergeEvaluated=cn.eachItem=cn.unescapeJsonPointer=cn.escapeJsonPointer=cn.escapeFragment=cn.unescapeFragment=cn.schemaRefOrVal=cn.schemaHasRulesButRef=cn.schemaHasRules=cn.checkUnknownRules=cn.alwaysValidSchema=cn.toHash=void 0;const e=sn(),t=en();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))}cn.toHash=function(e){const t={};for(const r of e)t[r]=!0;return t},cn.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(r(e,t),!n(t,e.self.RULES.all))},cn.checkUnknownRules=r,cn.schemaHasRules=n,cn.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},cn.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)}`},cn.unescapeFragment=function(e){return i(decodeURIComponent(e))},cn.escapeFragment=function(e){return encodeURIComponent(o(e))},cn.escapeJsonPointer=o,cn.unescapeJsonPointer=i,cn.eachItem=function(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)},cn.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)})},cn.evaluatedPropsToName=a,cn.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 cn.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||(cn.Type=d={})),cn.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)},cn.checkStrictMode=u,cn}var dn,un,pn,hn={};function fn(){if(dn)return hn;dn=1,Object.defineProperty(hn,"__esModule",{value:!0});const e=sn(),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 hn.default=t,hn}function mn(){return un||(un=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=sn(),r=ln(),n=fn();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]}}(Xr)),Xr}var gn,yn={},vn={};function bn(){if(gn)return vn;gn=1,Object.defineProperty(vn,"__esModule",{value:!0}),vn.getRules=vn.isJSONType=void 0;const e=new Set(["string","number","integer","boolean","null","object","array"]);return vn.isJSONType=function(t){return"string"==typeof t&&e.has(t)},vn.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:{}}},vn}var $n,wn,En={};function Sn(){if($n)return En;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 $n=1,Object.defineProperty(En,"__esModule",{value:!0}),En.shouldUseRule=En.shouldUseGroup=En.schemaHasRulesForType=void 0,En.schemaHasRulesForType=function({schema:t,self:r},n){const o=r.RULES.types[n];return o&&!0!==o&&e(t,o)},En.shouldUseGroup=e,En.shouldUseRule=t,En}function Pn(){if(wn)return yn;wn=1,Object.defineProperty(yn,"__esModule",{value:!0}),yn.reportTypeError=yn.checkDataTypes=yn.checkDataType=yn.coerceAndCheckDataType=yn.getJSONTypes=yn.getSchemaTypes=yn.DataType=void 0;const e=bn(),t=Sn(),r=mn(),n=sn(),o=ln();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||(yn.DataType=i={})),yn.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},yn.getJSONTypes=s,yn.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}yn.checkDataType=c,yn.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 yn.reportTypeError=u,yn}var Ln,_n={};var kn,Cn,Nn={},In={};function On(){if(kn)return In;kn=1,Object.defineProperty(In,"__esModule",{value:!0}),In.validateUnion=In.validateArray=In.usePattern=In.callValidateCode=In.schemaProperties=In.allSchemaProperties=In.noPropertyInData=In.propertyInData=In.isOwnProperty=In.hasPropFunc=In.reportMissingProp=In.checkMissingProp=In.checkReportMissingProp=void 0;const e=sn(),t=ln(),r=fn(),n=ln();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):[]}In.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()})},In.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}`)))},In.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},In.hasPropFunc=o,In.isOwnProperty=i,In.propertyInData=function(t,r,n,o){const s=e._`${r}${(0,e.getProperty)(n)} !== undefined`;return o?e._`${s} && ${i(t,r,n)}`:s},In.noPropertyInData=s,In.allSchemaProperties=a,In.schemaProperties=function(e,r){return a(r).filter(n=>!(0,t.alwaysValidSchema)(e,r[n]))},In.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 In.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})`})},In.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)})}},In.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))},In}function An(){if(Cn)return Nn;Cn=1,Object.defineProperty(Nn,"__esModule",{value:!0}),Nn.validateKeywordUsage=Nn.validSchemaType=Nn.funcKeywordCode=Nn.macroKeywordCode=void 0;const e=sn(),t=fn(),r=On(),n=mn();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 Nn.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))},Nn.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)},Nn.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)},Nn.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)}}},Nn}var xn,Tn={};var Dn,jn,Rn={};function Fn(){return jn||(jn=1,Dn=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}),Dn}var Mn,Gn,Un,Bn={exports:{}};function zn(){if(Mn)return Bn.exports;Mn=1;var e=Bn.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},Bn.exports}function Hn(){if(Gn)return Rn;Gn=1,Object.defineProperty(Rn,"__esModule",{value:!0}),Rn.getSchemaRefs=Rn.resolveUrl=Rn.normalizeId=Rn._getFullPath=Rn.getFullPath=Rn.inlineRef=void 0;const e=ln(),t=Fn(),r=zn(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);Rn.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]+"#"}Rn.getFullPath=a,Rn._getFullPath=c;const l=/#\/?$/;function d(e){return e?e.replace(l,""):""}Rn.normalizeId=d,Rn.resolveUrl=function(e,t,r){return r=d(r),e.resolve(t,r)};const u=/^[a-z_][-a-z0-9._]*$/i;return Rn.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`)}},Rn}function Vn(){if(Un)return Jr;Un=1,Object.defineProperty(Jr,"__esModule",{value:!0}),Jr.getData=Jr.KeywordCxt=Jr.validateFunctionCode=void 0;const e=function(){if(pn)return Yr;pn=1,Object.defineProperty(Yr,"__esModule",{value:!0}),Yr.boolOrEmptySchema=Yr.topBoolOrEmptySchema=void 0;const e=mn(),t=sn(),r=fn(),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 Yr.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))},Yr.boolOrEmptySchema=function(e,t){const{gen:r,schema:n}=e;!1===n?(r.var(t,!1),o(e)):r.var(t,!0)},Yr}(),t=Pn(),r=Sn(),n=Pn(),o=function(){if(Ln)return _n;Ln=1,Object.defineProperty(_n,"__esModule",{value:!0}),_n.assignDefaults=void 0;const e=sn(),t=ln();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 _n.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))},_n}(),i=An(),s=function(){if(xn)return Tn;xn=1,Object.defineProperty(Tn,"__esModule",{value:!0}),Tn.extendSubschemaMode=Tn.extendSubschemaData=Tn.getSubschema=void 0;const e=sn(),t=ln();return Tn.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')},Tn.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)},Tn.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},Tn}(),a=sn(),c=fn(),l=Hn(),d=ln(),u=mn();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)}Jr.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)}Jr.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 Jr.getData=N,Jr}var Wn,qn={};function Kn(){if(Wn)return qn;Wn=1,Object.defineProperty(qn,"__esModule",{value:!0});class e extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}return qn.default=e,qn}var Jn,Yn={};function Xn(){if(Jn)return Yn;Jn=1,Object.defineProperty(Yn,"__esModule",{value:!0});const e=Hn();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 Yn.default=t,Yn}var Zn,Qn={};function eo(){if(Zn)return Qn;Zn=1,Object.defineProperty(Qn,"__esModule",{value:!0}),Qn.resolveSchema=Qn.getCompilingSchema=Qn.resolveRef=Qn.compileSchema=Qn.SchemaEnv=void 0;const e=sn(),t=Kn(),r=fn(),n=Hn(),o=ln(),i=Vn();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)}}Qn.SchemaEnv=s,Qn.compileSchema=a,Qn.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},Qn.getCompilingSchema=l,Qn.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 Qn}var to,ro,no,oo,io,so,ao,co={$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},lo={},uo={exports:{}};function po(){if(ro)return to;ro=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 to={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 ho(){if(io)return uo.exports;io=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:o,nonSimpleDomain:i}=po(),{SCHEMES:s,getSchemeHandler:a}=function(){if(oo)return no;oo=1;const{isUUID:e}=po(),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),no={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 uo.exports=p,uo.exports.default=p,uo.exports.fastUri=p,uo.exports}function fo(){return ao||(ao=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=Vn();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=sn();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=Kn(),o=Xn(),i=bn(),s=eo(),a=sn(),c=Hn(),l=Pn(),d=ln(),u=co,p=function(){if(so)return lo;so=1,Object.defineProperty(lo,"__esModule",{value:!0});const e=ho();return e.code='require("ajv/dist/runtime/uri").default',lo.default=e,lo}(),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]=x(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=x(t)),e.validateSchema=this.compile(t,!0))}const A={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function x(e){return{anyOf:[e,A]}}}(Kr)),Kr}var mo,go={},yo={},vo={};var bo,$o,wo={};function Eo(){if(bo)return wo;bo=1,Object.defineProperty(wo,"__esModule",{value:!0}),wo.callRef=wo.getValidate=void 0;const e=Xn(),t=On(),r=sn(),n=fn(),o=eo(),i=ln(),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 wo.getValidate=a,wo.callRef=c,wo.default=s,wo}function So(){if($o)return yo;$o=1,Object.defineProperty(yo,"__esModule",{value:!0});const e=function(){if(mo)return vo;mo=1,Object.defineProperty(vo,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return vo.default=e,vo}(),t=Eo(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return yo.default=r,yo}var Po,Lo={},_o={};var ko,Co={};var No,Io,Oo={},Ao={};function xo(){if(Io)return Oo;Io=1,Object.defineProperty(Oo,"__esModule",{value:!0});const e=sn(),t=ln(),r=function(){if(No)return Ao;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 No=1,Object.defineProperty(Ao,"__esModule",{value:!0}),Ao.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',Ao}(),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 Oo.default=o,Oo}var To,Do={};var jo,Ro={};var Fo,Mo={};function Go(){if(Fo)return Mo;Fo=1,Object.defineProperty(Mo,"__esModule",{value:!0});const e=On(),t=sn(),r=ln(),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 Mo.default=n,Mo}var Uo,Bo={};var zo,Ho,Vo={},Wo={};function qo(){if(zo)return Wo;zo=1,Object.defineProperty(Wo,"__esModule",{value:!0});const e=Fn();return e.code='require("ajv/dist/runtime/equal").default',Wo.default=e,Wo}function Ko(){if(Ho)return Vo;Ho=1,Object.defineProperty(Vo,"__esModule",{value:!0});const e=Pn(),t=sn(),r=ln(),n=qo(),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 Vo.default=o,Vo}var Jo,Yo={};var Xo,Zo,Qo={};function ei(){if(Xo)return Qo;Xo=1,Object.defineProperty(Qo,"__esModule",{value:!0});const e=sn(),t=ln(),r=qo(),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 Qo.default=n,Qo}function ti(){if(Zo)return Lo;Zo=1,Object.defineProperty(Lo,"__esModule",{value:!0});const e=function(){if(Po)return _o;Po=1,Object.defineProperty(_o,"__esModule",{value:!0});const e=sn(),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 _o.default=o,_o}(),t=function(){if(ko)return Co;ko=1,Object.defineProperty(Co,"__esModule",{value:!0});const e=sn(),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 Co.default=t,Co}(),r=xo(),n=function(){if(To)return Do;To=1,Object.defineProperty(Do,"__esModule",{value:!0});const e=On(),t=sn(),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 Do.default=r,Do}(),o=function(){if(jo)return Ro;jo=1,Object.defineProperty(Ro,"__esModule",{value:!0});const e=sn(),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 Ro.default=r,Ro}(),i=Go(),s=function(){if(Uo)return Bo;Uo=1,Object.defineProperty(Bo,"__esModule",{value:!0});const e=sn(),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 Bo.default=r,Bo}(),a=Ko(),c=function(){if(Jo)return Yo;Jo=1,Object.defineProperty(Yo,"__esModule",{value:!0});const e=sn(),t=ln(),r=qo(),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 Yo.default=n,Yo}(),l=ei(),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 Lo.default=d,Lo}var ri,ni={},oi={};function ii(){if(ri)return oi;ri=1,Object.defineProperty(oi,"__esModule",{value:!0}),oi.validateAdditionalItems=void 0;const e=sn(),t=ln(),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 oi.validateAdditionalItems=n,oi.default=r,oi}var si,ai,ci={},li={};function di(){if(si)return li;si=1,Object.defineProperty(li,"__esModule",{value:!0}),li.validateTuple=void 0;const e=sn(),t=ln(),r=On(),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 li.validateTuple=o,li.default=n,li}var ui,pi={};var hi,fi={};function mi(){if(hi)return fi;hi=1,Object.defineProperty(fi,"__esModule",{value:!0});const e=sn(),t=ln(),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 fi.default=r,fi}var gi,yi={};function vi(){return gi||(gi=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=sn(),r=ln(),n=On();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},
6
6
  depsCount: ${r},
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}(BM)),BM}var VM,GM={};var HM,WM={};function KM(){if(HM)return WM;HM=1,Object.defineProperty(WM,"__esModule",{value:!0});const e=nL(),t=$R(),r=FR(),n=RR(),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 WM.default=a,WM}var ZM,JM={};var YM,XM={};var QM,ej={};var tj,rj={};var nj,aj={};var ij,sj={};var oj,cj={};var lj,uj,dj={};function pj(){if(uj)return CM;uj=1,Object.defineProperty(CM,"__esModule",{value:!0});const e=OM(),t=function(){if($M)return TM;$M=1,Object.defineProperty(TM,"__esModule",{value:!0});const e=RM(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,e.validateTuple)(t,"items")};return TM.default=t,TM}(),r=RM(),n=function(){if(LM)return MM;LM=1,Object.defineProperty(MM,"__esModule",{value:!0});const e=$R(),t=RR(),r=nL(),n=OM(),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 MM.default=a,MM}(),a=FM(),i=qM(),s=function(){if(VM)return GM;VM=1,Object.defineProperty(GM,"__esModule",{value:!0});const e=$R(),t=RR(),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 GM.default=r,GM}(),o=KM(),c=function(){if(ZM)return JM;ZM=1,Object.defineProperty(JM,"__esModule",{value:!0});const e=yL(),t=nL(),r=RR(),n=KM(),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 JM.default=a,JM}(),l=function(){if(YM)return XM;YM=1,Object.defineProperty(XM,"__esModule",{value:!0});const e=nL(),t=$R(),r=RR(),n=RR(),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 XM.default=a,XM}(),u=function(){if(QM)return ej;QM=1,Object.defineProperty(ej,"__esModule",{value:!0});const e=RR(),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 ej.default=t,ej}(),d=function(){if(tj)return rj;tj=1,Object.defineProperty(rj,"__esModule",{value:!0});const e={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:nL().validateUnion,error:{message:"must match a schema in anyOf"}};return rj.default=e,rj}(),p=function(){if(nj)return aj;nj=1,Object.defineProperty(aj,"__esModule",{value:!0});const e=$R(),t=RR(),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 aj.default=r,aj}(),m=function(){if(ij)return sj;ij=1,Object.defineProperty(sj,"__esModule",{value:!0});const e=RR(),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 sj.default=t,sj}(),h=function(){if(oj)return cj;oj=1,Object.defineProperty(cj,"__esModule",{value:!0});const e=$R(),t=RR(),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 cj.default=r,cj}(),f=function(){if(lj)return dj;lj=1,Object.defineProperty(dj,"__esModule",{value:!0});const e=RR(),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 dj.default=t,dj}();return CM.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},CM}var mj,hj={},fj={};function gj(){if(mj)return fj;mj=1,Object.defineProperty(fj,"__esModule",{value:!0}),fj.dynamicAnchor=void 0;const e=$R(),t=FR(),r=PL(),n=WL(),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 fj.dynamicAnchor=i,fj.default=a,fj}var yj,vj={};function bj(){if(yj)return vj;yj=1,Object.defineProperty(vj,"__esModule",{value:!0}),vj.dynamicRef=void 0;const e=$R(),t=FR(),r=WL(),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 vj.dynamicRef=a,vj.default=n,vj}var _j,wj={};var Sj,Nj,kj={};function xj(){if(Nj)return hj;Nj=1,Object.defineProperty(hj,"__esModule",{value:!0});const e=gj(),t=bj(),r=function(){if(_j)return wj;_j=1,Object.defineProperty(wj,"__esModule",{value:!0});const e=gj(),t=RR(),r={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,e.dynamicAnchor)(r,""):(0,t.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};return wj.default=r,wj}(),n=function(){if(Sj)return kj;Sj=1,Object.defineProperty(kj,"__esModule",{value:!0});const e=bj(),t={keyword:"$recursiveRef",schemaType:"string",code:t=>(0,e.dynamicRef)(t,t.schema)};return kj.default=t,kj}(),a=[e.default,t.default,r.default,n.default];return hj.default=a,hj}var Pj,Ej={},Cj={};var Aj,Oj={};var Ij,$j,Tj={};function zj(){if($j)return Ej;$j=1,Object.defineProperty(Ej,"__esModule",{value:!0});const e=function(){if(Pj)return Cj;Pj=1,Object.defineProperty(Cj,"__esModule",{value:!0});const e=qM(),t={keyword:"dependentRequired",type:"object",schemaType:"object",error:e.error,code:t=>(0,e.validatePropertyDeps)(t)};return Cj.default=t,Cj}(),t=function(){if(Aj)return Oj;Aj=1,Object.defineProperty(Oj,"__esModule",{value:!0});const e=qM(),t={keyword:"dependentSchemas",type:"object",schemaType:"object",code:t=>(0,e.validateSchemaDeps)(t)};return Oj.default=t,Oj}(),r=function(){if(Ij)return Tj;Ij=1,Object.defineProperty(Tj,"__esModule",{value:!0});const e=RR(),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 Tj.default=t,Tj}(),n=[e.default,t.default,r.default];return Ej.default=n,Ej}var Rj,Lj={},Mj={};function jj(){if(Rj)return Mj;Rj=1,Object.defineProperty(Mj,"__esModule",{value:!0});const e=$R(),t=RR(),r=FR(),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 Mj.default=n,Mj}var Dj,Fj,Uj={};function Bj(){if(Dj)return Uj;Dj=1,Object.defineProperty(Uj,"__esModule",{value:!0});const e=$R(),t=RR(),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 Uj.default=r,Uj}var qj,Vj,Gj={},Hj={};function Wj(){if(qj)return Hj;qj=1,Object.defineProperty(Hj,"__esModule",{value:!0});const e=$R(),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 Hj.default=t,Hj}var Kj,Zj,Jj={};function Yj(){if(Zj)return UL;Zj=1,Object.defineProperty(UL,"__esModule",{value:!0});const e=KL(),t=PM(),r=pj(),n=xj(),a=zj(),i=function(){if(Fj)return Lj;Fj=1,Object.defineProperty(Lj,"__esModule",{value:!0});const e=jj(),t=Bj(),r=[e.default,t.default];return Lj.default=r,Lj}(),s=function(){if(Vj)return Gj;Vj=1,Object.defineProperty(Gj,"__esModule",{value:!0});const e=[Wj().default];return Gj.default=e,Gj}(),o=(Kj||(Kj=1,Object.defineProperty(Jj,"__esModule",{value:!0}),Jj.contentVocabulary=Jj.metadataVocabulary=void 0,Jj.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Jj.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),Jj),c=[n.default,e.default,t.default,(0,r.default)(!0),s.default,o.metadataVocabulary,o.contentVocabulary,a.default,i.default];return UL.default=c,UL}var Xj,Qj,eD={},tD={};function rD(){if(Qj)return eD;Qj=1,Object.defineProperty(eD,"__esModule",{value:!0});const e=$R(),t=(Xj||(Xj=1,Object.defineProperty(tD,"__esModule",{value:!0}),tD.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(r||(tD.DiscrError=r={}))),tD);var r;const n=PL(),a=NL(),i=RR(),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 eD.default=s,eD}var nD,aD,iD={},sD={$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}}},oD={$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"}}}},cD={$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"}}},lD={$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"}}},uD={$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"}}},dD={$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"}}},pD={$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}}},mD={$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 hD=(aD||(aD=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=DL(),n=Yj(),a=rD(),i=function(){if(nD)return iD;nD=1,Object.defineProperty(iD,"__esModule",{value:!0});const e=sD,t=oD,r=cD,n=lD,a=uD,i=dD,s=pD,o=mD,c=["/properties"];return iD.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}},iD}(),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=yL();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var l=$R();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=_L();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return u.default}});var d=NL();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return d.default}})}(_R,_R.exports)),_R.exports),fD=Zn(hD);const gD=se.object({templateEntry:se.string({message:"templateEntry must be a string"}).describe("Main entry point for the portal"),schemaEntry:se.string({message:"schemaEntry must be a string"}).describe("Schema file for portal validation"),assetPath:se.string({message:"assetPath must be a string"}).optional().describe("Asset path for dev/preview builds"),githubRepo:se.string({message:"githubRepo must be a string"}).optional().describe("GitHub repo URL or local git remote"),version:se.string({message:"version must be a string"}).describe("Version from package.json"),timestamp:se.string({message:"timestamp must be a string"}).describe("Current build timestamp (ISO8601)"),commitSha:se.string({message:"commitSha must be a string"}).describe("Current git commit SHA"),annotations:se.record(se.string(),se.string()).optional().describe("Optional build annotations"),projectPage:se.string({message:"projectPage must be a string"}).optional().describe("Optional project homepage"),allowedExtensions:se.array(se.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:se.record(se.string(),se.unknown()).optional().describe("Optional schema for the portal"),config:se.record(se.string(),se.unknown()).optional().describe("Optional configuration for the portal")});se.object({name:se.string({message:"name must be a string"}).describe("Short app key (unscoped, derived from package name)"),displayName:se.string({message:"displayName must be a string"}).optional().describe("Full package name, may include scope"),description:se.string({message:"description must be a string"}).optional().describe("Description of the portal"),build:gD});const yD=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(pt({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 Ce(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));B(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 fD({strict:!0}).compile(n.schema),a=await Ae(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))}}),vD=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})}),bD=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 O({log:r,manifest:e,archive:t.archive,schema:t.schema}).catch(e=>{r.error("Failed to create package:",e),process.exit(1)})}),_D=vt(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(pt({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 I({log:r,framework:n,fileOrBundle:e}).catch(e=>{r.error("Failed to upload bundle:",e),process.exit(1)})}));const wD=vt(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(pt({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:",ct.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"),$({tag:e,name:a.name,version:a.version,framework:i,log:r}).catch(e=>{r?.error("😢 Failed to tag application:",e),process.exit(1)})})),SD=vt(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(pt({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:",ct.redBright(e.env)),t.start("📦 Bundling Portal Template...");const r=await O({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 I({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 $({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")})),ND=vt(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(pt({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",ct.blue("--publish")),r?.info("Example: fusion-framework-cli portal config --publish my-portal@1.2.3"),process.exit(1)),"dev"===t.env&&(r?.fail("🤪",ct.blue("--env"),'cannot be "dev" when',ct.blue("--publish")," is used"),process.exit(1)),T({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))})),kD=e("portal").description("Develop and deploy portal templates").addCommand(Cz).addCommand(vR).addCommand(yD).addCommand(vD).addCommand(bD).addCommand(_D).addCommand(wD).addCommand(SD).addCommand(ND);a();const[xD]=process.versions.node.split(".").map(Number);xD<Number(20)&&(console.error(ct.red("[ERROR]"),"Fusion Framework CLI requires Node.js 20 or higher."),process.exit(1));xD!==Number(22)&&console.warn(ct.yellow("[WARNING]"),"Node.js 22.x (LTS) is recommended for best compatibility. You are using Node.js",process.versions.node);const PD=p({cwd:s(import.meta.url)});if(!PD)throw Error("failed to find program root");process.env.CLI_BIN=c(l(PD.path),String(PD.packageJson.bin?.["fusion-framework-cli"]));const ED=new n;ED.name(PD.packageJson.name),ED.description([`${PD.packageJson.name}@${PD.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")),ED.version(PD.packageJson.version,"-V, --version","CLI version"),(e=>{e.addCommand(Zt),e.addCommand(er),e.addCommand(tr),e.addCommand(nr),e.addCommand(Ez),e.addCommand(kD)})(ED),ED.parse();
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}(yi)),yi}var bi,$i={};var wi,Ei={};function Si(){if(wi)return Ei;wi=1,Object.defineProperty(Ei,"__esModule",{value:!0});const e=On(),t=sn(),r=fn(),n=ln(),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 Ei.default=o,Ei}var Pi,Li={};var _i,ki={};var Ci,Ni={};var Ii,Oi={};var Ai,xi={};var Ti,Di={};var ji,Ri={};var Fi,Mi,Gi={};function Ui(){if(Mi)return ni;Mi=1,Object.defineProperty(ni,"__esModule",{value:!0});const e=ii(),t=function(){if(ai)return ci;ai=1,Object.defineProperty(ci,"__esModule",{value:!0});const e=di(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,e.validateTuple)(t,"items")};return ci.default=t,ci}(),r=di(),n=function(){if(ui)return pi;ui=1,Object.defineProperty(pi,"__esModule",{value:!0});const e=sn(),t=ln(),r=On(),n=ii(),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 pi.default=o,pi}(),o=mi(),i=vi(),s=function(){if(bi)return $i;bi=1,Object.defineProperty($i,"__esModule",{value:!0});const e=sn(),t=ln(),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 $i.default=r,$i}(),a=Si(),c=function(){if(Pi)return Li;Pi=1,Object.defineProperty(Li,"__esModule",{value:!0});const e=Vn(),t=On(),r=ln(),n=Si(),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 Li.default=o,Li}(),l=function(){if(_i)return ki;_i=1,Object.defineProperty(ki,"__esModule",{value:!0});const e=On(),t=sn(),r=ln(),n=ln(),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 ki.default=o,ki}(),d=function(){if(Ci)return Ni;Ci=1,Object.defineProperty(Ni,"__esModule",{value:!0});const e=ln(),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 Ni.default=t,Ni}(),u=function(){if(Ii)return Oi;Ii=1,Object.defineProperty(Oi,"__esModule",{value:!0});const e={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:On().validateUnion,error:{message:"must match a schema in anyOf"}};return Oi.default=e,Oi}(),p=function(){if(Ai)return xi;Ai=1,Object.defineProperty(xi,"__esModule",{value:!0});const e=sn(),t=ln(),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 xi.default=r,xi}(),h=function(){if(Ti)return Di;Ti=1,Object.defineProperty(Di,"__esModule",{value:!0});const e=ln(),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 Di.default=t,Di}(),f=function(){if(ji)return Ri;ji=1,Object.defineProperty(Ri,"__esModule",{value:!0});const e=sn(),t=ln(),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 Ri.default=r,Ri}(),m=function(){if(Fi)return Gi;Fi=1,Object.defineProperty(Gi,"__esModule",{value:!0});const e=ln(),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 Gi.default=t,Gi}();return ni.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},ni}var Bi,zi={},Hi={};function Vi(){if(Bi)return Hi;Bi=1,Object.defineProperty(Hi,"__esModule",{value:!0}),Hi.dynamicAnchor=void 0;const e=sn(),t=fn(),r=eo(),n=Eo(),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 Hi.dynamicAnchor=i,Hi.default=o,Hi}var Wi,qi={};function Ki(){if(Wi)return qi;Wi=1,Object.defineProperty(qi,"__esModule",{value:!0}),qi.dynamicRef=void 0;const e=sn(),t=fn(),r=Eo(),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 qi.dynamicRef=o,qi.default=n,qi}var Ji,Yi={};var Xi,Zi,Qi={};function es(){if(Zi)return zi;Zi=1,Object.defineProperty(zi,"__esModule",{value:!0});const e=Vi(),t=Ki(),r=function(){if(Ji)return Yi;Ji=1,Object.defineProperty(Yi,"__esModule",{value:!0});const e=Vi(),t=ln(),r={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,e.dynamicAnchor)(r,""):(0,t.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};return Yi.default=r,Yi}(),n=function(){if(Xi)return Qi;Xi=1,Object.defineProperty(Qi,"__esModule",{value:!0});const e=Ki(),t={keyword:"$recursiveRef",schemaType:"string",code:t=>(0,e.dynamicRef)(t,t.schema)};return Qi.default=t,Qi}(),o=[e.default,t.default,r.default,n.default];return zi.default=o,zi}var ts,rs={},ns={};var os,is={};var ss,as,cs={};function ls(){if(as)return rs;as=1,Object.defineProperty(rs,"__esModule",{value:!0});const e=function(){if(ts)return ns;ts=1,Object.defineProperty(ns,"__esModule",{value:!0});const e=vi(),t={keyword:"dependentRequired",type:"object",schemaType:"object",error:e.error,code:t=>(0,e.validatePropertyDeps)(t)};return ns.default=t,ns}(),t=function(){if(os)return is;os=1,Object.defineProperty(is,"__esModule",{value:!0});const e=vi(),t={keyword:"dependentSchemas",type:"object",schemaType:"object",code:t=>(0,e.validateSchemaDeps)(t)};return is.default=t,is}(),r=function(){if(ss)return cs;ss=1,Object.defineProperty(cs,"__esModule",{value:!0});const e=ln(),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 cs.default=t,cs}(),n=[e.default,t.default,r.default];return rs.default=n,rs}var ds,us={},ps={};function hs(){if(ds)return ps;ds=1,Object.defineProperty(ps,"__esModule",{value:!0});const e=sn(),t=ln(),r=fn(),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 ps.default=n,ps}var fs,ms,gs={};function ys(){if(fs)return gs;fs=1,Object.defineProperty(gs,"__esModule",{value:!0});const e=sn(),t=ln(),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 gs.default=r,gs}var vs,bs,$s={},ws={};function Es(){if(vs)return ws;vs=1,Object.defineProperty(ws,"__esModule",{value:!0});const e=sn(),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 ws.default=t,ws}var Ss,Ps,Ls={};function _s(){if(Ps)return go;Ps=1,Object.defineProperty(go,"__esModule",{value:!0});const e=So(),t=ti(),r=Ui(),n=es(),o=ls(),i=function(){if(ms)return us;ms=1,Object.defineProperty(us,"__esModule",{value:!0});const e=hs(),t=ys(),r=[e.default,t.default];return us.default=r,us}(),s=function(){if(bs)return $s;bs=1,Object.defineProperty($s,"__esModule",{value:!0});const e=[Es().default];return $s.default=e,$s}(),a=(Ss||(Ss=1,Object.defineProperty(Ls,"__esModule",{value:!0}),Ls.contentVocabulary=Ls.metadataVocabulary=void 0,Ls.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Ls.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),Ls),c=[n.default,e.default,t.default,(0,r.default)(!0),s.default,a.metadataVocabulary,a.contentVocabulary,o.default,i.default];return go.default=c,go}var ks,Cs,Ns={},Is={};function Os(){if(Cs)return Ns;Cs=1,Object.defineProperty(Ns,"__esModule",{value:!0});const e=sn(),t=(ks||(ks=1,Object.defineProperty(Is,"__esModule",{value:!0}),Is.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(r||(Is.DiscrError=r={}))),Is);var r;const n=eo(),o=Xn(),i=ln(),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 Ns.default=s,Ns}var As,xs,Ts={},Ds={$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}}},js={$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"}}}},Rs={$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"}}},Fs={$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"}}},Ms={$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"}}},Gs={$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"}}},Us={$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}}},Bs={$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 zs=(xs||(xs=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=fo(),n=_s(),o=Os(),i=function(){if(As)return Ts;As=1,Object.defineProperty(Ts,"__esModule",{value:!0});const e=Ds,t=js,r=Rs,n=Fs,o=Ms,i=Gs,s=Us,a=Bs,c=["/properties"];return Ts.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}},Ts}(),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=Vn();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var l=sn();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=Kn();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var u=Xn();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return u.default}})}(qr,qr.exports)),qr.exports),Hs=At(zs);const Vs=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:Vs});const Ws=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(Me({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 h("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 ae(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));B(n)||W(n,{recursive:!0}),G(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 Hs({strict:!0}).compile(n.schema),o=await ce(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))}}),qs=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 h("portal:build",{debug:t.debug});await N({log:r,manifest:e})}),Ks=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 h("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)})}),Js=Ve(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(Me({allowDev:!1})).argument("<bundle>","Portal bundle to upload (e.g., out/bundle.zip)").action(async(e,t)=>{const r=new h("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 Ys=Ve(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(Me({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 h("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 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:",De.greenBright(`${o.name}@${o.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"),A({tag:e,name:o.name,version:o.version,framework:i,log:r}).catch(e=>{r?.error("😢 Failed to tag application:",e),process.exit(1)})})),Xs=Ve(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(Me({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 h("portal:publish",{debug:e.debug});t?.info("Using environment:",De.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 A({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")})),Zs=Ve(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(Me({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 h("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",De.blue("--publish")),r?.info("Example: fusion-framework-cli portal config --publish my-portal@1.2.3"),process.exit(1)),"dev"===t.env&&(r?.fail("🤪",De.blue("--env"),'cannot be "dev" when',De.blue("--publish")," is used"),process.exit(1)),x({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 T({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))})),Qs=e("portal").description("Develop and deploy portal templates").addCommand(Ot).addCommand(Vr).addCommand(Ws).addCommand(qs).addCommand(Ks).addCommand(Js).addCommand(Ys).addCommand(Xs).addCommand(Zs);o();const[ea]=process.versions.node.split(".").map(Number);ea<Number(20)&&(console.error(De.red("[ERROR]"),"Fusion Framework CLI requires Node.js 20 or higher."),process.exit(1));ea!==Number(22)&&console.warn(De.yellow("[WARNING]"),"Node.js 22.x (LTS) is recommended for best compatibility. You are using Node.js",process.versions.node);const ta=p({cwd:s(import.meta.url)});if(!ta)throw Error("failed to find program root");process.env.CLI_BIN=c(l(ta.path),String(ta.packageJson.bin?.["fusion-framework-cli"]));const ra=new n;ra.name(ta.packageJson.name),ra.description([`${ta.packageJson.name}@${ta.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")),ra.version(ta.packageJson.version,"-V, --version","CLI version"),await(async e=>{e.addCommand(Et),e.addCommand(kt),e.addCommand(Ct),e.addCommand(It),e.addCommand(Qs),await async function(e){const t=[],r=async e=>{try{const t=l(e);return(await ae(["fusion-cli.config"],{baseDir:t,script:{resolve:async e=>{const r=e.default;return"function"==typeof r?await r({root:t})??{plugins:[]}:r??{plugins:[]}}}})).config.plugins||[]}catch(t){return t instanceof le||console.warn(`Warning: Failed to load plugin configuration from ${e}:`,t),[]}},n=[process.cwd(),s(import.meta.url)],o=await Promise.all(n.map(async e=>await de(["fusion-cli.config.ts","fusion-cli.config.js","fusion-cli.config.json"],{cwd:l(e)}))),i=Array.from(new Set(o.filter(e=>null!=e)));for(const e of i){const n=await r(e);t.push(...n)}if(0===t.length)return;const c=await u({cwd:process.cwd()}),p=c?l(c.path):process.cwd(),h=s(import.meta.url),f=await u({cwd:l(h)}),m=l(f?f.path:h);for(const r of t)try{if("function"==typeof r){r(e);continue}const t=r;let n=null,o=!1;if("function"==typeof import.meta.resolve)try{const e=import.meta.resolve(t);n=await import(e),o=!0}catch{}if(!o)try{n=await import(t),o=!0}catch{}if(!o)try{const e=d(m,"node_modules",t),r=d(e,"package.json"),i=JSON.parse(M(r,"utf-8")),s=i.exports?.["."]?.import||i.main,c=d(e,s),l=a(c).href;n=await import(l),o=!0}catch{}if(!o)try{const e=d(p,"node_modules",t),r=d(e,"package.json"),i=JSON.parse(M(r,"utf-8")),s=i.exports?.["."]?.import||i.main,c=d(e,s),l=a(c).href;n=await import(l),o=!0}catch{}if(!o||!n)throw new Error(`Could not resolve plugin "${t}" using any resolution strategy`);n.registerAiPlugin?n.registerAiPlugin(e):n.default?"function"==typeof n.default&&n.default(e):console.warn(`Warning: Plugin "${t}" does not export a registration function.`)}catch(e){if(e instanceof Error&&(e.message.includes("Cannot find module")||e.message.includes("MODULE_NOT_FOUND"))){const e="string"==typeof r?r:"function";console.warn(`Warning: Plugin "${e}" is not installed. Install it to use its commands.`)}else{const t="string"==typeof r?r:"function";console.warn(`Warning: Failed to load plugin "${t}":`,e)}}}(e)})(ra),ra.parse();