@sippulse/niva 0.4.0-rc.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +83 -66
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -1,58 +1,53 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// @bun
|
|
3
|
-
import{createRequire as
|
|
4
|
-
`)}displayWidth($){return
|
|
5
|
-
`+" ".repeat(U+j));return W+
|
|
6
|
-
${W}`)}boxWrap($,U){if(U<this.minWidthToWrap)return $;let K=$.split(/\r\n|\n/),q=/[\s]*[^\s]+/g,Q=[];return K.forEach((W)=>{let
|
|
7
|
-
`)}}function
|
|
3
|
+
import{createRequire as iV}from"node:module";var yV=Object.create;var{getPrototypeOf:gV,defineProperty:G8,getOwnPropertyNames:uV}=Object;var fV=Object.prototype.hasOwnProperty;function mV($){return this[$]}var hV,cV,N1=($,U,K)=>{var q=$!=null&&typeof $==="object";if(q){var Q=U?hV??=new WeakMap:cV??=new WeakMap,W=Q.get($);if(W)return W}K=$!=null?yV(gV($)):{};let G=U||!$||!$.__esModule?G8(K,"default",{value:$,enumerable:!0}):K;for(let j of uV($))if(!fV.call(G,j))G8(G,j,{get:mV.bind($,j),enumerable:!0});if(q)Q.set($,G);return G};var R1=($,U)=>()=>(U||$((U={exports:{}}).exports,U),U.exports);var lV=($)=>$;function rV($,U){this[$]=lV.bind(null,U)}var L1=($,U)=>{for(var K in U)G8($,K,{get:U[K],enumerable:!0,configurable:!0,set:rV.bind(U,K)})};var x6=iV(import.meta.url);var w6=R1((dV)=>{class j8 extends Error{constructor($,U,K){super(K);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=U,this.exitCode=$,this.nestedError=void 0}}class SG extends j8{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}dV.CommanderError=j8;dV.InvalidArgumentError=SG});var O0=R1((aV)=>{var{InvalidArgumentError:pV}=w6();class CG{constructor($,U){switch(this.description=U||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,$[0]){case"<":this.required=!0,this._name=$.slice(1,-1);break;case"[":this.required=!1,this._name=$.slice(1,-1);break;default:this.required=!0,this._name=$;break}if(this._name.length>3&&this._name.slice(-3)==="...")this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_concatValue($,U){if(U===this.defaultValue||!Array.isArray(U))return[$];return U.concat($)}default($,U){return this.defaultValue=$,this.defaultValueDescription=U,this}argParser($){return this.parseArg=$,this}choices($){return this.argChoices=$.slice(),this.parseArg=(U,K)=>{if(!this.argChoices.includes(U))throw new pV(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(U,K);return U},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function tV($){let U=$.name()+($.variadic===!0?"...":"");return $.required?"<"+U+">":"["+U+"]"}aV.Argument=CG;aV.humanReadableArgName=tV});var Y8=R1((UM)=>{var{humanReadableArgName:$M}=O0();class EG{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext($){this.helpWidth=this.helpWidth??$.helpWidth??80}visibleCommands($){let U=$.commands.filter((q)=>!q._hidden),K=$._getHelpCommand();if(K&&!K._hidden)U.push(K);if(this.sortSubcommands)U.sort((q,Q)=>{return q.name().localeCompare(Q.name())});return U}compareOptions($,U){let K=(q)=>{return q.short?q.short.replace(/^-/,""):q.long.replace(/^--/,"")};return K($).localeCompare(K(U))}visibleOptions($){let U=$.options.filter((q)=>!q.hidden),K=$._getHelpOption();if(K&&!K.hidden){let q=K.short&&$._findOption(K.short),Q=K.long&&$._findOption(K.long);if(!q&&!Q)U.push(K);else if(K.long&&!Q)U.push($.createOption(K.long,K.description));else if(K.short&&!q)U.push($.createOption(K.short,K.description))}if(this.sortOptions)U.sort(this.compareOptions);return U}visibleGlobalOptions($){if(!this.showGlobalOptions)return[];let U=[];for(let K=$.parent;K;K=K.parent){let q=K.options.filter((Q)=>!Q.hidden);U.push(...q)}if(this.sortOptions)U.sort(this.compareOptions);return U}visibleArguments($){if($._argsDescription)$.registeredArguments.forEach((U)=>{U.description=U.description||$._argsDescription[U.name()]||""});if($.registeredArguments.find((U)=>U.description))return $.registeredArguments;return[]}subcommandTerm($){let U=$.registeredArguments.map((K)=>$M(K)).join(" ");return $._name+($._aliases[0]?"|"+$._aliases[0]:"")+($.options.length?" [options]":"")+(U?" "+U:"")}optionTerm($){return $.flags}argumentTerm($){return $.name()}longestSubcommandTermLength($,U){return U.visibleCommands($).reduce((K,q)=>{return Math.max(K,this.displayWidth(U.styleSubcommandTerm(U.subcommandTerm(q))))},0)}longestOptionTermLength($,U){return U.visibleOptions($).reduce((K,q)=>{return Math.max(K,this.displayWidth(U.styleOptionTerm(U.optionTerm(q))))},0)}longestGlobalOptionTermLength($,U){return U.visibleGlobalOptions($).reduce((K,q)=>{return Math.max(K,this.displayWidth(U.styleOptionTerm(U.optionTerm(q))))},0)}longestArgumentTermLength($,U){return U.visibleArguments($).reduce((K,q)=>{return Math.max(K,this.displayWidth(U.styleArgumentTerm(U.argumentTerm(q))))},0)}commandUsage($){let U=$._name;if($._aliases[0])U=U+"|"+$._aliases[0];let K="";for(let q=$.parent;q;q=q.parent)K=q.name()+" "+K;return K+U+" "+$.usage()}commandDescription($){return $.description()}subcommandDescription($){return $.summary()||$.description()}optionDescription($){let U=[];if($.argChoices)U.push(`choices: ${$.argChoices.map((K)=>JSON.stringify(K)).join(", ")}`);if($.defaultValue!==void 0){if($.required||$.optional||$.isBoolean()&&typeof $.defaultValue==="boolean")U.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`)}if($.presetArg!==void 0&&$.optional)U.push(`preset: ${JSON.stringify($.presetArg)}`);if($.envVar!==void 0)U.push(`env: ${$.envVar}`);if(U.length>0)return`${$.description} (${U.join(", ")})`;return $.description}argumentDescription($){let U=[];if($.argChoices)U.push(`choices: ${$.argChoices.map((K)=>JSON.stringify(K)).join(", ")}`);if($.defaultValue!==void 0)U.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`);if(U.length>0){let K=`(${U.join(", ")})`;if($.description)return`${$.description} ${K}`;return K}return $.description}formatHelp($,U){let K=U.padWidth($,U),q=U.helpWidth??80;function Q(X,B){return U.formatItem(X,K,B,U)}let W=[`${U.styleTitle("Usage:")} ${U.styleUsage(U.commandUsage($))}`,""],G=U.commandDescription($);if(G.length>0)W=W.concat([U.boxWrap(U.styleCommandDescription(G),q),""]);let j=U.visibleArguments($).map((X)=>{return Q(U.styleArgumentTerm(U.argumentTerm(X)),U.styleArgumentDescription(U.argumentDescription(X)))});if(j.length>0)W=W.concat([U.styleTitle("Arguments:"),...j,""]);let Y=U.visibleOptions($).map((X)=>{return Q(U.styleOptionTerm(U.optionTerm(X)),U.styleOptionDescription(U.optionDescription(X)))});if(Y.length>0)W=W.concat([U.styleTitle("Options:"),...Y,""]);if(U.showGlobalOptions){let X=U.visibleGlobalOptions($).map((B)=>{return Q(U.styleOptionTerm(U.optionTerm(B)),U.styleOptionDescription(U.optionDescription(B)))});if(X.length>0)W=W.concat([U.styleTitle("Global Options:"),...X,""])}let H=U.visibleCommands($).map((X)=>{return Q(U.styleSubcommandTerm(U.subcommandTerm(X)),U.styleSubcommandDescription(U.subcommandDescription(X)))});if(H.length>0)W=W.concat([U.styleTitle("Commands:"),...H,""]);return W.join(`
|
|
4
|
+
`)}displayWidth($){return yG($).length}styleTitle($){return $}styleUsage($){return $.split(" ").map((U)=>{if(U==="[options]")return this.styleOptionText(U);if(U==="[command]")return this.styleSubcommandText(U);if(U[0]==="["||U[0]==="<")return this.styleArgumentText(U);return this.styleCommandText(U)}).join(" ")}styleCommandDescription($){return this.styleDescriptionText($)}styleOptionDescription($){return this.styleDescriptionText($)}styleSubcommandDescription($){return this.styleDescriptionText($)}styleArgumentDescription($){return this.styleDescriptionText($)}styleDescriptionText($){return $}styleOptionTerm($){return this.styleOptionText($)}styleSubcommandTerm($){return $.split(" ").map((U)=>{if(U==="[options]")return this.styleOptionText(U);if(U[0]==="["||U[0]==="<")return this.styleArgumentText(U);return this.styleSubcommandText(U)}).join(" ")}styleArgumentTerm($){return this.styleArgumentText($)}styleOptionText($){return $}styleArgumentText($){return $}styleSubcommandText($){return $}styleCommandText($){return $}padWidth($,U){return Math.max(U.longestOptionTermLength($,U),U.longestGlobalOptionTermLength($,U),U.longestSubcommandTermLength($,U),U.longestArgumentTermLength($,U))}preformatted($){return/\n[^\S\r\n]/.test($)}formatItem($,U,K,q){let W=" ".repeat(2);if(!K)return W+$;let G=$.padEnd(U+$.length-q.displayWidth($)),j=2,H=(this.helpWidth??80)-U-j-2,X;if(H<this.minWidthToWrap||q.preformatted(K))X=K;else X=q.boxWrap(K,H).replace(/\n/g,`
|
|
5
|
+
`+" ".repeat(U+j));return W+G+" ".repeat(j)+X.replace(/\n/g,`
|
|
6
|
+
${W}`)}boxWrap($,U){if(U<this.minWidthToWrap)return $;let K=$.split(/\r\n|\n/),q=/[\s]*[^\s]+/g,Q=[];return K.forEach((W)=>{let G=W.match(q);if(G===null){Q.push("");return}let j=[G.shift()],Y=this.displayWidth(j[0]);G.forEach((H)=>{let X=this.displayWidth(H);if(Y+X<=U){j.push(H),Y+=X;return}Q.push(j.join(""));let B=H.trimStart();j=[B],Y=this.displayWidth(B)}),Q.push(j.join(""))}),Q.join(`
|
|
7
|
+
`)}}function yG($){let U=/\x1b\[\d*(;\d*)*m/g;return $.replace(U,"")}UM.Help=EG;UM.stripColor=yG});var H8=R1((GM)=>{var{InvalidArgumentError:qM}=w6();class uG{constructor($,U){this.flags=$,this.description=U||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let K=WM($);if(this.short=K.shortFlag,this.long=K.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default($,U){return this.defaultValue=$,this.defaultValueDescription=U,this}preset($){return this.presetArg=$,this}conflicts($){return this.conflictsWith=this.conflictsWith.concat($),this}implies($){let U=$;if(typeof $==="string")U={[$]:!0};return this.implied=Object.assign(this.implied||{},U),this}env($){return this.envVar=$,this}argParser($){return this.parseArg=$,this}makeOptionMandatory($=!0){return this.mandatory=!!$,this}hideHelp($=!0){return this.hidden=!!$,this}_concatValue($,U){if(U===this.defaultValue||!Array.isArray(U))return[$];return U.concat($)}choices($){return this.argChoices=$.slice(),this.parseArg=(U,K)=>{if(!this.argChoices.includes(U))throw new qM(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(U,K);return U},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return gG(this.name().replace(/^no-/,""));return gG(this.name())}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class fG{constructor($){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,$.forEach((U)=>{if(U.negate)this.negativeOptions.set(U.attributeName(),U);else this.positiveOptions.set(U.attributeName(),U)}),this.negativeOptions.forEach((U,K)=>{if(this.positiveOptions.has(K))this.dualOptions.add(K)})}valueFromOption($,U){let K=U.attributeName();if(!this.dualOptions.has(K))return!0;let q=this.negativeOptions.get(K).presetArg,Q=q!==void 0?q:!1;return U.negate===(Q===$)}}function gG($){return $.split("-").reduce((U,K)=>{return U+K[0].toUpperCase()+K.slice(1)})}function WM($){let U,K,q=/^-[^-]$/,Q=/^--[^-]/,W=$.split(/[ |,]+/).concat("guard");if(q.test(W[0]))U=W.shift();if(Q.test(W[0]))K=W.shift();if(!U&&q.test(W[0]))U=W.shift();if(!U&&Q.test(W[0]))U=K,K=W.shift();if(W[0].startsWith("-")){let G=W[0],j=`option creation failed due to '${G}' in option flags '${$}'`;if(/^-[^-][^-]/.test(G))throw Error(`${j}
|
|
8
8
|
- a short flag is a single dash and a single character
|
|
9
9
|
- either use a single dash and a single character (for a short flag)
|
|
10
|
-
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(q.test(
|
|
11
|
-
- too many short flags`);if(Q.test(
|
|
10
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(q.test(G))throw Error(`${j}
|
|
11
|
+
- too many short flags`);if(Q.test(G))throw Error(`${j}
|
|
12
12
|
- too many long flags`);throw Error(`${j}
|
|
13
|
-
- unrecognised flag format`)}if(U===void 0&&K===void 0)throw Error(`option creation failed due to no flags found in '${$}'.`);return{shortFlag:U,longFlag:K}}
|
|
13
|
+
- unrecognised flag format`)}if(U===void 0&&K===void 0)throw Error(`option creation failed due to no flags found in '${$}'.`);return{shortFlag:U,longFlag:K}}GM.Option=uG;GM.DualOptions=fG});var mG=R1((XM)=>{function YM($,U){if(Math.abs($.length-U.length)>3)return Math.max($.length,U.length);let K=[];for(let q=0;q<=$.length;q++)K[q]=[q];for(let q=0;q<=U.length;q++)K[0][q]=q;for(let q=1;q<=U.length;q++)for(let Q=1;Q<=$.length;Q++){let W=1;if($[Q-1]===U[q-1])W=0;else W=1;if(K[Q][q]=Math.min(K[Q-1][q]+1,K[Q][q-1]+1,K[Q-1][q-1]+W),Q>1&&q>1&&$[Q-1]===U[q-2]&&$[Q-2]===U[q-1])K[Q][q]=Math.min(K[Q][q],K[Q-2][q-2]+1)}return K[$.length][U.length]}function HM($,U){if(!U||U.length===0)return"";U=Array.from(new Set(U));let K=$.startsWith("--");if(K)$=$.slice(2),U=U.map((G)=>G.slice(2));let q=[],Q=3,W=0.4;if(U.forEach((G)=>{if(G.length<=1)return;let j=YM($,G),Y=Math.max($.length,G.length);if((Y-j)/Y>W){if(j<Q)Q=j,q=[G];else if(j===Q)q.push(G)}}),q.sort((G,j)=>G.localeCompare(j)),K)q=q.map((G)=>`--${G}`);if(q.length>1)return`
|
|
14
14
|
(Did you mean one of ${q.join(", ")}?)`;if(q.length===1)return`
|
|
15
|
-
(Did you mean ${q[0]}?)`;return""}
|
|
16
|
-
- specify the name in Command constructor or using .name()`);if(U=U||{},U.isDefault)this._defaultCommandName=$._name;if(U.noHelp||U.hidden)$._hidden=!0;return this._registerCommand($),$.parent=this,$._checkForBrokenPassThrough(),this}createArgument($,U){return new
|
|
17
|
-
Expecting one of '${K.join("', '")}'`);if(this._lifeCycleHooks[$])this._lifeCycleHooks[$].push(U);else this._lifeCycleHooks[$]=[U];return this}exitOverride($){if($)this._exitCallback=$;else this._exitCallback=(U)=>{if(U.code!=="commander.executeSubCommandAsync")throw U};return this}_exit($,U,K){if(this._exitCallback)this._exitCallback(new
|
|
18
|
-
- already used by option '${U.flags}'`)}this.options.push($)}_registerCommand($){let U=(q)=>{return[q.name()].concat(q.aliases())},K=U($).find((q)=>this._findCommand(q));if(K){let q=U(this._findCommand(K)).join("|"),Q=U($).join("|");throw Error(`cannot add command '${Q}' as already have command '${q}'`)}this.commands.push($)}addOption($){this._registerOption($);let U=$.name(),K=$.attributeName();if($.negate){let Q=$.long.replace(/^--no-/,"--");if(!this._findOption(Q))this.setOptionValueWithSource(K,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(K,$.defaultValue,"default");let q=(Q,W,
|
|
19
|
-
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable($,U,K){if(
|
|
15
|
+
(Did you mean ${q[0]}?)`;return""}XM.suggestSimilar=HM});var rG=R1((LM)=>{var BM=x6("node:events").EventEmitter,X8=x6("node:child_process"),_1=x6("node:path"),T0=x6("node:fs"),p=x6("node:process"),{Argument:VM,humanReadableArgName:MM}=O0(),{CommanderError:Z8}=w6(),{Help:DM,stripColor:PM}=Y8(),{Option:hG,DualOptions:NM}=H8(),{suggestSimilar:cG}=mG();class V8 extends BM{constructor($){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=$||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:(U)=>p.stdout.write(U),writeErr:(U)=>p.stderr.write(U),outputError:(U,K)=>K(U),getOutHelpWidth:()=>p.stdout.isTTY?p.stdout.columns:void 0,getErrHelpWidth:()=>p.stderr.isTTY?p.stderr.columns:void 0,getOutHasColors:()=>B8()??(p.stdout.isTTY&&p.stdout.hasColors?.()),getErrHasColors:()=>B8()??(p.stderr.isTTY&&p.stderr.hasColors?.()),stripColor:(U)=>PM(U)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings($){return this._outputConfiguration=$._outputConfiguration,this._helpOption=$._helpOption,this._helpCommand=$._helpCommand,this._helpConfiguration=$._helpConfiguration,this._exitCallback=$._exitCallback,this._storeOptionsAsProperties=$._storeOptionsAsProperties,this._combineFlagAndOptionalValue=$._combineFlagAndOptionalValue,this._allowExcessArguments=$._allowExcessArguments,this._enablePositionalOptions=$._enablePositionalOptions,this._showHelpAfterError=$._showHelpAfterError,this._showSuggestionAfterError=$._showSuggestionAfterError,this}_getCommandAndAncestors(){let $=[];for(let U=this;U;U=U.parent)$.push(U);return $}command($,U,K){let q=U,Q=K;if(typeof q==="object"&&q!==null)Q=q,q=null;Q=Q||{};let[,W,G]=$.match(/([^ ]+) *(.*)/),j=this.createCommand(W);if(q)j.description(q),j._executableHandler=!0;if(Q.isDefault)this._defaultCommandName=j._name;if(j._hidden=!!(Q.noHelp||Q.hidden),j._executableFile=Q.executableFile||null,G)j.arguments(G);if(this._registerCommand(j),j.parent=this,j.copyInheritedSettings(this),q)return this;return j}createCommand($){return new V8($)}createHelp(){return Object.assign(new DM,this.configureHelp())}configureHelp($){if($===void 0)return this._helpConfiguration;return this._helpConfiguration=$,this}configureOutput($){if($===void 0)return this._outputConfiguration;return Object.assign(this._outputConfiguration,$),this}showHelpAfterError($=!0){if(typeof $!=="string")$=!!$;return this._showHelpAfterError=$,this}showSuggestionAfterError($=!0){return this._showSuggestionAfterError=!!$,this}addCommand($,U){if(!$._name)throw Error(`Command passed to .addCommand() must have a name
|
|
16
|
+
- specify the name in Command constructor or using .name()`);if(U=U||{},U.isDefault)this._defaultCommandName=$._name;if(U.noHelp||U.hidden)$._hidden=!0;return this._registerCommand($),$.parent=this,$._checkForBrokenPassThrough(),this}createArgument($,U){return new VM($,U)}argument($,U,K,q){let Q=this.createArgument($,U);if(typeof K==="function")Q.default(q).argParser(K);else Q.default(K);return this.addArgument(Q),this}arguments($){return $.trim().split(/ +/).forEach((U)=>{this.argument(U)}),this}addArgument($){let U=this.registeredArguments.slice(-1)[0];if(U&&U.variadic)throw Error(`only the last argument can be variadic '${U.name()}'`);if($.required&&$.defaultValue!==void 0&&$.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${$.name()}'`);return this.registeredArguments.push($),this}helpCommand($,U){if(typeof $==="boolean")return this._addImplicitHelpCommand=$,this;$=$??"help [command]";let[,K,q]=$.match(/([^ ]+) *(.*)/),Q=U??"display help for command",W=this.createCommand(K);if(W.helpOption(!1),q)W.arguments(q);if(Q)W.description(Q);return this._addImplicitHelpCommand=!0,this._helpCommand=W,this}addHelpCommand($,U){if(typeof $!=="object")return this.helpCommand($,U),this;return this._addImplicitHelpCommand=!0,this._helpCommand=$,this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook($,U){let K=["preSubcommand","preAction","postAction"];if(!K.includes($))throw Error(`Unexpected value for event passed to hook : '${$}'.
|
|
17
|
+
Expecting one of '${K.join("', '")}'`);if(this._lifeCycleHooks[$])this._lifeCycleHooks[$].push(U);else this._lifeCycleHooks[$]=[U];return this}exitOverride($){if($)this._exitCallback=$;else this._exitCallback=(U)=>{if(U.code!=="commander.executeSubCommandAsync")throw U};return this}_exit($,U,K){if(this._exitCallback)this._exitCallback(new Z8($,U,K));p.exit($)}action($){let U=(K)=>{let q=this.registeredArguments.length,Q=K.slice(0,q);if(this._storeOptionsAsProperties)Q[q]=this;else Q[q]=this.opts();return Q.push(this),$.apply(this,Q)};return this._actionHandler=U,this}createOption($,U){return new hG($,U)}_callParseArg($,U,K,q){try{return $.parseArg(U,K)}catch(Q){if(Q.code==="commander.invalidArgument"){let W=`${q} ${Q.message}`;this.error(W,{exitCode:Q.exitCode,code:Q.code})}throw Q}}_registerOption($){let U=$.short&&this._findOption($.short)||$.long&&this._findOption($.long);if(U){let K=$.long&&this._findOption($.long)?$.long:$.short;throw Error(`Cannot add option '${$.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${K}'
|
|
18
|
+
- already used by option '${U.flags}'`)}this.options.push($)}_registerCommand($){let U=(q)=>{return[q.name()].concat(q.aliases())},K=U($).find((q)=>this._findCommand(q));if(K){let q=U(this._findCommand(K)).join("|"),Q=U($).join("|");throw Error(`cannot add command '${Q}' as already have command '${q}'`)}this.commands.push($)}addOption($){this._registerOption($);let U=$.name(),K=$.attributeName();if($.negate){let Q=$.long.replace(/^--no-/,"--");if(!this._findOption(Q))this.setOptionValueWithSource(K,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(K,$.defaultValue,"default");let q=(Q,W,G)=>{if(Q==null&&$.presetArg!==void 0)Q=$.presetArg;let j=this.getOptionValue(K);if(Q!==null&&$.parseArg)Q=this._callParseArg($,Q,j,W);else if(Q!==null&&$.variadic)Q=$._concatValue(Q,j);if(Q==null)if($.negate)Q=!1;else if($.isBoolean()||$.optional)Q=!0;else Q="";this.setOptionValueWithSource(K,Q,G)};if(this.on("option:"+U,(Q)=>{let W=`error: option '${$.flags}' argument '${Q}' is invalid.`;q(Q,W,"cli")}),$.envVar)this.on("optionEnv:"+U,(Q)=>{let W=`error: option '${$.flags}' value '${Q}' from env '${$.envVar}' is invalid.`;q(Q,W,"env")});return this}_optionEx($,U,K,q,Q){if(typeof U==="object"&&U instanceof hG)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let W=this.createOption(U,K);if(W.makeOptionMandatory(!!$.mandatory),typeof q==="function")W.default(Q).argParser(q);else if(q instanceof RegExp){let G=q;q=(j,Y)=>{let H=G.exec(j);return H?H[0]:Y},W.default(Q).argParser(q)}else W.default(q);return this.addOption(W)}option($,U,K,q){return this._optionEx({},$,U,K,q)}requiredOption($,U,K,q){return this._optionEx({mandatory:!0},$,U,K,q)}combineFlagAndOptionalValue($=!0){return this._combineFlagAndOptionalValue=!!$,this}allowUnknownOption($=!0){return this._allowUnknownOption=!!$,this}allowExcessArguments($=!0){return this._allowExcessArguments=!!$,this}enablePositionalOptions($=!0){return this._enablePositionalOptions=!!$,this}passThroughOptions($=!0){return this._passThroughOptions=!!$,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties($=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!$,this}getOptionValue($){if(this._storeOptionsAsProperties)return this[$];return this._optionValues[$]}setOptionValue($,U){return this.setOptionValueWithSource($,U,void 0)}setOptionValueWithSource($,U,K){if(this._storeOptionsAsProperties)this[$]=U;else this._optionValues[$]=U;return this._optionValueSources[$]=K,this}getOptionValueSource($){return this._optionValueSources[$]}getOptionValueSourceWithGlobals($){let U;return this._getCommandAndAncestors().forEach((K)=>{if(K.getOptionValueSource($)!==void 0)U=K.getOptionValueSource($)}),U}_prepareUserArgs($,U){if($!==void 0&&!Array.isArray($))throw Error("first parameter to parse must be array or undefined");if(U=U||{},$===void 0&&U.from===void 0){if(p.versions?.electron)U.from="electron";let q=p.execArgv??[];if(q.includes("-e")||q.includes("--eval")||q.includes("-p")||q.includes("--print"))U.from="eval"}if($===void 0)$=p.argv;this.rawArgs=$.slice();let K;switch(U.from){case void 0:case"node":this._scriptPath=$[1],K=$.slice(2);break;case"electron":if(p.defaultApp)this._scriptPath=$[1],K=$.slice(2);else K=$.slice(1);break;case"user":K=$.slice(0);break;case"eval":K=$.slice(1);break;default:throw Error(`unexpected parse option { from: '${U.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",K}parse($,U){this._prepareForParse();let K=this._prepareUserArgs($,U);return this._parseCommand([],K),this}async parseAsync($,U){this._prepareForParse();let K=this._prepareUserArgs($,U);return await this._parseCommand([],K),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
19
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable($,U,K){if(T0.existsSync($))return;let q=U?`searched for local subcommand relative to directory '${U}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",Q=`'${$}' does not exist
|
|
20
20
|
- if '${K}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
21
21
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
22
|
-
- ${q}`;throw Error(Q)}_executeSubCommand($,U){U=U.slice();let K=!1,q=[".js",".ts",".tsx",".mjs",".cjs"];function Q(H,
|
|
22
|
+
- ${q}`;throw Error(Q)}_executeSubCommand($,U){U=U.slice();let K=!1,q=[".js",".ts",".tsx",".mjs",".cjs"];function Q(H,X){let B=_1.resolve(H,X);if(T0.existsSync(B))return B;if(q.includes(_1.extname(X)))return;let M=q.find((I)=>T0.existsSync(`${B}${I}`));if(M)return`${B}${M}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let W=$._executableFile||`${this._name}-${$._name}`,G=this._executableDir||"";if(this._scriptPath){let H;try{H=T0.realpathSync(this._scriptPath)}catch{H=this._scriptPath}G=_1.resolve(_1.dirname(H),G)}if(G){let H=Q(G,W);if(!H&&!$._executableFile&&this._scriptPath){let X=_1.basename(this._scriptPath,_1.extname(this._scriptPath));if(X!==this._name)H=Q(G,`${X}-${$._name}`)}W=H||W}K=q.includes(_1.extname(W));let j;if(p.platform!=="win32")if(K)U.unshift(W),U=lG(p.execArgv).concat(U),j=X8.spawn(p.argv[0],U,{stdio:"inherit"});else j=X8.spawn(W,U,{stdio:"inherit"});else this._checkForMissingExecutable(W,G,$._name),U.unshift(W),U=lG(p.execArgv).concat(U),j=X8.spawn(p.execPath,U,{stdio:"inherit"});if(!j.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((X)=>{p.on(X,()=>{if(j.killed===!1&&j.exitCode===null)j.kill(X)})});let Y=this._exitCallback;j.on("close",(H)=>{if(H=H??1,!Y)p.exit(H);else Y(new Z8(H,"commander.executeSubCommandAsync","(close)"))}),j.on("error",(H)=>{if(H.code==="ENOENT")this._checkForMissingExecutable(W,G,$._name);else if(H.code==="EACCES")throw Error(`'${W}' not executable`);if(!Y)p.exit(1);else{let X=new Z8(1,"commander.executeSubCommandAsync","(error)");X.nestedError=H,Y(X)}}),this.runningCommand=j}_dispatchSubcommand($,U,K){let q=this._findCommand($);if(!q)this.help({error:!0});q._prepareForParse();let Q;return Q=this._chainOrCallSubCommandHook(Q,q,"preSubcommand"),Q=this._chainOrCall(Q,()=>{if(q._executableHandler)this._executeSubCommand(q,U.concat(K));else return q._parseCommand(U,K)}),Q}_dispatchHelpCommand($){if(!$)this.help();let U=this._findCommand($);if(U&&!U._executableHandler)U.help();return this._dispatchSubcommand($,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach(($,U)=>{if($.required&&this.args[U]==null)this.missingArgument($.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let $=(K,q,Q)=>{let W=q;if(q!==null&&K.parseArg){let G=`error: command-argument value '${q}' is invalid for argument '${K.name()}'.`;W=this._callParseArg(K,q,Q,G)}return W};this._checkNumberOfArguments();let U=[];this.registeredArguments.forEach((K,q)=>{let Q=K.defaultValue;if(K.variadic){if(q<this.args.length){if(Q=this.args.slice(q),K.parseArg)Q=Q.reduce((W,G)=>{return $(K,G,W)},K.defaultValue)}else if(Q===void 0)Q=[]}else if(q<this.args.length){if(Q=this.args[q],K.parseArg)Q=$(K,Q,K.defaultValue)}U[q]=Q}),this.processedArgs=U}_chainOrCall($,U){if($&&$.then&&typeof $.then==="function")return $.then(()=>U());return U()}_chainOrCallHooks($,U){let K=$,q=[];if(this._getCommandAndAncestors().reverse().filter((Q)=>Q._lifeCycleHooks[U]!==void 0).forEach((Q)=>{Q._lifeCycleHooks[U].forEach((W)=>{q.push({hookedCommand:Q,callback:W})})}),U==="postAction")q.reverse();return q.forEach((Q)=>{K=this._chainOrCall(K,()=>{return Q.callback(Q.hookedCommand,this)})}),K}_chainOrCallSubCommandHook($,U,K){let q=$;if(this._lifeCycleHooks[K]!==void 0)this._lifeCycleHooks[K].forEach((Q)=>{q=this._chainOrCall(q,()=>{return Q(this,U)})});return q}_parseCommand($,U){let K=this.parseOptions(U);if(this._parseOptionsEnv(),this._parseOptionsImplied(),$=$.concat(K.operands),U=K.unknown,this.args=$.concat(U),$&&this._findCommand($[0]))return this._dispatchSubcommand($[0],$.slice(1),U);if(this._getHelpCommand()&&$[0]===this._getHelpCommand().name())return this._dispatchHelpCommand($[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(U),this._dispatchSubcommand(this._defaultCommandName,$,U);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(K.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let q=()=>{if(K.unknown.length>0)this.unknownOption(K.unknown[0])},Q=`command:${this.name()}`;if(this._actionHandler){q(),this._processArguments();let W;if(W=this._chainOrCallHooks(W,"preAction"),W=this._chainOrCall(W,()=>this._actionHandler(this.processedArgs)),this.parent)W=this._chainOrCall(W,()=>{this.parent.emit(Q,$,U)});return W=this._chainOrCallHooks(W,"postAction"),W}if(this.parent&&this.parent.listenerCount(Q))q(),this._processArguments(),this.parent.emit(Q,$,U);else if($.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",$,U);if(this.listenerCount("command:*"))this.emit("command:*",$,U);else if(this.commands.length)this.unknownCommand();else q(),this._processArguments()}else if(this.commands.length)q(),this.help({error:!0});else q(),this._processArguments()}_findCommand($){if(!$)return;return this.commands.find((U)=>U._name===$||U._aliases.includes($))}_findOption($){return this.options.find((U)=>U.is($))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(($)=>{$.options.forEach((U)=>{if(U.mandatory&&$.getOptionValue(U.attributeName())===void 0)$.missingMandatoryOptionValue(U)})})}_checkForConflictingLocalOptions(){let $=this.options.filter((K)=>{let q=K.attributeName();if(this.getOptionValue(q)===void 0)return!1;return this.getOptionValueSource(q)!=="default"});$.filter((K)=>K.conflictsWith.length>0).forEach((K)=>{let q=$.find((Q)=>K.conflictsWith.includes(Q.attributeName()));if(q)this._conflictingOption(K,q)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(($)=>{$._checkForConflictingLocalOptions()})}parseOptions($){let U=[],K=[],q=U,Q=$.slice();function W(j){return j.length>1&&j[0]==="-"}let G=null;while(Q.length){let j=Q.shift();if(j==="--"){if(q===K)q.push(j);q.push(...Q);break}if(G&&!W(j)){this.emit(`option:${G.name()}`,j);continue}if(G=null,W(j)){let Y=this._findOption(j);if(Y){if(Y.required){let H=Q.shift();if(H===void 0)this.optionMissingArgument(Y);this.emit(`option:${Y.name()}`,H)}else if(Y.optional){let H=null;if(Q.length>0&&!W(Q[0]))H=Q.shift();this.emit(`option:${Y.name()}`,H)}else this.emit(`option:${Y.name()}`);G=Y.variadic?Y:null;continue}}if(j.length>2&&j[0]==="-"&&j[1]!=="-"){let Y=this._findOption(`-${j[1]}`);if(Y){if(Y.required||Y.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${Y.name()}`,j.slice(2));else this.emit(`option:${Y.name()}`),Q.unshift(`-${j.slice(2)}`);continue}}if(/^--[^=]+=/.test(j)){let Y=j.indexOf("="),H=this._findOption(j.slice(0,Y));if(H&&(H.required||H.optional)){this.emit(`option:${H.name()}`,j.slice(Y+1));continue}}if(W(j))q=K;if((this._enablePositionalOptions||this._passThroughOptions)&&U.length===0&&K.length===0){if(this._findCommand(j)){if(U.push(j),Q.length>0)K.push(...Q);break}else if(this._getHelpCommand()&&j===this._getHelpCommand().name()){if(U.push(j),Q.length>0)U.push(...Q);break}else if(this._defaultCommandName){if(K.push(j),Q.length>0)K.push(...Q);break}}if(this._passThroughOptions){if(q.push(j),Q.length>0)q.push(...Q);break}q.push(j)}return{operands:U,unknown:K}}opts(){if(this._storeOptionsAsProperties){let $={},U=this.options.length;for(let K=0;K<U;K++){let q=this.options[K].attributeName();$[q]=q===this._versionOptionName?this._version:this[q]}return $}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce(($,U)=>Object.assign($,U.opts()),{})}error($,U){if(this._outputConfiguration.outputError(`${$}
|
|
23
23
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
24
24
|
`);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
|
|
25
|
-
`),this.outputHelp({error:!0});let K=U||{},q=K.exitCode||1,Q=K.code||"commander.error";this._exit(q,Q,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in p.env){let U=$.attributeName();if(this.getOptionValue(U)===void 0||["default","config","env"].includes(this.getOptionValueSource(U)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,p.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new
|
|
26
|
-
`),this._exit(0,"commander.version",$)}),this}description($,U){if($===void 0&&U===void 0)return this._description;if(this._description=$,U)this._argsDescription=U;return this}summary($){if($===void 0)return this._summary;return this._summary=$,this}alias($){if($===void 0)return this._aliases[0];let U=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)U=this.commands[this.commands.length-1];if($===U._name)throw Error("Command alias can't be the same as its name");let K=this.parent?._findCommand($);if(K){let q=[K.name()].concat(K.aliases()).join("|");throw Error(`cannot add alias '${$}' to command '${this.name()}' as already have command '${q}'`)}return U._aliases.push($),this}aliases($){if($===void 0)return this._aliases;return $.forEach((U)=>this.alias(U)),this}usage($){if($===void 0){if(this._usage)return this._usage;let U=this.registeredArguments.map((K)=>{return
|
|
25
|
+
`),this.outputHelp({error:!0});let K=U||{},q=K.exitCode||1,Q=K.code||"commander.error";this._exit(q,Q,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in p.env){let U=$.attributeName();if(this.getOptionValue(U)===void 0||["default","config","env"].includes(this.getOptionValueSource(U)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,p.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new NM(this.options),U=(K)=>{return this.getOptionValue(K)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(K))};this.options.filter((K)=>K.implied!==void 0&&U(K.attributeName())&&$.valueFromOption(this.getOptionValue(K.attributeName()),K)).forEach((K)=>{Object.keys(K.implied).filter((q)=>!U(q)).forEach((q)=>{this.setOptionValueWithSource(q,K.implied[q],"implied")})})}missingArgument($){let U=`error: missing required argument '${$}'`;this.error(U,{code:"commander.missingArgument"})}optionMissingArgument($){let U=`error: option '${$.flags}' argument missing`;this.error(U,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue($){let U=`error: required option '${$.flags}' not specified`;this.error(U,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption($,U){let K=(W)=>{let G=W.attributeName(),j=this.getOptionValue(G),Y=this.options.find((X)=>X.negate&&G===X.attributeName()),H=this.options.find((X)=>!X.negate&&G===X.attributeName());if(Y&&(Y.presetArg===void 0&&j===!1||Y.presetArg!==void 0&&j===Y.presetArg))return Y;return H||W},q=(W)=>{let G=K(W),j=G.attributeName();if(this.getOptionValueSource(j)==="env")return`environment variable '${G.envVar}'`;return`option '${G.flags}'`},Q=`error: ${q($)} cannot be used with ${q(U)}`;this.error(Q,{code:"commander.conflictingOption"})}unknownOption($){if(this._allowUnknownOption)return;let U="";if($.startsWith("--")&&this._showSuggestionAfterError){let q=[],Q=this;do{let W=Q.createHelp().visibleOptions(Q).filter((G)=>G.long).map((G)=>G.long);q=q.concat(W),Q=Q.parent}while(Q&&!Q._enablePositionalOptions);U=cG($,q)}let K=`error: unknown option '${$}'${U}`;this.error(K,{code:"commander.unknownOption"})}_excessArguments($){if(this._allowExcessArguments)return;let U=this.registeredArguments.length,K=U===1?"":"s",Q=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${U} argument${K} but got ${$.length}.`;this.error(Q,{code:"commander.excessArguments"})}unknownCommand(){let $=this.args[0],U="";if(this._showSuggestionAfterError){let q=[];this.createHelp().visibleCommands(this).forEach((Q)=>{if(q.push(Q.name()),Q.alias())q.push(Q.alias())}),U=cG($,q)}let K=`error: unknown command '${$}'${U}`;this.error(K,{code:"commander.unknownCommand"})}version($,U,K){if($===void 0)return this._version;this._version=$,U=U||"-V, --version",K=K||"output the version number";let q=this.createOption(U,K);return this._versionOptionName=q.attributeName(),this._registerOption(q),this.on("option:"+q.name(),()=>{this._outputConfiguration.writeOut(`${$}
|
|
26
|
+
`),this._exit(0,"commander.version",$)}),this}description($,U){if($===void 0&&U===void 0)return this._description;if(this._description=$,U)this._argsDescription=U;return this}summary($){if($===void 0)return this._summary;return this._summary=$,this}alias($){if($===void 0)return this._aliases[0];let U=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)U=this.commands[this.commands.length-1];if($===U._name)throw Error("Command alias can't be the same as its name");let K=this.parent?._findCommand($);if(K){let q=[K.name()].concat(K.aliases()).join("|");throw Error(`cannot add alias '${$}' to command '${this.name()}' as already have command '${q}'`)}return U._aliases.push($),this}aliases($){if($===void 0)return this._aliases;return $.forEach((U)=>this.alias(U)),this}usage($){if($===void 0){if(this._usage)return this._usage;let U=this.registeredArguments.map((K)=>{return MM(K)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?U:[]).join(" ")}return this._usage=$,this}name($){if($===void 0)return this._name;return this._name=$,this}nameFromFilename($){return this._name=_1.basename($,_1.extname($)),this}executableDir($){if($===void 0)return this._executableDir;return this._executableDir=$,this}helpInformation($){let U=this.createHelp(),K=this._getOutputContext($);U.prepareContext({error:K.error,helpWidth:K.helpWidth,outputHasColors:K.hasColors});let q=U.formatHelp(this,U);if(K.hasColors)return q;return this._outputConfiguration.stripColor(q)}_getOutputContext($){$=$||{};let U=!!$.error,K,q,Q;if(U)K=(G)=>this._outputConfiguration.writeErr(G),q=this._outputConfiguration.getErrHasColors(),Q=this._outputConfiguration.getErrHelpWidth();else K=(G)=>this._outputConfiguration.writeOut(G),q=this._outputConfiguration.getOutHasColors(),Q=this._outputConfiguration.getOutHelpWidth();return{error:U,write:(G)=>{if(!q)G=this._outputConfiguration.stripColor(G);return K(G)},hasColors:q,helpWidth:Q}}outputHelp($){let U;if(typeof $==="function")U=$,$=void 0;let K=this._getOutputContext($),q={error:K.error,write:K.write,command:this};this._getCommandAndAncestors().reverse().forEach((W)=>W.emit("beforeAllHelp",q)),this.emit("beforeHelp",q);let Q=this.helpInformation({error:K.error});if(U){if(Q=U(Q),typeof Q!=="string"&&!Buffer.isBuffer(Q))throw Error("outputHelp callback must return a string or a Buffer")}if(K.write(Q),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",q),this._getCommandAndAncestors().forEach((W)=>W.emit("afterAllHelp",q))}helpOption($,U){if(typeof $==="boolean"){if($)this._helpOption=this._helpOption??void 0;else this._helpOption=null;return this}return $=$??"-h, --help",U=U??"display help for command",this._helpOption=this.createOption($,U),this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption($){return this._helpOption=$,this}help($){this.outputHelp($);let U=Number(p.exitCode??0);if(U===0&&$&&typeof $!=="function"&&$.error)U=1;this._exit(U,"commander.help","(outputHelp)")}addHelpText($,U){let K=["beforeAll","before","after","afterAll"];if(!K.includes($))throw Error(`Unexpected value for position to addHelpText.
|
|
27
27
|
Expecting one of '${K.join("', '")}'`);let q=`${$}Help`;return this.on(q,(Q)=>{let W;if(typeof U==="function")W=U({error:Q.error,command:Q.command});else W=U;if(W)Q.write(`${W}
|
|
28
|
-
`)}),this}_outputHelpIfRequested($){let U=this._getHelpOption();if(U&&$.find((q)=>U.is(q)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function uJ($){return $.map((U)=>{if(!U.startsWith("--inspect"))return U;let K,q="127.0.0.1",Q="9229",W;if((W=U.match(/^(--inspect(-brk)?)$/))!==null)K=W[1];else if((W=U.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(K=W[1],/^\d+$/.test(W[3]))Q=W[3];else q=W[3];else if((W=U.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)K=W[1],q=W[3],Q=W[4];if(K&&Q!=="0")return`${K}=${q}:${parseInt(Q)+1}`;return U})}function X3(){if(p.env.NO_COLOR||p.env.FORCE_COLOR==="0"||p.env.FORCE_COLOR==="false")return!1;if(p.env.FORCE_COLOR||p.env.CLICOLOR_FORCE!==void 0)return!0;return}HM.Command=Z3;HM.useColor=X3});var lJ=z1((MM)=>{var{Argument:mJ}=b0(),{Command:B3}=fJ(),{CommanderError:BM,InvalidArgumentError:hJ}=x6(),{Help:VM}=G3(),{Option:cJ}=j3();MM.program=new B3;MM.createCommand=($)=>new B3($);MM.createOption=($,U)=>new cJ($,U);MM.createArgument=($,U)=>new mJ($,U);MM.Command=B3;MM.Option=cJ;MM.Argument=mJ;MM.Help=VM;MM.CommanderError=BM;MM.InvalidArgumentError=hJ;MM.InvalidOptionArgumentError=hJ});var I1=z1((cz,D3)=>{var C0=process||{},tJ=C0.argv||[],S0=C0.env||{},TM=!(!!S0.NO_COLOR||tJ.includes("--no-color"))&&(!!S0.FORCE_COLOR||tJ.includes("--color")||C0.platform==="win32"||(C0.stdout||{}).isTTY&&S0.TERM!=="dumb"||!!S0.CI),SM=($,U,K=$)=>(q)=>{let Q=""+q,W=Q.indexOf(U,$.length);return~W?$+CM(Q,U,K,W)+U:$+Q+U},CM=($,U,K,q)=>{let Q="",W=0;do Q+=$.substring(W,q)+K,W=q+U.length,q=$.indexOf(U,W);while(~q);return Q+$.substring(W)},aJ=($=TM)=>{let U=$?SM:()=>String;return{isColorSupported:$,reset:U("\x1B[0m","\x1B[0m"),bold:U("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:U("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:U("\x1B[3m","\x1B[23m"),underline:U("\x1B[4m","\x1B[24m"),inverse:U("\x1B[7m","\x1B[27m"),hidden:U("\x1B[8m","\x1B[28m"),strikethrough:U("\x1B[9m","\x1B[29m"),black:U("\x1B[30m","\x1B[39m"),red:U("\x1B[31m","\x1B[39m"),green:U("\x1B[32m","\x1B[39m"),yellow:U("\x1B[33m","\x1B[39m"),blue:U("\x1B[34m","\x1B[39m"),magenta:U("\x1B[35m","\x1B[39m"),cyan:U("\x1B[36m","\x1B[39m"),white:U("\x1B[37m","\x1B[39m"),gray:U("\x1B[90m","\x1B[39m"),bgBlack:U("\x1B[40m","\x1B[49m"),bgRed:U("\x1B[41m","\x1B[49m"),bgGreen:U("\x1B[42m","\x1B[49m"),bgYellow:U("\x1B[43m","\x1B[49m"),bgBlue:U("\x1B[44m","\x1B[49m"),bgMagenta:U("\x1B[45m","\x1B[49m"),bgCyan:U("\x1B[46m","\x1B[49m"),bgWhite:U("\x1B[47m","\x1B[49m"),blackBright:U("\x1B[90m","\x1B[39m"),redBright:U("\x1B[91m","\x1B[39m"),greenBright:U("\x1B[92m","\x1B[39m"),yellowBright:U("\x1B[93m","\x1B[39m"),blueBright:U("\x1B[94m","\x1B[39m"),magentaBright:U("\x1B[95m","\x1B[39m"),cyanBright:U("\x1B[96m","\x1B[39m"),whiteBright:U("\x1B[97m","\x1B[39m"),bgBlackBright:U("\x1B[100m","\x1B[49m"),bgRedBright:U("\x1B[101m","\x1B[49m"),bgGreenBright:U("\x1B[102m","\x1B[49m"),bgYellowBright:U("\x1B[103m","\x1B[49m"),bgBlueBright:U("\x1B[104m","\x1B[49m"),bgMagentaBright:U("\x1B[105m","\x1B[49m"),bgCyanBright:U("\x1B[106m","\x1B[49m"),bgWhiteBright:U("\x1B[107m","\x1B[49m")}};D3.exports=aJ();D3.exports.createColors=aJ});function W3($){let U=$.length;while(U>0&&$[U-1]==="/")U-=1;return $.slice(0,U)}var rJ=N1(lJ(),1),{program:Az,createCommand:vz,createArgument:kz,createOption:Rz,CommanderError:zz,InvalidArgumentError:bz,InvalidOptionArgumentError:Oz,Command:iJ,Argument:Tz,Option:Sz,Help:Cz}=rJ.default;import{readFileSync as kM}from"node:fs";function G$($){return typeof $==="object"&&$!=null&&!Array.isArray($)}function Q$($){return typeof $==="object"&&$!=null?{...$}:void 0}function l($){return typeof $==="string"?$:void 0}function p1($){return typeof $==="number"?$:void 0}function A$($){if(!Array.isArray($))return[];return $.map((U)=>Q$(U)).filter((U)=>U!=null)}function w6(){return"0.4.0-rc.1"}var V3="/cli/compatibilidade",T0=null;function RM(){if(T0!=null)return T0;let $='[{"niva_min":"2.0.0","niva_max":null,"dist_tag":"niva-2.0"}]',U='{"min":"2.0.0","max":null}',K=null;if(typeof U==="string"&&typeof $==="string"){let q=JSON.parse(U),Q=JSON.parse($);K=dJ(q,Q)}else{let q=JSON.parse(zM()),Q=G$(q)?q.supported_niva:void 0,W=G$(q)?q.compat_table:void 0;K=dJ(Q,W)}if(K==null)throw Error("Invalid apps/cli/compat.json, fix the compat table");return T0=K,T0}function dJ($,U){if(!G$($)||!Array.isArray(U))return null;let K=l($.min);if(K==null)return null;let q=l($.max)??null,Q=[];for(let W of A$(U)){let J=l(W.niva_min),j=l(W.dist_tag);if(J==null||j==null)return null;Q.push({niva_min:J,niva_max:l(W.niva_max)??null,dist_tag:j})}return{supported_niva:{min:K,max:q},compat_table:Q}}function zM(){return kM(new URL("../../compat.json",import.meta.url),"utf-8")}function oJ($){let K=($.split("-")[0]?.split("+")[0]??"").split(".");if(K.length!==3)return null;let q=K.map((Q)=>Number.parseInt(Q,10));if(q.some((Q)=>!Number.isFinite(Q)||Q<0))return null;return[q[0],q[1],q[2]]}function nJ($,U){let K=oJ($),q=oJ(U);if(K===null||q===null)return 0;for(let Q=0;Q<3;Q++)if(K[Q]!==q[Q])return K[Q]-q[Q];return 0}function pJ($,U){for(let K of U.compat_table){if(nJ($,K.niva_min)<0)continue;if(K.niva_max!=null&&nJ($,K.niva_max)>0)continue;return K.dist_tag}return null}var bM=null;function OM(){return bM}function M3(){let $=RM(),U=OM();if(U!=null)return pJ(U,$);return pJ($.supported_niva.min,$)}var K$=N1(I1(),1),EM=new Set(["json","table","plain"]);function yM($){return EM.has($)}function gM(){return process.stdout.isTTY===!0&&process.env.NO_COLOR==null}function t1($){if($.output!=null)return yM($.output)?$.output:"table";if($.json===!0)return"json";return gM()?"table":"json"}function uM($,U){return U in $}function O($,U){if(U==null)return $;let K={};for(let q of U)if(uM($,q))K[q]=$[q];return K}function P($){console.log(JSON.stringify($,null,2))}var fM=/\x1B\[[0-9;]*m/g;function mM($){return $.replaceAll(fM,"")}var hM=[[128512,128591],[127744,128511],[128640,128767],[129280,129535],[129536,129791],[9728,10175],[127456,127487]],cM=[[65024,65039],[8205,8205]];function sJ($,U){for(let[K,q]of U)if($>=K&&$<=q)return!0;return!1}function lM($){if(sJ($,hM))return 2;if(sJ($,cM))return 0;return 1}function UG($){let U=mM($),K=0;for(let q of U)K+=lM(q.codePointAt(0));return K}function P3($,U){let K=UG($);if(K>=U)return $;return $+" ".repeat(U-K)}function eJ($){if($==null)return"";return typeof $==="string"?$:JSON.stringify($)}function y($,U){if(U.length===0){console.log(K$.default.dim("No results."));return}let K=$.map((Q)=>{let W=Q.length,J=Math.max(...U.map((j)=>UG(eJ(j[Q]))));return Math.max(W,J)}),q=$.map((Q,W)=>Q.padEnd(K[W])).join(" ");console.log(K$.default.bold(q)),console.log(K$.default.dim(K.map((Q)=>"─".repeat(Q)).join("──")));for(let Q of U){let W=$.map((J,j)=>P3(eJ(Q[J]),K[j])).join(" ");console.log(W)}}function T($){console.log(K$.default.green($))}function x($){console.error(K$.default.red($))}function z($){console.log(K$.default.dim($))}function R4($){console.error(K$.default.dim($))}function $1($){console.error(K$.default.yellow($))}function L($){let{output:U,fields:K}=$,q=t1({json:$.json===!0,output:typeof U==="string"?U:void 0}),Q=typeof K==="string"?K.split(",").map((W)=>W.trim()):void 0;return{format:q,fields:Q}}function H$($){if($.page==null)return;if($.total_pages==null||$.total==null){z(`Page ${$.page}`);return}z(`Page ${$.page}/${$.total_pages} (${$.total} total)`)}function f$($){if($==null)return"—";let U=Math.ceil($/1000);if(U===0)return"0s";let K=Math.floor(U/3600),q=Math.floor(U%3600/60),Q=U%60;if(K>0)return q>0?`${K}h ${q}m`:`${K}h`;if(q>0)return Q>0?`${q}m ${Q}s`:`${q}m`;return`${Q}s`}function N3($){if($==null)return"—";switch($){case"answered":return K$.default.green(`✓ ${$}`);case"missed":return K$.default.red(`✗ ${$}`);case"busy":return K$.default.yellow(`● ${$}`);case"failed":return K$.default.dim(`✗ ${$}`);default:return $}}function L3($,U){if($==null)return"—";let K=U!=null&&U>0?"+":"",q=U!=null?` (${K}${U})`:"";switch($){case"positive":return K$.default.green(`\uD83D\uDE0A ${$}${q}`);case"negative":return K$.default.red(`\uD83D\uDE1E ${$}${q}`);case"neutral":return K$.default.yellow(`\uD83D\uDE10 ${$}${q}`);case"mixed":return K$.default.blue(`\uD83D\uDD00 ${$}${q}`);default:return`${$}${q}`}}var rM={voicemail:"Voicemail",announcement:"Carrier announcement",ivr:"IVR / switchboard",screening:"Call screening",human:"Human",unknown:"Unclassified"};function E0($){return $==null?"—":rM[$]}function a1($,U,K=20){let q=U>0?$/U:0,Q=Math.round(q*K),W=K-Q;return"█".repeat(Q)+"░".repeat(W)}function U1($,U,K,q=20){let Q=a1(U,K,q),W=K>0?Math.round(U/K*100):0;console.log(` ${P3($,14)} ${Q} ${U} (${W}%)`)}function o($){for(let U=0;U<$.length;U++){let K=$[U],q=Math.max(...K.rows.map((W)=>W.label.length)),Q=Math.max(q+4+30,K.title.length+4);console.log(K$.default.dim(`┌─ ${K.title} ${"─".repeat(Math.max(0,Q-K.title.length-4))}`));for(let W of K.rows){let J=W.value==null?"—":String(W.value);console.log(`${K$.default.dim("│")} ${P3(W.label,q)} ${J}`)}if(console.log(K$.default.dim(`└${"─".repeat(Q)}`)),U<$.length-1)console.log("")}}function _3($){for(let U=0;U<$.length;U++){let K=$[U],q=U===$.length-1,Q=q?"└──":"├──",W=K.detail!=null?K$.default.dim(` (${K.detail})`):"";if(console.log(` ${Q} ${K.label}${W}`),K.children!=null){let J=q?" ":"│ ";for(let j of K.children)console.log(K$.default.dim(` ${J}${j}`))}}}function iM($){let U=$.toLowerCase();return U==="caller"||U==="speaker_l"||U==="speaker_01"}function QG($){if($.length===0){z(" No transcript available.");return}for(let U of $){let K=Math.floor(U.initial_time/60),q=Math.floor(U.initial_time%60),Q=`${String(K).padStart(2,"0")}:${String(q).padStart(2,"0")}`,W=iM(U.speaker)?K$.default.blue("Caller"):K$.default.green("Agent "),J=K$.default.dim(`[${Q}]`);console.log(` ${J} ${W} ${K$.default.dim(">")} ${U.text}`)}}function $G($,U){if(/^\d{4}-\d{2}-\d{2}$/.test($))return U?`${$}T23:59:59.999Z`:`${$}T00:00:00.000Z`;return $}function G1($,U=0){let K=new Date,q=$.from!=null?$G($.from,!1):new Date(K.getFullYear(),K.getMonth(),K.getDate()-U).toISOString(),Q=$.to!=null?$G($.to,!0):K.toISOString();return{date_from:q,date_to:Q}}function j1($){let U=typeof $==="string"?new Date($):$,K=String(U.getDate()).padStart(2,"0"),q=String(U.getMonth()+1).padStart(2,"0"),Q=String(U.getHours()).padStart(2,"0"),W=String(U.getMinutes()).padStart(2,"0");return`${K}/${q} ${Q}:${W}`}var w={SUCCESS:0,GENERAL_ERROR:1,USAGE_ERROR:2,NOT_FOUND:3,PERMISSION_DENIED:4,CONFLICT:5},I3="table",dM="";function oM($){if($.endsWith("_NOT_FOUND")||$==="NOT_FOUND"||$==="AUDIO_FILE_CONTENT_MISSING")return w.NOT_FOUND;if($==="UNAUTHORIZED"||$==="FORBIDDEN"||$==="ADMIN_REQUIRED"||$==="API_KEY_INVALID"||$==="INSUFFICIENT_PERMISSIONS"||$==="INSUFFICIENT_SCOPE")return w.PERMISSION_DENIED;if($==="UNPROCESSABLE_CONTENT"||$==="BAD_REQUEST")return w.USAGE_ERROR;if($==="AUDIO_FILE_TOO_LARGE"||$==="AUDIO_FILE_INVALID_FORMAT"||$==="AUDIO_FILE_NOT_TTS"||$==="TTS_VOICE_UNAVAILABLE")return w.USAGE_ERROR;if($==="CONFLICT"||$.startsWith("DUPLICATE_")||$.endsWith("_IN_USE"))return w.CONFLICT;if($==="MODULE_DISABLED")return w.PERMISSION_DENIED;return w.GENERAL_ERROR}function nM($){return $==="INTERNAL_SERVER_ERROR"||$==="SERVICE_UNAVAILABLE"}var pM={LOGS_UNAVAILABLE:"journal gateway unreachable — log reading is available only on the appliance (NIVA-125+, journald + gateway).",LOGS_INVALID_FILTER:"invalid log filter — e.g. --follow is not supported for postgres, or a --since/--until value is malformed.",FORBIDDEN:"your API key's role lacks permission for this action (system logs require a platform-admin key).",AUDIO_FILE_INVALID_FORMAT:"accepted audio extensions: wav, mp3, ogg, flac, m4a.",AUDIO_FILE_TOO_LARGE:"the audio library accepts files up to 10 MB.",AUDIO_FILE_IN_USE:"remove the audio from the plans that reference it before deleting it.",AUDIO_FILE_NOT_TTS:"only TTS-generated audio can be regenerated; re-upload the file instead.",AUDIO_FILE_CONTENT_MISSING:"the record exists but its bytes are gone from storage — re-upload the audio.",TTS_VOICE_UNAVAILABLE:"list the voices available for this organization with: niva tts voices"};function tM($,U){let K=$.message.toLowerCase();if(K.includes("econnrefused")||K.includes("fetch failed")||K.includes("unable to connect"))return`Could not connect to ${U||"server"}
|
|
28
|
+
`)}),this}_outputHelpIfRequested($){let U=this._getHelpOption();if(U&&$.find((q)=>U.is(q)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function lG($){return $.map((U)=>{if(!U.startsWith("--inspect"))return U;let K,q="127.0.0.1",Q="9229",W;if((W=U.match(/^(--inspect(-brk)?)$/))!==null)K=W[1];else if((W=U.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(K=W[1],/^\d+$/.test(W[3]))Q=W[3];else q=W[3];else if((W=U.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)K=W[1],q=W[3],Q=W[4];if(K&&Q!=="0")return`${K}=${q}:${parseInt(Q)+1}`;return U})}function B8(){if(p.env.NO_COLOR||p.env.FORCE_COLOR==="0"||p.env.FORCE_COLOR==="false")return!1;if(p.env.FORCE_COLOR||p.env.CLICOLOR_FORCE!==void 0)return!0;return}LM.Command=V8;LM.useColor=B8});var nG=R1((wM)=>{var{Argument:iG}=O0(),{Command:M8}=rG(),{CommanderError:FM,InvalidArgumentError:dG}=w6(),{Help:xM}=Y8(),{Option:oG}=H8();wM.program=new M8;wM.createCommand=($)=>new M8($);wM.createOption=($,U)=>new oG($,U);wM.createArgument=($,U)=>new iG($,U);wM.Command=M8;wM.Option=oG;wM.Argument=iG;wM.Help=xM;wM.CommanderError=FM;wM.InvalidArgumentError=dG;wM.InvalidOptionArgumentError=dG});var I1=R1((qb,N8)=>{var E0=process||{},UJ=E0.argv||[],C0=E0.env||{},hM=!(!!C0.NO_COLOR||UJ.includes("--no-color"))&&(!!C0.FORCE_COLOR||UJ.includes("--color")||E0.platform==="win32"||(E0.stdout||{}).isTTY&&C0.TERM!=="dumb"||!!C0.CI),cM=($,U,K=$)=>(q)=>{let Q=""+q,W=Q.indexOf(U,$.length);return~W?$+lM(Q,U,K,W)+U:$+Q+U},lM=($,U,K,q)=>{let Q="",W=0;do Q+=$.substring(W,q)+K,W=q+U.length,q=$.indexOf(U,W);while(~q);return Q+$.substring(W)},QJ=($=hM)=>{let U=$?cM:()=>String;return{isColorSupported:$,reset:U("\x1B[0m","\x1B[0m"),bold:U("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:U("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:U("\x1B[3m","\x1B[23m"),underline:U("\x1B[4m","\x1B[24m"),inverse:U("\x1B[7m","\x1B[27m"),hidden:U("\x1B[8m","\x1B[28m"),strikethrough:U("\x1B[9m","\x1B[29m"),black:U("\x1B[30m","\x1B[39m"),red:U("\x1B[31m","\x1B[39m"),green:U("\x1B[32m","\x1B[39m"),yellow:U("\x1B[33m","\x1B[39m"),blue:U("\x1B[34m","\x1B[39m"),magenta:U("\x1B[35m","\x1B[39m"),cyan:U("\x1B[36m","\x1B[39m"),white:U("\x1B[37m","\x1B[39m"),gray:U("\x1B[90m","\x1B[39m"),bgBlack:U("\x1B[40m","\x1B[49m"),bgRed:U("\x1B[41m","\x1B[49m"),bgGreen:U("\x1B[42m","\x1B[49m"),bgYellow:U("\x1B[43m","\x1B[49m"),bgBlue:U("\x1B[44m","\x1B[49m"),bgMagenta:U("\x1B[45m","\x1B[49m"),bgCyan:U("\x1B[46m","\x1B[49m"),bgWhite:U("\x1B[47m","\x1B[49m"),blackBright:U("\x1B[90m","\x1B[39m"),redBright:U("\x1B[91m","\x1B[39m"),greenBright:U("\x1B[92m","\x1B[39m"),yellowBright:U("\x1B[93m","\x1B[39m"),blueBright:U("\x1B[94m","\x1B[39m"),magentaBright:U("\x1B[95m","\x1B[39m"),cyanBright:U("\x1B[96m","\x1B[39m"),whiteBright:U("\x1B[97m","\x1B[39m"),bgBlackBright:U("\x1B[100m","\x1B[49m"),bgRedBright:U("\x1B[101m","\x1B[49m"),bgGreenBright:U("\x1B[102m","\x1B[49m"),bgYellowBright:U("\x1B[103m","\x1B[49m"),bgBlueBright:U("\x1B[104m","\x1B[49m"),bgMagentaBright:U("\x1B[105m","\x1B[49m"),bgCyanBright:U("\x1B[106m","\x1B[49m"),bgWhiteBright:U("\x1B[107m","\x1B[49m")}};N8.exports=QJ();N8.exports.createColors=QJ});function J8($){let U=$.length;while(U>0&&$[U-1]==="/")U-=1;return $.slice(0,U)}var pG=N1(nG(),1),{program:hR,createCommand:cR,createArgument:lR,createOption:rR,CommanderError:iR,InvalidArgumentError:dR,InvalidOptionArgumentError:oR,Command:tG,Argument:nR,Option:pR,Help:tR}=pG.default;import{readFileSync as yM}from"node:fs";function Q$($){return typeof $==="object"&&$!=null&&!Array.isArray($)}function K$($){return typeof $==="object"&&$!=null?{...$}:void 0}function l($){return typeof $==="string"?$:void 0}function p1($){return typeof $==="number"?$:void 0}function A$($){if(!Array.isArray($))return[];return $.map((U)=>K$(U)).filter((U)=>U!=null)}function A6(){return"0.4.0"}var D8="/cli/compatibilidade",S0=null;function gM(){if(S0!=null)return S0;let $='[{"niva_min":"2.0.0","niva_max":null,"dist_tag":"niva-2.0"}]',U='{"min":"2.0.0","max":null}',K=null;if(typeof U==="string"&&typeof $==="string"){let q=JSON.parse(U),Q=JSON.parse($);K=aG(q,Q)}else{let q=JSON.parse(uM()),Q=Q$(q)?q.supported_niva:void 0,W=Q$(q)?q.compat_table:void 0;K=aG(Q,W)}if(K==null)throw Error("Invalid apps/cli/compat.json, fix the compat table");return S0=K,S0}function aG($,U){if(!Q$($)||!Array.isArray(U))return null;let K=l($.min);if(K==null)return null;let q=l($.max)??null,Q=[];for(let W of A$(U)){let G=l(W.niva_min),j=l(W.dist_tag);if(G==null||j==null)return null;Q.push({niva_min:G,niva_max:l(W.niva_max)??null,dist_tag:j})}return{supported_niva:{min:K,max:q},compat_table:Q}}function uM(){return yM(new URL("../../compat.json",import.meta.url),"utf-8")}function sG($){let K=($.split("-")[0]?.split("+")[0]??"").split(".");if(K.length!==3)return null;let q=K.map((Q)=>Number.parseInt(Q,10));if(q.some((Q)=>!Number.isFinite(Q)||Q<0))return null;return[q[0],q[1],q[2]]}function eG($,U){let K=sG($),q=sG(U);if(K===null||q===null)return 0;for(let Q=0;Q<3;Q++)if(K[Q]!==q[Q])return K[Q]-q[Q];return 0}function $J($,U){for(let K of U.compat_table){if(eG($,K.niva_min)<0)continue;if(K.niva_max!=null&&eG($,K.niva_max)>0)continue;return K.dist_tag}return null}var fM=null;function mM(){return fM}function P8(){let $=gM(),U=mM();if(U!=null)return $J(U,$);return $J($.supported_niva.min,$)}var q$=N1(I1(),1),rM=new Set(["json","table","plain"]);function iM($){return rM.has($)}function dM(){return process.stdout.isTTY===!0&&process.env.NO_COLOR==null}function t1($){if($.output!=null)return iM($.output)?$.output:"table";if($.json===!0)return"json";return dM()?"table":"json"}function oM($,U){return U in $}function O($,U){if(U==null)return $;let K={};for(let q of U)if(oM($,q))K[q]=$[q];return K}function P($){console.log(JSON.stringify($,null,2))}var nM=/\x1B\[[0-9;]*m/g;function pM($){return $.replaceAll(nM,"")}var tM=[[128512,128591],[127744,128511],[128640,128767],[129280,129535],[129536,129791],[9728,10175],[127456,127487]],aM=[[65024,65039],[8205,8205]];function KJ($,U){for(let[K,q]of U)if($>=K&&$<=q)return!0;return!1}function sM($){if(KJ($,tM))return 2;if(KJ($,aM))return 0;return 1}function GJ($){let U=pM($),K=0;for(let q of U)K+=sM(q.codePointAt(0));return K}function L8($,U){let K=GJ($);if(K>=U)return $;return $+" ".repeat(U-K)}function qJ($){if($==null)return"";return typeof $==="string"?$:JSON.stringify($)}function y($,U){if(U.length===0){console.log(q$.default.dim("No results."));return}let K=$.map((Q)=>{let W=Q.length,G=Math.max(...U.map((j)=>GJ(qJ(j[Q]))));return Math.max(W,G)}),q=$.map((Q,W)=>Q.padEnd(K[W])).join(" ");console.log(q$.default.bold(q)),console.log(q$.default.dim(K.map((Q)=>"─".repeat(Q)).join("──")));for(let Q of U){let W=$.map((G,j)=>L8(qJ(Q[G]),K[j])).join(" ");console.log(W)}}function T($){console.log(q$.default.green($))}function x($){console.error(q$.default.red($))}function R($){console.log(q$.default.dim($))}function z4($){console.error(q$.default.dim($))}function $1($){console.error(q$.default.yellow($))}function L($){let{output:U,fields:K}=$,q=t1({json:$.json===!0,output:typeof U==="string"?U:void 0}),Q=typeof K==="string"?K.split(",").map((W)=>W.trim()):void 0;return{format:q,fields:Q}}function Z$($){if($.page==null)return;if($.total_pages==null||$.total==null){R(`Page ${$.page}`);return}R(`Page ${$.page}/${$.total_pages} (${$.total} total)`)}function f$($){if($==null)return"—";let U=Math.ceil($/1000);if(U===0)return"0s";let K=Math.floor(U/3600),q=Math.floor(U%3600/60),Q=U%60;if(K>0)return q>0?`${K}h ${q}m`:`${K}h`;if(q>0)return Q>0?`${q}m ${Q}s`:`${q}m`;return`${Q}s`}function _8($){if($==null)return"—";switch($){case"answered":return q$.default.green(`✓ ${$}`);case"missed":return q$.default.red(`✗ ${$}`);case"busy":return q$.default.yellow(`● ${$}`);case"failed":return q$.default.dim(`✗ ${$}`);default:return $}}function I8($,U){if($==null)return"—";let K=U!=null&&U>0?"+":"",q=U!=null?` (${K}${U})`:"";switch($){case"positive":return q$.default.green(`\uD83D\uDE0A ${$}${q}`);case"negative":return q$.default.red(`\uD83D\uDE1E ${$}${q}`);case"neutral":return q$.default.yellow(`\uD83D\uDE10 ${$}${q}`);case"mixed":return q$.default.blue(`\uD83D\uDD00 ${$}${q}`);default:return`${$}${q}`}}var eM={voicemail:"Voicemail",announcement:"Carrier announcement",ivr:"IVR / switchboard",screening:"Call screening",human:"Human",unknown:"Unclassified"};function y0($){return $==null?"—":eM[$]}function a1($,U,K=20){let q=U>0?$/U:0,Q=Math.round(q*K),W=K-Q;return"█".repeat(Q)+"░".repeat(W)}function U1($,U,K,q=20){let Q=a1(U,K,q),W=K>0?Math.round(U/K*100):0;console.log(` ${L8($,14)} ${Q} ${U} (${W}%)`)}function o($){for(let U=0;U<$.length;U++){let K=$[U],q=Math.max(...K.rows.map((W)=>W.label.length)),Q=Math.max(q+4+30,K.title.length+4);console.log(q$.default.dim(`┌─ ${K.title} ${"─".repeat(Math.max(0,Q-K.title.length-4))}`));for(let W of K.rows){let G=W.value==null?"—":String(W.value);console.log(`${q$.default.dim("│")} ${L8(W.label,q)} ${G}`)}if(console.log(q$.default.dim(`└${"─".repeat(Q)}`)),U<$.length-1)console.log("")}}function F8($){for(let U=0;U<$.length;U++){let K=$[U],q=U===$.length-1,Q=q?"└──":"├──",W=K.detail!=null?q$.default.dim(` (${K.detail})`):"";if(console.log(` ${Q} ${K.label}${W}`),K.children!=null){let G=q?" ":"│ ";for(let j of K.children)console.log(q$.default.dim(` ${G}${j}`))}}}function $D($){let U=$.toLowerCase();return U==="caller"||U==="speaker_l"||U==="speaker_01"}function JJ($){if($.length===0){R(" No transcript available.");return}for(let U of $){let K=Math.floor(U.initial_time/60),q=Math.floor(U.initial_time%60),Q=`${String(K).padStart(2,"0")}:${String(q).padStart(2,"0")}`,W=$D(U.speaker)?q$.default.blue("Caller"):q$.default.green("Agent "),G=q$.default.dim(`[${Q}]`);console.log(` ${G} ${W} ${q$.default.dim(">")} ${U.text}`)}}function WJ($,U){if(/^\d{4}-\d{2}-\d{2}$/.test($))return U?`${$}T23:59:59.999Z`:`${$}T00:00:00.000Z`;return $}function J1($,U=0){let K=new Date,q=$.from!=null?WJ($.from,!1):new Date(K.getFullYear(),K.getMonth(),K.getDate()-U).toISOString(),Q=$.to!=null?WJ($.to,!0):K.toISOString();return{date_from:q,date_to:Q}}function j1($){let U=typeof $==="string"?new Date($):$,K=String(U.getDate()).padStart(2,"0"),q=String(U.getMonth()+1).padStart(2,"0"),Q=String(U.getHours()).padStart(2,"0"),W=String(U.getMinutes()).padStart(2,"0");return`${K}/${q} ${Q}:${W}`}var w={SUCCESS:0,GENERAL_ERROR:1,USAGE_ERROR:2,NOT_FOUND:3,PERMISSION_DENIED:4,CONFLICT:5},x8="table",UD="";function QD($){if($.endsWith("_NOT_FOUND")||$==="NOT_FOUND"||$==="AUDIO_FILE_CONTENT_MISSING")return w.NOT_FOUND;if($==="UNAUTHORIZED"||$==="FORBIDDEN"||$==="ADMIN_REQUIRED"||$==="API_KEY_INVALID"||$==="INSUFFICIENT_PERMISSIONS"||$==="INSUFFICIENT_SCOPE")return w.PERMISSION_DENIED;if($==="UNPROCESSABLE_CONTENT"||$==="BAD_REQUEST")return w.USAGE_ERROR;if($==="AUDIO_FILE_TOO_LARGE"||$==="AUDIO_FILE_INVALID_FORMAT"||$==="AUDIO_FILE_NOT_TTS"||$==="TTS_VOICE_UNAVAILABLE")return w.USAGE_ERROR;if($==="CONFLICT"||$.startsWith("DUPLICATE_")||$.endsWith("_IN_USE"))return w.CONFLICT;if($==="MODULE_DISABLED")return w.PERMISSION_DENIED;return w.GENERAL_ERROR}function KD($){return $==="INTERNAL_SERVER_ERROR"||$==="SERVICE_UNAVAILABLE"}var qD={LOGS_UNAVAILABLE:"journal gateway unreachable — log reading is available only on the appliance (NIVA-125+, journald + gateway).",LOGS_INVALID_FILTER:"invalid log filter — e.g. --follow is not supported for postgres, or a --since/--until value is malformed.",FORBIDDEN:"your API key's role lacks permission for this action (system logs require a platform-admin key).",AUDIO_FILE_INVALID_FORMAT:"accepted audio extensions: wav, mp3, ogg, flac, m4a.",AUDIO_FILE_TOO_LARGE:"the audio library accepts files up to 10 MB.",AUDIO_FILE_IN_USE:"remove the audio from the plans that reference it before deleting it.",AUDIO_FILE_NOT_TTS:"only TTS-generated audio can be regenerated; re-upload the file instead.",AUDIO_FILE_CONTENT_MISSING:"the record exists but its bytes are gone from storage — re-upload the audio.",TTS_VOICE_UNAVAILABLE:"list the voices available for this organization with: niva tts voices"};function WD($,U){let K=$.message.toLowerCase();if(K.includes("econnrefused")||K.includes("fetch failed")||K.includes("unable to connect"))return`Could not connect to ${U||"server"}
|
|
29
29
|
Is the server running? Check with: niva fs status
|
|
30
30
|
Current URL: ${U||"(not set)"} (change with: niva config set url <url>)`;if(K.includes("enotfound")||K.includes("getaddrinfo"))return`Could not resolve hostname in ${U||"(not set)"}
|
|
31
|
-
Check the URL: niva config set url <url>`;return`Connection error: ${$.message}`}function aM($){let U=Q$($);if(U==null)return` • ${String($)}`;let K=U.path,q=Array.isArray(K)?K.join("."):"",Q=U.messageKey??U.code??"invalid",W;if(typeof U.message==="string")W=U.message;else if(typeof Q==="string")W=Q;else W=JSON.stringify(Q);return` ✗ ${q?`${q}: `:""}${W}`}function b1($){return $ instanceof Error&&"defined"in $&&"code"in $}function s1($){let U=String(Q$($)?.code);if(U==="NOT_FOUND"&&Q$($)?.defined===!1)return sM();return{code:U,message:$.message,data:Q$(Q$($)?.data),hint:pM[U],exitCode:oM(U),retryable:nM(U)}}function sM(){let $=M3();return{code:"PROCEDURE_NOT_IMPLEMENTED",message:"This NIVA server does not have this command: it is newer than the deployment.",data:void 0,hint:`${$==null?`Check available compatibility at ${V3}`:`Run: npx @sippulse/niva@${$} <command>`} (the server's NIVA version does not offer this procedure).`,exitCode:w.USAGE_ERROR,retryable:!1}}function e1($){x(`Error: ${$.code} — ${$.message}`);let U=$.data?.issues;if(Array.isArray(U))for(let K of U)x(aM(K));if($.hint!=null)z(` ${$.hint}`)}function eM($){if(I3==="json")P({error:$.code,message:$.message,data:$.data,hint:$.hint,retryable:$.retryable});else e1($);process.exit($.exitCode)}function F3($){return $ instanceof Error?tM($,dM):String($)}function Q1($){if(b1($))eM(s1($));let U=F3($);if(I3==="json")P({error:"CONNECTION_ERROR",message:$ instanceof Error?$.message:String($),retryable:!0});else x(U);process.exit(w.GENERAL_ERROR)}function z4($){if(b1($))Q1($);let U=$ instanceof Error?$.message:String($);if(I3==="json")P({error:"STREAM_ERROR",message:U,retryable:!0});else x(`Stream error: ${U}`);process.exit(w.GENERAL_ERROR)}async function N($){try{return await $}catch(U){Q1(U)}}function F1($="Not yet implemented."){z($),process.exit(w.USAGE_ERROR)}function KG($,U){$.command("ai").description("AI module resources").command("agents").description("List AI agents available for voice interactions").action(async()=>{let{format:q,fields:Q}=L($.opts()),W=await N(U().ai.listAgents());if(q==="json"){let J=Q?W.map((j)=>O(j,Q)):W;P(J);return}y(["ID","Name","Language","SIP Inbound","Description"],W.map((J)=>({ID:J.id,Name:J.name,Language:J.language,"SIP Inbound":J.sip_inbound_enabled?"enabled":"disabled",Description:J.description??"—"})))})}var PG=N1(I1(),1);var qG=/^(?:[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 $D($){return typeof $==="string"&&qG.test($)}var WG=$D;var N$=[];for(let $=0;$<256;++$)N$.push(($+256).toString(16).slice(1));function x3($,U=0){return(N$[$[U+0]]+N$[$[U+1]]+N$[$[U+2]]+N$[$[U+3]]+"-"+N$[$[U+4]]+N$[$[U+5]]+"-"+N$[$[U+6]]+N$[$[U+7]]+"-"+N$[$[U+8]]+N$[$[U+9]]+"-"+N$[$[U+10]]+N$[$[U+11]]+N$[$[U+12]]+N$[$[U+13]]+N$[$[U+14]]+N$[$[U+15]]).toLowerCase()}function UD($,U=0){let K=x3($,U);if(!WG(K))throw TypeError("Stringified UUID is invalid");return K}var y0=UD;var QD=new Uint8Array(16);function g0(){return crypto.getRandomValues(QD)}var w3={};function KD($,U,K){let q;if($)q=JG($.random??$.rng?.()??g0(),$.msecs,$.seq,U,K);else{let Q=Date.now(),W=g0();qD(w3,Q,W),q=JG(W,w3.msecs,w3.seq,U,K)}return U??x3(q)}function qD($,U,K){if($.msecs??=-1/0,$.seq??=0,U>$.msecs)$.seq=K[6]<<23|K[7]<<16|K[8]<<8|K[9],$.msecs=U;else if($.seq=$.seq+1|0,$.seq===0)$.msecs++;return $}function JG($,U,K,q,Q=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!q)q=new Uint8Array(16),Q=0;else if(Q<0||Q+16>q.length)throw RangeError(`UUID byte range ${Q}:${Q+15} is out of buffer bounds`);return U??=Date.now(),K??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],q[Q++]=U/1099511627776&255,q[Q++]=U/4294967296&255,q[Q++]=U/16777216&255,q[Q++]=U/65536&255,q[Q++]=U/256&255,q[Q++]=U&255,q[Q++]=112|K>>>28&15,q[Q++]=K>>>20&255,q[Q++]=128|K>>>14&63,q[Q++]=K>>>6&255,q[Q++]=K<<2&255|$[10]&3,q[Q++]=$[11],q[Q++]=$[12],q[Q++]=$[13],q[Q++]=$[14],q[Q++]=$[15],q}var A3=KD;function WD($){let U,K=new Uint8Array(16);return K[0]=(U=parseInt($.slice(0,8),16))>>>24,K[1]=U>>>16&255,K[2]=U>>>8&255,K[3]=U&255,K[4]=(U=parseInt($.slice(9,13),16))>>>8,K[5]=U&255,K[6]=(U=parseInt($.slice(14,18),16))>>>8,K[7]=U&255,K[8]=(U=parseInt($.slice(19,23),16))>>>8,K[9]=U&255,K[10]=(U=parseInt($.slice(24,36),16))/1099511627776&255,K[11]=U/4294967296&255,K[12]=U>>>24&255,K[13]=U>>>16&255,K[14]=U>>>8&255,K[15]=U&255,K}var q$="0123456789abcdefghjkmnpqrstvwxyz",g=new Uint8Array([255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,10,11,12,13,14,15,16,17,255,18,19,255,20,21,255,22,23,24,25,26,255,27,28,29,30,31,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255]);function v3($){let U=Array(26).fill("");if($.length!==16)throw Error(`Invalid length. Expected 16 bytes, got ${$.length}. Input: ${$}`);return U[0]=q$[($[0]&224)>>5],U[1]=q$[$[0]&31],U[2]=q$[($[1]&248)>>3],U[3]=q$[($[1]&7)<<2|($[2]&192)>>6],U[4]=q$[($[2]&62)>>1],U[5]=q$[($[2]&1)<<4|($[3]&240)>>4],U[6]=q$[($[3]&15)<<1|($[4]&128)>>7],U[7]=q$[($[4]&124)>>2],U[8]=q$[($[4]&3)<<3|($[5]&224)>>5],U[9]=q$[$[5]&31],U[10]=q$[($[6]&248)>>3],U[11]=q$[($[6]&7)<<2|($[7]&192)>>6],U[12]=q$[($[7]&62)>>1],U[13]=q$[($[7]&1)<<4|($[8]&240)>>4],U[14]=q$[($[8]&15)<<1|($[9]&128)>>7],U[15]=q$[($[9]&124)>>2],U[16]=q$[($[9]&3)<<3|($[10]&224)>>5],U[17]=q$[$[10]&31],U[18]=q$[($[11]&248)>>3],U[19]=q$[($[11]&7)<<2|($[12]&192)>>6],U[20]=q$[($[12]&62)>>1],U[21]=q$[($[12]&1)<<4|($[13]&240)>>4],U[22]=q$[($[13]&15)<<1|($[14]&128)>>7],U[23]=q$[($[14]&124)>>2],U[24]=q$[($[14]&3)<<3|($[15]&224)>>5],U[25]=q$[$[15]&31],U.join("")}function YG($){if($.length!==26)throw Error(`Invalid length. Expected 26 bytes, got ${$.length}. Input: ${$}`);let K=new TextEncoder().encode($);if(g[K[0]]===255||g[K[1]]===255||g[K[2]]===255||g[K[3]]===255||g[K[4]]===255||g[K[5]]===255||g[K[6]]===255||g[K[7]]===255||g[K[8]]===255||g[K[9]]===255||g[K[10]]===255||g[K[11]]===255||g[K[12]]===255||g[K[13]]===255||g[K[14]]===255||g[K[15]]===255||g[K[16]]===255||g[K[17]]===255||g[K[18]]===255||g[K[19]]===255||g[K[20]]===255||g[K[21]]===255||g[K[22]]===255||g[K[23]]===255||g[K[24]]===255||g[K[25]]===255)throw Error("Invalid base32 character");let q=new Uint8Array(16);return q[0]=g[K[0]]<<5|g[K[1]],q[1]=g[K[2]]<<3|g[K[3]]>>2,q[2]=(g[K[3]]&3)<<6|g[K[4]]<<1|g[K[5]]>>4,q[3]=(g[K[5]]&15)<<4|g[K[6]]>>1,q[4]=(g[K[6]]&1)<<7|g[K[7]]<<2|g[K[8]]>>3,q[5]=(g[K[8]]&7)<<5|g[K[9]],q[6]=g[K[10]]<<3|g[K[11]]>>2,q[7]=(g[K[11]]&3)<<6|g[K[12]]<<1|g[K[13]]>>4,q[8]=(g[K[13]]&15)<<4|g[K[14]]>>1,q[9]=(g[K[14]]&1)<<7|g[K[15]]<<2|g[K[16]]>>3,q[10]=(g[K[16]]&7)<<5|g[K[17]],q[11]=g[K[18]]<<3|g[K[19]]>>2,q[12]=(g[K[19]]&3)<<6|g[K[20]]<<1|g[K[21]]>>4,q[13]=(g[K[21]]&15)<<4|g[K[22]]>>1,q[14]=(g[K[22]]&1)<<7|g[K[23]]<<2|g[K[24]]>>3,q[15]=(g[K[24]]&7)<<5|g[K[25]],q}function JD($){if($.length>63)return!1;let U,K,q;for(K=0,q=$.length;K<q;K+=1){U=$.charCodeAt(K);let Q=U>96&&U<123,W=U===95;if((K===0||K===q-1)&&!Q)return!1;if(!(Q||W))return!1}return!0}var GD=class extends Error{constructor($){super(`Invalid prefix "${$}". Must be at most 63 ASCII letters [a-z_]`);this.name="InvalidPrefixError"}},jD=class extends Error{constructor($,U){super(`Invalid TypeId. Prefix mismatch. Expected ${$}, got ${U}`);this.name="PrefixMismatchError"}},YD=class extends Error{constructor($){super(`Invalid TypeId. Prefix cannot be empty when there's a separator: ${$}`);this.name="EmptyPrefixError"}},HG=class extends Error{constructor($){super(`Invalid length. Suffix should have 26 characters, got ${$}`);this.name="InvalidSuffixLengthError"}},HD=class extends Error{constructor($){super(`Invalid suffix. First character "${$}" must be in the range [0-7]`);this.name="InvalidSuffixCharacterError"}},XD=class extends Error{constructor($,U){super(`Cannot convert TypeID of type ${$} to type ${U}`);this.name="TypeIDConversionError"}};function XG($="",U=""){if(!JD($))throw new GD($);let K;if(U)K=U;else{let q=new Uint8Array(16);A3(void 0,q),K=v3(q)}if(K.length!==26)throw new HG(K.length);if(K[0]>"7")throw new HD(K[0]);if(YG(K),$==="")return K;else return`${$}_${K}`}function ZD($,U){let K,q,Q=$.lastIndexOf("_");if(Q===-1)K="",q=$;else if(K=$.substring(0,Q),q=$.substring(Q+1),!K)throw new YD($);if(!q)throw new HG(0);if(U&&K!==U)throw new jD(U,K);return XG(K,q)}function GG($){let U=$.lastIndexOf("_");if(U===-1)return"";return $.substring(0,U)}function jG($){let U=$.lastIndexOf("_");if(U===-1)return $;return $.substring(U+1)}var b4=class{constructor($,U=""){this.prefix=$,this.suffix=U;let K=XG($,U);this.prefix=GG(K),this.suffix=jG(K)}getType(){return this.prefix}getSuffix(){return this.suffix}asType($){let U=this;if(U.prefix!==$)throw new XD(U.prefix,$);return U}toUUIDBytes(){return YG(this.suffix)}toUUID(){return y0(this.toUUIDBytes())}toString(){if(this.prefix==="")return this.suffix;return`${this.prefix}_${this.suffix}`}static fromString($,U){let K=ZD($,U);return new b4(GG(K),jG(K))}static fromUUIDBytes($,U){let K=v3(U);return new b4($,K)}static fromUUID($,U){let K=v3(WD(U));return new b4($,K)}};var m={acl_rules:"acl",organizations:"org",users:"usr",auth_sessions:"ses",user_passkeys:"pky",sso_providers:"sso",org_memberships:"mem",visual_plans:"vp",visual_plan_versions:"vpv",block_presets:"bpr",saved_recipes:"rcp",channels:"ch",schedules:"sched",holiday_groups:"hgrp",holidays:"hol",audio_files:"aud",destinations:"dest",call_records:"call",call_events:"cev",api_keys:"key",audit_logs:"audit",invitations:"inv",roles:"role",licenses:"lic",webhook_endpoints:"whep",webhook_delivery_logs:"whdl",call_transcriptions:"ctr",call_transcription_embeddings:"cte",analysis_templates:"at",call_analyses:"ca",ai_settings:"ais",usage_records:"ur",contacts:"ct",contact_channels:"ctch",chat_sessions:"csess",notifications:"notif",dialer_campaigns:"dcamp",dialer_contacts:"dct",dialer_attempts:"datt",dialer_dnc:"dnc",dialer_import_jobs:"dimp",org_secrets:"sec",connectors:"conn",oauth_clients:"oac",oauth_grants:"oag",signals:"sig",signal_versions:"sigv",call_signals:"csig",call_signal_timelines:"cstl",insight_views:"iv"};function u0($,U){return b4.fromUUID(m[$],U).toString()}var BD=new Map(Object.keys(m).map(($)=>[m[$],$]));function A6($){return BD.get($)}var VD=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function $4($){if(VD.test($))return{kind:"uuid",uuid:$};let U=$.lastIndexOf("_");if(U<=0||U===$.length-1)return{kind:"invalid",reason:"not-an-id"};let K=$.slice(0,U),q=A6(K);if(q===void 0)return{kind:"invalid",reason:"unknown-prefix"};try{return{kind:"typeid",entity:q,prefix:K,uuid:b4.fromString($,K).toUUID()}}catch{return{kind:"invalid",reason:"malformed-suffix"}}}function P$($){return $}function MD($){return`a ${m[$]}_... TypeID for ${$}, or the raw UUID of that row`}function ZG($,U,K){x(`Invalid id "${U}": ${K}`),z(` Expected ${MD($)}.`),z(" Convert between the two forms with: niva id <value> [--as <entity>]"),process.exit(w.USAGE_ERROR)}function DD($){let U=$.lastIndexOf("_");return U>0?$.slice(0,U):""}function BG($,U){let K=$4(U);if(K.kind==="uuid")return u0($,K.uuid);let q=A6(DD(U));if(q===$)return U;if(q!==void 0)ZG($,U,`it is a ${q} id`);ZG($,U,"it is neither a UUID nor an id of a known entity")}function A($,U){let K;if(Array.isArray(U))K=U.map((q)=>BG($,q));else if(U!==void 0)K=BG($,U);return K}var VG=["volume","answered","busy","no_answer","failed","duration","ai_cost","flow_errors"],MG=["day","week","month","hour_of_day","weekday","plan","plan_version","channel","outcome"],DG=["answered","busy","no_answer","failed"];function v6($){if($==null)return[];return $.split(",").map((U)=>U.trim()).filter((U)=>U.length>0)}function PD($,U){return[...U,$]}function K1($){x(`Error: ${$}`),process.exit(w.USAGE_ERROR)}function NG($,U){if(!$.startsWith("signal:")||$.length===7)K1(`invalid ${U} "${$}" — expected signal:<sig_id>`);return{signal_id:A("signals",$.slice(7))}}function ND($){let U=v6($);if(U.length===0)K1("--measure is required (e.g. --measure volume,answered)");if(U.length>6)K1("--measure accepts at most 6 measures");for(let K of U)if(!VG.includes(K))K1(`invalid --measure "${K}" — expected one of: ${VG.join(", ")}`);return U.map((K)=>P$(K))}function LD($){let U=[];for(let K of v6($)){if(K.startsWith("signal:")){U.push(NG(K,"--by"));continue}if(!MG.includes(K))K1(`invalid --by "${K}" — expected one of: ${MG.join(", ")} or signal:<sig_id>`);U.push(P$(K))}if(U.length>2)K1("--by accepts at most 2 dimensions");return U}function _D($){if($===void 0)return;let U=v6($);if(U.length===0)K1("--plan needs at least one id");return U.map((K)=>A("visual_plans",K))}function ID($){let U=v6($);for(let K of U)if(!DG.includes(K))K1(`invalid --outcome "${K}" — expected one of: ${DG.join(", ")}`);return U.map((K)=>P$(K))}function FD($){let U=[];for(let K of $){let q=K.indexOf("=");if(q<0)K1(`invalid --where "${K}" — expected signal:<sig_id>=<v1,v2>`);let Q=NG(K.slice(0,q),"--where"),W=v6(K.slice(q+1));if(W.length===0)K1(`invalid --where "${K}" — expected signal:<sig_id>=<v1,v2>`);U.push({...Q,values:W})}return U}function xD($){let U=Number($);if(!Number.isInteger(U)||U<1||U>1000)K1(`invalid --limit "${$}" — expected an integer from 1 to 1000`);return U}function LG($,U){$.command("analytics").description("Flexible aggregates over calls and signals").command("query").description("Aggregate call measures grouped by time, plan, channel, outcome or signal values").option("--measure <list>","Comma-separated measures: volume,answered,busy,no_answer,failed,duration,ai_cost,flow_errors").option("--by <list>","Comma-separated dimensions: day,week,month,hour_of_day,weekday,plan,plan_version,channel,outcome or signal:<sig_id> (max 2)").option("--from <date>","Start date (YYYY-MM-DD or ISO 8601)").option("--to <date>","End date (YYYY-MM-DD or ISO 8601)").option("--plan <ids>","Comma-separated visual plan IDs").option("--channel <channel>","Filter by channel: voice or chat").option("--outcome <list>","Comma-separated outcomes: answered,busy,no_answer,failed").option("--where <signal:values>","Signal filter signal:<sig_id>=<v1,v2>; repeatable",PD,[]).option("--limit <n>","Max rows (1-1000)","500").action(async(q)=>{let{format:Q}=L($.opts()),{date_from:W,date_to:J}=G1(q),j=ND(q.measure),Y=LD(q.by),H=_D(q.plan),Z=ID(q.outcome),B=FD(q.where),M=xD(q.limit),I=await N(U().insights.aggregate({measures:j,...Y.length>0?{group_by:Y}:{},...H!==void 0||q.channel!==void 0||Z.length>0||B.length>0?{filters:{...H!==void 0?{plan_ids:H}:{},...q.channel!==void 0?{channel:P$(q.channel)}:{},...Z.length>0?{outcomes:Z.map((u)=>P$(u))}:{},...B.length>0?{signals:B}:{}}}:{},period:{date_from:W,date_to:J},limit:M}));if(Q==="json"){P(I);return}if(I.truncated)$1(`Showing the first ${I.rows.length} rows (--limit ${M}). Narrow the period or filters.`);console.log(PG.default.bold("Analytics")),console.log("");let E=I.columns.map((u)=>u.key);y(E,I.rows.map((u)=>({...u})))})}import{readFile as kG,writeFile as RG}from"node:fs/promises";import{basename as zG}from"node:path";function wD($,U){let K=U.toLowerCase();if(K.endsWith(".wav"))return AD($);if(K.endsWith(".mp3"))return yD($);return}function f0($){if(!Number.isFinite($)||$<=0)return;let U=Math.round($);if(U<=0||U>86400000)return;return U}function _G($,U,K){let q="";for(let Q=0;Q<K;Q+=1)q+=String.fromCharCode($[U+Q]??0);return q}function k6($,U,K){if(U+K.length>$.byteLength)return!1;return _G($,U,K.length)===K}function IG($){return new DataView($.buffer,$.byteOffset,$.byteLength)}function AD($){let U=$.byteLength;if(U<12||!k6($,0,"RIFF")||!k6($,8,"WAVE"))return;let K=IG($),q,Q,W=12;while(W+8<=U){let J=_G($,W,4),j=K.getUint32(W+4,!0),Y=W+8;if(J==="fmt "&&j>=16&&Y+16<=U){let Z=K.getUint16(Y+2,!0),B=K.getUint32(Y+4,!0),M=K.getUint32(Y+8,!0),I=K.getUint16(Y+14,!0);q=M>0?M:B*Z*I/8}else if(J==="data"){Q=Math.min(j,U-Y);break}let H=Y+j+j%2;if(H<=W)return;W=H}if(q===void 0||q<=0||Q===void 0)return;return f0(Q/q*1000)}var vD=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320,0],kD=[0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,0],RD=[44100,48000,32000,0],zD=[22050,24000,16000,0],bD=[11025,12000,8000,0];function OD($){if($===3)return RD;if($===2)return zD;return bD}function TD($,U){if($)return U?17:32;return U?9:17}function SD($,U){let K=$[U+1],q=$[U+2],Q=$[U+3];if(K===void 0||q===void 0||Q===void 0)return;let W=K>>3&3,J=K>>1&3;if(W===1||J!==1)return;let j=W===3,Y=(j?vD:kD)[q>>4&15]??0,H=OD(W)[q>>2&3]??0;if(Y===0||H===0)return;let Z=(Q>>6&3)===3;return{bitrate:Y*1000,sampleRate:H,samplesPerFrame:j?1152:576,sideInfoSize:TD(j,Z)}}function CD($,U,K){let q=U+4+K;if(!k6($,q,"Xing")&&!k6($,q,"Info"))return;if(q+12>$.byteLength)return;let Q=IG($);if((Q.getUint32(q+4,!1)&1)===0)return;let J=Q.getUint32(q+8,!1);return J>0?J:void 0}function ED($){if(!k6($,0,"ID3")||$.byteLength<10)return 0;let U=$[5]??0,K=0;for(let Q=6;Q<=9;Q+=1)K=K<<7|($[Q]??0)&127;let q=(U&16)!==0?10:0;return 10+K+q}function yD($){let U=$.byteLength,K=ED($);for(let q=K;q+4<=U;q+=1){if($[q]!==255||(($[q+1]??0)&224)!==224)continue;let Q=SD($,q);if(Q===void 0)continue;let W=CD($,q,Q.sideInfoSize);if(W!==void 0)return f0(W*Q.samplesPerFrame*1000/Q.sampleRate);return f0((U-q)*8*1000/Q.bitrate)}return}async function gD($,U){let K=[U,"-v","error","-show_entries","format=duration","-of","csv=p=0",$],q;try{q=Bun.spawn(K,{stdout:"pipe",stderr:"ignore"})}catch{return}let Q=uD(q).catch(()=>{return}),W,J=new Promise((j)=>{W=setTimeout(()=>{q.kill(),setTimeout(()=>q.kill("SIGKILL"),250).unref(),j(void 0)},3000)});try{let j=await Promise.race([Q,J]);if(j?.exitCode!==0)return;return f0(Number(j.stdout.trim())*1000)}finally{if(W!==void 0)clearTimeout(W)}}async function uD($){let[U,K]=await Promise.all([new Response($.stdout).text(),$.exited]);return{stdout:U,exitCode:K}}async function FG($){let U=wD($.bytes,$.filePath);if(U!==void 0)return{durationMs:U,source:"header"};if($.noProbe===!0)return{source:"none"};let K=await gD($.filePath,$.ffprobePath??"ffprobe");if(K!==void 0)return{durationMs:K,source:"ffprobe"};return{source:"none"}}import{createInterface as m0}from"node:readline/promises";import{Writable as fD}from"node:stream";function R6(){return process.stdin.isTTY===!0}var xG=5;async function wG($,U,K){let q=$[U].value;for(let Q=0;Q<xG;Q++){let W=(await K(`Choice [${U+1}]: `)).trim();if(W==="")return q;let J=/^\d+$/.test(W)?$[Number(W)-1]:void 0;if(J!=null)return J.value;x(`Invalid choice — enter a number between 1 and ${$.length}.`)}return x(`No valid choice after ${xG} attempts — using the default.`),q}async function AG($,U){if(U!=null)return U($);let K=m0({input:process.stdin,output:process.stderr});try{return await K.question($)}finally{K.close()}}async function k3($,U){if(U!=null)return U($);let K=new fD({write(Q,W,J){J()}}),q=m0({input:process.stdin,output:K,terminal:!0});process.stderr.write($);try{return await q.question("")}finally{q.close(),process.stderr.write(`
|
|
32
|
-
`)}}async function
|
|
33
|
-
`)};Q($);for(let[J,j]of U.entries())Q(` ${J+1}) ${j.label}`);if(Q(""),K.ask!=null)return wG(U,q,K.ask);let W=m0({input:process.stdin,output:K.output??process.stdout});try{return await wG(U,q,async(J)=>W.question(J))}finally{W.close()}}async function d$($,U){if(U.yes)return;if(process.stdin.isTTY!==!0)x("Refusing to prompt in non-interactive mode. Re-run with --yes to confirm."),process.exit(w.USAGE_ERROR);let K=m0({input:process.stdin,output:process.stderr});try{let q=await K.question(`${$} [y/N] `);if(!/^y(?:es)?$/i.test(q.trim()))x("Aborted."),process.exit(w.USAGE_ERROR)}finally{K.close()}}import{Buffer as mD}from"node:buffer";async function v$(){return new Promise(($,U)=>{let K=[];process.stdin.on("data",(q)=>K.push(q)),process.stdin.on("end",()=>$(mD.concat(K).toString("utf-8"))),process.stdin.on("error",U)})}var hD=10,cD=new Set(["UNAUTHORIZED","FORBIDDEN","API_KEY_INVALID","ADMIN_REQUIRED","INSUFFICIENT_SCOPE"]);function bG($,U){let K=$.command("audio-files").description("Audio file library");K.command("list").description("List audio files").option("--limit <n>","Items per page","20").option("--page <n>","Page number","1").option("--search <term>","Search by name").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),J=await N(U().audioFiles.list({page:Number(q.page),limit:Number(q.limit),search:q.search}));if(Q==="json"){let j=W?J.items.map((Y)=>O(Y,W)):J;P(j);return}y(["ID","Name","Type","Duration"],J.items.map((j)=>({ID:j.id,Name:j.name,Type:j.type,Duration:OG(j.duration_ms)}))),H$(J)}),K.command("upload <file...>").description("Upload one or more audio files into the library").option("--name <name>","Library name (single file only; defaults to the filename)").option("--duration-ms <n>","Known duration in milliseconds (single file only); skips detection entirely").option("--no-probe","Do not fall back to ffprobe when the file header carries no duration (set NIVA_FFPROBE for an ffprobe outside PATH)").action(async(q,Q)=>{let{format:W}=L($.opts()),J=$.opts().yes===!0;if(Q.name!=null&&q.length>1)x("--name names a single audio file; drop it when uploading several at once."),process.exit(w.USAGE_ERROR);if(Q.durationMs!=null&&q.length>1)x("--duration-ms describes a single audio file; drop it when uploading several at once."),process.exit(w.USAGE_ERROR);let j=rD(Q.durationMs);if(q.length>hD)await d$(`Upload ${q.length} audio files to the library?`,{yes:J});let Y=[],H=w.SUCCESS;for(let Z of q){let B=await iD(U(),Z,{format:W,overrideMs:j,noProbe:Q.probe===!1,...Q.name!=null&&{name:Q.name}});if(Y.push(B),B.exitCode>H)H=B.exitCode;if(B.abort)break}if(tD(Y,W),H!==w.SUCCESS)process.exit(H)}),K.command("show <audio_file_id>").description("Show an audio file's metadata").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),J=await N(U().audioFiles.getById({audio_file_id:A("audio_files",q)}));if(J==null)x("Audio file not found"),process.exit(w.NOT_FOUND);if(Q==="json"){P(W?O(J,W):J);return}o(c0(J))}),K.command("download <audio_file_id>").description("Download an audio file's content").option("-o, --out <path>","Write to this path ('-' for stdout); defaults to the library filename").option("--force","Overwrite an existing file when writing to the default filename").action(async(q,Q)=>{let{format:W}=L($.opts()),J=$.opts(),j=J.json===!0||J.output==="json";if(Q.out==="-"&&j)x("--out - streams binary audio to stdout and cannot be combined with --json."),process.exit(w.USAGE_ERROR);let Y=U(),H=await N(Y.audioFiles.content({audio_file_id:A("audio_files",q)})),Z=new Uint8Array(await H.arrayBuffer());if(Q.out==="-"){process.stdout.write(Z);return}let B;if(Q.out!=null)B=Q.out,await RG(B,Z);else B=await nD(Y,q,H.name),await pD(B,Z,Q.force===!0);if(W==="json"){P({path:B,bytes:Z.length});return}T(`Saved ${B} (${Z.length} bytes)`)}),K.command("update <audio_file_id>").description("Update an audio file's name and/or description").option("--name <name>","New library name").option("--description <text>","New description").action(async(q,Q)=>{let{format:W}=L($.opts());if(Q.name==null&&Q.description==null)x("Nothing to update — pass --name and/or --description."),process.exit(w.USAGE_ERROR);let J=await N(U().audioFiles.update({audio_file_id:A("audio_files",q),...Q.name!=null&&{name:Q.name},...Q.description!=null&&{description:Q.description}}));if(W==="json"){P(J);return}T(`Audio file updated: ${J.name}`),o(c0(J))}),K.command("delete <audio_file_id>").description("Delete an audio file from the library").action(async(q)=>{let{format:Q}=L($.opts()),W=$.opts().yes===!0;await d$(`Delete audio file ${q}?`,{yes:W});try{await U().audioFiles.delete({audio_file_id:A("audio_files",q)})}catch(J){aD(J,Q)}if(Q==="json"){P({id:q,deleted:!0});return}T(`Audio file deleted: ${q}`)}),K.command("generate-tts").description("Generate a new audio file from text using TTS").requiredOption("--name <name>","Library name for the generated audio").option("--text <text>","Text to synthesize").option("--text-file <path>","Read the text from a file ('-' for stdin)").option("--voice <voice>","TTS voice id (resolved from the organization's language when omitted)").option("--model <model>","TTS model id (resolved from the active provider tier when omitted)").option("--description <text>","Description for the generated audio").action(async(q)=>{let{format:Q}=L($.opts()),W=await vG(q),J=await N(U().audioFiles.generateTts({name:q.name,text:W,...q.description!=null&&{description:q.description},...q.voice!=null&&{voice:q.voice},...q.model!=null&&{model:q.model}}));if(Q==="json"){P(J);return}T(`TTS audio generated: ${J.id}`),o(c0(J))}),K.command("regenerate-tts <audio_file_id>").description("Re-synthesize the content of an existing TTS audio file").option("--text <text>","New text to synthesize").option("--text-file <path>","Read the new text from a file ('-' for stdin)").option("--voice <voice>","TTS voice id (resolved from the organization's language when omitted)").option("--model <model>","TTS model id (resolved from the active provider tier when omitted)").action(async(q,Q)=>{let{format:W}=L($.opts()),J=$.opts().yes===!0,j=await vG(Q);await d$(`Overwrite the audio content of ${q}?`,{yes:J});let Y=await N(U().audioFiles.regenerateTts({audio_file_id:A("audio_files",q),text:j,...Q.voice!=null&&{voice:Q.voice},...Q.model!=null&&{model:Q.model}}));if(W==="json"){P(Y);return}T(`TTS audio regenerated: ${Y.id}`),o(c0(Y))})}var lD="FILE_UNREADABLE";function OG($){if($==null)return"—";if($<60000)return`${($/1000).toFixed(1)}s`;return f$($)}function rD($){if($==null)return;let U=Number($);if(!Number.isInteger(U)||U<=0)x(`Invalid --duration-ms "${$}": expected a positive whole number of milliseconds.`),process.exit(w.USAGE_ERROR);return U}async function iD($,U,K){let q;try{q=await kG(U)}catch(W){let J=W instanceof Error?W.message:String(W);if(K.format!=="json")x(`Cannot read ${U}: ${J}`);return{file:U,ok:!1,id:void 0,durationSource:"none",error:lD,message:J,exitCode:w.USAGE_ERROR,abort:!1}}let Q=await dD(U,q,K);try{let W=await $.audioFiles.upload({file:new File([q],zG(U)),...K.name!=null&&{name:K.name},...Q.durationMs!=null&&{duration_ms:Q.durationMs}});return{file:U,ok:!0,id:W.id,durationSource:Q.source,error:void 0,message:void 0,exitCode:w.SUCCESS,abort:!1}}catch(W){return oD(W,U,Q.source,K.format)}}async function dD($,U,K){if(K.overrideMs!=null)return{durationMs:K.overrideMs,source:"flag"};let q=process.env.NIVA_FFPROBE,Q=await FG({filePath:$,bytes:U,noProbe:K.noProbe,...q!=null&&q!==""&&{ffprobePath:q}});if(Q.source==="none"&&K.format!=="json")z(`duration unknown for ${$} — install ffmpeg or pass --duration-ms`);return Q}function oD($,U,K,q){let Q={file:U,ok:!1,id:void 0,durationSource:K};if(!b1($)){let J=F3($);if(q!=="json")x(J);return{...Q,error:"CONNECTION_ERROR",message:J,exitCode:w.GENERAL_ERROR,abort:!0}}let W=s1($);if(q!=="json")e1(W);return{...Q,error:W.code,message:W.message,exitCode:W.exitCode,abort:cD.has(W.code)}}async function nD($,U,K){let Q=[(await N($.audioFiles.getById({audio_file_id:A("audio_files",U)})))?.filename,K,U];return zG(Q.find((W)=>W!=null&&W!=="")??U)}async function pD($,U,K){try{await RG($,U,K?{}:{flag:"wx"})}catch(q){if(Q$(q)?.code!=="EEXIST")throw q;x(`${$} already exists — pass --out <path> to write elsewhere, or --force to overwrite it.`),process.exit(w.CONFLICT)}}function tD($,U){if(U==="json"){P($.map((q)=>({file:q.file,ok:q.ok,...q.id!=null&&{id:q.id},durationSource:q.durationSource,...q.error!=null&&{error:q.error},...q.message!=null&&{message:q.message}})));return}y(["File","ID","Status"],$.map((q)=>({File:q.file,ID:q.id??"—",Status:q.ok?"uploaded":q.error??"failed"})));let K=$.filter((q)=>!q.ok).length;T(`${$.length-K} uploaded, ${K} failed`)}function aD($,U){if(!b1($))Q1($);let K=s1($),q=sD(K);if(q==null)Q1($);if(U==="json")P({error:K.code,message:K.message,plans:q,hint:K.hint,retryable:K.retryable});else e1(K),z(` Referenced by: ${q.join(", ")}`);process.exit(K.exitCode)}function sD($){if($.code!=="AUDIO_FILE_IN_USE")return;let U=$.data?.plans;if(!Array.isArray(U))return;return U.map(String)}async function vG($){if($.text!=null&&$.textFile!=null)x("--text and --text-file are mutually exclusive."),process.exit(w.USAGE_ERROR);if($.text!=null)return $.text;if($.textFile==null)x("No text to synthesize — pass --text <text> or --text-file <path|->."),process.exit(w.USAGE_ERROR);let K=($.textFile==="-"?await v$():await kG($.textFile,"utf-8")).trim();if(K==="")x(`No text to synthesize: ${$.textFile==="-"?"stdin":$.textFile} is empty.`),process.exit(w.USAGE_ERROR);return K}function c0($){let U=[{title:"Audio file",rows:[{label:"ID",value:$.id},{label:"Name",value:$.name},{label:"Description",value:$.description},{label:"Type",value:$.type},{label:"Filename",value:$.filename},{label:"Duration",value:OG($.duration_ms)},{label:"Size",value:$.size_bytes!=null?`${$.size_bytes} bytes`:null},{label:"Default",value:String($.is_default)}]}];if($.tts_text!=null||$.voice_id!=null)U.push({title:"TTS",rows:[{label:"Provider",value:$.voice_provider},{label:"Voice",value:$.voice_id},{label:"Text",value:$.tts_text}]});return U}function TG($){return $[0]??{}}function Q4($){return Array.isArray($)?$:$===void 0||$===null?[]:[$]}var R3="orpc",eD="@orpc/shared",$P="1.15.0";class z3 extends Error{constructor(...$){super(...$);this.name="AbortError"}}function l0($){let U;return()=>{if(U)return U.result;let K=$();return U={result:K},K}}function UP($){let U=Promise.resolve();return(...K)=>{return U=U.catch(()=>{}).then(()=>{return $(...K)})}}var QP=2,KP=`__${eD}@${$P}/otel/config__`;function z6(){return globalThis[KP]}function r0($,U={},K){return z6()?.tracer?.startSpan($,U,K)}function O1($,U,K={}){if(!$)return;let q=qP(U);if($.recordException(q),!K.signal?.aborted||K.signal.reason!==U)$.setStatus({code:QP,message:q.message})}function qP($){if($ instanceof Error){let U={message:$.message,name:$.name,stack:$.stack};if("code"in $&&(typeof $.code==="string"||typeof $.code==="number"))U.code=$.code;return U}return{message:String($)}}async function K4({name:$,context:U,...K},q){let Q=z6()?.tracer;if(!Q)return q();let W=async(J)=>{try{return await q(J)}catch(j){throw O1(J,j,K),j}finally{J.end()}};if(U)return Q.startActiveSpan($,K,U,W);else return Q.startActiveSpan($,K,W)}async function U4($,U){let K=z6();if(!$||!K)return U();let q=K.trace.setSpan(K.context.active(),$);return K.context.with(q,U)}function x1($){if(!$||typeof $!=="object")return!1;return"next"in $&&typeof $.next==="function"&&Symbol.asyncIterator in $&&typeof $[Symbol.asyncIterator]==="function"}var WP=Symbol.for("asyncDispose"),JP=Symbol.asyncDispose??WP;class T1{#$=!1;#U=!1;#Q;#K;constructor($,U){this.#Q=U,this.#K=UP(async()=>{if(this.#$)return{done:!0,value:void 0};try{let K=await $();if(K.done)this.#$=!0;return K}catch(K){throw this.#$=!0,K}finally{if(this.#$&&!this.#U)this.#U=!0,await this.#Q("next")}})}next(){return this.#K()}async return($){if(this.#$=!0,!this.#U)this.#U=!0,await this.#Q("return");return{done:!0,value:$}}async throw($){if(this.#$=!0,!this.#U)this.#U=!0,await this.#Q("throw");throw $}async[JP](){if(this.#$=!0,!this.#U)this.#U=!0,await this.#Q("dispose")}[Symbol.asyncIterator](){return this}}function b3({name:$,...U},K){let q;return new T1(async()=>{q??=r0($);try{let Q=await U4(q,()=>K.next());return q?.addEvent(Q.done?"completed":"yielded"),Q}catch(Q){throw O1(q,Q,U),Q}},async(Q)=>{try{if(Q!=="next")await U4(q,()=>K.return?.())}catch(W){throw O1(q,W,U),W}finally{q?.end()}})}class GP{#$=new Map;#U;constructor($={}){this.#U=$.maxBufferedEvents??100}get size(){return this.#$.size}publish($,U){let K=this.#$.get($);if(!K)return;for(let q of K)q(U)}subscribe($,U){if(typeof U==="function"){let Y=this.#$.get($);if(!Y)this.#$.set($,Y=[]);return Y.push(U),l0(()=>{if(Y.splice(Y.indexOf(U),1),Y.length===0)this.#$.delete($)})}let K=U?.signal,q=U?.maxBufferedEvents??this.#U;K?.throwIfAborted();let Q=[],W=[],J=this.subscribe($,(Y)=>{let H=W.shift();if(H)H[0]({done:!1,value:Y});else if(Q.push(Y),Q.length>q)Q.shift()}),j=(Y)=>{J(),W.forEach((H)=>H[1](Y.target.reason)),W.length=0,Q.length=0};return K?.addEventListener("abort",j,{once:!0}),new T1(async()=>{if(K?.aborted)throw K.reason;if(Q.length>0)return{done:!1,value:Q.shift()};return new Promise((Y,H)=>{W.push([Y,H])})},async()=>{J(),K?.removeEventListener("abort",j),W.forEach((Y)=>Y[0]({done:!0,value:void 0})),W.length=0,Q.length=0})}}class jP{index=BigInt(1);generate(){let $=this.index.toString(36);return this.index++,$}}function b6($,U,K){let q=(Q,W)=>{let J=$[W];if(!J)return K(Q);return J({...Q,next:(j=Q)=>q(j,W+1)})};return q(U,0)}function O6($){if(!$)return;return JSON.parse($)}function q4($){return JSON.stringify($)}function SG($){if(!Y1($))return null;return Object.getPrototypeOf($)?.constructor}function i0($){if(!$||typeof $!=="object")return!1;let U=Object.getPrototypeOf($);return U===Object.prototype||!U||!U.constructor}function Y1($){return!!$&&(typeof $==="object"||typeof $==="function")}function T6($,...U){if(typeof $==="function")return $(...U);return $}function O3($){return new Proxy($,{get(U,K,q){let Q=Reflect.get(U,K,q);if(K!=="then"||typeof Q!=="function")return Q;return new Proxy(Q,{apply(W,J,j){if(j.length!==2||j.some((H)=>!HP(H)))return Reflect.apply(W,J,j);let Y=!0;j[0].call(J,O3(new Proxy(U,{get:(H,Z,B)=>{if(Y&&Z==="then"){Y=!1;return}return Reflect.get(H,Z,B)}})))}})}})}var YP=/^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;function HP($){return typeof $==="function"&&YP.test($.toString())}function CG($){try{return decodeURIComponent($)}catch{return $}}var XP="@orpc/client",ZP="1.15.0",EG=new Set(["bind","valueOf","toString","toJSON"]),o0={BAD_REQUEST:{status:400,message:"Bad Request"},UNAUTHORIZED:{status:401,message:"Unauthorized"},FORBIDDEN:{status:403,message:"Forbidden"},NOT_FOUND:{status:404,message:"Not Found"},METHOD_NOT_SUPPORTED:{status:405,message:"Method Not Supported"},NOT_ACCEPTABLE:{status:406,message:"Not Acceptable"},TIMEOUT:{status:408,message:"Request Timeout"},CONFLICT:{status:409,message:"Conflict"},PRECONDITION_FAILED:{status:412,message:"Precondition Failed"},PAYLOAD_TOO_LARGE:{status:413,message:"Payload Too Large"},UNSUPPORTED_MEDIA_TYPE:{status:415,message:"Unsupported Media Type"},UNPROCESSABLE_CONTENT:{status:422,message:"Unprocessable Content"},TOO_MANY_REQUESTS:{status:429,message:"Too Many Requests"},CLIENT_CLOSED_REQUEST:{status:499,message:"Client Closed Request"},INTERNAL_SERVER_ERROR:{status:500,message:"Internal Server Error"},NOT_IMPLEMENTED:{status:501,message:"Not Implemented"},BAD_GATEWAY:{status:502,message:"Bad Gateway"},SERVICE_UNAVAILABLE:{status:503,message:"Service Unavailable"},GATEWAY_TIMEOUT:{status:504,message:"Gateway Timeout"}};function BP($,U){return U??o0[$]?.status??500}function VP($,U){return U||o0[$]?.message||$}var d0;class W4 extends Error{defined;code;status;data;static{let $=Symbol.for(`__${XP}@${ZP}/error/ORPC_ERROR_CONSTRUCTORS__`);globalThis[$]??=new WeakSet,d0=globalThis[$],d0.add(W4)}constructor($,...U){let K=TG(U);if(K.status!==void 0&&!n0(K.status))throw Error("[ORPCError] Invalid error status code.");let q=VP($,K.message);super(q,K);this.code=$,this.status=BP($,K.status),this.defined=K.defined??!1,this.data=K.data}toJSON(){return{defined:this.defined,code:this.code,status:this.status,message:this.message,data:this.data}}static[Symbol.hasInstance]($){if(d0.has(this)){let U=SG($);if(U&&d0.has(U))return!0}return super[Symbol.hasInstance]($)}}function yG($){return $ instanceof W4?$:new W4("INTERNAL_SERVER_ERROR",{message:"Internal server error",cause:$})}function n0($){return $<200||$>=400}function T3($){if(!i0($))return!1;let U=["defined","code","status","message","data"];if(Object.keys($).some((K)=>!U.includes(K)))return!1;return"defined"in $&&typeof $.defined==="boolean"&&"code"in $&&typeof $.code==="string"&&"status"in $&&typeof $.status==="number"&&n0($.status)&&"message"in $&&typeof $.message==="string"}function S3($,U={}){return new W4($.code,{...U,...$})}class S6 extends TypeError{}class gG extends TypeError{}class w1 extends Error{data;constructor($){super($?.message??"An error event was received",$);this.data=$?.data}}var MP=/\r\n|\r(?!\n)|\n/,DP=/(?:\r\n|\r(?!\n)|\n){2}/,PP=/(?:\r\n|\r(?!\n)|\n){2}/g,NP=13,LP=10,_P=32;function IP($){let U={data:void 0,event:void 0,id:void 0,retry:void 0,comments:[]};for(let K of $.split(MP)){if(K==="")continue;let q=K.indexOf(":"),Q=q===-1?"":K.slice(K.charCodeAt(q+1)===_P?q+2:q+1);if(q===0){U.comments.push(Q);continue}switch(q===-1?K:K.slice(0,q)){case"data":U.data=U.data===void 0?Q:`${U.data}
|
|
34
|
-
${Q}`;break;case"event":U.event=Q;break;case"id":U.id=Q;break;case"retry":{let W=Number.parseInt(Q,10);if(W>=0&&W.toString()===Q)U.retry=W;break}}}return U}class
|
|
31
|
+
Check the URL: niva config set url <url>`;return`Connection error: ${$.message}`}function GD($){let U=K$($);if(U==null)return` • ${String($)}`;let K=U.path,q=Array.isArray(K)?K.join("."):"",Q=U.messageKey??U.code??"invalid",W;if(typeof U.message==="string")W=U.message;else if(typeof Q==="string")W=Q;else W=JSON.stringify(Q);return` ✗ ${q?`${q}: `:""}${W}`}function b1($){return $ instanceof Error&&"defined"in $&&"code"in $}function s1($){let U=String(K$($)?.code);if(U==="NOT_FOUND"&&K$($)?.defined===!1)return JD();return{code:U,message:$.message,data:K$(K$($)?.data),hint:qD[U],exitCode:QD(U),retryable:KD(U)}}function JD(){let $=P8();return{code:"PROCEDURE_NOT_IMPLEMENTED",message:"This NIVA server does not have this command: it is newer than the deployment.",data:void 0,hint:`${$==null?`Check available compatibility at ${D8}`:`Run: npx @sippulse/niva@${$} <command>`} (the server's NIVA version does not offer this procedure).`,exitCode:w.USAGE_ERROR,retryable:!1}}function e1($){x(`Error: ${$.code} — ${$.message}`);let U=$.data?.issues;if(Array.isArray(U))for(let K of U)x(GD(K));if($.hint!=null)R(` ${$.hint}`)}function jD($){if(x8==="json")P({error:$.code,message:$.message,data:$.data,hint:$.hint,retryable:$.retryable});else e1($);process.exit($.exitCode)}function w8($){return $ instanceof Error?WD($,UD):String($)}function Q1($){if(b1($))jD(s1($));let U=w8($);if(x8==="json")P({error:"CONNECTION_ERROR",message:$ instanceof Error?$.message:String($),retryable:!0});else x(U);process.exit(w.GENERAL_ERROR)}function R4($){if(b1($))Q1($);let U=$ instanceof Error?$.message:String($);if(x8==="json")P({error:"STREAM_ERROR",message:U,retryable:!0});else x(`Stream error: ${U}`);process.exit(w.GENERAL_ERROR)}async function N($){try{return await $}catch(U){Q1(U)}}function F1($="Not yet implemented."){R($),process.exit(w.USAGE_ERROR)}function jJ($,U){$.command("ai").description("AI module resources").command("agents").description("List AI agents available for voice interactions").action(async()=>{let{format:q,fields:Q}=L($.opts()),W=await N(U().ai.listAgents());if(q==="json"){let G=Q?W.map((j)=>O(j,Q)):W;P(G);return}y(["ID","Name","Language","SIP Inbound","Description"],W.map((G)=>({ID:G.id,Name:G.name,Language:G.language,"SIP Inbound":G.sip_inbound_enabled?"enabled":"disabled",Description:G.description??"—"})))})}var FJ=N1(I1(),1);var YJ=/^(?:[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 YD($){return typeof $==="string"&&YJ.test($)}var HJ=YD;var N$=[];for(let $=0;$<256;++$)N$.push(($+256).toString(16).slice(1));function A8($,U=0){return(N$[$[U+0]]+N$[$[U+1]]+N$[$[U+2]]+N$[$[U+3]]+"-"+N$[$[U+4]]+N$[$[U+5]]+"-"+N$[$[U+6]]+N$[$[U+7]]+"-"+N$[$[U+8]]+N$[$[U+9]]+"-"+N$[$[U+10]]+N$[$[U+11]]+N$[$[U+12]]+N$[$[U+13]]+N$[$[U+14]]+N$[$[U+15]]).toLowerCase()}function HD($,U=0){let K=A8($,U);if(!HJ(K))throw TypeError("Stringified UUID is invalid");return K}var g0=HD;var XD=new Uint8Array(16);function u0(){return crypto.getRandomValues(XD)}var v8={};function ZD($,U,K){let q;if($)q=XJ($.random??$.rng?.()??u0(),$.msecs,$.seq,U,K);else{let Q=Date.now(),W=u0();BD(v8,Q,W),q=XJ(W,v8.msecs,v8.seq,U,K)}return U??A8(q)}function BD($,U,K){if($.msecs??=-1/0,$.seq??=0,U>$.msecs)$.seq=K[6]<<23|K[7]<<16|K[8]<<8|K[9],$.msecs=U;else if($.seq=$.seq+1|0,$.seq===0)$.msecs++;return $}function XJ($,U,K,q,Q=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!q)q=new Uint8Array(16),Q=0;else if(Q<0||Q+16>q.length)throw RangeError(`UUID byte range ${Q}:${Q+15} is out of buffer bounds`);return U??=Date.now(),K??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],q[Q++]=U/1099511627776&255,q[Q++]=U/4294967296&255,q[Q++]=U/16777216&255,q[Q++]=U/65536&255,q[Q++]=U/256&255,q[Q++]=U&255,q[Q++]=112|K>>>28&15,q[Q++]=K>>>20&255,q[Q++]=128|K>>>14&63,q[Q++]=K>>>6&255,q[Q++]=K<<2&255|$[10]&3,q[Q++]=$[11],q[Q++]=$[12],q[Q++]=$[13],q[Q++]=$[14],q[Q++]=$[15],q}var k8=ZD;function VD($){let U,K=new Uint8Array(16);return K[0]=(U=parseInt($.slice(0,8),16))>>>24,K[1]=U>>>16&255,K[2]=U>>>8&255,K[3]=U&255,K[4]=(U=parseInt($.slice(9,13),16))>>>8,K[5]=U&255,K[6]=(U=parseInt($.slice(14,18),16))>>>8,K[7]=U&255,K[8]=(U=parseInt($.slice(19,23),16))>>>8,K[9]=U&255,K[10]=(U=parseInt($.slice(24,36),16))/1099511627776&255,K[11]=U/4294967296&255,K[12]=U>>>24&255,K[13]=U>>>16&255,K[14]=U>>>8&255,K[15]=U&255,K}var W$="0123456789abcdefghjkmnpqrstvwxyz",g=new Uint8Array([255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,10,11,12,13,14,15,16,17,255,18,19,255,20,21,255,22,23,24,25,26,255,27,28,29,30,31,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255]);function z8($){let U=Array(26).fill("");if($.length!==16)throw Error(`Invalid length. Expected 16 bytes, got ${$.length}. Input: ${$}`);return U[0]=W$[($[0]&224)>>5],U[1]=W$[$[0]&31],U[2]=W$[($[1]&248)>>3],U[3]=W$[($[1]&7)<<2|($[2]&192)>>6],U[4]=W$[($[2]&62)>>1],U[5]=W$[($[2]&1)<<4|($[3]&240)>>4],U[6]=W$[($[3]&15)<<1|($[4]&128)>>7],U[7]=W$[($[4]&124)>>2],U[8]=W$[($[4]&3)<<3|($[5]&224)>>5],U[9]=W$[$[5]&31],U[10]=W$[($[6]&248)>>3],U[11]=W$[($[6]&7)<<2|($[7]&192)>>6],U[12]=W$[($[7]&62)>>1],U[13]=W$[($[7]&1)<<4|($[8]&240)>>4],U[14]=W$[($[8]&15)<<1|($[9]&128)>>7],U[15]=W$[($[9]&124)>>2],U[16]=W$[($[9]&3)<<3|($[10]&224)>>5],U[17]=W$[$[10]&31],U[18]=W$[($[11]&248)>>3],U[19]=W$[($[11]&7)<<2|($[12]&192)>>6],U[20]=W$[($[12]&62)>>1],U[21]=W$[($[12]&1)<<4|($[13]&240)>>4],U[22]=W$[($[13]&15)<<1|($[14]&128)>>7],U[23]=W$[($[14]&124)>>2],U[24]=W$[($[14]&3)<<3|($[15]&224)>>5],U[25]=W$[$[15]&31],U.join("")}function VJ($){if($.length!==26)throw Error(`Invalid length. Expected 26 bytes, got ${$.length}. Input: ${$}`);let K=new TextEncoder().encode($);if(g[K[0]]===255||g[K[1]]===255||g[K[2]]===255||g[K[3]]===255||g[K[4]]===255||g[K[5]]===255||g[K[6]]===255||g[K[7]]===255||g[K[8]]===255||g[K[9]]===255||g[K[10]]===255||g[K[11]]===255||g[K[12]]===255||g[K[13]]===255||g[K[14]]===255||g[K[15]]===255||g[K[16]]===255||g[K[17]]===255||g[K[18]]===255||g[K[19]]===255||g[K[20]]===255||g[K[21]]===255||g[K[22]]===255||g[K[23]]===255||g[K[24]]===255||g[K[25]]===255)throw Error("Invalid base32 character");let q=new Uint8Array(16);return q[0]=g[K[0]]<<5|g[K[1]],q[1]=g[K[2]]<<3|g[K[3]]>>2,q[2]=(g[K[3]]&3)<<6|g[K[4]]<<1|g[K[5]]>>4,q[3]=(g[K[5]]&15)<<4|g[K[6]]>>1,q[4]=(g[K[6]]&1)<<7|g[K[7]]<<2|g[K[8]]>>3,q[5]=(g[K[8]]&7)<<5|g[K[9]],q[6]=g[K[10]]<<3|g[K[11]]>>2,q[7]=(g[K[11]]&3)<<6|g[K[12]]<<1|g[K[13]]>>4,q[8]=(g[K[13]]&15)<<4|g[K[14]]>>1,q[9]=(g[K[14]]&1)<<7|g[K[15]]<<2|g[K[16]]>>3,q[10]=(g[K[16]]&7)<<5|g[K[17]],q[11]=g[K[18]]<<3|g[K[19]]>>2,q[12]=(g[K[19]]&3)<<6|g[K[20]]<<1|g[K[21]]>>4,q[13]=(g[K[21]]&15)<<4|g[K[22]]>>1,q[14]=(g[K[22]]&1)<<7|g[K[23]]<<2|g[K[24]]>>3,q[15]=(g[K[24]]&7)<<5|g[K[25]],q}function MD($){if($.length>63)return!1;let U,K,q;for(K=0,q=$.length;K<q;K+=1){U=$.charCodeAt(K);let Q=U>96&&U<123,W=U===95;if((K===0||K===q-1)&&!Q)return!1;if(!(Q||W))return!1}return!0}var DD=class extends Error{constructor($){super(`Invalid prefix "${$}". Must be at most 63 ASCII letters [a-z_]`);this.name="InvalidPrefixError"}},PD=class extends Error{constructor($,U){super(`Invalid TypeId. Prefix mismatch. Expected ${$}, got ${U}`);this.name="PrefixMismatchError"}},ND=class extends Error{constructor($){super(`Invalid TypeId. Prefix cannot be empty when there's a separator: ${$}`);this.name="EmptyPrefixError"}},MJ=class extends Error{constructor($){super(`Invalid length. Suffix should have 26 characters, got ${$}`);this.name="InvalidSuffixLengthError"}},LD=class extends Error{constructor($){super(`Invalid suffix. First character "${$}" must be in the range [0-7]`);this.name="InvalidSuffixCharacterError"}},_D=class extends Error{constructor($,U){super(`Cannot convert TypeID of type ${$} to type ${U}`);this.name="TypeIDConversionError"}};function DJ($="",U=""){if(!MD($))throw new DD($);let K;if(U)K=U;else{let q=new Uint8Array(16);k8(void 0,q),K=z8(q)}if(K.length!==26)throw new MJ(K.length);if(K[0]>"7")throw new LD(K[0]);if(VJ(K),$==="")return K;else return`${$}_${K}`}function ID($,U){let K,q,Q=$.lastIndexOf("_");if(Q===-1)K="",q=$;else if(K=$.substring(0,Q),q=$.substring(Q+1),!K)throw new ND($);if(!q)throw new MJ(0);if(U&&K!==U)throw new PD(U,K);return DJ(K,q)}function ZJ($){let U=$.lastIndexOf("_");if(U===-1)return"";return $.substring(0,U)}function BJ($){let U=$.lastIndexOf("_");if(U===-1)return $;return $.substring(U+1)}var b4=class{constructor($,U=""){this.prefix=$,this.suffix=U;let K=DJ($,U);this.prefix=ZJ(K),this.suffix=BJ(K)}getType(){return this.prefix}getSuffix(){return this.suffix}asType($){let U=this;if(U.prefix!==$)throw new _D(U.prefix,$);return U}toUUIDBytes(){return VJ(this.suffix)}toUUID(){return g0(this.toUUIDBytes())}toString(){if(this.prefix==="")return this.suffix;return`${this.prefix}_${this.suffix}`}static fromString($,U){let K=ID($,U);return new b4(ZJ(K),BJ(K))}static fromUUIDBytes($,U){let K=z8(U);return new b4($,K)}static fromUUID($,U){let K=z8(VD(U));return new b4($,K)}};var m={acl_rules:"acl",organizations:"org",users:"usr",auth_sessions:"ses",user_passkeys:"pky",sso_providers:"sso",org_memberships:"mem",visual_plans:"vp",visual_plan_versions:"vpv",block_presets:"bpr",saved_recipes:"rcp",channels:"ch",schedules:"sched",holiday_groups:"hgrp",holidays:"hol",audio_files:"aud",destinations:"dest",call_records:"call",call_events:"cev",api_keys:"key",audit_logs:"audit",invitations:"inv",roles:"role",licenses:"lic",webhook_endpoints:"whep",webhook_delivery_logs:"whdl",call_transcriptions:"ctr",call_transcription_embeddings:"cte",analysis_templates:"at",call_analyses:"ca",ai_settings:"ais",usage_records:"ur",contacts:"ct",contact_channels:"ctch",chat_sessions:"csess",notifications:"notif",dialer_campaigns:"dcamp",dialer_contacts:"dct",dialer_attempts:"datt",dialer_dnc:"dnc",dialer_import_jobs:"dimp",org_secrets:"sec",connectors:"conn",oauth_clients:"oac",oauth_grants:"oag",signals:"sig",signal_versions:"sigv",call_signals:"csig",call_signal_timelines:"cstl",insight_views:"iv"};function f0($,U){return b4.fromUUID(m[$],U).toString()}var FD=new Map(Object.keys(m).map(($)=>[m[$],$]));function v6($){return FD.get($)}var xD=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function $4($){if(xD.test($))return{kind:"uuid",uuid:$};let U=$.lastIndexOf("_");if(U<=0||U===$.length-1)return{kind:"invalid",reason:"not-an-id"};let K=$.slice(0,U),q=v6(K);if(q===void 0)return{kind:"invalid",reason:"unknown-prefix"};try{return{kind:"typeid",entity:q,prefix:K,uuid:b4.fromString($,K).toUUID()}}catch{return{kind:"invalid",reason:"malformed-suffix"}}}function P$($){return $}function wD($){return`a ${m[$]}_... TypeID for ${$}, or the raw UUID of that row`}function PJ($,U,K){x(`Invalid id "${U}": ${K}`),R(` Expected ${wD($)}.`),R(" Convert between the two forms with: niva id <value> [--as <entity>]"),process.exit(w.USAGE_ERROR)}function AD($){let U=$.lastIndexOf("_");return U>0?$.slice(0,U):""}function NJ($,U){let K=$4(U);if(K.kind==="uuid")return f0($,K.uuid);let q=v6(AD(U));if(q===$)return U;if(q!==void 0)PJ($,U,`it is a ${q} id`);PJ($,U,"it is neither a UUID nor an id of a known entity")}function A($,U){let K;if(Array.isArray(U))K=U.map((q)=>NJ($,q));else if(U!==void 0)K=NJ($,U);return K}var LJ=["volume","answered","busy","no_answer","failed","duration","ai_cost","flow_errors"],_J=["day","week","month","hour_of_day","weekday","plan","plan_version","channel","outcome"],IJ=["answered","busy","no_answer","failed"];function k6($){if($==null)return[];return $.split(",").map((U)=>U.trim()).filter((U)=>U.length>0)}function vD($,U){return[...U,$]}function K1($){x(`Error: ${$}`),process.exit(w.USAGE_ERROR)}function xJ($,U){if(!$.startsWith("signal:")||$.length===7)K1(`invalid ${U} "${$}" — expected signal:<sig_id>`);return{signal_id:A("signals",$.slice(7))}}function kD($){let U=k6($);if(U.length===0)K1("--measure is required (e.g. --measure volume,answered)");if(U.length>6)K1("--measure accepts at most 6 measures");for(let K of U)if(!LJ.includes(K))K1(`invalid --measure "${K}" — expected one of: ${LJ.join(", ")}`);return U.map((K)=>P$(K))}function zD($){let U=[];for(let K of k6($)){if(K.startsWith("signal:")){U.push(xJ(K,"--by"));continue}if(!_J.includes(K))K1(`invalid --by "${K}" — expected one of: ${_J.join(", ")} or signal:<sig_id>`);U.push(P$(K))}if(U.length>2)K1("--by accepts at most 2 dimensions");return U}function RD($){if($===void 0)return;let U=k6($);if(U.length===0)K1("--plan needs at least one id");return U.map((K)=>A("visual_plans",K))}function bD($){let U=k6($);for(let K of U)if(!IJ.includes(K))K1(`invalid --outcome "${K}" — expected one of: ${IJ.join(", ")}`);return U.map((K)=>P$(K))}function OD($){let U=[];for(let K of $){let q=K.indexOf("=");if(q<0)K1(`invalid --where "${K}" — expected signal:<sig_id>=<v1,v2>`);let Q=xJ(K.slice(0,q),"--where"),W=k6(K.slice(q+1));if(W.length===0)K1(`invalid --where "${K}" — expected signal:<sig_id>=<v1,v2>`);U.push({...Q,values:W})}return U}function TD($){let U=Number($);if(!Number.isInteger(U)||U<1||U>1000)K1(`invalid --limit "${$}" — expected an integer from 1 to 1000`);return U}function wJ($,U){$.command("analytics").description("Flexible aggregates over calls and signals").command("query").description("Aggregate call measures grouped by time, plan, channel, outcome or signal values").option("--measure <list>","Comma-separated measures: volume,answered,busy,no_answer,failed,duration,ai_cost,flow_errors").option("--by <list>","Comma-separated dimensions: day,week,month,hour_of_day,weekday,plan,plan_version,channel,outcome or signal:<sig_id> (max 2)").option("--from <date>","Start date (YYYY-MM-DD or ISO 8601)").option("--to <date>","End date (YYYY-MM-DD or ISO 8601)").option("--plan <ids>","Comma-separated visual plan IDs").option("--channel <channel>","Filter by channel: voice or chat").option("--outcome <list>","Comma-separated outcomes: answered,busy,no_answer,failed").option("--where <signal:values>","Signal filter signal:<sig_id>=<v1,v2>; repeatable",vD,[]).option("--limit <n>","Max rows (1-1000)","500").action(async(q)=>{let{format:Q}=L($.opts()),{date_from:W,date_to:G}=J1(q),j=kD(q.measure),Y=zD(q.by),H=RD(q.plan),X=bD(q.outcome),B=OD(q.where),M=TD(q.limit),I=await N(U().insights.aggregate({measures:j,...Y.length>0?{group_by:Y}:{},...H!==void 0||q.channel!==void 0||X.length>0||B.length>0?{filters:{...H!==void 0?{plan_ids:H}:{},...q.channel!==void 0?{channel:P$(q.channel)}:{},...X.length>0?{outcomes:X.map((u)=>P$(u))}:{},...B.length>0?{signals:B}:{}}}:{},period:{date_from:W,date_to:G},limit:M}));if(Q==="json"){P(I);return}if(I.truncated)$1(`Showing the first ${I.rows.length} rows (--limit ${M}). Narrow the period or filters.`);console.log(FJ.default.bold("Analytics")),console.log("");let E=I.columns.map((u)=>u.key);y(E,I.rows.map((u)=>({...u})))})}import{readFile as TJ,writeFile as SJ}from"node:fs/promises";import{basename as CJ}from"node:path";function SD($,U){let K=U.toLowerCase();if(K.endsWith(".wav"))return CD($);if(K.endsWith(".mp3"))return iD($);return}function m0($){if(!Number.isFinite($)||$<=0)return;let U=Math.round($);if(U<=0||U>86400000)return;return U}function AJ($,U,K){let q="";for(let Q=0;Q<K;Q+=1)q+=String.fromCharCode($[U+Q]??0);return q}function z6($,U,K){if(U+K.length>$.byteLength)return!1;return AJ($,U,K.length)===K}function vJ($){return new DataView($.buffer,$.byteOffset,$.byteLength)}function CD($){let U=$.byteLength;if(U<12||!z6($,0,"RIFF")||!z6($,8,"WAVE"))return;let K=vJ($),q,Q,W=12;while(W+8<=U){let G=AJ($,W,4),j=K.getUint32(W+4,!0),Y=W+8;if(G==="fmt "&&j>=16&&Y+16<=U){let X=K.getUint16(Y+2,!0),B=K.getUint32(Y+4,!0),M=K.getUint32(Y+8,!0),I=K.getUint16(Y+14,!0);q=M>0?M:B*X*I/8}else if(G==="data"){Q=Math.min(j,U-Y);break}let H=Y+j+j%2;if(H<=W)return;W=H}if(q===void 0||q<=0||Q===void 0)return;return m0(Q/q*1000)}var ED=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320,0],yD=[0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,0],gD=[44100,48000,32000,0],uD=[22050,24000,16000,0],fD=[11025,12000,8000,0];function mD($){if($===3)return gD;if($===2)return uD;return fD}function hD($,U){if($)return U?17:32;return U?9:17}function cD($,U){let K=$[U+1],q=$[U+2],Q=$[U+3];if(K===void 0||q===void 0||Q===void 0)return;let W=K>>3&3,G=K>>1&3;if(W===1||G!==1)return;let j=W===3,Y=(j?ED:yD)[q>>4&15]??0,H=mD(W)[q>>2&3]??0;if(Y===0||H===0)return;let X=(Q>>6&3)===3;return{bitrate:Y*1000,sampleRate:H,samplesPerFrame:j?1152:576,sideInfoSize:hD(j,X)}}function lD($,U,K){let q=U+4+K;if(!z6($,q,"Xing")&&!z6($,q,"Info"))return;if(q+12>$.byteLength)return;let Q=vJ($);if((Q.getUint32(q+4,!1)&1)===0)return;let G=Q.getUint32(q+8,!1);return G>0?G:void 0}function rD($){if(!z6($,0,"ID3")||$.byteLength<10)return 0;let U=$[5]??0,K=0;for(let Q=6;Q<=9;Q+=1)K=K<<7|($[Q]??0)&127;let q=(U&16)!==0?10:0;return 10+K+q}function iD($){let U=$.byteLength,K=rD($);for(let q=K;q+4<=U;q+=1){if($[q]!==255||(($[q+1]??0)&224)!==224)continue;let Q=cD($,q);if(Q===void 0)continue;let W=lD($,q,Q.sideInfoSize);if(W!==void 0)return m0(W*Q.samplesPerFrame*1000/Q.sampleRate);return m0((U-q)*8*1000/Q.bitrate)}return}async function dD($,U){let K=[U,"-v","error","-show_entries","format=duration","-of","csv=p=0",$],q;try{q=Bun.spawn(K,{stdout:"pipe",stderr:"ignore"})}catch{return}let Q=oD(q).catch(()=>{return}),W,G=new Promise((j)=>{W=setTimeout(()=>{q.kill(),setTimeout(()=>q.kill("SIGKILL"),250).unref(),j(void 0)},3000)});try{let j=await Promise.race([Q,G]);if(j?.exitCode!==0)return;return m0(Number(j.stdout.trim())*1000)}finally{if(W!==void 0)clearTimeout(W)}}async function oD($){let[U,K]=await Promise.all([new Response($.stdout).text(),$.exited]);return{stdout:U,exitCode:K}}async function kJ($){let U=SD($.bytes,$.filePath);if(U!==void 0)return{durationMs:U,source:"header"};if($.noProbe===!0)return{source:"none"};let K=await dD($.filePath,$.ffprobePath??"ffprobe");if(K!==void 0)return{durationMs:K,source:"ffprobe"};return{source:"none"}}import{createInterface as h0}from"node:readline/promises";import{Writable as nD}from"node:stream";function R6(){return process.stdin.isTTY===!0}var zJ=5;async function RJ($,U,K){let q=$[U].value;for(let Q=0;Q<zJ;Q++){let W=(await K(`Choice [${U+1}]: `)).trim();if(W==="")return q;let G=/^\d+$/.test(W)?$[Number(W)-1]:void 0;if(G!=null)return G.value;x(`Invalid choice — enter a number between 1 and ${$.length}.`)}return x(`No valid choice after ${zJ} attempts — using the default.`),q}async function bJ($,U){if(U!=null)return U($);let K=h0({input:process.stdin,output:process.stderr});try{return await K.question($)}finally{K.close()}}async function R8($,U){if(U!=null)return U($);let K=new nD({write(Q,W,G){G()}}),q=h0({input:process.stdin,output:K,terminal:!0});process.stderr.write($);try{return await q.question("")}finally{q.close(),process.stderr.write(`
|
|
32
|
+
`)}}async function c0($,U,K={}){let q=K.defaultIndex??0,Q=(G)=>{if(K.output==null)console.log(G);else K.output.write(`${G}
|
|
33
|
+
`)};Q($);for(let[G,j]of U.entries())Q(` ${G+1}) ${j.label}`);if(Q(""),K.ask!=null)return RJ(U,q,K.ask);let W=h0({input:process.stdin,output:K.output??process.stdout});try{return await RJ(U,q,async(G)=>W.question(G))}finally{W.close()}}async function d$($,U){if(U.yes)return;if(process.stdin.isTTY!==!0)x("Refusing to prompt in non-interactive mode. Re-run with --yes to confirm."),process.exit(w.USAGE_ERROR);let K=h0({input:process.stdin,output:process.stderr});try{let q=await K.question(`${$} [y/N] `);if(!/^y(?:es)?$/i.test(q.trim()))x("Aborted."),process.exit(w.USAGE_ERROR)}finally{K.close()}}import{Buffer as pD}from"node:buffer";async function v$(){return new Promise(($,U)=>{let K=[];process.stdin.on("data",(q)=>K.push(q)),process.stdin.on("end",()=>$(pD.concat(K).toString("utf-8"))),process.stdin.on("error",U)})}var tD=10,aD=new Set(["UNAUTHORIZED","FORBIDDEN","API_KEY_INVALID","ADMIN_REQUIRED","INSUFFICIENT_SCOPE"]);function EJ($,U){let K=$.command("audio-files").description("Audio file library");K.command("list").description("List audio files").option("--limit <n>","Items per page","20").option("--page <n>","Page number","1").option("--search <term>","Search by name").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),G=await N(U().audioFiles.list({page:Number(q.page),limit:Number(q.limit),search:q.search}));if(Q==="json"){let j=W?G.items.map((Y)=>O(Y,W)):G;P(j);return}y(["ID","Name","Type","Duration"],G.items.map((j)=>({ID:j.id,Name:j.name,Type:j.type,Duration:yJ(j.duration_ms)}))),Z$(G)}),K.command("upload <file...>").description("Upload one or more audio files into the library").option("--name <name>","Library name (single file only; defaults to the filename)").option("--duration-ms <n>","Known duration in milliseconds (single file only); skips detection entirely").option("--no-probe","Do not fall back to ffprobe when the file header carries no duration (set NIVA_FFPROBE for an ffprobe outside PATH)").action(async(q,Q)=>{let{format:W}=L($.opts()),G=$.opts().yes===!0;if(Q.name!=null&&q.length>1)x("--name names a single audio file; drop it when uploading several at once."),process.exit(w.USAGE_ERROR);if(Q.durationMs!=null&&q.length>1)x("--duration-ms describes a single audio file; drop it when uploading several at once."),process.exit(w.USAGE_ERROR);let j=eD(Q.durationMs);if(q.length>tD)await d$(`Upload ${q.length} audio files to the library?`,{yes:G});let Y=[],H=w.SUCCESS;for(let X of q){let B=await $P(U(),X,{format:W,overrideMs:j,noProbe:Q.probe===!1,...Q.name!=null&&{name:Q.name}});if(Y.push(B),B.exitCode>H)H=B.exitCode;if(B.abort)break}if(WP(Y,W),H!==w.SUCCESS)process.exit(H)}),K.command("show <audio_file_id>").description("Show an audio file's metadata").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),G=await N(U().audioFiles.getById({audio_file_id:A("audio_files",q)}));if(G==null)x("Audio file not found"),process.exit(w.NOT_FOUND);if(Q==="json"){P(W?O(G,W):G);return}o(l0(G))}),K.command("download <audio_file_id>").description("Download an audio file's content").option("-o, --out <path>","Write to this path ('-' for stdout); defaults to the library filename").option("--force","Overwrite an existing file when writing to the default filename").action(async(q,Q)=>{let{format:W}=L($.opts()),G=$.opts(),j=G.json===!0||G.output==="json";if(Q.out==="-"&&j)x("--out - streams binary audio to stdout and cannot be combined with --json."),process.exit(w.USAGE_ERROR);let Y=U(),H=await N(Y.audioFiles.content({audio_file_id:A("audio_files",q)})),X=new Uint8Array(await H.arrayBuffer());if(Q.out==="-"){process.stdout.write(X);return}let B;if(Q.out!=null)B=Q.out,await SJ(B,X);else B=await KP(Y,q,H.name),await qP(B,X,Q.force===!0);if(W==="json"){P({path:B,bytes:X.length});return}T(`Saved ${B} (${X.length} bytes)`)}),K.command("update <audio_file_id>").description("Update an audio file's name and/or description").option("--name <name>","New library name").option("--description <text>","New description").action(async(q,Q)=>{let{format:W}=L($.opts());if(Q.name==null&&Q.description==null)x("Nothing to update — pass --name and/or --description."),process.exit(w.USAGE_ERROR);let G=await N(U().audioFiles.update({audio_file_id:A("audio_files",q),...Q.name!=null&&{name:Q.name},...Q.description!=null&&{description:Q.description}}));if(W==="json"){P(G);return}T(`Audio file updated: ${G.name}`),o(l0(G))}),K.command("delete <audio_file_id>").description("Delete an audio file from the library").action(async(q)=>{let{format:Q}=L($.opts()),W=$.opts().yes===!0;await d$(`Delete audio file ${q}?`,{yes:W});try{await U().audioFiles.delete({audio_file_id:A("audio_files",q)})}catch(G){GP(G,Q)}if(Q==="json"){P({id:q,deleted:!0});return}T(`Audio file deleted: ${q}`)}),K.command("generate-tts").description("Generate a new audio file from text using TTS").requiredOption("--name <name>","Library name for the generated audio").option("--text <text>","Text to synthesize").option("--text-file <path>","Read the text from a file ('-' for stdin)").option("--voice <voice>","TTS voice id (resolved from the organization's language when omitted)").option("--model <model>","TTS model id (resolved from the active provider tier when omitted)").option("--description <text>","Description for the generated audio").action(async(q)=>{let{format:Q}=L($.opts()),W=await OJ(q),G=await N(U().audioFiles.generateTts({name:q.name,text:W,...q.description!=null&&{description:q.description},...q.voice!=null&&{voice:q.voice},...q.model!=null&&{model:q.model}}));if(Q==="json"){P(G);return}T(`TTS audio generated: ${G.id}`),o(l0(G))}),K.command("regenerate-tts <audio_file_id>").description("Re-synthesize the content of an existing TTS audio file").option("--text <text>","New text to synthesize").option("--text-file <path>","Read the new text from a file ('-' for stdin)").option("--voice <voice>","TTS voice id (resolved from the organization's language when omitted)").option("--model <model>","TTS model id (resolved from the active provider tier when omitted)").action(async(q,Q)=>{let{format:W}=L($.opts()),G=$.opts().yes===!0,j=await OJ(Q);await d$(`Overwrite the audio content of ${q}?`,{yes:G});let Y=await N(U().audioFiles.regenerateTts({audio_file_id:A("audio_files",q),text:j,...Q.voice!=null&&{voice:Q.voice},...Q.model!=null&&{model:Q.model}}));if(W==="json"){P(Y);return}T(`TTS audio regenerated: ${Y.id}`),o(l0(Y))})}var sD="FILE_UNREADABLE";function yJ($){if($==null)return"—";if($<60000)return`${($/1000).toFixed(1)}s`;return f$($)}function eD($){if($==null)return;let U=Number($);if(!Number.isInteger(U)||U<=0)x(`Invalid --duration-ms "${$}": expected a positive whole number of milliseconds.`),process.exit(w.USAGE_ERROR);return U}async function $P($,U,K){let q;try{q=await TJ(U)}catch(W){let G=W instanceof Error?W.message:String(W);if(K.format!=="json")x(`Cannot read ${U}: ${G}`);return{file:U,ok:!1,id:void 0,durationSource:"none",error:sD,message:G,exitCode:w.USAGE_ERROR,abort:!1}}let Q=await UP(U,q,K);try{let W=await $.audioFiles.upload({file:new File([q],CJ(U)),...K.name!=null&&{name:K.name},...Q.durationMs!=null&&{duration_ms:Q.durationMs}});return{file:U,ok:!0,id:W.id,durationSource:Q.source,error:void 0,message:void 0,exitCode:w.SUCCESS,abort:!1}}catch(W){return QP(W,U,Q.source,K.format)}}async function UP($,U,K){if(K.overrideMs!=null)return{durationMs:K.overrideMs,source:"flag"};let q=process.env.NIVA_FFPROBE,Q=await kJ({filePath:$,bytes:U,noProbe:K.noProbe,...q!=null&&q!==""&&{ffprobePath:q}});if(Q.source==="none"&&K.format!=="json")R(`duration unknown for ${$} — install ffmpeg or pass --duration-ms`);return Q}function QP($,U,K,q){let Q={file:U,ok:!1,id:void 0,durationSource:K};if(!b1($)){let G=w8($);if(q!=="json")x(G);return{...Q,error:"CONNECTION_ERROR",message:G,exitCode:w.GENERAL_ERROR,abort:!0}}let W=s1($);if(q!=="json")e1(W);return{...Q,error:W.code,message:W.message,exitCode:W.exitCode,abort:aD.has(W.code)}}async function KP($,U,K){let Q=[(await N($.audioFiles.getById({audio_file_id:A("audio_files",U)})))?.filename,K,U];return CJ(Q.find((W)=>W!=null&&W!=="")??U)}async function qP($,U,K){try{await SJ($,U,K?{}:{flag:"wx"})}catch(q){if(K$(q)?.code!=="EEXIST")throw q;x(`${$} already exists — pass --out <path> to write elsewhere, or --force to overwrite it.`),process.exit(w.CONFLICT)}}function WP($,U){if(U==="json"){P($.map((q)=>({file:q.file,ok:q.ok,...q.id!=null&&{id:q.id},durationSource:q.durationSource,...q.error!=null&&{error:q.error},...q.message!=null&&{message:q.message}})));return}y(["File","ID","Status"],$.map((q)=>({File:q.file,ID:q.id??"—",Status:q.ok?"uploaded":q.error??"failed"})));let K=$.filter((q)=>!q.ok).length;T(`${$.length-K} uploaded, ${K} failed`)}function GP($,U){if(!b1($))Q1($);let K=s1($),q=JP(K);if(q==null)Q1($);if(U==="json")P({error:K.code,message:K.message,plans:q,hint:K.hint,retryable:K.retryable});else e1(K),R(` Referenced by: ${q.join(", ")}`);process.exit(K.exitCode)}function JP($){if($.code!=="AUDIO_FILE_IN_USE")return;let U=$.data?.plans;if(!Array.isArray(U))return;return U.map(String)}async function OJ($){if($.text!=null&&$.textFile!=null)x("--text and --text-file are mutually exclusive."),process.exit(w.USAGE_ERROR);if($.text!=null)return $.text;if($.textFile==null)x("No text to synthesize — pass --text <text> or --text-file <path|->."),process.exit(w.USAGE_ERROR);let K=($.textFile==="-"?await v$():await TJ($.textFile,"utf-8")).trim();if(K==="")x(`No text to synthesize: ${$.textFile==="-"?"stdin":$.textFile} is empty.`),process.exit(w.USAGE_ERROR);return K}function l0($){let U=[{title:"Audio file",rows:[{label:"ID",value:$.id},{label:"Name",value:$.name},{label:"Description",value:$.description},{label:"Type",value:$.type},{label:"Filename",value:$.filename},{label:"Duration",value:yJ($.duration_ms)},{label:"Size",value:$.size_bytes!=null?`${$.size_bytes} bytes`:null},{label:"Default",value:String($.is_default)}]}];if($.tts_text!=null||$.voice_id!=null)U.push({title:"TTS",rows:[{label:"Provider",value:$.voice_provider},{label:"Voice",value:$.voice_id},{label:"Text",value:$.tts_text}]});return U}function gJ($){return $[0]??{}}function Q4($){return Array.isArray($)?$:$===void 0||$===null?[]:[$]}var b8="orpc",jP="@orpc/shared",YP="1.15.0";class O8 extends Error{constructor(...$){super(...$);this.name="AbortError"}}function r0($){let U;return()=>{if(U)return U.result;let K=$();return U={result:K},K}}function HP($){let U=Promise.resolve();return(...K)=>{return U=U.catch(()=>{}).then(()=>{return $(...K)})}}var XP=2,ZP=`__${jP}@${YP}/otel/config__`;function b6(){return globalThis[ZP]}function i0($,U={},K){return b6()?.tracer?.startSpan($,U,K)}function O1($,U,K={}){if(!$)return;let q=BP(U);if($.recordException(q),!K.signal?.aborted||K.signal.reason!==U)$.setStatus({code:XP,message:q.message})}function BP($){if($ instanceof Error){let U={message:$.message,name:$.name,stack:$.stack};if("code"in $&&(typeof $.code==="string"||typeof $.code==="number"))U.code=$.code;return U}return{message:String($)}}async function K4({name:$,context:U,...K},q){let Q=b6()?.tracer;if(!Q)return q();let W=async(G)=>{try{return await q(G)}catch(j){throw O1(G,j,K),j}finally{G.end()}};if(U)return Q.startActiveSpan($,K,U,W);else return Q.startActiveSpan($,K,W)}async function U4($,U){let K=b6();if(!$||!K)return U();let q=K.trace.setSpan(K.context.active(),$);return K.context.with(q,U)}function x1($){if(!$||typeof $!=="object")return!1;return"next"in $&&typeof $.next==="function"&&Symbol.asyncIterator in $&&typeof $[Symbol.asyncIterator]==="function"}var VP=Symbol.for("asyncDispose"),MP=Symbol.asyncDispose??VP;class T1{#$=!1;#U=!1;#Q;#K;constructor($,U){this.#Q=U,this.#K=HP(async()=>{if(this.#$)return{done:!0,value:void 0};try{let K=await $();if(K.done)this.#$=!0;return K}catch(K){throw this.#$=!0,K}finally{if(this.#$&&!this.#U)this.#U=!0,await this.#Q("next")}})}next(){return this.#K()}async return($){if(this.#$=!0,!this.#U)this.#U=!0,await this.#Q("return");return{done:!0,value:$}}async throw($){if(this.#$=!0,!this.#U)this.#U=!0,await this.#Q("throw");throw $}async[MP](){if(this.#$=!0,!this.#U)this.#U=!0,await this.#Q("dispose")}[Symbol.asyncIterator](){return this}}function T8({name:$,...U},K){let q;return new T1(async()=>{q??=i0($);try{let Q=await U4(q,()=>K.next());return q?.addEvent(Q.done?"completed":"yielded"),Q}catch(Q){throw O1(q,Q,U),Q}},async(Q)=>{try{if(Q!=="next")await U4(q,()=>K.return?.())}catch(W){throw O1(q,W,U),W}finally{q?.end()}})}class DP{#$=new Map;#U;constructor($={}){this.#U=$.maxBufferedEvents??100}get size(){return this.#$.size}publish($,U){let K=this.#$.get($);if(!K)return;for(let q of K)q(U)}subscribe($,U){if(typeof U==="function"){let Y=this.#$.get($);if(!Y)this.#$.set($,Y=[]);return Y.push(U),r0(()=>{if(Y.splice(Y.indexOf(U),1),Y.length===0)this.#$.delete($)})}let K=U?.signal,q=U?.maxBufferedEvents??this.#U;K?.throwIfAborted();let Q=[],W=[],G=this.subscribe($,(Y)=>{let H=W.shift();if(H)H[0]({done:!1,value:Y});else if(Q.push(Y),Q.length>q)Q.shift()}),j=(Y)=>{G(),W.forEach((H)=>H[1](Y.target.reason)),W.length=0,Q.length=0};return K?.addEventListener("abort",j,{once:!0}),new T1(async()=>{if(K?.aborted)throw K.reason;if(Q.length>0)return{done:!1,value:Q.shift()};return new Promise((Y,H)=>{W.push([Y,H])})},async()=>{G(),K?.removeEventListener("abort",j),W.forEach((Y)=>Y[0]({done:!0,value:void 0})),W.length=0,Q.length=0})}}class PP{index=BigInt(1);generate(){let $=this.index.toString(36);return this.index++,$}}function O6($,U,K){let q=(Q,W)=>{let G=$[W];if(!G)return K(Q);return G({...Q,next:(j=Q)=>q(j,W+1)})};return q(U,0)}function T6($){if(!$)return;return JSON.parse($)}function q4($){return JSON.stringify($)}function uJ($){if(!Y1($))return null;return Object.getPrototypeOf($)?.constructor}function d0($){if(!$||typeof $!=="object")return!1;let U=Object.getPrototypeOf($);return U===Object.prototype||!U||!U.constructor}function Y1($){return!!$&&(typeof $==="object"||typeof $==="function")}function S6($,...U){if(typeof $==="function")return $(...U);return $}function S8($){return new Proxy($,{get(U,K,q){let Q=Reflect.get(U,K,q);if(K!=="then"||typeof Q!=="function")return Q;return new Proxy(Q,{apply(W,G,j){if(j.length!==2||j.some((H)=>!LP(H)))return Reflect.apply(W,G,j);let Y=!0;j[0].call(G,S8(new Proxy(U,{get:(H,X,B)=>{if(Y&&X==="then"){Y=!1;return}return Reflect.get(H,X,B)}})))}})}})}var NP=/^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;function LP($){return typeof $==="function"&&NP.test($.toString())}function fJ($){try{return decodeURIComponent($)}catch{return $}}var _P="@orpc/client",IP="1.15.0",mJ=new Set(["bind","valueOf","toString","toJSON"]),n0={BAD_REQUEST:{status:400,message:"Bad Request"},UNAUTHORIZED:{status:401,message:"Unauthorized"},FORBIDDEN:{status:403,message:"Forbidden"},NOT_FOUND:{status:404,message:"Not Found"},METHOD_NOT_SUPPORTED:{status:405,message:"Method Not Supported"},NOT_ACCEPTABLE:{status:406,message:"Not Acceptable"},TIMEOUT:{status:408,message:"Request Timeout"},CONFLICT:{status:409,message:"Conflict"},PRECONDITION_FAILED:{status:412,message:"Precondition Failed"},PAYLOAD_TOO_LARGE:{status:413,message:"Payload Too Large"},UNSUPPORTED_MEDIA_TYPE:{status:415,message:"Unsupported Media Type"},UNPROCESSABLE_CONTENT:{status:422,message:"Unprocessable Content"},TOO_MANY_REQUESTS:{status:429,message:"Too Many Requests"},CLIENT_CLOSED_REQUEST:{status:499,message:"Client Closed Request"},INTERNAL_SERVER_ERROR:{status:500,message:"Internal Server Error"},NOT_IMPLEMENTED:{status:501,message:"Not Implemented"},BAD_GATEWAY:{status:502,message:"Bad Gateway"},SERVICE_UNAVAILABLE:{status:503,message:"Service Unavailable"},GATEWAY_TIMEOUT:{status:504,message:"Gateway Timeout"}};function FP($,U){return U??n0[$]?.status??500}function xP($,U){return U||n0[$]?.message||$}var o0;class W4 extends Error{defined;code;status;data;static{let $=Symbol.for(`__${_P}@${IP}/error/ORPC_ERROR_CONSTRUCTORS__`);globalThis[$]??=new WeakSet,o0=globalThis[$],o0.add(W4)}constructor($,...U){let K=gJ(U);if(K.status!==void 0&&!p0(K.status))throw Error("[ORPCError] Invalid error status code.");let q=xP($,K.message);super(q,K);this.code=$,this.status=FP($,K.status),this.defined=K.defined??!1,this.data=K.data}toJSON(){return{defined:this.defined,code:this.code,status:this.status,message:this.message,data:this.data}}static[Symbol.hasInstance]($){if(o0.has(this)){let U=uJ($);if(U&&o0.has(U))return!0}return super[Symbol.hasInstance]($)}}function hJ($){return $ instanceof W4?$:new W4("INTERNAL_SERVER_ERROR",{message:"Internal server error",cause:$})}function p0($){return $<200||$>=400}function C8($){if(!d0($))return!1;let U=["defined","code","status","message","data"];if(Object.keys($).some((K)=>!U.includes(K)))return!1;return"defined"in $&&typeof $.defined==="boolean"&&"code"in $&&typeof $.code==="string"&&"status"in $&&typeof $.status==="number"&&p0($.status)&&"message"in $&&typeof $.message==="string"}function E8($,U={}){return new W4($.code,{...U,...$})}class C6 extends TypeError{}class cJ extends TypeError{}class w1 extends Error{data;constructor($){super($?.message??"An error event was received",$);this.data=$?.data}}var wP=/\r\n|\r(?!\n)|\n/,AP=/(?:\r\n|\r(?!\n)|\n){2}/,vP=/(?:\r\n|\r(?!\n)|\n){2}/g,kP=13,zP=10,RP=32;function bP($){let U={data:void 0,event:void 0,id:void 0,retry:void 0,comments:[]};for(let K of $.split(wP)){if(K==="")continue;let q=K.indexOf(":"),Q=q===-1?"":K.slice(K.charCodeAt(q+1)===RP?q+2:q+1);if(q===0){U.comments.push(Q);continue}switch(q===-1?K:K.slice(0,q)){case"data":U.data=U.data===void 0?Q:`${U.data}
|
|
34
|
+
${Q}`;break;case"event":U.event=Q;break;case"id":U.id=Q;break;case"retry":{let W=Number.parseInt(Q,10);if(W>=0&&W.toString()===Q)U.retry=W;break}}}return U}class lJ{constructor($={}){this.options=$}pending=[];tail="";discardLeadingLF=!1;feed($){if($==="")return;if(this.discardLeadingLF){if(this.discardLeadingLF=!1,$.charCodeAt(0)===zP){if($=$.slice(1),$==="")return}}let U=this.tail+$;if(!AP.test(U)){this.pending.push($),this.tail=U.slice(-3);return}this.pending.push($);let K=this.pending.length===1?$:this.pending.join(""),q=K.length-U.length,Q=[],W=0;for(let j of U.matchAll(vP))Q.push(K.slice(W,q+j.index)),W=q+j.index+j[0].length;let G=K.slice(W);if(this.pending.length=0,this.tail=G.slice(-3),G==="")this.discardLeadingLF=$.charCodeAt($.length-1)===kP;else this.pending.push(G);for(let j of Q){let Y=bP(j);if(this.options.onEvent)this.options.onEvent(Y)}}end(){if(this.pending.length!==0)throw new cJ("Event Iterator ended before complete")}}class y8 extends TransformStream{constructor(){let $;super({start(U){$=new lJ({onEvent:(K)=>{U.enqueue(K)}})},transform(U){$.feed(U)},flush(){$.end()}})}}var OP=/\r\n|[\n\r]/,TP=/\r\n|[\n\r]/g;function g8($){return OP.test($)}function rJ($){if(g8($))throw new C6("Event's id must not contain a carriage return or newline character")}function SP($){if(g8($))throw new C6("Event's event must not contain a carriage return or newline character")}function iJ($){if(!Number.isInteger($)||$<0)throw new C6("Event's retry must be a integer and >= 0")}function dJ($){if(g8($))throw new C6("Event's comment must not contain a carriage return or newline character")}function CP($){if($===void 0)return"";return`data: ${$.replace(TP,`
|
|
35
35
|
data: `)}
|
|
36
|
-
`}function
|
|
37
|
-
`;return U}function
|
|
38
|
-
`;if($.retry!==void 0)
|
|
39
|
-
`;if($.id!==void 0)
|
|
40
|
-
`;return U+=
|
|
41
|
-
`,U}var cG=Symbol("ORPC_EVENT_SOURCE_META");function J4($,U){if(U.id===void 0&&U.retry===void 0&&!U.comments?.length)return $;if(U.id!==void 0)fG(U.id);if(U.retry!==void 0)mG(U.retry);if(U.comments!==void 0)for(let K of U.comments)hG(K);return new Proxy($,{get(K,q,Q){if(q===cG)return U;return Reflect.get(K,q,Q)}})}function O4($){return Y1($)?Reflect.get($,cG):void 0}function lG($,U="inline"){let K=$.replace(/[^\x20-\x7E]/g,"_").replace(/"/g,"\\\""),q=encodeURIComponent($).replace(/['()*]/g,(Q)=>`%${Q.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(7C|60|5E)/g,(Q,W)=>String.fromCharCode(Number.parseInt(W,16)));return`${U}; filename="${K}"; filename*=utf-8''${q}`}function rG($){let U=$.match(/filename\*=(UTF-8'')?([^;]*)/i);if(U&&typeof U[2]==="string")return CG(U[2]);let K=$.match(/filename="((?:\\"|[^"])*)"/i);if(K&&typeof K[1]==="string")return K[1].replace(/\\"/g,'"')}function iG($,U){let K={...$};for(let q in U)if(Array.isArray(U[q]))K[q]=[...Q4(K[q]),...U[q]];else if(U[q]!==void 0)if(Array.isArray(K[q]))K[q]=[...K[q],U[q]];else if(K[q]!==void 0)K[q]=[K[q],U[q]];else K[q]=U[q];return K}function y3($,U){let K=async(q)=>{let Q=await U.error(q);if(Q!==q){let W=O4(q);if(W&&Y1(Q))Q=J4(Q,W)}return Q};return new T1(async()=>{let{done:q,value:Q}=await(async()=>{try{return await $.next()}catch(J){throw await K(J)}})(),W=await U.value(Q,q);if(W!==Q){let J=O4(Q);if(J&&Y1(W))W=J4(W,J)}return{done:q,value:W}},async()=>{try{await $.return?.()}catch(q){throw await K(q)}})}function kP($){return{...$,context:$.context??{}}}function S1($,U){return(async()=>{let K;try{let q=await $;while(!0){let{done:Q,value:W}=await q.next();if(Q){let J=W;K=[null,J,!0],U.onSuccess?.(J);break}U.onEvent(W)}}catch(q){if(K=[q,void 0,!1],!U.onError&&!U.onFinish)throw q;U.onError?.(q)}finally{U.onFinish?.(K)}})(),async()=>{await(await $)?.return?.()}}function G4($,U={}){let K=U.path??[],Q=new Proxy(async(...[W,J={}])=>{return await $.call(K,W,kP(J))},{get(W,J){if(typeof J!=="string"||EG.has(J))return Reflect.get(W,J);return G4($,{...U,path:[...K,J]})}});return O3(Q)}function RP($,U={}){let q=$?.pipeThrough(new TextDecoderStream).pipeThrough(new C3)?.getReader(),Q,W=!1;return new T1(async()=>{Q??=r0("consume_event_iterator_stream");try{while(!0){if(q===void 0)return{done:!0,value:void 0};let{done:J,value:j}=await U4(Q,()=>q.read());if(J){if(W)throw new z3("Stream was cancelled");return{done:!0,value:void 0}}switch(j.event){case"message":{let Y=O6(j.data);if(Y1(Y))Y=J4(Y,j);return Q?.addEvent("message"),{done:!1,value:Y}}case"error":{let Y=new w1({data:O6(j.data)});throw Y=J4(Y,j),Q?.addEvent("error"),Y}case"done":{let Y=O6(j.data);if(Y1(Y))Y=J4(Y,j);return Q?.addEvent("done"),{done:!0,value:Y}}default:Q?.addEvent("maybe_keepalive")}}}catch(J){if(!(J instanceof w1))O1(Q,J,U);throw J}},async(J)=>{try{if(J!=="next")W=!0,Q?.addEvent("cancelled");await U4(Q,()=>q?.cancel())}catch(j){throw O1(Q,j,U),j}finally{Q?.end()}})}function zP($,U={}){let K=U.eventIteratorKeepAliveEnabled??!0,q=U.eventIteratorKeepAliveInterval??5000,Q=U.eventIteratorKeepAliveComment??"",W=U.eventIteratorInitialCommentEnabled??!0,J=U.eventIteratorInitialComment??"",j=!1,Y,H;return new ReadableStream({start(B){if(H=r0("stream_event_iterator"),W)B.enqueue(C6({comments:[J]}))},async pull(B){try{if(K)Y=setInterval(()=>{B.enqueue(C6({comments:[Q]})),H?.addEvent("keepalive")},q);let M=await U4(H,()=>$.next());if(clearInterval(Y),j)return;let I=O4(M.value);if(!M.done||M.value!==void 0||I!==void 0){let E=M.done?"done":"message";B.enqueue(C6({...I,event:E,data:q4(M.value)})),H?.addEvent(E)}if(M.done)B.close(),H?.end()}catch(M){if(clearInterval(Y),j)return;if(M instanceof w1)B.enqueue(C6({...O4(M),event:"error",data:q4(M.data)})),H?.addEvent("error"),B.close();else O1(H,M),B.error(M);H?.end()}},async cancel(){try{j=!0,clearInterval(Y),H?.addEvent("cancelled"),await U4(H,()=>$.return?.())}catch(B){throw O1(H,B),B}finally{H?.end()}}}).pipeThrough(new TextEncoderStream)}function bP($,U={}){return K4({name:"parse_standard_body",signal:U.signal},async()=>{let K=$.headers.get("content-disposition");if(typeof K==="string"){let W=rG(K)??"blob",J=await $.blob();return new File([J],W,{type:J.type})}let q=$.headers.get("content-type");if(!q||q.startsWith("application/json")){let W=await $.text();return O6(W)}if(q.startsWith("multipart/form-data"))return await $.formData();if(q.startsWith("application/x-www-form-urlencoded")){let W=await $.text();return new URLSearchParams(W)}if(q.startsWith("text/event-stream"))return RP($.body,U);if(q.startsWith("text/plain"))return await $.text();let Q=await $.blob();return new File([Q],"blob",{type:Q.type})})}function OP($,U,K={}){if($ instanceof ReadableStream)return $;let q=U.get("content-disposition");if(U.delete("content-type"),U.delete("content-disposition"),$===void 0)return;if($ instanceof Blob)return U.set("content-type",$.type),U.set("content-length",$.size.toString()),U.set("content-disposition",q??lG($ instanceof File?$.name:"blob")),$;if($ instanceof FormData)return $;if($ instanceof URLSearchParams)return $;if(x1($))return U.set("content-type","text/event-stream"),zP($,K);return U.set("content-type","application/json"),q4($)}function g3($,U={}){return $.forEach((K,q)=>{if(Array.isArray(U[q]))U[q].push(K);else if(U[q]!==void 0)U[q]=[U[q],K];else U[q]=K}),U}function TP($,U=new Headers){for(let[K,q]of Object.entries($))if(Array.isArray(q))for(let Q of q)U.append(K,Q);else if(q!==void 0)U.append(K,q);return U}function dG($,U={}){let K=TP($.headers),q=OP($.body,K,U);return new Request($.url,{signal:$.signal,method:$.method,headers:K,body:q})}function oG($,U={}){return{body:l0(()=>bP($,U)),status:$.status,get headers(){let K=g3($.headers);return Object.defineProperty(this,"headers",{value:K,writable:!0}),K},set headers(K){Object.defineProperty(this,"headers",{value:K,writable:!0})}}}class p0{plugins;constructor($=[]){this.plugins=[...$].sort((U,K)=>(U.order??0)-(K.order??0))}init($){for(let U of this.plugins)U.init?.($)}}class nG{constructor($,U,K={}){this.codec=$,this.sender=U,new p0(K.plugins).init(K),this.interceptors=Q4(K.interceptors),this.clientInterceptors=Q4(K.clientInterceptors)}interceptors;clientInterceptors;call($,U,K){return K4({name:`${R3}.${$.join("/")}`,signal:K.signal},(q)=>{if(q?.setAttribute("rpc.system",R3),q?.setAttribute("rpc.method",$.join(".")),x1(U))U=b3({name:"consume_event_iterator_input",signal:K.signal},U);return b6(this.interceptors,{...K,path:$,input:U},async({path:Q,input:W,...J})=>{let j=z6(),Y,H=j?.trace.getActiveSpan()??q;if(H&&j)Y=j?.trace.setSpan(j.context.active(),H);let Z=await K4({name:"encode_request",context:Y},()=>this.codec.encode(Q,W,J)),B=await b6(this.clientInterceptors,{...J,input:W,path:Q,request:Z},({input:I,path:E,request:u,...U$})=>{return K4({name:"send_request",signal:U$.signal,context:Y},()=>this.sender.call(u,U$,E,I))}),M=await K4({name:"decode_response",context:Y},()=>this.codec.decode(B,J,Q,W));if(x1(M))return b3({name:"consume_event_iterator_output",signal:J.signal},M);return M})})}}var F$={BIGINT:0,DATE:1,NAN:2,UNDEFINED:3,URL:4,REGEXP:5,SET:6,MAP:7};class pG{customSerializers;constructor($={}){if(this.customSerializers=$.customJsonSerializers??[],this.customSerializers.length!==new Set(this.customSerializers.map((U)=>U.type)).size)throw Error("Custom serializer type must be unique.")}serialize($,U=[],K=[],q=[],Q=[]){for(let W of this.customSerializers)if(W.condition($)){let J=this.serialize(W.serialize($),U,K,q,Q);return K.push([W.type,...U]),J}if($ instanceof Blob)return q.push(U),Q.push($),[$,K,q,Q];if(typeof $==="bigint")return K.push([F$.BIGINT,...U]),[$.toString(),K,q,Q];if($ instanceof Date){if(K.push([F$.DATE,...U]),Number.isNaN($.getTime()))return[null,K,q,Q];return[$.toISOString(),K,q,Q]}if(Number.isNaN($))return K.push([F$.NAN,...U]),[null,K,q,Q];if($ instanceof URL)return K.push([F$.URL,...U]),[$.toString(),K,q,Q];if($ instanceof RegExp)return K.push([F$.REGEXP,...U]),[$.toString(),K,q,Q];if($ instanceof Set){let W=this.serialize(Array.from($),U,K,q,Q);return K.push([F$.SET,...U]),W}if($ instanceof Map){let W=this.serialize(Array.from($.entries()),U,K,q,Q);return K.push([F$.MAP,...U]),W}if(Array.isArray($))return[$.map((J,j)=>{if(J===void 0)return K.push([F$.UNDEFINED,...U,j]),null;return this.serialize(J,[...U,j],K,q,Q)[0]}),K,q,Q];if(i0($)){let W={};for(let J in $){if(J==="toJSON"&&typeof $[J]==="function")continue;W[J]=this.serialize($[J],[...U,J],K,q,Q)[0]}return[W,K,q,Q]}return[$,K,q,Q]}deserialize($,U,K,q){let Q={data:$};if(K&&q)K.forEach((W,J)=>{let j=Q,Y="data";W.forEach((H)=>{if(j=j[Y],Y=H,!Object.hasOwn(j,Y))throw Error(`Security error: accessing non-existent path during deserialization. Path segment: ${Y}`)}),j[Y]=q(J)});for(let W of U){let J=W[0],j=Q,Y="data";for(let H=1;H<W.length;H++)if(j=j[Y],Y=W[H],!Object.hasOwn(j,Y))throw Error(`Security error: accessing non-existent path during deserialization. Path segment: ${Y}`);for(let H of this.customSerializers)if(H.type===J){j[Y]=H.deserialize(j[Y]);break}switch(J){case F$.BIGINT:j[Y]=BigInt(j[Y]);break;case F$.DATE:j[Y]=new Date(j[Y]??"Invalid Date");break;case F$.NAN:j[Y]=Number.NaN;break;case F$.UNDEFINED:j[Y]=void 0;break;case F$.URL:j[Y]=new URL(j[Y]);break;case F$.REGEXP:{let[,H,Z]=j[Y].match(/^\/(.*)\/([a-z]*)$/);j[Y]=new RegExp(H,Z);break}case F$.SET:j[Y]=new Set(j[Y]);break;case F$.MAP:j[Y]=new Map(j[Y]);break}}return Q.data}}function SP($){return`/${$.map(encodeURIComponent).join("/")}`}function CP($){if(typeof $.forEach==="function")return g3($);return $}function EP($){return Object.entries(o0).find(([,U])=>U.status===$)?.[0]??"MALFORMED_ORPC_ERROR_RESPONSE"}class tG{constructor($,U){this.serializer=$,this.baseUrl=U.url,this.maxUrlLength=U.maxUrlLength??2083,this.fallbackMethod=U.fallbackMethod??"POST",this.expectedMethod=U.method??this.fallbackMethod,this.headers=U.headers??{}}baseUrl;maxUrlLength;fallbackMethod;expectedMethod;headers;async encode($,U,K){let q=CP(await T6(this.headers,K,$,U));if(K.lastEventId!==void 0)q=iG(q,{"last-event-id":K.lastEventId});let Q=await T6(this.expectedMethod,K,$,U),W=await T6(this.baseUrl,K,$,U),J=new URL(W);J.pathname=`${J.pathname.replace(/\/$/,"")}${SP($)}`;let j=this.serializer.serialize(U);if(Q==="GET"&&!(j instanceof FormData)&&!x1(j)){let Y=await T6(this.maxUrlLength,K,$,U),H=new URL(J);if(H.searchParams.append("data",q4(j)),H.toString().length<=Y)return{body:void 0,method:Q,headers:q,url:H,signal:K.signal}}return{url:J,method:Q==="GET"?this.fallbackMethod:Q,headers:q,body:j,signal:K.signal}}async decode($){let U=!n0($.status),K=await(async()=>{let q=!1;try{let Q=await $.body();return q=!0,this.serializer.deserialize(Q)}catch(Q){if(!q)throw Error("Cannot parse response body, please check the response body and content-type.",{cause:Q});throw Error("Invalid RPC response format.",{cause:Q})}})();if(!U){if(T3(K))throw S3(K);throw new W4(EP($.status),{status:$.status,data:{...$,body:K}})}return K}}class aG{constructor($){this.jsonSerializer=$}serialize($){if(x1($))return y3($,{value:async(U)=>this.#$(U,!1),error:async(U)=>{return new w1({data:this.#$(yG(U).toJSON(),!1),cause:U})}});return this.#$($,!0)}#$($,U){let[K,q,Q,W]=this.jsonSerializer.serialize($),J=q.length===0?void 0:q;if(!U||W.length===0)return{json:K,meta:J};let j=new FormData;return j.set("data",q4({json:K,meta:J,maps:Q})),W.forEach((Y,H)=>{j.set(H.toString(),Y)}),j}deserialize($){if(x1($))return y3($,{value:async(U)=>this.#U(U),error:async(U)=>{if(!(U instanceof w1))return U;let K=this.#U(U.data);if(T3(K))return S3(K,{cause:U});return new w1({data:K,cause:U})}});return this.#U($)}#U($){if($===void 0)return;if(!($ instanceof FormData))return this.jsonSerializer.deserialize($.json,$.meta??[]);let U=JSON.parse($.get("data"));return this.jsonSerializer.deserialize(U.json,U.meta??[],U.maps,(K)=>$.get(K.toString()))}}class u3 extends nG{constructor($,U){let K=new pG(U),q=new aG(K),Q=new tG(q,U);super(Q,$,U)}}class sG extends p0{initRuntimeAdapter($){for(let U of this.plugins)U.initRuntimeAdapter?.($)}}class eG{fetch;toFetchRequestOptions;adapterInterceptors;constructor($){new sG($.plugins).initRuntimeAdapter($),this.fetch=$.fetch??globalThis.fetch.bind(globalThis),this.toFetchRequestOptions=$,this.adapterInterceptors=Q4($.adapterInterceptors)}async call($,U,K,q){let Q=dG($,this.toFetchRequestOptions),W=await b6(this.adapterInterceptors,{...U,request:Q,path:K,input:q,init:{redirect:"manual"}},({request:j,path:Y,input:H,init:Z,...B})=>this.fetch(j,Z,B,Y,H));return oG(W,{signal:Q.signal})}}class j4 extends u3{constructor($){let U=new eG($);super(U,$)}}import{chmodSync as f3,mkdirSync as $j,readFileSync as yP,writeFileSync as m3}from"node:fs";import{homedir as gP}from"node:os";import{join as Uj}from"node:path";function T4($){let U=$.length;while(U>0&&$[U-1]==="/")U-=1;return $.slice(0,U)}var h3=Uj(gP(),".niva"),Y4=Uj(h3,"config.json");function E6(){try{let $=JSON.parse(yP(Y4,"utf-8"));return G$($)?$:{}}catch{return{}}}function Qj($,U){$j(h3,{recursive:!0});let q={...E6(),[$]:U};m3(Y4,`${JSON.stringify(q,null,2)}
|
|
42
|
-
`,{mode:384}),
|
|
43
|
-
`,{mode:384}),
|
|
44
|
-
`,{mode:384}),f3(Y4,384)}import{createHash as fP,randomBytes as Jj}from"node:crypto";import{createServer as mP}from"node:http";var hP=600000,cP=120,lP=5;class L$ extends Error{code;constructor($,U){super(U);this.code=$}}function rP($){let U=Q$($),K=l(U?.access_token),q=p1(U?.expires_in);if(U==null||K==null||q==null)return null;let Q=l(U.refresh_token),W=l(U.scope);return{access_token:K,expires_in:q,...Q!=null?{refresh_token:Q}:{},...W!=null?{scope:W}:{}}}function Gj($,U){let K=Q$($),q=l(K?.error)??`http_${String(U)}`,Q=l(K?.error_description)??q;return new L$(q,Q)}function iP(){return Jj(32).toString("base64url")}function dP($){return fP("sha256").update($).digest("base64url")}function jj($,U){if($.NIVA_NO_BROWSER==="1")return!1;let K=$.CI;if(K==="true"||K==="1")return!1;if(U==="linux")return $.DISPLAY!=null||$.WAYLAND_DISPLAY!=null;return!0}function r3($){let U;if(process.platform==="darwin")U=[["open",$]];else if(process.platform==="win32")U=[["cmd","/c","start","",$]];else U=[["xdg-open",$]];for(let K of U){let[q,...Q]=K;if(q==null)continue;try{return Bun.spawn([q,...Q],{stdout:"ignore",stderr:"ignore"}).exited.then((J)=>{if(J!==0)Wj($)}),!0}catch{continue}}return Wj($),!1}function Wj($){console.error(`Open this URL to continue: ${$}`)}async function i3($){let U=new URL("/.well-known/oauth-authorization-server",T4($)),K=await fetch(U),q=await K.json().catch(()=>({})),Q=Q$(q),W=l(Q?.issuer),J=l(Q?.authorization_endpoint),j=l(Q?.token_endpoint);if(!K.ok||Q==null||W==null||J==null||j==null)throw new L$("discovery_failed",`Could not read OAuth metadata from ${$}`);let Y=l(Q.device_authorization_endpoint);return{issuer:W,authorization_endpoint:J,token_endpoint:j,...Y!=null?{device_authorization_endpoint:Y}:{}}}async function d3($,U){let K=await fetch($,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(U).toString()}),q=await K.json().catch(()=>({}));if(!K.ok)throw Gj(q,K.status);let Q=rP(q);if(Q==null)throw new L$("invalid_response","The token endpoint answered an unexpected body");return Q}function oP($){return(U,K)=>{let q=new URL(U.url??"/","http://127.0.0.1");if(q.pathname!=="/callback"){K.writeHead(404).end();return}K.writeHead(200,{"content-type":"text/html; charset=utf-8"}),K.end("<html><body><p>Login complete. You can close this tab and go back to the terminal.</p></body></html>");let Q=q.searchParams.get("code"),W=q.searchParams.get("state"),J=q.searchParams.get("iss")??void 0,j=q.searchParams.get("error");if(j!=null)$({error:j});else if(Q!=null&&W!=null)$({code:Q,state:W,iss:J});else $({error:"invalid_request"})}}function nP($,U){return new Promise((K,q)=>{let Q=setTimeout(()=>{$.current=null,U(),q(new L$("timeout","Timed out waiting for the browser callback"))},hP);$.current=(W)=>{if(clearTimeout(Q),U(),"error"in W)q(new L$(W.error,`Authorization failed: ${W.error}`));else K(W)}})}function pP(){return new Promise(($,U)=>{let K={current:null},q=mP(oP((W)=>K.current?.(W))),Q=async()=>nP(K,()=>q.close());q.on("error",U),q.listen(0,"127.0.0.1",()=>{let W=q.address();if(W==null||typeof W==="string"){U(Error("Could not bind the loopback listener"));return}$({redirectUri:`http://127.0.0.1:${W.port}/callback`,waitForCode:Q,close:()=>q.close()})})})}async function Yj($,U){let K=await pP(),q=iP(),Q=Jj(16).toString("base64url"),W=new URL($.authorization_endpoint);W.searchParams.set("response_type","code"),W.searchParams.set("client_id",U.clientId),W.searchParams.set("redirect_uri",K.redirectUri),W.searchParams.set("scope",U.scopes.join(" ")),W.searchParams.set("state",Q),W.searchParams.set("code_challenge",dP(q)),W.searchParams.set("code_challenge_method","S256"),W.searchParams.set("resource",U.resource);try{r3(W.href);let J=await K.waitForCode();if(J.state!==Q)throw new L$("state_mismatch","The state returned by the server does not match");if(J.iss!=null&&J.iss!==$.issuer)throw new L$("issuer_mismatch","The issuer returned by the server does not match");return await d3($.token_endpoint,{grant_type:"authorization_code",code:J.code,redirect_uri:K.redirectUri,client_id:U.clientId,code_verifier:q})}finally{K.close()}}function tP($){let U=Q$($);if(U==null)return null;let K=["device_code","user_code","verification_uri","verification_uri_complete"].map((Q)=>l(U[Q])),q=["expires_in","interval"].map((Q)=>p1(U[Q]));if(K.some((Q)=>Q==null)||q.some((Q)=>Q==null))return null;return{device_code:K[0],user_code:K[1],verification_uri:K[2],verification_uri_complete:K[3],expires_in:q[0],interval:q[1]}}async function Hj($,U){let K=$.device_authorization_endpoint;if(K==null)throw new L$("unsupported_grant_type","This server does not support the device flow");let q=await fetch(K,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:U.clientId,scope:U.scopes.join(" "),resource:U.resource}).toString()}),Q=await q.json().catch(()=>({})),W=q.ok?tP(Q):null;if(W==null)throw q.ok?new L$("invalid_response","The device authorization endpoint answered an unexpected body"):Gj(Q,q.status);return W}async function Xj($,U,K){let q=U.interval*1000,Q=Date.now()+U.expires_in*1000;while(Date.now()<Q){await Bun.sleep(q);try{return await d3($,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:U.device_code,client_id:K})}catch(W){if(W instanceof L$){if(W.code==="authorization_pending")continue;if(W.code==="slow_down"){q+=lP*1000;continue}}throw W}}throw new L$("expired_token","The device code expired before authorization completed")}function t0($,U=Math.floor(Date.now()/1000)){return $.expires_at-U<cP}async function a0($,U){let K=await i3($),q=await d3(K.token_endpoint,{grant_type:"refresh_token",refresh_token:U.refresh_token,client_id:"niva-cli"});if(q.refresh_token==null)throw new L$("invalid_grant","The server did not return a refresh token");return{access_token:q.access_token,refresh_token:q.refresh_token,expires_at:Math.floor(Date.now()/1000)+q.expires_in,org_id:U.org_id,scopes:q.scope!=null?q.scope.split(" ").filter((Q)=>Q!==""):U.scopes}}function o3($){try{let{hostname:U}=new URL($);return U.endsWith(".orb.local")||process.env.NIVA_INSECURE==="true"}catch{return!1}}class Zj extends Error{constructor(){super("Your session has expired. Run 'niva login' to authenticate again.")}}function aP($){let U=$.fetchImpl??fetch,K=async()=>{try{return await $.refresh()}catch(q){if(q instanceof L$)throw new Zj;throw q}};return async(q)=>{let Q=$.getSession();if(t0(Q))Q=await K();let W=new Request(q);W.headers.set("authorization",`Bearer ${Q.access_token}`);let J=await U(W);if(J.status===401){Q=await K();let j=new Request(q);j.headers.set("authorization",`Bearer ${Q.access_token}`),J=await U(j)}return J}}function n3($,U,K){if(o3($))process.env.NODE_TLS_REJECT_UNAUTHORIZED="0";if(U.kind!=="oauth"){let W=new j4({url:new URL("/api/rpc",$).href,headers:()=>U.kind==="api-key"?{"X-API-Key":U.apiKey}:{}});return G4(W)}let q=U.session,Q=new j4({url:new URL("/api/rpc",$).href,fetch:aP({getSession:()=>q,refresh:async()=>{return q=await a0(K,q),C4(K,q),q}})});return G4(Q)}var p3="niva-cli",sP=["*:read","*:write","offline_access"],eP=["*:read","offline_access"];function Bj($,U){return{access_token:$.access_token,refresh_token:$.refresh_token??"",expires_at:Math.floor(Date.now()/1000)+$.expires_in,org_id:U,scopes:$.scope!=null?$.scope.split(" ").filter((K)=>K!==""):[]}}async function $N($,U){return(await n3($,{kind:"oauth",session:Bj(U,"")},$).oauth.whoami()).organization?.id??""}function Vj($,U,K){$.command("login").description("Authenticate with the server (browser by default, device flow with --device)").option("--device","Force the device flow (RFC 8628) even when a browser is available").option("--read-only","Request read-only scopes").action(async(q)=>{let Q=S4(U().url);if(!Q.startsWith("https://"))$1("Server URL is not https: tokens travel unencrypted on this network.");let W=q.readOnly===!0?eP:sP,J=`${Q}/api`,j=await i3(Q),Y={scopes:W,resource:J,clientId:p3},H,Z=jj(process.env,process.platform);if(q.device===!0||!Z){let M=await Hj(j,Y);if(z(`Open ${M.verification_uri} and enter the code: ${M.user_code}`),Z)r3(M.verification_uri_complete);H=await Xj(j.token_endpoint,M,p3)}else H=await Yj(j,Y);let B=await $N(Q,H);C4(Q,Bj(H,B)),T(`Logged in to ${Q}`)}),$.command("logout").description("Revoke the saved session and remove it from the config file").action(async()=>{let q=S4(U().url),Q=Kj()[q];if(Q==null){z(`No saved session for ${q}`);return}try{await fetch(new URL("/oauth/revoke",q),{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:Q.refresh_token,client_id:p3}).toString()})}catch{$1("Could not reach the server to revoke the token; clearing the local session anyway.")}qj(q),T(`Logged out of ${q}`)}),$.command("whoami").description("Show the authenticated user, organization, scopes and token expiry").action(async()=>{let q=S4(U().url),Q=K();if(Q.kind==="none"){x(`No credential configured for ${q}. Run 'niva login' first.`),process.exitCode=1;return}let J=await n3(q,Q,q).oauth.whoami();P({url:q,user:J.user.email,organization:J.organization?.name,scopes:J.scopes,credential:J.credential,...Q.kind==="oauth"?{expires_at:new Date(Q.session.expires_at*1000).toISOString()}:{}})})}var a=N1(I1(),1);var UN=/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i,Mj=4;async function s0($,U){if(UN.test(U))return U;if(U.length<Mj)x(`UUID prefix too short — provide at least ${Mj} characters.`),process.exit(w.USAGE_ERROR);let K=await N($.dashboard.activeCalls()),q=U.toLowerCase(),Q=K.filter((W)=>W.uuid.toLowerCase().startsWith(q));if(Q.length===0)x(`No active call matching "${U}".`),process.exit(w.NOT_FOUND);if(Q.length>1){x(`Ambiguous UUID prefix "${U}" — matches ${Q.length} calls. Be more specific.`);for(let W of Q)z(` ${W.uuid} ${W.callerId}`);process.exit(w.USAGE_ERROR)}return Q[0].uuid}var QN={no_credential:"Live transcription is not configured on this platform.",not_recorded:"This call is not being recorded.",test_call:"Test calls are not recorded, so they cannot be transcribed live."};function KN($){let U=Math.max(0,Math.floor($)),K=Math.floor(U/60),q=U%60;return`${String(K).padStart(2,"0")}:${String(q).padStart(2,"0")}`}function qN($){if($==null)return"—";return`${KN($.at_seconds)}${$.late?" (late)":""}`}function Nj($,U){let K=$.command("calls").description("Manage calls");K.command("list").description("List active calls").action(async()=>{let{format:q,fields:Q}=L($.opts()),W=await N(U().dashboard.activeCalls());if(q==="json"){let J=Q?W.map((j)=>O(j,Q)):W;P(J);return}if(W.length===0){z("No active calls.");return}y(["UUID","Caller","Plan","Duration"],W.map((J)=>({UUID:J.uuid,Caller:J.callerId,Plan:J.planName??"—",Duration:J.startedAt?`${Math.round((Date.now()-new Date(J.startedAt).getTime())/1000)}s`:"—"})))}),K.command("show <call_record_id>").description("Show call details from CDR (rich detail view)").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),J=await N(U().callRecords.getById({call_record_id:A("call_records",q)}));if(Q==="json"){let j=W&&J!=null?O(J,W):J;P(j);return}if(J==null){z("Call record not found.");return}o([{title:"Call Record",rows:JN(J)}])}),K.command("hangup <call>").description("Hang up an active call by TypeID (call_...), full channel UUID, or UUID prefix").action(async(q)=>{let{format:Q}=L($.opts()),W=U(),J=q,j;if(q.startsWith("call_"))j=await N(W.calls.hangupCall({call_id:A("call_records",q)}));else J=await s0(W,q),j=await N(W.calls.hangupActiveCall({uuid:J}));if(Q==="json"){P(j);return}T(`Call ${J} terminated.`)}),K.command("signals <call_record_id>").description("Show the signal results of a recorded call").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),J=await N(U().signals.callSignals({call_id:A("call_records",q)}));if(Q==="json"){let j=W?J.map((Y)=>O(Y,W)):J;P(j);return}if(J.length===0){z("No signal results for this call.");return}y(["Signal","Value","Confidence","Triggered at","Severity"],J.map((j)=>({Signal:j.signal.name,Value:j.value_label??"—",Confidence:j.confidence==null?"—":`${Math.round(j.confidence*100)}%`,"Triggered at":qN(j.trigger),Severity:j.definition.alert?.severity??"—"})))}),K.command("search").description("Search CDR records").option("--caller <caller>","Filter by caller ID").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),J=await N(U().callRecords.list({page:Number(q.page),limit:Number(q.limit),search:q.caller}));if(Q==="json"){let j=W?J.items.map((Y)=>O(Y,W)):J;P(j);return}y(["ID","Caller","Callee","Duration","Disposition","Date"],J.items.map((j)=>({ID:j.id,Caller:j.caller_id??"—",Callee:j.callee_id??"—",Duration:f$(j.duration_ms),Disposition:j.hangup_disposition??"—",Date:new Date(j.started_at).toLocaleString()}))),H$(J)}),K.command("follow <uuid>").description("Follow live transcription of an active call").action(async(q)=>{let{format:Q}=L($.opts()),W=U(),J=await s0(W,q),j=new AbortController;process.on("SIGINT",()=>{j.abort()});let Y=!1,H=!1;function Z(M){B();let I=Lj(M);process.stdout.write(a.default.dim(I)),H=!0}function B(){if(!H)return;process.stdout.clearLine(0),process.stdout.cursorTo(0),H=!1}await new Promise((M,I)=>{S1(W.dashboard.watchLiveTranscription({uuid:J},{signal:j.signal}),{onEvent:(E)=>{if(Y=!0,Q==="json"){P(E);return}switch(E.type){case"starting":z("Connecting...");break;case"started":z("Transcription started.");break;case"caught_up":break;case"unavailable":z(QN[E.reason]),M();break;case"ended":B(),z("Transcription ended."),M();break;case"error":console.error(a.default.red(`Error: ${E.message}`));break;case"history":for(let u of E.segments)Dj(u);for(let u of E.signals??[])Pj(u);break;case"signal_value":case"signal_triggered":Pj(E);break;case"segment":if(E.segment.isFinal)B(),Dj(E.segment);else Z(E.segment);break}},onError:(E)=>{if(E instanceof DOMException&&E.name==="AbortError"){B(),M();return}I(E)},onSuccess:()=>{if(!Y)z("Live transcription not available for this call.");M()}})}).catch((M)=>{B(),z4(M)})}),K.command("transfer <uuid> <destination>").description("Transfer an active call").action(()=>F1()),K.command("spy <uuid>").description("Spy on an active call").action(()=>F1()),K.command("history").description("List call records with rich filters and display").option("--from <date>","Start date (YYYY-MM-DD)").option("--to <date>","End date (YYYY-MM-DD)").option("--plan <id>","Filter by visual plan ID").option("--phone <id>","Filter by phone number ID").option("--status <status>","Filter by disposition (answered, missed, failed, busy)").option("--caller <search>","Search by caller ID").option("--min-duration <seconds>","Minimum duration in seconds").option("--max-duration <seconds>","Maximum duration in seconds").option("--has-recording","Only calls with recording").option("--has-transcription","Only calls with transcription").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),J=await N(U().callRecords.list({page:Number(q.page),limit:Number(q.limit),date_from:q.from,date_to:q.to,visual_plan_id:A("visual_plans",q.plan),channel_id:A("channels",q.phone),status:q.status,caller_search:q.caller,min_duration:q.minDuration!=null?Number(q.minDuration):void 0,max_duration:q.maxDuration!=null?Number(q.maxDuration):void 0,has_recording:q.hasRecording,has_transcription:q.hasTranscription}));if(Q==="json"){if(W)P(J.items.map((j)=>O(j,W)));else P(J);return}if(J.items.length===0){z("No call records found.");return}y(["ID","Caller","Direction","Duration","Status","Sentiment","Plan","Date"],J.items.map((j)=>{let Y=j.sentiment_score!=null?Number(j.sentiment_score):null;return{ID:j.id,Caller:j.caller_id??"—",Direction:j.direction??"—",Duration:f$(j.duration_ms),Status:N3(j.hangup_disposition),Sentiment:j.sentiment_label!=null?L3(j.sentiment_label,Y):"—",Plan:j.visual_plan_name??"—",Date:j1(j.started_at)}})),H$(J)}),K.command("trace <call_record_id>").description("Show node-by-node execution trace for a call").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),J=await N(U().callRecords.getTrace({call_record_id:A("call_records",q)}));if(Q==="json"){let M=W&&J!=null?O(J,W):J;P(M);return}if(J==null){z("Call trace not found.");return}let j=J.callRecord;if(console.log(`${a.default.bold("Call Trace")} — ${q} (${f$(j.duration_ms)}, ${j.hangup_disposition??"unknown"})`),j.visual_plan_name!=null)console.log(`Plan: ${j.visual_plan_name}`);console.log("");let Y=J.events;if(Y.length===0){z(" No events recorded (0 nodes visited).");return}let H=Y.map((M,I)=>{let E=M.duration_ms!=null?`${(M.duration_ms/1000).toFixed(1)}s`:"—",u=`${a.default.cyan(M.node_type)}`;if(M.node_label!=null){let S$=a.default.bold(`"${M.node_label}"`);u+=` ${S$}`}if(u+=a.default.dim(` (${E})`),M.digit!=null)u+=` → digit: ${a.default.yellow(M.digit)}`;let U$=[];if(M.handle_used!=null)U$.push(a.default.dim(`└─→ ${M.handle_used}`));if(G$(M.data)){let S$=Object.entries(M.data).filter(([,k4])=>k4!=null&&typeof k4!=="object").map(([k4,i$])=>`${k4}: ${String(i$)}`);if(S$.length>0)U$.push(a.default.dim(`└─ ${S$.join(", ")}`))}return{label:u,children:U$.length>0?U$:void 0}});_3(H),console.log("");let Z=Y.at(-1),B=Z.node_label??Z.node_type;z(` ${Y.length} nodes visited · Last: ${Z.node_type} "${B}" · Hangup: ${j.hangup_cause??"—"}`)}),K.command("transcript <call_record_id>").description("Show call transcription with speech analytics").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),J=await N(U().ai.getTranscription({call_record_id:A("call_records",q)}));if(Q==="json"){let H=W&&J!=null?O(J,W):J;P(H);return}console.log(`${a.default.bold("Transcript")} — ${q}`),console.log("");let j=jN(J?.segments);if(j.length===0||J?.status==="disabled")z(" No transcript available.");else QG(j);let Y=J!=null?YN(J):[];if(Y.length>0)console.log(""),o([{title:"Speech Analytics",rows:Y}])}),K.command("purge-voice <call_record_id>").description("Permanently erase a call's voice content (recording, transcription, embeddings)").action(async(q)=>{let{format:Q}=L($.opts()),W=$.opts().yes===!0;if(Q!=="json")console.log(`${a.default.bold("Erase voice content")} — ${q}`),z(" Deletes: recording file, transcription and its semantic-search embeddings."),z(" Keeps: the call record (CDR), its event timeline and existing analyses."),z(" This is irreversible."),console.log("");await d$("Erase the voice content of this call?",{yes:W});let J=await N(U().callRecords.purgeVoiceContent({call_record_id:A("call_records",q)}));if(Q==="json"){P(J);return}T("Voice content erased"),o([{title:"Deleted",rows:[{label:"Recording",value:String(J.deleted.recording)},{label:"Transcriptions",value:String(J.deleted.transcriptions)},{label:"Embeddings",value:String(J.deleted.embeddings)},{label:"Analyses detached",value:String(J.analyses_detached)}]}])}),K.command("search-text <query>").description("Semantic search across call transcriptions").option("--from <date>","Start date (YYYY-MM-DD)").option("--to <date>","End date (YYYY-MM-DD)").option("--plan <id>","Filter by visual plan ID").option("--limit <n>","Max results","20").option("--threshold <n>","Similarity threshold (0-1)","0.35").action(async(q,Q)=>{let{format:W,fields:J}=L($.opts()),j=await N(U().ai.searchTranscriptions({query:q,limit:Number(Q.limit),threshold:Number(Q.threshold),date_from:Q.from,date_to:Q.to,visual_plan_id:A("visual_plans",Q.plan)}));if(W==="json"){let H=J?j.map((Z)=>O(Z,J)):j;P(H);return}let Y=j;if(console.log(`${a.default.bold("Semantic Search")}: "${q}"`),console.log(`${Y.length} result${Y.length!==1?"s":""} (threshold: ${Q.threshold})`),Y.length===0){z(`
|
|
45
|
-
No results found.`);return}console.log("");for(let H of Y){let Z=`${Math.round(H.similarity*100)}%`,B=H.call_record_id,M=j1(H.started_at),I=f$(H.duration_ms);console.log(` ${a.default.bold(Z.padStart(4))} │ ${B} │ ${M} │ ${H.caller_id??"—"} │ ${H.direction} │ ${I} │ ${H.visual_plan_name??"—"}`);let E=String(H.chunk_text).replaceAll(/\s+/g," ").trim(),u=120,U$=E.length>u?`${E.slice(0,u)}...`:E;console.log(a.default.dim(` │ "${U$}"`)),console.log("")}}),K.command("inspect <uuid>").description("Inspect an active call: current node, variables, execution path").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),J=U(),j=await s0(J,q),Y=await N(J.dashboard.activeCallTrace({uuid:j}));if(Q==="json"){let B=W?O(Y,W):Y;P(B);return}o([{title:"Active Call",rows:[{label:"UUID",value:j},{label:"Current",value:Y.currentNodeId??"—"}]}]);let H=Y.variables;if(Object.keys(H).length>0){let B=Object.entries(H).map(([M,I])=>({label:M,value:I}));o([{title:`Variables (${Object.keys(H).length})`,rows:B}])}let Z=Y.events;if(Z.length>0){console.log(""),console.log(a.default.bold("Execution Path:"));let B=Z.map((M)=>{let I=M.duration_ms!=null?`${(M.duration_ms/1000).toFixed(1)}s`:"waiting...",E=M.node_id===Y.currentNodeId,U$=`${E?a.default.yellow("●"):a.default.green("✓")} ${a.default.cyan(M.node_type)}`;if(M.node_label!=null){let S$=a.default.bold(`"${M.node_label}"`);U$+=` ${S$}`}if(U$+=a.default.dim(` (${I})`),E)U$+=a.default.yellow(" ← current");return{label:U$}});_3(B)}})}function WN($){if($.has_recording)return"yes";if($.was_recorded)return"processing";return"no"}function e0($){return $!=null&&$!==""}function JN($){let U=$.answered_at!=null?new Date($.answered_at):null,K=new Date($.started_at),q=U!=null?`${Math.round((U.getTime()-K.getTime())/1000)}s ring`:null,Q=e0(q)?` (${q})`:"",W=$.visual_plan_version_number!=null?` v${$.visual_plan_version_number}`:"",J=e0($.visual_plan_name)?`${$.visual_plan_name}${W}`:null,j=e0($.sip_hangup_disposition)?` (${$.sip_hangup_disposition})`:"",Y=$.transcription_status==="none"?"disabled":$.transcription_status;return[{label:"ID",value:$.id},{label:"Direction",value:$.direction},{label:"Caller",value:$.caller_id},{label:"Callee",value:$.callee_id},{label:"Plan",value:J},{label:"Started",value:K.toLocaleString()},{label:"Answered",value:U!=null?`${U.toLocaleString()}${Q}`:null},{label:"Ended",value:$.ended_at!=null?new Date($.ended_at).toLocaleString():null},{label:"Duration",value:f$($.duration_ms)},{label:"Status",value:N3($.hangup_disposition)},{label:"Recording",value:WN($)},{label:"Transcribed",value:Y},{label:"Machine type",value:$.answer_recognition_results?.machine_type},{label:"Hangup",value:e0($.hangup_cause)?`${$.hangup_cause}${j}`:null}]}function GN($){let U=p1($.confidence),K=U!=null?` (${U.toFixed(2)})`:"";return`${l($.topic)??l($.label)??"?"}${K}`}function jN($){let U=[];for(let K of A$($)){let q=l(K.speaker),Q=l(K.text),W=p1(K.initial_time);if(q!=null&&Q!=null&&W!=null)U.push({speaker:q,text:Q,initial_time:W})}return U}function YN($){let U=[],K=Q$($.sentiment_overall);if(K!=null)U.push({label:"Sentiment",value:L3(l(K.label),p1(K.score))});if($.intent!=null)U.push({label:"Intent",value:$.intent});if($.summary!=null)U.push({label:"Summary",value:$.summary});let q=Array.isArray($.key_points)?$.key_points.filter((W)=>typeof W==="string"):[];if(q.length>0)U.push({label:"Key Points",value:q.map((W)=>`• ${W}`).join(`
|
|
46
|
-
│ `)});let Q=A$($.topics);if(Q.length>0)U.push({label:"Topics",value:Q.map((W)=>GN(W)).join(" · ")});return U}function Lj($){let U=Math.floor($.start/60),K=Math.floor($.start%60),q=`${String(U).padStart(2,"0")}:${String(K).padStart(2,"0")}`,Q=$.channel===0?a.default.blue("Caller"):a.default.green("System");return`${a.default.dim(`[${q}]`)} ${Q} ${a.default.dim(">")} ${$.text}`}function Dj($){console.log(Lj($))}function Pj($){let U=`${Math.round($.confidence*100)}%`;if($.type==="signal_value"){z(` ↳ ${$.signal.name}: ${$.value_label} (${U})`);return}let K=$.node!=null?` · ${$.node.label}`:"",q=$.late?" (late)":"";console.log(a.default.bold(a.default.yellow(` \uD83D\uDD14 ${$.signal.name}: ${$.value_label} (${U})${K}${q}`)))}import{readFile as HN}from"node:fs/promises";async function _j($){let U=$==="-"?await v$():await HN($,"utf-8"),K=JSON.parse(U);if(!G$(K))x(`Invalid campaign file "${$}": expected a JSON object`),process.exit(w.USAGE_ERROR);return K}function XN($){return{...$.name!=null&&{name:$.name},...$.description!=null&&{description:$.description},...$.callerId!=null&&{caller_id:$.callerId},...$.trunkOverride!=null&&{trunk_override:$.trunkOverride},...$.maxConcurrent!=null&&{max_concurrent_calls:Number($.maxConcurrent)},...$.ringTimeout!=null&&{ring_timeout_s:Number($.ringTimeout)},...$.maxDuration!=null&&{max_call_duration_s:Number($.maxDuration)},...$.priority!=null&&{priority:Number($.priority)}}}function ZN($){let U=$.retryOn!=null?new Set($.retryOn.split(",").map((K)=>K.trim())):void 0;return{...$.retryAttempts!=null&&{retry_max_attempts:Number($.retryAttempts)},...$.retryInterval!=null&&{retry_interval_min:Number($.retryInterval)},...$.windowStart!=null&&{call_window_start:$.windowStart},...$.windowEnd!=null&&{call_window_end:$.windowEnd},...$.windowDays!=null&&{call_window_days:$.windowDays},...$.autoStartAt!=null&&{auto_start_at:$.autoStartAt},...$.autoStopAt!=null&&{auto_stop_at:$.autoStopAt},...U!=null&&{retry_on_busy:U.has("busy"),retry_on_no_answer:U.has("no_answer"),retry_on_failed:U.has("failed")},...$.recurring===!0&&{recurring:!0}}}function Ij($){return{...XN($),...ZN($)}}function E4($){if($==null)return"inherit (org default)";if(typeof $==="boolean")return $?"yes":"no";return String($)}function Fj($){return $.option("--description <text>","Campaign description").option("--caller-id <id>","Caller ID for outbound calls").option("--trunk-override <trunk>","Trunk override (default: org trunk)").option("--max-concurrent <n>","Max concurrent calls").option("--ring-timeout <s>","Ring timeout in seconds before no-answer").option("--max-duration <s>","Max call duration in seconds").option("--retry-attempts <n>","Max retry attempts").option("--retry-interval <min>","Retry interval in minutes").option("--retry-on <list>","Retry on outcomes (comma list: busy,no_answer,failed)").option("--window-start <HH:MM>","Call window start time").option("--window-end <HH:MM>","Call window end time").option("--window-days <list>","Call window days (comma ints, 0=Sun..6=Sat)").option("--priority <n>","Campaign priority (0-100)").option("--recurring","Enable recurring dialing").option("--auto-start-at <iso>","Auto-start timestamp (ISO 8601)").option("--auto-stop-at <iso>","Auto-stop timestamp (ISO 8601)").option("--file <path>","JSON file with campaign fields (- for stdin)")}function xj($,U){let K=$.command("campaigns").description("Manage dialer campaigns");K.command("list").description("List dialer campaigns").option("--status <s>","Filter by status").option("--search <term>","Search by name").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),J=await N(U().dialerCampaigns.list({page:Number(q.page),limit:Number(q.limit),search:q.search,status:P$(q.status)}));if(Q==="json"){let j=W?J.items.map((Y)=>O(Y,W)):J;P(j);return}y(["ID","Name","Status","Contacts","Answered","Created"],J.items.map((j)=>({ID:j.id,Name:j.name,Status:j.status,Contacts:j.total_contacts,Answered:j.answered_count,Created:j1(j.created_at)}))),H$(J)}),K.command("show <campaign_id>").description("Show campaign details").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),J=await N(U().dialerCampaigns.get({campaign_id:A("dialer_campaigns",q)}));if(J==null){if(Q==="json")P(null),process.exit(w.NOT_FOUND);x("Campaign not found"),process.exit(w.NOT_FOUND)}if(Q==="json"){let j=W?O(J,W):J;P(j);return}o([{title:"Campaign",rows:[{label:"ID",value:J.id},{label:"Name",value:J.name},{label:"Description",value:J.description},{label:"Status",value:J.status},{label:"Plan",value:J.plan_id},{label:"Channel",value:J.channel_type},{label:"Priority",value:J.priority},{label:"Created",value:new Date(J.created_at).toLocaleString()},{label:"Updated",value:new Date(J.updated_at).toLocaleString()}]},{title:"Dialing",rows:[{label:"Caller ID",value:J.caller_id},{label:"Trunk",value:J.trunk_override},{label:"Max Concurrent",value:J.max_concurrent_calls},{label:"Ring Timeout",value:`${J.ring_timeout_s}s`},{label:"Max Duration",value:`${J.max_call_duration_s}s`}]},{title:"Retry",rows:[{label:"Max Attempts",value:J.retry_max_attempts},{label:"Interval",value:`${J.retry_interval_min}min`},{label:"On Busy",value:J.retry_on_busy?"yes":"no"},{label:"On No Answer",value:J.retry_on_no_answer?"yes":"no"},{label:"On Failed",value:J.retry_on_failed?"yes":"no"}]},{title:"Answering machine",rows:[{label:"Detection",value:J.amd_enabled?"on":"off"},{label:"Retry On Machine",value:J.retry_on_machine?"yes":"no"},{label:"Block After All",value:E4(J.amd_block_after_all_machine)},{label:"Block Min Attempts",value:E4(J.amd_block_min_attempts)},{label:"On Voicemail",value:E4(J.amd_action_voicemail)},{label:"On Announcement",value:E4(J.amd_action_announcement)},{label:"On IVR",value:E4(J.amd_action_ivr)},{label:"On Screening",value:E4(J.amd_action_screening)}]},{title:"Window & schedule",rows:[{label:"Window Start",value:J.call_window_start},{label:"Window End",value:J.call_window_end},{label:"Window Days",value:J.call_window_days},{label:"Recurring",value:J.recurring?"yes":"no"},{label:"Recurrence",value:J.recurrence_mode},{label:"Auto Start",value:J.auto_start_at?new Date(J.auto_start_at).toLocaleString():null},{label:"Auto Stop",value:J.auto_stop_at?new Date(J.auto_stop_at).toLocaleString():null}]}])}),K.command("stats <campaign_id>").description("Show campaign statistics").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),J=await N(U().dialerCampaigns.stats({campaign_id:A("dialer_campaigns",q)}));if(Q==="json"){let H=W?O(J,W):J;P(H);return}let j=J.capacity_context;o([{title:"Stats",rows:[{label:"Status",value:J.status},{label:"Total",value:J.total_contacts},{label:"Pending",value:J.pending_count},{label:"Calling",value:J.calling_count},{label:"Answered",value:J.answered_count},{label:"Machine",value:J.machine_count},{label:"Busy",value:J.busy_count},{label:"No Answer",value:J.no_answer_count},{label:"Failed",value:J.failed_count},{label:"DNC Skipped",value:J.dnc_skipped_count},{label:"Cancelled",value:J.cancelled_count}]},{title:"Capacity",rows:[{label:"Waiting",value:J.waiting_capacity?"yes":"no"},{label:"Used",value:j!=null?j.used:null},{label:"Capacity",value:j!=null?j.capacity:null},{label:"Reserve",value:j!=null?j.reserve:null},{label:"Module Disabled",value:J.module_disabled?"yes":"no"}]}]);let Y=Number(J.total_contacts);if(Y>0)console.log(""),U1("Answered",Number(J.answered_count),Y),U1("Busy",Number(J.busy_count),Y),U1("No Answer",Number(J.no_answer_count),Y),U1("Failed",Number(J.failed_count),Y)}),K.command("summary").description("Show running-campaign summary").action(async()=>{let{format:q,fields:Q}=L($.opts()),W=await N(U().dialerCampaigns.summary());if(q==="json"){let J=Q?O(W,Q):W;P(J);return}o([{title:"Summary",rows:[{label:"Running",value:W.running},{label:"Calling",value:W.calling},{label:"Campaign",value:W.campaign!=null?`${W.campaign.name} (${W.campaign.id})`:null}]}])}),Fj(K.command("create <name>").description("Create a dialer campaign").requiredOption("--plan <plan_id>","Visual plan ID to dial")).action(async(q,Q)=>{let{format:W}=L($.opts()),J=Q.file!=null?await _j(Q.file):{},j=Ij(Q),Y=await N(U().dialerCampaigns.create({...J,...j,name:q,plan_id:A("visual_plans",Q.plan)}));if(W==="json"){P(Y);return}T(`Campaign created: ${Y.id} — ${Y.name}`)}),Fj(K.command("edit <campaign_id>").description("Update a dialer campaign").option("--name <name>","Campaign name")).action(async(q,Q)=>{let{format:W}=L($.opts()),J=Q.file!=null?await _j(Q.file):{},j=Ij(Q),Y=await N(U().dialerCampaigns.update({campaign_id:A("dialer_campaigns",q),...J,...j}));if(W==="json"){P(Y);return}T(`Campaign updated: ${Y.name}`)}),K.command("delete <campaign_id>").description("Delete a dialer campaign").action(async(q)=>{let{format:Q}=L($.opts());if(await N(U().dialerCampaigns.delete({campaign_id:A("dialer_campaigns",q)})),Q==="json"){P({success:!0});return}T("Campaign deleted")});for(let q of["start","pause","resume","stop"])K.command(`${q} <campaign_id>`).description(`${q[0].toUpperCase()}${q.slice(1)} a campaign`).action(async(Q)=>{let{format:W}=L($.opts()),J=await N(U().dialerCampaigns.control({campaign_id:A("dialer_campaigns",Q),action:q}));if(W==="json"){P(J);return}T(`Campaign "${J.name}" → ${J.status}`)});K.command("watch <campaign_id>").description("Watch live campaign stats (streams until Ctrl-C)").action(async(q)=>{let{format:Q}=L($.opts()),W=U(),J=new AbortController;process.on("SIGINT",()=>{J.abort()}),await new Promise((j,Y)=>{S1(W.dialerCampaigns.liveStats({campaign_id:A("dialer_campaigns",q)},{signal:J.signal}),{onEvent:(H)=>{if(Q==="json"){console.log(JSON.stringify(H));return}let Z=new Date().toLocaleTimeString(),B=H.counters,M=H.waiting_capacity?"yes":"no";console.log(`${Z} status=${H.status} calling=${H.calling} pending_retry=${H.pending_retry} answered=${B.answered_count} busy=${B.busy_count} failed=${B.failed_count} waiting_capacity=${M}`)},onError:(H)=>{if(H instanceof DOMException&&H.name==="AbortError"){j();return}Y(H)},onSuccess:()=>{j()}})}).catch(z4)}),K.command("attempts <campaign_id>").description("List call attempts for a campaign").option("--status <s>","Filter by attempt status").option("--contact <contact_id>","Filter by contact ID").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(q,Q)=>{let{format:W,fields:J}=L($.opts()),j=await N(U().dialerAttempts.list({campaign_id:A("dialer_campaigns",q),status:P$(Q.status),contact_id:A("dialer_contacts",Q.contact),page:Number(Q.page),limit:Number(Q.limit)}));if(W==="json"){let Y=J?j.items.map((H)=>O(H,J)):j;P(Y);return}y(["ID","#","Phone","Name","Status","Machine","Cause","Started","Duration","Record"],j.items.map((Y)=>({ID:Y.id,"#":Y.attempt_number,Phone:Y.phone_number??"—",Name:Y.contact_name??"—",Status:Y.status??"—",Machine:E0(Y.machine_type),Cause:Y.hangup_cause??"—",Started:Y.started_at?j1(Y.started_at):"—",Duration:Y.duration_s!=null?f$(Y.duration_s*1000):"—",Record:Y.call_record_id??"—"}))),H$(j)})}import{readFile as BN}from"node:fs/promises";var VN=new Set(["bot_token","webhook_secret","sip_password_encrypted","sip_password_iv"]),MN="<hidden>";function H1($){x(`Error: ${$}`),process.exit(w.USAGE_ERROR)}function y4($){return A("channels",$)}function t3($){return A("connectors",$)}function a3($){return A("visual_plans",$)}function wj($){return A("schedules",$)}function Aj($){let U=Q$($);if(U==null)return $;return Object.fromEntries(Object.entries(U).map(([K,q])=>[K,VN.has(K)?MN:q]))}function s3($){return{...$,config:Aj($.config)}}async function DN($){let U=$==="-"?await v$():await BN($,"utf-8"),K;try{K=JSON.parse(U)}catch{H1(`invalid config file "${$}": not valid JSON.`)}if(!G$(K))H1(`invalid config file "${$}": expected a JSON object.`);return K}function vj($){return $.option("--bot-token-env <VAR>","Telegram bot token, read from this environment variable").option("--bot-token-stdin","Telegram bot token, read from stdin")}function kj($){return vj($).option("--phone-number-id <id>","WhatsApp phone_number_id (see: niva channels whatsapp-numbers <connector_id>)").option("--allow-groups","Telegram: let the bot answer in groups").option("--session-timeout <minutes>","Chat session timeout in minutes (5-10080)").option("--file <path>","JSON file with the channel config object (- for stdin); flags override its keys")}async function Rj($){if($.botTokenEnv!=null&&$.botTokenStdin===!0)H1("--bot-token-env and --bot-token-stdin are mutually exclusive.");if($.botTokenEnv!=null){let U=process.env[$.botTokenEnv];if(U==null||U==="")H1(`environment variable ${$.botTokenEnv} is not set or empty (--bot-token-env).`);return U}if($.botTokenStdin===!0)return(await v$()).replace(/\r?\n$/,"");return}async function zj($){if($.file==="-"&&$.botTokenStdin===!0)H1("--file - and --bot-token-stdin both read stdin; pass the token with --bot-token-env instead.");let U=$.file==null?{}:await DN($.file),K=await Rj($);if(K!=null)U.bot_token=K;if($.phoneNumberId!=null)U.phone_number_id=$.phoneNumberId;if($.allowGroups===!0)U.allow_groups=!0;if($.sessionTimeout!=null)U.session_timeout_minutes=Number($.sessionTimeout);return Object.keys(U).length===0?void 0:U}function PN($){if($.visual_plan_id==null)return"-";return`${$.visual_plan_name??"?"} (${$.visual_plan_id})`}function NN($){if($.visual_plan_id==null)return;let U=$.visual_plan_published_version==null?"never published":"v"+$.visual_plan_published_version;return $.visual_plan_has_unpublished_changes?U+" (unpublished changes)":U}function LN($){let U=Q$(Aj($.config))??{},K=Object.entries(U).map(([q,Q])=>({label:q,value:typeof Q==="object"&&Q!==null?JSON.stringify(Q):String(Q)}));o([{title:`${$.name} (${$.id})`,rows:[{label:"Type",value:$.channel_type},{label:"Description",value:$.description},{label:"Identifier",value:$.identifier},{label:"Active",value:$.is_active?"yes":"no"},{label:"Plan",value:PN($)},{label:"Plan version",value:NN($)},{label:"Schedule",value:$.schedule_id==null?void 0:`${$.schedule_name??"?"} (${$.schedule_id})`},{label:"Connector",value:$.connector_id},{label:"Webhook URL",value:$.webhook_url},{label:"Calls (7d)",value:$.calls_7d?.total},{label:"Last call",value:$.last_call_at?.toISOString()},{label:"Created",value:$.created_at.toISOString()},{label:"Updated",value:$.updated_at.toISOString()}]},{title:"Config (credentials hidden)",rows:K.length>0?K:[{label:"(empty)",value:""}]}])}function e3($,U,K,q){if(K==="json"){let Q=s3($);P(q?O(Q,q):Q);return}T(`Channel ${U}: ${$.name} (${$.id})`)}function _N($){return $.readiness.ready?"ready":"not ready"}function IN($,U,K){$.command("list").description("List channels with type, plan, active state and 7-day call count; --alert shows the ones needing attention").option("--type <type>","Filter by channel type (sip, whatsapp, telegram)").option("--active","Only active channels").option("--inactive","Only inactive channels").option("--alert","Only channels with an alert: active with no plan, never-published plan, or failed WhatsApp webhook sync").option("--search <term>","Search by name").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(q)=>{if(q.active===!0&&q.inactive===!0)H1("--active and --inactive are mutually exclusive.");let{format:Q,fields:W}=L(U.opts()),J=await N(K().channels.list({page:Number(q.page),limit:Number(q.limit),...q.search!=null&&{search:q.search},...q.type!=null&&{channel_type:q.type},...q.active===!0&&{is_active:!0},...q.inactive===!0&&{is_active:!1},...q.alert===!0&&{alert:!0}})),j=J.items.map((Y)=>s3(Y));if(Q==="json"){P(W?j.map((Y)=>O(Y,W)):{...J,items:j});return}y(["ID","Type","Name","Identifier","Plan","Active","Calls 7d"],j.map((Y)=>({ID:Y.id,Type:Y.channel_type,Name:Y.name,Identifier:Y.identifier??"-",Plan:Y.visual_plan_name??"-",Active:Y.is_active?"yes":"no","Calls 7d":Y.calls_7d?.total??"-"}))),H$(J)})}function FN($,U,K){$.command("show <id>").description("Show a channel: plan, schedule, connector, webhook URL and config (credentials hidden)").action(async(q)=>{let{format:Q,fields:W}=L(U.opts()),J=await N(K().channels.getById({channel_id:y4(q)}));if(J==null)x(`Channel not found: ${q}`),process.exit(w.NOT_FOUND);if(Q==="json"){let j=s3(J);P(W?O(j,W):j);return}LN(J)})}function xN($,U,K){let q=$.command("create <type>").description("Create a channel of type sip, whatsapp or telegram. WhatsApp needs --connector and --phone-number-id; Telegram needs a bot token (--bot-token-env or --bot-token-stdin).").requiredOption("--name <name>","Channel name").option("--description <text>","Channel description").option("--identifier <id>","Provider-facing identifier (e.g. the SIP number); unique within the organization").option("--connector <id>","WhatsApp: connector (conn_...) that owns the account").option("--plan <id>","Visual plan (vp_...) that answers on this channel").option("--schedule <id>","Schedule (sched_...) that gates when the channel is available").option("--inactive","Create the channel switched off");kj(q).action(async(Q,W)=>{let{format:J,fields:j}=L(U.opts()),Y=await zj(W),H={channel_type:P$(Q),name:W.name,...W.description!=null&&{description:W.description},...W.identifier!=null&&{identifier:W.identifier},...W.connector!=null&&{connector_id:t3(W.connector)},...W.plan!=null&&{visual_plan_id:a3(W.plan)},...W.schedule!=null&&{schedule_id:wj(W.schedule)},...W.inactive===!0&&{is_active:!1},...Y!=null&&{config:Y}},Z=await N(K().channels.create(H));e3(Z,"created",J,j)})}function wN($,U,K){let q=$.command("update <id>").description("Change a channel: name, plan, schedule, connector or config (merged into the stored config). Moving a channel off a plan it already has needs --reassign.").option("--name <name>","New name").option("--description <text>","New description").option("--identifier <id>","New provider-facing identifier").option("--connector <id>","WhatsApp: connector (conn_...) that owns the account").option("--plan <id>","Attach this visual plan (vp_...)").option("--detach-plan","Detach the current plan").option("--schedule <id>","Attach this schedule (sched_...)").option("--detach-schedule","Detach the current schedule").option("--reassign","Allow moving the channel to another plan even when it already has one");kj(q).action(async(Q,W)=>{if(W.plan!=null&&W.detachPlan===!0)H1("--plan and --detach-plan are mutually exclusive.");if(W.schedule!=null&&W.detachSchedule===!0)H1("--schedule and --detach-schedule are mutually exclusive.");let{format:J,fields:j}=L(U.opts()),Y=await zj(W),H={channel_id:y4(Q),...W.name!=null&&{name:W.name},...W.description!=null&&{description:W.description},...W.identifier!=null&&{identifier:W.identifier},...W.connector!=null&&{connector_id:t3(W.connector)},...W.plan!=null&&{visual_plan_id:a3(W.plan)},...W.detachPlan===!0&&{visual_plan_id:null},...W.schedule!=null&&{schedule_id:wj(W.schedule)},...W.detachSchedule===!0&&{schedule_id:null},...W.reassign===!0&&{reassign:!0},...Y!=null&&{config:Y}};if(Object.keys(H).length===1)H1("nothing to update: pass at least one of --name, --plan, --schedule, --connector, --file, ...");let Z=await N(K().channels.update(H));e3(Z,"updated",J,j)})}function AN($,U,K){$.command("assign <id>").description("Point a channel at a visual plan so it answers with it; the plan must be published. Moving a channel off a plan it already has needs --reassign.").requiredOption("--plan <plan_id>","Visual plan (vp_...) to answer with").option("--reassign","Allow moving the channel to another plan even when it already has one").action(async(q,Q)=>{let{format:W,fields:J}=L(U.opts()),j=await N(K().channels.update({channel_id:y4(q),visual_plan_id:a3(Q.plan),...Q.reassign===!0&&{reassign:!0}}));e3(j,"assigned to plan "+Q.plan,W,J)})}function vN($,U,K){for(let[q,Q]of[["enable",!0],["disable",!1]])$.command(`${q} <id>`).description(Q?"Switch a channel on so it answers calls and chats with its plan":"Switch a channel off; it stops answering until enabled again").action(async(W)=>{let{format:J}=L(U.opts());if(await N(K().channels.toggle({channel_id:y4(W),is_active:Q})),J==="json"){P({id:W,is_active:Q});return}T(`Channel ${Q?"enabled":"disabled"}: ${W}`)})}function kN($,U,K){$.command("delete <id>").description("Delete a channel (needs --yes in a non-interactive shell)").action(async(q)=>{let{format:Q}=L(U.opts()),W=U.opts().yes===!0;if(await d$(`Delete channel ${q}?`,{yes:W}),await N(K().channels.delete({channel_id:y4(q)})),Q==="json"){P({id:q,deleted:!0});return}T(`Channel deleted: ${q}`)})}function RN($,U,K){let q=$.command("test-connection").description("Check a Telegram bot token against Telegram without creating a channel; prints the bot username. Telegram is the only type the API accepts.");vj(q).action(async(Q)=>{let{format:W}=L(U.opts()),J=await Rj(Q);if(J==null)H1("pass the bot token with --bot-token-env <VAR> or --bot-token-stdin.");let j=await N(K().channels.testConnection({channel_type:"telegram",config:{bot_token:J}}));if(W==="json")P(j);else if(j.ok)T("Telegram bot reachable"+(j.username==null?"":": @"+j.username));else x(`Telegram connection failed: ${j.error??"unknown error"}`);if(!j.ok)process.exit(w.GENERAL_ERROR)})}function zN($,U,K){$.command("setup-whatsapp-sip <id>").description("Configure WhatsApp calling (SIP) with Meta for a WhatsApp channel, so voice calls reach NIVA. Run it after the channel exists.").action(async(q)=>{let{format:Q}=L(U.opts());if(await N(K().channels.setupWhatsappSip({channel_id:y4(q)})),Q==="json"){P({id:q,ok:!0});return}T(`WhatsApp SIP configured for channel ${q}`)})}function bN($,U,K){$.command("whatsapp-connectors").description("List the WhatsApp connectors a WhatsApp channel can use (id, name, status, account)").action(async()=>{let{format:q,fields:Q}=L(U.opts()),W=await N(K().channels.whatsappConnectors());if(q==="json"){P(Q?W.map((J)=>O(J,Q)):W);return}y(["ID","Name","Status","Account"],W.map((J)=>({ID:J.id,Name:J.name,Status:J.status,Account:J.account_label??"-"})))})}function ON($,U,K){$.command("whatsapp-numbers <connector_id>").description("List the WhatsApp phone numbers of a connector with readiness and the bound channel; the ID column is the --phone-number-id for channels create").option("--refresh","Bypass the 5-minute cache and read the numbers again").action(async(q,Q)=>{let{format:W,fields:J}=L(U.opts()),j=await N(K().channels.whatsappNumbers({connector_id:t3(q),refresh:Q.refresh===!0}));if(W==="json"){P(J?j.map((Y)=>O(Y,J)):j);return}y(["ID","Number","Name","Readiness","Channel"],j.map((Y)=>({ID:Y.id,Number:Y.display_phone_number,Name:Y.verified_name,Readiness:_N(Y),Channel:Y.channel==null?"-":`${Y.channel.name} (${Y.channel.id})`})))})}var TN=/unknown option '([^']*)'/;function SN($){let U=TN.exec($)?.[1];if(U==null)return $;let K=U.indexOf("=");if(K<0)return $;let q=U.slice(0,K),Q=$.replace(`'${U}'`,`'${q}=<redacted>'`);if(q!=="--bot-token")return Q;return`${Q}
|
|
47
|
-
Use --bot-token-env <VAR> or --bot-token-stdin for a credential instead of a literal value.`}function bj($,U){let K=$.createCommand("channels").description("Channels (SIP, WhatsApp, Telegram): the entry points a plan answers on");K.configureOutput({outputError:(q,Q)=>Q(SN(q))}),$.addCommand(K),IN(K,$,U),FN(K,$,U),xN(K,$,U),wN(K,$,U),AN(K,$,U),vN(K,$,U),kN(K,$,U),RN(K,$,U),zN(K,$,U),bN(K,$,U),ON(K,$,U)}import{readFile as fN}from"node:fs/promises";var k$=N1(I1(),1);async function $2($){z(`Connecting to ${$}`);let U=o3($)?{tls:{rejectUnauthorized:!1}}:void 0,K=new WebSocket($,U),q=!1;throw K.onopen=()=>{q=!0},K.onmessage=(Q)=>{let W=JSON.parse(typeof Q.data==="string"?Q.data:String(Q.data)),J=Q$(W)??{},j=l(J.type)??"";switch(j){case"connected":console.log(k$.default.green(` Connected. Type a message and press Enter. Ctrl+C or /quit to exit.
|
|
48
|
-
`)),uN(K);break;case"message":{let Y=Q$(J.message)??{};for(let H of gN(Y))console.log(H);break}case"typing":{if(J.active===!0)process.stdout.write(k$.default.dim(" bot is typing...\r"));else process.stdout.write(" \r");break}case"state":{if(J.status==="ended")console.log(k$.default.dim(`
|
|
49
|
-
Session ended.`)),process.exit(0);break}case"error":console.log(k$.default.red(` error: [${String(J.code)}] ${String(J.message)}`));break;case"pong":break;case"replay":{let Y=Array.isArray(J.messages)?J.messages:[];if(Y.length>0)z(` Replayed ${Y.length} missed message(s)`);break}default:console.log(k$.default.dim(` [${j}] ${JSON.stringify(J)}`))}},K.onclose=(Q)=>{if(q)z(`
|
|
50
|
-
Disconnected (code=${Q.code})`);else x("Failed to connect");process.exit(q?0:1)},K.onerror=()=>{x("WebSocket error"),process.exit(1)},await new Promise(()=>{}),Error("unreachable")}function g4($,U){return $.replace(/^http/,"ws")+U}var H4=k$.default.cyan(" bot");function CN($,U){let K=[`${H4} ${$}`];for(let q of A$(U.buttons)){let Q=k$.default.dim(`[${String(q.id)}]`);K.push(` ${Q} ${String(q.label)}`)}return K}function EN($,U){let K=[`${H4} ${$}`];for(let q of A$(U.sections)){K.push(` ${k$.default.bold(String(q.title))}`);for(let Q of A$(q.items)){let W=k$.default.dim(`[${String(Q.id)}]`);K.push(` ${W} ${String(Q.title)}`)}}return K}function yN($){return A$($.cards).map((U)=>{let K=l(U.description),q=K!=null?` — ${K}`:"";return`${H4} ${k$.default.bold(String(U.title))}${q}`})}function gN($){let U=l($.type)??"",K=l($.text)??"";switch(U){case"text":return[`${H4} ${K}`];case"buttons":return CN(K,$);case"list":return EN(K,$);case"media":{let q=k$.default.dim(`[${String($.mediaType)}]`),Q=typeof $.caption==="string"?` — ${$.caption}`:"";return[`${H4} ${q} ${String($.url)}${Q}`]}case"location":{let q=typeof $.label==="string"?` (${$.label})`:"";return[`${H4} ${k$.default.dim("[location]")} ${String($.lat)},${String($.lng)}${q}`]}case"carousel":return yN($);default:{let q=k$.default.dim(`[${U}]`);return[`${H4} ${q} ${JSON.stringify($)}`]}}}function uN($){let U=process.stdin;U.setEncoding("utf-8"),U.resume();let K="";U.on("data",(q)=>{K+=q;let Q=K.split(`
|
|
51
|
-
`);K=Q.pop();for(let W of Q){let J=W.trim();if(J==="")continue;if(J==="/ping"){$.send(JSON.stringify({type:"ping"})),z(" → ping");continue}if(J==="/quit"||J==="/exit"){$.close();return}console.log(`${k$.default.blue(" you")} ${J}`),$.send(JSON.stringify({type:"message",message:{type:"text",text:J}}))}}),process.once("SIGINT",()=>{z(`
|
|
52
|
-
Closing...`),$.close()})}function Oj($,U,K){let q=$.command("chat").description("Test chat — interactive session against a visual plan (draft or published)");q.command("test <plan_id>").description("Start a test chat session for a plan. Tests the published draft by default.").option("--editor-state <file>","Path to a JSON file with an unpublished editorState to test").action(async(Q,W)=>{let J=t1($.opts()),j=K(),Y;if(W.editorState!=null){let Z=await fN(W.editorState,"utf-8");Y=JSON.parse(Z)}if(J!=="json")z("Creating test chat session...");let H=await N(U().testChat.createSession({planId:A("visual_plans",Q),editor_state:Y}));if(J==="json"){P({...H,ws_url:g4(j.url,H.wsUrl)});return}T(`Session created: ${H.sessionId}`),await $2(g4(j.url,H.wsUrl))}),q.command("stop <sessionId>").description("Stop an active test chat session").action(async(Q)=>{let W=t1($.opts());if(await N(U().testChat.stop({sessionId:Q})),W==="json"){P({session_id:Q,stopped:!0});return}T(`Session ${Q} stopped.`)})}function Tj($){let U=$.command("config").description("Manage CLI configuration");U.command("set <key> <value>").description("Set a config value (url, api-key)").action((K,q)=>{Qj(K==="api-key"?"apiKey":K,q),T(`Set ${K} = ${q}`)}),U.command("get <key>").description("Get a config value (url, api-key)").action((K)=>{let q=K==="api-key"?"apiKey":K,W=c3()[q];if(W==null){z(`(${K} not set)`);return}console.log(typeof W==="string"?W:JSON.stringify(W))}),U.command("show").description("Show current configuration").action(()=>{let K=c3();P(K)})}var $U={"channel.whatsapp":{consumers:["channel"]},"whatsapp.templates":{consumers:["node"]},"sms.send":{consumers:["node","notification"]},"email.send":{consumers:["node","notification"]},"tools.catalog":{consumers:["node","mcp"]},"calendar.events":{consumers:["node"]},"voice.agent":{consumers:["node"]},"phone.lookup":{consumers:["node","mcp"]},"verify.otp":{consumers:["node","mcp"]}};function Sj($){return Object.hasOwn($U,$)}var mN=Object.keys($U).filter(($)=>Sj($));class UU{#$;constructor($){this.#$=$}static of($){return new UU($)}reveal(){return this.#$}toString(){return"[redacted]"}toJSON(){return"[redacted]"}[Symbol.for("nodejs.util.inspect.custom")](){return"[redacted]"}}var G={};L1(G,{xor:()=>JH,xid:()=>zY,void:()=>$H,uuidv7:()=>IY,uuidv6:()=>_Y,uuidv4:()=>LY,uuid:()=>NY,util:()=>R,url:()=>FY,uppercase:()=>p4,unknown:()=>N4,union:()=>R8,undefined:()=>sY,ulid:()=>RY,uint64:()=>tY,uint32:()=>oY,tuple:()=>NK,trim:()=>U6,treeifyError:()=>BU,transform:()=>b8,toUpperCase:()=>K6,toLowerCase:()=>Q6,toJSONSchema:()=>U8,templateLiteral:()=>LH,symbol:()=>aY,superRefine:()=>iK,success:()=>DH,stringbool:()=>kH,stringFormat:()=>mY,string:()=>G8,strictObject:()=>qH,startsWith:()=>a4,slugify:()=>q6,size:()=>M4,setErrorMap:()=>PI,set:()=>XH,safeParseAsync:()=>dQ,safeParse:()=>iQ,safeEncodeAsync:()=>eQ,safeEncode:()=>aQ,safeDecodeAsync:()=>$K,safeDecode:()=>sQ,registry:()=>v2,regexes:()=>n$,regex:()=>o4,refine:()=>rK,record:()=>LK,readonly:()=>uK,property:()=>a2,promise:()=>_H,prettifyError:()=>VU,preprocess:()=>zH,prefault:()=>OK,positive:()=>o2,pipe:()=>Y0,partialRecord:()=>jH,parseAsync:()=>rQ,parse:()=>lQ,overwrite:()=>q1,optional:()=>G0,object:()=>KH,number:()=>QK,nullish:()=>MH,nullable:()=>j0,null:()=>GK,normalize:()=>$6,nonpositive:()=>p2,nonoptional:()=>TK,nonnegative:()=>t2,never:()=>k8,negative:()=>n2,nativeEnum:()=>ZH,nanoid:()=>AY,nan:()=>PH,multipleOf:()=>u1,minSize:()=>V1,minLength:()=>v1,mime:()=>e4,meta:()=>AH,maxSize:()=>f1,maxLength:()=>D4,map:()=>HH,mac:()=>TY,lte:()=>h$,lt:()=>Z1,lowercase:()=>n4,looseRecord:()=>YH,looseObject:()=>WH,locales:()=>Q0,literal:()=>BH,length:()=>P4,lazy:()=>hK,ksuid:()=>bY,keyof:()=>QH,jwt:()=>fY,json:()=>RH,iso:()=>G6,ipv6:()=>SY,ipv4:()=>OY,intersection:()=>DK,int64:()=>pY,int32:()=>dY,int:()=>j8,instanceof:()=>vH,includes:()=>t4,httpUrl:()=>xY,hostname:()=>hY,hex:()=>cY,hash:()=>lY,guid:()=>PY,gte:()=>z$,gt:()=>B1,globalRegistry:()=>_$,getErrorMap:()=>NI,function:()=>IH,fromJSONSchema:()=>OH,formatError:()=>i6,float64:()=>iY,float32:()=>rY,flattenError:()=>r6,file:()=>VH,exactOptional:()=>vK,enum:()=>z8,endsWith:()=>s4,encodeAsync:()=>pQ,encode:()=>oQ,emoji:()=>wY,email:()=>DY,e164:()=>uY,discriminatedUnion:()=>GH,describe:()=>wH,decodeAsync:()=>tQ,decode:()=>nQ,date:()=>UH,custom:()=>xH,cuid2:()=>kY,cuid:()=>vY,core:()=>k1,config:()=>Z$,coerce:()=>oK,codec:()=>NH,clone:()=>R$,cidrv6:()=>EY,cidrv4:()=>CY,check:()=>FH,catch:()=>EK,boolean:()=>KK,bigint:()=>nY,base64url:()=>gY,base64:()=>yY,array:()=>Z0,any:()=>eY,_function:()=>IH,_default:()=>zK,_ZodString:()=>Y8,ZodXor:()=>BK,ZodXID:()=>D8,ZodVoid:()=>XK,ZodUnknown:()=>YK,ZodUnion:()=>V0,ZodUndefined:()=>WK,ZodUUID:()=>M1,ZodURL:()=>H0,ZodULID:()=>M8,ZodType:()=>c,ZodTuple:()=>PK,ZodTransform:()=>wK,ZodTemplateLiteral:()=>fK,ZodSymbol:()=>qK,ZodSuccess:()=>SK,ZodStringFormat:()=>e,ZodString:()=>Y6,ZodSet:()=>IK,ZodRecord:()=>M0,ZodRealError:()=>g$,ZodReadonly:()=>gK,ZodPromise:()=>cK,ZodPrefault:()=>bK,ZodPipe:()=>S8,ZodOptional:()=>O8,ZodObject:()=>B0,ZodNumberFormat:()=>L4,ZodNumber:()=>X6,ZodNullable:()=>kK,ZodNull:()=>JK,ZodNonOptional:()=>T8,ZodNever:()=>HK,ZodNanoID:()=>Z8,ZodNaN:()=>yK,ZodMap:()=>_K,ZodMAC:()=>UK,ZodLiteral:()=>FK,ZodLazy:()=>mK,ZodKSUID:()=>P8,ZodJWT:()=>A8,ZodIssueCode:()=>DI,ZodIntersection:()=>MK,ZodISOTime:()=>W8,ZodISODuration:()=>J8,ZodISODateTime:()=>K8,ZodISODate:()=>q8,ZodIPv6:()=>L8,ZodIPv4:()=>N8,ZodGUID:()=>J0,ZodFunction:()=>lK,ZodFirstPartyTypeKind:()=>dK,ZodFile:()=>xK,ZodExactOptional:()=>AK,ZodError:()=>VI,ZodEnum:()=>j6,ZodEmoji:()=>X8,ZodEmail:()=>H8,ZodE164:()=>w8,ZodDiscriminatedUnion:()=>VK,ZodDefault:()=>RK,ZodDate:()=>X0,ZodCustomStringFormat:()=>H6,ZodCustom:()=>D0,ZodCodec:()=>C8,ZodCatch:()=>CK,ZodCUID2:()=>V8,ZodCUID:()=>B8,ZodCIDRv6:()=>I8,ZodCIDRv4:()=>_8,ZodBoolean:()=>Z6,ZodBigIntFormat:()=>v8,ZodBigInt:()=>B6,ZodBase64URL:()=>x8,ZodBase64:()=>F8,ZodArray:()=>ZK,ZodAny:()=>jK,TimePrecision:()=>N7,NEVER:()=>QU,$output:()=>Z7,$input:()=>B7,$brand:()=>KU});var k1={};L1(k1,{version:()=>Y9,util:()=>R,treeifyError:()=>BU,toJSONSchema:()=>U8,toDotPath:()=>fj,safeParseAsync:()=>DU,safeParse:()=>MU,safeEncodeAsync:()=>LL,safeEncode:()=>PL,safeDecodeAsync:()=>_L,safeDecode:()=>NL,registry:()=>v2,regexes:()=>n$,process:()=>t,prettifyError:()=>VU,parseAsync:()=>q2,parse:()=>K2,meta:()=>s7,locales:()=>Q0,isValidJWT:()=>qY,isValidBase64URL:()=>KY,isValidBase64:()=>O9,initializeContext:()=>m1,globalRegistry:()=>_$,globalConfig:()=>y6,formatError:()=>i6,flattenError:()=>r6,finalize:()=>c1,extractDefs:()=>h1,encodeAsync:()=>ML,encode:()=>BL,describe:()=>a7,decodeAsync:()=>DL,decode:()=>VL,createToJSONSchemaMethod:()=>$Q,createStandardJSONSchemaMethod:()=>J6,config:()=>Z$,clone:()=>R$,_xor:()=>r_,_xid:()=>g2,_void:()=>c7,_uuidv7:()=>O2,_uuidv6:()=>b2,_uuidv4:()=>z2,_uuid:()=>R2,_url:()=>q0,_uppercase:()=>p4,_unknown:()=>m7,_union:()=>l_,_undefined:()=>g7,_ulid:()=>y2,_uint64:()=>E7,_uint32:()=>z7,_tuple:()=>o_,_trim:()=>U6,_transform:()=>$I,_toUpperCase:()=>K6,_toLowerCase:()=>Q6,_templateLiteral:()=>YI,_symbol:()=>y7,_superRefine:()=>t7,_success:()=>WI,_stringbool:()=>e7,_stringFormat:()=>W6,_string:()=>M7,_startsWith:()=>a4,_slugify:()=>q6,_size:()=>M4,_set:()=>t_,_safeParseAsync:()=>r4,_safeParse:()=>l4,_safeEncodeAsync:()=>X2,_safeEncode:()=>Y2,_safeDecodeAsync:()=>Z2,_safeDecode:()=>H2,_regex:()=>o4,_refine:()=>p7,_record:()=>n_,_readonly:()=>jI,_property:()=>a2,_promise:()=>XI,_positive:()=>o2,_pipe:()=>GI,_parseAsync:()=>c4,_parse:()=>h4,_overwrite:()=>q1,_optional:()=>UI,_number:()=>x7,_nullable:()=>QI,_null:()=>u7,_normalize:()=>$6,_nonpositive:()=>p2,_nonoptional:()=>qI,_nonnegative:()=>t2,_never:()=>h7,_negative:()=>n2,_nativeEnum:()=>s_,_nanoid:()=>S2,_nan:()=>i7,_multipleOf:()=>u1,_minSize:()=>V1,_minLength:()=>v1,_min:()=>z$,_mime:()=>e4,_maxSize:()=>f1,_maxLength:()=>D4,_max:()=>h$,_map:()=>p_,_mac:()=>P7,_lte:()=>h$,_lt:()=>Z1,_lowercase:()=>n4,_literal:()=>e_,_length:()=>P4,_lazy:()=>HI,_ksuid:()=>u2,_jwt:()=>d2,_isoTime:()=>I7,_isoDuration:()=>F7,_isoDateTime:()=>L7,_isoDate:()=>_7,_ipv6:()=>m2,_ipv4:()=>f2,_intersection:()=>d_,_int64:()=>C7,_int32:()=>R7,_int:()=>A7,_includes:()=>t4,_guid:()=>K0,_gte:()=>z$,_gt:()=>B1,_float64:()=>k7,_float32:()=>v7,_file:()=>o7,_enum:()=>a_,_endsWith:()=>s4,_encodeAsync:()=>G2,_encode:()=>W2,_emoji:()=>T2,_email:()=>k2,_e164:()=>i2,_discriminatedUnion:()=>i_,_default:()=>KI,_decodeAsync:()=>j2,_decode:()=>J2,_date:()=>l7,_custom:()=>n7,_cuid2:()=>E2,_cuid:()=>C2,_coercedString:()=>D7,_coercedNumber:()=>w7,_coercedDate:()=>r7,_coercedBoolean:()=>O7,_coercedBigint:()=>S7,_cidrv6:()=>c2,_cidrv4:()=>h2,_check:()=>BY,_catch:()=>JI,_boolean:()=>b7,_bigint:()=>T7,_base64url:()=>r2,_base64:()=>l2,_array:()=>d7,_any:()=>f7,TimePrecision:()=>N7,NEVER:()=>QU,JSONSchemaGenerator:()=>uQ,JSONSchema:()=>VY,Doc:()=>D2,$output:()=>Z7,$input:()=>B7,$constructor:()=>D,$brand:()=>KU,$ZodXor:()=>p9,$ZodXID:()=>_9,$ZodVoid:()=>i9,$ZodUnknown:()=>l9,$ZodUnion:()=>t6,$ZodUndefined:()=>m9,$ZodUUID:()=>Z9,$ZodURL:()=>V9,$ZodULID:()=>L9,$ZodType:()=>h,$ZodTuple:()=>w2,$ZodTransform:()=>q5,$ZodTemplateLiteral:()=>M5,$ZodSymbol:()=>f9,$ZodSuccess:()=>H5,$ZodStringFormat:()=>s,$ZodString:()=>V4,$ZodSet:()=>$5,$ZodRegistry:()=>V7,$ZodRecord:()=>s9,$ZodRealError:()=>y$,$ZodReadonly:()=>V5,$ZodPromise:()=>P5,$ZodPrefault:()=>j5,$ZodPipe:()=>B5,$ZodOptional:()=>A2,$ZodObjectJIT:()=>n9,$ZodObject:()=>GY,$ZodNumberFormat:()=>g9,$ZodNumber:()=>F2,$ZodNullable:()=>J5,$ZodNull:()=>h9,$ZodNonOptional:()=>Y5,$ZodNever:()=>r9,$ZodNanoID:()=>D9,$ZodNaN:()=>Z5,$ZodMap:()=>e9,$ZodMAC:()=>R9,$ZodLiteral:()=>Q5,$ZodLazy:()=>N5,$ZodKSUID:()=>I9,$ZodJWT:()=>E9,$ZodIntersection:()=>a9,$ZodISOTime:()=>w9,$ZodISODuration:()=>A9,$ZodISODateTime:()=>F9,$ZodISODate:()=>x9,$ZodIPv6:()=>k9,$ZodIPv4:()=>v9,$ZodGUID:()=>X9,$ZodFunction:()=>D5,$ZodFile:()=>K5,$ZodExactOptional:()=>W5,$ZodError:()=>l6,$ZodEnum:()=>U5,$ZodEncodeError:()=>X4,$ZodEmoji:()=>M9,$ZodEmail:()=>B9,$ZodE164:()=>C9,$ZodDiscriminatedUnion:()=>t9,$ZodDefault:()=>G5,$ZodDate:()=>d9,$ZodCustomStringFormat:()=>y9,$ZodCustom:()=>L5,$ZodCodec:()=>a6,$ZodCheckUpperCase:()=>Q9,$ZodCheckStringFormat:()=>i4,$ZodCheckStartsWith:()=>q9,$ZodCheckSizeEquals:()=>tU,$ZodCheckRegex:()=>$9,$ZodCheckProperty:()=>J9,$ZodCheckOverwrite:()=>j9,$ZodCheckNumberFormat:()=>dU,$ZodCheckMultipleOf:()=>iU,$ZodCheckMinSize:()=>pU,$ZodCheckMinLength:()=>sU,$ZodCheckMimeType:()=>G9,$ZodCheckMaxSize:()=>nU,$ZodCheckMaxLength:()=>aU,$ZodCheckLowerCase:()=>U9,$ZodCheckLessThan:()=>V2,$ZodCheckLengthEquals:()=>eU,$ZodCheckIncludes:()=>K9,$ZodCheckGreaterThan:()=>M2,$ZodCheckEndsWith:()=>W9,$ZodCheckBigIntFormat:()=>oU,$ZodCheck:()=>$$,$ZodCatch:()=>X5,$ZodCUID2:()=>N9,$ZodCUID:()=>P9,$ZodCIDRv6:()=>b9,$ZodCIDRv4:()=>z9,$ZodBoolean:()=>p6,$ZodBigIntFormat:()=>u9,$ZodBigInt:()=>x2,$ZodBase64URL:()=>S9,$ZodBase64:()=>T9,$ZodAsyncError:()=>X1,$ZodArray:()=>o9,$ZodAny:()=>c9});var QU=Object.freeze({status:"aborted"});function D($,U,K){function q(j,Y){if(!j._zod)Object.defineProperty(j,"_zod",{value:{def:Y,constr:J,traits:new Set},enumerable:!1});if(j._zod.traits.has($))return;j._zod.traits.add($),U(j,Y);let H=J.prototype,Z=Object.keys(H);for(let B=0;B<Z.length;B++){let M=Z[B];if(!(M in j))j[M]=H[M].bind(j)}}let Q=K?.Parent??Object;class W extends Q{}Object.defineProperty(W,"name",{value:$});function J(j){var Y;let H=K?.Parent?new W:this;q(H,j),(Y=H._zod).deferred??(Y.deferred=[]);for(let Z of H._zod.deferred)Z();return H}return Object.defineProperty(J,"init",{value:q}),Object.defineProperty(J,Symbol.hasInstance,{value:(j)=>{if(K?.Parent&&j instanceof K.Parent)return!0;return j?._zod?.traits?.has($)}}),Object.defineProperty(J,"name",{value:$}),J}var KU=Symbol("zod_brand");class X1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class X4 extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}}var y6={};function Z$($){if($)Object.assign(y6,$);return y6}var R={};L1(R,{unwrapMessage:()=>g6,uint8ArrayToHex:()=>XL,uint8ArrayToBase64url:()=>YL,uint8ArrayToBase64:()=>yj,stringifyPrimitive:()=>v,slugify:()=>JU,shallowClone:()=>jU,safeExtend:()=>KL,required:()=>JL,randomString:()=>tN,propertyKeyTypes:()=>m6,promiseAllObject:()=>pN,primitiveTypes:()=>YU,prefixIssues:()=>m$,pick:()=>$L,partial:()=>WL,parsedType:()=>k,optionalKeys:()=>HU,omit:()=>UL,objectClone:()=>dN,numKeys:()=>aN,nullish:()=>C1,normalizeParams:()=>b,mergeDefs:()=>A1,merge:()=>qL,jsonStringifyReplacer:()=>u4,joinValues:()=>_,issue:()=>m4,isPlainObject:()=>y1,isObject:()=>Z4,hexToUint8Array:()=>HL,getSizableOrigin:()=>h6,getParsedType:()=>sN,getLengthableOrigin:()=>c6,getEnumValues:()=>u6,getElementAtPath:()=>nN,floatSafeRemainder:()=>WU,finalizeIssue:()=>E$,extend:()=>QL,escapeRegex:()=>o$,esc:()=>U2,defineLazy:()=>r,createTransparentProxy:()=>eN,cloneDef:()=>oN,clone:()=>R$,cleanRegex:()=>f6,cleanEnum:()=>GL,captureStackTrace:()=>Q2,cached:()=>f4,base64urlToUint8Array:()=>jL,base64ToUint8Array:()=>Ej,assignProp:()=>E1,assertNotEqual:()=>cN,assertNever:()=>rN,assertIs:()=>lN,assertEqual:()=>hN,assert:()=>iN,allowsEval:()=>GU,aborted:()=>g1,NUMBER_FORMAT_RANGES:()=>XU,Class:()=>gj,BIGINT_FORMAT_RANGES:()=>ZU});function hN($){return $}function cN($){return $}function lN($){}function rN($){throw Error("Unexpected value in exhaustive check")}function iN($){}function u6($){let U=Object.values($).filter((q)=>typeof q==="number");return Object.entries($).filter(([q,Q])=>U.indexOf(+q)===-1).map(([q,Q])=>Q)}function _($,U="|"){return $.map((K)=>v(K)).join(U)}function u4($,U){if(typeof U==="bigint")return U.toString();return U}function f4($){return{get value(){{let K=$();return Object.defineProperty(this,"value",{value:K}),K}throw Error("cached value already set")}}}function C1($){return $===null||$===void 0}function f6($){let U=$.startsWith("^")?1:0,K=$.endsWith("$")?$.length-1:$.length;return $.slice(U,K)}function WU($,U){let K=($.toString().split(".")[1]||"").length,q=U.toString(),Q=(q.split(".")[1]||"").length;if(Q===0&&/\d?e-\d?/.test(q)){let Y=q.match(/\d?e-(\d?)/);if(Y?.[1])Q=Number.parseInt(Y[1])}let W=K>Q?K:Q,J=Number.parseInt($.toFixed(W).replace(".","")),j=Number.parseInt(U.toFixed(W).replace(".",""));return J%j/10**W}var Cj=Symbol("evaluating");function r($,U,K){let q=void 0;Object.defineProperty($,U,{get(){if(q===Cj)return;if(q===void 0)q=Cj,q=K();return q},set(Q){Object.defineProperty($,U,{value:Q})},configurable:!0})}function dN($){return Object.create(Object.getPrototypeOf($),Object.getOwnPropertyDescriptors($))}function E1($,U,K){Object.defineProperty($,U,{value:K,writable:!0,enumerable:!0,configurable:!0})}function A1(...$){let U={};for(let K of $){let q=Object.getOwnPropertyDescriptors(K);Object.assign(U,q)}return Object.defineProperties({},U)}function oN($){return A1($._zod.def)}function nN($,U){if(!U)return $;return U.reduce((K,q)=>K?.[q],$)}function pN($){let U=Object.keys($),K=U.map((q)=>$[q]);return Promise.all(K).then((q)=>{let Q={};for(let W=0;W<U.length;W++)Q[U[W]]=q[W];return Q})}function tN($=10){let K="";for(let q=0;q<$;q++)K+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return K}function U2($){return JSON.stringify($)}function JU($){return $.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Q2="captureStackTrace"in Error?Error.captureStackTrace:(...$)=>{};function Z4($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var GU=f4(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});function y1($){if(Z4($)===!1)return!1;let U=$.constructor;if(U===void 0)return!0;if(typeof U!=="function")return!0;let K=U.prototype;if(Z4(K)===!1)return!1;if(Object.prototype.hasOwnProperty.call(K,"isPrototypeOf")===!1)return!1;return!0}function jU($){if(y1($))return{...$};if(Array.isArray($))return[...$];return $}function aN($){let U=0;for(let K in $)if(Object.prototype.hasOwnProperty.call($,K))U++;return U}var sN=($)=>{let U=typeof $;switch(U){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN($)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray($))return"array";if($===null)return"null";if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return"promise";if(typeof Map<"u"&&$ instanceof Map)return"map";if(typeof Set<"u"&&$ instanceof Set)return"set";if(typeof Date<"u"&&$ instanceof Date)return"date";if(typeof File<"u"&&$ instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${U}`)}},m6=new Set(["string","number","symbol"]),YU=new Set(["string","number","bigint","boolean","symbol","undefined"]);function o$($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function R$($,U,K){let q=new $._zod.constr(U??$._zod.def);if(!U||K?.parent)q._zod.parent=$;return q}function b($){let U=$;if(!U)return{};if(typeof U==="string")return{error:()=>U};if(U?.message!==void 0){if(U?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");U.error=U.message}if(delete U.message,typeof U.error==="string")return{...U,error:()=>U.error};return U}function eN($){let U;return new Proxy({},{get(K,q,Q){return U??(U=$()),Reflect.get(U,q,Q)},set(K,q,Q,W){return U??(U=$()),Reflect.set(U,q,Q,W)},has(K,q){return U??(U=$()),Reflect.has(U,q)},deleteProperty(K,q){return U??(U=$()),Reflect.deleteProperty(U,q)},ownKeys(K){return U??(U=$()),Reflect.ownKeys(U)},getOwnPropertyDescriptor(K,q){return U??(U=$()),Reflect.getOwnPropertyDescriptor(U,q)},defineProperty(K,q,Q){return U??(U=$()),Reflect.defineProperty(U,q,Q)}})}function v($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function HU($){return Object.keys($).filter((U)=>{return $[U]._zod.optin==="optional"&&$[U]._zod.optout==="optional"})}var XU={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},ZU={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function $L($,U){let K=$._zod.def,q=K.checks;if(q&&q.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let W=A1($._zod.def,{get shape(){let J={};for(let j in U){if(!(j in K.shape))throw Error(`Unrecognized key: "${j}"`);if(!U[j])continue;J[j]=K.shape[j]}return E1(this,"shape",J),J},checks:[]});return R$($,W)}function UL($,U){let K=$._zod.def,q=K.checks;if(q&&q.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let W=A1($._zod.def,{get shape(){let J={...$._zod.def.shape};for(let j in U){if(!(j in K.shape))throw Error(`Unrecognized key: "${j}"`);if(!U[j])continue;delete J[j]}return E1(this,"shape",J),J},checks:[]});return R$($,W)}function QL($,U){if(!y1(U))throw Error("Invalid input to extend: expected a plain object");let K=$._zod.def.checks;if(K&&K.length>0){let W=$._zod.def.shape;for(let J in U)if(Object.getOwnPropertyDescriptor(W,J)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let Q=A1($._zod.def,{get shape(){let W={...$._zod.def.shape,...U};return E1(this,"shape",W),W}});return R$($,Q)}function KL($,U){if(!y1(U))throw Error("Invalid input to safeExtend: expected a plain object");let K=A1($._zod.def,{get shape(){let q={...$._zod.def.shape,...U};return E1(this,"shape",q),q}});return R$($,K)}function qL($,U){let K=A1($._zod.def,{get shape(){let q={...$._zod.def.shape,...U._zod.def.shape};return E1(this,"shape",q),q},get catchall(){return U._zod.def.catchall},checks:[]});return R$($,K)}function WL($,U,K){let Q=U._zod.def.checks;if(Q&&Q.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let J=A1(U._zod.def,{get shape(){let j=U._zod.def.shape,Y={...j};if(K)for(let H in K){if(!(H in j))throw Error(`Unrecognized key: "${H}"`);if(!K[H])continue;Y[H]=$?new $({type:"optional",innerType:j[H]}):j[H]}else for(let H in j)Y[H]=$?new $({type:"optional",innerType:j[H]}):j[H];return E1(this,"shape",Y),Y},checks:[]});return R$(U,J)}function JL($,U,K){let q=A1(U._zod.def,{get shape(){let Q=U._zod.def.shape,W={...Q};if(K)for(let J in K){if(!(J in W))throw Error(`Unrecognized key: "${J}"`);if(!K[J])continue;W[J]=new $({type:"nonoptional",innerType:Q[J]})}else for(let J in Q)W[J]=new $({type:"nonoptional",innerType:Q[J]});return E1(this,"shape",W),W}});return R$(U,q)}function g1($,U=0){if($.aborted===!0)return!0;for(let K=U;K<$.issues.length;K++)if($.issues[K]?.continue!==!0)return!0;return!1}function m$($,U){return U.map((K)=>{var q;return(q=K).path??(q.path=[]),K.path.unshift($),K})}function g6($){return typeof $==="string"?$:$?.message}function E$($,U,K){let q={...$,path:$.path??[]};if(!$.message){let Q=g6($.inst?._zod.def?.error?.($))??g6(U?.error?.($))??g6(K.customError?.($))??g6(K.localeError?.($))??"Invalid input";q.message=Q}if(delete q.inst,delete q.continue,!U?.reportInput)delete q.input;return q}function h6($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function c6($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function k($){let U=typeof $;switch(U){case"number":return Number.isNaN($)?"nan":"number";case"object":{if($===null)return"null";if(Array.isArray($))return"array";let K=$;if(K&&Object.getPrototypeOf(K)!==Object.prototype&&"constructor"in K&&K.constructor)return K.constructor.name}}return U}function m4(...$){let[U,K,q]=$;if(typeof U==="string")return{message:U,code:"custom",input:K,inst:q};return{...U}}function GL($){return Object.entries($).filter(([U,K])=>{return Number.isNaN(Number.parseInt(U,10))}).map((U)=>U[1])}function Ej($){let U=atob($),K=new Uint8Array(U.length);for(let q=0;q<U.length;q++)K[q]=U.charCodeAt(q);return K}function yj($){let U="";for(let K=0;K<$.length;K++)U+=String.fromCharCode($[K]);return btoa(U)}function jL($){let U=$.replace(/-/g,"+").replace(/_/g,"/"),K="=".repeat((4-U.length%4)%4);return Ej(U+K)}function YL($){return yj($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function HL($){let U=$.replace(/^0x/,"");if(U.length%2!==0)throw Error("Invalid hex string length");let K=new Uint8Array(U.length/2);for(let q=0;q<U.length;q+=2)K[q/2]=Number.parseInt(U.slice(q,q+2),16);return K}function XL($){return Array.from($).map((U)=>U.toString(16).padStart(2,"0")).join("")}class gj{constructor(...$){}}var uj=($,U)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:U,enumerable:!1}),$.message=JSON.stringify(U,u4,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},l6=D("$ZodError",uj),y$=D("$ZodError",uj,{Parent:Error});function r6($,U=(K)=>K.message){let K={},q=[];for(let Q of $.issues)if(Q.path.length>0)K[Q.path[0]]=K[Q.path[0]]||[],K[Q.path[0]].push(U(Q));else q.push(U(Q));return{formErrors:q,fieldErrors:K}}function i6($,U=(K)=>K.message){let K={_errors:[]},q=(Q)=>{for(let W of Q.issues)if(W.code==="invalid_union"&&W.errors.length)W.errors.map((J)=>q({issues:J}));else if(W.code==="invalid_key")q({issues:W.issues});else if(W.code==="invalid_element")q({issues:W.issues});else if(W.path.length===0)K._errors.push(U(W));else{let J=K,j=0;while(j<W.path.length){let Y=W.path[j];if(j!==W.path.length-1)J[Y]=J[Y]||{_errors:[]};else J[Y]=J[Y]||{_errors:[]},J[Y]._errors.push(U(W));J=J[Y],j++}}};return q($),K}function BU($,U=(K)=>K.message){let K={errors:[]},q=(Q,W=[])=>{var J,j;for(let Y of Q.issues)if(Y.code==="invalid_union"&&Y.errors.length)Y.errors.map((H)=>q({issues:H},Y.path));else if(Y.code==="invalid_key")q({issues:Y.issues},Y.path);else if(Y.code==="invalid_element")q({issues:Y.issues},Y.path);else{let H=[...W,...Y.path];if(H.length===0){K.errors.push(U(Y));continue}let Z=K,B=0;while(B<H.length){let M=H[B],I=B===H.length-1;if(typeof M==="string")Z.properties??(Z.properties={}),(J=Z.properties)[M]??(J[M]={errors:[]}),Z=Z.properties[M];else Z.items??(Z.items=[]),(j=Z.items)[M]??(j[M]={errors:[]}),Z=Z.items[M];if(I)Z.errors.push(U(Y));B++}}};return q($),K}function fj($){let U=[],K=$.map((q)=>typeof q==="object"?q.key:q);for(let q of K)if(typeof q==="number")U.push(`[${q}]`);else if(typeof q==="symbol")U.push(`[${JSON.stringify(String(q))}]`);else if(/[^\w$]/.test(q))U.push(`[${JSON.stringify(q)}]`);else{if(U.length)U.push(".");U.push(q)}return U.join("")}function VU($){let U=[],K=[...$.issues].sort((q,Q)=>(q.path??[]).length-(Q.path??[]).length);for(let q of K)if(U.push(`✖ ${q.message}`),q.path?.length)U.push(` → at ${fj(q.path)}`);return U.join(`
|
|
53
|
-
`)}var h4=($)=>(U,K,q,Q)=>{let W=q?Object.assign(q,{async:!1}):{async:!1},J=U._zod.run({value:K,issues:[]},W);if(J instanceof Promise)throw new X1;if(J.issues.length){let j=new(Q?.Err??$)(J.issues.map((Y)=>E$(Y,W,Z$())));throw Q2(j,Q?.callee),j}return J.value},K2=h4(y$),c4=($)=>async(U,K,q,Q)=>{let W=q?Object.assign(q,{async:!0}):{async:!0},J=U._zod.run({value:K,issues:[]},W);if(J instanceof Promise)J=await J;if(J.issues.length){let j=new(Q?.Err??$)(J.issues.map((Y)=>E$(Y,W,Z$())));throw Q2(j,Q?.callee),j}return J.value},q2=c4(y$),l4=($)=>(U,K,q)=>{let Q=q?{...q,async:!1}:{async:!1},W=U._zod.run({value:K,issues:[]},Q);if(W instanceof Promise)throw new X1;return W.issues.length?{success:!1,error:new($??l6)(W.issues.map((J)=>E$(J,Q,Z$())))}:{success:!0,data:W.value}},MU=l4(y$),r4=($)=>async(U,K,q)=>{let Q=q?Object.assign(q,{async:!0}):{async:!0},W=U._zod.run({value:K,issues:[]},Q);if(W instanceof Promise)W=await W;return W.issues.length?{success:!1,error:new $(W.issues.map((J)=>E$(J,Q,Z$())))}:{success:!0,data:W.value}},DU=r4(y$),W2=($)=>(U,K,q)=>{let Q=q?Object.assign(q,{direction:"backward"}):{direction:"backward"};return h4($)(U,K,Q)},BL=W2(y$),J2=($)=>(U,K,q)=>{return h4($)(U,K,q)},VL=J2(y$),G2=($)=>async(U,K,q)=>{let Q=q?Object.assign(q,{direction:"backward"}):{direction:"backward"};return c4($)(U,K,Q)},ML=G2(y$),j2=($)=>async(U,K,q)=>{return c4($)(U,K,q)},DL=j2(y$),Y2=($)=>(U,K,q)=>{let Q=q?Object.assign(q,{direction:"backward"}):{direction:"backward"};return l4($)(U,K,Q)},PL=Y2(y$),H2=($)=>(U,K,q)=>{return l4($)(U,K,q)},NL=H2(y$),X2=($)=>async(U,K,q)=>{let Q=q?Object.assign(q,{direction:"backward"}):{direction:"backward"};return r4($)(U,K,Q)},LL=X2(y$),Z2=($)=>async(U,K,q)=>{return r4($)(U,K,q)},_L=Z2(y$);var n$={};L1(n$,{xid:()=>_U,uuid7:()=>wL,uuid6:()=>xL,uuid4:()=>FL,uuid:()=>B4,uppercase:()=>rU,unicodeEmail:()=>mj,undefined:()=>cU,ulid:()=>LU,time:()=>EU,string:()=>gU,sha512_hex:()=>iL,sha512_base64url:()=>oL,sha512_base64:()=>dL,sha384_hex:()=>cL,sha384_base64url:()=>rL,sha384_base64:()=>lL,sha256_hex:()=>fL,sha256_base64url:()=>hL,sha256_base64:()=>mL,sha1_hex:()=>yL,sha1_base64url:()=>uL,sha1_base64:()=>gL,rfc5322Email:()=>vL,number:()=>d6,null:()=>hU,nanoid:()=>FU,md5_hex:()=>SL,md5_base64url:()=>EL,md5_base64:()=>CL,mac:()=>zU,lowercase:()=>lU,ksuid:()=>IU,ipv6:()=>RU,ipv4:()=>kU,integer:()=>fU,idnEmail:()=>kL,html5Email:()=>AL,hostname:()=>bL,hex:()=>TL,guid:()=>wU,extendedDuration:()=>IL,emoji:()=>vU,email:()=>AU,e164:()=>SU,duration:()=>xU,domain:()=>OL,datetime:()=>yU,date:()=>CU,cuid2:()=>NU,cuid:()=>PU,cidrv6:()=>OU,cidrv4:()=>bU,browserEmail:()=>RL,boolean:()=>mU,bigint:()=>uU,base64url:()=>B2,base64:()=>TU});var PU=/^[cC][^\s-]{8,}$/,NU=/^[0-9a-z]+$/,LU=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,_U=/^[0-9a-vA-V]{20}$/,IU=/^[A-Za-z0-9]{27}$/,FU=/^[a-zA-Z0-9_-]{21}$/,xU=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,IL=/^[-+]?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)?)??$/,wU=/^([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})$/,B4=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},FL=B4(4),xL=B4(6),wL=B4(7),AU=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,AL=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,vL=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,mj=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,kL=mj,RL=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,zL="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function vU(){return new RegExp(zL,"u")}var kU=/^(?:(?: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])$/,RU=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,zU=($)=>{let U=o$($??":");return new RegExp(`^(?:[0-9A-F]{2}${U}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${U}){5}[0-9a-f]{2}$`)},bU=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,OU=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,TU=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,B2=/^[A-Za-z0-9_-]*$/,bL=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,OL=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,SU=/^\+[1-9]\d{6,14}$/,hj="(?:(?:\\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])))",CU=new RegExp(`^${hj}$`);function cj($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function EU($){return new RegExp(`^${cj($)}$`)}function yU($){let U=cj({precision:$.precision}),K=["Z"];if($.local)K.push("");if($.offset)K.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let q=`${U}(?:${K.join("|")})`;return new RegExp(`^${hj}T(?:${q})$`)}var gU=($)=>{let U=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${U}$`)},uU=/^-?\d+n?$/,fU=/^-?\d+$/,d6=/^-?\d+(?:\.\d+)?$/,mU=/^(?:true|false)$/i,hU=/^null$/i;var cU=/^undefined$/i;var lU=/^[^A-Z]*$/,rU=/^[^a-z]*$/,TL=/^[0-9a-fA-F]*$/;function o6($,U){return new RegExp(`^[A-Za-z0-9+/]{${$}}${U}$`)}function n6($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var SL=/^[0-9a-fA-F]{32}$/,CL=o6(22,"=="),EL=n6(22),yL=/^[0-9a-fA-F]{40}$/,gL=o6(27,"="),uL=n6(27),fL=/^[0-9a-fA-F]{64}$/,mL=o6(43,"="),hL=n6(43),cL=/^[0-9a-fA-F]{96}$/,lL=o6(64,""),rL=n6(64),iL=/^[0-9a-fA-F]{128}$/,dL=o6(86,"=="),oL=n6(86);var $$=D("$ZodCheck",($,U)=>{var K;$._zod??($._zod={}),$._zod.def=U,(K=$._zod).onattach??(K.onattach=[])}),rj={number:"number",bigint:"bigint",object:"date"},V2=D("$ZodCheckLessThan",($,U)=>{$$.init($,U);let K=rj[typeof U.value];$._zod.onattach.push((q)=>{let Q=q._zod.bag,W=(U.inclusive?Q.maximum:Q.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(U.value<W)if(U.inclusive)Q.maximum=U.value;else Q.exclusiveMaximum=U.value}),$._zod.check=(q)=>{if(U.inclusive?q.value<=U.value:q.value<U.value)return;q.issues.push({origin:K,code:"too_big",maximum:typeof U.value==="object"?U.value.getTime():U.value,input:q.value,inclusive:U.inclusive,inst:$,continue:!U.abort})}}),M2=D("$ZodCheckGreaterThan",($,U)=>{$$.init($,U);let K=rj[typeof U.value];$._zod.onattach.push((q)=>{let Q=q._zod.bag,W=(U.inclusive?Q.minimum:Q.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(U.value>W)if(U.inclusive)Q.minimum=U.value;else Q.exclusiveMinimum=U.value}),$._zod.check=(q)=>{if(U.inclusive?q.value>=U.value:q.value>U.value)return;q.issues.push({origin:K,code:"too_small",minimum:typeof U.value==="object"?U.value.getTime():U.value,input:q.value,inclusive:U.inclusive,inst:$,continue:!U.abort})}}),iU=D("$ZodCheckMultipleOf",($,U)=>{$$.init($,U),$._zod.onattach.push((K)=>{var q;(q=K._zod.bag).multipleOf??(q.multipleOf=U.value)}),$._zod.check=(K)=>{if(typeof K.value!==typeof U.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof K.value==="bigint"?K.value%U.value===BigInt(0):WU(K.value,U.value)===0)return;K.issues.push({origin:typeof K.value,code:"not_multiple_of",divisor:U.value,input:K.value,inst:$,continue:!U.abort})}}),dU=D("$ZodCheckNumberFormat",($,U)=>{$$.init($,U),U.format=U.format||"float64";let K=U.format?.includes("int"),q=K?"int":"number",[Q,W]=XU[U.format];$._zod.onattach.push((J)=>{let j=J._zod.bag;if(j.format=U.format,j.minimum=Q,j.maximum=W,K)j.pattern=fU}),$._zod.check=(J)=>{let j=J.value;if(K){if(!Number.isInteger(j)){J.issues.push({expected:q,format:U.format,code:"invalid_type",continue:!1,input:j,inst:$});return}if(!Number.isSafeInteger(j)){if(j>0)J.issues.push({input:j,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:q,inclusive:!0,continue:!U.abort});else J.issues.push({input:j,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:q,inclusive:!0,continue:!U.abort});return}}if(j<Q)J.issues.push({origin:"number",input:j,code:"too_small",minimum:Q,inclusive:!0,inst:$,continue:!U.abort});if(j>W)J.issues.push({origin:"number",input:j,code:"too_big",maximum:W,inclusive:!0,inst:$,continue:!U.abort})}}),oU=D("$ZodCheckBigIntFormat",($,U)=>{$$.init($,U);let[K,q]=ZU[U.format];$._zod.onattach.push((Q)=>{let W=Q._zod.bag;W.format=U.format,W.minimum=K,W.maximum=q}),$._zod.check=(Q)=>{let W=Q.value;if(W<K)Q.issues.push({origin:"bigint",input:W,code:"too_small",minimum:K,inclusive:!0,inst:$,continue:!U.abort});if(W>q)Q.issues.push({origin:"bigint",input:W,code:"too_big",maximum:q,inclusive:!0,inst:$,continue:!U.abort})}}),nU=D("$ZodCheckMaxSize",($,U)=>{var K;$$.init($,U),(K=$._zod.def).when??(K.when=(q)=>{let Q=q.value;return!C1(Q)&&Q.size!==void 0}),$._zod.onattach.push((q)=>{let Q=q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(U.maximum<Q)q._zod.bag.maximum=U.maximum}),$._zod.check=(q)=>{let Q=q.value;if(Q.size<=U.maximum)return;q.issues.push({origin:h6(Q),code:"too_big",maximum:U.maximum,inclusive:!0,input:Q,inst:$,continue:!U.abort})}}),pU=D("$ZodCheckMinSize",($,U)=>{var K;$$.init($,U),(K=$._zod.def).when??(K.when=(q)=>{let Q=q.value;return!C1(Q)&&Q.size!==void 0}),$._zod.onattach.push((q)=>{let Q=q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(U.minimum>Q)q._zod.bag.minimum=U.minimum}),$._zod.check=(q)=>{let Q=q.value;if(Q.size>=U.minimum)return;q.issues.push({origin:h6(Q),code:"too_small",minimum:U.minimum,inclusive:!0,input:Q,inst:$,continue:!U.abort})}}),tU=D("$ZodCheckSizeEquals",($,U)=>{var K;$$.init($,U),(K=$._zod.def).when??(K.when=(q)=>{let Q=q.value;return!C1(Q)&&Q.size!==void 0}),$._zod.onattach.push((q)=>{let Q=q._zod.bag;Q.minimum=U.size,Q.maximum=U.size,Q.size=U.size}),$._zod.check=(q)=>{let Q=q.value,W=Q.size;if(W===U.size)return;let J=W>U.size;q.issues.push({origin:h6(Q),...J?{code:"too_big",maximum:U.size}:{code:"too_small",minimum:U.size},inclusive:!0,exact:!0,input:q.value,inst:$,continue:!U.abort})}}),aU=D("$ZodCheckMaxLength",($,U)=>{var K;$$.init($,U),(K=$._zod.def).when??(K.when=(q)=>{let Q=q.value;return!C1(Q)&&Q.length!==void 0}),$._zod.onattach.push((q)=>{let Q=q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(U.maximum<Q)q._zod.bag.maximum=U.maximum}),$._zod.check=(q)=>{let Q=q.value;if(Q.length<=U.maximum)return;let J=c6(Q);q.issues.push({origin:J,code:"too_big",maximum:U.maximum,inclusive:!0,input:Q,inst:$,continue:!U.abort})}}),sU=D("$ZodCheckMinLength",($,U)=>{var K;$$.init($,U),(K=$._zod.def).when??(K.when=(q)=>{let Q=q.value;return!C1(Q)&&Q.length!==void 0}),$._zod.onattach.push((q)=>{let Q=q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(U.minimum>Q)q._zod.bag.minimum=U.minimum}),$._zod.check=(q)=>{let Q=q.value;if(Q.length>=U.minimum)return;let J=c6(Q);q.issues.push({origin:J,code:"too_small",minimum:U.minimum,inclusive:!0,input:Q,inst:$,continue:!U.abort})}}),eU=D("$ZodCheckLengthEquals",($,U)=>{var K;$$.init($,U),(K=$._zod.def).when??(K.when=(q)=>{let Q=q.value;return!C1(Q)&&Q.length!==void 0}),$._zod.onattach.push((q)=>{let Q=q._zod.bag;Q.minimum=U.length,Q.maximum=U.length,Q.length=U.length}),$._zod.check=(q)=>{let Q=q.value,W=Q.length;if(W===U.length)return;let J=c6(Q),j=W>U.length;q.issues.push({origin:J,...j?{code:"too_big",maximum:U.length}:{code:"too_small",minimum:U.length},inclusive:!0,exact:!0,input:q.value,inst:$,continue:!U.abort})}}),i4=D("$ZodCheckStringFormat",($,U)=>{var K,q;if($$.init($,U),$._zod.onattach.push((Q)=>{let W=Q._zod.bag;if(W.format=U.format,U.pattern)W.patterns??(W.patterns=new Set),W.patterns.add(U.pattern)}),U.pattern)(K=$._zod).check??(K.check=(Q)=>{if(U.pattern.lastIndex=0,U.pattern.test(Q.value))return;Q.issues.push({origin:"string",code:"invalid_format",format:U.format,input:Q.value,...U.pattern?{pattern:U.pattern.toString()}:{},inst:$,continue:!U.abort})});else(q=$._zod).check??(q.check=()=>{})}),$9=D("$ZodCheckRegex",($,U)=>{i4.init($,U),$._zod.check=(K)=>{if(U.pattern.lastIndex=0,U.pattern.test(K.value))return;K.issues.push({origin:"string",code:"invalid_format",format:"regex",input:K.value,pattern:U.pattern.toString(),inst:$,continue:!U.abort})}}),U9=D("$ZodCheckLowerCase",($,U)=>{U.pattern??(U.pattern=lU),i4.init($,U)}),Q9=D("$ZodCheckUpperCase",($,U)=>{U.pattern??(U.pattern=rU),i4.init($,U)}),K9=D("$ZodCheckIncludes",($,U)=>{$$.init($,U);let K=o$(U.includes),q=new RegExp(typeof U.position==="number"?`^.{${U.position}}${K}`:K);U.pattern=q,$._zod.onattach.push((Q)=>{let W=Q._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add(q)}),$._zod.check=(Q)=>{if(Q.value.includes(U.includes,U.position))return;Q.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:U.includes,input:Q.value,inst:$,continue:!U.abort})}}),q9=D("$ZodCheckStartsWith",($,U)=>{$$.init($,U);let K=new RegExp(`^${o$(U.prefix)}.*`);U.pattern??(U.pattern=K),$._zod.onattach.push((q)=>{let Q=q._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add(K)}),$._zod.check=(q)=>{if(q.value.startsWith(U.prefix))return;q.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:U.prefix,input:q.value,inst:$,continue:!U.abort})}}),W9=D("$ZodCheckEndsWith",($,U)=>{$$.init($,U);let K=new RegExp(`.*${o$(U.suffix)}$`);U.pattern??(U.pattern=K),$._zod.onattach.push((q)=>{let Q=q._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add(K)}),$._zod.check=(q)=>{if(q.value.endsWith(U.suffix))return;q.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:U.suffix,input:q.value,inst:$,continue:!U.abort})}});function lj($,U,K){if($.issues.length)U.issues.push(...m$(K,$.issues))}var J9=D("$ZodCheckProperty",($,U)=>{$$.init($,U),$._zod.check=(K)=>{let q=U.schema._zod.run({value:K.value[U.property],issues:[]},{});if(q instanceof Promise)return q.then((Q)=>lj(Q,K,U.property));lj(q,K,U.property);return}}),G9=D("$ZodCheckMimeType",($,U)=>{$$.init($,U);let K=new Set(U.mime);$._zod.onattach.push((q)=>{q._zod.bag.mime=U.mime}),$._zod.check=(q)=>{if(K.has(q.value.type))return;q.issues.push({code:"invalid_value",values:U.mime,input:q.value.type,inst:$,continue:!U.abort})}}),j9=D("$ZodCheckOverwrite",($,U)=>{$$.init($,U),$._zod.check=(K)=>{K.value=U.tx(K.value)}});class D2{constructor($=[]){if(this.content=[],this.indent=0,this)this.args=$}indented($){this.indent+=1,$(this),this.indent-=1}write($){if(typeof $==="function"){$(this,{execution:"sync"}),$(this,{execution:"async"});return}let K=$.split(`
|
|
36
|
+
`}function EP($){let U="";for(let K of $??[])dJ(K),U+=`: ${K}
|
|
37
|
+
`;return U}function E6($){let U="";if(U+=EP($.comments),$.event!==void 0)SP($.event),U+=`event: ${$.event}
|
|
38
|
+
`;if($.retry!==void 0)iJ($.retry),U+=`retry: ${$.retry}
|
|
39
|
+
`;if($.id!==void 0)rJ($.id),U+=`id: ${$.id}
|
|
40
|
+
`;return U+=CP($.data),U+=`
|
|
41
|
+
`,U}var oJ=Symbol("ORPC_EVENT_SOURCE_META");function G4($,U){if(U.id===void 0&&U.retry===void 0&&!U.comments?.length)return $;if(U.id!==void 0)rJ(U.id);if(U.retry!==void 0)iJ(U.retry);if(U.comments!==void 0)for(let K of U.comments)dJ(K);return new Proxy($,{get(K,q,Q){if(q===oJ)return U;return Reflect.get(K,q,Q)}})}function O4($){return Y1($)?Reflect.get($,oJ):void 0}function nJ($,U="inline"){let K=$.replace(/[^\x20-\x7E]/g,"_").replace(/"/g,"\\\""),q=encodeURIComponent($).replace(/['()*]/g,(Q)=>`%${Q.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(7C|60|5E)/g,(Q,W)=>String.fromCharCode(Number.parseInt(W,16)));return`${U}; filename="${K}"; filename*=utf-8''${q}`}function pJ($){let U=$.match(/filename\*=(UTF-8'')?([^;]*)/i);if(U&&typeof U[2]==="string")return fJ(U[2]);let K=$.match(/filename="((?:\\"|[^"])*)"/i);if(K&&typeof K[1]==="string")return K[1].replace(/\\"/g,'"')}function tJ($,U){let K={...$};for(let q in U)if(Array.isArray(U[q]))K[q]=[...Q4(K[q]),...U[q]];else if(U[q]!==void 0)if(Array.isArray(K[q]))K[q]=[...K[q],U[q]];else if(K[q]!==void 0)K[q]=[K[q],U[q]];else K[q]=U[q];return K}function u8($,U){let K=async(q)=>{let Q=await U.error(q);if(Q!==q){let W=O4(q);if(W&&Y1(Q))Q=G4(Q,W)}return Q};return new T1(async()=>{let{done:q,value:Q}=await(async()=>{try{return await $.next()}catch(G){throw await K(G)}})(),W=await U.value(Q,q);if(W!==Q){let G=O4(Q);if(G&&Y1(W))W=G4(W,G)}return{done:q,value:W}},async()=>{try{await $.return?.()}catch(q){throw await K(q)}})}function yP($){return{...$,context:$.context??{}}}function S1($,U){return(async()=>{let K;try{let q=await $;while(!0){let{done:Q,value:W}=await q.next();if(Q){let G=W;K=[null,G,!0],U.onSuccess?.(G);break}U.onEvent(W)}}catch(q){if(K=[q,void 0,!1],!U.onError&&!U.onFinish)throw q;U.onError?.(q)}finally{U.onFinish?.(K)}})(),async()=>{await(await $)?.return?.()}}function J4($,U={}){let K=U.path??[],Q=new Proxy(async(...[W,G={}])=>{return await $.call(K,W,yP(G))},{get(W,G){if(typeof G!=="string"||mJ.has(G))return Reflect.get(W,G);return J4($,{...U,path:[...K,G]})}});return S8(Q)}function gP($,U={}){let q=$?.pipeThrough(new TextDecoderStream).pipeThrough(new y8)?.getReader(),Q,W=!1;return new T1(async()=>{Q??=i0("consume_event_iterator_stream");try{while(!0){if(q===void 0)return{done:!0,value:void 0};let{done:G,value:j}=await U4(Q,()=>q.read());if(G){if(W)throw new O8("Stream was cancelled");return{done:!0,value:void 0}}switch(j.event){case"message":{let Y=T6(j.data);if(Y1(Y))Y=G4(Y,j);return Q?.addEvent("message"),{done:!1,value:Y}}case"error":{let Y=new w1({data:T6(j.data)});throw Y=G4(Y,j),Q?.addEvent("error"),Y}case"done":{let Y=T6(j.data);if(Y1(Y))Y=G4(Y,j);return Q?.addEvent("done"),{done:!0,value:Y}}default:Q?.addEvent("maybe_keepalive")}}}catch(G){if(!(G instanceof w1))O1(Q,G,U);throw G}},async(G)=>{try{if(G!=="next")W=!0,Q?.addEvent("cancelled");await U4(Q,()=>q?.cancel())}catch(j){throw O1(Q,j,U),j}finally{Q?.end()}})}function uP($,U={}){let K=U.eventIteratorKeepAliveEnabled??!0,q=U.eventIteratorKeepAliveInterval??5000,Q=U.eventIteratorKeepAliveComment??"",W=U.eventIteratorInitialCommentEnabled??!0,G=U.eventIteratorInitialComment??"",j=!1,Y,H;return new ReadableStream({start(B){if(H=i0("stream_event_iterator"),W)B.enqueue(E6({comments:[G]}))},async pull(B){try{if(K)Y=setInterval(()=>{B.enqueue(E6({comments:[Q]})),H?.addEvent("keepalive")},q);let M=await U4(H,()=>$.next());if(clearInterval(Y),j)return;let I=O4(M.value);if(!M.done||M.value!==void 0||I!==void 0){let E=M.done?"done":"message";B.enqueue(E6({...I,event:E,data:q4(M.value)})),H?.addEvent(E)}if(M.done)B.close(),H?.end()}catch(M){if(clearInterval(Y),j)return;if(M instanceof w1)B.enqueue(E6({...O4(M),event:"error",data:q4(M.data)})),H?.addEvent("error"),B.close();else O1(H,M),B.error(M);H?.end()}},async cancel(){try{j=!0,clearInterval(Y),H?.addEvent("cancelled"),await U4(H,()=>$.return?.())}catch(B){throw O1(H,B),B}finally{H?.end()}}}).pipeThrough(new TextEncoderStream)}function fP($,U={}){return K4({name:"parse_standard_body",signal:U.signal},async()=>{let K=$.headers.get("content-disposition");if(typeof K==="string"){let W=pJ(K)??"blob",G=await $.blob();return new File([G],W,{type:G.type})}let q=$.headers.get("content-type");if(!q||q.startsWith("application/json")){let W=await $.text();return T6(W)}if(q.startsWith("multipart/form-data"))return await $.formData();if(q.startsWith("application/x-www-form-urlencoded")){let W=await $.text();return new URLSearchParams(W)}if(q.startsWith("text/event-stream"))return gP($.body,U);if(q.startsWith("text/plain"))return await $.text();let Q=await $.blob();return new File([Q],"blob",{type:Q.type})})}function mP($,U,K={}){if($ instanceof ReadableStream)return $;let q=U.get("content-disposition");if(U.delete("content-type"),U.delete("content-disposition"),$===void 0)return;if($ instanceof Blob)return U.set("content-type",$.type),U.set("content-length",$.size.toString()),U.set("content-disposition",q??nJ($ instanceof File?$.name:"blob")),$;if($ instanceof FormData)return $;if($ instanceof URLSearchParams)return $;if(x1($))return U.set("content-type","text/event-stream"),uP($,K);return U.set("content-type","application/json"),q4($)}function f8($,U={}){return $.forEach((K,q)=>{if(Array.isArray(U[q]))U[q].push(K);else if(U[q]!==void 0)U[q]=[U[q],K];else U[q]=K}),U}function hP($,U=new Headers){for(let[K,q]of Object.entries($))if(Array.isArray(q))for(let Q of q)U.append(K,Q);else if(q!==void 0)U.append(K,q);return U}function aJ($,U={}){let K=hP($.headers),q=mP($.body,K,U);return new Request($.url,{signal:$.signal,method:$.method,headers:K,body:q})}function sJ($,U={}){return{body:r0(()=>fP($,U)),status:$.status,get headers(){let K=f8($.headers);return Object.defineProperty(this,"headers",{value:K,writable:!0}),K},set headers(K){Object.defineProperty(this,"headers",{value:K,writable:!0})}}}class t0{plugins;constructor($=[]){this.plugins=[...$].sort((U,K)=>(U.order??0)-(K.order??0))}init($){for(let U of this.plugins)U.init?.($)}}class eJ{constructor($,U,K={}){this.codec=$,this.sender=U,new t0(K.plugins).init(K),this.interceptors=Q4(K.interceptors),this.clientInterceptors=Q4(K.clientInterceptors)}interceptors;clientInterceptors;call($,U,K){return K4({name:`${b8}.${$.join("/")}`,signal:K.signal},(q)=>{if(q?.setAttribute("rpc.system",b8),q?.setAttribute("rpc.method",$.join(".")),x1(U))U=T8({name:"consume_event_iterator_input",signal:K.signal},U);return O6(this.interceptors,{...K,path:$,input:U},async({path:Q,input:W,...G})=>{let j=b6(),Y,H=j?.trace.getActiveSpan()??q;if(H&&j)Y=j?.trace.setSpan(j.context.active(),H);let X=await K4({name:"encode_request",context:Y},()=>this.codec.encode(Q,W,G)),B=await O6(this.clientInterceptors,{...G,input:W,path:Q,request:X},({input:I,path:E,request:u,...U$})=>{return K4({name:"send_request",signal:U$.signal,context:Y},()=>this.sender.call(u,U$,E,I))}),M=await K4({name:"decode_response",context:Y},()=>this.codec.decode(B,G,Q,W));if(x1(M))return T8({name:"consume_event_iterator_output",signal:G.signal},M);return M})})}}var F$={BIGINT:0,DATE:1,NAN:2,UNDEFINED:3,URL:4,REGEXP:5,SET:6,MAP:7};class $j{customSerializers;constructor($={}){if(this.customSerializers=$.customJsonSerializers??[],this.customSerializers.length!==new Set(this.customSerializers.map((U)=>U.type)).size)throw Error("Custom serializer type must be unique.")}serialize($,U=[],K=[],q=[],Q=[]){for(let W of this.customSerializers)if(W.condition($)){let G=this.serialize(W.serialize($),U,K,q,Q);return K.push([W.type,...U]),G}if($ instanceof Blob)return q.push(U),Q.push($),[$,K,q,Q];if(typeof $==="bigint")return K.push([F$.BIGINT,...U]),[$.toString(),K,q,Q];if($ instanceof Date){if(K.push([F$.DATE,...U]),Number.isNaN($.getTime()))return[null,K,q,Q];return[$.toISOString(),K,q,Q]}if(Number.isNaN($))return K.push([F$.NAN,...U]),[null,K,q,Q];if($ instanceof URL)return K.push([F$.URL,...U]),[$.toString(),K,q,Q];if($ instanceof RegExp)return K.push([F$.REGEXP,...U]),[$.toString(),K,q,Q];if($ instanceof Set){let W=this.serialize(Array.from($),U,K,q,Q);return K.push([F$.SET,...U]),W}if($ instanceof Map){let W=this.serialize(Array.from($.entries()),U,K,q,Q);return K.push([F$.MAP,...U]),W}if(Array.isArray($))return[$.map((G,j)=>{if(G===void 0)return K.push([F$.UNDEFINED,...U,j]),null;return this.serialize(G,[...U,j],K,q,Q)[0]}),K,q,Q];if(d0($)){let W={};for(let G in $){if(G==="toJSON"&&typeof $[G]==="function")continue;W[G]=this.serialize($[G],[...U,G],K,q,Q)[0]}return[W,K,q,Q]}return[$,K,q,Q]}deserialize($,U,K,q){let Q={data:$};if(K&&q)K.forEach((W,G)=>{let j=Q,Y="data";W.forEach((H)=>{if(j=j[Y],Y=H,!Object.hasOwn(j,Y))throw Error(`Security error: accessing non-existent path during deserialization. Path segment: ${Y}`)}),j[Y]=q(G)});for(let W of U){let G=W[0],j=Q,Y="data";for(let H=1;H<W.length;H++)if(j=j[Y],Y=W[H],!Object.hasOwn(j,Y))throw Error(`Security error: accessing non-existent path during deserialization. Path segment: ${Y}`);for(let H of this.customSerializers)if(H.type===G){j[Y]=H.deserialize(j[Y]);break}switch(G){case F$.BIGINT:j[Y]=BigInt(j[Y]);break;case F$.DATE:j[Y]=new Date(j[Y]??"Invalid Date");break;case F$.NAN:j[Y]=Number.NaN;break;case F$.UNDEFINED:j[Y]=void 0;break;case F$.URL:j[Y]=new URL(j[Y]);break;case F$.REGEXP:{let[,H,X]=j[Y].match(/^\/(.*)\/([a-z]*)$/);j[Y]=new RegExp(H,X);break}case F$.SET:j[Y]=new Set(j[Y]);break;case F$.MAP:j[Y]=new Map(j[Y]);break}}return Q.data}}function cP($){return`/${$.map(encodeURIComponent).join("/")}`}function lP($){if(typeof $.forEach==="function")return f8($);return $}function rP($){return Object.entries(n0).find(([,U])=>U.status===$)?.[0]??"MALFORMED_ORPC_ERROR_RESPONSE"}class Uj{constructor($,U){this.serializer=$,this.baseUrl=U.url,this.maxUrlLength=U.maxUrlLength??2083,this.fallbackMethod=U.fallbackMethod??"POST",this.expectedMethod=U.method??this.fallbackMethod,this.headers=U.headers??{}}baseUrl;maxUrlLength;fallbackMethod;expectedMethod;headers;async encode($,U,K){let q=lP(await S6(this.headers,K,$,U));if(K.lastEventId!==void 0)q=tJ(q,{"last-event-id":K.lastEventId});let Q=await S6(this.expectedMethod,K,$,U),W=await S6(this.baseUrl,K,$,U),G=new URL(W);G.pathname=`${G.pathname.replace(/\/$/,"")}${cP($)}`;let j=this.serializer.serialize(U);if(Q==="GET"&&!(j instanceof FormData)&&!x1(j)){let Y=await S6(this.maxUrlLength,K,$,U),H=new URL(G);if(H.searchParams.append("data",q4(j)),H.toString().length<=Y)return{body:void 0,method:Q,headers:q,url:H,signal:K.signal}}return{url:G,method:Q==="GET"?this.fallbackMethod:Q,headers:q,body:j,signal:K.signal}}async decode($){let U=!p0($.status),K=await(async()=>{let q=!1;try{let Q=await $.body();return q=!0,this.serializer.deserialize(Q)}catch(Q){if(!q)throw Error("Cannot parse response body, please check the response body and content-type.",{cause:Q});throw Error("Invalid RPC response format.",{cause:Q})}})();if(!U){if(C8(K))throw E8(K);throw new W4(rP($.status),{status:$.status,data:{...$,body:K}})}return K}}class Qj{constructor($){this.jsonSerializer=$}serialize($){if(x1($))return u8($,{value:async(U)=>this.#$(U,!1),error:async(U)=>{return new w1({data:this.#$(hJ(U).toJSON(),!1),cause:U})}});return this.#$($,!0)}#$($,U){let[K,q,Q,W]=this.jsonSerializer.serialize($),G=q.length===0?void 0:q;if(!U||W.length===0)return{json:K,meta:G};let j=new FormData;return j.set("data",q4({json:K,meta:G,maps:Q})),W.forEach((Y,H)=>{j.set(H.toString(),Y)}),j}deserialize($){if(x1($))return u8($,{value:async(U)=>this.#U(U),error:async(U)=>{if(!(U instanceof w1))return U;let K=this.#U(U.data);if(C8(K))return E8(K,{cause:U});return new w1({data:K,cause:U})}});return this.#U($)}#U($){if($===void 0)return;if(!($ instanceof FormData))return this.jsonSerializer.deserialize($.json,$.meta??[]);let U=JSON.parse($.get("data"));return this.jsonSerializer.deserialize(U.json,U.meta??[],U.maps,(K)=>$.get(K.toString()))}}class m8 extends eJ{constructor($,U){let K=new $j(U),q=new Qj(K),Q=new Uj(q,U);super(Q,$,U)}}class Kj extends t0{initRuntimeAdapter($){for(let U of this.plugins)U.initRuntimeAdapter?.($)}}class qj{fetch;toFetchRequestOptions;adapterInterceptors;constructor($){new Kj($.plugins).initRuntimeAdapter($),this.fetch=$.fetch??globalThis.fetch.bind(globalThis),this.toFetchRequestOptions=$,this.adapterInterceptors=Q4($.adapterInterceptors)}async call($,U,K,q){let Q=aJ($,this.toFetchRequestOptions),W=await O6(this.adapterInterceptors,{...U,request:Q,path:K,input:q,init:{redirect:"manual"}},({request:j,path:Y,input:H,init:X,...B})=>this.fetch(j,X,B,Y,H));return sJ(W,{signal:Q.signal})}}class j4 extends m8{constructor($){let U=new qj($);super(U,$)}}import{chmodSync as h8,mkdirSync as Wj,readFileSync as iP,writeFileSync as c8}from"node:fs";import{homedir as dP}from"node:os";import{join as Gj}from"node:path";function T4($){let U=$.length;while(U>0&&$[U-1]==="/")U-=1;return $.slice(0,U)}var l8=Gj(dP(),".niva"),Y4=Gj(l8,"config.json");function y6(){try{let $=JSON.parse(iP(Y4,"utf-8"));return Q$($)?$:{}}catch{return{}}}function Jj($,U){Wj(l8,{recursive:!0});let q={...y6(),[$]:U};c8(Y4,`${JSON.stringify(q,null,2)}
|
|
42
|
+
`,{mode:384}),h8(Y4,384)}function r8(){return y6()}function S4($){return T4($)}function oP($){let U=Q$($)?{...$}:void 0;if(U==null)return!1;let K=U.scopes;return typeof U.access_token==="string"&&typeof U.refresh_token==="string"&&typeof U.expires_at==="number"&&typeof U.org_id==="string"&&Array.isArray(K)&&K.every((q)=>typeof q==="string")}function i8(){let $=y6().auth;return Q$($)?$:{}}function jj(){let $={};for(let[U,K]of Object.entries(i8()))if(oP(K))$[U]=K;return $}function C4($,U){Wj(l8,{recursive:!0});let K={...y6(),auth:{...i8(),[S4($)]:U}};c8(Y4,`${JSON.stringify(K,null,2)}
|
|
43
|
+
`,{mode:384}),h8(Y4,384)}function Yj($){let U=i8(),K=S4($);if(!(K in U))return;delete U[K];let q={...y6(),auth:U};c8(Y4,`${JSON.stringify(q,null,2)}
|
|
44
|
+
`,{mode:384}),h8(Y4,384)}import{createHash as nP,randomBytes as Xj}from"node:crypto";import{createServer as pP}from"node:http";var tP=600000,aP=120,sP=5;class L$ extends Error{code;constructor($,U){super(U);this.code=$}}function eP($){let U=K$($),K=l(U?.access_token),q=p1(U?.expires_in);if(U==null||K==null||q==null)return null;let Q=l(U.refresh_token),W=l(U.scope);return{access_token:K,expires_in:q,...Q!=null?{refresh_token:Q}:{},...W!=null?{scope:W}:{}}}function Zj($,U){let K=K$($),q=l(K?.error)??`http_${String(U)}`,Q=l(K?.error_description)??q;return new L$(q,Q)}function $N(){return Xj(32).toString("base64url")}function UN($){return nP("sha256").update($).digest("base64url")}function Bj($,U){if($.NIVA_NO_BROWSER==="1")return!1;let K=$.CI;if(K==="true"||K==="1")return!1;if(U==="linux")return $.DISPLAY!=null||$.WAYLAND_DISPLAY!=null;return!0}function d8($){let U;if(process.platform==="darwin")U=[["open",$]];else if(process.platform==="win32")U=[["cmd","/c","start","",$]];else U=[["xdg-open",$]];for(let K of U){let[q,...Q]=K;if(q==null)continue;try{return Bun.spawn([q,...Q],{stdout:"ignore",stderr:"ignore"}).exited.then((G)=>{if(G!==0)Hj($)}),!0}catch{continue}}return Hj($),!1}function Hj($){console.error(`Open this URL to continue: ${$}`)}async function o8($){let U=new URL("/.well-known/oauth-authorization-server",T4($)),K=await fetch(U),q=await K.json().catch(()=>({})),Q=K$(q),W=l(Q?.issuer),G=l(Q?.authorization_endpoint),j=l(Q?.token_endpoint);if(!K.ok||Q==null||W==null||G==null||j==null)throw new L$("discovery_failed",`Could not read OAuth metadata from ${$}`);let Y=l(Q.device_authorization_endpoint);return{issuer:W,authorization_endpoint:G,token_endpoint:j,...Y!=null?{device_authorization_endpoint:Y}:{}}}async function n8($,U){let K=await fetch($,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(U).toString()}),q=await K.json().catch(()=>({}));if(!K.ok)throw Zj(q,K.status);let Q=eP(q);if(Q==null)throw new L$("invalid_response","The token endpoint answered an unexpected body");return Q}function QN($){return(U,K)=>{let q=new URL(U.url??"/","http://127.0.0.1");if(q.pathname!=="/callback"){K.writeHead(404).end();return}K.writeHead(200,{"content-type":"text/html; charset=utf-8"}),K.end("<html><body><p>Login complete. You can close this tab and go back to the terminal.</p></body></html>");let Q=q.searchParams.get("code"),W=q.searchParams.get("state"),G=q.searchParams.get("iss")??void 0,j=q.searchParams.get("error");if(j!=null)$({error:j});else if(Q!=null&&W!=null)$({code:Q,state:W,iss:G});else $({error:"invalid_request"})}}function KN($,U){return new Promise((K,q)=>{let Q=setTimeout(()=>{$.current=null,U(),q(new L$("timeout","Timed out waiting for the browser callback"))},tP);$.current=(W)=>{if(clearTimeout(Q),U(),"error"in W)q(new L$(W.error,`Authorization failed: ${W.error}`));else K(W)}})}function qN(){return new Promise(($,U)=>{let K={current:null},q=pP(QN((W)=>K.current?.(W))),Q=async()=>KN(K,()=>q.close());q.on("error",U),q.listen(0,"127.0.0.1",()=>{let W=q.address();if(W==null||typeof W==="string"){U(Error("Could not bind the loopback listener"));return}$({redirectUri:`http://127.0.0.1:${W.port}/callback`,waitForCode:Q,close:()=>q.close()})})})}async function Vj($,U){let K=await qN(),q=$N(),Q=Xj(16).toString("base64url"),W=new URL($.authorization_endpoint);W.searchParams.set("response_type","code"),W.searchParams.set("client_id",U.clientId),W.searchParams.set("redirect_uri",K.redirectUri),W.searchParams.set("scope",U.scopes.join(" ")),W.searchParams.set("state",Q),W.searchParams.set("code_challenge",UN(q)),W.searchParams.set("code_challenge_method","S256"),W.searchParams.set("resource",U.resource);try{d8(W.href);let G=await K.waitForCode();if(G.state!==Q)throw new L$("state_mismatch","The state returned by the server does not match");if(G.iss!=null&&G.iss!==$.issuer)throw new L$("issuer_mismatch","The issuer returned by the server does not match");return await n8($.token_endpoint,{grant_type:"authorization_code",code:G.code,redirect_uri:K.redirectUri,client_id:U.clientId,code_verifier:q})}finally{K.close()}}function WN($){let U=K$($);if(U==null)return null;let K=["device_code","user_code","verification_uri","verification_uri_complete"].map((Q)=>l(U[Q])),q=["expires_in","interval"].map((Q)=>p1(U[Q]));if(K.some((Q)=>Q==null)||q.some((Q)=>Q==null))return null;return{device_code:K[0],user_code:K[1],verification_uri:K[2],verification_uri_complete:K[3],expires_in:q[0],interval:q[1]}}async function Mj($,U){let K=$.device_authorization_endpoint;if(K==null)throw new L$("unsupported_grant_type","This server does not support the device flow");let q=await fetch(K,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:U.clientId,scope:U.scopes.join(" "),resource:U.resource}).toString()}),Q=await q.json().catch(()=>({})),W=q.ok?WN(Q):null;if(W==null)throw q.ok?new L$("invalid_response","The device authorization endpoint answered an unexpected body"):Zj(Q,q.status);return W}async function Dj($,U,K){let q=U.interval*1000,Q=Date.now()+U.expires_in*1000;while(Date.now()<Q){await Bun.sleep(q);try{return await n8($,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:U.device_code,client_id:K})}catch(W){if(W instanceof L$){if(W.code==="authorization_pending")continue;if(W.code==="slow_down"){q+=sP*1000;continue}}throw W}}throw new L$("expired_token","The device code expired before authorization completed")}function a0($,U=Math.floor(Date.now()/1000)){return $.expires_at-U<aP}async function s0($,U){let K=await o8($),q=await n8(K.token_endpoint,{grant_type:"refresh_token",refresh_token:U.refresh_token,client_id:"niva-cli"});if(q.refresh_token==null)throw new L$("invalid_grant","The server did not return a refresh token");return{access_token:q.access_token,refresh_token:q.refresh_token,expires_at:Math.floor(Date.now()/1000)+q.expires_in,org_id:U.org_id,scopes:q.scope!=null?q.scope.split(" ").filter((Q)=>Q!==""):U.scopes}}function p8($){try{let{hostname:U}=new URL($);return U.endsWith(".orb.local")||process.env.NIVA_INSECURE==="true"}catch{return!1}}class Pj extends Error{constructor(){super("Your session has expired. Run 'niva login' to authenticate again.")}}function GN($){let U=$.fetchImpl??fetch,K=async()=>{try{return await $.refresh()}catch(q){if(q instanceof L$)throw new Pj;throw q}};return async(q)=>{let Q=$.getSession();if(a0(Q))Q=await K();let W=new Request(q);W.headers.set("authorization",`Bearer ${Q.access_token}`);let G=await U(W);if(G.status===401){Q=await K();let j=new Request(q);j.headers.set("authorization",`Bearer ${Q.access_token}`),G=await U(j)}return G}}function t8($,U,K){if(p8($))process.env.NODE_TLS_REJECT_UNAUTHORIZED="0";if(U.kind!=="oauth"){let W=new j4({url:new URL("/api/rpc",$).href,headers:()=>U.kind==="api-key"?{"X-API-Key":U.apiKey}:{}});return J4(W)}let q=U.session,Q=new j4({url:new URL("/api/rpc",$).href,fetch:GN({getSession:()=>q,refresh:async()=>{return q=await s0(K,q),C4(K,q),q}})});return J4(Q)}var a8="niva-cli",JN=["*:read","*:write","offline_access"],jN=["*:read","offline_access"];function Nj($,U){return{access_token:$.access_token,refresh_token:$.refresh_token??"",expires_at:Math.floor(Date.now()/1000)+$.expires_in,org_id:U,scopes:$.scope!=null?$.scope.split(" ").filter((K)=>K!==""):[]}}async function YN($,U){return(await t8($,{kind:"oauth",session:Nj(U,"")},$).oauth.whoami()).organization?.id??""}function Lj($,U,K){$.command("login").description("Authenticate with the server (browser by default, device flow with --device)").option("--device","Force the device flow (RFC 8628) even when a browser is available").option("--read-only","Request read-only scopes").action(async(q)=>{let Q=S4(U().url);if(!Q.startsWith("https://"))$1("Server URL is not https: tokens travel unencrypted on this network.");let W=q.readOnly===!0?jN:JN,G=`${Q}/api`,j=await o8(Q),Y={scopes:W,resource:G,clientId:a8},H,X=Bj(process.env,process.platform);if(q.device===!0||!X){let M=await Mj(j,Y);if(R(`Open ${M.verification_uri} and enter the code: ${M.user_code}`),X)d8(M.verification_uri_complete);H=await Dj(j.token_endpoint,M,a8)}else H=await Vj(j,Y);let B=await YN(Q,H);C4(Q,Nj(H,B)),T(`Logged in to ${Q}`)}),$.command("logout").description("Revoke the saved session and remove it from the config file").action(async()=>{let q=S4(U().url),Q=jj()[q];if(Q==null){R(`No saved session for ${q}`);return}try{await fetch(new URL("/oauth/revoke",q),{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:Q.refresh_token,client_id:a8}).toString()})}catch{$1("Could not reach the server to revoke the token; clearing the local session anyway.")}Yj(q),T(`Logged out of ${q}`)}),$.command("whoami").description("Show the authenticated user, organization, scopes and token expiry").action(async()=>{let q=S4(U().url),Q=K();if(Q.kind==="none"){x(`No credential configured for ${q}. Run 'niva login' first.`),process.exitCode=1;return}let G=await t8(q,Q,q).oauth.whoami();P({url:q,user:G.user.email,organization:G.organization?.name,scopes:G.scopes,credential:G.credential,...Q.kind==="oauth"?{expires_at:new Date(Q.session.expires_at*1000).toISOString()}:{}})})}var s8=["blocker","degraded","minor"],e8=["always","sometimes","once"],HN=s8,XN=e8;function _j($,U){return[...U,$]}function ZN($){return HN.includes($)}function BN($){return XN.includes($)}function Ij($,U){$.command("bug-report").description("Report a problem to the NIVA support team").option("--title <title>","Short summary (3-120 characters)").option("--description <description>","What happened (10-4000 characters)").option("--severity <level>",`How bad it is: ${s8.join(", ")}`).option("--expected <expected>","What you expected to happen").option("--step <step>","A reproduction step (repeatable)",_j,[]).option("--frequency <frequency>",`How often it happens: ${e8.join(", ")}`).option("--resource <typeid>","Related resource TypeID (repeatable)",_j,[]).action(async(K)=>{let{title:q,description:Q,severity:W,expected:G,frequency:j,step:Y,resource:H}=K,X=[];if(q===void 0||q==="")X.push("--title");if(Q===void 0||Q==="")X.push("--description");if(W===void 0||W==="")X.push("--severity");if(X.length>0)x(`Missing required option${X.length>1?"s":""}: ${X.join(", ")}`),process.exit(w.USAGE_ERROR);if(q===void 0||Q===void 0||W===void 0)process.exit(w.USAGE_ERROR);if(!ZN(W))x(`Invalid --severity '${W}'. Expected one of: ${s8.join(", ")}`),process.exit(w.USAGE_ERROR);if(j!==void 0&&!BN(j))x(`Invalid --frequency '${j}'. Expected one of: ${e8.join(", ")}`),process.exit(w.USAGE_ERROR);let{format:B}=L($.opts()),M=Y.length>0?Y.map((E,u)=>`${u+1}. ${E}`).join(`
|
|
45
|
+
`):void 0,I=await N(U().bugReports.create({title:q,description:Q,severity:W,expected:G,steps:M,frequency:j,resources:H.length>0?H:void 0,source:"cli"}));if(B==="json"){P(I);return}T(`Report sent (${I.reference})`)})}var a=N1(I1(),1);var VN=/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i,Fj=4;async function e0($,U){if(VN.test(U))return U;if(U.length<Fj)x(`UUID prefix too short — provide at least ${Fj} characters.`),process.exit(w.USAGE_ERROR);let K=await N($.dashboard.activeCalls()),q=U.toLowerCase(),Q=K.filter((W)=>W.uuid.toLowerCase().startsWith(q));if(Q.length===0)x(`No active call matching "${U}".`),process.exit(w.NOT_FOUND);if(Q.length>1){x(`Ambiguous UUID prefix "${U}" — matches ${Q.length} calls. Be more specific.`);for(let W of Q)R(` ${W.uuid} ${W.callerId}`);process.exit(w.USAGE_ERROR)}return Q[0].uuid}var MN={no_credential:"Live transcription is not configured on this platform.",not_recorded:"This call is not being recorded.",test_call:"Test calls are not recorded, so they cannot be transcribed live."};function DN($){let U=Math.max(0,Math.floor($)),K=Math.floor(U/60),q=U%60;return`${String(K).padStart(2,"0")}:${String(q).padStart(2,"0")}`}function PN($){if($==null)return"—";return`${DN($.at_seconds)}${$.late?" (late)":""}`}function Aj($,U){let K=$.command("calls").description("Manage calls");K.command("list").description("List active calls").action(async()=>{let{format:q,fields:Q}=L($.opts()),W=await N(U().dashboard.activeCalls());if(q==="json"){let G=Q?W.map((j)=>O(j,Q)):W;P(G);return}if(W.length===0){R("No active calls.");return}y(["UUID","Caller","Plan","Duration"],W.map((G)=>({UUID:G.uuid,Caller:G.callerId,Plan:G.planName??"—",Duration:G.startedAt?`${Math.round((Date.now()-new Date(G.startedAt).getTime())/1000)}s`:"—"})))}),K.command("show <call_record_id>").description("Show call details from CDR (rich detail view)").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),G=await N(U().callRecords.getById({call_record_id:A("call_records",q)}));if(Q==="json"){let j=W&&G!=null?O(G,W):G;P(j);return}if(G==null){R("Call record not found.");return}o([{title:"Call Record",rows:LN(G)}])}),K.command("hangup <call>").description("Hang up an active call by TypeID (call_...), full channel UUID, or UUID prefix").action(async(q)=>{let{format:Q}=L($.opts()),W=U(),G=q,j;if(q.startsWith("call_"))j=await N(W.calls.hangupCall({call_id:A("call_records",q)}));else G=await e0(W,q),j=await N(W.calls.hangupActiveCall({uuid:G}));if(Q==="json"){P(j);return}T(`Call ${G} terminated.`)}),K.command("signals <call_record_id>").description("Show the signal results of a recorded call").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),G=await N(U().signals.callSignals({call_id:A("call_records",q)}));if(Q==="json"){let j=W?G.map((Y)=>O(Y,W)):G;P(j);return}if(G.length===0){R("No signal results for this call.");return}y(["Signal","Value","Confidence","Triggered at","Severity"],G.map((j)=>({Signal:j.signal.name,Value:j.value_label??"—",Confidence:j.confidence==null?"—":`${Math.round(j.confidence*100)}%`,"Triggered at":PN(j.trigger),Severity:j.definition.alert?.severity??"—"})))}),K.command("search").description("Search CDR records").option("--caller <caller>","Filter by caller ID").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),G=await N(U().callRecords.list({page:Number(q.page),limit:Number(q.limit),search:q.caller}));if(Q==="json"){let j=W?G.items.map((Y)=>O(Y,W)):G;P(j);return}y(["ID","Caller","Callee","Duration","Disposition","Date"],G.items.map((j)=>({ID:j.id,Caller:j.caller_id??"—",Callee:j.callee_id??"—",Duration:f$(j.duration_ms),Disposition:j.hangup_disposition??"—",Date:new Date(j.started_at).toLocaleString()}))),Z$(G)}),K.command("follow <uuid>").description("Follow live transcription of an active call").action(async(q)=>{let{format:Q}=L($.opts()),W=U(),G=await e0(W,q),j=new AbortController;process.on("SIGINT",()=>{j.abort()});let Y=!1,H=!1;function X(M){B();let I=vj(M);process.stdout.write(a.default.dim(I)),H=!0}function B(){if(!H)return;process.stdout.clearLine(0),process.stdout.cursorTo(0),H=!1}await new Promise((M,I)=>{S1(W.dashboard.watchLiveTranscription({uuid:G},{signal:j.signal}),{onEvent:(E)=>{if(Y=!0,Q==="json"){P(E);return}switch(E.type){case"starting":R("Connecting...");break;case"started":R("Transcription started.");break;case"caught_up":break;case"unavailable":R(MN[E.reason]),M();break;case"ended":B(),R("Transcription ended."),M();break;case"error":console.error(a.default.red(`Error: ${E.message}`));break;case"history":for(let u of E.segments)xj(u);for(let u of E.signals??[])wj(u);break;case"signal_value":case"signal_triggered":wj(E);break;case"segment":if(E.segment.isFinal)B(),xj(E.segment);else X(E.segment);break}},onError:(E)=>{if(E instanceof DOMException&&E.name==="AbortError"){B(),M();return}I(E)},onSuccess:()=>{if(!Y)R("Live transcription not available for this call.");M()}})}).catch((M)=>{B(),R4(M)})}),K.command("transfer <uuid> <destination>").description("Transfer an active call").action(()=>F1()),K.command("spy <uuid>").description("Spy on an active call").action(()=>F1()),K.command("history").description("List call records with rich filters and display").option("--from <date>","Start date (YYYY-MM-DD)").option("--to <date>","End date (YYYY-MM-DD)").option("--plan <id>","Filter by visual plan ID").option("--phone <id>","Filter by phone number ID").option("--status <status>","Filter by disposition (answered, missed, failed, busy)").option("--caller <search>","Search by caller ID").option("--min-duration <seconds>","Minimum duration in seconds").option("--max-duration <seconds>","Maximum duration in seconds").option("--has-recording","Only calls with recording").option("--has-transcription","Only calls with transcription").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),G=await N(U().callRecords.list({page:Number(q.page),limit:Number(q.limit),date_from:q.from,date_to:q.to,visual_plan_id:A("visual_plans",q.plan),channel_id:A("channels",q.phone),status:q.status,caller_search:q.caller,min_duration:q.minDuration!=null?Number(q.minDuration):void 0,max_duration:q.maxDuration!=null?Number(q.maxDuration):void 0,has_recording:q.hasRecording,has_transcription:q.hasTranscription}));if(Q==="json"){if(W)P(G.items.map((j)=>O(j,W)));else P(G);return}if(G.items.length===0){R("No call records found.");return}y(["ID","Caller","Direction","Duration","Status","Sentiment","Plan","Date"],G.items.map((j)=>{let Y=j.sentiment_score!=null?Number(j.sentiment_score):null;return{ID:j.id,Caller:j.caller_id??"—",Direction:j.direction??"—",Duration:f$(j.duration_ms),Status:_8(j.hangup_disposition),Sentiment:j.sentiment_label!=null?I8(j.sentiment_label,Y):"—",Plan:j.visual_plan_name??"—",Date:j1(j.started_at)}})),Z$(G)}),K.command("trace <call_record_id>").description("Show node-by-node execution trace for a call").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),G=await N(U().callRecords.getTrace({call_record_id:A("call_records",q)}));if(Q==="json"){let M=W&&G!=null?O(G,W):G;P(M);return}if(G==null){R("Call trace not found.");return}let j=G.callRecord;if(console.log(`${a.default.bold("Call Trace")} — ${q} (${f$(j.duration_ms)}, ${j.hangup_disposition??"unknown"})`),j.visual_plan_name!=null)console.log(`Plan: ${j.visual_plan_name}`);console.log("");let Y=G.events;if(Y.length===0){R(" No events recorded (0 nodes visited).");return}let H=Y.map((M,I)=>{let E=M.duration_ms!=null?`${(M.duration_ms/1000).toFixed(1)}s`:"—",u=`${a.default.cyan(M.node_type)}`;if(M.node_label!=null){let S$=a.default.bold(`"${M.node_label}"`);u+=` ${S$}`}if(u+=a.default.dim(` (${E})`),M.digit!=null)u+=` → digit: ${a.default.yellow(M.digit)}`;let U$=[];if(M.handle_used!=null)U$.push(a.default.dim(`└─→ ${M.handle_used}`));if(Q$(M.data)){let S$=Object.entries(M.data).filter(([,k4])=>k4!=null&&typeof k4!=="object").map(([k4,i$])=>`${k4}: ${String(i$)}`);if(S$.length>0)U$.push(a.default.dim(`└─ ${S$.join(", ")}`))}return{label:u,children:U$.length>0?U$:void 0}});F8(H),console.log("");let X=Y.at(-1),B=X.node_label??X.node_type;R(` ${Y.length} nodes visited · Last: ${X.node_type} "${B}" · Hangup: ${j.hangup_cause??"—"}`)}),K.command("transcript <call_record_id>").description("Show call transcription with speech analytics").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),G=await N(U().ai.getTranscription({call_record_id:A("call_records",q)}));if(Q==="json"){let H=W&&G!=null?O(G,W):G;P(H);return}console.log(`${a.default.bold("Transcript")} — ${q}`),console.log("");let j=IN(G?.segments);if(j.length===0||G?.status==="disabled")R(" No transcript available.");else JJ(j);let Y=G!=null?FN(G):[];if(Y.length>0)console.log(""),o([{title:"Speech Analytics",rows:Y}])}),K.command("purge-voice <call_record_id>").description("Permanently erase a call's voice content (recording, transcription, embeddings)").action(async(q)=>{let{format:Q}=L($.opts()),W=$.opts().yes===!0;if(Q!=="json")console.log(`${a.default.bold("Erase voice content")} — ${q}`),R(" Deletes: recording file, transcription and its semantic-search embeddings."),R(" Keeps: the call record (CDR), its event timeline and existing analyses."),R(" This is irreversible."),console.log("");await d$("Erase the voice content of this call?",{yes:W});let G=await N(U().callRecords.purgeVoiceContent({call_record_id:A("call_records",q)}));if(Q==="json"){P(G);return}T("Voice content erased"),o([{title:"Deleted",rows:[{label:"Recording",value:String(G.deleted.recording)},{label:"Transcriptions",value:String(G.deleted.transcriptions)},{label:"Embeddings",value:String(G.deleted.embeddings)},{label:"Analyses detached",value:String(G.analyses_detached)}]}])}),K.command("search-text <query>").description("Semantic search across call transcriptions").option("--from <date>","Start date (YYYY-MM-DD)").option("--to <date>","End date (YYYY-MM-DD)").option("--plan <id>","Filter by visual plan ID").option("--limit <n>","Max results","20").option("--threshold <n>","Similarity threshold (0-1)","0.35").action(async(q,Q)=>{let{format:W,fields:G}=L($.opts()),j=await N(U().ai.searchTranscriptions({query:q,limit:Number(Q.limit),threshold:Number(Q.threshold),date_from:Q.from,date_to:Q.to,visual_plan_id:A("visual_plans",Q.plan)}));if(W==="json"){let H=G?j.map((X)=>O(X,G)):j;P(H);return}let Y=j;if(console.log(`${a.default.bold("Semantic Search")}: "${q}"`),console.log(`${Y.length} result${Y.length!==1?"s":""} (threshold: ${Q.threshold})`),Y.length===0){R(`
|
|
46
|
+
No results found.`);return}console.log("");for(let H of Y){let X=`${Math.round(H.similarity*100)}%`,B=H.call_record_id,M=j1(H.started_at),I=f$(H.duration_ms);console.log(` ${a.default.bold(X.padStart(4))} │ ${B} │ ${M} │ ${H.caller_id??"—"} │ ${H.direction} │ ${I} │ ${H.visual_plan_name??"—"}`);let E=String(H.chunk_text).replaceAll(/\s+/g," ").trim(),u=120,U$=E.length>u?`${E.slice(0,u)}...`:E;console.log(a.default.dim(` │ "${U$}"`)),console.log("")}}),K.command("inspect <uuid>").description("Inspect an active call: current node, variables, execution path").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),G=U(),j=await e0(G,q),Y=await N(G.dashboard.activeCallTrace({uuid:j}));if(Q==="json"){let B=W?O(Y,W):Y;P(B);return}o([{title:"Active Call",rows:[{label:"UUID",value:j},{label:"Current",value:Y.currentNodeId??"—"}]}]);let H=Y.variables;if(Object.keys(H).length>0){let B=Object.entries(H).map(([M,I])=>({label:M,value:I}));o([{title:`Variables (${Object.keys(H).length})`,rows:B}])}let X=Y.events;if(X.length>0){console.log(""),console.log(a.default.bold("Execution Path:"));let B=X.map((M)=>{let I=M.duration_ms!=null?`${(M.duration_ms/1000).toFixed(1)}s`:"waiting...",E=M.node_id===Y.currentNodeId,U$=`${E?a.default.yellow("●"):a.default.green("✓")} ${a.default.cyan(M.node_type)}`;if(M.node_label!=null){let S$=a.default.bold(`"${M.node_label}"`);U$+=` ${S$}`}if(U$+=a.default.dim(` (${I})`),E)U$+=a.default.yellow(" ← current");return{label:U$}});F8(B)}})}function NN($){if($.has_recording)return"yes";if($.was_recorded)return"processing";return"no"}function $2($){return $!=null&&$!==""}function LN($){let U=$.answered_at!=null?new Date($.answered_at):null,K=new Date($.started_at),q=U!=null?`${Math.round((U.getTime()-K.getTime())/1000)}s ring`:null,Q=$2(q)?` (${q})`:"",W=$.visual_plan_version_number!=null?` v${$.visual_plan_version_number}`:"",G=$2($.visual_plan_name)?`${$.visual_plan_name}${W}`:null,j=$2($.sip_hangup_disposition)?` (${$.sip_hangup_disposition})`:"",Y=$.transcription_status==="none"?"disabled":$.transcription_status;return[{label:"ID",value:$.id},{label:"Direction",value:$.direction},{label:"Caller",value:$.caller_id},{label:"Callee",value:$.callee_id},{label:"Plan",value:G},{label:"Started",value:K.toLocaleString()},{label:"Answered",value:U!=null?`${U.toLocaleString()}${Q}`:null},{label:"Ended",value:$.ended_at!=null?new Date($.ended_at).toLocaleString():null},{label:"Duration",value:f$($.duration_ms)},{label:"Status",value:_8($.hangup_disposition)},{label:"Recording",value:NN($)},{label:"Transcribed",value:Y},{label:"Machine type",value:$.answer_recognition_results?.machine_type},{label:"Hangup",value:$2($.hangup_cause)?`${$.hangup_cause}${j}`:null}]}function _N($){let U=p1($.confidence),K=U!=null?` (${U.toFixed(2)})`:"";return`${l($.topic)??l($.label)??"?"}${K}`}function IN($){let U=[];for(let K of A$($)){let q=l(K.speaker),Q=l(K.text),W=p1(K.initial_time);if(q!=null&&Q!=null&&W!=null)U.push({speaker:q,text:Q,initial_time:W})}return U}function FN($){let U=[],K=K$($.sentiment_overall);if(K!=null)U.push({label:"Sentiment",value:I8(l(K.label),p1(K.score))});if($.intent!=null)U.push({label:"Intent",value:$.intent});if($.summary!=null)U.push({label:"Summary",value:$.summary});let q=Array.isArray($.key_points)?$.key_points.filter((W)=>typeof W==="string"):[];if(q.length>0)U.push({label:"Key Points",value:q.map((W)=>`• ${W}`).join(`
|
|
47
|
+
│ `)});let Q=A$($.topics);if(Q.length>0)U.push({label:"Topics",value:Q.map((W)=>_N(W)).join(" · ")});return U}function vj($){let U=Math.floor($.start/60),K=Math.floor($.start%60),q=`${String(U).padStart(2,"0")}:${String(K).padStart(2,"0")}`,Q=$.channel===0?a.default.blue("Caller"):a.default.green("System");return`${a.default.dim(`[${q}]`)} ${Q} ${a.default.dim(">")} ${$.text}`}function xj($){console.log(vj($))}function wj($){let U=`${Math.round($.confidence*100)}%`;if($.type==="signal_value"){R(` ↳ ${$.signal.name}: ${$.value_label} (${U})`);return}let K=$.node!=null?` · ${$.node.label}`:"",q=$.late?" (late)":"";console.log(a.default.bold(a.default.yellow(` \uD83D\uDD14 ${$.signal.name}: ${$.value_label} (${U})${K}${q}`)))}import{readFile as hA}from"node:fs/promises";var J={};L1(J,{xor:()=>eY,xid:()=>FY,void:()=>oY,uuidv7:()=>VY,uuidv6:()=>BY,uuidv4:()=>ZY,uuid:()=>XY,util:()=>z,url:()=>MY,uppercase:()=>d4,unknown:()=>P4,union:()=>z3,undefined:()=>iY,ulid:()=>IY,uint64:()=>lY,uint32:()=>mY,tuple:()=>DK,trim:()=>s4,treeifyError:()=>XU,transform:()=>b3,toUpperCase:()=>$6,toLowerCase:()=>e4,toJSONSchema:()=>U3,templateLiteral:()=>ZH,symbol:()=>rY,superRefine:()=>lK,success:()=>YH,stringbool:()=>_H,stringFormat:()=>SY,string:()=>J3,strictObject:()=>aY,startsWith:()=>n4,slugify:()=>U6,size:()=>V4,setErrorMap:()=>e_,set:()=>qH,safeParseAsync:()=>rQ,safeParse:()=>lQ,safeEncodeAsync:()=>aQ,safeEncode:()=>pQ,safeDecodeAsync:()=>sQ,safeDecode:()=>tQ,registry:()=>v2,regexes:()=>n$,regex:()=>r4,refine:()=>cK,record:()=>PK,readonly:()=>yK,property:()=>a2,promise:()=>BH,prettifyError:()=>ZU,preprocess:()=>FH,prefault:()=>RK,positive:()=>o2,pipe:()=>H0,partialRecord:()=>UH,parseAsync:()=>cQ,parse:()=>hQ,overwrite:()=>q1,optional:()=>j0,object:()=>tY,number:()=>$K,nullish:()=>jH,nullable:()=>Y0,null:()=>WK,normalize:()=>a4,nonpositive:()=>p2,nonoptional:()=>bK,nonnegative:()=>t2,never:()=>k3,negative:()=>n2,nativeEnum:()=>WH,nanoid:()=>NY,nan:()=>HH,multipleOf:()=>u1,minSize:()=>B1,minLength:()=>v1,mime:()=>t4,meta:()=>NH,maxSize:()=>f1,maxLength:()=>M4,map:()=>KH,mac:()=>AY,lte:()=>h$,lt:()=>X1,lowercase:()=>i4,looseRecord:()=>QH,looseObject:()=>sY,locales:()=>K0,literal:()=>GH,length:()=>D4,lazy:()=>fK,ksuid:()=>xY,keyof:()=>pY,jwt:()=>TY,json:()=>IH,iso:()=>q6,ipv6:()=>vY,ipv4:()=>wY,intersection:()=>VK,int64:()=>cY,int32:()=>fY,int:()=>j3,instanceof:()=>LH,includes:()=>o4,httpUrl:()=>DY,hostname:()=>CY,hex:()=>EY,hash:()=>yY,guid:()=>HY,gte:()=>z$,gt:()=>Z1,globalRegistry:()=>_$,getErrorMap:()=>$I,function:()=>VH,fromJSONSchema:()=>wH,formatError:()=>d6,float64:()=>uY,float32:()=>gY,flattenError:()=>i6,file:()=>JH,exactOptional:()=>wK,enum:()=>R3,endsWith:()=>p4,encodeAsync:()=>oQ,encode:()=>iQ,emoji:()=>PY,email:()=>YY,e164:()=>OY,discriminatedUnion:()=>$H,describe:()=>PH,decodeAsync:()=>nQ,decode:()=>dQ,date:()=>nY,custom:()=>DH,cuid2:()=>_Y,cuid:()=>LY,core:()=>k1,config:()=>V$,coerce:()=>iK,codec:()=>XH,clone:()=>k$,cidrv6:()=>zY,cidrv4:()=>kY,check:()=>MH,catch:()=>SK,boolean:()=>UK,bigint:()=>hY,base64url:()=>bY,base64:()=>RY,array:()=>B0,any:()=>dY,_function:()=>VH,_default:()=>kK,_ZodString:()=>Y3,ZodXor:()=>XK,ZodXID:()=>D3,ZodVoid:()=>YK,ZodUnknown:()=>JK,ZodUnion:()=>M0,ZodUndefined:()=>KK,ZodUUID:()=>V1,ZodURL:()=>X0,ZodULID:()=>M3,ZodType:()=>c,ZodTuple:()=>MK,ZodTransform:()=>FK,ZodTemplateLiteral:()=>gK,ZodSymbol:()=>QK,ZodSuccess:()=>OK,ZodStringFormat:()=>e,ZodString:()=>G6,ZodSet:()=>LK,ZodRecord:()=>D0,ZodRealError:()=>g$,ZodReadonly:()=>EK,ZodPromise:()=>mK,ZodPrefault:()=>zK,ZodPipe:()=>S3,ZodOptional:()=>O3,ZodObject:()=>V0,ZodNumberFormat:()=>N4,ZodNumber:()=>j6,ZodNullable:()=>AK,ZodNull:()=>qK,ZodNonOptional:()=>T3,ZodNever:()=>jK,ZodNanoID:()=>Z3,ZodNaN:()=>CK,ZodMap:()=>NK,ZodMAC:()=>eQ,ZodLiteral:()=>_K,ZodLazy:()=>uK,ZodKSUID:()=>P3,ZodJWT:()=>A3,ZodIssueCode:()=>s_,ZodIntersection:()=>BK,ZodISOTime:()=>W3,ZodISODuration:()=>G3,ZodISODateTime:()=>K3,ZodISODate:()=>q3,ZodIPv6:()=>L3,ZodIPv4:()=>N3,ZodGUID:()=>J0,ZodFunction:()=>hK,ZodFirstPartyTypeKind:()=>rK,ZodFile:()=>IK,ZodExactOptional:()=>xK,ZodError:()=>t_,ZodEnum:()=>W6,ZodEmoji:()=>X3,ZodEmail:()=>H3,ZodE164:()=>w3,ZodDiscriminatedUnion:()=>ZK,ZodDefault:()=>vK,ZodDate:()=>Z0,ZodCustomStringFormat:()=>J6,ZodCustom:()=>P0,ZodCodec:()=>C3,ZodCatch:()=>TK,ZodCUID2:()=>V3,ZodCUID:()=>B3,ZodCIDRv6:()=>I3,ZodCIDRv4:()=>_3,ZodBoolean:()=>Y6,ZodBigIntFormat:()=>v3,ZodBigInt:()=>H6,ZodBase64URL:()=>x3,ZodBase64:()=>F3,ZodArray:()=>HK,ZodAny:()=>GK,TimePrecision:()=>D5,NEVER:()=>$U,$output:()=>H5,$input:()=>X5,$brand:()=>UU});var k1={};L1(k1,{version:()=>J9,util:()=>z,treeifyError:()=>XU,toJSONSchema:()=>U3,toDotPath:()=>Tj,safeParseAsync:()=>VU,safeParse:()=>BU,safeEncodeAsync:()=>UL,safeEncode:()=>eN,safeDecodeAsync:()=>QL,safeDecode:()=>$L,registry:()=>v2,regexes:()=>n$,process:()=>t,prettifyError:()=>ZU,parseAsync:()=>q2,parse:()=>K2,meta:()=>t5,locales:()=>K0,isValidJWT:()=>aj,isValidBase64URL:()=>tj,isValidBase64:()=>R9,initializeContext:()=>m1,globalRegistry:()=>_$,globalConfig:()=>g6,formatError:()=>d6,flattenError:()=>i6,finalize:()=>c1,extractDefs:()=>h1,encodeAsync:()=>aN,encode:()=>pN,describe:()=>p5,decodeAsync:()=>sN,decode:()=>tN,createToJSONSchemaMethod:()=>s5,createStandardJSONSchemaMethod:()=>K6,config:()=>V$,clone:()=>k$,_xor:()=>v_,_xid:()=>g2,_void:()=>m5,_uuidv7:()=>O2,_uuidv6:()=>b2,_uuidv4:()=>R2,_uuid:()=>z2,_url:()=>W0,_uppercase:()=>d4,_unknown:()=>u5,_union:()=>A_,_undefined:()=>E5,_ulid:()=>y2,_uint64:()=>S5,_uint32:()=>k5,_tuple:()=>R_,_trim:()=>s4,_transform:()=>y_,_toUpperCase:()=>$6,_toLowerCase:()=>e4,_templateLiteral:()=>i_,_symbol:()=>C5,_superRefine:()=>n5,_success:()=>h_,_stringbool:()=>a5,_stringFormat:()=>Q6,_string:()=>B5,_startsWith:()=>n4,_slugify:()=>U6,_size:()=>V4,_set:()=>T_,_safeParseAsync:()=>h4,_safeParse:()=>m4,_safeEncodeAsync:()=>X2,_safeEncode:()=>Y2,_safeDecodeAsync:()=>Z2,_safeDecode:()=>H2,_regex:()=>r4,_refine:()=>o5,_record:()=>b_,_readonly:()=>r_,_property:()=>a2,_promise:()=>o_,_positive:()=>o2,_pipe:()=>l_,_parseAsync:()=>f4,_parse:()=>u4,_overwrite:()=>q1,_optional:()=>g_,_number:()=>I5,_nullable:()=>u_,_null:()=>y5,_normalize:()=>a4,_nonpositive:()=>p2,_nonoptional:()=>m_,_nonnegative:()=>t2,_never:()=>f5,_negative:()=>n2,_nativeEnum:()=>C_,_nanoid:()=>S2,_nan:()=>l5,_multipleOf:()=>u1,_minSize:()=>B1,_minLength:()=>v1,_min:()=>z$,_mime:()=>t4,_maxSize:()=>f1,_maxLength:()=>M4,_max:()=>h$,_map:()=>O_,_mac:()=>M5,_lte:()=>h$,_lt:()=>X1,_lowercase:()=>i4,_literal:()=>E_,_length:()=>D4,_lazy:()=>d_,_ksuid:()=>u2,_jwt:()=>d2,_isoTime:()=>L5,_isoDuration:()=>_5,_isoDateTime:()=>P5,_isoDate:()=>N5,_ipv6:()=>m2,_ipv4:()=>f2,_intersection:()=>z_,_int64:()=>T5,_int32:()=>v5,_int:()=>x5,_includes:()=>o4,_guid:()=>q0,_gte:()=>z$,_gt:()=>Z1,_float64:()=>A5,_float32:()=>w5,_file:()=>i5,_enum:()=>S_,_endsWith:()=>p4,_encodeAsync:()=>J2,_encode:()=>W2,_emoji:()=>T2,_email:()=>k2,_e164:()=>i2,_discriminatedUnion:()=>k_,_default:()=>f_,_decodeAsync:()=>j2,_decode:()=>G2,_date:()=>h5,_custom:()=>d5,_cuid2:()=>E2,_cuid:()=>C2,_coercedString:()=>V5,_coercedNumber:()=>F5,_coercedDate:()=>c5,_coercedBoolean:()=>R5,_coercedBigint:()=>O5,_cidrv6:()=>c2,_cidrv4:()=>h2,_check:()=>GY,_catch:()=>c_,_boolean:()=>z5,_bigint:()=>b5,_base64url:()=>r2,_base64:()=>l2,_array:()=>r5,_any:()=>g5,TimePrecision:()=>D5,NEVER:()=>$U,JSONSchemaGenerator:()=>yQ,JSONSchema:()=>JY,Doc:()=>D2,$output:()=>H5,$input:()=>X5,$constructor:()=>D,$brand:()=>UU,$ZodXor:()=>o9,$ZodXID:()=>N9,$ZodVoid:()=>l9,$ZodUnknown:()=>h9,$ZodUnion:()=>a6,$ZodUndefined:()=>u9,$ZodUUID:()=>H9,$ZodURL:()=>Z9,$ZodULID:()=>P9,$ZodType:()=>h,$ZodTuple:()=>w2,$ZodTransform:()=>Q7,$ZodTemplateLiteral:()=>B7,$ZodSymbol:()=>g9,$ZodSuccess:()=>j7,$ZodStringFormat:()=>s,$ZodString:()=>B4,$ZodSet:()=>s9,$ZodRegistry:()=>Z5,$ZodRecord:()=>t9,$ZodRealError:()=>y$,$ZodReadonly:()=>Z7,$ZodPromise:()=>M7,$ZodPrefault:()=>G7,$ZodPipe:()=>X7,$ZodOptional:()=>A2,$ZodObjectJIT:()=>d9,$ZodObject:()=>$Y,$ZodNumberFormat:()=>E9,$ZodNumber:()=>F2,$ZodNullable:()=>q7,$ZodNull:()=>f9,$ZodNonOptional:()=>J7,$ZodNever:()=>c9,$ZodNanoID:()=>V9,$ZodNaN:()=>H7,$ZodMap:()=>a9,$ZodMAC:()=>v9,$ZodLiteral:()=>$7,$ZodLazy:()=>D7,$ZodKSUID:()=>L9,$ZodJWT:()=>S9,$ZodIntersection:()=>p9,$ZodISOTime:()=>F9,$ZodISODuration:()=>x9,$ZodISODateTime:()=>_9,$ZodISODate:()=>I9,$ZodIPv6:()=>A9,$ZodIPv4:()=>w9,$ZodGUID:()=>Y9,$ZodFunction:()=>V7,$ZodFile:()=>U7,$ZodExactOptional:()=>K7,$ZodError:()=>r6,$ZodEnum:()=>e9,$ZodEncodeError:()=>H4,$ZodEmoji:()=>B9,$ZodEmail:()=>X9,$ZodE164:()=>T9,$ZodDiscriminatedUnion:()=>n9,$ZodDefault:()=>W7,$ZodDate:()=>r9,$ZodCustomStringFormat:()=>C9,$ZodCustom:()=>P7,$ZodCodec:()=>s6,$ZodCheckUpperCase:()=>$9,$ZodCheckStringFormat:()=>c4,$ZodCheckStartsWith:()=>Q9,$ZodCheckSizeEquals:()=>nU,$ZodCheckRegex:()=>sU,$ZodCheckProperty:()=>q9,$ZodCheckOverwrite:()=>G9,$ZodCheckNumberFormat:()=>rU,$ZodCheckMultipleOf:()=>lU,$ZodCheckMinSize:()=>oU,$ZodCheckMinLength:()=>tU,$ZodCheckMimeType:()=>W9,$ZodCheckMaxSize:()=>dU,$ZodCheckMaxLength:()=>pU,$ZodCheckLowerCase:()=>eU,$ZodCheckLessThan:()=>V2,$ZodCheckLengthEquals:()=>aU,$ZodCheckIncludes:()=>U9,$ZodCheckGreaterThan:()=>M2,$ZodCheckEndsWith:()=>K9,$ZodCheckBigIntFormat:()=>iU,$ZodCheck:()=>$$,$ZodCatch:()=>Y7,$ZodCUID2:()=>D9,$ZodCUID:()=>M9,$ZodCIDRv6:()=>z9,$ZodCIDRv4:()=>k9,$ZodBoolean:()=>t6,$ZodBigIntFormat:()=>y9,$ZodBigInt:()=>x2,$ZodBase64URL:()=>O9,$ZodBase64:()=>b9,$ZodAsyncError:()=>H1,$ZodArray:()=>i9,$ZodAny:()=>m9});var $U=Object.freeze({status:"aborted"});function D($,U,K){function q(j,Y){if(!j._zod)Object.defineProperty(j,"_zod",{value:{def:Y,constr:G,traits:new Set},enumerable:!1});if(j._zod.traits.has($))return;j._zod.traits.add($),U(j,Y);let H=G.prototype,X=Object.keys(H);for(let B=0;B<X.length;B++){let M=X[B];if(!(M in j))j[M]=H[M].bind(j)}}let Q=K?.Parent??Object;class W extends Q{}Object.defineProperty(W,"name",{value:$});function G(j){var Y;let H=K?.Parent?new W:this;q(H,j),(Y=H._zod).deferred??(Y.deferred=[]);for(let X of H._zod.deferred)X();return H}return Object.defineProperty(G,"init",{value:q}),Object.defineProperty(G,Symbol.hasInstance,{value:(j)=>{if(K?.Parent&&j instanceof K.Parent)return!0;return j?._zod?.traits?.has($)}}),Object.defineProperty(G,"name",{value:$}),G}var UU=Symbol("zod_brand");class H1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class H4 extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}}var g6={};function V$($){if($)Object.assign(g6,$);return g6}var z={};L1(z,{unwrapMessage:()=>u6,uint8ArrayToHex:()=>oN,uint8ArrayToBase64url:()=>iN,uint8ArrayToBase64:()=>Rj,stringifyPrimitive:()=>v,slugify:()=>qU,shallowClone:()=>GU,safeExtend:()=>fN,required:()=>cN,randomString:()=>TN,propertyKeyTypes:()=>h6,promiseAllObject:()=>ON,primitiveTypes:()=>JU,prefixIssues:()=>m$,pick:()=>yN,partial:()=>hN,parsedType:()=>k,optionalKeys:()=>jU,omit:()=>gN,objectClone:()=>zN,numKeys:()=>SN,nullish:()=>C1,normalizeParams:()=>b,mergeDefs:()=>A1,merge:()=>mN,jsonStringifyReplacer:()=>E4,joinValues:()=>_,issue:()=>g4,isPlainObject:()=>y1,isObject:()=>X4,hexToUint8Array:()=>dN,getSizableOrigin:()=>c6,getParsedType:()=>CN,getLengthableOrigin:()=>l6,getEnumValues:()=>f6,getElementAtPath:()=>bN,floatSafeRemainder:()=>KU,finalizeIssue:()=>E$,extend:()=>uN,escapeRegex:()=>o$,esc:()=>U2,defineLazy:()=>r,createTransparentProxy:()=>EN,cloneDef:()=>RN,clone:()=>k$,cleanRegex:()=>m6,cleanEnum:()=>lN,captureStackTrace:()=>Q2,cached:()=>y4,base64urlToUint8Array:()=>rN,base64ToUint8Array:()=>zj,assignProp:()=>E1,assertNotEqual:()=>wN,assertNever:()=>vN,assertIs:()=>AN,assertEqual:()=>xN,assert:()=>kN,allowsEval:()=>WU,aborted:()=>g1,NUMBER_FORMAT_RANGES:()=>YU,Class:()=>bj,BIGINT_FORMAT_RANGES:()=>HU});function xN($){return $}function wN($){return $}function AN($){}function vN($){throw Error("Unexpected value in exhaustive check")}function kN($){}function f6($){let U=Object.values($).filter((q)=>typeof q==="number");return Object.entries($).filter(([q,Q])=>U.indexOf(+q)===-1).map(([q,Q])=>Q)}function _($,U="|"){return $.map((K)=>v(K)).join(U)}function E4($,U){if(typeof U==="bigint")return U.toString();return U}function y4($){return{get value(){{let K=$();return Object.defineProperty(this,"value",{value:K}),K}throw Error("cached value already set")}}}function C1($){return $===null||$===void 0}function m6($){let U=$.startsWith("^")?1:0,K=$.endsWith("$")?$.length-1:$.length;return $.slice(U,K)}function KU($,U){let K=($.toString().split(".")[1]||"").length,q=U.toString(),Q=(q.split(".")[1]||"").length;if(Q===0&&/\d?e-\d?/.test(q)){let Y=q.match(/\d?e-(\d?)/);if(Y?.[1])Q=Number.parseInt(Y[1])}let W=K>Q?K:Q,G=Number.parseInt($.toFixed(W).replace(".","")),j=Number.parseInt(U.toFixed(W).replace(".",""));return G%j/10**W}var kj=Symbol("evaluating");function r($,U,K){let q=void 0;Object.defineProperty($,U,{get(){if(q===kj)return;if(q===void 0)q=kj,q=K();return q},set(Q){Object.defineProperty($,U,{value:Q})},configurable:!0})}function zN($){return Object.create(Object.getPrototypeOf($),Object.getOwnPropertyDescriptors($))}function E1($,U,K){Object.defineProperty($,U,{value:K,writable:!0,enumerable:!0,configurable:!0})}function A1(...$){let U={};for(let K of $){let q=Object.getOwnPropertyDescriptors(K);Object.assign(U,q)}return Object.defineProperties({},U)}function RN($){return A1($._zod.def)}function bN($,U){if(!U)return $;return U.reduce((K,q)=>K?.[q],$)}function ON($){let U=Object.keys($),K=U.map((q)=>$[q]);return Promise.all(K).then((q)=>{let Q={};for(let W=0;W<U.length;W++)Q[U[W]]=q[W];return Q})}function TN($=10){let K="";for(let q=0;q<$;q++)K+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return K}function U2($){return JSON.stringify($)}function qU($){return $.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Q2="captureStackTrace"in Error?Error.captureStackTrace:(...$)=>{};function X4($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var WU=y4(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});function y1($){if(X4($)===!1)return!1;let U=$.constructor;if(U===void 0)return!0;if(typeof U!=="function")return!0;let K=U.prototype;if(X4(K)===!1)return!1;if(Object.prototype.hasOwnProperty.call(K,"isPrototypeOf")===!1)return!1;return!0}function GU($){if(y1($))return{...$};if(Array.isArray($))return[...$];return $}function SN($){let U=0;for(let K in $)if(Object.prototype.hasOwnProperty.call($,K))U++;return U}var CN=($)=>{let U=typeof $;switch(U){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN($)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray($))return"array";if($===null)return"null";if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return"promise";if(typeof Map<"u"&&$ instanceof Map)return"map";if(typeof Set<"u"&&$ instanceof Set)return"set";if(typeof Date<"u"&&$ instanceof Date)return"date";if(typeof File<"u"&&$ instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${U}`)}},h6=new Set(["string","number","symbol"]),JU=new Set(["string","number","bigint","boolean","symbol","undefined"]);function o$($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function k$($,U,K){let q=new $._zod.constr(U??$._zod.def);if(!U||K?.parent)q._zod.parent=$;return q}function b($){let U=$;if(!U)return{};if(typeof U==="string")return{error:()=>U};if(U?.message!==void 0){if(U?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");U.error=U.message}if(delete U.message,typeof U.error==="string")return{...U,error:()=>U.error};return U}function EN($){let U;return new Proxy({},{get(K,q,Q){return U??(U=$()),Reflect.get(U,q,Q)},set(K,q,Q,W){return U??(U=$()),Reflect.set(U,q,Q,W)},has(K,q){return U??(U=$()),Reflect.has(U,q)},deleteProperty(K,q){return U??(U=$()),Reflect.deleteProperty(U,q)},ownKeys(K){return U??(U=$()),Reflect.ownKeys(U)},getOwnPropertyDescriptor(K,q){return U??(U=$()),Reflect.getOwnPropertyDescriptor(U,q)},defineProperty(K,q,Q){return U??(U=$()),Reflect.defineProperty(U,q,Q)}})}function v($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function jU($){return Object.keys($).filter((U)=>{return $[U]._zod.optin==="optional"&&$[U]._zod.optout==="optional"})}var YU={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},HU={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function yN($,U){let K=$._zod.def,q=K.checks;if(q&&q.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let W=A1($._zod.def,{get shape(){let G={};for(let j in U){if(!(j in K.shape))throw Error(`Unrecognized key: "${j}"`);if(!U[j])continue;G[j]=K.shape[j]}return E1(this,"shape",G),G},checks:[]});return k$($,W)}function gN($,U){let K=$._zod.def,q=K.checks;if(q&&q.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let W=A1($._zod.def,{get shape(){let G={...$._zod.def.shape};for(let j in U){if(!(j in K.shape))throw Error(`Unrecognized key: "${j}"`);if(!U[j])continue;delete G[j]}return E1(this,"shape",G),G},checks:[]});return k$($,W)}function uN($,U){if(!y1(U))throw Error("Invalid input to extend: expected a plain object");let K=$._zod.def.checks;if(K&&K.length>0){let W=$._zod.def.shape;for(let G in U)if(Object.getOwnPropertyDescriptor(W,G)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let Q=A1($._zod.def,{get shape(){let W={...$._zod.def.shape,...U};return E1(this,"shape",W),W}});return k$($,Q)}function fN($,U){if(!y1(U))throw Error("Invalid input to safeExtend: expected a plain object");let K=A1($._zod.def,{get shape(){let q={...$._zod.def.shape,...U};return E1(this,"shape",q),q}});return k$($,K)}function mN($,U){let K=A1($._zod.def,{get shape(){let q={...$._zod.def.shape,...U._zod.def.shape};return E1(this,"shape",q),q},get catchall(){return U._zod.def.catchall},checks:[]});return k$($,K)}function hN($,U,K){let Q=U._zod.def.checks;if(Q&&Q.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let G=A1(U._zod.def,{get shape(){let j=U._zod.def.shape,Y={...j};if(K)for(let H in K){if(!(H in j))throw Error(`Unrecognized key: "${H}"`);if(!K[H])continue;Y[H]=$?new $({type:"optional",innerType:j[H]}):j[H]}else for(let H in j)Y[H]=$?new $({type:"optional",innerType:j[H]}):j[H];return E1(this,"shape",Y),Y},checks:[]});return k$(U,G)}function cN($,U,K){let q=A1(U._zod.def,{get shape(){let Q=U._zod.def.shape,W={...Q};if(K)for(let G in K){if(!(G in W))throw Error(`Unrecognized key: "${G}"`);if(!K[G])continue;W[G]=new $({type:"nonoptional",innerType:Q[G]})}else for(let G in Q)W[G]=new $({type:"nonoptional",innerType:Q[G]});return E1(this,"shape",W),W}});return k$(U,q)}function g1($,U=0){if($.aborted===!0)return!0;for(let K=U;K<$.issues.length;K++)if($.issues[K]?.continue!==!0)return!0;return!1}function m$($,U){return U.map((K)=>{var q;return(q=K).path??(q.path=[]),K.path.unshift($),K})}function u6($){return typeof $==="string"?$:$?.message}function E$($,U,K){let q={...$,path:$.path??[]};if(!$.message){let Q=u6($.inst?._zod.def?.error?.($))??u6(U?.error?.($))??u6(K.customError?.($))??u6(K.localeError?.($))??"Invalid input";q.message=Q}if(delete q.inst,delete q.continue,!U?.reportInput)delete q.input;return q}function c6($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function l6($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function k($){let U=typeof $;switch(U){case"number":return Number.isNaN($)?"nan":"number";case"object":{if($===null)return"null";if(Array.isArray($))return"array";let K=$;if(K&&Object.getPrototypeOf(K)!==Object.prototype&&"constructor"in K&&K.constructor)return K.constructor.name}}return U}function g4(...$){let[U,K,q]=$;if(typeof U==="string")return{message:U,code:"custom",input:K,inst:q};return{...U}}function lN($){return Object.entries($).filter(([U,K])=>{return Number.isNaN(Number.parseInt(U,10))}).map((U)=>U[1])}function zj($){let U=atob($),K=new Uint8Array(U.length);for(let q=0;q<U.length;q++)K[q]=U.charCodeAt(q);return K}function Rj($){let U="";for(let K=0;K<$.length;K++)U+=String.fromCharCode($[K]);return btoa(U)}function rN($){let U=$.replace(/-/g,"+").replace(/_/g,"/"),K="=".repeat((4-U.length%4)%4);return zj(U+K)}function iN($){return Rj($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function dN($){let U=$.replace(/^0x/,"");if(U.length%2!==0)throw Error("Invalid hex string length");let K=new Uint8Array(U.length/2);for(let q=0;q<U.length;q+=2)K[q/2]=Number.parseInt(U.slice(q,q+2),16);return K}function oN($){return Array.from($).map((U)=>U.toString(16).padStart(2,"0")).join("")}class bj{constructor(...$){}}var Oj=($,U)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:U,enumerable:!1}),$.message=JSON.stringify(U,E4,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},r6=D("$ZodError",Oj),y$=D("$ZodError",Oj,{Parent:Error});function i6($,U=(K)=>K.message){let K={},q=[];for(let Q of $.issues)if(Q.path.length>0)K[Q.path[0]]=K[Q.path[0]]||[],K[Q.path[0]].push(U(Q));else q.push(U(Q));return{formErrors:q,fieldErrors:K}}function d6($,U=(K)=>K.message){let K={_errors:[]},q=(Q)=>{for(let W of Q.issues)if(W.code==="invalid_union"&&W.errors.length)W.errors.map((G)=>q({issues:G}));else if(W.code==="invalid_key")q({issues:W.issues});else if(W.code==="invalid_element")q({issues:W.issues});else if(W.path.length===0)K._errors.push(U(W));else{let G=K,j=0;while(j<W.path.length){let Y=W.path[j];if(j!==W.path.length-1)G[Y]=G[Y]||{_errors:[]};else G[Y]=G[Y]||{_errors:[]},G[Y]._errors.push(U(W));G=G[Y],j++}}};return q($),K}function XU($,U=(K)=>K.message){let K={errors:[]},q=(Q,W=[])=>{var G,j;for(let Y of Q.issues)if(Y.code==="invalid_union"&&Y.errors.length)Y.errors.map((H)=>q({issues:H},Y.path));else if(Y.code==="invalid_key")q({issues:Y.issues},Y.path);else if(Y.code==="invalid_element")q({issues:Y.issues},Y.path);else{let H=[...W,...Y.path];if(H.length===0){K.errors.push(U(Y));continue}let X=K,B=0;while(B<H.length){let M=H[B],I=B===H.length-1;if(typeof M==="string")X.properties??(X.properties={}),(G=X.properties)[M]??(G[M]={errors:[]}),X=X.properties[M];else X.items??(X.items=[]),(j=X.items)[M]??(j[M]={errors:[]}),X=X.items[M];if(I)X.errors.push(U(Y));B++}}};return q($),K}function Tj($){let U=[],K=$.map((q)=>typeof q==="object"?q.key:q);for(let q of K)if(typeof q==="number")U.push(`[${q}]`);else if(typeof q==="symbol")U.push(`[${JSON.stringify(String(q))}]`);else if(/[^\w$]/.test(q))U.push(`[${JSON.stringify(q)}]`);else{if(U.length)U.push(".");U.push(q)}return U.join("")}function ZU($){let U=[],K=[...$.issues].sort((q,Q)=>(q.path??[]).length-(Q.path??[]).length);for(let q of K)if(U.push(`✖ ${q.message}`),q.path?.length)U.push(` → at ${Tj(q.path)}`);return U.join(`
|
|
48
|
+
`)}var u4=($)=>(U,K,q,Q)=>{let W=q?Object.assign(q,{async:!1}):{async:!1},G=U._zod.run({value:K,issues:[]},W);if(G instanceof Promise)throw new H1;if(G.issues.length){let j=new(Q?.Err??$)(G.issues.map((Y)=>E$(Y,W,V$())));throw Q2(j,Q?.callee),j}return G.value},K2=u4(y$),f4=($)=>async(U,K,q,Q)=>{let W=q?Object.assign(q,{async:!0}):{async:!0},G=U._zod.run({value:K,issues:[]},W);if(G instanceof Promise)G=await G;if(G.issues.length){let j=new(Q?.Err??$)(G.issues.map((Y)=>E$(Y,W,V$())));throw Q2(j,Q?.callee),j}return G.value},q2=f4(y$),m4=($)=>(U,K,q)=>{let Q=q?{...q,async:!1}:{async:!1},W=U._zod.run({value:K,issues:[]},Q);if(W instanceof Promise)throw new H1;return W.issues.length?{success:!1,error:new($??r6)(W.issues.map((G)=>E$(G,Q,V$())))}:{success:!0,data:W.value}},BU=m4(y$),h4=($)=>async(U,K,q)=>{let Q=q?Object.assign(q,{async:!0}):{async:!0},W=U._zod.run({value:K,issues:[]},Q);if(W instanceof Promise)W=await W;return W.issues.length?{success:!1,error:new $(W.issues.map((G)=>E$(G,Q,V$())))}:{success:!0,data:W.value}},VU=h4(y$),W2=($)=>(U,K,q)=>{let Q=q?Object.assign(q,{direction:"backward"}):{direction:"backward"};return u4($)(U,K,Q)},pN=W2(y$),G2=($)=>(U,K,q)=>{return u4($)(U,K,q)},tN=G2(y$),J2=($)=>async(U,K,q)=>{let Q=q?Object.assign(q,{direction:"backward"}):{direction:"backward"};return f4($)(U,K,Q)},aN=J2(y$),j2=($)=>async(U,K,q)=>{return f4($)(U,K,q)},sN=j2(y$),Y2=($)=>(U,K,q)=>{let Q=q?Object.assign(q,{direction:"backward"}):{direction:"backward"};return m4($)(U,K,Q)},eN=Y2(y$),H2=($)=>(U,K,q)=>{return m4($)(U,K,q)},$L=H2(y$),X2=($)=>async(U,K,q)=>{let Q=q?Object.assign(q,{direction:"backward"}):{direction:"backward"};return h4($)(U,K,Q)},UL=X2(y$),Z2=($)=>async(U,K,q)=>{return h4($)(U,K,q)},QL=Z2(y$);var n$={};L1(n$,{xid:()=>NU,uuid7:()=>GL,uuid6:()=>WL,uuid4:()=>qL,uuid:()=>Z4,uppercase:()=>cU,unicodeEmail:()=>Sj,undefined:()=>mU,ulid:()=>PU,time:()=>SU,string:()=>EU,sha512_hex:()=>kL,sha512_base64url:()=>RL,sha512_base64:()=>zL,sha384_hex:()=>wL,sha384_base64url:()=>vL,sha384_base64:()=>AL,sha256_hex:()=>IL,sha256_base64url:()=>xL,sha256_base64:()=>FL,sha1_hex:()=>NL,sha1_base64url:()=>_L,sha1_base64:()=>LL,rfc5322Email:()=>jL,number:()=>o6,null:()=>fU,nanoid:()=>_U,md5_hex:()=>ML,md5_base64url:()=>PL,md5_base64:()=>DL,mac:()=>kU,lowercase:()=>hU,ksuid:()=>LU,ipv6:()=>vU,ipv4:()=>AU,integer:()=>gU,idnEmail:()=>YL,html5Email:()=>JL,hostname:()=>ZL,hex:()=>VL,guid:()=>FU,extendedDuration:()=>KL,emoji:()=>wU,email:()=>xU,e164:()=>OU,duration:()=>IU,domain:()=>BL,datetime:()=>CU,date:()=>TU,cuid2:()=>DU,cuid:()=>MU,cidrv6:()=>RU,cidrv4:()=>zU,browserEmail:()=>HL,boolean:()=>uU,bigint:()=>yU,base64url:()=>B2,base64:()=>bU});var MU=/^[cC][^\s-]{8,}$/,DU=/^[0-9a-z]+$/,PU=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,NU=/^[0-9a-vA-V]{20}$/,LU=/^[A-Za-z0-9]{27}$/,_U=/^[a-zA-Z0-9_-]{21}$/,IU=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,KL=/^[-+]?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)?)??$/,FU=/^([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})$/,Z4=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},qL=Z4(4),WL=Z4(6),GL=Z4(7),xU=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,JL=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,jL=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,Sj=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,YL=Sj,HL=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,XL="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function wU(){return new RegExp(XL,"u")}var AU=/^(?:(?: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])$/,vU=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,kU=($)=>{let U=o$($??":");return new RegExp(`^(?:[0-9A-F]{2}${U}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${U}){5}[0-9a-f]{2}$`)},zU=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,RU=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,bU=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,B2=/^[A-Za-z0-9_-]*$/,ZL=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,BL=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,OU=/^\+[1-9]\d{6,14}$/,Cj="(?:(?:\\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])))",TU=new RegExp(`^${Cj}$`);function Ej($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function SU($){return new RegExp(`^${Ej($)}$`)}function CU($){let U=Ej({precision:$.precision}),K=["Z"];if($.local)K.push("");if($.offset)K.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let q=`${U}(?:${K.join("|")})`;return new RegExp(`^${Cj}T(?:${q})$`)}var EU=($)=>{let U=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${U}$`)},yU=/^-?\d+n?$/,gU=/^-?\d+$/,o6=/^-?\d+(?:\.\d+)?$/,uU=/^(?:true|false)$/i,fU=/^null$/i;var mU=/^undefined$/i;var hU=/^[^A-Z]*$/,cU=/^[^a-z]*$/,VL=/^[0-9a-fA-F]*$/;function n6($,U){return new RegExp(`^[A-Za-z0-9+/]{${$}}${U}$`)}function p6($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var ML=/^[0-9a-fA-F]{32}$/,DL=n6(22,"=="),PL=p6(22),NL=/^[0-9a-fA-F]{40}$/,LL=n6(27,"="),_L=p6(27),IL=/^[0-9a-fA-F]{64}$/,FL=n6(43,"="),xL=p6(43),wL=/^[0-9a-fA-F]{96}$/,AL=n6(64,""),vL=p6(64),kL=/^[0-9a-fA-F]{128}$/,zL=n6(86,"=="),RL=p6(86);var $$=D("$ZodCheck",($,U)=>{var K;$._zod??($._zod={}),$._zod.def=U,(K=$._zod).onattach??(K.onattach=[])}),gj={number:"number",bigint:"bigint",object:"date"},V2=D("$ZodCheckLessThan",($,U)=>{$$.init($,U);let K=gj[typeof U.value];$._zod.onattach.push((q)=>{let Q=q._zod.bag,W=(U.inclusive?Q.maximum:Q.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(U.value<W)if(U.inclusive)Q.maximum=U.value;else Q.exclusiveMaximum=U.value}),$._zod.check=(q)=>{if(U.inclusive?q.value<=U.value:q.value<U.value)return;q.issues.push({origin:K,code:"too_big",maximum:typeof U.value==="object"?U.value.getTime():U.value,input:q.value,inclusive:U.inclusive,inst:$,continue:!U.abort})}}),M2=D("$ZodCheckGreaterThan",($,U)=>{$$.init($,U);let K=gj[typeof U.value];$._zod.onattach.push((q)=>{let Q=q._zod.bag,W=(U.inclusive?Q.minimum:Q.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(U.value>W)if(U.inclusive)Q.minimum=U.value;else Q.exclusiveMinimum=U.value}),$._zod.check=(q)=>{if(U.inclusive?q.value>=U.value:q.value>U.value)return;q.issues.push({origin:K,code:"too_small",minimum:typeof U.value==="object"?U.value.getTime():U.value,input:q.value,inclusive:U.inclusive,inst:$,continue:!U.abort})}}),lU=D("$ZodCheckMultipleOf",($,U)=>{$$.init($,U),$._zod.onattach.push((K)=>{var q;(q=K._zod.bag).multipleOf??(q.multipleOf=U.value)}),$._zod.check=(K)=>{if(typeof K.value!==typeof U.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof K.value==="bigint"?K.value%U.value===BigInt(0):KU(K.value,U.value)===0)return;K.issues.push({origin:typeof K.value,code:"not_multiple_of",divisor:U.value,input:K.value,inst:$,continue:!U.abort})}}),rU=D("$ZodCheckNumberFormat",($,U)=>{$$.init($,U),U.format=U.format||"float64";let K=U.format?.includes("int"),q=K?"int":"number",[Q,W]=YU[U.format];$._zod.onattach.push((G)=>{let j=G._zod.bag;if(j.format=U.format,j.minimum=Q,j.maximum=W,K)j.pattern=gU}),$._zod.check=(G)=>{let j=G.value;if(K){if(!Number.isInteger(j)){G.issues.push({expected:q,format:U.format,code:"invalid_type",continue:!1,input:j,inst:$});return}if(!Number.isSafeInteger(j)){if(j>0)G.issues.push({input:j,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:q,inclusive:!0,continue:!U.abort});else G.issues.push({input:j,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:q,inclusive:!0,continue:!U.abort});return}}if(j<Q)G.issues.push({origin:"number",input:j,code:"too_small",minimum:Q,inclusive:!0,inst:$,continue:!U.abort});if(j>W)G.issues.push({origin:"number",input:j,code:"too_big",maximum:W,inclusive:!0,inst:$,continue:!U.abort})}}),iU=D("$ZodCheckBigIntFormat",($,U)=>{$$.init($,U);let[K,q]=HU[U.format];$._zod.onattach.push((Q)=>{let W=Q._zod.bag;W.format=U.format,W.minimum=K,W.maximum=q}),$._zod.check=(Q)=>{let W=Q.value;if(W<K)Q.issues.push({origin:"bigint",input:W,code:"too_small",minimum:K,inclusive:!0,inst:$,continue:!U.abort});if(W>q)Q.issues.push({origin:"bigint",input:W,code:"too_big",maximum:q,inclusive:!0,inst:$,continue:!U.abort})}}),dU=D("$ZodCheckMaxSize",($,U)=>{var K;$$.init($,U),(K=$._zod.def).when??(K.when=(q)=>{let Q=q.value;return!C1(Q)&&Q.size!==void 0}),$._zod.onattach.push((q)=>{let Q=q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(U.maximum<Q)q._zod.bag.maximum=U.maximum}),$._zod.check=(q)=>{let Q=q.value;if(Q.size<=U.maximum)return;q.issues.push({origin:c6(Q),code:"too_big",maximum:U.maximum,inclusive:!0,input:Q,inst:$,continue:!U.abort})}}),oU=D("$ZodCheckMinSize",($,U)=>{var K;$$.init($,U),(K=$._zod.def).when??(K.when=(q)=>{let Q=q.value;return!C1(Q)&&Q.size!==void 0}),$._zod.onattach.push((q)=>{let Q=q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(U.minimum>Q)q._zod.bag.minimum=U.minimum}),$._zod.check=(q)=>{let Q=q.value;if(Q.size>=U.minimum)return;q.issues.push({origin:c6(Q),code:"too_small",minimum:U.minimum,inclusive:!0,input:Q,inst:$,continue:!U.abort})}}),nU=D("$ZodCheckSizeEquals",($,U)=>{var K;$$.init($,U),(K=$._zod.def).when??(K.when=(q)=>{let Q=q.value;return!C1(Q)&&Q.size!==void 0}),$._zod.onattach.push((q)=>{let Q=q._zod.bag;Q.minimum=U.size,Q.maximum=U.size,Q.size=U.size}),$._zod.check=(q)=>{let Q=q.value,W=Q.size;if(W===U.size)return;let G=W>U.size;q.issues.push({origin:c6(Q),...G?{code:"too_big",maximum:U.size}:{code:"too_small",minimum:U.size},inclusive:!0,exact:!0,input:q.value,inst:$,continue:!U.abort})}}),pU=D("$ZodCheckMaxLength",($,U)=>{var K;$$.init($,U),(K=$._zod.def).when??(K.when=(q)=>{let Q=q.value;return!C1(Q)&&Q.length!==void 0}),$._zod.onattach.push((q)=>{let Q=q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(U.maximum<Q)q._zod.bag.maximum=U.maximum}),$._zod.check=(q)=>{let Q=q.value;if(Q.length<=U.maximum)return;let G=l6(Q);q.issues.push({origin:G,code:"too_big",maximum:U.maximum,inclusive:!0,input:Q,inst:$,continue:!U.abort})}}),tU=D("$ZodCheckMinLength",($,U)=>{var K;$$.init($,U),(K=$._zod.def).when??(K.when=(q)=>{let Q=q.value;return!C1(Q)&&Q.length!==void 0}),$._zod.onattach.push((q)=>{let Q=q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(U.minimum>Q)q._zod.bag.minimum=U.minimum}),$._zod.check=(q)=>{let Q=q.value;if(Q.length>=U.minimum)return;let G=l6(Q);q.issues.push({origin:G,code:"too_small",minimum:U.minimum,inclusive:!0,input:Q,inst:$,continue:!U.abort})}}),aU=D("$ZodCheckLengthEquals",($,U)=>{var K;$$.init($,U),(K=$._zod.def).when??(K.when=(q)=>{let Q=q.value;return!C1(Q)&&Q.length!==void 0}),$._zod.onattach.push((q)=>{let Q=q._zod.bag;Q.minimum=U.length,Q.maximum=U.length,Q.length=U.length}),$._zod.check=(q)=>{let Q=q.value,W=Q.length;if(W===U.length)return;let G=l6(Q),j=W>U.length;q.issues.push({origin:G,...j?{code:"too_big",maximum:U.length}:{code:"too_small",minimum:U.length},inclusive:!0,exact:!0,input:q.value,inst:$,continue:!U.abort})}}),c4=D("$ZodCheckStringFormat",($,U)=>{var K,q;if($$.init($,U),$._zod.onattach.push((Q)=>{let W=Q._zod.bag;if(W.format=U.format,U.pattern)W.patterns??(W.patterns=new Set),W.patterns.add(U.pattern)}),U.pattern)(K=$._zod).check??(K.check=(Q)=>{if(U.pattern.lastIndex=0,U.pattern.test(Q.value))return;Q.issues.push({origin:"string",code:"invalid_format",format:U.format,input:Q.value,...U.pattern?{pattern:U.pattern.toString()}:{},inst:$,continue:!U.abort})});else(q=$._zod).check??(q.check=()=>{})}),sU=D("$ZodCheckRegex",($,U)=>{c4.init($,U),$._zod.check=(K)=>{if(U.pattern.lastIndex=0,U.pattern.test(K.value))return;K.issues.push({origin:"string",code:"invalid_format",format:"regex",input:K.value,pattern:U.pattern.toString(),inst:$,continue:!U.abort})}}),eU=D("$ZodCheckLowerCase",($,U)=>{U.pattern??(U.pattern=hU),c4.init($,U)}),$9=D("$ZodCheckUpperCase",($,U)=>{U.pattern??(U.pattern=cU),c4.init($,U)}),U9=D("$ZodCheckIncludes",($,U)=>{$$.init($,U);let K=o$(U.includes),q=new RegExp(typeof U.position==="number"?`^.{${U.position}}${K}`:K);U.pattern=q,$._zod.onattach.push((Q)=>{let W=Q._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add(q)}),$._zod.check=(Q)=>{if(Q.value.includes(U.includes,U.position))return;Q.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:U.includes,input:Q.value,inst:$,continue:!U.abort})}}),Q9=D("$ZodCheckStartsWith",($,U)=>{$$.init($,U);let K=new RegExp(`^${o$(U.prefix)}.*`);U.pattern??(U.pattern=K),$._zod.onattach.push((q)=>{let Q=q._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add(K)}),$._zod.check=(q)=>{if(q.value.startsWith(U.prefix))return;q.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:U.prefix,input:q.value,inst:$,continue:!U.abort})}}),K9=D("$ZodCheckEndsWith",($,U)=>{$$.init($,U);let K=new RegExp(`.*${o$(U.suffix)}$`);U.pattern??(U.pattern=K),$._zod.onattach.push((q)=>{let Q=q._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add(K)}),$._zod.check=(q)=>{if(q.value.endsWith(U.suffix))return;q.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:U.suffix,input:q.value,inst:$,continue:!U.abort})}});function yj($,U,K){if($.issues.length)U.issues.push(...m$(K,$.issues))}var q9=D("$ZodCheckProperty",($,U)=>{$$.init($,U),$._zod.check=(K)=>{let q=U.schema._zod.run({value:K.value[U.property],issues:[]},{});if(q instanceof Promise)return q.then((Q)=>yj(Q,K,U.property));yj(q,K,U.property);return}}),W9=D("$ZodCheckMimeType",($,U)=>{$$.init($,U);let K=new Set(U.mime);$._zod.onattach.push((q)=>{q._zod.bag.mime=U.mime}),$._zod.check=(q)=>{if(K.has(q.value.type))return;q.issues.push({code:"invalid_value",values:U.mime,input:q.value.type,inst:$,continue:!U.abort})}}),G9=D("$ZodCheckOverwrite",($,U)=>{$$.init($,U),$._zod.check=(K)=>{K.value=U.tx(K.value)}});class D2{constructor($=[]){if(this.content=[],this.indent=0,this)this.args=$}indented($){this.indent+=1,$(this),this.indent-=1}write($){if(typeof $==="function"){$(this,{execution:"sync"}),$(this,{execution:"async"});return}let K=$.split(`
|
|
54
49
|
`).filter((W)=>W),q=Math.min(...K.map((W)=>W.length-W.trimStart().length)),Q=K.map((W)=>W.slice(q)).map((W)=>" ".repeat(this.indent*2)+W);for(let W of Q)this.content.push(W)}compile(){let $=Function,U=this?.args,q=[...(this?.content??[""]).map((Q)=>` ${Q}`)];return new $(...U,q.join(`
|
|
55
|
-
`))}}var Y9={major:4,minor:3,patch:6};var h=D("$ZodType",($,U)=>{var K;$??($={}),$._zod.def=U,$._zod.bag=$._zod.bag||{},$._zod.version=Y9;let q=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))q.unshift($);for(let Q of q)for(let W of Q._zod.onattach)W($);if(q.length===0)(K=$._zod).deferred??(K.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let Q=(J,j,Y)=>{let H=g1(J),Z;for(let B of j){if(B._zod.def.when){if(!B._zod.def.when(J))continue}else if(H)continue;let M=J.issues.length,I=B._zod.check(J);if(I instanceof Promise&&Y?.async===!1)throw new X1;if(Z||I instanceof Promise)Z=(Z??Promise.resolve()).then(async()=>{if(await I,J.issues.length===M)return;if(!H)H=g1(J,M)});else{if(J.issues.length===M)continue;if(!H)H=g1(J,M)}}if(Z)return Z.then(()=>{return J});return J},W=(J,j,Y)=>{if(g1(J))return J.aborted=!0,J;let H=Q(j,q,Y);if(H instanceof Promise){if(Y.async===!1)throw new X1;return H.then((Z)=>$._zod.parse(Z,Y))}return $._zod.parse(H,Y)};$._zod.run=(J,j)=>{if(j.skipChecks)return $._zod.parse(J,j);if(j.direction==="backward"){let H=$._zod.parse({value:J.value,issues:[]},{...j,skipChecks:!0});if(H instanceof Promise)return H.then((Z)=>{return W(Z,J,j)});return W(H,J,j)}let Y=$._zod.parse(J,j);if(Y instanceof Promise){if(j.async===!1)throw new X1;return Y.then((H)=>Q(H,q,j))}return Q(Y,q,j)}}r($,"~standard",()=>({validate:(Q)=>{try{let W=MU($,Q);return W.success?{value:W.data}:{issues:W.error?.issues}}catch(W){return DU($,Q).then((J)=>J.success?{value:J.data}:{issues:J.error?.issues})}},vendor:"zod",version:1}))}),V4=D("$ZodString",($,U)=>{h.init($,U),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??gU($._zod.bag),$._zod.parse=(K,q)=>{if(U.coerce)try{K.value=String(K.value)}catch(Q){}if(typeof K.value==="string")return K;return K.issues.push({expected:"string",code:"invalid_type",input:K.value,inst:$}),K}}),s=D("$ZodStringFormat",($,U)=>{i4.init($,U),V4.init($,U)}),X9=D("$ZodGUID",($,U)=>{U.pattern??(U.pattern=wU),s.init($,U)}),Z9=D("$ZodUUID",($,U)=>{if(U.version){let q={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[U.version];if(q===void 0)throw Error(`Invalid UUID version: "${U.version}"`);U.pattern??(U.pattern=B4(q))}else U.pattern??(U.pattern=B4());s.init($,U)}),B9=D("$ZodEmail",($,U)=>{U.pattern??(U.pattern=AU),s.init($,U)}),V9=D("$ZodURL",($,U)=>{s.init($,U),$._zod.check=(K)=>{try{let q=K.value.trim(),Q=new URL(q);if(U.hostname){if(U.hostname.lastIndex=0,!U.hostname.test(Q.hostname))K.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:U.hostname.source,input:K.value,inst:$,continue:!U.abort})}if(U.protocol){if(U.protocol.lastIndex=0,!U.protocol.test(Q.protocol.endsWith(":")?Q.protocol.slice(0,-1):Q.protocol))K.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:U.protocol.source,input:K.value,inst:$,continue:!U.abort})}if(U.normalize)K.value=Q.href;else K.value=q;return}catch(q){K.issues.push({code:"invalid_format",format:"url",input:K.value,inst:$,continue:!U.abort})}}}),M9=D("$ZodEmoji",($,U)=>{U.pattern??(U.pattern=vU()),s.init($,U)}),D9=D("$ZodNanoID",($,U)=>{U.pattern??(U.pattern=FU),s.init($,U)}),P9=D("$ZodCUID",($,U)=>{U.pattern??(U.pattern=PU),s.init($,U)}),N9=D("$ZodCUID2",($,U)=>{U.pattern??(U.pattern=NU),s.init($,U)}),L9=D("$ZodULID",($,U)=>{U.pattern??(U.pattern=LU),s.init($,U)}),_9=D("$ZodXID",($,U)=>{U.pattern??(U.pattern=_U),s.init($,U)}),I9=D("$ZodKSUID",($,U)=>{U.pattern??(U.pattern=IU),s.init($,U)}),F9=D("$ZodISODateTime",($,U)=>{U.pattern??(U.pattern=yU(U)),s.init($,U)}),x9=D("$ZodISODate",($,U)=>{U.pattern??(U.pattern=CU),s.init($,U)}),w9=D("$ZodISOTime",($,U)=>{U.pattern??(U.pattern=EU(U)),s.init($,U)}),A9=D("$ZodISODuration",($,U)=>{U.pattern??(U.pattern=xU),s.init($,U)}),v9=D("$ZodIPv4",($,U)=>{U.pattern??(U.pattern=kU),s.init($,U),$._zod.bag.format="ipv4"}),k9=D("$ZodIPv6",($,U)=>{U.pattern??(U.pattern=RU),s.init($,U),$._zod.bag.format="ipv6",$._zod.check=(K)=>{try{new URL(`http://[${K.value}]`)}catch{K.issues.push({code:"invalid_format",format:"ipv6",input:K.value,inst:$,continue:!U.abort})}}}),R9=D("$ZodMAC",($,U)=>{U.pattern??(U.pattern=zU(U.delimiter)),s.init($,U),$._zod.bag.format="mac"}),z9=D("$ZodCIDRv4",($,U)=>{U.pattern??(U.pattern=bU),s.init($,U)}),b9=D("$ZodCIDRv6",($,U)=>{U.pattern??(U.pattern=OU),s.init($,U),$._zod.check=(K)=>{let q=K.value.split("/");try{if(q.length!==2)throw Error();let[Q,W]=q;if(!W)throw Error();let J=Number(W);if(`${J}`!==W)throw Error();if(J<0||J>128)throw Error();new URL(`http://[${Q}]`)}catch{K.issues.push({code:"invalid_format",format:"cidrv6",input:K.value,inst:$,continue:!U.abort})}}});function O9($){if($==="")return!0;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}var T9=D("$ZodBase64",($,U)=>{U.pattern??(U.pattern=TU),s.init($,U),$._zod.bag.contentEncoding="base64",$._zod.check=(K)=>{if(O9(K.value))return;K.issues.push({code:"invalid_format",format:"base64",input:K.value,inst:$,continue:!U.abort})}});function KY($){if(!B2.test($))return!1;let U=$.replace(/[-_]/g,(q)=>q==="-"?"+":"/"),K=U.padEnd(Math.ceil(U.length/4)*4,"=");return O9(K)}var S9=D("$ZodBase64URL",($,U)=>{U.pattern??(U.pattern=B2),s.init($,U),$._zod.bag.contentEncoding="base64url",$._zod.check=(K)=>{if(KY(K.value))return;K.issues.push({code:"invalid_format",format:"base64url",input:K.value,inst:$,continue:!U.abort})}}),C9=D("$ZodE164",($,U)=>{U.pattern??(U.pattern=SU),s.init($,U)});function qY($,U=null){try{let K=$.split(".");if(K.length!==3)return!1;let[q]=K;if(!q)return!1;let Q=JSON.parse(atob(q));if("typ"in Q&&Q?.typ!=="JWT")return!1;if(!Q.alg)return!1;if(U&&(!("alg"in Q)||Q.alg!==U))return!1;return!0}catch{return!1}}var E9=D("$ZodJWT",($,U)=>{s.init($,U),$._zod.check=(K)=>{if(qY(K.value,U.alg))return;K.issues.push({code:"invalid_format",format:"jwt",input:K.value,inst:$,continue:!U.abort})}}),y9=D("$ZodCustomStringFormat",($,U)=>{s.init($,U),$._zod.check=(K)=>{if(U.fn(K.value))return;K.issues.push({code:"invalid_format",format:U.format,input:K.value,inst:$,continue:!U.abort})}}),F2=D("$ZodNumber",($,U)=>{h.init($,U),$._zod.pattern=$._zod.bag.pattern??d6,$._zod.parse=(K,q)=>{if(U.coerce)try{K.value=Number(K.value)}catch(J){}let Q=K.value;if(typeof Q==="number"&&!Number.isNaN(Q)&&Number.isFinite(Q))return K;let W=typeof Q==="number"?Number.isNaN(Q)?"NaN":!Number.isFinite(Q)?"Infinity":void 0:void 0;return K.issues.push({expected:"number",code:"invalid_type",input:Q,inst:$,...W?{received:W}:{}}),K}}),g9=D("$ZodNumberFormat",($,U)=>{dU.init($,U),F2.init($,U)}),p6=D("$ZodBoolean",($,U)=>{h.init($,U),$._zod.pattern=mU,$._zod.parse=(K,q)=>{if(U.coerce)try{K.value=Boolean(K.value)}catch(W){}let Q=K.value;if(typeof Q==="boolean")return K;return K.issues.push({expected:"boolean",code:"invalid_type",input:Q,inst:$}),K}}),x2=D("$ZodBigInt",($,U)=>{h.init($,U),$._zod.pattern=uU,$._zod.parse=(K,q)=>{if(U.coerce)try{K.value=BigInt(K.value)}catch(Q){}if(typeof K.value==="bigint")return K;return K.issues.push({expected:"bigint",code:"invalid_type",input:K.value,inst:$}),K}}),u9=D("$ZodBigIntFormat",($,U)=>{oU.init($,U),x2.init($,U)}),f9=D("$ZodSymbol",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{let Q=K.value;if(typeof Q==="symbol")return K;return K.issues.push({expected:"symbol",code:"invalid_type",input:Q,inst:$}),K}}),m9=D("$ZodUndefined",($,U)=>{h.init($,U),$._zod.pattern=cU,$._zod.values=new Set([void 0]),$._zod.optin="optional",$._zod.optout="optional",$._zod.parse=(K,q)=>{let Q=K.value;if(typeof Q>"u")return K;return K.issues.push({expected:"undefined",code:"invalid_type",input:Q,inst:$}),K}}),h9=D("$ZodNull",($,U)=>{h.init($,U),$._zod.pattern=hU,$._zod.values=new Set([null]),$._zod.parse=(K,q)=>{let Q=K.value;if(Q===null)return K;return K.issues.push({expected:"null",code:"invalid_type",input:Q,inst:$}),K}}),c9=D("$ZodAny",($,U)=>{h.init($,U),$._zod.parse=(K)=>K}),l9=D("$ZodUnknown",($,U)=>{h.init($,U),$._zod.parse=(K)=>K}),r9=D("$ZodNever",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{return K.issues.push({expected:"never",code:"invalid_type",input:K.value,inst:$}),K}}),i9=D("$ZodVoid",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{let Q=K.value;if(typeof Q>"u")return K;return K.issues.push({expected:"void",code:"invalid_type",input:Q,inst:$}),K}}),d9=D("$ZodDate",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{if(U.coerce)try{K.value=new Date(K.value)}catch(j){}let Q=K.value,W=Q instanceof Date;if(W&&!Number.isNaN(Q.getTime()))return K;return K.issues.push({expected:"date",code:"invalid_type",input:Q,...W?{received:"Invalid Date"}:{},inst:$}),K}});function dj($,U,K){if($.issues.length)U.issues.push(...m$(K,$.issues));U.value[K]=$.value}var o9=D("$ZodArray",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{let Q=K.value;if(!Array.isArray(Q))return K.issues.push({expected:"array",code:"invalid_type",input:Q,inst:$}),K;K.value=Array(Q.length);let W=[];for(let J=0;J<Q.length;J++){let j=Q[J],Y=U.element._zod.run({value:j,issues:[]},q);if(Y instanceof Promise)W.push(Y.then((H)=>dj(H,K,J)));else dj(Y,K,J)}if(W.length)return Promise.all(W).then(()=>K);return K}});function I2($,U,K,q,Q){if($.issues.length){if(Q&&!(K in q))return;U.issues.push(...m$(K,$.issues))}if($.value===void 0){if(K in q)U.value[K]=void 0}else U.value[K]=$.value}function WY($){let U=Object.keys($.shape);for(let q of U)if(!$.shape?.[q]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${q}": expected a Zod schema`);let K=HU($.shape);return{...$,keys:U,keySet:new Set(U),numKeys:U.length,optionalKeys:new Set(K)}}function JY($,U,K,q,Q,W){let J=[],j=Q.keySet,Y=Q.catchall._zod,H=Y.def.type,Z=Y.optout==="optional";for(let B in U){if(j.has(B))continue;if(H==="never"){J.push(B);continue}let M=Y.run({value:U[B],issues:[]},q);if(M instanceof Promise)$.push(M.then((I)=>I2(I,K,B,U,Z)));else I2(M,K,B,U,Z)}if(J.length)K.issues.push({code:"unrecognized_keys",keys:J,input:U,inst:W});if(!$.length)return K;return Promise.all($).then(()=>{return K})}var GY=D("$ZodObject",($,U)=>{if(h.init($,U),!Object.getOwnPropertyDescriptor(U,"shape")?.get){let j=U.shape;Object.defineProperty(U,"shape",{get:()=>{let Y={...j};return Object.defineProperty(U,"shape",{value:Y}),Y}})}let q=f4(()=>WY(U));r($._zod,"propValues",()=>{let j=U.shape,Y={};for(let H in j){let Z=j[H]._zod;if(Z.values){Y[H]??(Y[H]=new Set);for(let B of Z.values)Y[H].add(B)}}return Y});let Q=Z4,W=U.catchall,J;$._zod.parse=(j,Y)=>{J??(J=q.value);let H=j.value;if(!Q(H))return j.issues.push({expected:"object",code:"invalid_type",input:H,inst:$}),j;j.value={};let Z=[],B=J.shape;for(let M of J.keys){let I=B[M],E=I._zod.optout==="optional",u=I._zod.run({value:H[M],issues:[]},Y);if(u instanceof Promise)Z.push(u.then((U$)=>I2(U$,j,M,H,E)));else I2(u,j,M,H,E)}if(!W)return Z.length?Promise.all(Z).then(()=>j):j;return JY(Z,H,j,Y,q.value,$)}}),n9=D("$ZodObjectJIT",($,U)=>{GY.init($,U);let K=$._zod.parse,q=f4(()=>WY(U)),Q=(M)=>{let I=new D2(["shape","payload","ctx"]),E=q.value,u=(i$)=>{let C$=U2(i$);return`shape[${C$}]._zod.run({ value: input[${C$}], issues: [] }, ctx)`};I.write("const input = payload.value;");let U$=Object.create(null),S$=0;for(let i$ of E.keys)U$[i$]=`key_${S$++}`;I.write("const newResult = {};");for(let i$ of E.keys){let C$=U$[i$],e$=U2(i$),vV=M[i$]?._zod?.optout==="optional";if(I.write(`const ${C$} = ${u(i$)};`),vV)I.write(`
|
|
50
|
+
`))}}var J9={major:4,minor:3,patch:6};var h=D("$ZodType",($,U)=>{var K;$??($={}),$._zod.def=U,$._zod.bag=$._zod.bag||{},$._zod.version=J9;let q=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))q.unshift($);for(let Q of q)for(let W of Q._zod.onattach)W($);if(q.length===0)(K=$._zod).deferred??(K.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let Q=(G,j,Y)=>{let H=g1(G),X;for(let B of j){if(B._zod.def.when){if(!B._zod.def.when(G))continue}else if(H)continue;let M=G.issues.length,I=B._zod.check(G);if(I instanceof Promise&&Y?.async===!1)throw new H1;if(X||I instanceof Promise)X=(X??Promise.resolve()).then(async()=>{if(await I,G.issues.length===M)return;if(!H)H=g1(G,M)});else{if(G.issues.length===M)continue;if(!H)H=g1(G,M)}}if(X)return X.then(()=>{return G});return G},W=(G,j,Y)=>{if(g1(G))return G.aborted=!0,G;let H=Q(j,q,Y);if(H instanceof Promise){if(Y.async===!1)throw new H1;return H.then((X)=>$._zod.parse(X,Y))}return $._zod.parse(H,Y)};$._zod.run=(G,j)=>{if(j.skipChecks)return $._zod.parse(G,j);if(j.direction==="backward"){let H=$._zod.parse({value:G.value,issues:[]},{...j,skipChecks:!0});if(H instanceof Promise)return H.then((X)=>{return W(X,G,j)});return W(H,G,j)}let Y=$._zod.parse(G,j);if(Y instanceof Promise){if(j.async===!1)throw new H1;return Y.then((H)=>Q(H,q,j))}return Q(Y,q,j)}}r($,"~standard",()=>({validate:(Q)=>{try{let W=BU($,Q);return W.success?{value:W.data}:{issues:W.error?.issues}}catch(W){return VU($,Q).then((G)=>G.success?{value:G.data}:{issues:G.error?.issues})}},vendor:"zod",version:1}))}),B4=D("$ZodString",($,U)=>{h.init($,U),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??EU($._zod.bag),$._zod.parse=(K,q)=>{if(U.coerce)try{K.value=String(K.value)}catch(Q){}if(typeof K.value==="string")return K;return K.issues.push({expected:"string",code:"invalid_type",input:K.value,inst:$}),K}}),s=D("$ZodStringFormat",($,U)=>{c4.init($,U),B4.init($,U)}),Y9=D("$ZodGUID",($,U)=>{U.pattern??(U.pattern=FU),s.init($,U)}),H9=D("$ZodUUID",($,U)=>{if(U.version){let q={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[U.version];if(q===void 0)throw Error(`Invalid UUID version: "${U.version}"`);U.pattern??(U.pattern=Z4(q))}else U.pattern??(U.pattern=Z4());s.init($,U)}),X9=D("$ZodEmail",($,U)=>{U.pattern??(U.pattern=xU),s.init($,U)}),Z9=D("$ZodURL",($,U)=>{s.init($,U),$._zod.check=(K)=>{try{let q=K.value.trim(),Q=new URL(q);if(U.hostname){if(U.hostname.lastIndex=0,!U.hostname.test(Q.hostname))K.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:U.hostname.source,input:K.value,inst:$,continue:!U.abort})}if(U.protocol){if(U.protocol.lastIndex=0,!U.protocol.test(Q.protocol.endsWith(":")?Q.protocol.slice(0,-1):Q.protocol))K.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:U.protocol.source,input:K.value,inst:$,continue:!U.abort})}if(U.normalize)K.value=Q.href;else K.value=q;return}catch(q){K.issues.push({code:"invalid_format",format:"url",input:K.value,inst:$,continue:!U.abort})}}}),B9=D("$ZodEmoji",($,U)=>{U.pattern??(U.pattern=wU()),s.init($,U)}),V9=D("$ZodNanoID",($,U)=>{U.pattern??(U.pattern=_U),s.init($,U)}),M9=D("$ZodCUID",($,U)=>{U.pattern??(U.pattern=MU),s.init($,U)}),D9=D("$ZodCUID2",($,U)=>{U.pattern??(U.pattern=DU),s.init($,U)}),P9=D("$ZodULID",($,U)=>{U.pattern??(U.pattern=PU),s.init($,U)}),N9=D("$ZodXID",($,U)=>{U.pattern??(U.pattern=NU),s.init($,U)}),L9=D("$ZodKSUID",($,U)=>{U.pattern??(U.pattern=LU),s.init($,U)}),_9=D("$ZodISODateTime",($,U)=>{U.pattern??(U.pattern=CU(U)),s.init($,U)}),I9=D("$ZodISODate",($,U)=>{U.pattern??(U.pattern=TU),s.init($,U)}),F9=D("$ZodISOTime",($,U)=>{U.pattern??(U.pattern=SU(U)),s.init($,U)}),x9=D("$ZodISODuration",($,U)=>{U.pattern??(U.pattern=IU),s.init($,U)}),w9=D("$ZodIPv4",($,U)=>{U.pattern??(U.pattern=AU),s.init($,U),$._zod.bag.format="ipv4"}),A9=D("$ZodIPv6",($,U)=>{U.pattern??(U.pattern=vU),s.init($,U),$._zod.bag.format="ipv6",$._zod.check=(K)=>{try{new URL(`http://[${K.value}]`)}catch{K.issues.push({code:"invalid_format",format:"ipv6",input:K.value,inst:$,continue:!U.abort})}}}),v9=D("$ZodMAC",($,U)=>{U.pattern??(U.pattern=kU(U.delimiter)),s.init($,U),$._zod.bag.format="mac"}),k9=D("$ZodCIDRv4",($,U)=>{U.pattern??(U.pattern=zU),s.init($,U)}),z9=D("$ZodCIDRv6",($,U)=>{U.pattern??(U.pattern=RU),s.init($,U),$._zod.check=(K)=>{let q=K.value.split("/");try{if(q.length!==2)throw Error();let[Q,W]=q;if(!W)throw Error();let G=Number(W);if(`${G}`!==W)throw Error();if(G<0||G>128)throw Error();new URL(`http://[${Q}]`)}catch{K.issues.push({code:"invalid_format",format:"cidrv6",input:K.value,inst:$,continue:!U.abort})}}});function R9($){if($==="")return!0;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}var b9=D("$ZodBase64",($,U)=>{U.pattern??(U.pattern=bU),s.init($,U),$._zod.bag.contentEncoding="base64",$._zod.check=(K)=>{if(R9(K.value))return;K.issues.push({code:"invalid_format",format:"base64",input:K.value,inst:$,continue:!U.abort})}});function tj($){if(!B2.test($))return!1;let U=$.replace(/[-_]/g,(q)=>q==="-"?"+":"/"),K=U.padEnd(Math.ceil(U.length/4)*4,"=");return R9(K)}var O9=D("$ZodBase64URL",($,U)=>{U.pattern??(U.pattern=B2),s.init($,U),$._zod.bag.contentEncoding="base64url",$._zod.check=(K)=>{if(tj(K.value))return;K.issues.push({code:"invalid_format",format:"base64url",input:K.value,inst:$,continue:!U.abort})}}),T9=D("$ZodE164",($,U)=>{U.pattern??(U.pattern=OU),s.init($,U)});function aj($,U=null){try{let K=$.split(".");if(K.length!==3)return!1;let[q]=K;if(!q)return!1;let Q=JSON.parse(atob(q));if("typ"in Q&&Q?.typ!=="JWT")return!1;if(!Q.alg)return!1;if(U&&(!("alg"in Q)||Q.alg!==U))return!1;return!0}catch{return!1}}var S9=D("$ZodJWT",($,U)=>{s.init($,U),$._zod.check=(K)=>{if(aj(K.value,U.alg))return;K.issues.push({code:"invalid_format",format:"jwt",input:K.value,inst:$,continue:!U.abort})}}),C9=D("$ZodCustomStringFormat",($,U)=>{s.init($,U),$._zod.check=(K)=>{if(U.fn(K.value))return;K.issues.push({code:"invalid_format",format:U.format,input:K.value,inst:$,continue:!U.abort})}}),F2=D("$ZodNumber",($,U)=>{h.init($,U),$._zod.pattern=$._zod.bag.pattern??o6,$._zod.parse=(K,q)=>{if(U.coerce)try{K.value=Number(K.value)}catch(G){}let Q=K.value;if(typeof Q==="number"&&!Number.isNaN(Q)&&Number.isFinite(Q))return K;let W=typeof Q==="number"?Number.isNaN(Q)?"NaN":!Number.isFinite(Q)?"Infinity":void 0:void 0;return K.issues.push({expected:"number",code:"invalid_type",input:Q,inst:$,...W?{received:W}:{}}),K}}),E9=D("$ZodNumberFormat",($,U)=>{rU.init($,U),F2.init($,U)}),t6=D("$ZodBoolean",($,U)=>{h.init($,U),$._zod.pattern=uU,$._zod.parse=(K,q)=>{if(U.coerce)try{K.value=Boolean(K.value)}catch(W){}let Q=K.value;if(typeof Q==="boolean")return K;return K.issues.push({expected:"boolean",code:"invalid_type",input:Q,inst:$}),K}}),x2=D("$ZodBigInt",($,U)=>{h.init($,U),$._zod.pattern=yU,$._zod.parse=(K,q)=>{if(U.coerce)try{K.value=BigInt(K.value)}catch(Q){}if(typeof K.value==="bigint")return K;return K.issues.push({expected:"bigint",code:"invalid_type",input:K.value,inst:$}),K}}),y9=D("$ZodBigIntFormat",($,U)=>{iU.init($,U),x2.init($,U)}),g9=D("$ZodSymbol",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{let Q=K.value;if(typeof Q==="symbol")return K;return K.issues.push({expected:"symbol",code:"invalid_type",input:Q,inst:$}),K}}),u9=D("$ZodUndefined",($,U)=>{h.init($,U),$._zod.pattern=mU,$._zod.values=new Set([void 0]),$._zod.optin="optional",$._zod.optout="optional",$._zod.parse=(K,q)=>{let Q=K.value;if(typeof Q>"u")return K;return K.issues.push({expected:"undefined",code:"invalid_type",input:Q,inst:$}),K}}),f9=D("$ZodNull",($,U)=>{h.init($,U),$._zod.pattern=fU,$._zod.values=new Set([null]),$._zod.parse=(K,q)=>{let Q=K.value;if(Q===null)return K;return K.issues.push({expected:"null",code:"invalid_type",input:Q,inst:$}),K}}),m9=D("$ZodAny",($,U)=>{h.init($,U),$._zod.parse=(K)=>K}),h9=D("$ZodUnknown",($,U)=>{h.init($,U),$._zod.parse=(K)=>K}),c9=D("$ZodNever",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{return K.issues.push({expected:"never",code:"invalid_type",input:K.value,inst:$}),K}}),l9=D("$ZodVoid",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{let Q=K.value;if(typeof Q>"u")return K;return K.issues.push({expected:"void",code:"invalid_type",input:Q,inst:$}),K}}),r9=D("$ZodDate",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{if(U.coerce)try{K.value=new Date(K.value)}catch(j){}let Q=K.value,W=Q instanceof Date;if(W&&!Number.isNaN(Q.getTime()))return K;return K.issues.push({expected:"date",code:"invalid_type",input:Q,...W?{received:"Invalid Date"}:{},inst:$}),K}});function fj($,U,K){if($.issues.length)U.issues.push(...m$(K,$.issues));U.value[K]=$.value}var i9=D("$ZodArray",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{let Q=K.value;if(!Array.isArray(Q))return K.issues.push({expected:"array",code:"invalid_type",input:Q,inst:$}),K;K.value=Array(Q.length);let W=[];for(let G=0;G<Q.length;G++){let j=Q[G],Y=U.element._zod.run({value:j,issues:[]},q);if(Y instanceof Promise)W.push(Y.then((H)=>fj(H,K,G)));else fj(Y,K,G)}if(W.length)return Promise.all(W).then(()=>K);return K}});function I2($,U,K,q,Q){if($.issues.length){if(Q&&!(K in q))return;U.issues.push(...m$(K,$.issues))}if($.value===void 0){if(K in q)U.value[K]=void 0}else U.value[K]=$.value}function sj($){let U=Object.keys($.shape);for(let q of U)if(!$.shape?.[q]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${q}": expected a Zod schema`);let K=jU($.shape);return{...$,keys:U,keySet:new Set(U),numKeys:U.length,optionalKeys:new Set(K)}}function ej($,U,K,q,Q,W){let G=[],j=Q.keySet,Y=Q.catchall._zod,H=Y.def.type,X=Y.optout==="optional";for(let B in U){if(j.has(B))continue;if(H==="never"){G.push(B);continue}let M=Y.run({value:U[B],issues:[]},q);if(M instanceof Promise)$.push(M.then((I)=>I2(I,K,B,U,X)));else I2(M,K,B,U,X)}if(G.length)K.issues.push({code:"unrecognized_keys",keys:G,input:U,inst:W});if(!$.length)return K;return Promise.all($).then(()=>{return K})}var $Y=D("$ZodObject",($,U)=>{if(h.init($,U),!Object.getOwnPropertyDescriptor(U,"shape")?.get){let j=U.shape;Object.defineProperty(U,"shape",{get:()=>{let Y={...j};return Object.defineProperty(U,"shape",{value:Y}),Y}})}let q=y4(()=>sj(U));r($._zod,"propValues",()=>{let j=U.shape,Y={};for(let H in j){let X=j[H]._zod;if(X.values){Y[H]??(Y[H]=new Set);for(let B of X.values)Y[H].add(B)}}return Y});let Q=X4,W=U.catchall,G;$._zod.parse=(j,Y)=>{G??(G=q.value);let H=j.value;if(!Q(H))return j.issues.push({expected:"object",code:"invalid_type",input:H,inst:$}),j;j.value={};let X=[],B=G.shape;for(let M of G.keys){let I=B[M],E=I._zod.optout==="optional",u=I._zod.run({value:H[M],issues:[]},Y);if(u instanceof Promise)X.push(u.then((U$)=>I2(U$,j,M,H,E)));else I2(u,j,M,H,E)}if(!W)return X.length?Promise.all(X).then(()=>j):j;return ej(X,H,j,Y,q.value,$)}}),d9=D("$ZodObjectJIT",($,U)=>{$Y.init($,U);let K=$._zod.parse,q=y4(()=>sj(U)),Q=(M)=>{let I=new D2(["shape","payload","ctx"]),E=q.value,u=(i$)=>{let C$=U2(i$);return`shape[${C$}]._zod.run({ value: input[${C$}], issues: [] }, ctx)`};I.write("const input = payload.value;");let U$=Object.create(null),S$=0;for(let i$ of E.keys)U$[i$]=`key_${S$++}`;I.write("const newResult = {};");for(let i$ of E.keys){let C$=U$[i$],e$=U2(i$),EV=M[i$]?._zod?.optout==="optional";if(I.write(`const ${C$} = ${u(i$)};`),EV)I.write(`
|
|
56
51
|
if (${C$}.issues.length) {
|
|
57
52
|
if (${e$} in input) {
|
|
58
53
|
payload.issues = payload.issues.concat(${C$}.issues.map(iss => ({
|
|
@@ -86,18 +81,24 @@ Closing...`),$.close()})}function Oj($,U,K){let q=$.command("chat").description(
|
|
|
86
81
|
newResult[${e$}] = ${C$}.value;
|
|
87
82
|
}
|
|
88
83
|
|
|
89
|
-
`)}I.write("payload.value = newResult;"),I.write("return payload;");let k4=I.compile();return(i$,C$)=>k4(M,i$,C$)},W,J=Z4,j=!y6.jitless,H=j&&GU.value,Z=U.catchall,B;$._zod.parse=(M,I)=>{B??(B=q.value);let E=M.value;if(!J(E))return M.issues.push({expected:"object",code:"invalid_type",input:E,inst:$}),M;if(j&&H&&I?.async===!1&&I.jitless!==!0){if(!W)W=Q(U.shape);if(M=W(M,I),!Z)return M;return JY([],E,M,I,B,$)}return K(M,I)}});function oj($,U,K,q){for(let W of $)if(W.issues.length===0)return U.value=W.value,U;let Q=$.filter((W)=>!g1(W));if(Q.length===1)return U.value=Q[0].value,Q[0];return U.issues.push({code:"invalid_union",input:U.value,inst:K,errors:$.map((W)=>W.issues.map((J)=>E$(J,q,Z$())))}),U}var t6=D("$ZodUnion",($,U)=>{h.init($,U),r($._zod,"optin",()=>U.options.some((Q)=>Q._zod.optin==="optional")?"optional":void 0),r($._zod,"optout",()=>U.options.some((Q)=>Q._zod.optout==="optional")?"optional":void 0),r($._zod,"values",()=>{if(U.options.every((Q)=>Q._zod.values))return new Set(U.options.flatMap((Q)=>Array.from(Q._zod.values)));return}),r($._zod,"pattern",()=>{if(U.options.every((Q)=>Q._zod.pattern)){let Q=U.options.map((W)=>W._zod.pattern);return new RegExp(`^(${Q.map((W)=>f6(W.source)).join("|")})$`)}return});let K=U.options.length===1,q=U.options[0]._zod.run;$._zod.parse=(Q,W)=>{if(K)return q(Q,W);let J=!1,j=[];for(let Y of U.options){let H=Y._zod.run({value:Q.value,issues:[]},W);if(H instanceof Promise)j.push(H),J=!0;else{if(H.issues.length===0)return H;j.push(H)}}if(!J)return oj(j,Q,$,W);return Promise.all(j).then((Y)=>{return oj(Y,Q,$,W)})}});function nj($,U,K,q){let Q=$.filter((W)=>W.issues.length===0);if(Q.length===1)return U.value=Q[0].value,U;if(Q.length===0)U.issues.push({code:"invalid_union",input:U.value,inst:K,errors:$.map((W)=>W.issues.map((J)=>E$(J,q,Z$())))});else U.issues.push({code:"invalid_union",input:U.value,inst:K,errors:[],inclusive:!1});return U}var p9=D("$ZodXor",($,U)=>{t6.init($,U),U.inclusive=!1;let K=U.options.length===1,q=U.options[0]._zod.run;$._zod.parse=(Q,W)=>{if(K)return q(Q,W);let J=!1,j=[];for(let Y of U.options){let H=Y._zod.run({value:Q.value,issues:[]},W);if(H instanceof Promise)j.push(H),J=!0;else j.push(H)}if(!J)return nj(j,Q,$,W);return Promise.all(j).then((Y)=>{return nj(Y,Q,$,W)})}}),t9=D("$ZodDiscriminatedUnion",($,U)=>{U.inclusive=!1,t6.init($,U);let K=$._zod.parse;r($._zod,"propValues",()=>{let Q={};for(let W of U.options){let J=W._zod.propValues;if(!J||Object.keys(J).length===0)throw Error(`Invalid discriminated union option at index "${U.options.indexOf(W)}"`);for(let[j,Y]of Object.entries(J)){if(!Q[j])Q[j]=new Set;for(let H of Y)Q[j].add(H)}}return Q});let q=f4(()=>{let Q=U.options,W=new Map;for(let J of Q){let j=J._zod.propValues?.[U.discriminator];if(!j||j.size===0)throw Error(`Invalid discriminated union option at index "${U.options.indexOf(J)}"`);for(let Y of j){if(W.has(Y))throw Error(`Duplicate discriminator value "${String(Y)}"`);W.set(Y,J)}}return W});$._zod.parse=(Q,W)=>{let J=Q.value;if(!Z4(J))return Q.issues.push({code:"invalid_type",expected:"object",input:J,inst:$}),Q;let j=q.value.get(J?.[U.discriminator]);if(j)return j._zod.run(Q,W);if(U.unionFallback)return K(Q,W);return Q.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:U.discriminator,input:J,path:[U.discriminator],inst:$}),Q}}),a9=D("$ZodIntersection",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{let Q=K.value,W=U.left._zod.run({value:Q,issues:[]},q),J=U.right._zod.run({value:Q,issues:[]},q);if(W instanceof Promise||J instanceof Promise)return Promise.all([W,J]).then(([Y,H])=>{return pj(K,Y,H)});return pj(K,W,J)}});function H9($,U){if($===U)return{valid:!0,data:$};if($ instanceof Date&&U instanceof Date&&+$===+U)return{valid:!0,data:$};if(y1($)&&y1(U)){let K=Object.keys(U),q=Object.keys($).filter((W)=>K.indexOf(W)!==-1),Q={...$,...U};for(let W of q){let J=H9($[W],U[W]);if(!J.valid)return{valid:!1,mergeErrorPath:[W,...J.mergeErrorPath]};Q[W]=J.data}return{valid:!0,data:Q}}if(Array.isArray($)&&Array.isArray(U)){if($.length!==U.length)return{valid:!1,mergeErrorPath:[]};let K=[];for(let q=0;q<$.length;q++){let Q=$[q],W=U[q],J=H9(Q,W);if(!J.valid)return{valid:!1,mergeErrorPath:[q,...J.mergeErrorPath]};K.push(J.data)}return{valid:!0,data:K}}return{valid:!1,mergeErrorPath:[]}}function pj($,U,K){let q=new Map,Q;for(let j of U.issues)if(j.code==="unrecognized_keys"){Q??(Q=j);for(let Y of j.keys){if(!q.has(Y))q.set(Y,{});q.get(Y).l=!0}}else $.issues.push(j);for(let j of K.issues)if(j.code==="unrecognized_keys")for(let Y of j.keys){if(!q.has(Y))q.set(Y,{});q.get(Y).r=!0}else $.issues.push(j);let W=[...q].filter(([,j])=>j.l&&j.r).map(([j])=>j);if(W.length&&Q)$.issues.push({...Q,keys:W});if(g1($))return $;let J=H9(U.value,K.value);if(!J.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(J.mergeErrorPath)}`);return $.value=J.data,$}var w2=D("$ZodTuple",($,U)=>{h.init($,U);let K=U.items;$._zod.parse=(q,Q)=>{let W=q.value;if(!Array.isArray(W))return q.issues.push({input:W,inst:$,expected:"tuple",code:"invalid_type"}),q;q.value=[];let J=[],j=[...K].reverse().findIndex((Z)=>Z._zod.optin!=="optional"),Y=j===-1?0:K.length-j;if(!U.rest){let Z=W.length>K.length,B=W.length<Y-1;if(Z||B)return q.issues.push({...Z?{code:"too_big",maximum:K.length,inclusive:!0}:{code:"too_small",minimum:K.length},input:W,inst:$,origin:"array"}),q}let H=-1;for(let Z of K){if(H++,H>=W.length){if(H>=Y)continue}let B=Z._zod.run({value:W[H],issues:[]},Q);if(B instanceof Promise)J.push(B.then((M)=>P2(M,q,H)));else P2(B,q,H)}if(U.rest){let Z=W.slice(K.length);for(let B of Z){H++;let M=U.rest._zod.run({value:B,issues:[]},Q);if(M instanceof Promise)J.push(M.then((I)=>P2(I,q,H)));else P2(M,q,H)}}if(J.length)return Promise.all(J).then(()=>q);return q}});function P2($,U,K){if($.issues.length)U.issues.push(...m$(K,$.issues));U.value[K]=$.value}var s9=D("$ZodRecord",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{let Q=K.value;if(!y1(Q))return K.issues.push({expected:"record",code:"invalid_type",input:Q,inst:$}),K;let W=[],J=U.keyType._zod.values;if(J){K.value={};let j=new Set;for(let H of J)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){j.add(typeof H==="number"?H.toString():H);let Z=U.valueType._zod.run({value:Q[H],issues:[]},q);if(Z instanceof Promise)W.push(Z.then((B)=>{if(B.issues.length)K.issues.push(...m$(H,B.issues));K.value[H]=B.value}));else{if(Z.issues.length)K.issues.push(...m$(H,Z.issues));K.value[H]=Z.value}}let Y;for(let H in Q)if(!j.has(H))Y=Y??[],Y.push(H);if(Y&&Y.length>0)K.issues.push({code:"unrecognized_keys",input:Q,inst:$,keys:Y})}else{K.value={};for(let j of Reflect.ownKeys(Q)){if(j==="__proto__")continue;let Y=U.keyType._zod.run({value:j,issues:[]},q);if(Y instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof j==="string"&&d6.test(j)&&Y.issues.length){let B=U.keyType._zod.run({value:Number(j),issues:[]},q);if(B instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(B.issues.length===0)Y=B}if(Y.issues.length){if(U.mode==="loose")K.value[j]=Q[j];else K.issues.push({code:"invalid_key",origin:"record",issues:Y.issues.map((B)=>E$(B,q,Z$())),input:j,path:[j],inst:$});continue}let Z=U.valueType._zod.run({value:Q[j],issues:[]},q);if(Z instanceof Promise)W.push(Z.then((B)=>{if(B.issues.length)K.issues.push(...m$(j,B.issues));K.value[Y.value]=B.value}));else{if(Z.issues.length)K.issues.push(...m$(j,Z.issues));K.value[Y.value]=Z.value}}}if(W.length)return Promise.all(W).then(()=>K);return K}}),e9=D("$ZodMap",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{let Q=K.value;if(!(Q instanceof Map))return K.issues.push({expected:"map",code:"invalid_type",input:Q,inst:$}),K;let W=[];K.value=new Map;for(let[J,j]of Q){let Y=U.keyType._zod.run({value:J,issues:[]},q),H=U.valueType._zod.run({value:j,issues:[]},q);if(Y instanceof Promise||H instanceof Promise)W.push(Promise.all([Y,H]).then(([Z,B])=>{tj(Z,B,K,J,Q,$,q)}));else tj(Y,H,K,J,Q,$,q)}if(W.length)return Promise.all(W).then(()=>K);return K}});function tj($,U,K,q,Q,W,J){if($.issues.length)if(m6.has(typeof q))K.issues.push(...m$(q,$.issues));else K.issues.push({code:"invalid_key",origin:"map",input:Q,inst:W,issues:$.issues.map((j)=>E$(j,J,Z$()))});if(U.issues.length)if(m6.has(typeof q))K.issues.push(...m$(q,U.issues));else K.issues.push({origin:"map",code:"invalid_element",input:Q,inst:W,key:q,issues:U.issues.map((j)=>E$(j,J,Z$()))});K.value.set($.value,U.value)}var $5=D("$ZodSet",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{let Q=K.value;if(!(Q instanceof Set))return K.issues.push({input:Q,inst:$,expected:"set",code:"invalid_type"}),K;let W=[];K.value=new Set;for(let J of Q){let j=U.valueType._zod.run({value:J,issues:[]},q);if(j instanceof Promise)W.push(j.then((Y)=>aj(Y,K)));else aj(j,K)}if(W.length)return Promise.all(W).then(()=>K);return K}});function aj($,U){if($.issues.length)U.issues.push(...$.issues);U.value.add($.value)}var U5=D("$ZodEnum",($,U)=>{h.init($,U);let K=u6(U.entries),q=new Set(K);$._zod.values=q,$._zod.pattern=new RegExp(`^(${K.filter((Q)=>m6.has(typeof Q)).map((Q)=>typeof Q==="string"?o$(Q):Q.toString()).join("|")})$`),$._zod.parse=(Q,W)=>{let J=Q.value;if(q.has(J))return Q;return Q.issues.push({code:"invalid_value",values:K,input:J,inst:$}),Q}}),Q5=D("$ZodLiteral",($,U)=>{if(h.init($,U),U.values.length===0)throw Error("Cannot create literal schema with no valid values");let K=new Set(U.values);$._zod.values=K,$._zod.pattern=new RegExp(`^(${U.values.map((q)=>typeof q==="string"?o$(q):q?o$(q.toString()):String(q)).join("|")})$`),$._zod.parse=(q,Q)=>{let W=q.value;if(K.has(W))return q;return q.issues.push({code:"invalid_value",values:U.values,input:W,inst:$}),q}}),K5=D("$ZodFile",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{let Q=K.value;if(Q instanceof File)return K;return K.issues.push({expected:"file",code:"invalid_type",input:Q,inst:$}),K}}),q5=D("$ZodTransform",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{if(q.direction==="backward")throw new X4($.constructor.name);let Q=U.transform(K.value,K);if(q.async)return(Q instanceof Promise?Q:Promise.resolve(Q)).then((J)=>{return K.value=J,K});if(Q instanceof Promise)throw new X1;return K.value=Q,K}});function sj($,U){if($.issues.length&&U===void 0)return{issues:[],value:void 0};return $}var A2=D("$ZodOptional",($,U)=>{h.init($,U),$._zod.optin="optional",$._zod.optout="optional",r($._zod,"values",()=>{return U.innerType._zod.values?new Set([...U.innerType._zod.values,void 0]):void 0}),r($._zod,"pattern",()=>{let K=U.innerType._zod.pattern;return K?new RegExp(`^(${f6(K.source)})?$`):void 0}),$._zod.parse=(K,q)=>{if(U.innerType._zod.optin==="optional"){let Q=U.innerType._zod.run(K,q);if(Q instanceof Promise)return Q.then((W)=>sj(W,K.value));return sj(Q,K.value)}if(K.value===void 0)return K;return U.innerType._zod.run(K,q)}}),W5=D("$ZodExactOptional",($,U)=>{A2.init($,U),r($._zod,"values",()=>U.innerType._zod.values),r($._zod,"pattern",()=>U.innerType._zod.pattern),$._zod.parse=(K,q)=>{return U.innerType._zod.run(K,q)}}),J5=D("$ZodNullable",($,U)=>{h.init($,U),r($._zod,"optin",()=>U.innerType._zod.optin),r($._zod,"optout",()=>U.innerType._zod.optout),r($._zod,"pattern",()=>{let K=U.innerType._zod.pattern;return K?new RegExp(`^(${f6(K.source)}|null)$`):void 0}),r($._zod,"values",()=>{return U.innerType._zod.values?new Set([...U.innerType._zod.values,null]):void 0}),$._zod.parse=(K,q)=>{if(K.value===null)return K;return U.innerType._zod.run(K,q)}}),G5=D("$ZodDefault",($,U)=>{h.init($,U),$._zod.optin="optional",r($._zod,"values",()=>U.innerType._zod.values),$._zod.parse=(K,q)=>{if(q.direction==="backward")return U.innerType._zod.run(K,q);if(K.value===void 0)return K.value=U.defaultValue,K;let Q=U.innerType._zod.run(K,q);if(Q instanceof Promise)return Q.then((W)=>ej(W,U));return ej(Q,U)}});function ej($,U){if($.value===void 0)$.value=U.defaultValue;return $}var j5=D("$ZodPrefault",($,U)=>{h.init($,U),$._zod.optin="optional",r($._zod,"values",()=>U.innerType._zod.values),$._zod.parse=(K,q)=>{if(q.direction==="backward")return U.innerType._zod.run(K,q);if(K.value===void 0)K.value=U.defaultValue;return U.innerType._zod.run(K,q)}}),Y5=D("$ZodNonOptional",($,U)=>{h.init($,U),r($._zod,"values",()=>{let K=U.innerType._zod.values;return K?new Set([...K].filter((q)=>q!==void 0)):void 0}),$._zod.parse=(K,q)=>{let Q=U.innerType._zod.run(K,q);if(Q instanceof Promise)return Q.then((W)=>$Y(W,$));return $Y(Q,$)}});function $Y($,U){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:U});return $}var H5=D("$ZodSuccess",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{if(q.direction==="backward")throw new X4("ZodSuccess");let Q=U.innerType._zod.run(K,q);if(Q instanceof Promise)return Q.then((W)=>{return K.value=W.issues.length===0,K});return K.value=Q.issues.length===0,K}}),X5=D("$ZodCatch",($,U)=>{h.init($,U),r($._zod,"optin",()=>U.innerType._zod.optin),r($._zod,"optout",()=>U.innerType._zod.optout),r($._zod,"values",()=>U.innerType._zod.values),$._zod.parse=(K,q)=>{if(q.direction==="backward")return U.innerType._zod.run(K,q);let Q=U.innerType._zod.run(K,q);if(Q instanceof Promise)return Q.then((W)=>{if(K.value=W.value,W.issues.length)K.value=U.catchValue({...K,error:{issues:W.issues.map((J)=>E$(J,q,Z$()))},input:K.value}),K.issues=[];return K});if(K.value=Q.value,Q.issues.length)K.value=U.catchValue({...K,error:{issues:Q.issues.map((W)=>E$(W,q,Z$()))},input:K.value}),K.issues=[];return K}}),Z5=D("$ZodNaN",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{if(typeof K.value!=="number"||!Number.isNaN(K.value))return K.issues.push({input:K.value,inst:$,expected:"nan",code:"invalid_type"}),K;return K}}),B5=D("$ZodPipe",($,U)=>{h.init($,U),r($._zod,"values",()=>U.in._zod.values),r($._zod,"optin",()=>U.in._zod.optin),r($._zod,"optout",()=>U.out._zod.optout),r($._zod,"propValues",()=>U.in._zod.propValues),$._zod.parse=(K,q)=>{if(q.direction==="backward"){let W=U.out._zod.run(K,q);if(W instanceof Promise)return W.then((J)=>N2(J,U.in,q));return N2(W,U.in,q)}let Q=U.in._zod.run(K,q);if(Q instanceof Promise)return Q.then((W)=>N2(W,U.out,q));return N2(Q,U.out,q)}});function N2($,U,K){if($.issues.length)return $.aborted=!0,$;return U._zod.run({value:$.value,issues:$.issues},K)}var a6=D("$ZodCodec",($,U)=>{h.init($,U),r($._zod,"values",()=>U.in._zod.values),r($._zod,"optin",()=>U.in._zod.optin),r($._zod,"optout",()=>U.out._zod.optout),r($._zod,"propValues",()=>U.in._zod.propValues),$._zod.parse=(K,q)=>{if((q.direction||"forward")==="forward"){let W=U.in._zod.run(K,q);if(W instanceof Promise)return W.then((J)=>L2(J,U,q));return L2(W,U,q)}else{let W=U.out._zod.run(K,q);if(W instanceof Promise)return W.then((J)=>L2(J,U,q));return L2(W,U,q)}}});function L2($,U,K){if($.issues.length)return $.aborted=!0,$;if((K.direction||"forward")==="forward"){let Q=U.transform($.value,$);if(Q instanceof Promise)return Q.then((W)=>_2($,W,U.out,K));return _2($,Q,U.out,K)}else{let Q=U.reverseTransform($.value,$);if(Q instanceof Promise)return Q.then((W)=>_2($,W,U.in,K));return _2($,Q,U.in,K)}}function _2($,U,K,q){if($.issues.length)return $.aborted=!0,$;return K._zod.run({value:U,issues:$.issues},q)}var V5=D("$ZodReadonly",($,U)=>{h.init($,U),r($._zod,"propValues",()=>U.innerType._zod.propValues),r($._zod,"values",()=>U.innerType._zod.values),r($._zod,"optin",()=>U.innerType?._zod?.optin),r($._zod,"optout",()=>U.innerType?._zod?.optout),$._zod.parse=(K,q)=>{if(q.direction==="backward")return U.innerType._zod.run(K,q);let Q=U.innerType._zod.run(K,q);if(Q instanceof Promise)return Q.then(UY);return UY(Q)}});function UY($){return $.value=Object.freeze($.value),$}var M5=D("$ZodTemplateLiteral",($,U)=>{h.init($,U);let K=[];for(let q of U.parts)if(typeof q==="object"&&q!==null){if(!q._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...q._zod.traits].shift()}`);let Q=q._zod.pattern instanceof RegExp?q._zod.pattern.source:q._zod.pattern;if(!Q)throw Error(`Invalid template literal part: ${q._zod.traits}`);let W=Q.startsWith("^")?1:0,J=Q.endsWith("$")?Q.length-1:Q.length;K.push(Q.slice(W,J))}else if(q===null||YU.has(typeof q))K.push(o$(`${q}`));else throw Error(`Invalid template literal part: ${q}`);$._zod.pattern=new RegExp(`^${K.join("")}$`),$._zod.parse=(q,Q)=>{if(typeof q.value!=="string")return q.issues.push({input:q.value,inst:$,expected:"string",code:"invalid_type"}),q;if($._zod.pattern.lastIndex=0,!$._zod.pattern.test(q.value))return q.issues.push({input:q.value,inst:$,code:"invalid_format",format:U.format??"template_literal",pattern:$._zod.pattern.source}),q;return q}}),D5=D("$ZodFunction",($,U)=>{return h.init($,U),$._def=U,$._zod.def=U,$.implement=(K)=>{if(typeof K!=="function")throw Error("implement() must be called with a function");return function(...q){let Q=$._def.input?K2($._def.input,q):q,W=Reflect.apply(K,this,Q);if($._def.output)return K2($._def.output,W);return W}},$.implementAsync=(K)=>{if(typeof K!=="function")throw Error("implementAsync() must be called with a function");return async function(...q){let Q=$._def.input?await q2($._def.input,q):q,W=await Reflect.apply(K,this,Q);if($._def.output)return await q2($._def.output,W);return W}},$._zod.parse=(K,q)=>{if(typeof K.value!=="function")return K.issues.push({code:"invalid_type",expected:"function",input:K.value,inst:$}),K;if($._def.output&&$._def.output._zod.def.type==="promise")K.value=$.implementAsync(K.value);else K.value=$.implement(K.value);return K},$.input=(...K)=>{let q=$.constructor;if(Array.isArray(K[0]))return new q({type:"function",input:new w2({type:"tuple",items:K[0],rest:K[1]}),output:$._def.output});return new q({type:"function",input:K[0],output:$._def.output})},$.output=(K)=>{return new $.constructor({type:"function",input:$._def.input,output:K})},$}),P5=D("$ZodPromise",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{return Promise.resolve(K.value).then((Q)=>U.innerType._zod.run({value:Q,issues:[]},q))}}),N5=D("$ZodLazy",($,U)=>{h.init($,U),r($._zod,"innerType",()=>U.getter()),r($._zod,"pattern",()=>$._zod.innerType?._zod?.pattern),r($._zod,"propValues",()=>$._zod.innerType?._zod?.propValues),r($._zod,"optin",()=>$._zod.innerType?._zod?.optin??void 0),r($._zod,"optout",()=>$._zod.innerType?._zod?.optout??void 0),$._zod.parse=(K,q)=>{return $._zod.innerType._zod.run(K,q)}}),L5=D("$ZodCustom",($,U)=>{$$.init($,U),h.init($,U),$._zod.parse=(K,q)=>{return K},$._zod.check=(K)=>{let q=K.value,Q=U.fn(q);if(Q instanceof Promise)return Q.then((W)=>QY(W,K,q,$));QY(Q,K,q,$);return}});function QY($,U,K,q){if(!$){let Q={code:"custom",input:K,inst:q,path:[...q._zod.def.path??[]],continue:!q._zod.def.abort};if(q._zod.def.params)Q.params=q._zod.def.params;U.issues.push(m4(Q))}}var Q0={};L1(Q0,{zhTW:()=>H7,zhCN:()=>Y7,yo:()=>X7,vi:()=>j7,uz:()=>G7,ur:()=>J7,uk:()=>U0,ua:()=>W7,tr:()=>q7,th:()=>K7,ta:()=>Q7,sv:()=>U7,sl:()=>$7,ru:()=>e5,pt:()=>s5,ps:()=>t5,pl:()=>a5,ota:()=>p5,no:()=>n5,nl:()=>o5,ms:()=>d5,mk:()=>i5,lt:()=>r5,ko:()=>l5,km:()=>e6,kh:()=>c5,ka:()=>h5,ja:()=>m5,it:()=>f5,is:()=>u5,id:()=>g5,hy:()=>y5,hu:()=>E5,he:()=>C5,frCA:()=>S5,fr:()=>T5,fi:()=>O5,fa:()=>b5,es:()=>z5,eo:()=>R5,en:()=>s6,de:()=>k5,da:()=>v5,cs:()=>A5,ca:()=>w5,bg:()=>x5,be:()=>F5,az:()=>I5,ar:()=>_5});var pL=()=>{let $={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function U(Q){return $[Q]??null}let K={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"},q={nan:"NaN"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`مدخلات غير مقبولة: يفترض إدخال instanceof ${Q.expected}، ولكن تم إدخال ${j}`;return`مدخلات غير مقبولة: يفترض إدخال ${W}، ولكن تم إدخال ${j}`}case"invalid_value":if(Q.values.length===1)return`مدخلات غير مقبولة: يفترض إدخال ${v(Q.values[0])}`;return`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return` أكبر من اللازم: يفترض أن تكون ${Q.origin??"القيمة"} ${W} ${Q.maximum.toString()} ${J.unit??"عنصر"}`;return`أكبر من اللازم: يفترض أن تكون ${Q.origin??"القيمة"} ${W} ${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`أصغر من اللازم: يفترض لـ ${Q.origin} أن يكون ${W} ${Q.minimum.toString()} ${J.unit}`;return`أصغر من اللازم: يفترض لـ ${Q.origin} أن يكون ${W} ${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`نَص غير مقبول: يجب أن يبدأ بـ "${Q.prefix}"`;if(W.format==="ends_with")return`نَص غير مقبول: يجب أن ينتهي بـ "${W.suffix}"`;if(W.format==="includes")return`نَص غير مقبول: يجب أن يتضمَّن "${W.includes}"`;if(W.format==="regex")return`نَص غير مقبول: يجب أن يطابق النمط ${W.pattern}`;return`${K[W.format]??Q.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${Q.divisor}`;case"unrecognized_keys":return`معرف${Q.keys.length>1?"ات":""} غريب${Q.keys.length>1?"ة":""}: ${_(Q.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${Q.origin}`;case"invalid_union":return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${Q.origin}`;default:return"مدخل غير مقبول"}}};function _5(){return{localeError:pL()}}var tL=()=>{let $={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}};function U(Q){return $[Q]??null}let K={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},q={nan:"NaN"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Yanlış dəyər: gözlənilən instanceof ${Q.expected}, daxil olan ${j}`;return`Yanlış dəyər: gözlənilən ${W}, daxil olan ${j}`}case"invalid_value":if(Q.values.length===1)return`Yanlış dəyər: gözlənilən ${v(Q.values[0])}`;return`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Çox böyük: gözlənilən ${Q.origin??"dəyər"} ${W}${Q.maximum.toString()} ${J.unit??"element"}`;return`Çox böyük: gözlənilən ${Q.origin??"dəyər"} ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Çox kiçik: gözlənilən ${Q.origin} ${W}${Q.minimum.toString()} ${J.unit}`;return`Çox kiçik: gözlənilən ${Q.origin} ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Yanlış mətn: "${W.prefix}" ilə başlamalıdır`;if(W.format==="ends_with")return`Yanlış mətn: "${W.suffix}" ilə bitməlidir`;if(W.format==="includes")return`Yanlış mətn: "${W.includes}" daxil olmalıdır`;if(W.format==="regex")return`Yanlış mətn: ${W.pattern} şablonuna uyğun olmalıdır`;return`Yanlış ${K[W.format]??Q.format}`}case"not_multiple_of":return`Yanlış ədəd: ${Q.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${Q.keys.length>1?"lar":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`${Q.origin} daxilində yanlış açar`;case"invalid_union":return"Yanlış dəyər";case"invalid_element":return`${Q.origin} daxilində yanlış dəyər`;default:return"Yanlış dəyər"}}};function I5(){return{localeError:tL()}}function jY($,U,K,q){let Q=Math.abs($),W=Q%10,J=Q%100;if(J>=11&&J<=19)return q;if(W===1)return U;if(W>=2&&W<=4)return K;return q}var aL=()=>{let $={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function U(Q){return $[Q]??null}let K={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"},q={nan:"NaN",number:"лік",array:"масіў"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Няправільны ўвод: чакаўся instanceof ${Q.expected}, атрымана ${j}`;return`Няправільны ўвод: чакаўся ${W}, атрымана ${j}`}case"invalid_value":if(Q.values.length===1)return`Няправільны ўвод: чакалася ${v(Q.values[0])}`;return`Няправільны варыянт: чакаўся адзін з ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J){let j=Number(Q.maximum),Y=jY(j,J.unit.one,J.unit.few,J.unit.many);return`Занадта вялікі: чакалася, што ${Q.origin??"значэнне"} павінна ${J.verb} ${W}${Q.maximum.toString()} ${Y}`}return`Занадта вялікі: чакалася, што ${Q.origin??"значэнне"} павінна быць ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J){let j=Number(Q.minimum),Y=jY(j,J.unit.one,J.unit.few,J.unit.many);return`Занадта малы: чакалася, што ${Q.origin} павінна ${J.verb} ${W}${Q.minimum.toString()} ${Y}`}return`Занадта малы: чакалася, што ${Q.origin} павінна быць ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Няправільны радок: павінен пачынацца з "${W.prefix}"`;if(W.format==="ends_with")return`Няправільны радок: павінен заканчвацца на "${W.suffix}"`;if(W.format==="includes")return`Няправільны радок: павінен змяшчаць "${W.includes}"`;if(W.format==="regex")return`Няправільны радок: павінен адпавядаць шаблону ${W.pattern}`;return`Няправільны ${K[W.format]??Q.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${Q.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${Q.keys.length>1?"ключы":"ключ"}: ${_(Q.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${Q.origin}`;case"invalid_union":return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${Q.origin}`;default:return"Няправільны ўвод"}}};function F5(){return{localeError:aL()}}var sL=()=>{let $={string:{unit:"символа",verb:"да съдържа"},file:{unit:"байта",verb:"да съдържа"},array:{unit:"елемента",verb:"да съдържа"},set:{unit:"елемента",verb:"да съдържа"}};function U(Q){return $[Q]??null}let K={regex:"вход",email:"имейл адрес",url:"URL",emoji:"емоджи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO време",date:"ISO дата",time:"ISO време",duration:"ISO продължителност",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"base64-кодиран низ",base64url:"base64url-кодиран низ",json_string:"JSON низ",e164:"E.164 номер",jwt:"JWT",template_literal:"вход"},q={nan:"NaN",number:"число",array:"масив"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Невалиден вход: очакван instanceof ${Q.expected}, получен ${j}`;return`Невалиден вход: очакван ${W}, получен ${j}`}case"invalid_value":if(Q.values.length===1)return`Невалиден вход: очакван ${v(Q.values[0])}`;return`Невалидна опция: очаквано едно от ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Твърде голямо: очаква се ${Q.origin??"стойност"} да съдържа ${W}${Q.maximum.toString()} ${J.unit??"елемента"}`;return`Твърде голямо: очаква се ${Q.origin??"стойност"} да бъде ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Твърде малко: очаква се ${Q.origin} да съдържа ${W}${Q.minimum.toString()} ${J.unit}`;return`Твърде малко: очаква се ${Q.origin} да бъде ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Невалиден низ: трябва да започва с "${W.prefix}"`;if(W.format==="ends_with")return`Невалиден низ: трябва да завършва с "${W.suffix}"`;if(W.format==="includes")return`Невалиден низ: трябва да включва "${W.includes}"`;if(W.format==="regex")return`Невалиден низ: трябва да съвпада с ${W.pattern}`;let J="Невалиден";if(W.format==="emoji")J="Невалидно";if(W.format==="datetime")J="Невалидно";if(W.format==="date")J="Невалидна";if(W.format==="time")J="Невалидно";if(W.format==="duration")J="Невалидна";return`${J} ${K[W.format]??Q.format}`}case"not_multiple_of":return`Невалидно число: трябва да бъде кратно на ${Q.divisor}`;case"unrecognized_keys":return`Неразпознат${Q.keys.length>1?"и":""} ключ${Q.keys.length>1?"ове":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Невалиден ключ в ${Q.origin}`;case"invalid_union":return"Невалиден вход";case"invalid_element":return`Невалидна стойност в ${Q.origin}`;default:return"Невалиден вход"}}};function x5(){return{localeError:sL()}}var eL=()=>{let $={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function U(Q){return $[Q]??null}let K={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},q={nan:"NaN"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Tipus invàlid: s'esperava instanceof ${Q.expected}, s'ha rebut ${j}`;return`Tipus invàlid: s'esperava ${W}, s'ha rebut ${j}`}case"invalid_value":if(Q.values.length===1)return`Valor invàlid: s'esperava ${v(Q.values[0])}`;return`Opció invàlida: s'esperava una de ${_(Q.values," o ")}`;case"too_big":{let W=Q.inclusive?"com a màxim":"menys de",J=U(Q.origin);if(J)return`Massa gran: s'esperava que ${Q.origin??"el valor"} contingués ${W} ${Q.maximum.toString()} ${J.unit??"elements"}`;return`Massa gran: s'esperava que ${Q.origin??"el valor"} fos ${W} ${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?"com a mínim":"més de",J=U(Q.origin);if(J)return`Massa petit: s'esperava que ${Q.origin} contingués ${W} ${Q.minimum.toString()} ${J.unit}`;return`Massa petit: s'esperava que ${Q.origin} fos ${W} ${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Format invàlid: ha de començar amb "${W.prefix}"`;if(W.format==="ends_with")return`Format invàlid: ha d'acabar amb "${W.suffix}"`;if(W.format==="includes")return`Format invàlid: ha d'incloure "${W.includes}"`;if(W.format==="regex")return`Format invàlid: ha de coincidir amb el patró ${W.pattern}`;return`Format invàlid per a ${K[W.format]??Q.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${Q.divisor}`;case"unrecognized_keys":return`Clau${Q.keys.length>1?"s":""} no reconeguda${Q.keys.length>1?"s":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${Q.origin}`;case"invalid_union":return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${Q.origin}`;default:return"Entrada invàlida"}}};function w5(){return{localeError:eL()}}var $_=()=>{let $={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}};function U(Q){return $[Q]??null}let K={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"},q={nan:"NaN",number:"číslo",string:"řetězec",function:"funkce",array:"pole"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Neplatný vstup: očekáváno instanceof ${Q.expected}, obdrženo ${j}`;return`Neplatný vstup: očekáváno ${W}, obdrženo ${j}`}case"invalid_value":if(Q.values.length===1)return`Neplatný vstup: očekáváno ${v(Q.values[0])}`;return`Neplatná možnost: očekávána jedna z hodnot ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Hodnota je příliš velká: ${Q.origin??"hodnota"} musí mít ${W}${Q.maximum.toString()} ${J.unit??"prvků"}`;return`Hodnota je příliš velká: ${Q.origin??"hodnota"} musí být ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Hodnota je příliš malá: ${Q.origin??"hodnota"} musí mít ${W}${Q.minimum.toString()} ${J.unit??"prvků"}`;return`Hodnota je příliš malá: ${Q.origin??"hodnota"} musí být ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Neplatný řetězec: musí začínat na "${W.prefix}"`;if(W.format==="ends_with")return`Neplatný řetězec: musí končit na "${W.suffix}"`;if(W.format==="includes")return`Neplatný řetězec: musí obsahovat "${W.includes}"`;if(W.format==="regex")return`Neplatný řetězec: musí odpovídat vzoru ${W.pattern}`;return`Neplatný formát ${K[W.format]??Q.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${Q.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${_(Q.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${Q.origin}`;case"invalid_union":return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${Q.origin}`;default:return"Neplatný vstup"}}};function A5(){return{localeError:$_()}}var U_=()=>{let $={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function U(Q){return $[Q]??null}let K={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},q={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Ugyldigt input: forventede instanceof ${Q.expected}, fik ${j}`;return`Ugyldigt input: forventede ${W}, fik ${j}`}case"invalid_value":if(Q.values.length===1)return`Ugyldig værdi: forventede ${v(Q.values[0])}`;return`Ugyldigt valg: forventede en af følgende ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin),j=q[Q.origin]??Q.origin;if(J)return`For stor: forventede ${j??"value"} ${J.verb} ${W} ${Q.maximum.toString()} ${J.unit??"elementer"}`;return`For stor: forventede ${j??"value"} havde ${W} ${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin),j=q[Q.origin]??Q.origin;if(J)return`For lille: forventede ${j} ${J.verb} ${W} ${Q.minimum.toString()} ${J.unit}`;return`For lille: forventede ${j} havde ${W} ${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Ugyldig streng: skal starte med "${W.prefix}"`;if(W.format==="ends_with")return`Ugyldig streng: skal ende med "${W.suffix}"`;if(W.format==="includes")return`Ugyldig streng: skal indeholde "${W.includes}"`;if(W.format==="regex")return`Ugyldig streng: skal matche mønsteret ${W.pattern}`;return`Ugyldig ${K[W.format]??Q.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${Q.divisor}`;case"unrecognized_keys":return`${Q.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${_(Q.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${Q.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${Q.origin}`;default:return"Ugyldigt input"}}};function v5(){return{localeError:U_()}}var Q_=()=>{let $={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function U(Q){return $[Q]??null}let K={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},q={nan:"NaN",number:"Zahl",array:"Array"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Ungültige Eingabe: erwartet instanceof ${Q.expected}, erhalten ${j}`;return`Ungültige Eingabe: erwartet ${W}, erhalten ${j}`}case"invalid_value":if(Q.values.length===1)return`Ungültige Eingabe: erwartet ${v(Q.values[0])}`;return`Ungültige Option: erwartet eine von ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Zu groß: erwartet, dass ${Q.origin??"Wert"} ${W}${Q.maximum.toString()} ${J.unit??"Elemente"} hat`;return`Zu groß: erwartet, dass ${Q.origin??"Wert"} ${W}${Q.maximum.toString()} ist`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Zu klein: erwartet, dass ${Q.origin} ${W}${Q.minimum.toString()} ${J.unit} hat`;return`Zu klein: erwartet, dass ${Q.origin} ${W}${Q.minimum.toString()} ist`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Ungültiger String: muss mit "${W.prefix}" beginnen`;if(W.format==="ends_with")return`Ungültiger String: muss mit "${W.suffix}" enden`;if(W.format==="includes")return`Ungültiger String: muss "${W.includes}" enthalten`;if(W.format==="regex")return`Ungültiger String: muss dem Muster ${W.pattern} entsprechen`;return`Ungültig: ${K[W.format]??Q.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${Q.divisor} sein`;case"unrecognized_keys":return`${Q.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${_(Q.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${Q.origin}`;case"invalid_union":return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${Q.origin}`;default:return"Ungültige Eingabe"}}};function k5(){return{localeError:Q_()}}var K_=()=>{let $={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function U(Q){return $[Q]??null}let K={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},q={nan:"NaN"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;return`Invalid input: expected ${W}, received ${j}`}case"invalid_value":if(Q.values.length===1)return`Invalid input: expected ${v(Q.values[0])}`;return`Invalid option: expected one of ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Too big: expected ${Q.origin??"value"} to have ${W}${Q.maximum.toString()} ${J.unit??"elements"}`;return`Too big: expected ${Q.origin??"value"} to be ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Too small: expected ${Q.origin} to have ${W}${Q.minimum.toString()} ${J.unit}`;return`Too small: expected ${Q.origin} to be ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Invalid string: must start with "${W.prefix}"`;if(W.format==="ends_with")return`Invalid string: must end with "${W.suffix}"`;if(W.format==="includes")return`Invalid string: must include "${W.includes}"`;if(W.format==="regex")return`Invalid string: must match pattern ${W.pattern}`;return`Invalid ${K[W.format]??Q.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${Q.divisor}`;case"unrecognized_keys":return`Unrecognized key${Q.keys.length>1?"s":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Invalid key in ${Q.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${Q.origin}`;default:return"Invalid input"}}};function s6(){return{localeError:K_()}}var q_=()=>{let $={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function U(Q){return $[Q]??null}let K={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},q={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Nevalida enigo: atendiĝis instanceof ${Q.expected}, riceviĝis ${j}`;return`Nevalida enigo: atendiĝis ${W}, riceviĝis ${j}`}case"invalid_value":if(Q.values.length===1)return`Nevalida enigo: atendiĝis ${v(Q.values[0])}`;return`Nevalida opcio: atendiĝis unu el ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Tro granda: atendiĝis ke ${Q.origin??"valoro"} havu ${W}${Q.maximum.toString()} ${J.unit??"elementojn"}`;return`Tro granda: atendiĝis ke ${Q.origin??"valoro"} havu ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Tro malgranda: atendiĝis ke ${Q.origin} havu ${W}${Q.minimum.toString()} ${J.unit}`;return`Tro malgranda: atendiĝis ke ${Q.origin} estu ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Nevalida karaktraro: devas komenciĝi per "${W.prefix}"`;if(W.format==="ends_with")return`Nevalida karaktraro: devas finiĝi per "${W.suffix}"`;if(W.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${W.includes}"`;if(W.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${W.pattern}`;return`Nevalida ${K[W.format]??Q.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${Q.divisor}`;case"unrecognized_keys":return`Nekonata${Q.keys.length>1?"j":""} ŝlosilo${Q.keys.length>1?"j":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${Q.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${Q.origin}`;default:return"Nevalida enigo"}}};function R5(){return{localeError:q_()}}var W_=()=>{let $={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function U(Q){return $[Q]??null}let K={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},q={nan:"NaN",string:"texto",number:"número",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"número grande",symbol:"símbolo",undefined:"indefinido",null:"nulo",function:"función",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeración",union:"unión",literal:"literal",promise:"promesa",void:"vacío",never:"nunca",unknown:"desconocido",any:"cualquiera"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Entrada inválida: se esperaba instanceof ${Q.expected}, recibido ${j}`;return`Entrada inválida: se esperaba ${W}, recibido ${j}`}case"invalid_value":if(Q.values.length===1)return`Entrada inválida: se esperaba ${v(Q.values[0])}`;return`Opción inválida: se esperaba una de ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin),j=q[Q.origin]??Q.origin;if(J)return`Demasiado grande: se esperaba que ${j??"valor"} tuviera ${W}${Q.maximum.toString()} ${J.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${j??"valor"} fuera ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin),j=q[Q.origin]??Q.origin;if(J)return`Demasiado pequeño: se esperaba que ${j} tuviera ${W}${Q.minimum.toString()} ${J.unit}`;return`Demasiado pequeño: se esperaba que ${j} fuera ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Cadena inválida: debe comenzar con "${W.prefix}"`;if(W.format==="ends_with")return`Cadena inválida: debe terminar en "${W.suffix}"`;if(W.format==="includes")return`Cadena inválida: debe incluir "${W.includes}"`;if(W.format==="regex")return`Cadena inválida: debe coincidir con el patrón ${W.pattern}`;return`Inválido ${K[W.format]??Q.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${Q.divisor}`;case"unrecognized_keys":return`Llave${Q.keys.length>1?"s":""} desconocida${Q.keys.length>1?"s":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Llave inválida en ${q[Q.origin]??Q.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido en ${q[Q.origin]??Q.origin}`;default:return"Entrada inválida"}}};function z5(){return{localeError:W_()}}var J_=()=>{let $={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function U(Q){return $[Q]??null}let K={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"},q={nan:"NaN",number:"عدد",array:"آرایه"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`ورودی نامعتبر: میبایست instanceof ${Q.expected} میبود، ${j} دریافت شد`;return`ورودی نامعتبر: میبایست ${W} میبود، ${j} دریافت شد`}case"invalid_value":if(Q.values.length===1)return`ورودی نامعتبر: میبایست ${v(Q.values[0])} میبود`;return`گزینه نامعتبر: میبایست یکی از ${_(Q.values,"|")} میبود`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`خیلی بزرگ: ${Q.origin??"مقدار"} باید ${W}${Q.maximum.toString()} ${J.unit??"عنصر"} باشد`;return`خیلی بزرگ: ${Q.origin??"مقدار"} باید ${W}${Q.maximum.toString()} باشد`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`خیلی کوچک: ${Q.origin} باید ${W}${Q.minimum.toString()} ${J.unit} باشد`;return`خیلی کوچک: ${Q.origin} باید ${W}${Q.minimum.toString()} باشد`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`رشته نامعتبر: باید با "${W.prefix}" شروع شود`;if(W.format==="ends_with")return`رشته نامعتبر: باید با "${W.suffix}" تمام شود`;if(W.format==="includes")return`رشته نامعتبر: باید شامل "${W.includes}" باشد`;if(W.format==="regex")return`رشته نامعتبر: باید با الگوی ${W.pattern} مطابقت داشته باشد`;return`${K[W.format]??Q.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${Q.divisor} باشد`;case"unrecognized_keys":return`کلید${Q.keys.length>1?"های":""} ناشناس: ${_(Q.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${Q.origin}`;case"invalid_union":return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${Q.origin}`;default:return"ورودی نامعتبر"}}};function b5(){return{localeError:J_()}}var G_=()=>{let $={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function U(Q){return $[Q]??null}let K={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},q={nan:"NaN"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Virheellinen tyyppi: odotettiin instanceof ${Q.expected}, oli ${j}`;return`Virheellinen tyyppi: odotettiin ${W}, oli ${j}`}case"invalid_value":if(Q.values.length===1)return`Virheellinen syöte: täytyy olla ${v(Q.values[0])}`;return`Virheellinen valinta: täytyy olla yksi seuraavista: ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Liian suuri: ${J.subject} täytyy olla ${W}${Q.maximum.toString()} ${J.unit}`.trim();return`Liian suuri: arvon täytyy olla ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Liian pieni: ${J.subject} täytyy olla ${W}${Q.minimum.toString()} ${J.unit}`.trim();return`Liian pieni: arvon täytyy olla ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Virheellinen syöte: täytyy alkaa "${W.prefix}"`;if(W.format==="ends_with")return`Virheellinen syöte: täytyy loppua "${W.suffix}"`;if(W.format==="includes")return`Virheellinen syöte: täytyy sisältää "${W.includes}"`;if(W.format==="regex")return`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${W.pattern}`;return`Virheellinen ${K[W.format]??Q.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${Q.divisor} monikerta`;case"unrecognized_keys":return`${Q.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${_(Q.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};function O5(){return{localeError:G_()}}var j_=()=>{let $={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function U(Q){return $[Q]??null}let K={regex:"entrée",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},q={nan:"NaN",number:"nombre",array:"tableau"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Entrée invalide : instanceof ${Q.expected} attendu, ${j} reçu`;return`Entrée invalide : ${W} attendu, ${j} reçu`}case"invalid_value":if(Q.values.length===1)return`Entrée invalide : ${v(Q.values[0])} attendu`;return`Option invalide : une valeur parmi ${_(Q.values,"|")} attendue`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Trop grand : ${Q.origin??"valeur"} doit ${J.verb} ${W}${Q.maximum.toString()} ${J.unit??"élément(s)"}`;return`Trop grand : ${Q.origin??"valeur"} doit être ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Trop petit : ${Q.origin} doit ${J.verb} ${W}${Q.minimum.toString()} ${J.unit}`;return`Trop petit : ${Q.origin} doit être ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Chaîne invalide : doit commencer par "${W.prefix}"`;if(W.format==="ends_with")return`Chaîne invalide : doit se terminer par "${W.suffix}"`;if(W.format==="includes")return`Chaîne invalide : doit inclure "${W.includes}"`;if(W.format==="regex")return`Chaîne invalide : doit correspondre au modèle ${W.pattern}`;return`${K[W.format]??Q.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${Q.divisor}`;case"unrecognized_keys":return`Clé${Q.keys.length>1?"s":""} non reconnue${Q.keys.length>1?"s":""} : ${_(Q.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${Q.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${Q.origin}`;default:return"Entrée invalide"}}};function T5(){return{localeError:j_()}}var Y_=()=>{let $={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function U(Q){return $[Q]??null}let K={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},q={nan:"NaN"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Entrée invalide : attendu instanceof ${Q.expected}, reçu ${j}`;return`Entrée invalide : attendu ${W}, reçu ${j}`}case"invalid_value":if(Q.values.length===1)return`Entrée invalide : attendu ${v(Q.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"≤":"<",J=U(Q.origin);if(J)return`Trop grand : attendu que ${Q.origin??"la valeur"} ait ${W}${Q.maximum.toString()} ${J.unit}`;return`Trop grand : attendu que ${Q.origin??"la valeur"} soit ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?"≥":">",J=U(Q.origin);if(J)return`Trop petit : attendu que ${Q.origin} ait ${W}${Q.minimum.toString()} ${J.unit}`;return`Trop petit : attendu que ${Q.origin} soit ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Chaîne invalide : doit commencer par "${W.prefix}"`;if(W.format==="ends_with")return`Chaîne invalide : doit se terminer par "${W.suffix}"`;if(W.format==="includes")return`Chaîne invalide : doit inclure "${W.includes}"`;if(W.format==="regex")return`Chaîne invalide : doit correspondre au motif ${W.pattern}`;return`${K[W.format]??Q.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${Q.divisor}`;case"unrecognized_keys":return`Clé${Q.keys.length>1?"s":""} non reconnue${Q.keys.length>1?"s":""} : ${_(Q.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${Q.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${Q.origin}`;default:return"Entrée invalide"}}};function S5(){return{localeError:Y_()}}var H_=()=>{let $={string:{label:"מחרוזת",gender:"f"},number:{label:"מספר",gender:"m"},boolean:{label:"ערך בוליאני",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"תאריך",gender:"m"},array:{label:"מערך",gender:"m"},object:{label:"אובייקט",gender:"m"},null:{label:"ערך ריק (null)",gender:"m"},undefined:{label:"ערך לא מוגדר (undefined)",gender:"m"},symbol:{label:"סימבול (Symbol)",gender:"m"},function:{label:"פונקציה",gender:"f"},map:{label:"מפה (Map)",gender:"f"},set:{label:"קבוצה (Set)",gender:"f"},file:{label:"קובץ",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"ערך לא ידוע",gender:"m"},value:{label:"ערך",gender:"m"}},U={string:{unit:"תווים",shortLabel:"קצר",longLabel:"ארוך"},file:{unit:"בייטים",shortLabel:"קטן",longLabel:"גדול"},array:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},set:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},number:{unit:"",shortLabel:"קטן",longLabel:"גדול"}},K=(H)=>H?$[H]:void 0,q=(H)=>{let Z=K(H);if(Z)return Z.label;return H??$.unknown.label},Q=(H)=>`ה${q(H)}`,W=(H)=>{return(K(H)?.gender??"m")==="f"?"צריכה להיות":"צריך להיות"},J=(H)=>{if(!H)return null;return U[H]??null},j={regex:{label:"קלט",gender:"m"},email:{label:"כתובת אימייל",gender:"f"},url:{label:"כתובת רשת",gender:"f"},emoji:{label:"אימוג'י",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"תאריך וזמן ISO",gender:"m"},date:{label:"תאריך ISO",gender:"m"},time:{label:"זמן ISO",gender:"m"},duration:{label:"משך זמן ISO",gender:"m"},ipv4:{label:"כתובת IPv4",gender:"f"},ipv6:{label:"כתובת IPv6",gender:"f"},cidrv4:{label:"טווח IPv4",gender:"m"},cidrv6:{label:"טווח IPv6",gender:"m"},base64:{label:"מחרוזת בבסיס 64",gender:"f"},base64url:{label:"מחרוזת בבסיס 64 לכתובות רשת",gender:"f"},json_string:{label:"מחרוזת JSON",gender:"f"},e164:{label:"מספר E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"קלט",gender:"m"},includes:{label:"קלט",gender:"m"},lowercase:{label:"קלט",gender:"m"},starts_with:{label:"קלט",gender:"m"},uppercase:{label:"קלט",gender:"m"}},Y={nan:"NaN"};return(H)=>{switch(H.code){case"invalid_type":{let Z=H.expected,B=Y[Z??""]??q(Z),M=k(H.input),I=Y[M]??$[M]?.label??M;if(/^[A-Z]/.test(H.expected))return`קלט לא תקין: צריך להיות instanceof ${H.expected}, התקבל ${I}`;return`קלט לא תקין: צריך להיות ${B}, התקבל ${I}`}case"invalid_value":{if(H.values.length===1)return`ערך לא תקין: הערך חייב להיות ${v(H.values[0])}`;let Z=H.values.map((I)=>v(I));if(H.values.length===2)return`ערך לא תקין: האפשרויות המתאימות הן ${Z[0]} או ${Z[1]}`;let B=Z[Z.length-1];return`ערך לא תקין: האפשרויות המתאימות הן ${Z.slice(0,-1).join(", ")} או ${B}`}case"too_big":{let Z=J(H.origin),B=Q(H.origin??"value");if(H.origin==="string")return`${Z?.longLabel??"ארוך"} מדי: ${B} צריכה להכיל ${H.maximum.toString()} ${Z?.unit??""} ${H.inclusive?"או פחות":"לכל היותר"}`.trim();if(H.origin==="number"){let E=H.inclusive?`קטן או שווה ל-${H.maximum}`:`קטן מ-${H.maximum}`;return`גדול מדי: ${B} צריך להיות ${E}`}if(H.origin==="array"||H.origin==="set"){let E=H.origin==="set"?"צריכה":"צריך",u=H.inclusive?`${H.maximum} ${Z?.unit??""} או פחות`:`פחות מ-${H.maximum} ${Z?.unit??""}`;return`גדול מדי: ${B} ${E} להכיל ${u}`.trim()}let M=H.inclusive?"<=":"<",I=W(H.origin??"value");if(Z?.unit)return`${Z.longLabel} מדי: ${B} ${I} ${M}${H.maximum.toString()} ${Z.unit}`;return`${Z?.longLabel??"גדול"} מדי: ${B} ${I} ${M}${H.maximum.toString()}`}case"too_small":{let Z=J(H.origin),B=Q(H.origin??"value");if(H.origin==="string")return`${Z?.shortLabel??"קצר"} מדי: ${B} צריכה להכיל ${H.minimum.toString()} ${Z?.unit??""} ${H.inclusive?"או יותר":"לפחות"}`.trim();if(H.origin==="number"){let E=H.inclusive?`גדול או שווה ל-${H.minimum}`:`גדול מ-${H.minimum}`;return`קטן מדי: ${B} צריך להיות ${E}`}if(H.origin==="array"||H.origin==="set"){let E=H.origin==="set"?"צריכה":"צריך";if(H.minimum===1&&H.inclusive){let U$=H.origin==="set"?"לפחות פריט אחד":"לפחות פריט אחד";return`קטן מדי: ${B} ${E} להכיל ${U$}`}let u=H.inclusive?`${H.minimum} ${Z?.unit??""} או יותר`:`יותר מ-${H.minimum} ${Z?.unit??""}`;return`קטן מדי: ${B} ${E} להכיל ${u}`.trim()}let M=H.inclusive?">=":">",I=W(H.origin??"value");if(Z?.unit)return`${Z.shortLabel} מדי: ${B} ${I} ${M}${H.minimum.toString()} ${Z.unit}`;return`${Z?.shortLabel??"קטן"} מדי: ${B} ${I} ${M}${H.minimum.toString()}`}case"invalid_format":{let Z=H;if(Z.format==="starts_with")return`המחרוזת חייבת להתחיל ב "${Z.prefix}"`;if(Z.format==="ends_with")return`המחרוזת חייבת להסתיים ב "${Z.suffix}"`;if(Z.format==="includes")return`המחרוזת חייבת לכלול "${Z.includes}"`;if(Z.format==="regex")return`המחרוזת חייבת להתאים לתבנית ${Z.pattern}`;let B=j[Z.format],M=B?.label??Z.format,E=(B?.gender??"m")==="f"?"תקינה":"תקין";return`${M} לא ${E}`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${H.divisor}`;case"unrecognized_keys":return`מפתח${H.keys.length>1?"ות":""} לא מזוה${H.keys.length>1?"ים":"ה"}: ${_(H.keys,", ")}`;case"invalid_key":return"שדה לא תקין באובייקט";case"invalid_union":return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${Q(H.origin??"array")}`;default:return"קלט לא תקין"}}};function C5(){return{localeError:H_()}}var X_=()=>{let $={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function U(Q){return $[Q]??null}let K={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"},q={nan:"NaN",number:"szám",array:"tömb"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Érvénytelen bemenet: a várt érték instanceof ${Q.expected}, a kapott érték ${j}`;return`Érvénytelen bemenet: a várt érték ${W}, a kapott érték ${j}`}case"invalid_value":if(Q.values.length===1)return`Érvénytelen bemenet: a várt érték ${v(Q.values[0])}`;return`Érvénytelen opció: valamelyik érték várt ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Túl nagy: ${Q.origin??"érték"} mérete túl nagy ${W}${Q.maximum.toString()} ${J.unit??"elem"}`;return`Túl nagy: a bemeneti érték ${Q.origin??"érték"} túl nagy: ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Túl kicsi: a bemeneti érték ${Q.origin} mérete túl kicsi ${W}${Q.minimum.toString()} ${J.unit}`;return`Túl kicsi: a bemeneti érték ${Q.origin} túl kicsi ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Érvénytelen string: "${W.prefix}" értékkel kell kezdődnie`;if(W.format==="ends_with")return`Érvénytelen string: "${W.suffix}" értékkel kell végződnie`;if(W.format==="includes")return`Érvénytelen string: "${W.includes}" értéket kell tartalmaznia`;if(W.format==="regex")return`Érvénytelen string: ${W.pattern} mintának kell megfelelnie`;return`Érvénytelen ${K[W.format]??Q.format}`}case"not_multiple_of":return`Érvénytelen szám: ${Q.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${Q.keys.length>1?"s":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${Q.origin}`;case"invalid_union":return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${Q.origin}`;default:return"Érvénytelen bemenet"}}};function E5(){return{localeError:X_()}}function YY($,U,K){return Math.abs($)===1?U:K}function d4($){if(!$)return"";let U=["ա","ե","ը","ի","ո","ու","օ"],K=$[$.length-1];return $+(U.includes(K)?"ն":"ը")}var Z_=()=>{let $={string:{unit:{one:"նշան",many:"նշաններ"},verb:"ունենալ"},file:{unit:{one:"բայթ",many:"բայթեր"},verb:"ունենալ"},array:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"},set:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"}};function U(Q){return $[Q]??null}let K={regex:"մուտք",email:"էլ. հասցե",url:"URL",emoji:"էմոջի",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ամսաթիվ և ժամ",date:"ISO ամսաթիվ",time:"ISO ժամ",duration:"ISO տևողություն",ipv4:"IPv4 հասցե",ipv6:"IPv6 հասցե",cidrv4:"IPv4 միջակայք",cidrv6:"IPv6 միջակայք",base64:"base64 ձևաչափով տող",base64url:"base64url ձևաչափով տող",json_string:"JSON տող",e164:"E.164 համար",jwt:"JWT",template_literal:"մուտք"},q={nan:"NaN",number:"թիվ",array:"զանգված"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Սխալ մուտքագրում․ սպասվում էր instanceof ${Q.expected}, ստացվել է ${j}`;return`Սխալ մուտքագրում․ սպասվում էր ${W}, ստացվել է ${j}`}case"invalid_value":if(Q.values.length===1)return`Սխալ մուտքագրում․ սպասվում էր ${v(Q.values[1])}`;return`Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J){let j=Number(Q.maximum),Y=YY(j,J.unit.one,J.unit.many);return`Չափազանց մեծ արժեք․ սպասվում է, որ ${d4(Q.origin??"արժեք")} կունենա ${W}${Q.maximum.toString()} ${Y}`}return`Չափազանց մեծ արժեք․ սպասվում է, որ ${d4(Q.origin??"արժեք")} լինի ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J){let j=Number(Q.minimum),Y=YY(j,J.unit.one,J.unit.many);return`Չափազանց փոքր արժեք․ սպասվում է, որ ${d4(Q.origin)} կունենա ${W}${Q.minimum.toString()} ${Y}`}return`Չափազանց փոքր արժեք․ սպասվում է, որ ${d4(Q.origin)} լինի ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Սխալ տող․ պետք է սկսվի "${W.prefix}"-ով`;if(W.format==="ends_with")return`Սխալ տող․ պետք է ավարտվի "${W.suffix}"-ով`;if(W.format==="includes")return`Սխալ տող․ պետք է պարունակի "${W.includes}"`;if(W.format==="regex")return`Սխալ տող․ պետք է համապատասխանի ${W.pattern} ձևաչափին`;return`Սխալ ${K[W.format]??Q.format}`}case"not_multiple_of":return`Սխալ թիվ․ պետք է բազմապատիկ լինի ${Q.divisor}-ի`;case"unrecognized_keys":return`Չճանաչված բանալի${Q.keys.length>1?"ներ":""}. ${_(Q.keys,", ")}`;case"invalid_key":return`Սխալ բանալի ${d4(Q.origin)}-ում`;case"invalid_union":return"Սխալ մուտքագրում";case"invalid_element":return`Սխալ արժեք ${d4(Q.origin)}-ում`;default:return"Սխալ մուտքագրում"}}};function y5(){return{localeError:Z_()}}var B_=()=>{let $={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function U(Q){return $[Q]??null}let K={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},q={nan:"NaN"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Input tidak valid: diharapkan instanceof ${Q.expected}, diterima ${j}`;return`Input tidak valid: diharapkan ${W}, diterima ${j}`}case"invalid_value":if(Q.values.length===1)return`Input tidak valid: diharapkan ${v(Q.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Terlalu besar: diharapkan ${Q.origin??"value"} memiliki ${W}${Q.maximum.toString()} ${J.unit??"elemen"}`;return`Terlalu besar: diharapkan ${Q.origin??"value"} menjadi ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Terlalu kecil: diharapkan ${Q.origin} memiliki ${W}${Q.minimum.toString()} ${J.unit}`;return`Terlalu kecil: diharapkan ${Q.origin} menjadi ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`String tidak valid: harus dimulai dengan "${W.prefix}"`;if(W.format==="ends_with")return`String tidak valid: harus berakhir dengan "${W.suffix}"`;if(W.format==="includes")return`String tidak valid: harus menyertakan "${W.includes}"`;if(W.format==="regex")return`String tidak valid: harus sesuai pola ${W.pattern}`;return`${K[W.format]??Q.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${Q.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${Q.keys.length>1?"s":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${Q.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${Q.origin}`;default:return"Input tidak valid"}}};function g5(){return{localeError:B_()}}var V_=()=>{let $={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}};function U(Q){return $[Q]??null}let K={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"},q={nan:"NaN",number:"númer",array:"fylki"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Rangt gildi: Þú slóst inn ${j} þar sem á að vera instanceof ${Q.expected}`;return`Rangt gildi: Þú slóst inn ${j} þar sem á að vera ${W}`}case"invalid_value":if(Q.values.length===1)return`Rangt gildi: gert ráð fyrir ${v(Q.values[0])}`;return`Ógilt val: má vera eitt af eftirfarandi ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Of stórt: gert er ráð fyrir að ${Q.origin??"gildi"} hafi ${W}${Q.maximum.toString()} ${J.unit??"hluti"}`;return`Of stórt: gert er ráð fyrir að ${Q.origin??"gildi"} sé ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Of lítið: gert er ráð fyrir að ${Q.origin} hafi ${W}${Q.minimum.toString()} ${J.unit}`;return`Of lítið: gert er ráð fyrir að ${Q.origin} sé ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Ógildur strengur: verður að byrja á "${W.prefix}"`;if(W.format==="ends_with")return`Ógildur strengur: verður að enda á "${W.suffix}"`;if(W.format==="includes")return`Ógildur strengur: verður að innihalda "${W.includes}"`;if(W.format==="regex")return`Ógildur strengur: verður að fylgja mynstri ${W.pattern}`;return`Rangt ${K[W.format]??Q.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${Q.divisor}`;case"unrecognized_keys":return`Óþekkt ${Q.keys.length>1?"ir lyklar":"ur lykill"}: ${_(Q.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${Q.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${Q.origin}`;default:return"Rangt gildi"}}};function u5(){return{localeError:V_()}}var M_=()=>{let $={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function U(Q){return $[Q]??null}let K={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},q={nan:"NaN",number:"numero",array:"vettore"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Input non valido: atteso instanceof ${Q.expected}, ricevuto ${j}`;return`Input non valido: atteso ${W}, ricevuto ${j}`}case"invalid_value":if(Q.values.length===1)return`Input non valido: atteso ${v(Q.values[0])}`;return`Opzione non valida: atteso uno tra ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Troppo grande: ${Q.origin??"valore"} deve avere ${W}${Q.maximum.toString()} ${J.unit??"elementi"}`;return`Troppo grande: ${Q.origin??"valore"} deve essere ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Troppo piccolo: ${Q.origin} deve avere ${W}${Q.minimum.toString()} ${J.unit}`;return`Troppo piccolo: ${Q.origin} deve essere ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Stringa non valida: deve iniziare con "${W.prefix}"`;if(W.format==="ends_with")return`Stringa non valida: deve terminare con "${W.suffix}"`;if(W.format==="includes")return`Stringa non valida: deve includere "${W.includes}"`;if(W.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${W.pattern}`;return`Invalid ${K[W.format]??Q.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${Q.divisor}`;case"unrecognized_keys":return`Chiav${Q.keys.length>1?"i":"e"} non riconosciut${Q.keys.length>1?"e":"a"}: ${_(Q.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${Q.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${Q.origin}`;default:return"Input non valido"}}};function f5(){return{localeError:M_()}}var D_=()=>{let $={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function U(Q){return $[Q]??null}let K={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"},q={nan:"NaN",number:"数値",array:"配列"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`無効な入力: instanceof ${Q.expected}が期待されましたが、${j}が入力されました`;return`無効な入力: ${W}が期待されましたが、${j}が入力されました`}case"invalid_value":if(Q.values.length===1)return`無効な入力: ${v(Q.values[0])}が期待されました`;return`無効な選択: ${_(Q.values,"、")}のいずれかである必要があります`;case"too_big":{let W=Q.inclusive?"以下である":"より小さい",J=U(Q.origin);if(J)return`大きすぎる値: ${Q.origin??"値"}は${Q.maximum.toString()}${J.unit??"要素"}${W}必要があります`;return`大きすぎる値: ${Q.origin??"値"}は${Q.maximum.toString()}${W}必要があります`}case"too_small":{let W=Q.inclusive?"以上である":"より大きい",J=U(Q.origin);if(J)return`小さすぎる値: ${Q.origin}は${Q.minimum.toString()}${J.unit}${W}必要があります`;return`小さすぎる値: ${Q.origin}は${Q.minimum.toString()}${W}必要があります`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`無効な文字列: "${W.prefix}"で始まる必要があります`;if(W.format==="ends_with")return`無効な文字列: "${W.suffix}"で終わる必要があります`;if(W.format==="includes")return`無効な文字列: "${W.includes}"を含む必要があります`;if(W.format==="regex")return`無効な文字列: パターン${W.pattern}に一致する必要があります`;return`無効な${K[W.format]??Q.format}`}case"not_multiple_of":return`無効な数値: ${Q.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${Q.keys.length>1?"群":""}: ${_(Q.keys,"、")}`;case"invalid_key":return`${Q.origin}内の無効なキー`;case"invalid_union":return"無効な入力";case"invalid_element":return`${Q.origin}内の無効な値`;default:return"無効な入力"}}};function m5(){return{localeError:D_()}}var P_=()=>{let $={string:{unit:"სიმბოლო",verb:"უნდა შეიცავდეს"},file:{unit:"ბაიტი",verb:"უნდა შეიცავდეს"},array:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},set:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"}};function U(Q){return $[Q]??null}let K={regex:"შეყვანა",email:"ელ-ფოსტის მისამართი",url:"URL",emoji:"ემოჯი",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"თარიღი-დრო",date:"თარიღი",time:"დრო",duration:"ხანგრძლივობა",ipv4:"IPv4 მისამართი",ipv6:"IPv6 მისამართი",cidrv4:"IPv4 დიაპაზონი",cidrv6:"IPv6 დიაპაზონი",base64:"base64-კოდირებული სტრინგი",base64url:"base64url-კოდირებული სტრინგი",json_string:"JSON სტრინგი",e164:"E.164 ნომერი",jwt:"JWT",template_literal:"შეყვანა"},q={nan:"NaN",number:"რიცხვი",string:"სტრინგი",boolean:"ბულეანი",function:"ფუნქცია",array:"მასივი"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`არასწორი შეყვანა: მოსალოდნელი instanceof ${Q.expected}, მიღებული ${j}`;return`არასწორი შეყვანა: მოსალოდნელი ${W}, მიღებული ${j}`}case"invalid_value":if(Q.values.length===1)return`არასწორი შეყვანა: მოსალოდნელი ${v(Q.values[0])}`;return`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${_(Q.values,"|")}-დან`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`ზედმეტად დიდი: მოსალოდნელი ${Q.origin??"მნიშვნელობა"} ${J.verb} ${W}${Q.maximum.toString()} ${J.unit}`;return`ზედმეტად დიდი: მოსალოდნელი ${Q.origin??"მნიშვნელობა"} იყოს ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`ზედმეტად პატარა: მოსალოდნელი ${Q.origin} ${J.verb} ${W}${Q.minimum.toString()} ${J.unit}`;return`ზედმეტად პატარა: მოსალოდნელი ${Q.origin} იყოს ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`არასწორი სტრინგი: უნდა იწყებოდეს "${W.prefix}"-ით`;if(W.format==="ends_with")return`არასწორი სტრინგი: უნდა მთავრდებოდეს "${W.suffix}"-ით`;if(W.format==="includes")return`არასწორი სტრინგი: უნდა შეიცავდეს "${W.includes}"-ს`;if(W.format==="regex")return`არასწორი სტრინგი: უნდა შეესაბამებოდეს შაბლონს ${W.pattern}`;return`არასწორი ${K[W.format]??Q.format}`}case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${Q.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${Q.keys.length>1?"ები":"ი"}: ${_(Q.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${Q.origin}-ში`;case"invalid_union":return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${Q.origin}-ში`;default:return"არასწორი შეყვანა"}}};function h5(){return{localeError:P_()}}var N_=()=>{let $={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function U(Q){return $[Q]??null}let K={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"},q={nan:"NaN",number:"លេខ",array:"អារេ (Array)",null:"គ្មានតម្លៃ (null)"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${Q.expected} ប៉ុន្តែទទួលបាន ${j}`;return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${W} ប៉ុន្តែទទួលបាន ${j}`}case"invalid_value":if(Q.values.length===1)return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${v(Q.values[0])}`;return`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`ធំពេក៖ ត្រូវការ ${Q.origin??"តម្លៃ"} ${W} ${Q.maximum.toString()} ${J.unit??"ធាតុ"}`;return`ធំពេក៖ ត្រូវការ ${Q.origin??"តម្លៃ"} ${W} ${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`តូចពេក៖ ត្រូវការ ${Q.origin} ${W} ${Q.minimum.toString()} ${J.unit}`;return`តូចពេក៖ ត្រូវការ ${Q.origin} ${W} ${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${W.prefix}"`;if(W.format==="ends_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${W.suffix}"`;if(W.format==="includes")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${W.includes}"`;if(W.format==="regex")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${W.pattern}`;return`មិនត្រឹមត្រូវ៖ ${K[W.format]??Q.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${Q.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${_(Q.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${Q.origin}`;case"invalid_union":return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${Q.origin}`;default:return"ទិន្នន័យមិនត្រឹមត្រូវ"}}};function e6(){return{localeError:N_()}}function c5(){return e6()}var L_=()=>{let $={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function U(Q){return $[Q]??null}let K={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"},q={nan:"NaN"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`잘못된 입력: 예상 타입은 instanceof ${Q.expected}, 받은 타입은 ${j}입니다`;return`잘못된 입력: 예상 타입은 ${W}, 받은 타입은 ${j}입니다`}case"invalid_value":if(Q.values.length===1)return`잘못된 입력: 값은 ${v(Q.values[0])} 이어야 합니다`;return`잘못된 옵션: ${_(Q.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{let W=Q.inclusive?"이하":"미만",J=W==="미만"?"이어야 합니다":"여야 합니다",j=U(Q.origin),Y=j?.unit??"요소";if(j)return`${Q.origin??"값"}이 너무 큽니다: ${Q.maximum.toString()}${Y} ${W}${J}`;return`${Q.origin??"값"}이 너무 큽니다: ${Q.maximum.toString()} ${W}${J}`}case"too_small":{let W=Q.inclusive?"이상":"초과",J=W==="이상"?"이어야 합니다":"여야 합니다",j=U(Q.origin),Y=j?.unit??"요소";if(j)return`${Q.origin??"값"}이 너무 작습니다: ${Q.minimum.toString()}${Y} ${W}${J}`;return`${Q.origin??"값"}이 너무 작습니다: ${Q.minimum.toString()} ${W}${J}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`잘못된 문자열: "${W.prefix}"(으)로 시작해야 합니다`;if(W.format==="ends_with")return`잘못된 문자열: "${W.suffix}"(으)로 끝나야 합니다`;if(W.format==="includes")return`잘못된 문자열: "${W.includes}"을(를) 포함해야 합니다`;if(W.format==="regex")return`잘못된 문자열: 정규식 ${W.pattern} 패턴과 일치해야 합니다`;return`잘못된 ${K[W.format]??Q.format}`}case"not_multiple_of":return`잘못된 숫자: ${Q.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${_(Q.keys,", ")}`;case"invalid_key":return`잘못된 키: ${Q.origin}`;case"invalid_union":return"잘못된 입력";case"invalid_element":return`잘못된 값: ${Q.origin}`;default:return"잘못된 입력"}}};function l5(){return{localeError:L_()}}var $0=($)=>{return $.charAt(0).toUpperCase()+$.slice(1)};function HY($){let U=Math.abs($),K=U%10,q=U%100;if(q>=11&&q<=19||K===0)return"many";if(K===1)return"one";return"few"}var __=()=>{let $={string:{unit:{one:"simbolis",few:"simboliai",many:"simbolių"},verb:{smaller:{inclusive:"turi būti ne ilgesnė kaip",notInclusive:"turi būti trumpesnė kaip"},bigger:{inclusive:"turi būti ne trumpesnė kaip",notInclusive:"turi būti ilgesnė kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"baitų"},verb:{smaller:{inclusive:"turi būti ne didesnis kaip",notInclusive:"turi būti mažesnis kaip"},bigger:{inclusive:"turi būti ne mažesnis kaip",notInclusive:"turi būti didesnis kaip"}}},array:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}},set:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}}};function U(Q,W,J,j){let Y=$[Q]??null;if(Y===null)return Y;return{unit:Y.unit[W],verb:Y.verb[j][J?"inclusive":"notInclusive"]}}let K={regex:"įvestis",email:"el. pašto adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukmė",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 užkoduota eilutė",base64url:"base64url užkoduota eilutė",json_string:"JSON eilutė",e164:"E.164 numeris",jwt:"JWT",template_literal:"įvestis"},q={nan:"NaN",number:"skaičius",bigint:"sveikasis skaičius",string:"eilutė",boolean:"loginė reikšmė",undefined:"neapibrėžta reikšmė",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulinė reikšmė"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Gautas tipas ${j}, o tikėtasi - instanceof ${Q.expected}`;return`Gautas tipas ${j}, o tikėtasi - ${W}`}case"invalid_value":if(Q.values.length===1)return`Privalo būti ${v(Q.values[0])}`;return`Privalo būti vienas iš ${_(Q.values,"|")} pasirinkimų`;case"too_big":{let W=q[Q.origin]??Q.origin,J=U(Q.origin,HY(Number(Q.maximum)),Q.inclusive??!1,"smaller");if(J?.verb)return`${$0(W??Q.origin??"reikšmė")} ${J.verb} ${Q.maximum.toString()} ${J.unit??"elementų"}`;let j=Q.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${$0(W??Q.origin??"reikšmė")} turi būti ${j} ${Q.maximum.toString()} ${J?.unit}`}case"too_small":{let W=q[Q.origin]??Q.origin,J=U(Q.origin,HY(Number(Q.minimum)),Q.inclusive??!1,"bigger");if(J?.verb)return`${$0(W??Q.origin??"reikšmė")} ${J.verb} ${Q.minimum.toString()} ${J.unit??"elementų"}`;let j=Q.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${$0(W??Q.origin??"reikšmė")} turi būti ${j} ${Q.minimum.toString()} ${J?.unit}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Eilutė privalo prasidėti "${W.prefix}"`;if(W.format==="ends_with")return`Eilutė privalo pasibaigti "${W.suffix}"`;if(W.format==="includes")return`Eilutė privalo įtraukti "${W.includes}"`;if(W.format==="regex")return`Eilutė privalo atitikti ${W.pattern}`;return`Neteisingas ${K[W.format]??Q.format}`}case"not_multiple_of":return`Skaičius privalo būti ${Q.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpažint${Q.keys.length>1?"i":"as"} rakt${Q.keys.length>1?"ai":"as"}: ${_(Q.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga įvestis";case"invalid_element":{let W=q[Q.origin]??Q.origin;return`${$0(W??Q.origin??"reikšmė")} turi klaidingą įvestį`}default:return"Klaidinga įvestis"}}};function r5(){return{localeError:__()}}var I_=()=>{let $={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function U(Q){return $[Q]??null}let K={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"},q={nan:"NaN",number:"број",array:"низа"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Грешен внес: се очекува instanceof ${Q.expected}, примено ${j}`;return`Грешен внес: се очекува ${W}, примено ${j}`}case"invalid_value":if(Q.values.length===1)return`Invalid input: expected ${v(Q.values[0])}`;return`Грешана опција: се очекува една ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Премногу голем: се очекува ${Q.origin??"вредноста"} да има ${W}${Q.maximum.toString()} ${J.unit??"елементи"}`;return`Премногу голем: се очекува ${Q.origin??"вредноста"} да биде ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Премногу мал: се очекува ${Q.origin} да има ${W}${Q.minimum.toString()} ${J.unit}`;return`Премногу мал: се очекува ${Q.origin} да биде ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Неважечка низа: мора да започнува со "${W.prefix}"`;if(W.format==="ends_with")return`Неважечка низа: мора да завршува со "${W.suffix}"`;if(W.format==="includes")return`Неважечка низа: мора да вклучува "${W.includes}"`;if(W.format==="regex")return`Неважечка низа: мора да одгоара на патернот ${W.pattern}`;return`Invalid ${K[W.format]??Q.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${Q.divisor}`;case"unrecognized_keys":return`${Q.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${_(Q.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${Q.origin}`;case"invalid_union":return"Грешен внес";case"invalid_element":return`Грешна вредност во ${Q.origin}`;default:return"Грешен внес"}}};function i5(){return{localeError:I_()}}var F_=()=>{let $={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function U(Q){return $[Q]??null}let K={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},q={nan:"NaN",number:"nombor"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Input tidak sah: dijangka instanceof ${Q.expected}, diterima ${j}`;return`Input tidak sah: dijangka ${W}, diterima ${j}`}case"invalid_value":if(Q.values.length===1)return`Input tidak sah: dijangka ${v(Q.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Terlalu besar: dijangka ${Q.origin??"nilai"} ${J.verb} ${W}${Q.maximum.toString()} ${J.unit??"elemen"}`;return`Terlalu besar: dijangka ${Q.origin??"nilai"} adalah ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Terlalu kecil: dijangka ${Q.origin} ${J.verb} ${W}${Q.minimum.toString()} ${J.unit}`;return`Terlalu kecil: dijangka ${Q.origin} adalah ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`String tidak sah: mesti bermula dengan "${W.prefix}"`;if(W.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${W.suffix}"`;if(W.format==="includes")return`String tidak sah: mesti mengandungi "${W.includes}"`;if(W.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${W.pattern}`;return`${K[W.format]??Q.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${Q.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${_(Q.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${Q.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${Q.origin}`;default:return"Input tidak sah"}}};function d5(){return{localeError:F_()}}var x_=()=>{let $={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function U(Q){return $[Q]??null}let K={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},q={nan:"NaN",number:"getal"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Ongeldige invoer: verwacht instanceof ${Q.expected}, ontving ${j}`;return`Ongeldige invoer: verwacht ${W}, ontving ${j}`}case"invalid_value":if(Q.values.length===1)return`Ongeldige invoer: verwacht ${v(Q.values[0])}`;return`Ongeldige optie: verwacht één van ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin),j=Q.origin==="date"?"laat":Q.origin==="string"?"lang":"groot";if(J)return`Te ${j}: verwacht dat ${Q.origin??"waarde"} ${W}${Q.maximum.toString()} ${J.unit??"elementen"} ${J.verb}`;return`Te ${j}: verwacht dat ${Q.origin??"waarde"} ${W}${Q.maximum.toString()} is`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin),j=Q.origin==="date"?"vroeg":Q.origin==="string"?"kort":"klein";if(J)return`Te ${j}: verwacht dat ${Q.origin} ${W}${Q.minimum.toString()} ${J.unit} ${J.verb}`;return`Te ${j}: verwacht dat ${Q.origin} ${W}${Q.minimum.toString()} is`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Ongeldige tekst: moet met "${W.prefix}" beginnen`;if(W.format==="ends_with")return`Ongeldige tekst: moet op "${W.suffix}" eindigen`;if(W.format==="includes")return`Ongeldige tekst: moet "${W.includes}" bevatten`;if(W.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${W.pattern}`;return`Ongeldig: ${K[W.format]??Q.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${Q.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${Q.keys.length>1?"s":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${Q.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${Q.origin}`;default:return"Ongeldige invoer"}}};function o5(){return{localeError:x_()}}var w_=()=>{let $={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function U(Q){return $[Q]??null}let K={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},q={nan:"NaN",number:"tall",array:"liste"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Ugyldig input: forventet instanceof ${Q.expected}, fikk ${j}`;return`Ugyldig input: forventet ${W}, fikk ${j}`}case"invalid_value":if(Q.values.length===1)return`Ugyldig verdi: forventet ${v(Q.values[0])}`;return`Ugyldig valg: forventet en av ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`For stor(t): forventet ${Q.origin??"value"} til å ha ${W}${Q.maximum.toString()} ${J.unit??"elementer"}`;return`For stor(t): forventet ${Q.origin??"value"} til å ha ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`For lite(n): forventet ${Q.origin} til å ha ${W}${Q.minimum.toString()} ${J.unit}`;return`For lite(n): forventet ${Q.origin} til å ha ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Ugyldig streng: må starte med "${W.prefix}"`;if(W.format==="ends_with")return`Ugyldig streng: må ende med "${W.suffix}"`;if(W.format==="includes")return`Ugyldig streng: må inneholde "${W.includes}"`;if(W.format==="regex")return`Ugyldig streng: må matche mønsteret ${W.pattern}`;return`Ugyldig ${K[W.format]??Q.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${Q.divisor}`;case"unrecognized_keys":return`${Q.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${_(Q.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${Q.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${Q.origin}`;default:return"Ugyldig input"}}};function n5(){return{localeError:w_()}}var A_=()=>{let $={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}};function U(Q){return $[Q]??null}let K={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"},q={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Fâsit giren: umulan instanceof ${Q.expected}, alınan ${j}`;return`Fâsit giren: umulan ${W}, alınan ${j}`}case"invalid_value":if(Q.values.length===1)return`Fâsit giren: umulan ${v(Q.values[0])}`;return`Fâsit tercih: mûteberler ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Fazla büyük: ${Q.origin??"value"}, ${W}${Q.maximum.toString()} ${J.unit??"elements"} sahip olmalıydı.`;return`Fazla büyük: ${Q.origin??"value"}, ${W}${Q.maximum.toString()} olmalıydı.`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Fazla küçük: ${Q.origin}, ${W}${Q.minimum.toString()} ${J.unit} sahip olmalıydı.`;return`Fazla küçük: ${Q.origin}, ${W}${Q.minimum.toString()} olmalıydı.`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Fâsit metin: "${W.prefix}" ile başlamalı.`;if(W.format==="ends_with")return`Fâsit metin: "${W.suffix}" ile bitmeli.`;if(W.format==="includes")return`Fâsit metin: "${W.includes}" ihtivâ etmeli.`;if(W.format==="regex")return`Fâsit metin: ${W.pattern} nakşına uymalı.`;return`Fâsit ${K[W.format]??Q.format}`}case"not_multiple_of":return`Fâsit sayı: ${Q.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${Q.keys.length>1?"s":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`${Q.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${Q.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};function p5(){return{localeError:A_()}}var v_=()=>{let $={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function U(Q){return $[Q]??null}let K={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"},q={nan:"NaN",number:"عدد",array:"ارې"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`ناسم ورودي: باید instanceof ${Q.expected} وای, مګر ${j} ترلاسه شو`;return`ناسم ورودي: باید ${W} وای, مګر ${j} ترلاسه شو`}case"invalid_value":if(Q.values.length===1)return`ناسم ورودي: باید ${v(Q.values[0])} وای`;return`ناسم انتخاب: باید یو له ${_(Q.values,"|")} څخه وای`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`ډیر لوی: ${Q.origin??"ارزښت"} باید ${W}${Q.maximum.toString()} ${J.unit??"عنصرونه"} ولري`;return`ډیر لوی: ${Q.origin??"ارزښت"} باید ${W}${Q.maximum.toString()} وي`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`ډیر کوچنی: ${Q.origin} باید ${W}${Q.minimum.toString()} ${J.unit} ولري`;return`ډیر کوچنی: ${Q.origin} باید ${W}${Q.minimum.toString()} وي`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`ناسم متن: باید د "${W.prefix}" سره پیل شي`;if(W.format==="ends_with")return`ناسم متن: باید د "${W.suffix}" سره پای ته ورسيږي`;if(W.format==="includes")return`ناسم متن: باید "${W.includes}" ولري`;if(W.format==="regex")return`ناسم متن: باید د ${W.pattern} سره مطابقت ولري`;return`${K[W.format]??Q.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${Q.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${Q.keys.length>1?"کلیډونه":"کلیډ"}: ${_(Q.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${Q.origin} کې`;case"invalid_union":return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${Q.origin} کې`;default:return"ناسمه ورودي"}}};function t5(){return{localeError:v_()}}var k_=()=>{let $={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}};function U(Q){return $[Q]??null}let K={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"},q={nan:"NaN",number:"liczba",array:"tablica"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Nieprawidłowe dane wejściowe: oczekiwano instanceof ${Q.expected}, otrzymano ${j}`;return`Nieprawidłowe dane wejściowe: oczekiwano ${W}, otrzymano ${j}`}case"invalid_value":if(Q.values.length===1)return`Nieprawidłowe dane wejściowe: oczekiwano ${v(Q.values[0])}`;return`Nieprawidłowa opcja: oczekiwano jednej z wartości ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Za duża wartość: oczekiwano, że ${Q.origin??"wartość"} będzie mieć ${W}${Q.maximum.toString()} ${J.unit??"elementów"}`;return`Zbyt duż(y/a/e): oczekiwano, że ${Q.origin??"wartość"} będzie wynosić ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Za mała wartość: oczekiwano, że ${Q.origin??"wartość"} będzie mieć ${W}${Q.minimum.toString()} ${J.unit??"elementów"}`;return`Zbyt mał(y/a/e): oczekiwano, że ${Q.origin??"wartość"} będzie wynosić ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Nieprawidłowy ciąg znaków: musi zaczynać się od "${W.prefix}"`;if(W.format==="ends_with")return`Nieprawidłowy ciąg znaków: musi kończyć się na "${W.suffix}"`;if(W.format==="includes")return`Nieprawidłowy ciąg znaków: musi zawierać "${W.includes}"`;if(W.format==="regex")return`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${W.pattern}`;return`Nieprawidłow(y/a/e) ${K[W.format]??Q.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${Q.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${Q.keys.length>1?"s":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${Q.origin}`;case"invalid_union":return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${Q.origin}`;default:return"Nieprawidłowe dane wejściowe"}}};function a5(){return{localeError:k_()}}var R_=()=>{let $={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function U(Q){return $[Q]??null}let K={regex:"padrão",email:"endereço de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},q={nan:"NaN",number:"número",null:"nulo"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Tipo inválido: esperado instanceof ${Q.expected}, recebido ${j}`;return`Tipo inválido: esperado ${W}, recebido ${j}`}case"invalid_value":if(Q.values.length===1)return`Entrada inválida: esperado ${v(Q.values[0])}`;return`Opção inválida: esperada uma das ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Muito grande: esperado que ${Q.origin??"valor"} tivesse ${W}${Q.maximum.toString()} ${J.unit??"elementos"}`;return`Muito grande: esperado que ${Q.origin??"valor"} fosse ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Muito pequeno: esperado que ${Q.origin} tivesse ${W}${Q.minimum.toString()} ${J.unit}`;return`Muito pequeno: esperado que ${Q.origin} fosse ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Texto inválido: deve começar com "${W.prefix}"`;if(W.format==="ends_with")return`Texto inválido: deve terminar com "${W.suffix}"`;if(W.format==="includes")return`Texto inválido: deve incluir "${W.includes}"`;if(W.format==="regex")return`Texto inválido: deve corresponder ao padrão ${W.pattern}`;return`${K[W.format]??Q.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${Q.divisor}`;case"unrecognized_keys":return`Chave${Q.keys.length>1?"s":""} desconhecida${Q.keys.length>1?"s":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Chave inválida em ${Q.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${Q.origin}`;default:return"Campo inválido"}}};function s5(){return{localeError:R_()}}function XY($,U,K,q){let Q=Math.abs($),W=Q%10,J=Q%100;if(J>=11&&J<=19)return q;if(W===1)return U;if(W>=2&&W<=4)return K;return q}var z_=()=>{let $={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function U(Q){return $[Q]??null}let K={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"},q={nan:"NaN",number:"число",array:"массив"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Неверный ввод: ожидалось instanceof ${Q.expected}, получено ${j}`;return`Неверный ввод: ожидалось ${W}, получено ${j}`}case"invalid_value":if(Q.values.length===1)return`Неверный ввод: ожидалось ${v(Q.values[0])}`;return`Неверный вариант: ожидалось одно из ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J){let j=Number(Q.maximum),Y=XY(j,J.unit.one,J.unit.few,J.unit.many);return`Слишком большое значение: ожидалось, что ${Q.origin??"значение"} будет иметь ${W}${Q.maximum.toString()} ${Y}`}return`Слишком большое значение: ожидалось, что ${Q.origin??"значение"} будет ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J){let j=Number(Q.minimum),Y=XY(j,J.unit.one,J.unit.few,J.unit.many);return`Слишком маленькое значение: ожидалось, что ${Q.origin} будет иметь ${W}${Q.minimum.toString()} ${Y}`}return`Слишком маленькое значение: ожидалось, что ${Q.origin} будет ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Неверная строка: должна начинаться с "${W.prefix}"`;if(W.format==="ends_with")return`Неверная строка: должна заканчиваться на "${W.suffix}"`;if(W.format==="includes")return`Неверная строка: должна содержать "${W.includes}"`;if(W.format==="regex")return`Неверная строка: должна соответствовать шаблону ${W.pattern}`;return`Неверный ${K[W.format]??Q.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${Q.divisor}`;case"unrecognized_keys":return`Нераспознанн${Q.keys.length>1?"ые":"ый"} ключ${Q.keys.length>1?"и":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${Q.origin}`;case"invalid_union":return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${Q.origin}`;default:return"Неверные входные данные"}}};function e5(){return{localeError:z_()}}var b_=()=>{let $={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function U(Q){return $[Q]??null}let K={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"},q={nan:"NaN",number:"število",array:"tabela"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Neveljaven vnos: pričakovano instanceof ${Q.expected}, prejeto ${j}`;return`Neveljaven vnos: pričakovano ${W}, prejeto ${j}`}case"invalid_value":if(Q.values.length===1)return`Neveljaven vnos: pričakovano ${v(Q.values[0])}`;return`Neveljavna možnost: pričakovano eno izmed ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Preveliko: pričakovano, da bo ${Q.origin??"vrednost"} imelo ${W}${Q.maximum.toString()} ${J.unit??"elementov"}`;return`Preveliko: pričakovano, da bo ${Q.origin??"vrednost"} ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Premajhno: pričakovano, da bo ${Q.origin} imelo ${W}${Q.minimum.toString()} ${J.unit}`;return`Premajhno: pričakovano, da bo ${Q.origin} ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Neveljaven niz: mora se začeti z "${W.prefix}"`;if(W.format==="ends_with")return`Neveljaven niz: mora se končati z "${W.suffix}"`;if(W.format==="includes")return`Neveljaven niz: mora vsebovati "${W.includes}"`;if(W.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${W.pattern}`;return`Neveljaven ${K[W.format]??Q.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${Q.divisor}`;case"unrecognized_keys":return`Neprepoznan${Q.keys.length>1?"i ključi":" ključ"}: ${_(Q.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${Q.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${Q.origin}`;default:return"Neveljaven vnos"}}};function $7(){return{localeError:b_()}}var O_=()=>{let $={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}};function U(Q){return $[Q]??null}let K={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},q={nan:"NaN",number:"antal",array:"lista"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Ogiltig inmatning: förväntat instanceof ${Q.expected}, fick ${j}`;return`Ogiltig inmatning: förväntat ${W}, fick ${j}`}case"invalid_value":if(Q.values.length===1)return`Ogiltig inmatning: förväntat ${v(Q.values[0])}`;return`Ogiltigt val: förväntade en av ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`För stor(t): förväntade ${Q.origin??"värdet"} att ha ${W}${Q.maximum.toString()} ${J.unit??"element"}`;return`För stor(t): förväntat ${Q.origin??"värdet"} att ha ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`För lite(t): förväntade ${Q.origin??"värdet"} att ha ${W}${Q.minimum.toString()} ${J.unit}`;return`För lite(t): förväntade ${Q.origin??"värdet"} att ha ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Ogiltig sträng: måste börja med "${W.prefix}"`;if(W.format==="ends_with")return`Ogiltig sträng: måste sluta med "${W.suffix}"`;if(W.format==="includes")return`Ogiltig sträng: måste innehålla "${W.includes}"`;if(W.format==="regex")return`Ogiltig sträng: måste matcha mönstret "${W.pattern}"`;return`Ogiltig(t) ${K[W.format]??Q.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${Q.divisor}`;case"unrecognized_keys":return`${Q.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${_(Q.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${Q.origin??"värdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${Q.origin??"värdet"}`;default:return"Ogiltig input"}}};function U7(){return{localeError:O_()}}var T_=()=>{let $={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function U(Q){return $[Q]??null}let K={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"},q={nan:"NaN",number:"எண்",array:"அணி",null:"வெறுமை"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${Q.expected}, பெறப்பட்டது ${j}`;return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${W}, பெறப்பட்டது ${j}`}case"invalid_value":if(Q.values.length===1)return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${v(Q.values[0])}`;return`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${_(Q.values,"|")} இல் ஒன்று`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${Q.origin??"மதிப்பு"} ${W}${Q.maximum.toString()} ${J.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`;return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${Q.origin??"மதிப்பு"} ${W}${Q.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${Q.origin} ${W}${Q.minimum.toString()} ${J.unit} ஆக இருக்க வேண்டும்`;return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${Q.origin} ${W}${Q.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`தவறான சரம்: "${W.prefix}" இல் தொடங்க வேண்டும்`;if(W.format==="ends_with")return`தவறான சரம்: "${W.suffix}" இல் முடிவடைய வேண்டும்`;if(W.format==="includes")return`தவறான சரம்: "${W.includes}" ஐ உள்ளடக்க வேண்டும்`;if(W.format==="regex")return`தவறான சரம்: ${W.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`;return`தவறான ${K[W.format]??Q.format}`}case"not_multiple_of":return`தவறான எண்: ${Q.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${Q.keys.length>1?"கள்":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`${Q.origin} இல் தவறான விசை`;case"invalid_union":return"தவறான உள்ளீடு";case"invalid_element":return`${Q.origin} இல் தவறான மதிப்பு`;default:return"தவறான உள்ளீடு"}}};function Q7(){return{localeError:T_()}}var S_=()=>{let $={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function U(Q){return $[Q]??null}let K={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"},q={nan:"NaN",number:"ตัวเลข",array:"อาร์เรย์ (Array)",null:"ไม่มีค่า (null)"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${Q.expected} แต่ได้รับ ${j}`;return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${W} แต่ได้รับ ${j}`}case"invalid_value":if(Q.values.length===1)return`ค่าไม่ถูกต้อง: ควรเป็น ${v(Q.values[0])}`;return`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"ไม่เกิน":"น้อยกว่า",J=U(Q.origin);if(J)return`เกินกำหนด: ${Q.origin??"ค่า"} ควรมี${W} ${Q.maximum.toString()} ${J.unit??"รายการ"}`;return`เกินกำหนด: ${Q.origin??"ค่า"} ควรมี${W} ${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?"อย่างน้อย":"มากกว่า",J=U(Q.origin);if(J)return`น้อยกว่ากำหนด: ${Q.origin} ควรมี${W} ${Q.minimum.toString()} ${J.unit}`;return`น้อยกว่ากำหนด: ${Q.origin} ควรมี${W} ${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${W.prefix}"`;if(W.format==="ends_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${W.suffix}"`;if(W.format==="includes")return`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${W.includes}" อยู่ในข้อความ`;if(W.format==="regex")return`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${W.pattern}`;return`รูปแบบไม่ถูกต้อง: ${K[W.format]??Q.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${Q.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${_(Q.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${Q.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${Q.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};function K7(){return{localeError:S_()}}var C_=()=>{let $={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function U(Q){return $[Q]??null}let K={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"},q={nan:"NaN"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Geçersiz değer: beklenen instanceof ${Q.expected}, alınan ${j}`;return`Geçersiz değer: beklenen ${W}, alınan ${j}`}case"invalid_value":if(Q.values.length===1)return`Geçersiz değer: beklenen ${v(Q.values[0])}`;return`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Çok büyük: beklenen ${Q.origin??"değer"} ${W}${Q.maximum.toString()} ${J.unit??"öğe"}`;return`Çok büyük: beklenen ${Q.origin??"değer"} ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Çok küçük: beklenen ${Q.origin} ${W}${Q.minimum.toString()} ${J.unit}`;return`Çok küçük: beklenen ${Q.origin} ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Geçersiz metin: "${W.prefix}" ile başlamalı`;if(W.format==="ends_with")return`Geçersiz metin: "${W.suffix}" ile bitmeli`;if(W.format==="includes")return`Geçersiz metin: "${W.includes}" içermeli`;if(W.format==="regex")return`Geçersiz metin: ${W.pattern} desenine uymalı`;return`Geçersiz ${K[W.format]??Q.format}`}case"not_multiple_of":return`Geçersiz sayı: ${Q.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${Q.keys.length>1?"lar":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`${Q.origin} içinde geçersiz anahtar`;case"invalid_union":return"Geçersiz değer";case"invalid_element":return`${Q.origin} içinde geçersiz değer`;default:return"Geçersiz değer"}}};function q7(){return{localeError:C_()}}var E_=()=>{let $={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function U(Q){return $[Q]??null}let K={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"},q={nan:"NaN",number:"число",array:"масив"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Неправильні вхідні дані: очікується instanceof ${Q.expected}, отримано ${j}`;return`Неправильні вхідні дані: очікується ${W}, отримано ${j}`}case"invalid_value":if(Q.values.length===1)return`Неправильні вхідні дані: очікується ${v(Q.values[0])}`;return`Неправильна опція: очікується одне з ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Занадто велике: очікується, що ${Q.origin??"значення"} ${J.verb} ${W}${Q.maximum.toString()} ${J.unit??"елементів"}`;return`Занадто велике: очікується, що ${Q.origin??"значення"} буде ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Занадто мале: очікується, що ${Q.origin} ${J.verb} ${W}${Q.minimum.toString()} ${J.unit}`;return`Занадто мале: очікується, що ${Q.origin} буде ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Неправильний рядок: повинен починатися з "${W.prefix}"`;if(W.format==="ends_with")return`Неправильний рядок: повинен закінчуватися на "${W.suffix}"`;if(W.format==="includes")return`Неправильний рядок: повинен містити "${W.includes}"`;if(W.format==="regex")return`Неправильний рядок: повинен відповідати шаблону ${W.pattern}`;return`Неправильний ${K[W.format]??Q.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${Q.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${Q.keys.length>1?"і":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${Q.origin}`;case"invalid_union":return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${Q.origin}`;default:return"Неправильні вхідні дані"}}};function U0(){return{localeError:E_()}}function W7(){return U0()}var y_=()=>{let $={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function U(Q){return $[Q]??null}let K={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"},q={nan:"NaN",number:"نمبر",array:"آرے",null:"نل"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`غلط ان پٹ: instanceof ${Q.expected} متوقع تھا، ${j} موصول ہوا`;return`غلط ان پٹ: ${W} متوقع تھا، ${j} موصول ہوا`}case"invalid_value":if(Q.values.length===1)return`غلط ان پٹ: ${v(Q.values[0])} متوقع تھا`;return`غلط آپشن: ${_(Q.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`بہت بڑا: ${Q.origin??"ویلیو"} کے ${W}${Q.maximum.toString()} ${J.unit??"عناصر"} ہونے متوقع تھے`;return`بہت بڑا: ${Q.origin??"ویلیو"} کا ${W}${Q.maximum.toString()} ہونا متوقع تھا`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`بہت چھوٹا: ${Q.origin} کے ${W}${Q.minimum.toString()} ${J.unit} ہونے متوقع تھے`;return`بہت چھوٹا: ${Q.origin} کا ${W}${Q.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`غلط سٹرنگ: "${W.prefix}" سے شروع ہونا چاہیے`;if(W.format==="ends_with")return`غلط سٹرنگ: "${W.suffix}" پر ختم ہونا چاہیے`;if(W.format==="includes")return`غلط سٹرنگ: "${W.includes}" شامل ہونا چاہیے`;if(W.format==="regex")return`غلط سٹرنگ: پیٹرن ${W.pattern} سے میچ ہونا چاہیے`;return`غلط ${K[W.format]??Q.format}`}case"not_multiple_of":return`غلط نمبر: ${Q.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${Q.keys.length>1?"ز":""}: ${_(Q.keys,"، ")}`;case"invalid_key":return`${Q.origin} میں غلط کی`;case"invalid_union":return"غلط ان پٹ";case"invalid_element":return`${Q.origin} میں غلط ویلیو`;default:return"غلط ان پٹ"}}};function J7(){return{localeError:y_()}}var g_=()=>{let $={string:{unit:"belgi",verb:"bo‘lishi kerak"},file:{unit:"bayt",verb:"bo‘lishi kerak"},array:{unit:"element",verb:"bo‘lishi kerak"},set:{unit:"element",verb:"bo‘lishi kerak"}};function U(Q){return $[Q]??null}let K={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},q={nan:"NaN",number:"raqam",array:"massiv"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Noto‘g‘ri kirish: kutilgan instanceof ${Q.expected}, qabul qilingan ${j}`;return`Noto‘g‘ri kirish: kutilgan ${W}, qabul qilingan ${j}`}case"invalid_value":if(Q.values.length===1)return`Noto‘g‘ri kirish: kutilgan ${v(Q.values[0])}`;return`Noto‘g‘ri variant: quyidagilardan biri kutilgan ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Juda katta: kutilgan ${Q.origin??"qiymat"} ${W}${Q.maximum.toString()} ${J.unit} ${J.verb}`;return`Juda katta: kutilgan ${Q.origin??"qiymat"} ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Juda kichik: kutilgan ${Q.origin} ${W}${Q.minimum.toString()} ${J.unit} ${J.verb}`;return`Juda kichik: kutilgan ${Q.origin} ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Noto‘g‘ri satr: "${W.prefix}" bilan boshlanishi kerak`;if(W.format==="ends_with")return`Noto‘g‘ri satr: "${W.suffix}" bilan tugashi kerak`;if(W.format==="includes")return`Noto‘g‘ri satr: "${W.includes}" ni o‘z ichiga olishi kerak`;if(W.format==="regex")return`Noto‘g‘ri satr: ${W.pattern} shabloniga mos kelishi kerak`;return`Noto‘g‘ri ${K[W.format]??Q.format}`}case"not_multiple_of":return`Noto‘g‘ri raqam: ${Q.divisor} ning karralisi bo‘lishi kerak`;case"unrecognized_keys":return`Noma’lum kalit${Q.keys.length>1?"lar":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`${Q.origin} dagi kalit noto‘g‘ri`;case"invalid_union":return"Noto‘g‘ri kirish";case"invalid_element":return`${Q.origin} da noto‘g‘ri qiymat`;default:return"Noto‘g‘ri kirish"}}};function G7(){return{localeError:g_()}}var u_=()=>{let $={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}};function U(Q){return $[Q]??null}let K={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"},q={nan:"NaN",number:"số",array:"mảng"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Đầu vào không hợp lệ: mong đợi instanceof ${Q.expected}, nhận được ${j}`;return`Đầu vào không hợp lệ: mong đợi ${W}, nhận được ${j}`}case"invalid_value":if(Q.values.length===1)return`Đầu vào không hợp lệ: mong đợi ${v(Q.values[0])}`;return`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Quá lớn: mong đợi ${Q.origin??"giá trị"} ${J.verb} ${W}${Q.maximum.toString()} ${J.unit??"phần tử"}`;return`Quá lớn: mong đợi ${Q.origin??"giá trị"} ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Quá nhỏ: mong đợi ${Q.origin} ${J.verb} ${W}${Q.minimum.toString()} ${J.unit}`;return`Quá nhỏ: mong đợi ${Q.origin} ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Chuỗi không hợp lệ: phải bắt đầu bằng "${W.prefix}"`;if(W.format==="ends_with")return`Chuỗi không hợp lệ: phải kết thúc bằng "${W.suffix}"`;if(W.format==="includes")return`Chuỗi không hợp lệ: phải bao gồm "${W.includes}"`;if(W.format==="regex")return`Chuỗi không hợp lệ: phải khớp với mẫu ${W.pattern}`;return`${K[W.format]??Q.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${Q.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${_(Q.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${Q.origin}`;case"invalid_union":return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${Q.origin}`;default:return"Đầu vào không hợp lệ"}}};function j7(){return{localeError:u_()}}var f_=()=>{let $={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function U(Q){return $[Q]??null}let K={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"},q={nan:"NaN",number:"数字",array:"数组",null:"空值(null)"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`无效输入:期望 instanceof ${Q.expected},实际接收 ${j}`;return`无效输入:期望 ${W},实际接收 ${j}`}case"invalid_value":if(Q.values.length===1)return`无效输入:期望 ${v(Q.values[0])}`;return`无效选项:期望以下之一 ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`数值过大:期望 ${Q.origin??"值"} ${W}${Q.maximum.toString()} ${J.unit??"个元素"}`;return`数值过大:期望 ${Q.origin??"值"} ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`数值过小:期望 ${Q.origin} ${W}${Q.minimum.toString()} ${J.unit}`;return`数值过小:期望 ${Q.origin} ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`无效字符串:必须以 "${W.prefix}" 开头`;if(W.format==="ends_with")return`无效字符串:必须以 "${W.suffix}" 结尾`;if(W.format==="includes")return`无效字符串:必须包含 "${W.includes}"`;if(W.format==="regex")return`无效字符串:必须满足正则表达式 ${W.pattern}`;return`无效${K[W.format]??Q.format}`}case"not_multiple_of":return`无效数字:必须是 ${Q.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${_(Q.keys,", ")}`;case"invalid_key":return`${Q.origin} 中的键(key)无效`;case"invalid_union":return"无效输入";case"invalid_element":return`${Q.origin} 中包含无效值(value)`;default:return"无效输入"}}};function Y7(){return{localeError:f_()}}var m_=()=>{let $={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function U(Q){return $[Q]??null}let K={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"},q={nan:"NaN"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`無效的輸入值:預期為 instanceof ${Q.expected},但收到 ${j}`;return`無效的輸入值:預期為 ${W},但收到 ${j}`}case"invalid_value":if(Q.values.length===1)return`無效的輸入值:預期為 ${v(Q.values[0])}`;return`無效的選項:預期為以下其中之一 ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`數值過大:預期 ${Q.origin??"值"} 應為 ${W}${Q.maximum.toString()} ${J.unit??"個元素"}`;return`數值過大:預期 ${Q.origin??"值"} 應為 ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`數值過小:預期 ${Q.origin} 應為 ${W}${Q.minimum.toString()} ${J.unit}`;return`數值過小:預期 ${Q.origin} 應為 ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`無效的字串:必須以 "${W.prefix}" 開頭`;if(W.format==="ends_with")return`無效的字串:必須以 "${W.suffix}" 結尾`;if(W.format==="includes")return`無效的字串:必須包含 "${W.includes}"`;if(W.format==="regex")return`無效的字串:必須符合格式 ${W.pattern}`;return`無效的 ${K[W.format]??Q.format}`}case"not_multiple_of":return`無效的數字:必須為 ${Q.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${Q.keys.length>1?"們":""}:${_(Q.keys,"、")}`;case"invalid_key":return`${Q.origin} 中有無效的鍵值`;case"invalid_union":return"無效的輸入值";case"invalid_element":return`${Q.origin} 中有無效的值`;default:return"無效的輸入值"}}};function H7(){return{localeError:m_()}}var h_=()=>{let $={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function U(Q){return $[Q]??null}let K={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"},q={nan:"NaN",number:"nọ́mbà",array:"akopọ"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,J=k(Q.input),j=q[J]??J;if(/^[A-Z]/.test(Q.expected))return`Ìbáwọlé aṣìṣe: a ní láti fi instanceof ${Q.expected}, àmọ̀ a rí ${j}`;return`Ìbáwọlé aṣìṣe: a ní láti fi ${W}, àmọ̀ a rí ${j}`}case"invalid_value":if(Q.values.length===1)return`Ìbáwọlé aṣìṣe: a ní láti fi ${v(Q.values[0])}`;return`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",J=U(Q.origin);if(J)return`Tó pọ̀ jù: a ní láti jẹ́ pé ${Q.origin??"iye"} ${J.verb} ${W}${Q.maximum} ${J.unit}`;return`Tó pọ̀ jù: a ní láti jẹ́ ${W}${Q.maximum}`}case"too_small":{let W=Q.inclusive?">=":">",J=U(Q.origin);if(J)return`Kéré ju: a ní láti jẹ́ pé ${Q.origin} ${J.verb} ${W}${Q.minimum} ${J.unit}`;return`Kéré ju: a ní láti jẹ́ ${W}${Q.minimum}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${W.prefix}"`;if(W.format==="ends_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${W.suffix}"`;if(W.format==="includes")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${W.includes}"`;if(W.format==="regex")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${W.pattern}`;return`Aṣìṣe: ${K[W.format]??Q.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${Q.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${_(Q.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${Q.origin}`;case"invalid_union":return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${Q.origin}`;default:return"Ìbáwọlé aṣìṣe"}}};function X7(){return{localeError:h_()}}var ZY,Z7=Symbol("ZodOutput"),B7=Symbol("ZodInput");class V7{constructor(){this._map=new WeakMap,this._idmap=new Map}add($,...U){let K=U[0];if(this._map.set($,K),K&&typeof K==="object"&&"id"in K)this._idmap.set(K.id,$);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove($){let U=this._map.get($);if(U&&typeof U==="object"&&"id"in U)this._idmap.delete(U.id);return this._map.delete($),this}get($){let U=$._zod.parent;if(U){let K={...this.get(U)??{}};delete K.id;let q={...K,...this._map.get($)};return Object.keys(q).length?q:void 0}return this._map.get($)}has($){return this._map.has($)}}function v2(){return new V7}(ZY=globalThis).__zod_globalRegistry??(ZY.__zod_globalRegistry=v2());var _$=globalThis.__zod_globalRegistry;function M7($,U){return new $({type:"string",...b(U)})}function D7($,U){return new $({type:"string",coerce:!0,...b(U)})}function k2($,U){return new $({type:"string",format:"email",check:"string_format",abort:!1,...b(U)})}function K0($,U){return new $({type:"string",format:"guid",check:"string_format",abort:!1,...b(U)})}function R2($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,...b(U)})}function z2($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...b(U)})}function b2($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...b(U)})}function O2($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...b(U)})}function q0($,U){return new $({type:"string",format:"url",check:"string_format",abort:!1,...b(U)})}function T2($,U){return new $({type:"string",format:"emoji",check:"string_format",abort:!1,...b(U)})}function S2($,U){return new $({type:"string",format:"nanoid",check:"string_format",abort:!1,...b(U)})}function C2($,U){return new $({type:"string",format:"cuid",check:"string_format",abort:!1,...b(U)})}function E2($,U){return new $({type:"string",format:"cuid2",check:"string_format",abort:!1,...b(U)})}function y2($,U){return new $({type:"string",format:"ulid",check:"string_format",abort:!1,...b(U)})}function g2($,U){return new $({type:"string",format:"xid",check:"string_format",abort:!1,...b(U)})}function u2($,U){return new $({type:"string",format:"ksuid",check:"string_format",abort:!1,...b(U)})}function f2($,U){return new $({type:"string",format:"ipv4",check:"string_format",abort:!1,...b(U)})}function m2($,U){return new $({type:"string",format:"ipv6",check:"string_format",abort:!1,...b(U)})}function P7($,U){return new $({type:"string",format:"mac",check:"string_format",abort:!1,...b(U)})}function h2($,U){return new $({type:"string",format:"cidrv4",check:"string_format",abort:!1,...b(U)})}function c2($,U){return new $({type:"string",format:"cidrv6",check:"string_format",abort:!1,...b(U)})}function l2($,U){return new $({type:"string",format:"base64",check:"string_format",abort:!1,...b(U)})}function r2($,U){return new $({type:"string",format:"base64url",check:"string_format",abort:!1,...b(U)})}function i2($,U){return new $({type:"string",format:"e164",check:"string_format",abort:!1,...b(U)})}function d2($,U){return new $({type:"string",format:"jwt",check:"string_format",abort:!1,...b(U)})}var N7={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function L7($,U){return new $({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...b(U)})}function _7($,U){return new $({type:"string",format:"date",check:"string_format",...b(U)})}function I7($,U){return new $({type:"string",format:"time",check:"string_format",precision:null,...b(U)})}function F7($,U){return new $({type:"string",format:"duration",check:"string_format",...b(U)})}function x7($,U){return new $({type:"number",checks:[],...b(U)})}function w7($,U){return new $({type:"number",coerce:!0,checks:[],...b(U)})}function A7($,U){return new $({type:"number",check:"number_format",abort:!1,format:"safeint",...b(U)})}function v7($,U){return new $({type:"number",check:"number_format",abort:!1,format:"float32",...b(U)})}function k7($,U){return new $({type:"number",check:"number_format",abort:!1,format:"float64",...b(U)})}function R7($,U){return new $({type:"number",check:"number_format",abort:!1,format:"int32",...b(U)})}function z7($,U){return new $({type:"number",check:"number_format",abort:!1,format:"uint32",...b(U)})}function b7($,U){return new $({type:"boolean",...b(U)})}function O7($,U){return new $({type:"boolean",coerce:!0,...b(U)})}function T7($,U){return new $({type:"bigint",...b(U)})}function S7($,U){return new $({type:"bigint",coerce:!0,...b(U)})}function C7($,U){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...b(U)})}function E7($,U){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...b(U)})}function y7($,U){return new $({type:"symbol",...b(U)})}function g7($,U){return new $({type:"undefined",...b(U)})}function u7($,U){return new $({type:"null",...b(U)})}function f7($){return new $({type:"any"})}function m7($){return new $({type:"unknown"})}function h7($,U){return new $({type:"never",...b(U)})}function c7($,U){return new $({type:"void",...b(U)})}function l7($,U){return new $({type:"date",...b(U)})}function r7($,U){return new $({type:"date",coerce:!0,...b(U)})}function i7($,U){return new $({type:"nan",...b(U)})}function Z1($,U){return new V2({check:"less_than",...b(U),value:$,inclusive:!1})}function h$($,U){return new V2({check:"less_than",...b(U),value:$,inclusive:!0})}function B1($,U){return new M2({check:"greater_than",...b(U),value:$,inclusive:!1})}function z$($,U){return new M2({check:"greater_than",...b(U),value:$,inclusive:!0})}function o2($){return B1(0,$)}function n2($){return Z1(0,$)}function p2($){return h$(0,$)}function t2($){return z$(0,$)}function u1($,U){return new iU({check:"multiple_of",...b(U),value:$})}function f1($,U){return new nU({check:"max_size",...b(U),maximum:$})}function V1($,U){return new pU({check:"min_size",...b(U),minimum:$})}function M4($,U){return new tU({check:"size_equals",...b(U),size:$})}function D4($,U){return new aU({check:"max_length",...b(U),maximum:$})}function v1($,U){return new sU({check:"min_length",...b(U),minimum:$})}function P4($,U){return new eU({check:"length_equals",...b(U),length:$})}function o4($,U){return new $9({check:"string_format",format:"regex",...b(U),pattern:$})}function n4($){return new U9({check:"string_format",format:"lowercase",...b($)})}function p4($){return new Q9({check:"string_format",format:"uppercase",...b($)})}function t4($,U){return new K9({check:"string_format",format:"includes",...b(U),includes:$})}function a4($,U){return new q9({check:"string_format",format:"starts_with",...b(U),prefix:$})}function s4($,U){return new W9({check:"string_format",format:"ends_with",...b(U),suffix:$})}function a2($,U,K){return new J9({check:"property",property:$,schema:U,...b(K)})}function e4($,U){return new G9({check:"mime_type",mime:$,...b(U)})}function q1($){return new j9({check:"overwrite",tx:$})}function $6($){return q1((U)=>U.normalize($))}function U6(){return q1(($)=>$.trim())}function Q6(){return q1(($)=>$.toLowerCase())}function K6(){return q1(($)=>$.toUpperCase())}function q6(){return q1(($)=>JU($))}function d7($,U,K){return new $({type:"array",element:U,...b(K)})}function l_($,U,K){return new $({type:"union",options:U,...b(K)})}function r_($,U,K){return new $({type:"union",options:U,inclusive:!1,...b(K)})}function i_($,U,K,q){return new $({type:"union",options:K,discriminator:U,...b(q)})}function d_($,U,K){return new $({type:"intersection",left:U,right:K})}function o_($,U,K,q){let Q=K instanceof h;return new $({type:"tuple",items:U,rest:Q?K:null,...b(Q?q:K)})}function n_($,U,K,q){return new $({type:"record",keyType:U,valueType:K,...b(q)})}function p_($,U,K,q){return new $({type:"map",keyType:U,valueType:K,...b(q)})}function t_($,U,K){return new $({type:"set",valueType:U,...b(K)})}function a_($,U,K){let q=Array.isArray(U)?Object.fromEntries(U.map((Q)=>[Q,Q])):U;return new $({type:"enum",entries:q,...b(K)})}function s_($,U,K){return new $({type:"enum",entries:U,...b(K)})}function e_($,U,K){return new $({type:"literal",values:Array.isArray(U)?U:[U],...b(K)})}function o7($,U){return new $({type:"file",...b(U)})}function $I($,U){return new $({type:"transform",transform:U})}function UI($,U){return new $({type:"optional",innerType:U})}function QI($,U){return new $({type:"nullable",innerType:U})}function KI($,U,K){return new $({type:"default",innerType:U,get defaultValue(){return typeof K==="function"?K():jU(K)}})}function qI($,U,K){return new $({type:"nonoptional",innerType:U,...b(K)})}function WI($,U){return new $({type:"success",innerType:U})}function JI($,U,K){return new $({type:"catch",innerType:U,catchValue:typeof K==="function"?K:()=>K})}function GI($,U,K){return new $({type:"pipe",in:U,out:K})}function jI($,U){return new $({type:"readonly",innerType:U})}function YI($,U,K){return new $({type:"template_literal",parts:U,...b(K)})}function HI($,U){return new $({type:"lazy",getter:U})}function XI($,U){return new $({type:"promise",innerType:U})}function n7($,U,K){let q=b(K);return q.abort??(q.abort=!0),new $({type:"custom",check:"custom",fn:U,...q})}function p7($,U,K){return new $({type:"custom",check:"custom",fn:U,...b(K)})}function t7($){let U=BY((K)=>{return K.addIssue=(q)=>{if(typeof q==="string")K.issues.push(m4(q,K.value,U._zod.def));else{let Q=q;if(Q.fatal)Q.continue=!1;Q.code??(Q.code="custom"),Q.input??(Q.input=K.value),Q.inst??(Q.inst=U),Q.continue??(Q.continue=!U._zod.def.abort),K.issues.push(m4(Q))}},$(K.value,K)});return U}function BY($,U){let K=new $$({check:"custom",...b(U)});return K._zod.check=$,K}function a7($){let U=new $$({check:"describe"});return U._zod.onattach=[(K)=>{let q=_$.get(K)??{};_$.add(K,{...q,description:$})}],U._zod.check=()=>{},U}function s7($){let U=new $$({check:"meta"});return U._zod.onattach=[(K)=>{let q=_$.get(K)??{};_$.add(K,{...q,...$})}],U._zod.check=()=>{},U}function e7($,U){let K=b(U),q=K.truthy??["true","1","yes","on","y","enabled"],Q=K.falsy??["false","0","no","off","n","disabled"];if(K.case!=="sensitive")q=q.map((I)=>typeof I==="string"?I.toLowerCase():I),Q=Q.map((I)=>typeof I==="string"?I.toLowerCase():I);let W=new Set(q),J=new Set(Q),j=$.Codec??a6,Y=$.Boolean??p6,Z=new($.String??V4)({type:"string",error:K.error}),B=new Y({type:"boolean",error:K.error}),M=new j({type:"pipe",in:Z,out:B,transform:(I,E)=>{let u=I;if(K.case!=="sensitive")u=u.toLowerCase();if(W.has(u))return!0;else if(J.has(u))return!1;else return E.issues.push({code:"invalid_value",expected:"stringbool",values:[...W,...J],input:E.value,inst:M,continue:!1}),{}},reverseTransform:(I,E)=>{if(I===!0)return q[0]||"true";else return Q[0]||"false"},error:K.error});return M}function W6($,U,K,q={}){let Q=b(q),W={...b(q),check:"string_format",type:"string",format:U,fn:typeof K==="function"?K:(j)=>K.test(j),...Q};if(K instanceof RegExp)W.pattern=K;return new $(W)}function m1($){let U=$?.target??"draft-2020-12";if(U==="draft-4")U="draft-04";if(U==="draft-7")U="draft-07";return{processors:$.processors??{},metadataRegistry:$?.metadata??_$,target:U,unrepresentable:$?.unrepresentable??"throw",override:$?.override??(()=>{}),io:$?.io??"output",counter:0,seen:new Map,cycles:$?.cycles??"ref",reused:$?.reused??"inline",external:$?.external??void 0}}function t($,U,K={path:[],schemaPath:[]}){var q;let Q=$._zod.def,W=U.seen.get($);if(W){if(W.count++,K.schemaPath.includes($))W.cycle=K.path;return W.schema}let J={schema:{},count:1,cycle:void 0,path:K.path};U.seen.set($,J);let j=$._zod.toJSONSchema?.();if(j)J.schema=j;else{let Z={...K,schemaPath:[...K.schemaPath,$],path:K.path};if($._zod.processJSONSchema)$._zod.processJSONSchema(U,J.schema,Z);else{let M=J.schema,I=U.processors[Q.type];if(!I)throw Error(`[toJSONSchema]: Non-representable type encountered: ${Q.type}`);I($,U,M,Z)}let B=$._zod.parent;if(B){if(!J.ref)J.ref=B;t(B,U,Z),U.seen.get(B).isParent=!0}}let Y=U.metadataRegistry.get($);if(Y)Object.assign(J.schema,Y);if(U.io==="input"&&b$($))delete J.schema.examples,delete J.schema.default;if(U.io==="input"&&J.schema._prefault)(q=J.schema).default??(q.default=J.schema._prefault);return delete J.schema._prefault,U.seen.get($).schema}function h1($,U){let K=$.seen.get(U);if(!K)throw Error("Unprocessed schema. This is a bug in Zod.");let q=new Map;for(let J of $.seen.entries()){let j=$.metadataRegistry.get(J[0])?.id;if(j){let Y=q.get(j);if(Y&&Y!==J[0])throw Error(`Duplicate schema id "${j}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);q.set(j,J[0])}}let Q=(J)=>{let j=$.target==="draft-2020-12"?"$defs":"definitions";if($.external){let B=$.external.registry.get(J[0])?.id,M=$.external.uri??((E)=>E);if(B)return{ref:M(B)};let I=J[1].defId??J[1].schema.id??`schema${$.counter++}`;return J[1].defId=I,{defId:I,ref:`${M("__shared")}#/${j}/${I}`}}if(J[1]===K)return{ref:"#"};let H=`${"#"}/${j}/`,Z=J[1].schema.id??`__schema${$.counter++}`;return{defId:Z,ref:H+Z}},W=(J)=>{if(J[1].schema.$ref)return;let j=J[1],{ref:Y,defId:H}=Q(J);if(j.def={...j.schema},H)j.defId=H;let Z=j.schema;for(let B in Z)delete Z[B];Z.$ref=Y};if($.cycles==="throw")for(let J of $.seen.entries()){let j=J[1];if(j.cycle)throw Error(`Cycle detected: #/${j.cycle?.join("/")}/<root>
|
|
90
|
-
|
|
91
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let J of $.seen.entries()){let j=J[1];if(U===J[0]){W(J);continue}if($.external){let H=$.external.registry.get(J[0])?.id;if(U!==J[0]&&H){W(J);continue}}if($.metadataRegistry.get(J[0])?.id){W(J);continue}if(j.cycle){W(J);continue}if(j.count>1){if($.reused==="ref"){W(J);continue}}}}function c1($,U){let K=$.seen.get(U);if(!K)throw Error("Unprocessed schema. This is a bug in Zod.");let q=(J)=>{let j=$.seen.get(J);if(j.ref===null)return;let Y=j.def??j.schema,H={...Y},Z=j.ref;if(j.ref=null,Z){q(Z);let M=$.seen.get(Z),I=M.schema;if(I.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))Y.allOf=Y.allOf??[],Y.allOf.push(I);else Object.assign(Y,I);if(Object.assign(Y,H),J._zod.parent===Z)for(let u in Y){if(u==="$ref"||u==="allOf")continue;if(!(u in H))delete Y[u]}if(I.$ref&&M.def)for(let u in Y){if(u==="$ref"||u==="allOf")continue;if(u in M.def&&JSON.stringify(Y[u])===JSON.stringify(M.def[u]))delete Y[u]}}let B=J._zod.parent;if(B&&B!==Z){q(B);let M=$.seen.get(B);if(M?.schema.$ref){if(Y.$ref=M.schema.$ref,M.def)for(let I in Y){if(I==="$ref"||I==="allOf")continue;if(I in M.def&&JSON.stringify(Y[I])===JSON.stringify(M.def[I]))delete Y[I]}}}$.override({zodSchema:J,jsonSchema:Y,path:j.path??[]})};for(let J of[...$.seen.entries()].reverse())q(J[0]);let Q={};if($.target==="draft-2020-12")Q.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")Q.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")Q.$schema="http://json-schema.org/draft-04/schema#";else if($.target==="openapi-3.0");if($.external?.uri){let J=$.external.registry.get(U)?.id;if(!J)throw Error("Schema is missing an `id` property");Q.$id=$.external.uri(J)}Object.assign(Q,K.def??K.schema);let W=$.external?.defs??{};for(let J of $.seen.entries()){let j=J[1];if(j.def&&j.defId)W[j.defId]=j.def}if($.external);else if(Object.keys(W).length>0)if($.target==="draft-2020-12")Q.$defs=W;else Q.definitions=W;try{let J=JSON.parse(JSON.stringify(Q));return Object.defineProperty(J,"~standard",{value:{...U["~standard"],jsonSchema:{input:J6(U,"input",$.processors),output:J6(U,"output",$.processors)}},enumerable:!1,writable:!1}),J}catch(J){throw Error("Error converting schema to JSON.")}}function b$($,U){let K=U??{seen:new Set};if(K.seen.has($))return!1;K.seen.add($);let q=$._zod.def;if(q.type==="transform")return!0;if(q.type==="array")return b$(q.element,K);if(q.type==="set")return b$(q.valueType,K);if(q.type==="lazy")return b$(q.getter(),K);if(q.type==="promise"||q.type==="optional"||q.type==="nonoptional"||q.type==="nullable"||q.type==="readonly"||q.type==="default"||q.type==="prefault")return b$(q.innerType,K);if(q.type==="intersection")return b$(q.left,K)||b$(q.right,K);if(q.type==="record"||q.type==="map")return b$(q.keyType,K)||b$(q.valueType,K);if(q.type==="pipe")return b$(q.in,K)||b$(q.out,K);if(q.type==="object"){for(let Q in q.shape)if(b$(q.shape[Q],K))return!0;return!1}if(q.type==="union"){for(let Q of q.options)if(b$(Q,K))return!0;return!1}if(q.type==="tuple"){for(let Q of q.items)if(b$(Q,K))return!0;if(q.rest&&b$(q.rest,K))return!0;return!1}return!1}var $Q=($,U={})=>(K)=>{let q=m1({...K,processors:U});return t($,q),h1(q,$),c1(q,$)},J6=($,U,K={})=>(q)=>{let{libraryOptions:Q,target:W}=q??{},J=m1({...Q??{},target:W,io:U,processors:K});return t($,J),h1(J,$),c1(J,$)};var ZI={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},UQ=($,U,K,q)=>{let Q=K;Q.type="string";let{minimum:W,maximum:J,format:j,patterns:Y,contentEncoding:H}=$._zod.bag;if(typeof W==="number")Q.minLength=W;if(typeof J==="number")Q.maxLength=J;if(j){if(Q.format=ZI[j]??j,Q.format==="")delete Q.format;if(j==="time")delete Q.format}if(H)Q.contentEncoding=H;if(Y&&Y.size>0){let Z=[...Y];if(Z.length===1)Q.pattern=Z[0].source;else if(Z.length>1)Q.allOf=[...Z.map((B)=>({...U.target==="draft-07"||U.target==="draft-04"||U.target==="openapi-3.0"?{type:"string"}:{},pattern:B.source}))]}},QQ=($,U,K,q)=>{let Q=K,{minimum:W,maximum:J,format:j,multipleOf:Y,exclusiveMaximum:H,exclusiveMinimum:Z}=$._zod.bag;if(typeof j==="string"&&j.includes("int"))Q.type="integer";else Q.type="number";if(typeof Z==="number")if(U.target==="draft-04"||U.target==="openapi-3.0")Q.minimum=Z,Q.exclusiveMinimum=!0;else Q.exclusiveMinimum=Z;if(typeof W==="number"){if(Q.minimum=W,typeof Z==="number"&&U.target!=="draft-04")if(Z>=W)delete Q.minimum;else delete Q.exclusiveMinimum}if(typeof H==="number")if(U.target==="draft-04"||U.target==="openapi-3.0")Q.maximum=H,Q.exclusiveMaximum=!0;else Q.exclusiveMaximum=H;if(typeof J==="number"){if(Q.maximum=J,typeof H==="number"&&U.target!=="draft-04")if(H<=J)delete Q.maximum;else delete Q.exclusiveMaximum}if(typeof Y==="number")Q.multipleOf=Y},KQ=($,U,K,q)=>{K.type="boolean"},qQ=($,U,K,q)=>{if(U.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},WQ=($,U,K,q)=>{if(U.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},JQ=($,U,K,q)=>{if(U.target==="openapi-3.0")K.type="string",K.nullable=!0,K.enum=[null];else K.type="null"},GQ=($,U,K,q)=>{if(U.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},jQ=($,U,K,q)=>{if(U.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},YQ=($,U,K,q)=>{K.not={}},HQ=($,U,K,q)=>{},XQ=($,U,K,q)=>{},ZQ=($,U,K,q)=>{if(U.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},BQ=($,U,K,q)=>{let Q=$._zod.def,W=u6(Q.entries);if(W.every((J)=>typeof J==="number"))K.type="number";if(W.every((J)=>typeof J==="string"))K.type="string";K.enum=W},VQ=($,U,K,q)=>{let Q=$._zod.def,W=[];for(let J of Q.values)if(J===void 0){if(U.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof J==="bigint")if(U.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else W.push(Number(J));else W.push(J);if(W.length===0);else if(W.length===1){let J=W[0];if(K.type=J===null?"null":typeof J,U.target==="draft-04"||U.target==="openapi-3.0")K.enum=[J];else K.const=J}else{if(W.every((J)=>typeof J==="number"))K.type="number";if(W.every((J)=>typeof J==="string"))K.type="string";if(W.every((J)=>typeof J==="boolean"))K.type="boolean";if(W.every((J)=>J===null))K.type="null";K.enum=W}},MQ=($,U,K,q)=>{if(U.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},DQ=($,U,K,q)=>{let Q=K,W=$._zod.pattern;if(!W)throw Error("Pattern not found in template literal");Q.type="string",Q.pattern=W.source},PQ=($,U,K,q)=>{let Q=K,W={type:"string",format:"binary",contentEncoding:"binary"},{minimum:J,maximum:j,mime:Y}=$._zod.bag;if(J!==void 0)W.minLength=J;if(j!==void 0)W.maxLength=j;if(Y)if(Y.length===1)W.contentMediaType=Y[0],Object.assign(Q,W);else Object.assign(Q,W),Q.anyOf=Y.map((H)=>({contentMediaType:H}));else Object.assign(Q,W)},NQ=($,U,K,q)=>{K.type="boolean"},LQ=($,U,K,q)=>{if(U.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},_Q=($,U,K,q)=>{if(U.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},IQ=($,U,K,q)=>{if(U.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},FQ=($,U,K,q)=>{if(U.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},xQ=($,U,K,q)=>{if(U.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},wQ=($,U,K,q)=>{let Q=K,W=$._zod.def,{minimum:J,maximum:j}=$._zod.bag;if(typeof J==="number")Q.minItems=J;if(typeof j==="number")Q.maxItems=j;Q.type="array",Q.items=t(W.element,U,{...q,path:[...q.path,"items"]})},AQ=($,U,K,q)=>{let Q=K,W=$._zod.def;Q.type="object",Q.properties={};let J=W.shape;for(let H in J)Q.properties[H]=t(J[H],U,{...q,path:[...q.path,"properties",H]});let j=new Set(Object.keys(J)),Y=new Set([...j].filter((H)=>{let Z=W.shape[H]._zod;if(U.io==="input")return Z.optin===void 0;else return Z.optout===void 0}));if(Y.size>0)Q.required=Array.from(Y);if(W.catchall?._zod.def.type==="never")Q.additionalProperties=!1;else if(!W.catchall){if(U.io==="output")Q.additionalProperties=!1}else if(W.catchall)Q.additionalProperties=t(W.catchall,U,{...q,path:[...q.path,"additionalProperties"]})},e2=($,U,K,q)=>{let Q=$._zod.def,W=Q.inclusive===!1,J=Q.options.map((j,Y)=>t(j,U,{...q,path:[...q.path,W?"oneOf":"anyOf",Y]}));if(W)K.oneOf=J;else K.anyOf=J},vQ=($,U,K,q)=>{let Q=$._zod.def,W=t(Q.left,U,{...q,path:[...q.path,"allOf",0]}),J=t(Q.right,U,{...q,path:[...q.path,"allOf",1]}),j=(H)=>("allOf"in H)&&Object.keys(H).length===1,Y=[...j(W)?W.allOf:[W],...j(J)?J.allOf:[J]];K.allOf=Y},kQ=($,U,K,q)=>{let Q=K,W=$._zod.def;Q.type="array";let J=U.target==="draft-2020-12"?"prefixItems":"items",j=U.target==="draft-2020-12"?"items":U.target==="openapi-3.0"?"items":"additionalItems",Y=W.items.map((M,I)=>t(M,U,{...q,path:[...q.path,J,I]})),H=W.rest?t(W.rest,U,{...q,path:[...q.path,j,...U.target==="openapi-3.0"?[W.items.length]:[]]}):null;if(U.target==="draft-2020-12"){if(Q.prefixItems=Y,H)Q.items=H}else if(U.target==="openapi-3.0"){if(Q.items={anyOf:Y},H)Q.items.anyOf.push(H);if(Q.minItems=Y.length,!H)Q.maxItems=Y.length}else if(Q.items=Y,H)Q.additionalItems=H;let{minimum:Z,maximum:B}=$._zod.bag;if(typeof Z==="number")Q.minItems=Z;if(typeof B==="number")Q.maxItems=B},RQ=($,U,K,q)=>{let Q=K,W=$._zod.def;Q.type="object";let J=W.keyType,Y=J._zod.bag?.patterns;if(W.mode==="loose"&&Y&&Y.size>0){let Z=t(W.valueType,U,{...q,path:[...q.path,"patternProperties","*"]});Q.patternProperties={};for(let B of Y)Q.patternProperties[B.source]=Z}else{if(U.target==="draft-07"||U.target==="draft-2020-12")Q.propertyNames=t(W.keyType,U,{...q,path:[...q.path,"propertyNames"]});Q.additionalProperties=t(W.valueType,U,{...q,path:[...q.path,"additionalProperties"]})}let H=J._zod.values;if(H){let Z=[...H].filter((B)=>typeof B==="string"||typeof B==="number");if(Z.length>0)Q.required=Z}},zQ=($,U,K,q)=>{let Q=$._zod.def,W=t(Q.innerType,U,q),J=U.seen.get($);if(U.target==="openapi-3.0")J.ref=Q.innerType,K.nullable=!0;else K.anyOf=[W,{type:"null"}]},bQ=($,U,K,q)=>{let Q=$._zod.def;t(Q.innerType,U,q);let W=U.seen.get($);W.ref=Q.innerType},OQ=($,U,K,q)=>{let Q=$._zod.def;t(Q.innerType,U,q);let W=U.seen.get($);W.ref=Q.innerType,K.default=JSON.parse(JSON.stringify(Q.defaultValue))},TQ=($,U,K,q)=>{let Q=$._zod.def;t(Q.innerType,U,q);let W=U.seen.get($);if(W.ref=Q.innerType,U.io==="input")K._prefault=JSON.parse(JSON.stringify(Q.defaultValue))},SQ=($,U,K,q)=>{let Q=$._zod.def;t(Q.innerType,U,q);let W=U.seen.get($);W.ref=Q.innerType;let J;try{J=Q.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}K.default=J},CQ=($,U,K,q)=>{let Q=$._zod.def,W=U.io==="input"?Q.in._zod.def.type==="transform"?Q.out:Q.in:Q.out;t(W,U,q);let J=U.seen.get($);J.ref=W},EQ=($,U,K,q)=>{let Q=$._zod.def;t(Q.innerType,U,q);let W=U.seen.get($);W.ref=Q.innerType,K.readOnly=!0},yQ=($,U,K,q)=>{let Q=$._zod.def;t(Q.innerType,U,q);let W=U.seen.get($);W.ref=Q.innerType},$8=($,U,K,q)=>{let Q=$._zod.def;t(Q.innerType,U,q);let W=U.seen.get($);W.ref=Q.innerType},gQ=($,U,K,q)=>{let Q=$._zod.innerType;t(Q,U,q);let W=U.seen.get($);W.ref=Q},s2={string:UQ,number:QQ,boolean:KQ,bigint:qQ,symbol:WQ,null:JQ,undefined:GQ,void:jQ,never:YQ,any:HQ,unknown:XQ,date:ZQ,enum:BQ,literal:VQ,nan:MQ,template_literal:DQ,file:PQ,success:NQ,custom:LQ,function:_Q,transform:IQ,map:FQ,set:xQ,array:wQ,object:AQ,union:e2,intersection:vQ,tuple:kQ,record:RQ,nullable:zQ,nonoptional:bQ,default:OQ,prefault:TQ,catch:SQ,pipe:CQ,readonly:EQ,promise:yQ,optional:$8,lazy:gQ};function U8($,U){if("_idmap"in $){let q=$,Q=m1({...U,processors:s2}),W={};for(let Y of q._idmap.entries()){let[H,Z]=Y;t(Z,Q)}let J={},j={registry:q,uri:U?.uri,defs:W};Q.external=j;for(let Y of q._idmap.entries()){let[H,Z]=Y;h1(Q,Z),J[H]=c1(Q,Z)}if(Object.keys(W).length>0){let Y=Q.target==="draft-2020-12"?"$defs":"definitions";J.__shared={[Y]:W}}return{schemas:J}}let K=m1({...U,processors:s2});return t($,K),h1(K,$),c1(K,$)}class uQ{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter($){this.ctx.counter=$}get seen(){return this.ctx.seen}constructor($){let U=$?.target??"draft-2020-12";if(U==="draft-4")U="draft-04";if(U==="draft-7")U="draft-07";this.ctx=m1({processors:s2,target:U,...$?.metadata&&{metadata:$.metadata},...$?.unrepresentable&&{unrepresentable:$.unrepresentable},...$?.override&&{override:$.override},...$?.io&&{io:$.io}})}process($,U={path:[],schemaPath:[]}){return t($,this.ctx,U)}emit($,U){if(U){if(U.cycles)this.ctx.cycles=U.cycles;if(U.reused)this.ctx.reused=U.reused;if(U.external)this.ctx.external=U.external}h1(this.ctx,$);let K=c1(this.ctx,$),{"~standard":q,...Q}=K;return Q}}var VY={};var W0={};L1(W0,{xor:()=>JH,xid:()=>zY,void:()=>$H,uuidv7:()=>IY,uuidv6:()=>_Y,uuidv4:()=>LY,uuid:()=>NY,url:()=>FY,unknown:()=>N4,union:()=>R8,undefined:()=>sY,ulid:()=>RY,uint64:()=>tY,uint32:()=>oY,tuple:()=>NK,transform:()=>b8,templateLiteral:()=>LH,symbol:()=>aY,superRefine:()=>iK,success:()=>DH,stringbool:()=>kH,stringFormat:()=>mY,string:()=>G8,strictObject:()=>qH,set:()=>XH,refine:()=>rK,record:()=>LK,readonly:()=>uK,promise:()=>_H,preprocess:()=>zH,prefault:()=>OK,pipe:()=>Y0,partialRecord:()=>jH,optional:()=>G0,object:()=>KH,number:()=>QK,nullish:()=>MH,nullable:()=>j0,null:()=>GK,nonoptional:()=>TK,never:()=>k8,nativeEnum:()=>ZH,nanoid:()=>AY,nan:()=>PH,meta:()=>AH,map:()=>HH,mac:()=>TY,looseRecord:()=>YH,looseObject:()=>WH,literal:()=>BH,lazy:()=>hK,ksuid:()=>bY,keyof:()=>QH,jwt:()=>fY,json:()=>RH,ipv6:()=>SY,ipv4:()=>OY,intersection:()=>DK,int64:()=>pY,int32:()=>dY,int:()=>j8,instanceof:()=>vH,httpUrl:()=>xY,hostname:()=>hY,hex:()=>cY,hash:()=>lY,guid:()=>PY,function:()=>IH,float64:()=>iY,float32:()=>rY,file:()=>VH,exactOptional:()=>vK,enum:()=>z8,emoji:()=>wY,email:()=>DY,e164:()=>uY,discriminatedUnion:()=>GH,describe:()=>wH,date:()=>UH,custom:()=>xH,cuid2:()=>kY,cuid:()=>vY,codec:()=>NH,cidrv6:()=>EY,cidrv4:()=>CY,check:()=>FH,catch:()=>EK,boolean:()=>KK,bigint:()=>nY,base64url:()=>gY,base64:()=>yY,array:()=>Z0,any:()=>eY,_function:()=>IH,_default:()=>zK,_ZodString:()=>Y8,ZodXor:()=>BK,ZodXID:()=>D8,ZodVoid:()=>XK,ZodUnknown:()=>YK,ZodUnion:()=>V0,ZodUndefined:()=>WK,ZodUUID:()=>M1,ZodURL:()=>H0,ZodULID:()=>M8,ZodType:()=>c,ZodTuple:()=>PK,ZodTransform:()=>wK,ZodTemplateLiteral:()=>fK,ZodSymbol:()=>qK,ZodSuccess:()=>SK,ZodStringFormat:()=>e,ZodString:()=>Y6,ZodSet:()=>IK,ZodRecord:()=>M0,ZodReadonly:()=>gK,ZodPromise:()=>cK,ZodPrefault:()=>bK,ZodPipe:()=>S8,ZodOptional:()=>O8,ZodObject:()=>B0,ZodNumberFormat:()=>L4,ZodNumber:()=>X6,ZodNullable:()=>kK,ZodNull:()=>JK,ZodNonOptional:()=>T8,ZodNever:()=>HK,ZodNanoID:()=>Z8,ZodNaN:()=>yK,ZodMap:()=>_K,ZodMAC:()=>UK,ZodLiteral:()=>FK,ZodLazy:()=>mK,ZodKSUID:()=>P8,ZodJWT:()=>A8,ZodIntersection:()=>MK,ZodIPv6:()=>L8,ZodIPv4:()=>N8,ZodGUID:()=>J0,ZodFunction:()=>lK,ZodFile:()=>xK,ZodExactOptional:()=>AK,ZodEnum:()=>j6,ZodEmoji:()=>X8,ZodEmail:()=>H8,ZodE164:()=>w8,ZodDiscriminatedUnion:()=>VK,ZodDefault:()=>RK,ZodDate:()=>X0,ZodCustomStringFormat:()=>H6,ZodCustom:()=>D0,ZodCodec:()=>C8,ZodCatch:()=>CK,ZodCUID2:()=>V8,ZodCUID:()=>B8,ZodCIDRv6:()=>I8,ZodCIDRv4:()=>_8,ZodBoolean:()=>Z6,ZodBigIntFormat:()=>v8,ZodBigInt:()=>B6,ZodBase64URL:()=>x8,ZodBase64:()=>F8,ZodArray:()=>ZK,ZodAny:()=>jK});var Q8={};L1(Q8,{uppercase:()=>p4,trim:()=>U6,toUpperCase:()=>K6,toLowerCase:()=>Q6,startsWith:()=>a4,slugify:()=>q6,size:()=>M4,regex:()=>o4,property:()=>a2,positive:()=>o2,overwrite:()=>q1,normalize:()=>$6,nonpositive:()=>p2,nonnegative:()=>t2,negative:()=>n2,multipleOf:()=>u1,minSize:()=>V1,minLength:()=>v1,mime:()=>e4,maxSize:()=>f1,maxLength:()=>D4,lte:()=>h$,lt:()=>Z1,lowercase:()=>n4,length:()=>P4,includes:()=>t4,gte:()=>z$,gt:()=>B1,endsWith:()=>s4});var G6={};L1(G6,{time:()=>hQ,duration:()=>cQ,datetime:()=>fQ,date:()=>mQ,ZodISOTime:()=>W8,ZodISODuration:()=>J8,ZodISODateTime:()=>K8,ZodISODate:()=>q8});var K8=D("ZodISODateTime",($,U)=>{F9.init($,U),e.init($,U)});function fQ($){return L7(K8,$)}var q8=D("ZodISODate",($,U)=>{x9.init($,U),e.init($,U)});function mQ($){return _7(q8,$)}var W8=D("ZodISOTime",($,U)=>{w9.init($,U),e.init($,U)});function hQ($){return I7(W8,$)}var J8=D("ZodISODuration",($,U)=>{A9.init($,U),e.init($,U)});function cQ($){return F7(J8,$)}var MY=($,U)=>{l6.init($,U),$.name="ZodError",Object.defineProperties($,{format:{value:(K)=>i6($,K)},flatten:{value:(K)=>r6($,K)},addIssue:{value:(K)=>{$.issues.push(K),$.message=JSON.stringify($.issues,u4,2)}},addIssues:{value:(K)=>{$.issues.push(...K),$.message=JSON.stringify($.issues,u4,2)}},isEmpty:{get(){return $.issues.length===0}}})},VI=D("ZodError",MY),g$=D("ZodError",MY,{Parent:Error});var lQ=h4(g$),rQ=c4(g$),iQ=l4(g$),dQ=r4(g$),oQ=W2(g$),nQ=J2(g$),pQ=G2(g$),tQ=j2(g$),aQ=Y2(g$),sQ=H2(g$),eQ=X2(g$),$K=Z2(g$);var c=D("ZodType",($,U)=>{return h.init($,U),Object.assign($["~standard"],{jsonSchema:{input:J6($,"input"),output:J6($,"output")}}),$.toJSONSchema=$Q($,{}),$.def=U,$.type=U.type,Object.defineProperty($,"_def",{value:U}),$.check=(...K)=>{return $.clone(R.mergeDefs(U,{checks:[...U.checks??[],...K.map((q)=>typeof q==="function"?{_zod:{check:q,def:{check:"custom"},onattach:[]}}:q)]}),{parent:!0})},$.with=$.check,$.clone=(K,q)=>R$($,K,q),$.brand=()=>$,$.register=(K,q)=>{return K.add($,q),$},$.parse=(K,q)=>lQ($,K,q,{callee:$.parse}),$.safeParse=(K,q)=>iQ($,K,q),$.parseAsync=async(K,q)=>rQ($,K,q,{callee:$.parseAsync}),$.safeParseAsync=async(K,q)=>dQ($,K,q),$.spa=$.safeParseAsync,$.encode=(K,q)=>oQ($,K,q),$.decode=(K,q)=>nQ($,K,q),$.encodeAsync=async(K,q)=>pQ($,K,q),$.decodeAsync=async(K,q)=>tQ($,K,q),$.safeEncode=(K,q)=>aQ($,K,q),$.safeDecode=(K,q)=>sQ($,K,q),$.safeEncodeAsync=async(K,q)=>eQ($,K,q),$.safeDecodeAsync=async(K,q)=>$K($,K,q),$.refine=(K,q)=>$.check(rK(K,q)),$.superRefine=(K)=>$.check(iK(K)),$.overwrite=(K)=>$.check(q1(K)),$.optional=()=>G0($),$.exactOptional=()=>vK($),$.nullable=()=>j0($),$.nullish=()=>G0(j0($)),$.nonoptional=(K)=>TK($,K),$.array=()=>Z0($),$.or=(K)=>R8([$,K]),$.and=(K)=>DK($,K),$.transform=(K)=>Y0($,b8(K)),$.default=(K)=>zK($,K),$.prefault=(K)=>OK($,K),$.catch=(K)=>EK($,K),$.pipe=(K)=>Y0($,K),$.readonly=()=>uK($),$.describe=(K)=>{let q=$.clone();return _$.add(q,{description:K}),q},Object.defineProperty($,"description",{get(){return _$.get($)?.description},configurable:!0}),$.meta=(...K)=>{if(K.length===0)return _$.get($);let q=$.clone();return _$.add(q,K[0]),q},$.isOptional=()=>$.safeParse(void 0).success,$.isNullable=()=>$.safeParse(null).success,$.apply=(K)=>K($),$}),Y8=D("_ZodString",($,U)=>{V4.init($,U),c.init($,U),$._zod.processJSONSchema=(q,Q,W)=>UQ($,q,Q,W);let K=$._zod.bag;$.format=K.format??null,$.minLength=K.minimum??null,$.maxLength=K.maximum??null,$.regex=(...q)=>$.check(o4(...q)),$.includes=(...q)=>$.check(t4(...q)),$.startsWith=(...q)=>$.check(a4(...q)),$.endsWith=(...q)=>$.check(s4(...q)),$.min=(...q)=>$.check(v1(...q)),$.max=(...q)=>$.check(D4(...q)),$.length=(...q)=>$.check(P4(...q)),$.nonempty=(...q)=>$.check(v1(1,...q)),$.lowercase=(q)=>$.check(n4(q)),$.uppercase=(q)=>$.check(p4(q)),$.trim=()=>$.check(U6()),$.normalize=(...q)=>$.check($6(...q)),$.toLowerCase=()=>$.check(Q6()),$.toUpperCase=()=>$.check(K6()),$.slugify=()=>$.check(q6())}),Y6=D("ZodString",($,U)=>{V4.init($,U),Y8.init($,U),$.email=(K)=>$.check(k2(H8,K)),$.url=(K)=>$.check(q0(H0,K)),$.jwt=(K)=>$.check(d2(A8,K)),$.emoji=(K)=>$.check(T2(X8,K)),$.guid=(K)=>$.check(K0(J0,K)),$.uuid=(K)=>$.check(R2(M1,K)),$.uuidv4=(K)=>$.check(z2(M1,K)),$.uuidv6=(K)=>$.check(b2(M1,K)),$.uuidv7=(K)=>$.check(O2(M1,K)),$.nanoid=(K)=>$.check(S2(Z8,K)),$.guid=(K)=>$.check(K0(J0,K)),$.cuid=(K)=>$.check(C2(B8,K)),$.cuid2=(K)=>$.check(E2(V8,K)),$.ulid=(K)=>$.check(y2(M8,K)),$.base64=(K)=>$.check(l2(F8,K)),$.base64url=(K)=>$.check(r2(x8,K)),$.xid=(K)=>$.check(g2(D8,K)),$.ksuid=(K)=>$.check(u2(P8,K)),$.ipv4=(K)=>$.check(f2(N8,K)),$.ipv6=(K)=>$.check(m2(L8,K)),$.cidrv4=(K)=>$.check(h2(_8,K)),$.cidrv6=(K)=>$.check(c2(I8,K)),$.e164=(K)=>$.check(i2(w8,K)),$.datetime=(K)=>$.check(fQ(K)),$.date=(K)=>$.check(mQ(K)),$.time=(K)=>$.check(hQ(K)),$.duration=(K)=>$.check(cQ(K))});function G8($){return M7(Y6,$)}var e=D("ZodStringFormat",($,U)=>{s.init($,U),Y8.init($,U)}),H8=D("ZodEmail",($,U)=>{B9.init($,U),e.init($,U)});function DY($){return k2(H8,$)}var J0=D("ZodGUID",($,U)=>{X9.init($,U),e.init($,U)});function PY($){return K0(J0,$)}var M1=D("ZodUUID",($,U)=>{Z9.init($,U),e.init($,U)});function NY($){return R2(M1,$)}function LY($){return z2(M1,$)}function _Y($){return b2(M1,$)}function IY($){return O2(M1,$)}var H0=D("ZodURL",($,U)=>{V9.init($,U),e.init($,U)});function FY($){return q0(H0,$)}function xY($){return q0(H0,{protocol:/^https?$/,hostname:n$.domain,...R.normalizeParams($)})}var X8=D("ZodEmoji",($,U)=>{M9.init($,U),e.init($,U)});function wY($){return T2(X8,$)}var Z8=D("ZodNanoID",($,U)=>{D9.init($,U),e.init($,U)});function AY($){return S2(Z8,$)}var B8=D("ZodCUID",($,U)=>{P9.init($,U),e.init($,U)});function vY($){return C2(B8,$)}var V8=D("ZodCUID2",($,U)=>{N9.init($,U),e.init($,U)});function kY($){return E2(V8,$)}var M8=D("ZodULID",($,U)=>{L9.init($,U),e.init($,U)});function RY($){return y2(M8,$)}var D8=D("ZodXID",($,U)=>{_9.init($,U),e.init($,U)});function zY($){return g2(D8,$)}var P8=D("ZodKSUID",($,U)=>{I9.init($,U),e.init($,U)});function bY($){return u2(P8,$)}var N8=D("ZodIPv4",($,U)=>{v9.init($,U),e.init($,U)});function OY($){return f2(N8,$)}var UK=D("ZodMAC",($,U)=>{R9.init($,U),e.init($,U)});function TY($){return P7(UK,$)}var L8=D("ZodIPv6",($,U)=>{k9.init($,U),e.init($,U)});function SY($){return m2(L8,$)}var _8=D("ZodCIDRv4",($,U)=>{z9.init($,U),e.init($,U)});function CY($){return h2(_8,$)}var I8=D("ZodCIDRv6",($,U)=>{b9.init($,U),e.init($,U)});function EY($){return c2(I8,$)}var F8=D("ZodBase64",($,U)=>{T9.init($,U),e.init($,U)});function yY($){return l2(F8,$)}var x8=D("ZodBase64URL",($,U)=>{S9.init($,U),e.init($,U)});function gY($){return r2(x8,$)}var w8=D("ZodE164",($,U)=>{C9.init($,U),e.init($,U)});function uY($){return i2(w8,$)}var A8=D("ZodJWT",($,U)=>{E9.init($,U),e.init($,U)});function fY($){return d2(A8,$)}var H6=D("ZodCustomStringFormat",($,U)=>{y9.init($,U),e.init($,U)});function mY($,U,K={}){return W6(H6,$,U,K)}function hY($){return W6(H6,"hostname",n$.hostname,$)}function cY($){return W6(H6,"hex",n$.hex,$)}function lY($,U){let K=U?.enc??"hex",q=`${$}_${K}`,Q=n$[q];if(!Q)throw Error(`Unrecognized hash format: ${q}`);return W6(H6,q,Q,U)}var X6=D("ZodNumber",($,U)=>{F2.init($,U),c.init($,U),$._zod.processJSONSchema=(q,Q,W)=>QQ($,q,Q,W),$.gt=(q,Q)=>$.check(B1(q,Q)),$.gte=(q,Q)=>$.check(z$(q,Q)),$.min=(q,Q)=>$.check(z$(q,Q)),$.lt=(q,Q)=>$.check(Z1(q,Q)),$.lte=(q,Q)=>$.check(h$(q,Q)),$.max=(q,Q)=>$.check(h$(q,Q)),$.int=(q)=>$.check(j8(q)),$.safe=(q)=>$.check(j8(q)),$.positive=(q)=>$.check(B1(0,q)),$.nonnegative=(q)=>$.check(z$(0,q)),$.negative=(q)=>$.check(Z1(0,q)),$.nonpositive=(q)=>$.check(h$(0,q)),$.multipleOf=(q,Q)=>$.check(u1(q,Q)),$.step=(q,Q)=>$.check(u1(q,Q)),$.finite=()=>$;let K=$._zod.bag;$.minValue=Math.max(K.minimum??Number.NEGATIVE_INFINITY,K.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,$.maxValue=Math.min(K.maximum??Number.POSITIVE_INFINITY,K.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,$.isInt=(K.format??"").includes("int")||Number.isSafeInteger(K.multipleOf??0.5),$.isFinite=!0,$.format=K.format??null});function QK($){return x7(X6,$)}var L4=D("ZodNumberFormat",($,U)=>{g9.init($,U),X6.init($,U)});function j8($){return A7(L4,$)}function rY($){return v7(L4,$)}function iY($){return k7(L4,$)}function dY($){return R7(L4,$)}function oY($){return z7(L4,$)}var Z6=D("ZodBoolean",($,U)=>{p6.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>KQ($,K,q,Q)});function KK($){return b7(Z6,$)}var B6=D("ZodBigInt",($,U)=>{x2.init($,U),c.init($,U),$._zod.processJSONSchema=(q,Q,W)=>qQ($,q,Q,W),$.gte=(q,Q)=>$.check(z$(q,Q)),$.min=(q,Q)=>$.check(z$(q,Q)),$.gt=(q,Q)=>$.check(B1(q,Q)),$.gte=(q,Q)=>$.check(z$(q,Q)),$.min=(q,Q)=>$.check(z$(q,Q)),$.lt=(q,Q)=>$.check(Z1(q,Q)),$.lte=(q,Q)=>$.check(h$(q,Q)),$.max=(q,Q)=>$.check(h$(q,Q)),$.positive=(q)=>$.check(B1(BigInt(0),q)),$.negative=(q)=>$.check(Z1(BigInt(0),q)),$.nonpositive=(q)=>$.check(h$(BigInt(0),q)),$.nonnegative=(q)=>$.check(z$(BigInt(0),q)),$.multipleOf=(q,Q)=>$.check(u1(q,Q));let K=$._zod.bag;$.minValue=K.minimum??null,$.maxValue=K.maximum??null,$.format=K.format??null});function nY($){return T7(B6,$)}var v8=D("ZodBigIntFormat",($,U)=>{u9.init($,U),B6.init($,U)});function pY($){return C7(v8,$)}function tY($){return E7(v8,$)}var qK=D("ZodSymbol",($,U)=>{f9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>WQ($,K,q,Q)});function aY($){return y7(qK,$)}var WK=D("ZodUndefined",($,U)=>{m9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>GQ($,K,q,Q)});function sY($){return g7(WK,$)}var JK=D("ZodNull",($,U)=>{h9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>JQ($,K,q,Q)});function GK($){return u7(JK,$)}var jK=D("ZodAny",($,U)=>{c9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>HQ($,K,q,Q)});function eY(){return f7(jK)}var YK=D("ZodUnknown",($,U)=>{l9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>XQ($,K,q,Q)});function N4(){return m7(YK)}var HK=D("ZodNever",($,U)=>{r9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>YQ($,K,q,Q)});function k8($){return h7(HK,$)}var XK=D("ZodVoid",($,U)=>{i9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>jQ($,K,q,Q)});function $H($){return c7(XK,$)}var X0=D("ZodDate",($,U)=>{d9.init($,U),c.init($,U),$._zod.processJSONSchema=(q,Q,W)=>ZQ($,q,Q,W),$.min=(q,Q)=>$.check(z$(q,Q)),$.max=(q,Q)=>$.check(h$(q,Q));let K=$._zod.bag;$.minDate=K.minimum?new Date(K.minimum):null,$.maxDate=K.maximum?new Date(K.maximum):null});function UH($){return l7(X0,$)}var ZK=D("ZodArray",($,U)=>{o9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>wQ($,K,q,Q),$.element=U.element,$.min=(K,q)=>$.check(v1(K,q)),$.nonempty=(K)=>$.check(v1(1,K)),$.max=(K,q)=>$.check(D4(K,q)),$.length=(K,q)=>$.check(P4(K,q)),$.unwrap=()=>$.element});function Z0($,U){return d7(ZK,$,U)}function QH($){let U=$._zod.def.shape;return z8(Object.keys(U))}var B0=D("ZodObject",($,U)=>{n9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>AQ($,K,q,Q),R.defineLazy($,"shape",()=>{return U.shape}),$.keyof=()=>z8(Object.keys($._zod.def.shape)),$.catchall=(K)=>$.clone({...$._zod.def,catchall:K}),$.passthrough=()=>$.clone({...$._zod.def,catchall:N4()}),$.loose=()=>$.clone({...$._zod.def,catchall:N4()}),$.strict=()=>$.clone({...$._zod.def,catchall:k8()}),$.strip=()=>$.clone({...$._zod.def,catchall:void 0}),$.extend=(K)=>{return R.extend($,K)},$.safeExtend=(K)=>{return R.safeExtend($,K)},$.merge=(K)=>R.merge($,K),$.pick=(K)=>R.pick($,K),$.omit=(K)=>R.omit($,K),$.partial=(...K)=>R.partial(O8,$,K[0]),$.required=(...K)=>R.required(T8,$,K[0])});function KH($,U){let K={type:"object",shape:$??{},...R.normalizeParams(U)};return new B0(K)}function qH($,U){return new B0({type:"object",shape:$,catchall:k8(),...R.normalizeParams(U)})}function WH($,U){return new B0({type:"object",shape:$,catchall:N4(),...R.normalizeParams(U)})}var V0=D("ZodUnion",($,U)=>{t6.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>e2($,K,q,Q),$.options=U.options});function R8($,U){return new V0({type:"union",options:$,...R.normalizeParams(U)})}var BK=D("ZodXor",($,U)=>{V0.init($,U),p9.init($,U),$._zod.processJSONSchema=(K,q,Q)=>e2($,K,q,Q),$.options=U.options});function JH($,U){return new BK({type:"union",options:$,inclusive:!1,...R.normalizeParams(U)})}var VK=D("ZodDiscriminatedUnion",($,U)=>{V0.init($,U),t9.init($,U)});function GH($,U,K){return new VK({type:"union",options:U,discriminator:$,...R.normalizeParams(K)})}var MK=D("ZodIntersection",($,U)=>{a9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>vQ($,K,q,Q)});function DK($,U){return new MK({type:"intersection",left:$,right:U})}var PK=D("ZodTuple",($,U)=>{w2.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>kQ($,K,q,Q),$.rest=(K)=>$.clone({...$._zod.def,rest:K})});function NK($,U,K){let q=U instanceof h,Q=q?K:U;return new PK({type:"tuple",items:$,rest:q?U:null,...R.normalizeParams(Q)})}var M0=D("ZodRecord",($,U)=>{s9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>RQ($,K,q,Q),$.keyType=U.keyType,$.valueType=U.valueType});function LK($,U,K){return new M0({type:"record",keyType:$,valueType:U,...R.normalizeParams(K)})}function jH($,U,K){let q=R$($);return q._zod.values=void 0,new M0({type:"record",keyType:q,valueType:U,...R.normalizeParams(K)})}function YH($,U,K){return new M0({type:"record",keyType:$,valueType:U,mode:"loose",...R.normalizeParams(K)})}var _K=D("ZodMap",($,U)=>{e9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>FQ($,K,q,Q),$.keyType=U.keyType,$.valueType=U.valueType,$.min=(...K)=>$.check(V1(...K)),$.nonempty=(K)=>$.check(V1(1,K)),$.max=(...K)=>$.check(f1(...K)),$.size=(...K)=>$.check(M4(...K))});function HH($,U,K){return new _K({type:"map",keyType:$,valueType:U,...R.normalizeParams(K)})}var IK=D("ZodSet",($,U)=>{$5.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>xQ($,K,q,Q),$.min=(...K)=>$.check(V1(...K)),$.nonempty=(K)=>$.check(V1(1,K)),$.max=(...K)=>$.check(f1(...K)),$.size=(...K)=>$.check(M4(...K))});function XH($,U){return new IK({type:"set",valueType:$,...R.normalizeParams(U)})}var j6=D("ZodEnum",($,U)=>{U5.init($,U),c.init($,U),$._zod.processJSONSchema=(q,Q,W)=>BQ($,q,Q,W),$.enum=U.entries,$.options=Object.values(U.entries);let K=new Set(Object.keys(U.entries));$.extract=(q,Q)=>{let W={};for(let J of q)if(K.has(J))W[J]=U.entries[J];else throw Error(`Key ${J} not found in enum`);return new j6({...U,checks:[],...R.normalizeParams(Q),entries:W})},$.exclude=(q,Q)=>{let W={...U.entries};for(let J of q)if(K.has(J))delete W[J];else throw Error(`Key ${J} not found in enum`);return new j6({...U,checks:[],...R.normalizeParams(Q),entries:W})}});function z8($,U){let K=Array.isArray($)?Object.fromEntries($.map((q)=>[q,q])):$;return new j6({type:"enum",entries:K,...R.normalizeParams(U)})}function ZH($,U){return new j6({type:"enum",entries:$,...R.normalizeParams(U)})}var FK=D("ZodLiteral",($,U)=>{Q5.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>VQ($,K,q,Q),$.values=new Set(U.values),Object.defineProperty($,"value",{get(){if(U.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return U.values[0]}})});function BH($,U){return new FK({type:"literal",values:Array.isArray($)?$:[$],...R.normalizeParams(U)})}var xK=D("ZodFile",($,U)=>{K5.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>PQ($,K,q,Q),$.min=(K,q)=>$.check(V1(K,q)),$.max=(K,q)=>$.check(f1(K,q)),$.mime=(K,q)=>$.check(e4(Array.isArray(K)?K:[K],q))});function VH($){return o7(xK,$)}var wK=D("ZodTransform",($,U)=>{q5.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>IQ($,K,q,Q),$._zod.parse=(K,q)=>{if(q.direction==="backward")throw new X4($.constructor.name);K.addIssue=(W)=>{if(typeof W==="string")K.issues.push(R.issue(W,K.value,U));else{let J=W;if(J.fatal)J.continue=!1;J.code??(J.code="custom"),J.input??(J.input=K.value),J.inst??(J.inst=$),K.issues.push(R.issue(J))}};let Q=U.transform(K.value,K);if(Q instanceof Promise)return Q.then((W)=>{return K.value=W,K});return K.value=Q,K}});function b8($){return new wK({type:"transform",transform:$})}var O8=D("ZodOptional",($,U)=>{A2.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>$8($,K,q,Q),$.unwrap=()=>$._zod.def.innerType});function G0($){return new O8({type:"optional",innerType:$})}var AK=D("ZodExactOptional",($,U)=>{W5.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>$8($,K,q,Q),$.unwrap=()=>$._zod.def.innerType});function vK($){return new AK({type:"optional",innerType:$})}var kK=D("ZodNullable",($,U)=>{J5.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>zQ($,K,q,Q),$.unwrap=()=>$._zod.def.innerType});function j0($){return new kK({type:"nullable",innerType:$})}function MH($){return G0(j0($))}var RK=D("ZodDefault",($,U)=>{G5.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>OQ($,K,q,Q),$.unwrap=()=>$._zod.def.innerType,$.removeDefault=$.unwrap});function zK($,U){return new RK({type:"default",innerType:$,get defaultValue(){return typeof U==="function"?U():R.shallowClone(U)}})}var bK=D("ZodPrefault",($,U)=>{j5.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>TQ($,K,q,Q),$.unwrap=()=>$._zod.def.innerType});function OK($,U){return new bK({type:"prefault",innerType:$,get defaultValue(){return typeof U==="function"?U():R.shallowClone(U)}})}var T8=D("ZodNonOptional",($,U)=>{Y5.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>bQ($,K,q,Q),$.unwrap=()=>$._zod.def.innerType});function TK($,U){return new T8({type:"nonoptional",innerType:$,...R.normalizeParams(U)})}var SK=D("ZodSuccess",($,U)=>{H5.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>NQ($,K,q,Q),$.unwrap=()=>$._zod.def.innerType});function DH($){return new SK({type:"success",innerType:$})}var CK=D("ZodCatch",($,U)=>{X5.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>SQ($,K,q,Q),$.unwrap=()=>$._zod.def.innerType,$.removeCatch=$.unwrap});function EK($,U){return new CK({type:"catch",innerType:$,catchValue:typeof U==="function"?U:()=>U})}var yK=D("ZodNaN",($,U)=>{Z5.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>MQ($,K,q,Q)});function PH($){return i7(yK,$)}var S8=D("ZodPipe",($,U)=>{B5.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>CQ($,K,q,Q),$.in=U.in,$.out=U.out});function Y0($,U){return new S8({type:"pipe",in:$,out:U})}var C8=D("ZodCodec",($,U)=>{S8.init($,U),a6.init($,U)});function NH($,U,K){return new C8({type:"pipe",in:$,out:U,transform:K.decode,reverseTransform:K.encode})}var gK=D("ZodReadonly",($,U)=>{V5.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>EQ($,K,q,Q),$.unwrap=()=>$._zod.def.innerType});function uK($){return new gK({type:"readonly",innerType:$})}var fK=D("ZodTemplateLiteral",($,U)=>{M5.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>DQ($,K,q,Q)});function LH($,U){return new fK({type:"template_literal",parts:$,...R.normalizeParams(U)})}var mK=D("ZodLazy",($,U)=>{N5.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>gQ($,K,q,Q),$.unwrap=()=>$._zod.def.getter()});function hK($){return new mK({type:"lazy",getter:$})}var cK=D("ZodPromise",($,U)=>{P5.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>yQ($,K,q,Q),$.unwrap=()=>$._zod.def.innerType});function _H($){return new cK({type:"promise",innerType:$})}var lK=D("ZodFunction",($,U)=>{D5.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>_Q($,K,q,Q)});function IH($){return new lK({type:"function",input:Array.isArray($?.input)?NK($?.input):$?.input??Z0(N4()),output:$?.output??N4()})}var D0=D("ZodCustom",($,U)=>{L5.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>LQ($,K,q,Q)});function FH($){let U=new $$({check:"custom"});return U._zod.check=$,U}function xH($,U){return n7(D0,$??(()=>!0),U)}function rK($,U={}){return p7(D0,$,U)}function iK($){return t7($)}var wH=a7,AH=s7;function vH($,U={}){let K=new D0({type:"custom",check:"custom",fn:(q)=>q instanceof $,abort:!0,...R.normalizeParams(U)});return K._zod.bag.Class=$,K._zod.check=(q)=>{if(!(q.value instanceof $))q.issues.push({code:"invalid_type",expected:$.name,input:q.value,inst:K,path:[...K._zod.def.path??[]]})},K}var kH=(...$)=>e7({Codec:C8,Boolean:Z6,String:Y6},...$);function RH($){let U=hK(()=>{return R8([G8($),QK(),KK(),GK(),Z0(U),LK(G8(),U)])});return U}function zH($,U){return Y0(b8($),U)}var DI={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function PI($){Z$({customError:$})}function NI(){return Z$().customError}var dK;(function($){})(dK||(dK={}));var S={...W0,...Q8,iso:G6},LI=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function _I($,U){let K=$.$schema;if(K==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if(K==="http://json-schema.org/draft-07/schema#")return"draft-7";if(K==="http://json-schema.org/draft-04/schema#")return"draft-4";return U??"draft-2020-12"}function II($,U){if(!$.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let K=$.slice(1).split("/").filter(Boolean);if(K.length===0)return U.rootSchema;let q=U.version==="draft-2020-12"?"$defs":"definitions";if(K[0]===q){let Q=K[1];if(!Q||!U.defs[Q])throw Error(`Reference not found: ${$}`);return U.defs[Q]}throw Error(`Reference not found: ${$}`)}function bH($,U){if($.not!==void 0){if(typeof $.not==="object"&&Object.keys($.not).length===0)return S.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if($.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if($.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if($.if!==void 0||$.then!==void 0||$.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if($.dependentSchemas!==void 0||$.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if($.$ref){let Q=$.$ref;if(U.refs.has(Q))return U.refs.get(Q);if(U.processing.has(Q))return S.lazy(()=>{if(!U.refs.has(Q))throw Error(`Circular reference not resolved: ${Q}`);return U.refs.get(Q)});U.processing.add(Q);let W=II(Q,U),J=x$(W,U);return U.refs.set(Q,J),U.processing.delete(Q),J}if($.enum!==void 0){let Q=$.enum;if(U.version==="openapi-3.0"&&$.nullable===!0&&Q.length===1&&Q[0]===null)return S.null();if(Q.length===0)return S.never();if(Q.length===1)return S.literal(Q[0]);if(Q.every((J)=>typeof J==="string"))return S.enum(Q);let W=Q.map((J)=>S.literal(J));if(W.length<2)return W[0];return S.union([W[0],W[1],...W.slice(2)])}if($.const!==void 0)return S.literal($.const);let K=$.type;if(Array.isArray(K)){let Q=K.map((W)=>{let J={...$,type:W};return bH(J,U)});if(Q.length===0)return S.never();if(Q.length===1)return Q[0];return S.union(Q)}if(!K)return S.any();let q;switch(K){case"string":{let Q=S.string();if($.format){let W=$.format;if(W==="email")Q=Q.check(S.email());else if(W==="uri"||W==="uri-reference")Q=Q.check(S.url());else if(W==="uuid"||W==="guid")Q=Q.check(S.uuid());else if(W==="date-time")Q=Q.check(S.iso.datetime());else if(W==="date")Q=Q.check(S.iso.date());else if(W==="time")Q=Q.check(S.iso.time());else if(W==="duration")Q=Q.check(S.iso.duration());else if(W==="ipv4")Q=Q.check(S.ipv4());else if(W==="ipv6")Q=Q.check(S.ipv6());else if(W==="mac")Q=Q.check(S.mac());else if(W==="cidr")Q=Q.check(S.cidrv4());else if(W==="cidr-v6")Q=Q.check(S.cidrv6());else if(W==="base64")Q=Q.check(S.base64());else if(W==="base64url")Q=Q.check(S.base64url());else if(W==="e164")Q=Q.check(S.e164());else if(W==="jwt")Q=Q.check(S.jwt());else if(W==="emoji")Q=Q.check(S.emoji());else if(W==="nanoid")Q=Q.check(S.nanoid());else if(W==="cuid")Q=Q.check(S.cuid());else if(W==="cuid2")Q=Q.check(S.cuid2());else if(W==="ulid")Q=Q.check(S.ulid());else if(W==="xid")Q=Q.check(S.xid());else if(W==="ksuid")Q=Q.check(S.ksuid())}if(typeof $.minLength==="number")Q=Q.min($.minLength);if(typeof $.maxLength==="number")Q=Q.max($.maxLength);if($.pattern)Q=Q.regex(new RegExp($.pattern));q=Q;break}case"number":case"integer":{let Q=K==="integer"?S.number().int():S.number();if(typeof $.minimum==="number")Q=Q.min($.minimum);if(typeof $.maximum==="number")Q=Q.max($.maximum);if(typeof $.exclusiveMinimum==="number")Q=Q.gt($.exclusiveMinimum);else if($.exclusiveMinimum===!0&&typeof $.minimum==="number")Q=Q.gt($.minimum);if(typeof $.exclusiveMaximum==="number")Q=Q.lt($.exclusiveMaximum);else if($.exclusiveMaximum===!0&&typeof $.maximum==="number")Q=Q.lt($.maximum);if(typeof $.multipleOf==="number")Q=Q.multipleOf($.multipleOf);q=Q;break}case"boolean":{q=S.boolean();break}case"null":{q=S.null();break}case"object":{let Q={},W=$.properties||{},J=new Set($.required||[]);for(let[Y,H]of Object.entries(W)){let Z=x$(H,U);Q[Y]=J.has(Y)?Z:Z.optional()}if($.propertyNames){let Y=x$($.propertyNames,U),H=$.additionalProperties&&typeof $.additionalProperties==="object"?x$($.additionalProperties,U):S.any();if(Object.keys(Q).length===0){q=S.record(Y,H);break}let Z=S.object(Q).passthrough(),B=S.looseRecord(Y,H);q=S.intersection(Z,B);break}if($.patternProperties){let Y=$.patternProperties,H=Object.keys(Y),Z=[];for(let M of H){let I=x$(Y[M],U),E=S.string().regex(new RegExp(M));Z.push(S.looseRecord(E,I))}let B=[];if(Object.keys(Q).length>0)B.push(S.object(Q).passthrough());if(B.push(...Z),B.length===0)q=S.object({}).passthrough();else if(B.length===1)q=B[0];else{let M=S.intersection(B[0],B[1]);for(let I=2;I<B.length;I++)M=S.intersection(M,B[I]);q=M}break}let j=S.object(Q);if($.additionalProperties===!1)q=j.strict();else if(typeof $.additionalProperties==="object")q=j.catchall(x$($.additionalProperties,U));else q=j.passthrough();break}case"array":{let{prefixItems:Q,items:W}=$;if(Q&&Array.isArray(Q)){let J=Q.map((Y)=>x$(Y,U)),j=W&&typeof W==="object"&&!Array.isArray(W)?x$(W,U):void 0;if(j)q=S.tuple(J).rest(j);else q=S.tuple(J);if(typeof $.minItems==="number")q=q.check(S.minLength($.minItems));if(typeof $.maxItems==="number")q=q.check(S.maxLength($.maxItems))}else if(Array.isArray(W)){let J=W.map((Y)=>x$(Y,U)),j=$.additionalItems&&typeof $.additionalItems==="object"?x$($.additionalItems,U):void 0;if(j)q=S.tuple(J).rest(j);else q=S.tuple(J);if(typeof $.minItems==="number")q=q.check(S.minLength($.minItems));if(typeof $.maxItems==="number")q=q.check(S.maxLength($.maxItems))}else if(W!==void 0){let J=x$(W,U),j=S.array(J);if(typeof $.minItems==="number")j=j.min($.minItems);if(typeof $.maxItems==="number")j=j.max($.maxItems);q=j}else q=S.array(S.any());break}default:throw Error(`Unsupported type: ${K}`)}if($.description)q=q.describe($.description);if($.default!==void 0)q=q.default($.default);return q}function x$($,U){if(typeof $==="boolean")return $?S.any():S.never();let K=bH($,U),q=$.type||$.enum!==void 0||$.const!==void 0;if($.anyOf&&Array.isArray($.anyOf)){let j=$.anyOf.map((H)=>x$(H,U)),Y=S.union(j);K=q?S.intersection(K,Y):Y}if($.oneOf&&Array.isArray($.oneOf)){let j=$.oneOf.map((H)=>x$(H,U)),Y=S.xor(j);K=q?S.intersection(K,Y):Y}if($.allOf&&Array.isArray($.allOf))if($.allOf.length===0)K=q?K:S.any();else{let j=q?K:x$($.allOf[0],U),Y=q?0:1;for(let H=Y;H<$.allOf.length;H++)j=S.intersection(j,x$($.allOf[H],U));K=j}if($.nullable===!0&&U.version==="openapi-3.0")K=S.nullable(K);if($.readOnly===!0)K=S.readonly(K);let Q={},W=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let j of W)if(j in $)Q[j]=$[j];let J=["contentEncoding","contentMediaType","contentSchema"];for(let j of J)if(j in $)Q[j]=$[j];for(let j of Object.keys($))if(!LI.has(j))Q[j]=$[j];if(Object.keys(Q).length>0)U.registry.add(K,Q);return K}function OH($,U){if(typeof $==="boolean")return $?S.any():S.never();let K=_I($,U?.defaultTarget),q=$.$defs||$.definitions||{},Q={version:K,defs:q,refs:new Map,processing:new Set,rootSchema:$,registry:U?.registry??_$};return x$($,Q)}var oK={};L1(oK,{string:()=>FI,number:()=>xI,date:()=>vI,boolean:()=>wI,bigint:()=>AI});function FI($){return D7(Y6,$)}function xI($){return w7(X6,$)}function wI($){return O7(Z6,$)}function AI($){return S7(B6,$)}function vI($){return r7(X0,$)}Z$(s6());function RI($){return $.secret===!0}function W1($){let U={},K={},q={};for(let[Q,W]of Object.entries($.fields)){let J=W.secret===!0?G.string().min(1):W.schema,j=W.optional===!0?J.optional():J;if(U[Q]=j,RI(W))q[Q]=j;else K[Q]=j}return{...$,fieldsSchema:G.object(U),configSchema:G.object(K),credentialsSchema:G.object(q)}}var nK=W1({kind:"elevenlabs",version:1,nameKey:"connectors.kinds.elevenlabs.name",descriptionKey:"connectors.kinds.elevenlabs.description",icon:"elevenlabs",category:"telephony",module:"ai",docsPath:"/configuracoes/conectores-elevenlabs",auth:{strategy:"fields"},fields:{api_key:{secret:!0,step:"api_key"},agent_numbers:{schema:G.string().default("{}"),step:"numbers"}},setup:[{id:"api_key",titleKey:"connectors.kinds.elevenlabs.setup.api_key"},{id:"numbers",titleKey:"connectors.kinds.elevenlabs.setup.numbers"}],provides:["voice.agent"]});var pK=W1({kind:"retell",version:1,nameKey:"connectors.kinds.retell.name",descriptionKey:"connectors.kinds.retell.description",icon:"retell",category:"telephony",module:"ai",docsPath:"/configuracoes/conectores-retell",auth:{strategy:"fields"},fields:{api_key:{secret:!0,step:"api_key"}},setup:[{id:"api_key",titleKey:"connectors.kinds.retell.setup.api_key"}],provides:["voice.agent"]});var tK=W1({kind:"twilio",version:1,nameKey:"connectors.kinds.twilio.name",descriptionKey:"connectors.kinds.twilio.description",icon:"twilio",category:"telephony",module:"omnichannel",docsPath:"/configuracoes/conectores-twilio",auth:{strategy:"fields"},fields:{account_sid:{schema:G.string().regex(/^AC[0-9a-fA-F]{32}$/u),step:"credentials"},api_key_sid:{schema:G.string().regex(/^SK[0-9a-fA-F]{32}$/u),step:"credentials"},api_key_secret:{secret:!0,step:"credentials"},default_sender:{schema:G.string().regex(/^(MG[0-9a-fA-F]{32}|\+[1-9]\d{6,14})$/u),step:"senders",discover:"senders",optional:!0}},identity:"account_sid",discoverKeys:["verify_services"],setup:[{id:"credentials",titleKey:"connectors.kinds.twilio.setup.credentials",url:"https://console.twilio.com/"},{id:"senders",titleKey:"connectors.kinds.twilio.setup.senders"}],provides:["sms.send","phone.lookup","verify.otp"]});var TH=["us","eu"],aK=W1({kind:"vapi",version:1,nameKey:"connectors.kinds.vapi.name",descriptionKey:"connectors.kinds.vapi.description",icon:"vapi",category:"telephony",module:"ai",docsPath:"/configuracoes/conectores-vapi",auth:{strategy:"fields"},fields:{api_key:{secret:!0,step:"api_key"},region:{schema:G.enum(TH).default("us"),step:"region"}},setup:[{id:"api_key",titleKey:"connectors.kinds.vapi.setup.api_key"},{id:"region",titleKey:"connectors.kinds.vapi.setup.region"}],provides:["voice.agent"],webhook:{verification:"none",signature:"shared_secret_header"}});var sK=W1({kind:"whatsapp_business",version:1,nameKey:"connectors.kinds.whatsapp_business.name",descriptionKey:"connectors.kinds.whatsapp_business.description",icon:"whatsapp",category:"messaging",module:"omnichannel",docsPath:"/configuracoes/conectores-whatsapp",auth:{strategy:"fields"},fields:{app_id:{schema:G.string().regex(/^\d+$/),step:"meta_app"},app_secret:{secret:!0,step:"meta_app"},access_token:{secret:!0,step:"system_user"},waba_id:{schema:G.string().regex(/^\d+$/),step:"waba",discover:"wabas"},business_id:{schema:G.string().regex(/^\d+$/),step:"waba",optional:!0}},identity:"waba_id",setup:[{id:"meta_app",titleKey:"connectors.kinds.whatsapp_business.setup.meta_app",url:"https://developers.facebook.com/apps"},{id:"system_user",titleKey:"connectors.kinds.whatsapp_business.setup.system_user",url:"https://business.facebook.com/settings/system-users"},{id:"waba",titleKey:"connectors.kinds.whatsapp_business.setup.waba"}],provides:["channel.whatsapp","whatsapp.templates"],webhook:{verification:"meta_hub_challenge",signature:"meta_hmac_sha256"}});var l1={whatsapp_business:sK,twilio:tK,elevenlabs:nK,retell:pK,vapi:aK};function P0($){return Object.hasOwn(l1,$)}var N0=Object.keys(l1).filter(($)=>P0($));function bI($){return $.replaceAll("_","-")}function eK($){return $.replaceAll(/_([a-z0-9])/g,(U,K)=>K.toUpperCase())}function _4($){let[U]=$.cli.split(" ");return U??$.cli}function OI($,U){let K=bI($);if(U.secret===!0)return[{source:"stdin",key:`${eK($)}Stdin`,cli:`--${K}-stdin`},{source:"env",key:`${eK($)}Env`,cli:`--${K}-env <VAR>`}];return[{source:"value",key:eK($),cli:`--${K} <value>`}]}function V6($){let U=l1[$].fields;return Object.entries(U).map(([K,q])=>({field:K,secret:q.secret===!0,optional:q.optional===!0,step:q.step,discover:"discover"in q?q.discover:void 0,options:OI(K,q)}))}function L0(){return N0.flatMap(($)=>V6($))}function $q($,U){let K=$[U.key];if(K===void 0||K===!1)return!1;return U.source==="value"||K!==""}function SH($){return L0().some((U)=>U.options.some((K)=>$q($,K)))}function CH($,U){let K=new Set(V6(U).flatMap((W)=>W.options.map((J)=>J.key))),q=new Set,Q=[];for(let W of L0())for(let J of W.options){if(K.has(J.key)||q.has(J.key))continue;if(q.add(J.key),$q($,J))Q.push(_4(J))}return Q}function EH($){return V6($).flatMap((U)=>U.options.map((K)=>_4(K)))}function yH($,U){let K=[];for(let q of V6(U))for(let Q of q.options){if(!$q($,Q))continue;K.push({flag:q,option:Q,source:Q.source,raw:Q.source==="stdin"?"":String($[Q.key])})}return K}function gH(){let $=new Set,U=[];for(let K of L0())for(let q of K.options){if($.has(q.key))continue;$.add(q.key);let Q=K.secret?"credential":"field";U.push({cli:q.cli,description:`${Q} "${K.field}" (step "${K.step}")`})}return U}var _0;function p$($){x(`Error: ${$}`),process.exit(w.USAGE_ERROR)}function E8($){if(!P0($))p$(`unknown connector kind "${$}". Known kinds: ${N0.join(", ")}.`);return $}function u$($){return A("connectors",$)}function TI($){return $.split("_").map((U)=>U.charAt(0).toUpperCase()+U.slice(1)).join(" ")}function SI(){let $=new Set(["--pin"]);for(let U of L0())if(U.secret)$.add(`--${U.field.replaceAll("_","-")}`);return $}var CI=/unknown option '([^']*)'/;function EI($){let U=CI.exec($)?.[1];if(U==null)return $;let K=U.indexOf("=");if(K<0)return $;let q=U.slice(0,K),Q=$.replace(`'${U}'`,`'${q}=<redacted>'`);if(!SI().has(q))return Q;return`${Q}
|
|
92
|
-
Use ${q}-env <VAR> or ${q}-stdin for a credential instead of a literal value.`}function yI($){return $===""?"-":`···${$}`}function gI($,U){let K=l1[$].setup.find((q)=>q.id===U);return K!=null&&"url"in K?K.url:void 0}function Uq($){for(let U of gH())$.option(U.cli,U.description)}function Qq($,U){let K=CH($,U);if(K.length>0)p$(`${K.join(", ")} is not a field of ${U}. Valid flags: ${EH(U).join(", ")}.`)}async function uI($){if($.source==="value")return $.raw;if($.source==="env"){let U=process.env[$.raw];if(U==null||U==="")p$(`environment variable ${$.raw} is not set or empty (${_4($.option)}).`);return U}return(await v$()).replace(/\r?\n$/,"")}async function Kq($,U){let K=yH($,U),q=new Map;for(let J of K){let j=q.get(J.flag.field);if(j==null)q.set(J.flag.field,[J]);else j.push(J)}for(let[J,j]of q)if(j.length>1)p$(`multiple flags provide "${J}": ${j.map((Y)=>_4(Y.option)).join(", ")}. Pass only one.`);let Q=K.filter((J)=>J.source==="stdin");if(Q.length>1)p$(`at most one field may read from stdin per invocation: ${Q.map((J)=>_4(J.option)).join(", ")}.`);let W={};for(let J of K)W[J.flag.field]=await uI(J);return W}function fI($){return $.options.map(_4).join(" or ")}async function mI($,U,K,q){let Q=gI($,U.step),W=Q==null?`${U.field} (${U.step})`:`${U.field} (${U.step}: ${Q})`;if(U.discover!=null){let J=await N(q().connectors.discover({kind:$,key:U.discover,fields:{...K}})),j=J.length===1?J[0]:void 0;if(j!=null)return R4(`Using the only ${U.field}: ${j.label} (${j.value})`),j.value;if(J.length>1){let Y=J.map((H)=>({label:H.description==null?H.label:`${H.label} - ${H.description}`,value:H.value}));return h0(W,Y,_0==null?{output:process.stderr}:{ask:_0,output:process.stderr})}}if(U.secret)return k3(`${W}: `,_0);return AG(`${W}: `,_0)}async function hI($,U,K){let q=[];for(let Q of V6($)){if(U[Q.field]!=null||Q.optional)continue;if(!R6()){q.push(Q);continue}U[Q.field]=await mI($,Q,U,K)}if(q.length>0)p$(`missing required field(s): ${q.map((Q)=>fI(Q)).join(", ")}.`);return U}function cI($,U){if(!b1($))Q1($);let K=s1($);if(U==="json")P({error:K.code,message:K.message,data:K.data,hint:K.hint,retryable:K.retryable});else if(e1(K),K.code==="CONNECTOR_TEST_FAILED")iI(A$(K.data?.checks));process.exit(K.exitCode)}async function qq($,U){try{return await $}catch(K){cI(K,U)}}function lI($,U){if(!b1($))Q1($);let K=s1($);if(K.code!=="CONNECTOR_IN_USE")Q1($);let q=A$(K.data?.channels).map((Q)=>({id:l(Q.id)??"",name:l(Q.name)??""}));if(U==="json")P({error:K.code,message:K.message,channels:q,hint:K.hint,retryable:K.retryable});else e1(K),y(["Channel ID","Name"],q.map((Q)=>({"Channel ID":Q.id,Name:Q.name})));process.exit(K.exitCode)}function rI($){return $.map((U)=>({Check:U.id,OK:U.ok?"yes":"no",Message:U.message??""}))}function iI($){y(["Check","OK","Message"],$.map((U)=>({Check:l(U.id)??"",OK:U.ok===!0?"yes":"no",Message:l(U.message)??""})))}function dI($){if($.ready)return"ready";let U=[];if(!$.verified)U.push("not verified");if(!$.registered)U.push("not registered");if(!$.name_approved)U.push("name pending");return U.join(", ")}function oI($){let U=[{title:"Connector",rows:[{label:"ID",value:$.id},{label:"Name",value:$.name},{label:"Kind",value:$.kind},{label:"Status",value:$.status},{label:"Account",value:$.account_label},{label:"External ID",value:$.external_id},{label:"Created",value:new Date($.created_at).toLocaleString()},{label:"Updated",value:new Date($.updated_at).toLocaleString()},{label:"Last checked",value:$.last_checked_at==null?null:new Date($.last_checked_at).toLocaleString()},{label:"Last error",value:$.last_error==null?null:`${$.last_error.code}: ${$.last_error.message}`}]},{title:"Config",rows:Object.entries($.config).map(([K,q])=>({label:K,value:q}))},{title:"Credentials",rows:Object.entries($.secret_suffixes).map(([K,q])=>({label:K,value:yI(q)}))},{title:"Webhook",rows:[{label:"URL",value:$.webhook.url},{label:"Verify token",value:$.webhook.verify_token==null?null:"configured"},{label:"Verified at",value:$.webhook.verified_at==null?null:new Date($.webhook.verified_at).toLocaleString()}]}];if($.channels.length>0)U.push({title:"Channels",rows:$.channels.map((K)=>({label:K.name,value:`${K.channel_type} (${K.id})`}))});return U}function nI($,U){let K={...$,webhook:{url:$.webhook.url,verify_token_configured:$.webhook.verify_token!=null,verified_at:$.webhook.verified_at}};return U?O(K,U):K}function pI($,U){let K={...$,webhook:$.webhook===null?null:{status:$.webhook.status,reason:$.webhook.reason,url:$.webhook.url}};return U?O(K,U):K}function tI($){if($===null)return;if($.status==="subscribed"){R4("Webhook subscribed automatically.");return}let U=$.reason==null?"":` (${$.reason})`;if(R4(`Webhook needs manual setup${U}.`),$.url!=null)R4(` URL: ${$.url}`);R4(" Verify token: see the connector's page in the web app (never printed here).")}function aI($){let U=Q$($.properties)??{},K=new Set(Array.isArray($.required)?$.required.filter((q)=>typeof q==="string"):[]);return Object.entries(U).map(([q,Q])=>{let W=Q$(Q)??{},J=W["x-niva-secret"]===!0||W.writeOnly===!0;return{name:q,access:J?"secret":"public",required:K.has(q),step:l(W["x-niva-step"])??""}})}function sI($,U,K){$.command("types").description("List connector types, or describe one kind's fields and setup steps").action(async()=>{let{format:Q,fields:W}=L(U.opts()),J=await N(K().connectors.types.list());if(Q==="json"){P(W?J.map((j)=>O(j,W)):J);return}y(["Kind","Name","Capabilities"],J.map((j)=>({Kind:j.kind,Name:TI(j.kind),Capabilities:j.provides.join(", ")})))}).command("describe <kind>").description("Show a kind's fields (public/secret, required) and setup steps with their URLs").action(async(Q)=>{let{format:W,fields:J}=L(U.opts()),j=E8(Q),Y=await N(K().connectors.types.describe({kind:j}));if(W==="json"){P(J?O(Y,J):Y);return}o([{title:"Type",rows:[{label:"Kind",value:Y.kind},{label:"Version",value:Y.version},{label:"Auth",value:Y.auth_strategy},{label:"Category",value:Y.category},{label:"Module",value:Y.module},{label:"Docs",value:Y.docs_path},{label:"Provides",value:Y.provides.join(", ")},{label:"Discover",value:Y.discover.join(", ")||"-"}]}]),y(["Field","Access","Required","Step"],aI(Y.fields_json_schema).map((H)=>({Field:H.name,Access:H.access,Required:H.required?"yes":"no",Step:H.step}))),y(["Setup step","Title","URL"],Y.setup.map((H)=>({"Setup step":H.id,Title:H.title_key,URL:H.url??"-"})))})}function eI($,U,K){$.command("list").description("List connectors with their kind, status, account and channel count").action(async()=>{let{format:q,fields:Q}=L(U.opts()),W=await N(K().connectors.list());if(q==="json"){P(Q?W.map((J)=>O(J,Q)):W);return}y(["ID","Name","Kind","Status","Account","Channels"],W.map((J)=>({ID:J.id,Name:J.name,Kind:J.kind,Status:J.status,Account:J.account_label??"-",Channels:J.channel_count})))})}function $F($,U,K){$.command("show <id>").description("Show a connector's details, credentials suffixes and webhook status").action(async(q)=>{let{format:Q,fields:W}=L(U.opts()),J=await N(K().connectors.get({connector_id:u$(q)}));if(Q==="json"){P(nI(J,W));return}o(oI(J))})}function UF($){if($===void 0)return"-";return $?"yes":"no"}function QF($,U,K){let q=$.command("agents").description("Voice agents of a connector: list them, activate or deactivate an ElevenLabs agent's number");q.command("list <id>",{isDefault:!0}).description("List the voice agents of a connector that provides voice.agent; Ready says whether an activated agent can take calls").action(async(Q)=>{let{format:W,fields:J}=L(U.opts()),j=await N(K().connectors.voiceAgents({connector_id:u$(Q)}));if(W==="json"){P(J?{agents:j.agents.map((Y)=>O(Y,J))}:j);return}y(["ID","Name","Channel","Ready","Updated"],j.agents.map((Y)=>({ID:Y.id,Name:Y.name,Channel:Y.channel,Ready:UF(Y.ready),Updated:Y.updated_at?.toISOString()??"-"})))});for(let[Q,W]of[["activate",!1],["deactivate",!0]])q.command(`${Q} <id> <agent_id>`).description(W?"Deactivate an ElevenLabs agent: NIVA removes the SIP number it registered for the agent. Plans can no longer call it.":"Activate an ElevenLabs agent: NIVA registers a SIP number on the account and binds it to the agent. Needed before a plan can call it.").action(async(J,j)=>{let{format:Y,fields:H}=L(U.opts()),Z=await qq(K().connectors.agentNumbers.set({connector_id:u$(J),agent_id:j,remove:W}),Y);if(Y==="json"){P(H?O(Z,H):Z);return}T(`Agent ${j} ${W?"deactivated":"activated"} on connector ${Z.name} (${Z.id})`)})}function KF($,U,K){$.command("senders <id>").description("List the SMS senders (Messaging Services and numbers) of a connector that provides sms.send").action(async(q)=>{let{format:Q,fields:W}=L(U.opts()),J=await N(K().connectors.senders.list({connector_id:u$(q)}));if(Q==="json"){P(W?J.map((j)=>O(j,W)):J);return}y(["ID","Label","Kind","Number","SMS","Brazil"],J.map((j)=>({ID:j.id,Label:j.label,Kind:j.kind==="messaging_service"?"Messaging Service":"Number",Number:j.number??"-",SMS:j.capabilities.sms?"yes":"no",Brazil:j.brazil_p2p_only?"p2p only":"-"})))})}function qF($,U,K){$.command("verify-services <id>").description("List the Twilio Verify Services of a connector that provides verify.otp").action(async(q)=>{let{format:Q,fields:W}=L(U.opts()),J=await N(K().connectors.verifyServices.list({connector_id:u$(q)}));if(Q==="json"){P(W?J.map((j)=>O(j,W)):J);return}y(["SID","Name","Code length","Channels"],J.map((j)=>({SID:j.sid,Name:j.friendly_name,"Code length":j.code_length??"-",Channels:j.channels.join(", ")})))})}function WF($,U,K){$.command("test <id>").description("Run a connector's health test; exits 1 when any check fails").action(async(q)=>{let{format:Q,fields:W}=L(U.opts()),J=await N(K().connectors.test({connector_id:u$(q)}));if(Q==="json")P(W?O(J,W):J);else if(y(["Check","OK","Message"],rI(J.health.checks)),J.health.ok)T(`Connector test passed: ${J.status}`);else x(`Connector test failed: ${J.health.code} - ${J.health.message}`);if(!J.health.ok)process.exit(w.GENERAL_ERROR)})}function JF($,U,K){let q=$.command("discover <kind> <key>").description("Run a kind's discover function with credentials not yet stored (e.g. wabas)");Uq(q),q.action(async(Q,W,J)=>{let j=E8(Q);Qq(J,j);let{format:Y,fields:H}=L(U.opts()),Z=await Kq(J,j),B=await N(K().connectors.discover({kind:j,key:W,fields:Z}));if(Y==="json"){P(H?B.map((M)=>O(M,H)):B);return}y(["Value","Label","Description"],B.map((M)=>({Value:M.value,Label:M.label,Description:M.description??"-"})))})}function GF($,U,K){let q=$.command("create <kind>").description("Create a connector; credentials come from --<field>-env/--<field>-stdin or a hidden prompt").requiredOption("--name <name>","Human label shown in the UI");Uq(q),q.action(async(Q,W)=>{let J=E8(Q);Qq(W,J);let{format:j,fields:Y}=L(U.opts()),H=await Kq(W,J),Z=await hI(J,H,K),B=await qq(K().connectors.create({kind:J,name:W.name,fields:Z}),j);if(j==="json"){P(pI(B,Y));return}T(`Connector created: ${B.name} (${B.id})`),tI(B.webhook)})}function jF($,U,K){let q=$.command("update <id>").description("Rename a connector or rotate fields; only the flags given are sent").option("--name <name>","New human label");Uq(q),q.action(async(Q,W)=>{let{format:J,fields:j}=L(U.opts()),Y={connector_id:u$(Q)};if(W.name!=null)Y.name=W.name;if(SH(W)){let Z=await N(K().connectors.get({connector_id:u$(Q)})),B=E8(Z.kind);Qq(W,B),Y.fields=await Kq(W,B)}let H=await qq(K().connectors.update(Y),J);if(J==="json"){P(j?O(H,j):H);return}T(`Connector updated: ${H.name} (${H.id})`)})}function YF($,U,K){for(let[q,Q]of[["enable",!0],["disable",!1]])$.command(`${q} <id>`).description(`${Q?"Enable":"Disable"} a connector`).action(async(W)=>{let{format:J,fields:j}=L(U.opts()),Y=await N(K().connectors.setEnabled({connector_id:u$(W),enabled:Q}));if(J==="json"){P(j?O(Y,j):Y);return}T(`Connector ${Q?"enabled":"disabled"}: ${Y.name} (${Y.status})`)})}function HF($,U,K){$.command("delete <id>").description("Delete a connector; blocked and explained when a channel still references it").action(async(q)=>{let{format:Q}=L(U.opts()),W=U.opts().yes===!0;await d$(`Delete connector ${q}?`,{yes:W});try{await K().connectors.delete({connector_id:u$(q)})}catch(J){lI(J,Q)}if(Q==="json"){P({id:q,deleted:!0});return}T(`Connector deleted: ${q}`)})}function XF($,U,K){let q=$.command("numbers <id>").description("WhatsApp phone numbers of a connector, with readiness and the bound channel").option("--refresh","Bypass the 5-minute cache and read the numbers again");q.action(async(Q,W)=>{let{format:J,fields:j}=L(U.opts()),Y=await N(K().connectors.phoneNumbers.list({connector_id:u$(Q),refresh:W.refresh===!0}));if(J==="json"){P(j?Y.map((H)=>O(H,j)):Y);return}y(["ID","Number","Name","Readiness","Channel"],Y.map((H)=>({ID:H.id,Number:H.display_phone_number,Name:H.verified_name,Readiness:dI(H.readiness),Channel:H.channel==null?"-":H.channel.name})))}),q.command("request-code <id> <phone_number_id>").description("Ask Meta to send the phone number's ownership code by SMS or voice").requiredOption("--method <method>","sms or voice").option("--language <language>","Language for the message","pt_BR").action(async(Q,W,J)=>{let j=ZF(J.method),{format:Y}=L(U.opts());if(await N(K().connectors.phoneNumbers.requestCode({connector_id:u$(Q),phone_number_id:W,method:j,language:J.language})),Y==="json"){P({success:!0,phone_number_id:W});return}T(`Verification code requested for ${W} by ${J.method}.`)}),q.command("verify <id> <phone_number_id>").description("Submit the 6-digit ownership code Meta sent").requiredOption("--code <code>","The 6-digit code").action(async(Q,W,J)=>{if(!/^\d{6}$/u.test(J.code))p$("--code must be the 6-digit code Meta sent.");let{format:j}=L(U.opts());if(await N(K().connectors.phoneNumbers.verifyCode({connector_id:u$(Q),phone_number_id:W,code:J.code})),j==="json"){P({success:!0,phone_number_id:W});return}T(`Phone number verified: ${W}`)}),q.command("register <id> <phone_number_id>").description("Register a phone number on the Cloud API with its 6-digit PIN").option("--pin-stdin","Read the PIN from stdin").option("--pin-env <VAR>","Read the PIN from an environment variable").action(async(Q,W,J)=>{let j=await VF(J),{format:Y}=L(U.opts());if(await N(K().connectors.phoneNumbers.register({connector_id:u$(Q),phone_number_id:W,pin:j})),Y==="json"){P({success:!0,phone_number_id:W});return}T(`Phone number registered: ${W}`)})}function ZF($){let U=$.toUpperCase();if(U==="SMS"||U==="VOICE")return U;p$(`--method must be sms or voice (got "${$}").`)}async function BF($){if($.pinEnv!=null){let U=process.env[$.pinEnv];if(U==null||U==="")p$(`environment variable ${$.pinEnv} is not set or empty.`);return U}if($.pinStdin===!0)return(await v$()).replace(/\r?\n$/,"");if(R6())return k3("WhatsApp registration PIN (6 digits): ",_0);p$("no PIN given - pass --pin-env <VAR>, --pin-stdin, or run from a TTY.")}async function VF($){if($.pinStdin===!0&&$.pinEnv!=null)p$("--pin-stdin and --pin-env are mutually exclusive.");let U=await BF($);if(!/^\d{6}$/u.test(U))p$("the PIN must be the 6-digit number Meta gave you.");return U}function uH($,U){let K=$.createCommand("connectors").description("Connectors (WhatsApp, and the kinds that follow)");K.configureOutput({outputError:(q,Q)=>Q(EI(q))}),$.addCommand(K),sI(K,$,U),eI(K,$,U),$F(K,$,U),QF(K,$,U),KF(K,$,U),qF(K,$,U),WF(K,$,U),JF(K,$,U),GF(K,$,U),jF(K,$,U),YF(K,$,U),HF(K,$,U),XF(K,$,U)}var J1=N1(I1(),1);function I0($){return $.option("--from <date>","Start date (YYYY-MM-DD or ISO 8601)").option("--to <date>","End date (YYYY-MM-DD or ISO 8601)").option("--plan <id>","Filter by visual plan ID").option("--phone <id>","Filter by phone number ID")}function MF($){if($==null)return"";if($.missed>0)return`${$.total} (${$.missed} missed)`;return`${$.total}`}function DF($,U){if($>U)return"↑";if($<U)return"↓";return"→"}function PF($){let U=$.avg_score!=null?Number($.avg_score):null,K=$.previous_avg_score!=null?Number($.previous_avg_score):null,q=U!=null&&U>0?"+":"",Q=U!=null?`${q}${U.toFixed(2)}`:"—",W="";if(K!=null&&U!=null){let J=DF(U,K);W=` (prev: ${K>0?"+":""}${K.toFixed(2)} ${J})`}return` Avg Score: ${Q}${W}`}function fH($,U){let K=$.command("dashboard").description("Dashboard and monitoring");K.command("metrics").description("Get call metrics for a date range").option("--from <date>","Start date (YYYY-MM-DD or ISO 8601)").option("--to <date>","End date (YYYY-MM-DD or ISO 8601)").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),{date_from:J,date_to:j}=G1(q),Y=await N(U().dashboard.metrics({date_from:J,date_to:j}));if(Q==="json"){let H=W?O(Y,W):Y;P(H);return}if(console.log(`Period: ${J} → ${j}`),console.log(`Total calls: ${Y.current.total_calls}`),console.log(`Answered: ${Y.current.answered}`),console.log(`Missed: ${Y.current.missed}`),Y.current.avg_duration_ms!=null)console.log(`Avg duration: ${f$(Y.current.avg_duration_ms)}`)}),I0(K.command("sentiment").description("Show sentiment distribution for calls")).action(async(q)=>{let{format:Q,fields:W}=L($.opts()),{date_from:J,date_to:j}=G1(q),Y=await N(U().dashboard.speechSentiment({date_from:J,date_to:j,visual_plan_id:A("visual_plans",q.plan),channel_id:A("channels",q.phone)}));if(Q==="json"){let B=W?O(Y,W):Y;P(B);return}if(console.log(J1.default.bold("Sentiment Overview")),console.log(`Analyzed: ${Y.analyzed_count} calls`),!Y.has_enough_data){z(`
|
|
93
|
-
Not enough data (need ${Y.minimum_required}, have ${Y.analyzed_count})`);return}console.log("");let H=Y.distribution,Z=Math.max(H.positive,H.neutral,H.negative,H.mixed);U1(J1.default.green("positive"),H.positive,Z),U1(J1.default.yellow("neutral"),H.neutral,Z),U1(J1.default.red("negative"),H.negative,Z),U1(J1.default.blue("mixed"),H.mixed,Z),console.log(""),console.log(PF(Y))}),I0(K.command("topics").description("Show top discussed topics from call transcriptions")).option("--limit <n>","Max topics to show","15").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),{date_from:J,date_to:j}=G1(q),Y=await N(U().dashboard.speechTopics({date_from:J,date_to:j,limit:Number(q.limit),visual_plan_id:A("visual_plans",q.plan),channel_id:A("channels",q.phone)}));if(Q==="json"){let Z=W?O(Y,W):Y;P(Z);return}if(console.log(`${J1.default.bold("Top Topics")} (${Y.analyzed_count} analyzed)`),!Y.has_enough_data||Y.topics.length===0){z(`
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
No data available.`);return}console.log(""),y(["Plan","Total","Answered","Avg Duration"],Y.map((H)=>({Plan:H.visual_plan_name??"—",Total:H.total,Answered:`${H.answered} (${H.total>0?Math.round(H.answered/H.total*100):0}%)`,"Avg Duration":f$(H.avg_duration_ms)})))})}import{readFile as NF}from"node:fs/promises";var mH=1e4;function hH($,U){let K=$.command("dnc").description("Manage the do-not-call list");K.command("list").description("List do-not-call entries").option("--search <t>","Search by phone number").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),J=await N(U().dialerDnc.list({page:Number(q.page),limit:Number(q.limit),search:q.search}));if(Q==="json"){P(W?J.items.map((j)=>O(j,W)):J);return}y(["ID","Phone","Reason","Added"],J.items.map((j)=>({ID:j.id,Phone:j.phone_number,Reason:j.reason??"—",Added:j1(j.created_at)}))),H$(J)}),K.command("add <phone>").description("Add a number to the do-not-call list").option("--reason <r>","Reason for the block").action(async(q,Q)=>{let{format:W}=L($.opts()),J=await N(U().dialerDnc.add({phone_number:q,reason:Q.reason}));if(W==="json"){P(J);return}T(`Added ${J.phone_number} to DNC`)}),K.command("remove <ids...>").description("Remove do-not-call entries").action(async(q)=>{let{format:Q}=L($.opts());if(q.length===1){let J=await N(U().dialerDnc.remove({dnc_id:A("dialer_dnc",q[0])}));if(Q==="json"){P(J);return}T("Removed DNC entry");return}let W=await N(U().dialerDnc.bulkRemove({ids:A("dialer_dnc",q)}));if(Q==="json"){P(W);return}T(`Removed ${W.removed}`)}),K.command("check <phone>").description("Check if a number is on the DNC list (exit 0 = listed, 3 = not listed)").action(async(q)=>{let{format:Q}=L($.opts()),W=await N(U().dialerDnc.list({page:1,limit:20,search:q})),J=q.replaceAll(/\D/g,""),j=J===""?void 0:W.items.find((Y)=>{let H=String(Y.phone_number).replaceAll(/\D/g,"");return H===J||H.endsWith(J)});if(j!=null){if(Q==="json")P(j);else o([{title:"DNC entry",rows:[{label:"ID",value:j.id},{label:"Phone",value:j.phone_number},{label:"Reason",value:j.reason??"—"},{label:"Added",value:new Date(j.created_at).toLocaleString()}]}]);return}if(Q==="json")P({listed:!1});else z("Not in DNC list.");process.exit(w.NOT_FOUND)}),K.command("import <file>").description("Bulk-import DNC numbers (one per line; blank / # lines skipped)").option("--reason <r>","Reason applied to every imported number").action(async(q,Q)=>{let{format:W}=L($.opts()),j=(await NF(q,"utf-8")).split(/\r\n|\n|\r/).map((Z)=>Z.trim()).filter((Z)=>Z.length>0&&!Z.startsWith("#"));if(j.length===0)x("No phone numbers found in file"),process.exit(w.USAGE_ERROR);let Y=0,H=0;for(let Z=0;Z<j.length;Z+=mH){let B=j.slice(Z,Z+mH),M=await N(U().dialerDnc.bulkImport({numbers:B,reason:Q.reason}));Y+=M.added,H+=M.skipped}if(W==="json"){P({added:Y,skipped:H});return}T(`Added ${Y}, skipped ${H}`)})}var LF=/^(?:([^<>]*)<([^<>\s]+)>|([^<>\s]+))$/;function _F($){let U=LF.exec($.trim());if(U==null)return null;let K=U[2]??U[3]??"";if(!G.email().safeParse(K).success)return null;let q=U[1]?.trim().replaceAll(/^"|"$/g,"")??"";return{name:q===""?null:q,address:K}}var xg=G.string().trim().max(255).refine(($)=>_F($)!=null,{message:"Invalid sender"});var cH={"acl_rule.created":{},"acl_rule.updated":{},"acl_rule.deleted":{},"acl_rule.enabled":{},"acl_rule.disabled":{},"api_key.created":{},"api_key.revoked":{},"api_key.rotated":{},"api_key.rotation_finished":{},"api_key.updated":{},"audio_file.uploaded":{},"audio_file.updated":{},"audio_file.deleted":{},"audio_file.tts_generated":{},"audio_file.tts_regenerated":{},"audio_file.restored":{},"audio_file.purged":{},"audit_log.purged":{},"destination.created":{},"destination.updated":{},"destination.deleted":{},"holiday.created":{},"holiday.updated":{},"holiday.deleted":{},"holiday_group.created":{},"holiday_group.updated":{},"holiday_group.deleted":{},"holiday_group.imported":{},"invitation.created":{},"invitation.accepted":{},"invitation.revoked":{},"invitation.resent":{},"organization.created":{},"organization.updated":{},"organization.deleted":{},"oauth.authorized":{},"oauth.denied":{},"oauth_grant.revoked":{},"secret.created":{},"secret.updated":{},"secret.deleted":{},"connector.created":{},"connector.updated":{},"connector.deleted":{},"connector.tested":{},"connector.enabled":{},"connector.disabled":{},"connector.sms_sent":{},"connector.phone_number.code_requested":{},"connector.phone_number.verified":{},"connector.phone_number.registered":{},"connector.phone_number.assigned":{},"connector.phone_number.removed":{},"signal.created":{},"signal.updated":{},"signal.deleted":{},"signal.restored":{},"signal.purged":{},"insight_view.created":{},"insight_view.updated":{},"insight_view.deleted":{},"insight_view.reordered":{},"dashboard.updated":{},"role.created":{},"role.updated":{},"role.deleted":{},"channel.created":{},"channel.updated":{},"channel.deleted":{},"channel.activated":{},"channel.deactivated":{},"channel.restored":{},"channel.purged":{},"schedule.created":{},"schedule.updated":{},"schedule.deleted":{},"schedule.restored":{},"schedule.purged":{},"user.created":{},"user.signup":{},"user.login":{},"user.logout":{},"user.password_changed":{},"user.password_reset_requested":{},"user.password_reset_completed":{},"user.account_unlocked":{},"user.second_factor_enrollment_started":{},"user.second_factor_enrolled":{},"user.passkey_registered":{},"user.passkey_renamed":{},"user.passkey_removed":{},"user.second_factor_reset":{},"user.recovery_codes_regenerated":{},"user.session_revoked":{},"user.sessions_revoked":{},"user.role_changed":{},"user.suspended":{},"user.activated":{},"user.removed":{},"block_preset.created":{},"block_preset.updated":{},"block_preset.deleted":{},"saved_recipe.created":{},"saved_recipe.updated":{},"saved_recipe.deleted":{},"visual_plan.created":{},"visual_plan.cloned":{},"visual_plan.updated":{},"visual_plan.deleted":{},"visual_plan.imported":{},"visual_plan.published":{},"visual_plan.restored":{},"visual_plan.purged":{},"webhook_endpoint.created":{},"webhook_endpoint.updated":{},"webhook_endpoint.deleted":{},"webhook_endpoint.secret_rotated":{},"webhook_delivery.retried":{},"system.initialized":{},"system.fs_started":{},"system.fs_restarted":{},"system.engine_restarted":{},"system.update_requested":{},"system.update_cancelled":{},"platform_settings.updated":{},"storage_config.updated":{},"recording_storage.updated":{},"storage_cache.purged":{},"platform_admin.assigned":{},"platform_admin.revoked":{},"platform_admin.owner_transferred":{},"platform_admin.mfa_policy_updated":{},"org_settings.updated":{},"org_settings.limits_updated":{},"org_plan.modules_updated":{},"org_plan.ai_credential_updated":{},"tenant_module.enabled":{},"tenant_module.disabled":{},"tenant_module.limits_updated":{},"contact.updated":{},"dialer_campaign.created":{},"dialer_campaign.updated":{},"dialer_campaign.deleted":{},"dialer_campaign.controlled":{},"dialer_contact.added":{},"dialer_contact.updated":{},"dialer_contact.cancelled":{},"dialer_contact.requeued":{},"dialer_contact.removed":{},"dialer_import.created":{},"dialer_dnc.added":{},"dialer_dnc.removed":{},"dialer_dnc.imported":{},"analysis_template.created":{},"analysis_template.updated":{},"analysis_template.deleted":{},"ai_settings.updated":{},"ws_session.created":{},"ws_test_chat_session.created":{},"ws_test_chat_session.stopped":{},"call.originate":{retention:"operational"},"call_record.voice_purged":{},"call_record.recording_url_issued":{},"call_record.recording_downloaded":{},"notification.deleted":{},"notification_channel.created":{},"notification_channel.updated":{},"notification_channel.deleted":{},"notification_channel.tested":{},"notification_preference.updated":{},"notification_preference.reset":{},"screen_pop.fetched":{retention:"operational"}},IF=Object.keys(cH);var Wq=G.object({}).default({}),Jq=G.object({phone_number_id:G.string().min(1),voice_enabled:G.boolean().default(!0),chat_enabled:G.boolean().default(!0),sip_username:G.string().optional(),sip_password_encrypted:G.string().optional(),sip_password_iv:G.string().optional(),session_timeout_minutes:G.number().int().min(5).max(10080).default(1440),business_name:G.string().optional(),display_phone_number:G.string().optional(),last_webhook_received_at:G.iso.datetime().optional(),last_webhook_message_id:G.string().optional(),last_webhook_status_id:G.string().optional(),last_webhook_phone_number_id:G.string().optional(),last_webhook_error:G.string().optional()}),Gq=G.object({bot_token:G.string().min(1),webhook_secret:G.string().min(1),allow_groups:G.boolean().default(!1),session_timeout_minutes:G.number().int().min(5).max(10080).default(1440),bot_username:G.string().optional()}),lH={sip:Wq,telegram:Gq,whatsapp:Jq,webchat:G.object({}).default({}),sms:G.object({}).default({}),rcs:G.object({}).default({})};var M6=["sip"],F0=["telegram","webchat","sms","rcs"],D6=["whatsapp"],jq=[...M6,...F0,...D6],rH=[...M6,...D6],iH=[...F0,...D6];var Cg=new Set(M6),Eg=new Set(D6);var dH=String.raw`(?:25[0-5]|2[0-4]\d|[01]?\d\d?)`,oH=String.raw`(?:${dH}\.){3}${dH}`,wF=String.raw`${oH}(?:\/(?:3[0-2]|[12]?\d))?`,lg=new RegExp(`^${oH}$`);var w$="[0-9a-fA-F]{1,4}",AF=[`(?:${w$}:){7}${w$}`,`(?:${w$}:){1,7}:`,`(?:${w$}:){1,6}:${w$}`,`(?:${w$}:){1,5}(?::${w$}){1,2}`,`(?:${w$}:){1,4}(?::${w$}){1,3}`,`(?:${w$}:){1,3}(?::${w$}){1,4}`,`(?:${w$}:){1,2}(?::${w$}){1,5}`,`${w$}:(?::${w$}){1,6}`,`:(?::${w$}){1,7}`,"::(?:ffff(?::0{1,4})?:)?"],vF=`(?:${AF.join("|")})`,kF=String.raw`${vF}(?:\/(?:12[0-8]|1[01]\d|[1-9]?\d))?`,rg=new RegExp(`^(?:${wF}|${kF})$`);function RF($){let U=$;if(U==null||typeof U!=="object")throw Error("Execution plan must be a JSON object with { version, startNodeId, nodes, adjacency }");if(!("nodes"in U)||U.nodes==null||typeof U.nodes!=="object"){let K;if(!("nodes"in U))K="missing";else if(Array.isArray(U.nodes))K="an array";else K=typeof U.nodes;throw Error(`Execution plan "nodes" must be an object keyed by node ID, not ${K}`)}if(!("adjacency"in U)||U.adjacency==null||typeof U.adjacency!=="object")throw Error('Execution plan "adjacency" must be an object mapping source → { handle → target }')}function Yq($){RF($);let U=Object.entries($.nodes).map(([q,Q])=>({id:q,type:Q.type,label:Q.label,varName:Q.varName,position:{x:0,y:0},config:Q.config})),K=[];for(let[q,Q]of Object.entries($.adjacency))for(let[W,J]of Object.entries(Q))K.push({id:`${q}-${W}-${J}`,source:q,sourceHandle:W,target:J,targetHandle:"in"});return nH({nodes:U,edges:K,viewport:{x:0,y:0,zoom:1}})}function nH($){let U=$.nodes.find((Q)=>Q.type==="start");if(U==null||typeof U.config.channelType==="string")return $;let q=$.edges.some((Q)=>Q.source===U.id&&Q.sourceHandle==="next")?"voice":"both";return{...$,nodes:$.nodes.map((Q)=>Q===U?{...Q,config:{...Q.config,channelType:q}}:Q)}}var I4=3600;var R1=["none","both","caller"],Hq=G.object({callerSpeechMs:G.number().int().min(0),ivrSpeechMs:G.number().int().min(0),version:G.number().int().min(1)});var r1=["post_call","live"],Xq=G.object({startByte:G.number().int().min(0),endByte:G.number().int().min(0),openedAtMs:G.number().int().min(0)}).refine(($)=>$.endByte>=$.startByte,{message:"endByte must be greater than or equal to startByte",path:["endByte"]}),pH=G.object({nodeId:G.string().min(1),kind:G.enum(["recording","transcription","analysis"]),atByte:G.number().int().min(0),atMs:G.number().int().min(0),patch:G.record(G.string(),G.unknown())}),tH=G.object({samplingPercentage:G.number().int().min(0).max(100).describe("Recording sampling percentage"),transcriptionSamplingPercentage:G.number().int().min(0).max(100).default(100).describe("Transcription sampling percentage among selected recordings"),transcriptionEnabled:G.boolean().describe("Enable transcription"),transcriptionLanguage:G.string().nullable().describe("Transcription language"),transcriptionMinDurationSeconds:G.number().int().min(0).max(I4).describe("Minimum transcription duration"),transcriptionSpeechRequirement:G.enum(R1).default("none").describe("Which sides must have spoken for automatic transcription"),transcriptionType:G.enum(r1).default("post_call").describe("Transcription type: after the call ends, or live during the whole transcription window"),anonymizeEnabled:G.boolean().describe("Anonymize the transcript"),speechAnalyticsEnabled:G.boolean().describe("Enable speech analytics"),sentimentEnabled:G.boolean().optional().describe("Enable sentiment analysis"),topicDetectionTopics:G.array(G.string()).describe("Topic detection topics"),intentDetectionIntents:G.array(G.string()).describe("Intent detection intents"),autoAnalysisEnabled:G.boolean().describe("Enable structured analyses"),autoAnalysisInheritOrg:G.boolean().describe("Inherit structured analyses from the organization"),autoAnalysisIds:G.array(G.string()).describe("Structured analysis IDs")}).transform(($)=>({...$,sentimentEnabled:$.sentimentEnabled??$.speechAnalyticsEnabled})),zF=G.object({speechAnalyticsEnabled:G.boolean(),sentimentEnabled:G.boolean().optional(),topicDetectionTopics:G.array(G.string()),intentDetectionIntents:G.array(G.string()),autoAnalysisEnabled:G.boolean(),autoAnalysisIds:G.array(G.string())}).transform(($)=>({...$,sentimentEnabled:$.sentimentEnabled??$.speechAnalyticsEnabled}));var bF=G.object({usePlan:G.boolean().default(!0).describe("Use plan recording profile"),samplingPercentage:G.number().int().min(0).max(100).default(100).describe("Recording sampling percentage"),transcriptionSamplingPercentage:G.number().int().min(0).max(100).default(100).describe("Transcription sampling percentage"),transcriptionEnabled:G.boolean().default(!1).describe("Enable transcription"),transcriptionLanguage:G.string().default("").describe("Transcription language"),transcriptionMinDurationSeconds:G.number().int().min(0).max(I4).default(0).describe("Minimum transcription duration"),transcriptionSpeechRequirement:G.enum(R1).default("none").describe("Which sides must have spoken for automatic transcription"),transcriptionType:G.enum(r1).default("post_call").describe("Transcription type: after the call ends, or live during the whole transcription window"),anonymizeEnabled:G.boolean().default(!1).describe("Anonymize the transcript"),speechAnalyticsEnabled:G.boolean().default(!1).describe("Enable speech analytics"),sentimentEnabled:G.boolean().optional().describe("Enable sentiment analysis"),topicDetectionTopics:G.array(G.string()).default([]).describe("Topic detection topics"),intentDetectionIntents:G.array(G.string()).default([]).describe("Intent detection intents"),autoAnalysisEnabled:G.boolean().default(!1).describe("Enable structured analyses"),autoAnalysisIds:G.array(G.string()).default([]).describe("Structured analysis IDs")}).transform(($)=>({...$,sentimentEnabled:$.sentimentEnabled??$.speechAnalyticsEnabled})),aH=G.object({sampleRate:G.number().int().positive(),channels:G.number().int().positive(),bitsPerSample:G.number().int().positive()});var OF=G.object({sampled:G.boolean(),transcriptionSampled:G.boolean().optional(),profile:tH,recordingFormat:aH.optional(),recordingIntervals:Xq.array().default([]),transcriptionWindows:Xq.array().default([]),directives:pH.array().default([]),voiceActivity:Hq.optional()});var TF=["recordingEnabled","samplingPercentage","transcriptionSamplingPercentage","transcriptionEnabled","transcriptionLanguage","transcriptionMinDurationSeconds","transcriptionSpeechRequirement","transcriptionType","anonymizeEnabled","speechAnalyticsEnabled","sentimentEnabled","topicDetectionTopics","intentDetectionIntents","structuredAnalysisEnabled","structuredAnalysisIds"];function Bq($,U,K,q,Q=!1){let W=SF(q),J=new Map(K.map((H)=>[H.id,H])),j=uF(U,Q),Y={};return CF({startNodeId:$,planState:j,nodesById:J,adjacency:q,incoming:W,result:Y}),Y}function SF($){let U=new Map;for(let[K,q]of $)for(let Q of q.values()){let W=U.get(Q)??[];U.set(Q,[...W,K])}return U}function CF($){let{startNodeId:U,planState:K,nodesById:q,adjacency:Q,incoming:W,result:J}=$,j=[U],Y=new Set(j),H=0,Z=Math.max(20,q.size*q.size*4);while(j.length>0&&H++<Z){let B=j.shift();if(B===void 0)continue;Y.delete(B);let M=q.get(B);if(M===void 0)continue;let I=EF(B,K,M,W,J);if(tF(J[B],I))continue;J[B]=I,gF(j,Y,Q.get(B)?.values()??[])}}function EF($,U,K,q,Q){let W=(q.get($)??[]).map((j)=>Q[j]).filter((j)=>j!==void 0),J=yF(W,U);return fF(J,K)}function yF($,U){let K=$[0];return K===void 0?U:$.slice(1).reduce((q,Q)=>nF(q,Q),K)}function gF($,U,K){for(let q of K){if(U.has(q))continue;$.push(q),U.add(q)}}function uF($,U){let K={kind:"plan"};return{recordingEnabled:I$(U,K),samplingPercentage:I$($.samplingPercentage,K),transcriptionSamplingPercentage:I$($.transcriptionSamplingPercentage,K),transcriptionEnabled:I$($.transcriptionEnabled,K),transcriptionLanguage:I$($.transcriptionLanguage,K),transcriptionMinDurationSeconds:I$($.transcriptionMinDurationSeconds,K),transcriptionSpeechRequirement:I$($.transcriptionSpeechRequirement,K),transcriptionType:I$($.transcriptionType,K),anonymizeEnabled:I$($.anonymizeEnabled,K),speechAnalyticsEnabled:I$($.speechAnalyticsEnabled,K),sentimentEnabled:I$($.sentimentEnabled,K),topicDetectionTopics:I$([...$.topicDetectionTopics],K),intentDetectionIntents:I$([...$.intentDetectionIntents],K),structuredAnalysisEnabled:I$($.autoAnalysisEnabled,K),structuredAnalysisIds:I$([...$.autoAnalysisIds],K)}}function fF($,U){let K=mF(U),q={kind:"node",nodeId:U.id,nodeLabel:U.label};return{recordingEnabled:O$($.recordingEnabled,K.recordingEnabled,q),samplingPercentage:O$($.samplingPercentage,K.samplingPercentage,q),transcriptionSamplingPercentage:O$($.transcriptionSamplingPercentage,K.transcriptionSamplingPercentage,q),transcriptionEnabled:O$($.transcriptionEnabled,K.transcriptionEnabled,q),transcriptionLanguage:O$($.transcriptionLanguage,K.transcriptionLanguage,q),transcriptionMinDurationSeconds:O$($.transcriptionMinDurationSeconds,K.transcriptionMinDurationSeconds,q),transcriptionSpeechRequirement:O$($.transcriptionSpeechRequirement,K.transcriptionSpeechRequirement,q),transcriptionType:O$($.transcriptionType,K.transcriptionType,q),anonymizeEnabled:O$($.anonymizeEnabled,K.anonymizeEnabled,q),speechAnalyticsEnabled:O$($.speechAnalyticsEnabled,K.speechAnalyticsEnabled,q),sentimentEnabled:O$($.sentimentEnabled,K.sentimentEnabled,q),topicDetectionTopics:O$($.topicDetectionTopics,K.topicDetectionTopics,q),intentDetectionIntents:O$($.intentDetectionIntents,K.intentDetectionIntents,q),structuredAnalysisEnabled:O$($.structuredAnalysisEnabled,K.structuredAnalysisEnabled,q),structuredAnalysisIds:O$($.structuredAnalysisIds,K.structuredAnalysisIds,q)}}function mF($){if($.type==="recording")return hF($.config);if($.type==="transcription")return cF($.config);if($.type==="analysis")return lF($.config);return{}}function hF($){let U={},K=$.enabled;if(typeof K==="boolean")U.recordingEnabled=K;let q=$.samplingPercentage;if(typeof q==="number")U.samplingPercentage=q;return U}function cF($){let U={},K=$.enabled;if(typeof K==="boolean")U.transcriptionEnabled=K;let q=$.samplingPercentage;if(typeof q==="number")U.transcriptionSamplingPercentage=q;let Q=$.language;if(typeof Q==="string")U.transcriptionLanguage=Q.trim()||null;let W=$.minDurationSeconds;if(typeof W==="number")U.transcriptionMinDurationSeconds=W;let J=$.speechRequirement;if(iF(J))U.transcriptionSpeechRequirement=J;let j=$.transcriptionType;if(oF(j))U.transcriptionType=j;let Y=$.anonymizeEnabled;if(typeof Y==="boolean")U.anonymizeEnabled=Y;let{speechAnalyticsEnabled:H,sentimentEnabled:Z}=$;if(typeof H==="boolean")U.speechAnalyticsEnabled=H;if(typeof Z==="boolean")U.sentimentEnabled=Z;else if(typeof H==="boolean")U.sentimentEnabled=H;return U}function lF($){let U={},K=$.speechAnalyticsEnabled,q=$.sentimentEnabled;if(typeof K==="boolean")U.speechAnalyticsEnabled=K;if(typeof q==="boolean")U.sentimentEnabled=q;else if(q===void 0&&typeof K==="boolean")U.sentimentEnabled=K;let Q=$.topicDetectionTopics;if(Zq(Q))U.topicDetectionTopics=Q;let W=$.intentDetectionIntents;if(Zq(W))U.intentDetectionIntents=W;let J=$.structuredAnalysisEnabled;if(typeof J==="boolean")U.structuredAnalysisEnabled=J;let j=$.structuredAnalysisIds;if(Zq(j))U.structuredAnalysisIds=j;return U}var rF=R1;function iF($){return typeof $==="string"&&rF.includes($)}var dF=r1;function oF($){return typeof $==="string"&&dF.includes($)}function Zq($){return Array.isArray($)&&$.every((U)=>typeof U==="string")}function O$($,U,K){return U===void 0?$:I$(U,K)}function I$($,U){return{kind:"known",value:$,origin:U}}function nF($,U){return{recordingEnabled:T$($.recordingEnabled,U.recordingEnabled),samplingPercentage:T$($.samplingPercentage,U.samplingPercentage),transcriptionSamplingPercentage:T$($.transcriptionSamplingPercentage,U.transcriptionSamplingPercentage),transcriptionEnabled:T$($.transcriptionEnabled,U.transcriptionEnabled),transcriptionLanguage:T$($.transcriptionLanguage,U.transcriptionLanguage),transcriptionMinDurationSeconds:T$($.transcriptionMinDurationSeconds,U.transcriptionMinDurationSeconds),transcriptionSpeechRequirement:T$($.transcriptionSpeechRequirement,U.transcriptionSpeechRequirement),transcriptionType:T$($.transcriptionType,U.transcriptionType),anonymizeEnabled:T$($.anonymizeEnabled,U.anonymizeEnabled),speechAnalyticsEnabled:T$($.speechAnalyticsEnabled,U.speechAnalyticsEnabled),sentimentEnabled:T$($.sentimentEnabled,U.sentimentEnabled),topicDetectionTopics:T$($.topicDetectionTopics,U.topicDetectionTopics),intentDetectionIntents:T$($.intentDetectionIntents,U.intentDetectionIntents),structuredAnalysisEnabled:T$($.structuredAnalysisEnabled,U.structuredAnalysisEnabled),structuredAnalysisIds:T$($.structuredAnalysisIds,U.structuredAnalysisIds)}}function T$($,U){let K=[...sH($),...sH(U)],q=[];for(let Q of K)if(!q.some((W)=>eH(W.value,Q.value)))q.push(Q);if(q.length===1){let Q=pF($,U,q[0].viaNodeLabel);return I$(q[0].value,Q)}return{kind:"indeterminate",branches:q}}function pF($,U,K){if($.kind==="known")return $.origin;if(U.kind==="known")return U.origin;return{kind:"node",nodeId:"",nodeLabel:K}}function sH($){if($.kind==="indeterminate")return $.branches;let U=$.origin.kind==="plan"?"__plan__":$.origin.nodeLabel;return[{value:$.value,viaNodeLabel:U}]}function eH($,U){return JSON.stringify($)===JSON.stringify(U)}function tF($,U){if($===void 0)return!1;return TF.every((K)=>eH($[K],U[K]))}function C($){let U=$.producedVariables;return{meta:{...$.meta,inputs:$.meta.type==="start"?[]:[{key:"in",labelKey:"editor:handles.in"}],producedVariables:typeof U==="function"?(q)=>U(q):U,defaultConfig:$.configSchema.parse({})},configSchema:$.configSchema,producedVariables:$.producedVariables}}var $X=["volume","weekday_hour","composition","plans","topics","intents"],UX=G.string().regex(/^signal:sig_[A-Za-z0-9]+$/),aF=G.union([G.enum($X),UX]),sF=G.number().int().min(1).max(4);var eF=G.object({id:G.string(),type:G.string(),x:G.number(),y:G.number()}),$x=G.object({source:G.string(),target:G.string()}),Ux=G.object({nodes:G.array(eF),edges:G.array($x)});var QX=["voice","chat","both"];var KX=["pre","post"];var qX=["voicemail","announcement","ivr","screening","unknown"];var x0=["channels","calls","registrations","codecs","modules","aliases"];var Qx=new Set(["phone","telephone","telefone","fone","celular","cel","mobile","movel","numero","number","num","tel","msisdn","whatsapp","telefone celular","numero de telefone"]),Kx=new Set(["name","nome","cliente","contato","contact","nome completo","razao social","full name"]);function qx($){return $.normalize("NFD").replaceAll(/[\u0300-\u036F]/g,"").toLowerCase().replaceAll(/[\s\-_]+/g," ").trim()}function Wx($){return $.normalize("NFD").replaceAll(/[\u0300-\u036F]/g,"").toLowerCase().replaceAll(/[^a-z0-9]+/g,"_").replace(/^_/,"").replace(/_$/,"")}function WX($){return Qx.has($)||$.includes("telefone")||$.includes("phone")||$.includes("celular")}function Jx($){return Kx.has($)}function Vq($){let U={},K={},q=new Set,Q=!1,W=!1;function J(j){let Y=j,H=2;while(q.has(Y))Y=`${j}_${String(H)}`,H+=1;return q.add(Y),Y}for(let j of $){let Y=qx(j);if(Y===""){U[j]="ignore";continue}if(WX(Y)&&!Q){U[j]="phone",Q=!0;continue}if(Jx(Y)&&!W&&!WX(Y)){U[j]="name",W=!0;continue}let H=Wx(j);if(H===""){U[j]="ignore";continue}U[j]="custom",K[j]=J(H)}return{roles:U,customNames:K}}var F4={_nodes:{start:{name:"Start",description:"Where every call begins — receives caller ID, DID, and timestamp"},playback:{name:"Playback",description:"Plays a message using text-to-speech or an audio file"},ivr:{name:"IVR Menu",description:"Presents a menu and routes the call based on the digit pressed"},collectDigits:{name:"Collect Digits",description:"Collects a sequence of digits like CPF, account number, or PIN"},transfer:{name:"Transfer",description:"Bridges or redirects the call to an agent, queue, or external number"},hangup:{name:"Hang Up",description:"Terminates the call — place at the end of each plan path"},timeRouting:{name:"Schedule",description:"Checks the current time against a schedule to route on/off hours"},switchCase:{name:"Condition",description:"Evaluates a variable against regex patterns to pick a path"},trafficSplit:{name:"Traffic Split",description:"Distributes calls across several paths by percentage — A/B testing, load balancing between destinations and canary rollout"},setVariable:{name:"Set Variable",description:"Saves a value to reuse later during plan execution"},sequence:{name:"Sequence",description:"Generates sequential numbers for protocols, tickets, or any identifier — DB-backed, never regresses"},counter:{name:"Counter",description:"Counts attempts, events, or anything else — per call or across calls, with an optional limit output"},httpRequest:{name:"HTTP Request",description:"Calls a REST API and stores the response for downstream nodes"},webhook:{name:"Webhook",description:"Fires an HTTP call to an external system and moves on without waiting"},dataTransform:{name:"Transform Data",description:"Applies text, number, date, list, phone, and speech operations to a value without writing code"},sendDtmf:{name:"Send DTMF",description:"Sends DTMF tones to a bridged channel or PBX"},subPlan:{name:"Sub-Plan",description:"Delegates execution to another published plan and returns"},aiAgent:{name:"AI Agent",description:"Hands the call to an AI agent for free-form conversation"},retellAgent:{name:"Retell Agent",description:"Hands the call to a Retell voice agent"},vapiAgent:{name:"Vapi Agent",description:"Hands the call to a Vapi voice assistant"},elevenlabsAgent:{name:"ElevenLabs Agent",description:"Hands the call to an ElevenLabs voice agent"},voiceRecognition:{name:"Voice Recognition",description:"Listens to the caller, transcribes speech, and routes by intent"},tell:{name:"Message",description:"Says something to the user — plays audio in voice, sends a message in chat"},menu:{name:"Menu",description:"Presents options and routes by the user's choice — DTMF in voice, buttons in chat"},capture:{name:"Capture",description:"Collects user input — DTMF digits or speech in voice, text in chat"},routeAi:{name:"AI Classifier",description:"Classifies text via AI and routes by intent — a smart condition"},channelRouter:{name:"Channel",description:"Routes the plan based on the active channel mode (voice or chat)"},apiSwitch:{name:"API Switch",description:"Plays a prompt, collects digits, calls an API, and routes by response attribute (legacy)"},enableRecord:{name:"Enable Recording",description:"Activates call recording during plan execution with sampling and analysis options (legacy)"},recording:{name:"Recording",description:"Starts or stops recording from this point in the plan"},transcription:{name:"Transcription",description:"Chooses the transcription scope from this point in the plan"},analysis:{name:"Analysis",description:"Chooses analyses for all available transcription; each block overrides only defined fields"},whatsappTemplate:{name:"Send WhatsApp template",description:"Sends an approved Meta template through WhatsApp Business, in a voice call or in chat"},sendSms:{name:"Send SMS",description:"Sends a text message through Twilio, in a voice call or in chat"},phoneLookup:{name:"Phone lookup",description:"Checks a number's format and, optionally, its line type and carrier through Twilio Lookup"},verifyCode:{name:"Verify code",description:"Sends a verification code through Twilio Verify and checks it, in a voice call or in chat"},addToDnc:{name:"Add to DNC",description:"Adds the contact's number to the organization's do-not-call list — opt-out from inside the plan"}},_audio:{tts:{text:"Text to synthesize into speech.",voice:"TTS voice ID (e.g., 'pt-BR-FranciscaNeural').",model:"TTS model to use (default: 'edge')."},file:{id:"Audio file ID from the audio library.",name:"Display name of the audio file.",path:"Storage path of the audio file."},url:{value:"Audio URL fetched at call time. Supports {{variables}}; secrets are not allowed.",fallbackTts:"Spoken when the URL fails. Absent means take the error output."}},start:{autoAnswer:"Auto-answer incoming call before processing. Disable for pre-answer routing.",channelType:"Plan channel type."},playback:{audio:"Audio to play. Use TTS (text-to-speech) or a pre-recorded audio file."},hangup:{cause:"SIP hangup cause code (e.g., 'NORMAL_CLEARING'). Omit for default."},ivr:{audio:"Audio prompt played before collecting DTMF input.",timeout:"Seconds to wait for DTMF input after audio finishes (1-60).",maxAttempts:"Maximum retry attempts before following the error output (1-10)."},collectDigits:{audio:"Audio prompt played before collecting digits.",minDigits:"Minimum number of digits required (1-20).",maxDigits:"Maximum number of digits to collect (1-20).",terminator:"Key that terminates digit collection (e.g., '#'). Single character.",timeout:"Seconds to wait for the first digit after audio finishes (1-60).",interDigitTimeout:"Seconds to wait between consecutive digits (1-30).",maxAttempts:"Maximum retry attempts on invalid input (1-10).",invalidAudio:"Audio played when input fails regex validation. Optional.",regex:"Regex pattern to validate collected digits. Empty means accept any.",resetDigit:"Key that clears collected digits and restarts. Single character. Empty to disable."},transfer:{method:"Transfer method. 'bridge' keeps call control; 'transfer' hands off completely.",destinations:"SIP URIs or phone numbers to dial. At least one required. Tried in order.",timeout:"Ring timeout in seconds per destination (5-120). Omit for carrier default.",attachedData:"Key/value pairs delivered to the agent at transfer (screen-pop). Values support templates."},timeRouting:{scheduleId:"Schedule ID for time-based routing. Routes to onHours/offHours/holiday outputs."},switchCase:{expression:"Template expression to evaluate, e.g., '{{ivr.digits}}'. Matched against case patterns.",cases:"List of patterns to match. Each creates a dynamic output handle 'match:<pattern>'."},trafficSplit:{paths:"Weighted paths. Each creates a dynamic output handle 'path:<name>'.",mode:"'contact' keeps the same contact on the same path (stateless hash); 'call' draws per call (stateless, approximate); 'exact' rotates through a Redis counter so the proportion closes even at low volume."},setVariable:{assignments:"List of variable assignments. At least one required."},counter:{name:"Counter name. Supports templates, e.g. 'attempts_{{start.callerid}}'.",action:"Operation applied to the counter. 'reset' sets it to zero and ignores step.",step:"Amount added or subtracted on each execution (1-1000000). Ignored when the action is 'reset'.",limit:"Value that routes to the 'limitReached' output once the counter reaches it. Empty means count only.",scope:"'call' starts from zero on every call; 'plan' persists across the calls of one plan; 'organization' persists across every plan of the organization.",ttlSeconds:"Lifetime in seconds of a 'plan' or 'organization' counter (60-31536000). Applied when the key is created, so counting does not renew the window."},httpRequest:{method:"HTTP method for the request.",url:"Request URL. Supports template expressions, e.g., 'https://api.example.com/{{start.callerid}}'.",headers:"HTTP headers as key-value pairs. Values support template expressions.",body:"Request body (JSON string). Template expressions allowed. Only for POST/PUT/PATCH.",timeout:"Request timeout in milliseconds. Omit for default."},webhook:{method:"HTTP method for the request.",url:"Destination URL. Supports template expressions, e.g., 'https://hooks.example.com/{{start.callerid}}'.",headers:"HTTP headers as key-value pairs. Values support template expressions.",body:"Request body (JSON string). Template expressions allowed. Only for POST/PUT/PATCH/DELETE."},dataTransform:{steps:"Ordered list of transformation steps. Each step transforms a value and saves the result under a name.",onError:"What to do when a step fails: 'error' follows the error output, 'empty' continues with an empty value."},subPlan:{planId:"ID of a published visual plan to execute as a subplan. Must be published."},sendDtmf:{digits:"DTMF digits to send (0-9, *, #). Supports template expressions."},aiAgent:{agent_id:"SipPulse AI agent ID to invoke. Required for execution.",agent_name:"Display name for the AI agent (used in logs and UI).",additional_instructions:"Extra instructions appended to the agent's system prompt.",variables:"Key-value pairs passed to the agent as context variables.",initial_message:"First message the agent speaks when the conversation starts.",max_duration_minutes:"Maximum conversation duration in minutes (1-60). Call ends on timeout."},retellAgent:{connector_id:"Connector that provides the voice.agent capability, such as a Retell account.",agent_id:"ID of the Retell agent that answers the call. Required for execution.",agent_name:"Display name of the chosen agent, used in logs and the editor.",variables:"Key-value pairs sent to the agent. Every value supports {{variables}}.",max_duration_minutes:"Maximum call duration in minutes (1-60). The bridge ends on timeout.",result_wait_seconds:"How long to wait for Retell's post-call extraction before continuing (0-60)."},vapiAgent:{connector_id:"Connector that provides the voice.agent capability, such as a Vapi account.",assistant_id:"ID of the Vapi assistant that answers the call. Required for execution.",assistant_name:"Display name of the chosen assistant, used in logs and the editor.",variables:"Key-value pairs sent to the agent. Every value supports {{variables}}.",max_duration_minutes:"Maximum call duration in minutes (1-60). The bridge ends on timeout.",result_wait_seconds:"How long to wait for Vapi's end of call report before continuing (0-60)."},elevenlabsAgent:{connector_id:"Connector that provides the voice.agent capability, such as an ElevenLabs account.",agent_id:"ID of the ElevenLabs agent that answers the call. Required for execution.",agent_name:"Display name of the chosen agent, used in logs and the editor.",variables:"Key-value pairs sent to the agent as X-<name> SIP headers. Every value supports {{variables}}.",max_duration_minutes:"Maximum call duration in minutes (1-60). The bridge ends on timeout.",result_wait_seconds:"How long to wait for ElevenLabs' post-call analysis before continuing (0-60)."},voiceRecognition:{mode:"'intent' classifies speech into configured intents; 'capture' transcribes without classification.",prompt:"Audio prompt played before listening for speech.",intents:"List of intents the LLM should classify speech into. Each creates a dynamic output. Only used in intent mode.",classification_instructions:"Additional instructions for the LLM intent classifier. Only used in intent mode.",listen:"Listening configuration: silence timeout, max duration, language, beep.",processing_audio:"Audio played while the AI processes the speech. Optional.",retry:"Retry behavior: max attempts and alternative prompt when speech is not recognized."},tell:{audio:"Audio to play via TTS, a pre-recorded file, or a remote URL. Used in voice plans.",content:"Message content to send in chat. Used in chat plans."},menu:{options:"Menu options. Each creates a dynamic output handle.",audio:"Voice audio prompt played before collecting DTMF input.",text:"Chat message text displayed above buttons. Supports template expressions.",voiceTimeout:"Seconds to wait for DTMF input in voice mode (1-60).",maxAttempts:"Maximum retry attempts for invalid input before following noMatch (1-10).",invalidMessage:"Chat message sent when input doesn't match any option. Supports template expressions."},capture:{audio:"Audio prompt played before collecting input in voice mode.",voiceMethod:"Voice input method: 'dtmf' for digits, 'speech' for ASR transcription (requires AI).",minDigits:"Minimum number of DTMF digits required (1-20).",maxDigits:"Maximum number of DTMF digits to collect (1-20).",terminators:"Key that terminates digit collection (e.g., '#').",voiceTimeout:"Seconds to wait for input in voice mode (1-60).",listen:"Listening configuration for speech capture: silence detection, max duration, language.",processing_audio:"Audio played while ASR processes the speech. Optional.",retryAudio:"Audio played on retry instead of main prompt. Falls back to main if not set.",text:"Chat prompt message sent before waiting for user input.",validation:"Regex pattern to validate chat text input. Invalid input triggers retry.",invalidMessage:"Chat message sent when input fails validation.",maxAttempts:"Maximum retry attempts for invalid or empty input (1-10)."},routeAi:{input:"Template expression to evaluate. The resolved text is classified by AI.",intents:"List of intents the AI should classify the input into. Each creates a dynamic output handle.",instructions:"Additional instructions for the AI intent classifier."},channelRouter:{},apiSwitch:{audio:"Audio prompt played before collecting digits.",chatText:"Text prompt for chat mode. Supports {{variables}}.",timeout:"Seconds to wait for digit input (1-60).",maxAttempts:"Maximum retry attempts for digit collection (1-10).",digitRegex:"Regex to validate DTMF input. Empty means accept any.",method:"HTTP method for the API request.",url:"API endpoint URL. Supports {{variables}} including collected digits as {{digits}}.",headers:"HTTP headers as key-value pairs.",body:"Request body (JSON). Supports {{variables}}. Only for POST/PUT.",requestTimeout:"HTTP request timeout in milliseconds.",attribute:"JSON attribute name from the API response to match against cases.",cases:"Possible attribute values. Each creates a dynamic output handle 'match:<value>'."},enableRecord:{percentage:"Percentage of calls to record (0-100). 100 records all calls.",minDuration:"Minimum call duration in seconds before recording starts. 0 for immediate.",analyzeCalls:"Enable post-call AI analysis (requires AI module)."},recording:{enabled:"Start or stop recording from this point",samplingPercentage:"Recording sampling percentage when recording starts"},transcription:{enabled:"Start or stop transcription at this point",samplingPercentage:"Percentage of selected recordings that will be transcribed",scope:"Transcription scope: 'from_here' uses audio recorded from this point (default/legacy); 'whole_recording' includes all audio already recorded and continues until transcription is disabled",language:"Language applied to the whole transcription",minDurationSeconds:"Minimum duration applied to the whole transcription",speechRequirement:"Skip calls without conversation, applied to the whole transcription: none, both (caller and IVR) or caller (caller only)",anonymizeEnabled:"Anonymize the whole transcript",sentimentEnabled:"Enable sentiment analysis for all available transcription; omitted fields remain inherited",transcriptionType:"Transcription type: 'post_call' transcribes when the call ends; 'live' also transcribes during the call, billed per recorded minute"},analysis:{speechAnalyticsEnabled:"Enable call summary for all available transcription; omitted fields remain inherited",sentimentEnabled:"Enable sentiment analysis for all available transcription; omitted fields remain inherited",topicDetectionTopics:"Topics for all available transcription; omitted fields remain inherited",intentDetectionIntents:"Intents for all available transcription; omitted fields remain inherited",structuredAnalysisEnabled:"Enable structured analyses for all available transcription; omitted fields remain inherited",structuredAnalysisIds:"Structured analysis IDs for all available transcription; omitted fields remain inherited"},whatsappTemplate:{connectorId:"Connector that provides the WhatsApp templates capability (whatsapp.templates).",phoneNumberId:"Number the message is sent from, one of the connector's numbers.",template:"Approved template to send, by name and language (e.g. boleto / pt_BR).",to:"Recipient. Supports {{variables}}. A number without a country code gets the block's default country code.",defaultCountry:"Country that completes numbers written without a country code. Empty uses the organization's default country.",parameters:"Template variable values. Keys: variable number or name; a media header takes the URL; a URL button takes the suffix. Supports {{variables}}."},sendSms:{connector_id:"Connector that provides the sms.send capability, such as a Twilio account.",from:"Sender. Empty uses the connector's default sender; otherwise a Messaging Service SID (MG...) or an E.164 number.",to:"Recipient. Supports {{variables}}. A number without a country code gets the block's default country code.",default_country:"Country that completes numbers written without a country code. Empty uses the organization's default country.",body:"Message text. Supports {{variables}}; secrets are not allowed in the body.",transliterate:"Replace accented letters by their base letter before sending, so the message fits 160 characters per SMS instead of 70."},phoneLookup:{connector_id:"Connector that provides the phone.lookup capability, such as a Twilio account.",number:"Number to look up. Supports {{variables}}. A number without a country code gets the block's default country code.",default_country:"Country that completes numbers written without a country code. Empty uses the organization's default country.",line_type:"Also fetch line type and carrier. Twilio charges US$ 0,008 per query; format validation alone is free.",line_type_error:"Twilio's own code and message when it could not identify the line type; empty when it did."},verifyCode:{connector_id:"Connector that provides the verify.otp capability, such as a Twilio account.",service_sid:"Verify Service SID (VA...) whose code length and sender configuration the block uses.",to:"Recipient. Supports {{variables}}. A number without a country code gets the block's default country code.",default_country:"Country that completes numbers written without a country code. Empty uses the organization's default country.",channel:"How the code reaches the contact: sms, whatsapp or call.",prompt:"Audio prompt asking for the code, played with the plan's voice. In chat, its text is sent.",max_attempts:"Maximum wrong-code attempts before the block leaves by rejected (1-5).",timeout_seconds:"Seconds to wait for the code after the prompt (1-60)."},addToDnc:{reason:"Optional short reason recorded on the DNC entry (max 128 chars). Plain text, no templates.",phoneOverride:"Optional number/template to add instead of the auto-resolved one. Supports {{variables}}. Empty auto-resolves the dialer contact, then the caller ID."}};var y8={_nodes:{start:{name:"Início",description:"Onde toda chamada começa — recebe caller ID, DID e timestamp"},playback:{name:"Reprodução",description:"Reproduz uma mensagem usando TTS ou arquivo de áudio"},ivr:{name:"Menu IVR",description:"Apresenta um menu e roteia a chamada pelo dígito pressionado"},collectDigits:{name:"Coletar Dígitos",description:"Coleta uma sequência de dígitos como CPF, número de conta ou PIN"},transfer:{name:"Transferência",description:"Conecta ou redireciona a chamada para agente, fila ou número externo"},hangup:{name:"Desligar",description:"Encerra a chamada — coloque no final de cada caminho do plano"},timeRouting:{name:"Agenda",description:"Verifica o horário atual contra uma agenda para rotear dentro/fora do expediente"},switchCase:{name:"Condição",description:"Avalia uma variável contra padrões regex para escolher um caminho"},trafficSplit:{name:"Dividir tráfego",description:"Distribuidor de chamadas por percentual entre vários caminhos — teste A/B, balanceamento entre destinos e rampa de canário"},setVariable:{name:"Definir Variável",description:"Salva um valor para reusar depois durante a execução do plano"},sequence:{name:"Sequência",description:"Gera números sequenciais para protocolos, tickets ou qualquer identificador — durável em banco, nunca regride"},counter:{name:"Contador",description:"Conta tentativas, eventos ou qualquer coisa — por chamada ou entre chamadas, com saída opcional de limite"},httpRequest:{name:"Requisição HTTP",description:"Chama uma API REST e armazena a resposta para os blocos seguintes"},webhook:{name:"Webhook",description:"Dispara uma chamada HTTP para um sistema externo e segue sem esperar"},dataTransform:{name:"Transformar Dados",description:"Aplica operações de texto, número, data, lista, telefone e fala sobre um valor sem escrever código"},sendDtmf:{name:"Enviar DTMF",description:"Envia tons DTMF para o canal conectado ou PBX"},subPlan:{name:"Sub-Plano",description:"Delega execução para outro plano publicado e retorna"},aiAgent:{name:"Agente de IA",description:"Entrega a chamada para um agente IA para conversa livre"},retellAgent:{name:"Agente Retell",description:"Entrega a chamada para um agente de voz da Retell"},vapiAgent:{name:"Agente Vapi",description:"Entrega a chamada para um assistente de voz da Vapi"},elevenlabsAgent:{name:"Agente ElevenLabs",description:"Entrega a chamada para um agente de voz da ElevenLabs"},voiceRecognition:{name:"Reconhecimento de Voz",description:"Ouve o chamador, transcreve a fala e roteia por intenção"},tell:{name:"Mensagem",description:"Diz algo ao usuário — reproduz áudio na voz, envia mensagem no chat"},menu:{name:"Menu",description:"Apresenta opções e roteia pela escolha do usuário — DTMF na voz, botões no chat"},capture:{name:"Captura",description:"Coleta entrada do usuário — dígitos DTMF ou fala na voz, texto no chat"},routeAi:{name:"Classificador IA",description:"Classifica texto via IA e roteia por intenção — uma condição inteligente"},channelRouter:{name:"Canal",description:"Roteia o plano com base no modo ativo do canal (voz ou chat)"},apiSwitch:{name:"API Switch",description:"Reproduz prompt, coleta dígitos, chama API e roteia pelo atributo da resposta (legado)"},enableRecord:{name:"Ativar Gravação",description:"Ativa gravação da chamada durante o plano com amostragem e análise (legado)"},recording:{name:"Gravação",description:"Inicia ou encerra a gravação a partir deste ponto do plano"},transcription:{name:"Transcrição",description:"Escolhe o escopo da transcrição a partir deste ponto do plano"},analysis:{name:"Análise",description:"Escolhe análises para toda a transcrição disponível; cada bloco sobrescreve apenas os campos definidos"},whatsappTemplate:{name:"Enviar template WhatsApp",description:"Envia um template aprovado da Meta pelo WhatsApp Business, em chamada de voz ou em chat"},sendSms:{name:"Enviar SMS",description:"Envia uma mensagem de texto pela Twilio, em chamada de voz ou em chat"},phoneLookup:{name:"Consultar número",description:"Confere o formato do número e, se pedido, o tipo de linha e a operadora pela Twilio Lookup"},verifyCode:{name:"Verificar código",description:"Envia um código de verificação pela Twilio Verify e confere, em chamada de voz ou em chat"},addToDnc:{name:"Adicionar à DNC",description:"Adiciona o número do contato à lista de não perturbe da organização — opt-out de dentro do plano"}},_audio:{tts:{text:"Texto para sintetizar em fala.",voice:"ID da voz TTS (ex: 'pt-BR-FranciscaNeural').",model:"Modelo TTS a utilizar (padrão: 'edge')."},file:{id:"ID do arquivo de áudio da biblioteca.",name:"Nome de exibição do arquivo de áudio.",path:"Caminho de armazenamento do arquivo de áudio."},url:{value:"URL do áudio, buscada na hora da chamada. Aceita {{variáveis}}; secrets não são permitidos.",fallbackTts:"Falado quando a URL falha. Se estiver vazio, o nó segue pela saída de erro."}},start:{autoAnswer:"Atender chamada automaticamente antes de processar. Desabilite para roteamento pré-atendimento.",channelType:"Tipo de canal do plano."},playback:{audio:"Áudio para reproduzir. Use TTS (texto para fala) ou arquivo de áudio pré-gravado."},hangup:{cause:"Código de causa SIP para desligamento (ex: 'NORMAL_CLEARING'). Omita para padrão."},ivr:{audio:"Prompt de áudio reproduzido antes de coletar entrada DTMF.",timeout:"Segundos de espera por entrada DTMF após o áudio (1-60).",maxAttempts:"Máximo de tentativas antes de seguir pela saída de erro (1-10)."},collectDigits:{audio:"Prompt de áudio reproduzido antes de coletar dígitos.",minDigits:"Número mínimo de dígitos necessários (1-20).",maxDigits:"Número máximo de dígitos a coletar (1-20).",terminator:"Tecla que encerra a coleta de dígitos (ex: '#'). Um caractere.",timeout:"Segundos de espera pelo primeiro dígito após o áudio (1-60).",interDigitTimeout:"Segundos de espera entre dígitos consecutivos (1-30).",maxAttempts:"Máximo de tentativas em entrada inválida (1-10).",invalidAudio:"Áudio reproduzido quando a entrada falha na validação regex. Opcional.",regex:"Padrão regex para validar dígitos coletados. Vazio aceita qualquer entrada.",resetDigit:"Tecla que limpa dígitos coletados e reinicia. Um caractere. Vazio para desabilitar."},transfer:{method:"Método de transferência. 'bridge' mantém controle da chamada; 'transfer' transfere completamente.",destinations:"URIs SIP ou números de telefone para discar. Pelo menos um obrigatório. Tentados em ordem.",timeout:"Timeout de toque em segundos por destino (5-120). Omita para padrão da operadora.",attachedData:"Pares chave/valor entregues ao atendente na transferência (screen-pop). Valores aceitam templates."},timeRouting:{scheduleId:"ID da agenda para roteamento por horário. Direciona para saídas onHours/offHours/holiday."},switchCase:{expression:"Expressão template a avaliar, ex: '{{ivr.digits}}'. Comparada com os padrões dos cases.",cases:"Lista de padrões para comparar. Cada um cria uma saída dinâmica 'match:<padrão>'."},trafficSplit:{paths:"Caminhos com peso. Cada um cria uma saída dinâmica 'path:<nome>'.",mode:"'contact' mantém o mesmo contato sempre no mesmo caminho (hash sem estado); 'call' sorteia a cada chamada (sem estado, aproximado); 'exact' usa um rodízio contado no Redis e fecha a proporção mesmo em volume baixo."},setVariable:{assignments:"Lista de atribuições de variáveis. Pelo menos uma obrigatória."},counter:{name:"Nome do contador. Suporta templates, ex: 'tentativas_{{start.callerid}}'.",action:"Operação aplicada ao contador. 'reset' zera o contador e ignora o passo.",step:"Quantidade somada ou subtraída a cada execução (1-1000000). Ignorada quando a ação é 'reset'.",limit:"Valor que direciona para a saída 'limitReached' quando o contador o alcança. Vazio apenas conta.",scope:"'call' começa do zero a cada chamada; 'plan' persiste entre as chamadas de um plano; 'organization' persiste entre todos os planos da organização.",ttlSeconds:"Tempo de vida em segundos de um contador de escopo 'plan' ou 'organization' (60-31536000). Aplicado na criação da chave, então contar não renova a janela."},httpRequest:{method:"Método HTTP da requisição.",url:"URL da requisição. Suporta expressões template, ex: 'https://api.example.com/{{start.callerid}}'.",headers:"Cabeçalhos HTTP como pares chave-valor. Valores suportam expressões template.",body:"Corpo da requisição (string JSON). Expressões template permitidas. Apenas para POST/PUT/PATCH.",timeout:"Timeout da requisição em milissegundos. Omita para padrão."},webhook:{method:"Método HTTP da requisição.",url:"URL de destino. Suporta expressões template, ex: 'https://hooks.example.com/{{start.callerid}}'.",headers:"Cabeçalhos HTTP como pares chave-valor. Valores suportam expressões template.",body:"Corpo da requisição (string JSON). Expressões template permitidas. Apenas para POST/PUT/PATCH/DELETE."},dataTransform:{steps:"Lista ordenada de passos de transformação. Cada passo transforma um valor e salva o resultado num nome.",onError:"O que fazer quando um passo falha: 'error' segue pela saída de erro, 'empty' continua com um valor vazio."},subPlan:{planId:"ID de um plano visual publicado para executar como subplano. Deve estar publicado."},sendDtmf:{digits:"Dígitos DTMF para enviar (0-9, *, #). Suporta expressões template."},aiAgent:{agent_id:"ID do agente SipPulse AI a invocar. Obrigatório para execução.",agent_name:"Nome de exibição do agente AI (usado em logs e na interface).",additional_instructions:"Instruções extras adicionadas ao prompt do sistema do agente.",variables:"Pares chave-valor passados ao agente como variáveis de contexto.",initial_message:"Primeira mensagem que o agente fala ao iniciar a conversa.",max_duration_minutes:"Duração máxima da conversa em minutos (1-60). Chamada encerra no timeout."},retellAgent:{connector_id:"Conector com a capacidade de agente de voz (voice.agent), como uma conta Retell.",agent_id:"ID do agente da Retell que atende a ligação. Obrigatório para execução.",agent_name:"Nome de exibição do agente escolhido, usado nos logs e no editor.",variables:"Pares chave-valor enviados ao agente. Cada valor aceita {{variáveis}}.",max_duration_minutes:"Duração máxima da chamada em minutos (1-60). A ponte encerra no timeout.",result_wait_seconds:"Tempo de espera pela extração pós-chamada da Retell antes de seguir (0-60)."},vapiAgent:{connector_id:"Conector com a capacidade de agente de voz (voice.agent), como uma conta Vapi.",assistant_id:"ID do assistente da Vapi que atende a ligação. Obrigatório para execução.",assistant_name:"Nome de exibição do assistente escolhido, usado nos logs e no editor.",variables:"Pares chave-valor enviados ao agente. Cada valor aceita {{variáveis}}.",max_duration_minutes:"Duração máxima da chamada em minutos (1-60). A ponte encerra no timeout.",result_wait_seconds:"Tempo de espera pelo relatório da Vapi antes de seguir (0-60)."},elevenlabsAgent:{connector_id:"Conector com a capacidade de agente de voz (voice.agent), como uma conta ElevenLabs.",agent_id:"ID do agente da ElevenLabs que atende a ligação. Obrigatório para execução.",agent_name:"Nome de exibição do agente escolhido, usado nos logs e no editor.",variables:"Pares chave-valor enviados ao agente como cabeçalhos SIP X-<nome>. Cada valor aceita {{variáveis}}.",max_duration_minutes:"Duração máxima da chamada em minutos (1-60). A ponte encerra no timeout.",result_wait_seconds:"Tempo de espera pela análise pós-chamada da ElevenLabs antes de seguir (0-60)."},voiceRecognition:{mode:"'intent' classifica a fala em intenções configuradas; 'capture' transcreve sem classificação.",prompt:"Prompt de áudio reproduzido antes de escutar a fala.",intents:"Lista de intenções para o LLM classificar a fala. Cada uma cria uma saída dinâmica. Só usado no modo intent.",classification_instructions:"Instruções adicionais para o classificador de intenções do LLM. Só usado no modo intent.",listen:"Configuração de escuta: timeout de silêncio, duração máxima, idioma, beep.",processing_audio:"Áudio reproduzido enquanto a IA processa a fala. Opcional.",retry:"Comportamento de retentativa: máximo de tentativas e prompt alternativo quando a fala não é reconhecida."},tell:{audio:"Áudio para reproduzir via TTS, arquivo pré-gravado ou URL remota. Usado em planos de voz.",content:"Conteúdo da mensagem a enviar no chat. Usado em planos de chat."},menu:{options:"Opções do menu. Cada uma cria uma saída dinâmica.",audio:"Prompt de áudio reproduzido antes de coletar entrada DTMF na voz.",text:"Texto da mensagem no chat, exibido acima dos botões. Suporta expressões template.",voiceTimeout:"Segundos de espera por entrada DTMF no modo voz (1-60).",maxAttempts:"Máximo de tentativas para entrada inválida antes de seguir pela saída noMatch (1-10).",invalidMessage:"Mensagem enviada no chat quando a entrada não corresponde a nenhuma opção. Suporta expressões template."},capture:{audio:"Prompt de áudio reproduzido antes de coletar entrada no modo voz.",voiceMethod:"Método de entrada por voz: 'dtmf' para dígitos, 'speech' para transcrição ASR (requer IA).",minDigits:"Número mínimo de dígitos DTMF necessários (1-20).",maxDigits:"Número máximo de dígitos DTMF a coletar (1-20).",terminators:"Tecla que encerra a coleta de dígitos (ex: '#').",voiceTimeout:"Segundos de espera por entrada no modo voz (1-60).",listen:"Configuração de escuta para captura de fala: detecção de silêncio, duração máxima, idioma.",processing_audio:"Áudio reproduzido enquanto o ASR processa a fala. Opcional.",retryAudio:"Áudio reproduzido na retentativa ao invés do prompt principal. Usa o principal se não definido.",text:"Mensagem de prompt no chat enviada antes de aguardar a entrada do usuário.",validation:"Padrão regex para validar a entrada de texto no chat. Entrada inválida aciona retentativa.",invalidMessage:"Mensagem enviada no chat quando a entrada falha na validação.",maxAttempts:"Máximo de tentativas para entrada inválida ou vazia (1-10)."},routeAi:{input:"Expressão template para avaliar. O texto resolvido é classificado pela IA.",intents:"Lista de intenções para a IA classificar a entrada. Cada uma cria uma saída dinâmica.",instructions:"Instruções adicionais para o classificador de intenções da IA."},channelRouter:{},apiSwitch:{audio:"Prompt de áudio reproduzido antes de coletar dígitos.",chatText:"Prompt de texto para modo chat. Suporta {{variáveis}}.",timeout:"Segundos de espera por entrada de dígito (1-60).",maxAttempts:"Máximo de tentativas para coleta de dígitos (1-10).",digitRegex:"Regex para validar entrada DTMF. Vazio aceita qualquer entrada.",method:"Método HTTP da requisição à API.",url:"URL do endpoint da API. Suporta {{variáveis}} incluindo dígitos coletados como {{digits}}.",headers:"Cabeçalhos HTTP como pares chave-valor.",body:"Corpo da requisição (JSON). Suporta {{variáveis}}. Apenas para POST/PUT.",requestTimeout:"Timeout da requisição HTTP em milissegundos.",attribute:"Nome do atributo JSON da resposta da API para comparar com os cases.",cases:"Valores possíveis do atributo. Cada um cria uma saída dinâmica 'match:<valor>'."},enableRecord:{percentage:"Porcentagem de chamadas a gravar (0-100). 100 grava todas.",minDuration:"Duração mínima da chamada em segundos antes de iniciar a gravação. 0 para imediato.",analyzeCalls:"Ativar análise pós-chamada por IA (requer módulo AI)."},recording:{enabled:"Iniciar ou encerrar a gravação a partir deste ponto",samplingPercentage:"Porcentagem de amostragem quando a gravação começa"},transcription:{enabled:"Iniciar ou encerrar a transcrição a partir deste ponto",samplingPercentage:"Percentual das gravações selecionadas que serão transcritas",scope:"Escopo da transcrição: 'from_here' usa o áudio gravado a partir deste ponto (padrão/legado); 'whole_recording' inclui todo o áudio já gravado e continua até a transcrição ser desligada",language:"Idioma aplicado à transcrição inteira",minDurationSeconds:"Duração mínima aplicada à transcrição inteira",speechRequirement:"Pular chamadas sem conversa, aplicado à transcrição inteira: none, both (cliente e URA) ou caller (só o cliente)",anonymizeEnabled:"Anonimizar a transcrição inteira",sentimentEnabled:"Ativar análise de sentimento para toda a transcrição disponível; campos omitidos são herdados",transcriptionType:"Tipo de transcrição: 'post_call' transcreve quando a chamada termina; 'live' também transcreve durante a chamada, custo por minuto gravado"},analysis:{speechAnalyticsEnabled:"Ativar resumo da chamada para toda a transcrição disponível; campos omitidos são herdados",sentimentEnabled:"Ativar análise de sentimento para toda a transcrição disponível; campos omitidos são herdados",topicDetectionTopics:"Tópicos para toda a transcrição disponível; campos omitidos são herdados",intentDetectionIntents:"Intenções para toda a transcrição disponível; campos omitidos são herdados",structuredAnalysisEnabled:"Ativar análises estruturadas para toda a transcrição disponível; campos omitidos são herdados",structuredAnalysisIds:"IDs das análises estruturadas para toda a transcrição disponível; campos omitidos são herdados"},whatsappTemplate:{connectorId:"Conector com a capacidade de templates do WhatsApp (whatsapp.templates).",phoneNumberId:"Número de origem da mensagem, entre os números do conector.",template:"Template aprovado a enviar, por nome e idioma (ex.: boleto / pt_BR).",to:"Destinatário. Suporta {{variáveis}}. Número sem DDI recebe o DDI padrão do bloco.",defaultCountry:"País que completa os números escritos sem DDI. Vazio usa o país padrão da organização.",parameters:"Valores das variáveis do template. Chaves: número ou nome da variável; cabeçalho de mídia recebe a URL; botão de URL recebe o sufixo. Suporta {{variáveis}}."},sendSms:{connector_id:"Conector com a capacidade sms.send, como uma conta da Twilio.",from:"Remetente. Vazio usa o remetente padrão do conector; senão, um Messaging Service SID (MG...) ou um número E.164.",to:"Destinatário. Suporta {{variáveis}}. Número sem DDI recebe o DDI padrão do bloco.",default_country:"País que completa os números escritos sem DDI. Vazio usa o país padrão da organização.",body:"Texto da mensagem. Suporta {{variáveis}}; segredos não são permitidos no corpo.",transliterate:"Troca letras acentuadas pela letra sem acento antes de enviar, para caber 160 caracteres por SMS em vez de 70."},phoneLookup:{connector_id:"Conector com a capacidade phone.lookup, como uma conta da Twilio.",number:"Número a consultar. Suporta {{variáveis}}. Número sem DDI recebe o DDI padrão do bloco.",default_country:"País que completa os números escritos sem DDI. Vazio usa o país padrão da organização.",line_type:"Busca também o tipo de linha e a operadora. A Twilio cobra US$ 0,008 por consulta; só validar o formato é grátis.",line_type_error:"Código e mensagem da própria Twilio quando ela não conseguiu identificar o tipo de linha; vazio quando conseguiu."},verifyCode:{connector_id:"Conector com a capacidade verify.otp, como uma conta da Twilio.",service_sid:"SID do Serviço do Verify (VA...) cujo tamanho de código e remetente o bloco usa.",to:"Destinatário. Suporta {{variáveis}}. Número sem DDI recebe o DDI padrão do bloco.",default_country:"País que completa os números escritos sem DDI. Vazio usa o país padrão da organização.",channel:"Como o código chega ao contato: sms, whatsapp ou ligação.",prompt:"Áudio que pede o código, falado com a voz do plano. No chat, o texto dele é enviado.",max_attempts:"Máximo de códigos errados antes de o bloco sair por Recusado (1-5).",timeout_seconds:"Segundos de espera pelo código depois do aviso (1-60)."},addToDnc:{reason:"Motivo curto opcional registrado na entrada da DNC (máx. 128 caracteres). Texto simples, sem templates.",phoneOverride:"Número/template opcional a adicionar no lugar do resolvido automaticamente. Suporta {{variáveis}}. Vazio resolve o contato do discador e, depois, o caller ID."}};var Gx={en:F4,"pt-BR":y8};function Mq($,U="en"){return Gx[U]._nodes?.[$]}var JX=["core","ai","queues","dialer","omnichannel","enterprise"],jx=JX.filter(($)=>$!=="core");function x4($,U){return typeof $.outputs==="function"?$.outputs(U):$.outputs}var GX={interaction:{order:0},handling:{order:1},routing:{order:2},media:{order:3},data:{order:4},legacy:{order:5}},Yx=Object.entries(GX).sort(([,$],[,U])=>$.order-U.order).map(([$])=>$);var Dq=G.object({reason:G.string().max(128,{error:"editor:validation.dncReasonTooLong"}).default("").describe("Optional short reason recorded on the DNC entry (max 128 chars). Plain text, no templates."),phoneOverride:G.string().default("").describe("Optional number/template to add instead of the auto-resolved one. Supports {{variables}}. Empty = auto-resolve (dialer contact, then caller ID).")}),Pq=C({meta:{type:"addToDnc",module:"dialer",nameKey:"editor:nodes.addToDnc.name",descriptionKey:"editor:nodes.addToDnc.description",color:"red",icon:"Ban",category:"data",nature:"sideEffect",display:"compact",channel:"voice",order:3,outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:Dq,producedVariables:[{name:"dnc_added",type:"string",descriptionKey:"editor:vars.dncAdded"},{name:"dnc_phone",type:"string",descriptionKey:"editor:vars.dncPhone"}]});var Nq=G.object({agent_id:G.string().default("").describe("SipPulse AI agent ID to invoke. Required for execution."),agent_name:G.string().default("").describe("Display name for the AI agent (used in logs and UI)."),additional_instructions:G.string().default("").describe("Extra instructions appended to the agent's system prompt."),variables:G.record(G.string(),G.unknown()).default({}).describe("Key-value pairs passed to the agent as context variables."),initial_message:G.string().default("").describe("First message the agent speaks when the conversation starts."),max_duration_minutes:G.number().min(1).max(60).default(10).describe("Maximum conversation duration in minutes (1-60). Call ends on timeout.")}),Lq=C({meta:{type:"aiAgent",module:"ai",nameKey:"editor:nodes.aiAgent.name",descriptionKey:"editor:nodes.aiAgent.description",color:"iris",icon:"BotMessageSquare",category:"handling",order:1,nature:"composite",display:"full",channel:"both",outputs:[{key:"completed",labelKey:"editor:handles.completed"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:Nq,producedVariables:[{name:"duration_ms",type:"number",descriptionKey:"editor:vars.aiAgent.durationMs"},{name:"turns",type:"number",descriptionKey:"editor:vars.aiAgent.turns"},{name:"thread_uid",type:"string",descriptionKey:"editor:vars.aiAgent.threadUid"},{name:"output.*",type:"string",descriptionKey:"editor:vars.aiAgent.output"}]});var _q=G.string().min(1).max(255).regex(/^[A-Za-z0-9_-]+$/,{error:"Invalid structured analysis id"});var Iq=G.object({speechAnalyticsEnabled:G.boolean().optional(),sentimentEnabled:G.boolean().nullable().optional(),topicDetectionTopics:G.array(G.string()).optional(),intentDetectionIntents:G.array(G.string()).optional(),structuredAnalysisEnabled:G.boolean().optional(),structuredAnalysisIds:G.array(_q).max(100).optional()}),Fq=C({meta:{type:"analysis",module:"ai",nameKey:"editor:nodes.analysis.name",descriptionKey:"editor:nodes.analysis.description",color:"orange",icon:"ChartNoAxesColumn",category:"media",nature:"sideEffect",display:"compact",channel:"both",order:2,outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:Iq,producedVariables:[{name:"selected",type:"number",descriptionKey:"editor:vars.analysisSelected"}]});var Zx=/\{\{[^{}]*\}\}/g,Bx=/^\{\{[^{}]*\}\}$/,Vx=new Set(["http:","https:"]);function jX($){if(!URL.canParse($))return!1;return Vx.has(new URL($).protocol)}function YX($){let U=$.trim();if(U==="")return"empty";if(Bx.test(U))return"from-variable";let K=0,q=U.replaceAll(Zx,()=>{return K+=1,`v${K}`});return jX(q)?"valid":"malformed"}function xq($){return YX($)!=="malformed"}var HX=["postgres","redis","freeswitch","engine","server"],tu=new Set(HX);var wq=G.object({text:G.string().min(1,{error:"editor:validation.emptyTtsText"}).describe("Text to synthesize into speech."),voice:G.string().optional().describe("TTS voice ID (e.g., 'pt-BR-FranciscaNeural'). Resolved dynamically when absent."),model:G.string().optional().describe("TTS model ID (e.g., 'pulse-tts'). Resolved dynamically when absent.")}),J$=G.union([G.object({tts:wq.describe("Text-to-speech audio source.")}),G.object({file:G.object({id:G.string().min(1,{error:"editor:validation.noAudioFile"}).describe("Audio file ID from the audio library."),name:G.string().describe("Display name of the audio file."),path:G.string().describe("Storage path of the audio file.")}).describe("Pre-recorded audio file source.")}),G.object({url:G.object({value:G.string().min(1,{error:"editor:validation.emptyAudioUrl"}).refine(xq,{error:"editor:validation.malformedAudioUrl"}).describe("Audio URL fetched at call time. Supports {{variables}}; secrets are not allowed."),fallbackTts:wq.optional().describe("Spoken when the URL fails. Absent means take the error output.")}).describe("Remote audio source fetched at call time.")})]),Mx=J$.optional().catch(void 0);var P6=G.string().refine(($)=>$.trim()!=="",{error:"editor:validation.urlRequired"}).refine(($)=>!/\s/.test($.trim()),{error:"editor:validation.urlHasSpace"}).default("");var Dx=G.object({value:G.string().min(1,{error:"editor:validation.caseValueRequired"}).default("").describe("Attribute value to match. Creates a 'match:<value>' output.")}),Aq=G.object({audio:J$.optional().describe("Audio prompt played before collecting digits."),chatText:G.string().default("").describe("Text prompt for chat mode. Supports {{variables}}."),timeout:G.number().int().min(1).max(60).default(5).describe("Seconds to wait for digit input (1-60)."),maxAttempts:G.number().int().min(1).max(10).default(3).describe("Maximum retry attempts for digit collection (1-10)."),digitRegex:G.string().default("").describe("Regex to validate DTMF input. Empty means accept any."),method:G.enum(["GET","POST","PUT"]).default("GET").describe("HTTP method for the API request."),url:P6.describe("API endpoint URL. Supports {{variables}} including collected digits as {{digits}}."),headers:G.record(G.string(),G.string()).optional().describe("HTTP headers as key-value pairs."),body:G.string().optional().describe("Request body (JSON). Supports {{variables}}. Only for POST/PUT."),requestTimeout:G.number().int().min(1000).max(60000).default(1e4).describe("HTTP request timeout in milliseconds."),attribute:G.string().default("").describe("JSON attribute name from the API response to match against cases."),cases:G.array(Dx).default([]).describe("Possible attribute values. Each creates a dynamic output handle 'match:<value>'.")}),vq=C({meta:{type:"apiSwitch",module:"core",nameKey:"editor:nodes.apiSwitch.name",descriptionKey:"editor:nodes.apiSwitch.description",color:"teal",icon:"Globe",category:"legacy",nature:"composite",display:"full",channel:"both",order:3,legacy:!0,replacedBy:"httpRequest + switchCase",outputs:($)=>{return[...($.cases??[]).map((q)=>typeof q==="string"?q:q.value).filter((q)=>typeof q==="string"&&q!=="").map((q)=>({key:`match:${q}`,labelKey:q})),{key:"noInput",labelKey:"editor:handles.noInput"},{key:"error",labelKey:"editor:handles.error"}]}},configSchema:Aq,producedVariables:[{name:"digits",type:"string",descriptionKey:"editor:vars.collectedDigits"},{name:"status_code",type:"number",descriptionKey:"editor:vars.statusCode"},{name:"response",type:"object",descriptionKey:"editor:vars.response"},{name:"destination",type:"string",descriptionKey:"editor:vars.switchDestination"},{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"}]});var Px=G.object({language:G.string().optional().describe("BCP 47 language code for speech recognition (e.g., 'pt-BR'). Omit for plan default."),initial_timeout_s:G.number().min(3).max(60).default(10).describe("Maximum seconds to wait for speech to begin (3-60)."),timeout_s:G.number().min(1).max(30).default(3).describe("Seconds of post-speech silence before stopping recording (1-30)."),max_duration_s:G.number().min(1).max(60).default(15).describe("Maximum recording duration in seconds (1-60)."),beep:G.boolean().default(!1).describe("Play a beep sound before starting to listen.")}),kq=G.object({maxAttempts:G.number().min(1).max(10).default(3).describe("Maximum retry attempts for invalid or empty input (1-10)."),audio:J$.optional().describe("Audio prompt played before collecting input in voice mode."),voiceMethod:G.enum(["dtmf","speech"]).default("dtmf").describe("Voice input method: 'dtmf' for digits, 'speech' for ASR transcription (requires AI)."),minDigits:G.number().min(1).max(20).default(1).describe("Minimum number of DTMF digits required (1-20)."),maxDigits:G.number().min(1).max(20).default(1).describe("Maximum number of DTMF digits to collect (1-20)."),terminators:G.string().default("#").describe("Key that terminates digit collection (e.g., '#')."),voiceTimeout:G.number().min(1).max(60).default(5).describe("Seconds to wait for input in voice mode (1-60)."),listen:Px.default({initial_timeout_s:10,timeout_s:3,max_duration_s:15,beep:!1}).describe("Listening configuration for speech capture: silence detection, max duration, language."),processing_audio:J$.optional().describe("Audio played while ASR processes the speech. Optional."),retryAudio:J$.optional().describe("Audio played on retry instead of main prompt. Falls back to main if not set."),text:G.string().default("").describe("Chat prompt message sent before waiting for user input. Supports {{variables}}."),validation:G.string().optional().describe("Regex pattern to validate chat text input. Invalid input triggers retry."),invalidMessage:G.string().optional().describe("Chat message sent when input fails validation. Supports {{variables}}.")}),Rq=C({meta:{type:"capture",module:"core",nameKey:"editor:nodes.capture.name",descriptionKey:"editor:nodes.capture.description",color:"cyan",icon:"TextCursorInput",category:"interaction",order:3,nature:"composite",display:"full",channel:"both",outputs:[{key:"collected",labelKey:"editor:handles.collected"},{key:"noInput",labelKey:"editor:handles.noInput"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:kq,producedVariables:[{name:"text",type:"string",descriptionKey:"editor:vars.capturedText"},{name:"attempts",type:"number",descriptionKey:"editor:vars.captureAttempts"}]});var zq=G.object({}),bq=C({meta:{type:"channelRouter",module:"core",nameKey:"editor:nodes.channelRouter.name",descriptionKey:"editor:nodes.channelRouter.description",color:"lime",icon:"Router",category:"routing",order:3,nature:"routing",display:"full",channel:"both",outputs:[{key:"voice",labelKey:"editor:handles.voice"},{key:"chat",labelKey:"editor:handles.chat"}]},configSchema:zq,producedVariables:[{name:"channelType",type:"string",descriptionKey:"editor:vars.channelType"}]});var Oq=G.object({audio:J$.default({tts:{text:""}}).describe("Audio prompt played before collecting digits."),minDigits:G.number().min(1,{error:"editor:validation.minDigitsMin"}).max(20,{error:"editor:validation.minDigitsMax"}).default(1).describe("Minimum number of digits required (1-20)."),maxDigits:G.number().min(1,{error:"editor:validation.maxDigitsMin"}).max(20,{error:"editor:validation.maxDigitsMax"}).default(1).describe("Maximum number of digits to collect (1-20)."),terminator:G.string().max(1).default("#").describe("Key that terminates digit collection (e.g., '#'). Single character."),timeout:G.number().min(1,{error:"editor:validation.timeoutMin"}).max(60,{error:"editor:validation.timeoutMax"}).default(5).describe("Seconds to wait for the first digit after audio finishes (1-60)."),interDigitTimeout:G.number().min(1,{error:"editor:validation.interDigitTimeoutMin"}).max(30,{error:"editor:validation.interDigitTimeoutMax"}).default(3).describe("Seconds to wait between consecutive digits (1-30)."),maxAttempts:G.number().min(1,{error:"editor:validation.attemptsMin"}).max(10,{error:"editor:validation.attemptsMax"}).default(3).describe("Maximum retry attempts on invalid input (1-10)."),invalidAudio:J$.optional().describe("Audio played when input fails regex validation. Optional."),regex:G.string().default("").describe("Regex pattern to validate collected digits. Empty means accept any."),resetDigit:G.string().max(1).default("").describe("Key that clears collected digits and restarts. Single character. Empty to disable.")}),Tq=C({meta:{type:"collectDigits",module:"core",nameKey:"editor:nodes.collectDigits.name",descriptionKey:"editor:nodes.collectDigits.description",color:"sky",icon:"Keyboard",category:"interaction",order:4,nature:"composite",display:"full",channel:"voice",outputs:[{key:"collected",labelKey:"editor:handles.collected"},{key:"noInput",labelKey:"editor:handles.noInput"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:Oq,producedVariables:[{name:"digits",type:"string",descriptionKey:"editor:vars.collectedDigits"},{name:"attempts",type:"number",descriptionKey:"editor:vars.collectAttempts"}]});var Sq=G.object({name:G.string().min(1,{error:"editor:validation.counterNameRequired"}).default("").describe("Counter name. Supports templates, e.g. 'attempts_{{start.callerid}}'."),action:G.enum(["increment","decrement","reset"]).default("increment").describe("Operation applied to the counter. 'reset' sets it to zero and ignores step."),step:G.number().int().min(1,{error:"editor:validation.counterStepMin"}).max(1e6,{error:"editor:validation.counterStepMax"}).default(1).describe("Amount added or subtracted on each execution (1-1000000). Ignored when the action is 'reset'."),limit:G.number().int().min(1,{error:"editor:validation.counterLimitMin"}).optional().describe("Value that routes to the 'limitReached' output once the counter reaches it. Empty means count only."),scope:G.enum(["call","plan","organization"]).default("call").describe("'call' starts from zero on every call; 'plan' persists across the calls of one plan; 'organization' persists across every plan of the organization."),ttlSeconds:G.number().int().min(60).max(31536000).optional().describe("Lifetime in seconds of a 'plan' or 'organization' counter (60-31536000). Applied when the key is created, so counting does not renew the window.")}),Cq=C({meta:{type:"counter",module:"core",nameKey:"editor:nodes.counter.name",descriptionKey:"editor:nodes.counter.description",color:"cyan",icon:"Tally5",category:"routing",order:5,nature:"routing",display:"compact",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"},{key:"limitReached",labelKey:"editor:handles.limitReached"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:Sq,producedVariables:[{name:"value",type:"number",descriptionKey:"editor:vars.counter.value"},{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"}]});var ff=new Intl.NumberFormat("en-US",{useGrouping:!1,maximumFractionDigits:10});var _x={BR:"55",US:"1",CA:"1",MX:"52",AR:"54",CL:"56",CO:"57",PE:"51",UY:"598",PY:"595",BO:"591",EC:"593",VE:"58",PT:"351",ES:"34",GB:"44",FR:"33",DE:"49",IT:"39"},Ix=Object.entries(_x).map(([$,U])=>({country:$,callingCode:U}));var g8="secrets",xx="secrets".replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);function XX(){return new RegExp(String.raw`\{\{\s*${xx}\.([A-Z][A-Z0-9_]*)\s*\}\}`,"g")}function ZX($){if(!$.includes("{{"))return[];let U=new Set;for(let K of $.matchAll(XX()))U.add(K[1]);return[...U]}var BX={httpRequest:new Set(["url","headers","body"]),apiSwitch:new Set(["url","headers","body"]),webhook:new Set(["url","headers","body"])};function VX($,U){return BX[$]?.has(U)===!0}function Eq($,U,K){if(typeof $==="string"){K(U,$);return}if(Array.isArray($)){$.forEach((q,Q)=>Eq(q,`${U}.${Q}`,K));return}if($!=null&&typeof $==="object")for(let[q,Q]of Object.entries($))Eq(Q,U===""?q:`${U}.${q}`,K)}function u8($){let U=new Set,K=[];return Eq($.config,"",(q,Q)=>{let W=ZX(Q);if(W.length===0)return;let J=q.split(".")[0]??"";if(VX($.type,J)){for(let j of W)U.add(j);return}for(let j of W)K.push({nodeId:$.id,label:$.label,field:q,name:j})}),{allowed:[...U],misplaced:K}}function f8($){let U=new Set,K=[];for(let q of $){let Q=u8(q);for(let W of Q.allowed)U.add(W);for(let W of Q.misplaced)U.add(W.name),K.push(W)}return{names:U,misplaced:K}}function wx($){return $===`
|
|
99
|
-
`||$==="\r"||$==="\u2028"||$==="\u2029"}function Ax($,U){for(let K=U;K<$.length;K++)if(wx($[K]))return K;return $.length}function MX($){let U=[],K=0,q=-1,Q=-1;for(;;){let W=$.indexOf("{{",K);if(W===-1)return U;if(q<W+3){if(q=$.indexOf("}}",W+3),q===-1)return U}if(Q<W+2)Q=Ax($,W+2);if(Q<q){K=Q+1;continue}U.push({start:W,end:q+2,key:$.slice(W+2,q)}),K=q+2}}function vx($,U,K){let q="",Q=0;return U.forEach((W,J)=>{q+=$.slice(Q,W.start)+K(J),Q=W.end}),q+$.slice(Q)}function yq($,U){let K=[],q=0;for(let Q of MX($)){let W=Q.start-1>=q&&$[Q.start-1]==='"'?Q.start-1:Q.start,J=$[Q.end]==='"'?Q.end+1:Q.end;K.push({start:W,end:J}),q=J}return vx($,K,(Q)=>U($.slice(K[Q].start,K[Q].end)))}var m8=200;function DX($,U){let K=$[U];if(K==="*"||K==="+")return 1;if(K==="{"){let q=$.indexOf("}",U);if(q!==-1&&/^\d+,$/.test($.slice(U+1,q)))return q-U+1}return 0}function kx($,U){let K=U+1;while(K<$.length&&$[K]!=="]")K+=$[K]==="\\"?2:1;return K+1}function Rx($,U,K){let q=K.pop()??{repeat:!1},Q=DX($,U+1);if(Q>0&&q.repeat)return{catastrophic:!0,next:U};if((q.repeat||Q>0)&&K.length>0)K.at(-1).repeat=!0;return{catastrophic:!1,next:U+(Q>0?1+Q:1)}}function zx($,U,K){let q=$[U];if(q==="\\")return{catastrophic:!1,next:U+2};if(q==="[")return{catastrophic:!1,next:kx($,U)};if(q==="(")return K.push({repeat:!1}),{catastrophic:!1,next:U+1};if(q===")")return Rx($,U,K);let Q=DX($,U);if(Q>0&&K.length>0)K.at(-1).repeat=!0;return{catastrophic:!1,next:U+(Q>0?Q:1)}}function gq($){let U=[],K=0;while(K<$.length){let{catastrophic:q,next:Q}=zx($,K,U);if(q)return!0;K=Q}return!1}function bx($){let U=$.split("/");if(U.length<3)return null;return{key:U[0].trim(),pattern:U.slice(1,-1).join("/"),replacement:U.at(-1)}}function uq($){if(!$.includes("{{"))return{valid:!0};for(let U of MX($)){let K=$.slice(U.start,U.end),q=bx(U.key.trim());if(q===null)continue;if(q.pattern.length>m8)return{valid:!1,error:`Regex pattern too long in "${K}" (max ${m8})`};if(gq(q.pattern))return{valid:!1,error:`Unsafe regex (possible catastrophic backtracking) in "${K}"`};try{new RegExp(q.pattern)}catch(Q){let W=Q instanceof Error?Q.message:String(Q);return{valid:!1,error:`Invalid regex in "${K}": ${W}`}}}return{valid:!0}}var PX={uppercase:"string",lowercase:"string",capitalize:"string",trim:"string",replace:"string",regexReplace:"string",part:"string",add:"string",subtract:"string",multiply:"string",divide:"string",round:"string",currency:"string",dateOffset:"string",dateDiff:"string",dateFormat:"string",count:"number",join:"string",item:"string",filter:"array",spellOut:"string",inWords:"string",normalizePhone:"string",default:"string"};var mx=new Set(["error_code","error_message","error_step","error_var"]),hx=G.string().refine(($)=>$.trim()!=="",{error:"editor:validation.emptySaveAs"}).refine(($)=>!mx.has($.trim()),{error:"editor:validation.reservedSaveAs"}).describe("Name the result is saved under. Readable by later steps and by other nodes."),j$=($)=>G.literal($).describe("Operation this step applies to the source."),NX=G.enum(["minutes","hours","days","months","years"]).describe("Time unit used by the step: minutes, hours, days, months, or years."),Y$=G.object({source:G.string().describe("Value the step transforms. Literal text or a template like '{{start.callerid}}'."),saveAs:hx}),cx=G.discriminatedUnion("op",[Y$.extend({op:j$("uppercase")}),Y$.extend({op:j$("lowercase")}),Y$.extend({op:j$("capitalize")}),Y$.extend({op:j$("trim")}),Y$.extend({op:j$("replace"),search:G.string().describe("Literal text to look for. Not a regular expression. Empty leaves the source untouched."),replacement:G.string().describe("Text that replaces every occurrence of the searched text.")}),Y$.extend({op:j$("regexReplace"),pattern:G.string().describe("Regular expression used to match text. Nested repetition and patterns over 200 characters are rejected."),replacement:G.string().describe("Text that replaces every match. Supports JavaScript backreferences such as '$1'.")}),Y$.extend({op:j$("part"),separator:G.string().describe("Text that splits the source into parts. Empty splits into single characters."),index:G.number().int().describe("Zero-based index of the part to keep. Negative counts from the end.")}),Y$.extend({op:j$("add"),operand:G.string().describe("Number added to the source. Literal value or template.")}),Y$.extend({op:j$("subtract"),operand:G.string().describe("Number subtracted from the source. Literal value or template.")}),Y$.extend({op:j$("multiply"),operand:G.string().describe("Number the source is multiplied by. Literal value or template.")}),Y$.extend({op:j$("divide"),operand:G.string().describe("Number the source is divided by. Literal value or template. Zero fails with 'divide_by_zero'.")}),Y$.extend({op:j$("round"),decimals:G.number().int().min(0).max(10).default(0).describe("Decimal places to keep (0-10). Rounds half away from zero.")}),Y$.extend({op:j$("currency"),currency:G.string().default("BRL").describe("ISO 4217 currency code used to format the amount, e.g. 'BRL'."),locale:G.string().default("pt-BR").describe("Locale used to format the amount, e.g. 'pt-BR'.")}),Y$.extend({op:j$("dateOffset"),amount:G.number().int().describe("How many units to add to the date. Negative subtracts."),unit:NX}),Y$.extend({op:j$("dateDiff"),operand:G.string().describe("Date compared against the source. The result is operand minus source. Literal or template."),unit:NX}),Y$.extend({op:j$("dateFormat"),format:G.string().default("dd/MM/yyyy").describe("Output pattern, e.g. 'dd/MM/yyyy'. Text between single quotes is kept as written."),locale:G.string().default("pt-BR").describe("Locale used for month and weekday names, e.g. 'pt-BR'.")}),Y$.extend({op:j$("normalizePhone"),country:G.string().default("BR").describe("ISO 3166-1 alpha-2 country code used for national numbers. Defaults to 'BR'.")}),Y$.extend({op:j$("count")}),Y$.extend({op:j$("join"),separator:G.string().default(", ").describe("Text placed between items, except before the last one."),lastSeparator:G.string().default(" e ").describe("Text placed before the last item. Ignored when the list has a single item.")}),Y$.extend({op:j$("item"),index:G.number().int().describe("Zero-based index of the item to keep. Negative counts from the end.")}),Y$.extend({op:j$("filter"),field:G.string().default("").describe("Object field compared on each item. Empty compares the item itself."),operand:G.string().describe("Value each item is compared against, as text. Literal or template.")}),Y$.extend({op:j$("spellOut")}),Y$.extend({op:j$("inWords")}),Y$.extend({op:j$("default"),operand:G.string().describe("Value used when the source is empty. Literal value or template.")})]),fq=G.object({steps:G.array(cx).min(1,{error:"editor:validation.noSteps"}).default([]).describe("Ordered list of transformation steps. Each step transforms a value and saves the result under a name."),onError:G.enum(["error","empty"]).default("error").describe("What to do when a step fails: 'error' follows the error output, 'empty' continues with an empty value.")}),mq=C({meta:{type:"dataTransform",module:"core",nameKey:"editor:nodes.dataTransform.name",descriptionKey:"editor:nodes.dataTransform.description",color:"grass",icon:"Replace",category:"data",order:5,nature:"sideEffect",display:"compact",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:fq,producedVariables:($)=>{let U=new Map;for(let K of $.steps){if(K.saveAs==="")continue;U.set(K.saveAs,{name:K.saveAs,type:PX[K.op],descriptionKey:"editor:vars.transformed"})}return[...U.values(),{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"},{name:"error_step",type:"number",descriptionKey:"editor:vars.errorStep"},{name:"error_var",type:"string",descriptionKey:"editor:vars.errorVar"}]}});var hq=G.object({connector_id:G.string().default("").describe("Public id of the connector that provides voice.agent (an ElevenLabs account). Required for execution."),agent_id:G.string().default("").describe("Id of the ElevenLabs agent that answers the call. Required for execution."),agent_name:G.string().default("").describe("Display name of the chosen ElevenLabs agent, for logs and the editor."),variables:G.record(G.string(),G.string()).default({}).describe("Key-value pairs sent to the agent as X-<name> SIP headers. Every value supports {{variables}}."),max_duration_minutes:G.number().min(1).max(60).default(10).describe("Maximum call duration in minutes (1-60). The bridge ends on timeout."),result_wait_seconds:G.number().int().min(0).max(60).default(15).describe("How long to wait for ElevenLabs' post-call analysis before continuing.")}),cq=C({meta:{type:"elevenlabsAgent",module:"ai",nameKey:"editor:nodes.elevenlabsAgent.name",descriptionKey:"editor:nodes.elevenlabsAgent.description",color:"iris",icon:"Sparkles",category:"handling",order:5,nature:"composite",display:"full",channel:"voice",requires:"voice.agent",connector:{kind:"elevenlabs",configKey:"connector_id"},outputs:[{key:"completed",labelKey:"editor:handles.completed"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:hq,producedVariables:[{name:"duration_ms",type:"number",descriptionKey:"editor:vars.elevenlabsAgent.durationMs"},{name:"provider_call_id",type:"string",descriptionKey:"editor:vars.elevenlabsAgent.providerCallId"},{name:"ended_reason",type:"string",descriptionKey:"editor:vars.elevenlabsAgent.endedReason"},{name:"summary",type:"string",descriptionKey:"editor:vars.elevenlabsAgent.summary"},{name:"analysis_pending",type:"string",descriptionKey:"editor:vars.elevenlabsAgent.analysisPending"},{name:"output.*",type:"string",descriptionKey:"editor:vars.elevenlabsAgent.output"}]});var lq=G.object({percentage:G.number().int().min(0).max(100).default(100).describe("Percentage of calls to record (0-100). 100 records all calls."),minDuration:G.number().int().min(0).default(0).describe("Minimum call duration in seconds before recording starts. 0 for immediate."),analyzeCalls:G.boolean().default(!1).describe("Enable post-call AI analysis (requires AI module).")}),rq=C({meta:{type:"enableRecord",module:"core",nameKey:"editor:nodes.enableRecord.name",descriptionKey:"editor:nodes.enableRecord.description",color:"red",icon:"CircleDot",category:"legacy",nature:"sideEffect",display:"compact",channel:"both",order:4,legacy:!0,outputs:[{key:"next",labelKey:"editor:handles.next"},{key:"skipped",labelKey:"editor:handles.skipped"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:lq,producedVariables:[{name:"recording",type:"string",descriptionKey:"editor:vars.recordingStatus"}]});var iq=G.object({cause:G.string().optional().describe("SIP hangup cause code (e.g., 'NORMAL_CLEARING'). Omit for default.")}),dq=C({meta:{type:"hangup",module:"core",nameKey:"editor:nodes.hangup.name",descriptionKey:"editor:nodes.hangup.description",color:"red",icon:"PhoneOff",category:"interaction",order:5,nature:"flow",display:"full",channel:"both",outputs:[]},configSchema:iq,producedVariables:[]});var oq=G.object({method:G.enum(["GET","POST","PUT","PATCH","DELETE"]).default("GET").describe("HTTP method for the request."),url:P6.describe("Request URL. Supports template expressions, e.g., 'https://api.example.com/{{start.callerid}}'."),headers:G.record(G.string(),G.string()).optional().describe("HTTP headers as key-value pairs. Values support template expressions."),body:G.string().optional().describe("Request body (JSON string). Template expressions allowed. Only for POST/PUT/PATCH."),timeout:G.number().optional().describe("Request timeout in milliseconds. Omit for default.")}),nq=C({meta:{type:"httpRequest",module:"core",nameKey:"editor:nodes.httpRequest.name",descriptionKey:"editor:nodes.httpRequest.description",color:"indigo",icon:"Globe",category:"data",order:0,nature:"sideEffect",display:"compact",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:oq,producedVariables:[{name:"status_code",type:"number",descriptionKey:"editor:vars.statusCode"},{name:"response",type:"object",descriptionKey:"editor:vars.response"},{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"}]});var pq=G.object({audio:J$.default({tts:{text:""}}).describe("Audio prompt played before collecting DTMF input."),timeout:G.number().min(1,{error:"editor:validation.timeoutMin"}).max(60,{error:"editor:validation.timeoutMax"}).default(5).describe("Seconds to wait for DTMF input after audio finishes (1-60)."),maxAttempts:G.number().min(1,{error:"editor:validation.attemptsMin"}).max(10,{error:"editor:validation.attemptsMax"}).default(3).describe("Maximum retry attempts before following the error output (1-10).")}),tq=C({meta:{type:"ivr",module:"core",nameKey:"editor:nodes.ivr.name",descriptionKey:"editor:nodes.ivr.description",color:"violet",icon:"Grid3x3",category:"legacy",nature:"composite",display:"full",channel:"voice",order:1,deprecated:!0,replacedBy:"menu",outputs:[{key:"digit:0",labelKey:"0"},{key:"digit:1",labelKey:"1"},{key:"digit:2",labelKey:"2"},{key:"digit:3",labelKey:"3"},{key:"digit:4",labelKey:"4"},{key:"digit:5",labelKey:"5"},{key:"digit:6",labelKey:"6"},{key:"digit:7",labelKey:"7"},{key:"digit:8",labelKey:"8"},{key:"digit:9",labelKey:"9"},{key:"digit:*",labelKey:"*"},{key:"digit:#",labelKey:"#"},{key:"timeout",labelKey:"editor:handles.timeout"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:pq,producedVariables:[{name:"digits",type:"string",descriptionKey:"editor:vars.digits"},{name:"destination",type:"string",descriptionKey:"editor:vars.destination"},{name:"loops",type:"number",descriptionKey:"editor:vars.loops"}]});var aq=G.object({id:G.string().min(1).default("").describe("Unique option identifier. Used as button ID in chat and output handle suffix."),label:G.string().min(1).default("").describe("Display label shown to the user. Button text in chat, spoken in voice prompt."),digit:G.string().default("").describe("DTMF digit for voice mode (0-9, *, #). Leave empty to skip voice for this option.")}),sq=G.object({options:G.array(aq).default([]).describe("Menu options. Each creates a dynamic output handle."),maxAttempts:G.number().min(1).max(10).default(3).describe("Maximum retry attempts for invalid input before following noMatch (1-10)."),audio:J$.optional().describe("Voice audio prompt played before collecting DTMF input. If omitted, caller hears nothing before digit collection."),voiceTimeout:G.number().min(1).max(60).default(5).describe("Seconds to wait for DTMF input in voice mode (1-60)."),text:G.string().default("").describe("Chat message text displayed above buttons. Supports template expressions."),invalidMessage:G.string().optional().describe("Chat message sent when input doesn't match any option. Supports template expressions.")}),eq=C({meta:{type:"menu",module:"core",nameKey:"editor:nodes.menu.name",descriptionKey:"editor:nodes.menu.description",color:"violet",icon:"ListOrdered",category:"interaction",order:2,nature:"composite",display:"full",channel:"both",outputs:($)=>{return[...($.options??[]).map((q)=>typeof q==="object"&&q!=null?q:null).filter((q)=>q!=null&&typeof q.id==="string"&&q.id!=="").map((q)=>({key:`option:${q.id}`,labelKey:q.label})),{key:"noMatch",labelKey:"editor:handles.noMatch"},{key:"error",labelKey:"editor:handles.error"}]}},configSchema:sq,producedVariables:[{name:"selectedId",type:"string",descriptionKey:"editor:vars.menuSelectedId"},{name:"selectedLabel",type:"string",descriptionKey:"editor:vars.menuSelectedLabel"},{name:"digits",type:"string",descriptionKey:"editor:vars.menuDigits"},{name:"attempts",type:"number",descriptionKey:"editor:vars.menuAttempts"}]});var $W=G.object({connector_id:G.string().default("").describe("Public id of the connector that provides phone.lookup (a Twilio account). Required for execution."),number:G.string().default("{{Start.callerid}}").describe("Number expression. Supports {{variables}}. Normalized with the platform E.164 rule: a number without a country code is completed with the country below, or the organization's default country."),default_country:G.string().regex(/^([A-Za-z]{2})?$/u,{error:"editor:validation.whatsappCountry"}).default("").describe("ISO 3166-1 alpha-2 country (e.g. BR) that completes numbers written without a country code. Empty uses the organization's default country."),line_type:G.boolean().default(!1).describe("Also fetch line type and carrier. Twilio charges US$ 0,008 per query; format validation alone is free.")}),UW=C({meta:{type:"phoneLookup",module:"core",nameKey:"editor:nodes.phoneLookup.name",descriptionKey:"editor:nodes.phoneLookup.description",color:"blue",icon:"PhoneForwarded",category:"data",nature:"action",display:"compact",channel:"both",order:9,requires:"phone.lookup",connector:{kind:"twilio",configKey:"connector_id"},outputs:[{key:"valid",labelKey:"editor:handles.valid"},{key:"invalid",labelKey:"editor:handles.invalid"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:$W,producedVariables:[{name:"phone_number",type:"string",descriptionKey:"editor:vars.phoneLookup.phoneNumber"},{name:"national_format",type:"string",descriptionKey:"editor:vars.phoneLookup.nationalFormat"},{name:"country_code",type:"string",descriptionKey:"editor:vars.phoneLookup.countryCode"},{name:"line_type",type:"string",descriptionKey:"editor:vars.phoneLookup.lineType"},{name:"carrier_name",type:"string",descriptionKey:"editor:vars.phoneLookup.carrierName"},{name:"line_type_error",type:"string",descriptionKey:"editor:vars.phoneLookup.lineTypeError"}]});var QW=G.object({audio:J$.default({tts:{text:""}}).describe("Audio to play. Use TTS (text-to-speech) or a pre-recorded audio file.")}),KW=C({meta:{type:"playback",module:"core",nameKey:"editor:nodes.playback.name",descriptionKey:"editor:nodes.playback.description",color:"blue",icon:"Volume2",category:"legacy",nature:"action",display:"full",channel:"voice",order:0,deprecated:!0,replacedBy:"tell",outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:QW,producedVariables:[]});var qW=G.object({enabled:G.boolean().optional(),samplingPercentage:G.number().int().min(0).max(100).optional()}),WW=C({meta:{type:"recording",module:"core",nameKey:"editor:nodes.recording.name",descriptionKey:"editor:nodes.recording.description",color:"teal",icon:"Mic",category:"media",nature:"sideEffect",display:"compact",channel:"voice",order:0,outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:qW,producedVariables:[{name:"status",type:"string",descriptionKey:"editor:vars.recordingStatus"}]});var JW=G.object({connector_id:G.string().default("").describe("Public id of the connector that provides voice.agent (a Retell account). Required for execution."),agent_id:G.string().default("").describe("Id of the Retell agent that answers the call. Required for execution."),agent_name:G.string().default("").describe("Display name of the chosen Retell agent, for logs and the editor."),variables:G.record(G.string(),G.string()).default({}).describe("Key-value pairs sent to the agent. Every value supports {{variables}}."),max_duration_minutes:G.number().min(1).max(60).default(10).describe("Maximum call duration in minutes (1-60). The bridge ends on timeout."),result_wait_seconds:G.number().int().min(0).max(60).default(15).describe("How long to wait for Retell's post-call extraction before continuing.")}),GW=C({meta:{type:"retellAgent",module:"ai",nameKey:"editor:nodes.retellAgent.name",descriptionKey:"editor:nodes.retellAgent.description",color:"iris",icon:"AudioLines",category:"handling",order:3,nature:"composite",display:"full",channel:"voice",requires:"voice.agent",connector:{kind:"retell",configKey:"connector_id"},outputs:[{key:"completed",labelKey:"editor:handles.completed"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:JW,producedVariables:[{name:"duration_ms",type:"number",descriptionKey:"editor:vars.retellAgent.durationMs"},{name:"provider_call_id",type:"string",descriptionKey:"editor:vars.retellAgent.providerCallId"},{name:"ended_reason",type:"string",descriptionKey:"editor:vars.retellAgent.endedReason"},{name:"summary",type:"string",descriptionKey:"editor:vars.retellAgent.summary"},{name:"analysis_pending",type:"string",descriptionKey:"editor:vars.retellAgent.analysisPending"},{name:"output.*",type:"string",descriptionKey:"editor:vars.retellAgent.output"}]});var lx=G.object({label:G.string().min(1).describe("Intent name. Creates a dynamic output handle 'intent:<label>'."),description:G.string().default("").describe("Description of what this intent means, used for LLM classification.")}),jW=G.object({input:G.string().default("").describe("Template expression to evaluate, e.g. '{{resposta}}'. The resolved text is classified by AI."),intents:G.array(lx).default([]).describe("List of intents the LLM should classify the input into. Each creates a dynamic output handle."),instructions:G.string().default("").describe("Additional instructions for the LLM intent classifier.")}),YW=C({meta:{type:"routeAi",module:"ai",nameKey:"editor:nodes.routeAi.name",descriptionKey:"editor:nodes.routeAi.description",color:"plum",icon:"BrainCircuit",category:"routing",order:1,nature:"routing",display:"full",channel:"both",outputs:($)=>{return[...($.intents??[]).map((q)=>q.label).filter((q)=>typeof q==="string"&&q!=="").map((q)=>({key:`intent:${q}`,labelKey:q})),{key:"notApplicable",labelKey:"editor:handles.notApplicable"},{key:"error",labelKey:"editor:handles.error"}]}},configSchema:jW,producedVariables:[{name:"intent",type:"string",descriptionKey:"editor:vars.routeAi.intent"},{name:"confidence",type:"number",descriptionKey:"editor:vars.routeAi.confidence"}]});var HW=G.object({digits:G.string().min(1,{error:"editor:validation.digitsRequired"}).default("").describe("DTMF digits to send (0-9, *, #). Supports template expressions.")}),XW=C({meta:{type:"sendDtmf",module:"core",nameKey:"editor:nodes.sendDtmf.name",descriptionKey:"editor:nodes.sendDtmf.description",color:"bronze",icon:"Hash",category:"handling",order:2,nature:"sideEffect",display:"compact",channel:"voice",outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:HW,producedVariables:[{name:"dtmf",type:"string",descriptionKey:"editor:vars.dtmf"}]});var ZW=G.object({connector_id:G.string().default("").describe("Public id of the connector that provides sms.send (a Twilio account). Required for execution."),from:G.string().default("").describe("Sender expression: empty uses the connector's default sender, otherwise a Messaging Service SID (MG...) or an E.164 number."),to:G.string().default("{{Start.callerid}}").describe("Recipient expression. Supports {{variables}}. Normalized with the platform E.164 rule: a number without a country code is completed with the country below, or the organization's default country."),default_country:G.string().regex(/^([A-Za-z]{2})?$/u,{error:"editor:validation.whatsappCountry"}).default("").describe("ISO 3166-1 alpha-2 country (e.g. BR) that completes recipients written without a country code. Empty uses the organization's default country."),body:G.string().default("").describe("Message text. Supports {{variables}}; secrets are not allowed in the body."),transliterate:G.boolean().default(!1).describe("Replace accented letters by their base letter before sending, so the message fits 160 characters per SMS instead of 70.")}),BW=C({meta:{type:"sendSms",module:"core",nameKey:"editor:nodes.sendSms.name",descriptionKey:"editor:nodes.sendSms.description",color:"green",icon:"MessageSquare",category:"data",nature:"sideEffect",display:"compact",channel:"both",order:8,requires:"sms.send",connector:{kind:"twilio",configKey:"connector_id"},outputs:[{key:"sent",labelKey:"editor:handles.sent"},{key:"failed",labelKey:"editor:handles.failed"}]},configSchema:ZW,producedVariables:[{name:"message_sid",type:"string",descriptionKey:"editor:vars.sendSms.messageSid"},{name:"segments",type:"number",descriptionKey:"editor:vars.sendSms.segments"},{name:"encoding",type:"string",descriptionKey:"editor:vars.sendSms.encoding"},{name:"error_code",type:"string",descriptionKey:"editor:vars.sendSms.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.sendSms.errorMessage"}]});var VW=G.object({prefix:G.string().max(16,{error:"editor:validation.prefixMaxLength"}).default("").describe("Short prefix prepended to the sequence (e.g. 'SAC', '200')."),dateFormat:G.enum(["none","yyyyMMdd","yyMMdd","yyyyMM","ddMMyyyy","yyyyMMddHHmmss"]).default("yyyyMMdd").describe("Date format inserted between prefix and counter."),padding:G.number().int().min(1,{error:"editor:validation.paddingMin"}).max(12,{error:"editor:validation.paddingMax"}).default(5).describe("Minimum digits for the counter (zero-padded). Overflow uses natural width."),resetPeriod:G.enum(["daily","monthly","never"]).default("daily").describe("When the counter resets to 1. Uses org timezone for boundary.")}),MW=C({meta:{type:"sequence",module:"core",nameKey:"editor:nodes.sequence.name",descriptionKey:"editor:nodes.sequence.description",color:"mint",icon:"Hash",category:"data",order:6,nature:"sideEffect",display:"compact",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:VW,producedVariables:[{name:"value",type:"string",descriptionKey:"editor:vars.sequence.value"},{name:"spoken",type:"string",descriptionKey:"editor:vars.sequence.spoken"},{name:"counter",type:"string",descriptionKey:"editor:vars.sequence.counter"},{name:"date",type:"string",descriptionKey:"editor:vars.sequence.date"}]});var rx=G.object({key:G.string().describe("Variable name. Readable as '{{vars.key}}' and through the block's generated namespace."),value:G.string().describe("Value to assign. Supports template expressions like '{{start.callerid}}'.")}),DW=G.object({assignments:G.array(rx).min(1,{error:"editor:validation.noAssignments"}).default([]).describe("List of variable assignments. At least one required.")}),PW=C({meta:{type:"setVariable",module:"core",nameKey:"editor:nodes.setVariable.name",descriptionKey:"editor:nodes.setVariable.description",color:"teal",icon:"Variable",category:"data",order:4,nature:"sideEffect",display:"compact",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:DW,producedVariables:($)=>$.assignments.map((U)=>({name:U.key,type:"string",descriptionKey:"editor:vars.custom"}))});var NW=G.object({autoAnswer:G.boolean().optional().describe("Auto-answer incoming call before processing. Disable for pre-answer routing."),channelType:G.enum(QX).default("both").describe("Plan channel type.")}),LW=C({meta:{type:"start",module:"core",nameKey:"editor:nodes.start.name",descriptionKey:"editor:nodes.start.description",color:"jade",icon:"Play",category:"interaction",order:0,nature:"flow",display:"full",channel:"both",outputs:($)=>{let U=$.channelType;if((typeof U==="string"?U:"voice")==="both")return[{key:"voice",labelKey:"editor:handles.voice"},{key:"chat",labelKey:"editor:handles.chat"}];return[{key:"next",labelKey:"editor:handles.next"}]}},configSchema:NW,producedVariables:[{name:"uuid",type:"string",descriptionKey:"editor:vars.uuid"},{name:"callerid",type:"string",descriptionKey:"editor:vars.callerid"},{name:"did",type:"string",descriptionKey:"editor:vars.did"},{name:"time",type:"string",descriptionKey:"editor:vars.time"},{name:"mode",type:"string",descriptionKey:"editor:vars.mode"},{name:"recording",type:"string",descriptionKey:"editor:vars.recordingStatus"}]});var _W=G.object({planId:G.string().min(1,{error:"editor:validation.planIdRequired"}).default("").describe("ID of a published visual plan to execute as a sub-flow. Must be published."),args:G.record(G.string().regex(/^[A-Z_]\w*$/i).max(64),G.string().max(512)).default({}),endCallOnChildHangup:G.boolean().default(!1).describe("When true, a Hangup node executed inside the child plan really ends the call/session. When false (default), the child's hangup is absorbed: it only marks the end of the sub-plan and control returns to this node's 'next' output.")}),IW=C({meta:{type:"subPlan",module:"core",nameKey:"editor:nodes.subPlan.name",descriptionKey:"editor:nodes.subPlan.description",color:"purple",icon:"Layers",category:"data",order:2,nature:"flow",display:"full",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:_W,producedVariables:()=>[{name:"*",type:"string",descriptionKey:"editor:vars.subPlanOutput"},{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"},{name:"child_error_code",type:"string",descriptionKey:"editor:vars.childErrorCode"}]});var ix=G.object({pattern:G.string().min(1,{error:"editor:validation.casePatternRequired"}).default("").describe("Value to match against the expression. Creates a 'match:<pattern>' output.")}),FW=G.object({expression:G.string().min(1,{error:"editor:validation.expressionRequired"}).default("").describe("Template expression to evaluate, e.g., '{{ivr.digits}}'. Matched against case patterns."),cases:G.array(ix).default([]).describe("List of patterns to match. Each creates a dynamic output handle 'match:<pattern>'.")}),xW=C({meta:{type:"switchCase",module:"core",nameKey:"editor:nodes.switchCase.name",descriptionKey:"editor:nodes.switchCase.description",color:"orange",icon:"GitBranch",category:"routing",order:0,nature:"routing",display:"full",channel:"both",outputs:($)=>{return[...($.cases??[]).map((q)=>typeof q==="string"?q:q.pattern).filter((q)=>typeof q==="string"&&q!=="").map((q)=>({key:`match:${q}`,labelKey:q})),{key:"fallback",labelKey:"editor:handles.fallback"},{key:"error",labelKey:"editor:handles.error"}]}},configSchema:FW,producedVariables:[{name:"destination",type:"string",descriptionKey:"editor:vars.switchDestination"}]});var dx=G.object({type:G.literal("text"),text:G.string().min(1)}),ox=G.object({type:G.literal("media"),mediaType:G.enum(["image","audio","video","document"]),url:G.string().min(1),caption:G.string().optional()}),nx=G.object({type:G.literal("location"),lat:G.number(),lng:G.number()}),px=G.object({type:G.literal("button_reply"),buttonId:G.string().min(1),buttonText:G.string()}),tx=G.object({type:G.literal("list_reply"),listId:G.string().min(1),listTitle:G.string()}),ax=G.object({type:G.literal("command"),command:G.string().min(1),args:G.string().optional()}),wW=G.discriminatedUnion("type",[dx,ox,nx,px,tx,ax]),AW=G.object({id:G.string().min(1),label:G.string().min(1)}),sx=G.object({id:G.string().min(1),title:G.string().min(1),description:G.string().optional()}),LX=G.object({title:G.string().min(1),items:G.array(sx).min(1)}),_X=G.object({title:G.string().min(1),description:G.string().optional(),imageUrl:G.string().optional(),buttons:G.array(AW).default([])}),ex=G.object({type:G.literal("text"),text:G.string().min(1),markdown:G.boolean().optional()}),$w=G.object({type:G.literal("media"),mediaType:G.enum(["image","audio","video","document"]),url:G.string().min(1),caption:G.string().optional()}),Uw=G.object({type:G.literal("location"),lat:G.number(),lng:G.number(),label:G.string().optional()}),Qw=G.object({type:G.literal("buttons"),text:G.string().min(1),buttons:G.array(AW).min(1)}),Kw=G.object({type:G.literal("list"),text:G.string().min(1),buttonText:G.string().min(1),sections:G.array(LX).min(1)}),qw=G.object({type:G.literal("carousel"),cards:G.array(_X).min(1)}),Ww=G.object({type:G.literal("template"),templateId:G.string().min(1),params:G.record(G.string(),G.string()).default({})}),N6=G.discriminatedUnion("type",[ex,$w,Uw,Qw,Kw,qw,Ww]),Jw=N6.optional().catch(void 0);var vW=G.object({audio:J$.optional().describe("Audio to play via TTS, a pre-recorded file, or a remote URL. Used in voice plans."),content:N6.optional().describe("Message content to send in chat. Used in chat plans.")});function IX($){return typeof $==="object"&&$!==null&&"url"in $}var kW=C({meta:{type:"tell",module:"core",nameKey:"editor:nodes.tell.name",descriptionKey:"editor:nodes.tell.description",color:"blue",icon:"Volume2",category:"interaction",order:1,nature:"action",display:"full",channel:"both",outputs:($)=>IX($.audio)?[{key:"next",labelKey:"editor:handles.next"},{key:"error",labelKey:"editor:handles.error"}]:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:vW,producedVariables:($)=>IX($.audio)?[{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"}]:[]});var RW=G.object({scheduleId:G.string().optional().describe("Schedule ID for time-based routing. Routes to onHours/offHours/holiday outputs.")}),zW=C({meta:{type:"timeRouting",module:"core",nameKey:"editor:nodes.timeRouting.name",descriptionKey:"editor:nodes.timeRouting.description",color:"gold",icon:"Clock",category:"routing",order:2,nature:"routing",display:"full",channel:"both",outputs:[{key:"onHours",labelKey:"editor:handles.onHours"},{key:"offHours",labelKey:"editor:handles.offHours"},{key:"holiday",labelKey:"editor:handles.holiday"}]},configSchema:RW,producedVariables:[{name:"result",type:"string",descriptionKey:"editor:vars.timeResult"},{name:"holiday",type:"string",descriptionKey:"editor:vars.holiday"}]});var bW=G.object({name:G.string().min(1,{error:"editor:validation.trafficSplitPathNameRequired"}).default("").describe("Path name. Creates a 'path:<name>' output handle."),weight:G.number().int().min(0).max(100).default(1).describe("Relative share of this path (0-100). Zero disables it without deleting it.")}),OW=G.object({paths:G.array(bW).default([{name:"A",weight:50},{name:"B",weight:50}]).describe("Weighted paths. Each creates a dynamic output handle 'path:<name>'."),mode:G.enum(["contact","call","exact"]).default("contact").describe("'contact' keeps the same contact on the same path (stateless hash); 'call' draws per call (stateless, approximate); 'exact' rotates through a Redis counter so the proportion closes even at low volume.")}),TW=C({meta:{type:"trafficSplit",module:"core",nameKey:"editor:nodes.trafficSplit.name",descriptionKey:"editor:nodes.trafficSplit.description",color:"iris",icon:"Split",category:"routing",order:4,nature:"routing",display:"full",channel:"both",outputs:($)=>{let U=$.paths??[],K=[],q=new Set;for(let Q of U){let W=typeof Q==="object"&&Q!=null?Q.name:void 0;if(typeof W!=="string"||W===""||q.has(W))continue;q.add(W),K.push(W)}return[...K.map((Q)=>({key:`path:${Q}`,labelKey:Q})),{key:"error",labelKey:"editor:handles.error"}]}},configSchema:OW,producedVariables:[{name:"variant",type:"string",descriptionKey:"editor:vars.trafficSplit.variant"},{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"}]});var SW=G.object({enabled:G.boolean().optional(),scope:G.enum(["from_here","whole_recording"]).optional(),samplingPercentage:G.number().int().min(0).max(100).optional(),language:G.string().optional(),minDurationSeconds:G.number().int().min(0).max(I4).optional(),speechRequirement:G.enum(R1).optional(),anonymizeEnabled:G.boolean().optional(),speechAnalyticsEnabled:G.boolean().optional(),sentimentEnabled:G.boolean().optional(),transcriptionType:G.enum(r1).optional()}),CW=C({meta:{type:"transcription",module:"ai",nameKey:"editor:nodes.transcription.name",descriptionKey:"editor:nodes.transcription.description",color:"violet",icon:"Captions",category:"media",nature:"sideEffect",display:"compact",channel:"voice",order:1,outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:SW,producedVariables:[{name:"status",type:"string",descriptionKey:"editor:vars.transcriptionStatus"}]});var Gw=G.object({key:G.string().describe("Attached-data field name shown to the agent / CRM (e.g. 'Nome')."),value:G.string().default("").describe("Field value. Supports template expressions like '{{cliente.nome}}'.")}),EW=G.object({method:G.enum(["bridge","transfer"]).default("bridge").describe("Transfer method. 'bridge' keeps call control; 'transfer' hands off completely."),destinations:G.array(G.string()).default([]).describe("SIP URIs or phone numbers to dial. At least one required. Tried in order."),timeout:G.number().min(5).max(120).optional().describe("Ring timeout in seconds per destination (5-120). Omit for carrier default."),attachedData:G.array(Gw).default([]).describe("Key/value pairs delivered to the agent at transfer time (screen-pop). Values support templates.").superRefine(($,U)=>{let K=new Set;$.forEach((q,Q)=>{let W=q.key.trim();if(W===""){U.addIssue({code:"custom",message:"editor:validation.attachedKeyRequired",path:[Q,"key"]});return}if(K.has(W))U.addIssue({code:"custom",message:"editor:validation.duplicateAttachedKey",path:[Q,"key"]});K.add(W)})})}),yW=C({meta:{type:"transfer",module:"core",nameKey:"editor:nodes.transfer.name",descriptionKey:"editor:nodes.transfer.description",color:"amber",icon:"PhoneForwarded",category:"handling",order:0,nature:"action",display:"full",channel:"both",outputs:[{key:"answered",labelKey:"editor:handles.answered"},{key:"busy",labelKey:"editor:handles.busy"},{key:"noAnswer",labelKey:"editor:handles.noAnswer"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:EW,producedVariables:[{name:"status",type:"string",descriptionKey:"editor:vars.transferStatus"},{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"}]});var gW=G.object({connector_id:G.string().default("").describe("Public id of the connector that provides voice.agent (a Vapi account). Required for execution."),assistant_id:G.string().default("").describe("Id of the Vapi assistant that answers the call. Required for execution."),assistant_name:G.string().default("").describe("Display name of the chosen Vapi assistant, for logs and the editor."),variables:G.record(G.string(),G.string()).default({}).describe("Key-value pairs sent to the agent. Every value supports {{variables}}."),max_duration_minutes:G.number().min(1).max(60).default(10).describe("Maximum call duration in minutes (1-60). The bridge ends on timeout."),result_wait_seconds:G.number().int().min(0).max(60).default(15).describe("How long to wait for Vapi's end of call report before continuing.")}),uW=C({meta:{type:"vapiAgent",module:"ai",nameKey:"editor:nodes.vapiAgent.name",descriptionKey:"editor:nodes.vapiAgent.description",color:"iris",icon:"AudioWaveform",category:"handling",order:4,nature:"composite",display:"full",channel:"voice",requires:"voice.agent",connector:{kind:"vapi",configKey:"connector_id"},outputs:[{key:"completed",labelKey:"editor:handles.completed"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:gW,producedVariables:[{name:"duration_ms",type:"number",descriptionKey:"editor:vars.vapiAgent.durationMs"},{name:"provider_call_id",type:"string",descriptionKey:"editor:vars.vapiAgent.providerCallId"},{name:"ended_reason",type:"string",descriptionKey:"editor:vars.vapiAgent.endedReason"},{name:"summary",type:"string",descriptionKey:"editor:vars.vapiAgent.summary"},{name:"analysis_pending",type:"string",descriptionKey:"editor:vars.vapiAgent.analysisPending"},{name:"output.*",type:"string",descriptionKey:"editor:vars.vapiAgent.output"}]});var fW="Enviamos um código por SMS. Digite o código no teclado do telefone.",mW=G.object({connector_id:G.string().default("").describe("Public id of the connector that provides verify.otp (a Twilio account). Required for execution."),service_sid:G.string().default("").describe("Verify Service SID (VA...) whose code length and sender configuration the block uses."),to:G.string().default("{{Start.callerid}}").describe("Recipient expression. Supports {{variables}}. Normalized with the platform E.164 rule: a number without a country code is completed with the country below, or the organization's default country."),default_country:G.string().regex(/^([A-Za-z]{2})?$/u,{error:"editor:validation.whatsappCountry"}).default("").describe("ISO 3166-1 alpha-2 country (e.g. BR) that completes recipients written without a country code. Empty uses the organization's default country."),channel:G.enum(["sms","whatsapp","call"]).default("sms").describe("How the code reaches the contact: sms, whatsapp or call. Twilio sends it; NIVA needs no extra setup."),prompt:J$.default({tts:{text:fW}}).describe("Audio prompt asking for the code, played with the plan's voice. In chat, its text is sent."),max_attempts:G.number().int().min(1,{error:"editor:validation.attemptsMin"}).max(5,{error:"editor:validation.attemptsMax"}).default(3).describe("Maximum wrong-code attempts before the block leaves by rejected (1-5)."),timeout_seconds:G.number().int().min(1,{error:"editor:validation.timeoutMin"}).max(60,{error:"editor:validation.timeoutMax"}).default(10).describe("Seconds to wait for the code after the prompt (1-60).")}),hW=C({meta:{type:"verifyCode",module:"core",nameKey:"editor:nodes.verifyCode.name",descriptionKey:"editor:nodes.verifyCode.description",color:"purple",icon:"ShieldCheck",category:"data",nature:"composite",display:"full",channel:"both",order:10,requires:"verify.otp",connector:{kind:"twilio",configKey:"connector_id"},sensitiveInput:!0,outputs:[{key:"approved",labelKey:"editor:handles.approved"},{key:"rejected",labelKey:"editor:handles.rejected"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:mW,producedVariables:[{name:"status",type:"string",descriptionKey:"editor:vars.verifyCode.status"},{name:"attempts",type:"number",descriptionKey:"editor:vars.verifyCode.attempts"},{name:"channel",type:"string",descriptionKey:"editor:vars.verifyCode.channel"}]});var jw=G.object({label:G.string().min(1).describe("Intent name. Creates a dynamic output handle 'intent:<label>'."),description:G.string().default("").describe("Description of what this intent means, used for LLM classification.")}),Yw=G.object({language:G.string().optional().describe("BCP 47 language code for speech recognition (e.g., 'pt-BR'). Omit for plan default."),initial_timeout_s:G.number().min(3).max(60).default(10).describe("Maximum seconds to wait for speech to begin (3-60)."),timeout_s:G.number().min(1).max(30).default(3).describe("Seconds of post-speech silence before stopping recording (1-30)."),max_duration_s:G.number().min(1).max(60).default(15).describe("Maximum recording duration in seconds (1-60)."),beep:G.boolean().default(!1).describe("Play a beep sound before starting to listen.")}),Hw=G.object({max_retries:G.number().min(0).max(5).default(2).describe("Maximum retries when speech is not recognized (0-5)."),prompt:J$.optional().describe("Audio played when retrying after unrecognized speech. Falls back to main prompt if not set.")});var cW=G.object({mode:G.enum(["intent","capture"]).default("intent").describe("'intent' classifies speech into configured intents; 'capture' transcribes speech without classification."),prompt:J$.default({tts:{text:""}}).describe("Audio prompt played before listening for speech."),intents:G.array(jw).default([]).describe("List of intents the LLM should classify speech into. Only used when mode is 'intent'."),classification_instructions:G.string().default("").describe("Additional instructions for the LLM intent classifier. Only used when mode is 'intent'."),listen:Yw.default({initial_timeout_s:10,timeout_s:3,max_duration_s:15,beep:!1}).describe("Listening configuration: initial wait, post-speech silence, max duration, language, beep."),processing_audio:J$.optional().describe("Audio played while the AI processes the speech. Optional."),retry:Hw.default({max_retries:2}).describe("Retry behavior when speech is not recognized.")}),lW=C({meta:{type:"voiceRecognition",module:"ai",nameKey:"editor:nodes.voiceRecognition.name",descriptionKey:"editor:nodes.voiceRecognition.description",color:"cyan",icon:"Mic",category:"legacy",nature:"composite",display:"full",channel:"voice",order:2,deprecated:!0,replacedBy:"capture",outputs:($)=>{if(($.mode??"intent")==="capture")return[{key:"captured",labelKey:"editor:handles.captured"},{key:"noInput",labelKey:"editor:handles.noInput"},{key:"maxRetries",labelKey:"editor:handles.maxRetries"},{key:"error",labelKey:"editor:handles.error"}];return[...($.intents??[]).map((Q)=>typeof Q==="string"?Q:Q.label).filter((Q)=>typeof Q==="string"&&Q!=="").map((Q)=>({key:`intent:${Q}`,labelKey:Q})),{key:"noInput",labelKey:"editor:handles.noInput"},{key:"notApplicable",labelKey:"editor:handles.notApplicable"},{key:"maxRetries",labelKey:"editor:handles.maxRetries"},{key:"error",labelKey:"editor:handles.error"}]}},configSchema:cW,producedVariables:($)=>{if($.mode==="capture")return[{name:"speech",type:"string",descriptionKey:"editor:vars.voiceRecognition.speech"}];return[{name:"speech",type:"string",descriptionKey:"editor:vars.voiceRecognition.speech"},{name:"confidence",type:"number",descriptionKey:"editor:vars.voiceRecognition.confidence"},{name:"intent",type:"string",descriptionKey:"editor:vars.voiceRecognition.intent"}]}});var rW=G.object({method:G.enum(["POST","PUT","PATCH","GET","DELETE"]).default("POST").describe("HTTP method for the request."),url:P6.describe("Destination URL. Supports template expressions, e.g., 'https://hooks.example.com/{{start.callerid}}'."),headers:G.record(G.string(),G.string()).optional().describe("HTTP headers as key-value pairs. Values support template expressions."),body:G.string().optional().describe("Request body (JSON string). Template expressions allowed. Only for POST/PUT/PATCH/DELETE.")}),iW=C({meta:{type:"webhook",module:"core",nameKey:"editor:nodes.webhook.name",descriptionKey:"editor:nodes.webhook.description",color:"violet",icon:"Webhook",category:"data",order:1,nature:"sideEffect",display:"compact",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:rW,producedVariables:[]});var FX=G.record(G.string(),G.string()).default({}),dW=G.object({connectorId:G.string().default("").describe("Public id of the connector that provides whatsapp.templates (e.g. a WhatsApp Business connector)."),phoneNumberId:G.string().default("").describe("Id of the WhatsApp number the message is sent from, one of the connector's numbers."),template:G.object({name:G.string().default(""),language:G.string().default("")}).default({name:"",language:""}).describe("The approved message template to send, by name and language code (e.g. boleto / pt_BR)."),to:G.string().default("{{Start.callerid}}").describe("Recipient expression. Supports {{variables}}. Normalized with the platform E.164 rule: numbers without a country code are completed with the country below, or the organization's default country."),defaultCountry:G.string().regex(/^([A-Za-z]{2})?$/u,{error:"editor:validation.whatsappCountry"}).default("").describe("ISO 3166-1 alpha-2 country (e.g. BR) that completes recipients written without a country code. Empty uses the organization's default country."),parameters:G.object({header:G.string().optional().describe("Header value: the text variable of a text header, or the media URL of an image/video/document header."),body:FX.describe("Body variable values, keyed by variable name ('1', '2' or 'first_name')."),buttons:FX.describe("URL button suffix values, keyed by the button's index ('0', '1', ...).")}).default({body:{},buttons:{}}).describe("Template variable values. Every value supports {{variables}}.")}),oW=C({meta:{type:"whatsappTemplate",module:"core",nameKey:"editor:nodes.whatsappTemplate.name",descriptionKey:"editor:nodes.whatsappTemplate.description",color:"green",icon:"MessageCircle",category:"data",nature:"sideEffect",display:"compact",channel:"both",order:7,requires:"whatsapp.templates",connector:{kind:"whatsapp_business",configKey:"connectorId"},outputs:[{key:"sent",labelKey:"editor:handles.sent"},{key:"failed",labelKey:"editor:handles.failed"}]},configSchema:dW,producedVariables:[{name:"message_id",type:"string",descriptionKey:"editor:vars.whatsappMessageId"},{name:"error_code",type:"string",descriptionKey:"editor:vars.whatsappErrorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.whatsappErrorMessage"}]});var t$={start:LW,playback:KW,ivr:tq,collectDigits:Tq,transfer:yW,hangup:dq,timeRouting:zW,switchCase:xW,trafficSplit:TW,setVariable:PW,sequence:MW,counter:Cq,httpRequest:nq,webhook:iW,whatsappTemplate:oW,sendSms:BW,phoneLookup:UW,verifyCode:hW,dataTransform:mq,subPlan:IW,sendDtmf:XW,aiAgent:Lq,retellAgent:GW,vapiAgent:uW,elevenlabsAgent:cq,voiceRecognition:lW,tell:kW,menu:eq,capture:Rq,routeAi:YW,channelRouter:bq,addToDnc:Pq,apiSwitch:vq,enableRecord:rq,recording:WW,transcription:CW,analysis:Fq},a$=Object.fromEntries(Object.entries(t$).map(([$,U])=>[$,U.meta]));var el=Number.MAX_SAFE_INTEGER;var nW=["active","expired","suspended","poc"],xX=G.object({enabled:G.boolean(),limits:G.record(G.string(),G.union([G.number(),G.string(),G.boolean(),G.array(G.string())])).default({})}),Nw=G.object({customerId:G.string(),customerName:G.string().optional(),serial:G.string(),status:G.enum(nW),issuedAt:G.coerce.date(),expiresAt:G.coerce.date().nullable(),gracePeriodDays:G.number().int().min(0),modules:G.record(G.string(),xX),isExpired:G.boolean(),isInGracePeriod:G.boolean(),daysUntilExpiry:G.number().nullable()}),Lw=G.object({voice:G.number().int().default(0),chat:G.number().int().default(0)}).optional(),_w=G.object({customer_id:G.string().min(1),customer_name:G.string().min(1).optional(),serial:G.string().min(1),status:G.enum(nW),issued_at:G.coerce.date(),expires_at:G.coerce.date().nullable().default(null),grace_period_days:G.number().int().min(0).default(0),max_concurrent_channels:Lw,modules:G.record(G.string(),xX)});var L6=["yes_no","choice","scale"],wX=["caller","agent","both"],_6=["info","warning","critical"],w0=["worse","better","neutral"],Iw=/^[a-z][a-z0-9_]{0,63}$/,Fw=/^[a-z0-9][a-z0-9_]{0,47}$/,AX=G.object({key:G.string().regex(Fw),label:G.string().min(1).max(80),description:G.string().max(240).optional(),archived:G.boolean().default(!1)}),vX=G.union([G.object({answer:G.enum(["yes","no"])}),G.object({options:G.array(G.string()).min(1)}),G.object({level_at_least:G.number()}),G.object({level_at_most:G.number()})]),xw=G.object({when:vX,severity:G.enum(_6),bell:G.boolean().default(!1)}),ww=G.object({slug:G.string().regex(Iw),name:G.string().trim().min(1).max(80),question:G.string().trim().min(1).max(500),kind:G.enum(L6),options:G.array(AX).min(2).max(12).optional(),levels:G.array(G.string().min(1).max(40)).min(3).max(5).optional(),higher_is:G.enum(w0).optional(),speaker:G.enum(wX),scope:G.object({node_types:G.array(G.string().min(1)).min(1).max(20)}).nullable(),live:G.boolean(),alert:xw.nullable()});function kX($){return $.higher_is??"worse"}function Aw($,U){if($.kind==="choice"){if($.options===void 0){U.addIssue({code:"custom",message:"signals:validation.optionsRequired",path:["options"]});return}let K=$.options.map((q)=>q.key);if(new Set(K).size!==K.length)U.addIssue({code:"custom",message:"signals:validation.optionKeyUnique",path:["options"]});if($.options.filter((q)=>!q.archived).length<2)U.addIssue({code:"custom",message:"signals:validation.twoActiveOptions",path:["options"]})}else if($.options!==void 0)U.addIssue({code:"custom",message:"signals:validation.optionsChoiceOnly",path:["options"]})}function vw($,U){if($.kind==="scale"){if($.levels===void 0)U.addIssue({code:"custom",message:"signals:validation.levelsRequired",path:["levels"]})}else{if($.levels!==void 0)U.addIssue({code:"custom",message:"signals:validation.levelsScaleOnly",path:["levels"]});if($.higher_is!==void 0)U.addIssue({code:"custom",message:"signals:validation.higherIsScaleOnly",path:["higher_is"]})}}function kw($,U){if($.levels===void 0)return!1;let K=kX($),q=$.levels.length-1;if("level_at_least"in U){let Q=U.level_at_least;return K!=="better"&&Number.isInteger(Q)&&Q>=1&&Q<=q}if("level_at_most"in U){let Q=U.level_at_most;return K!=="worse"&&Number.isInteger(Q)&&Q>=0&&Q<=q-1}return!1}function Rw($){if($.alert===null)return!0;let U=$.alert.when;switch($.kind){case"yes_no":return"answer"in U;case"choice":return"options"in U&&$.options!==void 0&&U.options.every((K)=>$.options?.some((q)=>q.key===K&&!q.archived)===!0);case"scale":return kw($,U)}}function RX($,U){if(Aw($,U),vw($,U),!Rw($))U.addIssue({code:"custom",message:"signals:validation.whenMustMatchKind",path:["alert","when"]})}var I6=ww.superRefine(RX);var h8=G.object({channel:G.union([G.literal(0),G.literal(1)]),text:G.string(),isFinal:G.boolean(),confidence:G.number(),start:G.number(),end:G.number(),timestamp:G.string(),nodeId:G.string().optional(),nodeLabel:G.string().optional(),nodeType:G.string().optional(),redacted:G.boolean().optional()}),OX={signal:G.object({id:G.string().min(1),slug:G.string().min(1),name:G.string(),kind:G.enum(L6),severity:G.enum(_6).nullable(),bell:G.boolean()}),value:G.union([G.boolean(),G.string(),G.number(),G.null()]),value_label:G.string(),confidence:G.number(),at_seconds:G.number(),node:G.object({id:G.string(),label:G.string(),type:G.string()}).nullable(),late:G.boolean()},c8=G.object({type:G.literal("signal_value"),...OX}),l8=G.object({type:G.literal("signal_triggered"),...OX}),TX=G.discriminatedUnion("type",[c8,l8]),bw=G.discriminatedUnion("type",[G.object({type:G.literal("segment"),segment:h8}),c8,l8,G.object({type:G.literal("started"),backlog_seconds:G.number(),live_from:G.number()}),G.object({type:G.literal("caught_up")}),G.object({type:G.literal("ended")}),G.object({type:G.literal("error"),message:G.string()})]),Ow=G.discriminatedUnion("type",[G.object({type:G.literal("segment"),segment:h8}),G.object({type:G.literal("history"),segments:G.array(h8),signals:G.array(TX).optional()}),c8,l8,G.object({type:G.literal("starting")}),G.object({type:G.literal("started"),backlog_seconds:G.number(),live_from:G.number()}),G.object({type:G.literal("caught_up")}),G.object({type:G.literal("ended")}),G.object({type:G.literal("error"),message:G.string()}),G.object({type:G.literal("unavailable"),reason:G.enum(["not_recorded","no_credential","test_call"])})]),Tw=G.object({uuid:G.string(),action:G.enum(["start","stop"])}),SX=["not_live","provider_error","drain_timeout","redact_mid_call"],CX=G.object({startByte:G.number().int().min(0),endByte:G.number().int().min(0)}),Sw=G.object({complete:G.boolean(),reason:G.enum(SX).optional(),model:G.string(),redact:G.boolean(),coveredRanges:G.array(CX)});function W$($){return{...$,defaults:{...$.defaults,email:$.defaults.email??!1}}}var D1={enabled:!0,toast:!0},s$={enabled:!0,toast:!1},Cw={enabled:!1,toast:!1},Ew={freeswitch:"FreeSWITCH",database:"Database",redis:"Redis"},r8=($)=>Ew[$]??"Redis",P1=($,U,K)=>$===1?U:K,EX={"email.delivery_failed":W$({kind:"email.delivery_failed",area:"services",audience:"platform",severity:"warning",params:G.strictObject({}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/system/email",defaults:s$,en:{title:()=>"Email delivery failed",body:()=>"An email could not be delivered. Check the SMTP settings and server logs."},pt:{title:()=>"Falha no envio de e-mail",body:()=>"Um e-mail não pôde ser entregue. Confira o SMTP em Sistema > E-mail e os logs do servidor."}}),"service.down":W$({kind:"service.down",area:"services",audience:"platform",severity:"critical",params:G.strictObject({component:G.string()}),grouping:{mode:"incident"},groupKey:($)=>$.component,link:()=>"/dashboard",defaults:D1,en:{title:($)=>`${r8($.component)} offline`,body:($)=>`${r8($.component)} is unreachable.`},pt:{title:($)=>`${$.component} indisponível`,body:($)=>`Não foi possível acessar ${$.component}.`},webhook:{alertType:($)=>`service_offline:${$.component}`,resolvedTitle:($)=>`${r8($.component)} recovered`,resolvedBody:($)=>`${r8($.component)} is back online.`}}),"license.expiring":W$({kind:"license.expiring",area:"usage",audience:"platform",severity:"warning",params:G.strictObject({days:G.number(),expires_on:G.string()}),grouping:{mode:"incident"},groupKey:($)=>$.expires_on,link:()=>"/system/license",defaults:s$,en:{title:($)=>`License expires in ${$.days} ${P1($.days,"day","days")}`,body:($)=>`License expires in ${$.days} ${P1($.days,"day","days")}.`},pt:{title:()=>"Licença próxima do vencimento",body:($)=>`A licença vence em ${$.days} ${$.days===1?"dia":"dias"}.`},webhook:{alertType:()=>"license_expiring",metricValue:($)=>$.days,threshold:()=>30,resolvedTitle:()=>"License expiry warning closed",resolvedBody:()=>"The license was renewed or has expired."}}),"license.expired":W$({kind:"license.expired",area:"usage",audience:"platform",severity:"critical",params:G.strictObject({}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/system/license",defaults:D1,locked:!0,en:{title:()=>"License expired",body:()=>"NIVA license has expired."},pt:{title:()=>"Licença vencida",body:()=>"A licença da NIVA venceu."},webhook:{alertType:()=>"license_expired"}}),"storage.disk":W$({kind:"storage.disk",area:"services",audience:"platform",severity:"warning",params:G.strictObject({pct:G.number(),threshold:G.number()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/system/storage",defaults:s$,en:{title:($)=>`Disk usage ${$.pct}%`,body:($)=>`Disk usage at ${$.pct}%.`},pt:{title:()=>"Uso de disco elevado",body:($)=>`O uso do disco chegou a ${$.pct}%.`},webhook:{alertType:()=>"storage_high",metricValue:($)=>$.pct,threshold:($)=>$.threshold}}),"storage.recordings_blocked":W$({kind:"storage.recordings_blocked",area:"services",audience:"platform",severity:"warning",params:G.strictObject({used:G.number(),cap:G.number()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/system/storage",defaults:s$,en:{title:($)=>`Recording storage cap reached (${$.used} GB of ${$.cap} GB)`,body:($)=>`Recordings use ${$.used} GB against a ${$.cap} GB cap and none may be removed yet.`},pt:{title:()=>"Limite de armazenamento das gravações atingido",body:($)=>`As gravações ocupam ${$.used} GB de ${$.cap} GB e ainda não podem ser removidas.`},webhook:{alertType:()=>"recording_retention_blocked",metricValue:($)=>$.used,threshold:($)=>$.cap}}),"calls.error_rate":W$({kind:"calls.error_rate",area:"calls",audience:"organization",severity:"warning",params:G.strictObject({rate:G.number(),failures:G.number(),total:G.number(),threshold:G.number(),plan_name:G.string().optional()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/reports",defaults:D1,en:{title:($)=>`Call error rate ${$.rate}%`,body:($)=>`${$.failures}/${$.total} failed.`},pt:{title:()=>"Taxa de erros nas chamadas",body:($)=>`${$.failures} de ${$.total} chamadas falharam (${$.rate}%).`},webhook:{alertType:()=>"call_error_rate",metricValue:($)=>$.rate,threshold:($)=>$.threshold}}),"calls.plan_error_rate":W$({kind:"calls.plan_error_rate",area:"calls",audience:"organization",severity:"warning",params:G.strictObject({plan_id:G.string(),plan_name:G.string(),rate:G.number(),failures:G.number(),total:G.number(),threshold:G.number()}),grouping:{mode:"incident"},groupKey:($)=>$.plan_id,link:()=>"/reports",defaults:s$,en:{title:($)=>`${$.plan_name}: error rate ${$.rate}%`,body:($)=>`${$.failures}/${$.total} failed.`},pt:{title:($)=>`Erros no plano ${$.plan_name}`,body:($)=>`${$.failures} de ${$.total} chamadas falharam (${$.rate}%).`},webhook:{alertType:()=>"plan_error_rate",metricValue:($)=>$.rate,threshold:($)=>$.threshold}}),"calls.transfer_failure":W$({kind:"calls.transfer_failure",area:"calls",audience:"organization",severity:"warning",params:G.strictObject({rate:G.number(),failures:G.number(),total:G.number(),threshold:G.number()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/reports",defaults:s$,en:{title:($)=>`Transfer failure rate ${$.rate}%`,body:($)=>`${$.failures}/${$.total} failed.`},pt:{title:()=>"Falhas nas transferências",body:($)=>`${$.failures} de ${$.total} transferências falharam (${$.rate}%).`},webhook:{alertType:()=>"transfer_failure_rate",metricValue:($)=>$.rate,threshold:($)=>$.threshold}}),"calls.stale":W$({kind:"calls.stale",area:"calls",audience:"organization",severity:"warning",params:G.strictObject({count:G.number(),threshold:G.number()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/reports",defaults:s$,en:{title:()=>"Stale calls detected",body:($)=>`${$.count} ${P1($.count,"stale call","stale calls")}.`},pt:{title:()=>"Chamadas sem atividade",body:($)=>`Foram detectadas ${$.count} chamadas sem atividade.`},webhook:{alertType:()=>"stale_calls",metricValue:($)=>$.count,threshold:($)=>$.threshold}}),"calls.transcription_failed":W$({kind:"calls.transcription_failed",area:"calls",audience:"organization",severity:"warning",params:G.strictObject({count:G.number(),threshold:G.number()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/reports",defaults:s$,en:{title:()=>"Transcription failures",body:($)=>`${$.count} ${P1($.count,"failure","failures")}.`},pt:{title:()=>"Falhas na transcrição",body:($)=>`Foram detectadas ${$.count} falhas na transcrição.`},webhook:{alertType:()=>"transcription_failures",metricValue:($)=>$.count,threshold:($)=>$.threshold}}),"calls.rejected":W$({kind:"calls.rejected",area:"calls",audience:"organization",severity:"warning",params:G.strictObject({reason:G.string(),destination:G.string(),count:G.number()}),grouping:{mode:"window",windowSeconds:900},groupKey:($)=>$.reason,link:()=>"/reports",defaults:s$,en:{title:()=>"Calls rejected",body:($,U)=>`${U.count} ${P1(U.count,"call","calls")} rejected (${$.reason}).`},pt:{title:()=>"Chamadas rejeitadas",body:($,U)=>`${U.count} ${U.count===1?"chamada rejeitada":"chamadas rejeitadas"}: ${$.reason}.`}}),"calls.node_error":W$({kind:"calls.node_error",area:"calls",audience:"organization",severity:"warning",params:G.strictObject({node_id:G.string(),node_type:G.string(),node_label:G.string(),error_code:G.string(),visual_plan_id:G.string(),visual_plan_name:G.string(),count:G.number()}),grouping:{mode:"window",windowSeconds:900},groupKey:($)=>`${$.visual_plan_id}:${$.node_id}:${$.error_code}`,link:()=>"/reports",defaults:s$,en:{title:()=>"Call node errors",body:($,U)=>`${U.count} ${P1(U.count,"error","errors")} in ${$.node_label} (${$.error_code}).`},pt:{title:()=>"Erros nos nós de chamada",body:($,U)=>`${U.count} ${U.count===1?"erro":"erros"} em ${$.node_label} (${$.error_code}).`}}),"webhook.endpoint_down":W$({kind:"webhook.endpoint_down",area:"integrations",audience:"organization",severity:"critical",params:G.strictObject({endpoint_id:G.string(),endpoint_url:G.string(),endpoint_description:G.string().nullable(),failed_attempts:G.number(),last_error:G.string().nullable()}),grouping:{mode:"incident"},groupKey:($)=>$.endpoint_id,link:()=>"/settings/webhooks",defaults:D1,en:{title:()=>"Webhook endpoint failing",body:($)=>`${$.failed_attempts} consecutive ${P1($.failed_attempts,"failure","failures")}.`},pt:{title:()=>"Webhook com falhas",body:($)=>`${$.failed_attempts} ${$.failed_attempts===1?"falha consecutiva":"falhas consecutivas"} na entrega do webhook.`},webhook:{alertType:()=>"webhook_failures",metricValue:($)=>$.failed_attempts,threshold:()=>3}}),"webhook.queue_delayed":W$({kind:"webhook.queue_delayed",area:"integrations",audience:"organization",severity:"warning",params:G.strictObject({depth:G.number(),minutes:G.number(),threshold:G.number()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/settings/webhooks",defaults:s$,en:{title:($)=>`Webhook queue delayed ${$.minutes} min`,body:($)=>`${$.depth} pending ${P1($.depth,"delivery","deliveries")}; the oldest has waited ${$.minutes} min.`},pt:{title:()=>"Fila de webhooks atrasada",body:($)=>`${$.depth} entregas pendentes; a mais antiga aguarda há ${$.minutes} min.`},webhook:{alertType:()=>"webhook_queue_backlog",metricValue:($)=>$.minutes,threshold:($)=>$.threshold}}),"connector.needs_attention":W$({kind:"connector.needs_attention",area:"integrations",audience:"organization",severity:"critical",params:G.strictObject({connector_id:G.string(),connector_name:G.string(),kind:G.string(),error_code:G.string(),error_message:G.string()}),grouping:{mode:"incident"},groupKey:($)=>$.connector_id,link:($)=>`/settings/connectors/${$.connector_id}`,defaults:D1,en:{title:($)=>`Connector ${$.connector_name} needs attention`,body:($)=>`${$.error_code}: ${$.error_message}`},pt:{title:($)=>`O conector ${$.connector_name} precisa de atenção`,body:($)=>`${$.error_code}: ${$.error_message}`},webhook:{alertType:()=>"connector_needs_attention"}}),"secret.missing":W$({kind:"secret.missing",area:"integrations",audience:"organization",severity:"critical",params:G.strictObject({secret:G.string(),node_label:G.string()}),grouping:{mode:"window",windowSeconds:3600},groupKey:($)=>$.secret,link:()=>"/settings/secrets",defaults:D1,en:{title:()=>"Secret missing",body:($)=>`The secret ${$.secret} is missing for ${$.node_label}.`},pt:{title:()=>"Secret ausente",body:($)=>`O secret ${$.secret} está ausente em ${$.node_label}.`}}),"signal.triggered":W$({kind:"signal.triggered",area:"signals",audience:"organization",severity:"warning",params:G.strictObject({signal:G.string(),signal_id:G.string(),call_id:G.string(),caller:G.string().nullable()}),grouping:{mode:"window",windowSeconds:900},groupKey:($)=>$.signal_id,link:($,U)=>U.count===1?`/reports?trace=${$.call_id}`:`/reports?signal=${$.signal_id}`,defaults:D1,en:{title:($)=>`Signal triggered: ${$.signal}`,body:($,U)=>`${U.count} ${P1(U.count,"call","calls")} triggered ${$.signal}.`},pt:{title:($)=>`Sinal detectado: ${$.signal}`,body:($,U)=>`${U.count} ${U.count===1?"chamada acionou":"chamadas acionaram"} o sinal ${$.signal}.`}}),"usage.channel_capacity":W$({kind:"usage.channel_capacity",area:"usage",audience:"organization",severity:"warning",params:G.strictObject({pct:G.number(),active:G.number(),limit:G.number(),pool:G.string()}),grouping:{mode:"incident"},groupKey:($)=>$.pool,link:()=>"/dashboard",defaults:D1,en:{title:($)=>`${$.pool} channel capacity ${$.pct}%`,body:($)=>`${$.active}/${$.limit} ${$.pool} ${P1($.limit,"channel","channels")} in use.`},pt:{title:()=>"Capacidade de canais",body:($)=>`${$.active} de ${$.limit} canais ${$.pool} em uso (${$.pct}%).`},webhook:{alertType:()=>"channel_capacity",metricValue:($)=>$.pct,threshold:()=>90}}),"usage.audit_retention":W$({kind:"usage.audit_retention",area:"usage",audience:"organization",severity:"warning",params:G.strictObject({count:G.number(),limit:G.number()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/settings/audit",defaults:Cw,en:{title:()=>"Audit retention capacity exceeded",body:($)=>`Audit log count (${$.count}) exceeds the retention limit (${$.limit}).`},pt:{title:()=>"Limite de retenção da auditoria excedido",body:($)=>`${$.count} registros de auditoria ultrapassam o limite de ${$.limit}.`},webhook:{alertType:()=>"audit_retention_capacity",metricValue:($)=>$.count,threshold:($)=>$.limit}}),"system.update_available":W$({kind:"system.update_available",area:"services",audience:"platform",severity:"info",params:G.strictObject({version:G.string()}),grouping:{mode:"once"},groupKey:($)=>$.version,link:()=>"/system/updates",defaults:s$,en:{title:($)=>`NIVA ${$.version} is available`,body:($)=>`A new NIVA release is available: ${$.version}.`},pt:{title:($)=>`NIVA ${$.version} disponível`,body:($)=>`Uma nova versão da NIVA está disponível: ${$.version}.`}}),"system.update_completed":W$({kind:"system.update_completed",area:"services",audience:"platform",severity:"info",params:G.strictObject({run_id:G.string(),from_version:G.string(),to_version:G.string()}),grouping:{mode:"once"},groupKey:($)=>$.run_id,link:()=>"/system/updates",defaults:D1,en:{title:($)=>`NIVA updated to ${$.to_version}`,body:($)=>`NIVA was updated from ${$.from_version} to ${$.to_version}.`},pt:{title:($)=>`NIVA atualizada para ${$.to_version}`,body:($)=>`A NIVA foi atualizada de ${$.from_version} para ${$.to_version}.`}}),"system.update_failed":W$({kind:"system.update_failed",area:"services",audience:"platform",severity:"critical",params:G.strictObject({run_id:G.string(),status:G.enum(["failed","rolled_back","action_required"]),error_code:G.string()}),grouping:{mode:"once"},groupKey:($)=>$.run_id,link:()=>"/system/updates",defaults:D1,en:{title:()=>"NIVA update failed",body:($)=>`The update ended with status ${$.status} (${$.error_code}).`},pt:{title:()=>"Falha na atualização da NIVA",body:($)=>`A atualização terminou com o estado ${$.status} (${$.error_code}).`}})};var yX="urn:ietf:params:oauth:grant-type:device_code",gX=["authorization_code","refresh_token",yX],pW="ABCDEFGHJKLMNPQRSTUVWXYZ",uw=G.object({resource:G.string(),authorization_servers:G.array(G.string()).min(1),scopes_supported:G.array(G.string()),bearer_methods_supported:G.array(G.string()),resource_name:G.string().optional()}),fw=G.object({issuer:G.string(),authorization_endpoint:G.string(),token_endpoint:G.string(),registration_endpoint:G.string(),revocation_endpoint:G.string(),device_authorization_endpoint:G.string(),response_types_supported:G.array(G.string()),grant_types_supported:G.array(G.string()),code_challenge_methods_supported:G.array(G.string()),token_endpoint_auth_methods_supported:G.array(G.string()),client_id_metadata_document_supported:G.literal(!0),authorization_response_iss_parameter_supported:G.literal(!0),scopes_supported:G.array(G.string())}),mw=G.string().refine(($)=>{try{return new URL($).protocol==="https:"}catch{return!1}},"must be an https URL"),hw=G.object({client_id:mw,redirect_uris:G.array(G.string().min(1)).min(1),client_name:G.string().optional(),client_uri:G.string().optional(),logo_uri:G.string().optional(),scope:G.string().optional(),grant_types:G.array(G.string()).optional(),response_types:G.array(G.string()).optional(),token_endpoint_auth_method:G.string().optional(),token_endpoint_auth_methods_supported:G.array(G.string()).optional(),application_type:G.enum(["native","web"]).optional()}).refine(cw,{error:'client must support the "none" token endpoint auth method',path:["token_endpoint_auth_method"]});function cw($){let U=$.token_endpoint_auth_methods_supported;if(U!=null)return U.includes("none");let K=$.token_endpoint_auth_method;return K==null||K==="none"}var lw=G.object({redirect_uris:G.array(G.string().min(1)).min(1),client_name:G.string().max(200).optional(),client_uri:G.string().optional(),logo_uri:G.string().optional(),scope:G.string().optional(),grant_types:G.array(G.enum(gX)).optional(),response_types:G.array(G.literal("code")).optional(),token_endpoint_auth_method:G.literal("none").optional(),application_type:G.enum(["native","web"]).optional()}),rw=G.object({client_id:G.string(),client_id_issued_at:G.number().int(),redirect_uris:G.array(G.string()),client_name:G.string().optional(),token_endpoint_auth_method:G.literal("none"),grant_types:G.array(G.string()),response_types:G.array(G.string()),application_type:G.enum(["native","web"]).optional(),scope:G.string().optional()}),iw=G.object({client_id:G.string().min(1).max(2048),scope:G.string().max(2000).default(""),resource:G.string().min(1).max(2048)}),dw=G.object({device_code:G.string().min(1),user_code:G.string().regex(new RegExp(`^[${pW}]{4}-[${pW}]{4}$`)),verification_uri:G.string(),verification_uri_complete:G.string().optional(),expires_in:G.number().int().positive(),interval:G.number().int().positive()});var i8={visual_plan:["read","create","update","delete","publish"],channel:["read","create","update","delete"],destination:["read","create","update","delete"],schedule:["read","create","update","delete"],holiday:["read","create","update","delete"],audio_file:["read","create","update","delete"],call_record:["read","export","purge"],call_content:["read"],call:["originate","hangup"],dashboard:["read","update"],notification:["manage"],test_call:["execute"],tts:["read"],org_settings:["read","update"],user:["read","invite","update_role","suspend","remove","reset_password"],api_key:["read","create","revoke"],oauth_grant:["read","revoke"],acl:["read","create","update","delete"],audit:["read"],webhook:["read","create","update","delete"],ai:["read","execute","configure","manage_key"],org_integration:["read","update"],analysis_template:["read","create","update","delete"],contact:["read","update"],dialer_campaign:["read","create","update","delete","control"],dialer_dnc:["read","manage"],archive:["read","purge"],secret:["read","create","update","delete"],connector:["read","create","update","delete"],role:["read","create","update","delete"],license:["read"],organization:["list","create","update","delete"],integration:["read","update"],org_plan:["read","update"],platform_admin:["read","manage"],platform_storage:["manage"],system:["logs","diagnostics","operate","update"]},tW={visual_plan:"organization",channel:"organization",destination:"organization",schedule:"organization",holiday:"organization",audio_file:"organization",call_record:"organization",call_content:"organization",call:"organization",dashboard:"organization",notification:"organization",test_call:"organization",tts:"organization",org_settings:"organization",user:"organization",api_key:"organization",oauth_grant:"organization",acl:"organization",audit:"organization",webhook:"organization",ai:"organization",org_integration:"organization",analysis_template:"organization",contact:"organization",dialer_campaign:"organization",dialer_dnc:"organization",archive:"organization",secret:"organization",connector:"organization",role:"organization",license:"platform",organization:"platform",integration:"platform",org_plan:"platform",platform_admin:"platform",platform_storage:"platform",system:"platform"},uX=Object.entries(i8),fX=uX.flatMap(([$,U])=>U.map((K)=>`${$}:${K}`));var mX={super_admin:["*"],administrator:["*"],editor:["visual_plan:read","visual_plan:create","visual_plan:update","visual_plan:delete","visual_plan:publish","channel:read","channel:create","channel:update","channel:delete","destination:read","destination:create","destination:update","destination:delete","schedule:read","schedule:create","schedule:update","schedule:delete","holiday:read","holiday:create","holiday:update","holiday:delete","audio_file:read","audio_file:create","audio_file:update","audio_file:delete","test_call:execute","call:originate","call:hangup","dashboard:read","dashboard:update","call_record:read","call_record:export","call_content:read","tts:read","ai:read","ai:execute","ai:configure","analysis_template:read","analysis_template:create","analysis_template:update","analysis_template:delete","contact:read","contact:update","dialer_campaign:read","dialer_campaign:create","dialer_campaign:update","dialer_campaign:delete","dialer_campaign:control","dialer_dnc:read","dialer_dnc:manage","archive:read","user:read","role:read","webhook:read","api_key:read","oauth_grant:read"],supervisor:["visual_plan:read","channel:read","destination:read","schedule:read","holiday:read","audio_file:read","dashboard:read","dashboard:update","call_record:read","call_record:export","call_content:read","test_call:execute","call:hangup","tts:read","ai:read","ai:execute","analysis_template:read","contact:read","contact:update","dialer_campaign:read","dialer_campaign:control","dialer_dnc:read","user:read","role:read","webhook:read","api_key:read","oauth_grant:read","acl:read","audit:read","archive:read"],operator:["visual_plan:read","channel:read","destination:read","schedule:read","holiday:read","audio_file:read","dashboard:read","call_record:read","test_call:execute","call:hangup","tts:read","contact:read","contact:update","dialer_campaign:read","dialer_dnc:read","user:read","archive:read"],viewer:["visual_plan:read","channel:read","destination:read","schedule:read","holiday:read","audio_file:read","dashboard:read","call_record:read","tts:read","user:read","role:read","webhook:read","api_key:read","oauth_grant:read","acl:read","audit:read","ai:read","analysis_template:read","contact:read","dialer_campaign:read","dialer_dnc:read","archive:read"]},ow=Object.keys(mX);var wr=uX.filter(([$])=>tW[$]==="organization").flatMap(([$,U])=>U.map((K)=>`${$}:${K}`));var Ar=new Map(fX.map(($)=>[$,$])),vr=new Map(Object.entries(tW));var zr=new Set(`@£$¥èéùìòÇ
|
|
100
|
-
Øø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !"#¤%&'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà`);var aW={plans:{entities:["visual_plan","audio_file","tts","analysis_template","test_call"]},telephony:{entities:["channel","destination","schedule","holiday","acl"]},calls:{entities:["call","call_record","call_content","contact","dashboard","notification","archive","ai"]},dialer:{entities:["dialer_campaign","dialer_dnc"],module:"dialer"},admin:{entities:["user","role","api_key","oauth_grant","org_settings","webhook","org_integration","audit","secret","connector","license"]},platform:{entities:["organization","integration","org_plan","platform_admin","platform_storage","system"],platformOnly:!0}},pw=Object.keys(aW),tw=new Map;for(let $ of pw)for(let U of aW[$].entities)tw.set(U,$);var hX=new Set(["*:read","*:write","offline_access"]);for(let $ of Object.keys(i8))hX.add(`${$}:read`),hX.add(`${$}:write`);var sW=G.object({version:G.literal(1),startNodeId:G.string().min(1),nodes:G.record(G.string(),G.object({type:G.string().min(1),label:G.string(),varName:G.string(),config:G.record(G.string(),G.unknown())})),adjacency:G.record(G.string(),G.record(G.string(),G.string()))});function $J($,U,K,q,Q){let W=U.channelType,J=typeof W==="string"?W:"voice";if(J!=="both")return aw($,K,q,J==="voice"?"voice-only":"chat-only");return ew($,K,q,Q)}function aw($,U,K,q){let Q=eW($,U),W={};for(let J of K)W[J]=Q.has(J)?q:"unreachable";return W[$]=q,W}function sw($,U){if($&&U)return"converged";if($)return"voice-only";if(U)return"chat-only";return"unreachable"}function ew($,U,K,q){let Q=U.get($)?.get("voice"),W=U.get($)?.get("chat"),J=Q!=null?eW(Q,U,q,"voice"):new Set,j=W!=null?eW(W,U,q,"chat"):new Set;if(Q!=null)J.add(Q);if(W!=null)j.add(W);let Y={};for(let H of K)Y[H]=H===$?"converged":sw(J.has(H),j.has(H));return Y}function eW($,U,K,q){let Q=new Set,W=[$];Q.add($);let J=0;while(J<W.length){let j=W[J++],Y=U.get(j);if(Y==null)continue;if(q!=null&&K?.has(j)){let H=Y.get(q);if(H!=null&&!Q.has(H))Q.add(H),W.push(H);continue}for(let H of Y.values())if(!Q.has(H))Q.add(H),W.push(H)}return Q}function f(){return($,U)=>({key:U,prefix:`${$}:`})}var cX={call:f()("call",($)=>`call:${$}`),testPlan:f()("test-plan",($)=>`test-plan:${$}`),testChatPlan:f()("test-chat-plan",($)=>`test-chat-plan:${$}`),testEditorState:f()("test-editor-state",($)=>`test-editor-state:${$}`),testExecutionTrace:f()("test-execution-trace",($)=>`test-execution-trace:${$}`),refreshToken:f()("rt",($)=>`rt:${$}`),hostActionConfirmation:f()("host-action-confirmation",($)=>`host-action-confirmation:${$}`),revokedToken:f()("revoked",($)=>`revoked:${$}`),revokedSession:f()("revoked-session",($)=>`revoked-session:${$}`),legacyAuthCutoff:f()("legacy-auth-cutoff",($)=>`legacy-auth-cutoff:${$}`),oauthCode:f()("oauth:code",($)=>`oauth:code:${$}`),oauthCimd:f()("oauth:cimd",($)=>`oauth:cimd:${$}`),oauthDevice:f()("oauth:device",($)=>`oauth:device:${$}`),oauthUsercode:f()("oauth:usercode",($)=>`oauth:usercode:${$}`),oauthUsercodeAttempts:f()("oauth:usercode-attempts",($)=>`oauth:usercode-attempts:${$}`),channels:f()("niva:channels",($)=>`niva:channels:${$}`),concurrentChannels:f()("niva:concurrent_channels",($,U)=>`niva:concurrent_channels:${$}:${U}`),peakConcurrentChannels:f()("niva:peak_concurrent",($,U)=>`niva:peak_concurrent:${$}:${U}`),dialerCampaignActive:f()("niva:dialer_campaign_active",($)=>`niva:dialer_campaign_active:${$}`),capacityReservation:f()("niva:capacity_reservation",($)=>`niva:capacity_reservation:${$}`),capacityReservationData:f()("niva:capacity_reservation_data",()=>"niva:capacity_reservation_data"),capacityReservationExpiry:f()("niva:capacity_reservation_expiry",()=>"niva:capacity_reservation_expiry"),capacityReservationHandoff:f()("niva:capacity_reservation_handoff",($)=>`niva:capacity_reservation_handoff:${$}`),counterByPlan:f()("niva:counter:plan",($,U,K)=>`niva:counter:plan:${$}:${U}:${K}`),counterByOrg:f()("niva:counter:org",($,U)=>`niva:counter:org:${$}:${U}`),trafficSplitRotation:f()("niva:traffic_split",($,U,K,q)=>`niva:traffic_split:${$}:${U}:${K}:${q}`),rateLimit:f()("rl",($,U)=>`rl:${$}:${U}`),liveTranscriptionSegments:f()("live-ts",($)=>`live-ts:${$}`),liveSignalEvents:f()("live-sig",($)=>`live-sig:${$}`),liveTranscriptionSummary:f()("live-ts-summary",($)=>`live-ts-summary:${$}`),transcriptionWatchers:f()("ts-watchers",($)=>`ts-watchers:${$}`),chatSession:f()("chat-session",($)=>`chat-session:${$}`),chatLookup:f()("chat-lookup",($,U,K)=>`chat-lookup:${$}:${U}:${K}`),activeVoiceCalls:f()("niva:active:voice",($)=>`niva:active:voice:${$}`),activeChatSessions:f()("niva:active:chat",($)=>`niva:active:chat:${$}`),chatLock:f()("chat-lock",($,U)=>`chat-lock:${$}:${U}`),chatInboundMessage:f()("chat-inbound-message",($,U,K,q)=>`chat-inbound-message:${$}:${U}:${K}:${q}`),wsSession:f()("ws:session",($)=>`ws:session:${$}`),wsMessageLog:f()("ws:log",($)=>`ws:log:${$}`),wsSeq:f()("ws:seq",($)=>`ws:seq:${$}`),healthStatus:f()("health-status",($)=>`health-status:${$}`),alertCooldown:f()("alert-cd",($,U)=>`alert-cd:${$}:${U}`),auditRetentionOverCap:f()("audit-retention",()=>"audit-retention:over-cap"),storageCleanup:f()("storage:cleanup",($)=>`storage:cleanup:${$}`),recordingDownloadAudit:f()("rec-dl-audit",($,U)=>`rec-dl-audit:${$}:${U}`),connectorPhoneNumbers:f()("connector:phone-numbers",($,U)=>`connector:phone-numbers:v${U}:${$}`),connectorPhoneNumbersVersion:f()("connector:phone-numbers:version",($)=>`connector:${$}:phone-numbers:version`),connectorTemplates:f()("connector:templates",($,U)=>`connector:templates:v${U}:${$}`),connectorTemplatesVersion:f()("connector:templates:version",($)=>`connector:${$}:templates:version`),whatsappTemplateMessage:f()("wa-template-msg",($)=>`wa-template-msg:${$}`),screenPop:f()("screenpop",($,U)=>`screenpop:${$}:${U}`),screenPopLegacy:f()("call_info",($)=>`call_info_${$}`),engineHeartbeat:f()("engine:heartbeat",()=>"engine:heartbeat")};function UA($){return a$[$]?.connector}function UJ($,U){return typeof $==="string"&&$!==""&&!U.has($)}function A0($,U){return{nodeId:$.id,severity:"error",messageKey:U,params:{label:$.label}}}function QA($,U){if($.type!=="timeRouting"||U==null)return null;if(!UJ($.config.scheduleId,U))return null;return A0($,"editor:validation.danglingSchedule")}function KA($,U){if($.type!=="subPlan"||U==null)return null;if(!UJ($.config.planId,U))return null;return A0($,"editor:validation.danglingPlan")}function qA($,U){if(U==null)return null;let K=$.config.audio;if(K==null||typeof K!=="object"||!("file"in K))return null;let q=K.file;if(q==null||typeof q!=="object"||!("id"in q))return null;if(!UJ(q.id,U))return null;return A0($,"editor:validation.danglingAudioFile")}function WA($,U){if(U==null)return null;let K=UA($.type);if(K==null)return null;let q=$.config[K.configKey];if(typeof q!=="string"||q==="")return null;let Q=U.get(q);if(Q===void 0)return A0($,"editor:validation.danglingConnector");if(Q!==K.kind)return A0($,"editor:validation.connectorKindMismatch");return null}function JA($,U){if(U==null)return[];return u8($).allowed.filter((K)=>!U.has(K)).map((K)=>({nodeId:$.id,severity:"error",messageKey:"editor:validation.danglingSecret",params:{label:$.label,secret:K}}))}function QJ($,U){let K=[];for(let q of $){let Q=QA(q,U.schedules);if(Q!=null)K.push(Q);let W=KA(q,U.publishedPlans);if(W!=null)K.push(W);let J=qA(q,U.audioFiles);if(J!=null)K.push(J);let j=WA(q,U.connectors);if(j!=null)K.push(j);K.push(...JA(q,U.secrets))}return K}function KJ($,U){let K=[];for(let q of $){if(q.type!=="aiAgent"||U.aiAgents==null)continue;let Q=q.config.agent_id;if(typeof Q==="string"&&Q!==""&&!U.aiAgents.has(Q))K.push({nodeId:q.id,severity:"warning",messageKey:"editor:validation.danglingAiAgent",params:{label:q.label}})}return K}var c$={basic:["started_at","caller_id","callee_id","direction","channel_type","status","duration_s","hangup_cause","plan_name"],details:["answered_at","ended_at","billing_duration_s","sip_call_id","remote_addr","user_agent","sip_hangup_disposition","sip_code"],media:["was_recorded","transcription_status","transcription","analysis","sentiment_label","ai_agent_price","ai_agent_currency"],errors:["has_error","error_count","last_error_code"],origin:["origin_type","origin_name"],metadata:["metadata"],variables:["variables"]},qJ=[...c$.basic,...c$.details,...c$.media,...c$.errors,...c$.origin,...c$.metadata,...c$.variables],lX=/^analysis:[a-z0-9][a-z0-9-]*\.[A-Za-z0-9_-]+(?:\[\])?(?:\.[A-Za-z0-9_-]+(?:\[\])?)*$/,GA=G.string().regex(lX,{error:"Invalid structured-analysis export column"}).refine(($)=>rX($),{error:"Invalid structured-analysis export column"});function rX($){return lX.test($)}var iX=/^signal:[a-z][a-z0-9_]*(?:\.triggered_at)?$/;function dX($){return iX.test($)}var jA=G.string().regex(iX,{error:"Invalid signal export column"}).refine(($)=>dX($),{error:"Invalid signal export column"}),oX=["sip_call_id","remote_addr","user_agent"],YA=new Set(oX),HA=qJ.filter(($)=>!YA.has($)),XA=[...c$.basic];var ZA={basic:[...c$.basic],full:[...qJ],ai_audit:[...c$.basic,"transcription_status","transcription","analysis","sentiment_label","ai_agent_price","ai_agent_currency",...c$.errors,...c$.metadata,"variables"]};var WJ=["call.started","call.answered","call.amd_completed","call.hangup","call.rejected","call.node_entered","call.node_error","call.node_warning","call.transcribed","call.analysis_completed","call.transferred","call.recording_available","call.intent_matched","call.signal_triggered","plan.published","message.sent","dialer.attempt.finished","alert.fired","alert.resolved","service.down","service.up"];var nX=[1,5,30,120,300,600],BA=nX.length,pX=G.enum(["inbound","outbound"]),X$=G.iso.datetime(),l$=G.record(G.string(),G.string()),VA=G.strictObject({amd:G.literal(!0),machine_type:G.literal(!0).optional(),mode:G.enum(KX).optional(),max_wait_seconds:G.number().int().min(3).max(10).optional()}).superRefine(($,U)=>{if($.max_wait_seconds!==void 0&&$.mode!=="pre")U.addIssue({code:"custom",path:["max_wait_seconds"],message:"max_wait_seconds is only valid with mode=pre"})}),tX=G.strictObject({call_id:G.string().min(1).meta({"x-niva-typeid":m.call_records}),caller_id:G.string(),callee_id:G.string(),direction:pX,visual_plan_id:G.string().min(1).meta({"x-niva-typeid":m.visual_plans}),visual_plan_name:G.string(),started_at:X$,answer_recognition:VA.optional(),metadata:l$}),aX=G.strictObject({call_id:G.string().min(1).meta({"x-niva-typeid":m.call_records}),caller_id:G.string(),callee_id:G.string(),answered_at:X$,metadata:l$}),JJ=G.enum(["machine","human","silence","unknown"]),sX=G.enum(qX),eX=G.strictObject({call_id:G.string().min(1).meta({"x-niva-typeid":m.call_records}),channel_uuid:G.string().min(1),result:JJ,machine_type:sX.optional(),completed_at:X$,metadata:l$}).superRefine(($,U)=>{if($.machine_type!==void 0&&$.result!=="machine")U.addIssue({code:"custom",path:["machine_type"],message:"machine_type is only valid when result is machine"})}),$Z=G.strictObject({call_id:G.string().min(1).meta({"x-niva-typeid":m.call_records}),caller_id:G.string(),callee_id:G.string(),direction:pX,visual_plan_id:G.string().min(1).meta({"x-niva-typeid":m.visual_plans}),visual_plan_name:G.string(),started_at:X$,answered_at:X$.nullable(),ended_at:X$,duration_ms:G.number().nonnegative(),hangup_cause:G.string(),hangup_disposition:G.string(),was_recorded:G.boolean(),variables:G.record(G.string(),G.string()),sip_code:G.string().nullable(),billsec:G.number().nonnegative().nullable(),answer_recognition_results:G.strictObject({amd:JJ}).optional(),metadata:l$}),UZ=["not_found","channel_inactive","channel_deleted","plan_deleted","no_published_version","org_deleted","acl_denied","capacity_global","capacity_org","capacity_campaign","capacity_reservation"],QZ=G.enum(UZ),KZ=G.strictObject({caller:G.string(),destination:G.string(),reason:QZ,hangup_cause:G.string()}),qZ=G.strictObject({call_id:G.string().min(1).meta({"x-niva-typeid":m.call_records}),caller_id:G.string(),callee_id:G.string(),node_id:G.string().min(1),node_type:G.string(),node_label:G.string(),handle_used:G.string(),digit:G.string().nullable(),entered_at:X$,exited_at:X$,duration_ms:G.number().nonnegative(),visual_plan_id:G.string().min(1).meta({"x-niva-typeid":m.visual_plans}),metadata:l$}),GJ=G.strictObject({call_id:G.string().min(1).meta({"x-niva-typeid":m.call_records}),caller_id:G.string(),callee_id:G.string(),node_id:G.string().min(1),node_type:G.string(),node_label:G.string(),error_code:G.string(),error_message:G.string(),visual_plan_id:G.string().min(1).meta({"x-niva-typeid":m.visual_plans}),visual_plan_name:G.string(),occurred_at:X$,metadata:l$}),WZ=GJ,JZ=G.strictObject({call_record_id:G.string().min(1).meta({"x-niva-typeid":m.call_records}),transcription_id:G.string().min(1).meta({"x-niva-typeid":m.call_transcriptions}),full_text:G.string(),is_anonymized:G.boolean(),metadata:l$}),GZ=["native","local","sippulse_ai"],MA=G.enum(GZ),jZ=G.strictObject({source:G.literal("native"),id:G.null(),template_id:G.null(),name:G.string(),category:G.null()}),YZ=G.strictObject({source:G.literal("local"),id:G.string().min(1).meta({"x-niva-typeid":m.call_analyses}),template_id:G.string().min(1).meta({"x-niva-typeid":m.analysis_templates}),name:G.string(),category:G.string().nullable()}),HZ=G.strictObject({source:G.literal("sippulse_ai"),id:G.string().min(1).meta({"x-niva-typeid":m.call_analyses}),template_id:G.null(),external_id:G.string().min(1),slug:G.string().min(1),name:G.string(),category:G.null(),model:G.string().nullable()}),tr=G.discriminatedUnion("source",[jZ,YZ,HZ]),jJ={status:G.enum(["completed","failed"]),result:G.record(G.string(),G.unknown()).nullable(),error_message:G.string().nullable(),error_code:G.string().nullable()},DA=G.strictObject({...jZ.shape,...jJ}),PA=G.strictObject({...YZ.shape,...jJ}),NA=G.strictObject({...HZ.shape,...jJ}),LA=G.discriminatedUnion("source",[DA,PA,NA]).superRefine(($,U)=>{if($.status==="failed"&&$.result!==null)U.addIssue({code:"custom",path:["result"],message:"Failed analyses must have a null result"})}),XZ=G.enum(["caller","agent"]),ZZ=G.strictObject({id:G.string().min(1).meta({"x-niva-typeid":m.signals}),slug:G.string().min(1),name:G.string(),kind:G.enum(L6),version:G.number().int().positive()}),_A=G.strictObject({signal:ZZ,value:G.union([G.boolean(),G.string(),G.number(),G.null()]),value_label:G.string().nullable(),confidence:G.number().nullable(),triggered:G.strictObject({at_seconds:G.number(),value:G.union([G.boolean(),G.string(),G.number(),G.null()]),value_label:G.string().nullable(),confidence:G.number().nullable(),late:G.boolean(),node_id:G.string().nullable()}).nullable()}),BZ=G.strictObject({call_id:G.string().min(1).meta({"x-niva-typeid":m.call_records}),call_record_id:G.string().min(1).meta({"x-niva-typeid":m.call_records}),transcription_id:G.string().min(1).meta({"x-niva-typeid":m.call_transcriptions}),visual_plan_id:G.string().nullable().meta({"x-niva-typeid":m.visual_plans}),analyses:LA.array(),signals:_A.array(),analyzed_at:X$,metadata:l$}),VZ=["answered","busy","noAnswer","failed"],MZ=G.enum(VZ),DZ=G.strictObject({call_id:G.string().min(1).meta({"x-niva-typeid":m.call_records}),caller_id:G.string(),callee_id:G.string(),to_destination:G.string(),method:G.enum(["bridge","sip_message","blind"]),disposition:MZ,status:G.string(),duration_ms:G.number().nonnegative().nullable(),transferred_at:X$,metadata:l$}),PZ=G.strictObject({call_id:G.string().min(1).meta({"x-niva-typeid":m.call_records}),call_record_id:G.string().min(1).meta({"x-niva-typeid":m.call_records}),recording_url:G.string(),storage_path:G.string(),duration_seconds:G.number().nonnegative().nullable(),format:G.string(),size_bytes:G.number().nonnegative().nullable(),available_at:X$,metadata:l$}),IA=G.strictObject({intent:G.string(),confidence:G.number()}),NZ=G.strictObject({call_id:G.string().min(1).meta({"x-niva-typeid":m.call_records}),caller_id:G.string(),callee_id:G.string(),node_id:G.string().min(1),visual_plan_id:G.string().min(1).meta({"x-niva-typeid":m.visual_plans}),transcript:G.string(),intent:G.string(),confidence:G.number(),alternatives:G.array(IA),language:G.string().nullable(),matched_at:X$,metadata:l$}),FA=G.strictObject({speaker:XZ,text:G.string(),start_seconds:G.number()}),xA=G.strictObject({call_id:G.string().min(1).meta({"x-niva-typeid":m.call_records}),visual_plan_id:G.string().nullable().meta({"x-niva-typeid":m.visual_plans}),signal:ZZ,value:G.union([G.boolean(),G.string(),G.number(),G.null()]),value_label:G.string(),confidence:G.number(),severity:G.enum(_6),speaker:XZ,at_seconds:G.number(),late:G.boolean(),source:G.enum(["live","end_of_call"]),node:G.strictObject({id:G.string(),label:G.string(),type:G.string()}).nullable(),window:G.array(FA),is_anonymized:G.boolean(),trace_url:G.string().nullable(),metadata:l$}),LZ=G.strictObject({plan_id:G.string().min(1).meta({"x-niva-typeid":m.visual_plans}),plan_name:G.string(),version_id:G.string().min(1).meta({"x-niva-typeid":m.visual_plan_versions}),version_number:G.number().int().nonnegative(),published_by_user_id:G.string().min(1).meta({"x-niva-typeid":m.users}),notes:G.string().nullable(),published_at:X$}),_Z=["text","media","audio","image","video","document","location","interactive"],IZ=G.strictObject({session_id:G.string().min(1).meta({"x-niva-typeid":m.call_records}),channel_type:G.string(),to:G.string(),message_type:G.enum(_Z),text:G.string().nullable(),media_url:G.string().nullable(),node_id:G.string().nullable(),sent_at:X$}),FZ=["answered","machine","silence","busy","no_answer","failed","originate_error","cancelled"],xZ=G.enum(FZ),wZ=G.strictObject({campaign_id:G.string().min(1).meta({"x-niva-typeid":m.dialer_campaigns}),campaign_name:G.string(),contact_id:G.string().min(1).meta({"x-niva-typeid":m.dialer_contacts}),phone_number:G.string(),attempt_number:G.number().int().nonnegative(),status:xZ,hangup_cause:G.string().nullable(),sip_code:G.string().nullable(),call_uuid:G.string().nullable(),started_at:X$.nullable(),answered_at:X$.nullable(),ended_at:X$.nullable(),duration_s:G.number().nonnegative().nullable(),custom_fields:G.record(G.string(),G.string())}),AZ=G.strictObject({alert_type:G.string(),severity:G.enum(["critical","warning","info"]),title:G.string(),body:G.string(),metric_value:G.number().optional(),threshold:G.number().optional()}),vZ=G.strictObject({alert_type:G.string(),title:G.string(),body:G.string()}),kZ=G.strictObject({component:G.string(),checked_at:X$}),RZ=G.strictObject({component:G.string(),downtime_seconds:G.number().nonnegative().nullable(),recovered_at:X$}),d8={"call.started":tX,"call.answered":aX,"call.amd_completed":eX,"call.hangup":$Z,"call.rejected":KZ,"call.node_entered":qZ,"call.node_error":GJ,"call.node_warning":WZ,"call.transcribed":JZ,"call.analysis_completed":BZ,"call.transferred":DZ,"call.recording_available":PZ,"call.intent_matched":NZ,"call.signal_triggered":xA,"plan.published":LZ,"message.sent":IZ,"dialer.attempt.finished":wZ,"alert.fired":AZ,"alert.resolved":vZ,"service.down":kZ,"service.up":RZ};function B$($){return G.strictObject({event:G.literal($),event_id:G.string().min(1),org_id:G.string().min(1),timestamp:X$,data:d8[$]})}var wA=G.discriminatedUnion("event",[B$("call.started"),B$("call.answered"),B$("call.amd_completed"),B$("call.hangup"),B$("call.rejected"),B$("call.node_entered"),B$("call.node_error"),B$("call.node_warning"),B$("call.transcribed"),B$("call.analysis_completed"),B$("call.transferred"),B$("call.recording_available"),B$("call.intent_matched"),B$("call.signal_triggered"),B$("plan.published"),B$("message.sent"),B$("dialer.attempt.finished"),B$("alert.fired"),B$("alert.resolved"),B$("service.down"),B$("service.up")]);function V$($){return G.strictObject({event:G.literal($),event_id:G.string().min(1),timestamp:X$,data:d8[$]})}var AA=G.discriminatedUnion("event",[V$("call.started"),V$("call.answered"),V$("call.amd_completed"),V$("call.hangup"),V$("call.rejected"),V$("call.node_entered"),V$("call.node_error"),V$("call.node_warning"),V$("call.transcribed"),V$("call.analysis_completed"),V$("call.transferred"),V$("call.recording_available"),V$("call.intent_matched"),V$("call.signal_triggered"),V$("plan.published"),V$("message.sent"),V$("dialer.attempt.finished"),V$("alert.fired"),V$("alert.resolved"),V$("service.down"),V$("service.up")]),i="01kknxab29enebk2vhm0tz0yyd",zZ={"call.started":{call_id:`call_${i}`,caller_id:"+15551230001",callee_id:"+15551230002",direction:"inbound",visual_plan_id:`vp_${i}`,visual_plan_name:"Support IVR",started_at:"2026-01-15T12:00:00.000Z",metadata:{}},"call.answered":{call_id:`call_${i}`,caller_id:"+15551230001",callee_id:"+15551230002",answered_at:"2026-01-15T12:00:03.000Z",metadata:{}},"call.amd_completed":{call_id:`call_${i}`,channel_uuid:"freeswitch-channel-example",result:"machine",machine_type:"voicemail",completed_at:"2026-01-15T12:00:05.000Z",metadata:{}},"call.hangup":{call_id:`call_${i}`,caller_id:"+15551230001",callee_id:"+15551230002",direction:"inbound",visual_plan_id:`vp_${i}`,visual_plan_name:"Support IVR",started_at:"2026-01-15T12:00:00.000Z",answered_at:"2026-01-15T12:00:03.000Z",ended_at:"2026-01-15T12:01:00.000Z",duration_ms:60000,hangup_cause:"NORMAL_CLEARING",hangup_disposition:"answered",was_recorded:!0,variables:{customer_tier:"standard"},sip_code:"200",billsec:57,metadata:{}},"call.rejected":{caller:"+15551230001",destination:"+15551230002",reason:"channel_inactive",hangup_cause:"UNALLOCATED_NUMBER"},"call.node_entered":{call_id:`call_${i}`,caller_id:"+15551230001",callee_id:"+15551230002",node_id:"node_menu",node_type:"ivr",node_label:"Main menu",handle_used:"digit:1",digit:"1",entered_at:"2026-01-15T12:00:04.000Z",exited_at:"2026-01-15T12:00:08.000Z",duration_ms:4000,visual_plan_id:`vp_${i}`,metadata:{}},"call.node_error":{call_id:`call_${i}`,caller_id:"+15551230001",callee_id:"+15551230002",node_id:"node_api",node_type:"httpRequest",node_label:"Load customer",error_code:"HTTP_ERROR",error_message:"Request failed",visual_plan_id:`vp_${i}`,visual_plan_name:"Support IVR",occurred_at:"2026-01-15T12:00:10.000Z",metadata:{}},"call.node_warning":{call_id:`call_${i}`,caller_id:"+15551230001",callee_id:"+15551230002",node_id:"node_transcription",node_type:"transcription",node_label:"Transcribe call",error_code:"transcription_requires_recording",error_message:"Transcription requires an active recording",visual_plan_id:`vp_${i}`,visual_plan_name:"Support IVR",occurred_at:"2026-01-15T12:00:10.000Z",metadata:{}},"call.transcribed":{call_record_id:`call_${i}`,transcription_id:`ctr_${i}`,full_text:"Hello, I need help with my account.",is_anonymized:!0,metadata:{}},"call.analysis_completed":{call_id:`call_${i}`,call_record_id:`call_${i}`,transcription_id:`ctr_${i}`,visual_plan_id:`vp_${i}`,analyses:[{source:"native",id:null,template_id:null,name:"Speech analytics",category:null,status:"completed",error_code:null,result:{intent:"support",sentiment:{label:"positive",score:0.8},topics:[{topic:"billing",confidence:0.94}],summary:"Customer asked about their account.",key_points:["account question"]},error_message:null},{source:"sippulse_ai",id:`ca_${i}`,template_id:null,external_id:"sa_quality",slug:"quality",name:"Executive Summary",category:null,model:"deepseek-v4.1-flash",status:"failed",result:null,error_code:"upstream_failure",error_message:"Structured analysis service returned an error."}],analyzed_at:"2026-01-15T12:02:00.000Z",signals:[{signal:{id:`sig_${i}`,slug:"asked_for_human",name:"Asked for a human agent",kind:"yes_no",version:3},value:!0,value_label:"Yes",confidence:0.94,triggered:{at_seconds:134.2,value:!0,value_label:"Yes",confidence:0.94,late:!1,node_id:"menu_main"}}],metadata:{}},"call.transferred":{call_id:`call_${i}`,caller_id:"+15551230001",callee_id:"+15551230002",to_destination:"support@example.invalid",method:"bridge",disposition:"answered",status:"SUCCESS",duration_ms:null,transferred_at:"2026-01-15T12:00:20.000Z",metadata:{}},"call.recording_available":{call_id:`call_${i}`,call_record_id:`call_${i}`,recording_url:`https://example.invalid/recordings/call_${i}.wav`,storage_path:`recordings/example/call_${i}.wav`,duration_seconds:57,format:"wav",size_bytes:912000,available_at:"2026-01-15T12:01:01.000Z",metadata:{}},"call.intent_matched":{call_id:`call_${i}`,caller_id:"+15551230001",callee_id:"+15551230002",node_id:"node_intent",visual_plan_id:`vp_${i}`,transcript:"I need technical support",intent:"support",confidence:0.94,alternatives:[{intent:"support",confidence:0.94}],language:"en-US",matched_at:"2026-01-15T12:00:15.000Z",metadata:{}},"call.signal_triggered":{call_id:`call_${i}`,visual_plan_id:`vp_${i}`,signal:{id:`sig_${i}`,slug:"asked_for_human",name:"Asked for a human agent",kind:"yes_no",version:3},value:!0,value_label:"Yes",confidence:0.94,severity:"warning",speaker:"caller",at_seconds:134.2,late:!1,source:"live",node:{id:"menu_main",label:"Main menu",type:"menu"},window:[{speaker:"agent",text:"For a second copy, press 1",start_seconds:131.9},{speaker:"caller",text:"I want to talk to a person",start_seconds:133.4}],is_anonymized:!1,trace_url:`https://niva.example.com/reports?trace=call_${i}`,metadata:{}},"plan.published":{plan_id:`vp_${i}`,plan_name:"Support IVR",version_id:`vpv_${i}`,version_number:3,published_by_user_id:`usr_${i}`,notes:"Updated support routing",published_at:"2026-01-15T11:00:00.000Z"},"message.sent":{session_id:`call_${i}`,channel_type:"whatsapp",to:"+15551230001",message_type:"text",text:"How can we help?",media_url:null,node_id:"node_message",sent_at:"2026-01-15T12:00:05.000Z"},"dialer.attempt.finished":{campaign_id:`dcamp_${i}`,campaign_name:"January outreach",contact_id:`dct_${i}`,phone_number:"+15551230001",attempt_number:1,status:"answered",hangup_cause:"NORMAL_CLEARING",sip_code:"200",call_uuid:"fs-channel-example",started_at:"2026-01-15T12:00:00.000Z",answered_at:"2026-01-15T12:00:03.000Z",ended_at:"2026-01-15T12:01:00.000Z",duration_s:60,custom_fields:{segment:"example"}},"alert.fired":{alert_type:"service_offline",severity:"critical",title:"Example service offline",body:"The example service is unavailable.",metric_value:1,threshold:1},"alert.resolved":{alert_type:"service_offline",title:"Example service recovered",body:"The example service is available again."},"service.down":{component:"example-service",checked_at:"2026-01-15T12:00:00.000Z"},"service.up":{component:"example-service",downtime_seconds:null,recovered_at:"2026-01-15T12:05:00.000Z"}};function v0($){let U=t$[$],K=a$[$],q=K.defaultConfig,Q=x4(K,q),W=typeof K.producedVariables==="function"?K.producedVariables(q):K.producedVariables,J=Mq($,"en");return{type:$,name:J?.name??$,description:J?.description??"",nameKey:K.nameKey,descriptionKey:K.descriptionKey,module:K.module,category:K.category,channel:K.channel,nature:K.nature,configJsonSchema:G.toJSONSchema(U.configSchema,{unrepresentable:"any"}),outputs:Q,producedVariables:W,defaultConfig:q}}var kA=Object.keys(t$);function YJ(){return kA.map(($)=>v0($))}var RA=["string","number","boolean","object","array"],bZ=G.strictObject({name:G.string(),type:G.enum(RA),required:G.boolean(),nullable:G.boolean()}),OZ=G.strictObject({event:G.enum(WJ),required_module:G.enum(["core","ai","queues","dialer","omnichannel","enterprise"]).nullable(),fields:G.array(bZ),example:G.record(G.string(),G.unknown())}),zA=G.array(OZ);var TZ="edge";var bA=G.object({text:G.string().min(1).max(5000),voice:G.string().min(1),model:G.string().default(TZ)});var OA=G.object({signal_id:G.string(),t:G.number().min(0),v:G.union([G.boolean(),G.string(),G.null(),G.number()]),c:G.number().min(0).max(1),node_id:G.string().nullable()});function HJ($){let U=$.normalize("NFD").replaceAll(/[\u0300-\u036F]/g,"").toLowerCase().replaceAll(/[^a-z0-9]+/g,"_").replaceAll(/_+/g,"_").replaceAll(/^_|_$/g,"");if(!/^[a-z]/.test(U))return`signal_${U}`.slice(0,64)||"signal";return U.slice(0,64)}var o8=[{id:"asked_for_human",kind:"yes_no",speaker:"caller",live:!0,scope:null,alert:{when:{answer:"yes"},severity:"warning",bell:!0},texts:{"pt-BR":{name:"Pediu atendente humano",question:"O cliente pediu para falar com um atendente humano?"},en:{name:"Asked for a human agent",question:"Did the customer ask to speak with a human agent?"}}},{id:"wants_to_cancel",kind:"yes_no",speaker:"caller",live:!0,scope:null,alert:{when:{answer:"yes"},severity:"warning",bell:!1},texts:{"pt-BR":{name:"Quer cancelar",question:"O cliente disse que quer cancelar o serviço ou trocar de operadora?"},en:{name:"Wants to cancel",question:"Did the customer say they want to cancel the service or switch providers?"}}},{id:"caller_irritation",kind:"scale",speaker:"caller",live:!0,scope:null,alert:{when:{level_at_least:3},severity:"critical",bell:!0},texts:{"pt-BR":{name:"Irritação do cliente",question:"Quão irritado está o cliente?",levels:["calmo","impaciente","irritado","furioso"]},en:{name:"Caller irritation",question:"How irritated is the caller?",levels:["calm","impatient","irritated","furious"]}}},{id:"contact_reason",kind:"choice",speaker:"caller",live:!0,scope:null,alert:null,option_keys:["second_copy","bill_dispute","tech_support","cancellation"],texts:{"pt-BR":{name:"Motivo do contato",question:"Qual é o motivo principal da ligação?",options:[{label:"segunda via",description:"Cliente quer boleto ou fatura"},{label:"contestação de conta",description:"Cliente discorda de um valor cobrado"},{label:"suporte técnico",description:"Internet, sinal ou equipamento com problema"},{label:"cancelamento",description:"Cliente quer encerrar o serviço"}]},en:{name:"Contact reason",question:"What is the main reason for the call?",options:[{label:"second copy",description:"Customer wants a bill or invoice copy"},{label:"bill dispute",description:"Customer disagrees with a charged amount"},{label:"tech support",description:"Internet, signal or equipment issue"},{label:"cancellation",description:"Customer wants to end the service"}]}}},{id:"formal_complaint",kind:"yes_no",speaker:"caller",live:!0,scope:null,alert:{when:{answer:"yes"},severity:"critical",bell:!0},texts:{"pt-BR":{name:"Ameaça de reclamação formal",question:"O cliente ameaçou reclamar no Procon, no Reclame Aqui ou na Justiça?"},en:{name:"Formal complaint threat",question:"Did the customer threaten to complain to Procon, Reclame Aqui or the courts?"}}},{id:"emergency_symptom",kind:"yes_no",speaker:"caller",live:!0,scope:null,alert:{when:{answer:"yes"},severity:"critical",bell:!0},texts:{"pt-BR":{name:"Sintoma de emergência",question:"O paciente descreveu sintoma de emergência, como dor no peito, falta de ar ou desmaio?"},en:{name:"Emergency symptom",question:"Did the patient describe an emergency symptom, such as chest pain, shortness of breath or fainting?"}}},{id:"fraud_risk",kind:"scale",speaker:"caller",live:!0,scope:null,alert:{when:{level_at_least:2},severity:"critical",bell:!1},texts:{"pt-BR":{name:"Risco de golpe",question:"Qual é o risco de a ligação ser uma tentativa de golpe?",levels:["baixo","médio","alto"]},en:{name:"Fraud risk",question:"How likely is this call to be a scam attempt?",levels:["low","medium","high"]}}},{id:"protocol_given",kind:"yes_no",speaker:"agent",live:!1,scope:{node_types:["transfer"]},alert:{when:{answer:"no"},severity:"info",bell:!1},texts:{"pt-BR":{name:"Protocolo informado",question:"O atendente informou o número de protocolo ao cliente?"},en:{name:"Protocol number given",question:"Did the agent give the customer the protocol number?"}}},{id:"collection_outcome",kind:"choice",speaker:"both",live:!1,scope:null,alert:{when:{options:["disputed"]},severity:"info",bell:!1},option_keys:["promised_to_pay","refused","disputed","call_back_later"],texts:{"pt-BR":{name:"Desfecho da cobrança",question:"Qual foi o desfecho da cobrança?",options:[{label:"prometeu pagar"},{label:"recusou"},{label:"contestou a dívida",description:"Cliente diz que não deve ou que o valor está errado"},{label:"pediu para ligar depois"}]},en:{name:"Collection outcome",question:"What was the outcome of the collection?",options:[{label:"promised to pay"},{label:"refused"},{label:"disputed the debt",description:"Customer says they do not owe or the amount is wrong"},{label:"asked to call back later"}]}}},{id:"off_script_offer",kind:"yes_no",speaker:"agent",live:!0,scope:{node_types:["aiAgent"]},alert:{when:{answer:"yes"},severity:"warning",bell:!0},texts:{"pt-BR":{name:"Oferta fora do script",question:"O agente ofereceu desconto ou condição fora do que foi combinado?"},en:{name:"Off-script offer",question:"Did the agent offer a discount or terms outside what was agreed?"}}}];function XJ($,U){let K=$.texts[U];return I6.parse({slug:HJ(K.name),name:K.name,question:K.question,kind:$.kind,...$.kind==="choice"?{options:(K.options??[]).map((q,Q)=>({key:$.option_keys?.[Q]??`option_${Q}`,label:q.label,...q.description!==void 0?{description:q.description}:{}}))}:{},...$.kind==="scale"?{levels:K.levels??[]}:{},speaker:$.speaker,scope:$.scope,live:$.live,alert:$.alert})}var SZ=["not_applicable","disabled","waiting","pending","processing","completed","failed","skipped","purged","expired"];var ei=new Set(SZ);var ZJ=G.record(G.string(),G.string());var n8=G.object({id:G.string(),sequence:G.number().int().nonnegative(),nodeId:G.string(),nodeType:G.string(),nodeLabel:G.string(),status:G.enum(["running","completed","warning","error"]),enteredAt:G.string(),exitedAt:G.string().nullable(),durationMs:G.number().int().nonnegative().nullable(),handleUsed:G.string().nullable(),digit:G.string().nullable(),variablesBefore:ZJ,variablesAfter:ZJ.nullable(),resolvedConfig:G.record(G.string(),G.unknown()),resultData:G.record(G.string(),G.unknown()).nullable()}).superRefine(($,U)=>{let K=[$.exitedAt,$.durationMs,$.handleUsed,$.variablesAfter];if($.status==="running"?K.some((Q)=>Q!==null):K.includes(null))U.addIssue({code:"custom",path:["status"],message:"Running steps must have empty exit fields; terminal steps must have complete exit fields"})}),SA=G.object({orgId:G.string(),status:G.enum(["active","waiting_input","ended"]),currentNodeId:G.string(),variables:ZJ,steps:G.array(n8),truncated:G.boolean()});function w4($){return{audio:{tts:{text:$}}}}function EA($){return{type:"text",text:$}}function F($){return{...w4($),content:EA($)}}function n($,U,K={},q){return{options:U,maxAttempts:3,audio:w4($).audio,text:q??$,...K}}function D$($,U={}){return{audio:w4($).audio,text:$,...U}}function d($,U,K,q){return[X(`${$}a`,U,"answered",K),X(`${$}b`,U,"busy",q),X(`${$}n`,U,"noAnswer",q),X(`${$}e`,U,"error",q)]}var yA={x:0,y:0};function V($,U,K,q,Q){return{id:$,type:U,label:K,varName:q,position:yA,config:Q}}function X($,U,K,q){return{id:$,source:U,sourceHandle:K,target:q,targetHandle:"in"}}var CZ={id:"atendente-virtual-ia",category:"ai",requiredModules:["ai"],tags:["ia","agente","ai","virtual","conversacional"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Boas-vindas","boas_vindas",F("Olá! Sou o assistente virtual. Posso ajudar com diversas questões.")),V("ai1","aiAgent","Agente IA","agente_ia",{agent_id:"",agent_name:"",additional_instructions:"",variables:{},initial_message:"Olá, como posso ajudar?",max_duration_minutes:10}),V("m1","menu","Satisfação","satisfacao",n("Resolvemos sua dúvida? Se sim, tecle 1. Para falar com um atendente, tecle 2.",[{id:"satisfeito",label:"Satisfeito",digit:"1"},{id:"atendente",label:"Falar com atendente",digit:"2"}],{},"Escolha uma opção:")),V("t2","tell","Agradecimento","agradecimento",F("Obrigado pelo contato. Tenha um bom dia!")),V("t3","tell","Transferindo","transferindo",F("Vou transferir para um atendente humano.")),V("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["1000"],timeout:45}),V("t4","tell","Erro IA","erro_ia",F("Houve um problema com o assistente. Vou transferir para um atendente.")),V("t5","tell","Transferência Falhou","transferencia_falhou",F("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[X("e1v","s1","voice","t1"),X("e1c","s1","chat","t1"),X("e2","t1","next","ai1"),X("e3","ai1","completed","m1"),X("e4","ai1","error","t4"),X("e5","m1","option:satisfeito","t2"),X("e6","m1","option:atendente","t3"),X("e7","m1","noMatch","t3"),X("e8","m1","error","t3"),X("e9","t2","next","h1"),X("e10","t3","next","x1"),X("e11","t4","next","x1"),...d("ex1","x1","h1","t5"),X("e12","t5","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var EZ={id:"atendimento-agente-ia",category:"ai",requiredModules:["ai"],tags:["ia","ai","agente","atendimento","intencao","classificacao","transferencia"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Boas-vindas","boas_vindas",F("Olá! Você ligou para a nossa central. Em poucas palavras, me diga como posso ajudar.")),V("c1","capture","Captura","captura",D$("Fale agora o motivo do seu contato.",{voiceMethod:"speech",maxAttempts:3,listen:{initial_timeout_s:10,timeout_s:3,max_duration_s:15,beep:!0},processing_audio:w4("Um momento enquanto analiso o seu pedido.").audio})),V("ra1","routeAi","Classificador","classificador",{input:"{{captura.text}}",intents:[{label:"suporte",description:"Problemas técnicos, falhas, dúvidas de uso do produto ou serviço"},{label:"financeiro",description:"Faturas, cobranças, pagamentos, reembolsos e negociações"}],instructions:"Classifique o motivo do contato do cliente. Duplique um ramo para cada novo assunto atendido."}),V("ai1","aiAgent","Agente","agente",{agent_id:"",agent_name:"",additional_instructions:"O usuário está entrando com o seguinte pedido: {{captura.text}}",variables:{},initial_message:"",max_duration_minutes:10}),V("sw1","switchCase","Decidir","decidir",{expression:"{{agente.output.resultado}}",cases:[{pattern:"^resolvido$"}]}),V("t2","tell","Despedida","despedida",F("Obrigado pelo contato. Tenha um ótimo dia!")),V("t3","tell","Não Entendi","nao_entendeu",F("Não consegui entender o motivo do contato. Vou transferir para um atendente.")),V("t4","tell","Erro Técnico","erro_tecnico",F("Tivemos um problema no atendimento automático. Vou transferir para um atendente.")),V("x1","transfer","Transferência Humana","transfer_humano",{method:"bridge",destinations:["1000"]}),V("t5","tell","Transferência Falhou","transfer_falhou",F("Não conseguimos completar a transferência. Por favor, ligue novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[X("e1v","s1","voice","t1"),X("e1c","s1","chat","t1"),X("e2","t1","next","c1"),X("e3","c1","collected","ra1"),X("e4","c1","noInput","t3"),X("e5","c1","error","t4"),X("e6","ra1","intent:suporte","ai1"),X("e7","ra1","intent:financeiro","x1"),X("e8","ra1","notApplicable","t3"),X("e9","ra1","error","t4"),X("e10","ai1","completed","sw1"),X("e11","ai1","error","t4"),X("e12","sw1","match:^resolvido$","t2"),X("e13","sw1","fallback","x1"),X("e14","sw1","error","t4"),X("e15","t3","next","x1"),X("e16","t4","next","x1"),X("e17","t2","next","h1"),X("e18","x1","answered","t2"),X("e19","x1","busy","t5"),X("e20","x1","noAnswer","t5"),X("e21","x1","error","t5"),X("e22","t5","next","h1")],viewport:{x:0,y:0,zoom:0.75}}};var yZ={id:"atendimento-setores",category:"core",requiredModules:[],tags:["menu","transfer","setores","departamentos","ura"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Boas-vindas","boas_vindas",F("Bem-vindo. Escolha entre financeiro, suporte, vendas ou ouvidoria.")),V("m1","menu","Menu Principal","menu_principal",n("Para financeiro, tecle 1. Para suporte, tecle 2. Para vendas, tecle 3. Para ouvidoria, tecle 4.",[{id:"financeiro",label:"Financeiro",digit:"1"},{id:"suporte",label:"Suporte Técnico",digit:"2"},{id:"vendas",label:"Vendas",digit:"3"},{id:"ouvidoria",label:"Ouvidoria",digit:"4"}],{},"Escolha o setor desejado:")),V("t2","tell","Transferindo Financeiro","transferindo_financeiro",F("Aguarde, transferindo para o financeiro.")),V("t3","tell","Transferindo Suporte","transferindo_suporte",F("Aguarde, transferindo para o suporte técnico.")),V("t4","tell","Transferindo Vendas","transferindo_vendas",F("Aguarde, transferindo para vendas.")),V("t5","tell","Transferindo Ouvidoria","transferindo_ouvidoria",F("Aguarde, transferindo para a ouvidoria.")),V("x1","transfer","Financeiro","financeiro",{method:"bridge",destinations:["1001"],timeout:30}),V("x2","transfer","Suporte","suporte",{method:"bridge",destinations:["1002"],timeout:30}),V("x3","transfer","Vendas","vendas",{method:"bridge",destinations:["1003"],timeout:30}),V("x4","transfer","Ouvidoria","ouvidoria",{method:"bridge",destinations:["1004"],timeout:30}),V("t6","tell","Opção Inválida","opcao_invalida",F("Não entendi sua escolha. Por favor, ligue novamente.")),V("t7","tell","Transferência Falhou","transferencia_falhou",F("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[X("e1v","s1","voice","t1"),X("e1c","s1","chat","t1"),X("e2","t1","next","m1"),X("e3","m1","option:financeiro","t2"),X("e4","m1","option:suporte","t3"),X("e5","m1","option:vendas","t4"),X("e6","m1","option:ouvidoria","t5"),X("e7","t2","next","x1"),X("e8","t3","next","x2"),X("e9","t4","next","x3"),X("e10","t5","next","x4"),X("e11","m1","noMatch","t6"),X("e12","m1","error","t6"),X("e13","t6","next","h1"),...d("ex1","x1","h1","t7"),...d("ex2","x2","h1","t7"),...d("ex3","x3","h1","t7"),...d("ex4","x4","h1","t7"),X("e14","t7","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var gZ={id:"banco-sac",category:"industry",requiredModules:[],tags:["banco","financeiro","sac","saldo","extrato","cartao"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("c1","capture","CPF do Cliente","cpf_cliente",D$("Bem-vindo ao banco. Digite os onze números do seu CPF.",{voiceMethod:"dtmf",minDigits:11,maxDigits:11,terminators:"#",text:"Bem-vindo ao banco. Informe seu CPF (somente números):",validation:String.raw`^\d{11}$`,invalidMessage:"CPF inválido. Informe os 11 dígitos, somente números:"})),V("m1","menu","Menu Serviços","menu_servicos",n("Para consultar saldo, tecle 1. Para extrato, tecle 2. Para cartões, tecle 3. Para falar com um atendente, tecle 4.",[{id:"saldo",label:"Consultar saldo",digit:"1"},{id:"extrato",label:"Extrato",digit:"2"},{id:"cartao",label:"Cartões",digit:"3"},{id:"atendente",label:"Falar com atendente",digit:"4"}],{},"Escolha o serviço desejado:")),V("http1","httpRequest","Consultar Saldo","consultar_saldo",{method:"GET",url:"https://api.example.com/accounts/{{cpf_cliente.text}}/balance",headers:{},body:"",timeout:10}),V("t1","tell","Saldo Informado","saldo_informado",F("O seu saldo é: {{consultar_saldo.response}}. Obrigado pelo contato.")),V("t2","tell","Extrato","extrato",F("Seu extrato será enviado por SMS em instantes.")),V("t3","tell","Cartões","cartoes",F("Para informações sobre cartões, vou transferir para um especialista.")),V("t4","tell","Transferindo Atendente","transferindo_atendente",F("Aguarde, vou transferir para um atendente.")),V("t5","tell","Erro Consulta","erro_consulta",F("Não foi possível realizar a consulta agora. Vou transferir para um atendente.")),V("t6","tell","Sem Identificação","sem_identificacao",F("Não consegui identificar o seu CPF. Vou transferir para um atendente.")),V("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["5001"],timeout:45}),V("t7","tell","Transferência Falhou","transferencia_falhou",F("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[X("e1v","s1","voice","c1"),X("e1c","s1","chat","c1"),X("e2","c1","collected","m1"),X("e3","c1","noInput","t6"),X("e4","c1","error","t6"),X("e5","m1","option:saldo","http1"),X("e6","m1","option:extrato","t2"),X("e7","m1","option:cartao","t3"),X("e8","m1","option:atendente","t4"),X("e9","m1","noMatch","t6"),X("e10","m1","error","t6"),X("e11","http1","next","t1"),X("e12","http1","error","t5"),X("e13","t1","next","h1"),X("e14","t2","next","h1"),X("e15","t3","next","x1"),X("e16","t4","next","x1"),X("e17","t5","next","x1"),X("e18","t6","next","x1"),...d("ex1","x1","h1","t7"),X("e19","t7","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var uZ={id:"clinica-agendamento",category:"industry",requiredModules:[],tags:["clinica","saude","agendamento","consulta","medico"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Boas-vindas","boas_vindas",F("Bem-vindo à central de agendamentos.")),V("m1","menu","Especialidade","especialidade",n("Para Clínico Geral, tecle 1. Para Cardiologia, tecle 2. Para Ortopedia, tecle 3.",[{id:"clinico",label:"Clínico Geral",digit:"1"},{id:"cardio",label:"Cardiologia",digit:"2"},{id:"orto",label:"Ortopedia",digit:"3"}],{},"Escolha a especialidade desejada:")),V("c1","capture","CPF do Paciente","cpf_paciente",D$("Digite os onze números do CPF do paciente.",{voiceMethod:"dtmf",minDigits:11,maxDigits:11,terminators:"#",text:"Informe o CPF do paciente (somente números):",validation:String.raw`^\d{11}$`,invalidMessage:"CPF inválido. Informe os 11 dígitos, somente números:"})),V("http1","httpRequest","Consultar Agenda","consultar_agenda",{method:"POST",url:"https://api.example.com/appointments/check",headers:{"Content-Type":"application/json"},body:'{"cpf": "{{cpf_paciente.text}}", "specialty": "{{especialidade.selectedId}}"}',timeout:10}),V("t2","tell","Resultado da Consulta","resultado_consulta",F("{{consultar_agenda.response}}")),V("t3","tell","Erro na Consulta","erro_consulta",F("Não conseguimos consultar a agenda no momento. Por favor, tente novamente mais tarde.")),V("t4","tell","Sem Dados","sem_dados",F("Não consegui capturar as informações necessárias. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[X("e1v","s1","voice","t1"),X("e1c","s1","chat","t1"),X("e2","t1","next","m1"),X("e3","m1","option:clinico","c1"),X("e4","m1","option:cardio","c1"),X("e5","m1","option:orto","c1"),X("e6","m1","noMatch","t4"),X("e7","m1","error","t4"),X("e8","c1","collected","http1"),X("e9","c1","noInput","t4"),X("e10","c1","error","t4"),X("e11","http1","next","t2"),X("e12","http1","error","t3"),X("e13","t2","next","h1"),X("e14","t3","next","h1"),X("e15","t4","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var fZ={id:"cobranca-automatizada",category:"capture",requiredModules:[],tags:["cobranca","debito","pagamento","boleto","pix","negociacao"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Intro Cobrança","intro_cobranca",F("Olá, identificamos um débito em aberto na sua conta.")),V("m1","menu","Opções de Pagamento","opcoes_pagamento",n("Para negociar a dívida, tecle 1. Para receber o boleto atualizado, tecle 2. Para pagar via Pix, tecle 3.",[{id:"negociar",label:"Negociar dívida",digit:"1"},{id:"boleto",label:"Receber boleto",digit:"2"},{id:"pix",label:"Pagar via Pix",digit:"3"}],{},"Escolha uma opção de pagamento:")),V("c1","capture","Identificação","identificacao",D$("Informe seu CPF ou número de contrato e finalize com a tecla jogo da velha.",{voiceMethod:"dtmf",minDigits:4,maxDigits:14,terminators:"#",text:"Informe seu CPF ou número de contrato (somente números):",validation:String.raw`^\d{4,14}$`,invalidMessage:"Identificação inválida. Informe apenas números, entre 4 e 14 dígitos:"})),V("t2","tell","Transferindo Negociação","transferindo_negociacao",F("Recebi sua identificação. Vou transferir para um especialista em negociação.")),V("x1","transfer","Negociação","negociacao",{method:"bridge",destinations:["2001"],timeout:45}),V("t3","tell","Boleto Enviado","boleto_enviado",F("O boleto atualizado será enviado para seu contato cadastrado em até 5 minutos.")),V("t4","tell","Chave Pix","chave_pix",F("Nossa chave Pix é o CNPJ da empresa. Após o pagamento, a baixa será automática em até 2 horas.")),V("t5","tell","Opção Inválida","opcao_invalida",F("Não entendi sua escolha. Por favor, ligue novamente.")),V("t6","tell","Sem Identificação","sem_identificacao",F("Não recebi sua identificação. Por favor, ligue novamente com os dados em mãos.")),V("t7","tell","Transferência Falhou","transferencia_falhou",F("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[X("e1v","s1","voice","t1"),X("e1c","s1","chat","t1"),X("e2","t1","next","m1"),X("e3","m1","option:negociar","c1"),X("e4","m1","option:boleto","t3"),X("e5","m1","option:pix","t4"),X("e6","m1","noMatch","t5"),X("e7","m1","error","t5"),X("e8","c1","collected","t2"),X("e9","c1","noInput","t6"),X("e10","c1","error","t6"),X("e11","t2","next","x1"),X("e12","t3","next","h1"),X("e13","t4","next","h1"),X("e14","t5","next","h1"),X("e15","t6","next","h1"),...d("ex1","x1","h1","t7"),X("e16","t7","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var mZ={id:"coleta-dados-api",category:"capture",requiredModules:[],tags:["capture","api","http","dados","integracao"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Boas-vindas","boas_vindas",F("Olá. Vou consultar uma informação para você.")),V("c1","capture","Identificação","identificacao",D$("Informe seu número de identificação e finalize com a tecla jogo da velha.",{voiceMethod:"dtmf",minDigits:4,maxDigits:14,terminators:"#",text:"Informe seu número de identificação (somente números):",validation:String.raw`^\d{4,14}$`,invalidMessage:"Identificação inválida. Informe apenas números, entre 4 e 14 dígitos:"})),V("http1","httpRequest","Consultar API","consultar_api",{method:"GET",url:"https://api.example.com/lookup/{{identificacao.text}}",headers:{},body:"",timeout:10}),V("sw1","switchCase","Tipo de Falha","tipo_falha",{expression:"{{consultar_api.status_code}}",cases:[{pattern:"^404$"}]}),V("t2","tell","Resultado Encontrado","resultado_encontrado",F("Encontrei as informações solicitadas: {{consultar_api.response}}. Obrigado pelo contato.")),V("t3","tell","Não Encontrado","nao_encontrado",F("Não encontrei registros para essa identificação. Verifique o número e tente novamente.")),V("t4","tell","Erro de Consulta","erro_consulta",F("Houve um erro na consulta. Tente novamente mais tarde.")),V("t5","tell","Sem Identificação","sem_identificacao",F("Não consegui capturar sua identificação. Por favor, ligue novamente com o número em mãos.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[X("e1v","s1","voice","t1"),X("e1c","s1","chat","t1"),X("e2","t1","next","c1"),X("e3","c1","collected","http1"),X("e4","c1","noInput","t5"),X("e5","c1","error","t5"),X("e6","http1","next","t2"),X("e7","http1","error","sw1"),X("e8","sw1","match:^404$","t3"),X("e9","sw1","fallback","t4"),X("e10","sw1","error","t4"),X("e11","t2","next","h1"),X("e12","t3","next","h1"),X("e13","t4","next","h1"),X("e14","t5","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var hZ={id:"faq-ia-escalacao",category:"ai",requiredModules:["ai"],tags:["faq","ia","escalacao","ai","agente"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Boas-vindas","boas_vindas",F("Olá! Sou o assistente virtual. Posso tirar dúvidas sobre nossos serviços.")),V("ai1","aiAgent","Agente FAQ","agente_faq",{agent_id:"",agent_name:"",additional_instructions:"Responda perguntas frequentes sobre os serviços da empresa. Se não souber a resposta, informe que vai transferir para um atendente.",variables:{},initial_message:"Olá! Qual sua dúvida?",max_duration_minutes:5}),V("m1","menu","Resolveu?","resolveu",n("Sua dúvida foi resolvida? Se sim, tecle 1. Para falar com um atendente, tecle 2.",[{id:"resolvido",label:"Sim, resolvido",digit:"1"},{id:"atendente",label:"Falar com atendente",digit:"2"}],{},"Escolha uma opção:")),V("t2","tell","Agradecimento","agradecimento",F("Ótimo! Se precisar de algo mais, é só entrar em contato.")),V("t3","tell","Transferindo","transferindo",F("Aguarde, vou transferir para um atendente.")),V("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["1000"],timeout:45}),V("t4","tell","Transferência Falhou","transferencia_falhou",F("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[X("e1v","s1","voice","t1"),X("e1c","s1","chat","t1"),X("e2","t1","next","ai1"),X("e3","ai1","completed","m1"),X("e4","ai1","error","t3"),X("e5","m1","option:resolvido","t2"),X("e6","m1","option:atendente","t3"),X("e7","m1","noMatch","t3"),X("e8","m1","error","t3"),X("e9","t2","next","h1"),X("e10","t3","next","x1"),...d("ex1","x1","h1","t4"),X("e11","t4","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var cZ={id:"faq-informacoes",category:"core",requiredModules:[],tags:["faq","informacoes","autoatendimento","info"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Boas-vindas","boas_vindas",F("Olá, sou o assistente virtual. Posso ajudar com suporte, financeiro, vendas ou horários de atendimento.")),V("m1","menu","Menu FAQ","menu_faq",n("Para suporte técnico, tecle 1. Para financeiro, tecle 2. Para vendas, tecle 3. Para horários de atendimento, tecle 4.",[{id:"suporte",label:"Suporte Técnico",digit:"1"},{id:"financeiro",label:"Financeiro",digit:"2"},{id:"vendas",label:"Vendas",digit:"3"},{id:"horarios",label:"Horários",digit:"4"}],{},"Escolha um assunto:")),V("t2","tell","Info Suporte","info_suporte",F("Nossa equipe de suporte está disponível 24 horas por dia. Você também pode abrir um chamado pelo nosso portal.")),V("t3","tell","Info Financeiro","info_financeiro",F("Para boletos, notas fiscais e negociações, acesse nosso portal financeiro ou fale com atendimento em horário comercial.")),V("t4","tell","Info Vendas","info_vendas",F("Conheça nossos planos e promoções no nosso site. Para falar com um consultor, ligue em horário comercial.")),V("t5","tell","Info Horários","info_horarios",F("Nosso atendimento funciona de segunda a sexta, das 8h às 20h. Aos sábados, das 8h às 14h.")),V("t6","tell","Opção Inválida","opcao_invalida",F("Não entendi sua escolha. Encerrando o atendimento. Até logo.")),V("h1","hangup","Fim","fim",{})],edges:[X("e1v","s1","voice","t1"),X("e1c","s1","chat","t1"),X("e2","t1","next","m1"),X("e3","m1","option:suporte","t2"),X("e4","m1","option:financeiro","t3"),X("e5","m1","option:vendas","t4"),X("e6","m1","option:horarios","t5"),X("e7","t2","next","m1"),X("e8","t3","next","m1"),X("e9","t4","next","m1"),X("e10","t5","next","m1"),X("e11","m1","noMatch","t6"),X("e12","m1","error","t6"),X("e13","t6","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var lZ={id:"horario-comercial",category:"core",requiredModules:[],tags:["horario","schedule","tempo","comercial","expediente"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("tr1","timeRouting","Horário Atendimento","horario_atendimento",{}),V("t1","tell","Boas-vindas","boas_vindas",F("Bem-vindo. Como posso ajudar?")),V("m1","menu","Menu Principal","menu_principal",n("Para suporte, tecle 1. Para vendas, tecle 2.",[{id:"suporte",label:"Suporte",digit:"1"},{id:"vendas",label:"Vendas",digit:"2"}],{},"Escolha uma opção:")),V("t2","tell","Transferindo Suporte","transferindo_suporte",F("Transferindo para o suporte.")),V("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),V("t3","tell","Transferindo Vendas","transferindo_vendas",F("Transferindo para vendas.")),V("x2","transfer","Vendas","vendas",{method:"bridge",destinations:["1002"],timeout:30}),V("t4","tell","Fora do Horário","fora_horario",F("Nosso horário de atendimento é de segunda a sexta, das 8h às 18h. Ligue novamente no próximo dia útil.")),V("t5","tell","Opção Não Reconhecida","opcao_nao_reconhecida",F("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),V("t6","tell","Transferência Falhou","transferencia_falhou",F("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[X("e1v","s1","voice","tr1"),X("e1c","s1","chat","tr1"),X("e2","tr1","onHours","t1"),X("e3","tr1","offHours","t4"),X("e4","tr1","holiday","t4"),X("e5","t1","next","m1"),X("e6","m1","option:suporte","t2"),X("e7","m1","option:vendas","t3"),X("e8","t2","next","x1"),X("e9","t3","next","x2"),X("e10","m1","noMatch","t5"),X("e11","m1","error","t5"),X("e12","t5","next","x1"),...d("ex1","x1","h1","t6"),...d("ex2","x2","h1","t6"),X("e13","t4","next","h1"),X("e14","t6","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var rZ={id:"isp-suporte-tecnico",category:"industry",requiredModules:[],tags:["isp","provedor","internet","suporte","tecnico","telecom"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Boas-vindas","boas_vindas",F("Bem-vindo ao suporte técnico.")),V("m1","menu","Tipo de Serviço","tipo_servico",n("Para problemas de internet, tecle 1. Para problemas de telefonia, tecle 2.",[{id:"internet",label:"Internet",digit:"1"},{id:"telefonia",label:"Telefonia",digit:"2"}],{},"Escolha o tipo de serviço:")),V("c1","capture","Contrato Internet","contrato_internet",D$("Informe o número do seu contrato.",{voiceMethod:"dtmf",minDigits:3,maxDigits:10,terminators:"#",text:"Informe o número do seu contrato:",validation:String.raw`^\d{3,10}$`,invalidMessage:"O número do contrato deve ter de 3 a 10 dígitos. Tente novamente:"})),V("c2","capture","Contrato Telefonia","contrato_telefonia",D$("Informe o número do seu contrato.",{voiceMethod:"dtmf",minDigits:3,maxDigits:10,terminators:"#",text:"Informe o número do seu contrato:",validation:String.raw`^\d{3,10}$`,invalidMessage:"O número do contrato deve ter de 3 a 10 dígitos. Tente novamente:"})),V("http1","httpRequest","Status Internet","status_internet",{method:"GET",url:"https://api.example.com/contracts/{{contrato_internet.text}}/status?service=internet",headers:{},body:"",timeout:10}),V("http2","httpRequest","Status Telefonia","status_telefonia",{method:"GET",url:"https://api.example.com/contracts/{{contrato_telefonia.text}}/status?service=telefonia",headers:{},body:"",timeout:10}),V("t2","tell","Status Internet","status_internet_info",F("Sobre sua conexão de internet: {{status_internet.response}}")),V("t3","tell","Status Telefonia","status_telefonia_info",F("Sobre seu serviço de telefonia: {{status_telefonia.response}}")),V("sw1","switchCase","Falha Internet","falha_internet",{expression:"{{status_internet.status_code}}",cases:[{pattern:"^404$"}]}),V("sw2","switchCase","Falha Telefonia","falha_telefonia",{expression:"{{status_telefonia.status_code}}",cases:[{pattern:"^404$"}]}),V("t4","tell","Contrato Não Encontrado","contrato_nao_encontrado",F("Não encontrei esse contrato. Vou transferir para um atendente.")),V("t5","tell","Erro de Consulta","erro_consulta",F("Não foi possível consultar o status agora. Vou transferir para um atendente.")),V("t6","tell","Sem Contrato","sem_contrato",F("Não consegui capturar o número do contrato. Vou transferir para um atendente.")),V("t7","tell","Opção Não Reconhecida","opcao_nao_reconhecida",F("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),V("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["3001"],timeout:60}),V("t8","tell","Transferência Falhou","transferencia_falhou",F("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[X("e1v","s1","voice","t1"),X("e1c","s1","chat","t1"),X("e2","t1","next","m1"),X("e3","m1","option:internet","c1"),X("e4","m1","option:telefonia","c2"),X("e5","m1","noMatch","t7"),X("e5e","m1","error","t7"),X("e6","c1","collected","http1"),X("e7","c1","noInput","t6"),X("e7e","c1","error","t6"),X("e8","http1","next","t2"),X("e9","http1","error","sw1"),X("e10","sw1","match:^404$","t4"),X("e11","sw1","fallback","t5"),X("e11e","sw1","error","t5"),X("e12","t2","next","h1"),X("e13","c2","collected","http2"),X("e14","c2","noInput","t6"),X("e14e","c2","error","t6"),X("e15","http2","next","t3"),X("e16","http2","error","sw2"),X("e17","sw2","match:^404$","t4"),X("e18","sw2","fallback","t5"),X("e18e","sw2","error","t5"),X("e19","t3","next","h1"),X("e20","t4","next","x1"),X("e21","t5","next","x1"),X("e22","t6","next","x1"),X("e23","t7","next","x1"),...d("ex1","x1","h1","t8"),X("e24","t8","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var iZ={id:"mensagem-simples",category:"core",requiredModules:[],tags:["mensagem","simples","aviso","anuncio","basico"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Mensagem","mensagem",F("Obrigado por ligar. No momento não estamos disponíveis. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[X("e1v","s1","voice","t1"),X("e1c","s1","chat","t1"),X("e2","t1","next","h1")],viewport:{x:0,y:0,zoom:1}}};var dZ={id:"menu-multinivel",category:"advanced",requiredModules:[],tags:["menu","multinivel","departamento","hierarquia","complexo"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Boas-vindas","boas_vindas",F("Bem-vindo. Escolha o setor desejado.")),V("m1","menu","Menu Principal","menu_principal",n("Para atendimento, tecle 1. Para comercial, tecle 2. Para administrativo, tecle 3.",[{id:"atendimento",label:"Atendimento",digit:"1"},{id:"comercial",label:"Comercial",digit:"2"},{id:"administrativo",label:"Administrativo",digit:"3"}],{},"Escolha o setor desejado:")),V("m2","menu","Atendimento","atendimento",n("Para suporte técnico, tecle 1. Para financeiro, tecle 2.",[{id:"suporte",label:"Suporte Técnico",digit:"1"},{id:"financeiro",label:"Financeiro",digit:"2"}],{},"Escolha uma opção:")),V("m3","menu","Comercial","comercial",n("Para vendas, tecle 1. Para parcerias, tecle 2.",[{id:"vendas",label:"Vendas",digit:"1"},{id:"parcerias",label:"Parcerias",digit:"2"}],{},"Escolha uma opção:")),V("m4","menu","Administrativo","administrativo",n("Para RH, tecle 1. Para jurídico, tecle 2.",[{id:"rh",label:"RH",digit:"1"},{id:"juridico",label:"Jurídico",digit:"2"}],{},"Escolha uma opção:")),V("t2","tell","Transferindo Suporte","transferindo_suporte",F("Transferindo para suporte técnico.")),V("t3","tell","Transferindo Financeiro","transferindo_financeiro",F("Transferindo para financeiro.")),V("t4","tell","Transferindo Vendas","transferindo_vendas",F("Transferindo para vendas.")),V("t5","tell","Transferindo Parcerias","transferindo_parcerias",F("Transferindo para parcerias.")),V("t6","tell","Transferindo RH","transferindo_rh",F("Transferindo para RH.")),V("t7","tell","Transferindo Jurídico","transferindo_juridico",F("Transferindo para jurídico.")),V("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),V("x2","transfer","Financeiro","financeiro",{method:"bridge",destinations:["1002"],timeout:45}),V("x3","transfer","Vendas","vendas",{method:"bridge",destinations:["2001"],timeout:30}),V("x4","transfer","Parcerias","parcerias",{method:"bridge",destinations:["2002"],timeout:30}),V("x5","transfer","RH","rh",{method:"bridge",destinations:["3001"],timeout:30}),V("x6","transfer","Jurídico","juridico",{method:"bridge",destinations:["3002"],timeout:30}),V("t8","tell","Opção Não Reconhecida","opcao_nao_reconhecida",F("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),V("t9","tell","Transferência Falhou","transferencia_falhou",F("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[X("e1v","s1","voice","t1"),X("e1c","s1","chat","t1"),X("e2","t1","next","m1"),X("e3","m1","option:atendimento","m2"),X("e4","m1","option:comercial","m3"),X("e5","m1","option:administrativo","m4"),X("e6","m1","noMatch","t8"),X("e6e","m1","error","t8"),X("e7","m2","option:suporte","t2"),X("e8","m2","option:financeiro","t3"),X("e9","m2","noMatch","t8"),X("e9e","m2","error","t8"),X("e10","m3","option:vendas","t4"),X("e11","m3","option:parcerias","t5"),X("e12","m3","noMatch","t8"),X("e12e","m3","error","t8"),X("e13","m4","option:rh","t6"),X("e14","m4","option:juridico","t7"),X("e15","m4","noMatch","t8"),X("e15e","m4","error","t8"),X("e16","t2","next","x1"),X("e17","t3","next","x2"),X("e18","t4","next","x3"),X("e19","t5","next","x4"),X("e20","t6","next","x5"),X("e21","t7","next","x6"),X("e28","t8","next","x1"),...d("ex1","x1","h1","t9"),...d("ex2","x2","h1","t9"),...d("ex3","x3","h1","t9"),...d("ex4","x4","h1","t9"),...d("ex5","x5","h1","t9"),...d("ex6","x6","h1","t9"),X("e29","t9","next","h1")],viewport:{x:0,y:0,zoom:0.7}}};var oZ={id:"notificacao-atendimento",category:"core",requiredModules:[],tags:["notificacao","aviso","atendimento","callback"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Notificação","notificacao",F("Olá, temos uma informação importante sobre sua conta.")),V("m1","menu","Precisa de Ajuda?","precisa_ajuda",n("Tecle 1 para falar com um atendente, ou 2 para encerrar.",[{id:"sim",label:"Sim, falar com atendente",digit:"1"},{id:"nao",label:"Não, obrigado",digit:"2"}],{},"Deseja falar com um atendente?")),V("t2","tell","Transferindo","transferindo",F("Aguarde, vou transferir para um atendente.")),V("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["1000"],timeout:45}),V("t3","tell","Agradecimento","agradecimento",F("Obrigado pelo seu tempo. Tenha um bom dia!")),V("t4","tell","Transferência Falhou","transferencia_falhou",F("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[X("e1v","s1","voice","t1"),X("e1c","s1","chat","t1"),X("e2","t1","next","m1"),X("e3","m1","option:sim","t2"),X("e4","m1","option:nao","t3"),X("e5","m1","noMatch","t3"),X("e6","m1","error","t3"),X("e7","t2","next","x1"),...d("ex1","x1","h1","t4"),X("e8","t3","next","h1"),X("e9","t4","next","h1")],viewport:{x:0,y:0,zoom:0.9}}};var nZ={id:"pesquisa-nps",category:"advanced",requiredModules:["ai"],tags:["nps","pesquisa","promotor","detrator","feedback","avaliacao"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Intro NPS","intro_nps",F("Gostaríamos de saber sua opinião sobre nosso atendimento.")),V("c1","capture","Nota NPS","nota_nps",D$("De 0 a 10, qual a probabilidade de recomendar nossos serviços? Tecle a nota.",{voiceMethod:"dtmf",minDigits:1,maxDigits:2,terminators:"#",text:"De 0 a 10, qual a probabilidade de recomendar nossos serviços?",validation:"^(10|[0-9])$",invalidMessage:"Informe uma nota de 0 a 10:"})),V("sw1","switchCase","Classificar NPS","classificar_nps",{expression:"{{nota_nps.text}}",cases:[{pattern:"^9$"},{pattern:"^10$"},{pattern:"^7$"},{pattern:"^8$"}]}),V("t2","tell","Promotor","promotor",F("Que ótimo! Ficamos muito felizes com sua avaliação.")),V("t3","tell","Neutro","neutro",F("Obrigado pela avaliação. Vamos trabalhar para melhorar.")),V("t4","tell","Detrator","detrator",F("Lamentamos que sua experiência não tenha sido satisfatória.")),V("c2","capture","Feedback","feedback",D$("Pode nos dizer o que podemos melhorar? Fale após o sinal.",{voiceMethod:"speech",text:"Pode nos dizer o que podemos melhorar?"})),V("http1","httpRequest","Salvar Pesquisa","salvar_pesquisa",{method:"POST",url:"https://api.example.com/nps",headers:{"Content-Type":"application/json"},body:'{"score": "{{nota_nps.text}}", "feedback": "{{feedback.text}}"}',timeout:10}),V("t5","tell","Agradecimento","agradecimento",F("Obrigado pelo seu feedback. Ele é muito importante para nós.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[X("e1v","s1","voice","t1"),X("e1c","s1","chat","t1"),X("e2","t1","next","c1"),X("e3","c1","collected","sw1"),X("e4","c1","noInput","t5"),X("e4e","c1","error","t5"),X("e5","sw1","match:^9$","t2"),X("e6","sw1","match:^10$","t2"),X("e7","sw1","match:^7$","t3"),X("e8","sw1","match:^8$","t3"),X("e9","sw1","fallback","t4"),X("e9e","sw1","error","t4"),X("e10","t2","next","c2"),X("e11","t3","next","c2"),X("e12","t4","next","c2"),X("e13","c2","collected","http1"),X("e14","c2","noInput","http1"),X("e14e","c2","error","http1"),X("e15","http1","next","t5"),X("e16","http1","error","t5"),X("e17","t5","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var pZ={id:"pesquisa-satisfacao",category:"core",requiredModules:[],tags:["pesquisa","satisfacao","csat","avaliacao","nota"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Intro Pesquisa","intro_pesquisa",F("Gostaríamos de avaliar o atendimento que você recebeu.")),V("m1","menu","Nota de Satisfação","nota_satisfacao",n("Como você avalia o atendimento? Tecle 1 para péssimo, 2 para ruim, 3 para regular, 4 para bom, ou 5 para excelente.",[{id:"nota_1",label:"1 - Péssimo",digit:"1"},{id:"nota_2",label:"2 - Ruim",digit:"2"},{id:"nota_3",label:"3 - Regular",digit:"3"},{id:"nota_4",label:"4 - Bom",digit:"4"},{id:"nota_5",label:"5 - Excelente",digit:"5"}],{maxAttempts:2},"Como você avalia o atendimento que recebeu?")),V("t2","tell","Agradecimento","agradecimento",F("Você avaliou nosso atendimento como: {{nota_satisfacao.selectedLabel}}. Obrigado, sua opinião nos ajuda a melhorar.")),V("t3","tell","Sem Resposta","sem_resposta",F("Não conseguimos registrar sua avaliação. Agradecemos o contato.")),V("h1","hangup","Desligamento","desligamento",{}),V("h2","hangup","Desligamento Timeout","desligamento_timeout",{})],edges:[X("e1v","s1","voice","t1"),X("e1c","s1","chat","t1"),X("e2","t1","next","m1"),X("e3","m1","option:nota_1","t2"),X("e4","m1","option:nota_2","t2"),X("e5","m1","option:nota_3","t2"),X("e6","m1","option:nota_4","t2"),X("e7","m1","option:nota_5","t2"),X("e8","t2","next","h1"),X("e9","m1","noMatch","t3"),X("e10","m1","error","t3"),X("e11","t3","next","h2")],viewport:{x:0,y:0,zoom:0.9}}};var tZ={id:"roteamento-canal",category:"omnichannel",requiredModules:[],tags:["canal","omnichannel","voz","chat","roteamento"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("cr1","channelRouter","Roteador de Canal","roteador_canal",{}),V("t1","tell","Boas-vindas Voz","boas_vindas_voz",F("Bem-vindo ao nosso atendimento por telefone.")),V("m1","menu","Menu Voz","menu_voz",n("Para suporte, tecle 1. Para vendas, tecle 2.",[{id:"suporte",label:"Suporte",digit:"1"},{id:"vendas",label:"Vendas",digit:"2"}])),V("t2","tell","Boas-vindas Chat","boas_vindas_chat",F("Olá! Bem-vindo ao nosso atendimento por chat.")),V("m2","menu","Menu Chat","menu_chat",n("Para suporte, tecle 1. Para vendas, tecle 2.",[{id:"suporte",label:"Suporte",digit:"1"},{id:"vendas",label:"Vendas",digit:"2"}],{},"Escolha uma opção:")),V("t3","tell","Transferindo Suporte","transferindo_suporte",F("Transferindo para o suporte.")),V("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),V("t4","tell","Transferindo Vendas","transferindo_vendas",F("Transferindo para vendas.")),V("x2","transfer","Vendas","vendas",{method:"bridge",destinations:["1002"],timeout:30}),V("t5","tell","Opção Não Reconhecida","opcao_nao_reconhecida",F("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),V("t6","tell","Transferência Falhou","transferencia_falhou",F("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[X("e1v","s1","voice","cr1"),X("e1c","s1","chat","cr1"),X("e2","cr1","voice","t1"),X("e3","cr1","chat","t2"),X("e4","t1","next","m1"),X("e5","t2","next","m2"),X("e6","m1","option:suporte","t3"),X("e7","m1","option:vendas","t4"),X("e8","m2","option:suporte","t3"),X("e9","m2","option:vendas","t4"),X("e10","t3","next","x1"),X("e11","t4","next","x2"),...d("ex1","x1","h1","t6"),...d("ex2","x2","h1","t6"),X("e12","m1","noMatch","t5"),X("e13","m1","error","t5"),X("e14","m2","noMatch","t5"),X("e15","m2","error","t5"),X("e16","t5","next","x1"),X("e17","t6","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var aZ={id:"status-pedido",category:"capture",requiredModules:[],tags:["pedido","status","rastreio","ecommerce","api"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Boas-vindas","boas_vindas",F("Olá. Vou consultar o status do seu pedido.")),V("c1","capture","Número do Pedido","numero_pedido",D$("Informe o número do seu pedido e finalize com a tecla jogo da velha.",{voiceMethod:"dtmf",minDigits:1,maxDigits:10,terminators:"#",text:"Informe o número do seu pedido:",validation:String.raw`^\d{1,10}$`,invalidMessage:"O número do pedido deve conter apenas dígitos. Tente novamente:"})),V("http1","httpRequest","Consultar Pedido","consultar_pedido",{method:"GET",url:"https://api.example.com/orders/{{numero_pedido.text}}",headers:{},body:"",timeout:10}),V("sw1","switchCase","Tipo de Falha","tipo_falha",{expression:"{{consultar_pedido.status_code}}",cases:[{pattern:"^404$"}]}),V("t2","tell","Status do Pedido","status_do_pedido",F("O status do seu pedido é: {{consultar_pedido.response}}")),V("t3","tell","Pedido Não Encontrado","pedido_nao_encontrado",F("Não encontrei esse número de pedido. Verifique e tente novamente.")),V("t4","tell","Erro de Consulta","erro_consulta",F("Houve um erro ao consultar o pedido. Tente novamente mais tarde.")),V("t5","tell","Sem Número","sem_numero",F("Não consegui capturar o número do pedido. Por favor, ligue novamente com o número em mãos.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[X("e1v","s1","voice","t1"),X("e1c","s1","chat","t1"),X("e2","t1","next","c1"),X("e3","c1","collected","http1"),X("e4","c1","noInput","t5"),X("e5","c1","error","t5"),X("e6","http1","next","t2"),X("e7","http1","error","sw1"),X("e8","sw1","match:^404$","t3"),X("e9","sw1","fallback","t4"),X("e10","sw1","error","t4"),X("e11","t2","next","h1"),X("e12","t3","next","h1"),X("e13","t4","next","h1"),X("e14","t5","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var sZ={id:"triagem-inteligente",category:"ai",requiredModules:["ai"],tags:["triagem","intencao","intent","ia","roteamento","ai"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Boas-vindas","boas_vindas",F("Olá! Vou te direcionar para o setor correto.")),V("c1","capture","Motivo do Contato","motivo_contato",D$("Diga em poucas palavras com o que você precisa de ajuda.",{voiceMethod:"speech",maxAttempts:3,listen:{initial_timeout_s:10,timeout_s:3,max_duration_s:15,beep:!0},processing_audio:w4("Um momento enquanto identifico o setor correto.").audio,text:"Descreva em poucas palavras com o que você precisa de ajuda:"})),V("ra1","routeAi","Classificar Intenção","classificar_intencao",{input:"{{motivo_contato.text}}",intents:[{label:"suporte",description:"Problemas técnicos, dúvidas de uso, erros no sistema"},{label:"financeiro",description:"Faturas, cobranças, pagamentos, reembolsos"},{label:"vendas",description:"Novos produtos, planos, promoções, contratação"}],instructions:"Classifique a intenção do cliente com base no que ele disse."}),V("t2","tell","Direcionando Suporte","direcionando_suporte",F("Entendi, vou transferir para o suporte técnico.")),V("t3","tell","Direcionando Financeiro","direcionando_financeiro",F("Entendi, vou transferir para o financeiro.")),V("t4","tell","Direcionando Vendas","direcionando_vendas",F("Entendi, vou transferir para vendas.")),V("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),V("x2","transfer","Financeiro","financeiro",{method:"bridge",destinations:["1002"],timeout:45}),V("x3","transfer","Vendas","vendas",{method:"bridge",destinations:["1003"],timeout:30}),V("t5","tell","Não Identificado","nao_identificado",F("Não consegui identificar sua necessidade. Vou transferir para um atendente.")),V("x4","transfer","Atendente Geral","atendente_geral",{method:"bridge",destinations:["1000"],timeout:45}),V("t6","tell","Transferência Falhou","transferencia_falhou",F("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[X("e1v","s1","voice","t1"),X("e1c","s1","chat","t1"),X("e2","t1","next","c1"),X("e3","c1","collected","ra1"),X("e4","c1","noInput","t5"),X("e5","c1","error","t5"),X("e6","ra1","intent:suporte","t2"),X("e7","ra1","intent:financeiro","t3"),X("e8","ra1","intent:vendas","t4"),X("e9","ra1","notApplicable","t5"),X("e10","ra1","error","t5"),X("e11","t2","next","x1"),X("e12","t3","next","x2"),X("e13","t4","next","x3"),X("e14","t5","next","x4"),...d("ex1","x1","h1","t6"),...d("ex2","x2","h1","t6"),...d("ex3","x3","h1","t6"),...d("ex4","x4","h1","t6"),X("e15","t6","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var eZ={id:"ura-reversa-spot",category:"core",requiredModules:[],tags:["spot","ura reversa","campanha","outbound","discagem","tecla"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("m1","menu","Spot","spot",n("Substitua este texto pelo áudio do seu spot. Para falar com um atendente, tecle 1.",[{id:"interesse",label:"Falar com atendente",digit:"1"}],{maxAttempts:1},"Substitua este texto pelo conteúdo do seu spot.")),V("t1","tell","Agradecimento","agradecimento",F("Obrigado! Em instantes um atendente entrará em contato.")),V("t2","tell","Encerramento","encerramento",F("Obrigado pela atenção. Até logo!")),V("h1","hangup","Desligamento","desligamento",{})],edges:[X("e1v","s1","voice","m1"),X("e1c","s1","chat","m1"),X("e2","m1","option:interesse","t1"),X("e3","m1","noMatch","t2"),X("e4","m1","error","t2"),X("e5","t1","next","h1"),X("e6","t2","next","h1")],viewport:{x:0,y:0,zoom:0.9}}};var $B={"atendente-virtual-ia":{ai1:{x:752,y:180},h1:{x:2632,y:264},m1:{x:1128,y:0},s1:{x:0,y:36},t1:{x:376,y:119},t2:{x:1880,y:61},t3:{x:1504,y:113},t4:{x:1504,y:263},t5:{x:2256,y:316},x1:{x:1880,y:211}},"atendimento-agente-ia":{ai1:{x:1504,y:38},c1:{x:752,y:208},h1:{x:3384,y:129},ra1:{x:1128,y:116},s1:{x:0,y:64},sw1:{x:1880,y:0},t1:{x:376,y:147},t2:{x:3008,y:68},t3:{x:1504,y:221},t4:{x:2256,y:153},t5:{x:3008,y:218},x1:{x:2632,y:113}},"atendimento-setores":{h1:{x:2256,y:770},m1:{x:752,y:327},s1:{x:0,y:183},t1:{x:376,y:266},t2:{x:1128,y:0},t3:{x:1128,y:216},t4:{x:1128,y:432},t5:{x:1128,y:582},t6:{x:1128,y:732},t7:{x:1880,y:576},x1:{x:1504,y:61},x2:{x:1504,y:277},x3:{x:1504,y:493},x4:{x:1504,y:709}},"banco-sac":{c1:{x:376,y:376},h1:{x:2632,y:324},http1:{x:1128,y:0},m1:{x:752,y:180},s1:{x:0,y:293},t1:{x:1880,y:215},t2:{x:1504,y:263},t3:{x:1504,y:413},t4:{x:1128,y:331},t5:{x:1504,y:113},t6:{x:1128,y:481},t7:{x:2256,y:557},x1:{x:1880,y:474}},"clinica-agendamento":{c1:{x:1128,y:140},h1:{x:2256,y:306},http1:{x:1504,y:121},m1:{x:752,y:144},s1:{x:0,y:0},t1:{x:376,y:83},t2:{x:1880,y:95},t3:{x:1880,y:245},t4:{x:1504,y:293}},"cobranca-automatizada":{c1:{x:1128,y:139},h1:{x:2632,y:283},m1:{x:752,y:339},s1:{x:0,y:195},t1:{x:376,y:278},t2:{x:1504,y:0},t3:{x:1880,y:335},t4:{x:2256,y:444},t5:{x:1128,y:496},t6:{x:1504,y:222},t7:{x:2256,y:174},x1:{x:1880,y:61}},"coleta-dados-api":{c1:{x:752,y:206},h1:{x:2256,y:174},http1:{x:1128,y:75},s1:{x:0,y:62},sw1:{x:1504,y:158},t1:{x:376,y:145},t2:{x:1504,y:0},t3:{x:1880,y:113},t4:{x:1880,y:263},t5:{x:1128,y:311}},"faq-ia-escalacao":{ai1:{x:752,y:144},h1:{x:2632,y:316},m1:{x:1128,y:52},s1:{x:0,y:0},t1:{x:376,y:83},t2:{x:1880,y:113},t3:{x:1504,y:179},t4:{x:2256,y:368},x1:{x:1880,y:263}},"faq-informacoes":{h1:{x:1504,y:738},m1:{x:752,y:144},s1:{x:0,y:0},t1:{x:376,y:83},t2:{x:1128,y:67},t3:{x:1128,y:227},t4:{x:1128,y:377},t5:{x:1128,y:527},t6:{x:1128,y:677}},"horario-comercial":{h1:{x:2632,y:452},m1:{x:1128,y:216},s1:{x:0,y:203},t1:{x:752,y:155},t2:{x:1504,y:0},t3:{x:1504,y:193},t4:{x:752,y:391},t5:{x:1504,y:343},t6:{x:2256,y:343},tr1:{x:376,y:286},x1:{x:1880,y:61},x2:{x:1880,y:277}},"isp-suporte-tecnico":{c1:{x:1128,y:33},c2:{x:1128,y:227},h1:{x:3384,y:296},http1:{x:1504,y:22},http2:{x:1504,y:351},m1:{x:752,y:144},s1:{x:0,y:0},sw1:{x:1880,y:135},sw2:{x:1880,y:329},t1:{x:376,y:83},t2:{x:2632,y:115},t3:{x:3008,y:498},t4:{x:2256,y:196},t5:{x:2256,y:346},t6:{x:1504,y:201},t7:{x:1128,y:421},t8:{x:3008,y:348},x1:{x:2632,y:265}},"mensagem-simples":{h1:{x:752,y:144},s1:{x:0,y:0},t1:{x:376,y:83}},"menu-multinivel":{h1:{x:2632,y:507},m1:{x:752,y:522},m2:{x:1128,y:280},m3:{x:1128,y:496},m4:{x:1128,y:723},s1:{x:0,y:378},t1:{x:376,y:461},t2:{x:1504,y:71},t3:{x:1504,y:221},t4:{x:1504,y:371},t5:{x:1504,y:521},t6:{x:1504,y:821},t7:{x:1504,y:1019},t8:{x:1504,y:671},t9:{x:2256,y:559},x1:{x:1880,y:216},x2:{x:1880,y:0},x3:{x:1880,y:432},x4:{x:1880,y:648},x5:{x:1880,y:864},x6:{x:1880,y:1080}},"notificacao-atendimento":{h1:{x:2256,y:284},m1:{x:752,y:144},s1:{x:0,y:0},t1:{x:376,y:83},t2:{x:1128,y:49},t3:{x:1128,y:271},t4:{x:1880,y:223},x1:{x:1504,y:110}},"pesquisa-nps":{c1:{x:752,y:320},c2:{x:1880,y:211},h1:{x:3008,y:486},http1:{x:2256,y:294},s1:{x:0,y:176},sw1:{x:1128,y:45},t1:{x:376,y:259},t2:{x:1504,y:0},t3:{x:1504,y:150},t4:{x:1504,y:300},t5:{x:2632,y:425}},"pesquisa-satisfacao":{h1:{x:1504,y:288},h2:{x:1504,y:438},m1:{x:752,y:144},s1:{x:0,y:0},t1:{x:376,y:83},t2:{x:1128,y:227},t3:{x:1128,y:377}},"roteamento-canal":{cr1:{x:376,y:83},h1:{x:2632,y:497},m1:{x:1128,y:205},m2:{x:1128,y:421},s1:{x:0,y:0},t1:{x:752,y:144},t2:{x:752,y:360},t3:{x:1504,y:248},t4:{x:1504,y:398},t5:{x:1504,y:548},t6:{x:2256,y:436},x1:{x:1880,y:309},x2:{x:1880,y:525}},"status-pedido":{c1:{x:752,y:206},h1:{x:2256,y:174},http1:{x:1128,y:75},s1:{x:0,y:62},sw1:{x:1504,y:158},t1:{x:376,y:145},t2:{x:1504,y:0},t3:{x:1880,y:113},t4:{x:1880,y:263},t5:{x:1128,y:311}},"triagem-inteligente":{c1:{x:752,y:411},h1:{x:2632,y:465},ra1:{x:1128,y:261},s1:{x:0,y:267},t1:{x:376,y:350},t2:{x:1504,y:0},t3:{x:1504,y:216},t4:{x:1504,y:366},t5:{x:1504,y:516},t6:{x:2256,y:404},x1:{x:1880,y:61},x2:{x:1880,y:277},x3:{x:1880,y:493},x4:{x:1880,y:709}},"ura-reversa-spot":{h1:{x:1128,y:99},m1:{x:376,y:83},s1:{x:0,y:0},t1:{x:752,y:38},t2:{x:752,y:188}}};function gA($){let U=$B[$.id];if(U==null)return $;return{...$,editorState:{...$.editorState,nodes:$.editorState.nodes.map((K)=>{let q=U[K.id];return q==null?K:{...K,position:{...q}}})}}}var UB=[yZ,lZ,pZ,cZ,iZ,eZ,mZ,fZ,aZ,CZ,sZ,hZ,EZ,tZ,oZ,uZ,rZ,gZ,dZ,nZ].map(($)=>gA($));var QB=[{nodeId:"__global_args__",nodeLabel:"Args",nodeVarName:"args",nodeType:"start",variables:[{name:"*",type:"string",descriptionKey:"editor:vars.args"}]},{nodeId:"__global_dialer__",nodeLabel:"Dialer",nodeLabelKey:"editor:vars.dialerGroup",nodeVarName:"args",nodeType:"start",module:"dialer",variables:[{name:"dialer_contact_name",type:"string",descriptionKey:"editor:vars.dialerContactName"},{name:"dialer_contact_phone",type:"string",descriptionKey:"editor:vars.dialerContactPhone"},{name:"dialer_campaign_id",type:"string",descriptionKey:"editor:vars.dialerCampaignId"}]}],KB="vars",qB="counters",BJ=new Set([...QB.map(($)=>$.nodeVarName),g8,KB,qB].map(($)=>$.split(".")[0]));function VJ($){return BJ.has($)}var WB={tell:new Set(["audio"]),menu:new Set(["audio","voiceTimeout"]),capture:new Set(["audio","voiceMethod","minDigits","maxDigits","terminators","voiceTimeout","listen","processing_audio","retryAudio"])},JB={tell:new Set(["content"]),menu:new Set(["text","invalidMessage"]),capture:new Set(["text","validation","invalidMessage"])};function MJ($,U,K,q){let Q=$.filter((H)=>H.type==="start"),W=pA(U),J=Q[0]?.id,j=Yv($,U),Y=[...nA(Q),...tA($,W,J),...aA($),...sA($),...eA($),...$v($),...Qv($),...Kv($),...qv($,U,K),...Wv($,W,J),...Jv($),...Gv($),...jv($,K,q?.disabledModules),...q?.entities!=null?QJ($,q.entities):[],...q?.externalEntities!=null?KJ($,q.externalEntities):[],...Hv($,K,j),...Xv($),...Bv($),...q?.mediaProfile!=null?rA($,U,q.mediaProfile):[]];if(j!=null)return Vv(Y,$,j);return Y}function rA($,U,K){let q=$.find((j)=>j.type==="start");if(q==null)return[];let Q=new Map;for(let j of U){let Y=Q.get(j.source)??new Map;Y.set(j.sourceHandle,j.target),Q.set(j.source,Y)}let W=Bq(q.id,K.profile,$,Q,K.recordingEnabled),J=[];for(let j of $){let Y=W[j.id];if(Y==null||!iA(j.type))continue;let Z=dA(j.type,Y).filter((B)=>B.value.kind==="indeterminate");if(Z.length>0)J.push({nodeId:j.id,severity:"warning",messageKey:"editor:validation.mediaStateIndeterminate",params:{label:j.label,fields:Z.map((B)=>B.name).join(", "),paths:Z.map((B)=>oA(B.value)).join("; ")}});if(j.type==="transcription"&&Y.transcriptionEnabled.kind==="known"&&Y.transcriptionEnabled.value&&Y.recordingEnabled.kind==="known"&&!Y.recordingEnabled.value)J.push({nodeId:j.id,severity:"warning",messageKey:"editor:validation.transcriptionWithoutRecording",params:{label:j.label}})}return J}function iA($){return $==="recording"||$==="transcription"||$==="analysis"}function dA($,U){if($==="recording")return[{name:"recording",value:U.recordingEnabled},{name:"sampling",value:U.samplingPercentage}];if($==="transcription")return[{name:"recording",value:U.recordingEnabled},{name:"transcription",value:U.transcriptionEnabled},{name:"language",value:U.transcriptionLanguage},{name:"minimum_duration",value:U.transcriptionMinDurationSeconds},{name:"anonymization",value:U.anonymizeEnabled}];return[{name:"transcription",value:U.transcriptionEnabled},{name:"speech_analytics",value:U.speechAnalyticsEnabled},{name:"sentiment",value:U.sentimentEnabled},{name:"topics",value:U.topicDetectionTopics},{name:"intents",value:U.intentDetectionIntents},{name:"structured_analysis",value:U.structuredAnalysisEnabled},{name:"analysis_ids",value:U.structuredAnalysisIds}]}function oA($){if($.kind==="known")return"";return $.branches.map((U)=>U.viaNodeLabel).join(", ")}function nA($){if($.length===0)return[{nodeId:"",severity:"error",messageKey:"editor:validation.noStart"}];return $.slice(1).map((U)=>({nodeId:U.id,severity:"error",messageKey:"editor:validation.multipleStart"}))}function pA($){let U=new Map;for(let K of $){let q=U.get(K.source)??[];q.push(K.target),U.set(K.source,q)}return U}function tA($,U,K){if(K===void 0)return[];let q=new Set([K]),Q=[K];while(Q.length>0){let J=Q.pop();for(let j of U.get(J)??[])if(!q.has(j))q.add(j),Q.push(j)}let W=[];for(let J of $)if(J.type!=="start"&&!q.has(J.id))W.push({nodeId:J.id,severity:"warning",messageKey:"editor:validation.unreachable",params:{label:J.label}});return W}function aA($){let U=[];for(let K of $){if(!Object.hasOwn(t$,K.type)){U.push({nodeId:K.id,severity:"error",messageKey:"editor:validation.unknownNodeType",params:{label:K.label,type:K.type}});continue}let q=t$[K.type],Q=q.configSchema.safeParse(K.config),W=Q.success?Q.data:K.config,J=Q.success?q.configSchema.safeParse(W):Q;if(J.success)continue;for(let j of J.error.issues){let Y=j.message.startsWith("editor:")?j.message:"editor:validation.invalidField";U.push({nodeId:K.id,severity:"error",messageKey:Y,params:{label:K.label,field:j.path.join(".")}})}}return U}function DJ($){let U=[];for(let K of $){if(K.type!=="transfer")continue;let q=t$.transfer.configSchema.safeParse(K.config);if(!q.success)continue;U.push({node:K,destinations:q.data.destinations,attachedData:q.data.attachedData})}return U}function sA($){let U=[];for(let{node:K,destinations:q}of DJ($)){if(q.some((Q)=>Q.trim()!==""))continue;U.push({nodeId:K.id,severity:"error",messageKey:"editor:validation.noDestinations",params:{label:K.label}})}return U}function eA($){let U=[];for(let{node:K,destinations:q,attachedData:Q}of DJ($)){let W=[...q.map((J,j)=>({field:`destinations.${j}`,template:J})),...Q.map((J)=>({field:J.key,template:J.value}))];for(let{field:J,template:j}of W){if(uq(j).valid)continue;U.push({nodeId:K.id,severity:"error",messageKey:"editor:validation.invalidTemplateSyntax",params:{label:K.label,field:J}})}}return U}function $v($){let U=[];for(let{node:K,destinations:q}of DJ($))q.forEach((Q,W)=>{if(!/\s/.test(Q.trim()))return;U.push({nodeId:K.id,severity:"error",messageKey:"editor:validation.destinationHasSpace",params:{label:K.label,field:`destinations.${W}`}})});return U}var Uv=new Set(["httpRequest","webhook"]);function Qv($){let U=[];for(let K of $){if(!Uv.has(K.type))continue;let q=typeof K.config.body==="string"?K.config.body:"";if(q.trim()==="")continue;let Q=yq(q,()=>'"__tpl__"');try{JSON.parse(Q)}catch{U.push({nodeId:K.id,severity:"warning",messageKey:"editor:validation.invalidJson",params:{label:K.label}})}}return U}function Kv($){return f8($).misplaced.map((U)=>({nodeId:U.nodeId,severity:"error",messageKey:"editor:validation.secretFieldNotAllowed",params:{label:U.label,field:U.field,secret:U.name}}))}function qv($,U,K){let q=new Set(U.map((W)=>W.source)),Q=[];for(let W of $){if(!Object.hasOwn(K,W.type))continue;let J=K[W.type];if(x4(J,W.config).length===0)continue;if(q.has(W.id))continue;Q.push({nodeId:W.id,severity:"warning",messageKey:"editor:validation.noOutputConnection",params:{label:W.label}})}return Q}function Wv($,U,K){if(K===void 0)return[];let q=0,Q=1,W=2,J=new Map;for(let Z of $)J.set(Z.id,q);let j=new Set;function Y(Z){J.set(Z,Q);for(let B of U.get(Z)??[])if(J.get(B)===Q)j.add(B);else if(J.get(B)===q)Y(B);J.set(Z,W)}Y(K);let H=[];for(let Z of j){let B=$.find((I)=>I.id===Z);if(B===void 0)continue;if(!(typeof B.config.maxAttempts==="number"&&B.config.maxAttempts>0))H.push({nodeId:Z,severity:"error",messageKey:"editor:validation.infiniteCycle",params:{label:B.label}})}return H}function Jv($){let U=new Map,K=[];for(let q of $)if(U.get(q.varName)!==void 0)K.push({nodeId:q.id,severity:"error",messageKey:"editor:validation.duplicateVarName",params:{label:q.label,varName:q.varName}});else U.set(q.varName,q.id);return K}function Gv($){return $.filter((U)=>VJ(U.varName)).map((U)=>({nodeId:U.id,severity:"error",messageKey:"editor:validation.reservedVarName",params:{label:U.label,varName:U.varName}}))}function jv($,U,K){if(K==null||K.size===0)return[];let q=[];for(let Q of $){if(!Object.hasOwn(U,Q.type))continue;let W=U[Q.type];if(W.module!=="core"&&K.has(W.module))q.push({nodeId:Q.id,severity:"warning",messageKey:"editor:validation.moduleDisabled",params:{label:Q.label,module:W.module}})}return q}function Yv($,U){let K=$.find((j)=>j.type==="start");if(K==null)return null;let q=K.config.channelType;if((typeof q==="string"?q:"voice")!=="both")return null;let W=new Map;for(let j of U){let Y=W.get(j.source);if(Y==null)Y=new Map,W.set(j.source,Y);Y.set(j.sourceHandle,j.target)}let J=new Set;for(let j of $)if(j.type==="channelRouter")J.add(j.id);return $J(K.id,K.config,W,$.map((j)=>j.id),J.size>0?J:void 0)}function Hv($,U,K){if(K==null)return[];let q=[];for(let Q of $){if(Q.type==="start")continue;if(!Object.hasOwn(U,Q.type))continue;let W=U[Q.type],J=K[Q.id];if(J==null||J==="unreachable"||J==="converged")continue;if(W.channel==="voice"&&J==="chat-only")q.push({nodeId:Q.id,severity:"error",messageKey:"editor:validation.voiceNodeInChatBranch",params:{label:Q.label}});if(W.channel==="chat"&&J==="voice-only")q.push({nodeId:Q.id,severity:"error",messageKey:"editor:validation.chatNodeInVoiceBranch",params:{label:Q.label}})}return q}function Xv($){let K=$.find((W)=>W.type==="start")?.config.channelType;if((typeof K==="string"?K:"voice")!=="chat")return[];let Q=[];for(let W of $){if(W.type!=="retellAgent"&&W.type!=="vapiAgent"&&W.type!=="elevenlabsAgent")continue;Q.push({nodeId:W.id,severity:"error",messageKey:"editor:validation.voiceNodeInChatBranch",params:{label:W.label}})}return Q}var Zv={retellAgent:{agentField:"agent_id",agentMessageKey:"editor:validation.voiceAgentAgentRequired"},vapiAgent:{agentField:"assistant_id",agentMessageKey:"editor:validation.voiceAgentAssistantRequired"},elevenlabsAgent:{agentField:"agent_id",agentMessageKey:"editor:validation.voiceAgentAgentRequired"}};function Bv($){let U=[];for(let K of $){let q=Zv[K.type];if(q===void 0)continue;let Q=K.config.connector_id;if(typeof Q!=="string"||Q==="")U.push({nodeId:K.id,severity:"error",messageKey:"editor:validation.voiceAgentConnectorRequired",params:{label:K.label}});let W=K.config[q.agentField];if(typeof W!=="string"||W==="")U.push({nodeId:K.id,severity:"error",messageKey:q.agentMessageKey,params:{label:K.label}})}return U}function Vv($,U,K){let q=new Map(U.map((Q)=>[Q.id,Q.type]));return $.filter((Q)=>{let W=Q.params?.field;if(W==null||Q.nodeId==="")return!0;let J=q.get(Q.nodeId);if(J==null)return!0;let j=K[Q.nodeId];if(j==null||j==="converged"||j==="unreachable")return!0;let Y=W.split(".")[0];if(j==="chat-only"&&WB[J]?.has(Y))return!1;if(j==="voice-only"&&JB[J]?.has(Y))return!1;return!0})}function PJ($){return $.every((U)=>U.severity!=="error")}var Pv=G.object({type:G.literal("message"),message:wW}),Nv=G.object({type:G.literal("typing")}),Lv=G.object({type:G.literal("ping")}),_v=G.object({type:G.literal("resume"),lastSeq:G.number().int().min(0)}),Iv=G.object({type:G.literal("start")}),Fv=G.discriminatedUnion("type",[Pv,Nv,Lv,_v,Iv]),GB=G.object({type:G.literal("connected"),seq:G.number().int(),ts:G.number(),sessionId:G.string()}),jB=G.object({type:G.literal("message"),seq:G.number().int(),ts:G.number(),id:G.string(),message:N6}),YB=G.object({type:G.literal("typing"),seq:G.number().int(),ts:G.number(),active:G.boolean()}),HB=G.object({type:G.literal("state"),seq:G.number().int(),ts:G.number(),status:G.enum(["active","waiting_input","ended"])}),XB=G.object({type:G.literal("trace"),seq:G.number().int(),ts:G.number(),currentNodeId:G.string(),variables:G.record(G.string(),G.string()),status:G.enum(["active","waiting_input","ended"]),truncated:G.boolean(),step:n8.optional()}),ZB=G.object({type:G.literal("error"),seq:G.number().int(),ts:G.number(),code:G.string(),message:G.string()}),BB=G.object({type:G.literal("pong"),seq:G.number().int(),ts:G.number()}),xv=G.discriminatedUnion("type",[GB,jB,YB,HB,XB,ZB,BB]),wv=G.object({type:G.literal("replay"),seq:G.number().int(),ts:G.number(),messages:G.array(xv)}),Av=G.discriminatedUnion("type",[GB,jB,YB,HB,XB,ZB,BB,wv]);var p8=G.templateLiteral([G.literal(m.signals),G.literal("_"),G.string()]),vv=G.templateLiteral([G.literal(m.visual_plans),G.literal("_"),G.string()]),kv=["volume","answered","busy","no_answer","failed","outcome","duration","ai_cost","flow_errors"],Rv=["answered","busy","no_answer","failed"],zv=["number","trend","compare","distribution","weekday_hour"],bv=["plan_version","plan","hour_of_day","weekday","channel"];var $n=G.union([G.literal(1),G.literal(2),G.literal(3),G.literal(4)]).describe("Pinned-card column span (1-4). Null means the default for the query shape.");var Ov=["today","yesterday","last_7_days","last_30_days","this_month","last_month"],Tv=["voice","chat"],Sv=G.union([G.object({preset:G.enum(Ov)}),G.object({date_from:G.string(),date_to:G.string()}),G.object({last_days:G.number().int().min(1).max(366)})]),Cv=G.discriminatedUnion("kind",[G.object({kind:G.literal("calls"),measure:G.enum(kv),value:G.enum(Rv).optional()}),G.object({kind:G.literal("signal"),signal_id:p8,value:G.string().optional()})]),Ev=G.union([G.enum(bv),G.object({signal_id:p8})]),yv=G.object({subject:Cv,shape:G.enum(zv),compare_by:Ev.optional(),period:Sv,channel:G.enum(Tv).optional(),plan_id:vv.optional()}),gv=G.object({id:p8,name:G.string(),question:G.string(),kind:G.enum(["yes_no","choice","scale"]),options:G.array(G.object({key:G.string(),label:G.string()})).optional(),levels:G.array(G.string()).optional(),higher_is:G.enum(w0).optional()}),Un=G.object({org_id:G.string(),signals:G.array(gv)}),k0=G.object({answered:G.number().int(),no_answer:G.number().int().nullable(),not_evaluated:G.number().int().nullable()}),uv=G.object({shape:G.literal("number"),value:G.number(),n:G.number().int(),dist:G.array(G.object({key:G.string(),label:G.string(),value:G.number()})).optional(),rate:G.number().nullable(),low:G.number().nullable(),high:G.number().nullable(),previous:G.object({value:G.number(),rate:G.number().nullable(),low:G.number().nullable(),high:G.number().nullable()}).nullable(),change:G.enum(["up","down","stable"]).nullable(),denominator:k0}),MB=G.object({bucket:G.string(),value:G.number(),n:G.number().int(),low:G.number().nullable(),high:G.number().nullable(),small:G.boolean()}),fv=G.object({date:G.string(),label:G.string()}),mv=G.object({key:G.string(),label:G.string(),points:G.array(MB)}),hv=G.object({shape:G.literal("trend"),granularity:G.enum(["day","hour"]),points:G.array(MB),series:G.array(mv).optional(),plan_versions:G.array(fv),denominator:k0}),cv=G.object({key:G.string(),label:G.string().nullable(),version:G.number().int().nullable().optional(),value:G.number(),n:G.number().int(),low:G.number().nullable(),high:G.number().nullable(),small:G.boolean(),dist:G.array(G.object({key:G.string(),label:G.string(),value:G.number()})).optional()}),lv=G.object({shape:G.literal("compare"),rows:G.array(cv),denominator:k0}),rv=G.object({key:G.string(),label:G.string(),value:G.number(),n:G.number().int()}),iv=G.object({shape:G.literal("distribution"),rows:G.array(rv),denominator:k0}),dv=G.object({weekday:G.number().int(),hour:G.number().int(),value:G.number(),n:G.number().int(),low:G.number().nullable(),high:G.number().nullable()}),ov=G.object({shape:G.literal("weekday_hour"),cells:G.array(dv),denominator:k0}),Qn=G.discriminatedUnion("shape",[uv,hv,lv,iv,ov]),VB=G.object({rate:G.number(),low:G.number(),high:G.number()}),nv=G.object({signal_id:p8,kind:G.enum(["yes_no","choice","scale"]),name:G.string(),question:G.string(),alert_label:G.string().nullable(),alert_below:G.boolean(),higher_is:G.enum(w0).nullable(),n:G.number().int(),value:G.number().nullable(),rate:G.number().nullable(),low:G.number().nullable(),high:G.number().nullable(),distribution:G.array(G.object({key:G.string(),label:G.string(),value:G.number()})),series:G.array(G.object({bucket:G.string(),value:G.number(),n:G.number().int()})),alert_share:VB.nullable(),previous_share:VB.nullable(),in_alert:G.boolean()}),Kn=G.object({cards:G.array(nv)}),pv=G.object({strategy:G.string(),model:G.string(),ms:G.number(),input_tokens:G.number(),output_tokens:G.number()}),qn=G.object({query:yv.nullable(),confidence:G.number(),period_explicit:G.boolean(),meta:pv});var r$=N1(I1(),1);var tv=new Set(x0);function av($){return tv.has($)}var t8=($)=>$==="online"?r$.default.green($):r$.default.red($);function sv($){let U;if($.is_expired)U=r$.default.red("expired");else if($.is_in_grace_period)U=r$.default.yellow("grace period");else U=r$.default.green($.status);let K=$.days_until_expiry!=null?` (${$.days_until_expiry}d remaining)`:"";return` License: ${U}${K}`}var DB=10,ev="unlimited".padEnd(DB);function a8($,U,K,q,Q){let W=` ${$.padEnd(11)}`;if(K==null)return`${W}${r$.default.dim(ev)} ${U}${q}`;return`${W}${a1(U,K,DB)} ${U}/${K}${q} (${Math.round(Q)}%)`}function $k($){let U=[r$.default.bold(" AI Usage:")],{stt:K,tts:q,llm:Q}=$;if(K)U.push(a8("STT:",Math.round(K.current),K.limit," min",K.percentage));if(q)U.push(a8("TTS:",q.current,q.limit," chars",q.percentage));if(Q)U.push(a8("LLM:",Q.current,Q.limit," tokens",Q.percentage));return U}function PB($,U){let K=$.command("fs").description("FreeSWITCH status and debug");K.command("status").description("Check system health (server, DB, Redis, FreeSWITCH)").action(async()=>{let{format:q,fields:Q}=L($.opts()),W=await N(U().dashboard.health());if(q==="json"){let J=Q?O(W,Q):W;P(J);return}if(console.log(`Server: ${t8(W.server)}`),console.log(`PostgreSQL: ${t8(W.postgres)}`),console.log(`Redis: ${t8(W.redis)}`),console.log(`FreeSWITCH: ${t8(W.freeswitch.status)}`),W.freeswitch.uptime!=null&&W.freeswitch.uptime!=="")console.log(` Uptime: ${W.freeswitch.uptime}`);if(W.freeswitch.sessions)console.log(` Sessions: ${W.freeswitch.sessions.active}/${W.freeswitch.sessions.limit}`);if(W.freeswitch.cps)console.log(` CPS: ${W.freeswitch.cps.current}/${W.freeswitch.cps.limit}`);if(W.freeswitch.idleCpu!=null)console.log(` Idle CPU: ${W.freeswitch.idleCpu}%`)}),K.command("channels").description("List active FreeSWITCH channels").action(async()=>{let{format:q,fields:Q}=L($.opts()),W=await N(U().dashboard.activeCalls());if(q==="json"){let J=Q?W.map((j)=>O(j,Q)):W;P(J);return}if(W.length===0){z("No active channels.");return}y(["UUID","Caller","Plan","Node","Duration"],W.map((J)=>({UUID:J.uuid,Caller:J.callerId,Plan:J.planName??"—",Node:J.currentNodeLabel??"—",Duration:J.startedAt?`${Math.round((Date.now()-new Date(J.startedAt).getTime())/1000)}s`:"—"}))),z(`${W.length} active channel(s)`)}),K.command("registrations").description("List SIP registrations").action(async()=>{let{format:q,fields:Q}=L($.opts()),W=await N(U().testCall.registrations());if(q==="json"){let J=Q?W.map((j)=>O(j,Q)):W;P(J);return}if(W.length===0){z("No SIP registrations.");return}y(["Extension","Agent"],W.map((J)=>({Extension:J.extension,Agent:J.agent??"—"})))}),K.command("dump <uuid>").description("Dump all channel variables for an active call").action(async(q)=>{let{format:Q}=L($.opts()),W=await N(U().dashboard.fsDumpChannel({uuid:q}));if(Object.keys(W).length===0){if(Q==="json")P({});else x(`Channel ${q} not found.`);process.exit(w.NOT_FOUND)}if(Q==="json"){P(W);return}console.log(r$.default.bold(`Channel Variables — ${q}`)),console.log("");for(let[J,j]of Object.entries(W))console.log(` ${r$.default.cyan(J.padEnd(40))} ${j}`)}),K.command("sofia").description("Show SIP profile status").action(async()=>{let{format:q}=L($.opts()),Q=await N(U().dashboard.fsSofiaStatus());if(q==="json"){P(Q);return}if(Q.length===0){z("No Sofia profiles configured.");return}console.log(r$.default.bold("Sofia SIP Profiles")),console.log(""),y(["Name","Type","Data","State"],Q.map((W)=>({Name:W.name,Type:W.type,Data:W.data,State:W.state})))}),K.command("show <entity>").description(`Show FreeSWITCH data (${x0.join(", ")})`).action(async(q)=>{if(!av(q))x(`Unknown entity "${q}". Allowed: ${x0.join(", ")}`),process.exit(w.USAGE_ERROR);let{format:Q}=L($.opts()),W=await N(U().dashboard.fsShow({entity:q}));if(Q==="json"){P(W);return}console.log(r$.default.bold(`FreeSWITCH: show ${q}`)),console.log(""),console.log(JSON.stringify(W,null,2))}),K.command("capacity").description("Show system capacity: channels, license, AI usage").action(async()=>{let{format:q,fields:Q}=L($.opts()),W=await N(U().dashboard.capacityStatus());if(q==="json"){let j=Q?O(W,Q):W;P(j);return}console.log(r$.default.bold("System Capacity")),console.log("");let J=W.channels.total;if(console.log(a8("Channels:",J.active,J.limit,"",J.percentage??0)),console.log(sv(W.license)),W.ai_usage){console.log("");for(let j of $k(W.ai_usage))console.log(j)}})}function Uk(){return Object.entries(m).map(([$,U])=>`${$} (${U}_)`).sort(($,U)=>$.localeCompare(U))}function Qk($){return Object.hasOwn(m,$)}function NB($){x($),z(" Valid entities:");for(let U of Uk())z(` ${U}`);process.exit(w.USAGE_ERROR)}function LB($,U,K){return{input:$,entity:U,prefix:m[U],typeid:u0(U,K),uuid:K,sql:`'${K}'::uuid`}}function Kk($,U){if(U!=null&&!Qk(U))NB(`Unknown entity "${U}".`);let K=$4($);if(K.kind==="typeid"){if(U!=null&&U!==K.entity)x(`"${$}" is a ${K.entity} id, but --as says ${U}.`),z(" Drop --as: a TypeID already carries its entity."),process.exit(w.USAGE_ERROR);return LB($,K.entity,K.uuid)}if(K.kind==="uuid"){if(U==null)NB(`"${$}" is a UUID, which does not carry an entity - pass --as <entity>.`);return LB($,U,K.uuid)}x(`Cannot read "${$}" as an id: ${qk[K.reason]}.`),z(" A TypeID looks like vp_01k3vbk6hxe008000000000001; a UUID like 0198f6b9-9a3d-7000-8000-000000000001."),process.exit(w.USAGE_ERROR)}var qk={"unknown-prefix":"its prefix belongs to no known entity","malformed-suffix":"the part after the prefix is not a valid TypeID body","not-an-id":"it is neither a UUID nor a prefixed TypeID"};function _B($){$.command("id <value>").description("Convert between a TypeID and a raw UUID (local, no server call)").option("--as <entity>","Entity a raw UUID belongs to (required when converting a UUID)").option("--sql","Print only the UUID as a psql literal, ready to paste into a query").action((U,K)=>{let{format:q,fields:Q}=L($.opts()),W=Kk(U,K.as);if(K.sql===!0){console.log(W.sql);return}if(q==="json"){P(O(W,Q));return}o([{title:"Id",rows:[{label:"TypeID",value:W.typeid},{label:"UUID",value:W.uuid},{label:"Entity",value:W.entity},{label:"Prefix",value:W.prefix}]}])})}import{existsSync as wB,lstatSync as AB,mkdirSync as Zk,readFileSync as vB,realpathSync as FB,rmSync as Bk,statSync as Vk,writeFileSync as xB}from"node:fs";import{homedir as Mk}from"node:os";import{dirname as Dk,isAbsolute as kB,join as d1,relative as Pk}from"node:path";import{readdirSync as Wk,readFileSync as Jk}from"node:fs";import{join as Gk,relative as jk}from"node:path";import{fileURLToPath as Yk}from"node:url";var A4="SKILL.md";function Hk($,U){if($===U)return 0;return $<U?-1:1}function Xk($){let U={},K=Wk($,{recursive:!0,withFileTypes:!0});for(let q of K){if(!q.isFile()||q.name.startsWith("."))continue;let Q=Gk(q.parentPath,q.name);U[jk($,Q).replaceAll("\\","/")]=Jk(Q,"utf-8")}return Object.fromEntries(Object.entries(U).toSorted(([q],[Q])=>Hk(q,Q)))}function IB(){return{"SKILL.md":`---
|
|
84
|
+
`)}I.write("payload.value = newResult;"),I.write("return payload;");let k4=I.compile();return(i$,C$)=>k4(M,i$,C$)},W,G=X4,j=!g6.jitless,H=j&&WU.value,X=U.catchall,B;$._zod.parse=(M,I)=>{B??(B=q.value);let E=M.value;if(!G(E))return M.issues.push({expected:"object",code:"invalid_type",input:E,inst:$}),M;if(j&&H&&I?.async===!1&&I.jitless!==!0){if(!W)W=Q(U.shape);if(M=W(M,I),!X)return M;return ej([],E,M,I,B,$)}return K(M,I)}});function mj($,U,K,q){for(let W of $)if(W.issues.length===0)return U.value=W.value,U;let Q=$.filter((W)=>!g1(W));if(Q.length===1)return U.value=Q[0].value,Q[0];return U.issues.push({code:"invalid_union",input:U.value,inst:K,errors:$.map((W)=>W.issues.map((G)=>E$(G,q,V$())))}),U}var a6=D("$ZodUnion",($,U)=>{h.init($,U),r($._zod,"optin",()=>U.options.some((Q)=>Q._zod.optin==="optional")?"optional":void 0),r($._zod,"optout",()=>U.options.some((Q)=>Q._zod.optout==="optional")?"optional":void 0),r($._zod,"values",()=>{if(U.options.every((Q)=>Q._zod.values))return new Set(U.options.flatMap((Q)=>Array.from(Q._zod.values)));return}),r($._zod,"pattern",()=>{if(U.options.every((Q)=>Q._zod.pattern)){let Q=U.options.map((W)=>W._zod.pattern);return new RegExp(`^(${Q.map((W)=>m6(W.source)).join("|")})$`)}return});let K=U.options.length===1,q=U.options[0]._zod.run;$._zod.parse=(Q,W)=>{if(K)return q(Q,W);let G=!1,j=[];for(let Y of U.options){let H=Y._zod.run({value:Q.value,issues:[]},W);if(H instanceof Promise)j.push(H),G=!0;else{if(H.issues.length===0)return H;j.push(H)}}if(!G)return mj(j,Q,$,W);return Promise.all(j).then((Y)=>{return mj(Y,Q,$,W)})}});function hj($,U,K,q){let Q=$.filter((W)=>W.issues.length===0);if(Q.length===1)return U.value=Q[0].value,U;if(Q.length===0)U.issues.push({code:"invalid_union",input:U.value,inst:K,errors:$.map((W)=>W.issues.map((G)=>E$(G,q,V$())))});else U.issues.push({code:"invalid_union",input:U.value,inst:K,errors:[],inclusive:!1});return U}var o9=D("$ZodXor",($,U)=>{a6.init($,U),U.inclusive=!1;let K=U.options.length===1,q=U.options[0]._zod.run;$._zod.parse=(Q,W)=>{if(K)return q(Q,W);let G=!1,j=[];for(let Y of U.options){let H=Y._zod.run({value:Q.value,issues:[]},W);if(H instanceof Promise)j.push(H),G=!0;else j.push(H)}if(!G)return hj(j,Q,$,W);return Promise.all(j).then((Y)=>{return hj(Y,Q,$,W)})}}),n9=D("$ZodDiscriminatedUnion",($,U)=>{U.inclusive=!1,a6.init($,U);let K=$._zod.parse;r($._zod,"propValues",()=>{let Q={};for(let W of U.options){let G=W._zod.propValues;if(!G||Object.keys(G).length===0)throw Error(`Invalid discriminated union option at index "${U.options.indexOf(W)}"`);for(let[j,Y]of Object.entries(G)){if(!Q[j])Q[j]=new Set;for(let H of Y)Q[j].add(H)}}return Q});let q=y4(()=>{let Q=U.options,W=new Map;for(let G of Q){let j=G._zod.propValues?.[U.discriminator];if(!j||j.size===0)throw Error(`Invalid discriminated union option at index "${U.options.indexOf(G)}"`);for(let Y of j){if(W.has(Y))throw Error(`Duplicate discriminator value "${String(Y)}"`);W.set(Y,G)}}return W});$._zod.parse=(Q,W)=>{let G=Q.value;if(!X4(G))return Q.issues.push({code:"invalid_type",expected:"object",input:G,inst:$}),Q;let j=q.value.get(G?.[U.discriminator]);if(j)return j._zod.run(Q,W);if(U.unionFallback)return K(Q,W);return Q.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:U.discriminator,input:G,path:[U.discriminator],inst:$}),Q}}),p9=D("$ZodIntersection",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{let Q=K.value,W=U.left._zod.run({value:Q,issues:[]},q),G=U.right._zod.run({value:Q,issues:[]},q);if(W instanceof Promise||G instanceof Promise)return Promise.all([W,G]).then(([Y,H])=>{return cj(K,Y,H)});return cj(K,W,G)}});function j9($,U){if($===U)return{valid:!0,data:$};if($ instanceof Date&&U instanceof Date&&+$===+U)return{valid:!0,data:$};if(y1($)&&y1(U)){let K=Object.keys(U),q=Object.keys($).filter((W)=>K.indexOf(W)!==-1),Q={...$,...U};for(let W of q){let G=j9($[W],U[W]);if(!G.valid)return{valid:!1,mergeErrorPath:[W,...G.mergeErrorPath]};Q[W]=G.data}return{valid:!0,data:Q}}if(Array.isArray($)&&Array.isArray(U)){if($.length!==U.length)return{valid:!1,mergeErrorPath:[]};let K=[];for(let q=0;q<$.length;q++){let Q=$[q],W=U[q],G=j9(Q,W);if(!G.valid)return{valid:!1,mergeErrorPath:[q,...G.mergeErrorPath]};K.push(G.data)}return{valid:!0,data:K}}return{valid:!1,mergeErrorPath:[]}}function cj($,U,K){let q=new Map,Q;for(let j of U.issues)if(j.code==="unrecognized_keys"){Q??(Q=j);for(let Y of j.keys){if(!q.has(Y))q.set(Y,{});q.get(Y).l=!0}}else $.issues.push(j);for(let j of K.issues)if(j.code==="unrecognized_keys")for(let Y of j.keys){if(!q.has(Y))q.set(Y,{});q.get(Y).r=!0}else $.issues.push(j);let W=[...q].filter(([,j])=>j.l&&j.r).map(([j])=>j);if(W.length&&Q)$.issues.push({...Q,keys:W});if(g1($))return $;let G=j9(U.value,K.value);if(!G.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(G.mergeErrorPath)}`);return $.value=G.data,$}var w2=D("$ZodTuple",($,U)=>{h.init($,U);let K=U.items;$._zod.parse=(q,Q)=>{let W=q.value;if(!Array.isArray(W))return q.issues.push({input:W,inst:$,expected:"tuple",code:"invalid_type"}),q;q.value=[];let G=[],j=[...K].reverse().findIndex((X)=>X._zod.optin!=="optional"),Y=j===-1?0:K.length-j;if(!U.rest){let X=W.length>K.length,B=W.length<Y-1;if(X||B)return q.issues.push({...X?{code:"too_big",maximum:K.length,inclusive:!0}:{code:"too_small",minimum:K.length},input:W,inst:$,origin:"array"}),q}let H=-1;for(let X of K){if(H++,H>=W.length){if(H>=Y)continue}let B=X._zod.run({value:W[H],issues:[]},Q);if(B instanceof Promise)G.push(B.then((M)=>P2(M,q,H)));else P2(B,q,H)}if(U.rest){let X=W.slice(K.length);for(let B of X){H++;let M=U.rest._zod.run({value:B,issues:[]},Q);if(M instanceof Promise)G.push(M.then((I)=>P2(I,q,H)));else P2(M,q,H)}}if(G.length)return Promise.all(G).then(()=>q);return q}});function P2($,U,K){if($.issues.length)U.issues.push(...m$(K,$.issues));U.value[K]=$.value}var t9=D("$ZodRecord",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{let Q=K.value;if(!y1(Q))return K.issues.push({expected:"record",code:"invalid_type",input:Q,inst:$}),K;let W=[],G=U.keyType._zod.values;if(G){K.value={};let j=new Set;for(let H of G)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){j.add(typeof H==="number"?H.toString():H);let X=U.valueType._zod.run({value:Q[H],issues:[]},q);if(X instanceof Promise)W.push(X.then((B)=>{if(B.issues.length)K.issues.push(...m$(H,B.issues));K.value[H]=B.value}));else{if(X.issues.length)K.issues.push(...m$(H,X.issues));K.value[H]=X.value}}let Y;for(let H in Q)if(!j.has(H))Y=Y??[],Y.push(H);if(Y&&Y.length>0)K.issues.push({code:"unrecognized_keys",input:Q,inst:$,keys:Y})}else{K.value={};for(let j of Reflect.ownKeys(Q)){if(j==="__proto__")continue;let Y=U.keyType._zod.run({value:j,issues:[]},q);if(Y instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof j==="string"&&o6.test(j)&&Y.issues.length){let B=U.keyType._zod.run({value:Number(j),issues:[]},q);if(B instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(B.issues.length===0)Y=B}if(Y.issues.length){if(U.mode==="loose")K.value[j]=Q[j];else K.issues.push({code:"invalid_key",origin:"record",issues:Y.issues.map((B)=>E$(B,q,V$())),input:j,path:[j],inst:$});continue}let X=U.valueType._zod.run({value:Q[j],issues:[]},q);if(X instanceof Promise)W.push(X.then((B)=>{if(B.issues.length)K.issues.push(...m$(j,B.issues));K.value[Y.value]=B.value}));else{if(X.issues.length)K.issues.push(...m$(j,X.issues));K.value[Y.value]=X.value}}}if(W.length)return Promise.all(W).then(()=>K);return K}}),a9=D("$ZodMap",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{let Q=K.value;if(!(Q instanceof Map))return K.issues.push({expected:"map",code:"invalid_type",input:Q,inst:$}),K;let W=[];K.value=new Map;for(let[G,j]of Q){let Y=U.keyType._zod.run({value:G,issues:[]},q),H=U.valueType._zod.run({value:j,issues:[]},q);if(Y instanceof Promise||H instanceof Promise)W.push(Promise.all([Y,H]).then(([X,B])=>{lj(X,B,K,G,Q,$,q)}));else lj(Y,H,K,G,Q,$,q)}if(W.length)return Promise.all(W).then(()=>K);return K}});function lj($,U,K,q,Q,W,G){if($.issues.length)if(h6.has(typeof q))K.issues.push(...m$(q,$.issues));else K.issues.push({code:"invalid_key",origin:"map",input:Q,inst:W,issues:$.issues.map((j)=>E$(j,G,V$()))});if(U.issues.length)if(h6.has(typeof q))K.issues.push(...m$(q,U.issues));else K.issues.push({origin:"map",code:"invalid_element",input:Q,inst:W,key:q,issues:U.issues.map((j)=>E$(j,G,V$()))});K.value.set($.value,U.value)}var s9=D("$ZodSet",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{let Q=K.value;if(!(Q instanceof Set))return K.issues.push({input:Q,inst:$,expected:"set",code:"invalid_type"}),K;let W=[];K.value=new Set;for(let G of Q){let j=U.valueType._zod.run({value:G,issues:[]},q);if(j instanceof Promise)W.push(j.then((Y)=>rj(Y,K)));else rj(j,K)}if(W.length)return Promise.all(W).then(()=>K);return K}});function rj($,U){if($.issues.length)U.issues.push(...$.issues);U.value.add($.value)}var e9=D("$ZodEnum",($,U)=>{h.init($,U);let K=f6(U.entries),q=new Set(K);$._zod.values=q,$._zod.pattern=new RegExp(`^(${K.filter((Q)=>h6.has(typeof Q)).map((Q)=>typeof Q==="string"?o$(Q):Q.toString()).join("|")})$`),$._zod.parse=(Q,W)=>{let G=Q.value;if(q.has(G))return Q;return Q.issues.push({code:"invalid_value",values:K,input:G,inst:$}),Q}}),$7=D("$ZodLiteral",($,U)=>{if(h.init($,U),U.values.length===0)throw Error("Cannot create literal schema with no valid values");let K=new Set(U.values);$._zod.values=K,$._zod.pattern=new RegExp(`^(${U.values.map((q)=>typeof q==="string"?o$(q):q?o$(q.toString()):String(q)).join("|")})$`),$._zod.parse=(q,Q)=>{let W=q.value;if(K.has(W))return q;return q.issues.push({code:"invalid_value",values:U.values,input:W,inst:$}),q}}),U7=D("$ZodFile",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{let Q=K.value;if(Q instanceof File)return K;return K.issues.push({expected:"file",code:"invalid_type",input:Q,inst:$}),K}}),Q7=D("$ZodTransform",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{if(q.direction==="backward")throw new H4($.constructor.name);let Q=U.transform(K.value,K);if(q.async)return(Q instanceof Promise?Q:Promise.resolve(Q)).then((G)=>{return K.value=G,K});if(Q instanceof Promise)throw new H1;return K.value=Q,K}});function ij($,U){if($.issues.length&&U===void 0)return{issues:[],value:void 0};return $}var A2=D("$ZodOptional",($,U)=>{h.init($,U),$._zod.optin="optional",$._zod.optout="optional",r($._zod,"values",()=>{return U.innerType._zod.values?new Set([...U.innerType._zod.values,void 0]):void 0}),r($._zod,"pattern",()=>{let K=U.innerType._zod.pattern;return K?new RegExp(`^(${m6(K.source)})?$`):void 0}),$._zod.parse=(K,q)=>{if(U.innerType._zod.optin==="optional"){let Q=U.innerType._zod.run(K,q);if(Q instanceof Promise)return Q.then((W)=>ij(W,K.value));return ij(Q,K.value)}if(K.value===void 0)return K;return U.innerType._zod.run(K,q)}}),K7=D("$ZodExactOptional",($,U)=>{A2.init($,U),r($._zod,"values",()=>U.innerType._zod.values),r($._zod,"pattern",()=>U.innerType._zod.pattern),$._zod.parse=(K,q)=>{return U.innerType._zod.run(K,q)}}),q7=D("$ZodNullable",($,U)=>{h.init($,U),r($._zod,"optin",()=>U.innerType._zod.optin),r($._zod,"optout",()=>U.innerType._zod.optout),r($._zod,"pattern",()=>{let K=U.innerType._zod.pattern;return K?new RegExp(`^(${m6(K.source)}|null)$`):void 0}),r($._zod,"values",()=>{return U.innerType._zod.values?new Set([...U.innerType._zod.values,null]):void 0}),$._zod.parse=(K,q)=>{if(K.value===null)return K;return U.innerType._zod.run(K,q)}}),W7=D("$ZodDefault",($,U)=>{h.init($,U),$._zod.optin="optional",r($._zod,"values",()=>U.innerType._zod.values),$._zod.parse=(K,q)=>{if(q.direction==="backward")return U.innerType._zod.run(K,q);if(K.value===void 0)return K.value=U.defaultValue,K;let Q=U.innerType._zod.run(K,q);if(Q instanceof Promise)return Q.then((W)=>dj(W,U));return dj(Q,U)}});function dj($,U){if($.value===void 0)$.value=U.defaultValue;return $}var G7=D("$ZodPrefault",($,U)=>{h.init($,U),$._zod.optin="optional",r($._zod,"values",()=>U.innerType._zod.values),$._zod.parse=(K,q)=>{if(q.direction==="backward")return U.innerType._zod.run(K,q);if(K.value===void 0)K.value=U.defaultValue;return U.innerType._zod.run(K,q)}}),J7=D("$ZodNonOptional",($,U)=>{h.init($,U),r($._zod,"values",()=>{let K=U.innerType._zod.values;return K?new Set([...K].filter((q)=>q!==void 0)):void 0}),$._zod.parse=(K,q)=>{let Q=U.innerType._zod.run(K,q);if(Q instanceof Promise)return Q.then((W)=>oj(W,$));return oj(Q,$)}});function oj($,U){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:U});return $}var j7=D("$ZodSuccess",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{if(q.direction==="backward")throw new H4("ZodSuccess");let Q=U.innerType._zod.run(K,q);if(Q instanceof Promise)return Q.then((W)=>{return K.value=W.issues.length===0,K});return K.value=Q.issues.length===0,K}}),Y7=D("$ZodCatch",($,U)=>{h.init($,U),r($._zod,"optin",()=>U.innerType._zod.optin),r($._zod,"optout",()=>U.innerType._zod.optout),r($._zod,"values",()=>U.innerType._zod.values),$._zod.parse=(K,q)=>{if(q.direction==="backward")return U.innerType._zod.run(K,q);let Q=U.innerType._zod.run(K,q);if(Q instanceof Promise)return Q.then((W)=>{if(K.value=W.value,W.issues.length)K.value=U.catchValue({...K,error:{issues:W.issues.map((G)=>E$(G,q,V$()))},input:K.value}),K.issues=[];return K});if(K.value=Q.value,Q.issues.length)K.value=U.catchValue({...K,error:{issues:Q.issues.map((W)=>E$(W,q,V$()))},input:K.value}),K.issues=[];return K}}),H7=D("$ZodNaN",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{if(typeof K.value!=="number"||!Number.isNaN(K.value))return K.issues.push({input:K.value,inst:$,expected:"nan",code:"invalid_type"}),K;return K}}),X7=D("$ZodPipe",($,U)=>{h.init($,U),r($._zod,"values",()=>U.in._zod.values),r($._zod,"optin",()=>U.in._zod.optin),r($._zod,"optout",()=>U.out._zod.optout),r($._zod,"propValues",()=>U.in._zod.propValues),$._zod.parse=(K,q)=>{if(q.direction==="backward"){let W=U.out._zod.run(K,q);if(W instanceof Promise)return W.then((G)=>N2(G,U.in,q));return N2(W,U.in,q)}let Q=U.in._zod.run(K,q);if(Q instanceof Promise)return Q.then((W)=>N2(W,U.out,q));return N2(Q,U.out,q)}});function N2($,U,K){if($.issues.length)return $.aborted=!0,$;return U._zod.run({value:$.value,issues:$.issues},K)}var s6=D("$ZodCodec",($,U)=>{h.init($,U),r($._zod,"values",()=>U.in._zod.values),r($._zod,"optin",()=>U.in._zod.optin),r($._zod,"optout",()=>U.out._zod.optout),r($._zod,"propValues",()=>U.in._zod.propValues),$._zod.parse=(K,q)=>{if((q.direction||"forward")==="forward"){let W=U.in._zod.run(K,q);if(W instanceof Promise)return W.then((G)=>L2(G,U,q));return L2(W,U,q)}else{let W=U.out._zod.run(K,q);if(W instanceof Promise)return W.then((G)=>L2(G,U,q));return L2(W,U,q)}}});function L2($,U,K){if($.issues.length)return $.aborted=!0,$;if((K.direction||"forward")==="forward"){let Q=U.transform($.value,$);if(Q instanceof Promise)return Q.then((W)=>_2($,W,U.out,K));return _2($,Q,U.out,K)}else{let Q=U.reverseTransform($.value,$);if(Q instanceof Promise)return Q.then((W)=>_2($,W,U.in,K));return _2($,Q,U.in,K)}}function _2($,U,K,q){if($.issues.length)return $.aborted=!0,$;return K._zod.run({value:U,issues:$.issues},q)}var Z7=D("$ZodReadonly",($,U)=>{h.init($,U),r($._zod,"propValues",()=>U.innerType._zod.propValues),r($._zod,"values",()=>U.innerType._zod.values),r($._zod,"optin",()=>U.innerType?._zod?.optin),r($._zod,"optout",()=>U.innerType?._zod?.optout),$._zod.parse=(K,q)=>{if(q.direction==="backward")return U.innerType._zod.run(K,q);let Q=U.innerType._zod.run(K,q);if(Q instanceof Promise)return Q.then(nj);return nj(Q)}});function nj($){return $.value=Object.freeze($.value),$}var B7=D("$ZodTemplateLiteral",($,U)=>{h.init($,U);let K=[];for(let q of U.parts)if(typeof q==="object"&&q!==null){if(!q._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...q._zod.traits].shift()}`);let Q=q._zod.pattern instanceof RegExp?q._zod.pattern.source:q._zod.pattern;if(!Q)throw Error(`Invalid template literal part: ${q._zod.traits}`);let W=Q.startsWith("^")?1:0,G=Q.endsWith("$")?Q.length-1:Q.length;K.push(Q.slice(W,G))}else if(q===null||JU.has(typeof q))K.push(o$(`${q}`));else throw Error(`Invalid template literal part: ${q}`);$._zod.pattern=new RegExp(`^${K.join("")}$`),$._zod.parse=(q,Q)=>{if(typeof q.value!=="string")return q.issues.push({input:q.value,inst:$,expected:"string",code:"invalid_type"}),q;if($._zod.pattern.lastIndex=0,!$._zod.pattern.test(q.value))return q.issues.push({input:q.value,inst:$,code:"invalid_format",format:U.format??"template_literal",pattern:$._zod.pattern.source}),q;return q}}),V7=D("$ZodFunction",($,U)=>{return h.init($,U),$._def=U,$._zod.def=U,$.implement=(K)=>{if(typeof K!=="function")throw Error("implement() must be called with a function");return function(...q){let Q=$._def.input?K2($._def.input,q):q,W=Reflect.apply(K,this,Q);if($._def.output)return K2($._def.output,W);return W}},$.implementAsync=(K)=>{if(typeof K!=="function")throw Error("implementAsync() must be called with a function");return async function(...q){let Q=$._def.input?await q2($._def.input,q):q,W=await Reflect.apply(K,this,Q);if($._def.output)return await q2($._def.output,W);return W}},$._zod.parse=(K,q)=>{if(typeof K.value!=="function")return K.issues.push({code:"invalid_type",expected:"function",input:K.value,inst:$}),K;if($._def.output&&$._def.output._zod.def.type==="promise")K.value=$.implementAsync(K.value);else K.value=$.implement(K.value);return K},$.input=(...K)=>{let q=$.constructor;if(Array.isArray(K[0]))return new q({type:"function",input:new w2({type:"tuple",items:K[0],rest:K[1]}),output:$._def.output});return new q({type:"function",input:K[0],output:$._def.output})},$.output=(K)=>{return new $.constructor({type:"function",input:$._def.input,output:K})},$}),M7=D("$ZodPromise",($,U)=>{h.init($,U),$._zod.parse=(K,q)=>{return Promise.resolve(K.value).then((Q)=>U.innerType._zod.run({value:Q,issues:[]},q))}}),D7=D("$ZodLazy",($,U)=>{h.init($,U),r($._zod,"innerType",()=>U.getter()),r($._zod,"pattern",()=>$._zod.innerType?._zod?.pattern),r($._zod,"propValues",()=>$._zod.innerType?._zod?.propValues),r($._zod,"optin",()=>$._zod.innerType?._zod?.optin??void 0),r($._zod,"optout",()=>$._zod.innerType?._zod?.optout??void 0),$._zod.parse=(K,q)=>{return $._zod.innerType._zod.run(K,q)}}),P7=D("$ZodCustom",($,U)=>{$$.init($,U),h.init($,U),$._zod.parse=(K,q)=>{return K},$._zod.check=(K)=>{let q=K.value,Q=U.fn(q);if(Q instanceof Promise)return Q.then((W)=>pj(W,K,q,$));pj(Q,K,q,$);return}});function pj($,U,K,q){if(!$){let Q={code:"custom",input:K,inst:q,path:[...q._zod.def.path??[]],continue:!q._zod.def.abort};if(q._zod.def.params)Q.params=q._zod.def.params;U.issues.push(g4(Q))}}var K0={};L1(K0,{zhTW:()=>j5,zhCN:()=>J5,yo:()=>Y5,vi:()=>G5,uz:()=>W5,ur:()=>q5,uk:()=>Q0,ua:()=>K5,tr:()=>Q5,th:()=>U5,ta:()=>$5,sv:()=>e7,sl:()=>s7,ru:()=>a7,pt:()=>t7,ps:()=>n7,pl:()=>p7,ota:()=>o7,no:()=>d7,nl:()=>i7,ms:()=>r7,mk:()=>l7,lt:()=>c7,ko:()=>h7,km:()=>$0,kh:()=>m7,ka:()=>f7,ja:()=>u7,it:()=>g7,is:()=>y7,id:()=>E7,hy:()=>C7,hu:()=>S7,he:()=>T7,frCA:()=>O7,fr:()=>b7,fi:()=>R7,fa:()=>z7,es:()=>k7,eo:()=>v7,en:()=>e6,de:()=>A7,da:()=>w7,cs:()=>x7,ca:()=>F7,bg:()=>I7,be:()=>_7,az:()=>L7,ar:()=>N7});var OL=()=>{let $={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function U(Q){return $[Q]??null}let K={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"},q={nan:"NaN"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`مدخلات غير مقبولة: يفترض إدخال instanceof ${Q.expected}، ولكن تم إدخال ${j}`;return`مدخلات غير مقبولة: يفترض إدخال ${W}، ولكن تم إدخال ${j}`}case"invalid_value":if(Q.values.length===1)return`مدخلات غير مقبولة: يفترض إدخال ${v(Q.values[0])}`;return`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return` أكبر من اللازم: يفترض أن تكون ${Q.origin??"القيمة"} ${W} ${Q.maximum.toString()} ${G.unit??"عنصر"}`;return`أكبر من اللازم: يفترض أن تكون ${Q.origin??"القيمة"} ${W} ${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`أصغر من اللازم: يفترض لـ ${Q.origin} أن يكون ${W} ${Q.minimum.toString()} ${G.unit}`;return`أصغر من اللازم: يفترض لـ ${Q.origin} أن يكون ${W} ${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`نَص غير مقبول: يجب أن يبدأ بـ "${Q.prefix}"`;if(W.format==="ends_with")return`نَص غير مقبول: يجب أن ينتهي بـ "${W.suffix}"`;if(W.format==="includes")return`نَص غير مقبول: يجب أن يتضمَّن "${W.includes}"`;if(W.format==="regex")return`نَص غير مقبول: يجب أن يطابق النمط ${W.pattern}`;return`${K[W.format]??Q.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${Q.divisor}`;case"unrecognized_keys":return`معرف${Q.keys.length>1?"ات":""} غريب${Q.keys.length>1?"ة":""}: ${_(Q.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${Q.origin}`;case"invalid_union":return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${Q.origin}`;default:return"مدخل غير مقبول"}}};function N7(){return{localeError:OL()}}var TL=()=>{let $={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}};function U(Q){return $[Q]??null}let K={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},q={nan:"NaN"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Yanlış dəyər: gözlənilən instanceof ${Q.expected}, daxil olan ${j}`;return`Yanlış dəyər: gözlənilən ${W}, daxil olan ${j}`}case"invalid_value":if(Q.values.length===1)return`Yanlış dəyər: gözlənilən ${v(Q.values[0])}`;return`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Çox böyük: gözlənilən ${Q.origin??"dəyər"} ${W}${Q.maximum.toString()} ${G.unit??"element"}`;return`Çox böyük: gözlənilən ${Q.origin??"dəyər"} ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Çox kiçik: gözlənilən ${Q.origin} ${W}${Q.minimum.toString()} ${G.unit}`;return`Çox kiçik: gözlənilən ${Q.origin} ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Yanlış mətn: "${W.prefix}" ilə başlamalıdır`;if(W.format==="ends_with")return`Yanlış mətn: "${W.suffix}" ilə bitməlidir`;if(W.format==="includes")return`Yanlış mətn: "${W.includes}" daxil olmalıdır`;if(W.format==="regex")return`Yanlış mətn: ${W.pattern} şablonuna uyğun olmalıdır`;return`Yanlış ${K[W.format]??Q.format}`}case"not_multiple_of":return`Yanlış ədəd: ${Q.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${Q.keys.length>1?"lar":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`${Q.origin} daxilində yanlış açar`;case"invalid_union":return"Yanlış dəyər";case"invalid_element":return`${Q.origin} daxilində yanlış dəyər`;default:return"Yanlış dəyər"}}};function L7(){return{localeError:TL()}}function UY($,U,K,q){let Q=Math.abs($),W=Q%10,G=Q%100;if(G>=11&&G<=19)return q;if(W===1)return U;if(W>=2&&W<=4)return K;return q}var SL=()=>{let $={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function U(Q){return $[Q]??null}let K={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"},q={nan:"NaN",number:"лік",array:"масіў"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Няправільны ўвод: чакаўся instanceof ${Q.expected}, атрымана ${j}`;return`Няправільны ўвод: чакаўся ${W}, атрымана ${j}`}case"invalid_value":if(Q.values.length===1)return`Няправільны ўвод: чакалася ${v(Q.values[0])}`;return`Няправільны варыянт: чакаўся адзін з ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G){let j=Number(Q.maximum),Y=UY(j,G.unit.one,G.unit.few,G.unit.many);return`Занадта вялікі: чакалася, што ${Q.origin??"значэнне"} павінна ${G.verb} ${W}${Q.maximum.toString()} ${Y}`}return`Занадта вялікі: чакалася, што ${Q.origin??"значэнне"} павінна быць ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G){let j=Number(Q.minimum),Y=UY(j,G.unit.one,G.unit.few,G.unit.many);return`Занадта малы: чакалася, што ${Q.origin} павінна ${G.verb} ${W}${Q.minimum.toString()} ${Y}`}return`Занадта малы: чакалася, што ${Q.origin} павінна быць ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Няправільны радок: павінен пачынацца з "${W.prefix}"`;if(W.format==="ends_with")return`Няправільны радок: павінен заканчвацца на "${W.suffix}"`;if(W.format==="includes")return`Няправільны радок: павінен змяшчаць "${W.includes}"`;if(W.format==="regex")return`Няправільны радок: павінен адпавядаць шаблону ${W.pattern}`;return`Няправільны ${K[W.format]??Q.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${Q.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${Q.keys.length>1?"ключы":"ключ"}: ${_(Q.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${Q.origin}`;case"invalid_union":return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${Q.origin}`;default:return"Няправільны ўвод"}}};function _7(){return{localeError:SL()}}var CL=()=>{let $={string:{unit:"символа",verb:"да съдържа"},file:{unit:"байта",verb:"да съдържа"},array:{unit:"елемента",verb:"да съдържа"},set:{unit:"елемента",verb:"да съдържа"}};function U(Q){return $[Q]??null}let K={regex:"вход",email:"имейл адрес",url:"URL",emoji:"емоджи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO време",date:"ISO дата",time:"ISO време",duration:"ISO продължителност",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"base64-кодиран низ",base64url:"base64url-кодиран низ",json_string:"JSON низ",e164:"E.164 номер",jwt:"JWT",template_literal:"вход"},q={nan:"NaN",number:"число",array:"масив"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Невалиден вход: очакван instanceof ${Q.expected}, получен ${j}`;return`Невалиден вход: очакван ${W}, получен ${j}`}case"invalid_value":if(Q.values.length===1)return`Невалиден вход: очакван ${v(Q.values[0])}`;return`Невалидна опция: очаквано едно от ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Твърде голямо: очаква се ${Q.origin??"стойност"} да съдържа ${W}${Q.maximum.toString()} ${G.unit??"елемента"}`;return`Твърде голямо: очаква се ${Q.origin??"стойност"} да бъде ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Твърде малко: очаква се ${Q.origin} да съдържа ${W}${Q.minimum.toString()} ${G.unit}`;return`Твърде малко: очаква се ${Q.origin} да бъде ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Невалиден низ: трябва да започва с "${W.prefix}"`;if(W.format==="ends_with")return`Невалиден низ: трябва да завършва с "${W.suffix}"`;if(W.format==="includes")return`Невалиден низ: трябва да включва "${W.includes}"`;if(W.format==="regex")return`Невалиден низ: трябва да съвпада с ${W.pattern}`;let G="Невалиден";if(W.format==="emoji")G="Невалидно";if(W.format==="datetime")G="Невалидно";if(W.format==="date")G="Невалидна";if(W.format==="time")G="Невалидно";if(W.format==="duration")G="Невалидна";return`${G} ${K[W.format]??Q.format}`}case"not_multiple_of":return`Невалидно число: трябва да бъде кратно на ${Q.divisor}`;case"unrecognized_keys":return`Неразпознат${Q.keys.length>1?"и":""} ключ${Q.keys.length>1?"ове":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Невалиден ключ в ${Q.origin}`;case"invalid_union":return"Невалиден вход";case"invalid_element":return`Невалидна стойност в ${Q.origin}`;default:return"Невалиден вход"}}};function I7(){return{localeError:CL()}}var EL=()=>{let $={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function U(Q){return $[Q]??null}let K={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},q={nan:"NaN"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Tipus invàlid: s'esperava instanceof ${Q.expected}, s'ha rebut ${j}`;return`Tipus invàlid: s'esperava ${W}, s'ha rebut ${j}`}case"invalid_value":if(Q.values.length===1)return`Valor invàlid: s'esperava ${v(Q.values[0])}`;return`Opció invàlida: s'esperava una de ${_(Q.values," o ")}`;case"too_big":{let W=Q.inclusive?"com a màxim":"menys de",G=U(Q.origin);if(G)return`Massa gran: s'esperava que ${Q.origin??"el valor"} contingués ${W} ${Q.maximum.toString()} ${G.unit??"elements"}`;return`Massa gran: s'esperava que ${Q.origin??"el valor"} fos ${W} ${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?"com a mínim":"més de",G=U(Q.origin);if(G)return`Massa petit: s'esperava que ${Q.origin} contingués ${W} ${Q.minimum.toString()} ${G.unit}`;return`Massa petit: s'esperava que ${Q.origin} fos ${W} ${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Format invàlid: ha de començar amb "${W.prefix}"`;if(W.format==="ends_with")return`Format invàlid: ha d'acabar amb "${W.suffix}"`;if(W.format==="includes")return`Format invàlid: ha d'incloure "${W.includes}"`;if(W.format==="regex")return`Format invàlid: ha de coincidir amb el patró ${W.pattern}`;return`Format invàlid per a ${K[W.format]??Q.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${Q.divisor}`;case"unrecognized_keys":return`Clau${Q.keys.length>1?"s":""} no reconeguda${Q.keys.length>1?"s":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${Q.origin}`;case"invalid_union":return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${Q.origin}`;default:return"Entrada invàlida"}}};function F7(){return{localeError:EL()}}var yL=()=>{let $={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}};function U(Q){return $[Q]??null}let K={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"},q={nan:"NaN",number:"číslo",string:"řetězec",function:"funkce",array:"pole"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Neplatný vstup: očekáváno instanceof ${Q.expected}, obdrženo ${j}`;return`Neplatný vstup: očekáváno ${W}, obdrženo ${j}`}case"invalid_value":if(Q.values.length===1)return`Neplatný vstup: očekáváno ${v(Q.values[0])}`;return`Neplatná možnost: očekávána jedna z hodnot ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Hodnota je příliš velká: ${Q.origin??"hodnota"} musí mít ${W}${Q.maximum.toString()} ${G.unit??"prvků"}`;return`Hodnota je příliš velká: ${Q.origin??"hodnota"} musí být ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Hodnota je příliš malá: ${Q.origin??"hodnota"} musí mít ${W}${Q.minimum.toString()} ${G.unit??"prvků"}`;return`Hodnota je příliš malá: ${Q.origin??"hodnota"} musí být ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Neplatný řetězec: musí začínat na "${W.prefix}"`;if(W.format==="ends_with")return`Neplatný řetězec: musí končit na "${W.suffix}"`;if(W.format==="includes")return`Neplatný řetězec: musí obsahovat "${W.includes}"`;if(W.format==="regex")return`Neplatný řetězec: musí odpovídat vzoru ${W.pattern}`;return`Neplatný formát ${K[W.format]??Q.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${Q.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${_(Q.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${Q.origin}`;case"invalid_union":return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${Q.origin}`;default:return"Neplatný vstup"}}};function x7(){return{localeError:yL()}}var gL=()=>{let $={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function U(Q){return $[Q]??null}let K={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},q={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Ugyldigt input: forventede instanceof ${Q.expected}, fik ${j}`;return`Ugyldigt input: forventede ${W}, fik ${j}`}case"invalid_value":if(Q.values.length===1)return`Ugyldig værdi: forventede ${v(Q.values[0])}`;return`Ugyldigt valg: forventede en af følgende ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin),j=q[Q.origin]??Q.origin;if(G)return`For stor: forventede ${j??"value"} ${G.verb} ${W} ${Q.maximum.toString()} ${G.unit??"elementer"}`;return`For stor: forventede ${j??"value"} havde ${W} ${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin),j=q[Q.origin]??Q.origin;if(G)return`For lille: forventede ${j} ${G.verb} ${W} ${Q.minimum.toString()} ${G.unit}`;return`For lille: forventede ${j} havde ${W} ${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Ugyldig streng: skal starte med "${W.prefix}"`;if(W.format==="ends_with")return`Ugyldig streng: skal ende med "${W.suffix}"`;if(W.format==="includes")return`Ugyldig streng: skal indeholde "${W.includes}"`;if(W.format==="regex")return`Ugyldig streng: skal matche mønsteret ${W.pattern}`;return`Ugyldig ${K[W.format]??Q.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${Q.divisor}`;case"unrecognized_keys":return`${Q.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${_(Q.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${Q.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${Q.origin}`;default:return"Ugyldigt input"}}};function w7(){return{localeError:gL()}}var uL=()=>{let $={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function U(Q){return $[Q]??null}let K={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},q={nan:"NaN",number:"Zahl",array:"Array"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Ungültige Eingabe: erwartet instanceof ${Q.expected}, erhalten ${j}`;return`Ungültige Eingabe: erwartet ${W}, erhalten ${j}`}case"invalid_value":if(Q.values.length===1)return`Ungültige Eingabe: erwartet ${v(Q.values[0])}`;return`Ungültige Option: erwartet eine von ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Zu groß: erwartet, dass ${Q.origin??"Wert"} ${W}${Q.maximum.toString()} ${G.unit??"Elemente"} hat`;return`Zu groß: erwartet, dass ${Q.origin??"Wert"} ${W}${Q.maximum.toString()} ist`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Zu klein: erwartet, dass ${Q.origin} ${W}${Q.minimum.toString()} ${G.unit} hat`;return`Zu klein: erwartet, dass ${Q.origin} ${W}${Q.minimum.toString()} ist`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Ungültiger String: muss mit "${W.prefix}" beginnen`;if(W.format==="ends_with")return`Ungültiger String: muss mit "${W.suffix}" enden`;if(W.format==="includes")return`Ungültiger String: muss "${W.includes}" enthalten`;if(W.format==="regex")return`Ungültiger String: muss dem Muster ${W.pattern} entsprechen`;return`Ungültig: ${K[W.format]??Q.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${Q.divisor} sein`;case"unrecognized_keys":return`${Q.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${_(Q.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${Q.origin}`;case"invalid_union":return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${Q.origin}`;default:return"Ungültige Eingabe"}}};function A7(){return{localeError:uL()}}var fL=()=>{let $={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function U(Q){return $[Q]??null}let K={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},q={nan:"NaN"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;return`Invalid input: expected ${W}, received ${j}`}case"invalid_value":if(Q.values.length===1)return`Invalid input: expected ${v(Q.values[0])}`;return`Invalid option: expected one of ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Too big: expected ${Q.origin??"value"} to have ${W}${Q.maximum.toString()} ${G.unit??"elements"}`;return`Too big: expected ${Q.origin??"value"} to be ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Too small: expected ${Q.origin} to have ${W}${Q.minimum.toString()} ${G.unit}`;return`Too small: expected ${Q.origin} to be ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Invalid string: must start with "${W.prefix}"`;if(W.format==="ends_with")return`Invalid string: must end with "${W.suffix}"`;if(W.format==="includes")return`Invalid string: must include "${W.includes}"`;if(W.format==="regex")return`Invalid string: must match pattern ${W.pattern}`;return`Invalid ${K[W.format]??Q.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${Q.divisor}`;case"unrecognized_keys":return`Unrecognized key${Q.keys.length>1?"s":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Invalid key in ${Q.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${Q.origin}`;default:return"Invalid input"}}};function e6(){return{localeError:fL()}}var mL=()=>{let $={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function U(Q){return $[Q]??null}let K={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},q={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Nevalida enigo: atendiĝis instanceof ${Q.expected}, riceviĝis ${j}`;return`Nevalida enigo: atendiĝis ${W}, riceviĝis ${j}`}case"invalid_value":if(Q.values.length===1)return`Nevalida enigo: atendiĝis ${v(Q.values[0])}`;return`Nevalida opcio: atendiĝis unu el ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Tro granda: atendiĝis ke ${Q.origin??"valoro"} havu ${W}${Q.maximum.toString()} ${G.unit??"elementojn"}`;return`Tro granda: atendiĝis ke ${Q.origin??"valoro"} havu ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Tro malgranda: atendiĝis ke ${Q.origin} havu ${W}${Q.minimum.toString()} ${G.unit}`;return`Tro malgranda: atendiĝis ke ${Q.origin} estu ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Nevalida karaktraro: devas komenciĝi per "${W.prefix}"`;if(W.format==="ends_with")return`Nevalida karaktraro: devas finiĝi per "${W.suffix}"`;if(W.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${W.includes}"`;if(W.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${W.pattern}`;return`Nevalida ${K[W.format]??Q.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${Q.divisor}`;case"unrecognized_keys":return`Nekonata${Q.keys.length>1?"j":""} ŝlosilo${Q.keys.length>1?"j":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${Q.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${Q.origin}`;default:return"Nevalida enigo"}}};function v7(){return{localeError:mL()}}var hL=()=>{let $={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function U(Q){return $[Q]??null}let K={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},q={nan:"NaN",string:"texto",number:"número",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"número grande",symbol:"símbolo",undefined:"indefinido",null:"nulo",function:"función",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeración",union:"unión",literal:"literal",promise:"promesa",void:"vacío",never:"nunca",unknown:"desconocido",any:"cualquiera"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Entrada inválida: se esperaba instanceof ${Q.expected}, recibido ${j}`;return`Entrada inválida: se esperaba ${W}, recibido ${j}`}case"invalid_value":if(Q.values.length===1)return`Entrada inválida: se esperaba ${v(Q.values[0])}`;return`Opción inválida: se esperaba una de ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin),j=q[Q.origin]??Q.origin;if(G)return`Demasiado grande: se esperaba que ${j??"valor"} tuviera ${W}${Q.maximum.toString()} ${G.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${j??"valor"} fuera ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin),j=q[Q.origin]??Q.origin;if(G)return`Demasiado pequeño: se esperaba que ${j} tuviera ${W}${Q.minimum.toString()} ${G.unit}`;return`Demasiado pequeño: se esperaba que ${j} fuera ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Cadena inválida: debe comenzar con "${W.prefix}"`;if(W.format==="ends_with")return`Cadena inválida: debe terminar en "${W.suffix}"`;if(W.format==="includes")return`Cadena inválida: debe incluir "${W.includes}"`;if(W.format==="regex")return`Cadena inválida: debe coincidir con el patrón ${W.pattern}`;return`Inválido ${K[W.format]??Q.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${Q.divisor}`;case"unrecognized_keys":return`Llave${Q.keys.length>1?"s":""} desconocida${Q.keys.length>1?"s":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Llave inválida en ${q[Q.origin]??Q.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido en ${q[Q.origin]??Q.origin}`;default:return"Entrada inválida"}}};function k7(){return{localeError:hL()}}var cL=()=>{let $={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function U(Q){return $[Q]??null}let K={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"},q={nan:"NaN",number:"عدد",array:"آرایه"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`ورودی نامعتبر: میبایست instanceof ${Q.expected} میبود، ${j} دریافت شد`;return`ورودی نامعتبر: میبایست ${W} میبود، ${j} دریافت شد`}case"invalid_value":if(Q.values.length===1)return`ورودی نامعتبر: میبایست ${v(Q.values[0])} میبود`;return`گزینه نامعتبر: میبایست یکی از ${_(Q.values,"|")} میبود`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`خیلی بزرگ: ${Q.origin??"مقدار"} باید ${W}${Q.maximum.toString()} ${G.unit??"عنصر"} باشد`;return`خیلی بزرگ: ${Q.origin??"مقدار"} باید ${W}${Q.maximum.toString()} باشد`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`خیلی کوچک: ${Q.origin} باید ${W}${Q.minimum.toString()} ${G.unit} باشد`;return`خیلی کوچک: ${Q.origin} باید ${W}${Q.minimum.toString()} باشد`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`رشته نامعتبر: باید با "${W.prefix}" شروع شود`;if(W.format==="ends_with")return`رشته نامعتبر: باید با "${W.suffix}" تمام شود`;if(W.format==="includes")return`رشته نامعتبر: باید شامل "${W.includes}" باشد`;if(W.format==="regex")return`رشته نامعتبر: باید با الگوی ${W.pattern} مطابقت داشته باشد`;return`${K[W.format]??Q.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${Q.divisor} باشد`;case"unrecognized_keys":return`کلید${Q.keys.length>1?"های":""} ناشناس: ${_(Q.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${Q.origin}`;case"invalid_union":return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${Q.origin}`;default:return"ورودی نامعتبر"}}};function z7(){return{localeError:cL()}}var lL=()=>{let $={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function U(Q){return $[Q]??null}let K={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},q={nan:"NaN"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Virheellinen tyyppi: odotettiin instanceof ${Q.expected}, oli ${j}`;return`Virheellinen tyyppi: odotettiin ${W}, oli ${j}`}case"invalid_value":if(Q.values.length===1)return`Virheellinen syöte: täytyy olla ${v(Q.values[0])}`;return`Virheellinen valinta: täytyy olla yksi seuraavista: ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Liian suuri: ${G.subject} täytyy olla ${W}${Q.maximum.toString()} ${G.unit}`.trim();return`Liian suuri: arvon täytyy olla ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Liian pieni: ${G.subject} täytyy olla ${W}${Q.minimum.toString()} ${G.unit}`.trim();return`Liian pieni: arvon täytyy olla ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Virheellinen syöte: täytyy alkaa "${W.prefix}"`;if(W.format==="ends_with")return`Virheellinen syöte: täytyy loppua "${W.suffix}"`;if(W.format==="includes")return`Virheellinen syöte: täytyy sisältää "${W.includes}"`;if(W.format==="regex")return`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${W.pattern}`;return`Virheellinen ${K[W.format]??Q.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${Q.divisor} monikerta`;case"unrecognized_keys":return`${Q.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${_(Q.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};function R7(){return{localeError:lL()}}var rL=()=>{let $={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function U(Q){return $[Q]??null}let K={regex:"entrée",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},q={nan:"NaN",number:"nombre",array:"tableau"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Entrée invalide : instanceof ${Q.expected} attendu, ${j} reçu`;return`Entrée invalide : ${W} attendu, ${j} reçu`}case"invalid_value":if(Q.values.length===1)return`Entrée invalide : ${v(Q.values[0])} attendu`;return`Option invalide : une valeur parmi ${_(Q.values,"|")} attendue`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Trop grand : ${Q.origin??"valeur"} doit ${G.verb} ${W}${Q.maximum.toString()} ${G.unit??"élément(s)"}`;return`Trop grand : ${Q.origin??"valeur"} doit être ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Trop petit : ${Q.origin} doit ${G.verb} ${W}${Q.minimum.toString()} ${G.unit}`;return`Trop petit : ${Q.origin} doit être ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Chaîne invalide : doit commencer par "${W.prefix}"`;if(W.format==="ends_with")return`Chaîne invalide : doit se terminer par "${W.suffix}"`;if(W.format==="includes")return`Chaîne invalide : doit inclure "${W.includes}"`;if(W.format==="regex")return`Chaîne invalide : doit correspondre au modèle ${W.pattern}`;return`${K[W.format]??Q.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${Q.divisor}`;case"unrecognized_keys":return`Clé${Q.keys.length>1?"s":""} non reconnue${Q.keys.length>1?"s":""} : ${_(Q.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${Q.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${Q.origin}`;default:return"Entrée invalide"}}};function b7(){return{localeError:rL()}}var iL=()=>{let $={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function U(Q){return $[Q]??null}let K={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},q={nan:"NaN"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Entrée invalide : attendu instanceof ${Q.expected}, reçu ${j}`;return`Entrée invalide : attendu ${W}, reçu ${j}`}case"invalid_value":if(Q.values.length===1)return`Entrée invalide : attendu ${v(Q.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"≤":"<",G=U(Q.origin);if(G)return`Trop grand : attendu que ${Q.origin??"la valeur"} ait ${W}${Q.maximum.toString()} ${G.unit}`;return`Trop grand : attendu que ${Q.origin??"la valeur"} soit ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?"≥":">",G=U(Q.origin);if(G)return`Trop petit : attendu que ${Q.origin} ait ${W}${Q.minimum.toString()} ${G.unit}`;return`Trop petit : attendu que ${Q.origin} soit ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Chaîne invalide : doit commencer par "${W.prefix}"`;if(W.format==="ends_with")return`Chaîne invalide : doit se terminer par "${W.suffix}"`;if(W.format==="includes")return`Chaîne invalide : doit inclure "${W.includes}"`;if(W.format==="regex")return`Chaîne invalide : doit correspondre au motif ${W.pattern}`;return`${K[W.format]??Q.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${Q.divisor}`;case"unrecognized_keys":return`Clé${Q.keys.length>1?"s":""} non reconnue${Q.keys.length>1?"s":""} : ${_(Q.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${Q.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${Q.origin}`;default:return"Entrée invalide"}}};function O7(){return{localeError:iL()}}var dL=()=>{let $={string:{label:"מחרוזת",gender:"f"},number:{label:"מספר",gender:"m"},boolean:{label:"ערך בוליאני",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"תאריך",gender:"m"},array:{label:"מערך",gender:"m"},object:{label:"אובייקט",gender:"m"},null:{label:"ערך ריק (null)",gender:"m"},undefined:{label:"ערך לא מוגדר (undefined)",gender:"m"},symbol:{label:"סימבול (Symbol)",gender:"m"},function:{label:"פונקציה",gender:"f"},map:{label:"מפה (Map)",gender:"f"},set:{label:"קבוצה (Set)",gender:"f"},file:{label:"קובץ",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"ערך לא ידוע",gender:"m"},value:{label:"ערך",gender:"m"}},U={string:{unit:"תווים",shortLabel:"קצר",longLabel:"ארוך"},file:{unit:"בייטים",shortLabel:"קטן",longLabel:"גדול"},array:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},set:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},number:{unit:"",shortLabel:"קטן",longLabel:"גדול"}},K=(H)=>H?$[H]:void 0,q=(H)=>{let X=K(H);if(X)return X.label;return H??$.unknown.label},Q=(H)=>`ה${q(H)}`,W=(H)=>{return(K(H)?.gender??"m")==="f"?"צריכה להיות":"צריך להיות"},G=(H)=>{if(!H)return null;return U[H]??null},j={regex:{label:"קלט",gender:"m"},email:{label:"כתובת אימייל",gender:"f"},url:{label:"כתובת רשת",gender:"f"},emoji:{label:"אימוג'י",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"תאריך וזמן ISO",gender:"m"},date:{label:"תאריך ISO",gender:"m"},time:{label:"זמן ISO",gender:"m"},duration:{label:"משך זמן ISO",gender:"m"},ipv4:{label:"כתובת IPv4",gender:"f"},ipv6:{label:"כתובת IPv6",gender:"f"},cidrv4:{label:"טווח IPv4",gender:"m"},cidrv6:{label:"טווח IPv6",gender:"m"},base64:{label:"מחרוזת בבסיס 64",gender:"f"},base64url:{label:"מחרוזת בבסיס 64 לכתובות רשת",gender:"f"},json_string:{label:"מחרוזת JSON",gender:"f"},e164:{label:"מספר E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"קלט",gender:"m"},includes:{label:"קלט",gender:"m"},lowercase:{label:"קלט",gender:"m"},starts_with:{label:"קלט",gender:"m"},uppercase:{label:"קלט",gender:"m"}},Y={nan:"NaN"};return(H)=>{switch(H.code){case"invalid_type":{let X=H.expected,B=Y[X??""]??q(X),M=k(H.input),I=Y[M]??$[M]?.label??M;if(/^[A-Z]/.test(H.expected))return`קלט לא תקין: צריך להיות instanceof ${H.expected}, התקבל ${I}`;return`קלט לא תקין: צריך להיות ${B}, התקבל ${I}`}case"invalid_value":{if(H.values.length===1)return`ערך לא תקין: הערך חייב להיות ${v(H.values[0])}`;let X=H.values.map((I)=>v(I));if(H.values.length===2)return`ערך לא תקין: האפשרויות המתאימות הן ${X[0]} או ${X[1]}`;let B=X[X.length-1];return`ערך לא תקין: האפשרויות המתאימות הן ${X.slice(0,-1).join(", ")} או ${B}`}case"too_big":{let X=G(H.origin),B=Q(H.origin??"value");if(H.origin==="string")return`${X?.longLabel??"ארוך"} מדי: ${B} צריכה להכיל ${H.maximum.toString()} ${X?.unit??""} ${H.inclusive?"או פחות":"לכל היותר"}`.trim();if(H.origin==="number"){let E=H.inclusive?`קטן או שווה ל-${H.maximum}`:`קטן מ-${H.maximum}`;return`גדול מדי: ${B} צריך להיות ${E}`}if(H.origin==="array"||H.origin==="set"){let E=H.origin==="set"?"צריכה":"צריך",u=H.inclusive?`${H.maximum} ${X?.unit??""} או פחות`:`פחות מ-${H.maximum} ${X?.unit??""}`;return`גדול מדי: ${B} ${E} להכיל ${u}`.trim()}let M=H.inclusive?"<=":"<",I=W(H.origin??"value");if(X?.unit)return`${X.longLabel} מדי: ${B} ${I} ${M}${H.maximum.toString()} ${X.unit}`;return`${X?.longLabel??"גדול"} מדי: ${B} ${I} ${M}${H.maximum.toString()}`}case"too_small":{let X=G(H.origin),B=Q(H.origin??"value");if(H.origin==="string")return`${X?.shortLabel??"קצר"} מדי: ${B} צריכה להכיל ${H.minimum.toString()} ${X?.unit??""} ${H.inclusive?"או יותר":"לפחות"}`.trim();if(H.origin==="number"){let E=H.inclusive?`גדול או שווה ל-${H.minimum}`:`גדול מ-${H.minimum}`;return`קטן מדי: ${B} צריך להיות ${E}`}if(H.origin==="array"||H.origin==="set"){let E=H.origin==="set"?"צריכה":"צריך";if(H.minimum===1&&H.inclusive){let U$=H.origin==="set"?"לפחות פריט אחד":"לפחות פריט אחד";return`קטן מדי: ${B} ${E} להכיל ${U$}`}let u=H.inclusive?`${H.minimum} ${X?.unit??""} או יותר`:`יותר מ-${H.minimum} ${X?.unit??""}`;return`קטן מדי: ${B} ${E} להכיל ${u}`.trim()}let M=H.inclusive?">=":">",I=W(H.origin??"value");if(X?.unit)return`${X.shortLabel} מדי: ${B} ${I} ${M}${H.minimum.toString()} ${X.unit}`;return`${X?.shortLabel??"קטן"} מדי: ${B} ${I} ${M}${H.minimum.toString()}`}case"invalid_format":{let X=H;if(X.format==="starts_with")return`המחרוזת חייבת להתחיל ב "${X.prefix}"`;if(X.format==="ends_with")return`המחרוזת חייבת להסתיים ב "${X.suffix}"`;if(X.format==="includes")return`המחרוזת חייבת לכלול "${X.includes}"`;if(X.format==="regex")return`המחרוזת חייבת להתאים לתבנית ${X.pattern}`;let B=j[X.format],M=B?.label??X.format,E=(B?.gender??"m")==="f"?"תקינה":"תקין";return`${M} לא ${E}`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${H.divisor}`;case"unrecognized_keys":return`מפתח${H.keys.length>1?"ות":""} לא מזוה${H.keys.length>1?"ים":"ה"}: ${_(H.keys,", ")}`;case"invalid_key":return"שדה לא תקין באובייקט";case"invalid_union":return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${Q(H.origin??"array")}`;default:return"קלט לא תקין"}}};function T7(){return{localeError:dL()}}var oL=()=>{let $={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function U(Q){return $[Q]??null}let K={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"},q={nan:"NaN",number:"szám",array:"tömb"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Érvénytelen bemenet: a várt érték instanceof ${Q.expected}, a kapott érték ${j}`;return`Érvénytelen bemenet: a várt érték ${W}, a kapott érték ${j}`}case"invalid_value":if(Q.values.length===1)return`Érvénytelen bemenet: a várt érték ${v(Q.values[0])}`;return`Érvénytelen opció: valamelyik érték várt ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Túl nagy: ${Q.origin??"érték"} mérete túl nagy ${W}${Q.maximum.toString()} ${G.unit??"elem"}`;return`Túl nagy: a bemeneti érték ${Q.origin??"érték"} túl nagy: ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Túl kicsi: a bemeneti érték ${Q.origin} mérete túl kicsi ${W}${Q.minimum.toString()} ${G.unit}`;return`Túl kicsi: a bemeneti érték ${Q.origin} túl kicsi ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Érvénytelen string: "${W.prefix}" értékkel kell kezdődnie`;if(W.format==="ends_with")return`Érvénytelen string: "${W.suffix}" értékkel kell végződnie`;if(W.format==="includes")return`Érvénytelen string: "${W.includes}" értéket kell tartalmaznia`;if(W.format==="regex")return`Érvénytelen string: ${W.pattern} mintának kell megfelelnie`;return`Érvénytelen ${K[W.format]??Q.format}`}case"not_multiple_of":return`Érvénytelen szám: ${Q.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${Q.keys.length>1?"s":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${Q.origin}`;case"invalid_union":return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${Q.origin}`;default:return"Érvénytelen bemenet"}}};function S7(){return{localeError:oL()}}function QY($,U,K){return Math.abs($)===1?U:K}function l4($){if(!$)return"";let U=["ա","ե","ը","ի","ո","ու","օ"],K=$[$.length-1];return $+(U.includes(K)?"ն":"ը")}var nL=()=>{let $={string:{unit:{one:"նշան",many:"նշաններ"},verb:"ունենալ"},file:{unit:{one:"բայթ",many:"բայթեր"},verb:"ունենալ"},array:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"},set:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"}};function U(Q){return $[Q]??null}let K={regex:"մուտք",email:"էլ. հասցե",url:"URL",emoji:"էմոջի",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ամսաթիվ և ժամ",date:"ISO ամսաթիվ",time:"ISO ժամ",duration:"ISO տևողություն",ipv4:"IPv4 հասցե",ipv6:"IPv6 հասցե",cidrv4:"IPv4 միջակայք",cidrv6:"IPv6 միջակայք",base64:"base64 ձևաչափով տող",base64url:"base64url ձևաչափով տող",json_string:"JSON տող",e164:"E.164 համար",jwt:"JWT",template_literal:"մուտք"},q={nan:"NaN",number:"թիվ",array:"զանգված"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Սխալ մուտքագրում․ սպասվում էր instanceof ${Q.expected}, ստացվել է ${j}`;return`Սխալ մուտքագրում․ սպասվում էր ${W}, ստացվել է ${j}`}case"invalid_value":if(Q.values.length===1)return`Սխալ մուտքագրում․ սպասվում էր ${v(Q.values[1])}`;return`Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G){let j=Number(Q.maximum),Y=QY(j,G.unit.one,G.unit.many);return`Չափազանց մեծ արժեք․ սպասվում է, որ ${l4(Q.origin??"արժեք")} կունենա ${W}${Q.maximum.toString()} ${Y}`}return`Չափազանց մեծ արժեք․ սպասվում է, որ ${l4(Q.origin??"արժեք")} լինի ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G){let j=Number(Q.minimum),Y=QY(j,G.unit.one,G.unit.many);return`Չափազանց փոքր արժեք․ սպասվում է, որ ${l4(Q.origin)} կունենա ${W}${Q.minimum.toString()} ${Y}`}return`Չափազանց փոքր արժեք․ սպասվում է, որ ${l4(Q.origin)} լինի ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Սխալ տող․ պետք է սկսվի "${W.prefix}"-ով`;if(W.format==="ends_with")return`Սխալ տող․ պետք է ավարտվի "${W.suffix}"-ով`;if(W.format==="includes")return`Սխալ տող․ պետք է պարունակի "${W.includes}"`;if(W.format==="regex")return`Սխալ տող․ պետք է համապատասխանի ${W.pattern} ձևաչափին`;return`Սխալ ${K[W.format]??Q.format}`}case"not_multiple_of":return`Սխալ թիվ․ պետք է բազմապատիկ լինի ${Q.divisor}-ի`;case"unrecognized_keys":return`Չճանաչված բանալի${Q.keys.length>1?"ներ":""}. ${_(Q.keys,", ")}`;case"invalid_key":return`Սխալ բանալի ${l4(Q.origin)}-ում`;case"invalid_union":return"Սխալ մուտքագրում";case"invalid_element":return`Սխալ արժեք ${l4(Q.origin)}-ում`;default:return"Սխալ մուտքագրում"}}};function C7(){return{localeError:nL()}}var pL=()=>{let $={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function U(Q){return $[Q]??null}let K={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},q={nan:"NaN"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Input tidak valid: diharapkan instanceof ${Q.expected}, diterima ${j}`;return`Input tidak valid: diharapkan ${W}, diterima ${j}`}case"invalid_value":if(Q.values.length===1)return`Input tidak valid: diharapkan ${v(Q.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Terlalu besar: diharapkan ${Q.origin??"value"} memiliki ${W}${Q.maximum.toString()} ${G.unit??"elemen"}`;return`Terlalu besar: diharapkan ${Q.origin??"value"} menjadi ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Terlalu kecil: diharapkan ${Q.origin} memiliki ${W}${Q.minimum.toString()} ${G.unit}`;return`Terlalu kecil: diharapkan ${Q.origin} menjadi ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`String tidak valid: harus dimulai dengan "${W.prefix}"`;if(W.format==="ends_with")return`String tidak valid: harus berakhir dengan "${W.suffix}"`;if(W.format==="includes")return`String tidak valid: harus menyertakan "${W.includes}"`;if(W.format==="regex")return`String tidak valid: harus sesuai pola ${W.pattern}`;return`${K[W.format]??Q.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${Q.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${Q.keys.length>1?"s":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${Q.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${Q.origin}`;default:return"Input tidak valid"}}};function E7(){return{localeError:pL()}}var tL=()=>{let $={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}};function U(Q){return $[Q]??null}let K={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"},q={nan:"NaN",number:"númer",array:"fylki"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Rangt gildi: Þú slóst inn ${j} þar sem á að vera instanceof ${Q.expected}`;return`Rangt gildi: Þú slóst inn ${j} þar sem á að vera ${W}`}case"invalid_value":if(Q.values.length===1)return`Rangt gildi: gert ráð fyrir ${v(Q.values[0])}`;return`Ógilt val: má vera eitt af eftirfarandi ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Of stórt: gert er ráð fyrir að ${Q.origin??"gildi"} hafi ${W}${Q.maximum.toString()} ${G.unit??"hluti"}`;return`Of stórt: gert er ráð fyrir að ${Q.origin??"gildi"} sé ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Of lítið: gert er ráð fyrir að ${Q.origin} hafi ${W}${Q.minimum.toString()} ${G.unit}`;return`Of lítið: gert er ráð fyrir að ${Q.origin} sé ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Ógildur strengur: verður að byrja á "${W.prefix}"`;if(W.format==="ends_with")return`Ógildur strengur: verður að enda á "${W.suffix}"`;if(W.format==="includes")return`Ógildur strengur: verður að innihalda "${W.includes}"`;if(W.format==="regex")return`Ógildur strengur: verður að fylgja mynstri ${W.pattern}`;return`Rangt ${K[W.format]??Q.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${Q.divisor}`;case"unrecognized_keys":return`Óþekkt ${Q.keys.length>1?"ir lyklar":"ur lykill"}: ${_(Q.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${Q.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${Q.origin}`;default:return"Rangt gildi"}}};function y7(){return{localeError:tL()}}var aL=()=>{let $={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function U(Q){return $[Q]??null}let K={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},q={nan:"NaN",number:"numero",array:"vettore"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Input non valido: atteso instanceof ${Q.expected}, ricevuto ${j}`;return`Input non valido: atteso ${W}, ricevuto ${j}`}case"invalid_value":if(Q.values.length===1)return`Input non valido: atteso ${v(Q.values[0])}`;return`Opzione non valida: atteso uno tra ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Troppo grande: ${Q.origin??"valore"} deve avere ${W}${Q.maximum.toString()} ${G.unit??"elementi"}`;return`Troppo grande: ${Q.origin??"valore"} deve essere ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Troppo piccolo: ${Q.origin} deve avere ${W}${Q.minimum.toString()} ${G.unit}`;return`Troppo piccolo: ${Q.origin} deve essere ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Stringa non valida: deve iniziare con "${W.prefix}"`;if(W.format==="ends_with")return`Stringa non valida: deve terminare con "${W.suffix}"`;if(W.format==="includes")return`Stringa non valida: deve includere "${W.includes}"`;if(W.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${W.pattern}`;return`Invalid ${K[W.format]??Q.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${Q.divisor}`;case"unrecognized_keys":return`Chiav${Q.keys.length>1?"i":"e"} non riconosciut${Q.keys.length>1?"e":"a"}: ${_(Q.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${Q.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${Q.origin}`;default:return"Input non valido"}}};function g7(){return{localeError:aL()}}var sL=()=>{let $={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function U(Q){return $[Q]??null}let K={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"},q={nan:"NaN",number:"数値",array:"配列"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`無効な入力: instanceof ${Q.expected}が期待されましたが、${j}が入力されました`;return`無効な入力: ${W}が期待されましたが、${j}が入力されました`}case"invalid_value":if(Q.values.length===1)return`無効な入力: ${v(Q.values[0])}が期待されました`;return`無効な選択: ${_(Q.values,"、")}のいずれかである必要があります`;case"too_big":{let W=Q.inclusive?"以下である":"より小さい",G=U(Q.origin);if(G)return`大きすぎる値: ${Q.origin??"値"}は${Q.maximum.toString()}${G.unit??"要素"}${W}必要があります`;return`大きすぎる値: ${Q.origin??"値"}は${Q.maximum.toString()}${W}必要があります`}case"too_small":{let W=Q.inclusive?"以上である":"より大きい",G=U(Q.origin);if(G)return`小さすぎる値: ${Q.origin}は${Q.minimum.toString()}${G.unit}${W}必要があります`;return`小さすぎる値: ${Q.origin}は${Q.minimum.toString()}${W}必要があります`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`無効な文字列: "${W.prefix}"で始まる必要があります`;if(W.format==="ends_with")return`無効な文字列: "${W.suffix}"で終わる必要があります`;if(W.format==="includes")return`無効な文字列: "${W.includes}"を含む必要があります`;if(W.format==="regex")return`無効な文字列: パターン${W.pattern}に一致する必要があります`;return`無効な${K[W.format]??Q.format}`}case"not_multiple_of":return`無効な数値: ${Q.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${Q.keys.length>1?"群":""}: ${_(Q.keys,"、")}`;case"invalid_key":return`${Q.origin}内の無効なキー`;case"invalid_union":return"無効な入力";case"invalid_element":return`${Q.origin}内の無効な値`;default:return"無効な入力"}}};function u7(){return{localeError:sL()}}var eL=()=>{let $={string:{unit:"სიმბოლო",verb:"უნდა შეიცავდეს"},file:{unit:"ბაიტი",verb:"უნდა შეიცავდეს"},array:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},set:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"}};function U(Q){return $[Q]??null}let K={regex:"შეყვანა",email:"ელ-ფოსტის მისამართი",url:"URL",emoji:"ემოჯი",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"თარიღი-დრო",date:"თარიღი",time:"დრო",duration:"ხანგრძლივობა",ipv4:"IPv4 მისამართი",ipv6:"IPv6 მისამართი",cidrv4:"IPv4 დიაპაზონი",cidrv6:"IPv6 დიაპაზონი",base64:"base64-კოდირებული სტრინგი",base64url:"base64url-კოდირებული სტრინგი",json_string:"JSON სტრინგი",e164:"E.164 ნომერი",jwt:"JWT",template_literal:"შეყვანა"},q={nan:"NaN",number:"რიცხვი",string:"სტრინგი",boolean:"ბულეანი",function:"ფუნქცია",array:"მასივი"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`არასწორი შეყვანა: მოსალოდნელი instanceof ${Q.expected}, მიღებული ${j}`;return`არასწორი შეყვანა: მოსალოდნელი ${W}, მიღებული ${j}`}case"invalid_value":if(Q.values.length===1)return`არასწორი შეყვანა: მოსალოდნელი ${v(Q.values[0])}`;return`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${_(Q.values,"|")}-დან`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`ზედმეტად დიდი: მოსალოდნელი ${Q.origin??"მნიშვნელობა"} ${G.verb} ${W}${Q.maximum.toString()} ${G.unit}`;return`ზედმეტად დიდი: მოსალოდნელი ${Q.origin??"მნიშვნელობა"} იყოს ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`ზედმეტად პატარა: მოსალოდნელი ${Q.origin} ${G.verb} ${W}${Q.minimum.toString()} ${G.unit}`;return`ზედმეტად პატარა: მოსალოდნელი ${Q.origin} იყოს ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`არასწორი სტრინგი: უნდა იწყებოდეს "${W.prefix}"-ით`;if(W.format==="ends_with")return`არასწორი სტრინგი: უნდა მთავრდებოდეს "${W.suffix}"-ით`;if(W.format==="includes")return`არასწორი სტრინგი: უნდა შეიცავდეს "${W.includes}"-ს`;if(W.format==="regex")return`არასწორი სტრინგი: უნდა შეესაბამებოდეს შაბლონს ${W.pattern}`;return`არასწორი ${K[W.format]??Q.format}`}case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${Q.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${Q.keys.length>1?"ები":"ი"}: ${_(Q.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${Q.origin}-ში`;case"invalid_union":return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${Q.origin}-ში`;default:return"არასწორი შეყვანა"}}};function f7(){return{localeError:eL()}}var $_=()=>{let $={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function U(Q){return $[Q]??null}let K={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"},q={nan:"NaN",number:"លេខ",array:"អារេ (Array)",null:"គ្មានតម្លៃ (null)"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${Q.expected} ប៉ុន្តែទទួលបាន ${j}`;return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${W} ប៉ុន្តែទទួលបាន ${j}`}case"invalid_value":if(Q.values.length===1)return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${v(Q.values[0])}`;return`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`ធំពេក៖ ត្រូវការ ${Q.origin??"តម្លៃ"} ${W} ${Q.maximum.toString()} ${G.unit??"ធាតុ"}`;return`ធំពេក៖ ត្រូវការ ${Q.origin??"តម្លៃ"} ${W} ${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`តូចពេក៖ ត្រូវការ ${Q.origin} ${W} ${Q.minimum.toString()} ${G.unit}`;return`តូចពេក៖ ត្រូវការ ${Q.origin} ${W} ${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${W.prefix}"`;if(W.format==="ends_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${W.suffix}"`;if(W.format==="includes")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${W.includes}"`;if(W.format==="regex")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${W.pattern}`;return`មិនត្រឹមត្រូវ៖ ${K[W.format]??Q.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${Q.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${_(Q.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${Q.origin}`;case"invalid_union":return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${Q.origin}`;default:return"ទិន្នន័យមិនត្រឹមត្រូវ"}}};function $0(){return{localeError:$_()}}function m7(){return $0()}var U_=()=>{let $={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function U(Q){return $[Q]??null}let K={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"},q={nan:"NaN"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`잘못된 입력: 예상 타입은 instanceof ${Q.expected}, 받은 타입은 ${j}입니다`;return`잘못된 입력: 예상 타입은 ${W}, 받은 타입은 ${j}입니다`}case"invalid_value":if(Q.values.length===1)return`잘못된 입력: 값은 ${v(Q.values[0])} 이어야 합니다`;return`잘못된 옵션: ${_(Q.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{let W=Q.inclusive?"이하":"미만",G=W==="미만"?"이어야 합니다":"여야 합니다",j=U(Q.origin),Y=j?.unit??"요소";if(j)return`${Q.origin??"값"}이 너무 큽니다: ${Q.maximum.toString()}${Y} ${W}${G}`;return`${Q.origin??"값"}이 너무 큽니다: ${Q.maximum.toString()} ${W}${G}`}case"too_small":{let W=Q.inclusive?"이상":"초과",G=W==="이상"?"이어야 합니다":"여야 합니다",j=U(Q.origin),Y=j?.unit??"요소";if(j)return`${Q.origin??"값"}이 너무 작습니다: ${Q.minimum.toString()}${Y} ${W}${G}`;return`${Q.origin??"값"}이 너무 작습니다: ${Q.minimum.toString()} ${W}${G}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`잘못된 문자열: "${W.prefix}"(으)로 시작해야 합니다`;if(W.format==="ends_with")return`잘못된 문자열: "${W.suffix}"(으)로 끝나야 합니다`;if(W.format==="includes")return`잘못된 문자열: "${W.includes}"을(를) 포함해야 합니다`;if(W.format==="regex")return`잘못된 문자열: 정규식 ${W.pattern} 패턴과 일치해야 합니다`;return`잘못된 ${K[W.format]??Q.format}`}case"not_multiple_of":return`잘못된 숫자: ${Q.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${_(Q.keys,", ")}`;case"invalid_key":return`잘못된 키: ${Q.origin}`;case"invalid_union":return"잘못된 입력";case"invalid_element":return`잘못된 값: ${Q.origin}`;default:return"잘못된 입력"}}};function h7(){return{localeError:U_()}}var U0=($)=>{return $.charAt(0).toUpperCase()+$.slice(1)};function KY($){let U=Math.abs($),K=U%10,q=U%100;if(q>=11&&q<=19||K===0)return"many";if(K===1)return"one";return"few"}var Q_=()=>{let $={string:{unit:{one:"simbolis",few:"simboliai",many:"simbolių"},verb:{smaller:{inclusive:"turi būti ne ilgesnė kaip",notInclusive:"turi būti trumpesnė kaip"},bigger:{inclusive:"turi būti ne trumpesnė kaip",notInclusive:"turi būti ilgesnė kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"baitų"},verb:{smaller:{inclusive:"turi būti ne didesnis kaip",notInclusive:"turi būti mažesnis kaip"},bigger:{inclusive:"turi būti ne mažesnis kaip",notInclusive:"turi būti didesnis kaip"}}},array:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}},set:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}}};function U(Q,W,G,j){let Y=$[Q]??null;if(Y===null)return Y;return{unit:Y.unit[W],verb:Y.verb[j][G?"inclusive":"notInclusive"]}}let K={regex:"įvestis",email:"el. pašto adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukmė",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 užkoduota eilutė",base64url:"base64url užkoduota eilutė",json_string:"JSON eilutė",e164:"E.164 numeris",jwt:"JWT",template_literal:"įvestis"},q={nan:"NaN",number:"skaičius",bigint:"sveikasis skaičius",string:"eilutė",boolean:"loginė reikšmė",undefined:"neapibrėžta reikšmė",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulinė reikšmė"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Gautas tipas ${j}, o tikėtasi - instanceof ${Q.expected}`;return`Gautas tipas ${j}, o tikėtasi - ${W}`}case"invalid_value":if(Q.values.length===1)return`Privalo būti ${v(Q.values[0])}`;return`Privalo būti vienas iš ${_(Q.values,"|")} pasirinkimų`;case"too_big":{let W=q[Q.origin]??Q.origin,G=U(Q.origin,KY(Number(Q.maximum)),Q.inclusive??!1,"smaller");if(G?.verb)return`${U0(W??Q.origin??"reikšmė")} ${G.verb} ${Q.maximum.toString()} ${G.unit??"elementų"}`;let j=Q.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${U0(W??Q.origin??"reikšmė")} turi būti ${j} ${Q.maximum.toString()} ${G?.unit}`}case"too_small":{let W=q[Q.origin]??Q.origin,G=U(Q.origin,KY(Number(Q.minimum)),Q.inclusive??!1,"bigger");if(G?.verb)return`${U0(W??Q.origin??"reikšmė")} ${G.verb} ${Q.minimum.toString()} ${G.unit??"elementų"}`;let j=Q.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${U0(W??Q.origin??"reikšmė")} turi būti ${j} ${Q.minimum.toString()} ${G?.unit}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Eilutė privalo prasidėti "${W.prefix}"`;if(W.format==="ends_with")return`Eilutė privalo pasibaigti "${W.suffix}"`;if(W.format==="includes")return`Eilutė privalo įtraukti "${W.includes}"`;if(W.format==="regex")return`Eilutė privalo atitikti ${W.pattern}`;return`Neteisingas ${K[W.format]??Q.format}`}case"not_multiple_of":return`Skaičius privalo būti ${Q.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpažint${Q.keys.length>1?"i":"as"} rakt${Q.keys.length>1?"ai":"as"}: ${_(Q.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga įvestis";case"invalid_element":{let W=q[Q.origin]??Q.origin;return`${U0(W??Q.origin??"reikšmė")} turi klaidingą įvestį`}default:return"Klaidinga įvestis"}}};function c7(){return{localeError:Q_()}}var K_=()=>{let $={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function U(Q){return $[Q]??null}let K={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"},q={nan:"NaN",number:"број",array:"низа"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Грешен внес: се очекува instanceof ${Q.expected}, примено ${j}`;return`Грешен внес: се очекува ${W}, примено ${j}`}case"invalid_value":if(Q.values.length===1)return`Invalid input: expected ${v(Q.values[0])}`;return`Грешана опција: се очекува една ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Премногу голем: се очекува ${Q.origin??"вредноста"} да има ${W}${Q.maximum.toString()} ${G.unit??"елементи"}`;return`Премногу голем: се очекува ${Q.origin??"вредноста"} да биде ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Премногу мал: се очекува ${Q.origin} да има ${W}${Q.minimum.toString()} ${G.unit}`;return`Премногу мал: се очекува ${Q.origin} да биде ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Неважечка низа: мора да започнува со "${W.prefix}"`;if(W.format==="ends_with")return`Неважечка низа: мора да завршува со "${W.suffix}"`;if(W.format==="includes")return`Неважечка низа: мора да вклучува "${W.includes}"`;if(W.format==="regex")return`Неважечка низа: мора да одгоара на патернот ${W.pattern}`;return`Invalid ${K[W.format]??Q.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${Q.divisor}`;case"unrecognized_keys":return`${Q.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${_(Q.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${Q.origin}`;case"invalid_union":return"Грешен внес";case"invalid_element":return`Грешна вредност во ${Q.origin}`;default:return"Грешен внес"}}};function l7(){return{localeError:K_()}}var q_=()=>{let $={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function U(Q){return $[Q]??null}let K={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},q={nan:"NaN",number:"nombor"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Input tidak sah: dijangka instanceof ${Q.expected}, diterima ${j}`;return`Input tidak sah: dijangka ${W}, diterima ${j}`}case"invalid_value":if(Q.values.length===1)return`Input tidak sah: dijangka ${v(Q.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Terlalu besar: dijangka ${Q.origin??"nilai"} ${G.verb} ${W}${Q.maximum.toString()} ${G.unit??"elemen"}`;return`Terlalu besar: dijangka ${Q.origin??"nilai"} adalah ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Terlalu kecil: dijangka ${Q.origin} ${G.verb} ${W}${Q.minimum.toString()} ${G.unit}`;return`Terlalu kecil: dijangka ${Q.origin} adalah ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`String tidak sah: mesti bermula dengan "${W.prefix}"`;if(W.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${W.suffix}"`;if(W.format==="includes")return`String tidak sah: mesti mengandungi "${W.includes}"`;if(W.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${W.pattern}`;return`${K[W.format]??Q.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${Q.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${_(Q.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${Q.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${Q.origin}`;default:return"Input tidak sah"}}};function r7(){return{localeError:q_()}}var W_=()=>{let $={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function U(Q){return $[Q]??null}let K={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},q={nan:"NaN",number:"getal"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Ongeldige invoer: verwacht instanceof ${Q.expected}, ontving ${j}`;return`Ongeldige invoer: verwacht ${W}, ontving ${j}`}case"invalid_value":if(Q.values.length===1)return`Ongeldige invoer: verwacht ${v(Q.values[0])}`;return`Ongeldige optie: verwacht één van ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin),j=Q.origin==="date"?"laat":Q.origin==="string"?"lang":"groot";if(G)return`Te ${j}: verwacht dat ${Q.origin??"waarde"} ${W}${Q.maximum.toString()} ${G.unit??"elementen"} ${G.verb}`;return`Te ${j}: verwacht dat ${Q.origin??"waarde"} ${W}${Q.maximum.toString()} is`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin),j=Q.origin==="date"?"vroeg":Q.origin==="string"?"kort":"klein";if(G)return`Te ${j}: verwacht dat ${Q.origin} ${W}${Q.minimum.toString()} ${G.unit} ${G.verb}`;return`Te ${j}: verwacht dat ${Q.origin} ${W}${Q.minimum.toString()} is`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Ongeldige tekst: moet met "${W.prefix}" beginnen`;if(W.format==="ends_with")return`Ongeldige tekst: moet op "${W.suffix}" eindigen`;if(W.format==="includes")return`Ongeldige tekst: moet "${W.includes}" bevatten`;if(W.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${W.pattern}`;return`Ongeldig: ${K[W.format]??Q.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${Q.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${Q.keys.length>1?"s":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${Q.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${Q.origin}`;default:return"Ongeldige invoer"}}};function i7(){return{localeError:W_()}}var G_=()=>{let $={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function U(Q){return $[Q]??null}let K={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},q={nan:"NaN",number:"tall",array:"liste"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Ugyldig input: forventet instanceof ${Q.expected}, fikk ${j}`;return`Ugyldig input: forventet ${W}, fikk ${j}`}case"invalid_value":if(Q.values.length===1)return`Ugyldig verdi: forventet ${v(Q.values[0])}`;return`Ugyldig valg: forventet en av ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`For stor(t): forventet ${Q.origin??"value"} til å ha ${W}${Q.maximum.toString()} ${G.unit??"elementer"}`;return`For stor(t): forventet ${Q.origin??"value"} til å ha ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`For lite(n): forventet ${Q.origin} til å ha ${W}${Q.minimum.toString()} ${G.unit}`;return`For lite(n): forventet ${Q.origin} til å ha ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Ugyldig streng: må starte med "${W.prefix}"`;if(W.format==="ends_with")return`Ugyldig streng: må ende med "${W.suffix}"`;if(W.format==="includes")return`Ugyldig streng: må inneholde "${W.includes}"`;if(W.format==="regex")return`Ugyldig streng: må matche mønsteret ${W.pattern}`;return`Ugyldig ${K[W.format]??Q.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${Q.divisor}`;case"unrecognized_keys":return`${Q.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${_(Q.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${Q.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${Q.origin}`;default:return"Ugyldig input"}}};function d7(){return{localeError:G_()}}var J_=()=>{let $={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}};function U(Q){return $[Q]??null}let K={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"},q={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Fâsit giren: umulan instanceof ${Q.expected}, alınan ${j}`;return`Fâsit giren: umulan ${W}, alınan ${j}`}case"invalid_value":if(Q.values.length===1)return`Fâsit giren: umulan ${v(Q.values[0])}`;return`Fâsit tercih: mûteberler ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Fazla büyük: ${Q.origin??"value"}, ${W}${Q.maximum.toString()} ${G.unit??"elements"} sahip olmalıydı.`;return`Fazla büyük: ${Q.origin??"value"}, ${W}${Q.maximum.toString()} olmalıydı.`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Fazla küçük: ${Q.origin}, ${W}${Q.minimum.toString()} ${G.unit} sahip olmalıydı.`;return`Fazla küçük: ${Q.origin}, ${W}${Q.minimum.toString()} olmalıydı.`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Fâsit metin: "${W.prefix}" ile başlamalı.`;if(W.format==="ends_with")return`Fâsit metin: "${W.suffix}" ile bitmeli.`;if(W.format==="includes")return`Fâsit metin: "${W.includes}" ihtivâ etmeli.`;if(W.format==="regex")return`Fâsit metin: ${W.pattern} nakşına uymalı.`;return`Fâsit ${K[W.format]??Q.format}`}case"not_multiple_of":return`Fâsit sayı: ${Q.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${Q.keys.length>1?"s":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`${Q.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${Q.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};function o7(){return{localeError:J_()}}var j_=()=>{let $={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function U(Q){return $[Q]??null}let K={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"},q={nan:"NaN",number:"عدد",array:"ارې"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`ناسم ورودي: باید instanceof ${Q.expected} وای, مګر ${j} ترلاسه شو`;return`ناسم ورودي: باید ${W} وای, مګر ${j} ترلاسه شو`}case"invalid_value":if(Q.values.length===1)return`ناسم ورودي: باید ${v(Q.values[0])} وای`;return`ناسم انتخاب: باید یو له ${_(Q.values,"|")} څخه وای`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`ډیر لوی: ${Q.origin??"ارزښت"} باید ${W}${Q.maximum.toString()} ${G.unit??"عنصرونه"} ولري`;return`ډیر لوی: ${Q.origin??"ارزښت"} باید ${W}${Q.maximum.toString()} وي`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`ډیر کوچنی: ${Q.origin} باید ${W}${Q.minimum.toString()} ${G.unit} ولري`;return`ډیر کوچنی: ${Q.origin} باید ${W}${Q.minimum.toString()} وي`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`ناسم متن: باید د "${W.prefix}" سره پیل شي`;if(W.format==="ends_with")return`ناسم متن: باید د "${W.suffix}" سره پای ته ورسيږي`;if(W.format==="includes")return`ناسم متن: باید "${W.includes}" ولري`;if(W.format==="regex")return`ناسم متن: باید د ${W.pattern} سره مطابقت ولري`;return`${K[W.format]??Q.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${Q.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${Q.keys.length>1?"کلیډونه":"کلیډ"}: ${_(Q.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${Q.origin} کې`;case"invalid_union":return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${Q.origin} کې`;default:return"ناسمه ورودي"}}};function n7(){return{localeError:j_()}}var Y_=()=>{let $={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}};function U(Q){return $[Q]??null}let K={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"},q={nan:"NaN",number:"liczba",array:"tablica"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Nieprawidłowe dane wejściowe: oczekiwano instanceof ${Q.expected}, otrzymano ${j}`;return`Nieprawidłowe dane wejściowe: oczekiwano ${W}, otrzymano ${j}`}case"invalid_value":if(Q.values.length===1)return`Nieprawidłowe dane wejściowe: oczekiwano ${v(Q.values[0])}`;return`Nieprawidłowa opcja: oczekiwano jednej z wartości ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Za duża wartość: oczekiwano, że ${Q.origin??"wartość"} będzie mieć ${W}${Q.maximum.toString()} ${G.unit??"elementów"}`;return`Zbyt duż(y/a/e): oczekiwano, że ${Q.origin??"wartość"} będzie wynosić ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Za mała wartość: oczekiwano, że ${Q.origin??"wartość"} będzie mieć ${W}${Q.minimum.toString()} ${G.unit??"elementów"}`;return`Zbyt mał(y/a/e): oczekiwano, że ${Q.origin??"wartość"} będzie wynosić ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Nieprawidłowy ciąg znaków: musi zaczynać się od "${W.prefix}"`;if(W.format==="ends_with")return`Nieprawidłowy ciąg znaków: musi kończyć się na "${W.suffix}"`;if(W.format==="includes")return`Nieprawidłowy ciąg znaków: musi zawierać "${W.includes}"`;if(W.format==="regex")return`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${W.pattern}`;return`Nieprawidłow(y/a/e) ${K[W.format]??Q.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${Q.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${Q.keys.length>1?"s":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${Q.origin}`;case"invalid_union":return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${Q.origin}`;default:return"Nieprawidłowe dane wejściowe"}}};function p7(){return{localeError:Y_()}}var H_=()=>{let $={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function U(Q){return $[Q]??null}let K={regex:"padrão",email:"endereço de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},q={nan:"NaN",number:"número",null:"nulo"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Tipo inválido: esperado instanceof ${Q.expected}, recebido ${j}`;return`Tipo inválido: esperado ${W}, recebido ${j}`}case"invalid_value":if(Q.values.length===1)return`Entrada inválida: esperado ${v(Q.values[0])}`;return`Opção inválida: esperada uma das ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Muito grande: esperado que ${Q.origin??"valor"} tivesse ${W}${Q.maximum.toString()} ${G.unit??"elementos"}`;return`Muito grande: esperado que ${Q.origin??"valor"} fosse ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Muito pequeno: esperado que ${Q.origin} tivesse ${W}${Q.minimum.toString()} ${G.unit}`;return`Muito pequeno: esperado que ${Q.origin} fosse ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Texto inválido: deve começar com "${W.prefix}"`;if(W.format==="ends_with")return`Texto inválido: deve terminar com "${W.suffix}"`;if(W.format==="includes")return`Texto inválido: deve incluir "${W.includes}"`;if(W.format==="regex")return`Texto inválido: deve corresponder ao padrão ${W.pattern}`;return`${K[W.format]??Q.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${Q.divisor}`;case"unrecognized_keys":return`Chave${Q.keys.length>1?"s":""} desconhecida${Q.keys.length>1?"s":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Chave inválida em ${Q.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${Q.origin}`;default:return"Campo inválido"}}};function t7(){return{localeError:H_()}}function qY($,U,K,q){let Q=Math.abs($),W=Q%10,G=Q%100;if(G>=11&&G<=19)return q;if(W===1)return U;if(W>=2&&W<=4)return K;return q}var X_=()=>{let $={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function U(Q){return $[Q]??null}let K={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"},q={nan:"NaN",number:"число",array:"массив"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Неверный ввод: ожидалось instanceof ${Q.expected}, получено ${j}`;return`Неверный ввод: ожидалось ${W}, получено ${j}`}case"invalid_value":if(Q.values.length===1)return`Неверный ввод: ожидалось ${v(Q.values[0])}`;return`Неверный вариант: ожидалось одно из ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G){let j=Number(Q.maximum),Y=qY(j,G.unit.one,G.unit.few,G.unit.many);return`Слишком большое значение: ожидалось, что ${Q.origin??"значение"} будет иметь ${W}${Q.maximum.toString()} ${Y}`}return`Слишком большое значение: ожидалось, что ${Q.origin??"значение"} будет ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G){let j=Number(Q.minimum),Y=qY(j,G.unit.one,G.unit.few,G.unit.many);return`Слишком маленькое значение: ожидалось, что ${Q.origin} будет иметь ${W}${Q.minimum.toString()} ${Y}`}return`Слишком маленькое значение: ожидалось, что ${Q.origin} будет ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Неверная строка: должна начинаться с "${W.prefix}"`;if(W.format==="ends_with")return`Неверная строка: должна заканчиваться на "${W.suffix}"`;if(W.format==="includes")return`Неверная строка: должна содержать "${W.includes}"`;if(W.format==="regex")return`Неверная строка: должна соответствовать шаблону ${W.pattern}`;return`Неверный ${K[W.format]??Q.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${Q.divisor}`;case"unrecognized_keys":return`Нераспознанн${Q.keys.length>1?"ые":"ый"} ключ${Q.keys.length>1?"и":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${Q.origin}`;case"invalid_union":return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${Q.origin}`;default:return"Неверные входные данные"}}};function a7(){return{localeError:X_()}}var Z_=()=>{let $={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function U(Q){return $[Q]??null}let K={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"},q={nan:"NaN",number:"število",array:"tabela"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Neveljaven vnos: pričakovano instanceof ${Q.expected}, prejeto ${j}`;return`Neveljaven vnos: pričakovano ${W}, prejeto ${j}`}case"invalid_value":if(Q.values.length===1)return`Neveljaven vnos: pričakovano ${v(Q.values[0])}`;return`Neveljavna možnost: pričakovano eno izmed ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Preveliko: pričakovano, da bo ${Q.origin??"vrednost"} imelo ${W}${Q.maximum.toString()} ${G.unit??"elementov"}`;return`Preveliko: pričakovano, da bo ${Q.origin??"vrednost"} ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Premajhno: pričakovano, da bo ${Q.origin} imelo ${W}${Q.minimum.toString()} ${G.unit}`;return`Premajhno: pričakovano, da bo ${Q.origin} ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Neveljaven niz: mora se začeti z "${W.prefix}"`;if(W.format==="ends_with")return`Neveljaven niz: mora se končati z "${W.suffix}"`;if(W.format==="includes")return`Neveljaven niz: mora vsebovati "${W.includes}"`;if(W.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${W.pattern}`;return`Neveljaven ${K[W.format]??Q.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${Q.divisor}`;case"unrecognized_keys":return`Neprepoznan${Q.keys.length>1?"i ključi":" ključ"}: ${_(Q.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${Q.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${Q.origin}`;default:return"Neveljaven vnos"}}};function s7(){return{localeError:Z_()}}var B_=()=>{let $={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}};function U(Q){return $[Q]??null}let K={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},q={nan:"NaN",number:"antal",array:"lista"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Ogiltig inmatning: förväntat instanceof ${Q.expected}, fick ${j}`;return`Ogiltig inmatning: förväntat ${W}, fick ${j}`}case"invalid_value":if(Q.values.length===1)return`Ogiltig inmatning: förväntat ${v(Q.values[0])}`;return`Ogiltigt val: förväntade en av ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`För stor(t): förväntade ${Q.origin??"värdet"} att ha ${W}${Q.maximum.toString()} ${G.unit??"element"}`;return`För stor(t): förväntat ${Q.origin??"värdet"} att ha ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`För lite(t): förväntade ${Q.origin??"värdet"} att ha ${W}${Q.minimum.toString()} ${G.unit}`;return`För lite(t): förväntade ${Q.origin??"värdet"} att ha ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Ogiltig sträng: måste börja med "${W.prefix}"`;if(W.format==="ends_with")return`Ogiltig sträng: måste sluta med "${W.suffix}"`;if(W.format==="includes")return`Ogiltig sträng: måste innehålla "${W.includes}"`;if(W.format==="regex")return`Ogiltig sträng: måste matcha mönstret "${W.pattern}"`;return`Ogiltig(t) ${K[W.format]??Q.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${Q.divisor}`;case"unrecognized_keys":return`${Q.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${_(Q.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${Q.origin??"värdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${Q.origin??"värdet"}`;default:return"Ogiltig input"}}};function e7(){return{localeError:B_()}}var V_=()=>{let $={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function U(Q){return $[Q]??null}let K={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"},q={nan:"NaN",number:"எண்",array:"அணி",null:"வெறுமை"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${Q.expected}, பெறப்பட்டது ${j}`;return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${W}, பெறப்பட்டது ${j}`}case"invalid_value":if(Q.values.length===1)return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${v(Q.values[0])}`;return`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${_(Q.values,"|")} இல் ஒன்று`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${Q.origin??"மதிப்பு"} ${W}${Q.maximum.toString()} ${G.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`;return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${Q.origin??"மதிப்பு"} ${W}${Q.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${Q.origin} ${W}${Q.minimum.toString()} ${G.unit} ஆக இருக்க வேண்டும்`;return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${Q.origin} ${W}${Q.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`தவறான சரம்: "${W.prefix}" இல் தொடங்க வேண்டும்`;if(W.format==="ends_with")return`தவறான சரம்: "${W.suffix}" இல் முடிவடைய வேண்டும்`;if(W.format==="includes")return`தவறான சரம்: "${W.includes}" ஐ உள்ளடக்க வேண்டும்`;if(W.format==="regex")return`தவறான சரம்: ${W.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`;return`தவறான ${K[W.format]??Q.format}`}case"not_multiple_of":return`தவறான எண்: ${Q.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${Q.keys.length>1?"கள்":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`${Q.origin} இல் தவறான விசை`;case"invalid_union":return"தவறான உள்ளீடு";case"invalid_element":return`${Q.origin} இல் தவறான மதிப்பு`;default:return"தவறான உள்ளீடு"}}};function $5(){return{localeError:V_()}}var M_=()=>{let $={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function U(Q){return $[Q]??null}let K={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"},q={nan:"NaN",number:"ตัวเลข",array:"อาร์เรย์ (Array)",null:"ไม่มีค่า (null)"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${Q.expected} แต่ได้รับ ${j}`;return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${W} แต่ได้รับ ${j}`}case"invalid_value":if(Q.values.length===1)return`ค่าไม่ถูกต้อง: ควรเป็น ${v(Q.values[0])}`;return`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"ไม่เกิน":"น้อยกว่า",G=U(Q.origin);if(G)return`เกินกำหนด: ${Q.origin??"ค่า"} ควรมี${W} ${Q.maximum.toString()} ${G.unit??"รายการ"}`;return`เกินกำหนด: ${Q.origin??"ค่า"} ควรมี${W} ${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?"อย่างน้อย":"มากกว่า",G=U(Q.origin);if(G)return`น้อยกว่ากำหนด: ${Q.origin} ควรมี${W} ${Q.minimum.toString()} ${G.unit}`;return`น้อยกว่ากำหนด: ${Q.origin} ควรมี${W} ${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${W.prefix}"`;if(W.format==="ends_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${W.suffix}"`;if(W.format==="includes")return`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${W.includes}" อยู่ในข้อความ`;if(W.format==="regex")return`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${W.pattern}`;return`รูปแบบไม่ถูกต้อง: ${K[W.format]??Q.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${Q.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${_(Q.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${Q.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${Q.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};function U5(){return{localeError:M_()}}var D_=()=>{let $={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function U(Q){return $[Q]??null}let K={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"},q={nan:"NaN"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Geçersiz değer: beklenen instanceof ${Q.expected}, alınan ${j}`;return`Geçersiz değer: beklenen ${W}, alınan ${j}`}case"invalid_value":if(Q.values.length===1)return`Geçersiz değer: beklenen ${v(Q.values[0])}`;return`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Çok büyük: beklenen ${Q.origin??"değer"} ${W}${Q.maximum.toString()} ${G.unit??"öğe"}`;return`Çok büyük: beklenen ${Q.origin??"değer"} ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Çok küçük: beklenen ${Q.origin} ${W}${Q.minimum.toString()} ${G.unit}`;return`Çok küçük: beklenen ${Q.origin} ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Geçersiz metin: "${W.prefix}" ile başlamalı`;if(W.format==="ends_with")return`Geçersiz metin: "${W.suffix}" ile bitmeli`;if(W.format==="includes")return`Geçersiz metin: "${W.includes}" içermeli`;if(W.format==="regex")return`Geçersiz metin: ${W.pattern} desenine uymalı`;return`Geçersiz ${K[W.format]??Q.format}`}case"not_multiple_of":return`Geçersiz sayı: ${Q.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${Q.keys.length>1?"lar":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`${Q.origin} içinde geçersiz anahtar`;case"invalid_union":return"Geçersiz değer";case"invalid_element":return`${Q.origin} içinde geçersiz değer`;default:return"Geçersiz değer"}}};function Q5(){return{localeError:D_()}}var P_=()=>{let $={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function U(Q){return $[Q]??null}let K={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"},q={nan:"NaN",number:"число",array:"масив"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Неправильні вхідні дані: очікується instanceof ${Q.expected}, отримано ${j}`;return`Неправильні вхідні дані: очікується ${W}, отримано ${j}`}case"invalid_value":if(Q.values.length===1)return`Неправильні вхідні дані: очікується ${v(Q.values[0])}`;return`Неправильна опція: очікується одне з ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Занадто велике: очікується, що ${Q.origin??"значення"} ${G.verb} ${W}${Q.maximum.toString()} ${G.unit??"елементів"}`;return`Занадто велике: очікується, що ${Q.origin??"значення"} буде ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Занадто мале: очікується, що ${Q.origin} ${G.verb} ${W}${Q.minimum.toString()} ${G.unit}`;return`Занадто мале: очікується, що ${Q.origin} буде ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Неправильний рядок: повинен починатися з "${W.prefix}"`;if(W.format==="ends_with")return`Неправильний рядок: повинен закінчуватися на "${W.suffix}"`;if(W.format==="includes")return`Неправильний рядок: повинен містити "${W.includes}"`;if(W.format==="regex")return`Неправильний рядок: повинен відповідати шаблону ${W.pattern}`;return`Неправильний ${K[W.format]??Q.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${Q.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${Q.keys.length>1?"і":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${Q.origin}`;case"invalid_union":return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${Q.origin}`;default:return"Неправильні вхідні дані"}}};function Q0(){return{localeError:P_()}}function K5(){return Q0()}var N_=()=>{let $={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function U(Q){return $[Q]??null}let K={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"},q={nan:"NaN",number:"نمبر",array:"آرے",null:"نل"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`غلط ان پٹ: instanceof ${Q.expected} متوقع تھا، ${j} موصول ہوا`;return`غلط ان پٹ: ${W} متوقع تھا، ${j} موصول ہوا`}case"invalid_value":if(Q.values.length===1)return`غلط ان پٹ: ${v(Q.values[0])} متوقع تھا`;return`غلط آپشن: ${_(Q.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`بہت بڑا: ${Q.origin??"ویلیو"} کے ${W}${Q.maximum.toString()} ${G.unit??"عناصر"} ہونے متوقع تھے`;return`بہت بڑا: ${Q.origin??"ویلیو"} کا ${W}${Q.maximum.toString()} ہونا متوقع تھا`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`بہت چھوٹا: ${Q.origin} کے ${W}${Q.minimum.toString()} ${G.unit} ہونے متوقع تھے`;return`بہت چھوٹا: ${Q.origin} کا ${W}${Q.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`غلط سٹرنگ: "${W.prefix}" سے شروع ہونا چاہیے`;if(W.format==="ends_with")return`غلط سٹرنگ: "${W.suffix}" پر ختم ہونا چاہیے`;if(W.format==="includes")return`غلط سٹرنگ: "${W.includes}" شامل ہونا چاہیے`;if(W.format==="regex")return`غلط سٹرنگ: پیٹرن ${W.pattern} سے میچ ہونا چاہیے`;return`غلط ${K[W.format]??Q.format}`}case"not_multiple_of":return`غلط نمبر: ${Q.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${Q.keys.length>1?"ز":""}: ${_(Q.keys,"، ")}`;case"invalid_key":return`${Q.origin} میں غلط کی`;case"invalid_union":return"غلط ان پٹ";case"invalid_element":return`${Q.origin} میں غلط ویلیو`;default:return"غلط ان پٹ"}}};function q5(){return{localeError:N_()}}var L_=()=>{let $={string:{unit:"belgi",verb:"bo‘lishi kerak"},file:{unit:"bayt",verb:"bo‘lishi kerak"},array:{unit:"element",verb:"bo‘lishi kerak"},set:{unit:"element",verb:"bo‘lishi kerak"}};function U(Q){return $[Q]??null}let K={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},q={nan:"NaN",number:"raqam",array:"massiv"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Noto‘g‘ri kirish: kutilgan instanceof ${Q.expected}, qabul qilingan ${j}`;return`Noto‘g‘ri kirish: kutilgan ${W}, qabul qilingan ${j}`}case"invalid_value":if(Q.values.length===1)return`Noto‘g‘ri kirish: kutilgan ${v(Q.values[0])}`;return`Noto‘g‘ri variant: quyidagilardan biri kutilgan ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Juda katta: kutilgan ${Q.origin??"qiymat"} ${W}${Q.maximum.toString()} ${G.unit} ${G.verb}`;return`Juda katta: kutilgan ${Q.origin??"qiymat"} ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Juda kichik: kutilgan ${Q.origin} ${W}${Q.minimum.toString()} ${G.unit} ${G.verb}`;return`Juda kichik: kutilgan ${Q.origin} ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Noto‘g‘ri satr: "${W.prefix}" bilan boshlanishi kerak`;if(W.format==="ends_with")return`Noto‘g‘ri satr: "${W.suffix}" bilan tugashi kerak`;if(W.format==="includes")return`Noto‘g‘ri satr: "${W.includes}" ni o‘z ichiga olishi kerak`;if(W.format==="regex")return`Noto‘g‘ri satr: ${W.pattern} shabloniga mos kelishi kerak`;return`Noto‘g‘ri ${K[W.format]??Q.format}`}case"not_multiple_of":return`Noto‘g‘ri raqam: ${Q.divisor} ning karralisi bo‘lishi kerak`;case"unrecognized_keys":return`Noma’lum kalit${Q.keys.length>1?"lar":""}: ${_(Q.keys,", ")}`;case"invalid_key":return`${Q.origin} dagi kalit noto‘g‘ri`;case"invalid_union":return"Noto‘g‘ri kirish";case"invalid_element":return`${Q.origin} da noto‘g‘ri qiymat`;default:return"Noto‘g‘ri kirish"}}};function W5(){return{localeError:L_()}}var __=()=>{let $={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}};function U(Q){return $[Q]??null}let K={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"},q={nan:"NaN",number:"số",array:"mảng"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Đầu vào không hợp lệ: mong đợi instanceof ${Q.expected}, nhận được ${j}`;return`Đầu vào không hợp lệ: mong đợi ${W}, nhận được ${j}`}case"invalid_value":if(Q.values.length===1)return`Đầu vào không hợp lệ: mong đợi ${v(Q.values[0])}`;return`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Quá lớn: mong đợi ${Q.origin??"giá trị"} ${G.verb} ${W}${Q.maximum.toString()} ${G.unit??"phần tử"}`;return`Quá lớn: mong đợi ${Q.origin??"giá trị"} ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Quá nhỏ: mong đợi ${Q.origin} ${G.verb} ${W}${Q.minimum.toString()} ${G.unit}`;return`Quá nhỏ: mong đợi ${Q.origin} ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Chuỗi không hợp lệ: phải bắt đầu bằng "${W.prefix}"`;if(W.format==="ends_with")return`Chuỗi không hợp lệ: phải kết thúc bằng "${W.suffix}"`;if(W.format==="includes")return`Chuỗi không hợp lệ: phải bao gồm "${W.includes}"`;if(W.format==="regex")return`Chuỗi không hợp lệ: phải khớp với mẫu ${W.pattern}`;return`${K[W.format]??Q.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${Q.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${_(Q.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${Q.origin}`;case"invalid_union":return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${Q.origin}`;default:return"Đầu vào không hợp lệ"}}};function G5(){return{localeError:__()}}var I_=()=>{let $={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function U(Q){return $[Q]??null}let K={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"},q={nan:"NaN",number:"数字",array:"数组",null:"空值(null)"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`无效输入:期望 instanceof ${Q.expected},实际接收 ${j}`;return`无效输入:期望 ${W},实际接收 ${j}`}case"invalid_value":if(Q.values.length===1)return`无效输入:期望 ${v(Q.values[0])}`;return`无效选项:期望以下之一 ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`数值过大:期望 ${Q.origin??"值"} ${W}${Q.maximum.toString()} ${G.unit??"个元素"}`;return`数值过大:期望 ${Q.origin??"值"} ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`数值过小:期望 ${Q.origin} ${W}${Q.minimum.toString()} ${G.unit}`;return`数值过小:期望 ${Q.origin} ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`无效字符串:必须以 "${W.prefix}" 开头`;if(W.format==="ends_with")return`无效字符串:必须以 "${W.suffix}" 结尾`;if(W.format==="includes")return`无效字符串:必须包含 "${W.includes}"`;if(W.format==="regex")return`无效字符串:必须满足正则表达式 ${W.pattern}`;return`无效${K[W.format]??Q.format}`}case"not_multiple_of":return`无效数字:必须是 ${Q.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${_(Q.keys,", ")}`;case"invalid_key":return`${Q.origin} 中的键(key)无效`;case"invalid_union":return"无效输入";case"invalid_element":return`${Q.origin} 中包含无效值(value)`;default:return"无效输入"}}};function J5(){return{localeError:I_()}}var F_=()=>{let $={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function U(Q){return $[Q]??null}let K={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"},q={nan:"NaN"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`無效的輸入值:預期為 instanceof ${Q.expected},但收到 ${j}`;return`無效的輸入值:預期為 ${W},但收到 ${j}`}case"invalid_value":if(Q.values.length===1)return`無效的輸入值:預期為 ${v(Q.values[0])}`;return`無效的選項:預期為以下其中之一 ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`數值過大:預期 ${Q.origin??"值"} 應為 ${W}${Q.maximum.toString()} ${G.unit??"個元素"}`;return`數值過大:預期 ${Q.origin??"值"} 應為 ${W}${Q.maximum.toString()}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`數值過小:預期 ${Q.origin} 應為 ${W}${Q.minimum.toString()} ${G.unit}`;return`數值過小:預期 ${Q.origin} 應為 ${W}${Q.minimum.toString()}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`無效的字串:必須以 "${W.prefix}" 開頭`;if(W.format==="ends_with")return`無效的字串:必須以 "${W.suffix}" 結尾`;if(W.format==="includes")return`無效的字串:必須包含 "${W.includes}"`;if(W.format==="regex")return`無效的字串:必須符合格式 ${W.pattern}`;return`無效的 ${K[W.format]??Q.format}`}case"not_multiple_of":return`無效的數字:必須為 ${Q.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${Q.keys.length>1?"們":""}:${_(Q.keys,"、")}`;case"invalid_key":return`${Q.origin} 中有無效的鍵值`;case"invalid_union":return"無效的輸入值";case"invalid_element":return`${Q.origin} 中有無效的值`;default:return"無效的輸入值"}}};function j5(){return{localeError:F_()}}var x_=()=>{let $={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function U(Q){return $[Q]??null}let K={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"},q={nan:"NaN",number:"nọ́mbà",array:"akopọ"};return(Q)=>{switch(Q.code){case"invalid_type":{let W=q[Q.expected]??Q.expected,G=k(Q.input),j=q[G]??G;if(/^[A-Z]/.test(Q.expected))return`Ìbáwọlé aṣìṣe: a ní láti fi instanceof ${Q.expected}, àmọ̀ a rí ${j}`;return`Ìbáwọlé aṣìṣe: a ní láti fi ${W}, àmọ̀ a rí ${j}`}case"invalid_value":if(Q.values.length===1)return`Ìbáwọlé aṣìṣe: a ní láti fi ${v(Q.values[0])}`;return`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${_(Q.values,"|")}`;case"too_big":{let W=Q.inclusive?"<=":"<",G=U(Q.origin);if(G)return`Tó pọ̀ jù: a ní láti jẹ́ pé ${Q.origin??"iye"} ${G.verb} ${W}${Q.maximum} ${G.unit}`;return`Tó pọ̀ jù: a ní láti jẹ́ ${W}${Q.maximum}`}case"too_small":{let W=Q.inclusive?">=":">",G=U(Q.origin);if(G)return`Kéré ju: a ní láti jẹ́ pé ${Q.origin} ${G.verb} ${W}${Q.minimum} ${G.unit}`;return`Kéré ju: a ní láti jẹ́ ${W}${Q.minimum}`}case"invalid_format":{let W=Q;if(W.format==="starts_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${W.prefix}"`;if(W.format==="ends_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${W.suffix}"`;if(W.format==="includes")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${W.includes}"`;if(W.format==="regex")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${W.pattern}`;return`Aṣìṣe: ${K[W.format]??Q.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${Q.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${_(Q.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${Q.origin}`;case"invalid_union":return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${Q.origin}`;default:return"Ìbáwọlé aṣìṣe"}}};function Y5(){return{localeError:x_()}}var WY,H5=Symbol("ZodOutput"),X5=Symbol("ZodInput");class Z5{constructor(){this._map=new WeakMap,this._idmap=new Map}add($,...U){let K=U[0];if(this._map.set($,K),K&&typeof K==="object"&&"id"in K)this._idmap.set(K.id,$);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove($){let U=this._map.get($);if(U&&typeof U==="object"&&"id"in U)this._idmap.delete(U.id);return this._map.delete($),this}get($){let U=$._zod.parent;if(U){let K={...this.get(U)??{}};delete K.id;let q={...K,...this._map.get($)};return Object.keys(q).length?q:void 0}return this._map.get($)}has($){return this._map.has($)}}function v2(){return new Z5}(WY=globalThis).__zod_globalRegistry??(WY.__zod_globalRegistry=v2());var _$=globalThis.__zod_globalRegistry;function B5($,U){return new $({type:"string",...b(U)})}function V5($,U){return new $({type:"string",coerce:!0,...b(U)})}function k2($,U){return new $({type:"string",format:"email",check:"string_format",abort:!1,...b(U)})}function q0($,U){return new $({type:"string",format:"guid",check:"string_format",abort:!1,...b(U)})}function z2($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,...b(U)})}function R2($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...b(U)})}function b2($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...b(U)})}function O2($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...b(U)})}function W0($,U){return new $({type:"string",format:"url",check:"string_format",abort:!1,...b(U)})}function T2($,U){return new $({type:"string",format:"emoji",check:"string_format",abort:!1,...b(U)})}function S2($,U){return new $({type:"string",format:"nanoid",check:"string_format",abort:!1,...b(U)})}function C2($,U){return new $({type:"string",format:"cuid",check:"string_format",abort:!1,...b(U)})}function E2($,U){return new $({type:"string",format:"cuid2",check:"string_format",abort:!1,...b(U)})}function y2($,U){return new $({type:"string",format:"ulid",check:"string_format",abort:!1,...b(U)})}function g2($,U){return new $({type:"string",format:"xid",check:"string_format",abort:!1,...b(U)})}function u2($,U){return new $({type:"string",format:"ksuid",check:"string_format",abort:!1,...b(U)})}function f2($,U){return new $({type:"string",format:"ipv4",check:"string_format",abort:!1,...b(U)})}function m2($,U){return new $({type:"string",format:"ipv6",check:"string_format",abort:!1,...b(U)})}function M5($,U){return new $({type:"string",format:"mac",check:"string_format",abort:!1,...b(U)})}function h2($,U){return new $({type:"string",format:"cidrv4",check:"string_format",abort:!1,...b(U)})}function c2($,U){return new $({type:"string",format:"cidrv6",check:"string_format",abort:!1,...b(U)})}function l2($,U){return new $({type:"string",format:"base64",check:"string_format",abort:!1,...b(U)})}function r2($,U){return new $({type:"string",format:"base64url",check:"string_format",abort:!1,...b(U)})}function i2($,U){return new $({type:"string",format:"e164",check:"string_format",abort:!1,...b(U)})}function d2($,U){return new $({type:"string",format:"jwt",check:"string_format",abort:!1,...b(U)})}var D5={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function P5($,U){return new $({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...b(U)})}function N5($,U){return new $({type:"string",format:"date",check:"string_format",...b(U)})}function L5($,U){return new $({type:"string",format:"time",check:"string_format",precision:null,...b(U)})}function _5($,U){return new $({type:"string",format:"duration",check:"string_format",...b(U)})}function I5($,U){return new $({type:"number",checks:[],...b(U)})}function F5($,U){return new $({type:"number",coerce:!0,checks:[],...b(U)})}function x5($,U){return new $({type:"number",check:"number_format",abort:!1,format:"safeint",...b(U)})}function w5($,U){return new $({type:"number",check:"number_format",abort:!1,format:"float32",...b(U)})}function A5($,U){return new $({type:"number",check:"number_format",abort:!1,format:"float64",...b(U)})}function v5($,U){return new $({type:"number",check:"number_format",abort:!1,format:"int32",...b(U)})}function k5($,U){return new $({type:"number",check:"number_format",abort:!1,format:"uint32",...b(U)})}function z5($,U){return new $({type:"boolean",...b(U)})}function R5($,U){return new $({type:"boolean",coerce:!0,...b(U)})}function b5($,U){return new $({type:"bigint",...b(U)})}function O5($,U){return new $({type:"bigint",coerce:!0,...b(U)})}function T5($,U){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...b(U)})}function S5($,U){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...b(U)})}function C5($,U){return new $({type:"symbol",...b(U)})}function E5($,U){return new $({type:"undefined",...b(U)})}function y5($,U){return new $({type:"null",...b(U)})}function g5($){return new $({type:"any"})}function u5($){return new $({type:"unknown"})}function f5($,U){return new $({type:"never",...b(U)})}function m5($,U){return new $({type:"void",...b(U)})}function h5($,U){return new $({type:"date",...b(U)})}function c5($,U){return new $({type:"date",coerce:!0,...b(U)})}function l5($,U){return new $({type:"nan",...b(U)})}function X1($,U){return new V2({check:"less_than",...b(U),value:$,inclusive:!1})}function h$($,U){return new V2({check:"less_than",...b(U),value:$,inclusive:!0})}function Z1($,U){return new M2({check:"greater_than",...b(U),value:$,inclusive:!1})}function z$($,U){return new M2({check:"greater_than",...b(U),value:$,inclusive:!0})}function o2($){return Z1(0,$)}function n2($){return X1(0,$)}function p2($){return h$(0,$)}function t2($){return z$(0,$)}function u1($,U){return new lU({check:"multiple_of",...b(U),value:$})}function f1($,U){return new dU({check:"max_size",...b(U),maximum:$})}function B1($,U){return new oU({check:"min_size",...b(U),minimum:$})}function V4($,U){return new nU({check:"size_equals",...b(U),size:$})}function M4($,U){return new pU({check:"max_length",...b(U),maximum:$})}function v1($,U){return new tU({check:"min_length",...b(U),minimum:$})}function D4($,U){return new aU({check:"length_equals",...b(U),length:$})}function r4($,U){return new sU({check:"string_format",format:"regex",...b(U),pattern:$})}function i4($){return new eU({check:"string_format",format:"lowercase",...b($)})}function d4($){return new $9({check:"string_format",format:"uppercase",...b($)})}function o4($,U){return new U9({check:"string_format",format:"includes",...b(U),includes:$})}function n4($,U){return new Q9({check:"string_format",format:"starts_with",...b(U),prefix:$})}function p4($,U){return new K9({check:"string_format",format:"ends_with",...b(U),suffix:$})}function a2($,U,K){return new q9({check:"property",property:$,schema:U,...b(K)})}function t4($,U){return new W9({check:"mime_type",mime:$,...b(U)})}function q1($){return new G9({check:"overwrite",tx:$})}function a4($){return q1((U)=>U.normalize($))}function s4(){return q1(($)=>$.trim())}function e4(){return q1(($)=>$.toLowerCase())}function $6(){return q1(($)=>$.toUpperCase())}function U6(){return q1(($)=>qU($))}function r5($,U,K){return new $({type:"array",element:U,...b(K)})}function A_($,U,K){return new $({type:"union",options:U,...b(K)})}function v_($,U,K){return new $({type:"union",options:U,inclusive:!1,...b(K)})}function k_($,U,K,q){return new $({type:"union",options:K,discriminator:U,...b(q)})}function z_($,U,K){return new $({type:"intersection",left:U,right:K})}function R_($,U,K,q){let Q=K instanceof h;return new $({type:"tuple",items:U,rest:Q?K:null,...b(Q?q:K)})}function b_($,U,K,q){return new $({type:"record",keyType:U,valueType:K,...b(q)})}function O_($,U,K,q){return new $({type:"map",keyType:U,valueType:K,...b(q)})}function T_($,U,K){return new $({type:"set",valueType:U,...b(K)})}function S_($,U,K){let q=Array.isArray(U)?Object.fromEntries(U.map((Q)=>[Q,Q])):U;return new $({type:"enum",entries:q,...b(K)})}function C_($,U,K){return new $({type:"enum",entries:U,...b(K)})}function E_($,U,K){return new $({type:"literal",values:Array.isArray(U)?U:[U],...b(K)})}function i5($,U){return new $({type:"file",...b(U)})}function y_($,U){return new $({type:"transform",transform:U})}function g_($,U){return new $({type:"optional",innerType:U})}function u_($,U){return new $({type:"nullable",innerType:U})}function f_($,U,K){return new $({type:"default",innerType:U,get defaultValue(){return typeof K==="function"?K():GU(K)}})}function m_($,U,K){return new $({type:"nonoptional",innerType:U,...b(K)})}function h_($,U){return new $({type:"success",innerType:U})}function c_($,U,K){return new $({type:"catch",innerType:U,catchValue:typeof K==="function"?K:()=>K})}function l_($,U,K){return new $({type:"pipe",in:U,out:K})}function r_($,U){return new $({type:"readonly",innerType:U})}function i_($,U,K){return new $({type:"template_literal",parts:U,...b(K)})}function d_($,U){return new $({type:"lazy",getter:U})}function o_($,U){return new $({type:"promise",innerType:U})}function d5($,U,K){let q=b(K);return q.abort??(q.abort=!0),new $({type:"custom",check:"custom",fn:U,...q})}function o5($,U,K){return new $({type:"custom",check:"custom",fn:U,...b(K)})}function n5($){let U=GY((K)=>{return K.addIssue=(q)=>{if(typeof q==="string")K.issues.push(g4(q,K.value,U._zod.def));else{let Q=q;if(Q.fatal)Q.continue=!1;Q.code??(Q.code="custom"),Q.input??(Q.input=K.value),Q.inst??(Q.inst=U),Q.continue??(Q.continue=!U._zod.def.abort),K.issues.push(g4(Q))}},$(K.value,K)});return U}function GY($,U){let K=new $$({check:"custom",...b(U)});return K._zod.check=$,K}function p5($){let U=new $$({check:"describe"});return U._zod.onattach=[(K)=>{let q=_$.get(K)??{};_$.add(K,{...q,description:$})}],U._zod.check=()=>{},U}function t5($){let U=new $$({check:"meta"});return U._zod.onattach=[(K)=>{let q=_$.get(K)??{};_$.add(K,{...q,...$})}],U._zod.check=()=>{},U}function a5($,U){let K=b(U),q=K.truthy??["true","1","yes","on","y","enabled"],Q=K.falsy??["false","0","no","off","n","disabled"];if(K.case!=="sensitive")q=q.map((I)=>typeof I==="string"?I.toLowerCase():I),Q=Q.map((I)=>typeof I==="string"?I.toLowerCase():I);let W=new Set(q),G=new Set(Q),j=$.Codec??s6,Y=$.Boolean??t6,X=new($.String??B4)({type:"string",error:K.error}),B=new Y({type:"boolean",error:K.error}),M=new j({type:"pipe",in:X,out:B,transform:(I,E)=>{let u=I;if(K.case!=="sensitive")u=u.toLowerCase();if(W.has(u))return!0;else if(G.has(u))return!1;else return E.issues.push({code:"invalid_value",expected:"stringbool",values:[...W,...G],input:E.value,inst:M,continue:!1}),{}},reverseTransform:(I,E)=>{if(I===!0)return q[0]||"true";else return Q[0]||"false"},error:K.error});return M}function Q6($,U,K,q={}){let Q=b(q),W={...b(q),check:"string_format",type:"string",format:U,fn:typeof K==="function"?K:(j)=>K.test(j),...Q};if(K instanceof RegExp)W.pattern=K;return new $(W)}function m1($){let U=$?.target??"draft-2020-12";if(U==="draft-4")U="draft-04";if(U==="draft-7")U="draft-07";return{processors:$.processors??{},metadataRegistry:$?.metadata??_$,target:U,unrepresentable:$?.unrepresentable??"throw",override:$?.override??(()=>{}),io:$?.io??"output",counter:0,seen:new Map,cycles:$?.cycles??"ref",reused:$?.reused??"inline",external:$?.external??void 0}}function t($,U,K={path:[],schemaPath:[]}){var q;let Q=$._zod.def,W=U.seen.get($);if(W){if(W.count++,K.schemaPath.includes($))W.cycle=K.path;return W.schema}let G={schema:{},count:1,cycle:void 0,path:K.path};U.seen.set($,G);let j=$._zod.toJSONSchema?.();if(j)G.schema=j;else{let X={...K,schemaPath:[...K.schemaPath,$],path:K.path};if($._zod.processJSONSchema)$._zod.processJSONSchema(U,G.schema,X);else{let M=G.schema,I=U.processors[Q.type];if(!I)throw Error(`[toJSONSchema]: Non-representable type encountered: ${Q.type}`);I($,U,M,X)}let B=$._zod.parent;if(B){if(!G.ref)G.ref=B;t(B,U,X),U.seen.get(B).isParent=!0}}let Y=U.metadataRegistry.get($);if(Y)Object.assign(G.schema,Y);if(U.io==="input"&&R$($))delete G.schema.examples,delete G.schema.default;if(U.io==="input"&&G.schema._prefault)(q=G.schema).default??(q.default=G.schema._prefault);return delete G.schema._prefault,U.seen.get($).schema}function h1($,U){let K=$.seen.get(U);if(!K)throw Error("Unprocessed schema. This is a bug in Zod.");let q=new Map;for(let G of $.seen.entries()){let j=$.metadataRegistry.get(G[0])?.id;if(j){let Y=q.get(j);if(Y&&Y!==G[0])throw Error(`Duplicate schema id "${j}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);q.set(j,G[0])}}let Q=(G)=>{let j=$.target==="draft-2020-12"?"$defs":"definitions";if($.external){let B=$.external.registry.get(G[0])?.id,M=$.external.uri??((E)=>E);if(B)return{ref:M(B)};let I=G[1].defId??G[1].schema.id??`schema${$.counter++}`;return G[1].defId=I,{defId:I,ref:`${M("__shared")}#/${j}/${I}`}}if(G[1]===K)return{ref:"#"};let H=`${"#"}/${j}/`,X=G[1].schema.id??`__schema${$.counter++}`;return{defId:X,ref:H+X}},W=(G)=>{if(G[1].schema.$ref)return;let j=G[1],{ref:Y,defId:H}=Q(G);if(j.def={...j.schema},H)j.defId=H;let X=j.schema;for(let B in X)delete X[B];X.$ref=Y};if($.cycles==="throw")for(let G of $.seen.entries()){let j=G[1];if(j.cycle)throw Error(`Cycle detected: #/${j.cycle?.join("/")}/<root>
|
|
85
|
+
|
|
86
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let G of $.seen.entries()){let j=G[1];if(U===G[0]){W(G);continue}if($.external){let H=$.external.registry.get(G[0])?.id;if(U!==G[0]&&H){W(G);continue}}if($.metadataRegistry.get(G[0])?.id){W(G);continue}if(j.cycle){W(G);continue}if(j.count>1){if($.reused==="ref"){W(G);continue}}}}function c1($,U){let K=$.seen.get(U);if(!K)throw Error("Unprocessed schema. This is a bug in Zod.");let q=(G)=>{let j=$.seen.get(G);if(j.ref===null)return;let Y=j.def??j.schema,H={...Y},X=j.ref;if(j.ref=null,X){q(X);let M=$.seen.get(X),I=M.schema;if(I.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))Y.allOf=Y.allOf??[],Y.allOf.push(I);else Object.assign(Y,I);if(Object.assign(Y,H),G._zod.parent===X)for(let u in Y){if(u==="$ref"||u==="allOf")continue;if(!(u in H))delete Y[u]}if(I.$ref&&M.def)for(let u in Y){if(u==="$ref"||u==="allOf")continue;if(u in M.def&&JSON.stringify(Y[u])===JSON.stringify(M.def[u]))delete Y[u]}}let B=G._zod.parent;if(B&&B!==X){q(B);let M=$.seen.get(B);if(M?.schema.$ref){if(Y.$ref=M.schema.$ref,M.def)for(let I in Y){if(I==="$ref"||I==="allOf")continue;if(I in M.def&&JSON.stringify(Y[I])===JSON.stringify(M.def[I]))delete Y[I]}}}$.override({zodSchema:G,jsonSchema:Y,path:j.path??[]})};for(let G of[...$.seen.entries()].reverse())q(G[0]);let Q={};if($.target==="draft-2020-12")Q.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")Q.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")Q.$schema="http://json-schema.org/draft-04/schema#";else if($.target==="openapi-3.0");if($.external?.uri){let G=$.external.registry.get(U)?.id;if(!G)throw Error("Schema is missing an `id` property");Q.$id=$.external.uri(G)}Object.assign(Q,K.def??K.schema);let W=$.external?.defs??{};for(let G of $.seen.entries()){let j=G[1];if(j.def&&j.defId)W[j.defId]=j.def}if($.external);else if(Object.keys(W).length>0)if($.target==="draft-2020-12")Q.$defs=W;else Q.definitions=W;try{let G=JSON.parse(JSON.stringify(Q));return Object.defineProperty(G,"~standard",{value:{...U["~standard"],jsonSchema:{input:K6(U,"input",$.processors),output:K6(U,"output",$.processors)}},enumerable:!1,writable:!1}),G}catch(G){throw Error("Error converting schema to JSON.")}}function R$($,U){let K=U??{seen:new Set};if(K.seen.has($))return!1;K.seen.add($);let q=$._zod.def;if(q.type==="transform")return!0;if(q.type==="array")return R$(q.element,K);if(q.type==="set")return R$(q.valueType,K);if(q.type==="lazy")return R$(q.getter(),K);if(q.type==="promise"||q.type==="optional"||q.type==="nonoptional"||q.type==="nullable"||q.type==="readonly"||q.type==="default"||q.type==="prefault")return R$(q.innerType,K);if(q.type==="intersection")return R$(q.left,K)||R$(q.right,K);if(q.type==="record"||q.type==="map")return R$(q.keyType,K)||R$(q.valueType,K);if(q.type==="pipe")return R$(q.in,K)||R$(q.out,K);if(q.type==="object"){for(let Q in q.shape)if(R$(q.shape[Q],K))return!0;return!1}if(q.type==="union"){for(let Q of q.options)if(R$(Q,K))return!0;return!1}if(q.type==="tuple"){for(let Q of q.items)if(R$(Q,K))return!0;if(q.rest&&R$(q.rest,K))return!0;return!1}return!1}var s5=($,U={})=>(K)=>{let q=m1({...K,processors:U});return t($,q),h1(q,$),c1(q,$)},K6=($,U,K={})=>(q)=>{let{libraryOptions:Q,target:W}=q??{},G=m1({...Q??{},target:W,io:U,processors:K});return t($,G),h1(G,$),c1(G,$)};var n_={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},e5=($,U,K,q)=>{let Q=K;Q.type="string";let{minimum:W,maximum:G,format:j,patterns:Y,contentEncoding:H}=$._zod.bag;if(typeof W==="number")Q.minLength=W;if(typeof G==="number")Q.maxLength=G;if(j){if(Q.format=n_[j]??j,Q.format==="")delete Q.format;if(j==="time")delete Q.format}if(H)Q.contentEncoding=H;if(Y&&Y.size>0){let X=[...Y];if(X.length===1)Q.pattern=X[0].source;else if(X.length>1)Q.allOf=[...X.map((B)=>({...U.target==="draft-07"||U.target==="draft-04"||U.target==="openapi-3.0"?{type:"string"}:{},pattern:B.source}))]}},$Q=($,U,K,q)=>{let Q=K,{minimum:W,maximum:G,format:j,multipleOf:Y,exclusiveMaximum:H,exclusiveMinimum:X}=$._zod.bag;if(typeof j==="string"&&j.includes("int"))Q.type="integer";else Q.type="number";if(typeof X==="number")if(U.target==="draft-04"||U.target==="openapi-3.0")Q.minimum=X,Q.exclusiveMinimum=!0;else Q.exclusiveMinimum=X;if(typeof W==="number"){if(Q.minimum=W,typeof X==="number"&&U.target!=="draft-04")if(X>=W)delete Q.minimum;else delete Q.exclusiveMinimum}if(typeof H==="number")if(U.target==="draft-04"||U.target==="openapi-3.0")Q.maximum=H,Q.exclusiveMaximum=!0;else Q.exclusiveMaximum=H;if(typeof G==="number"){if(Q.maximum=G,typeof H==="number"&&U.target!=="draft-04")if(H<=G)delete Q.maximum;else delete Q.exclusiveMaximum}if(typeof Y==="number")Q.multipleOf=Y},UQ=($,U,K,q)=>{K.type="boolean"},QQ=($,U,K,q)=>{if(U.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},KQ=($,U,K,q)=>{if(U.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},qQ=($,U,K,q)=>{if(U.target==="openapi-3.0")K.type="string",K.nullable=!0,K.enum=[null];else K.type="null"},WQ=($,U,K,q)=>{if(U.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},GQ=($,U,K,q)=>{if(U.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},JQ=($,U,K,q)=>{K.not={}},jQ=($,U,K,q)=>{},YQ=($,U,K,q)=>{},HQ=($,U,K,q)=>{if(U.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},XQ=($,U,K,q)=>{let Q=$._zod.def,W=f6(Q.entries);if(W.every((G)=>typeof G==="number"))K.type="number";if(W.every((G)=>typeof G==="string"))K.type="string";K.enum=W},ZQ=($,U,K,q)=>{let Q=$._zod.def,W=[];for(let G of Q.values)if(G===void 0){if(U.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof G==="bigint")if(U.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else W.push(Number(G));else W.push(G);if(W.length===0);else if(W.length===1){let G=W[0];if(K.type=G===null?"null":typeof G,U.target==="draft-04"||U.target==="openapi-3.0")K.enum=[G];else K.const=G}else{if(W.every((G)=>typeof G==="number"))K.type="number";if(W.every((G)=>typeof G==="string"))K.type="string";if(W.every((G)=>typeof G==="boolean"))K.type="boolean";if(W.every((G)=>G===null))K.type="null";K.enum=W}},BQ=($,U,K,q)=>{if(U.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},VQ=($,U,K,q)=>{let Q=K,W=$._zod.pattern;if(!W)throw Error("Pattern not found in template literal");Q.type="string",Q.pattern=W.source},MQ=($,U,K,q)=>{let Q=K,W={type:"string",format:"binary",contentEncoding:"binary"},{minimum:G,maximum:j,mime:Y}=$._zod.bag;if(G!==void 0)W.minLength=G;if(j!==void 0)W.maxLength=j;if(Y)if(Y.length===1)W.contentMediaType=Y[0],Object.assign(Q,W);else Object.assign(Q,W),Q.anyOf=Y.map((H)=>({contentMediaType:H}));else Object.assign(Q,W)},DQ=($,U,K,q)=>{K.type="boolean"},PQ=($,U,K,q)=>{if(U.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},NQ=($,U,K,q)=>{if(U.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},LQ=($,U,K,q)=>{if(U.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},_Q=($,U,K,q)=>{if(U.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},IQ=($,U,K,q)=>{if(U.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},FQ=($,U,K,q)=>{let Q=K,W=$._zod.def,{minimum:G,maximum:j}=$._zod.bag;if(typeof G==="number")Q.minItems=G;if(typeof j==="number")Q.maxItems=j;Q.type="array",Q.items=t(W.element,U,{...q,path:[...q.path,"items"]})},xQ=($,U,K,q)=>{let Q=K,W=$._zod.def;Q.type="object",Q.properties={};let G=W.shape;for(let H in G)Q.properties[H]=t(G[H],U,{...q,path:[...q.path,"properties",H]});let j=new Set(Object.keys(G)),Y=new Set([...j].filter((H)=>{let X=W.shape[H]._zod;if(U.io==="input")return X.optin===void 0;else return X.optout===void 0}));if(Y.size>0)Q.required=Array.from(Y);if(W.catchall?._zod.def.type==="never")Q.additionalProperties=!1;else if(!W.catchall){if(U.io==="output")Q.additionalProperties=!1}else if(W.catchall)Q.additionalProperties=t(W.catchall,U,{...q,path:[...q.path,"additionalProperties"]})},e2=($,U,K,q)=>{let Q=$._zod.def,W=Q.inclusive===!1,G=Q.options.map((j,Y)=>t(j,U,{...q,path:[...q.path,W?"oneOf":"anyOf",Y]}));if(W)K.oneOf=G;else K.anyOf=G},wQ=($,U,K,q)=>{let Q=$._zod.def,W=t(Q.left,U,{...q,path:[...q.path,"allOf",0]}),G=t(Q.right,U,{...q,path:[...q.path,"allOf",1]}),j=(H)=>("allOf"in H)&&Object.keys(H).length===1,Y=[...j(W)?W.allOf:[W],...j(G)?G.allOf:[G]];K.allOf=Y},AQ=($,U,K,q)=>{let Q=K,W=$._zod.def;Q.type="array";let G=U.target==="draft-2020-12"?"prefixItems":"items",j=U.target==="draft-2020-12"?"items":U.target==="openapi-3.0"?"items":"additionalItems",Y=W.items.map((M,I)=>t(M,U,{...q,path:[...q.path,G,I]})),H=W.rest?t(W.rest,U,{...q,path:[...q.path,j,...U.target==="openapi-3.0"?[W.items.length]:[]]}):null;if(U.target==="draft-2020-12"){if(Q.prefixItems=Y,H)Q.items=H}else if(U.target==="openapi-3.0"){if(Q.items={anyOf:Y},H)Q.items.anyOf.push(H);if(Q.minItems=Y.length,!H)Q.maxItems=Y.length}else if(Q.items=Y,H)Q.additionalItems=H;let{minimum:X,maximum:B}=$._zod.bag;if(typeof X==="number")Q.minItems=X;if(typeof B==="number")Q.maxItems=B},vQ=($,U,K,q)=>{let Q=K,W=$._zod.def;Q.type="object";let G=W.keyType,Y=G._zod.bag?.patterns;if(W.mode==="loose"&&Y&&Y.size>0){let X=t(W.valueType,U,{...q,path:[...q.path,"patternProperties","*"]});Q.patternProperties={};for(let B of Y)Q.patternProperties[B.source]=X}else{if(U.target==="draft-07"||U.target==="draft-2020-12")Q.propertyNames=t(W.keyType,U,{...q,path:[...q.path,"propertyNames"]});Q.additionalProperties=t(W.valueType,U,{...q,path:[...q.path,"additionalProperties"]})}let H=G._zod.values;if(H){let X=[...H].filter((B)=>typeof B==="string"||typeof B==="number");if(X.length>0)Q.required=X}},kQ=($,U,K,q)=>{let Q=$._zod.def,W=t(Q.innerType,U,q),G=U.seen.get($);if(U.target==="openapi-3.0")G.ref=Q.innerType,K.nullable=!0;else K.anyOf=[W,{type:"null"}]},zQ=($,U,K,q)=>{let Q=$._zod.def;t(Q.innerType,U,q);let W=U.seen.get($);W.ref=Q.innerType},RQ=($,U,K,q)=>{let Q=$._zod.def;t(Q.innerType,U,q);let W=U.seen.get($);W.ref=Q.innerType,K.default=JSON.parse(JSON.stringify(Q.defaultValue))},bQ=($,U,K,q)=>{let Q=$._zod.def;t(Q.innerType,U,q);let W=U.seen.get($);if(W.ref=Q.innerType,U.io==="input")K._prefault=JSON.parse(JSON.stringify(Q.defaultValue))},OQ=($,U,K,q)=>{let Q=$._zod.def;t(Q.innerType,U,q);let W=U.seen.get($);W.ref=Q.innerType;let G;try{G=Q.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}K.default=G},TQ=($,U,K,q)=>{let Q=$._zod.def,W=U.io==="input"?Q.in._zod.def.type==="transform"?Q.out:Q.in:Q.out;t(W,U,q);let G=U.seen.get($);G.ref=W},SQ=($,U,K,q)=>{let Q=$._zod.def;t(Q.innerType,U,q);let W=U.seen.get($);W.ref=Q.innerType,K.readOnly=!0},CQ=($,U,K,q)=>{let Q=$._zod.def;t(Q.innerType,U,q);let W=U.seen.get($);W.ref=Q.innerType},$3=($,U,K,q)=>{let Q=$._zod.def;t(Q.innerType,U,q);let W=U.seen.get($);W.ref=Q.innerType},EQ=($,U,K,q)=>{let Q=$._zod.innerType;t(Q,U,q);let W=U.seen.get($);W.ref=Q},s2={string:e5,number:$Q,boolean:UQ,bigint:QQ,symbol:KQ,null:qQ,undefined:WQ,void:GQ,never:JQ,any:jQ,unknown:YQ,date:HQ,enum:XQ,literal:ZQ,nan:BQ,template_literal:VQ,file:MQ,success:DQ,custom:PQ,function:NQ,transform:LQ,map:_Q,set:IQ,array:FQ,object:xQ,union:e2,intersection:wQ,tuple:AQ,record:vQ,nullable:kQ,nonoptional:zQ,default:RQ,prefault:bQ,catch:OQ,pipe:TQ,readonly:SQ,promise:CQ,optional:$3,lazy:EQ};function U3($,U){if("_idmap"in $){let q=$,Q=m1({...U,processors:s2}),W={};for(let Y of q._idmap.entries()){let[H,X]=Y;t(X,Q)}let G={},j={registry:q,uri:U?.uri,defs:W};Q.external=j;for(let Y of q._idmap.entries()){let[H,X]=Y;h1(Q,X),G[H]=c1(Q,X)}if(Object.keys(W).length>0){let Y=Q.target==="draft-2020-12"?"$defs":"definitions";G.__shared={[Y]:W}}return{schemas:G}}let K=m1({...U,processors:s2});return t($,K),h1(K,$),c1(K,$)}class yQ{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter($){this.ctx.counter=$}get seen(){return this.ctx.seen}constructor($){let U=$?.target??"draft-2020-12";if(U==="draft-4")U="draft-04";if(U==="draft-7")U="draft-07";this.ctx=m1({processors:s2,target:U,...$?.metadata&&{metadata:$.metadata},...$?.unrepresentable&&{unrepresentable:$.unrepresentable},...$?.override&&{override:$.override},...$?.io&&{io:$.io}})}process($,U={path:[],schemaPath:[]}){return t($,this.ctx,U)}emit($,U){if(U){if(U.cycles)this.ctx.cycles=U.cycles;if(U.reused)this.ctx.reused=U.reused;if(U.external)this.ctx.external=U.external}h1(this.ctx,$);let K=c1(this.ctx,$),{"~standard":q,...Q}=K;return Q}}var JY={};var G0={};L1(G0,{xor:()=>eY,xid:()=>FY,void:()=>oY,uuidv7:()=>VY,uuidv6:()=>BY,uuidv4:()=>ZY,uuid:()=>XY,url:()=>MY,unknown:()=>P4,union:()=>z3,undefined:()=>iY,ulid:()=>IY,uint64:()=>lY,uint32:()=>mY,tuple:()=>DK,transform:()=>b3,templateLiteral:()=>ZH,symbol:()=>rY,superRefine:()=>lK,success:()=>YH,stringbool:()=>_H,stringFormat:()=>SY,string:()=>J3,strictObject:()=>aY,set:()=>qH,refine:()=>cK,record:()=>PK,readonly:()=>yK,promise:()=>BH,preprocess:()=>FH,prefault:()=>RK,pipe:()=>H0,partialRecord:()=>UH,optional:()=>j0,object:()=>tY,number:()=>$K,nullish:()=>jH,nullable:()=>Y0,null:()=>WK,nonoptional:()=>bK,never:()=>k3,nativeEnum:()=>WH,nanoid:()=>NY,nan:()=>HH,meta:()=>NH,map:()=>KH,mac:()=>AY,looseRecord:()=>QH,looseObject:()=>sY,literal:()=>GH,lazy:()=>fK,ksuid:()=>xY,keyof:()=>pY,jwt:()=>TY,json:()=>IH,ipv6:()=>vY,ipv4:()=>wY,intersection:()=>VK,int64:()=>cY,int32:()=>fY,int:()=>j3,instanceof:()=>LH,httpUrl:()=>DY,hostname:()=>CY,hex:()=>EY,hash:()=>yY,guid:()=>HY,function:()=>VH,float64:()=>uY,float32:()=>gY,file:()=>JH,exactOptional:()=>wK,enum:()=>R3,emoji:()=>PY,email:()=>YY,e164:()=>OY,discriminatedUnion:()=>$H,describe:()=>PH,date:()=>nY,custom:()=>DH,cuid2:()=>_Y,cuid:()=>LY,codec:()=>XH,cidrv6:()=>zY,cidrv4:()=>kY,check:()=>MH,catch:()=>SK,boolean:()=>UK,bigint:()=>hY,base64url:()=>bY,base64:()=>RY,array:()=>B0,any:()=>dY,_function:()=>VH,_default:()=>kK,_ZodString:()=>Y3,ZodXor:()=>XK,ZodXID:()=>D3,ZodVoid:()=>YK,ZodUnknown:()=>JK,ZodUnion:()=>M0,ZodUndefined:()=>KK,ZodUUID:()=>V1,ZodURL:()=>X0,ZodULID:()=>M3,ZodType:()=>c,ZodTuple:()=>MK,ZodTransform:()=>FK,ZodTemplateLiteral:()=>gK,ZodSymbol:()=>QK,ZodSuccess:()=>OK,ZodStringFormat:()=>e,ZodString:()=>G6,ZodSet:()=>LK,ZodRecord:()=>D0,ZodReadonly:()=>EK,ZodPromise:()=>mK,ZodPrefault:()=>zK,ZodPipe:()=>S3,ZodOptional:()=>O3,ZodObject:()=>V0,ZodNumberFormat:()=>N4,ZodNumber:()=>j6,ZodNullable:()=>AK,ZodNull:()=>qK,ZodNonOptional:()=>T3,ZodNever:()=>jK,ZodNanoID:()=>Z3,ZodNaN:()=>CK,ZodMap:()=>NK,ZodMAC:()=>eQ,ZodLiteral:()=>_K,ZodLazy:()=>uK,ZodKSUID:()=>P3,ZodJWT:()=>A3,ZodIntersection:()=>BK,ZodIPv6:()=>L3,ZodIPv4:()=>N3,ZodGUID:()=>J0,ZodFunction:()=>hK,ZodFile:()=>IK,ZodExactOptional:()=>xK,ZodEnum:()=>W6,ZodEmoji:()=>X3,ZodEmail:()=>H3,ZodE164:()=>w3,ZodDiscriminatedUnion:()=>ZK,ZodDefault:()=>vK,ZodDate:()=>Z0,ZodCustomStringFormat:()=>J6,ZodCustom:()=>P0,ZodCodec:()=>C3,ZodCatch:()=>TK,ZodCUID2:()=>V3,ZodCUID:()=>B3,ZodCIDRv6:()=>I3,ZodCIDRv4:()=>_3,ZodBoolean:()=>Y6,ZodBigIntFormat:()=>v3,ZodBigInt:()=>H6,ZodBase64URL:()=>x3,ZodBase64:()=>F3,ZodArray:()=>HK,ZodAny:()=>GK});var Q3={};L1(Q3,{uppercase:()=>d4,trim:()=>s4,toUpperCase:()=>$6,toLowerCase:()=>e4,startsWith:()=>n4,slugify:()=>U6,size:()=>V4,regex:()=>r4,property:()=>a2,positive:()=>o2,overwrite:()=>q1,normalize:()=>a4,nonpositive:()=>p2,nonnegative:()=>t2,negative:()=>n2,multipleOf:()=>u1,minSize:()=>B1,minLength:()=>v1,mime:()=>t4,maxSize:()=>f1,maxLength:()=>M4,lte:()=>h$,lt:()=>X1,lowercase:()=>i4,length:()=>D4,includes:()=>o4,gte:()=>z$,gt:()=>Z1,endsWith:()=>p4});var q6={};L1(q6,{time:()=>fQ,duration:()=>mQ,datetime:()=>gQ,date:()=>uQ,ZodISOTime:()=>W3,ZodISODuration:()=>G3,ZodISODateTime:()=>K3,ZodISODate:()=>q3});var K3=D("ZodISODateTime",($,U)=>{_9.init($,U),e.init($,U)});function gQ($){return P5(K3,$)}var q3=D("ZodISODate",($,U)=>{I9.init($,U),e.init($,U)});function uQ($){return N5(q3,$)}var W3=D("ZodISOTime",($,U)=>{F9.init($,U),e.init($,U)});function fQ($){return L5(W3,$)}var G3=D("ZodISODuration",($,U)=>{x9.init($,U),e.init($,U)});function mQ($){return _5(G3,$)}var jY=($,U)=>{r6.init($,U),$.name="ZodError",Object.defineProperties($,{format:{value:(K)=>d6($,K)},flatten:{value:(K)=>i6($,K)},addIssue:{value:(K)=>{$.issues.push(K),$.message=JSON.stringify($.issues,E4,2)}},addIssues:{value:(K)=>{$.issues.push(...K),$.message=JSON.stringify($.issues,E4,2)}},isEmpty:{get(){return $.issues.length===0}}})},t_=D("ZodError",jY),g$=D("ZodError",jY,{Parent:Error});var hQ=u4(g$),cQ=f4(g$),lQ=m4(g$),rQ=h4(g$),iQ=W2(g$),dQ=G2(g$),oQ=J2(g$),nQ=j2(g$),pQ=Y2(g$),tQ=H2(g$),aQ=X2(g$),sQ=Z2(g$);var c=D("ZodType",($,U)=>{return h.init($,U),Object.assign($["~standard"],{jsonSchema:{input:K6($,"input"),output:K6($,"output")}}),$.toJSONSchema=s5($,{}),$.def=U,$.type=U.type,Object.defineProperty($,"_def",{value:U}),$.check=(...K)=>{return $.clone(z.mergeDefs(U,{checks:[...U.checks??[],...K.map((q)=>typeof q==="function"?{_zod:{check:q,def:{check:"custom"},onattach:[]}}:q)]}),{parent:!0})},$.with=$.check,$.clone=(K,q)=>k$($,K,q),$.brand=()=>$,$.register=(K,q)=>{return K.add($,q),$},$.parse=(K,q)=>hQ($,K,q,{callee:$.parse}),$.safeParse=(K,q)=>lQ($,K,q),$.parseAsync=async(K,q)=>cQ($,K,q,{callee:$.parseAsync}),$.safeParseAsync=async(K,q)=>rQ($,K,q),$.spa=$.safeParseAsync,$.encode=(K,q)=>iQ($,K,q),$.decode=(K,q)=>dQ($,K,q),$.encodeAsync=async(K,q)=>oQ($,K,q),$.decodeAsync=async(K,q)=>nQ($,K,q),$.safeEncode=(K,q)=>pQ($,K,q),$.safeDecode=(K,q)=>tQ($,K,q),$.safeEncodeAsync=async(K,q)=>aQ($,K,q),$.safeDecodeAsync=async(K,q)=>sQ($,K,q),$.refine=(K,q)=>$.check(cK(K,q)),$.superRefine=(K)=>$.check(lK(K)),$.overwrite=(K)=>$.check(q1(K)),$.optional=()=>j0($),$.exactOptional=()=>wK($),$.nullable=()=>Y0($),$.nullish=()=>j0(Y0($)),$.nonoptional=(K)=>bK($,K),$.array=()=>B0($),$.or=(K)=>z3([$,K]),$.and=(K)=>VK($,K),$.transform=(K)=>H0($,b3(K)),$.default=(K)=>kK($,K),$.prefault=(K)=>RK($,K),$.catch=(K)=>SK($,K),$.pipe=(K)=>H0($,K),$.readonly=()=>yK($),$.describe=(K)=>{let q=$.clone();return _$.add(q,{description:K}),q},Object.defineProperty($,"description",{get(){return _$.get($)?.description},configurable:!0}),$.meta=(...K)=>{if(K.length===0)return _$.get($);let q=$.clone();return _$.add(q,K[0]),q},$.isOptional=()=>$.safeParse(void 0).success,$.isNullable=()=>$.safeParse(null).success,$.apply=(K)=>K($),$}),Y3=D("_ZodString",($,U)=>{B4.init($,U),c.init($,U),$._zod.processJSONSchema=(q,Q,W)=>e5($,q,Q,W);let K=$._zod.bag;$.format=K.format??null,$.minLength=K.minimum??null,$.maxLength=K.maximum??null,$.regex=(...q)=>$.check(r4(...q)),$.includes=(...q)=>$.check(o4(...q)),$.startsWith=(...q)=>$.check(n4(...q)),$.endsWith=(...q)=>$.check(p4(...q)),$.min=(...q)=>$.check(v1(...q)),$.max=(...q)=>$.check(M4(...q)),$.length=(...q)=>$.check(D4(...q)),$.nonempty=(...q)=>$.check(v1(1,...q)),$.lowercase=(q)=>$.check(i4(q)),$.uppercase=(q)=>$.check(d4(q)),$.trim=()=>$.check(s4()),$.normalize=(...q)=>$.check(a4(...q)),$.toLowerCase=()=>$.check(e4()),$.toUpperCase=()=>$.check($6()),$.slugify=()=>$.check(U6())}),G6=D("ZodString",($,U)=>{B4.init($,U),Y3.init($,U),$.email=(K)=>$.check(k2(H3,K)),$.url=(K)=>$.check(W0(X0,K)),$.jwt=(K)=>$.check(d2(A3,K)),$.emoji=(K)=>$.check(T2(X3,K)),$.guid=(K)=>$.check(q0(J0,K)),$.uuid=(K)=>$.check(z2(V1,K)),$.uuidv4=(K)=>$.check(R2(V1,K)),$.uuidv6=(K)=>$.check(b2(V1,K)),$.uuidv7=(K)=>$.check(O2(V1,K)),$.nanoid=(K)=>$.check(S2(Z3,K)),$.guid=(K)=>$.check(q0(J0,K)),$.cuid=(K)=>$.check(C2(B3,K)),$.cuid2=(K)=>$.check(E2(V3,K)),$.ulid=(K)=>$.check(y2(M3,K)),$.base64=(K)=>$.check(l2(F3,K)),$.base64url=(K)=>$.check(r2(x3,K)),$.xid=(K)=>$.check(g2(D3,K)),$.ksuid=(K)=>$.check(u2(P3,K)),$.ipv4=(K)=>$.check(f2(N3,K)),$.ipv6=(K)=>$.check(m2(L3,K)),$.cidrv4=(K)=>$.check(h2(_3,K)),$.cidrv6=(K)=>$.check(c2(I3,K)),$.e164=(K)=>$.check(i2(w3,K)),$.datetime=(K)=>$.check(gQ(K)),$.date=(K)=>$.check(uQ(K)),$.time=(K)=>$.check(fQ(K)),$.duration=(K)=>$.check(mQ(K))});function J3($){return B5(G6,$)}var e=D("ZodStringFormat",($,U)=>{s.init($,U),Y3.init($,U)}),H3=D("ZodEmail",($,U)=>{X9.init($,U),e.init($,U)});function YY($){return k2(H3,$)}var J0=D("ZodGUID",($,U)=>{Y9.init($,U),e.init($,U)});function HY($){return q0(J0,$)}var V1=D("ZodUUID",($,U)=>{H9.init($,U),e.init($,U)});function XY($){return z2(V1,$)}function ZY($){return R2(V1,$)}function BY($){return b2(V1,$)}function VY($){return O2(V1,$)}var X0=D("ZodURL",($,U)=>{Z9.init($,U),e.init($,U)});function MY($){return W0(X0,$)}function DY($){return W0(X0,{protocol:/^https?$/,hostname:n$.domain,...z.normalizeParams($)})}var X3=D("ZodEmoji",($,U)=>{B9.init($,U),e.init($,U)});function PY($){return T2(X3,$)}var Z3=D("ZodNanoID",($,U)=>{V9.init($,U),e.init($,U)});function NY($){return S2(Z3,$)}var B3=D("ZodCUID",($,U)=>{M9.init($,U),e.init($,U)});function LY($){return C2(B3,$)}var V3=D("ZodCUID2",($,U)=>{D9.init($,U),e.init($,U)});function _Y($){return E2(V3,$)}var M3=D("ZodULID",($,U)=>{P9.init($,U),e.init($,U)});function IY($){return y2(M3,$)}var D3=D("ZodXID",($,U)=>{N9.init($,U),e.init($,U)});function FY($){return g2(D3,$)}var P3=D("ZodKSUID",($,U)=>{L9.init($,U),e.init($,U)});function xY($){return u2(P3,$)}var N3=D("ZodIPv4",($,U)=>{w9.init($,U),e.init($,U)});function wY($){return f2(N3,$)}var eQ=D("ZodMAC",($,U)=>{v9.init($,U),e.init($,U)});function AY($){return M5(eQ,$)}var L3=D("ZodIPv6",($,U)=>{A9.init($,U),e.init($,U)});function vY($){return m2(L3,$)}var _3=D("ZodCIDRv4",($,U)=>{k9.init($,U),e.init($,U)});function kY($){return h2(_3,$)}var I3=D("ZodCIDRv6",($,U)=>{z9.init($,U),e.init($,U)});function zY($){return c2(I3,$)}var F3=D("ZodBase64",($,U)=>{b9.init($,U),e.init($,U)});function RY($){return l2(F3,$)}var x3=D("ZodBase64URL",($,U)=>{O9.init($,U),e.init($,U)});function bY($){return r2(x3,$)}var w3=D("ZodE164",($,U)=>{T9.init($,U),e.init($,U)});function OY($){return i2(w3,$)}var A3=D("ZodJWT",($,U)=>{S9.init($,U),e.init($,U)});function TY($){return d2(A3,$)}var J6=D("ZodCustomStringFormat",($,U)=>{C9.init($,U),e.init($,U)});function SY($,U,K={}){return Q6(J6,$,U,K)}function CY($){return Q6(J6,"hostname",n$.hostname,$)}function EY($){return Q6(J6,"hex",n$.hex,$)}function yY($,U){let K=U?.enc??"hex",q=`${$}_${K}`,Q=n$[q];if(!Q)throw Error(`Unrecognized hash format: ${q}`);return Q6(J6,q,Q,U)}var j6=D("ZodNumber",($,U)=>{F2.init($,U),c.init($,U),$._zod.processJSONSchema=(q,Q,W)=>$Q($,q,Q,W),$.gt=(q,Q)=>$.check(Z1(q,Q)),$.gte=(q,Q)=>$.check(z$(q,Q)),$.min=(q,Q)=>$.check(z$(q,Q)),$.lt=(q,Q)=>$.check(X1(q,Q)),$.lte=(q,Q)=>$.check(h$(q,Q)),$.max=(q,Q)=>$.check(h$(q,Q)),$.int=(q)=>$.check(j3(q)),$.safe=(q)=>$.check(j3(q)),$.positive=(q)=>$.check(Z1(0,q)),$.nonnegative=(q)=>$.check(z$(0,q)),$.negative=(q)=>$.check(X1(0,q)),$.nonpositive=(q)=>$.check(h$(0,q)),$.multipleOf=(q,Q)=>$.check(u1(q,Q)),$.step=(q,Q)=>$.check(u1(q,Q)),$.finite=()=>$;let K=$._zod.bag;$.minValue=Math.max(K.minimum??Number.NEGATIVE_INFINITY,K.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,$.maxValue=Math.min(K.maximum??Number.POSITIVE_INFINITY,K.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,$.isInt=(K.format??"").includes("int")||Number.isSafeInteger(K.multipleOf??0.5),$.isFinite=!0,$.format=K.format??null});function $K($){return I5(j6,$)}var N4=D("ZodNumberFormat",($,U)=>{E9.init($,U),j6.init($,U)});function j3($){return x5(N4,$)}function gY($){return w5(N4,$)}function uY($){return A5(N4,$)}function fY($){return v5(N4,$)}function mY($){return k5(N4,$)}var Y6=D("ZodBoolean",($,U)=>{t6.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>UQ($,K,q,Q)});function UK($){return z5(Y6,$)}var H6=D("ZodBigInt",($,U)=>{x2.init($,U),c.init($,U),$._zod.processJSONSchema=(q,Q,W)=>QQ($,q,Q,W),$.gte=(q,Q)=>$.check(z$(q,Q)),$.min=(q,Q)=>$.check(z$(q,Q)),$.gt=(q,Q)=>$.check(Z1(q,Q)),$.gte=(q,Q)=>$.check(z$(q,Q)),$.min=(q,Q)=>$.check(z$(q,Q)),$.lt=(q,Q)=>$.check(X1(q,Q)),$.lte=(q,Q)=>$.check(h$(q,Q)),$.max=(q,Q)=>$.check(h$(q,Q)),$.positive=(q)=>$.check(Z1(BigInt(0),q)),$.negative=(q)=>$.check(X1(BigInt(0),q)),$.nonpositive=(q)=>$.check(h$(BigInt(0),q)),$.nonnegative=(q)=>$.check(z$(BigInt(0),q)),$.multipleOf=(q,Q)=>$.check(u1(q,Q));let K=$._zod.bag;$.minValue=K.minimum??null,$.maxValue=K.maximum??null,$.format=K.format??null});function hY($){return b5(H6,$)}var v3=D("ZodBigIntFormat",($,U)=>{y9.init($,U),H6.init($,U)});function cY($){return T5(v3,$)}function lY($){return S5(v3,$)}var QK=D("ZodSymbol",($,U)=>{g9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>KQ($,K,q,Q)});function rY($){return C5(QK,$)}var KK=D("ZodUndefined",($,U)=>{u9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>WQ($,K,q,Q)});function iY($){return E5(KK,$)}var qK=D("ZodNull",($,U)=>{f9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>qQ($,K,q,Q)});function WK($){return y5(qK,$)}var GK=D("ZodAny",($,U)=>{m9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>jQ($,K,q,Q)});function dY(){return g5(GK)}var JK=D("ZodUnknown",($,U)=>{h9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>YQ($,K,q,Q)});function P4(){return u5(JK)}var jK=D("ZodNever",($,U)=>{c9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>JQ($,K,q,Q)});function k3($){return f5(jK,$)}var YK=D("ZodVoid",($,U)=>{l9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>GQ($,K,q,Q)});function oY($){return m5(YK,$)}var Z0=D("ZodDate",($,U)=>{r9.init($,U),c.init($,U),$._zod.processJSONSchema=(q,Q,W)=>HQ($,q,Q,W),$.min=(q,Q)=>$.check(z$(q,Q)),$.max=(q,Q)=>$.check(h$(q,Q));let K=$._zod.bag;$.minDate=K.minimum?new Date(K.minimum):null,$.maxDate=K.maximum?new Date(K.maximum):null});function nY($){return h5(Z0,$)}var HK=D("ZodArray",($,U)=>{i9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>FQ($,K,q,Q),$.element=U.element,$.min=(K,q)=>$.check(v1(K,q)),$.nonempty=(K)=>$.check(v1(1,K)),$.max=(K,q)=>$.check(M4(K,q)),$.length=(K,q)=>$.check(D4(K,q)),$.unwrap=()=>$.element});function B0($,U){return r5(HK,$,U)}function pY($){let U=$._zod.def.shape;return R3(Object.keys(U))}var V0=D("ZodObject",($,U)=>{d9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>xQ($,K,q,Q),z.defineLazy($,"shape",()=>{return U.shape}),$.keyof=()=>R3(Object.keys($._zod.def.shape)),$.catchall=(K)=>$.clone({...$._zod.def,catchall:K}),$.passthrough=()=>$.clone({...$._zod.def,catchall:P4()}),$.loose=()=>$.clone({...$._zod.def,catchall:P4()}),$.strict=()=>$.clone({...$._zod.def,catchall:k3()}),$.strip=()=>$.clone({...$._zod.def,catchall:void 0}),$.extend=(K)=>{return z.extend($,K)},$.safeExtend=(K)=>{return z.safeExtend($,K)},$.merge=(K)=>z.merge($,K),$.pick=(K)=>z.pick($,K),$.omit=(K)=>z.omit($,K),$.partial=(...K)=>z.partial(O3,$,K[0]),$.required=(...K)=>z.required(T3,$,K[0])});function tY($,U){let K={type:"object",shape:$??{},...z.normalizeParams(U)};return new V0(K)}function aY($,U){return new V0({type:"object",shape:$,catchall:k3(),...z.normalizeParams(U)})}function sY($,U){return new V0({type:"object",shape:$,catchall:P4(),...z.normalizeParams(U)})}var M0=D("ZodUnion",($,U)=>{a6.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>e2($,K,q,Q),$.options=U.options});function z3($,U){return new M0({type:"union",options:$,...z.normalizeParams(U)})}var XK=D("ZodXor",($,U)=>{M0.init($,U),o9.init($,U),$._zod.processJSONSchema=(K,q,Q)=>e2($,K,q,Q),$.options=U.options});function eY($,U){return new XK({type:"union",options:$,inclusive:!1,...z.normalizeParams(U)})}var ZK=D("ZodDiscriminatedUnion",($,U)=>{M0.init($,U),n9.init($,U)});function $H($,U,K){return new ZK({type:"union",options:U,discriminator:$,...z.normalizeParams(K)})}var BK=D("ZodIntersection",($,U)=>{p9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>wQ($,K,q,Q)});function VK($,U){return new BK({type:"intersection",left:$,right:U})}var MK=D("ZodTuple",($,U)=>{w2.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>AQ($,K,q,Q),$.rest=(K)=>$.clone({...$._zod.def,rest:K})});function DK($,U,K){let q=U instanceof h,Q=q?K:U;return new MK({type:"tuple",items:$,rest:q?U:null,...z.normalizeParams(Q)})}var D0=D("ZodRecord",($,U)=>{t9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>vQ($,K,q,Q),$.keyType=U.keyType,$.valueType=U.valueType});function PK($,U,K){return new D0({type:"record",keyType:$,valueType:U,...z.normalizeParams(K)})}function UH($,U,K){let q=k$($);return q._zod.values=void 0,new D0({type:"record",keyType:q,valueType:U,...z.normalizeParams(K)})}function QH($,U,K){return new D0({type:"record",keyType:$,valueType:U,mode:"loose",...z.normalizeParams(K)})}var NK=D("ZodMap",($,U)=>{a9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>_Q($,K,q,Q),$.keyType=U.keyType,$.valueType=U.valueType,$.min=(...K)=>$.check(B1(...K)),$.nonempty=(K)=>$.check(B1(1,K)),$.max=(...K)=>$.check(f1(...K)),$.size=(...K)=>$.check(V4(...K))});function KH($,U,K){return new NK({type:"map",keyType:$,valueType:U,...z.normalizeParams(K)})}var LK=D("ZodSet",($,U)=>{s9.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>IQ($,K,q,Q),$.min=(...K)=>$.check(B1(...K)),$.nonempty=(K)=>$.check(B1(1,K)),$.max=(...K)=>$.check(f1(...K)),$.size=(...K)=>$.check(V4(...K))});function qH($,U){return new LK({type:"set",valueType:$,...z.normalizeParams(U)})}var W6=D("ZodEnum",($,U)=>{e9.init($,U),c.init($,U),$._zod.processJSONSchema=(q,Q,W)=>XQ($,q,Q,W),$.enum=U.entries,$.options=Object.values(U.entries);let K=new Set(Object.keys(U.entries));$.extract=(q,Q)=>{let W={};for(let G of q)if(K.has(G))W[G]=U.entries[G];else throw Error(`Key ${G} not found in enum`);return new W6({...U,checks:[],...z.normalizeParams(Q),entries:W})},$.exclude=(q,Q)=>{let W={...U.entries};for(let G of q)if(K.has(G))delete W[G];else throw Error(`Key ${G} not found in enum`);return new W6({...U,checks:[],...z.normalizeParams(Q),entries:W})}});function R3($,U){let K=Array.isArray($)?Object.fromEntries($.map((q)=>[q,q])):$;return new W6({type:"enum",entries:K,...z.normalizeParams(U)})}function WH($,U){return new W6({type:"enum",entries:$,...z.normalizeParams(U)})}var _K=D("ZodLiteral",($,U)=>{$7.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>ZQ($,K,q,Q),$.values=new Set(U.values),Object.defineProperty($,"value",{get(){if(U.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return U.values[0]}})});function GH($,U){return new _K({type:"literal",values:Array.isArray($)?$:[$],...z.normalizeParams(U)})}var IK=D("ZodFile",($,U)=>{U7.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>MQ($,K,q,Q),$.min=(K,q)=>$.check(B1(K,q)),$.max=(K,q)=>$.check(f1(K,q)),$.mime=(K,q)=>$.check(t4(Array.isArray(K)?K:[K],q))});function JH($){return i5(IK,$)}var FK=D("ZodTransform",($,U)=>{Q7.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>LQ($,K,q,Q),$._zod.parse=(K,q)=>{if(q.direction==="backward")throw new H4($.constructor.name);K.addIssue=(W)=>{if(typeof W==="string")K.issues.push(z.issue(W,K.value,U));else{let G=W;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=K.value),G.inst??(G.inst=$),K.issues.push(z.issue(G))}};let Q=U.transform(K.value,K);if(Q instanceof Promise)return Q.then((W)=>{return K.value=W,K});return K.value=Q,K}});function b3($){return new FK({type:"transform",transform:$})}var O3=D("ZodOptional",($,U)=>{A2.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>$3($,K,q,Q),$.unwrap=()=>$._zod.def.innerType});function j0($){return new O3({type:"optional",innerType:$})}var xK=D("ZodExactOptional",($,U)=>{K7.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>$3($,K,q,Q),$.unwrap=()=>$._zod.def.innerType});function wK($){return new xK({type:"optional",innerType:$})}var AK=D("ZodNullable",($,U)=>{q7.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>kQ($,K,q,Q),$.unwrap=()=>$._zod.def.innerType});function Y0($){return new AK({type:"nullable",innerType:$})}function jH($){return j0(Y0($))}var vK=D("ZodDefault",($,U)=>{W7.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>RQ($,K,q,Q),$.unwrap=()=>$._zod.def.innerType,$.removeDefault=$.unwrap});function kK($,U){return new vK({type:"default",innerType:$,get defaultValue(){return typeof U==="function"?U():z.shallowClone(U)}})}var zK=D("ZodPrefault",($,U)=>{G7.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>bQ($,K,q,Q),$.unwrap=()=>$._zod.def.innerType});function RK($,U){return new zK({type:"prefault",innerType:$,get defaultValue(){return typeof U==="function"?U():z.shallowClone(U)}})}var T3=D("ZodNonOptional",($,U)=>{J7.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>zQ($,K,q,Q),$.unwrap=()=>$._zod.def.innerType});function bK($,U){return new T3({type:"nonoptional",innerType:$,...z.normalizeParams(U)})}var OK=D("ZodSuccess",($,U)=>{j7.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>DQ($,K,q,Q),$.unwrap=()=>$._zod.def.innerType});function YH($){return new OK({type:"success",innerType:$})}var TK=D("ZodCatch",($,U)=>{Y7.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>OQ($,K,q,Q),$.unwrap=()=>$._zod.def.innerType,$.removeCatch=$.unwrap});function SK($,U){return new TK({type:"catch",innerType:$,catchValue:typeof U==="function"?U:()=>U})}var CK=D("ZodNaN",($,U)=>{H7.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>BQ($,K,q,Q)});function HH($){return l5(CK,$)}var S3=D("ZodPipe",($,U)=>{X7.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>TQ($,K,q,Q),$.in=U.in,$.out=U.out});function H0($,U){return new S3({type:"pipe",in:$,out:U})}var C3=D("ZodCodec",($,U)=>{S3.init($,U),s6.init($,U)});function XH($,U,K){return new C3({type:"pipe",in:$,out:U,transform:K.decode,reverseTransform:K.encode})}var EK=D("ZodReadonly",($,U)=>{Z7.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>SQ($,K,q,Q),$.unwrap=()=>$._zod.def.innerType});function yK($){return new EK({type:"readonly",innerType:$})}var gK=D("ZodTemplateLiteral",($,U)=>{B7.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>VQ($,K,q,Q)});function ZH($,U){return new gK({type:"template_literal",parts:$,...z.normalizeParams(U)})}var uK=D("ZodLazy",($,U)=>{D7.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>EQ($,K,q,Q),$.unwrap=()=>$._zod.def.getter()});function fK($){return new uK({type:"lazy",getter:$})}var mK=D("ZodPromise",($,U)=>{M7.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>CQ($,K,q,Q),$.unwrap=()=>$._zod.def.innerType});function BH($){return new mK({type:"promise",innerType:$})}var hK=D("ZodFunction",($,U)=>{V7.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>NQ($,K,q,Q)});function VH($){return new hK({type:"function",input:Array.isArray($?.input)?DK($?.input):$?.input??B0(P4()),output:$?.output??P4()})}var P0=D("ZodCustom",($,U)=>{P7.init($,U),c.init($,U),$._zod.processJSONSchema=(K,q,Q)=>PQ($,K,q,Q)});function MH($){let U=new $$({check:"custom"});return U._zod.check=$,U}function DH($,U){return d5(P0,$??(()=>!0),U)}function cK($,U={}){return o5(P0,$,U)}function lK($){return n5($)}var PH=p5,NH=t5;function LH($,U={}){let K=new P0({type:"custom",check:"custom",fn:(q)=>q instanceof $,abort:!0,...z.normalizeParams(U)});return K._zod.bag.Class=$,K._zod.check=(q)=>{if(!(q.value instanceof $))q.issues.push({code:"invalid_type",expected:$.name,input:q.value,inst:K,path:[...K._zod.def.path??[]]})},K}var _H=(...$)=>a5({Codec:C3,Boolean:Y6,String:G6},...$);function IH($){let U=fK(()=>{return z3([J3($),$K(),UK(),WK(),B0(U),PK(J3(),U)])});return U}function FH($,U){return H0(b3($),U)}var s_={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function e_($){V$({customError:$})}function $I(){return V$().customError}var rK;(function($){})(rK||(rK={}));var S={...G0,...Q3,iso:q6},UI=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function QI($,U){let K=$.$schema;if(K==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if(K==="http://json-schema.org/draft-07/schema#")return"draft-7";if(K==="http://json-schema.org/draft-04/schema#")return"draft-4";return U??"draft-2020-12"}function KI($,U){if(!$.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let K=$.slice(1).split("/").filter(Boolean);if(K.length===0)return U.rootSchema;let q=U.version==="draft-2020-12"?"$defs":"definitions";if(K[0]===q){let Q=K[1];if(!Q||!U.defs[Q])throw Error(`Reference not found: ${$}`);return U.defs[Q]}throw Error(`Reference not found: ${$}`)}function xH($,U){if($.not!==void 0){if(typeof $.not==="object"&&Object.keys($.not).length===0)return S.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if($.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if($.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if($.if!==void 0||$.then!==void 0||$.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if($.dependentSchemas!==void 0||$.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if($.$ref){let Q=$.$ref;if(U.refs.has(Q))return U.refs.get(Q);if(U.processing.has(Q))return S.lazy(()=>{if(!U.refs.has(Q))throw Error(`Circular reference not resolved: ${Q}`);return U.refs.get(Q)});U.processing.add(Q);let W=KI(Q,U),G=x$(W,U);return U.refs.set(Q,G),U.processing.delete(Q),G}if($.enum!==void 0){let Q=$.enum;if(U.version==="openapi-3.0"&&$.nullable===!0&&Q.length===1&&Q[0]===null)return S.null();if(Q.length===0)return S.never();if(Q.length===1)return S.literal(Q[0]);if(Q.every((G)=>typeof G==="string"))return S.enum(Q);let W=Q.map((G)=>S.literal(G));if(W.length<2)return W[0];return S.union([W[0],W[1],...W.slice(2)])}if($.const!==void 0)return S.literal($.const);let K=$.type;if(Array.isArray(K)){let Q=K.map((W)=>{let G={...$,type:W};return xH(G,U)});if(Q.length===0)return S.never();if(Q.length===1)return Q[0];return S.union(Q)}if(!K)return S.any();let q;switch(K){case"string":{let Q=S.string();if($.format){let W=$.format;if(W==="email")Q=Q.check(S.email());else if(W==="uri"||W==="uri-reference")Q=Q.check(S.url());else if(W==="uuid"||W==="guid")Q=Q.check(S.uuid());else if(W==="date-time")Q=Q.check(S.iso.datetime());else if(W==="date")Q=Q.check(S.iso.date());else if(W==="time")Q=Q.check(S.iso.time());else if(W==="duration")Q=Q.check(S.iso.duration());else if(W==="ipv4")Q=Q.check(S.ipv4());else if(W==="ipv6")Q=Q.check(S.ipv6());else if(W==="mac")Q=Q.check(S.mac());else if(W==="cidr")Q=Q.check(S.cidrv4());else if(W==="cidr-v6")Q=Q.check(S.cidrv6());else if(W==="base64")Q=Q.check(S.base64());else if(W==="base64url")Q=Q.check(S.base64url());else if(W==="e164")Q=Q.check(S.e164());else if(W==="jwt")Q=Q.check(S.jwt());else if(W==="emoji")Q=Q.check(S.emoji());else if(W==="nanoid")Q=Q.check(S.nanoid());else if(W==="cuid")Q=Q.check(S.cuid());else if(W==="cuid2")Q=Q.check(S.cuid2());else if(W==="ulid")Q=Q.check(S.ulid());else if(W==="xid")Q=Q.check(S.xid());else if(W==="ksuid")Q=Q.check(S.ksuid())}if(typeof $.minLength==="number")Q=Q.min($.minLength);if(typeof $.maxLength==="number")Q=Q.max($.maxLength);if($.pattern)Q=Q.regex(new RegExp($.pattern));q=Q;break}case"number":case"integer":{let Q=K==="integer"?S.number().int():S.number();if(typeof $.minimum==="number")Q=Q.min($.minimum);if(typeof $.maximum==="number")Q=Q.max($.maximum);if(typeof $.exclusiveMinimum==="number")Q=Q.gt($.exclusiveMinimum);else if($.exclusiveMinimum===!0&&typeof $.minimum==="number")Q=Q.gt($.minimum);if(typeof $.exclusiveMaximum==="number")Q=Q.lt($.exclusiveMaximum);else if($.exclusiveMaximum===!0&&typeof $.maximum==="number")Q=Q.lt($.maximum);if(typeof $.multipleOf==="number")Q=Q.multipleOf($.multipleOf);q=Q;break}case"boolean":{q=S.boolean();break}case"null":{q=S.null();break}case"object":{let Q={},W=$.properties||{},G=new Set($.required||[]);for(let[Y,H]of Object.entries(W)){let X=x$(H,U);Q[Y]=G.has(Y)?X:X.optional()}if($.propertyNames){let Y=x$($.propertyNames,U),H=$.additionalProperties&&typeof $.additionalProperties==="object"?x$($.additionalProperties,U):S.any();if(Object.keys(Q).length===0){q=S.record(Y,H);break}let X=S.object(Q).passthrough(),B=S.looseRecord(Y,H);q=S.intersection(X,B);break}if($.patternProperties){let Y=$.patternProperties,H=Object.keys(Y),X=[];for(let M of H){let I=x$(Y[M],U),E=S.string().regex(new RegExp(M));X.push(S.looseRecord(E,I))}let B=[];if(Object.keys(Q).length>0)B.push(S.object(Q).passthrough());if(B.push(...X),B.length===0)q=S.object({}).passthrough();else if(B.length===1)q=B[0];else{let M=S.intersection(B[0],B[1]);for(let I=2;I<B.length;I++)M=S.intersection(M,B[I]);q=M}break}let j=S.object(Q);if($.additionalProperties===!1)q=j.strict();else if(typeof $.additionalProperties==="object")q=j.catchall(x$($.additionalProperties,U));else q=j.passthrough();break}case"array":{let{prefixItems:Q,items:W}=$;if(Q&&Array.isArray(Q)){let G=Q.map((Y)=>x$(Y,U)),j=W&&typeof W==="object"&&!Array.isArray(W)?x$(W,U):void 0;if(j)q=S.tuple(G).rest(j);else q=S.tuple(G);if(typeof $.minItems==="number")q=q.check(S.minLength($.minItems));if(typeof $.maxItems==="number")q=q.check(S.maxLength($.maxItems))}else if(Array.isArray(W)){let G=W.map((Y)=>x$(Y,U)),j=$.additionalItems&&typeof $.additionalItems==="object"?x$($.additionalItems,U):void 0;if(j)q=S.tuple(G).rest(j);else q=S.tuple(G);if(typeof $.minItems==="number")q=q.check(S.minLength($.minItems));if(typeof $.maxItems==="number")q=q.check(S.maxLength($.maxItems))}else if(W!==void 0){let G=x$(W,U),j=S.array(G);if(typeof $.minItems==="number")j=j.min($.minItems);if(typeof $.maxItems==="number")j=j.max($.maxItems);q=j}else q=S.array(S.any());break}default:throw Error(`Unsupported type: ${K}`)}if($.description)q=q.describe($.description);if($.default!==void 0)q=q.default($.default);return q}function x$($,U){if(typeof $==="boolean")return $?S.any():S.never();let K=xH($,U),q=$.type||$.enum!==void 0||$.const!==void 0;if($.anyOf&&Array.isArray($.anyOf)){let j=$.anyOf.map((H)=>x$(H,U)),Y=S.union(j);K=q?S.intersection(K,Y):Y}if($.oneOf&&Array.isArray($.oneOf)){let j=$.oneOf.map((H)=>x$(H,U)),Y=S.xor(j);K=q?S.intersection(K,Y):Y}if($.allOf&&Array.isArray($.allOf))if($.allOf.length===0)K=q?K:S.any();else{let j=q?K:x$($.allOf[0],U),Y=q?0:1;for(let H=Y;H<$.allOf.length;H++)j=S.intersection(j,x$($.allOf[H],U));K=j}if($.nullable===!0&&U.version==="openapi-3.0")K=S.nullable(K);if($.readOnly===!0)K=S.readonly(K);let Q={},W=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let j of W)if(j in $)Q[j]=$[j];let G=["contentEncoding","contentMediaType","contentSchema"];for(let j of G)if(j in $)Q[j]=$[j];for(let j of Object.keys($))if(!UI.has(j))Q[j]=$[j];if(Object.keys(Q).length>0)U.registry.add(K,Q);return K}function wH($,U){if(typeof $==="boolean")return $?S.any():S.never();let K=QI($,U?.defaultTarget),q=$.$defs||$.definitions||{},Q={version:K,defs:q,refs:new Map,processing:new Set,rootSchema:$,registry:U?.registry??_$};return x$($,Q)}var iK={};L1(iK,{string:()=>qI,number:()=>WI,date:()=>jI,boolean:()=>GI,bigint:()=>JI});function qI($){return V5(G6,$)}function WI($){return F5(j6,$)}function GI($){return R5(Y6,$)}function JI($){return O5(H6,$)}function jI($){return c5(Z0,$)}V$(e6());var YI=/^(?:([^<>]*)<([^<>\s]+)>|([^<>\s]+))$/;function HI($){let U=YI.exec($.trim());if(U==null)return null;let K=U[2]??U[3]??"";if(!J.email().safeParse(K).success)return null;let q=U[1]?.trim().replaceAll(/^"|"$/g,"")??"";return{name:q===""?null:q,address:K}}var EE=J.string().trim().max(255).refine(($)=>HI($)!=null,{message:"Invalid sender"});var AH={"acl_rule.created":{},"acl_rule.updated":{},"acl_rule.deleted":{},"acl_rule.enabled":{},"acl_rule.disabled":{},"api_key.created":{},"api_key.revoked":{},"api_key.rotated":{},"api_key.rotation_finished":{},"api_key.updated":{},"audio_file.uploaded":{},"audio_file.updated":{},"audio_file.deleted":{},"audio_file.tts_generated":{},"audio_file.tts_regenerated":{},"audio_file.restored":{},"audio_file.purged":{},"audit_log.purged":{},"destination.created":{},"destination.updated":{},"destination.deleted":{},"holiday.created":{},"holiday.updated":{},"holiday.deleted":{},"holiday_group.created":{},"holiday_group.updated":{},"holiday_group.deleted":{},"holiday_group.imported":{},"invitation.created":{},"invitation.accepted":{},"invitation.revoked":{},"invitation.resent":{},"organization.created":{},"organization.updated":{},"organization.deleted":{},"oauth.authorized":{},"oauth.denied":{},"oauth_grant.revoked":{},"secret.created":{},"secret.updated":{},"secret.deleted":{},"connector.created":{},"connector.updated":{},"connector.deleted":{},"connector.tested":{},"connector.enabled":{},"connector.disabled":{},"connector.sms_sent":{},"connector.phone_number.code_requested":{},"connector.phone_number.verified":{},"connector.phone_number.registered":{},"connector.phone_number.assigned":{},"connector.phone_number.removed":{},"signal.created":{},"signal.updated":{},"signal.deleted":{},"signal.restored":{},"signal.purged":{},"insight_view.created":{},"insight_view.updated":{},"insight_view.deleted":{},"insight_view.reordered":{},"dashboard.updated":{},"role.created":{},"role.updated":{},"role.deleted":{},"channel.created":{},"channel.updated":{},"channel.deleted":{},"channel.activated":{},"channel.deactivated":{},"channel.restored":{},"channel.purged":{},"schedule.created":{},"schedule.updated":{},"schedule.deleted":{},"schedule.restored":{},"schedule.purged":{},"user.created":{},"user.signup":{},"user.login":{},"user.logout":{},"user.password_changed":{},"user.password_reset_requested":{},"user.password_reset_completed":{},"user.account_unlocked":{},"user.second_factor_enrollment_started":{},"user.second_factor_enrolled":{},"user.passkey_registered":{},"user.passkey_renamed":{},"user.passkey_removed":{},"user.second_factor_reset":{},"user.recovery_codes_regenerated":{},"user.session_revoked":{},"user.sessions_revoked":{},"user.role_changed":{},"user.suspended":{},"user.activated":{},"user.removed":{},"block_preset.created":{},"block_preset.updated":{},"block_preset.deleted":{},"saved_recipe.created":{},"saved_recipe.updated":{},"saved_recipe.deleted":{},"visual_plan.created":{},"visual_plan.cloned":{},"visual_plan.updated":{},"visual_plan.deleted":{},"visual_plan.imported":{},"visual_plan.published":{},"visual_plan.restored":{},"visual_plan.purged":{},"webhook_endpoint.created":{},"webhook_endpoint.updated":{},"webhook_endpoint.deleted":{},"webhook_endpoint.secret_rotated":{},"webhook_endpoint.test_sent":{},"webhook_delivery.retried":{},"system.initialized":{},"system.fs_started":{},"system.fs_restarted":{},"system.engine_restarted":{},"system.update_requested":{},"system.update_cancelled":{},"platform_settings.updated":{},"storage_config.updated":{},"recording_storage.updated":{},"storage_cache.purged":{},"platform_admin.assigned":{},"platform_admin.revoked":{},"platform_admin.owner_transferred":{},"platform_admin.mfa_policy_updated":{},"org_settings.updated":{},"org_settings.limits_updated":{},"org_plan.modules_updated":{},"org_plan.ai_credential_updated":{},"tenant_module.enabled":{},"tenant_module.disabled":{},"tenant_module.limits_updated":{},"contact.updated":{},"dialer_campaign.created":{},"dialer_campaign.updated":{},"dialer_campaign.deleted":{},"dialer_campaign.controlled":{},"dialer_contact.added":{},"dialer_contact.updated":{},"dialer_contact.cancelled":{},"dialer_contact.requeued":{},"dialer_contact.removed":{},"dialer_import.created":{},"dialer_dnc.added":{},"dialer_dnc.removed":{},"dialer_dnc.imported":{},"analysis_template.created":{},"analysis_template.updated":{},"analysis_template.deleted":{},"ai_settings.updated":{},"ws_session.created":{},"ws_test_chat_session.created":{},"ws_test_chat_session.stopped":{},"call.originate":{retention:"operational"},"call_record.voice_purged":{},"call_record.recording_url_issued":{},"call_record.recording_downloaded":{},"notification.deleted":{},"notification_channel.created":{},"notification_channel.updated":{},"notification_channel.deleted":{},"notification_channel.tested":{},"notification_preference.updated":{},"notification_preference.reset":{},"screen_pop.fetched":{retention:"operational"}},XI=Object.keys(AH);var dK=J.object({}).default({}),oK=J.object({phone_number_id:J.string().min(1),voice_enabled:J.boolean().default(!0),chat_enabled:J.boolean().default(!0),sip_username:J.string().optional(),sip_password_encrypted:J.string().optional(),sip_password_iv:J.string().optional(),session_timeout_minutes:J.number().int().min(5).max(10080).default(1440),business_name:J.string().optional(),display_phone_number:J.string().optional(),last_webhook_received_at:J.iso.datetime().optional(),last_webhook_message_id:J.string().optional(),last_webhook_status_id:J.string().optional(),last_webhook_phone_number_id:J.string().optional(),last_webhook_error:J.string().optional()}),nK=J.object({bot_token:J.string().min(1),webhook_secret:J.string().min(1),allow_groups:J.boolean().default(!1),session_timeout_minutes:J.number().int().min(5).max(10080).default(1440),bot_username:J.string().optional()}),vH={sip:dK,telegram:nK,whatsapp:oK,webchat:J.object({}).default({}),sms:J.object({}).default({}),rcs:J.object({}).default({})};var X6=["sip"],N0=["telegram","webchat","sms","rcs"],Z6=["whatsapp"],pK=[...X6,...N0,...Z6],kH=[...X6,...Z6],zH=[...N0,...Z6];var dE=new Set(X6),oE=new Set(Z6);var RH=String.raw`(?:25[0-5]|2[0-4]\d|[01]?\d\d?)`,bH=String.raw`(?:${RH}\.){3}${RH}`,VI=String.raw`${bH}(?:\/(?:3[0-2]|[12]?\d))?`,Uy=new RegExp(`^${bH}$`);var w$="[0-9a-fA-F]{1,4}",MI=[`(?:${w$}:){7}${w$}`,`(?:${w$}:){1,7}:`,`(?:${w$}:){1,6}:${w$}`,`(?:${w$}:){1,5}(?::${w$}){1,2}`,`(?:${w$}:){1,4}(?::${w$}){1,3}`,`(?:${w$}:){1,3}(?::${w$}){1,4}`,`(?:${w$}:){1,2}(?::${w$}){1,5}`,`${w$}:(?::${w$}){1,6}`,`:(?::${w$}){1,7}`,"::(?:ffff(?::0{1,4})?:)?"],DI=`(?:${MI.join("|")})`,PI=String.raw`${DI}(?:\/(?:12[0-8]|1[01]\d|[1-9]?\d))?`,Qy=new RegExp(`^(?:${VI}|${PI})$`);function NI($){let U=$;if(U==null||typeof U!=="object")throw Error("Execution plan must be a JSON object with { version, startNodeId, nodes, adjacency }");if(!("nodes"in U)||U.nodes==null||typeof U.nodes!=="object"){let K;if(!("nodes"in U))K="missing";else if(Array.isArray(U.nodes))K="an array";else K=typeof U.nodes;throw Error(`Execution plan "nodes" must be an object keyed by node ID, not ${K}`)}if(!("adjacency"in U)||U.adjacency==null||typeof U.adjacency!=="object")throw Error('Execution plan "adjacency" must be an object mapping source → { handle → target }')}function tK($){NI($);let U=Object.entries($.nodes).map(([q,Q])=>({id:q,type:Q.type,label:Q.label,varName:Q.varName,position:{x:0,y:0},config:Q.config})),K=[];for(let[q,Q]of Object.entries($.adjacency))for(let[W,G]of Object.entries(Q))K.push({id:`${q}-${W}-${G}`,source:q,sourceHandle:W,target:G,targetHandle:"in"});return OH({nodes:U,edges:K,viewport:{x:0,y:0,zoom:1}})}function OH($){let U=$.nodes.find((Q)=>Q.type==="start");if(U==null||typeof U.config.channelType==="string")return $;let q=$.edges.some((Q)=>Q.source===U.id&&Q.sourceHandle==="next")?"voice":"both";return{...$,nodes:$.nodes.map((Q)=>Q===U?{...Q,config:{...Q.config,channelType:q}}:Q)}}var L4=3600;var z1=["none","both","caller"],aK=J.object({callerSpeechMs:J.number().int().min(0),ivrSpeechMs:J.number().int().min(0),version:J.number().int().min(1)});var l1=["post_call","live"],sK=J.object({startByte:J.number().int().min(0),endByte:J.number().int().min(0),openedAtMs:J.number().int().min(0)}).refine(($)=>$.endByte>=$.startByte,{message:"endByte must be greater than or equal to startByte",path:["endByte"]}),TH=J.object({nodeId:J.string().min(1),kind:J.enum(["recording","transcription","analysis"]),atByte:J.number().int().min(0),atMs:J.number().int().min(0),patch:J.record(J.string(),J.unknown())}),SH=J.object({samplingPercentage:J.number().int().min(0).max(100).describe("Recording sampling percentage"),transcriptionSamplingPercentage:J.number().int().min(0).max(100).default(100).describe("Transcription sampling percentage among selected recordings"),transcriptionEnabled:J.boolean().describe("Enable transcription"),transcriptionLanguage:J.string().nullable().describe("Transcription language"),transcriptionMinDurationSeconds:J.number().int().min(0).max(L4).describe("Minimum transcription duration"),transcriptionSpeechRequirement:J.enum(z1).default("none").describe("Which sides must have spoken for automatic transcription"),transcriptionType:J.enum(l1).default("post_call").describe("Transcription type: after the call ends, or live during the whole transcription window"),anonymizeEnabled:J.boolean().describe("Anonymize the transcript"),speechAnalyticsEnabled:J.boolean().describe("Enable speech analytics"),sentimentEnabled:J.boolean().optional().describe("Enable sentiment analysis"),topicDetectionTopics:J.array(J.string()).describe("Topic detection topics"),intentDetectionIntents:J.array(J.string()).describe("Intent detection intents"),autoAnalysisEnabled:J.boolean().describe("Enable structured analyses"),autoAnalysisInheritOrg:J.boolean().describe("Inherit structured analyses from the organization"),autoAnalysisIds:J.array(J.string()).describe("Structured analysis IDs")}).transform(($)=>({...$,sentimentEnabled:$.sentimentEnabled??$.speechAnalyticsEnabled})),LI=J.object({speechAnalyticsEnabled:J.boolean(),sentimentEnabled:J.boolean().optional(),topicDetectionTopics:J.array(J.string()),intentDetectionIntents:J.array(J.string()),autoAnalysisEnabled:J.boolean(),autoAnalysisIds:J.array(J.string())}).transform(($)=>({...$,sentimentEnabled:$.sentimentEnabled??$.speechAnalyticsEnabled}));var _I=J.object({usePlan:J.boolean().default(!0).describe("Use plan recording profile"),samplingPercentage:J.number().int().min(0).max(100).default(100).describe("Recording sampling percentage"),transcriptionSamplingPercentage:J.number().int().min(0).max(100).default(100).describe("Transcription sampling percentage"),transcriptionEnabled:J.boolean().default(!1).describe("Enable transcription"),transcriptionLanguage:J.string().default("").describe("Transcription language"),transcriptionMinDurationSeconds:J.number().int().min(0).max(L4).default(0).describe("Minimum transcription duration"),transcriptionSpeechRequirement:J.enum(z1).default("none").describe("Which sides must have spoken for automatic transcription"),transcriptionType:J.enum(l1).default("post_call").describe("Transcription type: after the call ends, or live during the whole transcription window"),anonymizeEnabled:J.boolean().default(!1).describe("Anonymize the transcript"),speechAnalyticsEnabled:J.boolean().default(!1).describe("Enable speech analytics"),sentimentEnabled:J.boolean().optional().describe("Enable sentiment analysis"),topicDetectionTopics:J.array(J.string()).default([]).describe("Topic detection topics"),intentDetectionIntents:J.array(J.string()).default([]).describe("Intent detection intents"),autoAnalysisEnabled:J.boolean().default(!1).describe("Enable structured analyses"),autoAnalysisIds:J.array(J.string()).default([]).describe("Structured analysis IDs")}).transform(($)=>({...$,sentimentEnabled:$.sentimentEnabled??$.speechAnalyticsEnabled})),CH=J.object({sampleRate:J.number().int().positive(),channels:J.number().int().positive(),bitsPerSample:J.number().int().positive()});var II=J.object({sampled:J.boolean(),transcriptionSampled:J.boolean().optional(),profile:SH,recordingFormat:CH.optional(),recordingIntervals:sK.array().default([]),transcriptionWindows:sK.array().default([]),directives:TH.array().default([]),voiceActivity:aK.optional()});var FI=["recordingEnabled","samplingPercentage","transcriptionSamplingPercentage","transcriptionEnabled","transcriptionLanguage","transcriptionMinDurationSeconds","transcriptionSpeechRequirement","transcriptionType","anonymizeEnabled","speechAnalyticsEnabled","sentimentEnabled","topicDetectionTopics","intentDetectionIntents","structuredAnalysisEnabled","structuredAnalysisIds"];function $q($,U,K,q,Q=!1){let W=xI(q),G=new Map(K.map((H)=>[H.id,H])),j=zI(U,Q),Y={};return wI({startNodeId:$,planState:j,nodesById:G,adjacency:q,incoming:W,result:Y}),Y}function xI($){let U=new Map;for(let[K,q]of $)for(let Q of q.values()){let W=U.get(Q)??[];U.set(Q,[...W,K])}return U}function wI($){let{startNodeId:U,planState:K,nodesById:q,adjacency:Q,incoming:W,result:G}=$,j=[U],Y=new Set(j),H=0,X=Math.max(20,q.size*q.size*4);while(j.length>0&&H++<X){let B=j.shift();if(B===void 0)continue;Y.delete(B);let M=q.get(B);if(M===void 0)continue;let I=AI(B,K,M,W,G);if(mI(G[B],I))continue;G[B]=I,kI(j,Y,Q.get(B)?.values()??[])}}function AI($,U,K,q,Q){let W=(q.get($)??[]).map((j)=>Q[j]).filter((j)=>j!==void 0),G=vI(W,U);return RI(G,K)}function vI($,U){let K=$[0];return K===void 0?U:$.slice(1).reduce((q,Q)=>uI(q,Q),K)}function kI($,U,K){for(let q of K){if(U.has(q))continue;$.push(q),U.add(q)}}function zI($,U){let K={kind:"plan"};return{recordingEnabled:I$(U,K),samplingPercentage:I$($.samplingPercentage,K),transcriptionSamplingPercentage:I$($.transcriptionSamplingPercentage,K),transcriptionEnabled:I$($.transcriptionEnabled,K),transcriptionLanguage:I$($.transcriptionLanguage,K),transcriptionMinDurationSeconds:I$($.transcriptionMinDurationSeconds,K),transcriptionSpeechRequirement:I$($.transcriptionSpeechRequirement,K),transcriptionType:I$($.transcriptionType,K),anonymizeEnabled:I$($.anonymizeEnabled,K),speechAnalyticsEnabled:I$($.speechAnalyticsEnabled,K),sentimentEnabled:I$($.sentimentEnabled,K),topicDetectionTopics:I$([...$.topicDetectionTopics],K),intentDetectionIntents:I$([...$.intentDetectionIntents],K),structuredAnalysisEnabled:I$($.autoAnalysisEnabled,K),structuredAnalysisIds:I$([...$.autoAnalysisIds],K)}}function RI($,U){let K=bI(U),q={kind:"node",nodeId:U.id,nodeLabel:U.label};return{recordingEnabled:b$($.recordingEnabled,K.recordingEnabled,q),samplingPercentage:b$($.samplingPercentage,K.samplingPercentage,q),transcriptionSamplingPercentage:b$($.transcriptionSamplingPercentage,K.transcriptionSamplingPercentage,q),transcriptionEnabled:b$($.transcriptionEnabled,K.transcriptionEnabled,q),transcriptionLanguage:b$($.transcriptionLanguage,K.transcriptionLanguage,q),transcriptionMinDurationSeconds:b$($.transcriptionMinDurationSeconds,K.transcriptionMinDurationSeconds,q),transcriptionSpeechRequirement:b$($.transcriptionSpeechRequirement,K.transcriptionSpeechRequirement,q),transcriptionType:b$($.transcriptionType,K.transcriptionType,q),anonymizeEnabled:b$($.anonymizeEnabled,K.anonymizeEnabled,q),speechAnalyticsEnabled:b$($.speechAnalyticsEnabled,K.speechAnalyticsEnabled,q),sentimentEnabled:b$($.sentimentEnabled,K.sentimentEnabled,q),topicDetectionTopics:b$($.topicDetectionTopics,K.topicDetectionTopics,q),intentDetectionIntents:b$($.intentDetectionIntents,K.intentDetectionIntents,q),structuredAnalysisEnabled:b$($.structuredAnalysisEnabled,K.structuredAnalysisEnabled,q),structuredAnalysisIds:b$($.structuredAnalysisIds,K.structuredAnalysisIds,q)}}function bI($){if($.type==="recording")return OI($.config);if($.type==="transcription")return TI($.config);if($.type==="analysis")return SI($.config);return{}}function OI($){let U={},K=$.enabled;if(typeof K==="boolean")U.recordingEnabled=K;let q=$.samplingPercentage;if(typeof q==="number")U.samplingPercentage=q;return U}function TI($){let U={},K=$.enabled;if(typeof K==="boolean")U.transcriptionEnabled=K;let q=$.samplingPercentage;if(typeof q==="number")U.transcriptionSamplingPercentage=q;let Q=$.language;if(typeof Q==="string")U.transcriptionLanguage=Q.trim()||null;let W=$.minDurationSeconds;if(typeof W==="number")U.transcriptionMinDurationSeconds=W;let G=$.speechRequirement;if(EI(G))U.transcriptionSpeechRequirement=G;let j=$.transcriptionType;if(gI(j))U.transcriptionType=j;let Y=$.anonymizeEnabled;if(typeof Y==="boolean")U.anonymizeEnabled=Y;let{speechAnalyticsEnabled:H,sentimentEnabled:X}=$;if(typeof H==="boolean")U.speechAnalyticsEnabled=H;if(typeof X==="boolean")U.sentimentEnabled=X;else if(typeof H==="boolean")U.sentimentEnabled=H;return U}function SI($){let U={},K=$.speechAnalyticsEnabled,q=$.sentimentEnabled;if(typeof K==="boolean")U.speechAnalyticsEnabled=K;if(typeof q==="boolean")U.sentimentEnabled=q;else if(q===void 0&&typeof K==="boolean")U.sentimentEnabled=K;let Q=$.topicDetectionTopics;if(eK(Q))U.topicDetectionTopics=Q;let W=$.intentDetectionIntents;if(eK(W))U.intentDetectionIntents=W;let G=$.structuredAnalysisEnabled;if(typeof G==="boolean")U.structuredAnalysisEnabled=G;let j=$.structuredAnalysisIds;if(eK(j))U.structuredAnalysisIds=j;return U}var CI=z1;function EI($){return typeof $==="string"&&CI.includes($)}var yI=l1;function gI($){return typeof $==="string"&&yI.includes($)}function eK($){return Array.isArray($)&&$.every((U)=>typeof U==="string")}function b$($,U,K){return U===void 0?$:I$(U,K)}function I$($,U){return{kind:"known",value:$,origin:U}}function uI($,U){return{recordingEnabled:O$($.recordingEnabled,U.recordingEnabled),samplingPercentage:O$($.samplingPercentage,U.samplingPercentage),transcriptionSamplingPercentage:O$($.transcriptionSamplingPercentage,U.transcriptionSamplingPercentage),transcriptionEnabled:O$($.transcriptionEnabled,U.transcriptionEnabled),transcriptionLanguage:O$($.transcriptionLanguage,U.transcriptionLanguage),transcriptionMinDurationSeconds:O$($.transcriptionMinDurationSeconds,U.transcriptionMinDurationSeconds),transcriptionSpeechRequirement:O$($.transcriptionSpeechRequirement,U.transcriptionSpeechRequirement),transcriptionType:O$($.transcriptionType,U.transcriptionType),anonymizeEnabled:O$($.anonymizeEnabled,U.anonymizeEnabled),speechAnalyticsEnabled:O$($.speechAnalyticsEnabled,U.speechAnalyticsEnabled),sentimentEnabled:O$($.sentimentEnabled,U.sentimentEnabled),topicDetectionTopics:O$($.topicDetectionTopics,U.topicDetectionTopics),intentDetectionIntents:O$($.intentDetectionIntents,U.intentDetectionIntents),structuredAnalysisEnabled:O$($.structuredAnalysisEnabled,U.structuredAnalysisEnabled),structuredAnalysisIds:O$($.structuredAnalysisIds,U.structuredAnalysisIds)}}function O$($,U){let K=[...EH($),...EH(U)],q=[];for(let Q of K)if(!q.some((W)=>yH(W.value,Q.value)))q.push(Q);if(q.length===1){let Q=fI($,U,q[0].viaNodeLabel);return I$(q[0].value,Q)}return{kind:"indeterminate",branches:q}}function fI($,U,K){if($.kind==="known")return $.origin;if(U.kind==="known")return U.origin;return{kind:"node",nodeId:"",nodeLabel:K}}function EH($){if($.kind==="indeterminate")return $.branches;let U=$.origin.kind==="plan"?"__plan__":$.origin.nodeLabel;return[{value:$.value,viaNodeLabel:U}]}function yH($,U){return JSON.stringify($)===JSON.stringify(U)}function mI($,U){if($===void 0)return!1;return FI.every((K)=>yH($[K],U[K]))}function C($){let U=$.producedVariables;return{meta:{...$.meta,inputs:$.meta.type==="start"?[]:[{key:"in",labelKey:"editor:handles.in"}],producedVariables:typeof U==="function"?(q)=>U(q):U,defaultConfig:$.configSchema.parse({})},configSchema:$.configSchema,producedVariables:$.producedVariables}}var gH=["volume","weekday_hour","composition","plans","topics","intents"],uH=J.string().regex(/^signal:sig_[A-Za-z0-9]+$/),hI=J.union([J.enum(gH),uH]),cI=J.number().int().min(1).max(4);var lI=J.object({id:J.string(),type:J.string(),x:J.number(),y:J.number()}),rI=J.object({source:J.string(),target:J.string()}),iI=J.object({nodes:J.array(lI),edges:J.array(rI)});var fH=["voice","chat","both"];var mH=["pre","post"];var hH=["voicemail","announcement","ivr","screening","unknown"];var Uq=["busy","no_answer","failed","machine"];var L0=["channels","calls","registrations","codecs","modules","aliases"];var dI=new Set(["phone","telephone","telefone","fone","celular","cel","mobile","movel","numero","number","num","tel","msisdn","whatsapp","telefone celular","numero de telefone"]),oI=new Set(["name","nome","cliente","contato","contact","nome completo","razao social","full name"]);function nI($){return $.normalize("NFD").replaceAll(/[\u0300-\u036F]/g,"").toLowerCase().replaceAll(/[\s\-_]+/g," ").trim()}function pI($){return $.normalize("NFD").replaceAll(/[\u0300-\u036F]/g,"").toLowerCase().replaceAll(/[^a-z0-9]+/g,"_").replace(/^_/,"").replace(/_$/,"")}function cH($){return dI.has($)||$.includes("telefone")||$.includes("phone")||$.includes("celular")}function tI($){return oI.has($)}function Qq($){let U={},K={},q=new Set,Q=!1,W=!1;function G(j){let Y=j,H=2;while(q.has(Y))Y=`${j}_${String(H)}`,H+=1;return q.add(Y),Y}for(let j of $){let Y=nI(j);if(Y===""){U[j]="ignore";continue}if(cH(Y)&&!Q){U[j]="phone",Q=!0;continue}if(tI(Y)&&!W&&!cH(Y)){U[j]="name",W=!0;continue}let H=pI(j);if(H===""){U[j]="ignore";continue}U[j]="custom",K[j]=G(H)}return{roles:U,customNames:K}}var _4={_nodes:{start:{name:"Start",description:"Where every call begins — receives caller ID, DID, and timestamp"},playback:{name:"Playback",description:"Plays a message using text-to-speech or an audio file"},ivr:{name:"IVR Menu",description:"Presents a menu and routes the call based on the digit pressed"},collectDigits:{name:"Collect Digits",description:"Collects a sequence of digits like CPF, account number, or PIN"},transfer:{name:"Transfer",description:"Bridges or redirects the call to an agent, queue, or external number"},hangup:{name:"Hang Up",description:"Terminates the call — place at the end of each plan path"},timeRouting:{name:"Schedule",description:"Checks the current time against a schedule to route on/off hours"},switchCase:{name:"Condition",description:"Evaluates a variable against regex patterns to pick a path"},trafficSplit:{name:"Traffic Split",description:"Distributes calls across several paths by percentage — A/B testing, load balancing between destinations and canary rollout"},setVariable:{name:"Set Variable",description:"Saves a value to reuse later during plan execution"},sequence:{name:"Sequence",description:"Generates sequential numbers for protocols, tickets, or any identifier — DB-backed, never regresses"},counter:{name:"Counter",description:"Counts attempts, events, or anything else — per call or across calls, with an optional limit output"},httpRequest:{name:"HTTP Request",description:"Calls a REST API and stores the response for downstream nodes"},webhook:{name:"Webhook",description:"Fires an HTTP call to an external system and moves on without waiting"},dataTransform:{name:"Transform Data",description:"Applies text, number, date, list, phone, and speech operations to a value without writing code"},sendDtmf:{name:"Send DTMF",description:"Sends DTMF tones to a bridged channel or PBX"},subPlan:{name:"Sub-Plan",description:"Delegates execution to another published plan and returns"},aiAgent:{name:"AI Agent",description:"Hands the call to an AI agent for free-form conversation"},retellAgent:{name:"Retell Agent",description:"Hands the call to a Retell voice agent"},vapiAgent:{name:"Vapi Agent",description:"Hands the call to a Vapi voice assistant"},elevenlabsAgent:{name:"ElevenLabs Agent",description:"Hands the call to an ElevenLabs voice agent"},voiceRecognition:{name:"Voice Recognition",description:"Listens to the caller, transcribes speech, and routes by intent"},tell:{name:"Message",description:"Says something to the user — plays audio in voice, sends a message in chat"},menu:{name:"Menu",description:"Presents options and routes by the user's choice — DTMF in voice, buttons in chat"},capture:{name:"Capture",description:"Collects user input — DTMF digits or speech in voice, text in chat"},routeAi:{name:"AI Classifier",description:"Classifies text via AI and routes by intent — a smart condition"},channelRouter:{name:"Channel",description:"Routes the plan based on the active channel mode (voice or chat)"},apiSwitch:{name:"API Switch",description:"Plays a prompt, collects digits, calls an API, and routes by response attribute (legacy)"},enableRecord:{name:"Enable Recording",description:"Activates call recording during plan execution with sampling and analysis options (legacy)"},recording:{name:"Recording",description:"Starts or stops recording from this point in the plan"},transcription:{name:"Transcription",description:"Chooses the transcription scope from this point in the plan"},analysis:{name:"Analysis",description:"Chooses analyses for all available transcription; each block overrides only defined fields"},whatsappTemplate:{name:"Send WhatsApp template",description:"Sends an approved Meta template through WhatsApp Business, in a voice call or in chat"},sendSms:{name:"Send SMS",description:"Sends a text message through Twilio, in a voice call or in chat"},phoneLookup:{name:"Phone lookup",description:"Checks a number's format and, optionally, its line type and carrier through Twilio Lookup"},verifyCode:{name:"Verify code",description:"Sends a verification code through Twilio Verify and checks it, in a voice call or in chat"},addToDnc:{name:"Add to DNC",description:"Adds the contact's number to the organization's do-not-call list — opt-out from inside the plan"}},_audio:{tts:{text:"Text to synthesize into speech.",voice:"TTS voice ID (e.g., 'pt-BR-FranciscaNeural').",model:"TTS model to use (default: 'edge')."},file:{id:"Audio file ID from the audio library.",name:"Display name of the audio file.",path:"Storage path of the audio file."},url:{value:"Audio URL fetched at call time. Supports {{variables}}; secrets are not allowed.",fallbackTts:"Spoken when the URL fails. Absent means take the error output."}},start:{autoAnswer:"Auto-answer incoming call before processing. Disable for pre-answer routing.",channelType:"Plan channel type."},playback:{audio:"Audio to play. Use TTS (text-to-speech) or a pre-recorded audio file."},hangup:{cause:"SIP hangup cause code (e.g., 'NORMAL_CLEARING'). Omit for default."},ivr:{audio:"Audio prompt played before collecting DTMF input.",timeout:"Seconds to wait for DTMF input after audio finishes (1-60).",maxAttempts:"Maximum retry attempts before following the error output (1-10)."},collectDigits:{audio:"Audio prompt played before collecting digits.",minDigits:"Minimum number of digits required (1-20).",maxDigits:"Maximum number of digits to collect (1-20).",terminator:"Key that terminates digit collection (e.g., '#'). Single character.",timeout:"Seconds to wait for the first digit after audio finishes (1-60).",interDigitTimeout:"Seconds to wait between consecutive digits (1-30).",maxAttempts:"Maximum retry attempts on invalid input (1-10).",invalidAudio:"Audio played when input fails regex validation. Optional.",regex:"Regex pattern to validate collected digits. Empty means accept any.",resetDigit:"Key that clears collected digits and restarts. Single character. Empty to disable."},transfer:{method:"Transfer method. 'bridge' keeps call control; 'transfer' hands off completely.",destinations:"SIP URIs or phone numbers to dial. At least one required. Tried in order.",timeout:"Ring timeout in seconds per destination (5-120). Omit for carrier default.",attachedData:"Key/value pairs delivered to the agent at transfer (screen-pop). Values support templates."},timeRouting:{scheduleId:"Schedule ID for time-based routing. Routes to onHours/offHours/holiday outputs."},switchCase:{expression:"Template expression to evaluate, e.g., '{{ivr.digits}}'. Matched against case patterns.",cases:"List of patterns to match. Each creates a dynamic output handle 'match:<pattern>'."},trafficSplit:{paths:"Weighted paths. Each creates a dynamic output handle 'path:<name>'.",mode:"'contact' keeps the same contact on the same path (stateless hash); 'call' draws per call (stateless, approximate); 'exact' rotates through a Redis counter so the proportion closes even at low volume."},setVariable:{assignments:"List of variable assignments. At least one required."},counter:{name:"Counter name. Supports templates, e.g. 'attempts_{{start.callerid}}'.",action:"Operation applied to the counter. 'reset' sets it to zero and ignores step.",step:"Amount added or subtracted on each execution (1-1000000). Ignored when the action is 'reset'.",limit:"Value that routes to the 'limitReached' output once the counter reaches it. Empty means count only.",scope:"'call' starts from zero on every call; 'plan' persists across the calls of one plan; 'organization' persists across every plan of the organization.",ttlSeconds:"Lifetime in seconds of a 'plan' or 'organization' counter (60-31536000). Applied when the key is created, so counting does not renew the window."},httpRequest:{method:"HTTP method for the request.",url:"Request URL. Supports template expressions, e.g., 'https://api.example.com/{{start.callerid}}'.",headers:"HTTP headers as key-value pairs. Values support template expressions.",body:"Request body (JSON string). Template expressions allowed. Only for POST/PUT/PATCH.",timeout:"Request timeout in milliseconds. Omit for default."},webhook:{method:"HTTP method for the request.",url:"Destination URL. Supports template expressions, e.g., 'https://hooks.example.com/{{start.callerid}}'.",headers:"HTTP headers as key-value pairs. Values support template expressions.",body:"Request body (JSON string). Template expressions allowed. Only for POST/PUT/PATCH/DELETE."},dataTransform:{steps:"Ordered list of transformation steps. Each step transforms a value and saves the result under a name.",onError:"What to do when a step fails: 'error' follows the error output, 'empty' continues with an empty value."},subPlan:{planId:"ID of a published visual plan to execute as a subplan. Must be published."},sendDtmf:{digits:"DTMF digits to send (0-9, *, #). Supports template expressions."},aiAgent:{agent_id:"SipPulse AI agent ID to invoke. Required for execution.",agent_name:"Display name for the AI agent (used in logs and UI).",additional_instructions:"Extra instructions appended to the agent's system prompt.",variables:"Key-value pairs passed to the agent as context variables.",initial_message:"First message the agent speaks when the conversation starts.",max_duration_minutes:"Maximum conversation duration in minutes (1-60). Call ends on timeout."},retellAgent:{connector_id:"Connector that provides the voice.agent capability, such as a Retell account.",agent_id:"ID of the Retell agent that answers the call. Required for execution.",agent_name:"Display name of the chosen agent, used in logs and the editor.",variables:"Key-value pairs sent to the agent. Every value supports {{variables}}.",max_duration_minutes:"Maximum call duration in minutes (1-60). The bridge ends on timeout.",result_wait_seconds:"How long to wait for Retell's post-call extraction before continuing (0-60)."},vapiAgent:{connector_id:"Connector that provides the voice.agent capability, such as a Vapi account.",assistant_id:"ID of the Vapi assistant that answers the call. Required for execution.",assistant_name:"Display name of the chosen assistant, used in logs and the editor.",variables:"Key-value pairs sent to the agent. Every value supports {{variables}}.",max_duration_minutes:"Maximum call duration in minutes (1-60). The bridge ends on timeout.",result_wait_seconds:"How long to wait for Vapi's end of call report before continuing (0-60)."},elevenlabsAgent:{connector_id:"Connector that provides the voice.agent capability, such as an ElevenLabs account.",agent_id:"ID of the ElevenLabs agent that answers the call. Required for execution.",agent_name:"Display name of the chosen agent, used in logs and the editor.",variables:"Key-value pairs sent to the agent as X-<name> SIP headers. Every value supports {{variables}}.",max_duration_minutes:"Maximum call duration in minutes (1-60). The bridge ends on timeout.",result_wait_seconds:"How long to wait for ElevenLabs' post-call analysis before continuing (0-60)."},voiceRecognition:{mode:"'intent' classifies speech into configured intents; 'capture' transcribes without classification.",prompt:"Audio prompt played before listening for speech.",intents:"List of intents the LLM should classify speech into. Each creates a dynamic output. Only used in intent mode.",classification_instructions:"Additional instructions for the LLM intent classifier. Only used in intent mode.",listen:"Listening configuration: silence timeout, max duration, language, beep.",processing_audio:"Audio played while the AI processes the speech. Optional.",retry:"Retry behavior: max attempts and alternative prompt when speech is not recognized."},tell:{audio:"Audio to play via TTS, a pre-recorded file, or a remote URL. Used in voice plans.",content:"Message content to send in chat. Used in chat plans."},menu:{options:"Menu options. Each creates a dynamic output handle.",audio:"Voice audio prompt played before collecting DTMF input.",text:"Chat message text displayed above buttons. Supports template expressions.",voiceTimeout:"Seconds to wait for DTMF input in voice mode (1-60).",maxAttempts:"Maximum retry attempts for invalid input before following noMatch (1-10).",invalidMessage:"Chat message sent when input doesn't match any option. Supports template expressions."},capture:{audio:"Audio prompt played before collecting input in voice mode.",voiceMethod:"Voice input method: 'dtmf' for digits, 'speech' for ASR transcription (requires AI).",minDigits:"Minimum number of DTMF digits required (1-20).",maxDigits:"Maximum number of DTMF digits to collect (1-20).",terminators:"Key that terminates digit collection (e.g., '#').",voiceTimeout:"Seconds to wait for input in voice mode (1-60).",listen:"Listening configuration for speech capture: silence detection, max duration, language.",processing_audio:"Audio played while ASR processes the speech. Optional.",retryAudio:"Audio played on retry instead of main prompt. Falls back to main if not set.",text:"Chat prompt message sent before waiting for user input.",validation:"Regex pattern to validate chat text input. Invalid input triggers retry.",invalidMessage:"Chat message sent when input fails validation.",maxAttempts:"Maximum retry attempts for invalid or empty input (1-10)."},routeAi:{input:"Template expression to evaluate. The resolved text is classified by AI.",intents:"List of intents the AI should classify the input into. Each creates a dynamic output handle.",instructions:"Additional instructions for the AI intent classifier."},channelRouter:{},apiSwitch:{audio:"Audio prompt played before collecting digits.",chatText:"Text prompt for chat mode. Supports {{variables}}.",timeout:"Seconds to wait for digit input (1-60).",maxAttempts:"Maximum retry attempts for digit collection (1-10).",digitRegex:"Regex to validate DTMF input. Empty means accept any.",method:"HTTP method for the API request.",url:"API endpoint URL. Supports {{variables}} including collected digits as {{digits}}.",headers:"HTTP headers as key-value pairs.",body:"Request body (JSON). Supports {{variables}}. Only for POST/PUT.",requestTimeout:"HTTP request timeout in milliseconds.",attribute:"JSON attribute name from the API response to match against cases.",cases:"Possible attribute values. Each creates a dynamic output handle 'match:<value>'."},enableRecord:{percentage:"Percentage of calls to record (0-100). 100 records all calls.",minDuration:"Minimum call duration in seconds before recording starts. 0 for immediate.",analyzeCalls:"Enable post-call AI analysis (requires AI module)."},recording:{enabled:"Start or stop recording from this point",samplingPercentage:"Recording sampling percentage when recording starts"},transcription:{enabled:"Start or stop transcription at this point",samplingPercentage:"Percentage of selected recordings that will be transcribed",scope:"Transcription scope: 'from_here' uses audio recorded from this point (default/legacy); 'whole_recording' includes all audio already recorded and continues until transcription is disabled",language:"Language applied to the whole transcription",minDurationSeconds:"Minimum duration applied to the whole transcription",speechRequirement:"Skip calls without conversation, applied to the whole transcription: none, both (caller and IVR) or caller (caller only)",anonymizeEnabled:"Anonymize the whole transcript",sentimentEnabled:"Enable sentiment analysis for all available transcription; omitted fields remain inherited",transcriptionType:"Transcription type: 'post_call' transcribes when the call ends; 'live' also transcribes during the call, billed per recorded minute"},analysis:{speechAnalyticsEnabled:"Enable call summary for all available transcription; omitted fields remain inherited",sentimentEnabled:"Enable sentiment analysis for all available transcription; omitted fields remain inherited",topicDetectionTopics:"Topics for all available transcription; omitted fields remain inherited",intentDetectionIntents:"Intents for all available transcription; omitted fields remain inherited",structuredAnalysisEnabled:"Enable structured analyses for all available transcription; omitted fields remain inherited",structuredAnalysisIds:"Structured analysis IDs for all available transcription; omitted fields remain inherited"},whatsappTemplate:{connectorId:"Connector that provides the WhatsApp templates capability (whatsapp.templates).",phoneNumberId:"Number the message is sent from, one of the connector's numbers.",template:"Approved template to send, by name and language (e.g. boleto / pt_BR).",to:"Recipient. Supports {{variables}}. A number without a country code gets the block's default country code.",defaultCountry:"Country that completes numbers written without a country code. Empty uses the organization's default country.",parameters:"Template variable values. Keys: variable number or name; a media header takes the URL; a URL button takes the suffix. Supports {{variables}}."},sendSms:{connector_id:"Connector that provides the sms.send capability, such as a Twilio account.",from:"Sender. Empty uses the connector's default sender; otherwise a Messaging Service SID (MG...) or an E.164 number.",to:"Recipient. Supports {{variables}}. A number without a country code gets the block's default country code.",default_country:"Country that completes numbers written without a country code. Empty uses the organization's default country.",body:"Message text. Supports {{variables}}; secrets are not allowed in the body.",transliterate:"Replace accented letters by their base letter before sending, so the message fits 160 characters per SMS instead of 70."},phoneLookup:{connector_id:"Connector that provides the phone.lookup capability, such as a Twilio account.",number:"Number to look up. Supports {{variables}}. A number without a country code gets the block's default country code.",default_country:"Country that completes numbers written without a country code. Empty uses the organization's default country.",line_type:"Also fetch line type and carrier. Twilio charges US$ 0,008 per query; format validation alone is free.",line_type_error:"Twilio's own code and message when it could not identify the line type; empty when it did."},verifyCode:{connector_id:"Connector that provides the verify.otp capability, such as a Twilio account.",service_sid:"Verify Service SID (VA...) whose code length and sender configuration the block uses.",to:"Recipient. Supports {{variables}}. A number without a country code gets the block's default country code.",default_country:"Country that completes numbers written without a country code. Empty uses the organization's default country.",channel:"How the code reaches the contact: sms, whatsapp or call.",prompt:"Audio prompt asking for the code, played with the plan's voice. In chat, its text is sent.",max_attempts:"Maximum wrong-code attempts before the block leaves by rejected (1-5).",timeout_seconds:"Seconds to wait for the code after the prompt (1-60)."},addToDnc:{reason:"Optional short reason recorded on the DNC entry (max 128 chars). Plain text, no templates.",phoneOverride:"Optional number/template to add instead of the auto-resolved one. Supports {{variables}}. Empty auto-resolves the dialer contact, then the caller ID."}};var E3={_nodes:{start:{name:"Início",description:"Onde toda chamada começa — recebe caller ID, DID e timestamp"},playback:{name:"Reprodução",description:"Reproduz uma mensagem usando TTS ou arquivo de áudio"},ivr:{name:"Menu IVR",description:"Apresenta um menu e roteia a chamada pelo dígito pressionado"},collectDigits:{name:"Coletar Dígitos",description:"Coleta uma sequência de dígitos como CPF, número de conta ou PIN"},transfer:{name:"Transferência",description:"Conecta ou redireciona a chamada para agente, fila ou número externo"},hangup:{name:"Desligar",description:"Encerra a chamada — coloque no final de cada caminho do plano"},timeRouting:{name:"Agenda",description:"Verifica o horário atual contra uma agenda para rotear dentro/fora do expediente"},switchCase:{name:"Condição",description:"Avalia uma variável contra padrões regex para escolher um caminho"},trafficSplit:{name:"Dividir tráfego",description:"Distribuidor de chamadas por percentual entre vários caminhos — teste A/B, balanceamento entre destinos e rampa de canário"},setVariable:{name:"Definir Variável",description:"Salva um valor para reusar depois durante a execução do plano"},sequence:{name:"Sequência",description:"Gera números sequenciais para protocolos, tickets ou qualquer identificador — durável em banco, nunca regride"},counter:{name:"Contador",description:"Conta tentativas, eventos ou qualquer coisa — por chamada ou entre chamadas, com saída opcional de limite"},httpRequest:{name:"Requisição HTTP",description:"Chama uma API REST e armazena a resposta para os blocos seguintes"},webhook:{name:"Webhook",description:"Dispara uma chamada HTTP para um sistema externo e segue sem esperar"},dataTransform:{name:"Transformar Dados",description:"Aplica operações de texto, número, data, lista, telefone e fala sobre um valor sem escrever código"},sendDtmf:{name:"Enviar DTMF",description:"Envia tons DTMF para o canal conectado ou PBX"},subPlan:{name:"Sub-Plano",description:"Delega execução para outro plano publicado e retorna"},aiAgent:{name:"Agente de IA",description:"Entrega a chamada para um agente IA para conversa livre"},retellAgent:{name:"Agente Retell",description:"Entrega a chamada para um agente de voz da Retell"},vapiAgent:{name:"Agente Vapi",description:"Entrega a chamada para um assistente de voz da Vapi"},elevenlabsAgent:{name:"Agente ElevenLabs",description:"Entrega a chamada para um agente de voz da ElevenLabs"},voiceRecognition:{name:"Reconhecimento de Voz",description:"Ouve o chamador, transcreve a fala e roteia por intenção"},tell:{name:"Mensagem",description:"Diz algo ao usuário — reproduz áudio na voz, envia mensagem no chat"},menu:{name:"Menu",description:"Apresenta opções e roteia pela escolha do usuário — DTMF na voz, botões no chat"},capture:{name:"Captura",description:"Coleta entrada do usuário — dígitos DTMF ou fala na voz, texto no chat"},routeAi:{name:"Classificador IA",description:"Classifica texto via IA e roteia por intenção — uma condição inteligente"},channelRouter:{name:"Canal",description:"Roteia o plano com base no modo ativo do canal (voz ou chat)"},apiSwitch:{name:"API Switch",description:"Reproduz prompt, coleta dígitos, chama API e roteia pelo atributo da resposta (legado)"},enableRecord:{name:"Ativar Gravação",description:"Ativa gravação da chamada durante o plano com amostragem e análise (legado)"},recording:{name:"Gravação",description:"Inicia ou encerra a gravação a partir deste ponto do plano"},transcription:{name:"Transcrição",description:"Escolhe o escopo da transcrição a partir deste ponto do plano"},analysis:{name:"Análise",description:"Escolhe análises para toda a transcrição disponível; cada bloco sobrescreve apenas os campos definidos"},whatsappTemplate:{name:"Enviar template WhatsApp",description:"Envia um template aprovado da Meta pelo WhatsApp Business, em chamada de voz ou em chat"},sendSms:{name:"Enviar SMS",description:"Envia uma mensagem de texto pela Twilio, em chamada de voz ou em chat"},phoneLookup:{name:"Consultar número",description:"Confere o formato do número e, se pedido, o tipo de linha e a operadora pela Twilio Lookup"},verifyCode:{name:"Verificar código",description:"Envia um código de verificação pela Twilio Verify e confere, em chamada de voz ou em chat"},addToDnc:{name:"Adicionar à DNC",description:"Adiciona o número do contato à lista de não perturbe da organização — opt-out de dentro do plano"}},_audio:{tts:{text:"Texto para sintetizar em fala.",voice:"ID da voz TTS (ex: 'pt-BR-FranciscaNeural').",model:"Modelo TTS a utilizar (padrão: 'edge')."},file:{id:"ID do arquivo de áudio da biblioteca.",name:"Nome de exibição do arquivo de áudio.",path:"Caminho de armazenamento do arquivo de áudio."},url:{value:"URL do áudio, buscada na hora da chamada. Aceita {{variáveis}}; secrets não são permitidos.",fallbackTts:"Falado quando a URL falha. Se estiver vazio, o nó segue pela saída de erro."}},start:{autoAnswer:"Atender chamada automaticamente antes de processar. Desabilite para roteamento pré-atendimento.",channelType:"Tipo de canal do plano."},playback:{audio:"Áudio para reproduzir. Use TTS (texto para fala) ou arquivo de áudio pré-gravado."},hangup:{cause:"Código de causa SIP para desligamento (ex: 'NORMAL_CLEARING'). Omita para padrão."},ivr:{audio:"Prompt de áudio reproduzido antes de coletar entrada DTMF.",timeout:"Segundos de espera por entrada DTMF após o áudio (1-60).",maxAttempts:"Máximo de tentativas antes de seguir pela saída de erro (1-10)."},collectDigits:{audio:"Prompt de áudio reproduzido antes de coletar dígitos.",minDigits:"Número mínimo de dígitos necessários (1-20).",maxDigits:"Número máximo de dígitos a coletar (1-20).",terminator:"Tecla que encerra a coleta de dígitos (ex: '#'). Um caractere.",timeout:"Segundos de espera pelo primeiro dígito após o áudio (1-60).",interDigitTimeout:"Segundos de espera entre dígitos consecutivos (1-30).",maxAttempts:"Máximo de tentativas em entrada inválida (1-10).",invalidAudio:"Áudio reproduzido quando a entrada falha na validação regex. Opcional.",regex:"Padrão regex para validar dígitos coletados. Vazio aceita qualquer entrada.",resetDigit:"Tecla que limpa dígitos coletados e reinicia. Um caractere. Vazio para desabilitar."},transfer:{method:"Método de transferência. 'bridge' mantém controle da chamada; 'transfer' transfere completamente.",destinations:"URIs SIP ou números de telefone para discar. Pelo menos um obrigatório. Tentados em ordem.",timeout:"Timeout de toque em segundos por destino (5-120). Omita para padrão da operadora.",attachedData:"Pares chave/valor entregues ao atendente na transferência (screen-pop). Valores aceitam templates."},timeRouting:{scheduleId:"ID da agenda para roteamento por horário. Direciona para saídas onHours/offHours/holiday."},switchCase:{expression:"Expressão template a avaliar, ex: '{{ivr.digits}}'. Comparada com os padrões dos cases.",cases:"Lista de padrões para comparar. Cada um cria uma saída dinâmica 'match:<padrão>'."},trafficSplit:{paths:"Caminhos com peso. Cada um cria uma saída dinâmica 'path:<nome>'.",mode:"'contact' mantém o mesmo contato sempre no mesmo caminho (hash sem estado); 'call' sorteia a cada chamada (sem estado, aproximado); 'exact' usa um rodízio contado no Redis e fecha a proporção mesmo em volume baixo."},setVariable:{assignments:"Lista de atribuições de variáveis. Pelo menos uma obrigatória."},counter:{name:"Nome do contador. Suporta templates, ex: 'tentativas_{{start.callerid}}'.",action:"Operação aplicada ao contador. 'reset' zera o contador e ignora o passo.",step:"Quantidade somada ou subtraída a cada execução (1-1000000). Ignorada quando a ação é 'reset'.",limit:"Valor que direciona para a saída 'limitReached' quando o contador o alcança. Vazio apenas conta.",scope:"'call' começa do zero a cada chamada; 'plan' persiste entre as chamadas de um plano; 'organization' persiste entre todos os planos da organização.",ttlSeconds:"Tempo de vida em segundos de um contador de escopo 'plan' ou 'organization' (60-31536000). Aplicado na criação da chave, então contar não renova a janela."},httpRequest:{method:"Método HTTP da requisição.",url:"URL da requisição. Suporta expressões template, ex: 'https://api.example.com/{{start.callerid}}'.",headers:"Cabeçalhos HTTP como pares chave-valor. Valores suportam expressões template.",body:"Corpo da requisição (string JSON). Expressões template permitidas. Apenas para POST/PUT/PATCH.",timeout:"Timeout da requisição em milissegundos. Omita para padrão."},webhook:{method:"Método HTTP da requisição.",url:"URL de destino. Suporta expressões template, ex: 'https://hooks.example.com/{{start.callerid}}'.",headers:"Cabeçalhos HTTP como pares chave-valor. Valores suportam expressões template.",body:"Corpo da requisição (string JSON). Expressões template permitidas. Apenas para POST/PUT/PATCH/DELETE."},dataTransform:{steps:"Lista ordenada de passos de transformação. Cada passo transforma um valor e salva o resultado num nome.",onError:"O que fazer quando um passo falha: 'error' segue pela saída de erro, 'empty' continua com um valor vazio."},subPlan:{planId:"ID de um plano visual publicado para executar como subplano. Deve estar publicado."},sendDtmf:{digits:"Dígitos DTMF para enviar (0-9, *, #). Suporta expressões template."},aiAgent:{agent_id:"ID do agente SipPulse AI a invocar. Obrigatório para execução.",agent_name:"Nome de exibição do agente AI (usado em logs e na interface).",additional_instructions:"Instruções extras adicionadas ao prompt do sistema do agente.",variables:"Pares chave-valor passados ao agente como variáveis de contexto.",initial_message:"Primeira mensagem que o agente fala ao iniciar a conversa.",max_duration_minutes:"Duração máxima da conversa em minutos (1-60). Chamada encerra no timeout."},retellAgent:{connector_id:"Conector com a capacidade de agente de voz (voice.agent), como uma conta Retell.",agent_id:"ID do agente da Retell que atende a ligação. Obrigatório para execução.",agent_name:"Nome de exibição do agente escolhido, usado nos logs e no editor.",variables:"Pares chave-valor enviados ao agente. Cada valor aceita {{variáveis}}.",max_duration_minutes:"Duração máxima da chamada em minutos (1-60). A ponte encerra no timeout.",result_wait_seconds:"Tempo de espera pela extração pós-chamada da Retell antes de seguir (0-60)."},vapiAgent:{connector_id:"Conector com a capacidade de agente de voz (voice.agent), como uma conta Vapi.",assistant_id:"ID do assistente da Vapi que atende a ligação. Obrigatório para execução.",assistant_name:"Nome de exibição do assistente escolhido, usado nos logs e no editor.",variables:"Pares chave-valor enviados ao agente. Cada valor aceita {{variáveis}}.",max_duration_minutes:"Duração máxima da chamada em minutos (1-60). A ponte encerra no timeout.",result_wait_seconds:"Tempo de espera pelo relatório da Vapi antes de seguir (0-60)."},elevenlabsAgent:{connector_id:"Conector com a capacidade de agente de voz (voice.agent), como uma conta ElevenLabs.",agent_id:"ID do agente da ElevenLabs que atende a ligação. Obrigatório para execução.",agent_name:"Nome de exibição do agente escolhido, usado nos logs e no editor.",variables:"Pares chave-valor enviados ao agente como cabeçalhos SIP X-<nome>. Cada valor aceita {{variáveis}}.",max_duration_minutes:"Duração máxima da chamada em minutos (1-60). A ponte encerra no timeout.",result_wait_seconds:"Tempo de espera pela análise pós-chamada da ElevenLabs antes de seguir (0-60)."},voiceRecognition:{mode:"'intent' classifica a fala em intenções configuradas; 'capture' transcreve sem classificação.",prompt:"Prompt de áudio reproduzido antes de escutar a fala.",intents:"Lista de intenções para o LLM classificar a fala. Cada uma cria uma saída dinâmica. Só usado no modo intent.",classification_instructions:"Instruções adicionais para o classificador de intenções do LLM. Só usado no modo intent.",listen:"Configuração de escuta: timeout de silêncio, duração máxima, idioma, beep.",processing_audio:"Áudio reproduzido enquanto a IA processa a fala. Opcional.",retry:"Comportamento de retentativa: máximo de tentativas e prompt alternativo quando a fala não é reconhecida."},tell:{audio:"Áudio para reproduzir via TTS, arquivo pré-gravado ou URL remota. Usado em planos de voz.",content:"Conteúdo da mensagem a enviar no chat. Usado em planos de chat."},menu:{options:"Opções do menu. Cada uma cria uma saída dinâmica.",audio:"Prompt de áudio reproduzido antes de coletar entrada DTMF na voz.",text:"Texto da mensagem no chat, exibido acima dos botões. Suporta expressões template.",voiceTimeout:"Segundos de espera por entrada DTMF no modo voz (1-60).",maxAttempts:"Máximo de tentativas para entrada inválida antes de seguir pela saída noMatch (1-10).",invalidMessage:"Mensagem enviada no chat quando a entrada não corresponde a nenhuma opção. Suporta expressões template."},capture:{audio:"Prompt de áudio reproduzido antes de coletar entrada no modo voz.",voiceMethod:"Método de entrada por voz: 'dtmf' para dígitos, 'speech' para transcrição ASR (requer IA).",minDigits:"Número mínimo de dígitos DTMF necessários (1-20).",maxDigits:"Número máximo de dígitos DTMF a coletar (1-20).",terminators:"Tecla que encerra a coleta de dígitos (ex: '#').",voiceTimeout:"Segundos de espera por entrada no modo voz (1-60).",listen:"Configuração de escuta para captura de fala: detecção de silêncio, duração máxima, idioma.",processing_audio:"Áudio reproduzido enquanto o ASR processa a fala. Opcional.",retryAudio:"Áudio reproduzido na retentativa ao invés do prompt principal. Usa o principal se não definido.",text:"Mensagem de prompt no chat enviada antes de aguardar a entrada do usuário.",validation:"Padrão regex para validar a entrada de texto no chat. Entrada inválida aciona retentativa.",invalidMessage:"Mensagem enviada no chat quando a entrada falha na validação.",maxAttempts:"Máximo de tentativas para entrada inválida ou vazia (1-10)."},routeAi:{input:"Expressão template para avaliar. O texto resolvido é classificado pela IA.",intents:"Lista de intenções para a IA classificar a entrada. Cada uma cria uma saída dinâmica.",instructions:"Instruções adicionais para o classificador de intenções da IA."},channelRouter:{},apiSwitch:{audio:"Prompt de áudio reproduzido antes de coletar dígitos.",chatText:"Prompt de texto para modo chat. Suporta {{variáveis}}.",timeout:"Segundos de espera por entrada de dígito (1-60).",maxAttempts:"Máximo de tentativas para coleta de dígitos (1-10).",digitRegex:"Regex para validar entrada DTMF. Vazio aceita qualquer entrada.",method:"Método HTTP da requisição à API.",url:"URL do endpoint da API. Suporta {{variáveis}} incluindo dígitos coletados como {{digits}}.",headers:"Cabeçalhos HTTP como pares chave-valor.",body:"Corpo da requisição (JSON). Suporta {{variáveis}}. Apenas para POST/PUT.",requestTimeout:"Timeout da requisição HTTP em milissegundos.",attribute:"Nome do atributo JSON da resposta da API para comparar com os cases.",cases:"Valores possíveis do atributo. Cada um cria uma saída dinâmica 'match:<valor>'."},enableRecord:{percentage:"Porcentagem de chamadas a gravar (0-100). 100 grava todas.",minDuration:"Duração mínima da chamada em segundos antes de iniciar a gravação. 0 para imediato.",analyzeCalls:"Ativar análise pós-chamada por IA (requer módulo AI)."},recording:{enabled:"Iniciar ou encerrar a gravação a partir deste ponto",samplingPercentage:"Porcentagem de amostragem quando a gravação começa"},transcription:{enabled:"Iniciar ou encerrar a transcrição a partir deste ponto",samplingPercentage:"Percentual das gravações selecionadas que serão transcritas",scope:"Escopo da transcrição: 'from_here' usa o áudio gravado a partir deste ponto (padrão/legado); 'whole_recording' inclui todo o áudio já gravado e continua até a transcrição ser desligada",language:"Idioma aplicado à transcrição inteira",minDurationSeconds:"Duração mínima aplicada à transcrição inteira",speechRequirement:"Pular chamadas sem conversa, aplicado à transcrição inteira: none, both (cliente e URA) ou caller (só o cliente)",anonymizeEnabled:"Anonimizar a transcrição inteira",sentimentEnabled:"Ativar análise de sentimento para toda a transcrição disponível; campos omitidos são herdados",transcriptionType:"Tipo de transcrição: 'post_call' transcreve quando a chamada termina; 'live' também transcreve durante a chamada, custo por minuto gravado"},analysis:{speechAnalyticsEnabled:"Ativar resumo da chamada para toda a transcrição disponível; campos omitidos são herdados",sentimentEnabled:"Ativar análise de sentimento para toda a transcrição disponível; campos omitidos são herdados",topicDetectionTopics:"Tópicos para toda a transcrição disponível; campos omitidos são herdados",intentDetectionIntents:"Intenções para toda a transcrição disponível; campos omitidos são herdados",structuredAnalysisEnabled:"Ativar análises estruturadas para toda a transcrição disponível; campos omitidos são herdados",structuredAnalysisIds:"IDs das análises estruturadas para toda a transcrição disponível; campos omitidos são herdados"},whatsappTemplate:{connectorId:"Conector com a capacidade de templates do WhatsApp (whatsapp.templates).",phoneNumberId:"Número de origem da mensagem, entre os números do conector.",template:"Template aprovado a enviar, por nome e idioma (ex.: boleto / pt_BR).",to:"Destinatário. Suporta {{variáveis}}. Número sem DDI recebe o DDI padrão do bloco.",defaultCountry:"País que completa os números escritos sem DDI. Vazio usa o país padrão da organização.",parameters:"Valores das variáveis do template. Chaves: número ou nome da variável; cabeçalho de mídia recebe a URL; botão de URL recebe o sufixo. Suporta {{variáveis}}."},sendSms:{connector_id:"Conector com a capacidade sms.send, como uma conta da Twilio.",from:"Remetente. Vazio usa o remetente padrão do conector; senão, um Messaging Service SID (MG...) ou um número E.164.",to:"Destinatário. Suporta {{variáveis}}. Número sem DDI recebe o DDI padrão do bloco.",default_country:"País que completa os números escritos sem DDI. Vazio usa o país padrão da organização.",body:"Texto da mensagem. Suporta {{variáveis}}; segredos não são permitidos no corpo.",transliterate:"Troca letras acentuadas pela letra sem acento antes de enviar, para caber 160 caracteres por SMS em vez de 70."},phoneLookup:{connector_id:"Conector com a capacidade phone.lookup, como uma conta da Twilio.",number:"Número a consultar. Suporta {{variáveis}}. Número sem DDI recebe o DDI padrão do bloco.",default_country:"País que completa os números escritos sem DDI. Vazio usa o país padrão da organização.",line_type:"Busca também o tipo de linha e a operadora. A Twilio cobra US$ 0,008 por consulta; só validar o formato é grátis.",line_type_error:"Código e mensagem da própria Twilio quando ela não conseguiu identificar o tipo de linha; vazio quando conseguiu."},verifyCode:{connector_id:"Conector com a capacidade verify.otp, como uma conta da Twilio.",service_sid:"SID do Serviço do Verify (VA...) cujo tamanho de código e remetente o bloco usa.",to:"Destinatário. Suporta {{variáveis}}. Número sem DDI recebe o DDI padrão do bloco.",default_country:"País que completa os números escritos sem DDI. Vazio usa o país padrão da organização.",channel:"Como o código chega ao contato: sms, whatsapp ou ligação.",prompt:"Áudio que pede o código, falado com a voz do plano. No chat, o texto dele é enviado.",max_attempts:"Máximo de códigos errados antes de o bloco sair por Recusado (1-5).",timeout_seconds:"Segundos de espera pelo código depois do aviso (1-60)."},addToDnc:{reason:"Motivo curto opcional registrado na entrada da DNC (máx. 128 caracteres). Texto simples, sem templates.",phoneOverride:"Número/template opcional a adicionar no lugar do resolvido automaticamente. Suporta {{variáveis}}. Vazio resolve o contato do discador e, depois, o caller ID."}};var aI={en:_4,"pt-BR":E3};function Kq($,U="en"){return aI[U]._nodes?.[$]}var lH=["core","ai","queues","dialer","omnichannel","enterprise"],sI=lH.filter(($)=>$!=="core");function I4($,U){return typeof $.outputs==="function"?$.outputs(U):$.outputs}var rH={interaction:{order:0},handling:{order:1},routing:{order:2},media:{order:3},data:{order:4},legacy:{order:5}},eI=Object.entries(rH).sort(([,$],[,U])=>$.order-U.order).map(([$])=>$);var qq=J.object({reason:J.string().max(128,{error:"editor:validation.dncReasonTooLong"}).default("").describe("Optional short reason recorded on the DNC entry (max 128 chars). Plain text, no templates."),phoneOverride:J.string().default("").describe("Optional number/template to add instead of the auto-resolved one. Supports {{variables}}. Empty = auto-resolve (dialer contact, then caller ID).")}),Wq=C({meta:{type:"addToDnc",module:"dialer",nameKey:"editor:nodes.addToDnc.name",descriptionKey:"editor:nodes.addToDnc.description",color:"red",icon:"Ban",category:"data",nature:"sideEffect",display:"compact",channel:"voice",order:3,outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:qq,producedVariables:[{name:"dnc_added",type:"string",descriptionKey:"editor:vars.dncAdded"},{name:"dnc_phone",type:"string",descriptionKey:"editor:vars.dncPhone"}]});var Gq=J.object({agent_id:J.string().default("").describe("SipPulse AI agent ID to invoke. Required for execution."),agent_name:J.string().default("").describe("Display name for the AI agent (used in logs and UI)."),additional_instructions:J.string().default("").describe("Extra instructions appended to the agent's system prompt."),variables:J.record(J.string(),J.unknown()).default({}).describe("Key-value pairs passed to the agent as context variables."),initial_message:J.string().default("").describe("First message the agent speaks when the conversation starts."),max_duration_minutes:J.number().min(1).max(60).default(10).describe("Maximum conversation duration in minutes (1-60). Call ends on timeout.")}),Jq=C({meta:{type:"aiAgent",module:"ai",nameKey:"editor:nodes.aiAgent.name",descriptionKey:"editor:nodes.aiAgent.description",color:"iris",icon:"BotMessageSquare",category:"handling",order:1,nature:"composite",display:"full",channel:"both",outputs:[{key:"completed",labelKey:"editor:handles.completed"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:Gq,producedVariables:[{name:"duration_ms",type:"number",descriptionKey:"editor:vars.aiAgent.durationMs"},{name:"turns",type:"number",descriptionKey:"editor:vars.aiAgent.turns"},{name:"thread_uid",type:"string",descriptionKey:"editor:vars.aiAgent.threadUid"},{name:"output.*",type:"string",descriptionKey:"editor:vars.aiAgent.output"}]});var jq=J.string().min(1).max(255).regex(/^[A-Za-z0-9_-]+$/,{error:"Invalid structured analysis id"});var Yq=J.object({speechAnalyticsEnabled:J.boolean().optional(),sentimentEnabled:J.boolean().nullable().optional(),topicDetectionTopics:J.array(J.string()).optional(),intentDetectionIntents:J.array(J.string()).optional(),structuredAnalysisEnabled:J.boolean().optional(),structuredAnalysisIds:J.array(jq).max(100).optional()}),Hq=C({meta:{type:"analysis",module:"ai",nameKey:"editor:nodes.analysis.name",descriptionKey:"editor:nodes.analysis.description",color:"orange",icon:"ChartNoAxesColumn",category:"media",nature:"sideEffect",display:"compact",channel:"both",order:2,outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:Yq,producedVariables:[{name:"selected",type:"number",descriptionKey:"editor:vars.analysisSelected"}]});var QF=/\{\{[^{}]*\}\}/g,KF=/^\{\{[^{}]*\}\}$/,qF=new Set(["http:","https:"]);function iH($){if(!URL.canParse($))return!1;return qF.has(new URL($).protocol)}function dH($){let U=$.trim();if(U==="")return"empty";if(KF.test(U))return"from-variable";let K=0,q=U.replaceAll(QF,()=>{return K+=1,`v${K}`});return iH(q)?"valid":"malformed"}function Xq($){return dH($)!=="malformed"}var oH=["postgres","redis","freeswitch","engine","server"],jg=new Set(oH);var Zq=J.object({text:J.string().min(1,{error:"editor:validation.emptyTtsText"}).describe("Text to synthesize into speech."),voice:J.string().optional().describe("TTS voice ID (e.g., 'pt-BR-FranciscaNeural'). Resolved dynamically when absent."),model:J.string().optional().describe("TTS model ID (e.g., 'pulse-tts'). Resolved dynamically when absent.")}),J$=J.union([J.object({tts:Zq.describe("Text-to-speech audio source.")}),J.object({file:J.object({id:J.string().min(1,{error:"editor:validation.noAudioFile"}).describe("Audio file ID from the audio library."),name:J.string().describe("Display name of the audio file."),path:J.string().describe("Storage path of the audio file.")}).describe("Pre-recorded audio file source.")}),J.object({url:J.object({value:J.string().min(1,{error:"editor:validation.emptyAudioUrl"}).refine(Xq,{error:"editor:validation.malformedAudioUrl"}).describe("Audio URL fetched at call time. Supports {{variables}}; secrets are not allowed."),fallbackTts:Zq.optional().describe("Spoken when the URL fails. Absent means take the error output.")}).describe("Remote audio source fetched at call time.")})]),WF=J$.optional().catch(void 0);var B6=J.string().refine(($)=>$.trim()!=="",{error:"editor:validation.urlRequired"}).refine(($)=>!/\s/.test($.trim()),{error:"editor:validation.urlHasSpace"}).default("");var GF=J.object({value:J.string().min(1,{error:"editor:validation.caseValueRequired"}).default("").describe("Attribute value to match. Creates a 'match:<value>' output.")}),Bq=J.object({audio:J$.optional().describe("Audio prompt played before collecting digits."),chatText:J.string().default("").describe("Text prompt for chat mode. Supports {{variables}}."),timeout:J.number().int().min(1).max(60).default(5).describe("Seconds to wait for digit input (1-60)."),maxAttempts:J.number().int().min(1).max(10).default(3).describe("Maximum retry attempts for digit collection (1-10)."),digitRegex:J.string().default("").describe("Regex to validate DTMF input. Empty means accept any."),method:J.enum(["GET","POST","PUT"]).default("GET").describe("HTTP method for the API request."),url:B6.describe("API endpoint URL. Supports {{variables}} including collected digits as {{digits}}."),headers:J.record(J.string(),J.string()).optional().describe("HTTP headers as key-value pairs."),body:J.string().optional().describe("Request body (JSON). Supports {{variables}}. Only for POST/PUT."),requestTimeout:J.number().int().min(1000).max(60000).default(1e4).describe("HTTP request timeout in milliseconds."),attribute:J.string().default("").describe("JSON attribute name from the API response to match against cases."),cases:J.array(GF).default([]).describe("Possible attribute values. Each creates a dynamic output handle 'match:<value>'.")}),Vq=C({meta:{type:"apiSwitch",module:"core",nameKey:"editor:nodes.apiSwitch.name",descriptionKey:"editor:nodes.apiSwitch.description",color:"teal",icon:"Globe",category:"legacy",nature:"composite",display:"full",channel:"both",order:3,legacy:!0,replacedBy:"httpRequest + switchCase",outputs:($)=>{return[...($.cases??[]).map((q)=>typeof q==="string"?q:q.value).filter((q)=>typeof q==="string"&&q!=="").map((q)=>({key:`match:${q}`,labelKey:q})),{key:"noInput",labelKey:"editor:handles.noInput"},{key:"error",labelKey:"editor:handles.error"}]}},configSchema:Bq,producedVariables:[{name:"digits",type:"string",descriptionKey:"editor:vars.collectedDigits"},{name:"status_code",type:"number",descriptionKey:"editor:vars.statusCode"},{name:"response",type:"object",descriptionKey:"editor:vars.response"},{name:"destination",type:"string",descriptionKey:"editor:vars.switchDestination"},{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"}]});var JF=J.object({language:J.string().optional().describe("BCP 47 language code for speech recognition (e.g., 'pt-BR'). Omit for plan default."),initial_timeout_s:J.number().min(3).max(60).default(10).describe("Maximum seconds to wait for speech to begin (3-60)."),timeout_s:J.number().min(1).max(30).default(3).describe("Seconds of post-speech silence before stopping recording (1-30)."),max_duration_s:J.number().min(1).max(60).default(15).describe("Maximum recording duration in seconds (1-60)."),beep:J.boolean().default(!1).describe("Play a beep sound before starting to listen.")}),Mq=J.object({maxAttempts:J.number().min(1).max(10).default(3).describe("Maximum retry attempts for invalid or empty input (1-10)."),audio:J$.optional().describe("Audio prompt played before collecting input in voice mode."),voiceMethod:J.enum(["dtmf","speech"]).default("dtmf").describe("Voice input method: 'dtmf' for digits, 'speech' for ASR transcription (requires AI)."),minDigits:J.number().min(1).max(20).default(1).describe("Minimum number of DTMF digits required (1-20)."),maxDigits:J.number().min(1).max(20).default(1).describe("Maximum number of DTMF digits to collect (1-20)."),terminators:J.string().default("#").describe("Key that terminates digit collection (e.g., '#')."),voiceTimeout:J.number().min(1).max(60).default(5).describe("Seconds to wait for input in voice mode (1-60)."),listen:JF.default({initial_timeout_s:10,timeout_s:3,max_duration_s:15,beep:!1}).describe("Listening configuration for speech capture: silence detection, max duration, language."),processing_audio:J$.optional().describe("Audio played while ASR processes the speech. Optional."),retryAudio:J$.optional().describe("Audio played on retry instead of main prompt. Falls back to main if not set."),text:J.string().default("").describe("Chat prompt message sent before waiting for user input. Supports {{variables}}."),validation:J.string().optional().describe("Regex pattern to validate chat text input. Invalid input triggers retry."),invalidMessage:J.string().optional().describe("Chat message sent when input fails validation. Supports {{variables}}.")}),Dq=C({meta:{type:"capture",module:"core",nameKey:"editor:nodes.capture.name",descriptionKey:"editor:nodes.capture.description",color:"cyan",icon:"TextCursorInput",category:"interaction",order:3,nature:"composite",display:"full",channel:"both",outputs:[{key:"collected",labelKey:"editor:handles.collected"},{key:"noInput",labelKey:"editor:handles.noInput"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:Mq,producedVariables:[{name:"text",type:"string",descriptionKey:"editor:vars.capturedText"},{name:"attempts",type:"number",descriptionKey:"editor:vars.captureAttempts"}]});var Pq=J.object({}),Nq=C({meta:{type:"channelRouter",module:"core",nameKey:"editor:nodes.channelRouter.name",descriptionKey:"editor:nodes.channelRouter.description",color:"lime",icon:"Router",category:"routing",order:3,nature:"routing",display:"full",channel:"both",outputs:[{key:"voice",labelKey:"editor:handles.voice"},{key:"chat",labelKey:"editor:handles.chat"}]},configSchema:Pq,producedVariables:[{name:"channelType",type:"string",descriptionKey:"editor:vars.channelType"}]});var Lq=J.object({audio:J$.default({tts:{text:""}}).describe("Audio prompt played before collecting digits."),minDigits:J.number().min(1,{error:"editor:validation.minDigitsMin"}).max(20,{error:"editor:validation.minDigitsMax"}).default(1).describe("Minimum number of digits required (1-20)."),maxDigits:J.number().min(1,{error:"editor:validation.maxDigitsMin"}).max(20,{error:"editor:validation.maxDigitsMax"}).default(1).describe("Maximum number of digits to collect (1-20)."),terminator:J.string().max(1).default("#").describe("Key that terminates digit collection (e.g., '#'). Single character."),timeout:J.number().min(1,{error:"editor:validation.timeoutMin"}).max(60,{error:"editor:validation.timeoutMax"}).default(5).describe("Seconds to wait for the first digit after audio finishes (1-60)."),interDigitTimeout:J.number().min(1,{error:"editor:validation.interDigitTimeoutMin"}).max(30,{error:"editor:validation.interDigitTimeoutMax"}).default(3).describe("Seconds to wait between consecutive digits (1-30)."),maxAttempts:J.number().min(1,{error:"editor:validation.attemptsMin"}).max(10,{error:"editor:validation.attemptsMax"}).default(3).describe("Maximum retry attempts on invalid input (1-10)."),invalidAudio:J$.optional().describe("Audio played when input fails regex validation. Optional."),regex:J.string().default("").describe("Regex pattern to validate collected digits. Empty means accept any."),resetDigit:J.string().max(1).default("").describe("Key that clears collected digits and restarts. Single character. Empty to disable.")}),_q=C({meta:{type:"collectDigits",module:"core",nameKey:"editor:nodes.collectDigits.name",descriptionKey:"editor:nodes.collectDigits.description",color:"sky",icon:"Keyboard",category:"interaction",order:4,nature:"composite",display:"full",channel:"voice",outputs:[{key:"collected",labelKey:"editor:handles.collected"},{key:"noInput",labelKey:"editor:handles.noInput"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:Lq,producedVariables:[{name:"digits",type:"string",descriptionKey:"editor:vars.collectedDigits"},{name:"attempts",type:"number",descriptionKey:"editor:vars.collectAttempts"}]});var Iq=J.object({name:J.string().min(1,{error:"editor:validation.counterNameRequired"}).default("").describe("Counter name. Supports templates, e.g. 'attempts_{{start.callerid}}'."),action:J.enum(["increment","decrement","reset"]).default("increment").describe("Operation applied to the counter. 'reset' sets it to zero and ignores step."),step:J.number().int().min(1,{error:"editor:validation.counterStepMin"}).max(1e6,{error:"editor:validation.counterStepMax"}).default(1).describe("Amount added or subtracted on each execution (1-1000000). Ignored when the action is 'reset'."),limit:J.number().int().min(1,{error:"editor:validation.counterLimitMin"}).optional().describe("Value that routes to the 'limitReached' output once the counter reaches it. Empty means count only."),scope:J.enum(["call","plan","organization"]).default("call").describe("'call' starts from zero on every call; 'plan' persists across the calls of one plan; 'organization' persists across every plan of the organization."),ttlSeconds:J.number().int().min(60).max(31536000).optional().describe("Lifetime in seconds of a 'plan' or 'organization' counter (60-31536000). Applied when the key is created, so counting does not renew the window.")}),Fq=C({meta:{type:"counter",module:"core",nameKey:"editor:nodes.counter.name",descriptionKey:"editor:nodes.counter.description",color:"cyan",icon:"Tally5",category:"routing",order:5,nature:"routing",display:"compact",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"},{key:"limitReached",labelKey:"editor:handles.limitReached"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:Iq,producedVariables:[{name:"value",type:"number",descriptionKey:"editor:vars.counter.value"},{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"}]});var ag=new Intl.NumberFormat("en-US",{useGrouping:!1,maximumFractionDigits:10});var HF={BR:"55",US:"1",CA:"1",MX:"52",AR:"54",CL:"56",CO:"57",PE:"51",UY:"598",PY:"595",BO:"591",EC:"593",VE:"58",PT:"351",ES:"34",GB:"44",FR:"33",DE:"49",IT:"39"},XF=Object.entries(HF).map(([$,U])=>({country:$,callingCode:U}));var y3="secrets",BF="secrets".replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);function nH(){return new RegExp(String.raw`\{\{\s*${BF}\.([A-Z][A-Z0-9_]*)\s*\}\}`,"g")}function pH($){if(!$.includes("{{"))return[];let U=new Set;for(let K of $.matchAll(nH()))U.add(K[1]);return[...U]}var tH={httpRequest:new Set(["url","headers","body"]),apiSwitch:new Set(["url","headers","body"]),webhook:new Set(["url","headers","body"])};function aH($,U){return tH[$]?.has(U)===!0}function xq($,U,K){if(typeof $==="string"){K(U,$);return}if(Array.isArray($)){$.forEach((q,Q)=>xq(q,`${U}.${Q}`,K));return}if($!=null&&typeof $==="object")for(let[q,Q]of Object.entries($))xq(Q,U===""?q:`${U}.${q}`,K)}function g3($){let U=new Set,K=[];return xq($.config,"",(q,Q)=>{let W=pH(Q);if(W.length===0)return;let G=q.split(".")[0]??"";if(aH($.type,G)){for(let j of W)U.add(j);return}for(let j of W)K.push({nodeId:$.id,label:$.label,field:q,name:j})}),{allowed:[...U],misplaced:K}}function u3($){let U=new Set,K=[];for(let q of $){let Q=g3(q);for(let W of Q.allowed)U.add(W);for(let W of Q.misplaced)U.add(W.name),K.push(W)}return{names:U,misplaced:K}}function VF($){return $===`
|
|
87
|
+
`||$==="\r"||$==="\u2028"||$==="\u2029"}function MF($,U){for(let K=U;K<$.length;K++)if(VF($[K]))return K;return $.length}function sH($){let U=[],K=0,q=-1,Q=-1;for(;;){let W=$.indexOf("{{",K);if(W===-1)return U;if(q<W+3){if(q=$.indexOf("}}",W+3),q===-1)return U}if(Q<W+2)Q=MF($,W+2);if(Q<q){K=Q+1;continue}U.push({start:W,end:q+2,key:$.slice(W+2,q)}),K=q+2}}function DF($,U,K){let q="",Q=0;return U.forEach((W,G)=>{q+=$.slice(Q,W.start)+K(G),Q=W.end}),q+$.slice(Q)}function wq($,U){let K=[],q=0;for(let Q of sH($)){let W=Q.start-1>=q&&$[Q.start-1]==='"'?Q.start-1:Q.start,G=$[Q.end]==='"'?Q.end+1:Q.end;K.push({start:W,end:G}),q=G}return DF($,K,(Q)=>U($.slice(K[Q].start,K[Q].end)))}var f3=200;function eH($,U){let K=$[U];if(K==="*"||K==="+")return 1;if(K==="{"){let q=$.indexOf("}",U);if(q!==-1&&/^\d+,$/.test($.slice(U+1,q)))return q-U+1}return 0}function PF($,U){let K=U+1;while(K<$.length&&$[K]!=="]")K+=$[K]==="\\"?2:1;return K+1}function NF($,U,K){let q=K.pop()??{repeat:!1},Q=eH($,U+1);if(Q>0&&q.repeat)return{catastrophic:!0,next:U};if((q.repeat||Q>0)&&K.length>0)K.at(-1).repeat=!0;return{catastrophic:!1,next:U+(Q>0?1+Q:1)}}function LF($,U,K){let q=$[U];if(q==="\\")return{catastrophic:!1,next:U+2};if(q==="[")return{catastrophic:!1,next:PF($,U)};if(q==="(")return K.push({repeat:!1}),{catastrophic:!1,next:U+1};if(q===")")return NF($,U,K);let Q=eH($,U);if(Q>0&&K.length>0)K.at(-1).repeat=!0;return{catastrophic:!1,next:U+(Q>0?Q:1)}}function Aq($){let U=[],K=0;while(K<$.length){let{catastrophic:q,next:Q}=LF($,K,U);if(q)return!0;K=Q}return!1}function _F($){let U=$.split("/");if(U.length<3)return null;return{key:U[0].trim(),pattern:U.slice(1,-1).join("/"),replacement:U.at(-1)}}function vq($){if(!$.includes("{{"))return{valid:!0};for(let U of sH($)){let K=$.slice(U.start,U.end),q=_F(U.key.trim());if(q===null)continue;if(q.pattern.length>f3)return{valid:!1,error:`Regex pattern too long in "${K}" (max ${f3})`};if(Aq(q.pattern))return{valid:!1,error:`Unsafe regex (possible catastrophic backtracking) in "${K}"`};try{new RegExp(q.pattern)}catch(Q){let W=Q instanceof Error?Q.message:String(Q);return{valid:!1,error:`Invalid regex in "${K}": ${W}`}}}return{valid:!0}}var $X={uppercase:"string",lowercase:"string",capitalize:"string",trim:"string",replace:"string",regexReplace:"string",part:"string",add:"string",subtract:"string",multiply:"string",divide:"string",round:"string",currency:"string",dateOffset:"string",dateDiff:"string",dateFormat:"string",count:"number",join:"string",item:"string",filter:"array",spellOut:"string",inWords:"string",normalizePhone:"string",default:"string"};var bF=new Set(["error_code","error_message","error_step","error_var"]),OF=J.string().refine(($)=>$.trim()!=="",{error:"editor:validation.emptySaveAs"}).refine(($)=>!bF.has($.trim()),{error:"editor:validation.reservedSaveAs"}).describe("Name the result is saved under. Readable by later steps and by other nodes."),j$=($)=>J.literal($).describe("Operation this step applies to the source."),UX=J.enum(["minutes","hours","days","months","years"]).describe("Time unit used by the step: minutes, hours, days, months, or years."),Y$=J.object({source:J.string().describe("Value the step transforms. Literal text or a template like '{{start.callerid}}'."),saveAs:OF}),TF=J.discriminatedUnion("op",[Y$.extend({op:j$("uppercase")}),Y$.extend({op:j$("lowercase")}),Y$.extend({op:j$("capitalize")}),Y$.extend({op:j$("trim")}),Y$.extend({op:j$("replace"),search:J.string().describe("Literal text to look for. Not a regular expression. Empty leaves the source untouched."),replacement:J.string().describe("Text that replaces every occurrence of the searched text.")}),Y$.extend({op:j$("regexReplace"),pattern:J.string().describe("Regular expression used to match text. Nested repetition and patterns over 200 characters are rejected."),replacement:J.string().describe("Text that replaces every match. Supports JavaScript backreferences such as '$1'.")}),Y$.extend({op:j$("part"),separator:J.string().describe("Text that splits the source into parts. Empty splits into single characters."),index:J.number().int().describe("Zero-based index of the part to keep. Negative counts from the end.")}),Y$.extend({op:j$("add"),operand:J.string().describe("Number added to the source. Literal value or template.")}),Y$.extend({op:j$("subtract"),operand:J.string().describe("Number subtracted from the source. Literal value or template.")}),Y$.extend({op:j$("multiply"),operand:J.string().describe("Number the source is multiplied by. Literal value or template.")}),Y$.extend({op:j$("divide"),operand:J.string().describe("Number the source is divided by. Literal value or template. Zero fails with 'divide_by_zero'.")}),Y$.extend({op:j$("round"),decimals:J.number().int().min(0).max(10).default(0).describe("Decimal places to keep (0-10). Rounds half away from zero.")}),Y$.extend({op:j$("currency"),currency:J.string().default("BRL").describe("ISO 4217 currency code used to format the amount, e.g. 'BRL'."),locale:J.string().default("pt-BR").describe("Locale used to format the amount, e.g. 'pt-BR'.")}),Y$.extend({op:j$("dateOffset"),amount:J.number().int().describe("How many units to add to the date. Negative subtracts."),unit:UX}),Y$.extend({op:j$("dateDiff"),operand:J.string().describe("Date compared against the source. The result is operand minus source. Literal or template."),unit:UX}),Y$.extend({op:j$("dateFormat"),format:J.string().default("dd/MM/yyyy").describe("Output pattern, e.g. 'dd/MM/yyyy'. Text between single quotes is kept as written."),locale:J.string().default("pt-BR").describe("Locale used for month and weekday names, e.g. 'pt-BR'.")}),Y$.extend({op:j$("normalizePhone"),country:J.string().default("BR").describe("ISO 3166-1 alpha-2 country code used for national numbers. Defaults to 'BR'.")}),Y$.extend({op:j$("count")}),Y$.extend({op:j$("join"),separator:J.string().default(", ").describe("Text placed between items, except before the last one."),lastSeparator:J.string().default(" e ").describe("Text placed before the last item. Ignored when the list has a single item.")}),Y$.extend({op:j$("item"),index:J.number().int().describe("Zero-based index of the item to keep. Negative counts from the end.")}),Y$.extend({op:j$("filter"),field:J.string().default("").describe("Object field compared on each item. Empty compares the item itself."),operand:J.string().describe("Value each item is compared against, as text. Literal or template.")}),Y$.extend({op:j$("spellOut")}),Y$.extend({op:j$("inWords")}),Y$.extend({op:j$("default"),operand:J.string().describe("Value used when the source is empty. Literal value or template.")})]),kq=J.object({steps:J.array(TF).min(1,{error:"editor:validation.noSteps"}).default([]).describe("Ordered list of transformation steps. Each step transforms a value and saves the result under a name."),onError:J.enum(["error","empty"]).default("error").describe("What to do when a step fails: 'error' follows the error output, 'empty' continues with an empty value.")}),zq=C({meta:{type:"dataTransform",module:"core",nameKey:"editor:nodes.dataTransform.name",descriptionKey:"editor:nodes.dataTransform.description",color:"grass",icon:"Replace",category:"data",order:5,nature:"sideEffect",display:"compact",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:kq,producedVariables:($)=>{let U=new Map;for(let K of $.steps){if(K.saveAs==="")continue;U.set(K.saveAs,{name:K.saveAs,type:$X[K.op],descriptionKey:"editor:vars.transformed"})}return[...U.values(),{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"},{name:"error_step",type:"number",descriptionKey:"editor:vars.errorStep"},{name:"error_var",type:"string",descriptionKey:"editor:vars.errorVar"}]}});var Rq=J.object({connector_id:J.string().default("").describe("Public id of the connector that provides voice.agent (an ElevenLabs account). Required for execution."),agent_id:J.string().default("").describe("Id of the ElevenLabs agent that answers the call. Required for execution."),agent_name:J.string().default("").describe("Display name of the chosen ElevenLabs agent, for logs and the editor."),variables:J.record(J.string(),J.string()).default({}).describe("Key-value pairs sent to the agent as X-<name> SIP headers. Every value supports {{variables}}."),max_duration_minutes:J.number().min(1).max(60).default(10).describe("Maximum call duration in minutes (1-60). The bridge ends on timeout."),result_wait_seconds:J.number().int().min(0).max(60).default(15).describe("How long to wait for ElevenLabs' post-call analysis before continuing.")}),bq=C({meta:{type:"elevenlabsAgent",module:"ai",nameKey:"editor:nodes.elevenlabsAgent.name",descriptionKey:"editor:nodes.elevenlabsAgent.description",color:"iris",icon:"Sparkles",category:"handling",order:5,nature:"composite",display:"full",channel:"voice",requires:"voice.agent",connector:{kind:"elevenlabs",configKey:"connector_id"},outputs:[{key:"completed",labelKey:"editor:handles.completed"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:Rq,producedVariables:[{name:"duration_ms",type:"number",descriptionKey:"editor:vars.elevenlabsAgent.durationMs"},{name:"provider_call_id",type:"string",descriptionKey:"editor:vars.elevenlabsAgent.providerCallId"},{name:"ended_reason",type:"string",descriptionKey:"editor:vars.elevenlabsAgent.endedReason"},{name:"summary",type:"string",descriptionKey:"editor:vars.elevenlabsAgent.summary"},{name:"analysis_pending",type:"string",descriptionKey:"editor:vars.elevenlabsAgent.analysisPending"},{name:"output.*",type:"string",descriptionKey:"editor:vars.elevenlabsAgent.output"}]});var Oq=J.object({percentage:J.number().int().min(0).max(100).default(100).describe("Percentage of calls to record (0-100). 100 records all calls."),minDuration:J.number().int().min(0).default(0).describe("Minimum call duration in seconds before recording starts. 0 for immediate."),analyzeCalls:J.boolean().default(!1).describe("Enable post-call AI analysis (requires AI module).")}),Tq=C({meta:{type:"enableRecord",module:"core",nameKey:"editor:nodes.enableRecord.name",descriptionKey:"editor:nodes.enableRecord.description",color:"red",icon:"CircleDot",category:"legacy",nature:"sideEffect",display:"compact",channel:"both",order:4,legacy:!0,outputs:[{key:"next",labelKey:"editor:handles.next"},{key:"skipped",labelKey:"editor:handles.skipped"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:Oq,producedVariables:[{name:"recording",type:"string",descriptionKey:"editor:vars.recordingStatus"}]});var Sq=J.object({cause:J.string().optional().describe("SIP hangup cause code (e.g., 'NORMAL_CLEARING'). Omit for default.")}),Cq=C({meta:{type:"hangup",module:"core",nameKey:"editor:nodes.hangup.name",descriptionKey:"editor:nodes.hangup.description",color:"red",icon:"PhoneOff",category:"interaction",order:5,nature:"flow",display:"full",channel:"both",outputs:[]},configSchema:Sq,producedVariables:[]});var Eq=J.object({method:J.enum(["GET","POST","PUT","PATCH","DELETE"]).default("GET").describe("HTTP method for the request."),url:B6.describe("Request URL. Supports template expressions, e.g., 'https://api.example.com/{{start.callerid}}'."),headers:J.record(J.string(),J.string()).optional().describe("HTTP headers as key-value pairs. Values support template expressions."),body:J.string().optional().describe("Request body (JSON string). Template expressions allowed. Only for POST/PUT/PATCH."),timeout:J.number().optional().describe("Request timeout in milliseconds. Omit for default.")}),yq=C({meta:{type:"httpRequest",module:"core",nameKey:"editor:nodes.httpRequest.name",descriptionKey:"editor:nodes.httpRequest.description",color:"indigo",icon:"Globe",category:"data",order:0,nature:"sideEffect",display:"compact",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:Eq,producedVariables:[{name:"status_code",type:"number",descriptionKey:"editor:vars.statusCode"},{name:"response",type:"object",descriptionKey:"editor:vars.response"},{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"}]});var gq=J.object({audio:J$.default({tts:{text:""}}).describe("Audio prompt played before collecting DTMF input."),timeout:J.number().min(1,{error:"editor:validation.timeoutMin"}).max(60,{error:"editor:validation.timeoutMax"}).default(5).describe("Seconds to wait for DTMF input after audio finishes (1-60)."),maxAttempts:J.number().min(1,{error:"editor:validation.attemptsMin"}).max(10,{error:"editor:validation.attemptsMax"}).default(3).describe("Maximum retry attempts before following the error output (1-10).")}),uq=C({meta:{type:"ivr",module:"core",nameKey:"editor:nodes.ivr.name",descriptionKey:"editor:nodes.ivr.description",color:"violet",icon:"Grid3x3",category:"legacy",nature:"composite",display:"full",channel:"voice",order:1,deprecated:!0,replacedBy:"menu",outputs:[{key:"digit:0",labelKey:"0"},{key:"digit:1",labelKey:"1"},{key:"digit:2",labelKey:"2"},{key:"digit:3",labelKey:"3"},{key:"digit:4",labelKey:"4"},{key:"digit:5",labelKey:"5"},{key:"digit:6",labelKey:"6"},{key:"digit:7",labelKey:"7"},{key:"digit:8",labelKey:"8"},{key:"digit:9",labelKey:"9"},{key:"digit:*",labelKey:"*"},{key:"digit:#",labelKey:"#"},{key:"timeout",labelKey:"editor:handles.timeout"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:gq,producedVariables:[{name:"digits",type:"string",descriptionKey:"editor:vars.digits"},{name:"destination",type:"string",descriptionKey:"editor:vars.destination"},{name:"loops",type:"number",descriptionKey:"editor:vars.loops"}]});var fq=J.object({id:J.string().min(1).default("").describe("Unique option identifier. Used as button ID in chat and output handle suffix."),label:J.string().min(1).default("").describe("Display label shown to the user. Button text in chat, spoken in voice prompt."),digit:J.string().default("").describe("DTMF digit for voice mode (0-9, *, #). Leave empty to skip voice for this option.")}),mq=J.object({options:J.array(fq).default([]).describe("Menu options. Each creates a dynamic output handle."),maxAttempts:J.number().min(1).max(10).default(3).describe("Maximum retry attempts for invalid input before following noMatch (1-10)."),audio:J$.optional().describe("Voice audio prompt played before collecting DTMF input. If omitted, caller hears nothing before digit collection."),voiceTimeout:J.number().min(1).max(60).default(5).describe("Seconds to wait for DTMF input in voice mode (1-60)."),text:J.string().default("").describe("Chat message text displayed above buttons. Supports template expressions."),invalidMessage:J.string().optional().describe("Chat message sent when input doesn't match any option. Supports template expressions.")}),hq=C({meta:{type:"menu",module:"core",nameKey:"editor:nodes.menu.name",descriptionKey:"editor:nodes.menu.description",color:"violet",icon:"ListOrdered",category:"interaction",order:2,nature:"composite",display:"full",channel:"both",outputs:($)=>{return[...($.options??[]).map((q)=>typeof q==="object"&&q!=null?q:null).filter((q)=>q!=null&&typeof q.id==="string"&&q.id!=="").map((q)=>({key:`option:${q.id}`,labelKey:q.label})),{key:"noMatch",labelKey:"editor:handles.noMatch"},{key:"error",labelKey:"editor:handles.error"}]}},configSchema:mq,producedVariables:[{name:"selectedId",type:"string",descriptionKey:"editor:vars.menuSelectedId"},{name:"selectedLabel",type:"string",descriptionKey:"editor:vars.menuSelectedLabel"},{name:"digits",type:"string",descriptionKey:"editor:vars.menuDigits"},{name:"attempts",type:"number",descriptionKey:"editor:vars.menuAttempts"}]});var cq=J.object({connector_id:J.string().default("").describe("Public id of the connector that provides phone.lookup (a Twilio account). Required for execution."),number:J.string().default("{{Start.callerid}}").describe("Number expression. Supports {{variables}}. Normalized with the platform E.164 rule: a number without a country code is completed with the country below, or the organization's default country."),default_country:J.string().regex(/^([A-Za-z]{2})?$/u,{error:"editor:validation.whatsappCountry"}).default("").describe("ISO 3166-1 alpha-2 country (e.g. BR) that completes numbers written without a country code. Empty uses the organization's default country."),line_type:J.boolean().default(!1).describe("Also fetch line type and carrier. Twilio charges US$ 0,008 per query; format validation alone is free.")}),lq=C({meta:{type:"phoneLookup",module:"core",nameKey:"editor:nodes.phoneLookup.name",descriptionKey:"editor:nodes.phoneLookup.description",color:"blue",icon:"PhoneForwarded",category:"data",nature:"action",display:"compact",channel:"both",order:9,requires:"phone.lookup",connector:{kind:"twilio",configKey:"connector_id"},outputs:[{key:"valid",labelKey:"editor:handles.valid"},{key:"invalid",labelKey:"editor:handles.invalid"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:cq,producedVariables:[{name:"phone_number",type:"string",descriptionKey:"editor:vars.phoneLookup.phoneNumber"},{name:"national_format",type:"string",descriptionKey:"editor:vars.phoneLookup.nationalFormat"},{name:"country_code",type:"string",descriptionKey:"editor:vars.phoneLookup.countryCode"},{name:"line_type",type:"string",descriptionKey:"editor:vars.phoneLookup.lineType"},{name:"carrier_name",type:"string",descriptionKey:"editor:vars.phoneLookup.carrierName"},{name:"line_type_error",type:"string",descriptionKey:"editor:vars.phoneLookup.lineTypeError"}]});var rq=J.object({audio:J$.default({tts:{text:""}}).describe("Audio to play. Use TTS (text-to-speech) or a pre-recorded audio file.")}),iq=C({meta:{type:"playback",module:"core",nameKey:"editor:nodes.playback.name",descriptionKey:"editor:nodes.playback.description",color:"blue",icon:"Volume2",category:"legacy",nature:"action",display:"full",channel:"voice",order:0,deprecated:!0,replacedBy:"tell",outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:rq,producedVariables:[]});var dq=J.object({enabled:J.boolean().optional(),samplingPercentage:J.number().int().min(0).max(100).optional()}),oq=C({meta:{type:"recording",module:"core",nameKey:"editor:nodes.recording.name",descriptionKey:"editor:nodes.recording.description",color:"teal",icon:"Mic",category:"media",nature:"sideEffect",display:"compact",channel:"voice",order:0,outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:dq,producedVariables:[{name:"status",type:"string",descriptionKey:"editor:vars.recordingStatus"}]});var nq=J.object({connector_id:J.string().default("").describe("Public id of the connector that provides voice.agent (a Retell account). Required for execution."),agent_id:J.string().default("").describe("Id of the Retell agent that answers the call. Required for execution."),agent_name:J.string().default("").describe("Display name of the chosen Retell agent, for logs and the editor."),variables:J.record(J.string(),J.string()).default({}).describe("Key-value pairs sent to the agent. Every value supports {{variables}}."),max_duration_minutes:J.number().min(1).max(60).default(10).describe("Maximum call duration in minutes (1-60). The bridge ends on timeout."),result_wait_seconds:J.number().int().min(0).max(60).default(15).describe("How long to wait for Retell's post-call extraction before continuing.")}),pq=C({meta:{type:"retellAgent",module:"ai",nameKey:"editor:nodes.retellAgent.name",descriptionKey:"editor:nodes.retellAgent.description",color:"iris",icon:"AudioLines",category:"handling",order:3,nature:"composite",display:"full",channel:"voice",requires:"voice.agent",connector:{kind:"retell",configKey:"connector_id"},outputs:[{key:"completed",labelKey:"editor:handles.completed"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:nq,producedVariables:[{name:"duration_ms",type:"number",descriptionKey:"editor:vars.retellAgent.durationMs"},{name:"provider_call_id",type:"string",descriptionKey:"editor:vars.retellAgent.providerCallId"},{name:"ended_reason",type:"string",descriptionKey:"editor:vars.retellAgent.endedReason"},{name:"summary",type:"string",descriptionKey:"editor:vars.retellAgent.summary"},{name:"analysis_pending",type:"string",descriptionKey:"editor:vars.retellAgent.analysisPending"},{name:"output.*",type:"string",descriptionKey:"editor:vars.retellAgent.output"}]});var SF=J.object({label:J.string().min(1).describe("Intent name. Creates a dynamic output handle 'intent:<label>'."),description:J.string().default("").describe("Description of what this intent means, used for LLM classification.")}),tq=J.object({input:J.string().default("").describe("Template expression to evaluate, e.g. '{{resposta}}'. The resolved text is classified by AI."),intents:J.array(SF).default([]).describe("List of intents the LLM should classify the input into. Each creates a dynamic output handle."),instructions:J.string().default("").describe("Additional instructions for the LLM intent classifier.")}),aq=C({meta:{type:"routeAi",module:"ai",nameKey:"editor:nodes.routeAi.name",descriptionKey:"editor:nodes.routeAi.description",color:"plum",icon:"BrainCircuit",category:"routing",order:1,nature:"routing",display:"full",channel:"both",outputs:($)=>{return[...($.intents??[]).map((q)=>q.label).filter((q)=>typeof q==="string"&&q!=="").map((q)=>({key:`intent:${q}`,labelKey:q})),{key:"notApplicable",labelKey:"editor:handles.notApplicable"},{key:"error",labelKey:"editor:handles.error"}]}},configSchema:tq,producedVariables:[{name:"intent",type:"string",descriptionKey:"editor:vars.routeAi.intent"},{name:"confidence",type:"number",descriptionKey:"editor:vars.routeAi.confidence"}]});var sq=J.object({digits:J.string().min(1,{error:"editor:validation.digitsRequired"}).default("").describe("DTMF digits to send (0-9, *, #). Supports template expressions.")}),eq=C({meta:{type:"sendDtmf",module:"core",nameKey:"editor:nodes.sendDtmf.name",descriptionKey:"editor:nodes.sendDtmf.description",color:"bronze",icon:"Hash",category:"handling",order:2,nature:"sideEffect",display:"compact",channel:"voice",outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:sq,producedVariables:[{name:"dtmf",type:"string",descriptionKey:"editor:vars.dtmf"}]});var $W=J.object({connector_id:J.string().default("").describe("Public id of the connector that provides sms.send (a Twilio account). Required for execution."),from:J.string().default("").describe("Sender expression: empty uses the connector's default sender, otherwise a Messaging Service SID (MG...) or an E.164 number."),to:J.string().default("{{Start.callerid}}").describe("Recipient expression. Supports {{variables}}. Normalized with the platform E.164 rule: a number without a country code is completed with the country below, or the organization's default country."),default_country:J.string().regex(/^([A-Za-z]{2})?$/u,{error:"editor:validation.whatsappCountry"}).default("").describe("ISO 3166-1 alpha-2 country (e.g. BR) that completes recipients written without a country code. Empty uses the organization's default country."),body:J.string().default("").describe("Message text. Supports {{variables}}; secrets are not allowed in the body."),transliterate:J.boolean().default(!1).describe("Replace accented letters by their base letter before sending, so the message fits 160 characters per SMS instead of 70.")}),UW=C({meta:{type:"sendSms",module:"core",nameKey:"editor:nodes.sendSms.name",descriptionKey:"editor:nodes.sendSms.description",color:"green",icon:"MessageSquare",category:"data",nature:"sideEffect",display:"compact",channel:"both",order:8,requires:"sms.send",connector:{kind:"twilio",configKey:"connector_id"},outputs:[{key:"sent",labelKey:"editor:handles.sent"},{key:"failed",labelKey:"editor:handles.failed"}]},configSchema:$W,producedVariables:[{name:"message_sid",type:"string",descriptionKey:"editor:vars.sendSms.messageSid"},{name:"segments",type:"number",descriptionKey:"editor:vars.sendSms.segments"},{name:"encoding",type:"string",descriptionKey:"editor:vars.sendSms.encoding"},{name:"error_code",type:"string",descriptionKey:"editor:vars.sendSms.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.sendSms.errorMessage"}]});var QW=J.object({prefix:J.string().max(16,{error:"editor:validation.prefixMaxLength"}).default("").describe("Short prefix prepended to the sequence (e.g. 'SAC', '200')."),dateFormat:J.enum(["none","yyyyMMdd","yyMMdd","yyyyMM","ddMMyyyy","yyyyMMddHHmmss"]).default("yyyyMMdd").describe("Date format inserted between prefix and counter."),padding:J.number().int().min(1,{error:"editor:validation.paddingMin"}).max(12,{error:"editor:validation.paddingMax"}).default(5).describe("Minimum digits for the counter (zero-padded). Overflow uses natural width."),resetPeriod:J.enum(["daily","monthly","never"]).default("daily").describe("When the counter resets to 1. Uses org timezone for boundary.")}),KW=C({meta:{type:"sequence",module:"core",nameKey:"editor:nodes.sequence.name",descriptionKey:"editor:nodes.sequence.description",color:"mint",icon:"Hash",category:"data",order:6,nature:"sideEffect",display:"compact",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:QW,producedVariables:[{name:"value",type:"string",descriptionKey:"editor:vars.sequence.value"},{name:"spoken",type:"string",descriptionKey:"editor:vars.sequence.spoken"},{name:"counter",type:"string",descriptionKey:"editor:vars.sequence.counter"},{name:"date",type:"string",descriptionKey:"editor:vars.sequence.date"}]});var CF=J.object({key:J.string().describe("Variable name. Readable as '{{vars.key}}' and through the block's generated namespace."),value:J.string().describe("Value to assign. Supports template expressions like '{{start.callerid}}'.")}),qW=J.object({assignments:J.array(CF).min(1,{error:"editor:validation.noAssignments"}).default([]).describe("List of variable assignments. At least one required.")}),WW=C({meta:{type:"setVariable",module:"core",nameKey:"editor:nodes.setVariable.name",descriptionKey:"editor:nodes.setVariable.description",color:"teal",icon:"Variable",category:"data",order:4,nature:"sideEffect",display:"compact",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:qW,producedVariables:($)=>$.assignments.map((U)=>({name:U.key,type:"string",descriptionKey:"editor:vars.custom"}))});var GW=J.object({autoAnswer:J.boolean().optional().describe("Auto-answer incoming call before processing. Disable for pre-answer routing."),channelType:J.enum(fH).default("both").describe("Plan channel type.")}),JW=C({meta:{type:"start",module:"core",nameKey:"editor:nodes.start.name",descriptionKey:"editor:nodes.start.description",color:"jade",icon:"Play",category:"interaction",order:0,nature:"flow",display:"full",channel:"both",outputs:($)=>{let U=$.channelType;if((typeof U==="string"?U:"voice")==="both")return[{key:"voice",labelKey:"editor:handles.voice"},{key:"chat",labelKey:"editor:handles.chat"}];return[{key:"next",labelKey:"editor:handles.next"}]}},configSchema:GW,producedVariables:[{name:"uuid",type:"string",descriptionKey:"editor:vars.uuid"},{name:"callerid",type:"string",descriptionKey:"editor:vars.callerid"},{name:"did",type:"string",descriptionKey:"editor:vars.did"},{name:"time",type:"string",descriptionKey:"editor:vars.time"},{name:"mode",type:"string",descriptionKey:"editor:vars.mode"},{name:"recording",type:"string",descriptionKey:"editor:vars.recordingStatus"}]});var jW=J.object({planId:J.string().min(1,{error:"editor:validation.planIdRequired"}).default("").describe("ID of a published visual plan to execute as a sub-flow. Must be published."),args:J.record(J.string().regex(/^[A-Z_]\w*$/i).max(64),J.string().max(512)).default({}),endCallOnChildHangup:J.boolean().default(!1).describe("When true, a Hangup node executed inside the child plan really ends the call/session. When false (default), the child's hangup is absorbed: it only marks the end of the sub-plan and control returns to this node's 'next' output.")}),YW=C({meta:{type:"subPlan",module:"core",nameKey:"editor:nodes.subPlan.name",descriptionKey:"editor:nodes.subPlan.description",color:"purple",icon:"Layers",category:"data",order:2,nature:"flow",display:"full",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:jW,producedVariables:()=>[{name:"*",type:"string",descriptionKey:"editor:vars.subPlanOutput"},{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"},{name:"child_error_code",type:"string",descriptionKey:"editor:vars.childErrorCode"}]});var EF=J.object({pattern:J.string().min(1,{error:"editor:validation.casePatternRequired"}).default("").describe("Value to match against the expression. Creates a 'match:<pattern>' output.")}),HW=J.object({expression:J.string().min(1,{error:"editor:validation.expressionRequired"}).default("").describe("Template expression to evaluate, e.g., '{{ivr.digits}}'. Matched against case patterns."),cases:J.array(EF).default([]).describe("List of patterns to match. Each creates a dynamic output handle 'match:<pattern>'.")}),XW=C({meta:{type:"switchCase",module:"core",nameKey:"editor:nodes.switchCase.name",descriptionKey:"editor:nodes.switchCase.description",color:"orange",icon:"GitBranch",category:"routing",order:0,nature:"routing",display:"full",channel:"both",outputs:($)=>{return[...($.cases??[]).map((q)=>typeof q==="string"?q:q.pattern).filter((q)=>typeof q==="string"&&q!=="").map((q)=>({key:`match:${q}`,labelKey:q})),{key:"fallback",labelKey:"editor:handles.fallback"},{key:"error",labelKey:"editor:handles.error"}]}},configSchema:HW,producedVariables:[{name:"destination",type:"string",descriptionKey:"editor:vars.switchDestination"}]});var yF=J.object({type:J.literal("text"),text:J.string().min(1)}),gF=J.object({type:J.literal("media"),mediaType:J.enum(["image","audio","video","document"]),url:J.string().min(1),caption:J.string().optional()}),uF=J.object({type:J.literal("location"),lat:J.number(),lng:J.number()}),fF=J.object({type:J.literal("button_reply"),buttonId:J.string().min(1),buttonText:J.string()}),mF=J.object({type:J.literal("list_reply"),listId:J.string().min(1),listTitle:J.string()}),hF=J.object({type:J.literal("command"),command:J.string().min(1),args:J.string().optional()}),ZW=J.discriminatedUnion("type",[yF,gF,uF,fF,mF,hF]),BW=J.object({id:J.string().min(1),label:J.string().min(1)}),cF=J.object({id:J.string().min(1),title:J.string().min(1),description:J.string().optional()}),QX=J.object({title:J.string().min(1),items:J.array(cF).min(1)}),KX=J.object({title:J.string().min(1),description:J.string().optional(),imageUrl:J.string().optional(),buttons:J.array(BW).default([])}),lF=J.object({type:J.literal("text"),text:J.string().min(1),markdown:J.boolean().optional()}),rF=J.object({type:J.literal("media"),mediaType:J.enum(["image","audio","video","document"]),url:J.string().min(1),caption:J.string().optional()}),iF=J.object({type:J.literal("location"),lat:J.number(),lng:J.number(),label:J.string().optional()}),dF=J.object({type:J.literal("buttons"),text:J.string().min(1),buttons:J.array(BW).min(1)}),oF=J.object({type:J.literal("list"),text:J.string().min(1),buttonText:J.string().min(1),sections:J.array(QX).min(1)}),nF=J.object({type:J.literal("carousel"),cards:J.array(KX).min(1)}),pF=J.object({type:J.literal("template"),templateId:J.string().min(1),params:J.record(J.string(),J.string()).default({})}),V6=J.discriminatedUnion("type",[lF,rF,iF,dF,oF,nF,pF]),tF=V6.optional().catch(void 0);var VW=J.object({audio:J$.optional().describe("Audio to play via TTS, a pre-recorded file, or a remote URL. Used in voice plans."),content:V6.optional().describe("Message content to send in chat. Used in chat plans.")});function qX($){return typeof $==="object"&&$!==null&&"url"in $}var MW=C({meta:{type:"tell",module:"core",nameKey:"editor:nodes.tell.name",descriptionKey:"editor:nodes.tell.description",color:"blue",icon:"Volume2",category:"interaction",order:1,nature:"action",display:"full",channel:"both",outputs:($)=>qX($.audio)?[{key:"next",labelKey:"editor:handles.next"},{key:"error",labelKey:"editor:handles.error"}]:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:VW,producedVariables:($)=>qX($.audio)?[{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"}]:[]});var DW=J.object({scheduleId:J.string().optional().describe("Schedule ID for time-based routing. Routes to onHours/offHours/holiday outputs.")}),PW=C({meta:{type:"timeRouting",module:"core",nameKey:"editor:nodes.timeRouting.name",descriptionKey:"editor:nodes.timeRouting.description",color:"gold",icon:"Clock",category:"routing",order:2,nature:"routing",display:"full",channel:"both",outputs:[{key:"onHours",labelKey:"editor:handles.onHours"},{key:"offHours",labelKey:"editor:handles.offHours"},{key:"holiday",labelKey:"editor:handles.holiday"}]},configSchema:DW,producedVariables:[{name:"result",type:"string",descriptionKey:"editor:vars.timeResult"},{name:"holiday",type:"string",descriptionKey:"editor:vars.holiday"}]});var NW=J.object({name:J.string().min(1,{error:"editor:validation.trafficSplitPathNameRequired"}).default("").describe("Path name. Creates a 'path:<name>' output handle."),weight:J.number().int().min(0).max(100).default(1).describe("Relative share of this path (0-100). Zero disables it without deleting it.")}),LW=J.object({paths:J.array(NW).default([{name:"A",weight:50},{name:"B",weight:50}]).describe("Weighted paths. Each creates a dynamic output handle 'path:<name>'."),mode:J.enum(["contact","call","exact"]).default("contact").describe("'contact' keeps the same contact on the same path (stateless hash); 'call' draws per call (stateless, approximate); 'exact' rotates through a Redis counter so the proportion closes even at low volume.")}),_W=C({meta:{type:"trafficSplit",module:"core",nameKey:"editor:nodes.trafficSplit.name",descriptionKey:"editor:nodes.trafficSplit.description",color:"iris",icon:"Split",category:"routing",order:4,nature:"routing",display:"full",channel:"both",outputs:($)=>{let U=$.paths??[],K=[],q=new Set;for(let Q of U){let W=typeof Q==="object"&&Q!=null?Q.name:void 0;if(typeof W!=="string"||W===""||q.has(W))continue;q.add(W),K.push(W)}return[...K.map((Q)=>({key:`path:${Q}`,labelKey:Q})),{key:"error",labelKey:"editor:handles.error"}]}},configSchema:LW,producedVariables:[{name:"variant",type:"string",descriptionKey:"editor:vars.trafficSplit.variant"},{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"}]});var IW=J.object({enabled:J.boolean().optional(),scope:J.enum(["from_here","whole_recording"]).optional(),samplingPercentage:J.number().int().min(0).max(100).optional(),language:J.string().optional(),minDurationSeconds:J.number().int().min(0).max(L4).optional(),speechRequirement:J.enum(z1).optional(),anonymizeEnabled:J.boolean().optional(),speechAnalyticsEnabled:J.boolean().optional(),sentimentEnabled:J.boolean().optional(),transcriptionType:J.enum(l1).optional()}),FW=C({meta:{type:"transcription",module:"ai",nameKey:"editor:nodes.transcription.name",descriptionKey:"editor:nodes.transcription.description",color:"violet",icon:"Captions",category:"media",nature:"sideEffect",display:"compact",channel:"voice",order:1,outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:IW,producedVariables:[{name:"status",type:"string",descriptionKey:"editor:vars.transcriptionStatus"}]});var aF=J.object({key:J.string().describe("Attached-data field name shown to the agent / CRM (e.g. 'Nome')."),value:J.string().default("").describe("Field value. Supports template expressions like '{{cliente.nome}}'.")}),xW=J.object({method:J.enum(["bridge","transfer"]).default("bridge").describe("Transfer method. 'bridge' keeps call control; 'transfer' hands off completely."),destinations:J.array(J.string()).default([]).describe("SIP URIs or phone numbers to dial. At least one required. Tried in order."),timeout:J.number().min(5).max(120).optional().describe("Ring timeout in seconds per destination (5-120). Omit for carrier default."),attachedData:J.array(aF).default([]).describe("Key/value pairs delivered to the agent at transfer time (screen-pop). Values support templates.").superRefine(($,U)=>{let K=new Set;$.forEach((q,Q)=>{let W=q.key.trim();if(W===""){U.addIssue({code:"custom",message:"editor:validation.attachedKeyRequired",path:[Q,"key"]});return}if(K.has(W))U.addIssue({code:"custom",message:"editor:validation.duplicateAttachedKey",path:[Q,"key"]});K.add(W)})})}),wW=C({meta:{type:"transfer",module:"core",nameKey:"editor:nodes.transfer.name",descriptionKey:"editor:nodes.transfer.description",color:"amber",icon:"PhoneForwarded",category:"handling",order:0,nature:"action",display:"full",channel:"both",outputs:[{key:"answered",labelKey:"editor:handles.answered"},{key:"busy",labelKey:"editor:handles.busy"},{key:"noAnswer",labelKey:"editor:handles.noAnswer"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:xW,producedVariables:[{name:"status",type:"string",descriptionKey:"editor:vars.transferStatus"},{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"}]});var AW=J.object({connector_id:J.string().default("").describe("Public id of the connector that provides voice.agent (a Vapi account). Required for execution."),assistant_id:J.string().default("").describe("Id of the Vapi assistant that answers the call. Required for execution."),assistant_name:J.string().default("").describe("Display name of the chosen Vapi assistant, for logs and the editor."),variables:J.record(J.string(),J.string()).default({}).describe("Key-value pairs sent to the agent. Every value supports {{variables}}."),max_duration_minutes:J.number().min(1).max(60).default(10).describe("Maximum call duration in minutes (1-60). The bridge ends on timeout."),result_wait_seconds:J.number().int().min(0).max(60).default(15).describe("How long to wait for Vapi's end of call report before continuing.")}),vW=C({meta:{type:"vapiAgent",module:"ai",nameKey:"editor:nodes.vapiAgent.name",descriptionKey:"editor:nodes.vapiAgent.description",color:"iris",icon:"AudioWaveform",category:"handling",order:4,nature:"composite",display:"full",channel:"voice",requires:"voice.agent",connector:{kind:"vapi",configKey:"connector_id"},outputs:[{key:"completed",labelKey:"editor:handles.completed"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:AW,producedVariables:[{name:"duration_ms",type:"number",descriptionKey:"editor:vars.vapiAgent.durationMs"},{name:"provider_call_id",type:"string",descriptionKey:"editor:vars.vapiAgent.providerCallId"},{name:"ended_reason",type:"string",descriptionKey:"editor:vars.vapiAgent.endedReason"},{name:"summary",type:"string",descriptionKey:"editor:vars.vapiAgent.summary"},{name:"analysis_pending",type:"string",descriptionKey:"editor:vars.vapiAgent.analysisPending"},{name:"output.*",type:"string",descriptionKey:"editor:vars.vapiAgent.output"}]});var kW="Enviamos um código por SMS. Digite o código no teclado do telefone.",zW=J.object({connector_id:J.string().default("").describe("Public id of the connector that provides verify.otp (a Twilio account). Required for execution."),service_sid:J.string().default("").describe("Verify Service SID (VA...) whose code length and sender configuration the block uses."),to:J.string().default("{{Start.callerid}}").describe("Recipient expression. Supports {{variables}}. Normalized with the platform E.164 rule: a number without a country code is completed with the country below, or the organization's default country."),default_country:J.string().regex(/^([A-Za-z]{2})?$/u,{error:"editor:validation.whatsappCountry"}).default("").describe("ISO 3166-1 alpha-2 country (e.g. BR) that completes recipients written without a country code. Empty uses the organization's default country."),channel:J.enum(["sms","whatsapp","call"]).default("sms").describe("How the code reaches the contact: sms, whatsapp or call. Twilio sends it; NIVA needs no extra setup."),prompt:J$.default({tts:{text:kW}}).describe("Audio prompt asking for the code, played with the plan's voice. In chat, its text is sent."),max_attempts:J.number().int().min(1,{error:"editor:validation.attemptsMin"}).max(5,{error:"editor:validation.attemptsMax"}).default(3).describe("Maximum wrong-code attempts before the block leaves by rejected (1-5)."),timeout_seconds:J.number().int().min(1,{error:"editor:validation.timeoutMin"}).max(60,{error:"editor:validation.timeoutMax"}).default(10).describe("Seconds to wait for the code after the prompt (1-60).")}),RW=C({meta:{type:"verifyCode",module:"core",nameKey:"editor:nodes.verifyCode.name",descriptionKey:"editor:nodes.verifyCode.description",color:"purple",icon:"ShieldCheck",category:"data",nature:"composite",display:"full",channel:"both",order:10,requires:"verify.otp",connector:{kind:"twilio",configKey:"connector_id"},sensitiveInput:!0,outputs:[{key:"approved",labelKey:"editor:handles.approved"},{key:"rejected",labelKey:"editor:handles.rejected"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:zW,producedVariables:[{name:"status",type:"string",descriptionKey:"editor:vars.verifyCode.status"},{name:"attempts",type:"number",descriptionKey:"editor:vars.verifyCode.attempts"},{name:"channel",type:"string",descriptionKey:"editor:vars.verifyCode.channel"}]});var sF=J.object({label:J.string().min(1).describe("Intent name. Creates a dynamic output handle 'intent:<label>'."),description:J.string().default("").describe("Description of what this intent means, used for LLM classification.")}),eF=J.object({language:J.string().optional().describe("BCP 47 language code for speech recognition (e.g., 'pt-BR'). Omit for plan default."),initial_timeout_s:J.number().min(3).max(60).default(10).describe("Maximum seconds to wait for speech to begin (3-60)."),timeout_s:J.number().min(1).max(30).default(3).describe("Seconds of post-speech silence before stopping recording (1-30)."),max_duration_s:J.number().min(1).max(60).default(15).describe("Maximum recording duration in seconds (1-60)."),beep:J.boolean().default(!1).describe("Play a beep sound before starting to listen.")}),$x=J.object({max_retries:J.number().min(0).max(5).default(2).describe("Maximum retries when speech is not recognized (0-5)."),prompt:J$.optional().describe("Audio played when retrying after unrecognized speech. Falls back to main prompt if not set.")});var bW=J.object({mode:J.enum(["intent","capture"]).default("intent").describe("'intent' classifies speech into configured intents; 'capture' transcribes speech without classification."),prompt:J$.default({tts:{text:""}}).describe("Audio prompt played before listening for speech."),intents:J.array(sF).default([]).describe("List of intents the LLM should classify speech into. Only used when mode is 'intent'."),classification_instructions:J.string().default("").describe("Additional instructions for the LLM intent classifier. Only used when mode is 'intent'."),listen:eF.default({initial_timeout_s:10,timeout_s:3,max_duration_s:15,beep:!1}).describe("Listening configuration: initial wait, post-speech silence, max duration, language, beep."),processing_audio:J$.optional().describe("Audio played while the AI processes the speech. Optional."),retry:$x.default({max_retries:2}).describe("Retry behavior when speech is not recognized.")}),OW=C({meta:{type:"voiceRecognition",module:"ai",nameKey:"editor:nodes.voiceRecognition.name",descriptionKey:"editor:nodes.voiceRecognition.description",color:"cyan",icon:"Mic",category:"legacy",nature:"composite",display:"full",channel:"voice",order:2,deprecated:!0,replacedBy:"capture",outputs:($)=>{if(($.mode??"intent")==="capture")return[{key:"captured",labelKey:"editor:handles.captured"},{key:"noInput",labelKey:"editor:handles.noInput"},{key:"maxRetries",labelKey:"editor:handles.maxRetries"},{key:"error",labelKey:"editor:handles.error"}];return[...($.intents??[]).map((Q)=>typeof Q==="string"?Q:Q.label).filter((Q)=>typeof Q==="string"&&Q!=="").map((Q)=>({key:`intent:${Q}`,labelKey:Q})),{key:"noInput",labelKey:"editor:handles.noInput"},{key:"notApplicable",labelKey:"editor:handles.notApplicable"},{key:"maxRetries",labelKey:"editor:handles.maxRetries"},{key:"error",labelKey:"editor:handles.error"}]}},configSchema:bW,producedVariables:($)=>{if($.mode==="capture")return[{name:"speech",type:"string",descriptionKey:"editor:vars.voiceRecognition.speech"}];return[{name:"speech",type:"string",descriptionKey:"editor:vars.voiceRecognition.speech"},{name:"confidence",type:"number",descriptionKey:"editor:vars.voiceRecognition.confidence"},{name:"intent",type:"string",descriptionKey:"editor:vars.voiceRecognition.intent"}]}});var TW=J.object({method:J.enum(["POST","PUT","PATCH","GET","DELETE"]).default("POST").describe("HTTP method for the request."),url:B6.describe("Destination URL. Supports template expressions, e.g., 'https://hooks.example.com/{{start.callerid}}'."),headers:J.record(J.string(),J.string()).optional().describe("HTTP headers as key-value pairs. Values support template expressions."),body:J.string().optional().describe("Request body (JSON string). Template expressions allowed. Only for POST/PUT/PATCH/DELETE.")}),SW=C({meta:{type:"webhook",module:"core",nameKey:"editor:nodes.webhook.name",descriptionKey:"editor:nodes.webhook.description",color:"violet",icon:"Webhook",category:"data",order:1,nature:"sideEffect",display:"compact",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:TW,producedVariables:[]});var WX=J.record(J.string(),J.string()).default({}),CW=J.object({connectorId:J.string().default("").describe("Public id of the connector that provides whatsapp.templates (e.g. a WhatsApp Business connector)."),phoneNumberId:J.string().default("").describe("Id of the WhatsApp number the message is sent from, one of the connector's numbers."),template:J.object({name:J.string().default(""),language:J.string().default("")}).default({name:"",language:""}).describe("The approved message template to send, by name and language code (e.g. boleto / pt_BR)."),to:J.string().default("{{Start.callerid}}").describe("Recipient expression. Supports {{variables}}. Normalized with the platform E.164 rule: numbers without a country code are completed with the country below, or the organization's default country."),defaultCountry:J.string().regex(/^([A-Za-z]{2})?$/u,{error:"editor:validation.whatsappCountry"}).default("").describe("ISO 3166-1 alpha-2 country (e.g. BR) that completes recipients written without a country code. Empty uses the organization's default country."),parameters:J.object({header:J.string().optional().describe("Header value: the text variable of a text header, or the media URL of an image/video/document header."),body:WX.describe("Body variable values, keyed by variable name ('1', '2' or 'first_name')."),buttons:WX.describe("URL button suffix values, keyed by the button's index ('0', '1', ...).")}).default({body:{},buttons:{}}).describe("Template variable values. Every value supports {{variables}}.")}),EW=C({meta:{type:"whatsappTemplate",module:"core",nameKey:"editor:nodes.whatsappTemplate.name",descriptionKey:"editor:nodes.whatsappTemplate.description",color:"green",icon:"MessageCircle",category:"data",nature:"sideEffect",display:"compact",channel:"both",order:7,requires:"whatsapp.templates",connector:{kind:"whatsapp_business",configKey:"connectorId"},outputs:[{key:"sent",labelKey:"editor:handles.sent"},{key:"failed",labelKey:"editor:handles.failed"}]},configSchema:CW,producedVariables:[{name:"message_id",type:"string",descriptionKey:"editor:vars.whatsappMessageId"},{name:"error_code",type:"string",descriptionKey:"editor:vars.whatsappErrorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.whatsappErrorMessage"}]});var p$={start:JW,playback:iq,ivr:uq,collectDigits:_q,transfer:wW,hangup:Cq,timeRouting:PW,switchCase:XW,trafficSplit:_W,setVariable:WW,sequence:KW,counter:Fq,httpRequest:yq,webhook:SW,whatsappTemplate:EW,sendSms:UW,phoneLookup:lq,verifyCode:RW,dataTransform:zq,subPlan:YW,sendDtmf:eq,aiAgent:Jq,retellAgent:pq,vapiAgent:vW,elevenlabsAgent:bq,voiceRecognition:OW,tell:MW,menu:hq,capture:Dq,routeAi:aq,channelRouter:Nq,addToDnc:Wq,apiSwitch:Vq,enableRecord:Tq,recording:oq,transcription:FW,analysis:Hq},t$=Object.fromEntries(Object.entries(p$).map(([$,U])=>[$,U.meta]));var Xc=Number.MAX_SAFE_INTEGER;var yW=["active","expired","suspended","poc"],GX=J.object({enabled:J.boolean(),limits:J.record(J.string(),J.union([J.number(),J.string(),J.boolean(),J.array(J.string())])).default({})}),jx=J.object({customerId:J.string(),customerName:J.string().optional(),serial:J.string(),status:J.enum(yW),issuedAt:J.coerce.date(),expiresAt:J.coerce.date().nullable(),gracePeriodDays:J.number().int().min(0),modules:J.record(J.string(),GX),isExpired:J.boolean(),isInGracePeriod:J.boolean(),daysUntilExpiry:J.number().nullable()}),Yx=J.object({voice:J.number().int().default(0),chat:J.number().int().default(0)}).optional(),Hx=J.object({customer_id:J.string().min(1),customer_name:J.string().min(1).optional(),serial:J.string().min(1),status:J.enum(yW),issued_at:J.coerce.date(),expires_at:J.coerce.date().nullable().default(null),grace_period_days:J.number().int().min(0).default(0),max_concurrent_channels:Yx,modules:J.record(J.string(),GX)});var M6=["yes_no","choice","scale"],JX=["caller","agent","both"],D6=["info","warning","critical"],_0=["worse","better","neutral"],Xx=/^[a-z][a-z0-9_]{0,63}$/,Zx=/^[a-z0-9][a-z0-9_]{0,47}$/,jX=J.object({key:J.string().regex(Zx),label:J.string().min(1).max(80),description:J.string().max(240).optional(),archived:J.boolean().default(!1)}),YX=J.union([J.object({answer:J.enum(["yes","no"])}),J.object({options:J.array(J.string()).min(1)}),J.object({level_at_least:J.number()}),J.object({level_at_most:J.number()})]),Bx=J.object({when:YX,severity:J.enum(D6),bell:J.boolean().default(!1)}),Vx=J.object({slug:J.string().regex(Xx),name:J.string().trim().min(1).max(80),question:J.string().trim().min(1).max(500),kind:J.enum(M6),options:J.array(jX).min(2).max(12).optional(),levels:J.array(J.string().min(1).max(40)).min(3).max(5).optional(),higher_is:J.enum(_0).optional(),speaker:J.enum(JX),scope:J.object({node_types:J.array(J.string().min(1)).min(1).max(20)}).nullable(),live:J.boolean(),alert:Bx.nullable()});function HX($){return $.higher_is??"worse"}function Mx($,U){if($.kind==="choice"){if($.options===void 0){U.addIssue({code:"custom",message:"signals:validation.optionsRequired",path:["options"]});return}let K=$.options.map((q)=>q.key);if(new Set(K).size!==K.length)U.addIssue({code:"custom",message:"signals:validation.optionKeyUnique",path:["options"]});if($.options.filter((q)=>!q.archived).length<2)U.addIssue({code:"custom",message:"signals:validation.twoActiveOptions",path:["options"]})}else if($.options!==void 0)U.addIssue({code:"custom",message:"signals:validation.optionsChoiceOnly",path:["options"]})}function Dx($,U){if($.kind==="scale"){if($.levels===void 0)U.addIssue({code:"custom",message:"signals:validation.levelsRequired",path:["levels"]})}else{if($.levels!==void 0)U.addIssue({code:"custom",message:"signals:validation.levelsScaleOnly",path:["levels"]});if($.higher_is!==void 0)U.addIssue({code:"custom",message:"signals:validation.higherIsScaleOnly",path:["higher_is"]})}}function Px($,U){if($.levels===void 0)return!1;let K=HX($),q=$.levels.length-1;if("level_at_least"in U){let Q=U.level_at_least;return K!=="better"&&Number.isInteger(Q)&&Q>=1&&Q<=q}if("level_at_most"in U){let Q=U.level_at_most;return K!=="worse"&&Number.isInteger(Q)&&Q>=0&&Q<=q-1}return!1}function Nx($){if($.alert===null)return!0;let U=$.alert.when;switch($.kind){case"yes_no":return"answer"in U;case"choice":return"options"in U&&$.options!==void 0&&U.options.every((K)=>$.options?.some((q)=>q.key===K&&!q.archived)===!0);case"scale":return Px($,U)}}function XX($,U){if(Mx($,U),Dx($,U),!Nx($))U.addIssue({code:"custom",message:"signals:validation.whenMustMatchKind",path:["alert","when"]})}var P6=Vx.superRefine(XX);var m3=J.object({channel:J.union([J.literal(0),J.literal(1)]),text:J.string(),isFinal:J.boolean(),confidence:J.number(),start:J.number(),end:J.number(),timestamp:J.string(),nodeId:J.string().optional(),nodeLabel:J.string().optional(),nodeType:J.string().optional(),redacted:J.boolean().optional()}),VX={signal:J.object({id:J.string().min(1),slug:J.string().min(1),name:J.string(),kind:J.enum(M6),severity:J.enum(D6).nullable(),bell:J.boolean()}),value:J.union([J.boolean(),J.string(),J.number(),J.null()]),value_label:J.string(),confidence:J.number(),at_seconds:J.number(),node:J.object({id:J.string(),label:J.string(),type:J.string()}).nullable(),late:J.boolean()},h3=J.object({type:J.literal("signal_value"),...VX}),c3=J.object({type:J.literal("signal_triggered"),...VX}),MX=J.discriminatedUnion("type",[h3,c3]),_x=J.discriminatedUnion("type",[J.object({type:J.literal("segment"),segment:m3}),h3,c3,J.object({type:J.literal("started"),backlog_seconds:J.number(),live_from:J.number()}),J.object({type:J.literal("caught_up")}),J.object({type:J.literal("ended")}),J.object({type:J.literal("error"),message:J.string()})]),Ix=J.discriminatedUnion("type",[J.object({type:J.literal("segment"),segment:m3}),J.object({type:J.literal("history"),segments:J.array(m3),signals:J.array(MX).optional()}),h3,c3,J.object({type:J.literal("starting")}),J.object({type:J.literal("started"),backlog_seconds:J.number(),live_from:J.number()}),J.object({type:J.literal("caught_up")}),J.object({type:J.literal("ended")}),J.object({type:J.literal("error"),message:J.string()}),J.object({type:J.literal("unavailable"),reason:J.enum(["not_recorded","no_credential","test_call"])})]),Fx=J.object({uuid:J.string(),action:J.enum(["start","stop"])}),DX=["not_live","provider_error","drain_timeout","redact_mid_call"],PX=J.object({startByte:J.number().int().min(0),endByte:J.number().int().min(0)}),xx=J.object({complete:J.boolean(),reason:J.enum(DX).optional(),model:J.string(),redact:J.boolean(),coveredRanges:J.array(PX)});function G$($){return{...$,defaults:{...$.defaults,email:$.defaults.email??!1}}}var M1={enabled:!0,toast:!0},a$={enabled:!0,toast:!1},wx={enabled:!1,toast:!1},Ax={freeswitch:"FreeSWITCH",database:"Database",redis:"Redis"},l3=($)=>Ax[$]??"Redis",D1=($,U,K)=>$===1?U:K,NX={"email.delivery_failed":G$({kind:"email.delivery_failed",area:"services",audience:"platform",permission:"system:diagnostics",severity:"warning",params:J.strictObject({}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/system/email",defaults:a$,en:{title:()=>"Email delivery failed",body:()=>"An email could not be delivered. Check the SMTP settings and server logs."},pt:{title:()=>"Falha no envio de e-mail",body:()=>"Um e-mail não pôde ser entregue. Confira o SMTP em Sistema > E-mail e os logs do servidor."}}),"service.down":G$({kind:"service.down",area:"services",audience:"platform",permission:"system:diagnostics",severity:"critical",params:J.strictObject({component:J.string()}),grouping:{mode:"incident"},groupKey:($)=>$.component,link:()=>"/dashboard",defaults:M1,en:{title:($)=>`${l3($.component)} offline`,body:($)=>`${l3($.component)} is unreachable.`},pt:{title:($)=>`${$.component} indisponível`,body:($)=>`Não foi possível acessar ${$.component}.`},webhook:{alertType:($)=>`service_offline:${$.component}`,resolvedTitle:($)=>`${l3($.component)} recovered`,resolvedBody:($)=>`${l3($.component)} is back online.`}}),"license.expiring":G$({kind:"license.expiring",area:"usage",audience:"platform",permission:"system:diagnostics",severity:"warning",params:J.strictObject({days:J.number(),expires_on:J.string()}),grouping:{mode:"incident"},groupKey:($)=>$.expires_on,link:()=>"/system/license",defaults:a$,en:{title:($)=>`License expires in ${$.days} ${D1($.days,"day","days")}`,body:($)=>`License expires in ${$.days} ${D1($.days,"day","days")}.`},pt:{title:()=>"Licença próxima do vencimento",body:($)=>`A licença vence em ${$.days} ${$.days===1?"dia":"dias"}.`},webhook:{alertType:()=>"license_expiring",metricValue:($)=>$.days,threshold:()=>30,resolvedTitle:()=>"License expiry warning closed",resolvedBody:()=>"The license was renewed or has expired."}}),"license.expired":G$({kind:"license.expired",area:"usage",audience:"platform",permission:"system:diagnostics",severity:"critical",params:J.strictObject({}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/system/license",defaults:M1,locked:!0,en:{title:()=>"License expired",body:()=>"NIVA license has expired."},pt:{title:()=>"Licença vencida",body:()=>"A licença da NIVA venceu."},webhook:{alertType:()=>"license_expired"}}),"storage.disk":G$({kind:"storage.disk",area:"services",audience:"platform",permission:"system:diagnostics",severity:"warning",params:J.strictObject({pct:J.number(),threshold:J.number()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/system/storage",defaults:a$,en:{title:($)=>`Disk usage ${$.pct}%`,body:($)=>`Disk usage at ${$.pct}%.`},pt:{title:()=>"Uso de disco elevado",body:($)=>`O uso do disco chegou a ${$.pct}%.`},webhook:{alertType:()=>"storage_high",metricValue:($)=>$.pct,threshold:($)=>$.threshold}}),"storage.recordings_blocked":G$({kind:"storage.recordings_blocked",area:"services",audience:"platform",permission:"system:diagnostics",severity:"warning",params:J.strictObject({used:J.number(),cap:J.number()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/system/storage",defaults:a$,en:{title:($)=>`Recording storage cap reached (${$.used} GB of ${$.cap} GB)`,body:($)=>`Recordings use ${$.used} GB against a ${$.cap} GB cap and none may be removed yet.`},pt:{title:()=>"Limite de armazenamento das gravações atingido",body:($)=>`As gravações ocupam ${$.used} GB de ${$.cap} GB e ainda não podem ser removidas.`},webhook:{alertType:()=>"recording_retention_blocked",metricValue:($)=>$.used,threshold:($)=>$.cap}}),"calls.error_rate":G$({kind:"calls.error_rate",area:"calls",audience:"organization",permission:"call_record:read",severity:"warning",params:J.strictObject({rate:J.number(),failures:J.number(),total:J.number(),threshold:J.number(),plan_name:J.string().optional()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/reports",defaults:M1,en:{title:($)=>`Call error rate ${$.rate}%`,body:($)=>`${$.failures}/${$.total} failed.`},pt:{title:()=>"Taxa de erros nas chamadas",body:($)=>`${$.failures} de ${$.total} chamadas falharam (${$.rate}%).`},webhook:{alertType:()=>"call_error_rate",metricValue:($)=>$.rate,threshold:($)=>$.threshold}}),"calls.plan_error_rate":G$({kind:"calls.plan_error_rate",area:"calls",audience:"organization",permission:"call_record:read",severity:"warning",params:J.strictObject({plan_id:J.string(),plan_name:J.string(),rate:J.number(),failures:J.number(),total:J.number(),threshold:J.number()}),grouping:{mode:"incident"},groupKey:($)=>$.plan_id,link:()=>"/reports",defaults:a$,en:{title:($)=>`${$.plan_name}: error rate ${$.rate}%`,body:($)=>`${$.failures}/${$.total} failed.`},pt:{title:($)=>`Erros no plano ${$.plan_name}`,body:($)=>`${$.failures} de ${$.total} chamadas falharam (${$.rate}%).`},webhook:{alertType:()=>"plan_error_rate",metricValue:($)=>$.rate,threshold:($)=>$.threshold}}),"calls.transfer_failure":G$({kind:"calls.transfer_failure",area:"calls",audience:"organization",permission:"call_record:read",severity:"warning",params:J.strictObject({rate:J.number(),failures:J.number(),total:J.number(),threshold:J.number()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/reports",defaults:a$,en:{title:($)=>`Transfer failure rate ${$.rate}%`,body:($)=>`${$.failures}/${$.total} failed.`},pt:{title:()=>"Falhas nas transferências",body:($)=>`${$.failures} de ${$.total} transferências falharam (${$.rate}%).`},webhook:{alertType:()=>"transfer_failure_rate",metricValue:($)=>$.rate,threshold:($)=>$.threshold}}),"calls.stale":G$({kind:"calls.stale",area:"calls",audience:"organization",permission:"call_record:read",severity:"warning",params:J.strictObject({count:J.number(),threshold:J.number()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/reports",defaults:a$,en:{title:()=>"Stale calls detected",body:($)=>`${$.count} ${D1($.count,"stale call","stale calls")}.`},pt:{title:()=>"Chamadas sem atividade",body:($)=>`Foram detectadas ${$.count} chamadas sem atividade.`},webhook:{alertType:()=>"stale_calls",metricValue:($)=>$.count,threshold:($)=>$.threshold}}),"calls.transcription_failed":G$({kind:"calls.transcription_failed",area:"calls",audience:"organization",permission:"call_record:read",severity:"warning",params:J.strictObject({count:J.number(),threshold:J.number()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/reports",defaults:a$,en:{title:()=>"Transcription failures",body:($)=>`${$.count} ${D1($.count,"failure","failures")}.`},pt:{title:()=>"Falhas na transcrição",body:($)=>`Foram detectadas ${$.count} falhas na transcrição.`},webhook:{alertType:()=>"transcription_failures",metricValue:($)=>$.count,threshold:($)=>$.threshold}}),"calls.rejected":G$({kind:"calls.rejected",area:"calls",audience:"organization",permission:"call_record:read",severity:"warning",params:J.strictObject({reason:J.string(),destination:J.string(),count:J.number()}),grouping:{mode:"window",windowSeconds:900},groupKey:($)=>$.reason,link:()=>"/reports",defaults:a$,en:{title:()=>"Calls rejected",body:($,U)=>`${U.count} ${D1(U.count,"call","calls")} rejected (${$.reason}).`},pt:{title:()=>"Chamadas rejeitadas",body:($,U)=>`${U.count} ${U.count===1?"chamada rejeitada":"chamadas rejeitadas"}: ${$.reason}.`}}),"calls.node_error":G$({kind:"calls.node_error",area:"calls",audience:"organization",permission:"call_record:read",severity:"warning",params:J.strictObject({node_id:J.string(),node_type:J.string(),node_label:J.string(),error_code:J.string(),visual_plan_id:J.string(),visual_plan_name:J.string(),count:J.number()}),grouping:{mode:"window",windowSeconds:900},groupKey:($)=>`${$.visual_plan_id}:${$.node_id}:${$.error_code}`,link:()=>"/reports",defaults:a$,en:{title:()=>"Call node errors",body:($,U)=>`${U.count} ${D1(U.count,"error","errors")} in ${$.node_label} (${$.error_code}).`},pt:{title:()=>"Erros nos nós de chamada",body:($,U)=>`${U.count} ${U.count===1?"erro":"erros"} em ${$.node_label} (${$.error_code}).`}}),"webhook.endpoint_down":G$({kind:"webhook.endpoint_down",area:"integrations",audience:"organization",permission:"webhook:read",severity:"critical",params:J.strictObject({endpoint_id:J.string(),endpoint_url:J.string(),endpoint_description:J.string().nullable(),failed_attempts:J.number(),last_error:J.string().nullable()}),grouping:{mode:"incident"},groupKey:($)=>$.endpoint_id,link:()=>"/settings/webhooks",defaults:M1,en:{title:()=>"Webhook endpoint failing",body:($)=>`${$.failed_attempts} consecutive ${D1($.failed_attempts,"failure","failures")}.`},pt:{title:()=>"Webhook com falhas",body:($)=>`${$.failed_attempts} ${$.failed_attempts===1?"falha consecutiva":"falhas consecutivas"} na entrega do webhook.`},webhook:{alertType:()=>"webhook_failures",metricValue:($)=>$.failed_attempts,threshold:()=>3}}),"webhook.queue_delayed":G$({kind:"webhook.queue_delayed",area:"integrations",audience:"organization",permission:"webhook:read",severity:"warning",params:J.strictObject({depth:J.number(),minutes:J.number(),threshold:J.number()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/settings/webhooks",defaults:a$,en:{title:($)=>`Webhook queue delayed ${$.minutes} min`,body:($)=>`${$.depth} pending ${D1($.depth,"delivery","deliveries")}; the oldest has waited ${$.minutes} min.`},pt:{title:()=>"Fila de webhooks atrasada",body:($)=>`${$.depth} entregas pendentes; a mais antiga aguarda há ${$.minutes} min.`},webhook:{alertType:()=>"webhook_queue_backlog",metricValue:($)=>$.minutes,threshold:($)=>$.threshold}}),"connector.needs_attention":G$({kind:"connector.needs_attention",area:"integrations",audience:"organization",permission:"connector:read",severity:"critical",params:J.strictObject({connector_id:J.string(),connector_name:J.string(),kind:J.string(),error_code:J.string(),error_message:J.string()}),grouping:{mode:"incident"},groupKey:($)=>$.connector_id,link:($)=>`/settings/connectors/${$.connector_id}`,defaults:M1,en:{title:($)=>`Connector ${$.connector_name} needs attention`,body:($)=>`${$.error_code}: ${$.error_message}`},pt:{title:($)=>`O conector ${$.connector_name} precisa de atenção`,body:($)=>`${$.error_code}: ${$.error_message}`},webhook:{alertType:()=>"connector_needs_attention"}}),"secret.missing":G$({kind:"secret.missing",area:"integrations",audience:"organization",permission:"secret:read",severity:"critical",params:J.strictObject({secret:J.string(),node_label:J.string()}),grouping:{mode:"window",windowSeconds:3600},groupKey:($)=>$.secret,link:()=>"/settings/secrets",defaults:M1,en:{title:()=>"Secret missing",body:($)=>`The secret ${$.secret} is missing for ${$.node_label}.`},pt:{title:()=>"Secret ausente",body:($)=>`O secret ${$.secret} está ausente em ${$.node_label}.`}}),"signal.triggered":G$({kind:"signal.triggered",area:"signals",audience:"organization",permission:"ai:read",severity:"warning",params:J.strictObject({signal:J.string(),signal_id:J.string(),call_id:J.string(),caller:J.string().nullable()}),grouping:{mode:"window",windowSeconds:900},groupKey:($)=>$.signal_id,link:($,U)=>U.count===1?`/reports?trace=${$.call_id}`:`/reports?signal=${$.signal_id}`,defaults:M1,en:{title:($)=>`Signal triggered: ${$.signal}`,body:($,U)=>`${U.count} ${D1(U.count,"call","calls")} triggered ${$.signal}.`},pt:{title:($)=>`Sinal detectado: ${$.signal}`,body:($,U)=>`${U.count} ${U.count===1?"chamada acionou":"chamadas acionaram"} o sinal ${$.signal}.`}}),"usage.channel_capacity":G$({kind:"usage.channel_capacity",area:"usage",audience:"organization",permission:"channel:read",severity:"warning",params:J.strictObject({pct:J.number(),active:J.number(),limit:J.number(),pool:J.string()}),grouping:{mode:"incident"},groupKey:($)=>$.pool,link:()=>"/dashboard",defaults:M1,en:{title:($)=>`${$.pool} channel capacity ${$.pct}%`,body:($)=>`${$.active}/${$.limit} ${$.pool} ${D1($.limit,"channel","channels")} in use.`},pt:{title:()=>"Capacidade de canais",body:($)=>`${$.active} de ${$.limit} canais ${$.pool} em uso (${$.pct}%).`},webhook:{alertType:()=>"channel_capacity",metricValue:($)=>$.pct,threshold:()=>90}}),"usage.audit_retention":G$({kind:"usage.audit_retention",area:"usage",audience:"organization",permission:"audit:read",severity:"warning",params:J.strictObject({count:J.number(),limit:J.number()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/settings/audit",defaults:wx,en:{title:()=>"Audit retention capacity exceeded",body:($)=>`Audit log count (${$.count}) exceeds the retention limit (${$.limit}).`},pt:{title:()=>"Limite de retenção da auditoria excedido",body:($)=>`${$.count} registros de auditoria ultrapassam o limite de ${$.limit}.`},webhook:{alertType:()=>"audit_retention_capacity",metricValue:($)=>$.count,threshold:($)=>$.limit}}),"system.update_available":G$({kind:"system.update_available",area:"services",audience:"platform",permission:"system:diagnostics",severity:"info",params:J.strictObject({version:J.string()}),grouping:{mode:"once"},groupKey:($)=>$.version,link:()=>"/system/updates",defaults:a$,en:{title:($)=>`NIVA ${$.version} is available`,body:($)=>`A new NIVA release is available: ${$.version}.`},pt:{title:($)=>`NIVA ${$.version} disponível`,body:($)=>`Uma nova versão da NIVA está disponível: ${$.version}.`}}),"system.update_completed":G$({kind:"system.update_completed",area:"services",audience:"platform",permission:"system:diagnostics",severity:"info",params:J.strictObject({run_id:J.string(),from_version:J.string(),to_version:J.string()}),grouping:{mode:"once"},groupKey:($)=>$.run_id,link:()=>"/system/updates",defaults:M1,en:{title:($)=>`NIVA updated to ${$.to_version}`,body:($)=>`NIVA was updated from ${$.from_version} to ${$.to_version}.`},pt:{title:($)=>`NIVA atualizada para ${$.to_version}`,body:($)=>`A NIVA foi atualizada de ${$.from_version} para ${$.to_version}.`}}),"system.update_failed":G$({kind:"system.update_failed",area:"services",audience:"platform",permission:"system:diagnostics",severity:"critical",params:J.strictObject({run_id:J.string(),status:J.enum(["failed","rolled_back","action_required"]),error_code:J.string()}),grouping:{mode:"once"},groupKey:($)=>$.run_id,link:()=>"/system/updates",defaults:M1,en:{title:()=>"NIVA update failed",body:($)=>`The update ended with status ${$.status} (${$.error_code}).`},pt:{title:()=>"Falha na atualização da NIVA",body:($)=>`A atualização terminou com o estado ${$.status} (${$.error_code}).`}})};var LX="urn:ietf:params:oauth:grant-type:device_code",_X=["authorization_code","refresh_token",LX],gW="ABCDEFGHJKLMNPQRSTUVWXYZ",zx=J.object({resource:J.string(),authorization_servers:J.array(J.string()).min(1),scopes_supported:J.array(J.string()),bearer_methods_supported:J.array(J.string()),resource_name:J.string().optional()}),Rx=J.object({issuer:J.string(),authorization_endpoint:J.string(),token_endpoint:J.string(),registration_endpoint:J.string(),revocation_endpoint:J.string(),device_authorization_endpoint:J.string(),response_types_supported:J.array(J.string()),grant_types_supported:J.array(J.string()),code_challenge_methods_supported:J.array(J.string()),token_endpoint_auth_methods_supported:J.array(J.string()),client_id_metadata_document_supported:J.literal(!0),authorization_response_iss_parameter_supported:J.literal(!0),scopes_supported:J.array(J.string())}),bx=J.string().refine(($)=>{try{return new URL($).protocol==="https:"}catch{return!1}},"must be an https URL"),Ox=J.object({client_id:bx,redirect_uris:J.array(J.string().min(1)).min(1),client_name:J.string().optional(),client_uri:J.string().optional(),logo_uri:J.string().optional(),scope:J.string().optional(),grant_types:J.array(J.string()).optional(),response_types:J.array(J.string()).optional(),token_endpoint_auth_method:J.string().optional(),token_endpoint_auth_methods_supported:J.array(J.string()).optional(),application_type:J.enum(["native","web"]).optional()}).refine(Tx,{error:'client must support the "none" token endpoint auth method',path:["token_endpoint_auth_method"]});function Tx($){let U=$.token_endpoint_auth_methods_supported;if(U!=null)return U.includes("none");let K=$.token_endpoint_auth_method;return K==null||K==="none"}var Sx=J.object({redirect_uris:J.array(J.string().min(1)).min(1),client_name:J.string().max(200).optional(),client_uri:J.string().optional(),logo_uri:J.string().optional(),scope:J.string().optional(),grant_types:J.array(J.enum(_X)).optional(),response_types:J.array(J.literal("code")).optional(),token_endpoint_auth_method:J.literal("none").optional(),application_type:J.enum(["native","web"]).optional()}),Cx=J.object({client_id:J.string(),client_id_issued_at:J.number().int(),redirect_uris:J.array(J.string()),client_name:J.string().optional(),token_endpoint_auth_method:J.literal("none"),grant_types:J.array(J.string()),response_types:J.array(J.string()),application_type:J.enum(["native","web"]).optional(),scope:J.string().optional()}),Ex=J.object({client_id:J.string().min(1).max(2048),scope:J.string().max(2000).default(""),resource:J.string().min(1).max(2048)}),yx=J.object({device_code:J.string().min(1),user_code:J.string().regex(new RegExp(`^[${gW}]{4}-[${gW}]{4}$`)),verification_uri:J.string(),verification_uri_complete:J.string().optional(),expires_in:J.number().int().positive(),interval:J.number().int().positive()});var r3={visual_plan:["read","create","update","delete","publish"],channel:["read","create","update","delete"],destination:["read","create","update","delete"],schedule:["read","create","update","delete"],holiday:["read","create","update","delete"],audio_file:["read","create","update","delete"],call_record:["read","export","purge"],call_content:["read"],call:["originate","hangup"],dashboard:["read","update"],notification:["manage"],test_call:["execute"],tts:["read"],org_settings:["read","update"],user:["read","invite","update_role","suspend","remove","reset_password"],api_key:["read","create","revoke"],oauth_grant:["read","revoke"],acl:["read","create","update","delete"],audit:["read"],webhook:["read","create","update","delete"],ai:["read","execute","configure","manage_key"],org_integration:["read","update"],analysis_template:["read","create","update","delete"],contact:["read","update"],dialer_campaign:["read","create","update","delete","control"],dialer_dnc:["read","manage"],archive:["read","purge"],secret:["read","create","update","delete"],connector:["read","create","update","delete"],role:["read","create","update","delete"],license:["read"],organization:["list","create","update","delete"],integration:["read","update"],org_plan:["read","update"],platform_admin:["read","manage"],platform_storage:["manage"],system:["logs","diagnostics","operate","update"]},uW={visual_plan:"organization",channel:"organization",destination:"organization",schedule:"organization",holiday:"organization",audio_file:"organization",call_record:"organization",call_content:"organization",call:"organization",dashboard:"organization",notification:"organization",test_call:"organization",tts:"organization",org_settings:"organization",user:"organization",api_key:"organization",oauth_grant:"organization",acl:"organization",audit:"organization",webhook:"organization",ai:"organization",org_integration:"organization",analysis_template:"organization",contact:"organization",dialer_campaign:"organization",dialer_dnc:"organization",archive:"organization",secret:"organization",connector:"organization",role:"organization",license:"platform",organization:"platform",integration:"platform",org_plan:"platform",platform_admin:"platform",platform_storage:"platform",system:"platform"},IX=Object.entries(r3),FX=IX.flatMap(([$,U])=>U.map((K)=>`${$}:${K}`));var xX={super_admin:["*"],administrator:["*"],editor:["visual_plan:read","visual_plan:create","visual_plan:update","visual_plan:delete","visual_plan:publish","channel:read","channel:create","channel:update","channel:delete","destination:read","destination:create","destination:update","destination:delete","schedule:read","schedule:create","schedule:update","schedule:delete","holiday:read","holiday:create","holiday:update","holiday:delete","audio_file:read","audio_file:create","audio_file:update","audio_file:delete","test_call:execute","call:originate","call:hangup","dashboard:read","dashboard:update","call_record:read","call_record:export","call_content:read","tts:read","ai:read","ai:execute","ai:configure","analysis_template:read","analysis_template:create","analysis_template:update","analysis_template:delete","contact:read","contact:update","dialer_campaign:read","dialer_campaign:create","dialer_campaign:update","dialer_campaign:delete","dialer_campaign:control","dialer_dnc:read","dialer_dnc:manage","archive:read","user:read","role:read","webhook:read","api_key:read","oauth_grant:read"],supervisor:["visual_plan:read","channel:read","destination:read","schedule:read","holiday:read","audio_file:read","dashboard:read","dashboard:update","call_record:read","call_record:export","call_content:read","test_call:execute","call:hangup","tts:read","ai:read","ai:execute","analysis_template:read","contact:read","contact:update","dialer_campaign:read","dialer_campaign:control","dialer_dnc:read","user:read","role:read","webhook:read","api_key:read","oauth_grant:read","acl:read","audit:read","archive:read"],operator:["visual_plan:read","channel:read","destination:read","schedule:read","holiday:read","audio_file:read","dashboard:read","call_record:read","test_call:execute","call:hangup","tts:read","contact:read","contact:update","dialer_campaign:read","dialer_dnc:read","user:read","archive:read"],viewer:["visual_plan:read","channel:read","destination:read","schedule:read","holiday:read","audio_file:read","dashboard:read","call_record:read","tts:read","user:read","role:read","webhook:read","api_key:read","oauth_grant:read","acl:read","audit:read","ai:read","analysis_template:read","contact:read","dialer_campaign:read","dialer_dnc:read","archive:read"]},gx=Object.keys(xX);var yc=IX.filter(([$])=>uW[$]==="organization").flatMap(([$,U])=>U.map((K)=>`${$}:${K}`));var gc=new Map(FX.map(($)=>[$,$])),uc=new Map(Object.entries(uW));var hc=new Set(`@£$¥èéùìòÇ
|
|
88
|
+
Øø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !"#¤%&'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà`);var fW={plans:{entities:["visual_plan","audio_file","tts","analysis_template","test_call"]},telephony:{entities:["channel","destination","schedule","holiday","acl"]},calls:{entities:["call","call_record","call_content","contact","dashboard","notification","archive","ai"]},dialer:{entities:["dialer_campaign","dialer_dnc"],module:"dialer"},admin:{entities:["user","role","api_key","oauth_grant","org_settings","webhook","org_integration","audit","secret","connector","license"]},platform:{entities:["organization","integration","org_plan","platform_admin","platform_storage","system"],platformOnly:!0}},fx=Object.keys(fW),mx=new Map;for(let $ of fx)for(let U of fW[$].entities)mx.set(U,$);var wX=new Set(["*:read","*:write","offline_access"]);for(let $ of Object.keys(r3))wX.add(`${$}:read`),wX.add(`${$}:write`);var mW=J.object({version:J.literal(1),startNodeId:J.string().min(1),nodes:J.record(J.string(),J.object({type:J.string().min(1),label:J.string(),varName:J.string(),config:J.record(J.string(),J.unknown())})),adjacency:J.record(J.string(),J.record(J.string(),J.string()))});function cW($,U,K,q,Q){let W=U.channelType,G=typeof W==="string"?W:"voice";if(G!=="both")return hx($,K,q,G==="voice"?"voice-only":"chat-only");return lx($,K,q,Q)}function hx($,U,K,q){let Q=hW($,U),W={};for(let G of K)W[G]=Q.has(G)?q:"unreachable";return W[$]=q,W}function cx($,U){if($&&U)return"converged";if($)return"voice-only";if(U)return"chat-only";return"unreachable"}function lx($,U,K,q){let Q=U.get($)?.get("voice"),W=U.get($)?.get("chat"),G=Q!=null?hW(Q,U,q,"voice"):new Set,j=W!=null?hW(W,U,q,"chat"):new Set;if(Q!=null)G.add(Q);if(W!=null)j.add(W);let Y={};for(let H of K)Y[H]=H===$?"converged":cx(G.has(H),j.has(H));return Y}function hW($,U,K,q){let Q=new Set,W=[$];Q.add($);let G=0;while(G<W.length){let j=W[G++],Y=U.get(j);if(Y==null)continue;if(q!=null&&K?.has(j)){let H=Y.get(q);if(H!=null&&!Q.has(H))Q.add(H),W.push(H);continue}for(let H of Y.values())if(!Q.has(H))Q.add(H),W.push(H)}return Q}function f(){return($,U)=>({key:U,prefix:`${$}:`})}var AX={call:f()("call",($)=>`call:${$}`),testPlan:f()("test-plan",($)=>`test-plan:${$}`),testChatPlan:f()("test-chat-plan",($)=>`test-chat-plan:${$}`),testEditorState:f()("test-editor-state",($)=>`test-editor-state:${$}`),testExecutionTrace:f()("test-execution-trace",($)=>`test-execution-trace:${$}`),refreshToken:f()("rt",($)=>`rt:${$}`),hostActionConfirmation:f()("host-action-confirmation",($)=>`host-action-confirmation:${$}`),revokedToken:f()("revoked",($)=>`revoked:${$}`),revokedSession:f()("revoked-session",($)=>`revoked-session:${$}`),legacyAuthCutoff:f()("legacy-auth-cutoff",($)=>`legacy-auth-cutoff:${$}`),oauthCode:f()("oauth:code",($)=>`oauth:code:${$}`),oauthCimd:f()("oauth:cimd",($)=>`oauth:cimd:${$}`),oauthDevice:f()("oauth:device",($)=>`oauth:device:${$}`),oauthUsercode:f()("oauth:usercode",($)=>`oauth:usercode:${$}`),oauthUsercodeAttempts:f()("oauth:usercode-attempts",($)=>`oauth:usercode-attempts:${$}`),channels:f()("niva:channels",($)=>`niva:channels:${$}`),concurrentChannels:f()("niva:concurrent_channels",($,U)=>`niva:concurrent_channels:${$}:${U}`),peakConcurrentChannels:f()("niva:peak_concurrent",($,U)=>`niva:peak_concurrent:${$}:${U}`),dialerCampaignActive:f()("niva:dialer_campaign_active",($)=>`niva:dialer_campaign_active:${$}`),capacityReservation:f()("niva:capacity_reservation",($)=>`niva:capacity_reservation:${$}`),capacityReservationData:f()("niva:capacity_reservation_data",()=>"niva:capacity_reservation_data"),capacityReservationExpiry:f()("niva:capacity_reservation_expiry",()=>"niva:capacity_reservation_expiry"),capacityReservationHandoff:f()("niva:capacity_reservation_handoff",($)=>`niva:capacity_reservation_handoff:${$}`),counterByPlan:f()("niva:counter:plan",($,U,K)=>`niva:counter:plan:${$}:${U}:${K}`),counterByOrg:f()("niva:counter:org",($,U)=>`niva:counter:org:${$}:${U}`),trafficSplitRotation:f()("niva:traffic_split",($,U,K,q)=>`niva:traffic_split:${$}:${U}:${K}:${q}`),rateLimit:f()("rl",($,U)=>`rl:${$}:${U}`),liveTranscriptionSegments:f()("live-ts",($)=>`live-ts:${$}`),liveSignalEvents:f()("live-sig",($)=>`live-sig:${$}`),liveTranscriptionSummary:f()("live-ts-summary",($)=>`live-ts-summary:${$}`),transcriptionWatchers:f()("ts-watchers",($)=>`ts-watchers:${$}`),transcriptionDeferredJobs:f()("transcription:deferred:jobs",()=>"transcription:deferred:jobs"),transcriptionDeferredReady:f()("transcription:deferred:ready",()=>"transcription:deferred:ready"),transcriptionDeferredLeases:f()("transcription:deferred:leases",()=>"transcription:deferred:leases"),chatSession:f()("chat-session",($)=>`chat-session:${$}`),chatLookup:f()("chat-lookup",($,U,K)=>`chat-lookup:${$}:${U}:${K}`),activeVoiceCalls:f()("niva:active:voice",($)=>`niva:active:voice:${$}`),activeChatSessions:f()("niva:active:chat",($)=>`niva:active:chat:${$}`),chatLock:f()("chat-lock",($,U)=>`chat-lock:${$}:${U}`),chatInboundMessage:f()("chat-inbound-message",($,U,K,q)=>`chat-inbound-message:${$}:${U}:${K}:${q}`),wsSession:f()("ws:session",($)=>`ws:session:${$}`),wsMessageLog:f()("ws:log",($)=>`ws:log:${$}`),wsSeq:f()("ws:seq",($)=>`ws:seq:${$}`),healthStatus:f()("health-status",($)=>`health-status:${$}`),alertCooldown:f()("alert-cd",($,U)=>`alert-cd:${$}:${U}`),auditRetentionOverCap:f()("audit-retention",()=>"audit-retention:over-cap"),storageCleanup:f()("storage:cleanup",($)=>`storage:cleanup:${$}`),recordingDownloadAudit:f()("rec-dl-audit",($,U)=>`rec-dl-audit:${$}:${U}`),connectorPhoneNumbers:f()("connector:phone-numbers",($,U)=>`connector:phone-numbers:v${U}:${$}`),connectorPhoneNumbersVersion:f()("connector:phone-numbers:version",($)=>`connector:${$}:phone-numbers:version`),connectorTemplates:f()("connector:templates",($,U)=>`connector:templates:v${U}:${$}`),connectorTemplatesVersion:f()("connector:templates:version",($)=>`connector:${$}:templates:version`),whatsappTemplateMessage:f()("wa-template-msg",($)=>`wa-template-msg:${$}`),screenPop:f()("screenpop",($,U)=>`screenpop:${$}:${U}`),screenPopLegacy:f()("call_info",($)=>`call_info_${$}`),engineHeartbeat:f()("engine:heartbeat",()=>"engine:heartbeat")};function ix($){return t$[$]?.connector}function lW($,U){return typeof $==="string"&&$!==""&&!U.has($)}function I0($,U){return{nodeId:$.id,severity:"error",messageKey:U,params:{label:$.label}}}function dx($,U){if($.type!=="timeRouting"||U==null)return null;if(!lW($.config.scheduleId,U))return null;return I0($,"editor:validation.danglingSchedule")}function ox($,U){if($.type!=="subPlan"||U==null)return null;if(!lW($.config.planId,U))return null;return I0($,"editor:validation.danglingPlan")}function nx($,U){if(U==null)return null;let K=$.config.audio;if(K==null||typeof K!=="object"||!("file"in K))return null;let q=K.file;if(q==null||typeof q!=="object"||!("id"in q))return null;if(!lW(q.id,U))return null;return I0($,"editor:validation.danglingAudioFile")}function px($,U){if(U==null)return null;let K=ix($.type);if(K==null)return null;let q=$.config[K.configKey];if(typeof q!=="string"||q==="")return null;let Q=U.get(q);if(Q===void 0)return I0($,"editor:validation.danglingConnector");if(Q!==K.kind)return I0($,"editor:validation.connectorKindMismatch");return null}function tx($,U){if(U==null)return[];return g3($).allowed.filter((K)=>!U.has(K)).map((K)=>({nodeId:$.id,severity:"error",messageKey:"editor:validation.danglingSecret",params:{label:$.label,secret:K}}))}function rW($,U){let K=[];for(let q of $){let Q=dx(q,U.schedules);if(Q!=null)K.push(Q);let W=ox(q,U.publishedPlans);if(W!=null)K.push(W);let G=nx(q,U.audioFiles);if(G!=null)K.push(G);let j=px(q,U.connectors);if(j!=null)K.push(j);K.push(...tx(q,U.secrets))}return K}function iW($,U){let K=[];for(let q of $){if(q.type!=="aiAgent"||U.aiAgents==null)continue;let Q=q.config.agent_id;if(typeof Q==="string"&&Q!==""&&!U.aiAgents.has(Q))K.push({nodeId:q.id,severity:"warning",messageKey:"editor:validation.danglingAiAgent",params:{label:q.label}})}return K}var c$={basic:["started_at","caller_id","callee_id","direction","channel_type","status","duration_s","hangup_cause","plan_name"],details:["answered_at","ended_at","billing_duration_s","sip_call_id","remote_addr","user_agent","sip_hangup_disposition","sip_code"],media:["was_recorded","transcription_status","transcription","analysis","sentiment_label","ai_agent_price","ai_agent_currency"],errors:["has_error","error_count","last_error_code"],origin:["origin_type","origin_name"],metadata:["metadata"],variables:["variables"]},dW=[...c$.basic,...c$.details,...c$.media,...c$.errors,...c$.origin,...c$.metadata,...c$.variables],vX=/^analysis:[a-z0-9][a-z0-9-]*\.[A-Za-z0-9_-]+(?:\[\])?(?:\.[A-Za-z0-9_-]+(?:\[\])?)*$/,ax=J.string().regex(vX,{error:"Invalid structured-analysis export column"}).refine(($)=>kX($),{error:"Invalid structured-analysis export column"});function kX($){return vX.test($)}var zX=/^signal:[a-z][a-z0-9_]*(?:\.triggered_at)?$/;function RX($){return zX.test($)}var sx=J.string().regex(zX,{error:"Invalid signal export column"}).refine(($)=>RX($),{error:"Invalid signal export column"}),bX=["sip_call_id","remote_addr","user_agent"],ex=new Set(bX),$w=dW.filter(($)=>!ex.has($)),Uw=[...c$.basic];var Qw={basic:[...c$.basic],full:[...dW],ai_audit:[...c$.basic,"transcription_status","transcription","analysis","sentiment_label","ai_agent_price","ai_agent_currency",...c$.errors,...c$.metadata,"variables"]};var i3=["call.started","call.answered","call.amd_completed","call.hangup","call.rejected","call.node_entered","call.node_error","call.node_warning","call.transcribed","call.transcription_failed","call.analysis_completed","call.transferred","call.recording_available","call.intent_matched","call.signal_triggered","plan.published","message.sent","dialer.attempt.finished","alert.fired","alert.resolved","service.down","service.up","webhook.test"],Kw=i3.filter(($)=>$!=="webhook.test");var OX=[1,5,30,120,300,600],qw=OX.length,TX=J.enum(["inbound","outbound"]),B$=J.iso.datetime(),l$=J.record(J.string(),J.string()),Ww=J.strictObject({amd:J.literal(!0),machine_type:J.literal(!0).optional(),mode:J.enum(mH).optional(),max_wait_seconds:J.number().int().min(3).max(10).optional()}).superRefine(($,U)=>{if($.max_wait_seconds!==void 0&&$.mode!=="pre")U.addIssue({code:"custom",path:["max_wait_seconds"],message:"max_wait_seconds is only valid with mode=pre"})}),SX=J.strictObject({call_id:J.string().min(1).meta({"x-niva-typeid":m.call_records}),caller_id:J.string(),callee_id:J.string(),direction:TX,visual_plan_id:J.string().min(1).meta({"x-niva-typeid":m.visual_plans}),visual_plan_name:J.string(),started_at:B$,answer_recognition:Ww.optional(),metadata:l$}),CX=J.strictObject({call_id:J.string().min(1).meta({"x-niva-typeid":m.call_records}),caller_id:J.string(),callee_id:J.string(),answered_at:B$,metadata:l$}),oW=J.enum(["machine","human","silence","unknown"]),EX=J.enum(hH),yX=J.strictObject({call_id:J.string().min(1).meta({"x-niva-typeid":m.call_records}),channel_uuid:J.string().min(1),result:oW,machine_type:EX.optional(),completed_at:B$,metadata:l$}).superRefine(($,U)=>{if($.machine_type!==void 0&&$.result!=="machine")U.addIssue({code:"custom",path:["machine_type"],message:"machine_type is only valid when result is machine"})}),gX=J.strictObject({call_id:J.string().min(1).meta({"x-niva-typeid":m.call_records}),caller_id:J.string(),callee_id:J.string(),direction:TX,visual_plan_id:J.string().min(1).meta({"x-niva-typeid":m.visual_plans}),visual_plan_name:J.string(),started_at:B$,answered_at:B$.nullable(),ended_at:B$,duration_ms:J.number().nonnegative(),hangup_cause:J.string(),hangup_disposition:J.string(),was_recorded:J.boolean(),variables:J.record(J.string(),J.string()),sip_code:J.string().nullable(),billsec:J.number().nonnegative().nullable(),answer_recognition_results:J.strictObject({amd:oW}).optional(),metadata:l$}),uX=["not_found","channel_inactive","channel_deleted","plan_deleted","no_published_version","org_deleted","acl_denied","capacity_global","capacity_org","capacity_campaign","capacity_reservation"],fX=J.enum(uX),mX=J.strictObject({caller:J.string(),destination:J.string(),reason:fX,hangup_cause:J.string()}),hX=J.strictObject({call_id:J.string().min(1).meta({"x-niva-typeid":m.call_records}),caller_id:J.string(),callee_id:J.string(),node_id:J.string().min(1),node_type:J.string(),node_label:J.string(),handle_used:J.string(),digit:J.string().nullable(),entered_at:B$,exited_at:B$,duration_ms:J.number().nonnegative(),visual_plan_id:J.string().min(1).meta({"x-niva-typeid":m.visual_plans}),metadata:l$}),nW=J.strictObject({call_id:J.string().min(1).meta({"x-niva-typeid":m.call_records}),caller_id:J.string(),callee_id:J.string(),node_id:J.string().min(1),node_type:J.string(),node_label:J.string(),error_code:J.string(),error_message:J.string(),visual_plan_id:J.string().min(1).meta({"x-niva-typeid":m.visual_plans}),visual_plan_name:J.string(),occurred_at:B$,metadata:l$}),cX=nW,pW=J.strictObject({call_record_id:J.string().min(1).meta({"x-niva-typeid":m.call_records}),transcription_id:J.string().min(1).meta({"x-niva-typeid":m.call_transcriptions}),full_text:J.string(),is_anonymized:J.boolean(),metadata:l$}),lX=pW.pick({call_record_id:!0,transcription_id:!0,metadata:!0}).extend({error_code:J.enum(["ASR_REJECTED","RETRIES_EXHAUSTED","RANGE_TRANSCRIPTION_FAILED","PROCESSING_TIMEOUT"]),error_message:J.string()}),rX=["native","local","sippulse_ai"],Gw=J.enum(rX),iX=J.strictObject({source:J.literal("native"),id:J.null(),template_id:J.null(),name:J.string(),category:J.null()}),dX=J.strictObject({source:J.literal("local"),id:J.string().min(1).meta({"x-niva-typeid":m.call_analyses}),template_id:J.string().min(1).meta({"x-niva-typeid":m.analysis_templates}),name:J.string(),category:J.string().nullable()}),oX=J.strictObject({source:J.literal("sippulse_ai"),id:J.string().min(1).meta({"x-niva-typeid":m.call_analyses}),template_id:J.null(),external_id:J.string().min(1),slug:J.string().min(1),name:J.string(),category:J.null(),model:J.string().nullable()}),jl=J.discriminatedUnion("source",[iX,dX,oX]),tW={status:J.enum(["completed","failed"]),result:J.record(J.string(),J.unknown()).nullable(),error_message:J.string().nullable(),error_code:J.string().nullable()},Jw=J.strictObject({...iX.shape,...tW}),jw=J.strictObject({...dX.shape,...tW}),Yw=J.strictObject({...oX.shape,...tW}),Hw=J.discriminatedUnion("source",[Jw,jw,Yw]).superRefine(($,U)=>{if($.status==="failed"&&$.result!==null)U.addIssue({code:"custom",path:["result"],message:"Failed analyses must have a null result"})}),nX=J.enum(["caller","agent"]),pX=J.strictObject({id:J.string().min(1).meta({"x-niva-typeid":m.signals}),slug:J.string().min(1),name:J.string(),kind:J.enum(M6),version:J.number().int().positive()}),Xw=J.strictObject({signal:pX,value:J.union([J.boolean(),J.string(),J.number(),J.null()]),value_label:J.string().nullable(),confidence:J.number().nullable(),triggered:J.strictObject({at_seconds:J.number(),value:J.union([J.boolean(),J.string(),J.number(),J.null()]),value_label:J.string().nullable(),confidence:J.number().nullable(),late:J.boolean(),node_id:J.string().nullable()}).nullable()}),tX=J.strictObject({call_id:J.string().min(1).meta({"x-niva-typeid":m.call_records}),call_record_id:J.string().min(1).meta({"x-niva-typeid":m.call_records}),transcription_id:J.string().min(1).meta({"x-niva-typeid":m.call_transcriptions}),visual_plan_id:J.string().nullable().meta({"x-niva-typeid":m.visual_plans}),analyses:Hw.array(),signals:Xw.array(),analyzed_at:B$,metadata:l$}),aX=["answered","busy","noAnswer","failed"],sX=J.enum(aX),eX=J.strictObject({call_id:J.string().min(1).meta({"x-niva-typeid":m.call_records}),caller_id:J.string(),callee_id:J.string(),to_destination:J.string(),method:J.enum(["bridge","sip_message","blind"]),disposition:sX,status:J.string(),duration_ms:J.number().nonnegative().nullable(),transferred_at:B$,metadata:l$}),$Z=J.strictObject({call_id:J.string().min(1).meta({"x-niva-typeid":m.call_records}),call_record_id:J.string().min(1).meta({"x-niva-typeid":m.call_records}),recording_url:J.string(),storage_path:J.string(),duration_seconds:J.number().nonnegative().nullable(),format:J.string(),size_bytes:J.number().nonnegative().nullable(),available_at:B$,metadata:l$}),Zw=J.strictObject({intent:J.string(),confidence:J.number()}),UZ=J.strictObject({call_id:J.string().min(1).meta({"x-niva-typeid":m.call_records}),caller_id:J.string(),callee_id:J.string(),node_id:J.string().min(1),visual_plan_id:J.string().min(1).meta({"x-niva-typeid":m.visual_plans}),transcript:J.string(),intent:J.string(),confidence:J.number(),alternatives:J.array(Zw),language:J.string().nullable(),matched_at:B$,metadata:l$}),Bw=J.strictObject({speaker:nX,text:J.string(),start_seconds:J.number()}),Vw=J.strictObject({call_id:J.string().min(1).meta({"x-niva-typeid":m.call_records}),visual_plan_id:J.string().nullable().meta({"x-niva-typeid":m.visual_plans}),signal:pX,value:J.union([J.boolean(),J.string(),J.number(),J.null()]),value_label:J.string(),confidence:J.number(),severity:J.enum(D6),speaker:nX,at_seconds:J.number(),late:J.boolean(),source:J.enum(["live","end_of_call"]),node:J.strictObject({id:J.string(),label:J.string(),type:J.string()}).nullable(),window:J.array(Bw),is_anonymized:J.boolean(),trace_url:J.string().nullable(),metadata:l$}),QZ=J.strictObject({plan_id:J.string().min(1).meta({"x-niva-typeid":m.visual_plans}),plan_name:J.string(),version_id:J.string().min(1).meta({"x-niva-typeid":m.visual_plan_versions}),version_number:J.number().int().nonnegative(),published_by_user_id:J.string().min(1).meta({"x-niva-typeid":m.users}),notes:J.string().nullable(),published_at:B$}),KZ=["text","media","audio","image","video","document","location","interactive"],qZ=J.strictObject({session_id:J.string().min(1).meta({"x-niva-typeid":m.call_records}),channel_type:J.string(),to:J.string(),message_type:J.enum(KZ),text:J.string().nullable(),media_url:J.string().nullable(),node_id:J.string().nullable(),sent_at:B$}),WZ=["answered","machine","silence","busy","no_answer","failed","originate_error","cancelled"],GZ=J.enum(WZ),JZ=J.strictObject({campaign_id:J.string().min(1).meta({"x-niva-typeid":m.dialer_campaigns}),campaign_name:J.string(),contact_id:J.string().min(1).meta({"x-niva-typeid":m.dialer_contacts}),phone_number:J.string(),attempt_number:J.number().int().nonnegative(),status:GZ,hangup_cause:J.string().nullable(),sip_code:J.string().nullable(),call_uuid:J.string().nullable(),started_at:B$.nullable(),answered_at:B$.nullable(),ended_at:B$.nullable(),duration_s:J.number().nonnegative().nullable(),custom_fields:J.record(J.string(),J.string())}),jZ=J.strictObject({alert_type:J.string(),severity:J.enum(["critical","warning","info"]),title:J.string(),body:J.string(),metric_value:J.number().optional(),threshold:J.number().optional()}),YZ=J.strictObject({alert_type:J.string(),title:J.string(),body:J.string()}),HZ=J.strictObject({component:J.string(),checked_at:B$}),XZ=J.strictObject({component:J.string(),downtime_seconds:J.number().nonnegative().nullable(),recovered_at:B$}),ZZ=J.strictObject({webhook_endpoint_id:J.string().min(1),message:J.string().min(1)}),d3={"call.started":SX,"call.answered":CX,"call.amd_completed":yX,"call.hangup":gX,"call.rejected":mX,"call.node_entered":hX,"call.node_error":nW,"call.node_warning":cX,"call.transcribed":pW,"call.transcription_failed":lX,"call.analysis_completed":tX,"call.transferred":eX,"call.recording_available":$Z,"call.intent_matched":UZ,"call.signal_triggered":Vw,"plan.published":QZ,"message.sent":qZ,"dialer.attempt.finished":JZ,"alert.fired":jZ,"alert.resolved":YZ,"service.down":HZ,"service.up":XZ,"webhook.test":ZZ};function H$($){return J.strictObject({event:J.literal($),event_id:J.string().min(1),org_id:J.string().min(1),timestamp:B$,data:d3[$]})}var Mw=J.discriminatedUnion("event",[H$("call.started"),H$("call.answered"),H$("call.amd_completed"),H$("call.hangup"),H$("call.rejected"),H$("call.node_entered"),H$("call.node_error"),H$("call.node_warning"),H$("call.transcribed"),H$("call.transcription_failed"),H$("call.analysis_completed"),H$("call.transferred"),H$("call.recording_available"),H$("call.intent_matched"),H$("call.signal_triggered"),H$("plan.published"),H$("message.sent"),H$("dialer.attempt.finished"),H$("alert.fired"),H$("alert.resolved"),H$("service.down"),H$("service.up"),H$("webhook.test")]);function X$($){return J.strictObject({event:J.literal($),event_id:J.string().min(1),timestamp:B$,data:d3[$]})}var Dw=J.discriminatedUnion("event",[X$("call.started"),X$("call.answered"),X$("call.amd_completed"),X$("call.hangup"),X$("call.rejected"),X$("call.node_entered"),X$("call.node_error"),X$("call.node_warning"),X$("call.transcribed"),X$("call.transcription_failed"),X$("call.analysis_completed"),X$("call.transferred"),X$("call.recording_available"),X$("call.intent_matched"),X$("call.signal_triggered"),X$("plan.published"),X$("message.sent"),X$("dialer.attempt.finished"),X$("alert.fired"),X$("alert.resolved"),X$("service.down"),X$("service.up"),X$("webhook.test")]),i="01kknxab29enebk2vhm0tz0yyd",BZ={"call.started":{call_id:`call_${i}`,caller_id:"+15551230001",callee_id:"+15551230002",direction:"inbound",visual_plan_id:`vp_${i}`,visual_plan_name:"Support IVR",started_at:"2026-01-15T12:00:00.000Z",metadata:{}},"call.answered":{call_id:`call_${i}`,caller_id:"+15551230001",callee_id:"+15551230002",answered_at:"2026-01-15T12:00:03.000Z",metadata:{}},"call.amd_completed":{call_id:`call_${i}`,channel_uuid:"freeswitch-channel-example",result:"machine",machine_type:"voicemail",completed_at:"2026-01-15T12:00:05.000Z",metadata:{}},"call.hangup":{call_id:`call_${i}`,caller_id:"+15551230001",callee_id:"+15551230002",direction:"inbound",visual_plan_id:`vp_${i}`,visual_plan_name:"Support IVR",started_at:"2026-01-15T12:00:00.000Z",answered_at:"2026-01-15T12:00:03.000Z",ended_at:"2026-01-15T12:01:00.000Z",duration_ms:60000,hangup_cause:"NORMAL_CLEARING",hangup_disposition:"answered",was_recorded:!0,variables:{customer_tier:"standard"},sip_code:"200",billsec:57,metadata:{}},"call.rejected":{caller:"+15551230001",destination:"+15551230002",reason:"channel_inactive",hangup_cause:"UNALLOCATED_NUMBER"},"call.node_entered":{call_id:`call_${i}`,caller_id:"+15551230001",callee_id:"+15551230002",node_id:"node_menu",node_type:"ivr",node_label:"Main menu",handle_used:"digit:1",digit:"1",entered_at:"2026-01-15T12:00:04.000Z",exited_at:"2026-01-15T12:00:08.000Z",duration_ms:4000,visual_plan_id:`vp_${i}`,metadata:{}},"call.node_error":{call_id:`call_${i}`,caller_id:"+15551230001",callee_id:"+15551230002",node_id:"node_api",node_type:"httpRequest",node_label:"Load customer",error_code:"HTTP_ERROR",error_message:"Request failed",visual_plan_id:`vp_${i}`,visual_plan_name:"Support IVR",occurred_at:"2026-01-15T12:00:10.000Z",metadata:{}},"call.node_warning":{call_id:`call_${i}`,caller_id:"+15551230001",callee_id:"+15551230002",node_id:"node_transcription",node_type:"transcription",node_label:"Transcribe call",error_code:"transcription_requires_recording",error_message:"Transcription requires an active recording",visual_plan_id:`vp_${i}`,visual_plan_name:"Support IVR",occurred_at:"2026-01-15T12:00:10.000Z",metadata:{}},"call.transcribed":{call_record_id:`call_${i}`,transcription_id:`ctr_${i}`,full_text:"Hello, I need help with my account.",is_anonymized:!0,metadata:{}},"call.transcription_failed":{call_record_id:`call_${i}`,transcription_id:`ctr_${i}`,error_code:"ASR_REJECTED",error_message:"The speech recognition provider rejected the transcription.",metadata:{}},"call.analysis_completed":{call_id:`call_${i}`,call_record_id:`call_${i}`,transcription_id:`ctr_${i}`,visual_plan_id:`vp_${i}`,analyses:[{source:"native",id:null,template_id:null,name:"Speech analytics",category:null,status:"completed",error_code:null,result:{intent:"support",sentiment:{label:"positive",score:0.8},topics:[{topic:"billing",confidence:0.94}],summary:"Customer asked about their account.",key_points:["account question"]},error_message:null},{source:"sippulse_ai",id:`ca_${i}`,template_id:null,external_id:"sa_quality",slug:"quality",name:"Executive Summary",category:null,model:"deepseek-v4.1-flash",status:"failed",result:null,error_code:"upstream_failure",error_message:"Structured analysis service returned an error."}],analyzed_at:"2026-01-15T12:02:00.000Z",signals:[{signal:{id:`sig_${i}`,slug:"asked_for_human",name:"Asked for a human agent",kind:"yes_no",version:3},value:!0,value_label:"Yes",confidence:0.94,triggered:{at_seconds:134.2,value:!0,value_label:"Yes",confidence:0.94,late:!1,node_id:"menu_main"}}],metadata:{}},"call.transferred":{call_id:`call_${i}`,caller_id:"+15551230001",callee_id:"+15551230002",to_destination:"support@example.invalid",method:"bridge",disposition:"answered",status:"SUCCESS",duration_ms:null,transferred_at:"2026-01-15T12:00:20.000Z",metadata:{}},"call.recording_available":{call_id:`call_${i}`,call_record_id:`call_${i}`,recording_url:`https://example.invalid/recordings/call_${i}.wav`,storage_path:`recordings/example/call_${i}.wav`,duration_seconds:57,format:"wav",size_bytes:912000,available_at:"2026-01-15T12:01:01.000Z",metadata:{}},"call.intent_matched":{call_id:`call_${i}`,caller_id:"+15551230001",callee_id:"+15551230002",node_id:"node_intent",visual_plan_id:`vp_${i}`,transcript:"I need technical support",intent:"support",confidence:0.94,alternatives:[{intent:"support",confidence:0.94}],language:"en-US",matched_at:"2026-01-15T12:00:15.000Z",metadata:{}},"call.signal_triggered":{call_id:`call_${i}`,visual_plan_id:`vp_${i}`,signal:{id:`sig_${i}`,slug:"asked_for_human",name:"Asked for a human agent",kind:"yes_no",version:3},value:!0,value_label:"Yes",confidence:0.94,severity:"warning",speaker:"caller",at_seconds:134.2,late:!1,source:"live",node:{id:"menu_main",label:"Main menu",type:"menu"},window:[{speaker:"agent",text:"For a second copy, press 1",start_seconds:131.9},{speaker:"caller",text:"I want to talk to a person",start_seconds:133.4}],is_anonymized:!1,trace_url:`https://niva.example.com/reports?trace=call_${i}`,metadata:{}},"plan.published":{plan_id:`vp_${i}`,plan_name:"Support IVR",version_id:`vpv_${i}`,version_number:3,published_by_user_id:`usr_${i}`,notes:"Updated support routing",published_at:"2026-01-15T11:00:00.000Z"},"message.sent":{session_id:`call_${i}`,channel_type:"whatsapp",to:"+15551230001",message_type:"text",text:"How can we help?",media_url:null,node_id:"node_message",sent_at:"2026-01-15T12:00:05.000Z"},"dialer.attempt.finished":{campaign_id:`dcamp_${i}`,campaign_name:"January outreach",contact_id:`dct_${i}`,phone_number:"+15551230001",attempt_number:1,status:"answered",hangup_cause:"NORMAL_CLEARING",sip_code:"200",call_uuid:"fs-channel-example",started_at:"2026-01-15T12:00:00.000Z",answered_at:"2026-01-15T12:00:03.000Z",ended_at:"2026-01-15T12:01:00.000Z",duration_s:60,custom_fields:{segment:"example"}},"alert.fired":{alert_type:"service_offline",severity:"critical",title:"Example service offline",body:"The example service is unavailable.",metric_value:1,threshold:1},"alert.resolved":{alert_type:"service_offline",title:"Example service recovered",body:"The example service is available again."},"service.down":{component:"example-service",checked_at:"2026-01-15T12:00:00.000Z"},"service.up":{component:"example-service",downtime_seconds:null,recovered_at:"2026-01-15T12:05:00.000Z"},"webhook.test":{webhook_endpoint_id:`whep_${i}`,message:"This is a test webhook delivery."}};function F0($){let U=p$[$],K=t$[$],q=K.defaultConfig,Q=I4(K,q),W=typeof K.producedVariables==="function"?K.producedVariables(q):K.producedVariables,G=Kq($,"en");return{type:$,name:G?.name??$,description:G?.description??"",nameKey:K.nameKey,descriptionKey:K.descriptionKey,module:K.module,category:K.category,channel:K.channel,nature:K.nature,configJsonSchema:J.toJSONSchema(U.configSchema,{unrepresentable:"any"}),outputs:Q,producedVariables:W,defaultConfig:q}}var Nw=Object.keys(p$);function aW(){return Nw.map(($)=>F0($))}var Lw=["string","number","boolean","object","array"],VZ=J.strictObject({name:J.string(),type:J.enum(Lw),required:J.boolean(),nullable:J.boolean()}),MZ=J.strictObject({event:J.enum(i3),required_module:J.enum(["core","ai","queues","dialer","omnichannel","enterprise"]).nullable(),fields:J.array(VZ),example:J.record(J.string(),J.unknown())}),_w=J.array(MZ);var DZ="edge";var Iw=J.object({text:J.string().min(1).max(5000),voice:J.string().min(1),model:J.string().default(DZ)});var Fw=J.object({signal_id:J.string(),t:J.number().min(0),v:J.union([J.boolean(),J.string(),J.null(),J.number()]),c:J.number().min(0).max(1),node_id:J.string().nullable()});function sW($){let U=$.normalize("NFD").replaceAll(/[\u0300-\u036F]/g,"").toLowerCase().replaceAll(/[^a-z0-9]+/g,"_").replaceAll(/_+/g,"_").replaceAll(/^_|_$/g,"");if(!/^[a-z]/.test(U))return`signal_${U}`.slice(0,64)||"signal";return U.slice(0,64)}var o3=[{id:"asked_for_human",kind:"yes_no",speaker:"caller",live:!0,scope:null,alert:{when:{answer:"yes"},severity:"warning",bell:!0},texts:{"pt-BR":{name:"Pediu atendente humano",question:"O cliente pediu para falar com um atendente humano?"},en:{name:"Asked for a human agent",question:"Did the customer ask to speak with a human agent?"}}},{id:"wants_to_cancel",kind:"yes_no",speaker:"caller",live:!0,scope:null,alert:{when:{answer:"yes"},severity:"warning",bell:!1},texts:{"pt-BR":{name:"Quer cancelar",question:"O cliente disse que quer cancelar o serviço ou trocar de operadora?"},en:{name:"Wants to cancel",question:"Did the customer say they want to cancel the service or switch providers?"}}},{id:"caller_irritation",kind:"scale",speaker:"caller",live:!0,scope:null,alert:{when:{level_at_least:3},severity:"critical",bell:!0},texts:{"pt-BR":{name:"Irritação do cliente",question:"Quão irritado está o cliente?",levels:["calmo","impaciente","irritado","furioso"]},en:{name:"Caller irritation",question:"How irritated is the caller?",levels:["calm","impatient","irritated","furious"]}}},{id:"contact_reason",kind:"choice",speaker:"caller",live:!0,scope:null,alert:null,option_keys:["second_copy","bill_dispute","tech_support","cancellation"],texts:{"pt-BR":{name:"Motivo do contato",question:"Qual é o motivo principal da ligação?",options:[{label:"segunda via",description:"Cliente quer boleto ou fatura"},{label:"contestação de conta",description:"Cliente discorda de um valor cobrado"},{label:"suporte técnico",description:"Internet, sinal ou equipamento com problema"},{label:"cancelamento",description:"Cliente quer encerrar o serviço"}]},en:{name:"Contact reason",question:"What is the main reason for the call?",options:[{label:"second copy",description:"Customer wants a bill or invoice copy"},{label:"bill dispute",description:"Customer disagrees with a charged amount"},{label:"tech support",description:"Internet, signal or equipment issue"},{label:"cancellation",description:"Customer wants to end the service"}]}}},{id:"formal_complaint",kind:"yes_no",speaker:"caller",live:!0,scope:null,alert:{when:{answer:"yes"},severity:"critical",bell:!0},texts:{"pt-BR":{name:"Ameaça de reclamação formal",question:"O cliente ameaçou reclamar no Procon, no Reclame Aqui ou na Justiça?"},en:{name:"Formal complaint threat",question:"Did the customer threaten to complain to Procon, Reclame Aqui or the courts?"}}},{id:"emergency_symptom",kind:"yes_no",speaker:"caller",live:!0,scope:null,alert:{when:{answer:"yes"},severity:"critical",bell:!0},texts:{"pt-BR":{name:"Sintoma de emergência",question:"O paciente descreveu sintoma de emergência, como dor no peito, falta de ar ou desmaio?"},en:{name:"Emergency symptom",question:"Did the patient describe an emergency symptom, such as chest pain, shortness of breath or fainting?"}}},{id:"fraud_risk",kind:"scale",speaker:"caller",live:!0,scope:null,alert:{when:{level_at_least:2},severity:"critical",bell:!1},texts:{"pt-BR":{name:"Risco de golpe",question:"Qual é o risco de a ligação ser uma tentativa de golpe?",levels:["baixo","médio","alto"]},en:{name:"Fraud risk",question:"How likely is this call to be a scam attempt?",levels:["low","medium","high"]}}},{id:"protocol_given",kind:"yes_no",speaker:"agent",live:!1,scope:{node_types:["transfer"]},alert:{when:{answer:"no"},severity:"info",bell:!1},texts:{"pt-BR":{name:"Protocolo informado",question:"O atendente informou o número de protocolo ao cliente?"},en:{name:"Protocol number given",question:"Did the agent give the customer the protocol number?"}}},{id:"collection_outcome",kind:"choice",speaker:"both",live:!1,scope:null,alert:{when:{options:["disputed"]},severity:"info",bell:!1},option_keys:["promised_to_pay","refused","disputed","call_back_later"],texts:{"pt-BR":{name:"Desfecho da cobrança",question:"Qual foi o desfecho da cobrança?",options:[{label:"prometeu pagar"},{label:"recusou"},{label:"contestou a dívida",description:"Cliente diz que não deve ou que o valor está errado"},{label:"pediu para ligar depois"}]},en:{name:"Collection outcome",question:"What was the outcome of the collection?",options:[{label:"promised to pay"},{label:"refused"},{label:"disputed the debt",description:"Customer says they do not owe or the amount is wrong"},{label:"asked to call back later"}]}}},{id:"off_script_offer",kind:"yes_no",speaker:"agent",live:!0,scope:{node_types:["aiAgent"]},alert:{when:{answer:"yes"},severity:"warning",bell:!0},texts:{"pt-BR":{name:"Oferta fora do script",question:"O agente ofereceu desconto ou condição fora do que foi combinado?"},en:{name:"Off-script offer",question:"Did the agent offer a discount or terms outside what was agreed?"}}}];function eW($,U){let K=$.texts[U];return P6.parse({slug:sW(K.name),name:K.name,question:K.question,kind:$.kind,...$.kind==="choice"?{options:(K.options??[]).map((q,Q)=>({key:$.option_keys?.[Q]??`option_${Q}`,label:q.label,...q.description!==void 0?{description:q.description}:{}}))}:{},...$.kind==="scale"?{levels:K.levels??[]}:{},speaker:$.speaker,scope:$.scope,live:$.live,alert:$.alert})}var PZ=["not_applicable","disabled","waiting","pending","processing","completed","failed","skipped","purged","expired"];var Xr=new Set(PZ);var $G=J.record(J.string(),J.string());var n3=J.object({id:J.string(),sequence:J.number().int().nonnegative(),nodeId:J.string(),nodeType:J.string(),nodeLabel:J.string(),status:J.enum(["running","completed","warning","error"]),enteredAt:J.string(),exitedAt:J.string().nullable(),durationMs:J.number().int().nonnegative().nullable(),handleUsed:J.string().nullable(),digit:J.string().nullable(),variablesBefore:$G,variablesAfter:$G.nullable(),resolvedConfig:J.record(J.string(),J.unknown()),resultData:J.record(J.string(),J.unknown()).nullable()}).superRefine(($,U)=>{let K=[$.exitedAt,$.durationMs,$.handleUsed,$.variablesAfter];if($.status==="running"?K.some((Q)=>Q!==null):K.includes(null))U.addIssue({code:"custom",path:["status"],message:"Running steps must have empty exit fields; terminal steps must have complete exit fields"})}),ww=J.object({orgId:J.string(),status:J.enum(["active","waiting_input","ended"]),currentNodeId:J.string(),variables:$G,steps:J.array(n3),truncated:J.boolean()});function F4($){return{audio:{tts:{text:$}}}}function vw($){return{type:"text",text:$}}function F($){return{...F4($),content:vw($)}}function n($,U,K={},q){return{options:U,maxAttempts:3,audio:F4($).audio,text:q??$,...K}}function D$($,U={}){return{audio:F4($).audio,text:$,...U}}function d($,U,K,q){return[Z(`${$}a`,U,"answered",K),Z(`${$}b`,U,"busy",q),Z(`${$}n`,U,"noAnswer",q),Z(`${$}e`,U,"error",q)]}var kw={x:0,y:0};function V($,U,K,q,Q){return{id:$,type:U,label:K,varName:q,position:kw,config:Q}}function Z($,U,K,q){return{id:$,source:U,sourceHandle:K,target:q,targetHandle:"in"}}var NZ={id:"atendente-virtual-ia",category:"ai",requiredModules:["ai"],tags:["ia","agente","ai","virtual","conversacional"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Boas-vindas","boas_vindas",F("Olá! Sou o assistente virtual. Posso ajudar com diversas questões.")),V("ai1","aiAgent","Agente IA","agente_ia",{agent_id:"",agent_name:"",additional_instructions:"",variables:{},initial_message:"Olá, como posso ajudar?",max_duration_minutes:10}),V("m1","menu","Satisfação","satisfacao",n("Resolvemos sua dúvida? Se sim, tecle 1. Para falar com um atendente, tecle 2.",[{id:"satisfeito",label:"Satisfeito",digit:"1"},{id:"atendente",label:"Falar com atendente",digit:"2"}],{},"Escolha uma opção:")),V("t2","tell","Agradecimento","agradecimento",F("Obrigado pelo contato. Tenha um bom dia!")),V("t3","tell","Transferindo","transferindo",F("Vou transferir para um atendente humano.")),V("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["1000"],timeout:45}),V("t4","tell","Erro IA","erro_ia",F("Houve um problema com o assistente. Vou transferir para um atendente.")),V("t5","tell","Transferência Falhou","transferencia_falhou",F("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[Z("e1v","s1","voice","t1"),Z("e1c","s1","chat","t1"),Z("e2","t1","next","ai1"),Z("e3","ai1","completed","m1"),Z("e4","ai1","error","t4"),Z("e5","m1","option:satisfeito","t2"),Z("e6","m1","option:atendente","t3"),Z("e7","m1","noMatch","t3"),Z("e8","m1","error","t3"),Z("e9","t2","next","h1"),Z("e10","t3","next","x1"),Z("e11","t4","next","x1"),...d("ex1","x1","h1","t5"),Z("e12","t5","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var LZ={id:"atendimento-agente-ia",category:"ai",requiredModules:["ai"],tags:["ia","ai","agente","atendimento","intencao","classificacao","transferencia"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Boas-vindas","boas_vindas",F("Olá! Você ligou para a nossa central. Em poucas palavras, me diga como posso ajudar.")),V("c1","capture","Captura","captura",D$("Fale agora o motivo do seu contato.",{voiceMethod:"speech",maxAttempts:3,listen:{initial_timeout_s:10,timeout_s:3,max_duration_s:15,beep:!0},processing_audio:F4("Um momento enquanto analiso o seu pedido.").audio})),V("ra1","routeAi","Classificador","classificador",{input:"{{captura.text}}",intents:[{label:"suporte",description:"Problemas técnicos, falhas, dúvidas de uso do produto ou serviço"},{label:"financeiro",description:"Faturas, cobranças, pagamentos, reembolsos e negociações"}],instructions:"Classifique o motivo do contato do cliente. Duplique um ramo para cada novo assunto atendido."}),V("ai1","aiAgent","Agente","agente",{agent_id:"",agent_name:"",additional_instructions:"O usuário está entrando com o seguinte pedido: {{captura.text}}",variables:{},initial_message:"",max_duration_minutes:10}),V("sw1","switchCase","Decidir","decidir",{expression:"{{agente.output.resultado}}",cases:[{pattern:"^resolvido$"}]}),V("t2","tell","Despedida","despedida",F("Obrigado pelo contato. Tenha um ótimo dia!")),V("t3","tell","Não Entendi","nao_entendeu",F("Não consegui entender o motivo do contato. Vou transferir para um atendente.")),V("t4","tell","Erro Técnico","erro_tecnico",F("Tivemos um problema no atendimento automático. Vou transferir para um atendente.")),V("x1","transfer","Transferência Humana","transfer_humano",{method:"bridge",destinations:["1000"]}),V("t5","tell","Transferência Falhou","transfer_falhou",F("Não conseguimos completar a transferência. Por favor, ligue novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[Z("e1v","s1","voice","t1"),Z("e1c","s1","chat","t1"),Z("e2","t1","next","c1"),Z("e3","c1","collected","ra1"),Z("e4","c1","noInput","t3"),Z("e5","c1","error","t4"),Z("e6","ra1","intent:suporte","ai1"),Z("e7","ra1","intent:financeiro","x1"),Z("e8","ra1","notApplicable","t3"),Z("e9","ra1","error","t4"),Z("e10","ai1","completed","sw1"),Z("e11","ai1","error","t4"),Z("e12","sw1","match:^resolvido$","t2"),Z("e13","sw1","fallback","x1"),Z("e14","sw1","error","t4"),Z("e15","t3","next","x1"),Z("e16","t4","next","x1"),Z("e17","t2","next","h1"),Z("e18","x1","answered","t2"),Z("e19","x1","busy","t5"),Z("e20","x1","noAnswer","t5"),Z("e21","x1","error","t5"),Z("e22","t5","next","h1")],viewport:{x:0,y:0,zoom:0.75}}};var _Z={id:"atendimento-setores",category:"core",requiredModules:[],tags:["menu","transfer","setores","departamentos","ura"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Boas-vindas","boas_vindas",F("Bem-vindo. Escolha entre financeiro, suporte, vendas ou ouvidoria.")),V("m1","menu","Menu Principal","menu_principal",n("Para financeiro, tecle 1. Para suporte, tecle 2. Para vendas, tecle 3. Para ouvidoria, tecle 4.",[{id:"financeiro",label:"Financeiro",digit:"1"},{id:"suporte",label:"Suporte Técnico",digit:"2"},{id:"vendas",label:"Vendas",digit:"3"},{id:"ouvidoria",label:"Ouvidoria",digit:"4"}],{},"Escolha o setor desejado:")),V("t2","tell","Transferindo Financeiro","transferindo_financeiro",F("Aguarde, transferindo para o financeiro.")),V("t3","tell","Transferindo Suporte","transferindo_suporte",F("Aguarde, transferindo para o suporte técnico.")),V("t4","tell","Transferindo Vendas","transferindo_vendas",F("Aguarde, transferindo para vendas.")),V("t5","tell","Transferindo Ouvidoria","transferindo_ouvidoria",F("Aguarde, transferindo para a ouvidoria.")),V("x1","transfer","Financeiro","financeiro",{method:"bridge",destinations:["1001"],timeout:30}),V("x2","transfer","Suporte","suporte",{method:"bridge",destinations:["1002"],timeout:30}),V("x3","transfer","Vendas","vendas",{method:"bridge",destinations:["1003"],timeout:30}),V("x4","transfer","Ouvidoria","ouvidoria",{method:"bridge",destinations:["1004"],timeout:30}),V("t6","tell","Opção Inválida","opcao_invalida",F("Não entendi sua escolha. Por favor, ligue novamente.")),V("t7","tell","Transferência Falhou","transferencia_falhou",F("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[Z("e1v","s1","voice","t1"),Z("e1c","s1","chat","t1"),Z("e2","t1","next","m1"),Z("e3","m1","option:financeiro","t2"),Z("e4","m1","option:suporte","t3"),Z("e5","m1","option:vendas","t4"),Z("e6","m1","option:ouvidoria","t5"),Z("e7","t2","next","x1"),Z("e8","t3","next","x2"),Z("e9","t4","next","x3"),Z("e10","t5","next","x4"),Z("e11","m1","noMatch","t6"),Z("e12","m1","error","t6"),Z("e13","t6","next","h1"),...d("ex1","x1","h1","t7"),...d("ex2","x2","h1","t7"),...d("ex3","x3","h1","t7"),...d("ex4","x4","h1","t7"),Z("e14","t7","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var IZ={id:"banco-sac",category:"industry",requiredModules:[],tags:["banco","financeiro","sac","saldo","extrato","cartao"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("c1","capture","CPF do Cliente","cpf_cliente",D$("Bem-vindo ao banco. Digite os onze números do seu CPF.",{voiceMethod:"dtmf",minDigits:11,maxDigits:11,terminators:"#",text:"Bem-vindo ao banco. Informe seu CPF (somente números):",validation:String.raw`^\d{11}$`,invalidMessage:"CPF inválido. Informe os 11 dígitos, somente números:"})),V("m1","menu","Menu Serviços","menu_servicos",n("Para consultar saldo, tecle 1. Para extrato, tecle 2. Para cartões, tecle 3. Para falar com um atendente, tecle 4.",[{id:"saldo",label:"Consultar saldo",digit:"1"},{id:"extrato",label:"Extrato",digit:"2"},{id:"cartao",label:"Cartões",digit:"3"},{id:"atendente",label:"Falar com atendente",digit:"4"}],{},"Escolha o serviço desejado:")),V("http1","httpRequest","Consultar Saldo","consultar_saldo",{method:"GET",url:"https://api.example.com/accounts/{{cpf_cliente.text}}/balance",headers:{},body:"",timeout:10}),V("t1","tell","Saldo Informado","saldo_informado",F("O seu saldo é: {{consultar_saldo.response}}. Obrigado pelo contato.")),V("t2","tell","Extrato","extrato",F("Seu extrato será enviado por SMS em instantes.")),V("t3","tell","Cartões","cartoes",F("Para informações sobre cartões, vou transferir para um especialista.")),V("t4","tell","Transferindo Atendente","transferindo_atendente",F("Aguarde, vou transferir para um atendente.")),V("t5","tell","Erro Consulta","erro_consulta",F("Não foi possível realizar a consulta agora. Vou transferir para um atendente.")),V("t6","tell","Sem Identificação","sem_identificacao",F("Não consegui identificar o seu CPF. Vou transferir para um atendente.")),V("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["5001"],timeout:45}),V("t7","tell","Transferência Falhou","transferencia_falhou",F("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[Z("e1v","s1","voice","c1"),Z("e1c","s1","chat","c1"),Z("e2","c1","collected","m1"),Z("e3","c1","noInput","t6"),Z("e4","c1","error","t6"),Z("e5","m1","option:saldo","http1"),Z("e6","m1","option:extrato","t2"),Z("e7","m1","option:cartao","t3"),Z("e8","m1","option:atendente","t4"),Z("e9","m1","noMatch","t6"),Z("e10","m1","error","t6"),Z("e11","http1","next","t1"),Z("e12","http1","error","t5"),Z("e13","t1","next","h1"),Z("e14","t2","next","h1"),Z("e15","t3","next","x1"),Z("e16","t4","next","x1"),Z("e17","t5","next","x1"),Z("e18","t6","next","x1"),...d("ex1","x1","h1","t7"),Z("e19","t7","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var FZ={id:"clinica-agendamento",category:"industry",requiredModules:[],tags:["clinica","saude","agendamento","consulta","medico"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Boas-vindas","boas_vindas",F("Bem-vindo à central de agendamentos.")),V("m1","menu","Especialidade","especialidade",n("Para Clínico Geral, tecle 1. Para Cardiologia, tecle 2. Para Ortopedia, tecle 3.",[{id:"clinico",label:"Clínico Geral",digit:"1"},{id:"cardio",label:"Cardiologia",digit:"2"},{id:"orto",label:"Ortopedia",digit:"3"}],{},"Escolha a especialidade desejada:")),V("c1","capture","CPF do Paciente","cpf_paciente",D$("Digite os onze números do CPF do paciente.",{voiceMethod:"dtmf",minDigits:11,maxDigits:11,terminators:"#",text:"Informe o CPF do paciente (somente números):",validation:String.raw`^\d{11}$`,invalidMessage:"CPF inválido. Informe os 11 dígitos, somente números:"})),V("http1","httpRequest","Consultar Agenda","consultar_agenda",{method:"POST",url:"https://api.example.com/appointments/check",headers:{"Content-Type":"application/json"},body:'{"cpf": "{{cpf_paciente.text}}", "specialty": "{{especialidade.selectedId}}"}',timeout:10}),V("t2","tell","Resultado da Consulta","resultado_consulta",F("{{consultar_agenda.response}}")),V("t3","tell","Erro na Consulta","erro_consulta",F("Não conseguimos consultar a agenda no momento. Por favor, tente novamente mais tarde.")),V("t4","tell","Sem Dados","sem_dados",F("Não consegui capturar as informações necessárias. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[Z("e1v","s1","voice","t1"),Z("e1c","s1","chat","t1"),Z("e2","t1","next","m1"),Z("e3","m1","option:clinico","c1"),Z("e4","m1","option:cardio","c1"),Z("e5","m1","option:orto","c1"),Z("e6","m1","noMatch","t4"),Z("e7","m1","error","t4"),Z("e8","c1","collected","http1"),Z("e9","c1","noInput","t4"),Z("e10","c1","error","t4"),Z("e11","http1","next","t2"),Z("e12","http1","error","t3"),Z("e13","t2","next","h1"),Z("e14","t3","next","h1"),Z("e15","t4","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var xZ={id:"cobranca-automatizada",category:"capture",requiredModules:[],tags:["cobranca","debito","pagamento","boleto","pix","negociacao"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Intro Cobrança","intro_cobranca",F("Olá, identificamos um débito em aberto na sua conta.")),V("m1","menu","Opções de Pagamento","opcoes_pagamento",n("Para negociar a dívida, tecle 1. Para receber o boleto atualizado, tecle 2. Para pagar via Pix, tecle 3.",[{id:"negociar",label:"Negociar dívida",digit:"1"},{id:"boleto",label:"Receber boleto",digit:"2"},{id:"pix",label:"Pagar via Pix",digit:"3"}],{},"Escolha uma opção de pagamento:")),V("c1","capture","Identificação","identificacao",D$("Informe seu CPF ou número de contrato e finalize com a tecla jogo da velha.",{voiceMethod:"dtmf",minDigits:4,maxDigits:14,terminators:"#",text:"Informe seu CPF ou número de contrato (somente números):",validation:String.raw`^\d{4,14}$`,invalidMessage:"Identificação inválida. Informe apenas números, entre 4 e 14 dígitos:"})),V("t2","tell","Transferindo Negociação","transferindo_negociacao",F("Recebi sua identificação. Vou transferir para um especialista em negociação.")),V("x1","transfer","Negociação","negociacao",{method:"bridge",destinations:["2001"],timeout:45}),V("t3","tell","Boleto Enviado","boleto_enviado",F("O boleto atualizado será enviado para seu contato cadastrado em até 5 minutos.")),V("t4","tell","Chave Pix","chave_pix",F("Nossa chave Pix é o CNPJ da empresa. Após o pagamento, a baixa será automática em até 2 horas.")),V("t5","tell","Opção Inválida","opcao_invalida",F("Não entendi sua escolha. Por favor, ligue novamente.")),V("t6","tell","Sem Identificação","sem_identificacao",F("Não recebi sua identificação. Por favor, ligue novamente com os dados em mãos.")),V("t7","tell","Transferência Falhou","transferencia_falhou",F("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[Z("e1v","s1","voice","t1"),Z("e1c","s1","chat","t1"),Z("e2","t1","next","m1"),Z("e3","m1","option:negociar","c1"),Z("e4","m1","option:boleto","t3"),Z("e5","m1","option:pix","t4"),Z("e6","m1","noMatch","t5"),Z("e7","m1","error","t5"),Z("e8","c1","collected","t2"),Z("e9","c1","noInput","t6"),Z("e10","c1","error","t6"),Z("e11","t2","next","x1"),Z("e12","t3","next","h1"),Z("e13","t4","next","h1"),Z("e14","t5","next","h1"),Z("e15","t6","next","h1"),...d("ex1","x1","h1","t7"),Z("e16","t7","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var wZ={id:"coleta-dados-api",category:"capture",requiredModules:[],tags:["capture","api","http","dados","integracao"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Boas-vindas","boas_vindas",F("Olá. Vou consultar uma informação para você.")),V("c1","capture","Identificação","identificacao",D$("Informe seu número de identificação e finalize com a tecla jogo da velha.",{voiceMethod:"dtmf",minDigits:4,maxDigits:14,terminators:"#",text:"Informe seu número de identificação (somente números):",validation:String.raw`^\d{4,14}$`,invalidMessage:"Identificação inválida. Informe apenas números, entre 4 e 14 dígitos:"})),V("http1","httpRequest","Consultar API","consultar_api",{method:"GET",url:"https://api.example.com/lookup/{{identificacao.text}}",headers:{},body:"",timeout:10}),V("sw1","switchCase","Tipo de Falha","tipo_falha",{expression:"{{consultar_api.status_code}}",cases:[{pattern:"^404$"}]}),V("t2","tell","Resultado Encontrado","resultado_encontrado",F("Encontrei as informações solicitadas: {{consultar_api.response}}. Obrigado pelo contato.")),V("t3","tell","Não Encontrado","nao_encontrado",F("Não encontrei registros para essa identificação. Verifique o número e tente novamente.")),V("t4","tell","Erro de Consulta","erro_consulta",F("Houve um erro na consulta. Tente novamente mais tarde.")),V("t5","tell","Sem Identificação","sem_identificacao",F("Não consegui capturar sua identificação. Por favor, ligue novamente com o número em mãos.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[Z("e1v","s1","voice","t1"),Z("e1c","s1","chat","t1"),Z("e2","t1","next","c1"),Z("e3","c1","collected","http1"),Z("e4","c1","noInput","t5"),Z("e5","c1","error","t5"),Z("e6","http1","next","t2"),Z("e7","http1","error","sw1"),Z("e8","sw1","match:^404$","t3"),Z("e9","sw1","fallback","t4"),Z("e10","sw1","error","t4"),Z("e11","t2","next","h1"),Z("e12","t3","next","h1"),Z("e13","t4","next","h1"),Z("e14","t5","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var AZ={id:"faq-ia-escalacao",category:"ai",requiredModules:["ai"],tags:["faq","ia","escalacao","ai","agente"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Boas-vindas","boas_vindas",F("Olá! Sou o assistente virtual. Posso tirar dúvidas sobre nossos serviços.")),V("ai1","aiAgent","Agente FAQ","agente_faq",{agent_id:"",agent_name:"",additional_instructions:"Responda perguntas frequentes sobre os serviços da empresa. Se não souber a resposta, informe que vai transferir para um atendente.",variables:{},initial_message:"Olá! Qual sua dúvida?",max_duration_minutes:5}),V("m1","menu","Resolveu?","resolveu",n("Sua dúvida foi resolvida? Se sim, tecle 1. Para falar com um atendente, tecle 2.",[{id:"resolvido",label:"Sim, resolvido",digit:"1"},{id:"atendente",label:"Falar com atendente",digit:"2"}],{},"Escolha uma opção:")),V("t2","tell","Agradecimento","agradecimento",F("Ótimo! Se precisar de algo mais, é só entrar em contato.")),V("t3","tell","Transferindo","transferindo",F("Aguarde, vou transferir para um atendente.")),V("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["1000"],timeout:45}),V("t4","tell","Transferência Falhou","transferencia_falhou",F("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[Z("e1v","s1","voice","t1"),Z("e1c","s1","chat","t1"),Z("e2","t1","next","ai1"),Z("e3","ai1","completed","m1"),Z("e4","ai1","error","t3"),Z("e5","m1","option:resolvido","t2"),Z("e6","m1","option:atendente","t3"),Z("e7","m1","noMatch","t3"),Z("e8","m1","error","t3"),Z("e9","t2","next","h1"),Z("e10","t3","next","x1"),...d("ex1","x1","h1","t4"),Z("e11","t4","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var vZ={id:"faq-informacoes",category:"core",requiredModules:[],tags:["faq","informacoes","autoatendimento","info"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Boas-vindas","boas_vindas",F("Olá, sou o assistente virtual. Posso ajudar com suporte, financeiro, vendas ou horários de atendimento.")),V("m1","menu","Menu FAQ","menu_faq",n("Para suporte técnico, tecle 1. Para financeiro, tecle 2. Para vendas, tecle 3. Para horários de atendimento, tecle 4.",[{id:"suporte",label:"Suporte Técnico",digit:"1"},{id:"financeiro",label:"Financeiro",digit:"2"},{id:"vendas",label:"Vendas",digit:"3"},{id:"horarios",label:"Horários",digit:"4"}],{},"Escolha um assunto:")),V("t2","tell","Info Suporte","info_suporte",F("Nossa equipe de suporte está disponível 24 horas por dia. Você também pode abrir um chamado pelo nosso portal.")),V("t3","tell","Info Financeiro","info_financeiro",F("Para boletos, notas fiscais e negociações, acesse nosso portal financeiro ou fale com atendimento em horário comercial.")),V("t4","tell","Info Vendas","info_vendas",F("Conheça nossos planos e promoções no nosso site. Para falar com um consultor, ligue em horário comercial.")),V("t5","tell","Info Horários","info_horarios",F("Nosso atendimento funciona de segunda a sexta, das 8h às 20h. Aos sábados, das 8h às 14h.")),V("t6","tell","Opção Inválida","opcao_invalida",F("Não entendi sua escolha. Encerrando o atendimento. Até logo.")),V("h1","hangup","Fim","fim",{})],edges:[Z("e1v","s1","voice","t1"),Z("e1c","s1","chat","t1"),Z("e2","t1","next","m1"),Z("e3","m1","option:suporte","t2"),Z("e4","m1","option:financeiro","t3"),Z("e5","m1","option:vendas","t4"),Z("e6","m1","option:horarios","t5"),Z("e7","t2","next","m1"),Z("e8","t3","next","m1"),Z("e9","t4","next","m1"),Z("e10","t5","next","m1"),Z("e11","m1","noMatch","t6"),Z("e12","m1","error","t6"),Z("e13","t6","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var kZ={id:"horario-comercial",category:"core",requiredModules:[],tags:["horario","schedule","tempo","comercial","expediente"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("tr1","timeRouting","Horário Atendimento","horario_atendimento",{}),V("t1","tell","Boas-vindas","boas_vindas",F("Bem-vindo. Como posso ajudar?")),V("m1","menu","Menu Principal","menu_principal",n("Para suporte, tecle 1. Para vendas, tecle 2.",[{id:"suporte",label:"Suporte",digit:"1"},{id:"vendas",label:"Vendas",digit:"2"}],{},"Escolha uma opção:")),V("t2","tell","Transferindo Suporte","transferindo_suporte",F("Transferindo para o suporte.")),V("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),V("t3","tell","Transferindo Vendas","transferindo_vendas",F("Transferindo para vendas.")),V("x2","transfer","Vendas","vendas",{method:"bridge",destinations:["1002"],timeout:30}),V("t4","tell","Fora do Horário","fora_horario",F("Nosso horário de atendimento é de segunda a sexta, das 8h às 18h. Ligue novamente no próximo dia útil.")),V("t5","tell","Opção Não Reconhecida","opcao_nao_reconhecida",F("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),V("t6","tell","Transferência Falhou","transferencia_falhou",F("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[Z("e1v","s1","voice","tr1"),Z("e1c","s1","chat","tr1"),Z("e2","tr1","onHours","t1"),Z("e3","tr1","offHours","t4"),Z("e4","tr1","holiday","t4"),Z("e5","t1","next","m1"),Z("e6","m1","option:suporte","t2"),Z("e7","m1","option:vendas","t3"),Z("e8","t2","next","x1"),Z("e9","t3","next","x2"),Z("e10","m1","noMatch","t5"),Z("e11","m1","error","t5"),Z("e12","t5","next","x1"),...d("ex1","x1","h1","t6"),...d("ex2","x2","h1","t6"),Z("e13","t4","next","h1"),Z("e14","t6","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var zZ={id:"isp-suporte-tecnico",category:"industry",requiredModules:[],tags:["isp","provedor","internet","suporte","tecnico","telecom"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Boas-vindas","boas_vindas",F("Bem-vindo ao suporte técnico.")),V("m1","menu","Tipo de Serviço","tipo_servico",n("Para problemas de internet, tecle 1. Para problemas de telefonia, tecle 2.",[{id:"internet",label:"Internet",digit:"1"},{id:"telefonia",label:"Telefonia",digit:"2"}],{},"Escolha o tipo de serviço:")),V("c1","capture","Contrato Internet","contrato_internet",D$("Informe o número do seu contrato.",{voiceMethod:"dtmf",minDigits:3,maxDigits:10,terminators:"#",text:"Informe o número do seu contrato:",validation:String.raw`^\d{3,10}$`,invalidMessage:"O número do contrato deve ter de 3 a 10 dígitos. Tente novamente:"})),V("c2","capture","Contrato Telefonia","contrato_telefonia",D$("Informe o número do seu contrato.",{voiceMethod:"dtmf",minDigits:3,maxDigits:10,terminators:"#",text:"Informe o número do seu contrato:",validation:String.raw`^\d{3,10}$`,invalidMessage:"O número do contrato deve ter de 3 a 10 dígitos. Tente novamente:"})),V("http1","httpRequest","Status Internet","status_internet",{method:"GET",url:"https://api.example.com/contracts/{{contrato_internet.text}}/status?service=internet",headers:{},body:"",timeout:10}),V("http2","httpRequest","Status Telefonia","status_telefonia",{method:"GET",url:"https://api.example.com/contracts/{{contrato_telefonia.text}}/status?service=telefonia",headers:{},body:"",timeout:10}),V("t2","tell","Status Internet","status_internet_info",F("Sobre sua conexão de internet: {{status_internet.response}}")),V("t3","tell","Status Telefonia","status_telefonia_info",F("Sobre seu serviço de telefonia: {{status_telefonia.response}}")),V("sw1","switchCase","Falha Internet","falha_internet",{expression:"{{status_internet.status_code}}",cases:[{pattern:"^404$"}]}),V("sw2","switchCase","Falha Telefonia","falha_telefonia",{expression:"{{status_telefonia.status_code}}",cases:[{pattern:"^404$"}]}),V("t4","tell","Contrato Não Encontrado","contrato_nao_encontrado",F("Não encontrei esse contrato. Vou transferir para um atendente.")),V("t5","tell","Erro de Consulta","erro_consulta",F("Não foi possível consultar o status agora. Vou transferir para um atendente.")),V("t6","tell","Sem Contrato","sem_contrato",F("Não consegui capturar o número do contrato. Vou transferir para um atendente.")),V("t7","tell","Opção Não Reconhecida","opcao_nao_reconhecida",F("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),V("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["3001"],timeout:60}),V("t8","tell","Transferência Falhou","transferencia_falhou",F("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[Z("e1v","s1","voice","t1"),Z("e1c","s1","chat","t1"),Z("e2","t1","next","m1"),Z("e3","m1","option:internet","c1"),Z("e4","m1","option:telefonia","c2"),Z("e5","m1","noMatch","t7"),Z("e5e","m1","error","t7"),Z("e6","c1","collected","http1"),Z("e7","c1","noInput","t6"),Z("e7e","c1","error","t6"),Z("e8","http1","next","t2"),Z("e9","http1","error","sw1"),Z("e10","sw1","match:^404$","t4"),Z("e11","sw1","fallback","t5"),Z("e11e","sw1","error","t5"),Z("e12","t2","next","h1"),Z("e13","c2","collected","http2"),Z("e14","c2","noInput","t6"),Z("e14e","c2","error","t6"),Z("e15","http2","next","t3"),Z("e16","http2","error","sw2"),Z("e17","sw2","match:^404$","t4"),Z("e18","sw2","fallback","t5"),Z("e18e","sw2","error","t5"),Z("e19","t3","next","h1"),Z("e20","t4","next","x1"),Z("e21","t5","next","x1"),Z("e22","t6","next","x1"),Z("e23","t7","next","x1"),...d("ex1","x1","h1","t8"),Z("e24","t8","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var RZ={id:"mensagem-simples",category:"core",requiredModules:[],tags:["mensagem","simples","aviso","anuncio","basico"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Mensagem","mensagem",F("Obrigado por ligar. No momento não estamos disponíveis. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[Z("e1v","s1","voice","t1"),Z("e1c","s1","chat","t1"),Z("e2","t1","next","h1")],viewport:{x:0,y:0,zoom:1}}};var bZ={id:"menu-multinivel",category:"advanced",requiredModules:[],tags:["menu","multinivel","departamento","hierarquia","complexo"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Boas-vindas","boas_vindas",F("Bem-vindo. Escolha o setor desejado.")),V("m1","menu","Menu Principal","menu_principal",n("Para atendimento, tecle 1. Para comercial, tecle 2. Para administrativo, tecle 3.",[{id:"atendimento",label:"Atendimento",digit:"1"},{id:"comercial",label:"Comercial",digit:"2"},{id:"administrativo",label:"Administrativo",digit:"3"}],{},"Escolha o setor desejado:")),V("m2","menu","Atendimento","atendimento",n("Para suporte técnico, tecle 1. Para financeiro, tecle 2.",[{id:"suporte",label:"Suporte Técnico",digit:"1"},{id:"financeiro",label:"Financeiro",digit:"2"}],{},"Escolha uma opção:")),V("m3","menu","Comercial","comercial",n("Para vendas, tecle 1. Para parcerias, tecle 2.",[{id:"vendas",label:"Vendas",digit:"1"},{id:"parcerias",label:"Parcerias",digit:"2"}],{},"Escolha uma opção:")),V("m4","menu","Administrativo","administrativo",n("Para RH, tecle 1. Para jurídico, tecle 2.",[{id:"rh",label:"RH",digit:"1"},{id:"juridico",label:"Jurídico",digit:"2"}],{},"Escolha uma opção:")),V("t2","tell","Transferindo Suporte","transferindo_suporte",F("Transferindo para suporte técnico.")),V("t3","tell","Transferindo Financeiro","transferindo_financeiro",F("Transferindo para financeiro.")),V("t4","tell","Transferindo Vendas","transferindo_vendas",F("Transferindo para vendas.")),V("t5","tell","Transferindo Parcerias","transferindo_parcerias",F("Transferindo para parcerias.")),V("t6","tell","Transferindo RH","transferindo_rh",F("Transferindo para RH.")),V("t7","tell","Transferindo Jurídico","transferindo_juridico",F("Transferindo para jurídico.")),V("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),V("x2","transfer","Financeiro","financeiro",{method:"bridge",destinations:["1002"],timeout:45}),V("x3","transfer","Vendas","vendas",{method:"bridge",destinations:["2001"],timeout:30}),V("x4","transfer","Parcerias","parcerias",{method:"bridge",destinations:["2002"],timeout:30}),V("x5","transfer","RH","rh",{method:"bridge",destinations:["3001"],timeout:30}),V("x6","transfer","Jurídico","juridico",{method:"bridge",destinations:["3002"],timeout:30}),V("t8","tell","Opção Não Reconhecida","opcao_nao_reconhecida",F("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),V("t9","tell","Transferência Falhou","transferencia_falhou",F("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[Z("e1v","s1","voice","t1"),Z("e1c","s1","chat","t1"),Z("e2","t1","next","m1"),Z("e3","m1","option:atendimento","m2"),Z("e4","m1","option:comercial","m3"),Z("e5","m1","option:administrativo","m4"),Z("e6","m1","noMatch","t8"),Z("e6e","m1","error","t8"),Z("e7","m2","option:suporte","t2"),Z("e8","m2","option:financeiro","t3"),Z("e9","m2","noMatch","t8"),Z("e9e","m2","error","t8"),Z("e10","m3","option:vendas","t4"),Z("e11","m3","option:parcerias","t5"),Z("e12","m3","noMatch","t8"),Z("e12e","m3","error","t8"),Z("e13","m4","option:rh","t6"),Z("e14","m4","option:juridico","t7"),Z("e15","m4","noMatch","t8"),Z("e15e","m4","error","t8"),Z("e16","t2","next","x1"),Z("e17","t3","next","x2"),Z("e18","t4","next","x3"),Z("e19","t5","next","x4"),Z("e20","t6","next","x5"),Z("e21","t7","next","x6"),Z("e28","t8","next","x1"),...d("ex1","x1","h1","t9"),...d("ex2","x2","h1","t9"),...d("ex3","x3","h1","t9"),...d("ex4","x4","h1","t9"),...d("ex5","x5","h1","t9"),...d("ex6","x6","h1","t9"),Z("e29","t9","next","h1")],viewport:{x:0,y:0,zoom:0.7}}};var OZ={id:"notificacao-atendimento",category:"core",requiredModules:[],tags:["notificacao","aviso","atendimento","callback"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Notificação","notificacao",F("Olá, temos uma informação importante sobre sua conta.")),V("m1","menu","Precisa de Ajuda?","precisa_ajuda",n("Tecle 1 para falar com um atendente, ou 2 para encerrar.",[{id:"sim",label:"Sim, falar com atendente",digit:"1"},{id:"nao",label:"Não, obrigado",digit:"2"}],{},"Deseja falar com um atendente?")),V("t2","tell","Transferindo","transferindo",F("Aguarde, vou transferir para um atendente.")),V("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["1000"],timeout:45}),V("t3","tell","Agradecimento","agradecimento",F("Obrigado pelo seu tempo. Tenha um bom dia!")),V("t4","tell","Transferência Falhou","transferencia_falhou",F("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[Z("e1v","s1","voice","t1"),Z("e1c","s1","chat","t1"),Z("e2","t1","next","m1"),Z("e3","m1","option:sim","t2"),Z("e4","m1","option:nao","t3"),Z("e5","m1","noMatch","t3"),Z("e6","m1","error","t3"),Z("e7","t2","next","x1"),...d("ex1","x1","h1","t4"),Z("e8","t3","next","h1"),Z("e9","t4","next","h1")],viewport:{x:0,y:0,zoom:0.9}}};var TZ={id:"pesquisa-nps",category:"advanced",requiredModules:["ai"],tags:["nps","pesquisa","promotor","detrator","feedback","avaliacao"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Intro NPS","intro_nps",F("Gostaríamos de saber sua opinião sobre nosso atendimento.")),V("c1","capture","Nota NPS","nota_nps",D$("De 0 a 10, qual a probabilidade de recomendar nossos serviços? Tecle a nota.",{voiceMethod:"dtmf",minDigits:1,maxDigits:2,terminators:"#",text:"De 0 a 10, qual a probabilidade de recomendar nossos serviços?",validation:"^(10|[0-9])$",invalidMessage:"Informe uma nota de 0 a 10:"})),V("sw1","switchCase","Classificar NPS","classificar_nps",{expression:"{{nota_nps.text}}",cases:[{pattern:"^9$"},{pattern:"^10$"},{pattern:"^7$"},{pattern:"^8$"}]}),V("t2","tell","Promotor","promotor",F("Que ótimo! Ficamos muito felizes com sua avaliação.")),V("t3","tell","Neutro","neutro",F("Obrigado pela avaliação. Vamos trabalhar para melhorar.")),V("t4","tell","Detrator","detrator",F("Lamentamos que sua experiência não tenha sido satisfatória.")),V("c2","capture","Feedback","feedback",D$("Pode nos dizer o que podemos melhorar? Fale após o sinal.",{voiceMethod:"speech",text:"Pode nos dizer o que podemos melhorar?"})),V("http1","httpRequest","Salvar Pesquisa","salvar_pesquisa",{method:"POST",url:"https://api.example.com/nps",headers:{"Content-Type":"application/json"},body:'{"score": "{{nota_nps.text}}", "feedback": "{{feedback.text}}"}',timeout:10}),V("t5","tell","Agradecimento","agradecimento",F("Obrigado pelo seu feedback. Ele é muito importante para nós.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[Z("e1v","s1","voice","t1"),Z("e1c","s1","chat","t1"),Z("e2","t1","next","c1"),Z("e3","c1","collected","sw1"),Z("e4","c1","noInput","t5"),Z("e4e","c1","error","t5"),Z("e5","sw1","match:^9$","t2"),Z("e6","sw1","match:^10$","t2"),Z("e7","sw1","match:^7$","t3"),Z("e8","sw1","match:^8$","t3"),Z("e9","sw1","fallback","t4"),Z("e9e","sw1","error","t4"),Z("e10","t2","next","c2"),Z("e11","t3","next","c2"),Z("e12","t4","next","c2"),Z("e13","c2","collected","http1"),Z("e14","c2","noInput","http1"),Z("e14e","c2","error","http1"),Z("e15","http1","next","t5"),Z("e16","http1","error","t5"),Z("e17","t5","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var SZ={id:"pesquisa-satisfacao",category:"core",requiredModules:[],tags:["pesquisa","satisfacao","csat","avaliacao","nota"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Intro Pesquisa","intro_pesquisa",F("Gostaríamos de avaliar o atendimento que você recebeu.")),V("m1","menu","Nota de Satisfação","nota_satisfacao",n("Como você avalia o atendimento? Tecle 1 para péssimo, 2 para ruim, 3 para regular, 4 para bom, ou 5 para excelente.",[{id:"nota_1",label:"1 - Péssimo",digit:"1"},{id:"nota_2",label:"2 - Ruim",digit:"2"},{id:"nota_3",label:"3 - Regular",digit:"3"},{id:"nota_4",label:"4 - Bom",digit:"4"},{id:"nota_5",label:"5 - Excelente",digit:"5"}],{maxAttempts:2},"Como você avalia o atendimento que recebeu?")),V("t2","tell","Agradecimento","agradecimento",F("Você avaliou nosso atendimento como: {{nota_satisfacao.selectedLabel}}. Obrigado, sua opinião nos ajuda a melhorar.")),V("t3","tell","Sem Resposta","sem_resposta",F("Não conseguimos registrar sua avaliação. Agradecemos o contato.")),V("h1","hangup","Desligamento","desligamento",{}),V("h2","hangup","Desligamento Timeout","desligamento_timeout",{})],edges:[Z("e1v","s1","voice","t1"),Z("e1c","s1","chat","t1"),Z("e2","t1","next","m1"),Z("e3","m1","option:nota_1","t2"),Z("e4","m1","option:nota_2","t2"),Z("e5","m1","option:nota_3","t2"),Z("e6","m1","option:nota_4","t2"),Z("e7","m1","option:nota_5","t2"),Z("e8","t2","next","h1"),Z("e9","m1","noMatch","t3"),Z("e10","m1","error","t3"),Z("e11","t3","next","h2")],viewport:{x:0,y:0,zoom:0.9}}};var CZ={id:"roteamento-canal",category:"omnichannel",requiredModules:[],tags:["canal","omnichannel","voz","chat","roteamento"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("cr1","channelRouter","Roteador de Canal","roteador_canal",{}),V("t1","tell","Boas-vindas Voz","boas_vindas_voz",F("Bem-vindo ao nosso atendimento por telefone.")),V("m1","menu","Menu Voz","menu_voz",n("Para suporte, tecle 1. Para vendas, tecle 2.",[{id:"suporte",label:"Suporte",digit:"1"},{id:"vendas",label:"Vendas",digit:"2"}])),V("t2","tell","Boas-vindas Chat","boas_vindas_chat",F("Olá! Bem-vindo ao nosso atendimento por chat.")),V("m2","menu","Menu Chat","menu_chat",n("Para suporte, tecle 1. Para vendas, tecle 2.",[{id:"suporte",label:"Suporte",digit:"1"},{id:"vendas",label:"Vendas",digit:"2"}],{},"Escolha uma opção:")),V("t3","tell","Transferindo Suporte","transferindo_suporte",F("Transferindo para o suporte.")),V("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),V("t4","tell","Transferindo Vendas","transferindo_vendas",F("Transferindo para vendas.")),V("x2","transfer","Vendas","vendas",{method:"bridge",destinations:["1002"],timeout:30}),V("t5","tell","Opção Não Reconhecida","opcao_nao_reconhecida",F("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),V("t6","tell","Transferência Falhou","transferencia_falhou",F("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[Z("e1v","s1","voice","cr1"),Z("e1c","s1","chat","cr1"),Z("e2","cr1","voice","t1"),Z("e3","cr1","chat","t2"),Z("e4","t1","next","m1"),Z("e5","t2","next","m2"),Z("e6","m1","option:suporte","t3"),Z("e7","m1","option:vendas","t4"),Z("e8","m2","option:suporte","t3"),Z("e9","m2","option:vendas","t4"),Z("e10","t3","next","x1"),Z("e11","t4","next","x2"),...d("ex1","x1","h1","t6"),...d("ex2","x2","h1","t6"),Z("e12","m1","noMatch","t5"),Z("e13","m1","error","t5"),Z("e14","m2","noMatch","t5"),Z("e15","m2","error","t5"),Z("e16","t5","next","x1"),Z("e17","t6","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var EZ={id:"status-pedido",category:"capture",requiredModules:[],tags:["pedido","status","rastreio","ecommerce","api"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Boas-vindas","boas_vindas",F("Olá. Vou consultar o status do seu pedido.")),V("c1","capture","Número do Pedido","numero_pedido",D$("Informe o número do seu pedido e finalize com a tecla jogo da velha.",{voiceMethod:"dtmf",minDigits:1,maxDigits:10,terminators:"#",text:"Informe o número do seu pedido:",validation:String.raw`^\d{1,10}$`,invalidMessage:"O número do pedido deve conter apenas dígitos. Tente novamente:"})),V("http1","httpRequest","Consultar Pedido","consultar_pedido",{method:"GET",url:"https://api.example.com/orders/{{numero_pedido.text}}",headers:{},body:"",timeout:10}),V("sw1","switchCase","Tipo de Falha","tipo_falha",{expression:"{{consultar_pedido.status_code}}",cases:[{pattern:"^404$"}]}),V("t2","tell","Status do Pedido","status_do_pedido",F("O status do seu pedido é: {{consultar_pedido.response}}")),V("t3","tell","Pedido Não Encontrado","pedido_nao_encontrado",F("Não encontrei esse número de pedido. Verifique e tente novamente.")),V("t4","tell","Erro de Consulta","erro_consulta",F("Houve um erro ao consultar o pedido. Tente novamente mais tarde.")),V("t5","tell","Sem Número","sem_numero",F("Não consegui capturar o número do pedido. Por favor, ligue novamente com o número em mãos.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[Z("e1v","s1","voice","t1"),Z("e1c","s1","chat","t1"),Z("e2","t1","next","c1"),Z("e3","c1","collected","http1"),Z("e4","c1","noInput","t5"),Z("e5","c1","error","t5"),Z("e6","http1","next","t2"),Z("e7","http1","error","sw1"),Z("e8","sw1","match:^404$","t3"),Z("e9","sw1","fallback","t4"),Z("e10","sw1","error","t4"),Z("e11","t2","next","h1"),Z("e12","t3","next","h1"),Z("e13","t4","next","h1"),Z("e14","t5","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var yZ={id:"triagem-inteligente",category:"ai",requiredModules:["ai"],tags:["triagem","intencao","intent","ia","roteamento","ai"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("t1","tell","Boas-vindas","boas_vindas",F("Olá! Vou te direcionar para o setor correto.")),V("c1","capture","Motivo do Contato","motivo_contato",D$("Diga em poucas palavras com o que você precisa de ajuda.",{voiceMethod:"speech",maxAttempts:3,listen:{initial_timeout_s:10,timeout_s:3,max_duration_s:15,beep:!0},processing_audio:F4("Um momento enquanto identifico o setor correto.").audio,text:"Descreva em poucas palavras com o que você precisa de ajuda:"})),V("ra1","routeAi","Classificar Intenção","classificar_intencao",{input:"{{motivo_contato.text}}",intents:[{label:"suporte",description:"Problemas técnicos, dúvidas de uso, erros no sistema"},{label:"financeiro",description:"Faturas, cobranças, pagamentos, reembolsos"},{label:"vendas",description:"Novos produtos, planos, promoções, contratação"}],instructions:"Classifique a intenção do cliente com base no que ele disse."}),V("t2","tell","Direcionando Suporte","direcionando_suporte",F("Entendi, vou transferir para o suporte técnico.")),V("t3","tell","Direcionando Financeiro","direcionando_financeiro",F("Entendi, vou transferir para o financeiro.")),V("t4","tell","Direcionando Vendas","direcionando_vendas",F("Entendi, vou transferir para vendas.")),V("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),V("x2","transfer","Financeiro","financeiro",{method:"bridge",destinations:["1002"],timeout:45}),V("x3","transfer","Vendas","vendas",{method:"bridge",destinations:["1003"],timeout:30}),V("t5","tell","Não Identificado","nao_identificado",F("Não consegui identificar sua necessidade. Vou transferir para um atendente.")),V("x4","transfer","Atendente Geral","atendente_geral",{method:"bridge",destinations:["1000"],timeout:45}),V("t6","tell","Transferência Falhou","transferencia_falhou",F("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),V("h1","hangup","Desligamento","desligamento",{})],edges:[Z("e1v","s1","voice","t1"),Z("e1c","s1","chat","t1"),Z("e2","t1","next","c1"),Z("e3","c1","collected","ra1"),Z("e4","c1","noInput","t5"),Z("e5","c1","error","t5"),Z("e6","ra1","intent:suporte","t2"),Z("e7","ra1","intent:financeiro","t3"),Z("e8","ra1","intent:vendas","t4"),Z("e9","ra1","notApplicable","t5"),Z("e10","ra1","error","t5"),Z("e11","t2","next","x1"),Z("e12","t3","next","x2"),Z("e13","t4","next","x3"),Z("e14","t5","next","x4"),...d("ex1","x1","h1","t6"),...d("ex2","x2","h1","t6"),...d("ex3","x3","h1","t6"),...d("ex4","x4","h1","t6"),Z("e15","t6","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var gZ={id:"ura-reversa-spot",category:"core",requiredModules:[],tags:["spot","ura reversa","campanha","outbound","discagem","tecla"],editorState:{nodes:[V("s1","start","Início","inicio",{channelType:"both"}),V("m1","menu","Spot","spot",n("Substitua este texto pelo áudio do seu spot. Para falar com um atendente, tecle 1.",[{id:"interesse",label:"Falar com atendente",digit:"1"}],{maxAttempts:1},"Substitua este texto pelo conteúdo do seu spot.")),V("t1","tell","Agradecimento","agradecimento",F("Obrigado! Em instantes um atendente entrará em contato.")),V("t2","tell","Encerramento","encerramento",F("Obrigado pela atenção. Até logo!")),V("h1","hangup","Desligamento","desligamento",{})],edges:[Z("e1v","s1","voice","m1"),Z("e1c","s1","chat","m1"),Z("e2","m1","option:interesse","t1"),Z("e3","m1","noMatch","t2"),Z("e4","m1","error","t2"),Z("e5","t1","next","h1"),Z("e6","t2","next","h1")],viewport:{x:0,y:0,zoom:0.9}}};var uZ={"atendente-virtual-ia":{ai1:{x:672,y:170},h1:{x:2352,y:254},m1:{x:1008,y:0},s1:{x:0,y:26},t1:{x:336,y:109},t2:{x:1680,y:61},t3:{x:1344,y:113},t4:{x:1344,y:253},t5:{x:2016,y:306},x1:{x:1680,y:201}},"atendimento-agente-ia":{ai1:{x:1344,y:38},c1:{x:672,y:208},h1:{x:3024,y:139},ra1:{x:1008,y:116},s1:{x:0,y:64},sw1:{x:1680,y:0},t1:{x:336,y:147},t2:{x:2688,y:78},t3:{x:1344,y:221},t4:{x:2016,y:153},t5:{x:2688,y:218},x1:{x:2352,y:113}},"atendimento-setores":{h1:{x:2016,y:740},m1:{x:672,y:307},s1:{x:0,y:163},t1:{x:336,y:246},t2:{x:1008,y:0},t3:{x:1008,y:206},t4:{x:1008,y:412},t5:{x:1008,y:552},t6:{x:1008,y:692},t7:{x:1680,y:556},x1:{x:1344,y:61},x2:{x:1344,y:267},x3:{x:1344,y:473},x4:{x:1344,y:679}},"banco-sac":{c1:{x:336,y:356},h1:{x:2352,y:314},http1:{x:1008,y:0},m1:{x:672,y:170},s1:{x:0,y:273},t1:{x:1680,y:205},t2:{x:1344,y:253},t3:{x:1344,y:393},t4:{x:1008,y:321},t5:{x:1344,y:113},t6:{x:1008,y:461},t7:{x:2016,y:537},x1:{x:1680,y:454}},"clinica-agendamento":{c1:{x:1008,y:140},h1:{x:2016,y:306},http1:{x:1344,y:131},m1:{x:672,y:144},s1:{x:0,y:0},t1:{x:336,y:83},t2:{x:1680,y:105},t3:{x:1680,y:245},t4:{x:1344,y:293}},"cobranca-automatizada":{c1:{x:1008,y:139},h1:{x:2352,y:283},m1:{x:672,y:339},s1:{x:0,y:195},t1:{x:336,y:278},t2:{x:1344,y:0},t3:{x:1680,y:335},t4:{x:2016,y:444},t5:{x:1008,y:496},t6:{x:1344,y:222},t7:{x:2016,y:174},x1:{x:1680,y:61}},"coleta-dados-api":{c1:{x:672,y:196},h1:{x:2016,y:174},http1:{x:1008,y:65},s1:{x:0,y:52},sw1:{x:1344,y:148},t1:{x:336,y:135},t2:{x:1344,y:0},t3:{x:1680,y:113},t4:{x:1680,y:253},t5:{x:1008,y:301}},"faq-ia-escalacao":{ai1:{x:672,y:144},h1:{x:2352,y:306},m1:{x:1008,y:52},s1:{x:0,y:0},t1:{x:336,y:83},t2:{x:1680,y:113},t3:{x:1344,y:179},t4:{x:2016,y:358},x1:{x:1680,y:253}},"faq-informacoes":{h1:{x:1354,y:708},m1:{x:672,y:144},s1:{x:0,y:0},t1:{x:336,y:83},t2:{x:1018,y:67},t3:{x:1018,y:227},t4:{x:1018,y:367},t5:{x:1018,y:507},t6:{x:1018,y:647}},"horario-comercial":{h1:{x:2352,y:442},m1:{x:1008,y:206},s1:{x:0,y:193},t1:{x:672,y:145},t2:{x:1344,y:0},t3:{x:1344,y:193},t4:{x:672,y:381},t5:{x:1344,y:333},t6:{x:2016,y:333},tr1:{x:336,y:276},x1:{x:1680,y:61},x2:{x:1680,y:267}},"isp-suporte-tecnico":{c1:{x:1008,y:43},c2:{x:1008,y:227},h1:{x:3034,y:296},http1:{x:1344,y:22},http2:{x:1344,y:341},m1:{x:672,y:144},s1:{x:0,y:0},sw1:{x:1690,y:135},sw2:{x:1690,y:319},t1:{x:336,y:83},t2:{x:2362,y:83},t3:{x:2698,y:488},t4:{x:2026,y:204},t5:{x:2026,y:344},t6:{x:1344,y:201},t7:{x:1008,y:411},t8:{x:2698,y:348},x1:{x:2362,y:265}},"mensagem-simples":{h1:{x:672,y:144},s1:{x:0,y:0},t1:{x:336,y:83}},"menu-multinivel":{h1:{x:2372,y:487},m1:{x:672,y:482},m2:{x:1008,y:250},m3:{x:1008,y:456},m4:{x:1008,y:683},s1:{x:0,y:338},t1:{x:336,y:421},t2:{x:1354,y:71},t3:{x:1354,y:211},t4:{x:1354,y:351},t5:{x:1354,y:491},t6:{x:1354,y:771},t7:{x:1354,y:969},t8:{x:1354,y:631},t9:{x:2036,y:539},x1:{x:1690,y:206},x2:{x:1690,y:0},x3:{x:1690,y:412},x4:{x:1690,y:618},x5:{x:1690,y:824},x6:{x:1690,y:1030}},"notificacao-atendimento":{h1:{x:2016,y:284},m1:{x:672,y:144},s1:{x:0,y:0},t1:{x:336,y:83},t2:{x:1008,y:49},t3:{x:1008,y:271},t4:{x:1680,y:223},x1:{x:1344,y:110}},"pesquisa-nps":{c1:{x:672,y:310},c2:{x:1680,y:201},h1:{x:2688,y:476},http1:{x:2016,y:284},s1:{x:0,y:166},sw1:{x:1008,y:35},t1:{x:336,y:249},t2:{x:1344,y:0},t3:{x:1344,y:140},t4:{x:1344,y:280},t5:{x:2352,y:415}},"pesquisa-satisfacao":{h1:{x:1344,y:288},h2:{x:1344,y:428},m1:{x:672,y:144},s1:{x:0,y:0},t1:{x:336,y:83},t2:{x:1008,y:227},t3:{x:1008,y:367}},"roteamento-canal":{cr1:{x:336,y:83},h1:{x:2362,y:507},m1:{x:1008,y:205},m2:{x:1008,y:411},s1:{x:0,y:0},t1:{x:672,y:144},t2:{x:672,y:350},t3:{x:1354,y:258},t4:{x:1354,y:398},t5:{x:1354,y:538},t6:{x:2026,y:446},x1:{x:1690,y:319},x2:{x:1690,y:525}},"status-pedido":{c1:{x:672,y:196},h1:{x:2016,y:174},http1:{x:1008,y:65},s1:{x:0,y:52},sw1:{x:1344,y:148},t1:{x:336,y:135},t2:{x:1344,y:0},t3:{x:1680,y:113},t4:{x:1680,y:253},t5:{x:1008,y:301}},"triagem-inteligente":{c1:{x:672,y:381},h1:{x:2352,y:455},ra1:{x:1008,y:241},s1:{x:0,y:237},t1:{x:336,y:320},t2:{x:1344,y:0},t3:{x:1344,y:206},t4:{x:1344,y:346},t5:{x:1344,y:486},t6:{x:2016,y:394},x1:{x:1680,y:61},x2:{x:1680,y:267},x3:{x:1680,y:473},x4:{x:1680,y:679}},"ura-reversa-spot":{h1:{x:1008,y:109},m1:{x:336,y:83},s1:{x:0,y:0},t1:{x:672,y:48},t2:{x:672,y:188}}};function zw($){let U=uZ[$.id];if(U==null)return $;return{...$,editorState:{...$.editorState,nodes:$.editorState.nodes.map((K)=>{let q=U[K.id];return q==null?K:{...K,position:{...q}}})}}}var fZ=[_Z,kZ,SZ,vZ,RZ,gZ,wZ,xZ,EZ,NZ,yZ,AZ,LZ,CZ,OZ,FZ,zZ,IZ,bZ,TZ].map(($)=>zw($));var mZ=[{nodeId:"__global_args__",nodeLabel:"Args",nodeVarName:"args",nodeType:"start",variables:[{name:"*",type:"string",descriptionKey:"editor:vars.args"}]},{nodeId:"__global_dialer__",nodeLabel:"Dialer",nodeLabelKey:"editor:vars.dialerGroup",nodeVarName:"args",nodeType:"start",module:"dialer",variables:[{name:"dialer_contact_name",type:"string",descriptionKey:"editor:vars.dialerContactName"},{name:"dialer_contact_phone",type:"string",descriptionKey:"editor:vars.dialerContactPhone"},{name:"dialer_campaign_id",type:"string",descriptionKey:"editor:vars.dialerCampaignId"}]}],hZ="vars",cZ="counters",UG=new Set([...mZ.map(($)=>$.nodeVarName),y3,hZ,cZ].map(($)=>$.split(".")[0]));function QG($){return UG.has($)}var lZ={tell:new Set(["audio"]),menu:new Set(["audio","voiceTimeout"]),capture:new Set(["audio","voiceMethod","minDigits","maxDigits","terminators","voiceTimeout","listen","processing_audio","retryAudio"])},rZ={tell:new Set(["content"]),menu:new Set(["text","invalidMessage"]),capture:new Set(["text","validation","invalidMessage"])};function KG($,U,K,q){let Q=$.filter((H)=>H.type==="start"),W=mw(U),G=Q[0]?.id,j=$A($,U),Y=[...fw(Q),...hw($,W,G),...cw($),...lw($),...rw($),...iw($),...ow($),...nw($),...pw($,U,K),...tw($,W,G),...aw($),...sw($),...ew($,K,q?.disabledModules),...q?.entities!=null?rW($,q.entities):[],...q?.externalEntities!=null?iW($,q.externalEntities):[],...UA($,K,j),...QA($),...qA($),...q?.mediaProfile!=null?Ew($,U,q.mediaProfile):[]];if(j!=null)return WA(Y,$,j);return Y}function Ew($,U,K){let q=$.find((j)=>j.type==="start");if(q==null)return[];let Q=new Map;for(let j of U){let Y=Q.get(j.source)??new Map;Y.set(j.sourceHandle,j.target),Q.set(j.source,Y)}let W=$q(q.id,K.profile,$,Q,K.recordingEnabled),G=[];for(let j of $){let Y=W[j.id];if(Y==null||!yw(j.type))continue;let X=gw(j.type,Y).filter((B)=>B.value.kind==="indeterminate");if(X.length>0)G.push({nodeId:j.id,severity:"warning",messageKey:"editor:validation.mediaStateIndeterminate",params:{label:j.label,fields:X.map((B)=>B.name).join(", "),paths:X.map((B)=>uw(B.value)).join("; ")}});if(j.type==="transcription"&&Y.transcriptionEnabled.kind==="known"&&Y.transcriptionEnabled.value&&Y.recordingEnabled.kind==="known"&&!Y.recordingEnabled.value)G.push({nodeId:j.id,severity:"warning",messageKey:"editor:validation.transcriptionWithoutRecording",params:{label:j.label}})}return G}function yw($){return $==="recording"||$==="transcription"||$==="analysis"}function gw($,U){if($==="recording")return[{name:"recording",value:U.recordingEnabled},{name:"sampling",value:U.samplingPercentage}];if($==="transcription")return[{name:"recording",value:U.recordingEnabled},{name:"transcription",value:U.transcriptionEnabled},{name:"language",value:U.transcriptionLanguage},{name:"minimum_duration",value:U.transcriptionMinDurationSeconds},{name:"anonymization",value:U.anonymizeEnabled}];return[{name:"transcription",value:U.transcriptionEnabled},{name:"speech_analytics",value:U.speechAnalyticsEnabled},{name:"sentiment",value:U.sentimentEnabled},{name:"topics",value:U.topicDetectionTopics},{name:"intents",value:U.intentDetectionIntents},{name:"structured_analysis",value:U.structuredAnalysisEnabled},{name:"analysis_ids",value:U.structuredAnalysisIds}]}function uw($){if($.kind==="known")return"";return $.branches.map((U)=>U.viaNodeLabel).join(", ")}function fw($){if($.length===0)return[{nodeId:"",severity:"error",messageKey:"editor:validation.noStart"}];return $.slice(1).map((U)=>({nodeId:U.id,severity:"error",messageKey:"editor:validation.multipleStart"}))}function mw($){let U=new Map;for(let K of $){let q=U.get(K.source)??[];q.push(K.target),U.set(K.source,q)}return U}function hw($,U,K){if(K===void 0)return[];let q=new Set([K]),Q=[K];while(Q.length>0){let G=Q.pop();for(let j of U.get(G)??[])if(!q.has(j))q.add(j),Q.push(j)}let W=[];for(let G of $)if(G.type!=="start"&&!q.has(G.id))W.push({nodeId:G.id,severity:"warning",messageKey:"editor:validation.unreachable",params:{label:G.label}});return W}function cw($){let U=[];for(let K of $){if(!Object.hasOwn(p$,K.type)){U.push({nodeId:K.id,severity:"error",messageKey:"editor:validation.unknownNodeType",params:{label:K.label,type:K.type}});continue}let q=p$[K.type],Q=q.configSchema.safeParse(K.config),W=Q.success?Q.data:K.config,G=Q.success?q.configSchema.safeParse(W):Q;if(G.success)continue;for(let j of G.error.issues){let Y=j.message.startsWith("editor:")?j.message:"editor:validation.invalidField";U.push({nodeId:K.id,severity:"error",messageKey:Y,params:{label:K.label,field:j.path.join(".")}})}}return U}function qG($){let U=[];for(let K of $){if(K.type!=="transfer")continue;let q=p$.transfer.configSchema.safeParse(K.config);if(!q.success)continue;U.push({node:K,destinations:q.data.destinations,attachedData:q.data.attachedData})}return U}function lw($){let U=[];for(let{node:K,destinations:q}of qG($)){if(q.some((Q)=>Q.trim()!==""))continue;U.push({nodeId:K.id,severity:"error",messageKey:"editor:validation.noDestinations",params:{label:K.label}})}return U}function rw($){let U=[];for(let{node:K,destinations:q,attachedData:Q}of qG($)){let W=[...q.map((G,j)=>({field:`destinations.${j}`,template:G})),...Q.map((G)=>({field:G.key,template:G.value}))];for(let{field:G,template:j}of W){if(vq(j).valid)continue;U.push({nodeId:K.id,severity:"error",messageKey:"editor:validation.invalidTemplateSyntax",params:{label:K.label,field:G}})}}return U}function iw($){let U=[];for(let{node:K,destinations:q}of qG($))q.forEach((Q,W)=>{if(!/\s/.test(Q.trim()))return;U.push({nodeId:K.id,severity:"error",messageKey:"editor:validation.destinationHasSpace",params:{label:K.label,field:`destinations.${W}`}})});return U}var dw=new Set(["httpRequest","webhook"]);function ow($){let U=[];for(let K of $){if(!dw.has(K.type))continue;let q=typeof K.config.body==="string"?K.config.body:"";if(q.trim()==="")continue;let Q=wq(q,()=>'"__tpl__"');try{JSON.parse(Q)}catch{U.push({nodeId:K.id,severity:"warning",messageKey:"editor:validation.invalidJson",params:{label:K.label}})}}return U}function nw($){return u3($).misplaced.map((U)=>({nodeId:U.nodeId,severity:"error",messageKey:"editor:validation.secretFieldNotAllowed",params:{label:U.label,field:U.field,secret:U.name}}))}function pw($,U,K){let q=new Set(U.map((W)=>W.source)),Q=[];for(let W of $){if(!Object.hasOwn(K,W.type))continue;let G=K[W.type];if(I4(G,W.config).length===0)continue;if(q.has(W.id))continue;Q.push({nodeId:W.id,severity:"warning",messageKey:"editor:validation.noOutputConnection",params:{label:W.label}})}return Q}function tw($,U,K){if(K===void 0)return[];let q=0,Q=1,W=2,G=new Map;for(let X of $)G.set(X.id,q);let j=new Set;function Y(X){G.set(X,Q);for(let B of U.get(X)??[])if(G.get(B)===Q)j.add(B);else if(G.get(B)===q)Y(B);G.set(X,W)}Y(K);let H=[];for(let X of j){let B=$.find((I)=>I.id===X);if(B===void 0)continue;if(!(typeof B.config.maxAttempts==="number"&&B.config.maxAttempts>0))H.push({nodeId:X,severity:"error",messageKey:"editor:validation.infiniteCycle",params:{label:B.label}})}return H}function aw($){let U=new Map,K=[];for(let q of $)if(U.get(q.varName)!==void 0)K.push({nodeId:q.id,severity:"error",messageKey:"editor:validation.duplicateVarName",params:{label:q.label,varName:q.varName}});else U.set(q.varName,q.id);return K}function sw($){return $.filter((U)=>QG(U.varName)).map((U)=>({nodeId:U.id,severity:"error",messageKey:"editor:validation.reservedVarName",params:{label:U.label,varName:U.varName}}))}function ew($,U,K){if(K==null||K.size===0)return[];let q=[];for(let Q of $){if(!Object.hasOwn(U,Q.type))continue;let W=U[Q.type];if(W.module!=="core"&&K.has(W.module))q.push({nodeId:Q.id,severity:"warning",messageKey:"editor:validation.moduleDisabled",params:{label:Q.label,module:W.module}})}return q}function $A($,U){let K=$.find((j)=>j.type==="start");if(K==null)return null;let q=K.config.channelType;if((typeof q==="string"?q:"voice")!=="both")return null;let W=new Map;for(let j of U){let Y=W.get(j.source);if(Y==null)Y=new Map,W.set(j.source,Y);Y.set(j.sourceHandle,j.target)}let G=new Set;for(let j of $)if(j.type==="channelRouter")G.add(j.id);return cW(K.id,K.config,W,$.map((j)=>j.id),G.size>0?G:void 0)}function UA($,U,K){if(K==null)return[];let q=[];for(let Q of $){if(Q.type==="start")continue;if(!Object.hasOwn(U,Q.type))continue;let W=U[Q.type],G=K[Q.id];if(G==null||G==="unreachable"||G==="converged")continue;if(W.channel==="voice"&&G==="chat-only")q.push({nodeId:Q.id,severity:"error",messageKey:"editor:validation.voiceNodeInChatBranch",params:{label:Q.label}});if(W.channel==="chat"&&G==="voice-only")q.push({nodeId:Q.id,severity:"error",messageKey:"editor:validation.chatNodeInVoiceBranch",params:{label:Q.label}})}return q}function QA($){let K=$.find((W)=>W.type==="start")?.config.channelType;if((typeof K==="string"?K:"voice")!=="chat")return[];let Q=[];for(let W of $){if(W.type!=="retellAgent"&&W.type!=="vapiAgent"&&W.type!=="elevenlabsAgent")continue;Q.push({nodeId:W.id,severity:"error",messageKey:"editor:validation.voiceNodeInChatBranch",params:{label:W.label}})}return Q}var KA={retellAgent:{agentField:"agent_id",agentMessageKey:"editor:validation.voiceAgentAgentRequired"},vapiAgent:{agentField:"assistant_id",agentMessageKey:"editor:validation.voiceAgentAssistantRequired"},elevenlabsAgent:{agentField:"agent_id",agentMessageKey:"editor:validation.voiceAgentAgentRequired"}};function qA($){let U=[];for(let K of $){let q=KA[K.type];if(q===void 0)continue;let Q=K.config.connector_id;if(typeof Q!=="string"||Q==="")U.push({nodeId:K.id,severity:"error",messageKey:"editor:validation.voiceAgentConnectorRequired",params:{label:K.label}});let W=K.config[q.agentField];if(typeof W!=="string"||W==="")U.push({nodeId:K.id,severity:"error",messageKey:q.agentMessageKey,params:{label:K.label}})}return U}function WA($,U,K){let q=new Map(U.map((Q)=>[Q.id,Q.type]));return $.filter((Q)=>{let W=Q.params?.field;if(W==null||Q.nodeId==="")return!0;let G=q.get(Q.nodeId);if(G==null)return!0;let j=K[Q.nodeId];if(j==null||j==="converged"||j==="unreachable")return!0;let Y=W.split(".")[0];if(j==="chat-only"&&lZ[G]?.has(Y))return!1;if(j==="voice-only"&&rZ[G]?.has(Y))return!1;return!0})}function WG($){return $.every((U)=>U.severity!=="error")}var jA=J.object({type:J.literal("message"),message:ZW}),YA=J.object({type:J.literal("typing")}),HA=J.object({type:J.literal("ping")}),XA=J.object({type:J.literal("resume"),lastSeq:J.number().int().min(0)}),ZA=J.object({type:J.literal("start")}),BA=J.discriminatedUnion("type",[jA,YA,HA,XA,ZA]),iZ=J.object({type:J.literal("connected"),seq:J.number().int(),ts:J.number(),sessionId:J.string()}),dZ=J.object({type:J.literal("message"),seq:J.number().int(),ts:J.number(),id:J.string(),message:V6}),oZ=J.object({type:J.literal("typing"),seq:J.number().int(),ts:J.number(),active:J.boolean()}),nZ=J.object({type:J.literal("state"),seq:J.number().int(),ts:J.number(),status:J.enum(["active","waiting_input","ended"])}),pZ=J.object({type:J.literal("trace"),seq:J.number().int(),ts:J.number(),currentNodeId:J.string(),variables:J.record(J.string(),J.string()),status:J.enum(["active","waiting_input","ended"]),truncated:J.boolean(),step:n3.optional()}),tZ=J.object({type:J.literal("error"),seq:J.number().int(),ts:J.number(),code:J.string(),message:J.string()}),aZ=J.object({type:J.literal("pong"),seq:J.number().int(),ts:J.number()}),VA=J.discriminatedUnion("type",[iZ,dZ,oZ,nZ,pZ,tZ,aZ]),MA=J.object({type:J.literal("replay"),seq:J.number().int(),ts:J.number(),messages:J.array(VA)}),DA=J.discriminatedUnion("type",[iZ,dZ,oZ,nZ,pZ,tZ,aZ,MA]);var p3=J.templateLiteral([J.literal(m.signals),J.literal("_"),J.string()]),PA=J.templateLiteral([J.literal(m.visual_plans),J.literal("_"),J.string()]),NA=["volume","answered","busy","no_answer","failed","outcome","duration","ai_cost","flow_errors"],LA=["answered","busy","no_answer","failed"],_A=["number","trend","compare","distribution","weekday_hour"],IA=["plan_version","plan","hour_of_day","weekday","channel"];var Xd=J.union([J.literal(1),J.literal(2),J.literal(3),J.literal(4)]).describe("Pinned-card column span (1-4). Null means the default for the query shape.");var FA=["today","yesterday","last_7_days","last_30_days","this_month","last_month"],xA=["voice","chat"],wA=J.union([J.object({preset:J.enum(FA)}),J.object({date_from:J.string(),date_to:J.string()}),J.object({last_days:J.number().int().min(1).max(366)})]),AA=J.discriminatedUnion("kind",[J.object({kind:J.literal("calls"),measure:J.enum(NA),value:J.enum(LA).optional()}),J.object({kind:J.literal("signal"),signal_id:p3,value:J.string().optional()})]),vA=J.union([J.enum(IA),J.object({signal_id:p3})]),kA=J.object({subject:AA,shape:J.enum(_A),compare_by:vA.optional(),period:wA,channel:J.enum(xA).optional(),plan_id:PA.optional()}),zA=J.object({id:p3,name:J.string(),question:J.string(),kind:J.enum(["yes_no","choice","scale"]),options:J.array(J.object({key:J.string(),label:J.string()})).optional(),levels:J.array(J.string()).optional(),higher_is:J.enum(_0).optional()}),Zd=J.object({org_id:J.string(),signals:J.array(zA)}),x0=J.object({answered:J.number().int(),no_answer:J.number().int().nullable(),not_evaluated:J.number().int().nullable()}),RA=J.object({shape:J.literal("number"),value:J.number(),n:J.number().int(),dist:J.array(J.object({key:J.string(),label:J.string(),value:J.number()})).optional(),rate:J.number().nullable(),low:J.number().nullable(),high:J.number().nullable(),previous:J.object({value:J.number(),rate:J.number().nullable(),low:J.number().nullable(),high:J.number().nullable()}).nullable(),change:J.enum(["up","down","stable"]).nullable(),denominator:x0}),eZ=J.object({bucket:J.string(),value:J.number(),n:J.number().int(),low:J.number().nullable(),high:J.number().nullable(),small:J.boolean()}),bA=J.object({date:J.string(),label:J.string()}),OA=J.object({key:J.string(),label:J.string(),points:J.array(eZ)}),TA=J.object({shape:J.literal("trend"),granularity:J.enum(["day","hour"]),points:J.array(eZ),series:J.array(OA).optional(),plan_versions:J.array(bA),denominator:x0}),SA=J.object({key:J.string(),label:J.string().nullable(),version:J.number().int().nullable().optional(),value:J.number(),n:J.number().int(),low:J.number().nullable(),high:J.number().nullable(),small:J.boolean(),dist:J.array(J.object({key:J.string(),label:J.string(),value:J.number()})).optional()}),CA=J.object({shape:J.literal("compare"),rows:J.array(SA),denominator:x0}),EA=J.object({key:J.string(),label:J.string(),value:J.number(),n:J.number().int()}),yA=J.object({shape:J.literal("distribution"),rows:J.array(EA),denominator:x0}),gA=J.object({weekday:J.number().int(),hour:J.number().int(),value:J.number(),n:J.number().int(),low:J.number().nullable(),high:J.number().nullable()}),uA=J.object({shape:J.literal("weekday_hour"),cells:J.array(gA),denominator:x0}),Bd=J.discriminatedUnion("shape",[RA,TA,CA,yA,uA]),sZ=J.object({rate:J.number(),low:J.number(),high:J.number()}),fA=J.object({signal_id:p3,kind:J.enum(["yes_no","choice","scale"]),name:J.string(),question:J.string(),alert_label:J.string().nullable(),alert_below:J.boolean(),higher_is:J.enum(_0).nullable(),n:J.number().int(),value:J.number().nullable(),rate:J.number().nullable(),low:J.number().nullable(),high:J.number().nullable(),distribution:J.array(J.object({key:J.string(),label:J.string(),value:J.number()})),series:J.array(J.object({bucket:J.string(),value:J.number(),n:J.number().int()})),alert_share:sZ.nullable(),previous_share:sZ.nullable(),in_alert:J.boolean()}),Vd=J.object({cards:J.array(fA)}),mA=J.object({strategy:J.string(),model:J.string(),ms:J.number(),input_tokens:J.number(),output_tokens:J.number()}),Md=J.object({query:kA.nullable(),confidence:J.number(),period_explicit:J.boolean(),meta:mA});async function $B($){let U=$==="-"?await v$():await hA($,"utf-8"),K=JSON.parse(U);if(!Q$(K))x(`Invalid campaign file "${$}": expected a JSON object`),process.exit(w.USAGE_ERROR);return K}function cA($){return{...$.name!=null&&{name:$.name},...$.description!=null&&{description:$.description},...$.callerId!=null&&{caller_id:$.callerId},...$.trunkOverride!=null&&{trunk_override:$.trunkOverride},...$.maxConcurrent!=null&&{max_concurrent_calls:Number($.maxConcurrent)},...$.ringTimeout!=null&&{ring_timeout_s:Number($.ringTimeout)},...$.maxDuration!=null&&{max_call_duration_s:Number($.maxDuration)},...$.priority!=null&&{priority:Number($.priority)}}}var UB=["interval_min","max_attempts"];function L6($){x(`Invalid --retry-rules: ${$}`),process.exit(w.USAGE_ERROR)}function lA($,U){if(!Q$(U))return L6(`"${$}" must be an object`);let K={};for(let[q,Q]of Object.entries(U)){let W=UB.find((G)=>G===q);if(W===void 0)return L6(`unknown field "${q}" in "${$}" (allowed: ${UB.join(", ")})`);if(typeof Q!=="number")return L6(`"${$}.${q}" must be a number`);K[W]=Q}return K}function rA($){let U;try{U=JSON.parse($)}catch{return L6("not valid JSON")}if(U===null)return null;if(!Q$(U))return L6("expected a JSON object or null");let K={};for(let[q,Q]of Object.entries(U)){let W=Uq.find((G)=>G===q);if(W===void 0)return L6(`unknown class "${q}" (allowed: ${Uq.join(", ")})`);K[W]=lA(W,Q)}return K}function iA($){let U=$.retryOn!=null?new Set($.retryOn.split(",").map((K)=>K.trim())):void 0;return{...$.retryAttempts!=null&&{retry_max_attempts:Number($.retryAttempts)},...$.retryInterval!=null&&{retry_interval_min:Number($.retryInterval)},...$.retryRules!=null&&{retry_rules:rA($.retryRules)},...$.windowStart!=null&&{call_window_start:$.windowStart},...$.windowEnd!=null&&{call_window_end:$.windowEnd},...$.windowDays!=null&&{call_window_days:$.windowDays},...$.autoStartAt!=null&&{auto_start_at:$.autoStartAt},...$.autoStopAt!=null&&{auto_stop_at:$.autoStopAt},...U!=null&&{retry_on_busy:U.has("busy"),retry_on_no_answer:U.has("no_answer"),retry_on_failed:U.has("failed")},...$.recurring===!0&&{recurring:!0}}}function QB($){return{...cA($),...iA($)}}function N6($){if($==null)return"inherit (org default)";if(typeof $==="boolean")return $?"yes":"no";return String($)}function KB($){return $.option("--description <text>","Campaign description").option("--caller-id <id>","Caller ID for outbound calls").option("--trunk-override <trunk>","Trunk override (default: org trunk)").option("--max-concurrent <n>","Max concurrent calls").option("--ring-timeout <s>","Ring timeout in seconds before no-answer").option("--max-duration <s>","Max call duration in seconds").option("--retry-attempts <n>","Max retry attempts").option("--retry-interval <min>","Retry interval in minutes").option("--retry-on <list>","Retry on outcomes (comma list: busy,no_answer,failed)").option("--retry-rules <json>",`Per-outcome retry overrides, e.g. '{"busy":{"interval_min":5,"max_attempts":3}}' (null clears)`).option("--window-start <HH:MM>","Call window start time").option("--window-end <HH:MM>","Call window end time").option("--window-days <list>","Call window days (comma ints, 0=Sun..6=Sat)").option("--priority <n>","Campaign priority (0-100)").option("--recurring","Enable recurring dialing").option("--auto-start-at <iso>","Auto-start timestamp (ISO 8601)").option("--auto-stop-at <iso>","Auto-stop timestamp (ISO 8601)").option("--file <path>","JSON file with campaign fields (- for stdin)")}function qB($,U){let K=$.command("campaigns").description("Manage dialer campaigns");K.command("list").description("List dialer campaigns").option("--status <s>","Filter by status").option("--search <term>","Search by name").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),G=await N(U().dialerCampaigns.list({page:Number(q.page),limit:Number(q.limit),search:q.search,status:P$(q.status)}));if(Q==="json"){let j=W?G.items.map((Y)=>O(Y,W)):G;P(j);return}y(["ID","Name","Status","Contacts","Answered","Created"],G.items.map((j)=>({ID:j.id,Name:j.name,Status:j.status,Contacts:j.total_contacts,Answered:j.answered_count,Created:j1(j.created_at)}))),Z$(G)}),K.command("show <campaign_id>").description("Show campaign details").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),G=await N(U().dialerCampaigns.get({campaign_id:A("dialer_campaigns",q)}));if(G==null){if(Q==="json")P(null),process.exit(w.NOT_FOUND);x("Campaign not found"),process.exit(w.NOT_FOUND)}if(Q==="json"){let j=W?O(G,W):G;P(j);return}o([{title:"Campaign",rows:[{label:"ID",value:G.id},{label:"Name",value:G.name},{label:"Description",value:G.description},{label:"Status",value:G.status},{label:"Plan",value:G.plan_id},{label:"Channel",value:G.channel_type},{label:"Priority",value:G.priority},{label:"Created",value:new Date(G.created_at).toLocaleString()},{label:"Updated",value:new Date(G.updated_at).toLocaleString()}]},{title:"Dialing",rows:[{label:"Caller ID",value:G.caller_id},{label:"Trunk",value:G.trunk_override},{label:"Max Concurrent",value:G.max_concurrent_calls},{label:"Ring Timeout",value:`${G.ring_timeout_s}s`},{label:"Max Duration",value:`${G.max_call_duration_s}s`}]},{title:"Retry",rows:[{label:"Max Attempts",value:G.retry_max_attempts},{label:"Interval",value:`${G.retry_interval_min}min`},{label:"On Busy",value:G.retry_on_busy?"yes":"no"},{label:"On No Answer",value:G.retry_on_no_answer?"yes":"no"},{label:"On Failed",value:G.retry_on_failed?"yes":"no"},...G.retry_rules!=null?[{label:"Retry Rules",value:JSON.stringify(G.retry_rules)}]:[]]},{title:"Answering machine",rows:[{label:"Detection",value:G.amd_enabled?"on":"off"},{label:"Retry On Machine",value:G.retry_on_machine?"yes":"no"},{label:"Block After All",value:N6(G.amd_block_after_all_machine)},{label:"Block Min Attempts",value:N6(G.amd_block_min_attempts)},{label:"On Voicemail",value:N6(G.amd_action_voicemail)},{label:"On Announcement",value:N6(G.amd_action_announcement)},{label:"On IVR",value:N6(G.amd_action_ivr)},{label:"On Screening",value:N6(G.amd_action_screening)}]},{title:"Window & schedule",rows:[{label:"Window Start",value:G.call_window_start},{label:"Window End",value:G.call_window_end},{label:"Window Days",value:G.call_window_days},{label:"Recurring",value:G.recurring?"yes":"no"},{label:"Recurrence",value:G.recurrence_mode},{label:"Auto Start",value:G.auto_start_at?new Date(G.auto_start_at).toLocaleString():null},{label:"Auto Stop",value:G.auto_stop_at?new Date(G.auto_stop_at).toLocaleString():null}]}])}),K.command("stats <campaign_id>").description("Show campaign statistics").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),G=await N(U().dialerCampaigns.stats({campaign_id:A("dialer_campaigns",q)}));if(Q==="json"){let H=W?O(G,W):G;P(H);return}let j=G.capacity_context;o([{title:"Stats",rows:[{label:"Status",value:G.status},{label:"Total",value:G.total_contacts},{label:"Pending",value:G.pending_count},{label:"Calling",value:G.calling_count},{label:"Answered",value:G.answered_count},{label:"Machine",value:G.machine_count},{label:"Busy",value:G.busy_count},{label:"No Answer",value:G.no_answer_count},{label:"Failed",value:G.failed_count},{label:"DNC Skipped",value:G.dnc_skipped_count},{label:"Cancelled",value:G.cancelled_count}]},{title:"Capacity",rows:[{label:"Waiting",value:G.waiting_capacity?"yes":"no"},{label:"Used",value:j!=null?j.used:null},{label:"Capacity",value:j!=null?j.capacity:null},{label:"Reserve",value:j!=null?j.reserve:null},{label:"Module Disabled",value:G.module_disabled?"yes":"no"}]}]);let Y=Number(G.total_contacts);if(Y>0)console.log(""),U1("Answered",Number(G.answered_count),Y),U1("Busy",Number(G.busy_count),Y),U1("No Answer",Number(G.no_answer_count),Y),U1("Failed",Number(G.failed_count),Y)}),K.command("summary").description("Show running-campaign summary").action(async()=>{let{format:q,fields:Q}=L($.opts()),W=await N(U().dialerCampaigns.summary());if(q==="json"){let G=Q?O(W,Q):W;P(G);return}o([{title:"Summary",rows:[{label:"Running",value:W.running},{label:"Calling",value:W.calling},{label:"Campaign",value:W.campaign!=null?`${W.campaign.name} (${W.campaign.id})`:null}]}])}),KB(K.command("create <name>").description("Create a dialer campaign").requiredOption("--plan <plan_id>","Visual plan ID to dial")).action(async(q,Q)=>{let{format:W}=L($.opts()),G=Q.file!=null?await $B(Q.file):{},j=QB(Q),Y=await N(U().dialerCampaigns.create({...G,...j,name:q,plan_id:A("visual_plans",Q.plan)}));if(W==="json"){P(Y);return}T(`Campaign created: ${Y.id} — ${Y.name}`)}),KB(K.command("edit <campaign_id>").description("Update a dialer campaign").option("--name <name>","Campaign name")).action(async(q,Q)=>{let{format:W}=L($.opts()),G=Q.file!=null?await $B(Q.file):{},j=QB(Q),Y=await N(U().dialerCampaigns.update({campaign_id:A("dialer_campaigns",q),...G,...j}));if(W==="json"){P(Y);return}T(`Campaign updated: ${Y.name}`)}),K.command("delete <campaign_id>").description("Delete a dialer campaign").action(async(q)=>{let{format:Q}=L($.opts());if(await N(U().dialerCampaigns.delete({campaign_id:A("dialer_campaigns",q)})),Q==="json"){P({success:!0});return}T("Campaign deleted")});for(let q of["start","pause","resume","stop"])K.command(`${q} <campaign_id>`).description(`${q[0].toUpperCase()}${q.slice(1)} a campaign`).action(async(Q)=>{let{format:W}=L($.opts()),G=await N(U().dialerCampaigns.control({campaign_id:A("dialer_campaigns",Q),action:q}));if(W==="json"){P(G);return}T(`Campaign "${G.name}" → ${G.status}`)});K.command("watch <campaign_id>").description("Watch live campaign stats (streams until Ctrl-C)").action(async(q)=>{let{format:Q}=L($.opts()),W=U(),G=new AbortController;process.on("SIGINT",()=>{G.abort()}),await new Promise((j,Y)=>{S1(W.dialerCampaigns.liveStats({campaign_id:A("dialer_campaigns",q)},{signal:G.signal}),{onEvent:(H)=>{if(Q==="json"){console.log(JSON.stringify(H));return}let X=new Date().toLocaleTimeString(),B=H.counters,M=H.waiting_capacity?"yes":"no";console.log(`${X} status=${H.status} calling=${H.calling} pending_retry=${H.pending_retry} answered=${B.answered_count} busy=${B.busy_count} failed=${B.failed_count} waiting_capacity=${M}`)},onError:(H)=>{if(H instanceof DOMException&&H.name==="AbortError"){j();return}Y(H)},onSuccess:()=>{j()}})}).catch(R4)}),K.command("attempts <campaign_id>").description("List call attempts for a campaign").option("--status <s>","Filter by attempt status").option("--contact <contact_id>","Filter by contact ID").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(q,Q)=>{let{format:W,fields:G}=L($.opts()),j=await N(U().dialerAttempts.list({campaign_id:A("dialer_campaigns",q),status:P$(Q.status),contact_id:A("dialer_contacts",Q.contact),page:Number(Q.page),limit:Number(Q.limit)}));if(W==="json"){let Y=G?j.items.map((H)=>O(H,G)):j;P(Y);return}y(["ID","#","Phone","Name","Status","Machine","Cause","Started","Duration","Record"],j.items.map((Y)=>({ID:Y.id,"#":Y.attempt_number,Phone:Y.phone_number??"—",Name:Y.contact_name??"—",Status:Y.status??"—",Machine:y0(Y.machine_type),Cause:Y.hangup_cause??"—",Started:Y.started_at?j1(Y.started_at):"—",Duration:Y.duration_s!=null?f$(Y.duration_s*1000):"—",Record:Y.call_record_id??"—"}))),Z$(j)})}import{readFile as dA}from"node:fs/promises";var oA=new Set(["bot_token","webhook_secret","sip_password_encrypted","sip_password_iv"]),nA="<hidden>";function P1($){x(`Error: ${$}`),process.exit(w.USAGE_ERROR)}function _6($){return A("channels",$)}function GG($){return A("connectors",$)}function JG($){return A("visual_plans",$)}function WB($){return A("schedules",$)}function GB($){let U=K$($);if(U==null)return $;return Object.fromEntries(Object.entries(U).map(([K,q])=>[K,oA.has(K)?nA:q]))}function jG($){return{...$,config:GB($.config)}}async function pA($){let U=$==="-"?await v$():await dA($,"utf-8"),K;try{K=JSON.parse(U)}catch{P1(`invalid config file "${$}": not valid JSON.`)}if(!Q$(K))P1(`invalid config file "${$}": expected a JSON object.`);return K}function JB($){return $.option("--bot-token-env <VAR>","Telegram bot token, read from this environment variable").option("--bot-token-stdin","Telegram bot token, read from stdin")}function jB($){return JB($).option("--phone-number-id <id>","WhatsApp phone_number_id (see: niva channels whatsapp-numbers <connector_id>)").option("--allow-groups","Telegram: let the bot answer in groups").option("--session-timeout <minutes>","Chat session timeout in minutes (5-10080)").option("--file <path>","JSON file with the channel config object (- for stdin); flags override its keys")}async function YB($){if($.botTokenEnv!=null&&$.botTokenStdin===!0)P1("--bot-token-env and --bot-token-stdin are mutually exclusive.");if($.botTokenEnv!=null){let U=process.env[$.botTokenEnv];if(U==null||U==="")P1(`environment variable ${$.botTokenEnv} is not set or empty (--bot-token-env).`);return U}if($.botTokenStdin===!0)return(await v$()).replace(/\r?\n$/,"");return}async function HB($){if($.file==="-"&&$.botTokenStdin===!0)P1("--file - and --bot-token-stdin both read stdin; pass the token with --bot-token-env instead.");let U=$.file==null?{}:await pA($.file),K=await YB($);if(K!=null)U.bot_token=K;if($.phoneNumberId!=null)U.phone_number_id=$.phoneNumberId;if($.allowGroups===!0)U.allow_groups=!0;if($.sessionTimeout!=null)U.session_timeout_minutes=Number($.sessionTimeout);return Object.keys(U).length===0?void 0:U}function tA($){if($.visual_plan_id==null)return"-";return`${$.visual_plan_name??"?"} (${$.visual_plan_id})`}function aA($){if($.visual_plan_id==null)return;let U=$.visual_plan_published_version==null?"never published":"v"+$.visual_plan_published_version;return $.visual_plan_has_unpublished_changes?U+" (unpublished changes)":U}function sA($){let U=K$(GB($.config))??{},K=Object.entries(U).map(([q,Q])=>({label:q,value:typeof Q==="object"&&Q!==null?JSON.stringify(Q):String(Q)}));o([{title:`${$.name} (${$.id})`,rows:[{label:"Type",value:$.channel_type},{label:"Description",value:$.description},{label:"Identifier",value:$.identifier},{label:"Active",value:$.is_active?"yes":"no"},{label:"Plan",value:tA($)},{label:"Plan version",value:aA($)},{label:"Schedule",value:$.schedule_id==null?void 0:`${$.schedule_name??"?"} (${$.schedule_id})`},{label:"Connector",value:$.connector_id},{label:"Webhook URL",value:$.webhook_url},{label:"Calls (7d)",value:$.calls_7d?.total},{label:"Last call",value:$.last_call_at?.toISOString()},{label:"Created",value:$.created_at.toISOString()},{label:"Updated",value:$.updated_at.toISOString()}]},{title:"Config (credentials hidden)",rows:K.length>0?K:[{label:"(empty)",value:""}]}])}function YG($,U,K,q){if(K==="json"){let Q=jG($);P(q?O(Q,q):Q);return}T(`Channel ${U}: ${$.name} (${$.id})`)}function eA($){return $.readiness.ready?"ready":"not ready"}function $v($,U,K){$.command("list").description("List channels with type, plan, active state and 7-day call count; --alert shows the ones needing attention").option("--type <type>","Filter by channel type (sip, whatsapp, telegram)").option("--active","Only active channels").option("--inactive","Only inactive channels").option("--alert","Only channels with an alert: active with no plan, never-published plan, or failed WhatsApp webhook sync").option("--search <term>","Search by name").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(q)=>{if(q.active===!0&&q.inactive===!0)P1("--active and --inactive are mutually exclusive.");let{format:Q,fields:W}=L(U.opts()),G=await N(K().channels.list({page:Number(q.page),limit:Number(q.limit),...q.search!=null&&{search:q.search},...q.type!=null&&{channel_type:q.type},...q.active===!0&&{is_active:!0},...q.inactive===!0&&{is_active:!1},...q.alert===!0&&{alert:!0}})),j=G.items.map((Y)=>jG(Y));if(Q==="json"){P(W?j.map((Y)=>O(Y,W)):{...G,items:j});return}y(["ID","Type","Name","Identifier","Plan","Active","Calls 7d"],j.map((Y)=>({ID:Y.id,Type:Y.channel_type,Name:Y.name,Identifier:Y.identifier??"-",Plan:Y.visual_plan_name??"-",Active:Y.is_active?"yes":"no","Calls 7d":Y.calls_7d?.total??"-"}))),Z$(G)})}function Uv($,U,K){$.command("show <id>").description("Show a channel: plan, schedule, connector, webhook URL and config (credentials hidden)").action(async(q)=>{let{format:Q,fields:W}=L(U.opts()),G=await N(K().channels.getById({channel_id:_6(q)}));if(G==null)x(`Channel not found: ${q}`),process.exit(w.NOT_FOUND);if(Q==="json"){let j=jG(G);P(W?O(j,W):j);return}sA(G)})}function Qv($,U,K){let q=$.command("create <type>").description("Create a channel of type sip, whatsapp or telegram. WhatsApp needs --connector and --phone-number-id; Telegram needs a bot token (--bot-token-env or --bot-token-stdin).").requiredOption("--name <name>","Channel name").option("--description <text>","Channel description").option("--identifier <id>","Provider-facing identifier (e.g. the SIP number); unique within the organization").option("--connector <id>","WhatsApp: connector (conn_...) that owns the account").option("--plan <id>","Visual plan (vp_...) that answers on this channel").option("--schedule <id>","Schedule (sched_...) that gates when the channel is available").option("--inactive","Create the channel switched off");jB(q).action(async(Q,W)=>{let{format:G,fields:j}=L(U.opts()),Y=await HB(W),H={channel_type:P$(Q),name:W.name,...W.description!=null&&{description:W.description},...W.identifier!=null&&{identifier:W.identifier},...W.connector!=null&&{connector_id:GG(W.connector)},...W.plan!=null&&{visual_plan_id:JG(W.plan)},...W.schedule!=null&&{schedule_id:WB(W.schedule)},...W.inactive===!0&&{is_active:!1},...Y!=null&&{config:Y}},X=await N(K().channels.create(H));YG(X,"created",G,j)})}function Kv($,U,K){let q=$.command("update <id>").description("Change a channel: name, plan, schedule, connector or config (merged into the stored config). Moving a channel off a plan it already has needs --reassign.").option("--name <name>","New name").option("--description <text>","New description").option("--identifier <id>","New provider-facing identifier").option("--connector <id>","WhatsApp: connector (conn_...) that owns the account").option("--plan <id>","Attach this visual plan (vp_...)").option("--detach-plan","Detach the current plan").option("--schedule <id>","Attach this schedule (sched_...)").option("--detach-schedule","Detach the current schedule").option("--reassign","Allow moving the channel to another plan even when it already has one");jB(q).action(async(Q,W)=>{if(W.plan!=null&&W.detachPlan===!0)P1("--plan and --detach-plan are mutually exclusive.");if(W.schedule!=null&&W.detachSchedule===!0)P1("--schedule and --detach-schedule are mutually exclusive.");let{format:G,fields:j}=L(U.opts()),Y=await HB(W),H={channel_id:_6(Q),...W.name!=null&&{name:W.name},...W.description!=null&&{description:W.description},...W.identifier!=null&&{identifier:W.identifier},...W.connector!=null&&{connector_id:GG(W.connector)},...W.plan!=null&&{visual_plan_id:JG(W.plan)},...W.detachPlan===!0&&{visual_plan_id:null},...W.schedule!=null&&{schedule_id:WB(W.schedule)},...W.detachSchedule===!0&&{schedule_id:null},...W.reassign===!0&&{reassign:!0},...Y!=null&&{config:Y}};if(Object.keys(H).length===1)P1("nothing to update: pass at least one of --name, --plan, --schedule, --connector, --file, ...");let X=await N(K().channels.update(H));YG(X,"updated",G,j)})}function qv($,U,K){$.command("assign <id>").description("Point a channel at a visual plan so it answers with it; the plan must be published. Moving a channel off a plan it already has needs --reassign.").requiredOption("--plan <plan_id>","Visual plan (vp_...) to answer with").option("--reassign","Allow moving the channel to another plan even when it already has one").action(async(q,Q)=>{let{format:W,fields:G}=L(U.opts()),j=await N(K().channels.update({channel_id:_6(q),visual_plan_id:JG(Q.plan),...Q.reassign===!0&&{reassign:!0}}));YG(j,"assigned to plan "+Q.plan,W,G)})}function Wv($,U,K){for(let[q,Q]of[["enable",!0],["disable",!1]])$.command(`${q} <id>`).description(Q?"Switch a channel on so it answers calls and chats with its plan":"Switch a channel off; it stops answering until enabled again").action(async(W)=>{let{format:G}=L(U.opts());if(await N(K().channels.toggle({channel_id:_6(W),is_active:Q})),G==="json"){P({id:W,is_active:Q});return}T(`Channel ${Q?"enabled":"disabled"}: ${W}`)})}function Gv($,U,K){$.command("delete <id>").description("Delete a channel (needs --yes in a non-interactive shell)").action(async(q)=>{let{format:Q}=L(U.opts()),W=U.opts().yes===!0;if(await d$(`Delete channel ${q}?`,{yes:W}),await N(K().channels.delete({channel_id:_6(q)})),Q==="json"){P({id:q,deleted:!0});return}T(`Channel deleted: ${q}`)})}function Jv($,U,K){let q=$.command("test-connection").description("Check a Telegram bot token against Telegram without creating a channel; prints the bot username. Telegram is the only type the API accepts.");JB(q).action(async(Q)=>{let{format:W}=L(U.opts()),G=await YB(Q);if(G==null)P1("pass the bot token with --bot-token-env <VAR> or --bot-token-stdin.");let j=await N(K().channels.testConnection({channel_type:"telegram",config:{bot_token:G}}));if(W==="json")P(j);else if(j.ok)T("Telegram bot reachable"+(j.username==null?"":": @"+j.username));else x(`Telegram connection failed: ${j.error??"unknown error"}`);if(!j.ok)process.exit(w.GENERAL_ERROR)})}function jv($,U,K){$.command("setup-whatsapp-sip <id>").description("Configure WhatsApp calling (SIP) with Meta for a WhatsApp channel, so voice calls reach NIVA. Run it after the channel exists.").action(async(q)=>{let{format:Q}=L(U.opts());if(await N(K().channels.setupWhatsappSip({channel_id:_6(q)})),Q==="json"){P({id:q,ok:!0});return}T(`WhatsApp SIP configured for channel ${q}`)})}function Yv($,U,K){$.command("whatsapp-connectors").description("List the WhatsApp connectors a WhatsApp channel can use (id, name, status, account)").action(async()=>{let{format:q,fields:Q}=L(U.opts()),W=await N(K().channels.whatsappConnectors());if(q==="json"){P(Q?W.map((G)=>O(G,Q)):W);return}y(["ID","Name","Status","Account"],W.map((G)=>({ID:G.id,Name:G.name,Status:G.status,Account:G.account_label??"-"})))})}function Hv($,U,K){$.command("whatsapp-numbers <connector_id>").description("List the WhatsApp phone numbers of a connector with readiness and the bound channel; the ID column is the --phone-number-id for channels create").option("--refresh","Bypass the 5-minute cache and read the numbers again").action(async(q,Q)=>{let{format:W,fields:G}=L(U.opts()),j=await N(K().channels.whatsappNumbers({connector_id:GG(q),refresh:Q.refresh===!0}));if(W==="json"){P(G?j.map((Y)=>O(Y,G)):j);return}y(["ID","Number","Name","Readiness","Channel"],j.map((Y)=>({ID:Y.id,Number:Y.display_phone_number,Name:Y.verified_name,Readiness:eA(Y),Channel:Y.channel==null?"-":`${Y.channel.name} (${Y.channel.id})`})))})}var Xv=/unknown option '([^']*)'/;function Zv($){let U=Xv.exec($)?.[1];if(U==null)return $;let K=U.indexOf("=");if(K<0)return $;let q=U.slice(0,K),Q=$.replace(`'${U}'`,`'${q}=<redacted>'`);if(q!=="--bot-token")return Q;return`${Q}
|
|
89
|
+
Use --bot-token-env <VAR> or --bot-token-stdin for a credential instead of a literal value.`}function XB($,U){let K=$.createCommand("channels").description("Channels (SIP, WhatsApp, Telegram): the entry points a plan answers on");K.configureOutput({outputError:(q,Q)=>Q(Zv(q))}),$.addCommand(K),$v(K,$,U),Uv(K,$,U),Qv(K,$,U),Kv(K,$,U),qv(K,$,U),Wv(K,$,U),Gv(K,$,U),Jv(K,$,U),jv(K,$,U),Yv(K,$,U),Hv(K,$,U)}import{readFile as Nv}from"node:fs/promises";var T$=N1(I1(),1);async function t3($){R(`Connecting to ${$}`);let U=p8($)?{tls:{rejectUnauthorized:!1}}:void 0,K=new WebSocket($,U),q=!1;throw K.onopen=()=>{q=!0},K.onmessage=(Q)=>{let W=JSON.parse(typeof Q.data==="string"?Q.data:String(Q.data)),G=K$(W)??{},j=l(G.type)??"";switch(j){case"connected":console.log(T$.default.green(` Connected. Type a message and press Enter. Ctrl+C or /quit to exit.
|
|
90
|
+
`)),Pv(K);break;case"message":{let Y=K$(G.message)??{};for(let H of Dv(Y))console.log(H);break}case"typing":{if(G.active===!0)process.stdout.write(T$.default.dim(" bot is typing...\r"));else process.stdout.write(" \r");break}case"state":{if(G.status==="ended")console.log(T$.default.dim(`
|
|
91
|
+
Session ended.`)),process.exit(0);break}case"error":console.log(T$.default.red(` error: [${String(G.code)}] ${String(G.message)}`));break;case"pong":break;case"replay":{let Y=Array.isArray(G.messages)?G.messages:[];if(Y.length>0)R(` Replayed ${Y.length} missed message(s)`);break}default:console.log(T$.default.dim(` [${j}] ${JSON.stringify(G)}`))}},K.onclose=(Q)=>{if(q)R(`
|
|
92
|
+
Disconnected (code=${Q.code})`);else x("Failed to connect");process.exit(q?0:1)},K.onerror=()=>{x("WebSocket error"),process.exit(1)},await new Promise(()=>{}),Error("unreachable")}function I6($,U){return $.replace(/^http/,"ws")+U}var x4=T$.default.cyan(" bot");function Bv($,U){let K=[`${x4} ${$}`];for(let q of A$(U.buttons)){let Q=T$.default.dim(`[${String(q.id)}]`);K.push(` ${Q} ${String(q.label)}`)}return K}function Vv($,U){let K=[`${x4} ${$}`];for(let q of A$(U.sections)){K.push(` ${T$.default.bold(String(q.title))}`);for(let Q of A$(q.items)){let W=T$.default.dim(`[${String(Q.id)}]`);K.push(` ${W} ${String(Q.title)}`)}}return K}function Mv($){return A$($.cards).map((U)=>{let K=l(U.description),q=K!=null?` — ${K}`:"";return`${x4} ${T$.default.bold(String(U.title))}${q}`})}function Dv($){let U=l($.type)??"",K=l($.text)??"";switch(U){case"text":return[`${x4} ${K}`];case"buttons":return Bv(K,$);case"list":return Vv(K,$);case"media":{let q=T$.default.dim(`[${String($.mediaType)}]`),Q=typeof $.caption==="string"?` — ${$.caption}`:"";return[`${x4} ${q} ${String($.url)}${Q}`]}case"location":{let q=typeof $.label==="string"?` (${$.label})`:"";return[`${x4} ${T$.default.dim("[location]")} ${String($.lat)},${String($.lng)}${q}`]}case"carousel":return Mv($);default:{let q=T$.default.dim(`[${U}]`);return[`${x4} ${q} ${JSON.stringify($)}`]}}}function Pv($){let U=process.stdin;U.setEncoding("utf-8"),U.resume();let K="";U.on("data",(q)=>{K+=q;let Q=K.split(`
|
|
93
|
+
`);K=Q.pop();for(let W of Q){let G=W.trim();if(G==="")continue;if(G==="/ping"){$.send(JSON.stringify({type:"ping"})),R(" → ping");continue}if(G==="/quit"||G==="/exit"){$.close();return}console.log(`${T$.default.blue(" you")} ${G}`),$.send(JSON.stringify({type:"message",message:{type:"text",text:G}}))}}),process.once("SIGINT",()=>{R(`
|
|
94
|
+
Closing...`),$.close()})}function ZB($,U,K){let q=$.command("chat").description("Test chat — interactive session against a visual plan (draft or published)");q.command("test <plan_id>").description("Start a test chat session for a plan. Tests the published draft by default.").option("--editor-state <file>","Path to a JSON file with an unpublished editorState to test").action(async(Q,W)=>{let G=t1($.opts()),j=K(),Y;if(W.editorState!=null){let X=await Nv(W.editorState,"utf-8");Y=JSON.parse(X)}if(G!=="json")R("Creating test chat session...");let H=await N(U().testChat.createSession({planId:A("visual_plans",Q),editor_state:Y}));if(G==="json"){P({...H,ws_url:I6(j.url,H.wsUrl)});return}T(`Session created: ${H.sessionId}`),await t3(I6(j.url,H.wsUrl))}),q.command("stop <sessionId>").description("Stop an active test chat session").action(async(Q)=>{let W=t1($.opts());if(await N(U().testChat.stop({sessionId:Q})),W==="json"){P({session_id:Q,stopped:!0});return}T(`Session ${Q} stopped.`)})}function BB($){let U=$.command("config").description("Manage CLI configuration");U.command("set <key> <value>").description("Set a config value (url, api-key)").action((K,q)=>{Jj(K==="api-key"?"apiKey":K,q),T(`Set ${K} = ${q}`)}),U.command("get <key>").description("Get a config value (url, api-key)").action((K)=>{let q=K==="api-key"?"apiKey":K,W=r8()[q];if(W==null){R(`(${K} not set)`);return}console.log(typeof W==="string"?W:JSON.stringify(W))}),U.command("show").description("Show current configuration").action(()=>{let K=r8();P(K)})}var HG={"channel.whatsapp":{consumers:["channel"]},"whatsapp.templates":{consumers:["node"]},"sms.send":{consumers:["node","notification"]},"email.send":{consumers:["node","notification"]},"tools.catalog":{consumers:["node","mcp"]},"calendar.events":{consumers:["node"]},"voice.agent":{consumers:["node"]},"phone.lookup":{consumers:["node","mcp"]},"verify.otp":{consumers:["node","mcp"]}};function VB($){return Object.hasOwn(HG,$)}var Lv=Object.keys(HG).filter(($)=>VB($));class XG{#$;constructor($){this.#$=$}static of($){return new XG($)}reveal(){return this.#$}toString(){return"[redacted]"}toJSON(){return"[redacted]"}[Symbol.for("nodejs.util.inspect.custom")](){return"[redacted]"}}function Iv($){return $.secret===!0}function W1($){let U={},K={},q={};for(let[Q,W]of Object.entries($.fields)){let G=W.secret===!0?J.string().min(1):W.schema,j=W.optional===!0?G.optional():G;if(U[Q]=j,Iv(W))q[Q]=j;else K[Q]=j}return{...$,fieldsSchema:J.object(U),configSchema:J.object(K),credentialsSchema:J.object(q)}}var ZG=W1({kind:"elevenlabs",version:1,nameKey:"connectors.kinds.elevenlabs.name",descriptionKey:"connectors.kinds.elevenlabs.description",icon:"elevenlabs",category:"telephony",module:"ai",docsPath:"/configuracoes/conectores-elevenlabs",auth:{strategy:"fields"},fields:{api_key:{secret:!0,step:"api_key"},agent_numbers:{schema:J.string().default("{}"),step:"numbers"}},setup:[{id:"api_key",titleKey:"connectors.kinds.elevenlabs.setup.api_key"},{id:"numbers",titleKey:"connectors.kinds.elevenlabs.setup.numbers"}],provides:["voice.agent"]});var BG=W1({kind:"retell",version:1,nameKey:"connectors.kinds.retell.name",descriptionKey:"connectors.kinds.retell.description",icon:"retell",category:"telephony",module:"ai",docsPath:"/configuracoes/conectores-retell",auth:{strategy:"fields"},fields:{api_key:{secret:!0,step:"api_key"}},setup:[{id:"api_key",titleKey:"connectors.kinds.retell.setup.api_key"}],provides:["voice.agent"]});var VG=W1({kind:"twilio",version:1,nameKey:"connectors.kinds.twilio.name",descriptionKey:"connectors.kinds.twilio.description",icon:"twilio",category:"telephony",module:"omnichannel",docsPath:"/configuracoes/conectores-twilio",auth:{strategy:"fields"},fields:{account_sid:{schema:J.string().regex(/^AC[0-9a-fA-F]{32}$/u),step:"credentials"},api_key_sid:{schema:J.string().regex(/^SK[0-9a-fA-F]{32}$/u),step:"credentials"},api_key_secret:{secret:!0,step:"credentials"},default_sender:{schema:J.string().regex(/^(MG[0-9a-fA-F]{32}|\+[1-9]\d{6,14})$/u),step:"senders",discover:"senders",optional:!0}},identity:"account_sid",discoverKeys:["verify_services"],setup:[{id:"credentials",titleKey:"connectors.kinds.twilio.setup.credentials",url:"https://console.twilio.com/"},{id:"senders",titleKey:"connectors.kinds.twilio.setup.senders"}],provides:["sms.send","phone.lookup","verify.otp"]});var MB=["us","eu"],MG=W1({kind:"vapi",version:1,nameKey:"connectors.kinds.vapi.name",descriptionKey:"connectors.kinds.vapi.description",icon:"vapi",category:"telephony",module:"ai",docsPath:"/configuracoes/conectores-vapi",auth:{strategy:"fields"},fields:{api_key:{secret:!0,step:"api_key"},region:{schema:J.enum(MB).default("us"),step:"region"}},setup:[{id:"api_key",titleKey:"connectors.kinds.vapi.setup.api_key"},{id:"region",titleKey:"connectors.kinds.vapi.setup.region"}],provides:["voice.agent"],webhook:{verification:"none",signature:"shared_secret_header"}});var DG=W1({kind:"whatsapp_business",version:1,nameKey:"connectors.kinds.whatsapp_business.name",descriptionKey:"connectors.kinds.whatsapp_business.description",icon:"whatsapp",category:"messaging",module:"omnichannel",docsPath:"/configuracoes/conectores-whatsapp",auth:{strategy:"fields"},fields:{app_id:{schema:J.string().regex(/^\d+$/),step:"meta_app"},app_secret:{secret:!0,step:"meta_app"},access_token:{secret:!0,step:"system_user"},waba_id:{schema:J.string().regex(/^\d+$/),step:"waba",discover:"wabas"},business_id:{schema:J.string().regex(/^\d+$/),step:"waba",optional:!0}},identity:"waba_id",setup:[{id:"meta_app",titleKey:"connectors.kinds.whatsapp_business.setup.meta_app",url:"https://developers.facebook.com/apps"},{id:"system_user",titleKey:"connectors.kinds.whatsapp_business.setup.system_user",url:"https://business.facebook.com/settings/system-users"},{id:"waba",titleKey:"connectors.kinds.whatsapp_business.setup.waba"}],provides:["channel.whatsapp","whatsapp.templates"],webhook:{verification:"meta_hub_challenge",signature:"meta_hmac_sha256"}});var i1={whatsapp_business:DG,twilio:VG,elevenlabs:ZG,retell:BG,vapi:MG};function w0($){return Object.hasOwn(i1,$)}var A0=Object.keys(i1).filter(($)=>w0($));function xv($){return $.replaceAll("_","-")}function PG($){return $.replaceAll(/_([a-z0-9])/g,(U,K)=>K.toUpperCase())}function w4($){let[U]=$.cli.split(" ");return U??$.cli}function wv($,U){let K=xv($);if(U.secret===!0)return[{source:"stdin",key:`${PG($)}Stdin`,cli:`--${K}-stdin`},{source:"env",key:`${PG($)}Env`,cli:`--${K}-env <VAR>`}];return[{source:"value",key:PG($),cli:`--${K} <value>`}]}function F6($){let U=i1[$].fields;return Object.entries(U).map(([K,q])=>({field:K,secret:q.secret===!0,optional:q.optional===!0,step:q.step,discover:"discover"in q?q.discover:void 0,options:wv(K,q)}))}function v0(){return A0.flatMap(($)=>F6($))}function NG($,U){let K=$[U.key];if(K===void 0||K===!1)return!1;return U.source==="value"||K!==""}function DB($){return v0().some((U)=>U.options.some((K)=>NG($,K)))}function PB($,U){let K=new Set(F6(U).flatMap((W)=>W.options.map((G)=>G.key))),q=new Set,Q=[];for(let W of v0())for(let G of W.options){if(K.has(G.key)||q.has(G.key))continue;if(q.add(G.key),NG($,G))Q.push(w4(G))}return Q}function NB($){return F6($).flatMap((U)=>U.options.map((K)=>w4(K)))}function LB($,U){let K=[];for(let q of F6(U))for(let Q of q.options){if(!NG($,Q))continue;K.push({flag:q,option:Q,source:Q.source,raw:Q.source==="stdin"?"":String($[Q.key])})}return K}function _B(){let $=new Set,U=[];for(let K of v0())for(let q of K.options){if($.has(q.key))continue;$.add(q.key);let Q=K.secret?"credential":"field";U.push({cli:q.cli,description:`${Q} "${K.field}" (step "${K.step}")`})}return U}var k0;function s$($){x(`Error: ${$}`),process.exit(w.USAGE_ERROR)}function a3($){if(!w0($))s$(`unknown connector kind "${$}". Known kinds: ${A0.join(", ")}.`);return $}function u$($){return A("connectors",$)}function Av($){return $.split("_").map((U)=>U.charAt(0).toUpperCase()+U.slice(1)).join(" ")}function vv(){let $=new Set(["--pin"]);for(let U of v0())if(U.secret)$.add(`--${U.field.replaceAll("_","-")}`);return $}var kv=/unknown option '([^']*)'/;function zv($){let U=kv.exec($)?.[1];if(U==null)return $;let K=U.indexOf("=");if(K<0)return $;let q=U.slice(0,K),Q=$.replace(`'${U}'`,`'${q}=<redacted>'`);if(!vv().has(q))return Q;return`${Q}
|
|
95
|
+
Use ${q}-env <VAR> or ${q}-stdin for a credential instead of a literal value.`}function Rv($){return $===""?"-":`···${$}`}function bv($,U){let K=i1[$].setup.find((q)=>q.id===U);return K!=null&&"url"in K?K.url:void 0}function LG($){for(let U of _B())$.option(U.cli,U.description)}function _G($,U){let K=PB($,U);if(K.length>0)s$(`${K.join(", ")} is not a field of ${U}. Valid flags: ${NB(U).join(", ")}.`)}async function Ov($){if($.source==="value")return $.raw;if($.source==="env"){let U=process.env[$.raw];if(U==null||U==="")s$(`environment variable ${$.raw} is not set or empty (${w4($.option)}).`);return U}return(await v$()).replace(/\r?\n$/,"")}async function IG($,U){let K=LB($,U),q=new Map;for(let G of K){let j=q.get(G.flag.field);if(j==null)q.set(G.flag.field,[G]);else j.push(G)}for(let[G,j]of q)if(j.length>1)s$(`multiple flags provide "${G}": ${j.map((Y)=>w4(Y.option)).join(", ")}. Pass only one.`);let Q=K.filter((G)=>G.source==="stdin");if(Q.length>1)s$(`at most one field may read from stdin per invocation: ${Q.map((G)=>w4(G.option)).join(", ")}.`);let W={};for(let G of K)W[G.flag.field]=await Ov(G);return W}function Tv($){return $.options.map(w4).join(" or ")}async function Sv($,U,K,q){let Q=bv($,U.step),W=Q==null?`${U.field} (${U.step})`:`${U.field} (${U.step}: ${Q})`;if(U.discover!=null){let G=await N(q().connectors.discover({kind:$,key:U.discover,fields:{...K}})),j=G.length===1?G[0]:void 0;if(j!=null)return z4(`Using the only ${U.field}: ${j.label} (${j.value})`),j.value;if(G.length>1){let Y=G.map((H)=>({label:H.description==null?H.label:`${H.label} - ${H.description}`,value:H.value}));return c0(W,Y,k0==null?{output:process.stderr}:{ask:k0,output:process.stderr})}}if(U.secret)return R8(`${W}: `,k0);return bJ(`${W}: `,k0)}async function Cv($,U,K){let q=[];for(let Q of F6($)){if(U[Q.field]!=null||Q.optional)continue;if(!R6()){q.push(Q);continue}U[Q.field]=await Sv($,Q,U,K)}if(q.length>0)s$(`missing required field(s): ${q.map((Q)=>Tv(Q)).join(", ")}.`);return U}function Ev($,U){if(!b1($))Q1($);let K=s1($);if(U==="json")P({error:K.code,message:K.message,data:K.data,hint:K.hint,retryable:K.retryable});else if(e1(K),K.code==="CONNECTOR_TEST_FAILED")uv(A$(K.data?.checks));process.exit(K.exitCode)}async function FG($,U){try{return await $}catch(K){Ev(K,U)}}function yv($,U){if(!b1($))Q1($);let K=s1($);if(K.code!=="CONNECTOR_IN_USE")Q1($);let q=A$(K.data?.channels).map((Q)=>({id:l(Q.id)??"",name:l(Q.name)??""}));if(U==="json")P({error:K.code,message:K.message,channels:q,hint:K.hint,retryable:K.retryable});else e1(K),y(["Channel ID","Name"],q.map((Q)=>({"Channel ID":Q.id,Name:Q.name})));process.exit(K.exitCode)}function gv($){return $.map((U)=>({Check:U.id,OK:U.ok?"yes":"no",Message:U.message??""}))}function uv($){y(["Check","OK","Message"],$.map((U)=>({Check:l(U.id)??"",OK:U.ok===!0?"yes":"no",Message:l(U.message)??""})))}function fv($){if($.ready)return"ready";let U=[];if(!$.verified)U.push("not verified");if(!$.registered)U.push("not registered");if(!$.name_approved)U.push("name pending");return U.join(", ")}function mv($){let U=[{title:"Connector",rows:[{label:"ID",value:$.id},{label:"Name",value:$.name},{label:"Kind",value:$.kind},{label:"Status",value:$.status},{label:"Account",value:$.account_label},{label:"External ID",value:$.external_id},{label:"Created",value:new Date($.created_at).toLocaleString()},{label:"Updated",value:new Date($.updated_at).toLocaleString()},{label:"Last checked",value:$.last_checked_at==null?null:new Date($.last_checked_at).toLocaleString()},{label:"Last error",value:$.last_error==null?null:`${$.last_error.code}: ${$.last_error.message}`}]},{title:"Config",rows:Object.entries($.config).map(([K,q])=>({label:K,value:q}))},{title:"Credentials",rows:Object.entries($.secret_suffixes).map(([K,q])=>({label:K,value:Rv(q)}))},{title:"Webhook",rows:[{label:"URL",value:$.webhook.url},{label:"Verify token",value:$.webhook.verify_token==null?null:"configured"},{label:"Verified at",value:$.webhook.verified_at==null?null:new Date($.webhook.verified_at).toLocaleString()}]}];if($.channels.length>0)U.push({title:"Channels",rows:$.channels.map((K)=>({label:K.name,value:`${K.channel_type} (${K.id})`}))});return U}function hv($,U){let K={...$,webhook:{url:$.webhook.url,verify_token_configured:$.webhook.verify_token!=null,verified_at:$.webhook.verified_at}};return U?O(K,U):K}function cv($,U){let K={...$,webhook:$.webhook===null?null:{status:$.webhook.status,reason:$.webhook.reason,url:$.webhook.url}};return U?O(K,U):K}function lv($){if($===null)return;if($.status==="subscribed"){z4("Webhook subscribed automatically.");return}let U=$.reason==null?"":` (${$.reason})`;if(z4(`Webhook needs manual setup${U}.`),$.url!=null)z4(` URL: ${$.url}`);z4(" Verify token: see the connector's page in the web app (never printed here).")}function rv($){let U=K$($.properties)??{},K=new Set(Array.isArray($.required)?$.required.filter((q)=>typeof q==="string"):[]);return Object.entries(U).map(([q,Q])=>{let W=K$(Q)??{},G=W["x-niva-secret"]===!0||W.writeOnly===!0;return{name:q,access:G?"secret":"public",required:K.has(q),step:l(W["x-niva-step"])??""}})}function iv($,U,K){$.command("types").description("List connector types, or describe one kind's fields and setup steps").action(async()=>{let{format:Q,fields:W}=L(U.opts()),G=await N(K().connectors.types.list());if(Q==="json"){P(W?G.map((j)=>O(j,W)):G);return}y(["Kind","Name","Capabilities"],G.map((j)=>({Kind:j.kind,Name:Av(j.kind),Capabilities:j.provides.join(", ")})))}).command("describe <kind>").description("Show a kind's fields (public/secret, required) and setup steps with their URLs").action(async(Q)=>{let{format:W,fields:G}=L(U.opts()),j=a3(Q),Y=await N(K().connectors.types.describe({kind:j}));if(W==="json"){P(G?O(Y,G):Y);return}o([{title:"Type",rows:[{label:"Kind",value:Y.kind},{label:"Version",value:Y.version},{label:"Auth",value:Y.auth_strategy},{label:"Category",value:Y.category},{label:"Module",value:Y.module},{label:"Docs",value:Y.docs_path},{label:"Provides",value:Y.provides.join(", ")},{label:"Discover",value:Y.discover.join(", ")||"-"}]}]),y(["Field","Access","Required","Step"],rv(Y.fields_json_schema).map((H)=>({Field:H.name,Access:H.access,Required:H.required?"yes":"no",Step:H.step}))),y(["Setup step","Title","URL"],Y.setup.map((H)=>({"Setup step":H.id,Title:H.title_key,URL:H.url??"-"})))})}function dv($,U,K){$.command("list").description("List connectors with their kind, status, account and channel count").action(async()=>{let{format:q,fields:Q}=L(U.opts()),W=await N(K().connectors.list());if(q==="json"){P(Q?W.map((G)=>O(G,Q)):W);return}y(["ID","Name","Kind","Status","Account","Channels"],W.map((G)=>({ID:G.id,Name:G.name,Kind:G.kind,Status:G.status,Account:G.account_label??"-",Channels:G.channel_count})))})}function ov($,U,K){$.command("show <id>").description("Show a connector's details, credentials suffixes and webhook status").action(async(q)=>{let{format:Q,fields:W}=L(U.opts()),G=await N(K().connectors.get({connector_id:u$(q)}));if(Q==="json"){P(hv(G,W));return}o(mv(G))})}function nv($){if($===void 0)return"-";return $?"yes":"no"}function pv($,U,K){let q=$.command("agents").description("Voice agents of a connector: list them, activate or deactivate an ElevenLabs agent's number");q.command("list <id>",{isDefault:!0}).description("List the voice agents of a connector that provides voice.agent; Ready says whether an activated agent can take calls").action(async(Q)=>{let{format:W,fields:G}=L(U.opts()),j=await N(K().connectors.voiceAgents({connector_id:u$(Q)}));if(W==="json"){P(G?{agents:j.agents.map((Y)=>O(Y,G))}:j);return}y(["ID","Name","Channel","Ready","Updated"],j.agents.map((Y)=>({ID:Y.id,Name:Y.name,Channel:Y.channel,Ready:nv(Y.ready),Updated:Y.updated_at?.toISOString()??"-"})))});for(let[Q,W]of[["activate",!1],["deactivate",!0]])q.command(`${Q} <id> <agent_id>`).description(W?"Deactivate an ElevenLabs agent: NIVA removes the SIP number it registered for the agent. Plans can no longer call it.":"Activate an ElevenLabs agent: NIVA registers a SIP number on the account and binds it to the agent. Needed before a plan can call it.").action(async(G,j)=>{let{format:Y,fields:H}=L(U.opts()),X=await FG(K().connectors.agentNumbers.set({connector_id:u$(G),agent_id:j,remove:W}),Y);if(Y==="json"){P(H?O(X,H):X);return}T(`Agent ${j} ${W?"deactivated":"activated"} on connector ${X.name} (${X.id})`)})}function tv($,U,K){$.command("senders <id>").description("List the SMS senders (Messaging Services and numbers) of a connector that provides sms.send").action(async(q)=>{let{format:Q,fields:W}=L(U.opts()),G=await N(K().connectors.senders.list({connector_id:u$(q)}));if(Q==="json"){P(W?G.map((j)=>O(j,W)):G);return}y(["ID","Label","Kind","Number","SMS","Brazil"],G.map((j)=>({ID:j.id,Label:j.label,Kind:j.kind==="messaging_service"?"Messaging Service":"Number",Number:j.number??"-",SMS:j.capabilities.sms?"yes":"no",Brazil:j.brazil_p2p_only?"p2p only":"-"})))})}function av($,U,K){$.command("verify-services <id>").description("List the Twilio Verify Services of a connector that provides verify.otp").action(async(q)=>{let{format:Q,fields:W}=L(U.opts()),G=await N(K().connectors.verifyServices.list({connector_id:u$(q)}));if(Q==="json"){P(W?G.map((j)=>O(j,W)):G);return}y(["SID","Name","Code length","Channels"],G.map((j)=>({SID:j.sid,Name:j.friendly_name,"Code length":j.code_length??"-",Channels:j.channels.join(", ")})))})}function sv($,U,K){$.command("test <id>").description("Run a connector's health test; exits 1 when any check fails").action(async(q)=>{let{format:Q,fields:W}=L(U.opts()),G=await N(K().connectors.test({connector_id:u$(q)}));if(Q==="json")P(W?O(G,W):G);else if(y(["Check","OK","Message"],gv(G.health.checks)),G.health.ok)T(`Connector test passed: ${G.status}`);else x(`Connector test failed: ${G.health.code} - ${G.health.message}`);if(!G.health.ok)process.exit(w.GENERAL_ERROR)})}function ev($,U,K){let q=$.command("discover <kind> <key>").description("Run a kind's discover function with credentials not yet stored (e.g. wabas)");LG(q),q.action(async(Q,W,G)=>{let j=a3(Q);_G(G,j);let{format:Y,fields:H}=L(U.opts()),X=await IG(G,j),B=await N(K().connectors.discover({kind:j,key:W,fields:X}));if(Y==="json"){P(H?B.map((M)=>O(M,H)):B);return}y(["Value","Label","Description"],B.map((M)=>({Value:M.value,Label:M.label,Description:M.description??"-"})))})}function $k($,U,K){let q=$.command("create <kind>").description("Create a connector; credentials come from --<field>-env/--<field>-stdin or a hidden prompt").requiredOption("--name <name>","Human label shown in the UI");LG(q),q.action(async(Q,W)=>{let G=a3(Q);_G(W,G);let{format:j,fields:Y}=L(U.opts()),H=await IG(W,G),X=await Cv(G,H,K),B=await FG(K().connectors.create({kind:G,name:W.name,fields:X}),j);if(j==="json"){P(cv(B,Y));return}T(`Connector created: ${B.name} (${B.id})`),lv(B.webhook)})}function Uk($,U,K){let q=$.command("update <id>").description("Rename a connector or rotate fields; only the flags given are sent").option("--name <name>","New human label");LG(q),q.action(async(Q,W)=>{let{format:G,fields:j}=L(U.opts()),Y={connector_id:u$(Q)};if(W.name!=null)Y.name=W.name;if(DB(W)){let X=await N(K().connectors.get({connector_id:u$(Q)})),B=a3(X.kind);_G(W,B),Y.fields=await IG(W,B)}let H=await FG(K().connectors.update(Y),G);if(G==="json"){P(j?O(H,j):H);return}T(`Connector updated: ${H.name} (${H.id})`)})}function Qk($,U,K){for(let[q,Q]of[["enable",!0],["disable",!1]])$.command(`${q} <id>`).description(`${Q?"Enable":"Disable"} a connector`).action(async(W)=>{let{format:G,fields:j}=L(U.opts()),Y=await N(K().connectors.setEnabled({connector_id:u$(W),enabled:Q}));if(G==="json"){P(j?O(Y,j):Y);return}T(`Connector ${Q?"enabled":"disabled"}: ${Y.name} (${Y.status})`)})}function Kk($,U,K){$.command("delete <id>").description("Delete a connector; blocked and explained when a channel still references it").action(async(q)=>{let{format:Q}=L(U.opts()),W=U.opts().yes===!0;await d$(`Delete connector ${q}?`,{yes:W});try{await K().connectors.delete({connector_id:u$(q)})}catch(G){yv(G,Q)}if(Q==="json"){P({id:q,deleted:!0});return}T(`Connector deleted: ${q}`)})}function qk($,U,K){let q=$.command("numbers <id>").description("WhatsApp phone numbers of a connector, with readiness and the bound channel").option("--refresh","Bypass the 5-minute cache and read the numbers again");q.action(async(Q,W)=>{let{format:G,fields:j}=L(U.opts()),Y=await N(K().connectors.phoneNumbers.list({connector_id:u$(Q),refresh:W.refresh===!0}));if(G==="json"){P(j?Y.map((H)=>O(H,j)):Y);return}y(["ID","Number","Name","Readiness","Channel"],Y.map((H)=>({ID:H.id,Number:H.display_phone_number,Name:H.verified_name,Readiness:fv(H.readiness),Channel:H.channel==null?"-":H.channel.name})))}),q.command("request-code <id> <phone_number_id>").description("Ask Meta to send the phone number's ownership code by SMS or voice").requiredOption("--method <method>","sms or voice").option("--language <language>","Language for the message","pt_BR").action(async(Q,W,G)=>{let j=Wk(G.method),{format:Y}=L(U.opts());if(await N(K().connectors.phoneNumbers.requestCode({connector_id:u$(Q),phone_number_id:W,method:j,language:G.language})),Y==="json"){P({success:!0,phone_number_id:W});return}T(`Verification code requested for ${W} by ${G.method}.`)}),q.command("verify <id> <phone_number_id>").description("Submit the 6-digit ownership code Meta sent").requiredOption("--code <code>","The 6-digit code").action(async(Q,W,G)=>{if(!/^\d{6}$/u.test(G.code))s$("--code must be the 6-digit code Meta sent.");let{format:j}=L(U.opts());if(await N(K().connectors.phoneNumbers.verifyCode({connector_id:u$(Q),phone_number_id:W,code:G.code})),j==="json"){P({success:!0,phone_number_id:W});return}T(`Phone number verified: ${W}`)}),q.command("register <id> <phone_number_id>").description("Register a phone number on the Cloud API with its 6-digit PIN").option("--pin-stdin","Read the PIN from stdin").option("--pin-env <VAR>","Read the PIN from an environment variable").action(async(Q,W,G)=>{let j=await Jk(G),{format:Y}=L(U.opts());if(await N(K().connectors.phoneNumbers.register({connector_id:u$(Q),phone_number_id:W,pin:j})),Y==="json"){P({success:!0,phone_number_id:W});return}T(`Phone number registered: ${W}`)})}function Wk($){let U=$.toUpperCase();if(U==="SMS"||U==="VOICE")return U;s$(`--method must be sms or voice (got "${$}").`)}async function Gk($){if($.pinEnv!=null){let U=process.env[$.pinEnv];if(U==null||U==="")s$(`environment variable ${$.pinEnv} is not set or empty.`);return U}if($.pinStdin===!0)return(await v$()).replace(/\r?\n$/,"");if(R6())return R8("WhatsApp registration PIN (6 digits): ",k0);s$("no PIN given - pass --pin-env <VAR>, --pin-stdin, or run from a TTY.")}async function Jk($){if($.pinStdin===!0&&$.pinEnv!=null)s$("--pin-stdin and --pin-env are mutually exclusive.");let U=await Gk($);if(!/^\d{6}$/u.test(U))s$("the PIN must be the 6-digit number Meta gave you.");return U}function IB($,U){let K=$.createCommand("connectors").description("Connectors (WhatsApp, and the kinds that follow)");K.configureOutput({outputError:(q,Q)=>Q(zv(q))}),$.addCommand(K),iv(K,$,U),dv(K,$,U),ov(K,$,U),pv(K,$,U),tv(K,$,U),av(K,$,U),sv(K,$,U),ev(K,$,U),$k(K,$,U),Uk(K,$,U),Qk(K,$,U),Kk(K,$,U),qk(K,$,U)}var G1=N1(I1(),1);function z0($){return $.option("--from <date>","Start date (YYYY-MM-DD or ISO 8601)").option("--to <date>","End date (YYYY-MM-DD or ISO 8601)").option("--plan <id>","Filter by visual plan ID").option("--phone <id>","Filter by phone number ID")}function jk($){if($==null)return"";if($.missed>0)return`${$.total} (${$.missed} missed)`;return`${$.total}`}function Yk($,U){if($>U)return"↑";if($<U)return"↓";return"→"}function Hk($){let U=$.avg_score!=null?Number($.avg_score):null,K=$.previous_avg_score!=null?Number($.previous_avg_score):null,q=U!=null&&U>0?"+":"",Q=U!=null?`${q}${U.toFixed(2)}`:"—",W="";if(K!=null&&U!=null){let G=Yk(U,K);W=` (prev: ${K>0?"+":""}${K.toFixed(2)} ${G})`}return` Avg Score: ${Q}${W}`}function FB($,U){let K=$.command("dashboard").description("Dashboard and monitoring");K.command("metrics").description("Get call metrics for a date range").option("--from <date>","Start date (YYYY-MM-DD or ISO 8601)").option("--to <date>","End date (YYYY-MM-DD or ISO 8601)").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),{date_from:G,date_to:j}=J1(q),Y=await N(U().dashboard.metrics({date_from:G,date_to:j}));if(Q==="json"){let H=W?O(Y,W):Y;P(H);return}if(console.log(`Period: ${G} → ${j}`),console.log(`Total calls: ${Y.current.total_calls}`),console.log(`Answered: ${Y.current.answered}`),console.log(`Missed: ${Y.current.missed}`),Y.current.avg_duration_ms!=null)console.log(`Avg duration: ${f$(Y.current.avg_duration_ms)}`)}),z0(K.command("sentiment").description("Show sentiment distribution for calls")).action(async(q)=>{let{format:Q,fields:W}=L($.opts()),{date_from:G,date_to:j}=J1(q),Y=await N(U().dashboard.speechSentiment({date_from:G,date_to:j,visual_plan_id:A("visual_plans",q.plan),channel_id:A("channels",q.phone)}));if(Q==="json"){let B=W?O(Y,W):Y;P(B);return}if(console.log(G1.default.bold("Sentiment Overview")),console.log(`Analyzed: ${Y.analyzed_count} calls`),!Y.has_enough_data){R(`
|
|
96
|
+
Not enough data (need ${Y.minimum_required}, have ${Y.analyzed_count})`);return}console.log("");let H=Y.distribution,X=Math.max(H.positive,H.neutral,H.negative,H.mixed);U1(G1.default.green("positive"),H.positive,X),U1(G1.default.yellow("neutral"),H.neutral,X),U1(G1.default.red("negative"),H.negative,X),U1(G1.default.blue("mixed"),H.mixed,X),console.log(""),console.log(Hk(Y))}),z0(K.command("topics").description("Show top discussed topics from call transcriptions")).option("--limit <n>","Max topics to show","15").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),{date_from:G,date_to:j}=J1(q),Y=await N(U().dashboard.speechTopics({date_from:G,date_to:j,limit:Number(q.limit),visual_plan_id:A("visual_plans",q.plan),channel_id:A("channels",q.phone)}));if(Q==="json"){let X=W?O(Y,W):Y;P(X);return}if(console.log(`${G1.default.bold("Top Topics")} (${Y.analyzed_count} analyzed)`),!Y.has_enough_data||Y.topics.length===0){R(`
|
|
97
|
+
Not enough data.`);return}console.log("");let H=Math.max(...Y.topics.map((X)=>X.call_count));for(let X of Y.topics){let B=Y.analyzed_count>0?Math.round(X.call_count/Y.analyzed_count*100):0,M=a1(X.call_count,H);console.log(` ${X.label.padEnd(16)} ${M} ${X.call_count} calls (${B}%) confidence: ${X.avg_confidence.toFixed(2)}`)}}),z0(K.command("intents").description("Show detected intents from call transcriptions")).option("--limit <n>","Max intents to show","10").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),{date_from:G,date_to:j}=J1(q),Y=await N(U().dashboard.speechIntents({date_from:G,date_to:j,limit:Number(q.limit),visual_plan_id:A("visual_plans",q.plan),channel_id:A("channels",q.phone)}));if(Q==="json"){let X=W?O(Y,W):Y;P(X);return}if(console.log(`${G1.default.bold("Detected Intents")} (${Y.analyzed_count} analyzed)`),!Y.has_enough_data||Y.intents.length===0){R(`
|
|
98
|
+
Not enough data.`);return}console.log("");let H=Math.max(...Y.intents.map((X)=>X.call_count));for(let X of Y.intents)U1(X.label,X.call_count,H)}),z0(K.command("trend").description("Show sentiment trend over time")).option("--granularity <g>","Granularity: hour or day","day").action(async(q)=>{let{format:Q}=L($.opts()),{date_from:W,date_to:G}=J1(q,7),j=await N(U().dashboard.speechSentimentTrend({date_from:W,date_to:G,granularity:P$(q.granularity),visual_plan_id:A("visual_plans",q.plan),channel_id:A("channels",q.phone)}));if(Q==="json"){P(j);return}if(console.log(G1.default.bold("Sentiment Trend")),j.length===0){R(`
|
|
99
|
+
No data available.`);return}console.log(""),y(["Date","Analyzed","Positive","Neutral","Negative","Avg Score"],j.map((Y)=>{let H=new Date(Y.bucket),X=`${String(H.getDate()).padStart(2,"0")}/${String(H.getMonth()+1).padStart(2,"0")}`,B=Y.avg_score!=null&&Y.avg_score>0?"+":"",M=Y.avg_score!=null?`${B}${Y.avg_score.toFixed(2)}`:"—";return{Date:X,Analyzed:Y.analyzed,Positive:Y.positive,Neutral:Y.neutral,Negative:Y.negative,"Avg Score":M}}))}),z0(K.command("weekday-hour").description("Show call volume heatmap by weekday and hour")).action(async(q)=>{let{format:Q}=L($.opts()),{date_from:W,date_to:G}=J1(q),j=await N(U().dashboard.weekdayHour({date_from:W,date_to:G,visual_plan_id:A("visual_plans",q.plan),channel_id:A("channels",q.phone)}));if(Q==="json"){P(j);return}if(console.log(G1.default.bold("Weekday × Hour")),j.cells.length===0){R(`
|
|
100
|
+
No data available.`);return}let Y=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],H=new Map(j.cells.map((B)=>[`${B.weekday}:${B.hour}`,B])),X=Array.from({length:24},(B,M)=>String(M).padStart(2,"0"));console.log(""),y(["Weekday",...X],Y.map((B,M)=>{let I={Weekday:B};for(let E of X)I[E]=jk(H.get(`${M}:${Number(E)}`));return I}))}),K.command("top-plans").description("Show top IVR plans by call volume").option("--from <date>","Start date (YYYY-MM-DD or ISO 8601)").option("--to <date>","End date (YYYY-MM-DD or ISO 8601)").option("--limit <n>","Max plans to show","5").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),{date_from:G,date_to:j}=J1(q),Y=await N(U().dashboard.topPlans({date_from:G,date_to:j,limit:Number(q.limit)}));if(Q==="json"){let H=W?Y.map((X)=>O(X,W)):Y;P(H);return}if(console.log(G1.default.bold("Top Plans")),Y.length===0){R(`
|
|
101
|
+
No data available.`);return}console.log(""),y(["Plan","Total","Answered","Avg Duration"],Y.map((H)=>({Plan:H.visual_plan_name??"—",Total:H.total,Answered:`${H.answered} (${H.total>0?Math.round(H.answered/H.total*100):0}%)`,"Avg Duration":f$(H.avg_duration_ms)})))})}import{readFile as Xk}from"node:fs/promises";var xB=1e4;function wB($,U){let K=$.command("dnc").description("Manage the do-not-call list");K.command("list").description("List do-not-call entries").option("--search <t>","Search by phone number").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),G=await N(U().dialerDnc.list({page:Number(q.page),limit:Number(q.limit),search:q.search}));if(Q==="json"){P(W?G.items.map((j)=>O(j,W)):G);return}y(["ID","Phone","Reason","Added"],G.items.map((j)=>({ID:j.id,Phone:j.phone_number,Reason:j.reason??"—",Added:j1(j.created_at)}))),Z$(G)}),K.command("add <phone>").description("Add a number to the do-not-call list").option("--reason <r>","Reason for the block").action(async(q,Q)=>{let{format:W}=L($.opts()),G=await N(U().dialerDnc.add({phone_number:q,reason:Q.reason}));if(W==="json"){P(G);return}T(`Added ${G.phone_number} to DNC`)}),K.command("remove <ids...>").description("Remove do-not-call entries").action(async(q)=>{let{format:Q}=L($.opts());if(q.length===1){let G=await N(U().dialerDnc.remove({dnc_id:A("dialer_dnc",q[0])}));if(Q==="json"){P(G);return}T("Removed DNC entry");return}let W=await N(U().dialerDnc.bulkRemove({ids:A("dialer_dnc",q)}));if(Q==="json"){P(W);return}T(`Removed ${W.removed}`)}),K.command("check <phone>").description("Check if a number is on the DNC list (exit 0 = listed, 3 = not listed)").action(async(q)=>{let{format:Q}=L($.opts()),W=await N(U().dialerDnc.list({page:1,limit:20,search:q})),G=q.replaceAll(/\D/g,""),j=G===""?void 0:W.items.find((Y)=>{let H=String(Y.phone_number).replaceAll(/\D/g,"");return H===G||H.endsWith(G)});if(j!=null){if(Q==="json")P(j);else o([{title:"DNC entry",rows:[{label:"ID",value:j.id},{label:"Phone",value:j.phone_number},{label:"Reason",value:j.reason??"—"},{label:"Added",value:new Date(j.created_at).toLocaleString()}]}]);return}if(Q==="json")P({listed:!1});else R("Not in DNC list.");process.exit(w.NOT_FOUND)}),K.command("import <file>").description("Bulk-import DNC numbers (one per line; blank / # lines skipped)").option("--reason <r>","Reason applied to every imported number").action(async(q,Q)=>{let{format:W}=L($.opts()),j=(await Xk(q,"utf-8")).split(/\r\n|\n|\r/).map((X)=>X.trim()).filter((X)=>X.length>0&&!X.startsWith("#"));if(j.length===0)x("No phone numbers found in file"),process.exit(w.USAGE_ERROR);let Y=0,H=0;for(let X=0;X<j.length;X+=xB){let B=j.slice(X,X+xB),M=await N(U().dialerDnc.bulkImport({numbers:B,reason:Q.reason}));Y+=M.added,H+=M.skipped}if(W==="json"){P({added:Y,skipped:H});return}T(`Added ${Y}, skipped ${H}`)})}var r$=N1(I1(),1);var Zk=new Set(L0);function Bk($){return Zk.has($)}var s3=($)=>$==="online"?r$.default.green($):r$.default.red($);function Vk($){let U;if($.is_expired)U=r$.default.red("expired");else if($.is_in_grace_period)U=r$.default.yellow("grace period");else U=r$.default.green($.status);let K=$.days_until_expiry!=null?` (${$.days_until_expiry}d remaining)`:"";return` License: ${U}${K}`}var AB=10,Mk="unlimited".padEnd(AB);function e3($,U,K,q,Q){let W=` ${$.padEnd(11)}`;if(K==null)return`${W}${r$.default.dim(Mk)} ${U}${q}`;return`${W}${a1(U,K,AB)} ${U}/${K}${q} (${Math.round(Q)}%)`}function Dk($){let U=[r$.default.bold(" AI Usage:")],{stt:K,tts:q,llm:Q}=$;if(K)U.push(e3("STT:",Math.round(K.current),K.limit," min",K.percentage));if(q)U.push(e3("TTS:",q.current,q.limit," chars",q.percentage));if(Q)U.push(e3("LLM:",Q.current,Q.limit," tokens",Q.percentage));return U}function vB($,U){let K=$.command("fs").description("FreeSWITCH status and debug");K.command("status").description("Check system health (server, DB, Redis, FreeSWITCH)").action(async()=>{let{format:q,fields:Q}=L($.opts()),W=await N(U().dashboard.health());if(q==="json"){let G=Q?O(W,Q):W;P(G);return}if(console.log(`Server: ${s3(W.server)}`),console.log(`PostgreSQL: ${s3(W.postgres)}`),console.log(`Redis: ${s3(W.redis)}`),console.log(`FreeSWITCH: ${s3(W.freeswitch.status)}`),W.freeswitch.uptime!=null&&W.freeswitch.uptime!=="")console.log(` Uptime: ${W.freeswitch.uptime}`);if(W.freeswitch.sessions)console.log(` Sessions: ${W.freeswitch.sessions.active}/${W.freeswitch.sessions.limit}`);if(W.freeswitch.cps)console.log(` CPS: ${W.freeswitch.cps.current}/${W.freeswitch.cps.limit}`);if(W.freeswitch.idleCpu!=null)console.log(` Idle CPU: ${W.freeswitch.idleCpu}%`)}),K.command("channels").description("List active FreeSWITCH channels").action(async()=>{let{format:q,fields:Q}=L($.opts()),W=await N(U().dashboard.activeCalls());if(q==="json"){let G=Q?W.map((j)=>O(j,Q)):W;P(G);return}if(W.length===0){R("No active channels.");return}y(["UUID","Caller","Plan","Node","Duration"],W.map((G)=>({UUID:G.uuid,Caller:G.callerId,Plan:G.planName??"—",Node:G.currentNodeLabel??"—",Duration:G.startedAt?`${Math.round((Date.now()-new Date(G.startedAt).getTime())/1000)}s`:"—"}))),R(`${W.length} active channel(s)`)}),K.command("registrations").description("List SIP registrations").action(async()=>{let{format:q,fields:Q}=L($.opts()),W=await N(U().testCall.registrations());if(q==="json"){let G=Q?W.map((j)=>O(j,Q)):W;P(G);return}if(W.length===0){R("No SIP registrations.");return}y(["Extension","Agent"],W.map((G)=>({Extension:G.extension,Agent:G.agent??"—"})))}),K.command("dump <uuid>").description("Dump all channel variables for an active call").action(async(q)=>{let{format:Q}=L($.opts()),W=await N(U().dashboard.fsDumpChannel({uuid:q}));if(Object.keys(W).length===0){if(Q==="json")P({});else x(`Channel ${q} not found.`);process.exit(w.NOT_FOUND)}if(Q==="json"){P(W);return}console.log(r$.default.bold(`Channel Variables — ${q}`)),console.log("");for(let[G,j]of Object.entries(W))console.log(` ${r$.default.cyan(G.padEnd(40))} ${j}`)}),K.command("sofia").description("Show SIP profile status").action(async()=>{let{format:q}=L($.opts()),Q=await N(U().dashboard.fsSofiaStatus());if(q==="json"){P(Q);return}if(Q.length===0){R("No Sofia profiles configured.");return}console.log(r$.default.bold("Sofia SIP Profiles")),console.log(""),y(["Name","Type","Data","State"],Q.map((W)=>({Name:W.name,Type:W.type,Data:W.data,State:W.state})))}),K.command("show <entity>").description(`Show FreeSWITCH data (${L0.join(", ")})`).action(async(q)=>{if(!Bk(q))x(`Unknown entity "${q}". Allowed: ${L0.join(", ")}`),process.exit(w.USAGE_ERROR);let{format:Q}=L($.opts()),W=await N(U().dashboard.fsShow({entity:q}));if(Q==="json"){P(W);return}console.log(r$.default.bold(`FreeSWITCH: show ${q}`)),console.log(""),console.log(JSON.stringify(W,null,2))}),K.command("capacity").description("Show system capacity: channels, license, AI usage").action(async()=>{let{format:q,fields:Q}=L($.opts()),W=await N(U().dashboard.capacityStatus());if(q==="json"){let j=Q?O(W,Q):W;P(j);return}console.log(r$.default.bold("System Capacity")),console.log("");let G=W.channels.total;if(console.log(e3("Channels:",G.active,G.limit,"",G.percentage??0)),console.log(Vk(W.license)),W.ai_usage){console.log("");for(let j of Dk(W.ai_usage))console.log(j)}})}function Pk(){return Object.entries(m).map(([$,U])=>`${$} (${U}_)`).sort(($,U)=>$.localeCompare(U))}function Nk($){return Object.hasOwn(m,$)}function kB($){x($),R(" Valid entities:");for(let U of Pk())R(` ${U}`);process.exit(w.USAGE_ERROR)}function zB($,U,K){return{input:$,entity:U,prefix:m[U],typeid:f0(U,K),uuid:K,sql:`'${K}'::uuid`}}function Lk($,U){if(U!=null&&!Nk(U))kB(`Unknown entity "${U}".`);let K=$4($);if(K.kind==="typeid"){if(U!=null&&U!==K.entity)x(`"${$}" is a ${K.entity} id, but --as says ${U}.`),R(" Drop --as: a TypeID already carries its entity."),process.exit(w.USAGE_ERROR);return zB($,K.entity,K.uuid)}if(K.kind==="uuid"){if(U==null)kB(`"${$}" is a UUID, which does not carry an entity - pass --as <entity>.`);return zB($,U,K.uuid)}x(`Cannot read "${$}" as an id: ${_k[K.reason]}.`),R(" A TypeID looks like vp_01k3vbk6hxe008000000000001; a UUID like 0198f6b9-9a3d-7000-8000-000000000001."),process.exit(w.USAGE_ERROR)}var _k={"unknown-prefix":"its prefix belongs to no known entity","malformed-suffix":"the part after the prefix is not a valid TypeID body","not-an-id":"it is neither a UUID nor a prefixed TypeID"};function RB($){$.command("id <value>").description("Convert between a TypeID and a raw UUID (local, no server call)").option("--as <entity>","Entity a raw UUID belongs to (required when converting a UUID)").option("--sql","Print only the UUID as a psql literal, ready to paste into a query").action((U,K)=>{let{format:q,fields:Q}=L($.opts()),W=Lk(U,K.as);if(K.sql===!0){console.log(W.sql);return}if(q==="json"){P(O(W,Q));return}o([{title:"Id",rows:[{label:"TypeID",value:W.typeid},{label:"UUID",value:W.uuid},{label:"Entity",value:W.entity},{label:"Prefix",value:W.prefix}]}])})}import{existsSync as SB,lstatSync as CB,mkdirSync as zk,readFileSync as EB,realpathSync as OB,rmSync as Rk,statSync as bk,writeFileSync as TB}from"node:fs";import{homedir as Ok}from"node:os";import{dirname as Tk,isAbsolute as yB,join as d1,relative as Sk}from"node:path";import{readdirSync as Ik,readFileSync as Fk}from"node:fs";import{join as xk,relative as wk}from"node:path";import{fileURLToPath as Ak}from"node:url";var A4="SKILL.md";function vk($,U){if($===U)return 0;return $<U?-1:1}function kk($){let U={},K=Ik($,{recursive:!0,withFileTypes:!0});for(let q of K){if(!q.isFile()||q.name.startsWith("."))continue;let Q=xk(q.parentPath,q.name);U[wk($,Q).replaceAll("\\","/")]=Fk(Q,"utf-8")}return Object.fromEntries(Object.entries(U).toSorted(([q],[Q])=>vk(q,Q)))}function bB(){return{"SKILL.md":`---
|
|
101
102
|
name: niva-cli
|
|
102
103
|
description: >
|
|
103
104
|
NIVA CLI for the IVR/omnichannel platform: debug calls, monitor health, read logs,
|
|
@@ -421,6 +422,22 @@ Writes \`skills/niva-cli/\` under \`.claude/\` and/or \`.agents/\` (project, or
|
|
|
421
422
|
version in \`SKILL.md\`. Reinstall after upgrading the CLI to refresh it; files an older version installed and the
|
|
422
423
|
new one dropped are removed.
|
|
423
424
|
|
|
425
|
+
## Reporting a problem
|
|
426
|
+
|
|
427
|
+
\`\`\`bash
|
|
428
|
+
niva bug-report --title "Outbound call drops" \\
|
|
429
|
+
--description "Every outbound call ends after 10 seconds" \\
|
|
430
|
+
--severity blocker --frequency always \\
|
|
431
|
+
--step "Open the dialer" --step "Start a campaign" \\
|
|
432
|
+
--resource vp_01k...
|
|
433
|
+
\`\`\`
|
|
434
|
+
|
|
435
|
+
Files a structured report with the support team and prints its reference. \`--severity\` is
|
|
436
|
+
\`blocker|degraded|minor\`; \`--frequency\` is \`always|sometimes|once\`; \`--expected\`, repeated \`--step\` and
|
|
437
|
+
repeated \`--resource\` (TypeIDs) are optional. Non-interactive: without \`--title\`, \`--description\` or
|
|
438
|
+
\`--severity\` it exits \`2\` listing exactly what is missing. Reporting only works when the installation
|
|
439
|
+
has error reporting enabled; otherwise the server answers \`BUG_REPORTING_DISABLED\` and nothing is sent.
|
|
440
|
+
|
|
424
441
|
## Support material
|
|
425
442
|
|
|
426
443
|
Pages on this installation's docs (open them when the task needs the user-facing detail):
|
|
@@ -979,21 +996,21 @@ niva signals test --preset off_script_offer --plan <plan_id> --last 5
|
|
|
979
996
|
Pages on this installation's docs (open them when the task needs the user-facing detail):
|
|
980
997
|
|
|
981
998
|
- \`<NIVA_URL>/docs/en/configuracoes/signals\`, \`<NIVA_URL>/docs/en/dashboard/signals\`, \`<NIVA_URL>/docs/en/configuracoes/webhooks\`
|
|
982
|
-
`}}var
|
|
999
|
+
`}}var gB=["claude","agents","both"],Ck={claude:[".claude"],agents:[".agents"],both:[".agents",".claude"]},Ek=new Set(gB);function yk($){return Ek.has($)}function gk(){let $=process.env.HOME;return $!=null&&$!==""?$:Ok()}var uk="Install the skill for which agent?",fk=[{label:"All (recommended)",value:"both"},{label:"Claude Code",value:"claude"},{label:"Codex / Cursor / Copilot / Gemini CLI / opencode",value:"agents"}];async function mk($){if($.target!=null){if(!yk($.target))x(`Error: invalid --target "${$.target}" — expected one of: ${gB.join(", ")}`),process.exit(w.USAGE_ERROR);return $.target}if($.yes)return"both";if($.interactive!==!0)return R("Non-interactive shell — installing for all agents. Pass --target to choose."),"both";return c0(uk,fk,$.ask==null?{}:{ask:$.ask})}var uB=/^---\r?\n([\s\S]*?)\r?\n---/,hk=/^[\w.+-]+$/;function xG($){return hk.test($)}function ck($){let U=uB.exec($)?.[1];if(U==null)return;let q=/^[ \t]+cli_version:(.*)$/m.exec(U)?.[1]?.trim().replaceAll(/^"|"$/g,"").trim();return q==null||!xG(q)?void 0:q}function lk($,U){let K=$.split(`
|
|
983
1000
|
`),q=K.findIndex((Q)=>Q.startsWith("metadata:"));if(q===-1)return`${$}
|
|
984
1001
|
metadata:
|
|
985
1002
|
cli_version: "${U}"`;if(K[q]!=="metadata:")return $;for(let Q=q+1;Q<K.length;Q++){let W=K[Q];if(!/^\s+\S/.test(W))break;if(/^\s+cli_version:/.test(W))return K[Q]=` cli_version: "${U}"`,K.join(`
|
|
986
1003
|
`)}return K.splice(q+1,0,` cli_version: "${U}"`),K.join(`
|
|
987
|
-
`)}function
|
|
988
|
-
${
|
|
989
|
-
---${$.slice(K.index+K[0].length)}`}var
|
|
990
|
-
`)}catch(Q){x(`Error: could not write ${U} — ${Q instanceof Error?Q.message:String(Q)}`),process.exit(w.GENERAL_ERROR)}}function
|
|
991
|
-
Next page: --cursor ${H.nextCursor}`)}function
|
|
992
|
-
`)}function yB($){let U=0,K=0,q=!1;for(let Q=0;Q<$.length;Q+=1){let W=$[Q];if(W==='"'){if(q&&$[Q+1]==='"'){Q+=1;continue}q=!q}else if(!q){if(W===",")U+=1;else if(W===";")K+=1}}return K>U?";":","}function rk($,U){let K="",q=U;for(;q<$.length;q+=1){let Q=$[q];if(Q!=='"')K+=Q;else if($[q+1]==='"')K+='"',q+=1;else return{value:K,end:q}}return{value:K,end:q}}function gB($,U){let K=[],q="",Q=!1,W=0;while(W<$.length){let J=$[W];if(J==='"'){let j=rk($,W+1);q+=j.value,W=j.end,Q=!0}else if(J===U)K.push(Q?q:q.trim()),q="",Q=!1;else q+=J;W+=1}return K.push(Q?q:q.trim()),K}var FJ=["phone_number","name","status","attempt_count","machine_attempts","machine_type","last_attempt_at"],ok=new Set(FJ);function IJ($,U){return[...U,$]}function fB($){let U={};for(let K of $){let q=K.indexOf("=");if(q<=0)x(`Invalid --field "${K}" (expected key=value)`),process.exit(w.USAGE_ERROR);U[K.slice(0,q)]=K.slice(q+1)}return U}function nk($){return $==="phone"||$==="name"||$==="ignore"||/^custom:.+$/.test($)}function pk($,U){if(U==null)return yB($);if(U!==","&&U!==";")x(`Invalid --separator "${U}" (must be , or ;)`),process.exit(w.USAGE_ERROR);return U}function tk($,U){let K=Vq($),q={};for(let Q of $){let W=K.roles[Q]??"ignore";if(W!=="custom"){q[Q]=W;continue}let J=K.customNames[Q];q[Q]=J!=null&&J.length>0?`custom:${J}`:"ignore"}for(let Q of U){let W=Q.indexOf("=");if(W<=0)x(`Invalid --map "${Q}" (expected <Column>=<role>)`),process.exit(w.USAGE_ERROR);let J=Q.slice(0,W),j=Q.slice(W+1);if(!$.includes(J))x(`Unknown column "${J}". Available: ${$.join(", ")}`),process.exit(w.USAGE_ERROR);if(!nk(j))x(`Invalid role "${j}" for column "${J}" (phone|name|ignore|custom:<field>)`),process.exit(w.USAGE_ERROR);q[J]=j}return q}function ak($){if($==null)return"—";if(typeof $==="string")return $;if(typeof $==="number"||typeof $==="boolean")return String($);return JSON.stringify($)}async function sk($,U,K){let q=new AbortController;process.on("SIGINT",()=>q.abort());let Q="",W=0;if(await new Promise((J,j)=>{S1($.dialerImports.progress({import_job_id:A("dialer_import_jobs",U)},{signal:q.signal}),{onEvent:(Y)=>{if(Q=Y.status,W=Y.invalid,K==="json")console.log(JSON.stringify(Y));else{let H=Y.total_rows!=null?String(Y.total_rows):"-";z(`[${Y.status}] processed ${Y.processed_rows}/${H} · imported ${Y.imported} · skipped ${Y.skipped} · invalid ${Y.invalid}`)}if(Y.status==="done"||Y.status==="failed")J()},onError:(Y)=>{if(Y instanceof DOMException&&Y.name==="AbortError"){J();return}j(Y)},onSuccess:()=>J()})}).catch(z4),Q==="failed")return w.GENERAL_ERROR;if(Q==="done"&&W>0&&K!=="json")z(`${W} invalid row(s). Inspect with: niva mailing invalid-rows ${U}`);return w.SUCCESS}function mB($,U){let K=$.command("mailing").description("Manage campaign mailing (contacts & imports)");K.command("list <campaign_id>").description("List contacts of a campaign mailing").option("--status <s>","Filter by contact status").option("--search <t>","Search by phone or name").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(q,Q)=>{let{format:W,fields:J}=L($.opts()),j=await N(U().dialerContacts.list({campaign_id:A("dialer_campaigns",q),page:Number(Q.page),limit:Number(Q.limit),status:P$(Q.status),search:Q.search}));if(W==="json"){P(J?j.items.map((Y)=>O(Y,J)):j);return}y(["ID","Phone","Name","Status","Attempts","Machine","Last attempt"],j.items.map((Y)=>({ID:Y.id,Phone:Y.phone_number,Name:Y.name??"—",Status:Y.status,Attempts:Y.attempt_count,Machine:E0(Y.machine_type),"Last attempt":Y.last_attempt_at!=null?j1(Y.last_attempt_at):"—"}))),H$(j)}),K.command("show <campaign_id> <contact_id>").description("Show a mailing contact with its custom fields").action(async(q,Q)=>{let{format:W,fields:J}=L($.opts()),j=await N(U().dialerContacts.get({campaign_id:A("dialer_campaigns",q),contact_id:A("dialer_contacts",Q)}));if(W==="json"){P(J?O(j,J):j);return}let Y=[{title:"Contact",rows:[{label:"ID",value:j.id},{label:"Phone",value:j.phone_number},{label:"Name",value:j.name??"—"},{label:"Status",value:j.status},{label:"Attempts",value:j.attempt_count},{label:"Last attempt",value:j.last_attempt_at!=null?new Date(j.last_attempt_at).toLocaleString():"—"},{label:"Next attempt",value:j.next_attempt_at!=null?new Date(j.next_attempt_at).toLocaleString():"—"},{label:"Created",value:new Date(j.created_at).toLocaleString()}]}],H=j.custom_fields;if(H!=null&&typeof H==="object"&&!Array.isArray(H)&&Object.keys(H).length>0)Y.push({title:"Custom fields",rows:Object.entries(H).map(([Z,B])=>({label:Z,value:ak(B)}))});o(Y)}),K.command("add <campaign_id> <phone>").description("Add a single contact to a campaign mailing").option("--name <n>","Contact name").option("--field <pair>","Custom field key=value (repeatable)",IJ,[]).action(async(q,Q,W)=>{let{format:J}=L($.opts()),j=fB(W.field),Y=await N(U().dialerContacts.add({campaign_id:A("dialer_campaigns",q),phone_number:Q,name:W.name,custom_fields:Object.keys(j).length>0?j:void 0}));if(J==="json"){P(Y);return}T(`Contact added: ${Y.id}`)}),K.command("edit <campaign_id> <contact_id>").description("Edit a pending mailing contact (only provided fields)").option("--phone <p>","New phone number").option("--name <n>","New contact name").option("--field <pair>","Custom field key=value (repeatable)",IJ,[]).action(async(q,Q,W)=>{let{format:J}=L($.opts()),j=await N(U().dialerContacts.update({campaign_id:A("dialer_campaigns",q),contact_id:A("dialer_contacts",Q),...W.phone!=null&&{phone_number:W.phone},...W.name!=null&&{name:W.name},...W.field.length>0&&{custom_fields:fB(W.field)}}));if(J==="json"){P(j);return}T("Contact updated")}),K.command("remove <campaign_id> <contactIds...>").description("Remove (soft-delete) mailing contacts").action(async(q,Q)=>{let{format:W}=L($.opts()),J=await N(U().dialerContacts.remove({campaign_id:A("dialer_campaigns",q),ids:A("dialer_contacts",Q)}));if(W==="json"){P(J);return}T(`Removed ${J.removed}, skipped ${J.skipped}`)}),K.command("cancel <campaign_id> <contactIds...>").description("Cancel pending mailing contacts").action(async(q,Q)=>{let{format:W}=L($.opts()),J=await N(U().dialerContacts.bulkCancel({campaign_id:A("dialer_campaigns",q),ids:A("dialer_contacts",Q)}));if(W==="json"){P(J);return}T(`Cancelled ${J.cancelled}, skipped ${J.skipped}`)}),K.command("requeue <campaign_id> [contactIds...]").description("Requeue terminal contacts (lead recycling): pass IDs, or --all").option("--all","Requeue every terminal contact of the campaign").option("--status <terminal>","Restrict --all to a single terminal status").action(async(q,Q,W)=>{let{format:J}=L($.opts()),j=Q.length>0;if(j&&W.all===!0)x("Use either <contactIds...> or --all, not both"),process.exit(w.USAGE_ERROR);if(!j&&W.all!==!0)x("Provide contact IDs or --all to requeue"),process.exit(w.USAGE_ERROR);if(j){let H=await N(U().dialerContacts.bulkRequeue({campaign_id:A("dialer_campaigns",q),ids:A("dialer_contacts",Q)}));if(J==="json"){P(H);return}T(`Requeued ${H.requeued}, skipped ${H.skipped}`);return}let Y=await N(U().dialerContacts.requeueAll({campaign_id:A("dialer_campaigns",q),status:P$(W.status)}));if(J==="json"){P(Y);return}T(`Requeued ${Y.requeued}`)}),K.command("import <campaign_id> <file>").description("Import a CSV mailing into a campaign").option("--map <pair>","Column mapping override <Column>=<role> (repeatable)",IJ,[]).option("--separator <sep>","CSV separator (, or ;) — sniffed when omitted").option("--watch","Follow import progress until it finishes").action(async(q,Q,W)=>{let{format:J}=L($.opts()),j=$.opts().yes===!0,Y=await ik(Q),H=Y.toString("utf-8"),Z=H.search(/\r\n|\n|\r/),B=Z===-1?H:H.slice(0,Z);if(B.trim()==="")x("File is empty or has no header row"),process.exit(w.USAGE_ERROR);let M=pk(B,W.separator),I=gB(B,M),E=tk(I,W.map);if(J!=="json")y(["Column","Role"],I.map((S$)=>({Column:S$,Role:E[S$]??"ignore"})));await d$("Import with this mapping?",{yes:j});let u=U(),U$=await N(u.dialerImports.create({campaign_id:A("dialer_campaigns",q),column_mapping:E,file:new File([Y],dk(Q))}));if(J!=="json")T(`Import started: ${U$.id} (${U$.status})`);else if(W.watch!==!0)P(U$);if(W.watch===!0){let S$=await sk(u,U$.id,J);if(S$!==w.SUCCESS)process.exit(S$)}}),K.command("import-status <import_job_id>").description("Show the status of a mailing import job").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),J=await N(U().dialerImports.get({import_job_id:A("dialer_import_jobs",q)}));if(Q==="json"){P(W?O(J,W):J);return}o([{title:"Import job",rows:[{label:"ID",value:J.id},{label:"Status",value:J.status},{label:"Total rows",value:J.total_rows??"—"},{label:"Processed",value:J.processed_rows},{label:"Imported",value:J.imported},{label:"Skipped",value:J.skipped},{label:"Invalid",value:J.invalid},{label:"Has invalid rows",value:J.has_invalid_rows?"yes":"no"},{label:"Created",value:new Date(J.created_at).toLocaleString()}]}])}),K.command("invalid-rows <import_job_id>").description("Output the CSV of rows an import rejected").option("-o, --out <file>","Write the CSV to a file instead of stdout").action(async(q,Q)=>{let W=await N(U().dialerImports.invalidRows({import_job_id:A("dialer_import_jobs",q)}));if(W==null){z("No invalid rows.");return}if(Q.out!=null){await uB(Q.out,W.csv,"utf-8"),T(`Wrote invalid rows to ${Q.out}`);return}process.stdout.write(W.csv)}),K.command("export <campaign_id>").description("Export a campaign mailing to CSV (stdout or -o file)").option("--status <s>","Filter by contact status").option("--search <t>","Search by phone or name").option("-o, --out <file>","Write the CSV to a file instead of stdout").action(async(q,Q)=>{let W=await N(U().dialerContacts.exportCsv({campaign_id:A("dialer_campaigns",q),status:P$(Q.status),search:Q.search})),J=[],j=new Set;for await(let M of W){J.push(M);for(let I of Object.keys(M))if(!ok.has(I))j.add(I)}if(J.length===0){z("No contacts to export.");return}let Y=[...j].sort((M,I)=>M.localeCompare(I)),H=[...FJ,...Y],Z=J.map((M)=>[...FJ.map((I)=>M[I]??""),...Y.map((I)=>M[I]??"")]),B=EB(H,Z);if(Q.out!=null){await uB(Q.out,B,"utf-8"),T(`Wrote ${J.length} contacts to ${Q.out}`);return}process.stdout.write(B)})}function hB($){if(!($ in t$))console.error(`Unknown node type: ${$}`),console.error(`Available: ${Object.keys(t$).join(", ")}`),process.exit(2)}function xJ($){return a$[$]?.connector}function ek($){return`${$.kind} (config key ${$.configKey}) - create it with niva connectors create ${$.kind}`}function $R($){return $ in F4}function cB($){let U=$.command("nodes").description("IVR node types reference");U.command("list").description("List node types with module, channel and the connector kind a block needs (- when none)").option("--module <module>","Filter by module (core, ai)").option("--category <cat>","Filter by category (interaction, handling, routing, data, legacy)").option("--channel <ch>","Filter by channel (voice, chat, both)").action((K)=>{let{format:q,fields:Q}=L($.opts()),W=YJ();if(K.module!=null)W=W.filter((J)=>J.module===K.module);if(K.category!=null)W=W.filter((J)=>J.category===K.category);if(K.channel!=null)W=W.filter((J)=>J.channel===K.channel);if(q==="json"){let J=W.map((j)=>({...j,connector:xJ(j.type)??null}));P(Q?J.map((j)=>O(j,Q)):J);return}y(["Type","Name","Description","Module","Channel","Connector"],W.map((J)=>({Type:J.type,Name:J.name,Description:J.description,Module:J.module,Channel:J.channel,Connector:xJ(J.type)?.kind??"-"})))}),U.command("show <type>").description("Show a node type: config fields, outputs, variables and the connector it needs").action((K)=>{let{format:q}=L($.opts());hB(K);let Q=v0(K),W=xJ(K);if(q==="json"){P({...Q,connector:W??null});return}let J=$R(K)?F4[K]:void 0,j=J!=null?Object.entries(J).map(([Y,H])=>({label:Y,value:String(H)})):[{label:"(no fields)",value:""}];o([{title:`${Q.name} (${Q.type})`,rows:[{label:"Description",value:Q.description},{label:"Module",value:Q.module},{label:"Category",value:Q.category},{label:"Channel",value:Q.channel},{label:"Nature",value:Q.nature},...W!=null?[{label:"Connector",value:ek(W)}]:[]]},{title:"Config Fields",rows:j},{title:"Outputs",rows:Q.outputs.map((Y)=>({label:Y.key,value:Y.labelKey}))},{title:"Produced Variables",rows:Q.producedVariables.length>0?Q.producedVariables.map((Y)=>({label:`${Y.name} (${Y.type})`,value:Y.descriptionKey})):[{label:"(none)",value:""}]}])}),U.command("schema <type>").description("Output JSON Schema for a node's config (agent-friendly)").action((K)=>{hB(K);let q=v0(K);P(q.configJsonSchema)})}function lB($,U,K){let q=$.indexOf("=");if(q===-1)throw Error(`${K} expects key=value (got: ${$})`);let Q=$.slice(0,q),W=$.slice(q+1);if(Q==="")throw Error(`${K} expects key=value (got: ${$})`);return U[Q]=W,U}function UR($,U){return lB($,U,"--var")}function QR($,U){return lB($,U,"--metadata")}function KR($){return $==="pre"||$==="post"}function qR($){let U=$.amd===!0||$.machineType===!0;if($.amdMode!==void 0&&!U)x("--amd-mode requires --amd or --machine-type"),process.exit(w.USAGE_ERROR);if($.amdMaxWait!==void 0&&$.amdMode!=="pre")x("--amd-max-wait requires --amd-mode pre"),process.exit(w.USAGE_ERROR);let K;if($.amdMode!==void 0){if(!KR($.amdMode))x(`Invalid --amd-mode "${$.amdMode}": expected pre or post`),process.exit(w.USAGE_ERROR);K=$.amdMode}let q=$.amdMaxWait===void 0?void 0:Number($.amdMaxWait);if(q!==void 0&&(!Number.isInteger(q)||q<3||q>10))x(`Invalid --amd-max-wait "${$.amdMaxWait}": expected an integer from 3 to 10`),process.exit(w.USAGE_ERROR);if(!U)return;let Q=$.machineType===!0?{amd:!0,machine_type:!0}:{amd:!0};if(K==="pre")return{...Q,mode:K,max_wait_seconds:q??6};if(K==="post")return{...Q,mode:K};return Q}function rB($,U){$.command("originate").description("Originate outbound calls").command("start").description("Start an outbound call that runs a published visual plan").requiredOption("--plan <id>","Visual plan TypeID (e.g. vp_...)").requiredOption("--destination <target>","Destination: number, number@host, or sofia/... URI").option("--caller-id <number>","Caller ID number to present").option("--caller-id-name <name>","Caller ID display name").option("--amd","Beta: detect whether a machine or human answered").option("--machine-type","Beta: identify voicemail, carrier announcement, IVR, or call screening; requires licensed AI and a SipPulse AI key").option("--amd-mode <mode>","AMD timing mode: pre waits before the plan; post runs in parallel (pre|post)").option("--amd-max-wait <seconds>","Absolute pre-plan AMD wait in seconds (3-10; default 6)").option("--timeout <seconds>","Ring timeout in seconds (10-120)","30").option("--max-duration <seconds>","Maximum call duration after answer in seconds (1-14400)").option("--var <key=value>","Plan input available as {{args.<key>}}; repeatable",UR,{}).option("--metadata <key=value>","Opaque call metadata persisted with the CDR; repeatable",QR,{}).action(async(q)=>{let{format:Q}=L($.opts()),W=Object.entries(q.var),J=Object.entries(q.metadata),j=qR(q),Y={plan_id:A("visual_plans",q.plan),destination:q.destination,timeout:Number(q.timeout),...q.maxDuration!==void 0?{max_call_duration_s:Number(q.maxDuration)}:{},...q.callerId!==void 0?{caller_id:q.callerId}:{},...q.callerIdName!==void 0?{caller_id_name:q.callerIdName}:{},...j!==void 0?{answer_recognition:j}:{},...W.length>0?{variables:q.var}:{},...J.length>0?{metadata:q.metadata}:{}},H=await N(U().calls.originate(Y));if(Q==="json")P(H);else if(H.status==="failed")$1(`Originate outcome: status=failed call_id=${H.call_id} channel_uuid=${H.channel_uuid} answered_at=${H.answered_at??"none"} hangup_cause=${H.hangup_cause??"unknown"} sip_code=${H.sip_code??"unknown"}`);else T(`Originate outcome: status=answered call_id=${H.call_id} channel_uuid=${H.channel_uuid} answered_at=${H.answered_at??"none"} hangup_cause=${H.hangup_cause??"none"} sip_code=${H.sip_code??"none"}`);if(H.status==="failed")process.exit(w.GENERAL_ERROR)})}import{readFile as eB}from"node:fs/promises";import{readFile as WR}from"node:fs/promises";function JR($){return"usage_count"in $}function GR($){let U=Math.max(0,Math.floor($)),K=Math.floor(U/60),q=U%60;return`${String(K).padStart(2,"0")}:${String(q).padStart(2,"0")}`}function jR($){return $==="caller"?"Cliente":"Atendimento"}function iB($){if($==null||$==="pt-BR")return"pt-BR";if($==="en")return"en";x(`Error: invalid --locale "${$}" — expected one of: pt-BR, en`),process.exit(w.USAGE_ERROR)}async function nB($){let U=$==="-"?await v$():await WR($,"utf-8"),K;try{K=JSON.parse(U)}catch{x(`Invalid JSON in "${$}"`),process.exit(w.USAGE_ERROR)}if(!G$(K))x(`Invalid signal file "${$}": expected a JSON object`),process.exit(w.USAGE_ERROR);return K}function pB($,U){let K=$.slug==null&&U!=null?{...$,slug:U}:$,q=I6.safeParse(K);if(!q.success){x("Invalid signal definition:");for(let Q of q.error.issues)x(` ✗ ${Q.path.join(".")||"(root)"}: ${Q.message}`);process.exit(w.USAGE_ERROR)}return q.data}function YR($){return I6.parse({slug:$.slug,name:$.name,question:$.question,kind:$.kind,...$.options!==void 0?{options:$.options}:{},...$.levels!==void 0?{levels:$.levels}:{},...$.higher_is!==void 0?{higher_is:$.higher_is}:{},speaker:$.speaker,scope:$.scope,live:$.live,alert:$.alert})}async function R0($,U){return(await N($.signals.list({search:U,limit:100,page:1,include_archived:!0}))).items.find((q)=>q.slug===U)}function HR($){if($4($).kind==="uuid")return!0;let U=$.lastIndexOf("_");return U>0&&A6($.slice(0,U))==="signals"}async function dB($,U){if(!HR(U))return R0($,U);let K=await N($.signals.get({signal_id:A("signals",U)}));return await R0($,K.slug)??K}function XR($){if("answer"in $)return $.answer==="yes"?"for Sim":"for Não";if("options"in $)return`for ${$.options.join(", ")}`;if("level_at_most"in $)return`dropping to level ${$.level_at_most}`;return`reaching level ${$.level_at_least}`}function ZR($){let U=$.description!=null?` — ${$.description}`:"",K=$.archived?" (archived)":"";return`${$.label}${U}${K}`}function oB($){for(let U of $.turns){let K=U.index===$.first_trigger_index?" <- would trigger":"";console.log(`${GR(U.start)} ${jR(U.speaker)} ${U.value_label}${K}`)}console.log(`Fim da chamada ${$.final==null?"ninguém falou no trecho que o signal escuta":$.final.value_label}`)}async function BR($,U,K){if(U.file!=null)return pB(await nB(U.file),"test_signal");if(U.preset!=null){let Q=o8.find((W)=>W.id===U.preset);if(Q==null)x(`Error: unknown preset "${U.preset}".`),z(` Valid presets: ${o8.map((W)=>W.id).join(", ")}`),process.exit(w.USAGE_ERROR);return XJ(Q,K)}let q=await R0($,U.slug??"");if(q==null)x(`Signal "${U.slug}" not found.`),process.exit(w.NOT_FOUND);return YR(q)}function VR($,U,K){if($.text!=null)return{definition:U,text:$.text,locale:K};if($.call!=null)return{definition:U,call_id:A("call_records",$.call),locale:K};return{definition:U,visual_plan_id:A("visual_plans",$.plan??""),last:$.last!=null?Number($.last):void 0,locale:K}}function tB($,U){let K=$.command("signals").description("Signal library and testing");K.command("presets").description("List the ten signal models").option("--locale <locale>","Locale of the texts: pt-BR or en","pt-BR").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),J=iB(q.locale),j=await N(U().signals.presets({locale:J}));if(Q==="json"){P(W?j.map((Y)=>O(Y,W)):j);return}y(["ID","Name","Kind","Speaker","Live","Severity"],j.map((Y)=>({ID:Y.id,Name:Y.definition.name,Kind:Y.definition.kind,Speaker:Y.definition.speaker,Live:Y.definition.live?"yes":"no",Severity:Y.definition.alert?.severity??"—"})))}),K.command("list").description("List the organization's signal library").option("--search <term>","Search by name or slug").option("--include-archived","Include archived signals").option("--limit <n>","Items per page","20").option("--page <n>","Page number","1").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),J=await N(U().signals.list({page:Number(q.page),limit:Number(q.limit),search:q.search,include_archived:q.includeArchived===!0}));if(Q==="json"){let j=W?J.items.map((Y)=>O(Y,W)):J;P(j);return}y(["Slug","Name","Kind","Live","Org default","Usage","Fires 7d","Version","Archived"],J.items.map((j)=>({Slug:j.slug,Name:j.name,Kind:j.kind,Live:j.live?"yes":"no","Org default":j.is_org_default?"yes":"no",Usage:`${j.usage_count.published}/${j.usage_count.draft}`,"Fires 7d":j.fires_last_7_days.reduce((Y,H)=>Y+H,0),Version:j.version,Archived:j.archived_at!=null?"yes":"no"}))),H$(J)}),K.command("show <slug_or_id>").description("Show one signal (slug or sig_... TypeID) with its usage").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),J=await dB(U(),q);if(J==null)x(`Signal "${q}" not found.`),process.exit(w.NOT_FOUND);if(Q==="json"){P(W?O(J,W):J);return}let j=[{title:"Signal",rows:[{label:"ID",value:J.id},{label:"Slug",value:J.slug},{label:"Name",value:J.name},{label:"Question",value:J.question},{label:"Kind",value:J.kind},...J.higher_is!==void 0?[{label:"Higher is",value:J.higher_is}]:[],{label:"Speaker",value:J.speaker},{label:"Scope",value:J.scope?.node_types.join(", ")??"whole call"},{label:"Live",value:J.live?"yes":"no"},{label:"Org default",value:J.is_org_default?"yes":"no"},{label:"Version",value:J.version},{label:"Archived",value:J.archived_at!=null?"yes":"no"}]},{title:"Alert",rows:J.alert==null?[{label:"When",value:"—"}]:[{label:"When",value:XR(J.alert.when)},{label:"Severity",value:J.alert.severity},{label:"Bell",value:J.alert.bell?"yes":"no"}]}];if(J.options!==void 0)j.push({title:"Options",rows:J.options.map((Y)=>({label:Y.key,value:ZR(Y)}))});if(J.levels!==void 0)j.push({title:"Levels",rows:J.levels.map((Y,H)=>({label:String(H+1),value:Y}))});if(JR(J))j.push({title:"Usage",rows:[{label:"Published plans",value:J.usage_count.published},{label:"Draft plans",value:J.usage_count.draft},{label:"Fires 7d",value:J.fires_last_7_days.reduce((Y,H)=>Y+H,0)},{label:"Evaluated calls 7d",value:J.evaluated_calls_last_7_days.reduce((Y,H)=>Y+H,0)}]});o(j)}),K.command("test").description("Test a definition against a text, a recorded call or a plan's last calls").option("--file <path>","JSON file with the definition (- for stdin)").option("--preset <id>","Start from one of the ten models").option("--slug <slug>","Use a saved signal from the library").option("--text <text>","Evaluate a single caller utterance").option("--call <call_id>","Replay a recorded call turn by turn").option("--plan <plan_id>","Replay the plan's last transcribed calls").option("--last <n>","How many calls to replay with --plan (1-5)").option("--locale <locale>","Locale: pt-BR or en","pt-BR").action(async(q)=>{let{format:Q}=L($.opts()),W=U(),J=iB(q.locale),j=[q.file,q.preset,q.slug].filter((M)=>M!=null).length,Y=[q.text,q.call,q.plan].filter((M)=>M!=null).length;if(j!==1||Y!==1)x("Error: signals test needs exactly one definition source (--file, --preset or --slug) and exactly one evaluation source (--text, --call or --plan)."),process.exit(w.USAGE_ERROR);if(q.last!=null&&q.plan==null)x("Error: --last only applies with --plan."),process.exit(w.USAGE_ERROR);let H=await BR(W,q,J),Z=VR(q,H,J),B=await N(W.signals.test(Z));if(Q==="json"){P(B);return}if("calls"in B)B.calls.forEach((M,I)=>{if(I>0)console.log("");console.log(`Call ${M.call_id}`),oB(M)});else if("turns"in B)oB(B);else console.log(`${B.value_label}${B.would_trigger?" <- would trigger":""}`)}),K.command("apply").description("Create or update a signal by slug (idempotent)").requiredOption("--file <path>","JSON file with the signal body (- for stdin)").option("--dry-run","Show what would change without writing").action(async(q)=>{let{format:Q}=L($.opts()),W=U(),J=await nB(q.file),j=pB(J),Y=typeof J.is_org_default==="boolean"?J.is_org_default:void 0,H=await N(W.signals.upsertBySlug({...j,...Y!==void 0?{is_org_default:Y}:{},dry_run:q.dryRun===!0}));if(Q==="json"){P(H);return}MR(H.status,H.changed_fields,H.signal.slug,q.dryRun===!0)}),K.command("delete <slug_or_id>").description("Move a signal to the trash (slug or sig_... TypeID)").action(async(q)=>{let{format:Q}=L($.opts()),W=await dB(U(),q);if(W==null)x(`Signal "${q}" not found.`),process.exit(w.NOT_FOUND);let J=await N(U().signals.delete({signal_id:A("signals",W.id)}));if(Q==="json"){P(J);return}T(`Signal moved to the trash: ${J.slug}. Restore it from Settings > Archive.`)})}function MR($,U,K,q){if($==="created"){T(q?`would create: ${K}`:`created: ${K}`);return}if($==="unchanged"){z(`unchanged: ${K}`);return}T(q?`would update: ${K} (changed: ${U.join(", ")})`:`updated: ${K} (changed: ${U.join(", ")})`)}async function wJ($){let U=$==="-"?await v$():await eB($,"utf-8"),K=sW.safeParse(JSON.parse(U));if(!K.success){x(`Invalid execution plan in "${$}":`);for(let q of K.error.issues)x(` ✗ ${q.path.join(".")||"(root)"}: ${q.message}`);process.exit(w.GENERAL_ERROR)}return K.data}function v4($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function DR($){if(!v4($)||!Array.isArray($.nodes)||!Array.isArray($.edges))return!1;let U=$.viewport;return v4(U)&&typeof U.x==="number"&&typeof U.y==="number"&&typeof U.zoom==="number"}async function PR($){let U=$==="-"?await v$():await eB($,"utf-8"),K;try{K=JSON.parse(U)}catch{x(`Invalid JSON in plan export "${$}"`),process.exit(w.GENERAL_ERROR)}let q;if(v4(K)&&K.format==="niva-plan-v1")q=K.state;else if(v4(K)&&v4(K.draft)&&K.draft.editor_state!=null)q=K.draft.editor_state;else if(v4(K)&&K.published_editor_state!=null)q=K.published_editor_state;else if(v4(K)&&Array.isArray(K.nodes)&&Array.isArray(K.edges))q=K;else x(`Invalid plan export in "${$}"`),process.exit(w.GENERAL_ERROR);if(!DR(q))x(`Invalid editor state in plan export "${$}"`),process.exit(w.GENERAL_ERROR);return q}function AJ($){let U=$.severity==="error"?"✗":"⚠",K=$.node_id!=null?` [${$.node_id}]`:"";return` ${U}${K} ${$.message_key}`}var NR="! Partial validation: structure only. References to secrets, schedules, sub-plans, audio files and AI agents were NOT checked - run 'niva plans validate --file <path>' for the full check against this server.";function aB($){try{let U=Yq($),K=MJ(U.nodes,U.edges,a$);if(!PJ(K)){for(let q of K)x(AJ({node_id:q.nodeId,severity:q.severity,message_key:q.messageKey}));return!1}return $1(NR),!0}catch(U){return x(U instanceof Error?U.message:String(U)),!1}}async function LR($,U,K,q){if(await N($.channels.update({channel_id:A("channels",U),visual_plan_id:A("visual_plans",K),reassign:!0})),q!=="json")T(`Channel ${U} assigned to plan`)}async function _R($,U,K){if(await N($.channels.update({channel_id:A("channels",U),visual_plan_id:null})),K!=="json")T(`Channel ${U} unassigned from plan`)}async function IR($,U,K){let q=A("visual_plans",U),Q=await N($.channels.list({page:1,limit:100})),W=Q.items.filter((j)=>j.visual_plan_id===q),J=Q.items.filter((j)=>j.visual_plan_id==null);if(K==="json"){P({assigned:W,available:J});return}if(W.length>0)console.log(`
|
|
993
|
-
Assigned to this plan:`),y(["ID","Type","Name","Identifier","Active"],W.map((j)=>({ID:j.id,Type:j.channel_type,Name:j.name,Identifier:j.identifier??"—",Active:j.is_active?"yes":"no"})));if(
|
|
994
|
-
Available (unassigned):`),y(["ID","Type","Name","Identifier"],J.map((j)=>({ID:j.id,Type:j.channel_type,Name:j.name,Identifier:j.identifier??"—"})))}function FR($,U){return{plan_id:A("visual_plans",$),...U.name!=null&&{name:U.name},...U.description!=null&&{description:U.description},...U.recording!==void 0&&{recording_enabled:U.recording},...U.transcription!==void 0&&{transcription_enabled:U.transcription},...U.transcriptionLanguage!=null&&{transcription_language:U.transcriptionLanguage},...U.anonymize!==void 0&&{anonymize_enabled:U.anonymize},...U.speechAnalytics!==void 0&&{speech_analytics_enabled:U.speechAnalytics},...U.sentiment!==void 0&&{sentiment_enabled:U.sentiment},...U.topics!=null&&{topic_detection_topics:U.topics.split(",").map((K)=>K.trim())},...U.intents!=null&&{intent_detection_intents:U.intents.split(",").map((K)=>K.trim())},...U.signalsInherit!==void 0&&{signals_inherit_org:U.signalsInherit}}}async function xR($,U,K,q,Q,W){let J=U.startsWith("-")?"-":"+",j=U.startsWith("+")||U.startsWith("-")?U.slice(1):U,Y=await R0($,j);if(Y==null){Q.push(j);return}if(J==="-"){q.delete(Y.id);return}if(q.add(Y.id),Y.live===!0&&K.transcription_type!=="live")W.push(`Signal "${Y.name}" runs live, but this plan uses ${K.transcription_type} transcription: it only runs at the end of the call until the plan switches to live transcription.`)}async function wR($,U,K){let q=await N($.visualPlans.getById({plan_id:A("visual_plans",U)})),Q=q.signals_inherit_org===!0,W=new Set(Q?await AR($):q.signal_ids),J=[],j=[];for(let Y of K.split(",")){let H=Y.trim();if(H==="")continue;await xR($,H,q,W,J,j)}if(J.length>0)x(`Unknown signal slug(s): ${J.join(", ")}`),z("List the library with: niva signals list"),process.exit(w.USAGE_ERROR);return{signal_ids:[...W].sort((Y,H)=>Y.localeCompare(H)),warnings:j,switchedToCustom:Q}}async function AR($){let U=[],K=1;for(;;){let q=await N($.signals.list({page:K,limit:100,include_archived:!1}));for(let Q of q.items)if(Q.is_org_default)U.push(Q.id);if(q.page>=q.total_pages)break;K+=1}return U}function $V($,U){let K=$.command("plans").description("Manage visual plans");K.command("list").description("List visual plans").option("--limit <n>","Items per page","20").option("--page <n>","Page number","1").option("--search <term>","Search by name").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),J=await N(U().visualPlans.list({page:Number(q.page),limit:Number(q.limit),search:q.search}));if(Q==="json"){let j=W?J.items.map((Y)=>O(Y,W)):J;P(j);return}y(["ID","Name","Status","Created"],J.items.map((j)=>({ID:j.id,Name:j.name,Status:j.published_version_id!=null?"published":"draft",Created:new Date(j.created_at).toLocaleDateString()}))),H$(J)}),K.command("show <plan_id>").description("Show plan details with settings").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),J=await N(U().visualPlans.getById({plan_id:A("visual_plans",q)}));if(Q==="json"){let j=W?O(J,W):J;P(j);return}o([{title:"Plan",rows:[{label:"ID",value:J.id},{label:"Name",value:J.name},{label:"Status",value:J.published_version_id!=null?"published":"draft"},{label:"Created",value:new Date(J.created_at).toLocaleString()},{label:"Updated",value:new Date(J.updated_at).toLocaleString()}]},{title:"Settings",rows:[{label:"Recording",value:J.recording_enabled?"enabled":"disabled"},{label:"Transcription",value:J.transcription_enabled?"enabled":"disabled"},{label:"Language",value:J.transcription_language??"—"},{label:"Anonymize",value:J.anonymize_enabled?"enabled":"disabled"},{label:"Call Summary",value:J.speech_analytics_enabled?"enabled":"disabled"},{label:"Sentiment",value:J.sentiment_enabled?"enabled":"disabled"}]}])}),K.command("create <name>").description("Create a new visual plan").option("--language <code>","Language code (e.g., pt-BR)").option("--description <text>","Plan description").option("--execution-plan <file>","JSON file with execution plan (- for stdin)").option("--recording","Enable recording").option("--transcription","Enable transcription").action(async(q,Q)=>{let{format:W}=L($.opts()),J;if(Q.executionPlan!=null){if(J=await wJ(Q.executionPlan),!aB(J))process.exit(1)}let j=await N(U().visualPlans.create({name:q,language:Q.language,description:Q.description,recording_enabled:Q.recording??!1,transcription_enabled:Q.transcription??!1,execution_plan:J}));if(W==="json"){P(j);return}T(`Plan created: ${j.id}`)}),K.command("edit <plan_id>").description("Update plan draft with a new execution plan").option("--execution-plan <file>","JSON file with execution plan (- for stdin)","-").option("--expected-revision <n>","Expected draft revision (optimistic locking)").action(async(q,Q)=>{let{format:W}=L($.opts()),J=await wJ(Q.executionPlan);if(!aB(J))process.exit(1);let j=await N(U().visualPlans.saveDraft({plan_id:A("visual_plans",q),execution_plan:J,expected_revision:Q.expectedRevision!=null?Number(Q.expectedRevision):void 0}));if(W==="json"){P(j);return}T(`Draft updated (revision ${j.revision})`)}),K.command("import <plan_id> <file>").description("Import a browser or CLI-exported plan JSON as the draft of an existing destination plan").action(async(q,Q)=>{let{format:W}=L($.opts()),J=await PR(Q),j=await N(U().visualPlans.importDraft({plan_id:A("visual_plans",q),editor_state:J}));if(W==="json"){P(j);return}T(`Draft imported (revision ${j.revision})`)}),K.command("configure <plan_id>").description("Configure plan settings, metadata, and DIDs").option("--name <name>","Plan name").option("--description <text>","Plan description").option("--recording","Enable recording").option("--no-recording","Disable recording").option("--transcription","Enable transcription").option("--no-transcription","Disable transcription").option("--transcription-language <code>","Transcription language").option("--anonymize","Enable anonymization").option("--no-anonymize","Disable anonymization").option("--speech-analytics","Enable call summary and key points").option("--no-speech-analytics","Disable call summary and key points").option("--sentiment","Enable sentiment analysis").option("--no-sentiment","Disable sentiment analysis").option("--topics <list>","Legacy topic hints (comma-separated)").option("--intents <list>","Legacy intent hints (comma-separated)").option("--signals <list>","Link signals (comma-separated: +slug to add, -slug to remove, bare slug to add)").option("--signals-inherit","Follow the organization's signal library").option("--no-signals-inherit","Own the plan's signal list").option("--assign-did <id>","Assign a phone number to this plan").option("--unassign-did <id>","Unassign a phone number from this plan").option("--list-dids","List DIDs assigned to this plan").action(async(q,Q)=>{let{format:W}=L($.opts()),J=U();if(Q.assignDid!=null)await LR(J,Q.assignDid,q,W);if(Q.unassignDid!=null)await _R(J,Q.unassignDid,W);if(Q.listDids===!0){await IR(J,q,W);return}let j=FR(q,Q);if(Q.signals!=null){if(Q.signalsInherit===!0)x("Error: --signals cannot be combined with --signals-inherit: the plan follows the organization and would ignore the list."),process.exit(w.USAGE_ERROR);let{signal_ids:Y,warnings:H,switchedToCustom:Z}=await wR(J,q,Q.signals);if(j.signal_ids=Y,Z)j.signals_inherit_org=!1,$1("This plan now chooses its own signals instead of following the organization.");for(let B of H)$1(B)}if(Object.keys(j).length>1){let Y=await N(J.visualPlans.update(j));if(W==="json"){P(Y);return}T("Plan configuration updated")}}),K.command("scaffold").description("Output a minimal valid execution plan JSON template").option("--channel <type>","Channel type: voice, chat, both","both").action((q)=>{let Q=["voice","chat","both"];if(!Q.includes(q.channel))x(`Invalid channel type: ${q.channel}. Must be one of: ${Q.join(", ")}`),process.exit(2);let W=q.channel;P({version:1,startNodeId:"start",nodes:{start:{type:"start",label:"Start",varName:"start",config:W==="both"?{}:{channelType:W}},greeting:{type:"tell",label:"Greeting",varName:"greeting",config:{audio:{tts:{text:"Olá! Como posso ajudá-lo?",voice:"pt-BR-FranciscaNeural",model:"edge"}},content:{type:"text",text:"Olá! Como posso ajudá-lo?"}}},end:{type:"hangup",label:"End",varName:"end",config:{}}},adjacency:{start:W==="both"?{voice:"greeting",chat:"greeting"}:{next:"greeting"},greeting:{next:"end"}}})}),K.command("delete <plan_id>").description("Delete a visual plan").action(async(q)=>{let{format:Q}=L($.opts());if(await N(U().visualPlans.delete({plan_id:A("visual_plans",q)})),Q==="json"){P({success:!0});return}T("Plan deleted")}),K.command("validate [plan_id]").description("Validate a plan (saved draft or local file)").option("--file <path>","Validate a local execution plan JSON file").action(async(q,Q)=>{let{format:W}=L($.opts());if(Q.file!=null){let j=await wJ(Q.file),Y=await N(U().visualPlans.validate({execution_plan:j}));if(W==="json"){P(Y);return}sB(Y),process.exit(Y.valid?0:1)}if(q==null)x("Provide a plan ID or --file <path>"),process.exit(2);let J=await N(U().visualPlans.validate({plan_id:A("visual_plans",q)}));if(W==="json"){P(J);return}sB(J),process.exit(J.valid?0:1)}),K.command("test <plan_id>").description("Start a test call for a plan").requiredOption("--extension <ext>","SIP extension to call").action(async(q,Q)=>{let{format:W}=L($.opts()),J=await N(U().testCall.start({planId:A("visual_plans",q),extension:Q.extension}));if(W==="json"){P(J);return}T(`Test call started: uuid=${J.uuid}`),z(`Test ID: ${J.testId}`),z("Use 'niva calls follow <uuid>' to watch the call")}),K.command("publish <plan_id>").description("Publish the current draft").option("--notes <text>","Publication notes").action(async(q,Q)=>{let{format:W}=L($.opts()),J=await N(U().visualPlans.publish({plan_id:A("visual_plans",q),notes:Q.notes}));if(W==="json"){P(J);return}T(`Plan published (version ${J.version})`)}),K.command("versions <plan_id>").description("List version history").action(async(q)=>{let{format:Q}=L($.opts()),W=await N(U().visualPlans.listVersions({plan_id:A("visual_plans",q)}));if(Q==="json"){P(W);return}y(["Version","Status","Published By","Published At","Notes"],W.items.map((J)=>({Version:J.version,Status:J.status,"Published By":J.last_edited_by_name??"—","Published At":J.published_at!=null?new Date(J.published_at).toLocaleString():"—",Notes:J.notes??"—"})))}),K.command("export <plan_id>").description("Export plan as JSON to stdout (pipe-friendly)").option("--execution-plan","Export only the execution plan (if published)").action(async(q,Q)=>{if(Q.executionPlan===!0){let j=(await N(U().visualPlans.listVersions({plan_id:A("visual_plans",q)}))).items.find((Y)=>Y.status==="published"&&Y.execution_plan!=null);if(j!=null)P(j.execution_plan);else x("No published version with execution plan found"),process.exit(1);return}let W=await N(U().visualPlans.getById({plan_id:A("visual_plans",q)}));P(W)})}function sB($){if($.valid){T("✓ Plan is valid");return}let U=$.issues.filter((q)=>q.severity==="error"),K=$.issues.filter((q)=>q.severity==="warning");if(U.length>0){x(`✗ ${U.length} error(s):`);for(let q of U)x(AJ(q))}if(K.length>0){z(` ${K.length} warning(s):`);for(let q of K)z(AJ(q))}}function UV($,U){$.command("schedules").description("Time-based routing schedules").command("list").description("List schedules").option("--limit <n>","Items per page","20").option("--page <n>","Page number","1").option("--search <term>","Search by name").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),J=await N(U().schedules.list({page:Number(q.page),limit:Number(q.limit),search:q.search}));if(Q==="json"){let j=W?J.items.map((Y)=>O(Y,W)):J;P(j);return}y(["ID","Name","Description"],J.items.map((j)=>({ID:j.id,Name:j.name,Description:j.description??"—"}))),H$(J)})}var vR="···";function kR($){return $===""?"—":`${vR}${$}`}function QV($,U){$.command("secrets").description("Organization secrets (read-only)").command("list").description("List secrets: name, value suffix, and how many plans use each one").option("--limit <n>","Items per page","20").option("--page <n>","Page number","1").option("--search <term>","Search by name").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),J=await N(U().secrets.list({page:Number(q.page),limit:Number(q.limit),search:q.search}));if(Q==="json"){let j=W?J.items.map((Y)=>O(Y,W)):J;P(j);return}y(["ID","Name","Description","Value","Published","Draft","Updated"],J.items.map((j)=>({ID:j.id,Name:j.name,Description:j.description??"—",Value:kR(j.value_suffix),Published:j.usage_count.published,Draft:j.usage_count.draft,Updated:new Date(j.updated_at).toLocaleString()}))),H$(J)})}var M$=N1(I1(),1);var RR=[{key:"recordings",label:"Recordings"},{key:"ttsCache",label:"TTS Cache"},{key:"audio",label:"Audio Library"},{key:"database",label:"Database"},{key:"logs",label:"Logs"},{key:"backups",label:"Backups"},{key:"system",label:"System"}];function n1($){if($<1024)return`${$} B`;if($<1048576)return`${($/1024).toFixed(1)} KB`;if($<1073741824)return`${($/1048576).toFixed(1)} MB`;return`${($/1073741824).toFixed(1)} GB`}function zR($){if($==="critical")return M$.default.red($.toUpperCase());if($==="warning")return M$.default.yellow($.toUpperCase());return M$.default.green($.toUpperCase())}function bR($){if($>0)return"+";if($<0)return"-";return""}function OR($){if($===void 0)return"not available";return $.bytes==null?"not measured":n1($.bytes)}function KV($){if($?.bytesPerDay==null)return"-";return`${bR($.bytesPerDay)}${n1(Math.abs($.bytesPerDay))}/day`}function TR($){if($?.fileCount==null)return"-";return`${$.fileCount} files`}function SR($){switch($){case"cdr":return"CDR (calls/chat)";case"trail":return"Trail (call events)";case"content":return"Content (transcriptions)";case"webhook":return"Webhook";case"audit":return"Audit";case"other":return"Other"}}function CR($){if($==="webhook")return"webhook";if($==="audit")return"audit";if($==="other")return null;return"call"}function ER($,U){let K=CR(U);if(K==null)return"-";let q=$.cleanups.find((Q)=>Q.name===K);if(q==null)return"no data";if(!q.ok)return M$.default.red("failed");return q.backlog==null?"not reported":`${q.backlog} pending`}function yR($){if($.collecting)return`${M$.default.yellow("Collecting")} - no sample yet, categories are not measured.`;if($.daysUntilFull!=null)return`Full in ~${$.daysUntilFull} days at the current net rate.`;if($.stable)return"Stable - no net growth since the last samples.";return"Collecting - not enough history for a projection yet."}function gR($){let U=Math.round($.disk.usagePercent);if(console.log(`
|
|
995
|
-
${M$.default.bold("Disk")} ${
|
|
996
|
-
${M$.default.bold("Categories")}`);for(let{key:U,label:K}of
|
|
997
|
-
${M$.default.bold("Database")}`),$.databaseClasses===void 0){console.log(` ${M$.default.dim("Not available - requires platform_storage:manage.")}`);return}if($.databaseClasses.length===0){console.log(` ${M$.default.yellow("Collecting")} - no sample yet.`);return}let U=$.databaseClasses.reduce((K,q)=>K+q.bytes,0);console.log(` Sum by class: ${M$.default.cyan(n1(U))}`),console.log(` ${"Class".padEnd(22)} ${"Size".padEnd(10)} ${"Rows (est.)".padEnd(11)} ${"Oldest".padEnd(11)} ${"Growth".padEnd(13)} ${"Retention".padEnd(18)} ${"Reclaimable (est.)".padEnd(18)} Last pass`);for(let K of $.databaseClasses)
|
|
998
|
-
${M$.default.bold("Cleanups")}`),$.cleanups.length===0){console.log(` ${M$.default.dim("No data - no pass has been recorded yet.")}`);return}for(let U of $.cleanups){let K=U.ok?M$.default.green("ok".padEnd(16)):M$.default.red("failed".padEnd(16)),q=U.backlog==null?"not reported":`${U.backlog} pending`;console.log(` ${U.name.padEnd(10)} ${K} deleted ${U.deleted} backlog ${q}`)}}function
|
|
999
|
-
${M$.default.bold("Thresholds")}`),console.log(` Warning: ${$.thresholds.warning}%`),console.log(` Critical: ${$.thresholds.critical}%`)}function qV($,U){$.command("storage").description("Storage observability and cache stats").command("usage").description("Show storage usage breakdown").action(async()=>{let{format:q}=L($.opts()),Q=await N(U().dashboard.storageUsage({}));if(q==="json"){P(Q);return}gR(Q),uR(Q),mR(Q),hR(Q),cR(Q),console.log()})}function WV($,U){let K=$.command("tenants").description("Manage tenants");K.command("list").description("List tenants").action(()=>F1()),K.command("create").description("Create a tenant").action(()=>F1())}function JV($,U){let K=$.command("tts").description("Text-to-speech resources (to synthesize audio, see: niva audio-files generate-tts)");K.command("voices").description("List available TTS voices").option("--language <code>","Filter by language (e.g., pt-BR)").option("--model <model>","Filter by TTS model").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),J=await N(U().tts.listVoices({language:q.language,model:q.model}));if(Q==="json"){let j=W?J.map((Y)=>O(Y,W)):J;P(j);return}y(["ID","Name","Gender","Languages","Model"],J.map((j)=>({ID:j.id,Name:j.name,Gender:j.gender??"-",Languages:j.languages.join(", "),Model:j.model})))}),K.command("models").description("List available TTS models").action(async()=>{let{format:q,fields:Q}=L($.opts()),W=await N(U().tts.listModels());if(q==="json"){let J=Q?W.map((j)=>O(j,Q)):W;P(J);return}y(["ID","Name","Provider"],W.map((J)=>({ID:J.id,Name:J.name,Provider:J.provider})))}),K.command("languages").description("List available TTS languages").action(async()=>{let{format:q}=L($.opts()),Q=await N(U().tts.listLanguages());if(q==="json"){P(Q);return}y(["Language"],Q.map((W)=>({Language:W})))})}function lR($){return $.fields.map((U)=>`${U.name}${U.required?"":"?"}${U.nullable?"|null":""}`).join(", ")}function GV($,U){$.command("webhooks").description("Inspect webhook contracts and event schemas").command("events").description("List webhook event schemas, required modules, fields, and examples").action(async()=>{let{format:q,fields:Q}=L($.opts()),W=await N(U().webhooks.events.list());if(q==="json"){P(Q?W.map((J)=>O(J,Q)):W);return}y(["Event","Module","Fields"],W.map((J)=>({Event:J.event,Module:J.required_module??"core",Fields:lR(J)})))})}function jV($,U,K){let q=$.command("ws").description("WebSocket chat — connect to a published plan");q.command("chat <plan_id>").description("Start an interactive WebSocket chat session with a published plan").action(async(Q)=>{let W=t1($.opts()),J=K();z("Creating WebSocket session...");let j=await N(U().ws.createSession({planId:A("visual_plans",Q)}));if(W==="json"){P(j);return}T(`Session created: ${j.sessionId}`),await $2(g4(J.url,j.wsUrl))}),q.command("session <plan_id>").description("Create a WebSocket session (returns sessionId + wsUrl)").action(async(Q)=>{let W=t1($.opts()),J=await N(U().ws.createSession({planId:A("visual_plans",Q)})),j=K(),Y=g4(j.url,J.wsUrl);if(W==="json"){P({...J,ws_url:Y});return}T(`Session: ${J.sessionId}`),console.log(` WebSocket URL: ${Y}`),console.log(` Connect with: websocat ${Y}`)})}function YV($,U,K,q){Tj($),Vj($,K,q),cB($),_B($),KG($,U),LG($,U),bG($,U),Nj($,U),rB($,U),$V($,U),mB($,U),hH($,U),PB($,U),SB($,U),fH($,U),xj($,U),bj($,U),uH($,U),UV($,U),QV($,U),tB($,U),qV($,U),WV($,U),JV($,U),jV($,U,K),Oj($,U,K),GV($,U),OB($)}function rR($){try{let{hostname:U}=new URL($);return U.endsWith(".orb.local")||process.env.NIVA_INSECURE==="true"}catch{return!1}}class HV extends Error{constructor(){super("Your session has expired. Run 'niva login' to authenticate again.")}}function iR($){let U=$.fetchImpl??fetch,K=async()=>{try{return await $.refresh()}catch(q){if(q instanceof L$)throw new HV;throw q}};return async(q)=>{let Q=$.getSession();if(t0(Q))Q=await K();let W=new Request(q);W.headers.set("authorization",`Bearer ${Q.access_token}`);let J=await U(W);if(J.status===401){Q=await K();let j=new Request(q);j.headers.set("authorization",`Bearer ${Q.access_token}`),J=await U(j)}return J}}function XV($,U,K){if(rR($))process.env.NODE_TLS_REJECT_UNAUTHORIZED="0";if(U.kind!=="oauth"){let W=new j4({url:new URL("/api/rpc",$).href,headers:()=>U.kind==="api-key"?{"X-API-Key":U.apiKey}:{}});return G4(W)}let q=U.session,Q=new j4({url:new URL("/api/rpc",$).href,fetch:iR({getSession:()=>q,refresh:async()=>{return q=await a0(K,q),C4(K,q),q}})});return G4(Q)}import{readFileSync as dR}from"node:fs";var oR=1500,nR="/cli/compatibilidade",s8=null;function pR(){if(s8!=null)return s8;let $='[{"niva_min":"2.0.0","niva_max":null,"dist_tag":"niva-2.0"}]',U='{"min":"2.0.0","max":null}',K=null;if(typeof U==="string"&&typeof $==="string"){let q=JSON.parse(U),Q=JSON.parse($);K=ZV(q,Q)}else{let q=JSON.parse(tR()),Q=G$(q)?q.supported_niva:void 0,W=G$(q)?q.compat_table:void 0;K=ZV(Q,W)}if(K==null)throw Error("Invalid apps/cli/compat.json, fix the compat table");return s8=K,s8}function ZV($,U){if(!G$($)||!Array.isArray(U))return null;let K=l($.min);if(K==null)return null;let q=l($.max)??null,Q=[];for(let W of A$(U)){let J=l(W.niva_min),j=l(W.dist_tag);if(J==null||j==null)return null;Q.push({niva_min:J,niva_max:l(W.niva_max)??null,dist_tag:j})}return{supported_niva:{min:K,max:q},compat_table:Q}}function tR(){return dR(new URL("../../compat.json",import.meta.url),"utf-8")}function vJ($){let K=($.split("-")[0]?.split("+")[0]??"").split(".");if(K.length!==3)return null;let q=K.map((Q)=>Number.parseInt(Q,10));if(q.some((Q)=>!Number.isFinite(Q)||Q<0))return null;return[q[0],q[1],q[2]]}function e8($,U){let K=vJ($),q=vJ(U);if(K===null||q===null)return 0;for(let Q=0;Q<3;Q++)if(K[Q]!==q[Q])return K[Q]-q[Q];return 0}function aR($,U){let{min:K,max:q}=U.supported_niva;if(e8($,K)<0)return!1;if(q!=null&&e8($,q)>0)return!1;return!0}function sR($,U){for(let K of U.compat_table){if(e8($,K.niva_min)<0)continue;if(K.niva_max!=null&&e8($,K.niva_max)>0)continue;return K.dist_tag}return null}function eR($,U,K){let{min:q,max:Q}=K.supported_niva,W=Q==null?`>= ${q}`:`>= ${q} <= ${Q}`,J=sR($,K),j=J==null?`See ${nR}`:`For the compatible release: npx @sippulse/niva@${J} <command>`;return`warning: this CLI (${w6()}) supports NIVA ${W}; ${U} reports ${$}. Some commands may not exist. ${j}`}async function $z($,U=fetch){let K=new AbortController,q=setTimeout(()=>K.abort(),oR);try{let Q=await U(new URL("/api/version",$).href,{signal:K.signal,headers:{accept:"application/json"}});if(!Q.ok)return null;let W=await Q.json();if(W===null||typeof W!=="object"||!("niva_version"in W))return null;let J=W.niva_version;if(typeof J!=="string"||vJ(J)===null)return null;return J}catch{return null}finally{clearTimeout(q)}}var Uz=null;async function BV($,U={}){if(!$)return;let K=U.config??pR(),q=await $z($,U.fetchImpl);if(q===null)return;if(Uz=q,aR(q,K))return;console.error(eR(q,$,K))}import{chmodSync as F1$,mkdirSync as x1$,readFileSync as Qz,writeFileSync as w1$}from"node:fs";import{homedir as Kz}from"node:os";import{join as DV}from"node:path";var qz=DV(Kz(),".niva"),Wz=DV(qz,"config.json"),VV={url:"http://localhost:3000",apiKey:""};function MV($,U){let K=$[U];return typeof K==="string"?K:void 0}function kJ(){try{let $=JSON.parse(Qz(Wz,"utf-8"));return G$($)?$:{}}catch{return{}}}function PV(){return kJ()}function NV($){if($.flagApiKey!=null&&$.flagApiKey!=="")return{kind:"api-key",apiKey:$.flagApiKey};if($.envApiKey!=null&&$.envApiKey!=="")return{kind:"api-key",apiKey:$.envApiKey};if($.session!=null)return{kind:"oauth",session:$.session};if($.fileApiKey!=null&&$.fileApiKey!=="")return{kind:"api-key",apiKey:$.fileApiKey};return{kind:"none"}}function Jz($){let U=G$($)?{...$}:void 0;if(U==null)return!1;let K=U.scopes;return typeof U.access_token==="string"&&typeof U.refresh_token==="string"&&typeof U.expires_at==="number"&&typeof U.org_id==="string"&&Array.isArray(K)&&K.every((q)=>typeof q==="string")}function Gz(){let $=kJ().auth;return G$($)?$:{}}function LV(){let $={};for(let[U,K]of Object.entries(Gz()))if(Jz(K))$[U]=K;return $}function _V($){let U=kJ();return{url:$.url??process.env.NIVA_URL??MV(U,"url")??VV.url,apiKey:$.apiKey??process.env.NIVA_API_KEY??MV(U,"apiKey")??VV.apiKey}}var jz="table",Yz="";function IV($){jz=$}function FV($){Yz=$}var Hz=new Set(["json","table","plain"]);function Xz($){return Hz.has($)}function Zz(){return process.stdout.isTTY===!0&&process.env.NO_COLOR==null}function xV($){if($.output!=null)return Xz($.output)?$.output:"table";if($.json===!0)return"json";return Zz()?"table":"json"}function wV(){return"0.4.0-rc.1"}var z0=new iJ("niva").description("NIVA CLI \u2014 manage your IVR platform").version(wV()).option("--url <url>","Server URL (overrides NIVA_URL / config)").option("--api-key <key>","API key (overrides NIVA_API_KEY / config)").option("--output <format>","Output format: json, table, plain (default: auto-detect TTY)").option("--json","Shorthand for --output json").option("--fields <list>","Comma-separated fields to include in JSON output").option("--yes","Skip confirmation prompts").option("--no-color","Disable colors").hook("preAction",()=>{let $=z0.opts(),U=xV({json:$.json===!0,output:typeof $.output==="string"?$.output:void 0});IV(U)}).hook("preAction",async()=>{await BV(K3().url)}),$3;function K3(){if($3!=null)return $3;let $=z0.opts();return $3=_V({url:typeof $.url==="string"?$.url:void 0,apiKey:typeof $.apiKey==="string"?$.apiKey:void 0}),$3}var U3;function AV(){if(U3!=null)return U3;let $=K3(),U=PV(),K=z0.opts().apiKey;return U3=NV({flagApiKey:typeof K==="string"?K:void 0,envApiKey:process.env.NIVA_API_KEY,fileApiKey:typeof U.apiKey==="string"?U.apiKey:void 0,session:LV()[W3($.url)]}),U3}var Q3;function Bz(){if(Q3!=null)return Q3;let $=K3();FV($.url);let U=AV();if(U.kind==="none")console.error("Error: No credential configured."),console.error(" Run: niva login"),console.error(" Or set: niva config set api-key <your-key>"),console.error(" Or env: NIVA_API_KEY=niva_xxx"),process.exit(1);return Q3=XV($.url,U,W3($.url)),Q3}YV(z0,Bz,K3,AV);z0.parseAsync().catch(($)=>{console.error($ instanceof Error?$.message:String($)),process.exit(1)});
|
|
1004
|
+
`)}function rk($,U){if(!xG(U))throw Error(`Refusing to stamp a malformed CLI version: ${JSON.stringify(U)}`);let K=uB.exec($),q=K?.[1];if(K==null||q==null)return $;return`---
|
|
1005
|
+
${lk(q,U)}
|
|
1006
|
+
---${$.slice(K.index+K[0].length)}`}var ik=["skills","niva-cli","references"];function dk($,U){let K=Sk(U,$);return K===""||!K.startsWith("..")&&!yB(K)}function ok($,U){let K;try{K=OB($)}catch{return`${$} does not exist or cannot be resolved.`}let q=$;for(let Q of[U,...ik]){q=d1(q,Q);let W=CB(q,{throwIfNoEntry:!1});if(W==null)return;if(W.isSymbolicLink()){let G;try{G=OB(q)}catch{return`${q} is a broken symlink — remove it and retry.`}if(!dk(G,K))return`${q} is a symlink pointing outside ${K} (${G}) — refusing to write through it.`}if(!bk(q).isDirectory())return`${q} already exists and is not a directory — remove it and retry.`}return}function nk($){try{return ck(EB($,"utf-8"))}catch{return}}function pk($,U,K){if(!SB($))return;let q=nk($);if(q==null)R(`Existing skill found in ${U} (version unknown) — overwriting.`);else if(q===K)R(`Existing skill found in ${U} — overwriting.`);else R(`Updating skill in ${U} from ${q} to ${K}.`)}var fB=".niva-install.json",tk=[A4,"references/cli-reference.md","references/node-handles.md","references/signals.md"];function ak($){if(typeof $!=="string"||$===""||yB($)||$.includes("\\"))return!1;return!$.split("/").some((U)=>U===".."||U==="."||U==="")}function sk($){try{let U=JSON.parse(EB(d1($,fB),"utf-8"));if(typeof U!=="object"||U===null||!("files"in U)||!Array.isArray(U.files))return[];return U.files.filter((K)=>ak(K))}catch{return SB(d1($,A4))?[...tk]:[]}}function ek($,U,K){for(let q of U){if(K.has(q))continue;let Q=d1($,q);if(CB(Q,{throwIfNoEntry:!1})?.isFile()===!0)Rk(Q)}}function $z($,U,K){let q=Object.keys(K);try{ek($,sk($),new Set(q));for(let[Q,W]of Object.entries(K)){let G=d1($,Q);zk(Tk(G),{recursive:!0}),TB(G,W)}TB(d1($,fB),`${JSON.stringify({version:1,files:q},null,2)}
|
|
1007
|
+
`)}catch(Q){x(`Error: could not write ${U} — ${Q instanceof Error?Q.message:String(Q)}`),process.exit(w.GENERAL_ERROR)}}function mB($){$.command("install-skill").description("Install the NIVA CLI agent skill (.agents/ and/or .claude/)").option("--global","Install to the home directory instead of the current project").option("--target <target>","Install target: claude, agents, or both (asks when omitted)").action(async(U)=>{let K=await mk({target:U.target,yes:$.opts().yes===!0,interactive:R6()}),q=A6();if(!xG(q))x(`Error: CLI_VERSION is not a plain version string (${JSON.stringify(q)}) — refusing to write the skill.`),process.exit(w.USAGE_ERROR);let Q=U.global===!0,W=Q?gk():process.cwd(),G=Q?"~/":"",j=Ck[K],Y=j.map((I)=>ok(W,I)).filter((I)=>I!=null);if(Y.length>0){for(let I of Y)x(`Error: ${I}`);R("Nothing was installed."),process.exit(w.GENERAL_ERROR)}let H=bB(),X=H[A4];if(X==null)x(`Error: this build carries no ${A4} — reinstall the CLI.`),process.exit(w.GENERAL_ERROR);let B={...H,[A4]:rk(X,q)},M=[];for(let I of j){let E=d1(W,I,"skills","niva-cli"),u=`${G}${I}/skills/niva-cli/`;pk(d1(E,A4),u,q),$z(E,u,B),M.push(u)}T(`NIVA CLI skill v${q} installed to:`);for(let I of M)T(` ${I}`);R("Your coding agent will now use the NIVA CLI for IVR management tasks.")})}var o1=N1(I1(),1);var Uz=["server","engine","freeswitch","traefik","redis","postgres","client","docs"],Qz={error:o1.default.red,warn:o1.default.yellow,info:o1.default.green,debug:o1.default.dim};function Kz($){if($==null)return;let U=$.error;if(U!=null&&typeof U==="object"&&"message"in U){let K=U.message;if(typeof K==="string")return K}return}function hB($){let U=new Date($.ts),K=Number.isNaN(U.getTime())?$.ts:`${String(U.getHours()).padStart(2,"0")}:${String(U.getMinutes()).padStart(2,"0")}:${String(U.getSeconds()).padStart(2,"0")}`,Q=(Qz[$.level]??((Y)=>Y))($.level.toUpperCase().padEnd(5)),W=o1.default.cyan(`[${$.service}]`),G=`${o1.default.dim(K)} ${W} ${Q} ${$.message}`,j=Kz($.meta);if(j!=null)G+=o1.default.red(` — ${j}`);return G}function wG($,U={}){if($.option("--since <v>","Start time — relative (e.g. 1h, 30m, 45s) or ISO date").option("--until <v>","End time — relative or ISO date"),U.fixedLevel!==!0)$.option("--level <level>","Minimum severity: error, warn, info, debug");return $.option("--grep <regex>","Filter messages by case-insensitive regex").option("--limit <n>","Max entries per page","200").option("--cursor <c>","Pagination cursor from a previous page's nextCursor").option("--follow","Stream new entries in real time (Ctrl+C to stop)"),$}async function qz($,U){return new Promise((K,q)=>{S1($,{onEvent:(Q)=>{if(U==="json")console.log(JSON.stringify(Q));else console.log(hB(Q))},onError:(Q)=>{if(Q instanceof DOMException&&Q.name==="AbortError"){K();return}q(Q)},onSuccess:()=>K()})})}async function Wz($,U,K){let q=new AbortController;process.on("SIGINT",()=>{q.abort()});try{await qz($.system.watchLogs(U,{signal:q.signal}),K)}catch(Q){Q1(Q)}}async function AG($,U,K,q,Q){let{format:W,fields:G}=L(K.opts()),j=P$(Q??U.level);if(U.follow===!0){await Wz(q(),{service:$,level:j,grep:U.grep},W);return}let Y={service:$,since:U.since,until:U.until,level:j,grep:U.grep,limit:U.limit!=null?Number(U.limit):void 0,cursor:U.cursor},H=await N(q().system.logs(Y));if(W==="json"){for(let X of H.entries){let B=G?O(X,G):X;console.log(JSON.stringify(B))}if(H.nextCursor!=null)console.log(JSON.stringify({nextCursor:H.nextCursor}));return}if(H.entries.length===0){R("No log entries.");return}for(let X of H.entries)console.log(hB(X));if(H.nextCursor!=null)R(`
|
|
1008
|
+
Next page: --cursor ${H.nextCursor}`)}function cB($,U){let K=$.command("logs").description("View service logs and call events");K.command("calls").description("View call events").option("--call-record <id>","Call record id: a call_... TypeID or the raw UUID of the row").option("--uuid <id>","Deprecated alias for --call-record").option("--follow","Stream events in real-time").action(async(W)=>{if(W.follow===!0)F1("Live call-event streaming is not available here. Use `niva calls follow <uuid>` to stream a call's live transcription.");let G=W.callRecord??W.uuid;if(G==null)F1("Please provide --call-record or --follow.");let{format:j,fields:Y}=L($.opts()),H=await N(U().callRecords.getEvents({call_record_id:A("call_records",G)}));if(j==="json"){let X=Y?H.map((B)=>O(B,Y)):H;P(X);return}if(H.length===0){R("No events found.");return}y(["Timestamp","Event","Details"],H.map((X)=>({Timestamp:new Date(X.entered_at).toLocaleString(),Event:X.node_type,Details:X.data!=null?JSON.stringify(X.data):"—"})))});for(let W of Uz){let G=K.command(W).description(`View ${W} service logs from the appliance journal`);wG(G),G.action(async(j)=>AG(W,j,$,U))}let q=K.command("errors").description("View error-level logs across all services (merged timeline)");wG(q,{fixedLevel:!0}),q.action(async(W)=>AG("all",W,$,U,"error"));let Q=K.command("all").description("View a merged timeline of logs from all services");wG(Q),Q.action(async(W)=>AG("all",W,$,U))}import{readFile as Jz,writeFile as oB}from"node:fs/promises";import{basename as jz}from"node:path";function lB($){if($==null)return'""';return`"${String($).replaceAll('"','""')}"`}function rB($,U,K=","){let q=[$.map((Q)=>lB(Q)).join(K)];for(let Q of U)q.push(Q.map((W)=>lB(W)).join(K));return q.join(`\r
|
|
1009
|
+
`)}function iB($){let U=0,K=0,q=!1;for(let Q=0;Q<$.length;Q+=1){let W=$[Q];if(W==='"'){if(q&&$[Q+1]==='"'){Q+=1;continue}q=!q}else if(!q){if(W===",")U+=1;else if(W===";")K+=1}}return K>U?";":","}function Gz($,U){let K="",q=U;for(;q<$.length;q+=1){let Q=$[q];if(Q!=='"')K+=Q;else if($[q+1]==='"')K+='"',q+=1;else return{value:K,end:q}}return{value:K,end:q}}function dB($,U){let K=[],q="",Q=!1,W=0;while(W<$.length){let G=$[W];if(G==='"'){let j=Gz($,W+1);q+=j.value,W=j.end,Q=!0}else if(G===U)K.push(Q?q:q.trim()),q="",Q=!1;else q+=G;W+=1}return K.push(Q?q:q.trim()),K}var kG=["phone_number","name","status","attempt_count","machine_attempts","machine_type","last_attempt_at"],Yz=new Set(kG);function vG($,U){return[...U,$]}function nB($){let U={};for(let K of $){let q=K.indexOf("=");if(q<=0)x(`Invalid --field "${K}" (expected key=value)`),process.exit(w.USAGE_ERROR);U[K.slice(0,q)]=K.slice(q+1)}return U}function Hz($){return $==="phone"||$==="name"||$==="ignore"||/^custom:.+$/.test($)}function Xz($,U){if(U==null)return iB($);if(U!==","&&U!==";")x(`Invalid --separator "${U}" (must be , or ;)`),process.exit(w.USAGE_ERROR);return U}function Zz($,U){let K=Qq($),q={};for(let Q of $){let W=K.roles[Q]??"ignore";if(W!=="custom"){q[Q]=W;continue}let G=K.customNames[Q];q[Q]=G!=null&&G.length>0?`custom:${G}`:"ignore"}for(let Q of U){let W=Q.indexOf("=");if(W<=0)x(`Invalid --map "${Q}" (expected <Column>=<role>)`),process.exit(w.USAGE_ERROR);let G=Q.slice(0,W),j=Q.slice(W+1);if(!$.includes(G))x(`Unknown column "${G}". Available: ${$.join(", ")}`),process.exit(w.USAGE_ERROR);if(!Hz(j))x(`Invalid role "${j}" for column "${G}" (phone|name|ignore|custom:<field>)`),process.exit(w.USAGE_ERROR);q[G]=j}return q}function Bz($){if($==null)return"—";if(typeof $==="string")return $;if(typeof $==="number"||typeof $==="boolean")return String($);return JSON.stringify($)}async function Vz($,U,K){let q=new AbortController;process.on("SIGINT",()=>q.abort());let Q="",W=0;if(await new Promise((G,j)=>{S1($.dialerImports.progress({import_job_id:A("dialer_import_jobs",U)},{signal:q.signal}),{onEvent:(Y)=>{if(Q=Y.status,W=Y.invalid,K==="json")console.log(JSON.stringify(Y));else{let H=Y.total_rows!=null?String(Y.total_rows):"-";R(`[${Y.status}] processed ${Y.processed_rows}/${H} · imported ${Y.imported} · skipped ${Y.skipped} · invalid ${Y.invalid}`)}if(Y.status==="done"||Y.status==="failed")G()},onError:(Y)=>{if(Y instanceof DOMException&&Y.name==="AbortError"){G();return}j(Y)},onSuccess:()=>G()})}).catch(R4),Q==="failed")return w.GENERAL_ERROR;if(Q==="done"&&W>0&&K!=="json")R(`${W} invalid row(s). Inspect with: niva mailing invalid-rows ${U}`);return w.SUCCESS}function pB($,U){let K=$.command("mailing").description("Manage campaign mailing (contacts & imports)");K.command("list <campaign_id>").description("List contacts of a campaign mailing").option("--status <s>","Filter by contact status").option("--search <t>","Search by phone or name").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(q,Q)=>{let{format:W,fields:G}=L($.opts()),j=await N(U().dialerContacts.list({campaign_id:A("dialer_campaigns",q),page:Number(Q.page),limit:Number(Q.limit),status:P$(Q.status),search:Q.search}));if(W==="json"){P(G?j.items.map((Y)=>O(Y,G)):j);return}y(["ID","Phone","Name","Status","Attempts","Machine","Last attempt"],j.items.map((Y)=>({ID:Y.id,Phone:Y.phone_number,Name:Y.name??"—",Status:Y.status,Attempts:Y.attempt_count,Machine:y0(Y.machine_type),"Last attempt":Y.last_attempt_at!=null?j1(Y.last_attempt_at):"—"}))),Z$(j)}),K.command("show <campaign_id> <contact_id>").description("Show a mailing contact with its custom fields").action(async(q,Q)=>{let{format:W,fields:G}=L($.opts()),j=await N(U().dialerContacts.get({campaign_id:A("dialer_campaigns",q),contact_id:A("dialer_contacts",Q)}));if(W==="json"){P(G?O(j,G):j);return}let Y=[{title:"Contact",rows:[{label:"ID",value:j.id},{label:"Phone",value:j.phone_number},{label:"Name",value:j.name??"—"},{label:"Status",value:j.status},{label:"Attempts",value:j.attempt_count},{label:"Last attempt",value:j.last_attempt_at!=null?new Date(j.last_attempt_at).toLocaleString():"—"},{label:"Next attempt",value:j.next_attempt_at!=null?new Date(j.next_attempt_at).toLocaleString():"—"},{label:"Created",value:new Date(j.created_at).toLocaleString()}]}],H=j.custom_fields;if(H!=null&&typeof H==="object"&&!Array.isArray(H)&&Object.keys(H).length>0)Y.push({title:"Custom fields",rows:Object.entries(H).map(([X,B])=>({label:X,value:Bz(B)}))});o(Y)}),K.command("add <campaign_id> <phone>").description("Add a single contact to a campaign mailing").option("--name <n>","Contact name").option("--field <pair>","Custom field key=value (repeatable)",vG,[]).action(async(q,Q,W)=>{let{format:G}=L($.opts()),j=nB(W.field),Y=await N(U().dialerContacts.add({campaign_id:A("dialer_campaigns",q),phone_number:Q,name:W.name,custom_fields:Object.keys(j).length>0?j:void 0}));if(G==="json"){P(Y);return}T(`Contact added: ${Y.id}`)}),K.command("edit <campaign_id> <contact_id>").description("Edit a pending mailing contact (only provided fields)").option("--phone <p>","New phone number").option("--name <n>","New contact name").option("--field <pair>","Custom field key=value (repeatable)",vG,[]).action(async(q,Q,W)=>{let{format:G}=L($.opts()),j=await N(U().dialerContacts.update({campaign_id:A("dialer_campaigns",q),contact_id:A("dialer_contacts",Q),...W.phone!=null&&{phone_number:W.phone},...W.name!=null&&{name:W.name},...W.field.length>0&&{custom_fields:nB(W.field)}}));if(G==="json"){P(j);return}T("Contact updated")}),K.command("remove <campaign_id> <contactIds...>").description("Remove (soft-delete) mailing contacts").action(async(q,Q)=>{let{format:W}=L($.opts()),G=await N(U().dialerContacts.remove({campaign_id:A("dialer_campaigns",q),ids:A("dialer_contacts",Q)}));if(W==="json"){P(G);return}T(`Removed ${G.removed}, skipped ${G.skipped}`)}),K.command("cancel <campaign_id> <contactIds...>").description("Cancel pending mailing contacts").action(async(q,Q)=>{let{format:W}=L($.opts()),G=await N(U().dialerContacts.bulkCancel({campaign_id:A("dialer_campaigns",q),ids:A("dialer_contacts",Q)}));if(W==="json"){P(G);return}T(`Cancelled ${G.cancelled}, skipped ${G.skipped}`)}),K.command("requeue <campaign_id> [contactIds...]").description("Requeue terminal contacts (lead recycling): pass IDs, or --all").option("--all","Requeue every terminal contact of the campaign").option("--status <terminal>","Restrict --all to a single terminal status").action(async(q,Q,W)=>{let{format:G}=L($.opts()),j=Q.length>0;if(j&&W.all===!0)x("Use either <contactIds...> or --all, not both"),process.exit(w.USAGE_ERROR);if(!j&&W.all!==!0)x("Provide contact IDs or --all to requeue"),process.exit(w.USAGE_ERROR);if(j){let H=await N(U().dialerContacts.bulkRequeue({campaign_id:A("dialer_campaigns",q),ids:A("dialer_contacts",Q)}));if(G==="json"){P(H);return}T(`Requeued ${H.requeued}, skipped ${H.skipped}`);return}let Y=await N(U().dialerContacts.requeueAll({campaign_id:A("dialer_campaigns",q),status:P$(W.status)}));if(G==="json"){P(Y);return}T(`Requeued ${Y.requeued}`)}),K.command("import <campaign_id> <file>").description("Import a CSV mailing into a campaign").option("--map <pair>","Column mapping override <Column>=<role> (repeatable)",vG,[]).option("--separator <sep>","CSV separator (, or ;) — sniffed when omitted").option("--watch","Follow import progress until it finishes").action(async(q,Q,W)=>{let{format:G}=L($.opts()),j=$.opts().yes===!0,Y=await Jz(Q),H=Y.toString("utf-8"),X=H.search(/\r\n|\n|\r/),B=X===-1?H:H.slice(0,X);if(B.trim()==="")x("File is empty or has no header row"),process.exit(w.USAGE_ERROR);let M=Xz(B,W.separator),I=dB(B,M),E=Zz(I,W.map);if(G!=="json")y(["Column","Role"],I.map((S$)=>({Column:S$,Role:E[S$]??"ignore"})));await d$("Import with this mapping?",{yes:j});let u=U(),U$=await N(u.dialerImports.create({campaign_id:A("dialer_campaigns",q),column_mapping:E,file:new File([Y],jz(Q))}));if(G!=="json")T(`Import started: ${U$.id} (${U$.status})`);else if(W.watch!==!0)P(U$);if(W.watch===!0){let S$=await Vz(u,U$.id,G);if(S$!==w.SUCCESS)process.exit(S$)}}),K.command("import-status <import_job_id>").description("Show the status of a mailing import job").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),G=await N(U().dialerImports.get({import_job_id:A("dialer_import_jobs",q)}));if(Q==="json"){P(W?O(G,W):G);return}o([{title:"Import job",rows:[{label:"ID",value:G.id},{label:"Status",value:G.status},{label:"Total rows",value:G.total_rows??"—"},{label:"Processed",value:G.processed_rows},{label:"Imported",value:G.imported},{label:"Skipped",value:G.skipped},{label:"Invalid",value:G.invalid},{label:"Has invalid rows",value:G.has_invalid_rows?"yes":"no"},{label:"Created",value:new Date(G.created_at).toLocaleString()}]}])}),K.command("invalid-rows <import_job_id>").description("Output the CSV of rows an import rejected").option("-o, --out <file>","Write the CSV to a file instead of stdout").action(async(q,Q)=>{let W=await N(U().dialerImports.invalidRows({import_job_id:A("dialer_import_jobs",q)}));if(W==null){R("No invalid rows.");return}if(Q.out!=null){await oB(Q.out,W.csv,"utf-8"),T(`Wrote invalid rows to ${Q.out}`);return}process.stdout.write(W.csv)}),K.command("export <campaign_id>").description("Export a campaign mailing to CSV (stdout or -o file)").option("--status <s>","Filter by contact status").option("--search <t>","Search by phone or name").option("-o, --out <file>","Write the CSV to a file instead of stdout").action(async(q,Q)=>{let W=await N(U().dialerContacts.exportCsv({campaign_id:A("dialer_campaigns",q),status:P$(Q.status),search:Q.search})),G=[],j=new Set;for await(let M of W){G.push(M);for(let I of Object.keys(M))if(!Yz.has(I))j.add(I)}if(G.length===0){R("No contacts to export.");return}let Y=[...j].sort((M,I)=>M.localeCompare(I)),H=[...kG,...Y],X=G.map((M)=>[...kG.map((I)=>M[I]??""),...Y.map((I)=>M[I]??"")]),B=rB(H,X);if(Q.out!=null){await oB(Q.out,B,"utf-8"),T(`Wrote ${G.length} contacts to ${Q.out}`);return}process.stdout.write(B)})}function tB($){if(!($ in p$))console.error(`Unknown node type: ${$}`),console.error(`Available: ${Object.keys(p$).join(", ")}`),process.exit(2)}function zG($){return t$[$]?.connector}function Mz($){return`${$.kind} (config key ${$.configKey}) - create it with niva connectors create ${$.kind}`}function Dz($){return $ in _4}function aB($){let U=$.command("nodes").description("IVR node types reference");U.command("list").description("List node types with module, channel and the connector kind a block needs (- when none)").option("--module <module>","Filter by module (core, ai)").option("--category <cat>","Filter by category (interaction, handling, routing, data, legacy)").option("--channel <ch>","Filter by channel (voice, chat, both)").action((K)=>{let{format:q,fields:Q}=L($.opts()),W=aW();if(K.module!=null)W=W.filter((G)=>G.module===K.module);if(K.category!=null)W=W.filter((G)=>G.category===K.category);if(K.channel!=null)W=W.filter((G)=>G.channel===K.channel);if(q==="json"){let G=W.map((j)=>({...j,connector:zG(j.type)??null}));P(Q?G.map((j)=>O(j,Q)):G);return}y(["Type","Name","Description","Module","Channel","Connector"],W.map((G)=>({Type:G.type,Name:G.name,Description:G.description,Module:G.module,Channel:G.channel,Connector:zG(G.type)?.kind??"-"})))}),U.command("show <type>").description("Show a node type: config fields, outputs, variables and the connector it needs").action((K)=>{let{format:q}=L($.opts());tB(K);let Q=F0(K),W=zG(K);if(q==="json"){P({...Q,connector:W??null});return}let G=Dz(K)?_4[K]:void 0,j=G!=null?Object.entries(G).map(([Y,H])=>({label:Y,value:String(H)})):[{label:"(no fields)",value:""}];o([{title:`${Q.name} (${Q.type})`,rows:[{label:"Description",value:Q.description},{label:"Module",value:Q.module},{label:"Category",value:Q.category},{label:"Channel",value:Q.channel},{label:"Nature",value:Q.nature},...W!=null?[{label:"Connector",value:Mz(W)}]:[]]},{title:"Config Fields",rows:j},{title:"Outputs",rows:Q.outputs.map((Y)=>({label:Y.key,value:Y.labelKey}))},{title:"Produced Variables",rows:Q.producedVariables.length>0?Q.producedVariables.map((Y)=>({label:`${Y.name} (${Y.type})`,value:Y.descriptionKey})):[{label:"(none)",value:""}]}])}),U.command("schema <type>").description("Output JSON Schema for a node's config (agent-friendly)").action((K)=>{tB(K);let q=F0(K);P(q.configJsonSchema)})}function sB($,U,K){let q=$.indexOf("=");if(q===-1)throw Error(`${K} expects key=value (got: ${$})`);let Q=$.slice(0,q),W=$.slice(q+1);if(Q==="")throw Error(`${K} expects key=value (got: ${$})`);return U[Q]=W,U}function Pz($,U){return sB($,U,"--var")}function Nz($,U){return sB($,U,"--metadata")}function Lz($){return $==="pre"||$==="post"}function _z($){let U=$.amd===!0||$.machineType===!0;if($.amdMode!==void 0&&!U)x("--amd-mode requires --amd or --machine-type"),process.exit(w.USAGE_ERROR);if($.amdMaxWait!==void 0&&$.amdMode!=="pre")x("--amd-max-wait requires --amd-mode pre"),process.exit(w.USAGE_ERROR);let K;if($.amdMode!==void 0){if(!Lz($.amdMode))x(`Invalid --amd-mode "${$.amdMode}": expected pre or post`),process.exit(w.USAGE_ERROR);K=$.amdMode}let q=$.amdMaxWait===void 0?void 0:Number($.amdMaxWait);if(q!==void 0&&(!Number.isInteger(q)||q<3||q>10))x(`Invalid --amd-max-wait "${$.amdMaxWait}": expected an integer from 3 to 10`),process.exit(w.USAGE_ERROR);if(!U)return;let Q=$.machineType===!0?{amd:!0,machine_type:!0}:{amd:!0};if(K==="pre")return{...Q,mode:K,max_wait_seconds:q??6};if(K==="post")return{...Q,mode:K};return Q}function eB($,U){$.command("originate").description("Originate outbound calls").command("start").description("Start an outbound call that runs a published visual plan").requiredOption("--plan <id>","Visual plan TypeID (e.g. vp_...)").requiredOption("--destination <target>","Destination: number, number@host, or sofia/... URI").option("--caller-id <number>","Caller ID number to present").option("--caller-id-name <name>","Caller ID display name").option("--amd","Beta: detect whether a machine or human answered").option("--machine-type","Beta: identify voicemail, carrier announcement, IVR, or call screening; requires licensed AI and a SipPulse AI key").option("--amd-mode <mode>","AMD timing mode: pre waits before the plan; post runs in parallel (pre|post)").option("--amd-max-wait <seconds>","Absolute pre-plan AMD wait in seconds (3-10; default 6)").option("--timeout <seconds>","Ring timeout in seconds (10-120)","30").option("--max-duration <seconds>","Maximum call duration after answer in seconds (1-14400)").option("--var <key=value>","Plan input available as {{args.<key>}}; repeatable",Pz,{}).option("--metadata <key=value>","Opaque call metadata persisted with the CDR; repeatable",Nz,{}).action(async(q)=>{let{format:Q}=L($.opts()),W=Object.entries(q.var),G=Object.entries(q.metadata),j=_z(q),Y={plan_id:A("visual_plans",q.plan),destination:q.destination,timeout:Number(q.timeout),...q.maxDuration!==void 0?{max_call_duration_s:Number(q.maxDuration)}:{},...q.callerId!==void 0?{caller_id:q.callerId}:{},...q.callerIdName!==void 0?{caller_id_name:q.callerIdName}:{},...j!==void 0?{answer_recognition:j}:{},...W.length>0?{variables:q.var}:{},...G.length>0?{metadata:q.metadata}:{}},H=await N(U().calls.originate(Y));if(Q==="json")P(H);else if(H.status==="failed")$1(`Originate outcome: status=failed call_id=${H.call_id} channel_uuid=${H.channel_uuid} answered_at=${H.answered_at??"none"} hangup_cause=${H.hangup_cause??"unknown"} sip_code=${H.sip_code??"unknown"}`);else T(`Originate outcome: status=answered call_id=${H.call_id} channel_uuid=${H.channel_uuid} answered_at=${H.answered_at??"none"} hangup_cause=${H.hangup_cause??"none"} sip_code=${H.sip_code??"none"}`);if(H.status==="failed")process.exit(w.GENERAL_ERROR)})}import{readFile as jV}from"node:fs/promises";import{readFile as Iz}from"node:fs/promises";function Fz($){return"usage_count"in $}function xz($){let U=Math.max(0,Math.floor($)),K=Math.floor(U/60),q=U%60;return`${String(K).padStart(2,"0")}:${String(q).padStart(2,"0")}`}function wz($){return $==="caller"?"Cliente":"Atendimento"}function $V($){if($==null||$==="pt-BR")return"pt-BR";if($==="en")return"en";x(`Error: invalid --locale "${$}" — expected one of: pt-BR, en`),process.exit(w.USAGE_ERROR)}async function KV($){let U=$==="-"?await v$():await Iz($,"utf-8"),K;try{K=JSON.parse(U)}catch{x(`Invalid JSON in "${$}"`),process.exit(w.USAGE_ERROR)}if(!Q$(K))x(`Invalid signal file "${$}": expected a JSON object`),process.exit(w.USAGE_ERROR);return K}function qV($,U){let K=$.slug==null&&U!=null?{...$,slug:U}:$,q=P6.safeParse(K);if(!q.success){x("Invalid signal definition:");for(let Q of q.error.issues)x(` ✗ ${Q.path.join(".")||"(root)"}: ${Q.message}`);process.exit(w.USAGE_ERROR)}return q.data}function Az($){return P6.parse({slug:$.slug,name:$.name,question:$.question,kind:$.kind,...$.options!==void 0?{options:$.options}:{},...$.levels!==void 0?{levels:$.levels}:{},...$.higher_is!==void 0?{higher_is:$.higher_is}:{},speaker:$.speaker,scope:$.scope,live:$.live,alert:$.alert})}async function R0($,U){return(await N($.signals.list({search:U,limit:100,page:1,include_archived:!0}))).items.find((q)=>q.slug===U)}function vz($){if($4($).kind==="uuid")return!0;let U=$.lastIndexOf("_");return U>0&&v6($.slice(0,U))==="signals"}async function UV($,U){if(!vz(U))return R0($,U);let K=await N($.signals.get({signal_id:A("signals",U)}));return await R0($,K.slug)??K}function kz($){if("answer"in $)return $.answer==="yes"?"for Sim":"for Não";if("options"in $)return`for ${$.options.join(", ")}`;if("level_at_most"in $)return`dropping to level ${$.level_at_most}`;return`reaching level ${$.level_at_least}`}function zz($){let U=$.description!=null?` — ${$.description}`:"",K=$.archived?" (archived)":"";return`${$.label}${U}${K}`}function QV($){for(let U of $.turns){let K=U.index===$.first_trigger_index?" <- would trigger":"";console.log(`${xz(U.start)} ${wz(U.speaker)} ${U.value_label}${K}`)}console.log(`Fim da chamada ${$.final==null?"ninguém falou no trecho que o signal escuta":$.final.value_label}`)}async function Rz($,U,K){if(U.file!=null)return qV(await KV(U.file),"test_signal");if(U.preset!=null){let Q=o3.find((W)=>W.id===U.preset);if(Q==null)x(`Error: unknown preset "${U.preset}".`),R(` Valid presets: ${o3.map((W)=>W.id).join(", ")}`),process.exit(w.USAGE_ERROR);return eW(Q,K)}let q=await R0($,U.slug??"");if(q==null)x(`Signal "${U.slug}" not found.`),process.exit(w.NOT_FOUND);return Az(q)}function bz($,U,K){if($.text!=null)return{definition:U,text:$.text,locale:K};if($.call!=null)return{definition:U,call_id:A("call_records",$.call),locale:K};return{definition:U,visual_plan_id:A("visual_plans",$.plan??""),last:$.last!=null?Number($.last):void 0,locale:K}}function WV($,U){let K=$.command("signals").description("Signal library and testing");K.command("presets").description("List the ten signal models").option("--locale <locale>","Locale of the texts: pt-BR or en","pt-BR").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),G=$V(q.locale),j=await N(U().signals.presets({locale:G}));if(Q==="json"){P(W?j.map((Y)=>O(Y,W)):j);return}y(["ID","Name","Kind","Speaker","Live","Severity"],j.map((Y)=>({ID:Y.id,Name:Y.definition.name,Kind:Y.definition.kind,Speaker:Y.definition.speaker,Live:Y.definition.live?"yes":"no",Severity:Y.definition.alert?.severity??"—"})))}),K.command("list").description("List the organization's signal library").option("--search <term>","Search by name or slug").option("--include-archived","Include archived signals").option("--limit <n>","Items per page","20").option("--page <n>","Page number","1").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),G=await N(U().signals.list({page:Number(q.page),limit:Number(q.limit),search:q.search,include_archived:q.includeArchived===!0}));if(Q==="json"){let j=W?G.items.map((Y)=>O(Y,W)):G;P(j);return}y(["Slug","Name","Kind","Live","Org default","Usage","Fires 7d","Version","Archived"],G.items.map((j)=>({Slug:j.slug,Name:j.name,Kind:j.kind,Live:j.live?"yes":"no","Org default":j.is_org_default?"yes":"no",Usage:`${j.usage_count.published}/${j.usage_count.draft}`,"Fires 7d":j.fires_last_7_days.reduce((Y,H)=>Y+H,0),Version:j.version,Archived:j.archived_at!=null?"yes":"no"}))),Z$(G)}),K.command("show <slug_or_id>").description("Show one signal (slug or sig_... TypeID) with its usage").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),G=await UV(U(),q);if(G==null)x(`Signal "${q}" not found.`),process.exit(w.NOT_FOUND);if(Q==="json"){P(W?O(G,W):G);return}let j=[{title:"Signal",rows:[{label:"ID",value:G.id},{label:"Slug",value:G.slug},{label:"Name",value:G.name},{label:"Question",value:G.question},{label:"Kind",value:G.kind},...G.higher_is!==void 0?[{label:"Higher is",value:G.higher_is}]:[],{label:"Speaker",value:G.speaker},{label:"Scope",value:G.scope?.node_types.join(", ")??"whole call"},{label:"Live",value:G.live?"yes":"no"},{label:"Org default",value:G.is_org_default?"yes":"no"},{label:"Version",value:G.version},{label:"Archived",value:G.archived_at!=null?"yes":"no"}]},{title:"Alert",rows:G.alert==null?[{label:"When",value:"—"}]:[{label:"When",value:kz(G.alert.when)},{label:"Severity",value:G.alert.severity},{label:"Bell",value:G.alert.bell?"yes":"no"}]}];if(G.options!==void 0)j.push({title:"Options",rows:G.options.map((Y)=>({label:Y.key,value:zz(Y)}))});if(G.levels!==void 0)j.push({title:"Levels",rows:G.levels.map((Y,H)=>({label:String(H+1),value:Y}))});if(Fz(G))j.push({title:"Usage",rows:[{label:"Published plans",value:G.usage_count.published},{label:"Draft plans",value:G.usage_count.draft},{label:"Fires 7d",value:G.fires_last_7_days.reduce((Y,H)=>Y+H,0)},{label:"Evaluated calls 7d",value:G.evaluated_calls_last_7_days.reduce((Y,H)=>Y+H,0)}]});o(j)}),K.command("test").description("Test a definition against a text, a recorded call or a plan's last calls").option("--file <path>","JSON file with the definition (- for stdin)").option("--preset <id>","Start from one of the ten models").option("--slug <slug>","Use a saved signal from the library").option("--text <text>","Evaluate a single caller utterance").option("--call <call_id>","Replay a recorded call turn by turn").option("--plan <plan_id>","Replay the plan's last transcribed calls").option("--last <n>","How many calls to replay with --plan (1-5)").option("--locale <locale>","Locale: pt-BR or en","pt-BR").action(async(q)=>{let{format:Q}=L($.opts()),W=U(),G=$V(q.locale),j=[q.file,q.preset,q.slug].filter((M)=>M!=null).length,Y=[q.text,q.call,q.plan].filter((M)=>M!=null).length;if(j!==1||Y!==1)x("Error: signals test needs exactly one definition source (--file, --preset or --slug) and exactly one evaluation source (--text, --call or --plan)."),process.exit(w.USAGE_ERROR);if(q.last!=null&&q.plan==null)x("Error: --last only applies with --plan."),process.exit(w.USAGE_ERROR);let H=await Rz(W,q,G),X=bz(q,H,G),B=await N(W.signals.test(X));if(Q==="json"){P(B);return}if("calls"in B)B.calls.forEach((M,I)=>{if(I>0)console.log("");console.log(`Call ${M.call_id}`),QV(M)});else if("turns"in B)QV(B);else console.log(`${B.value_label}${B.would_trigger?" <- would trigger":""}`)}),K.command("apply").description("Create or update a signal by slug (idempotent)").requiredOption("--file <path>","JSON file with the signal body (- for stdin)").option("--dry-run","Show what would change without writing").action(async(q)=>{let{format:Q}=L($.opts()),W=U(),G=await KV(q.file),j=qV(G),Y=typeof G.is_org_default==="boolean"?G.is_org_default:void 0,H=await N(W.signals.upsertBySlug({...j,...Y!==void 0?{is_org_default:Y}:{},dry_run:q.dryRun===!0}));if(Q==="json"){P(H);return}Oz(H.status,H.changed_fields,H.signal.slug,q.dryRun===!0)}),K.command("delete <slug_or_id>").description("Move a signal to the trash (slug or sig_... TypeID)").action(async(q)=>{let{format:Q}=L($.opts()),W=await UV(U(),q);if(W==null)x(`Signal "${q}" not found.`),process.exit(w.NOT_FOUND);let G=await N(U().signals.delete({signal_id:A("signals",W.id)}));if(Q==="json"){P(G);return}T(`Signal moved to the trash: ${G.slug}. Restore it from Settings > Archive.`)})}function Oz($,U,K,q){if($==="created"){T(q?`would create: ${K}`:`created: ${K}`);return}if($==="unchanged"){R(`unchanged: ${K}`);return}T(q?`would update: ${K} (changed: ${U.join(", ")})`:`updated: ${K} (changed: ${U.join(", ")})`)}async function RG($){let U=$==="-"?await v$():await jV($,"utf-8"),K=mW.safeParse(JSON.parse(U));if(!K.success){x(`Invalid execution plan in "${$}":`);for(let q of K.error.issues)x(` ✗ ${q.path.join(".")||"(root)"}: ${q.message}`);process.exit(w.GENERAL_ERROR)}return K.data}function v4($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function Tz($){if(!v4($)||!Array.isArray($.nodes)||!Array.isArray($.edges))return!1;let U=$.viewport;return v4(U)&&typeof U.x==="number"&&typeof U.y==="number"&&typeof U.zoom==="number"}async function Sz($){let U=$==="-"?await v$():await jV($,"utf-8"),K;try{K=JSON.parse(U)}catch{x(`Invalid JSON in plan export "${$}"`),process.exit(w.GENERAL_ERROR)}let q;if(v4(K)&&K.format==="niva-plan-v1")q=K.state;else if(v4(K)&&v4(K.draft)&&K.draft.editor_state!=null)q=K.draft.editor_state;else if(v4(K)&&K.published_editor_state!=null)q=K.published_editor_state;else if(v4(K)&&Array.isArray(K.nodes)&&Array.isArray(K.edges))q=K;else x(`Invalid plan export in "${$}"`),process.exit(w.GENERAL_ERROR);if(!Tz(q))x(`Invalid editor state in plan export "${$}"`),process.exit(w.GENERAL_ERROR);return q}function bG($){let U=$.severity==="error"?"✗":"⚠",K=$.node_id!=null?` [${$.node_id}]`:"";return` ${U}${K} ${$.message_key}`}var Cz="! Partial validation: structure only. References to secrets, schedules, sub-plans, audio files and AI agents were NOT checked - run 'niva plans validate --file <path>' for the full check against this server.";function GV($){try{let U=tK($),K=KG(U.nodes,U.edges,t$);if(!WG(K)){for(let q of K)x(bG({node_id:q.nodeId,severity:q.severity,message_key:q.messageKey}));return!1}return $1(Cz),!0}catch(U){return x(U instanceof Error?U.message:String(U)),!1}}async function Ez($,U,K,q){if(await N($.channels.update({channel_id:A("channels",U),visual_plan_id:A("visual_plans",K),reassign:!0})),q!=="json")T(`Channel ${U} assigned to plan`)}async function yz($,U,K){if(await N($.channels.update({channel_id:A("channels",U),visual_plan_id:null})),K!=="json")T(`Channel ${U} unassigned from plan`)}async function gz($,U,K){let q=A("visual_plans",U),Q=await N($.channels.list({page:1,limit:100})),W=Q.items.filter((j)=>j.visual_plan_id===q),G=Q.items.filter((j)=>j.visual_plan_id==null);if(K==="json"){P({assigned:W,available:G});return}if(W.length>0)console.log(`
|
|
1010
|
+
Assigned to this plan:`),y(["ID","Type","Name","Identifier","Active"],W.map((j)=>({ID:j.id,Type:j.channel_type,Name:j.name,Identifier:j.identifier??"—",Active:j.is_active?"yes":"no"})));if(G.length>0)console.log(`
|
|
1011
|
+
Available (unassigned):`),y(["ID","Type","Name","Identifier"],G.map((j)=>({ID:j.id,Type:j.channel_type,Name:j.name,Identifier:j.identifier??"—"})))}function uz($,U){return{plan_id:A("visual_plans",$),...U.name!=null&&{name:U.name},...U.description!=null&&{description:U.description},...U.recording!==void 0&&{recording_enabled:U.recording},...U.transcription!==void 0&&{transcription_enabled:U.transcription},...U.transcriptionLanguage!=null&&{transcription_language:U.transcriptionLanguage},...U.anonymize!==void 0&&{anonymize_enabled:U.anonymize},...U.speechAnalytics!==void 0&&{speech_analytics_enabled:U.speechAnalytics},...U.sentiment!==void 0&&{sentiment_enabled:U.sentiment},...U.topics!=null&&{topic_detection_topics:U.topics.split(",").map((K)=>K.trim())},...U.intents!=null&&{intent_detection_intents:U.intents.split(",").map((K)=>K.trim())},...U.signalsInherit!==void 0&&{signals_inherit_org:U.signalsInherit}}}async function fz($,U,K,q,Q,W){let G=U.startsWith("-")?"-":"+",j=U.startsWith("+")||U.startsWith("-")?U.slice(1):U,Y=await R0($,j);if(Y==null){Q.push(j);return}if(G==="-"){q.delete(Y.id);return}if(q.add(Y.id),Y.live===!0&&K.transcription_type!=="live")W.push(`Signal "${Y.name}" runs live, but this plan uses ${K.transcription_type} transcription: it only runs at the end of the call until the plan switches to live transcription.`)}async function mz($,U,K){let q=await N($.visualPlans.getById({plan_id:A("visual_plans",U)})),Q=q.signals_inherit_org===!0,W=new Set(Q?await hz($):q.signal_ids),G=[],j=[];for(let Y of K.split(",")){let H=Y.trim();if(H==="")continue;await fz($,H,q,W,G,j)}if(G.length>0)x(`Unknown signal slug(s): ${G.join(", ")}`),R("List the library with: niva signals list"),process.exit(w.USAGE_ERROR);return{signal_ids:[...W].sort((Y,H)=>Y.localeCompare(H)),warnings:j,switchedToCustom:Q}}async function hz($){let U=[],K=1;for(;;){let q=await N($.signals.list({page:K,limit:100,include_archived:!1}));for(let Q of q.items)if(Q.is_org_default)U.push(Q.id);if(q.page>=q.total_pages)break;K+=1}return U}function YV($,U){let K=$.command("plans").description("Manage visual plans");K.command("list").description("List visual plans").option("--limit <n>","Items per page","20").option("--page <n>","Page number","1").option("--search <term>","Search by name").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),G=await N(U().visualPlans.list({page:Number(q.page),limit:Number(q.limit),search:q.search}));if(Q==="json"){let j=W?G.items.map((Y)=>O(Y,W)):G;P(j);return}y(["ID","Name","Status","Created"],G.items.map((j)=>({ID:j.id,Name:j.name,Status:j.published_version_id!=null?"published":"draft",Created:new Date(j.created_at).toLocaleDateString()}))),Z$(G)}),K.command("show <plan_id>").description("Show plan details with settings").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),G=await N(U().visualPlans.getById({plan_id:A("visual_plans",q)}));if(Q==="json"){let j=W?O(G,W):G;P(j);return}o([{title:"Plan",rows:[{label:"ID",value:G.id},{label:"Name",value:G.name},{label:"Status",value:G.published_version_id!=null?"published":"draft"},{label:"Created",value:new Date(G.created_at).toLocaleString()},{label:"Updated",value:new Date(G.updated_at).toLocaleString()}]},{title:"Settings",rows:[{label:"Recording",value:G.recording_enabled?"enabled":"disabled"},{label:"Transcription",value:G.transcription_enabled?"enabled":"disabled"},{label:"Language",value:G.transcription_language??"—"},{label:"Anonymize",value:G.anonymize_enabled?"enabled":"disabled"},{label:"Call Summary",value:G.speech_analytics_enabled?"enabled":"disabled"},{label:"Sentiment",value:G.sentiment_enabled?"enabled":"disabled"}]}])}),K.command("create <name>").description("Create a new visual plan").option("--language <code>","Language code (e.g., pt-BR)").option("--description <text>","Plan description").option("--execution-plan <file>","JSON file with execution plan (- for stdin)").option("--recording","Enable recording").option("--transcription","Enable transcription").action(async(q,Q)=>{let{format:W}=L($.opts()),G;if(Q.executionPlan!=null){if(G=await RG(Q.executionPlan),!GV(G))process.exit(1)}let j=await N(U().visualPlans.create({name:q,language:Q.language,description:Q.description,recording_enabled:Q.recording??!1,transcription_enabled:Q.transcription??!1,execution_plan:G}));if(W==="json"){P(j);return}T(`Plan created: ${j.id}`)}),K.command("edit <plan_id>").description("Update plan draft with a new execution plan").option("--execution-plan <file>","JSON file with execution plan (- for stdin)","-").option("--expected-revision <n>","Expected draft revision (optimistic locking)").action(async(q,Q)=>{let{format:W}=L($.opts()),G=await RG(Q.executionPlan);if(!GV(G))process.exit(1);let j=await N(U().visualPlans.saveDraft({plan_id:A("visual_plans",q),execution_plan:G,expected_revision:Q.expectedRevision!=null?Number(Q.expectedRevision):void 0}));if(W==="json"){P(j);return}T(`Draft updated (revision ${j.revision})`)}),K.command("import <plan_id> <file>").description("Import a browser or CLI-exported plan JSON as the draft of an existing destination plan").action(async(q,Q)=>{let{format:W}=L($.opts()),G=await Sz(Q),j=await N(U().visualPlans.importDraft({plan_id:A("visual_plans",q),editor_state:G}));if(W==="json"){P(j);return}T(`Draft imported (revision ${j.revision})`)}),K.command("configure <plan_id>").description("Configure plan settings, metadata, and DIDs").option("--name <name>","Plan name").option("--description <text>","Plan description").option("--recording","Enable recording").option("--no-recording","Disable recording").option("--transcription","Enable transcription").option("--no-transcription","Disable transcription").option("--transcription-language <code>","Transcription language").option("--anonymize","Enable anonymization").option("--no-anonymize","Disable anonymization").option("--speech-analytics","Enable call summary and key points").option("--no-speech-analytics","Disable call summary and key points").option("--sentiment","Enable sentiment analysis").option("--no-sentiment","Disable sentiment analysis").option("--topics <list>","Legacy topic hints (comma-separated)").option("--intents <list>","Legacy intent hints (comma-separated)").option("--signals <list>","Link signals (comma-separated: +slug to add, -slug to remove, bare slug to add)").option("--signals-inherit","Follow the organization's signal library").option("--no-signals-inherit","Own the plan's signal list").option("--assign-did <id>","Assign a phone number to this plan").option("--unassign-did <id>","Unassign a phone number from this plan").option("--list-dids","List DIDs assigned to this plan").action(async(q,Q)=>{let{format:W}=L($.opts()),G=U();if(Q.assignDid!=null)await Ez(G,Q.assignDid,q,W);if(Q.unassignDid!=null)await yz(G,Q.unassignDid,W);if(Q.listDids===!0){await gz(G,q,W);return}let j=uz(q,Q);if(Q.signals!=null){if(Q.signalsInherit===!0)x("Error: --signals cannot be combined with --signals-inherit: the plan follows the organization and would ignore the list."),process.exit(w.USAGE_ERROR);let{signal_ids:Y,warnings:H,switchedToCustom:X}=await mz(G,q,Q.signals);if(j.signal_ids=Y,X)j.signals_inherit_org=!1,$1("This plan now chooses its own signals instead of following the organization.");for(let B of H)$1(B)}if(Object.keys(j).length>1){let Y=await N(G.visualPlans.update(j));if(W==="json"){P(Y);return}T("Plan configuration updated")}}),K.command("scaffold").description("Output a minimal valid execution plan JSON template").option("--channel <type>","Channel type: voice, chat, both","both").action((q)=>{let Q=["voice","chat","both"];if(!Q.includes(q.channel))x(`Invalid channel type: ${q.channel}. Must be one of: ${Q.join(", ")}`),process.exit(2);let W=q.channel;P({version:1,startNodeId:"start",nodes:{start:{type:"start",label:"Start",varName:"start",config:W==="both"?{}:{channelType:W}},greeting:{type:"tell",label:"Greeting",varName:"greeting",config:{audio:{tts:{text:"Olá! Como posso ajudá-lo?",voice:"pt-BR-FranciscaNeural",model:"edge"}},content:{type:"text",text:"Olá! Como posso ajudá-lo?"}}},end:{type:"hangup",label:"End",varName:"end",config:{}}},adjacency:{start:W==="both"?{voice:"greeting",chat:"greeting"}:{next:"greeting"},greeting:{next:"end"}}})}),K.command("delete <plan_id>").description("Delete a visual plan").action(async(q)=>{let{format:Q}=L($.opts());if(await N(U().visualPlans.delete({plan_id:A("visual_plans",q)})),Q==="json"){P({success:!0});return}T("Plan deleted")}),K.command("validate [plan_id]").description("Validate a plan (saved draft or local file)").option("--file <path>","Validate a local execution plan JSON file").action(async(q,Q)=>{let{format:W}=L($.opts());if(Q.file!=null){let j=await RG(Q.file),Y=await N(U().visualPlans.validate({execution_plan:j}));if(W==="json"){P(Y);return}JV(Y),process.exit(Y.valid?0:1)}if(q==null)x("Provide a plan ID or --file <path>"),process.exit(2);let G=await N(U().visualPlans.validate({plan_id:A("visual_plans",q)}));if(W==="json"){P(G);return}JV(G),process.exit(G.valid?0:1)}),K.command("test <plan_id>").description("Start a test call for a plan").requiredOption("--extension <ext>","SIP extension to call").action(async(q,Q)=>{let{format:W}=L($.opts()),G=await N(U().testCall.start({planId:A("visual_plans",q),extension:Q.extension}));if(W==="json"){P(G);return}T(`Test call started: uuid=${G.uuid}`),R(`Test ID: ${G.testId}`),R("Use 'niva calls follow <uuid>' to watch the call")}),K.command("publish <plan_id>").description("Publish the current draft").option("--notes <text>","Publication notes").action(async(q,Q)=>{let{format:W}=L($.opts()),G=await N(U().visualPlans.publish({plan_id:A("visual_plans",q),notes:Q.notes}));if(W==="json"){P(G);return}T(`Plan published (version ${G.version})`)}),K.command("versions <plan_id>").description("List version history").action(async(q)=>{let{format:Q}=L($.opts()),W=await N(U().visualPlans.listVersions({plan_id:A("visual_plans",q)}));if(Q==="json"){P(W);return}y(["Version","Status","Published By","Published At","Notes"],W.items.map((G)=>({Version:G.version,Status:G.status,"Published By":G.last_edited_by_name??"—","Published At":G.published_at!=null?new Date(G.published_at).toLocaleString():"—",Notes:G.notes??"—"})))}),K.command("export <plan_id>").description("Export plan as JSON to stdout (pipe-friendly)").option("--execution-plan","Export only the execution plan (if published)").action(async(q,Q)=>{if(Q.executionPlan===!0){let j=(await N(U().visualPlans.listVersions({plan_id:A("visual_plans",q)}))).items.find((Y)=>Y.status==="published"&&Y.execution_plan!=null);if(j!=null)P(j.execution_plan);else x("No published version with execution plan found"),process.exit(1);return}let W=await N(U().visualPlans.getById({plan_id:A("visual_plans",q)}));P(W)})}function JV($){if($.valid){T("✓ Plan is valid");return}let U=$.issues.filter((q)=>q.severity==="error"),K=$.issues.filter((q)=>q.severity==="warning");if(U.length>0){x(`✗ ${U.length} error(s):`);for(let q of U)x(bG(q))}if(K.length>0){R(` ${K.length} warning(s):`);for(let q of K)R(bG(q))}}function HV($,U){$.command("schedules").description("Time-based routing schedules").command("list").description("List schedules").option("--limit <n>","Items per page","20").option("--page <n>","Page number","1").option("--search <term>","Search by name").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),G=await N(U().schedules.list({page:Number(q.page),limit:Number(q.limit),search:q.search}));if(Q==="json"){let j=W?G.items.map((Y)=>O(Y,W)):G;P(j);return}y(["ID","Name","Description"],G.items.map((j)=>({ID:j.id,Name:j.name,Description:j.description??"—"}))),Z$(G)})}var cz="···";function lz($){return $===""?"—":`${cz}${$}`}function XV($,U){$.command("secrets").description("Organization secrets (read-only)").command("list").description("List secrets: name, value suffix, and how many plans use each one").option("--limit <n>","Items per page","20").option("--page <n>","Page number","1").option("--search <term>","Search by name").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),G=await N(U().secrets.list({page:Number(q.page),limit:Number(q.limit),search:q.search}));if(Q==="json"){let j=W?G.items.map((Y)=>O(Y,W)):G;P(j);return}y(["ID","Name","Description","Value","Published","Draft","Updated"],G.items.map((j)=>({ID:j.id,Name:j.name,Description:j.description??"—",Value:lz(j.value_suffix),Published:j.usage_count.published,Draft:j.usage_count.draft,Updated:new Date(j.updated_at).toLocaleString()}))),Z$(G)})}var M$=N1(I1(),1);var rz=[{key:"recordings",label:"Recordings"},{key:"ttsCache",label:"TTS Cache"},{key:"audio",label:"Audio Library"},{key:"database",label:"Database"},{key:"logs",label:"Logs"},{key:"backups",label:"Backups"},{key:"system",label:"System"}];function n1($){if($<1024)return`${$} B`;if($<1048576)return`${($/1024).toFixed(1)} KB`;if($<1073741824)return`${($/1048576).toFixed(1)} MB`;return`${($/1073741824).toFixed(1)} GB`}function iz($){if($==="critical")return M$.default.red($.toUpperCase());if($==="warning")return M$.default.yellow($.toUpperCase());return M$.default.green($.toUpperCase())}function dz($){if($>0)return"+";if($<0)return"-";return""}function oz($){if($===void 0)return"not available";return $.bytes==null?"not measured":n1($.bytes)}function ZV($){if($?.bytesPerDay==null)return"-";return`${dz($.bytesPerDay)}${n1(Math.abs($.bytesPerDay))}/day`}function nz($){if($?.fileCount==null)return"-";return`${$.fileCount} files`}function pz($){switch($){case"cdr":return"CDR (calls/chat)";case"trail":return"Trail (call events)";case"content":return"Content (transcriptions)";case"webhook":return"Webhook";case"audit":return"Audit";case"other":return"Other"}}function tz($){if($==="webhook")return"webhook";if($==="audit")return"audit";if($==="other")return null;return"call"}function az($,U){let K=tz(U);if(K==null)return"-";let q=$.cleanups.find((Q)=>Q.name===K);if(q==null)return"no data";if(!q.ok)return M$.default.red("failed");return q.backlog==null?"not reported":`${q.backlog} pending`}function sz($){if($.collecting)return`${M$.default.yellow("Collecting")} - no sample yet, categories are not measured.`;if($.daysUntilFull!=null)return`Full in ~${$.daysUntilFull} days at the current net rate.`;if($.stable)return"Stable - no net growth since the last samples.";return"Collecting - not enough history for a projection yet."}function ez($){let U=Math.round($.disk.usagePercent);if(console.log(`
|
|
1012
|
+
${M$.default.bold("Disk")} ${iz($.status)}`),console.log(` Total: ${n1($.disk.totalBytes)}`),console.log(` Used: ${n1($.disk.usedBytes)} (${U}%)`),console.log(` Available: ${n1($.disk.availableBytes)}`),console.log(` ${a1(U,100,30)}`),console.log(` ${sz($)}`),$.retentionStartsInDays!=null)console.log(` Retention starts acting in ${$.retentionStartsInDays} days.`);if($.sampledAt!=null)console.log(` Categories measured at ${$.sampledAt}`)}function $R($){console.log(`
|
|
1013
|
+
${M$.default.bold("Categories")}`);for(let{key:U,label:K}of rz){let q=$.categories[U];console.log(` ${K.padEnd(16)} ${M$.default.cyan(oz(q).padEnd(20))} ${ZV(q).padEnd(14)} ${nz(q)}`)}}function UR($,U){let K=U.retentionDays==null?U.retentionSource:`${U.retentionDays}d (${U.retentionSource})`;console.log(` ${pz(U.class).padEnd(22)} ${n1(U.bytes).padEnd(10)} ${String(U.rows).padEnd(11)} ${(U.oldestAt?.slice(0,10)??"-").padEnd(11)} ${ZV(U).padEnd(13)} ${K.padEnd(18)} ${n1(U.reclaimableBytes).padEnd(18)} ${az($,U.class)}`)}function QR($){if(console.log(`
|
|
1014
|
+
${M$.default.bold("Database")}`),$.databaseClasses===void 0){console.log(` ${M$.default.dim("Not available - requires platform_storage:manage.")}`);return}if($.databaseClasses.length===0){console.log(` ${M$.default.yellow("Collecting")} - no sample yet.`);return}let U=$.databaseClasses.reduce((K,q)=>K+q.bytes,0);console.log(` Sum by class: ${M$.default.cyan(n1(U))}`),console.log(` ${"Class".padEnd(22)} ${"Size".padEnd(10)} ${"Rows (est.)".padEnd(11)} ${"Oldest".padEnd(11)} ${"Growth".padEnd(13)} ${"Retention".padEnd(18)} ${"Reclaimable (est.)".padEnd(18)} Last pass`);for(let K of $.databaseClasses)UR($,K);console.log(` ${M$.default.dim("Rows and reclaimable are estimates from pg_stat_user_tables (updated after ANALYZE).")}`),console.log(` ${M$.default.dim("This total adds up the NIVA tables and is below the Database line of the disk table, which includes catalog and space not yet returned to disk.")}`),console.log(` ${M$.default.dim("Retention frees space for reuse inside PostgreSQL; returning it to disk needs VACUUM FULL or pg_repack.")}`)}function KR($){if(console.log(`
|
|
1015
|
+
${M$.default.bold("Cleanups")}`),$.cleanups.length===0){console.log(` ${M$.default.dim("No data - no pass has been recorded yet.")}`);return}for(let U of $.cleanups){let K=U.ok?M$.default.green("ok".padEnd(16)):M$.default.red("failed".padEnd(16)),q=U.backlog==null?"not reported":`${U.backlog} pending`;console.log(` ${U.name.padEnd(10)} ${K} deleted ${U.deleted} backlog ${q}`)}}function qR($){console.log(`
|
|
1016
|
+
${M$.default.bold("Thresholds")}`),console.log(` Warning: ${$.thresholds.warning}%`),console.log(` Critical: ${$.thresholds.critical}%`)}function BV($,U){$.command("storage").description("Storage observability and cache stats").command("usage").description("Show storage usage breakdown").action(async()=>{let{format:q}=L($.opts()),Q=await N(U().dashboard.storageUsage({}));if(q==="json"){P(Q);return}ez(Q),$R(Q),QR(Q),KR(Q),qR(Q),console.log()})}function VV($,U){let K=$.command("tenants").description("Manage tenants");K.command("list").description("List tenants").action(()=>F1()),K.command("create").description("Create a tenant").action(()=>F1())}function MV($,U){let K=$.command("tts").description("Text-to-speech resources (to synthesize audio, see: niva audio-files generate-tts)");K.command("voices").description("List available TTS voices").option("--language <code>","Filter by language (e.g., pt-BR)").option("--model <model>","Filter by TTS model").action(async(q)=>{let{format:Q,fields:W}=L($.opts()),G=await N(U().tts.listVoices({language:q.language,model:q.model}));if(Q==="json"){let j=W?G.map((Y)=>O(Y,W)):G;P(j);return}y(["ID","Name","Gender","Languages","Model"],G.map((j)=>({ID:j.id,Name:j.name,Gender:j.gender??"-",Languages:j.languages.join(", "),Model:j.model})))}),K.command("models").description("List available TTS models").action(async()=>{let{format:q,fields:Q}=L($.opts()),W=await N(U().tts.listModels());if(q==="json"){let G=Q?W.map((j)=>O(j,Q)):W;P(G);return}y(["ID","Name","Provider"],W.map((G)=>({ID:G.id,Name:G.name,Provider:G.provider})))}),K.command("languages").description("List available TTS languages").action(async()=>{let{format:q}=L($.opts()),Q=await N(U().tts.listLanguages());if(q==="json"){P(Q);return}y(["Language"],Q.map((W)=>({Language:W})))})}function WR($){return $.fields.map((U)=>`${U.name}${U.required?"":"?"}${U.nullable?"|null":""}`).join(", ")}function DV($,U){$.command("webhooks").description("Inspect webhook contracts and event schemas").command("events").description("List webhook event schemas, required modules, fields, and examples").action(async()=>{let{format:q,fields:Q}=L($.opts()),W=await N(U().webhooks.events.list());if(q==="json"){P(Q?W.map((G)=>O(G,Q)):W);return}y(["Event","Module","Fields"],W.map((G)=>({Event:G.event,Module:G.required_module??"core",Fields:WR(G)})))})}function PV($,U,K){let q=$.command("ws").description("WebSocket chat — connect to a published plan");q.command("chat <plan_id>").description("Start an interactive WebSocket chat session with a published plan").action(async(Q)=>{let W=t1($.opts()),G=K();R("Creating WebSocket session...");let j=await N(U().ws.createSession({planId:A("visual_plans",Q)}));if(W==="json"){P(j);return}T(`Session created: ${j.sessionId}`),await t3(I6(G.url,j.wsUrl))}),q.command("session <plan_id>").description("Create a WebSocket session (returns sessionId + wsUrl)").action(async(Q)=>{let W=t1($.opts()),G=await N(U().ws.createSession({planId:A("visual_plans",Q)})),j=K(),Y=I6(j.url,G.wsUrl);if(W==="json"){P({...G,ws_url:Y});return}T(`Session: ${G.sessionId}`),console.log(` WebSocket URL: ${Y}`),console.log(` Connect with: websocat ${Y}`)})}function NV($,U,K,q){BB($),Lj($,K,q),aB($),RB($),jJ($,U),Ij($,U),wJ($,U),EJ($,U),Aj($,U),eB($,U),YV($,U),pB($,U),wB($,U),vB($,U),cB($,U),FB($,U),qB($,U),XB($,U),IB($,U),HV($,U),XV($,U),WV($,U),BV($,U),VV($,U),MV($,U),PV($,U,K),ZB($,U,K),DV($,U),mB($)}function GR($){try{let{hostname:U}=new URL($);return U.endsWith(".orb.local")||process.env.NIVA_INSECURE==="true"}catch{return!1}}class LV extends Error{constructor(){super("Your session has expired. Run 'niva login' to authenticate again.")}}function JR($){let U=$.fetchImpl??fetch,K=async()=>{try{return await $.refresh()}catch(q){if(q instanceof L$)throw new LV;throw q}};return async(q)=>{let Q=$.getSession();if(a0(Q))Q=await K();let W=new Request(q);W.headers.set("authorization",`Bearer ${Q.access_token}`);let G=await U(W);if(G.status===401){Q=await K();let j=new Request(q);j.headers.set("authorization",`Bearer ${Q.access_token}`),G=await U(j)}return G}}function _V($,U,K){if(GR($))process.env.NODE_TLS_REJECT_UNAUTHORIZED="0";if(U.kind!=="oauth"){let W=new j4({url:new URL("/api/rpc",$).href,headers:()=>U.kind==="api-key"?{"X-API-Key":U.apiKey}:{}});return J4(W)}let q=U.session,Q=new j4({url:new URL("/api/rpc",$).href,fetch:JR({getSession:()=>q,refresh:async()=>{return q=await s0(K,q),C4(K,q),q}})});return J4(Q)}import{readFileSync as jR}from"node:fs";var YR=1500,HR="/cli/compatibilidade",$8=null;function XR(){if($8!=null)return $8;let $='[{"niva_min":"2.0.0","niva_max":null,"dist_tag":"niva-2.0"}]',U='{"min":"2.0.0","max":null}',K=null;if(typeof U==="string"&&typeof $==="string"){let q=JSON.parse(U),Q=JSON.parse($);K=IV(q,Q)}else{let q=JSON.parse(ZR()),Q=Q$(q)?q.supported_niva:void 0,W=Q$(q)?q.compat_table:void 0;K=IV(Q,W)}if(K==null)throw Error("Invalid apps/cli/compat.json, fix the compat table");return $8=K,$8}function IV($,U){if(!Q$($)||!Array.isArray(U))return null;let K=l($.min);if(K==null)return null;let q=l($.max)??null,Q=[];for(let W of A$(U)){let G=l(W.niva_min),j=l(W.dist_tag);if(G==null||j==null)return null;Q.push({niva_min:G,niva_max:l(W.niva_max)??null,dist_tag:j})}return{supported_niva:{min:K,max:q},compat_table:Q}}function ZR(){return jR(new URL("../../compat.json",import.meta.url),"utf-8")}function OG($){let K=($.split("-")[0]?.split("+")[0]??"").split(".");if(K.length!==3)return null;let q=K.map((Q)=>Number.parseInt(Q,10));if(q.some((Q)=>!Number.isFinite(Q)||Q<0))return null;return[q[0],q[1],q[2]]}function U8($,U){let K=OG($),q=OG(U);if(K===null||q===null)return 0;for(let Q=0;Q<3;Q++)if(K[Q]!==q[Q])return K[Q]-q[Q];return 0}function BR($,U){let{min:K,max:q}=U.supported_niva;if(U8($,K)<0)return!1;if(q!=null&&U8($,q)>0)return!1;return!0}function VR($,U){for(let K of U.compat_table){if(U8($,K.niva_min)<0)continue;if(K.niva_max!=null&&U8($,K.niva_max)>0)continue;return K.dist_tag}return null}function MR($,U,K){let{min:q,max:Q}=K.supported_niva,W=Q==null?`>= ${q}`:`>= ${q} <= ${Q}`,G=VR($,K),j=G==null?`See ${HR}`:`For the compatible release: npx @sippulse/niva@${G} <command>`;return`warning: this CLI (${A6()}) supports NIVA ${W}; ${U} reports ${$}. Some commands may not exist. ${j}`}async function DR($,U=fetch){let K=new AbortController,q=setTimeout(()=>K.abort(),YR);try{let Q=await U(new URL("/api/version",$).href,{signal:K.signal,headers:{accept:"application/json"}});if(!Q.ok)return null;let W=await Q.json();if(W===null||typeof W!=="object"||!("niva_version"in W))return null;let G=W.niva_version;if(typeof G!=="string"||OG(G)===null)return null;return G}catch{return null}finally{clearTimeout(q)}}var PR=null;async function FV($,U={}){if(!$)return;let K=U.config??XR(),q=await DR($,U.fetchImpl);if(q===null)return;if(PR=q,BR(q,K))return;console.error(MR(q,$,K))}import{chmodSync as r1$,mkdirSync as i1$,readFileSync as NR,writeFileSync as d1$}from"node:fs";import{homedir as LR}from"node:os";import{join as AV}from"node:path";var _R=AV(LR(),".niva"),IR=AV(_R,"config.json"),xV={url:"http://localhost:3000",apiKey:""};function wV($,U){let K=$[U];return typeof K==="string"?K:void 0}function TG(){try{let $=JSON.parse(NR(IR,"utf-8"));return Q$($)?$:{}}catch{return{}}}function vV(){return TG()}function kV($){if($.flagApiKey!=null&&$.flagApiKey!=="")return{kind:"api-key",apiKey:$.flagApiKey};if($.envApiKey!=null&&$.envApiKey!=="")return{kind:"api-key",apiKey:$.envApiKey};if($.session!=null)return{kind:"oauth",session:$.session};if($.fileApiKey!=null&&$.fileApiKey!=="")return{kind:"api-key",apiKey:$.fileApiKey};return{kind:"none"}}function FR($){let U=Q$($)?{...$}:void 0;if(U==null)return!1;let K=U.scopes;return typeof U.access_token==="string"&&typeof U.refresh_token==="string"&&typeof U.expires_at==="number"&&typeof U.org_id==="string"&&Array.isArray(K)&&K.every((q)=>typeof q==="string")}function xR(){let $=TG().auth;return Q$($)?$:{}}function zV(){let $={};for(let[U,K]of Object.entries(xR()))if(FR(K))$[U]=K;return $}function RV($){let U=TG();return{url:$.url??process.env.NIVA_URL??wV(U,"url")??xV.url,apiKey:$.apiKey??process.env.NIVA_API_KEY??wV(U,"apiKey")??xV.apiKey}}var wR="table",AR="";function bV($){wR=$}function OV($){AR=$}var vR=new Set(["json","table","plain"]);function kR($){return vR.has($)}function zR(){return process.stdout.isTTY===!0&&process.env.NO_COLOR==null}function TV($){if($.output!=null)return kR($.output)?$.output:"table";if($.json===!0)return"json";return zR()?"table":"json"}function SV(){return"0.4.0"}var b0=new tG("niva").description("NIVA CLI \u2014 manage your IVR platform").version(SV()).option("--url <url>","Server URL (overrides NIVA_URL / config)").option("--api-key <key>","API key (overrides NIVA_API_KEY / config)").option("--output <format>","Output format: json, table, plain (default: auto-detect TTY)").option("--json","Shorthand for --output json").option("--fields <list>","Comma-separated fields to include in JSON output").option("--yes","Skip confirmation prompts").option("--no-color","Disable colors").hook("preAction",()=>{let $=b0.opts(),U=TV({json:$.json===!0,output:typeof $.output==="string"?$.output:void 0});bV(U)}).hook("preAction",async()=>{await FV(W8().url)}),Q8;function W8(){if(Q8!=null)return Q8;let $=b0.opts();return Q8=RV({url:typeof $.url==="string"?$.url:void 0,apiKey:typeof $.apiKey==="string"?$.apiKey:void 0}),Q8}var K8;function CV(){if(K8!=null)return K8;let $=W8(),U=vV(),K=b0.opts().apiKey;return K8=kV({flagApiKey:typeof K==="string"?K:void 0,envApiKey:process.env.NIVA_API_KEY,fileApiKey:typeof U.apiKey==="string"?U.apiKey:void 0,session:zV()[J8($.url)]}),K8}var q8;function RR(){if(q8!=null)return q8;let $=W8();OV($.url);let U=CV();if(U.kind==="none")console.error("Error: No credential configured."),console.error(" Run: niva login"),console.error(" Or set: niva config set api-key <your-key>"),console.error(" Or env: NIVA_API_KEY=niva_xxx"),process.exit(1);return q8=_V($.url,U,J8($.url)),q8}NV(b0,RR,W8,CV);b0.parseAsync().catch(($)=>{console.error($ instanceof Error?$.message:String($)),process.exit(1)});
|