@sippulse/niva 0.2.0 → 0.3.1-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -11
- package/index.js +499 -92
- package/package.json +2 -2
package/index.js
CHANGED
|
@@ -1,108 +1,104 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// @bun
|
|
3
|
-
import{createRequire as
|
|
4
|
-
`)}displayWidth($){return
|
|
5
|
-
`+" ".repeat(
|
|
6
|
-
${
|
|
7
|
-
`)}}function
|
|
3
|
+
import{createRequire as oB}from"node:module";var uB=Object.create;var{getPrototypeOf:fB,defineProperty:b8,getOwnPropertyNames:hB}=Object;var mB=Object.prototype.hasOwnProperty;function cB($){return this[$]}var lB,rB,M1=($,U,Q)=>{var q=$!=null&&typeof $==="object";if(q){var K=U?lB??=new WeakMap:rB??=new WeakMap,W=K.get($);if(W)return W}Q=$!=null?uB(fB($)):{};let J=U||!$||!$.__esModule?b8(Q,"default",{value:$,enumerable:!0}):Q;for(let G of hB($))if(!mB.call(J,G))b8(J,G,{get:cB.bind($,G),enumerable:!0});if(q)K.set($,J);return J};var V1=($,U)=>()=>(U||$((U={exports:{}}).exports,U),U.exports);var nB=($)=>$;function iB($,U){this[$]=nB.bind(null,U)}var q1=($,U)=>{for(var Q in U)b8($,Q,{get:U[Q],enumerable:!0,configurable:!0,set:iB.bind(U,Q)})};var Q6=oB(import.meta.url);var q6=V1((dB)=>{class O8 extends Error{constructor($,U,Q){super(Q);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=U,this.exitCode=$,this.nestedError=void 0}}class IW extends O8{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}dB.CommanderError=O8;dB.InvalidArgumentError=IW});var Q0=V1((eB)=>{var{InvalidArgumentError:aB}=q6();class _W{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,Q)=>{if(!this.argChoices.includes(U))throw new aB(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(U,Q);return U},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function sB($){let U=$.name()+($.variadic===!0?"...":"");return $.required?"<"+U+">":"["+U+"]"}eB.Argument=_W;eB.humanReadableArgName=sB});var R8=V1((QZ)=>{var{humanReadableArgName:KZ}=Q0();class LW{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),Q=$._getHelpCommand();if(Q&&!Q._hidden)U.push(Q);if(this.sortSubcommands)U.sort((q,K)=>{return q.name().localeCompare(K.name())});return U}compareOptions($,U){let Q=(q)=>{return q.short?q.short.replace(/^-/,""):q.long.replace(/^--/,"")};return Q($).localeCompare(Q(U))}visibleOptions($){let U=$.options.filter((q)=>!q.hidden),Q=$._getHelpOption();if(Q&&!Q.hidden){let q=Q.short&&$._findOption(Q.short),K=Q.long&&$._findOption(Q.long);if(!q&&!K)U.push(Q);else if(Q.long&&!K)U.push($.createOption(Q.long,Q.description));else if(Q.short&&!q)U.push($.createOption(Q.short,Q.description))}if(this.sortOptions)U.sort(this.compareOptions);return U}visibleGlobalOptions($){if(!this.showGlobalOptions)return[];let U=[];for(let Q=$.parent;Q;Q=Q.parent){let q=Q.options.filter((K)=>!K.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((Q)=>KZ(Q)).join(" ");return $._name+($._aliases[0]?"|"+$._aliases[0]:"")+($.options.length?" [options]":"")+(U?" "+U:"")}optionTerm($){return $.flags}argumentTerm($){return $.name()}longestSubcommandTermLength($,U){return U.visibleCommands($).reduce((Q,q)=>{return Math.max(Q,this.displayWidth(U.styleSubcommandTerm(U.subcommandTerm(q))))},0)}longestOptionTermLength($,U){return U.visibleOptions($).reduce((Q,q)=>{return Math.max(Q,this.displayWidth(U.styleOptionTerm(U.optionTerm(q))))},0)}longestGlobalOptionTermLength($,U){return U.visibleGlobalOptions($).reduce((Q,q)=>{return Math.max(Q,this.displayWidth(U.styleOptionTerm(U.optionTerm(q))))},0)}longestArgumentTermLength($,U){return U.visibleArguments($).reduce((Q,q)=>{return Math.max(Q,this.displayWidth(U.styleArgumentTerm(U.argumentTerm(q))))},0)}commandUsage($){let U=$._name;if($._aliases[0])U=U+"|"+$._aliases[0];let Q="";for(let q=$.parent;q;q=q.parent)Q=q.name()+" "+Q;return Q+U+" "+$.usage()}commandDescription($){return $.description()}subcommandDescription($){return $.summary()||$.description()}optionDescription($){let U=[];if($.argChoices)U.push(`choices: ${$.argChoices.map((Q)=>JSON.stringify(Q)).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((Q)=>JSON.stringify(Q)).join(", ")}`);if($.defaultValue!==void 0)U.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`);if(U.length>0){let Q=`(${U.join(", ")})`;if($.description)return`${$.description} ${Q}`;return Q}return $.description}formatHelp($,U){let Q=U.padWidth($,U),q=U.helpWidth??80;function K(B,M){return U.formatItem(B,Q,M,U)}let W=[`${U.styleTitle("Usage:")} ${U.styleUsage(U.commandUsage($))}`,""],J=U.commandDescription($);if(J.length>0)W=W.concat([U.boxWrap(U.styleCommandDescription(J),q),""]);let G=U.visibleArguments($).map((B)=>{return K(U.styleArgumentTerm(U.argumentTerm(B)),U.styleArgumentDescription(U.argumentDescription(B)))});if(G.length>0)W=W.concat([U.styleTitle("Arguments:"),...G,""]);let Y=U.visibleOptions($).map((B)=>{return K(U.styleOptionTerm(U.optionTerm(B)),U.styleOptionDescription(U.optionDescription(B)))});if(Y.length>0)W=W.concat([U.styleTitle("Options:"),...Y,""]);if(U.showGlobalOptions){let B=U.visibleGlobalOptions($).map((M)=>{return K(U.styleOptionTerm(U.optionTerm(M)),U.styleOptionDescription(U.optionDescription(M)))});if(B.length>0)W=W.concat([U.styleTitle("Global Options:"),...B,""])}let H=U.visibleCommands($).map((B)=>{return K(U.styleSubcommandTerm(U.subcommandTerm(B)),U.styleSubcommandDescription(U.subcommandDescription(B)))});if(H.length>0)W=W.concat([U.styleTitle("Commands:"),...H,""]);return W.join(`
|
|
4
|
+
`)}displayWidth($){return FW($).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,Q,q){let W=" ".repeat(2);if(!Q)return W+$;let J=$.padEnd(U+$.length-q.displayWidth($)),G=2,H=(this.helpWidth??80)-U-G-2,B;if(H<this.minWidthToWrap||q.preformatted(Q))B=Q;else B=q.boxWrap(Q,H).replace(/\n/g,`
|
|
5
|
+
`+" ".repeat(U+G));return W+J+" ".repeat(G)+B.replace(/\n/g,`
|
|
6
|
+
${W}`)}boxWrap($,U){if(U<this.minWidthToWrap)return $;let Q=$.split(/\r\n|\n/),q=/[\s]*[^\s]+/g,K=[];return Q.forEach((W)=>{let J=W.match(q);if(J===null){K.push("");return}let G=[J.shift()],Y=this.displayWidth(G[0]);J.forEach((H)=>{let B=this.displayWidth(H);if(Y+B<=U){G.push(H),Y+=B;return}K.push(G.join(""));let M=H.trimStart();G=[M],Y=this.displayWidth(M)}),K.push(G.join(""))}),K.join(`
|
|
7
|
+
`)}}function FW($){let U=/\x1b\[\d*(;\d*)*m/g;return $.replace(U,"")}QZ.Help=LW;QZ.stripColor=FW});var T8=V1((jZ)=>{var{InvalidArgumentError:JZ}=q6();class zW{constructor($,U){this.flags=$,this.description=U||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let Q=GZ($);if(this.short=Q.shortFlag,this.long=Q.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,Q)=>{if(!this.argChoices.includes(U))throw new JZ(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(U,Q);return U},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return vW(this.name().replace(/^no-/,""));return vW(this.name())}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class kW{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,Q)=>{if(this.positiveOptions.has(Q))this.dualOptions.add(Q)})}valueFromOption($,U){let Q=U.attributeName();if(!this.dualOptions.has(Q))return!0;let q=this.negativeOptions.get(Q).presetArg,K=q!==void 0?q:!1;return U.negate===(K===$)}}function vW($){return $.split("-").reduce((U,Q)=>{return U+Q[0].toUpperCase()+Q.slice(1)})}function GZ($){let U,Q,q=/^-[^-]$/,K=/^--[^-]/,W=$.split(/[ |,]+/).concat("guard");if(q.test(W[0]))U=W.shift();if(K.test(W[0]))Q=W.shift();if(!U&&q.test(W[0]))U=W.shift();if(!U&&K.test(W[0]))U=Q,Q=W.shift();if(W[0].startsWith("-")){let J=W[0],G=`option creation failed due to '${J}' in option flags '${$}'`;if(/^-[^-][^-]/.test(J))throw Error(`${G}
|
|
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(
|
|
11
|
-
- too many short flags`);if(
|
|
10
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(q.test(J))throw Error(`${G}
|
|
11
|
+
- too many short flags`);if(K.test(J))throw Error(`${G}
|
|
12
12
|
- too many long flags`);throw Error(`${G}
|
|
13
|
-
- unrecognised flag format`)}if(
|
|
14
|
-
(Did you mean one of ${
|
|
15
|
-
(Did you mean ${
|
|
16
|
-
- specify the name in Command constructor or using .name()`);if(
|
|
17
|
-
Expecting one of '${
|
|
18
|
-
- already used by option '${
|
|
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($,
|
|
20
|
-
- if '${
|
|
13
|
+
- unrecognised flag format`)}if(U===void 0&&Q===void 0)throw Error(`option creation failed due to no flags found in '${$}'.`);return{shortFlag:U,longFlag:Q}}jZ.Option=zW;jZ.DualOptions=kW});var wW=V1((ZZ)=>{function XZ($,U){if(Math.abs($.length-U.length)>3)return Math.max($.length,U.length);let Q=[];for(let q=0;q<=$.length;q++)Q[q]=[q];for(let q=0;q<=U.length;q++)Q[0][q]=q;for(let q=1;q<=U.length;q++)for(let K=1;K<=$.length;K++){let W=1;if($[K-1]===U[q-1])W=0;else W=1;if(Q[K][q]=Math.min(Q[K-1][q]+1,Q[K][q-1]+1,Q[K-1][q-1]+W),K>1&&q>1&&$[K-1]===U[q-2]&&$[K-2]===U[q-1])Q[K][q]=Math.min(Q[K][q],Q[K-2][q-2]+1)}return Q[$.length][U.length]}function BZ($,U){if(!U||U.length===0)return"";U=Array.from(new Set(U));let Q=$.startsWith("--");if(Q)$=$.slice(2),U=U.map((J)=>J.slice(2));let q=[],K=3,W=0.4;if(U.forEach((J)=>{if(J.length<=1)return;let G=XZ($,J),Y=Math.max($.length,J.length);if((Y-G)/Y>W){if(G<K)K=G,q=[J];else if(G===K)q.push(J)}}),q.sort((J,G)=>J.localeCompare(G)),Q)q=q.map((J)=>`--${J}`);if(q.length>1)return`
|
|
14
|
+
(Did you mean one of ${q.join(", ")}?)`;if(q.length===1)return`
|
|
15
|
+
(Did you mean ${q[0]}?)`;return""}ZZ.suggestSimilar=BZ});var OW=V1((LZ)=>{var VZ=Q6("node:events").EventEmitter,S8=Q6("node:child_process"),W1=Q6("node:path"),q0=Q6("node:fs"),d=Q6("node:process"),{Argument:DZ,humanReadableArgName:NZ}=Q0(),{CommanderError:C8}=q6(),{Help:PZ,stripColor:IZ}=R8(),{Option:xW,DualOptions:_Z}=T8(),{suggestSimilar:AW}=wW();class g8 extends VZ{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)=>d.stdout.write(U),writeErr:(U)=>d.stderr.write(U),outputError:(U,Q)=>Q(U),getOutHelpWidth:()=>d.stdout.isTTY?d.stdout.columns:void 0,getErrHelpWidth:()=>d.stderr.isTTY?d.stderr.columns:void 0,getOutHasColors:()=>E8()??(d.stdout.isTTY&&d.stdout.hasColors?.()),getErrHasColors:()=>E8()??(d.stderr.isTTY&&d.stderr.hasColors?.()),stripColor:(U)=>IZ(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,Q){let q=U,K=Q;if(typeof q==="object"&&q!==null)K=q,q=null;K=K||{};let[,W,J]=$.match(/([^ ]+) *(.*)/),G=this.createCommand(W);if(q)G.description(q),G._executableHandler=!0;if(K.isDefault)this._defaultCommandName=G._name;if(G._hidden=!!(K.noHelp||K.hidden),G._executableFile=K.executableFile||null,J)G.arguments(J);if(this._registerCommand(G),G.parent=this,G.copyInheritedSettings(this),q)return this;return G}createCommand($){return new g8($)}createHelp(){return Object.assign(new PZ,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 DZ($,U)}argument($,U,Q,q){let K=this.createArgument($,U);if(typeof Q==="function")K.default(q).argParser(Q);else K.default(Q);return this.addArgument(K),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[,Q,q]=$.match(/([^ ]+) *(.*)/),K=U??"display help for command",W=this.createCommand(Q);if(W.helpOption(!1),q)W.arguments(q);if(K)W.description(K);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 Q=["preSubcommand","preAction","postAction"];if(!Q.includes($))throw Error(`Unexpected value for event passed to hook : '${$}'.
|
|
17
|
+
Expecting one of '${Q.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,Q){if(this._exitCallback)this._exitCallback(new C8($,U,Q));d.exit($)}action($){let U=(Q)=>{let q=this.registeredArguments.length,K=Q.slice(0,q);if(this._storeOptionsAsProperties)K[q]=this;else K[q]=this.opts();return K.push(this),$.apply(this,K)};return this._actionHandler=U,this}createOption($,U){return new xW($,U)}_callParseArg($,U,Q,q){try{return $.parseArg(U,Q)}catch(K){if(K.code==="commander.invalidArgument"){let W=`${q} ${K.message}`;this.error(W,{exitCode:K.exitCode,code:K.code})}throw K}}_registerOption($){let U=$.short&&this._findOption($.short)||$.long&&this._findOption($.long);if(U){let Q=$.long&&this._findOption($.long)?$.long:$.short;throw Error(`Cannot add option '${$.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${Q}'
|
|
18
|
+
- already used by option '${U.flags}'`)}this.options.push($)}_registerCommand($){let U=(q)=>{return[q.name()].concat(q.aliases())},Q=U($).find((q)=>this._findCommand(q));if(Q){let q=U(this._findCommand(Q)).join("|"),K=U($).join("|");throw Error(`cannot add command '${K}' as already have command '${q}'`)}this.commands.push($)}addOption($){this._registerOption($);let U=$.name(),Q=$.attributeName();if($.negate){let K=$.long.replace(/^--no-/,"--");if(!this._findOption(K))this.setOptionValueWithSource(Q,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(Q,$.defaultValue,"default");let q=(K,W,J)=>{if(K==null&&$.presetArg!==void 0)K=$.presetArg;let G=this.getOptionValue(Q);if(K!==null&&$.parseArg)K=this._callParseArg($,K,G,W);else if(K!==null&&$.variadic)K=$._concatValue(K,G);if(K==null)if($.negate)K=!1;else if($.isBoolean()||$.optional)K=!0;else K="";this.setOptionValueWithSource(Q,K,J)};if(this.on("option:"+U,(K)=>{let W=`error: option '${$.flags}' argument '${K}' is invalid.`;q(K,W,"cli")}),$.envVar)this.on("optionEnv:"+U,(K)=>{let W=`error: option '${$.flags}' value '${K}' from env '${$.envVar}' is invalid.`;q(K,W,"env")});return this}_optionEx($,U,Q,q,K){if(typeof U==="object"&&U instanceof xW)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let W=this.createOption(U,Q);if(W.makeOptionMandatory(!!$.mandatory),typeof q==="function")W.default(K).argParser(q);else if(q instanceof RegExp){let J=q;q=(G,Y)=>{let H=J.exec(G);return H?H[0]:Y},W.default(K).argParser(q)}else W.default(q);return this.addOption(W)}option($,U,Q,q){return this._optionEx({},$,U,Q,q)}requiredOption($,U,Q,q){return this._optionEx({mandatory:!0},$,U,Q,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,Q){if(this._storeOptionsAsProperties)this[$]=U;else this._optionValues[$]=U;return this._optionValueSources[$]=Q,this}getOptionValueSource($){return this._optionValueSources[$]}getOptionValueSourceWithGlobals($){let U;return this._getCommandAndAncestors().forEach((Q)=>{if(Q.getOptionValueSource($)!==void 0)U=Q.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(d.versions?.electron)U.from="electron";let q=d.execArgv??[];if(q.includes("-e")||q.includes("--eval")||q.includes("-p")||q.includes("--print"))U.from="eval"}if($===void 0)$=d.argv;this.rawArgs=$.slice();let Q;switch(U.from){case void 0:case"node":this._scriptPath=$[1],Q=$.slice(2);break;case"electron":if(d.defaultApp)this._scriptPath=$[1],Q=$.slice(2);else Q=$.slice(1);break;case"user":Q=$.slice(0);break;case"eval":Q=$.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",Q}parse($,U){this._prepareForParse();let Q=this._prepareUserArgs($,U);return this._parseCommand([],Q),this}async parseAsync($,U){this._prepareForParse();let Q=this._prepareUserArgs($,U);return await this._parseCommand([],Q),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,Q){if(q0.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",K=`'${$}' does not exist
|
|
20
|
+
- if '${Q}' 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
|
-
- ${
|
|
22
|
+
- ${q}`;throw Error(K)}_executeSubCommand($,U){U=U.slice();let Q=!1,q=[".js",".ts",".tsx",".mjs",".cjs"];function K(H,B){let M=W1.resolve(H,B);if(q0.existsSync(M))return M;if(q.includes(W1.extname(B)))return;let V=q.find((L)=>q0.existsSync(`${M}${L}`));if(V)return`${M}${V}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let W=$._executableFile||`${this._name}-${$._name}`,J=this._executableDir||"";if(this._scriptPath){let H;try{H=q0.realpathSync(this._scriptPath)}catch{H=this._scriptPath}J=W1.resolve(W1.dirname(H),J)}if(J){let H=K(J,W);if(!H&&!$._executableFile&&this._scriptPath){let B=W1.basename(this._scriptPath,W1.extname(this._scriptPath));if(B!==this._name)H=K(J,`${B}-${$._name}`)}W=H||W}Q=q.includes(W1.extname(W));let G;if(d.platform!=="win32")if(Q)U.unshift(W),U=bW(d.execArgv).concat(U),G=S8.spawn(d.argv[0],U,{stdio:"inherit"});else G=S8.spawn(W,U,{stdio:"inherit"});else this._checkForMissingExecutable(W,J,$._name),U.unshift(W),U=bW(d.execArgv).concat(U),G=S8.spawn(d.execPath,U,{stdio:"inherit"});if(!G.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((B)=>{d.on(B,()=>{if(G.killed===!1&&G.exitCode===null)G.kill(B)})});let Y=this._exitCallback;G.on("close",(H)=>{if(H=H??1,!Y)d.exit(H);else Y(new C8(H,"commander.executeSubCommandAsync","(close)"))}),G.on("error",(H)=>{if(H.code==="ENOENT")this._checkForMissingExecutable(W,J,$._name);else if(H.code==="EACCES")throw Error(`'${W}' not executable`);if(!Y)d.exit(1);else{let B=new C8(1,"commander.executeSubCommandAsync","(error)");B.nestedError=H,Y(B)}}),this.runningCommand=G}_dispatchSubcommand($,U,Q){let q=this._findCommand($);if(!q)this.help({error:!0});q._prepareForParse();let K;return K=this._chainOrCallSubCommandHook(K,q,"preSubcommand"),K=this._chainOrCall(K,()=>{if(q._executableHandler)this._executeSubCommand(q,U.concat(Q));else return q._parseCommand(U,Q)}),K}_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 $=(Q,q,K)=>{let W=q;if(q!==null&&Q.parseArg){let J=`error: command-argument value '${q}' is invalid for argument '${Q.name()}'.`;W=this._callParseArg(Q,q,K,J)}return W};this._checkNumberOfArguments();let U=[];this.registeredArguments.forEach((Q,q)=>{let K=Q.defaultValue;if(Q.variadic){if(q<this.args.length){if(K=this.args.slice(q),Q.parseArg)K=K.reduce((W,J)=>{return $(Q,J,W)},Q.defaultValue)}else if(K===void 0)K=[]}else if(q<this.args.length){if(K=this.args[q],Q.parseArg)K=$(Q,K,Q.defaultValue)}U[q]=K}),this.processedArgs=U}_chainOrCall($,U){if($&&$.then&&typeof $.then==="function")return $.then(()=>U());return U()}_chainOrCallHooks($,U){let Q=$,q=[];if(this._getCommandAndAncestors().reverse().filter((K)=>K._lifeCycleHooks[U]!==void 0).forEach((K)=>{K._lifeCycleHooks[U].forEach((W)=>{q.push({hookedCommand:K,callback:W})})}),U==="postAction")q.reverse();return q.forEach((K)=>{Q=this._chainOrCall(Q,()=>{return K.callback(K.hookedCommand,this)})}),Q}_chainOrCallSubCommandHook($,U,Q){let q=$;if(this._lifeCycleHooks[Q]!==void 0)this._lifeCycleHooks[Q].forEach((K)=>{q=this._chainOrCall(q,()=>{return K(this,U)})});return q}_parseCommand($,U){let Q=this.parseOptions(U);if(this._parseOptionsEnv(),this._parseOptionsImplied(),$=$.concat(Q.operands),U=Q.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(Q.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let q=()=>{if(Q.unknown.length>0)this.unknownOption(Q.unknown[0])},K=`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(K,$,U)});return W=this._chainOrCallHooks(W,"postAction"),W}if(this.parent&&this.parent.listenerCount(K))q(),this._processArguments(),this.parent.emit(K,$,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((Q)=>{let q=Q.attributeName();if(this.getOptionValue(q)===void 0)return!1;return this.getOptionValueSource(q)!=="default"});$.filter((Q)=>Q.conflictsWith.length>0).forEach((Q)=>{let q=$.find((K)=>Q.conflictsWith.includes(K.attributeName()));if(q)this._conflictingOption(Q,q)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(($)=>{$._checkForConflictingLocalOptions()})}parseOptions($){let U=[],Q=[],q=U,K=$.slice();function W(G){return G.length>1&&G[0]==="-"}let J=null;while(K.length){let G=K.shift();if(G==="--"){if(q===Q)q.push(G);q.push(...K);break}if(J&&!W(G)){this.emit(`option:${J.name()}`,G);continue}if(J=null,W(G)){let Y=this._findOption(G);if(Y){if(Y.required){let H=K.shift();if(H===void 0)this.optionMissingArgument(Y);this.emit(`option:${Y.name()}`,H)}else if(Y.optional){let H=null;if(K.length>0&&!W(K[0]))H=K.shift();this.emit(`option:${Y.name()}`,H)}else this.emit(`option:${Y.name()}`);J=Y.variadic?Y:null;continue}}if(G.length>2&&G[0]==="-"&&G[1]!=="-"){let Y=this._findOption(`-${G[1]}`);if(Y){if(Y.required||Y.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${Y.name()}`,G.slice(2));else this.emit(`option:${Y.name()}`),K.unshift(`-${G.slice(2)}`);continue}}if(/^--[^=]+=/.test(G)){let Y=G.indexOf("="),H=this._findOption(G.slice(0,Y));if(H&&(H.required||H.optional)){this.emit(`option:${H.name()}`,G.slice(Y+1));continue}}if(W(G))q=Q;if((this._enablePositionalOptions||this._passThroughOptions)&&U.length===0&&Q.length===0){if(this._findCommand(G)){if(U.push(G),K.length>0)Q.push(...K);break}else if(this._getHelpCommand()&&G===this._getHelpCommand().name()){if(U.push(G),K.length>0)U.push(...K);break}else if(this._defaultCommandName){if(Q.push(G),K.length>0)Q.push(...K);break}}if(this._passThroughOptions){if(q.push(G),K.length>0)q.push(...K);break}q.push(G)}return{operands:U,unknown:Q}}opts(){if(this._storeOptionsAsProperties){let $={},U=this.options.length;for(let Q=0;Q<U;Q++){let q=this.options[Q].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
|
|
26
|
-
`),this._exit(0,"commander.version",$)}),this}description($,
|
|
27
|
-
Expecting one of '${
|
|
28
|
-
`)}),this}_outputHelpIfRequested($){let v=this._getHelpOption();if(v&&$.find((_)=>v.is(_)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function KQ($){return $.map((v)=>{if(!v.startsWith("--inspect"))return v;let K,_="127.0.0.1",U="9229",Q;if((Q=v.match(/^(--inspect(-brk)?)$/))!==null)K=Q[1];else if((Q=v.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(K=Q[1],/^\d+$/.test(Q[3]))U=Q[3];else _=Q[3];else if((Q=v.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)K=Q[1],_=Q[3],U=Q[4];if(K&&U!=="0")return`${K}=${_}:${parseInt(U)+1}`;return v})}function tv(){if(i.env.NO_COLOR||i.env.FORCE_COLOR==="0"||i.env.FORCE_COLOR==="false")return!1;if(i.env.FORCE_COLOR||i.env.CLICOLOR_FORCE!==void 0)return!0;return}GY.Command=pv;GY.useColor=tv});var WQ=U1((XY)=>{var{Argument:QQ}=A6(),{Command:av}=_Q(),{CommanderError:YY,InvalidArgumentError:qQ}=u4(),{Help:JY}=nv(),{Option:GQ}=lv();XY.program=new av;XY.createCommand=($)=>new av($);XY.createOption=($,v)=>new GQ($,v);XY.createArgument=($,v)=>new QQ($,v);XY.Command=av;XY.Option=GQ;XY.Argument=QQ;XY.Help=JY;XY.CommanderError=YY;XY.InvalidArgumentError=qQ;XY.InvalidOptionArgumentError=qQ});var Q1=U1((hk,ev)=>{var R6=process||{},JQ=R6.argv||[],x6=R6.env||{},ZY=!(!!x6.NO_COLOR||JQ.includes("--no-color"))&&(!!x6.FORCE_COLOR||JQ.includes("--color")||R6.platform==="win32"||(R6.stdout||{}).isTTY&&x6.TERM!=="dumb"||!!x6.CI),zY=($,v,K=$)=>(_)=>{let U=""+_,Q=U.indexOf(v,$.length);return~Q?$+LY(U,v,K,Q)+v:$+U+v},LY=($,v,K,_)=>{let U="",Q=0;do U+=$.substring(Q,_)+K,Q=_+v.length,_=$.indexOf(v,Q);while(~_);return U+$.substring(Q)},XQ=($=ZY)=>{let v=$?zY:()=>String;return{isColorSupported:$,reset:v("\x1B[0m","\x1B[0m"),bold:v("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:v("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:v("\x1B[3m","\x1B[23m"),underline:v("\x1B[4m","\x1B[24m"),inverse:v("\x1B[7m","\x1B[27m"),hidden:v("\x1B[8m","\x1B[28m"),strikethrough:v("\x1B[9m","\x1B[29m"),black:v("\x1B[30m","\x1B[39m"),red:v("\x1B[31m","\x1B[39m"),green:v("\x1B[32m","\x1B[39m"),yellow:v("\x1B[33m","\x1B[39m"),blue:v("\x1B[34m","\x1B[39m"),magenta:v("\x1B[35m","\x1B[39m"),cyan:v("\x1B[36m","\x1B[39m"),white:v("\x1B[37m","\x1B[39m"),gray:v("\x1B[90m","\x1B[39m"),bgBlack:v("\x1B[40m","\x1B[49m"),bgRed:v("\x1B[41m","\x1B[49m"),bgGreen:v("\x1B[42m","\x1B[49m"),bgYellow:v("\x1B[43m","\x1B[49m"),bgBlue:v("\x1B[44m","\x1B[49m"),bgMagenta:v("\x1B[45m","\x1B[49m"),bgCyan:v("\x1B[46m","\x1B[49m"),bgWhite:v("\x1B[47m","\x1B[49m"),blackBright:v("\x1B[90m","\x1B[39m"),redBright:v("\x1B[91m","\x1B[39m"),greenBright:v("\x1B[92m","\x1B[39m"),yellowBright:v("\x1B[93m","\x1B[39m"),blueBright:v("\x1B[94m","\x1B[39m"),magentaBright:v("\x1B[95m","\x1B[39m"),cyanBright:v("\x1B[96m","\x1B[39m"),whiteBright:v("\x1B[97m","\x1B[39m"),bgBlackBright:v("\x1B[100m","\x1B[49m"),bgRedBright:v("\x1B[101m","\x1B[49m"),bgGreenBright:v("\x1B[102m","\x1B[49m"),bgYellowBright:v("\x1B[103m","\x1B[49m"),bgBlueBright:v("\x1B[104m","\x1B[49m"),bgMagentaBright:v("\x1B[105m","\x1B[49m"),bgCyanBright:v("\x1B[106m","\x1B[49m"),bgWhiteBright:v("\x1B[107m","\x1B[49m")}};ev.exports=XQ();ev.exports.createColors=XQ});var jQ=v1(WQ(),1),{program:Ok,createCommand:xk,createArgument:Rk,createOption:Sk,CommanderError:uk,InvalidArgumentError:Tk,InvalidOptionArgumentError:gk,Command:YQ,Argument:Ek,Option:Ck,Help:yk}=jQ.default;function K1($){return typeof $==="object"&&$!=null&&!Array.isArray($)}function k$($){return typeof $==="object"&&$!=null?{...$}:void 0}function u$($){return typeof $==="string"?$:void 0}function O6($){return typeof $==="number"?$:void 0}function _1($){if(!Array.isArray($))return[];return $.map(k$).filter((v)=>v!=null)}var $$=v1(Q1(),1),AY=new Set(["json","table","plain"]);function FY($){return AY.has($)}function OY(){return process.stdout.isTTY===!0&&process.env.NO_COLOR==null}function I1($){if($.output!=null)return FY($.output)?$.output:"table";if($.json===!0)return"json";return OY()?"table":"json"}function xY($,v){return v in $}function T($,v){if(v==null)return $;let K={};for(let _ of v)if(xY($,_))K[_]=$[_];return K}function k($){console.log(JSON.stringify($,null,2))}var RY=/\x1B\[[0-9;]*m/g;function SY($){return $.replaceAll(RY,"")}var uY=[[128512,128591],[127744,128511],[128640,128767],[129280,129535],[129536,129791],[9728,10175],[127456,127487]],TY=[[65024,65039],[8205,8205]];function HQ($,v){for(let[K,_]of v)if($>=K&&$<=_)return!0;return!1}function gY($){if(HQ($,uY))return 2;if(HQ($,TY))return 0;return 1}function BQ($){let v=SY($),K=0;for(let _ of v)K+=gY(_.codePointAt(0));return K}function sv($,v){let K=BQ($);if(K>=v)return $;return $+" ".repeat(v-K)}function PQ($){if($==null)return"";return typeof $==="string"?$:JSON.stringify($)}function y($,v){if(v.length===0){console.log($$.default.dim("No results."));return}let K=$.map((U)=>{let Q=U.length,q=Math.max(...v.map((G)=>BQ(PQ(G[U]))));return Math.max(Q,q)}),_=$.map((U,Q)=>U.padEnd(K[Q])).join(" ");console.log($$.default.bold(_)),console.log($$.default.dim(K.map((U)=>"─".repeat(U)).join("──")));for(let U of v){let Q=$.map((q,G)=>sv(PQ(U[q]),K[G])).join(" ");console.log(Q)}}function g($){console.log($$.default.green($))}function x($){console.error($$.default.red($))}function A($){console.log($$.default.dim($))}function DQ($){console.error($$.default.yellow($))}function M($){let{output:v,fields:K}=$,_=I1({json:$.json===!0,output:typeof v==="string"?v:void 0}),U=typeof K==="string"?K.split(",").map((Q)=>Q.trim()):void 0;return{format:_,fields:U}}function _$($){A(`Page ${$.page}/${$.totalPages} (${$.total} total)`)}function I$($){if($==null)return"—";let v=Math.ceil($/1000);if(v===0)return"0s";let K=Math.floor(v/3600),_=Math.floor(v%3600/60),U=v%60;if(K>0)return _>0?`${K}h ${_}m`:`${K}h`;if(_>0)return U>0?`${_}m ${U}s`:`${_}m`;return`${U}s`}function $U($){if($==null)return"—";switch($){case"answered":return $$.default.green(`✓ ${$}`);case"missed":return $$.default.red(`✗ ${$}`);case"busy":return $$.default.yellow(`● ${$}`);case"failed":return $$.default.dim(`✗ ${$}`);default:return $}}function vU($,v){if($==null)return"—";let K=v!=null&&v>0?"+":"",_=v!=null?` (${K}${v})`:"";switch($){case"positive":return $$.default.green(`\uD83D\uDE0A ${$}${_}`);case"negative":return $$.default.red(`\uD83D\uDE1E ${$}${_}`);case"neutral":return $$.default.yellow(`\uD83D\uDE10 ${$}${_}`);case"mixed":return $$.default.blue(`\uD83D\uDD00 ${$}${_}`);default:return`${$}${_}`}}var EY={voicemail:"Voicemail",announcement:"Carrier announcement",ivr:"IVR / switchboard",screening:"Call screening",human:"Human",unknown:"Unclassified"};function S6($){return $==null?"—":EY[$]}function q1($,v,K=20){let _=v>0?$/v:0,U=Math.round(_*K),Q=K-U;return"█".repeat(U)+"░".repeat(Q)}function T$($,v,K,_=20){let U=q1(v,K,_),Q=K>0?Math.round(v/K*100):0;console.log(` ${sv($,14)} ${U} ${v} (${Q}%)`)}function a($){for(let v=0;v<$.length;v++){let K=$[v],_=Math.max(...K.rows.map((Q)=>Q.label.length)),U=Math.max(_+4+30,K.title.length+4);console.log($$.default.dim(`┌─ ${K.title} ${"─".repeat(Math.max(0,U-K.title.length-4))}`));for(let Q of K.rows){let q=Q.value==null?"—":String(Q.value);console.log(`${$$.default.dim("│")} ${sv(Q.label,_)} ${q}`)}if(console.log($$.default.dim(`└${"─".repeat(U)}`)),v<$.length-1)console.log("")}}function UU($){for(let v=0;v<$.length;v++){let K=$[v],_=v===$.length-1,U=_?"└──":"├──",Q=K.detail!=null?$$.default.dim(` (${K.detail})`):"";if(console.log(` ${U} ${K.label}${Q}`),K.children!=null){let q=_?" ":"│ ";for(let G of K.children)console.log($$.default.dim(` ${q}${G}`))}}}function CY($){let v=$.toLowerCase();return v==="caller"||v==="speaker_l"||v==="speaker_01"}function bQ($){if($.length===0){A(" No transcript available.");return}for(let v of $){let K=Math.floor(v.initial_time/60),_=Math.floor(v.initial_time%60),U=`${String(K).padStart(2,"0")}:${String(_).padStart(2,"0")}`,Q=CY(v.speaker)?$$.default.blue("Caller"):$$.default.green("Agent "),q=$$.default.dim(`[${U}]`);console.log(` ${q} ${Q} ${$$.default.dim(">")} ${v.text}`)}}function VQ($,v){if(/^\d{4}-\d{2}-\d{2}$/.test($))return v?`${$}T23:59:59.999Z`:`${$}T00:00:00.000Z`;return $}function G1($,v=0){let K=new Date,_=$.from!=null?VQ($.from,!1):new Date(K.getFullYear(),K.getMonth(),K.getDate()-v).toISOString(),U=$.to!=null?VQ($.to,!0):K.toISOString();return{dateFrom:_,dateTo:U}}function m$($){let v=typeof $==="string"?new Date($):$,K=String(v.getDate()).padStart(2,"0"),_=String(v.getMonth()+1).padStart(2,"0"),U=String(v.getHours()).padStart(2,"0"),Q=String(v.getMinutes()).padStart(2,"0");return`${K}/${_} ${U}:${Q}`}var R={SUCCESS:0,GENERAL_ERROR:1,USAGE_ERROR:2,NOT_FOUND:3,PERMISSION_DENIED:4,CONFLICT:5},KU="table",yY="";function fY($){if($.endsWith("_NOT_FOUND")||$==="NOT_FOUND"||$==="AUDIO_FILE_CONTENT_MISSING")return R.NOT_FOUND;if($==="UNAUTHORIZED"||$==="FORBIDDEN"||$==="ADMIN_REQUIRED"||$==="API_KEY_INVALID"||$==="INSUFFICIENT_SCOPE")return R.PERMISSION_DENIED;if($==="UNPROCESSABLE_CONTENT"||$==="BAD_REQUEST")return R.USAGE_ERROR;if($==="AUDIO_FILE_TOO_LARGE"||$==="AUDIO_FILE_INVALID_FORMAT"||$==="AUDIO_FILE_NOT_TTS"||$==="TTS_VOICE_UNAVAILABLE")return R.USAGE_ERROR;if($==="CONFLICT"||$.startsWith("DUPLICATE_")||$.endsWith("_IN_USE"))return R.CONFLICT;return R.GENERAL_ERROR}function mY($){return $==="INTERNAL_SERVER_ERROR"||$==="SERVICE_UNAVAILABLE"}var hY={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 cY($,v){let K=$.message.toLowerCase();if(K.includes("econnrefused")||K.includes("fetch failed")||K.includes("unable to connect"))return`Could not connect to ${v||"server"}
|
|
25
|
+
`),this.outputHelp({error:!0});let Q=U||{},q=Q.exitCode||1,K=Q.code||"commander.error";this._exit(q,K,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in d.env){let U=$.attributeName();if(this.getOptionValue(U)===void 0||["default","config","env"].includes(this.getOptionValueSource(U)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,d.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new _Z(this.options),U=(Q)=>{return this.getOptionValue(Q)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(Q))};this.options.filter((Q)=>Q.implied!==void 0&&U(Q.attributeName())&&$.valueFromOption(this.getOptionValue(Q.attributeName()),Q)).forEach((Q)=>{Object.keys(Q.implied).filter((q)=>!U(q)).forEach((q)=>{this.setOptionValueWithSource(q,Q.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 Q=(W)=>{let J=W.attributeName(),G=this.getOptionValue(J),Y=this.options.find((B)=>B.negate&&J===B.attributeName()),H=this.options.find((B)=>!B.negate&&J===B.attributeName());if(Y&&(Y.presetArg===void 0&&G===!1||Y.presetArg!==void 0&&G===Y.presetArg))return Y;return H||W},q=(W)=>{let J=Q(W),G=J.attributeName();if(this.getOptionValueSource(G)==="env")return`environment variable '${J.envVar}'`;return`option '${J.flags}'`},K=`error: ${q($)} cannot be used with ${q(U)}`;this.error(K,{code:"commander.conflictingOption"})}unknownOption($){if(this._allowUnknownOption)return;let U="";if($.startsWith("--")&&this._showSuggestionAfterError){let q=[],K=this;do{let W=K.createHelp().visibleOptions(K).filter((J)=>J.long).map((J)=>J.long);q=q.concat(W),K=K.parent}while(K&&!K._enablePositionalOptions);U=AW($,q)}let Q=`error: unknown option '${$}'${U}`;this.error(Q,{code:"commander.unknownOption"})}_excessArguments($){if(this._allowExcessArguments)return;let U=this.registeredArguments.length,Q=U===1?"":"s",K=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${U} argument${Q} but got ${$.length}.`;this.error(K,{code:"commander.excessArguments"})}unknownCommand(){let $=this.args[0],U="";if(this._showSuggestionAfterError){let q=[];this.createHelp().visibleCommands(this).forEach((K)=>{if(q.push(K.name()),K.alias())q.push(K.alias())}),U=AW($,q)}let Q=`error: unknown command '${$}'${U}`;this.error(Q,{code:"commander.unknownCommand"})}version($,U,Q){if($===void 0)return this._version;this._version=$,U=U||"-V, --version",Q=Q||"output the version number";let q=this.createOption(U,Q);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 Q=this.parent?._findCommand($);if(Q){let q=[Q.name()].concat(Q.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((Q)=>{return NZ(Q)});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=W1.basename($,W1.extname($)),this}executableDir($){if($===void 0)return this._executableDir;return this._executableDir=$,this}helpInformation($){let U=this.createHelp(),Q=this._getOutputContext($);U.prepareContext({error:Q.error,helpWidth:Q.helpWidth,outputHasColors:Q.hasColors});let q=U.formatHelp(this,U);if(Q.hasColors)return q;return this._outputConfiguration.stripColor(q)}_getOutputContext($){$=$||{};let U=!!$.error,Q,q,K;if(U)Q=(J)=>this._outputConfiguration.writeErr(J),q=this._outputConfiguration.getErrHasColors(),K=this._outputConfiguration.getErrHelpWidth();else Q=(J)=>this._outputConfiguration.writeOut(J),q=this._outputConfiguration.getOutHasColors(),K=this._outputConfiguration.getOutHelpWidth();return{error:U,write:(J)=>{if(!q)J=this._outputConfiguration.stripColor(J);return Q(J)},hasColors:q,helpWidth:K}}outputHelp($){let U;if(typeof $==="function")U=$,$=void 0;let Q=this._getOutputContext($),q={error:Q.error,write:Q.write,command:this};this._getCommandAndAncestors().reverse().forEach((W)=>W.emit("beforeAllHelp",q)),this.emit("beforeHelp",q);let K=this.helpInformation({error:Q.error});if(U){if(K=U(K),typeof K!=="string"&&!Buffer.isBuffer(K))throw Error("outputHelp callback must return a string or a Buffer")}if(Q.write(K),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(d.exitCode??0);if(U===0&&$&&typeof $!=="function"&&$.error)U=1;this._exit(U,"commander.help","(outputHelp)")}addHelpText($,U){let Q=["beforeAll","before","after","afterAll"];if(!Q.includes($))throw Error(`Unexpected value for position to addHelpText.
|
|
27
|
+
Expecting one of '${Q.join("', '")}'`);let q=`${$}Help`;return this.on(q,(K)=>{let W;if(typeof U==="function")W=U({error:K.error,command:K.command});else W=U;if(W)K.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 bW($){return $.map((U)=>{if(!U.startsWith("--inspect"))return U;let Q,q="127.0.0.1",K="9229",W;if((W=U.match(/^(--inspect(-brk)?)$/))!==null)Q=W[1];else if((W=U.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(Q=W[1],/^\d+$/.test(W[3]))K=W[3];else q=W[3];else if((W=U.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)Q=W[1],q=W[3],K=W[4];if(Q&&K!=="0")return`${Q}=${q}:${parseInt(K)+1}`;return U})}function E8(){if(d.env.NO_COLOR||d.env.FORCE_COLOR==="0"||d.env.FORCE_COLOR==="false")return!1;if(d.env.FORCE_COLOR||d.env.CLICOLOR_FORCE!==void 0)return!0;return}LZ.Command=g8;LZ.useColor=E8});var CW=V1((wZ)=>{var{Argument:RW}=Q0(),{Command:y8}=OW(),{CommanderError:zZ,InvalidArgumentError:TW}=q6(),{Help:kZ}=R8(),{Option:SW}=T8();wZ.program=new y8;wZ.createCommand=($)=>new y8($);wZ.createOption=($,U)=>new SW($,U);wZ.createArgument=($,U)=>new RW($,U);wZ.Command=y8;wZ.Option=SW;wZ.Argument=RW;wZ.Help=kZ;wZ.CommanderError=zZ;wZ.InvalidArgumentError=TW;wZ.InvalidOptionArgumentError=TW});var D1=V1((Ek,h8)=>{var G0=process||{},mW=G0.argv||[],J0=G0.env||{},lZ=!(!!J0.NO_COLOR||mW.includes("--no-color"))&&(!!J0.FORCE_COLOR||mW.includes("--color")||G0.platform==="win32"||(G0.stdout||{}).isTTY&&J0.TERM!=="dumb"||!!J0.CI),rZ=($,U,Q=$)=>(q)=>{let K=""+q,W=K.indexOf(U,$.length);return~W?$+nZ(K,U,Q,W)+U:$+K+U},nZ=($,U,Q,q)=>{let K="",W=0;do K+=$.substring(W,q)+Q,W=q+U.length,q=$.indexOf(U,W);while(~q);return K+$.substring(W)},cW=($=lZ)=>{let U=$?rZ:()=>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")}};h8.exports=cW();h8.exports.createColors=cW});var EW=M1(CW(),1),{program:Pk,createCommand:Ik,createArgument:_k,createOption:Lk,CommanderError:Fk,InvalidArgumentError:vk,InvalidOptionArgumentError:zk,Command:gW,Argument:kk,Option:wk,Help:xk}=EW.default;import{readFileSync as uZ}from"node:fs";function G$($){return typeof $==="object"&&$!=null&&!Array.isArray($)}function M$($){return typeof $==="object"&&$!=null?{...$}:void 0}function i($){return typeof $==="string"?$:void 0}function u1($){return typeof $==="number"?$:void 0}function m$($){if(!Array.isArray($))return[];return $.map((U)=>M$(U)).filter((U)=>U!=null)}function W6(){return"0.3.1-rc.0"}var u8="/cli/compatibilidade",W0=null;function fZ(){if(W0!=null)return W0;let $='[{"niva_min":"2.0.0","niva_max":null,"dist_tag":"niva-2.0"}]',U='{"min":"2.0.0","max":null}',Q=null;if(typeof U==="string"&&typeof $==="string"){let q=JSON.parse(U),K=JSON.parse($);Q=yW(q,K)}else{let q=JSON.parse(hZ()),K=G$(q)?q.supported_niva:void 0,W=G$(q)?q.compat_table:void 0;Q=yW(K,W)}if(Q==null)throw Error("Invalid apps/cli/compat.json, fix the compat table");return W0=Q,W0}function yW($,U){if(!G$($)||!Array.isArray(U))return null;let Q=i($.min);if(Q==null)return null;let q=i($.max)??null,K=[];for(let W of m$(U)){let J=i(W.niva_min),G=i(W.dist_tag);if(J==null||G==null)return null;K.push({niva_min:J,niva_max:i(W.niva_max)??null,dist_tag:G})}return{supported_niva:{min:Q,max:q},compat_table:K}}function hZ(){return uZ(new URL("../../compat.json",import.meta.url),"utf-8")}function uW($){let Q=($.split("-")[0]?.split("+")[0]??"").split(".");if(Q.length!==3)return null;let q=Q.map((K)=>Number.parseInt(K,10));if(q.some((K)=>!Number.isFinite(K)||K<0))return null;return[q[0],q[1],q[2]]}function fW($,U){let Q=uW($),q=uW(U);if(Q===null||q===null)return 0;for(let K=0;K<3;K++)if(Q[K]!==q[K])return Q[K]-q[K];return 0}function hW($,U){for(let Q of U.compat_table){if(fW($,Q.niva_min)<0)continue;if(Q.niva_max!=null&&fW($,Q.niva_max)>0)continue;return Q.dist_tag}return null}var mZ=null;function cZ(){return mZ}function f8(){let $=fZ(),U=cZ();if(U!=null)return hW(U,$);return hW($.supported_niva.min,$)}var Q$=M1(D1(),1),iZ=new Set(["json","table","plain"]);function oZ($){return iZ.has($)}function dZ(){return process.stdout.isTTY===!0&&process.env.NO_COLOR==null}function f1($){if($.output!=null)return oZ($.output)?$.output:"table";if($.json===!0)return"json";return dZ()?"table":"json"}function pZ($,U){return U in $}function C($,U){if(U==null)return $;let Q={};for(let q of U)if(pZ($,q))Q[q]=$[q];return Q}function P($){console.log(JSON.stringify($,null,2))}var tZ=/\x1B\[[0-9;]*m/g;function aZ($){return $.replaceAll(tZ,"")}var sZ=[[128512,128591],[127744,128511],[128640,128767],[129280,129535],[129536,129791],[9728,10175],[127456,127487]],eZ=[[65024,65039],[8205,8205]];function lW($,U){for(let[Q,q]of U)if($>=Q&&$<=q)return!0;return!1}function $M($){if(lW($,sZ))return 2;if(lW($,eZ))return 0;return 1}function iW($){let U=aZ($),Q=0;for(let q of U)Q+=$M(q.codePointAt(0));return Q}function m8($,U){let Q=iW($);if(Q>=U)return $;return $+" ".repeat(U-Q)}function rW($){if($==null)return"";return typeof $==="string"?$:JSON.stringify($)}function y($,U){if(U.length===0){console.log(Q$.default.dim("No results."));return}let Q=$.map((K)=>{let W=K.length,J=Math.max(...U.map((G)=>iW(rW(G[K]))));return Math.max(W,J)}),q=$.map((K,W)=>K.padEnd(Q[W])).join(" ");console.log(Q$.default.bold(q)),console.log(Q$.default.dim(Q.map((K)=>"─".repeat(K)).join("──")));for(let K of U){let W=$.map((J,G)=>m8(rW(K[J]),Q[G])).join(" ");console.log(W)}}function E($){console.log(Q$.default.green($))}function x($){console.error(Q$.default.red($))}function w($){console.log(Q$.default.dim($))}function J1($){console.error(Q$.default.yellow($))}function F($){let{output:U,fields:Q}=$,q=f1({json:$.json===!0,output:typeof U==="string"?U:void 0}),K=typeof Q==="string"?Q.split(",").map((W)=>W.trim()):void 0;return{format:q,fields:K}}function j$($){if($.page==null)return;if($.total_pages==null||$.total==null){w(`Page ${$.page}`);return}w(`Page ${$.page}/${$.total_pages} (${$.total} total)`)}function C$($){if($==null)return"—";let U=Math.ceil($/1000);if(U===0)return"0s";let Q=Math.floor(U/3600),q=Math.floor(U%3600/60),K=U%60;if(Q>0)return q>0?`${Q}h ${q}m`:`${Q}h`;if(q>0)return K>0?`${q}m ${K}s`:`${q}m`;return`${K}s`}function c8($){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 l8($,U){if($==null)return"—";let Q=U!=null&&U>0?"+":"",q=U!=null?` (${Q}${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 UM={voicemail:"Voicemail",announcement:"Carrier announcement",ivr:"IVR / switchboard",screening:"Call screening",human:"Human",unknown:"Unclassified"};function j0($){return $==null?"—":UM[$]}function N1($,U,Q=20){let q=U>0?$/U:0,K=Math.round(q*Q),W=Q-K;return"█".repeat(K)+"░".repeat(W)}function o$($,U,Q,q=20){let K=N1(U,Q,q),W=Q>0?Math.round(U/Q*100):0;console.log(` ${m8($,14)} ${K} ${U} (${W}%)`)}function t($){for(let U=0;U<$.length;U++){let Q=$[U],q=Math.max(...Q.rows.map((W)=>W.label.length)),K=Math.max(q+4+30,Q.title.length+4);console.log(Q$.default.dim(`┌─ ${Q.title} ${"─".repeat(Math.max(0,K-Q.title.length-4))}`));for(let W of Q.rows){let J=W.value==null?"—":String(W.value);console.log(`${Q$.default.dim("│")} ${m8(W.label,q)} ${J}`)}if(console.log(Q$.default.dim(`└${"─".repeat(K)}`)),U<$.length-1)console.log("")}}function r8($){for(let U=0;U<$.length;U++){let Q=$[U],q=U===$.length-1,K=q?"└──":"├──",W=Q.detail!=null?Q$.default.dim(` (${Q.detail})`):"";if(console.log(` ${K} ${Q.label}${W}`),Q.children!=null){let J=q?" ":"│ ";for(let G of Q.children)console.log(Q$.default.dim(` ${J}${G}`))}}}function KM($){let U=$.toLowerCase();return U==="caller"||U==="speaker_l"||U==="speaker_01"}function oW($){if($.length===0){w(" No transcript available.");return}for(let U of $){let Q=Math.floor(U.initial_time/60),q=Math.floor(U.initial_time%60),K=`${String(Q).padStart(2,"0")}:${String(q).padStart(2,"0")}`,W=KM(U.speaker)?Q$.default.blue("Caller"):Q$.default.green("Agent "),J=Q$.default.dim(`[${K}]`);console.log(` ${J} ${W} ${Q$.default.dim(">")} ${U.text}`)}}function nW($,U){if(/^\d{4}-\d{2}-\d{2}$/.test($))return U?`${$}T23:59:59.999Z`:`${$}T00:00:00.000Z`;return $}function P1($,U=0){let Q=new Date,q=$.from!=null?nW($.from,!1):new Date(Q.getFullYear(),Q.getMonth(),Q.getDate()-U).toISOString(),K=$.to!=null?nW($.to,!0):Q.toISOString();return{date_from:q,date_to:K}}function a$($){let U=typeof $==="string"?new Date($):$,Q=String(U.getDate()).padStart(2,"0"),q=String(U.getMonth()+1).padStart(2,"0"),K=String(U.getHours()).padStart(2,"0"),W=String(U.getMinutes()).padStart(2,"0");return`${Q}/${q} ${K}:${W}`}var A={SUCCESS:0,GENERAL_ERROR:1,USAGE_ERROR:2,NOT_FOUND:3,PERMISSION_DENIED:4,CONFLICT:5},n8="table",QM="";function qM($){if($.endsWith("_NOT_FOUND")||$==="NOT_FOUND"||$==="AUDIO_FILE_CONTENT_MISSING")return A.NOT_FOUND;if($==="UNAUTHORIZED"||$==="FORBIDDEN"||$==="ADMIN_REQUIRED"||$==="API_KEY_INVALID"||$==="INSUFFICIENT_SCOPE")return A.PERMISSION_DENIED;if($==="UNPROCESSABLE_CONTENT"||$==="BAD_REQUEST")return A.USAGE_ERROR;if($==="AUDIO_FILE_TOO_LARGE"||$==="AUDIO_FILE_INVALID_FORMAT"||$==="AUDIO_FILE_NOT_TTS"||$==="TTS_VOICE_UNAVAILABLE")return A.USAGE_ERROR;if($==="CONFLICT"||$.startsWith("DUPLICATE_")||$.endsWith("_IN_USE"))return A.CONFLICT;if($==="MODULE_DISABLED")return A.PERMISSION_DENIED;return A.GENERAL_ERROR}function WM($){return $==="INTERNAL_SERVER_ERROR"||$==="SERVICE_UNAVAILABLE"}var JM={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 GM($,U){let Q=$.message.toLowerCase();if(Q.includes("econnrefused")||Q.includes("fetch failed")||Q.includes("unable to connect"))return`Could not connect to ${U||"server"}
|
|
29
29
|
Is the server running? Check with: niva fs status
|
|
30
|
-
Current URL: ${
|
|
31
|
-
Check the URL: niva config set url <url>`;return`Connection error: ${$.message}`}function rY($){let v=k$($);if(v==null)return` • ${String($)}`;let K=v.path,_=Array.isArray(K)?K.join("."):"",U=v.messageKey??v.code??"invalid",Q;if(typeof v.message==="string")Q=v.message;else if(typeof U==="string")Q=U;else Q=JSON.stringify(U);return` ✗ ${_?`${_}: `:""}${Q}`}function T4($){return $ instanceof Error&&"defined"in $&&"code"in $}function u6($){let v=String(k$($)?.code);return{code:v,message:$.message,data:k$(k$($)?.data),hint:hY[v],exitCode:fY(v),retryable:mY(v)}}function T6($){x(`Error: ${$.code} — ${$.message}`);let v=$.data?.issues;if(Array.isArray(v))for(let K of v)x(rY(K));if($.hint!=null)A(` ${$.hint}`)}function iY($){if(KU==="json")k({error:$.code,message:$.message,data:$.data,hint:$.hint,retryable:$.retryable});else T6($);process.exit($.exitCode)}function _U($){return $ instanceof Error?cY($,yY):String($)}function Z1($){if(T4($))iY(u6($));let v=_U($);if(KU==="json")k({error:"CONNECTION_ERROR",message:$ instanceof Error?$.message:String($),retryable:!0});else x(v);process.exit(R.GENERAL_ERROR)}function o1($){if(T4($))Z1($);let v=$ instanceof Error?$.message:String($);if(KU==="json")k({error:"STREAM_ERROR",message:v,retryable:!0});else x(`Stream error: ${v}`);process.exit(R.GENERAL_ERROR)}async function w($){try{return await $}catch(v){Z1(v)}}function g$($="Not yet implemented."){A($),process.exit(R.USAGE_ERROR)}function kQ($,v){$.command("ai").description("AI module resources").command("agents").description("List AI agents available for voice interactions").action(async()=>{let{format:_,fields:U}=M($.opts()),Q=await w(v().ai.listAgents());if(_==="json"){let q=U?Q.map((G)=>T(G,U)):Q;k(q);return}y(["ID","Name","Language","SIP Inbound","Description"],Q.map((q)=>({ID:q.id,Name:q.name,Language:q.language,"SIP Inbound":q.sip_inbound_enabled?"enabled":"disabled",Description:q.description??"—"})))})}import{readFile as fQ,writeFile as mQ}from"node:fs/promises";import{basename as hQ}from"node:path";function nY($,v){let K=v.toLowerCase();if(K.endsWith(".wav"))return lY($);if(K.endsWith(".mp3"))return KJ($);return}function g6($){if(!Number.isFinite($)||$<=0)return;let v=Math.round($);if(v<=0||v>86400000)return;return v}function NQ($,v,K){let _="";for(let U=0;U<K;U+=1)_+=String.fromCharCode($[v+U]??0);return _}function g4($,v,K){if(v+K.length>$.byteLength)return!1;return NQ($,v,K.length)===K}function wQ($){return new DataView($.buffer,$.byteOffset,$.byteLength)}function lY($){let v=$.byteLength;if(v<12||!g4($,0,"RIFF")||!g4($,8,"WAVE"))return;let K=wQ($),_,U,Q=12;while(Q+8<=v){let q=NQ($,Q,4),G=K.getUint32(Q+4,!0),j=Q+8;if(q==="fmt "&&G>=16&&j+16<=v){let X=K.getUint16(j+2,!0),P=K.getUint32(j+4,!0),B=K.getUint32(j+8,!0),N=K.getUint16(j+14,!0);_=B>0?B:P*X*N/8}else if(q==="data"){U=Math.min(G,v-j);break}let Y=j+G+G%2;if(Y<=Q)return;Q=Y}if(_===void 0||_<=0||U===void 0)return;return g6(U/_*1000)}var oY=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320,0],dY=[0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,0],tY=[44100,48000,32000,0],pY=[22050,24000,16000,0],aY=[11025,12000,8000,0];function eY($){if($===3)return tY;if($===2)return pY;return aY}function sY($,v){if($)return v?17:32;return v?9:17}function $J($,v){let K=$[v+1],_=$[v+2],U=$[v+3];if(K===void 0||_===void 0||U===void 0)return;let Q=K>>3&3,q=K>>1&3;if(Q===1||q!==1)return;let G=Q===3,j=(G?oY:dY)[_>>4&15]??0,Y=eY(Q)[_>>2&3]??0;if(j===0||Y===0)return;let X=(U>>6&3)===3;return{bitrate:j*1000,sampleRate:Y,samplesPerFrame:G?1152:576,sideInfoSize:sY(G,X)}}function vJ($,v,K){let _=v+4+K;if(!g4($,_,"Xing")&&!g4($,_,"Info"))return;if(_+12>$.byteLength)return;let U=wQ($);if((U.getUint32(_+4,!1)&1)===0)return;let q=U.getUint32(_+8,!1);return q>0?q:void 0}function UJ($){if(!g4($,0,"ID3")||$.byteLength<10)return 0;let v=$[5]??0,K=0;for(let U=6;U<=9;U+=1)K=K<<7|($[U]??0)&127;let _=(v&16)!==0?10:0;return 10+K+_}function KJ($){let v=$.byteLength,K=UJ($);for(let _=K;_+4<=v;_+=1){if($[_]!==255||(($[_+1]??0)&224)!==224)continue;let U=$J($,_);if(U===void 0)continue;let Q=vJ($,_,U.sideInfoSize);if(Q!==void 0)return g6(Q*U.samplesPerFrame*1000/U.sampleRate);return g6((v-_)*8*1000/U.bitrate)}return}async function _J($,v){let K=[v,"-v","error","-show_entries","format=duration","-of","csv=p=0",$],_;try{_=Bun.spawn(K,{stdout:"pipe",stderr:"ignore"})}catch{return}let U=QJ(_).catch(()=>{return}),Q,q=new Promise((G)=>{Q=setTimeout(()=>{_.kill(),setTimeout(()=>_.kill("SIGKILL"),250).unref(),G(void 0)},3000)});try{let G=await Promise.race([U,q]);if(G?.exitCode!==0)return;return g6(Number(G.stdout.trim())*1000)}finally{if(Q!==void 0)clearTimeout(Q)}}async function QJ($){let[v,K]=await Promise.all([new Response($.stdout).text(),$.exited]);return{stdout:v,exitCode:K}}async function MQ($){let v=nY($.bytes,$.filePath);if(v!==void 0)return{durationMs:v,source:"header"};if($.noProbe===!0)return{source:"none"};let K=await _J($.filePath,$.ffprobePath??"ffprobe");if(K!==void 0)return{durationMs:K,source:"ffprobe"};return{source:"none"}}import{createInterface as zQ}from"node:readline/promises";function LQ(){return process.stdin.isTTY===!0}var IQ=5;async function ZQ($,v,K){let _=$[v].value;for(let U=0;U<IQ;U++){let Q=(await K(`Choice [${v+1}]: `)).trim();if(Q==="")return _;let q=/^\d+$/.test(Q)?$[Number(Q)-1]:void 0;if(q!=null)return q.value;x(`Invalid choice — enter a number between 1 and ${$.length}.`)}return x(`No valid choice after ${IQ} attempts — using the default.`),_}async function AQ($,v,K={}){let _=K.defaultIndex??0;console.log($);for(let[Q,q]of v.entries())console.log(` ${Q+1}) ${q.label}`);if(console.log(""),K.ask!=null)return ZQ(v,_,K.ask);let U=zQ({input:process.stdin,output:process.stdout});try{return await ZQ(v,_,async(Q)=>U.question(Q))}finally{U.close()}}async function W1($,v){if(v.yes)return;if(process.stdin.isTTY!==!0)x("Refusing to prompt in non-interactive mode. Re-run with --yes to confirm."),process.exit(R.USAGE_ERROR);let K=zQ({input:process.stdin,output:process.stdout});try{let _=await K.question(`${$} [y/N] `);if(!/^y(?:es)?$/i.test(_.trim()))x("Aborted."),process.exit(R.USAGE_ERROR)}finally{K.close()}}var FQ=/^(?:[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 qJ($){return typeof $==="string"&&FQ.test($)}var OQ=qJ;var G$=[];for(let $=0;$<256;++$)G$.push(($+256).toString(16).slice(1));function QU($,v=0){return(G$[$[v+0]]+G$[$[v+1]]+G$[$[v+2]]+G$[$[v+3]]+"-"+G$[$[v+4]]+G$[$[v+5]]+"-"+G$[$[v+6]]+G$[$[v+7]]+"-"+G$[$[v+8]]+G$[$[v+9]]+"-"+G$[$[v+10]]+G$[$[v+11]]+G$[$[v+12]]+G$[$[v+13]]+G$[$[v+14]]+G$[$[v+15]]).toLowerCase()}function GJ($,v=0){let K=QU($,v);if(!OQ(K))throw TypeError("Stringified UUID is invalid");return K}var E6=GJ;var WJ=new Uint8Array(16);function C6(){return crypto.getRandomValues(WJ)}var qU={};function jJ($,v,K){let _;if($)_=xQ($.random??$.rng?.()??C6(),$.msecs,$.seq,v,K);else{let U=Date.now(),Q=C6();YJ(qU,U,Q),_=xQ(Q,qU.msecs,qU.seq,v,K)}return v??QU(_)}function YJ($,v,K){if($.msecs??=-1/0,$.seq??=0,v>$.msecs)$.seq=K[6]<<23|K[7]<<16|K[8]<<8|K[9],$.msecs=v;else if($.seq=$.seq+1|0,$.seq===0)$.msecs++;return $}function xQ($,v,K,_,U=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!_)_=new Uint8Array(16),U=0;else if(U<0||U+16>_.length)throw RangeError(`UUID byte range ${U}:${U+15} is out of buffer bounds`);return v??=Date.now(),K??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],_[U++]=v/1099511627776&255,_[U++]=v/4294967296&255,_[U++]=v/16777216&255,_[U++]=v/65536&255,_[U++]=v/256&255,_[U++]=v&255,_[U++]=112|K>>>28&15,_[U++]=K>>>20&255,_[U++]=128|K>>>14&63,_[U++]=K>>>6&255,_[U++]=K<<2&255|$[10]&3,_[U++]=$[11],_[U++]=$[12],_[U++]=$[13],_[U++]=$[14],_[U++]=$[15],_}var GU=jJ;function JJ($){let v,K=new Uint8Array(16);return K[0]=(v=parseInt($.slice(0,8),16))>>>24,K[1]=v>>>16&255,K[2]=v>>>8&255,K[3]=v&255,K[4]=(v=parseInt($.slice(9,13),16))>>>8,K[5]=v&255,K[6]=(v=parseInt($.slice(14,18),16))>>>8,K[7]=v&255,K[8]=(v=parseInt($.slice(19,23),16))>>>8,K[9]=v&255,K[10]=(v=parseInt($.slice(24,36),16))/1099511627776&255,K[11]=v/4294967296&255,K[12]=v>>>24&255,K[13]=v>>>16&255,K[14]=v>>>8&255,K[15]=v&255,K}var e="0123456789abcdefghjkmnpqrstvwxyz",u=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 WU($){let v=Array(26).fill("");if($.length!==16)throw Error(`Invalid length. Expected 16 bytes, got ${$.length}. Input: ${$}`);return v[0]=e[($[0]&224)>>5],v[1]=e[$[0]&31],v[2]=e[($[1]&248)>>3],v[3]=e[($[1]&7)<<2|($[2]&192)>>6],v[4]=e[($[2]&62)>>1],v[5]=e[($[2]&1)<<4|($[3]&240)>>4],v[6]=e[($[3]&15)<<1|($[4]&128)>>7],v[7]=e[($[4]&124)>>2],v[8]=e[($[4]&3)<<3|($[5]&224)>>5],v[9]=e[$[5]&31],v[10]=e[($[6]&248)>>3],v[11]=e[($[6]&7)<<2|($[7]&192)>>6],v[12]=e[($[7]&62)>>1],v[13]=e[($[7]&1)<<4|($[8]&240)>>4],v[14]=e[($[8]&15)<<1|($[9]&128)>>7],v[15]=e[($[9]&124)>>2],v[16]=e[($[9]&3)<<3|($[10]&224)>>5],v[17]=e[$[10]&31],v[18]=e[($[11]&248)>>3],v[19]=e[($[11]&7)<<2|($[12]&192)>>6],v[20]=e[($[12]&62)>>1],v[21]=e[($[12]&1)<<4|($[13]&240)>>4],v[22]=e[($[13]&15)<<1|($[14]&128)>>7],v[23]=e[($[14]&124)>>2],v[24]=e[($[14]&3)<<3|($[15]&224)>>5],v[25]=e[$[15]&31],v.join("")}function uQ($){if($.length!==26)throw Error(`Invalid length. Expected 26 bytes, got ${$.length}. Input: ${$}`);let K=new TextEncoder().encode($);if(u[K[0]]===255||u[K[1]]===255||u[K[2]]===255||u[K[3]]===255||u[K[4]]===255||u[K[5]]===255||u[K[6]]===255||u[K[7]]===255||u[K[8]]===255||u[K[9]]===255||u[K[10]]===255||u[K[11]]===255||u[K[12]]===255||u[K[13]]===255||u[K[14]]===255||u[K[15]]===255||u[K[16]]===255||u[K[17]]===255||u[K[18]]===255||u[K[19]]===255||u[K[20]]===255||u[K[21]]===255||u[K[22]]===255||u[K[23]]===255||u[K[24]]===255||u[K[25]]===255)throw Error("Invalid base32 character");let _=new Uint8Array(16);return _[0]=u[K[0]]<<5|u[K[1]],_[1]=u[K[2]]<<3|u[K[3]]>>2,_[2]=(u[K[3]]&3)<<6|u[K[4]]<<1|u[K[5]]>>4,_[3]=(u[K[5]]&15)<<4|u[K[6]]>>1,_[4]=(u[K[6]]&1)<<7|u[K[7]]<<2|u[K[8]]>>3,_[5]=(u[K[8]]&7)<<5|u[K[9]],_[6]=u[K[10]]<<3|u[K[11]]>>2,_[7]=(u[K[11]]&3)<<6|u[K[12]]<<1|u[K[13]]>>4,_[8]=(u[K[13]]&15)<<4|u[K[14]]>>1,_[9]=(u[K[14]]&1)<<7|u[K[15]]<<2|u[K[16]]>>3,_[10]=(u[K[16]]&7)<<5|u[K[17]],_[11]=u[K[18]]<<3|u[K[19]]>>2,_[12]=(u[K[19]]&3)<<6|u[K[20]]<<1|u[K[21]]>>4,_[13]=(u[K[21]]&15)<<4|u[K[22]]>>1,_[14]=(u[K[22]]&1)<<7|u[K[23]]<<2|u[K[24]]>>3,_[15]=(u[K[24]]&7)<<5|u[K[25]],_}function XJ($){if($.length>63)return!1;let v,K,_;for(K=0,_=$.length;K<_;K+=1){v=$.charCodeAt(K);let U=v>96&&v<123,Q=v===95;if((K===0||K===_-1)&&!U)return!1;if(!(U||Q))return!1}return!0}var HJ=class extends Error{constructor($){super(`Invalid prefix "${$}". Must be at most 63 ASCII letters [a-z_]`);this.name="InvalidPrefixError"}},PJ=class extends Error{constructor($,v){super(`Invalid TypeId. Prefix mismatch. Expected ${$}, got ${v}`);this.name="PrefixMismatchError"}},VJ=class extends Error{constructor($){super(`Invalid TypeId. Prefix cannot be empty when there's a separator: ${$}`);this.name="EmptyPrefixError"}},TQ=class extends Error{constructor($){super(`Invalid length. Suffix should have 26 characters, got ${$}`);this.name="InvalidSuffixLengthError"}},BJ=class extends Error{constructor($){super(`Invalid suffix. First character "${$}" must be in the range [0-7]`);this.name="InvalidSuffixCharacterError"}},DJ=class extends Error{constructor($,v){super(`Cannot convert TypeID of type ${$} to type ${v}`);this.name="TypeIDConversionError"}};function gQ($="",v=""){if(!XJ($))throw new HJ($);let K;if(v)K=v;else{let _=new Uint8Array(16);GU(void 0,_),K=WU(_)}if(K.length!==26)throw new TQ(K.length);if(K[0]>"7")throw new BJ(K[0]);if(uQ(K),$==="")return K;else return`${$}_${K}`}function bJ($,v){let K,_,U=$.lastIndexOf("_");if(U===-1)K="",_=$;else if(K=$.substring(0,U),_=$.substring(U+1),!K)throw new VJ($);if(!_)throw new TQ(0);if(v&&K!==v)throw new PJ(v,K);return gQ(K,_)}function RQ($){let v=$.lastIndexOf("_");if(v===-1)return"";return $.substring(0,v)}function SQ($){let v=$.lastIndexOf("_");if(v===-1)return $;return $.substring(v+1)}var d1=class{constructor($,v=""){this.prefix=$,this.suffix=v;let K=gQ($,v);this.prefix=RQ(K),this.suffix=SQ(K)}getType(){return this.prefix}getSuffix(){return this.suffix}asType($){let v=this;if(v.prefix!==$)throw new DJ(v.prefix,$);return v}toUUIDBytes(){return uQ(this.suffix)}toUUID(){return E6(this.toUUIDBytes())}toString(){if(this.prefix==="")return this.suffix;return`${this.prefix}_${this.suffix}`}static fromString($,v){let K=bJ($,v);return new d1(RQ(K),SQ(K))}static fromUUIDBytes($,v){let K=WU(v);return new d1($,K)}static fromUUID($,v){let K=WU(JJ(v));return new d1($,K)}};var t$={acl_rules:"acl",organizations:"org",users:"usr",org_memberships:"mem",visual_plans:"vp",visual_plan_versions:"vpv",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"};function y6($,v){return d1.fromUUID(t$[$],v).toString()}var kJ=new Map(Object.keys(t$).map(($)=>[t$[$],$]));function jU($){return kJ.get($)}var NJ=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function f6($){if(NJ.test($))return{kind:"uuid",uuid:$};let v=$.lastIndexOf("_");if(v<=0||v===$.length-1)return{kind:"invalid",reason:"not-an-id"};let K=$.slice(0,v),_=jU(K);if(_===void 0)return{kind:"invalid",reason:"unknown-prefix"};try{return{kind:"typeid",entity:_,prefix:K,uuid:d1.fromString($,K).toUUID()}}catch{return{kind:"invalid",reason:"malformed-suffix"}}}function E$($){return $}function wJ($){return`a ${t$[$]}_... TypeID for ${$}, or the raw UUID of that row`}function EQ($,v,K){x(`Invalid id "${v}": ${K}`),A(` Expected ${wJ($)}.`),A(" Convert between the two forms with: niva id <value> [--as <entity>]"),process.exit(R.USAGE_ERROR)}function MJ($){let v=$.lastIndexOf("_");return v>0?$.slice(0,v):""}function CQ($,v){let K=f6(v);if(K.kind==="uuid")return y6($,K.uuid);let _=jU(MJ(v));if(_===$)return v;if(_!==void 0)EQ($,v,`it is a ${_} id`);EQ($,v,"it is neither a UUID nor an id of a known entity")}function F($,v){let K;if(Array.isArray(v))K=v.map((_)=>CQ($,_));else if(v!==void 0)K=CQ($,v);return K}import{Buffer as IJ}from"node:buffer";async function t1(){return new Promise(($,v)=>{let K=[];process.stdin.on("data",(_)=>K.push(_)),process.stdin.on("end",()=>$(IJ.concat(K).toString("utf-8"))),process.stdin.on("error",v)})}var ZJ=10,zJ=new Set(["UNAUTHORIZED","FORBIDDEN","API_KEY_INVALID","ADMIN_REQUIRED","INSUFFICIENT_SCOPE"]);function cQ($,v){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(_)=>{let{format:U,fields:Q}=M($.opts()),q=await w(v().audioFiles.list({page:Number(_.page),limit:Number(_.limit),search:_.search}));if(U==="json"){let G=Q?q.items.map((j)=>T(j,Q)):q;k(G);return}y(["ID","Name","Type","Duration"],q.items.map((G)=>({ID:G.id,Name:G.name,Type:G.type,Duration:rQ(G.duration_ms)}))),_$(q)}),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(_,U)=>{let{format:Q}=M($.opts()),q=$.opts().yes===!0;if(U.name!=null&&_.length>1)x("--name names a single audio file; drop it when uploading several at once."),process.exit(R.USAGE_ERROR);if(U.durationMs!=null&&_.length>1)x("--duration-ms describes a single audio file; drop it when uploading several at once."),process.exit(R.USAGE_ERROR);let G=AJ(U.durationMs);if(_.length>ZJ)await W1(`Upload ${_.length} audio files to the library?`,{yes:q});let j=[],Y=R.SUCCESS;for(let X of _){let P=await FJ(v(),X,{format:Q,overrideMs:G,noProbe:U.probe===!1,...U.name!=null&&{name:U.name}});if(j.push(P),P.exitCode>Y)Y=P.exitCode;if(P.abort)break}if(uJ(j,Q),Y!==R.SUCCESS)process.exit(Y)}),K.command("show <audioFileId>").description("Show an audio file's metadata").action(async(_)=>{let{format:U,fields:Q}=M($.opts()),q=await w(v().audioFiles.getById({audioFileId:F("audio_files",_)}));if(q==null)x("Audio file not found"),process.exit(R.NOT_FOUND);if(U==="json"){k(Q?T(q,Q):q);return}a(m6(q))}),K.command("download <audioFileId>").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(_,U)=>{let{format:Q}=M($.opts()),q=$.opts(),G=q.json===!0||q.output==="json";if(U.out==="-"&&G)x("--out - streams binary audio to stdout and cannot be combined with --json."),process.exit(R.USAGE_ERROR);let j=v(),Y=await w(j.audioFiles.content({audioFileId:F("audio_files",_)})),X=new Uint8Array(await Y.arrayBuffer());if(U.out==="-"){process.stdout.write(X);return}let P;if(U.out!=null)P=U.out,await mQ(P,X);else P=await RJ(j,_,Y.name),await SJ(P,X,U.force===!0);if(Q==="json"){k({path:P,bytes:X.length});return}g(`Saved ${P} (${X.length} bytes)`)}),K.command("update <audioFileId>").description("Update an audio file's name and/or description").option("--name <name>","New library name").option("--description <text>","New description").action(async(_,U)=>{let{format:Q}=M($.opts());if(U.name==null&&U.description==null)x("Nothing to update — pass --name and/or --description."),process.exit(R.USAGE_ERROR);let q=await w(v().audioFiles.update({audioFileId:F("audio_files",_),...U.name!=null&&{name:U.name},...U.description!=null&&{description:U.description}}));if(Q==="json"){k(q);return}g(`Audio file updated: ${q.name}`),a(m6(q))}),K.command("delete <audioFileId>").description("Delete an audio file from the library").action(async(_)=>{let{format:U}=M($.opts()),Q=$.opts().yes===!0;await W1(`Delete audio file ${_}?`,{yes:Q});try{await v().audioFiles.delete({audioFileId:F("audio_files",_)})}catch(q){TJ(q,U)}if(U==="json"){k({id:_,deleted:!0});return}g(`Audio file deleted: ${_}`)}),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(_)=>{let{format:U}=M($.opts()),Q=await yQ(_),q=await w(v().audioFiles.generateTts({name:_.name,text:Q,..._.description!=null&&{description:_.description},..._.voice!=null&&{voice:_.voice},..._.model!=null&&{model:_.model}}));if(U==="json"){k(q);return}g(`TTS audio generated: ${q.id}`),a(m6(q))}),K.command("regenerate-tts <audioFileId>").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(_,U)=>{let{format:Q}=M($.opts()),q=$.opts().yes===!0,G=await yQ(U);await W1(`Overwrite the audio content of ${_}?`,{yes:q});let j=await w(v().audioFiles.regenerateTts({audioFileId:F("audio_files",_),text:G,...U.voice!=null&&{voice:U.voice},...U.model!=null&&{model:U.model}}));if(Q==="json"){k(j);return}g(`TTS audio regenerated: ${j.id}`),a(m6(j))})}var LJ="FILE_UNREADABLE";function rQ($){if($==null)return"—";if($<60000)return`${($/1000).toFixed(1)}s`;return I$($)}function AJ($){if($==null)return;let v=Number($);if(!Number.isInteger(v)||v<=0)x(`Invalid --duration-ms "${$}": expected a positive whole number of milliseconds.`),process.exit(R.USAGE_ERROR);return v}async function FJ($,v,K){let _;try{_=await fQ(v)}catch(Q){let q=Q instanceof Error?Q.message:String(Q);if(K.format!=="json")x(`Cannot read ${v}: ${q}`);return{file:v,ok:!1,id:void 0,durationSource:"none",error:LJ,message:q,exitCode:R.USAGE_ERROR,abort:!1}}let U=await OJ(v,_,K);try{let Q=await $.audioFiles.upload({file:new File([_],hQ(v)),...K.name!=null&&{name:K.name},...U.durationMs!=null&&{duration_ms:U.durationMs}});return{file:v,ok:!0,id:Q.id,durationSource:U.source,error:void 0,message:void 0,exitCode:R.SUCCESS,abort:!1}}catch(Q){return xJ(Q,v,U.source,K.format)}}async function OJ($,v,K){if(K.overrideMs!=null)return{durationMs:K.overrideMs,source:"flag"};let _=process.env.NIVA_FFPROBE,U=await MQ({filePath:$,bytes:v,noProbe:K.noProbe,..._!=null&&_!==""&&{ffprobePath:_}});if(U.source==="none"&&K.format!=="json")A(`duration unknown for ${$} — install ffmpeg or pass --duration-ms`);return U}function xJ($,v,K,_){let U={file:v,ok:!1,id:void 0,durationSource:K};if(!T4($)){let q=_U($);if(_!=="json")x(q);return{...U,error:"CONNECTION_ERROR",message:q,exitCode:R.GENERAL_ERROR,abort:!0}}let Q=u6($);if(_!=="json")T6(Q);return{...U,error:Q.code,message:Q.message,exitCode:Q.exitCode,abort:zJ.has(Q.code)}}async function RJ($,v,K){let U=[(await w($.audioFiles.getById({audioFileId:F("audio_files",v)})))?.filename,K,v];return hQ(U.find((Q)=>Q!=null&&Q!=="")??v)}async function SJ($,v,K){try{await mQ($,v,K?{}:{flag:"wx"})}catch(_){if(k$(_)?.code!=="EEXIST")throw _;x(`${$} already exists — pass --out <path> to write elsewhere, or --force to overwrite it.`),process.exit(R.CONFLICT)}}function uJ($,v){if(v==="json"){k($.map((_)=>({file:_.file,ok:_.ok,..._.id!=null&&{id:_.id},durationSource:_.durationSource,..._.error!=null&&{error:_.error},..._.message!=null&&{message:_.message}})));return}y(["File","ID","Status"],$.map((_)=>({File:_.file,ID:_.id??"—",Status:_.ok?"uploaded":_.error??"failed"})));let K=$.filter((_)=>!_.ok).length;g(`${$.length-K} uploaded, ${K} failed`)}function TJ($,v){if(!T4($))Z1($);let K=u6($),_=gJ(K);if(_==null)Z1($);if(v==="json")k({error:K.code,message:K.message,plans:_,hint:K.hint,retryable:K.retryable});else T6(K),A(` Referenced by: ${_.join(", ")}`);process.exit(K.exitCode)}function gJ($){if($.code!=="AUDIO_FILE_IN_USE")return;let v=$.data?.plans;if(!Array.isArray(v))return;return v.map(String)}async function yQ($){if($.text!=null&&$.textFile!=null)x("--text and --text-file are mutually exclusive."),process.exit(R.USAGE_ERROR);if($.text!=null)return $.text;if($.textFile==null)x("No text to synthesize — pass --text <text> or --text-file <path|->."),process.exit(R.USAGE_ERROR);let K=($.textFile==="-"?await t1():await fQ($.textFile,"utf-8")).trim();if(K==="")x(`No text to synthesize: ${$.textFile==="-"?"stdin":$.textFile} is empty.`),process.exit(R.USAGE_ERROR);return K}function m6($){let v=[{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:rQ($.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)v.push({title:"TTS",rows:[{label:"Provider",value:$.voice_provider},{label:"Voice",value:$.voice_id},{label:"Text",value:$.tts_text}]});return v}function iQ($){return $[0]??{}}function L1($){return Array.isArray($)?$:$===void 0||$===null?[]:[$]}var YU="orpc",EJ="@orpc/shared",CJ="1.14.8";class JU extends Error{constructor(...$){super(...$);this.name="AbortError"}}function h6($){let v;return()=>{if(v)return v.result;let K=$();return v={result:K},K}}function yJ($){let v=Promise.resolve();return(...K)=>{return v=v.catch(()=>{}).then(()=>{return $(...K)})}}var fJ=2,mJ=`__${EJ}@${CJ}/otel/config__`;function E4(){return globalThis[mJ]}function c6($,v={},K){return E4()?.tracer?.startSpan($,v,K)}function j1($,v,K={}){if(!$)return;let _=hJ(v);if($.recordException(_),!K.signal?.aborted||K.signal.reason!==v)$.setStatus({code:fJ,message:_.message})}function hJ($){if($ instanceof Error){let v={message:$.message,name:$.name,stack:$.stack};if("code"in $&&(typeof $.code==="string"||typeof $.code==="number"))v.code=$.code;return v}return{message:String($)}}async function A1({name:$,context:v,...K},_){let U=E4()?.tracer;if(!U)return _();let Q=async(q)=>{try{return await _(q)}catch(G){throw j1(q,G,K),G}finally{q.end()}};if(v)return U.startActiveSpan($,K,v,Q);else return U.startActiveSpan($,K,Q)}async function z1($,v){let K=E4();if(!$||!K)return v();let _=K.trace.setSpan(K.context.active(),$);return K.context.with(_,v)}function p$($){if(!$||typeof $!=="object")return!1;return"next"in $&&typeof $.next==="function"&&Symbol.asyncIterator in $&&typeof $[Symbol.asyncIterator]==="function"}var cJ=Symbol.for("asyncDispose"),rJ=Symbol.asyncDispose??cJ;class Y1{#$=!1;#v=!1;#U;#K;constructor($,v){this.#U=v,this.#K=yJ(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.#v)this.#v=!0,await this.#U("next")}})}next(){return this.#K()}async return($){if(this.#$=!0,!this.#v)this.#v=!0,await this.#U("return");return{done:!0,value:$}}async throw($){if(this.#$=!0,!this.#v)this.#v=!0,await this.#U("throw");throw $}async[rJ](){if(this.#$=!0,!this.#v)this.#v=!0,await this.#U("dispose")}[Symbol.asyncIterator](){return this}}function XU({name:$,...v},K){let _;return new Y1(async()=>{_??=c6($);try{let U=await z1(_,()=>K.next());return _?.addEvent(U.done?"completed":"yielded"),U}catch(U){throw j1(_,U,v),U}},async(U)=>{try{if(U!=="next")await z1(_,()=>K.return?.())}catch(Q){throw j1(_,Q,v),Q}finally{_?.end()}})}class iJ{#$=new Map;#v;constructor($={}){this.#v=$.maxBufferedEvents??100}get size(){return this.#$.size}publish($,v){let K=this.#$.get($);if(!K)return;for(let _ of K)_(v)}subscribe($,v){if(typeof v==="function"){let j=this.#$.get($);if(!j)this.#$.set($,j=[]);return j.push(v),h6(()=>{if(j.splice(j.indexOf(v),1),j.length===0)this.#$.delete($)})}let K=v?.signal,_=v?.maxBufferedEvents??this.#v;K?.throwIfAborted();let U=[],Q=[],q=this.subscribe($,(j)=>{let Y=Q.shift();if(Y)Y[0]({done:!1,value:j});else if(U.push(j),U.length>_)U.shift()}),G=(j)=>{q(),Q.forEach((Y)=>Y[1](j.target.reason)),Q.length=0,U.length=0};return K?.addEventListener("abort",G,{once:!0}),new Y1(async()=>{if(K?.aborted)throw K.reason;if(U.length>0)return{done:!1,value:U.shift()};return new Promise((j,Y)=>{Q.push([j,Y])})},async()=>{q(),K?.removeEventListener("abort",G),Q.forEach((j)=>j[0]({done:!0,value:void 0})),Q.length=0,U.length=0})}}class nJ{index=BigInt(1);generate(){let $=this.index.toString(36);return this.index++,$}}function C4($,v,K){let _=(U,Q)=>{let q=$[Q];if(!q)return K(U);return q({...U,next:(G=U)=>_(G,Q+1)})};return _(v,0)}function y4($){if(!$)return;return JSON.parse($)}function F1($){return JSON.stringify($)}function nQ($){if(!h$($))return null;return Object.getPrototypeOf($)?.constructor}function r6($){if(!$||typeof $!=="object")return!1;let v=Object.getPrototypeOf($);return v===Object.prototype||!v||!v.constructor}function h$($){return!!$&&(typeof $==="object"||typeof $==="function")}function f4($,...v){if(typeof $==="function")return $(...v);return $}function HU($){return new Proxy($,{get(v,K,_){let U=Reflect.get(v,K,_);if(K!=="then"||typeof U!=="function")return U;return new Proxy(U,{apply(Q,q,G){if(G.length!==2||G.some((Y)=>!oJ(Y)))return Reflect.apply(Q,q,G);let j=!0;G[0].call(q,HU(new Proxy(v,{get:(Y,X,P)=>{if(j&&X==="then"){j=!1;return}return Reflect.get(Y,X,P)}})))}})}})}var lJ=/^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;function oJ($){return typeof $==="function"&&lJ.test($.toString())}function lQ($){try{return decodeURIComponent($)}catch{return $}}var dJ="@orpc/client",tJ="1.14.8",n6={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 pJ($,v){return v??n6[$]?.status??500}function aJ($,v){return v||n6[$]?.message||$}var i6;class O1 extends Error{defined;code;status;data;static{let $=Symbol.for(`__${dJ}@${tJ}/error/ORPC_ERROR_CONSTRUCTORS__`);globalThis[$]??=new WeakSet,i6=globalThis[$],i6.add(O1)}constructor($,...v){let K=iQ(v);if(K.status!==void 0&&!l6(K.status))throw Error("[ORPCError] Invalid error status code.");let _=aJ($,K.message);super(_,K);this.code=$,this.status=pJ($,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(i6.has(this)){let v=nQ($);if(v&&i6.has(v))return!0}return super[Symbol.hasInstance]($)}}function oQ($){return $ instanceof O1?$:new O1("INTERNAL_SERVER_ERROR",{message:"Internal server error",cause:$})}function l6($){return $<200||$>=400}function PU($){if(!r6($))return!1;let v=["defined","code","status","message","data"];if(Object.keys($).some((K)=>!v.includes(K)))return!1;return"defined"in $&&typeof $.defined==="boolean"&&"code"in $&&typeof $.code==="string"&&"status"in $&&typeof $.status==="number"&&l6($.status)&&"message"in $&&typeof $.message==="string"}function VU($,v={}){return new O1($.code,{...v,...$})}class m4 extends TypeError{}class dQ extends TypeError{}class a$ extends Error{data;constructor($){super($?.message??"An error event was received",$);this.data=$?.data}}function eJ($){let v=$.replace(/\n+$/,"").split(/\n/),K={data:void 0,event:void 0,id:void 0,retry:void 0,comments:[]};for(let _ of v){let U=_.indexOf(":"),Q=U===-1?_:_.slice(0,U),q=U===-1?"":_.slice(U+1).replace(/^\s/,"");if(U===0)K.comments.push(q);else if(Q==="data")K.data??="",K.data+=`${q}
|
|
32
|
-
`;
|
|
33
|
-
|
|
34
|
-
`
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
`))throw new m4("Event's comment must not contain a newline character")}function $X($){let v=$?.split(/\n/)??[],K="";for(let _ of v)K+=`data: ${_}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
`;if($.retry!==void 0)aQ($.retry),v+=`retry: ${$.retry}
|
|
43
|
-
`;if($.
|
|
44
|
-
`;return v+=$X($.data),v+=`
|
|
45
|
-
`,v}var sQ=Symbol("ORPC_EVENT_SOURCE_META");function x1($,v){if(v.id===void 0&&v.retry===void 0&&!v.comments?.length)return $;if(v.id!==void 0)pQ(v.id);if(v.retry!==void 0)aQ(v.retry);if(v.comments!==void 0)for(let K of v.comments)eQ(K);return new Proxy($,{get(K,_,U){if(_===sQ)return v;return Reflect.get(K,_,U)}})}function p1($){return h$($)?Reflect.get($,sQ):void 0}function $q($,v="inline"){let K=$.replace(/[^\x20-\x7E]/g,"_").replace(/"/g,"\\\""),_=encodeURIComponent($).replace(/['()*]/g,(U)=>`%${U.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(7C|60|5E)/g,(U,Q)=>String.fromCharCode(Number.parseInt(Q,16)));return`${v}; filename="${K}"; filename*=utf-8''${_}`}function vq($){let v=$.match(/filename\*=(UTF-8'')?([^;]*)/i);if(v&&typeof v[2]==="string")return lQ(v[2]);let K=$.match(/filename="((?:\\"|[^"])*)"/i);if(K&&typeof K[1]==="string")return K[1].replace(/\\"/g,'"')}function Uq($,v){let K={...$};for(let _ in v)if(Array.isArray(v[_]))K[_]=[...L1(K[_]),...v[_]];else if(v[_]!==void 0)if(Array.isArray(K[_]))K[_]=[...K[_],v[_]];else if(K[_]!==void 0)K[_]=[K[_],v[_]];else K[_]=v[_];return K}function DU($,v){let K=async(_)=>{let U=await v.error(_);if(U!==_){let Q=p1(_);if(Q&&h$(U))U=x1(U,Q)}return U};return new Y1(async()=>{let{done:_,value:U}=await(async()=>{try{return await $.next()}catch(q){throw await K(q)}})(),Q=await v.value(U,_);if(Q!==U){let q=p1(U);if(q&&h$(Q))Q=x1(Q,q)}return{done:_,value:Q}},async()=>{try{await $.return?.()}catch(_){throw await K(_)}})}function UX($){return{...$,context:$.context??{}}}function J1($,v){return(async()=>{let K;try{let _=await $;while(!0){let{done:U,value:Q}=await _.next();if(U){let q=Q;K=[null,q,!0],v.onSuccess?.(q);break}v.onEvent(Q)}}catch(_){if(K=[_,void 0,!1],!v.onError&&!v.onFinish)throw _;v.onError?.(_)}finally{v.onFinish?.(K)}})(),async()=>{await(await $)?.return?.()}}function bU($,v={}){let K=v.path??[],U=new Proxy(async(...[Q,q={}])=>{return await $.call(K,Q,UX(q))},{get(Q,q){if(typeof q!=="string")return Reflect.get(Q,q);return bU($,{...v,path:[...K,q]})}});return HU(U)}var s=v1(Q1(),1);var KX=/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i,Kq=4;async function o6($,v){if(KX.test(v))return v;if(v.length<Kq)x(`UUID prefix too short — provide at least ${Kq} characters.`),process.exit(R.USAGE_ERROR);let K=await w($.dashboard.activeCalls()),_=v.toLowerCase(),U=K.filter((Q)=>Q.uuid.toLowerCase().startsWith(_));if(U.length===0)x(`No active call matching "${v}".`),process.exit(R.NOT_FOUND);if(U.length>1){x(`Ambiguous UUID prefix "${v}" — matches ${U.length} calls. Be more specific.`);for(let Q of U)A(` ${Q.uuid} ${Q.callerId}`);process.exit(R.USAGE_ERROR)}return U[0].uuid}function Qq($,v){let K=$.command("calls").description("Manage calls");K.command("list").description("List active calls").action(async()=>{let{format:_,fields:U}=M($.opts()),Q=await w(v().dashboard.activeCalls());if(_==="json"){let q=U?Q.map((G)=>T(G,U)):Q;k(q);return}if(Q.length===0){A("No active calls.");return}y(["UUID","Caller","Plan","Duration"],Q.map((q)=>({UUID:q.uuid,Caller:q.callerId,Plan:q.planName??"—",Duration:q.startedAt?`${Math.round((Date.now()-new Date(q.startedAt).getTime())/1000)}s`:"—"})))}),K.command("show <callRecordId>").description("Show call details from CDR (rich detail view)").action(async(_)=>{let{format:U,fields:Q}=M($.opts()),q=await w(v().callRecords.getById({callRecordId:F("call_records",_)}));if(U==="json"){let G=Q&&q!=null?T(q,Q):q;k(G);return}if(q==null){A("Call record not found.");return}a([{title:"Call Record",rows:QX(q)}])}),K.command("hangup <uuid>").description("Hang up an active call").action(async(_)=>{let{format:U}=M($.opts()),Q=v(),q=await o6(Q,_),G=await w(Q.dashboard.hangupCall({uuid:q}));if(U==="json"){k(G);return}g(`Call ${q} terminated.`)}),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(_)=>{let{format:U,fields:Q}=M($.opts()),q=await w(v().callRecords.list({page:Number(_.page),limit:Number(_.limit),search:_.caller}));if(U==="json"){let G=Q?q.items.map((j)=>T(j,Q)):q;k(G);return}y(["ID","Caller","Callee","Duration","Disposition","Date"],q.items.map((G)=>({ID:G.id,Caller:G.caller_id??"—",Callee:G.callee_id??"—",Duration:I$(G.duration_ms),Disposition:G.hangup_disposition??"—",Date:new Date(G.started_at).toLocaleString()}))),_$(q)}),K.command("follow <uuid>").description("Follow live transcription of an active call").action(async(_)=>{let{format:U}=M($.opts()),Q=v(),q=await o6(Q,_),G=new AbortController;process.on("SIGINT",()=>{G.abort()});let j=!1,Y=!1;function X(B){P();let N=qq(B);process.stdout.write(s.default.dim(N)),Y=!0}function P(){if(!Y)return;process.stdout.clearLine(0),process.stdout.cursorTo(0),Y=!1}await new Promise((B,N)=>{J1(Q.dashboard.watchLiveTranscription({uuid:q},{signal:G.signal}),{onEvent:(S)=>{if(j=!0,U==="json"){k(S);return}switch(S.type){case"starting":A("Connecting...");break;case"started":A("Transcription started.");break;case"ended":P(),A("Transcription ended."),B();break;case"error":console.error(s.default.red(`Error: ${S.message}`));break;case"history":for(let f of S.segments)_q(f);break;case"segment":if(S.segment.isFinal)P(),_q(S.segment);else X(S.segment);break}},onError:(S)=>{if(S instanceof DOMException&&S.name==="AbortError"){P(),B();return}N(S)},onSuccess:()=>{if(!j)A("Live transcription not available for this call.");B()}})}).catch((B)=>{P(),o1(B)})}),K.command("transfer <uuid> <destination>").description("Transfer an active call").action(()=>g$()),K.command("spy <uuid>").description("Spy on an active call").action(()=>g$()),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(_)=>{let{format:U,fields:Q}=M($.opts()),q=await w(v().callRecords.list({page:Number(_.page),limit:Number(_.limit),dateFrom:_.from,dateTo:_.to,visualPlanId:F("visual_plans",_.plan),channelId:F("channels",_.phone),status:_.status,callerSearch:_.caller,minDuration:_.minDuration!=null?Number(_.minDuration):void 0,maxDuration:_.maxDuration!=null?Number(_.maxDuration):void 0,hasRecording:_.hasRecording,hasTranscription:_.hasTranscription}));if(U==="json"){if(Q)k(q.items.map((G)=>T(G,Q)));else k(q);return}if(q.items.length===0){A("No call records found.");return}y(["ID","Caller","Direction","Duration","Status","Sentiment","Plan","Date"],q.items.map((G)=>{let j=G.sentiment_score!=null?Number(G.sentiment_score):null;return{ID:G.id,Caller:G.caller_id??"—",Direction:G.direction??"—",Duration:I$(G.duration_ms),Status:$U(G.hangup_disposition),Sentiment:G.sentiment_label!=null?vU(G.sentiment_label,j):"—",Plan:G.visual_plan_name??"—",Date:m$(G.started_at)}})),_$(q)}),K.command("trace <callRecordId>").description("Show node-by-node execution trace for a call").action(async(_)=>{let{format:U,fields:Q}=M($.opts()),q=await w(v().callRecords.getTrace({callRecordId:F("call_records",_)}));if(U==="json"){let B=Q&&q!=null?T(q,Q):q;k(B);return}if(q==null){A("Call trace not found.");return}let G=q.callRecord;if(console.log(`${s.default.bold("Call Trace")} — ${_} (${I$(G.duration_ms)}, ${G.hangup_disposition??"unknown"})`),G.visual_plan_name!=null)console.log(`Plan: ${G.visual_plan_name}`);console.log("");let j=q.events;if(j.length===0){A(" No events recorded (0 nodes visited).");return}let Y=j.map((B,N)=>{let S=B.duration_ms!=null?`${(B.duration_ms/1000).toFixed(1)}s`:"—",f=`${s.default.cyan(B.node_type)}`;if(B.node_label!=null){let D$=s.default.bold(`"${B.node_label}"`);f+=` ${D$}`}if(f+=s.default.dim(` (${S})`),B.digit!=null)f+=` → digit: ${s.default.yellow(B.digit)}`;let p=[];if(B.handle_used!=null)p.push(s.default.dim(`└─→ ${B.handle_used}`));if(K1(B.data)){let D$=Object.entries(B.data).filter(([,l1])=>l1!=null&&typeof l1!=="object").map(([l1,A$])=>`${l1}: ${String(A$)}`);if(D$.length>0)p.push(s.default.dim(`└─ ${D$.join(", ")}`))}return{label:f,children:p.length>0?p:void 0}});UU(Y),console.log("");let X=j.at(-1),P=X.node_label??X.node_type;A(` ${j.length} nodes visited · Last: ${X.node_type} "${P}" · Hangup: ${G.hangup_cause??"—"}`)}),K.command("transcript <callRecordId>").description("Show call transcription with speech analytics").action(async(_)=>{let{format:U,fields:Q}=M($.opts()),q=await w(v().ai.getTranscription({callRecordId:F("call_records",_)}));if(U==="json"){let Y=Q&&q!=null?T(q,Q):q;k(Y);return}console.log(`${s.default.bold("Transcript")} — ${_}`),console.log("");let G=GX(q?.segments);if(G.length===0||q?.status==="none")A(" No transcript available.");else bQ(G);let j=q!=null?WX(q):[];if(j.length>0)console.log(""),a([{title:"Speech Analytics",rows:j}])}),K.command("purge-voice <callRecordId>").description("Permanently erase a call's voice content (recording, transcription, embeddings)").action(async(_)=>{let{format:U}=M($.opts()),Q=$.opts().yes===!0;if(U!=="json")console.log(`${s.default.bold("Erase voice content")} — ${_}`),A(" Deletes: recording file, transcription and its semantic-search embeddings."),A(" Keeps: the call record (CDR), its event timeline and existing analyses."),A(" This is irreversible."),console.log("");await W1("Erase the voice content of this call?",{yes:Q});let q=await w(v().callRecords.purgeVoiceContent({callRecordId:F("call_records",_)}));if(U==="json"){k(q);return}g("Voice content erased"),a([{title:"Deleted",rows:[{label:"Recording",value:String(q.deleted.recording)},{label:"Transcriptions",value:String(q.deleted.transcriptions)},{label:"Embeddings",value:String(q.deleted.embeddings)},{label:"Analyses detached",value:String(q.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(_,U)=>{let{format:Q,fields:q}=M($.opts()),G=await w(v().ai.searchTranscriptions({query:_,limit:Number(U.limit),threshold:Number(U.threshold),dateFrom:U.from,dateTo:U.to,visualPlanId:F("visual_plans",U.plan)}));if(Q==="json"){let Y=q?G.map((X)=>T(X,q)):G;k(Y);return}let j=G;if(console.log(`${s.default.bold("Semantic Search")}: "${_}"`),console.log(`${j.length} result${j.length!==1?"s":""} (threshold: ${U.threshold})`),j.length===0){A(`
|
|
46
|
-
|
|
47
|
-
│ `)});let U=_1($.topics);if(U.length>0)v.push({label:"Topics",value:U.map(qX).join(" · ")});return v}function qq($){let v=Math.floor($.start/60),K=Math.floor($.start%60),_=`${String(v).padStart(2,"0")}:${String(K).padStart(2,"0")}`,U=$.channel===0?s.default.blue("Caller"):s.default.green("System");return`${s.default.dim(`[${_}]`)} ${U} ${s.default.dim(">")} ${$.text}`}function _q($){console.log(qq($))}import{readFile as jX}from"node:fs/promises";async function Gq($){let v=$==="-"?await t1():await jX($,"utf-8"),K=JSON.parse(v);if(!K1(K))x(`Invalid campaign file "${$}": expected a JSON object`),process.exit(R.USAGE_ERROR);return K}function YX($){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 JX($){let v=$.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},...v!=null&&{retry_on_busy:v.has("busy"),retry_on_no_answer:v.has("no_answer"),retry_on_failed:v.has("failed")},...$.recurring===!0&&{recurring:!0}}}function Wq($){return{...YX($),...JX($)}}function a1($){if($==null)return"inherit (org default)";if(typeof $==="boolean")return $?"yes":"no";return String($)}function jq($){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 Yq($,v){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(_)=>{let{format:U,fields:Q}=M($.opts()),q=await w(v().dialerCampaigns.list({page:Number(_.page),limit:Number(_.limit),search:_.search,status:E$(_.status)}));if(U==="json"){let G=Q?q.items.map((j)=>T(j,Q)):q;k(G);return}y(["ID","Name","Status","Contacts","Answered","Created"],q.items.map((G)=>({ID:G.id,Name:G.name,Status:G.status,Contacts:G.total_contacts,Answered:G.answered_count,Created:m$(G.created_at)}))),_$(q)}),K.command("show <campaignId>").description("Show campaign details").action(async(_)=>{let{format:U,fields:Q}=M($.opts()),q=await w(v().dialerCampaigns.get({campaignId:F("dialer_campaigns",_)}));if(q==null){if(U==="json")k(null),process.exit(R.NOT_FOUND);x("Campaign not found"),process.exit(R.NOT_FOUND)}if(U==="json"){let G=Q?T(q,Q):q;k(G);return}a([{title:"Campaign",rows:[{label:"ID",value:q.id},{label:"Name",value:q.name},{label:"Description",value:q.description},{label:"Status",value:q.status},{label:"Plan",value:q.plan_id},{label:"Channel",value:q.channel_type},{label:"Priority",value:q.priority},{label:"Created",value:new Date(q.created_at).toLocaleString()},{label:"Updated",value:new Date(q.updated_at).toLocaleString()}]},{title:"Dialing",rows:[{label:"Caller ID",value:q.caller_id},{label:"Trunk",value:q.trunk_override},{label:"Max Concurrent",value:q.max_concurrent_calls},{label:"Ring Timeout",value:`${q.ring_timeout_s}s`},{label:"Max Duration",value:`${q.max_call_duration_s}s`}]},{title:"Retry",rows:[{label:"Max Attempts",value:q.retry_max_attempts},{label:"Interval",value:`${q.retry_interval_min}min`},{label:"On Busy",value:q.retry_on_busy?"yes":"no"},{label:"On No Answer",value:q.retry_on_no_answer?"yes":"no"},{label:"On Failed",value:q.retry_on_failed?"yes":"no"}]},{title:"Answering machine",rows:[{label:"Detection",value:q.amd_enabled?"on":"off"},{label:"Retry On Machine",value:q.retry_on_machine?"yes":"no"},{label:"Block After All",value:a1(q.amd_block_after_all_machine)},{label:"Block Min Attempts",value:a1(q.amd_block_min_attempts)},{label:"On Voicemail",value:a1(q.amd_action_voicemail)},{label:"On Announcement",value:a1(q.amd_action_announcement)},{label:"On IVR",value:a1(q.amd_action_ivr)},{label:"On Screening",value:a1(q.amd_action_screening)}]},{title:"Window & schedule",rows:[{label:"Window Start",value:q.call_window_start},{label:"Window End",value:q.call_window_end},{label:"Window Days",value:q.call_window_days},{label:"Recurring",value:q.recurring?"yes":"no"},{label:"Recurrence",value:q.recurrence_mode},{label:"Auto Start",value:q.auto_start_at?new Date(q.auto_start_at).toLocaleString():null},{label:"Auto Stop",value:q.auto_stop_at?new Date(q.auto_stop_at).toLocaleString():null}]}])}),K.command("stats <campaignId>").description("Show campaign statistics").action(async(_)=>{let{format:U,fields:Q}=M($.opts()),q=await w(v().dialerCampaigns.stats({campaignId:F("dialer_campaigns",_)}));if(U==="json"){let Y=Q?T(q,Q):q;k(Y);return}let G=q.capacityContext;a([{title:"Stats",rows:[{label:"Status",value:q.status},{label:"Total",value:q.total_contacts},{label:"Pending",value:q.pendingCount},{label:"Calling",value:q.callingCount},{label:"Answered",value:q.answered_count},{label:"Machine",value:q.machine_count},{label:"Busy",value:q.busy_count},{label:"No Answer",value:q.no_answer_count},{label:"Failed",value:q.failed_count},{label:"DNC Skipped",value:q.dnc_skipped_count},{label:"Cancelled",value:q.cancelled_count}]},{title:"Capacity",rows:[{label:"Waiting",value:q.waitingCapacity?"yes":"no"},{label:"Used",value:G!=null?G.used:null},{label:"Capacity",value:G!=null?G.capacity:null},{label:"Reserve",value:G!=null?G.reserve:null},{label:"Module Disabled",value:q.moduleDisabled?"yes":"no"}]}]);let j=Number(q.total_contacts);if(j>0)console.log(""),T$("Answered",Number(q.answered_count),j),T$("Busy",Number(q.busy_count),j),T$("No Answer",Number(q.no_answer_count),j),T$("Failed",Number(q.failed_count),j)}),K.command("summary").description("Show running-campaign summary").action(async()=>{let{format:_,fields:U}=M($.opts()),Q=await w(v().dialerCampaigns.summary());if(_==="json"){let q=U?T(Q,U):Q;k(q);return}a([{title:"Summary",rows:[{label:"Running",value:Q.running},{label:"Calling",value:Q.calling},{label:"Campaign",value:Q.campaign!=null?`${Q.campaign.name} (${Q.campaign.id})`:null}]}])}),jq(K.command("create <name>").description("Create a dialer campaign").requiredOption("--plan <planId>","Visual plan ID to dial")).action(async(_,U)=>{let{format:Q}=M($.opts()),q=U.file!=null?await Gq(U.file):{},G=Wq(U),j=await w(v().dialerCampaigns.create({...q,...G,name:_,plan_id:F("visual_plans",U.plan)}));if(Q==="json"){k(j);return}g(`Campaign created: ${j.id} — ${j.name}`)}),jq(K.command("edit <campaignId>").description("Update a dialer campaign").option("--name <name>","Campaign name")).action(async(_,U)=>{let{format:Q}=M($.opts()),q=U.file!=null?await Gq(U.file):{},G=Wq(U),j=await w(v().dialerCampaigns.update({campaignId:F("dialer_campaigns",_),...q,...G}));if(Q==="json"){k(j);return}g(`Campaign updated: ${j.name}`)}),K.command("delete <campaignId>").description("Delete a dialer campaign").action(async(_)=>{let{format:U}=M($.opts());if(await w(v().dialerCampaigns.delete({campaignId:F("dialer_campaigns",_)})),U==="json"){k({success:!0});return}g("Campaign deleted")});for(let _ of["start","pause","resume","stop"])K.command(`${_} <campaignId>`).description(`${_[0].toUpperCase()}${_.slice(1)} a campaign`).action(async(U)=>{let{format:Q}=M($.opts()),q=await w(v().dialerCampaigns.control({campaignId:F("dialer_campaigns",U),action:_}));if(Q==="json"){k(q);return}g(`Campaign "${q.name}" → ${q.status}`)});K.command("watch <campaignId>").description("Watch live campaign stats (streams until Ctrl-C)").action(async(_)=>{let{format:U}=M($.opts()),Q=v(),q=new AbortController;process.on("SIGINT",()=>{q.abort()}),await new Promise((G,j)=>{J1(Q.dialerCampaigns.liveStats({campaignId:F("dialer_campaigns",_)},{signal:q.signal}),{onEvent:(Y)=>{if(U==="json"){console.log(JSON.stringify(Y));return}let X=new Date().toLocaleTimeString(),P=Y.counters,B=Y.waitingCapacity?"yes":"no";console.log(`${X} status=${Y.status} calling=${Y.calling} pending_retry=${Y.pendingRetry} answered=${P.answered_count} busy=${P.busy_count} failed=${P.failed_count} waiting_capacity=${B}`)},onError:(Y)=>{if(Y instanceof DOMException&&Y.name==="AbortError"){G();return}j(Y)},onSuccess:()=>{G()}})}).catch(o1)}),K.command("attempts <campaignId>").description("List call attempts for a campaign").option("--status <s>","Filter by attempt status").option("--contact <contactId>","Filter by contact ID").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(_,U)=>{let{format:Q,fields:q}=M($.opts()),G=await w(v().dialerAttempts.list({campaignId:F("dialer_campaigns",_),status:E$(U.status),contactId:F("dialer_contacts",U.contact),page:Number(U.page),limit:Number(U.limit)}));if(Q==="json"){let j=q?G.items.map((Y)=>T(Y,q)):G;k(j);return}y(["ID","#","Phone","Name","Status","Machine","Cause","Started","Duration","Record"],G.items.map((j)=>({ID:j.id,"#":j.attempt_number,Phone:j.phone_number??"—",Name:j.contact_name??"—",Status:j.status??"—",Machine:S6(j.machine_type),Cause:j.hangup_cause??"—",Started:j.started_at?m$(j.started_at):"—",Duration:j.duration_s!=null?I$(j.duration_s*1000):"—",Record:j.call_record_id??"—"}))),_$(G)})}import{readFile as zX}from"node:fs/promises";var H$=v1(Q1(),1);function XX($,v={}){let _=$?.pipeThrough(new TextDecoderStream).pipeThrough(new BU)?.getReader(),U,Q=!1;return new Y1(async()=>{U??=c6("consume_event_iterator_stream");try{while(!0){if(_===void 0)return{done:!0,value:void 0};let{done:q,value:G}=await z1(U,()=>_.read());if(q){if(Q)throw new JU("Stream was cancelled");return{done:!0,value:void 0}}switch(G.event){case"message":{let j=y4(G.data);if(h$(j))j=x1(j,G);return U?.addEvent("message"),{done:!1,value:j}}case"error":{let j=new a$({data:y4(G.data)});throw j=x1(j,G),U?.addEvent("error"),j}case"done":{let j=y4(G.data);if(h$(j))j=x1(j,G);return U?.addEvent("done"),{done:!0,value:j}}default:U?.addEvent("maybe_keepalive")}}}catch(q){if(!(q instanceof a$))j1(U,q,v);throw q}},async(q)=>{try{if(q!=="next")Q=!0,U?.addEvent("cancelled");await z1(U,()=>_?.cancel())}catch(G){throw j1(U,G,v),G}finally{U?.end()}})}function HX($,v={}){let K=v.eventIteratorKeepAliveEnabled??!0,_=v.eventIteratorKeepAliveInterval??5000,U=v.eventIteratorKeepAliveComment??"",Q=v.eventIteratorInitialCommentEnabled??!0,q=v.eventIteratorInitialComment??"",G=!1,j,Y;return new ReadableStream({start(P){if(Y=c6("stream_event_iterator"),Q)P.enqueue(h4({comments:[q]}))},async pull(P){try{if(K)j=setInterval(()=>{P.enqueue(h4({comments:[U]})),Y?.addEvent("keepalive")},_);let B=await z1(Y,()=>$.next());if(clearInterval(j),G)return;let N=p1(B.value);if(!B.done||B.value!==void 0||N!==void 0){let S=B.done?"done":"message";P.enqueue(h4({...N,event:S,data:F1(B.value)})),Y?.addEvent(S)}if(B.done)P.close(),Y?.end()}catch(B){if(clearInterval(j),G)return;if(B instanceof a$)P.enqueue(h4({...p1(B),event:"error",data:F1(B.data)})),Y?.addEvent("error"),P.close();else j1(Y,B),P.error(B);Y?.end()}},async cancel(){try{G=!0,clearInterval(j),Y?.addEvent("cancelled"),await z1(Y,()=>$.return?.())}catch(P){throw j1(Y,P),P}finally{Y?.end()}}}).pipeThrough(new TextEncoderStream)}function PX($,v={}){return A1({name:"parse_standard_body",signal:v.signal},async()=>{let K=$.headers.get("content-disposition");if(typeof K==="string"){let Q=vq(K)??"blob",q=await $.blob();return new File([q],Q,{type:q.type})}let _=$.headers.get("content-type");if(!_||_.startsWith("application/json")){let Q=await $.text();return y4(Q)}if(_.startsWith("multipart/form-data"))return await $.formData();if(_.startsWith("application/x-www-form-urlencoded")){let Q=await $.text();return new URLSearchParams(Q)}if(_.startsWith("text/event-stream"))return XX($.body,v);if(_.startsWith("text/plain"))return await $.text();let U=await $.blob();return new File([U],"blob",{type:U.type})})}function VX($,v,K={}){if($ instanceof ReadableStream)return $;let _=v.get("content-disposition");if(v.delete("content-type"),v.delete("content-disposition"),$===void 0)return;if($ instanceof Blob)return v.set("content-type",$.type),v.set("content-length",$.size.toString()),v.set("content-disposition",_??$q($ instanceof File?$.name:"blob")),$;if($ instanceof FormData)return $;if($ instanceof URLSearchParams)return $;if(p$($))return v.set("content-type","text/event-stream"),HX($,K);return v.set("content-type","application/json"),F1($)}function kU($,v={}){return $.forEach((K,_)=>{if(Array.isArray(v[_]))v[_].push(K);else if(v[_]!==void 0)v[_]=[v[_],K];else v[_]=K}),v}function BX($,v=new Headers){for(let[K,_]of Object.entries($))if(Array.isArray(_))for(let U of _)v.append(K,U);else if(_!==void 0)v.append(K,_);return v}function Jq($,v={}){let K=BX($.headers),_=VX($.body,K,v);return new Request($.url,{signal:$.signal,method:$.method,headers:K,body:_})}function Xq($,v={}){return{body:h6(()=>PX($,v)),status:$.status,get headers(){let K=kU($.headers);return Object.defineProperty(this,"headers",{value:K,writable:!0}),K},set headers(K){Object.defineProperty(this,"headers",{value:K,writable:!0})}}}class t6{plugins;constructor($=[]){this.plugins=[...$].sort((v,K)=>(v.order??0)-(K.order??0))}init($){for(let v of this.plugins)v.init?.($)}}class Hq{constructor($,v,K={}){this.codec=$,this.sender=v,new t6(K.plugins).init(K),this.interceptors=L1(K.interceptors),this.clientInterceptors=L1(K.clientInterceptors)}interceptors;clientInterceptors;call($,v,K){return A1({name:`${YU}.${$.join("/")}`,signal:K.signal},(_)=>{if(_?.setAttribute("rpc.system",YU),_?.setAttribute("rpc.method",$.join(".")),p$(v))v=XU({name:"consume_event_iterator_input",signal:K.signal},v);return C4(this.interceptors,{...K,path:$,input:v},async({path:U,input:Q,...q})=>{let G=E4(),j,Y=G?.trace.getActiveSpan()??_;if(Y&&G)j=G?.trace.setSpan(G.context.active(),Y);let X=await A1({name:"encode_request",context:j},()=>this.codec.encode(U,Q,q)),P=await C4(this.clientInterceptors,{...q,input:Q,path:U,request:X},({input:N,path:S,request:f,...p})=>{return A1({name:"send_request",signal:p.signal,context:j},()=>this.sender.call(f,p,S,N))}),B=await A1({name:"decode_response",context:j},()=>this.codec.decode(P,q,U,Q));if(p$(B))return XU({name:"consume_event_iterator_output",signal:q.signal},B);return B})})}}var Y$={BIGINT:0,DATE:1,NAN:2,UNDEFINED:3,URL:4,REGEXP:5,SET:6,MAP:7};class Pq{customSerializers;constructor($={}){if(this.customSerializers=$.customJsonSerializers??[],this.customSerializers.length!==new Set(this.customSerializers.map((v)=>v.type)).size)throw Error("Custom serializer type must be unique.")}serialize($,v=[],K=[],_=[],U=[]){for(let Q of this.customSerializers)if(Q.condition($)){let q=this.serialize(Q.serialize($),v,K,_,U);return K.push([Q.type,...v]),q}if($ instanceof Blob)return _.push(v),U.push($),[$,K,_,U];if(typeof $==="bigint")return K.push([Y$.BIGINT,...v]),[$.toString(),K,_,U];if($ instanceof Date){if(K.push([Y$.DATE,...v]),Number.isNaN($.getTime()))return[null,K,_,U];return[$.toISOString(),K,_,U]}if(Number.isNaN($))return K.push([Y$.NAN,...v]),[null,K,_,U];if($ instanceof URL)return K.push([Y$.URL,...v]),[$.toString(),K,_,U];if($ instanceof RegExp)return K.push([Y$.REGEXP,...v]),[$.toString(),K,_,U];if($ instanceof Set){let Q=this.serialize(Array.from($),v,K,_,U);return K.push([Y$.SET,...v]),Q}if($ instanceof Map){let Q=this.serialize(Array.from($.entries()),v,K,_,U);return K.push([Y$.MAP,...v]),Q}if(Array.isArray($))return[$.map((q,G)=>{if(q===void 0)return K.push([Y$.UNDEFINED,...v,G]),null;return this.serialize(q,[...v,G],K,_,U)[0]}),K,_,U];if(r6($)){let Q={};for(let q in $){if(q==="toJSON"&&typeof $[q]==="function")continue;Q[q]=this.serialize($[q],[...v,q],K,_,U)[0]}return[Q,K,_,U]}return[$,K,_,U]}deserialize($,v,K,_){let U={data:$};if(K&&_)K.forEach((Q,q)=>{let G=U,j="data";Q.forEach((Y)=>{if(G=G[j],j=Y,!Object.hasOwn(G,j))throw Error(`Security error: accessing non-existent path during deserialization. Path segment: ${j}`)}),G[j]=_(q)});for(let Q of v){let q=Q[0],G=U,j="data";for(let Y=1;Y<Q.length;Y++)if(G=G[j],j=Q[Y],!Object.hasOwn(G,j))throw Error(`Security error: accessing non-existent path during deserialization. Path segment: ${j}`);for(let Y of this.customSerializers)if(Y.type===q){G[j]=Y.deserialize(G[j]);break}switch(q){case Y$.BIGINT:G[j]=BigInt(G[j]);break;case Y$.DATE:G[j]=new Date(G[j]??"Invalid Date");break;case Y$.NAN:G[j]=Number.NaN;break;case Y$.UNDEFINED:G[j]=void 0;break;case Y$.URL:G[j]=new URL(G[j]);break;case Y$.REGEXP:{let[,Y,X]=G[j].match(/^\/(.*)\/([a-z]*)$/);G[j]=new RegExp(Y,X);break}case Y$.SET:G[j]=new Set(G[j]);break;case Y$.MAP:G[j]=new Map(G[j]);break}}return U.data}}function DX($){return`/${$.map(encodeURIComponent).join("/")}`}function bX($){if(typeof $.forEach==="function")return kU($);return $}function kX($){return Object.entries(n6).find(([,v])=>v.status===$)?.[0]??"MALFORMED_ORPC_ERROR_RESPONSE"}class Vq{constructor($,v){this.serializer=$,this.baseUrl=v.url,this.maxUrlLength=v.maxUrlLength??2083,this.fallbackMethod=v.fallbackMethod??"POST",this.expectedMethod=v.method??this.fallbackMethod,this.headers=v.headers??{}}baseUrl;maxUrlLength;fallbackMethod;expectedMethod;headers;async encode($,v,K){let _=bX(await f4(this.headers,K,$,v));if(K.lastEventId!==void 0)_=Uq(_,{"last-event-id":K.lastEventId});let U=await f4(this.expectedMethod,K,$,v),Q=await f4(this.baseUrl,K,$,v),q=new URL(Q);q.pathname=`${q.pathname.replace(/\/$/,"")}${DX($)}`;let G=this.serializer.serialize(v);if(U==="GET"&&!(G instanceof FormData)&&!p$(G)){let j=await f4(this.maxUrlLength,K,$,v),Y=new URL(q);if(Y.searchParams.append("data",F1(G)),Y.toString().length<=j)return{body:void 0,method:U,headers:_,url:Y,signal:K.signal}}return{url:q,method:U==="GET"?this.fallbackMethod:U,headers:_,body:G,signal:K.signal}}async decode($){let v=!l6($.status),K=await(async()=>{let _=!1;try{let U=await $.body();return _=!0,this.serializer.deserialize(U)}catch(U){if(!_)throw Error("Cannot parse response body, please check the response body and content-type.",{cause:U});throw Error("Invalid RPC response format.",{cause:U})}})();if(!v){if(PU(K))throw VU(K);throw new O1(kX($.status),{status:$.status,data:{...$,body:K}})}return K}}class Bq{constructor($){this.jsonSerializer=$}serialize($){if(p$($))return DU($,{value:async(v)=>this.#$(v,!1),error:async(v)=>{return new a$({data:this.#$(oQ(v).toJSON(),!1),cause:v})}});return this.#$($,!0)}#$($,v){let[K,_,U,Q]=this.jsonSerializer.serialize($),q=_.length===0?void 0:_;if(!v||Q.length===0)return{json:K,meta:q};let G=new FormData;return G.set("data",F1({json:K,meta:q,maps:U})),Q.forEach((j,Y)=>{G.set(Y.toString(),j)}),G}deserialize($){if(p$($))return DU($,{value:async(v)=>this.#v(v),error:async(v)=>{if(!(v instanceof a$))return v;let K=this.#v(v.data);if(PU(K))return VU(K,{cause:v});return new a$({data:K,cause:v})}});return this.#v($)}#v($){if($===void 0)return;if(!($ instanceof FormData))return this.jsonSerializer.deserialize($.json,$.meta??[]);let v=JSON.parse($.get("data"));return this.jsonSerializer.deserialize(v.json,v.meta??[],v.maps,(K)=>$.get(K.toString()))}}class NU extends Hq{constructor($,v){let K=new Pq(v),_=new Bq(K),U=new Vq(_,v);super(U,$,v)}}class Dq extends t6{initRuntimeAdapter($){for(let v of this.plugins)v.initRuntimeAdapter?.($)}}class bq{fetch;toFetchRequestOptions;adapterInterceptors;constructor($){new Dq($.plugins).initRuntimeAdapter($),this.fetch=$.fetch??globalThis.fetch.bind(globalThis),this.toFetchRequestOptions=$,this.adapterInterceptors=L1($.adapterInterceptors)}async call($,v,K,_){let U=Jq($,this.toFetchRequestOptions),Q=await C4(this.adapterInterceptors,{...v,request:U,path:K,input:_,init:{redirect:"manual"}},({request:G,path:j,input:Y,init:X,...P})=>this.fetch(G,X,P,j,Y));return Xq(Q,{signal:U.signal})}}class wU extends NU{constructor($){let v=new bq($);super(v,$)}}function kq($){try{let{hostname:v}=new URL($);return v.endsWith(".orb.local")||process.env.NIVA_INSECURE==="true"}catch{return!1}}async function p6($){A(`Connecting to ${$}`);let v=kq($)?{tls:{rejectUnauthorized:!1}}:void 0,K=new WebSocket($,v),_=!1;throw K.onopen=()=>{_=!0},K.onmessage=(U)=>{let Q=JSON.parse(typeof U.data==="string"?U.data:String(U.data)),q=k$(Q)??{},G=u$(q.type)??"";switch(G){case"connected":console.log(H$.default.green(` Connected. Type a message and press Enter. Ctrl+C or /quit to exit.
|
|
48
|
-
`)
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
Not enough data.`);return}console.log("");let Y=Math.max(...j.topics.map((X)=>X.call_count));for(let X of j.topics){let P=j.analyzed_count>0?Math.round(X.call_count/j.analyzed_count*100):0,B=q1(X.call_count,Y);console.log(` ${X.label.padEnd(16)} ${B} ${X.call_count} calls (${P}%) confidence: ${X.avg_confidence.toFixed(2)}`)}}),c4(K.command("intents").description("Show detected intents from call transcriptions")).option("--limit <n>","Max intents to show","10").action(async(_)=>{let{format:U,fields:Q}=M($.opts()),{dateFrom:q,dateTo:G}=G1(_),j=await w(v().dashboard.speechIntents({dateFrom:q,dateTo:G,limit:Number(_.limit),visualPlanId:F("visual_plans",_.plan),channelId:F("channels",_.phone)}));if(U==="json"){let X=Q?T(j,Q):j;k(X);return}if(console.log(`${F$.default.bold("Detected Intents")} (${j.analyzed_count} analyzed)`),!j.has_enough_data||j.intents.length===0){A(`
|
|
56
|
-
Not enough data.`);return}console.log("");let Y=Math.max(...j.intents.map((X)=>X.call_count));for(let X of j.intents)T$(X.label,X.call_count,Y)}),c4(K.command("trend").description("Show sentiment trend over time")).option("--granularity <g>","Granularity: hour or day","day").action(async(_)=>{let{format:U}=M($.opts()),{dateFrom:Q,dateTo:q}=G1(_,7),G=await w(v().dashboard.speechSentimentTrend({dateFrom:Q,dateTo:q,granularity:E$(_.granularity),visualPlanId:F("visual_plans",_.plan),channelId:F("channels",_.phone)}));if(U==="json"){k(G);return}if(console.log(F$.default.bold("Sentiment Trend")),G.length===0){A(`
|
|
57
|
-
|
|
58
|
-
No data available.`);return}console.log("");let j=Math.max(...G.map((Y)=>Y.total));for(let Y of G){let X=`${String(Y.hour).padStart(2,"0")}:00`,P=q1(Y.total,j),B=Y.total===j?F$.default.yellow(" ← peak"):"";console.log(` ${X} ${P} ${Y.total}${B}`)}}),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(_)=>{let{format:U,fields:Q}=M($.opts()),{dateFrom:q,dateTo:G}=G1(_),j=await w(v().dashboard.topPlans({dateFrom:q,dateTo:G,limit:Number(_.limit)}));if(U==="json"){let Y=Q?j.map((X)=>T(X,Q)):j;k(Y);return}if(console.log(F$.default.bold("Top Plans")),j.length===0){A(`
|
|
59
|
-
No data available.`);return}console.log(""),y(["Plan","Total","Answered","Avg Duration"],j.map((Y)=>({Plan:Y.visual_plan_name??"—",Total:Y.total,Answered:`${Y.answered} (${Y.total>0?Math.round(Y.answered/Y.total*100):0}%)`,"Avg Duration":I$(Y.avg_duration_ms)})))})}function Aq($,v){let K=$.command("channels").description("Channels (SIP, Telegram, etc.)");K.command("list").description("List channels").option("--limit <n>","Items per page","20").option("--page <n>","Page number","1").option("--type <type>","Filter by channel type").action(async(_)=>{let{format:U,fields:Q}=M($.opts()),q=await w(v().channels.list({page:Number(_.page),limit:Number(_.limit),..._.type!=null?{channelType:_.type}:{}}));if(U==="json"){let G=Q?q.items.map((j)=>T(j,Q)):q;k(G);return}y(["ID","Type","Name","Identifier","Active"],q.items.map((G)=>({ID:G.id,Type:G.channel_type,Name:G.name,Identifier:G.identifier??"—",Active:G.is_active?"yes":"no"}))),_$(q)}),K.command("assign <channelId>").description("Assign a channel to a plan").option("--plan <planId>","Plan ID to assign").action(()=>g$())}import{readFile as uX}from"node:fs/promises";var Fq=1e4;function Oq($,v){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(_)=>{let{format:U,fields:Q}=M($.opts()),q=await w(v().dialerDnc.list({page:Number(_.page),limit:Number(_.limit),search:_.search}));if(U==="json"){k(Q?q.items.map((G)=>T(G,Q)):q);return}y(["ID","Phone","Reason","Added"],q.items.map((G)=>({ID:G.id,Phone:G.phone_number,Reason:G.reason??"—",Added:m$(G.created_at)}))),_$(q)}),K.command("add <phone>").description("Add a number to the do-not-call list").option("--reason <r>","Reason for the block").action(async(_,U)=>{let{format:Q}=M($.opts()),q=await w(v().dialerDnc.add({phone_number:_,reason:U.reason}));if(Q==="json"){k(q);return}g(`Added ${q.phone_number} to DNC`)}),K.command("remove <ids...>").description("Remove do-not-call entries").action(async(_)=>{let{format:U}=M($.opts());if(_.length===1){let q=await w(v().dialerDnc.remove({dncId:F("dialer_dnc",_[0])}));if(U==="json"){k(q);return}g("Removed DNC entry");return}let Q=await w(v().dialerDnc.bulkRemove({ids:F("dialer_dnc",_)}));if(U==="json"){k(Q);return}g(`Removed ${Q.removed}`)}),K.command("check <phone>").description("Check if a number is on the DNC list (exit 0 = listed, 3 = not listed)").action(async(_)=>{let{format:U}=M($.opts()),Q=await w(v().dialerDnc.list({page:1,limit:20,search:_})),q=_.replaceAll(/\D/g,""),G=q===""?void 0:Q.items.find((j)=>{let Y=String(j.phone_number).replaceAll(/\D/g,"");return Y===q||Y.endsWith(q)});if(G!=null){if(U==="json")k(G);else a([{title:"DNC entry",rows:[{label:"ID",value:G.id},{label:"Phone",value:G.phone_number},{label:"Reason",value:G.reason??"—"},{label:"Added",value:new Date(G.created_at).toLocaleString()}]}]);return}if(U==="json")k({listed:!1});else A("Not in DNC list.");process.exit(R.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(_,U)=>{let{format:Q}=M($.opts()),G=(await uX(_,"utf-8")).split(/\r\n|\n|\r/).map((X)=>X.trim()).filter((X)=>X.length>0&&!X.startsWith("#"));if(G.length===0)x("No phone numbers found in file"),process.exit(R.USAGE_ERROR);let j=0,Y=0;for(let X=0;X<G.length;X+=Fq){let P=G.slice(X,X+Fq),B=await w(v().dialerDnc.bulkImport({numbers:P,reason:U.reason}));j+=B.added,Y+=B.skipped}if(Q==="json"){k({added:j,skipped:Y});return}g(`Added ${j}, skipped ${Y}`)})}var W={};o$(W,{xor:()=>U5,xid:()=>zG,void:()=>pG,uuidv7:()=>DG,uuidv6:()=>BG,uuidv4:()=>VG,uuid:()=>PG,util:()=>z,url:()=>bG,uppercase:()=>Y4,unknown:()=>f1,union:()=>Zv,undefined:()=>dG,ulid:()=>ZG,uint64:()=>lG,uint32:()=>rG,tuple:()=>m3,trim:()=>B4,treeifyError:()=>gU,transform:()=>Lv,toUpperCase:()=>b4,toLowerCase:()=>D4,toJSONSchema:()=>a0,templateLiteral:()=>V5,symbol:()=>oG,superRefine:()=>H_,success:()=>X5,stringbool:()=>I5,stringFormat:()=>EG,string:()=>Kv,strictObject:()=>$5,startsWith:()=>X4,slugify:()=>k4,size:()=>E1,setErrorMap:()=>YV,set:()=>G5,safeParseAsync:()=>P3,safeParse:()=>H3,safeEncodeAsync:()=>w3,safeEncode:()=>k3,safeDecodeAsync:()=>M3,safeDecode:()=>N3,registry:()=>M0,regexes:()=>x$,regex:()=>W4,refine:()=>X_,record:()=>h3,readonly:()=>q_,property:()=>o0,promise:()=>B5,prettifyError:()=>EU,preprocess:()=>z5,prefault:()=>s3,positive:()=>r0,pipe:()=>B6,partialRecord:()=>_5,parseAsync:()=>X3,parse:()=>J3,overwrite:()=>C$,optional:()=>P6,object:()=>sG,number:()=>Z3,nullish:()=>J5,nullable:()=>V6,null:()=>O3,normalize:()=>V4,nonpositive:()=>n0,nonoptional:()=>$_,nonnegative:()=>l0,never:()=>Iv,negative:()=>i0,nativeEnum:()=>W5,nanoid:()=>wG,nan:()=>H5,multipleOf:()=>B1,minSize:()=>n$,minLength:()=>s$,mime:()=>P4,meta:()=>w5,maxSize:()=>D1,maxLength:()=>C1,map:()=>q5,mac:()=>FG,lte:()=>z$,lt:()=>r$,lowercase:()=>j4,looseRecord:()=>Q5,looseObject:()=>v5,locales:()=>j6,literal:()=>j5,length:()=>y1,lazy:()=>j_,ksuid:()=>LG,keyof:()=>eG,jwt:()=>gG,json:()=>Z5,iso:()=>M4,ipv6:()=>OG,ipv4:()=>AG,intersection:()=>y3,int64:()=>nG,int32:()=>cG,int:()=>_v,instanceof:()=>M5,includes:()=>J4,httpUrl:()=>kG,hostname:()=>CG,hex:()=>yG,hash:()=>fG,guid:()=>HG,gte:()=>V$,gt:()=>i$,globalRegistry:()=>W$,getErrorMap:()=>JV,function:()=>D5,fromJSONSchema:()=>A5,formatError:()=>e4,float64:()=>hG,float32:()=>mG,flattenError:()=>a4,file:()=>Y5,exactOptional:()=>d3,enum:()=>zv,endsWith:()=>H4,encodeAsync:()=>D3,encode:()=>V3,emoji:()=>NG,email:()=>XG,e164:()=>TG,discriminatedUnion:()=>K5,describe:()=>N5,decodeAsync:()=>b3,decode:()=>B3,date:()=>aG,custom:()=>k5,cuid2:()=>IG,cuid:()=>MG,core:()=>$1,config:()=>K$,coerce:()=>V_,codec:()=>P5,clone:()=>P$,cidrv6:()=>RG,cidrv4:()=>xG,check:()=>b5,catch:()=>K_,boolean:()=>z3,bigint:()=>iG,base64url:()=>uG,base64:()=>SG,array:()=>k6,any:()=>tG,_function:()=>D5,_default:()=>a3,_ZodString:()=>Qv,ZodXor:()=>g3,ZodXID:()=>Xv,ZodVoid:()=>u3,ZodUnknown:()=>R3,ZodUnion:()=>w6,ZodUndefined:()=>A3,ZodUUID:()=>l$,ZodURL:()=>D6,ZodULID:()=>Jv,ZodType:()=>m,ZodTuple:()=>f3,ZodTransform:()=>l3,ZodTemplateLiteral:()=>G_,ZodSymbol:()=>L3,ZodSuccess:()=>v_,ZodStringFormat:()=>o,ZodString:()=>Z4,ZodSet:()=>r3,ZodRecord:()=>M6,ZodRealError:()=>M$,ZodReadonly:()=>Q_,ZodPromise:()=>Y_,ZodPrefault:()=>e3,ZodPipe:()=>Ov,ZodOptional:()=>Av,ZodObject:()=>N6,ZodNumberFormat:()=>m1,ZodNumber:()=>L4,ZodNullable:()=>t3,ZodNull:()=>F3,ZodNonOptional:()=>Fv,ZodNever:()=>S3,ZodNanoID:()=>Wv,ZodNaN:()=>__,ZodMap:()=>c3,ZodMAC:()=>I3,ZodLiteral:()=>i3,ZodLazy:()=>W_,ZodKSUID:()=>Hv,ZodJWT:()=>wv,ZodIssueCode:()=>jV,ZodIntersection:()=>C3,ZodISOTime:()=>vv,ZodISODuration:()=>Uv,ZodISODateTime:()=>s0,ZodISODate:()=>$v,ZodIPv6:()=>Vv,ZodIPv4:()=>Pv,ZodGUID:()=>H6,ZodFunction:()=>J_,ZodFirstPartyTypeKind:()=>P_,ZodFile:()=>n3,ZodExactOptional:()=>o3,ZodError:()=>GV,ZodEnum:()=>I4,ZodEmoji:()=>Gv,ZodEmail:()=>qv,ZodE164:()=>Nv,ZodDiscriminatedUnion:()=>E3,ZodDefault:()=>p3,ZodDate:()=>b6,ZodCustomStringFormat:()=>z4,ZodCustom:()=>I6,ZodCodec:()=>xv,ZodCatch:()=>U_,ZodCUID2:()=>Yv,ZodCUID:()=>jv,ZodCIDRv6:()=>Dv,ZodCIDRv4:()=>Bv,ZodBoolean:()=>A4,ZodBigIntFormat:()=>Mv,ZodBigInt:()=>F4,ZodBase64URL:()=>kv,ZodBase64:()=>bv,ZodArray:()=>T3,ZodAny:()=>x3,TimePrecision:()=>mK,NEVER:()=>ZU,$output:()=>TK,$input:()=>gK,$brand:()=>zU});var $1={};o$($1,{version:()=>R2,util:()=>z,treeifyError:()=>gU,toJSONSchema:()=>a0,toDotPath:()=>gq,safeParseAsync:()=>yU,safeParse:()=>CU,safeEncodeAsync:()=>XH,safeEncode:()=>YH,safeDecodeAsync:()=>HH,safeDecode:()=>JH,registry:()=>M0,regexes:()=>x$,process:()=>n,prettifyError:()=>EU,parseAsync:()=>$0,parse:()=>s6,meta:()=>N8,locales:()=>j6,isValidJWT:()=>$G,isValidBase64URL:()=>sq,isValidBase64:()=>s2,initializeContext:()=>b1,globalRegistry:()=>W$,globalConfig:()=>r4,formatError:()=>e4,flattenError:()=>a4,finalize:()=>N1,extractDefs:()=>k1,encodeAsync:()=>WH,encode:()=>qH,describe:()=>k8,decodeAsync:()=>jH,decode:()=>GH,createToJSONSchemaMethod:()=>M8,createStandardJSONSchemaMethod:()=>w4,config:()=>K$,clone:()=>P$,_xor:()=>CP,_xid:()=>u0,_void:()=>Y8,_uuidv7:()=>A0,_uuidv6:()=>L0,_uuidv4:()=>z0,_uuid:()=>Z0,_url:()=>J6,_uppercase:()=>Y4,_unknown:()=>W8,_union:()=>EP,_undefined:()=>Q8,_ulid:()=>S0,_uint64:()=>K8,_uint32:()=>aK,_tuple:()=>mP,_trim:()=>B4,_transform:()=>oP,_toUpperCase:()=>b4,_toLowerCase:()=>D4,_templateLiteral:()=>UV,_symbol:()=>_8,_superRefine:()=>b8,_success:()=>eP,_stringbool:()=>w8,_stringFormat:()=>N4,_string:()=>CK,_startsWith:()=>X4,_slugify:()=>k4,_size:()=>E1,_set:()=>rP,_safeParseAsync:()=>Q4,_safeParse:()=>_4,_safeEncodeAsync:()=>G0,_safeEncode:()=>Q0,_safeDecodeAsync:()=>W0,_safeDecode:()=>q0,_regex:()=>W4,_refine:()=>D8,_record:()=>hP,_readonly:()=>vV,_property:()=>o0,_promise:()=>_V,_positive:()=>r0,_pipe:()=>$V,_parseAsync:()=>K4,_parse:()=>U4,_overwrite:()=>C$,_optional:()=>dP,_number:()=>nK,_nullable:()=>tP,_null:()=>q8,_normalize:()=>V4,_nonpositive:()=>n0,_nonoptional:()=>aP,_nonnegative:()=>l0,_never:()=>j8,_negative:()=>i0,_nativeEnum:()=>nP,_nanoid:()=>O0,_nan:()=>H8,_multipleOf:()=>B1,_minSize:()=>n$,_minLength:()=>s$,_min:()=>V$,_mime:()=>P4,_maxSize:()=>D1,_maxLength:()=>C1,_max:()=>z$,_map:()=>cP,_mac:()=>fK,_lte:()=>z$,_lt:()=>r$,_lowercase:()=>j4,_literal:()=>lP,_length:()=>y1,_lazy:()=>KV,_ksuid:()=>T0,_jwt:()=>c0,_isoTime:()=>rK,_isoDuration:()=>iK,_isoDateTime:()=>hK,_isoDate:()=>cK,_ipv6:()=>E0,_ipv4:()=>g0,_intersection:()=>fP,_int64:()=>U8,_int32:()=>pK,_int:()=>oK,_includes:()=>J4,_guid:()=>Y6,_gte:()=>V$,_gt:()=>i$,_float64:()=>tK,_float32:()=>dK,_file:()=>V8,_enum:()=>iP,_endsWith:()=>H4,_encodeAsync:()=>K0,_encode:()=>v0,_emoji:()=>F0,_email:()=>I0,_e164:()=>h0,_discriminatedUnion:()=>yP,_default:()=>pP,_decodeAsync:()=>_0,_decode:()=>U0,_date:()=>J8,_custom:()=>B8,_cuid2:()=>R0,_cuid:()=>x0,_coercedString:()=>yK,_coercedNumber:()=>lK,_coercedDate:()=>X8,_coercedBoolean:()=>sK,_coercedBigint:()=>v8,_cidrv6:()=>y0,_cidrv4:()=>C0,_check:()=>jG,_catch:()=>sP,_boolean:()=>eK,_bigint:()=>$8,_base64url:()=>m0,_base64:()=>f0,_array:()=>P8,_any:()=>G8,TimePrecision:()=>mK,NEVER:()=>ZU,JSONSchemaGenerator:()=>q3,JSONSchema:()=>YG,Doc:()=>X0,$output:()=>TK,$input:()=>gK,$constructor:()=>V,$brand:()=>zU,$ZodXor:()=>D9,$ZodXID:()=>c2,$ZodVoid:()=>H9,$ZodUnknown:()=>J9,$ZodUnion:()=>K6,$ZodUndefined:()=>W9,$ZodUUID:()=>T2,$ZodURL:()=>E2,$ZodULID:()=>h2,$ZodType:()=>C,$ZodTuple:()=>N0,$ZodTransform:()=>L9,$ZodTemplateLiteral:()=>C9,$ZodSymbol:()=>G9,$ZodSuccess:()=>S9,$ZodStringFormat:()=>l,$ZodString:()=>g1,$ZodSet:()=>M9,$ZodRegistry:()=>EK,$ZodRecord:()=>N9,$ZodRealError:()=>w$,$ZodReadonly:()=>E9,$ZodPromise:()=>f9,$ZodPrefault:()=>x9,$ZodPipe:()=>g9,$ZodOptional:()=>w0,$ZodObjectJIT:()=>B9,$ZodObject:()=>KG,$ZodNumberFormat:()=>Q9,$ZodNumber:()=>b0,$ZodNullable:()=>F9,$ZodNull:()=>j9,$ZodNonOptional:()=>R9,$ZodNever:()=>X9,$ZodNanoID:()=>y2,$ZodNaN:()=>T9,$ZodMap:()=>w9,$ZodMAC:()=>p2,$ZodLiteral:()=>Z9,$ZodLazy:()=>m9,$ZodKSUID:()=>r2,$ZodJWT:()=>K9,$ZodIntersection:()=>k9,$ZodISOTime:()=>l2,$ZodISODuration:()=>o2,$ZodISODateTime:()=>i2,$ZodISODate:()=>n2,$ZodIPv6:()=>t2,$ZodIPv4:()=>d2,$ZodGUID:()=>u2,$ZodFunction:()=>y9,$ZodFile:()=>z9,$ZodExactOptional:()=>A9,$ZodError:()=>p4,$ZodEnum:()=>I9,$ZodEncodeError:()=>S1,$ZodEmoji:()=>C2,$ZodEmail:()=>g2,$ZodE164:()=>U9,$ZodDiscriminatedUnion:()=>b9,$ZodDefault:()=>O9,$ZodDate:()=>P9,$ZodCustomStringFormat:()=>_9,$ZodCustom:()=>h9,$ZodCodec:()=>_6,$ZodCheckUpperCase:()=>Z2,$ZodCheckStringFormat:()=>q4,$ZodCheckStartsWith:()=>L2,$ZodCheckSizeEquals:()=>b2,$ZodCheckRegex:()=>M2,$ZodCheckProperty:()=>F2,$ZodCheckOverwrite:()=>x2,$ZodCheckNumberFormat:()=>P2,$ZodCheckMultipleOf:()=>H2,$ZodCheckMinSize:()=>D2,$ZodCheckMinLength:()=>N2,$ZodCheckMimeType:()=>O2,$ZodCheckMaxSize:()=>B2,$ZodCheckMaxLength:()=>k2,$ZodCheckLowerCase:()=>I2,$ZodCheckLessThan:()=>Y0,$ZodCheckLengthEquals:()=>w2,$ZodCheckIncludes:()=>z2,$ZodCheckGreaterThan:()=>J0,$ZodCheckEndsWith:()=>A2,$ZodCheckBigIntFormat:()=>V2,$ZodCheck:()=>t,$ZodCatch:()=>u9,$ZodCUID2:()=>m2,$ZodCUID:()=>f2,$ZodCIDRv6:()=>e2,$ZodCIDRv4:()=>a2,$ZodBoolean:()=>U6,$ZodBigIntFormat:()=>q9,$ZodBigInt:()=>k0,$ZodBase64URL:()=>v9,$ZodBase64:()=>$9,$ZodAsyncError:()=>c$,$ZodArray:()=>V9,$ZodAny:()=>Y9});var ZU=Object.freeze({status:"aborted"});function V($,v,K){function _(G,j){if(!G._zod)Object.defineProperty(G,"_zod",{value:{def:j,constr:q,traits:new Set},enumerable:!1});if(G._zod.traits.has($))return;G._zod.traits.add($),v(G,j);let Y=q.prototype,X=Object.keys(Y);for(let P=0;P<X.length;P++){let B=X[P];if(!(B in G))G[B]=Y[B].bind(G)}}let U=K?.Parent??Object;class Q extends U{}Object.defineProperty(Q,"name",{value:$});function q(G){var j;let Y=K?.Parent?new Q:this;_(Y,G),(j=Y._zod).deferred??(j.deferred=[]);for(let X of Y._zod.deferred)X();return Y}return Object.defineProperty(q,"init",{value:_}),Object.defineProperty(q,Symbol.hasInstance,{value:(G)=>{if(K?.Parent&&G instanceof K.Parent)return!0;return G?._zod?.traits?.has($)}}),Object.defineProperty(q,"name",{value:$}),q}var zU=Symbol("zod_brand");class c$ extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class S1 extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}}var r4={};function K$($){if($)Object.assign(r4,$);return r4}var z={};o$(z,{unwrapMessage:()=>i4,uint8ArrayToHex:()=>_H,uint8ArrayToBase64url:()=>UH,uint8ArrayToBase64:()=>Sq,stringifyPrimitive:()=>I,slugify:()=>FU,shallowClone:()=>xU,safeExtend:()=>pX,required:()=>sX,randomString:()=>rX,propertyKeyTypes:()=>o4,promiseAllObject:()=>cX,primitiveTypes:()=>RU,prefixIssues:()=>Z$,pick:()=>oX,partial:()=>eX,parsedType:()=>Z,optionalKeys:()=>SU,omit:()=>dX,objectClone:()=>fX,numKeys:()=>iX,nullish:()=>X1,normalizeParams:()=>L,mergeDefs:()=>e$,merge:()=>aX,jsonStringifyReplacer:()=>s1,joinValues:()=>D,issue:()=>v4,isPlainObject:()=>P1,isObject:()=>u1,hexToUint8Array:()=>KH,getSizableOrigin:()=>d4,getParsedType:()=>nX,getLengthableOrigin:()=>t4,getEnumValues:()=>n4,getElementAtPath:()=>hX,floatSafeRemainder:()=>AU,finalizeIssue:()=>N$,extend:()=>tX,escapeRegex:()=>O$,esc:()=>a6,defineLazy:()=>h,createTransparentProxy:()=>lX,cloneDef:()=>mX,clone:()=>P$,cleanRegex:()=>l4,cleanEnum:()=>$H,captureStackTrace:()=>e6,cached:()=>$4,base64urlToUint8Array:()=>vH,base64ToUint8Array:()=>Rq,assignProp:()=>H1,assertNotEqual:()=>gX,assertNever:()=>CX,assertIs:()=>EX,assertEqual:()=>TX,assert:()=>yX,allowsEval:()=>OU,aborted:()=>V1,NUMBER_FORMAT_RANGES:()=>uU,Class:()=>uq,BIGINT_FORMAT_RANGES:()=>TU});function TX($){return $}function gX($){return $}function EX($){}function CX($){throw Error("Unexpected value in exhaustive check")}function yX($){}function n4($){let v=Object.values($).filter((_)=>typeof _==="number");return Object.entries($).filter(([_,U])=>v.indexOf(+_)===-1).map(([_,U])=>U)}function D($,v="|"){return $.map((K)=>I(K)).join(v)}function s1($,v){if(typeof v==="bigint")return v.toString();return v}function $4($){return{get value(){{let K=$();return Object.defineProperty(this,"value",{value:K}),K}throw Error("cached value already set")}}}function X1($){return $===null||$===void 0}function l4($){let v=$.startsWith("^")?1:0,K=$.endsWith("$")?$.length-1:$.length;return $.slice(v,K)}function AU($,v){let K=($.toString().split(".")[1]||"").length,_=v.toString(),U=(_.split(".")[1]||"").length;if(U===0&&/\d?e-\d?/.test(_)){let j=_.match(/\d?e-(\d?)/);if(j?.[1])U=Number.parseInt(j[1])}let Q=K>U?K:U,q=Number.parseInt($.toFixed(Q).replace(".","")),G=Number.parseInt(v.toFixed(Q).replace(".",""));return q%G/10**Q}var xq=Symbol("evaluating");function h($,v,K){let _=void 0;Object.defineProperty($,v,{get(){if(_===xq)return;if(_===void 0)_=xq,_=K();return _},set(U){Object.defineProperty($,v,{value:U})},configurable:!0})}function fX($){return Object.create(Object.getPrototypeOf($),Object.getOwnPropertyDescriptors($))}function H1($,v,K){Object.defineProperty($,v,{value:K,writable:!0,enumerable:!0,configurable:!0})}function e$(...$){let v={};for(let K of $){let _=Object.getOwnPropertyDescriptors(K);Object.assign(v,_)}return Object.defineProperties({},v)}function mX($){return e$($._zod.def)}function hX($,v){if(!v)return $;return v.reduce((K,_)=>K?.[_],$)}function cX($){let v=Object.keys($),K=v.map((_)=>$[_]);return Promise.all(K).then((_)=>{let U={};for(let Q=0;Q<v.length;Q++)U[v[Q]]=_[Q];return U})}function rX($=10){let K="";for(let _=0;_<$;_++)K+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return K}function a6($){return JSON.stringify($)}function FU($){return $.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var e6="captureStackTrace"in Error?Error.captureStackTrace:(...$)=>{};function u1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var OU=$4(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});function P1($){if(u1($)===!1)return!1;let v=$.constructor;if(v===void 0)return!0;if(typeof v!=="function")return!0;let K=v.prototype;if(u1(K)===!1)return!1;if(Object.prototype.hasOwnProperty.call(K,"isPrototypeOf")===!1)return!1;return!0}function xU($){if(P1($))return{...$};if(Array.isArray($))return[...$];return $}function iX($){let v=0;for(let K in $)if(Object.prototype.hasOwnProperty.call($,K))v++;return v}var nX=($)=>{let v=typeof $;switch(v){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: ${v}`)}},o4=new Set(["string","number","symbol"]),RU=new Set(["string","number","bigint","boolean","symbol","undefined"]);function O$($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function P$($,v,K){let _=new $._zod.constr(v??$._zod.def);if(!v||K?.parent)_._zod.parent=$;return _}function L($){let v=$;if(!v)return{};if(typeof v==="string")return{error:()=>v};if(v?.message!==void 0){if(v?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");v.error=v.message}if(delete v.message,typeof v.error==="string")return{...v,error:()=>v.error};return v}function lX($){let v;return new Proxy({},{get(K,_,U){return v??(v=$()),Reflect.get(v,_,U)},set(K,_,U,Q){return v??(v=$()),Reflect.set(v,_,U,Q)},has(K,_){return v??(v=$()),Reflect.has(v,_)},deleteProperty(K,_){return v??(v=$()),Reflect.deleteProperty(v,_)},ownKeys(K){return v??(v=$()),Reflect.ownKeys(v)},getOwnPropertyDescriptor(K,_){return v??(v=$()),Reflect.getOwnPropertyDescriptor(v,_)},defineProperty(K,_,U){return v??(v=$()),Reflect.defineProperty(v,_,U)}})}function I($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function SU($){return Object.keys($).filter((v)=>{return $[v]._zod.optin==="optional"&&$[v]._zod.optout==="optional"})}var uU={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]},TU={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function oX($,v){let K=$._zod.def,_=K.checks;if(_&&_.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let Q=e$($._zod.def,{get shape(){let q={};for(let G in v){if(!(G in K.shape))throw Error(`Unrecognized key: "${G}"`);if(!v[G])continue;q[G]=K.shape[G]}return H1(this,"shape",q),q},checks:[]});return P$($,Q)}function dX($,v){let K=$._zod.def,_=K.checks;if(_&&_.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let Q=e$($._zod.def,{get shape(){let q={...$._zod.def.shape};for(let G in v){if(!(G in K.shape))throw Error(`Unrecognized key: "${G}"`);if(!v[G])continue;delete q[G]}return H1(this,"shape",q),q},checks:[]});return P$($,Q)}function tX($,v){if(!P1(v))throw Error("Invalid input to extend: expected a plain object");let K=$._zod.def.checks;if(K&&K.length>0){let Q=$._zod.def.shape;for(let q in v)if(Object.getOwnPropertyDescriptor(Q,q)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let U=e$($._zod.def,{get shape(){let Q={...$._zod.def.shape,...v};return H1(this,"shape",Q),Q}});return P$($,U)}function pX($,v){if(!P1(v))throw Error("Invalid input to safeExtend: expected a plain object");let K=e$($._zod.def,{get shape(){let _={...$._zod.def.shape,...v};return H1(this,"shape",_),_}});return P$($,K)}function aX($,v){let K=e$($._zod.def,{get shape(){let _={...$._zod.def.shape,...v._zod.def.shape};return H1(this,"shape",_),_},get catchall(){return v._zod.def.catchall},checks:[]});return P$($,K)}function eX($,v,K){let U=v._zod.def.checks;if(U&&U.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let q=e$(v._zod.def,{get shape(){let G=v._zod.def.shape,j={...G};if(K)for(let Y in K){if(!(Y in G))throw Error(`Unrecognized key: "${Y}"`);if(!K[Y])continue;j[Y]=$?new $({type:"optional",innerType:G[Y]}):G[Y]}else for(let Y in G)j[Y]=$?new $({type:"optional",innerType:G[Y]}):G[Y];return H1(this,"shape",j),j},checks:[]});return P$(v,q)}function sX($,v,K){let _=e$(v._zod.def,{get shape(){let U=v._zod.def.shape,Q={...U};if(K)for(let q in K){if(!(q in Q))throw Error(`Unrecognized key: "${q}"`);if(!K[q])continue;Q[q]=new $({type:"nonoptional",innerType:U[q]})}else for(let q in U)Q[q]=new $({type:"nonoptional",innerType:U[q]});return H1(this,"shape",Q),Q}});return P$(v,_)}function V1($,v=0){if($.aborted===!0)return!0;for(let K=v;K<$.issues.length;K++)if($.issues[K]?.continue!==!0)return!0;return!1}function Z$($,v){return v.map((K)=>{var _;return(_=K).path??(_.path=[]),K.path.unshift($),K})}function i4($){return typeof $==="string"?$:$?.message}function N$($,v,K){let _={...$,path:$.path??[]};if(!$.message){let U=i4($.inst?._zod.def?.error?.($))??i4(v?.error?.($))??i4(K.customError?.($))??i4(K.localeError?.($))??"Invalid input";_.message=U}if(delete _.inst,delete _.continue,!v?.reportInput)delete _.input;return _}function d4($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function t4($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function Z($){let v=typeof $;switch(v){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 v}function v4(...$){let[v,K,_]=$;if(typeof v==="string")return{message:v,code:"custom",input:K,inst:_};return{...v}}function $H($){return Object.entries($).filter(([v,K])=>{return Number.isNaN(Number.parseInt(v,10))}).map((v)=>v[1])}function Rq($){let v=atob($),K=new Uint8Array(v.length);for(let _=0;_<v.length;_++)K[_]=v.charCodeAt(_);return K}function Sq($){let v="";for(let K=0;K<$.length;K++)v+=String.fromCharCode($[K]);return btoa(v)}function vH($){let v=$.replace(/-/g,"+").replace(/_/g,"/"),K="=".repeat((4-v.length%4)%4);return Rq(v+K)}function UH($){return Sq($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function KH($){let v=$.replace(/^0x/,"");if(v.length%2!==0)throw Error("Invalid hex string length");let K=new Uint8Array(v.length/2);for(let _=0;_<v.length;_+=2)K[_/2]=Number.parseInt(v.slice(_,_+2),16);return K}function _H($){return Array.from($).map((v)=>v.toString(16).padStart(2,"0")).join("")}class uq{constructor(...$){}}var Tq=($,v)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:v,enumerable:!1}),$.message=JSON.stringify(v,s1,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},p4=V("$ZodError",Tq),w$=V("$ZodError",Tq,{Parent:Error});function a4($,v=(K)=>K.message){let K={},_=[];for(let U of $.issues)if(U.path.length>0)K[U.path[0]]=K[U.path[0]]||[],K[U.path[0]].push(v(U));else _.push(v(U));return{formErrors:_,fieldErrors:K}}function e4($,v=(K)=>K.message){let K={_errors:[]},_=(U)=>{for(let Q of U.issues)if(Q.code==="invalid_union"&&Q.errors.length)Q.errors.map((q)=>_({issues:q}));else if(Q.code==="invalid_key")_({issues:Q.issues});else if(Q.code==="invalid_element")_({issues:Q.issues});else if(Q.path.length===0)K._errors.push(v(Q));else{let q=K,G=0;while(G<Q.path.length){let j=Q.path[G];if(G!==Q.path.length-1)q[j]=q[j]||{_errors:[]};else q[j]=q[j]||{_errors:[]},q[j]._errors.push(v(Q));q=q[j],G++}}};return _($),K}function gU($,v=(K)=>K.message){let K={errors:[]},_=(U,Q=[])=>{var q,G;for(let j of U.issues)if(j.code==="invalid_union"&&j.errors.length)j.errors.map((Y)=>_({issues:Y},j.path));else if(j.code==="invalid_key")_({issues:j.issues},j.path);else if(j.code==="invalid_element")_({issues:j.issues},j.path);else{let Y=[...Q,...j.path];if(Y.length===0){K.errors.push(v(j));continue}let X=K,P=0;while(P<Y.length){let B=Y[P],N=P===Y.length-1;if(typeof B==="string")X.properties??(X.properties={}),(q=X.properties)[B]??(q[B]={errors:[]}),X=X.properties[B];else X.items??(X.items=[]),(G=X.items)[B]??(G[B]={errors:[]}),X=X.items[B];if(N)X.errors.push(v(j));P++}}};return _($),K}function gq($){let v=[],K=$.map((_)=>typeof _==="object"?_.key:_);for(let _ of K)if(typeof _==="number")v.push(`[${_}]`);else if(typeof _==="symbol")v.push(`[${JSON.stringify(String(_))}]`);else if(/[^\w$]/.test(_))v.push(`[${JSON.stringify(_)}]`);else{if(v.length)v.push(".");v.push(_)}return v.join("")}function EU($){let v=[],K=[...$.issues].sort((_,U)=>(_.path??[]).length-(U.path??[]).length);for(let _ of K)if(v.push(`✖ ${_.message}`),_.path?.length)v.push(` → at ${gq(_.path)}`);return v.join(`
|
|
60
|
-
`)}var U4=($)=>(v,K,_,U)=>{let Q=_?Object.assign(_,{async:!1}):{async:!1},q=v._zod.run({value:K,issues:[]},Q);if(q instanceof Promise)throw new c$;if(q.issues.length){let G=new(U?.Err??$)(q.issues.map((j)=>N$(j,Q,K$())));throw e6(G,U?.callee),G}return q.value},s6=U4(w$),K4=($)=>async(v,K,_,U)=>{let Q=_?Object.assign(_,{async:!0}):{async:!0},q=v._zod.run({value:K,issues:[]},Q);if(q instanceof Promise)q=await q;if(q.issues.length){let G=new(U?.Err??$)(q.issues.map((j)=>N$(j,Q,K$())));throw e6(G,U?.callee),G}return q.value},$0=K4(w$),_4=($)=>(v,K,_)=>{let U=_?{..._,async:!1}:{async:!1},Q=v._zod.run({value:K,issues:[]},U);if(Q instanceof Promise)throw new c$;return Q.issues.length?{success:!1,error:new($??p4)(Q.issues.map((q)=>N$(q,U,K$())))}:{success:!0,data:Q.value}},CU=_4(w$),Q4=($)=>async(v,K,_)=>{let U=_?Object.assign(_,{async:!0}):{async:!0},Q=v._zod.run({value:K,issues:[]},U);if(Q instanceof Promise)Q=await Q;return Q.issues.length?{success:!1,error:new $(Q.issues.map((q)=>N$(q,U,K$())))}:{success:!0,data:Q.value}},yU=Q4(w$),v0=($)=>(v,K,_)=>{let U=_?Object.assign(_,{direction:"backward"}):{direction:"backward"};return U4($)(v,K,U)},qH=v0(w$),U0=($)=>(v,K,_)=>{return U4($)(v,K,_)},GH=U0(w$),K0=($)=>async(v,K,_)=>{let U=_?Object.assign(_,{direction:"backward"}):{direction:"backward"};return K4($)(v,K,U)},WH=K0(w$),_0=($)=>async(v,K,_)=>{return K4($)(v,K,_)},jH=_0(w$),Q0=($)=>(v,K,_)=>{let U=_?Object.assign(_,{direction:"backward"}):{direction:"backward"};return _4($)(v,K,U)},YH=Q0(w$),q0=($)=>(v,K,_)=>{return _4($)(v,K,_)},JH=q0(w$),G0=($)=>async(v,K,_)=>{let U=_?Object.assign(_,{direction:"backward"}):{direction:"backward"};return Q4($)(v,K,U)},XH=G0(w$),W0=($)=>async(v,K,_)=>{return Q4($)(v,K,_)},HH=W0(w$);var x$={};o$(x$,{xid:()=>cU,uuid7:()=>DH,uuid6:()=>BH,uuid4:()=>VH,uuid:()=>T1,uppercase:()=>X2,unicodeEmail:()=>Eq,undefined:()=>Y2,ulid:()=>hU,time:()=>K2,string:()=>Q2,sha512_hex:()=>yH,sha512_base64url:()=>mH,sha512_base64:()=>fH,sha384_hex:()=>gH,sha384_base64url:()=>CH,sha384_base64:()=>EH,sha256_hex:()=>SH,sha256_base64url:()=>TH,sha256_base64:()=>uH,sha1_hex:()=>OH,sha1_base64url:()=>RH,sha1_base64:()=>xH,rfc5322Email:()=>kH,number:()=>s4,null:()=>j2,nanoid:()=>iU,md5_hex:()=>LH,md5_base64url:()=>FH,md5_base64:()=>AH,mac:()=>aU,lowercase:()=>J2,ksuid:()=>rU,ipv6:()=>pU,ipv4:()=>tU,integer:()=>G2,idnEmail:()=>NH,html5Email:()=>bH,hostname:()=>IH,hex:()=>zH,guid:()=>lU,extendedDuration:()=>PH,emoji:()=>dU,email:()=>oU,e164:()=>v2,duration:()=>nU,domain:()=>ZH,datetime:()=>_2,date:()=>U2,cuid2:()=>mU,cuid:()=>fU,cidrv6:()=>sU,cidrv4:()=>eU,browserEmail:()=>wH,boolean:()=>W2,bigint:()=>q2,base64url:()=>j0,base64:()=>$2});var fU=/^[cC][^\s-]{8,}$/,mU=/^[0-9a-z]+$/,hU=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,cU=/^[0-9a-vA-V]{20}$/,rU=/^[A-Za-z0-9]{27}$/,iU=/^[a-zA-Z0-9_-]{21}$/,nU=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,PH=/^[-+]?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)?)??$/,lU=/^([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})$/,T1=($)=>{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})$`)},VH=T1(4),BH=T1(6),DH=T1(7),oU=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,bH=/^[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])?)*$/,kH=/^(([^<>()\[\]\\.,;:\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,}))$/,Eq=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,NH=Eq,wH=/^[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])?)*$/,MH="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function dU(){return new RegExp(MH,"u")}var tU=/^(?:(?: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])$/,pU=/^(([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}|:))$/,aU=($)=>{let v=O$($??":");return new RegExp(`^(?:[0-9A-F]{2}${v}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${v}){5}[0-9a-f]{2}$`)},eU=/^((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])$/,sU=/^(([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])$/,$2=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,j0=/^[A-Za-z0-9_-]*$/,IH=/^(?=.{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])?)*\.?$/,ZH=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,v2=/^\+[1-9]\d{6,14}$/,Cq="(?:(?:\\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])))",U2=new RegExp(`^${Cq}$`);function yq($){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 K2($){return new RegExp(`^${yq($)}$`)}function _2($){let v=yq({precision:$.precision}),K=["Z"];if($.local)K.push("");if($.offset)K.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let _=`${v}(?:${K.join("|")})`;return new RegExp(`^${Cq}T(?:${_})$`)}var Q2=($)=>{let v=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${v}$`)},q2=/^-?\d+n?$/,G2=/^-?\d+$/,s4=/^-?\d+(?:\.\d+)?$/,W2=/^(?:true|false)$/i,j2=/^null$/i;var Y2=/^undefined$/i;var J2=/^[^A-Z]*$/,X2=/^[^a-z]*$/,zH=/^[0-9a-fA-F]*$/;function $6($,v){return new RegExp(`^[A-Za-z0-9+/]{${$}}${v}$`)}function v6($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var LH=/^[0-9a-fA-F]{32}$/,AH=$6(22,"=="),FH=v6(22),OH=/^[0-9a-fA-F]{40}$/,xH=$6(27,"="),RH=v6(27),SH=/^[0-9a-fA-F]{64}$/,uH=$6(43,"="),TH=v6(43),gH=/^[0-9a-fA-F]{96}$/,EH=$6(64,""),CH=v6(64),yH=/^[0-9a-fA-F]{128}$/,fH=$6(86,"=="),mH=v6(86);var t=V("$ZodCheck",($,v)=>{var K;$._zod??($._zod={}),$._zod.def=v,(K=$._zod).onattach??(K.onattach=[])}),mq={number:"number",bigint:"bigint",object:"date"},Y0=V("$ZodCheckLessThan",($,v)=>{t.init($,v);let K=mq[typeof v.value];$._zod.onattach.push((_)=>{let U=_._zod.bag,Q=(v.inclusive?U.maximum:U.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(v.value<Q)if(v.inclusive)U.maximum=v.value;else U.exclusiveMaximum=v.value}),$._zod.check=(_)=>{if(v.inclusive?_.value<=v.value:_.value<v.value)return;_.issues.push({origin:K,code:"too_big",maximum:typeof v.value==="object"?v.value.getTime():v.value,input:_.value,inclusive:v.inclusive,inst:$,continue:!v.abort})}}),J0=V("$ZodCheckGreaterThan",($,v)=>{t.init($,v);let K=mq[typeof v.value];$._zod.onattach.push((_)=>{let U=_._zod.bag,Q=(v.inclusive?U.minimum:U.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(v.value>Q)if(v.inclusive)U.minimum=v.value;else U.exclusiveMinimum=v.value}),$._zod.check=(_)=>{if(v.inclusive?_.value>=v.value:_.value>v.value)return;_.issues.push({origin:K,code:"too_small",minimum:typeof v.value==="object"?v.value.getTime():v.value,input:_.value,inclusive:v.inclusive,inst:$,continue:!v.abort})}}),H2=V("$ZodCheckMultipleOf",($,v)=>{t.init($,v),$._zod.onattach.push((K)=>{var _;(_=K._zod.bag).multipleOf??(_.multipleOf=v.value)}),$._zod.check=(K)=>{if(typeof K.value!==typeof v.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof K.value==="bigint"?K.value%v.value===BigInt(0):AU(K.value,v.value)===0)return;K.issues.push({origin:typeof K.value,code:"not_multiple_of",divisor:v.value,input:K.value,inst:$,continue:!v.abort})}}),P2=V("$ZodCheckNumberFormat",($,v)=>{t.init($,v),v.format=v.format||"float64";let K=v.format?.includes("int"),_=K?"int":"number",[U,Q]=uU[v.format];$._zod.onattach.push((q)=>{let G=q._zod.bag;if(G.format=v.format,G.minimum=U,G.maximum=Q,K)G.pattern=G2}),$._zod.check=(q)=>{let G=q.value;if(K){if(!Number.isInteger(G)){q.issues.push({expected:_,format:v.format,code:"invalid_type",continue:!1,input:G,inst:$});return}if(!Number.isSafeInteger(G)){if(G>0)q.issues.push({input:G,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:_,inclusive:!0,continue:!v.abort});else q.issues.push({input:G,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:_,inclusive:!0,continue:!v.abort});return}}if(G<U)q.issues.push({origin:"number",input:G,code:"too_small",minimum:U,inclusive:!0,inst:$,continue:!v.abort});if(G>Q)q.issues.push({origin:"number",input:G,code:"too_big",maximum:Q,inclusive:!0,inst:$,continue:!v.abort})}}),V2=V("$ZodCheckBigIntFormat",($,v)=>{t.init($,v);let[K,_]=TU[v.format];$._zod.onattach.push((U)=>{let Q=U._zod.bag;Q.format=v.format,Q.minimum=K,Q.maximum=_}),$._zod.check=(U)=>{let Q=U.value;if(Q<K)U.issues.push({origin:"bigint",input:Q,code:"too_small",minimum:K,inclusive:!0,inst:$,continue:!v.abort});if(Q>_)U.issues.push({origin:"bigint",input:Q,code:"too_big",maximum:_,inclusive:!0,inst:$,continue:!v.abort})}}),B2=V("$ZodCheckMaxSize",($,v)=>{var K;t.init($,v),(K=$._zod.def).when??(K.when=(_)=>{let U=_.value;return!X1(U)&&U.size!==void 0}),$._zod.onattach.push((_)=>{let U=_._zod.bag.maximum??Number.POSITIVE_INFINITY;if(v.maximum<U)_._zod.bag.maximum=v.maximum}),$._zod.check=(_)=>{let U=_.value;if(U.size<=v.maximum)return;_.issues.push({origin:d4(U),code:"too_big",maximum:v.maximum,inclusive:!0,input:U,inst:$,continue:!v.abort})}}),D2=V("$ZodCheckMinSize",($,v)=>{var K;t.init($,v),(K=$._zod.def).when??(K.when=(_)=>{let U=_.value;return!X1(U)&&U.size!==void 0}),$._zod.onattach.push((_)=>{let U=_._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(v.minimum>U)_._zod.bag.minimum=v.minimum}),$._zod.check=(_)=>{let U=_.value;if(U.size>=v.minimum)return;_.issues.push({origin:d4(U),code:"too_small",minimum:v.minimum,inclusive:!0,input:U,inst:$,continue:!v.abort})}}),b2=V("$ZodCheckSizeEquals",($,v)=>{var K;t.init($,v),(K=$._zod.def).when??(K.when=(_)=>{let U=_.value;return!X1(U)&&U.size!==void 0}),$._zod.onattach.push((_)=>{let U=_._zod.bag;U.minimum=v.size,U.maximum=v.size,U.size=v.size}),$._zod.check=(_)=>{let U=_.value,Q=U.size;if(Q===v.size)return;let q=Q>v.size;_.issues.push({origin:d4(U),...q?{code:"too_big",maximum:v.size}:{code:"too_small",minimum:v.size},inclusive:!0,exact:!0,input:_.value,inst:$,continue:!v.abort})}}),k2=V("$ZodCheckMaxLength",($,v)=>{var K;t.init($,v),(K=$._zod.def).when??(K.when=(_)=>{let U=_.value;return!X1(U)&&U.length!==void 0}),$._zod.onattach.push((_)=>{let U=_._zod.bag.maximum??Number.POSITIVE_INFINITY;if(v.maximum<U)_._zod.bag.maximum=v.maximum}),$._zod.check=(_)=>{let U=_.value;if(U.length<=v.maximum)return;let q=t4(U);_.issues.push({origin:q,code:"too_big",maximum:v.maximum,inclusive:!0,input:U,inst:$,continue:!v.abort})}}),N2=V("$ZodCheckMinLength",($,v)=>{var K;t.init($,v),(K=$._zod.def).when??(K.when=(_)=>{let U=_.value;return!X1(U)&&U.length!==void 0}),$._zod.onattach.push((_)=>{let U=_._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(v.minimum>U)_._zod.bag.minimum=v.minimum}),$._zod.check=(_)=>{let U=_.value;if(U.length>=v.minimum)return;let q=t4(U);_.issues.push({origin:q,code:"too_small",minimum:v.minimum,inclusive:!0,input:U,inst:$,continue:!v.abort})}}),w2=V("$ZodCheckLengthEquals",($,v)=>{var K;t.init($,v),(K=$._zod.def).when??(K.when=(_)=>{let U=_.value;return!X1(U)&&U.length!==void 0}),$._zod.onattach.push((_)=>{let U=_._zod.bag;U.minimum=v.length,U.maximum=v.length,U.length=v.length}),$._zod.check=(_)=>{let U=_.value,Q=U.length;if(Q===v.length)return;let q=t4(U),G=Q>v.length;_.issues.push({origin:q,...G?{code:"too_big",maximum:v.length}:{code:"too_small",minimum:v.length},inclusive:!0,exact:!0,input:_.value,inst:$,continue:!v.abort})}}),q4=V("$ZodCheckStringFormat",($,v)=>{var K,_;if(t.init($,v),$._zod.onattach.push((U)=>{let Q=U._zod.bag;if(Q.format=v.format,v.pattern)Q.patterns??(Q.patterns=new Set),Q.patterns.add(v.pattern)}),v.pattern)(K=$._zod).check??(K.check=(U)=>{if(v.pattern.lastIndex=0,v.pattern.test(U.value))return;U.issues.push({origin:"string",code:"invalid_format",format:v.format,input:U.value,...v.pattern?{pattern:v.pattern.toString()}:{},inst:$,continue:!v.abort})});else(_=$._zod).check??(_.check=()=>{})}),M2=V("$ZodCheckRegex",($,v)=>{q4.init($,v),$._zod.check=(K)=>{if(v.pattern.lastIndex=0,v.pattern.test(K.value))return;K.issues.push({origin:"string",code:"invalid_format",format:"regex",input:K.value,pattern:v.pattern.toString(),inst:$,continue:!v.abort})}}),I2=V("$ZodCheckLowerCase",($,v)=>{v.pattern??(v.pattern=J2),q4.init($,v)}),Z2=V("$ZodCheckUpperCase",($,v)=>{v.pattern??(v.pattern=X2),q4.init($,v)}),z2=V("$ZodCheckIncludes",($,v)=>{t.init($,v);let K=O$(v.includes),_=new RegExp(typeof v.position==="number"?`^.{${v.position}}${K}`:K);v.pattern=_,$._zod.onattach.push((U)=>{let Q=U._zod.bag;Q.patterns??(Q.patterns=new Set),Q.patterns.add(_)}),$._zod.check=(U)=>{if(U.value.includes(v.includes,v.position))return;U.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:v.includes,input:U.value,inst:$,continue:!v.abort})}}),L2=V("$ZodCheckStartsWith",($,v)=>{t.init($,v);let K=new RegExp(`^${O$(v.prefix)}.*`);v.pattern??(v.pattern=K),$._zod.onattach.push((_)=>{let U=_._zod.bag;U.patterns??(U.patterns=new Set),U.patterns.add(K)}),$._zod.check=(_)=>{if(_.value.startsWith(v.prefix))return;_.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:v.prefix,input:_.value,inst:$,continue:!v.abort})}}),A2=V("$ZodCheckEndsWith",($,v)=>{t.init($,v);let K=new RegExp(`.*${O$(v.suffix)}$`);v.pattern??(v.pattern=K),$._zod.onattach.push((_)=>{let U=_._zod.bag;U.patterns??(U.patterns=new Set),U.patterns.add(K)}),$._zod.check=(_)=>{if(_.value.endsWith(v.suffix))return;_.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:v.suffix,input:_.value,inst:$,continue:!v.abort})}});function fq($,v,K){if($.issues.length)v.issues.push(...Z$(K,$.issues))}var F2=V("$ZodCheckProperty",($,v)=>{t.init($,v),$._zod.check=(K)=>{let _=v.schema._zod.run({value:K.value[v.property],issues:[]},{});if(_ instanceof Promise)return _.then((U)=>fq(U,K,v.property));fq(_,K,v.property);return}}),O2=V("$ZodCheckMimeType",($,v)=>{t.init($,v);let K=new Set(v.mime);$._zod.onattach.push((_)=>{_._zod.bag.mime=v.mime}),$._zod.check=(_)=>{if(K.has(_.value.type))return;_.issues.push({code:"invalid_value",values:v.mime,input:_.value.type,inst:$,continue:!v.abort})}}),x2=V("$ZodCheckOverwrite",($,v)=>{t.init($,v),$._zod.check=(K)=>{K.value=v.tx(K.value)}});class X0{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(`
|
|
61
|
-
|
|
62
|
-
`))}}var R2={major:4,minor:3,patch:6};var C=V("$ZodType",($,v)=>{var K;$??($={}),$._zod.def=v,$._zod.bag=$._zod.bag||{},$._zod.version=R2;let _=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))_.unshift($);for(let U of _)for(let Q of U._zod.onattach)Q($);if(_.length===0)(K=$._zod).deferred??(K.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let U=(q,G,j)=>{let Y=V1(q),X;for(let P of G){if(P._zod.def.when){if(!P._zod.def.when(q))continue}else if(Y)continue;let B=q.issues.length,N=P._zod.check(q);if(N instanceof Promise&&j?.async===!1)throw new c$;if(X||N instanceof Promise)X=(X??Promise.resolve()).then(async()=>{if(await N,q.issues.length===B)return;if(!Y)Y=V1(q,B)});else{if(q.issues.length===B)continue;if(!Y)Y=V1(q,B)}}if(X)return X.then(()=>{return q});return q},Q=(q,G,j)=>{if(V1(q))return q.aborted=!0,q;let Y=U(G,_,j);if(Y instanceof Promise){if(j.async===!1)throw new c$;return Y.then((X)=>$._zod.parse(X,j))}return $._zod.parse(Y,j)};$._zod.run=(q,G)=>{if(G.skipChecks)return $._zod.parse(q,G);if(G.direction==="backward"){let Y=$._zod.parse({value:q.value,issues:[]},{...G,skipChecks:!0});if(Y instanceof Promise)return Y.then((X)=>{return Q(X,q,G)});return Q(Y,q,G)}let j=$._zod.parse(q,G);if(j instanceof Promise){if(G.async===!1)throw new c$;return j.then((Y)=>U(Y,_,G))}return U(j,_,G)}}h($,"~standard",()=>({validate:(U)=>{try{let Q=CU($,U);return Q.success?{value:Q.data}:{issues:Q.error?.issues}}catch(Q){return yU($,U).then((q)=>q.success?{value:q.data}:{issues:q.error?.issues})}},vendor:"zod",version:1}))}),g1=V("$ZodString",($,v)=>{C.init($,v),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??Q2($._zod.bag),$._zod.parse=(K,_)=>{if(v.coerce)try{K.value=String(K.value)}catch(U){}if(typeof K.value==="string")return K;return K.issues.push({expected:"string",code:"invalid_type",input:K.value,inst:$}),K}}),l=V("$ZodStringFormat",($,v)=>{q4.init($,v),g1.init($,v)}),u2=V("$ZodGUID",($,v)=>{v.pattern??(v.pattern=lU),l.init($,v)}),T2=V("$ZodUUID",($,v)=>{if(v.version){let _={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[v.version];if(_===void 0)throw Error(`Invalid UUID version: "${v.version}"`);v.pattern??(v.pattern=T1(_))}else v.pattern??(v.pattern=T1());l.init($,v)}),g2=V("$ZodEmail",($,v)=>{v.pattern??(v.pattern=oU),l.init($,v)}),E2=V("$ZodURL",($,v)=>{l.init($,v),$._zod.check=(K)=>{try{let _=K.value.trim(),U=new URL(_);if(v.hostname){if(v.hostname.lastIndex=0,!v.hostname.test(U.hostname))K.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:v.hostname.source,input:K.value,inst:$,continue:!v.abort})}if(v.protocol){if(v.protocol.lastIndex=0,!v.protocol.test(U.protocol.endsWith(":")?U.protocol.slice(0,-1):U.protocol))K.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:v.protocol.source,input:K.value,inst:$,continue:!v.abort})}if(v.normalize)K.value=U.href;else K.value=_;return}catch(_){K.issues.push({code:"invalid_format",format:"url",input:K.value,inst:$,continue:!v.abort})}}}),C2=V("$ZodEmoji",($,v)=>{v.pattern??(v.pattern=dU()),l.init($,v)}),y2=V("$ZodNanoID",($,v)=>{v.pattern??(v.pattern=iU),l.init($,v)}),f2=V("$ZodCUID",($,v)=>{v.pattern??(v.pattern=fU),l.init($,v)}),m2=V("$ZodCUID2",($,v)=>{v.pattern??(v.pattern=mU),l.init($,v)}),h2=V("$ZodULID",($,v)=>{v.pattern??(v.pattern=hU),l.init($,v)}),c2=V("$ZodXID",($,v)=>{v.pattern??(v.pattern=cU),l.init($,v)}),r2=V("$ZodKSUID",($,v)=>{v.pattern??(v.pattern=rU),l.init($,v)}),i2=V("$ZodISODateTime",($,v)=>{v.pattern??(v.pattern=_2(v)),l.init($,v)}),n2=V("$ZodISODate",($,v)=>{v.pattern??(v.pattern=U2),l.init($,v)}),l2=V("$ZodISOTime",($,v)=>{v.pattern??(v.pattern=K2(v)),l.init($,v)}),o2=V("$ZodISODuration",($,v)=>{v.pattern??(v.pattern=nU),l.init($,v)}),d2=V("$ZodIPv4",($,v)=>{v.pattern??(v.pattern=tU),l.init($,v),$._zod.bag.format="ipv4"}),t2=V("$ZodIPv6",($,v)=>{v.pattern??(v.pattern=pU),l.init($,v),$._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:!v.abort})}}}),p2=V("$ZodMAC",($,v)=>{v.pattern??(v.pattern=aU(v.delimiter)),l.init($,v),$._zod.bag.format="mac"}),a2=V("$ZodCIDRv4",($,v)=>{v.pattern??(v.pattern=eU),l.init($,v)}),e2=V("$ZodCIDRv6",($,v)=>{v.pattern??(v.pattern=sU),l.init($,v),$._zod.check=(K)=>{let _=K.value.split("/");try{if(_.length!==2)throw Error();let[U,Q]=_;if(!Q)throw Error();let q=Number(Q);if(`${q}`!==Q)throw Error();if(q<0||q>128)throw Error();new URL(`http://[${U}]`)}catch{K.issues.push({code:"invalid_format",format:"cidrv6",input:K.value,inst:$,continue:!v.abort})}}});function s2($){if($==="")return!0;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}var $9=V("$ZodBase64",($,v)=>{v.pattern??(v.pattern=$2),l.init($,v),$._zod.bag.contentEncoding="base64",$._zod.check=(K)=>{if(s2(K.value))return;K.issues.push({code:"invalid_format",format:"base64",input:K.value,inst:$,continue:!v.abort})}});function sq($){if(!j0.test($))return!1;let v=$.replace(/[-_]/g,(_)=>_==="-"?"+":"/"),K=v.padEnd(Math.ceil(v.length/4)*4,"=");return s2(K)}var v9=V("$ZodBase64URL",($,v)=>{v.pattern??(v.pattern=j0),l.init($,v),$._zod.bag.contentEncoding="base64url",$._zod.check=(K)=>{if(sq(K.value))return;K.issues.push({code:"invalid_format",format:"base64url",input:K.value,inst:$,continue:!v.abort})}}),U9=V("$ZodE164",($,v)=>{v.pattern??(v.pattern=v2),l.init($,v)});function $G($,v=null){try{let K=$.split(".");if(K.length!==3)return!1;let[_]=K;if(!_)return!1;let U=JSON.parse(atob(_));if("typ"in U&&U?.typ!=="JWT")return!1;if(!U.alg)return!1;if(v&&(!("alg"in U)||U.alg!==v))return!1;return!0}catch{return!1}}var K9=V("$ZodJWT",($,v)=>{l.init($,v),$._zod.check=(K)=>{if($G(K.value,v.alg))return;K.issues.push({code:"invalid_format",format:"jwt",input:K.value,inst:$,continue:!v.abort})}}),_9=V("$ZodCustomStringFormat",($,v)=>{l.init($,v),$._zod.check=(K)=>{if(v.fn(K.value))return;K.issues.push({code:"invalid_format",format:v.format,input:K.value,inst:$,continue:!v.abort})}}),b0=V("$ZodNumber",($,v)=>{C.init($,v),$._zod.pattern=$._zod.bag.pattern??s4,$._zod.parse=(K,_)=>{if(v.coerce)try{K.value=Number(K.value)}catch(q){}let U=K.value;if(typeof U==="number"&&!Number.isNaN(U)&&Number.isFinite(U))return K;let Q=typeof U==="number"?Number.isNaN(U)?"NaN":!Number.isFinite(U)?"Infinity":void 0:void 0;return K.issues.push({expected:"number",code:"invalid_type",input:U,inst:$,...Q?{received:Q}:{}}),K}}),Q9=V("$ZodNumberFormat",($,v)=>{P2.init($,v),b0.init($,v)}),U6=V("$ZodBoolean",($,v)=>{C.init($,v),$._zod.pattern=W2,$._zod.parse=(K,_)=>{if(v.coerce)try{K.value=Boolean(K.value)}catch(Q){}let U=K.value;if(typeof U==="boolean")return K;return K.issues.push({expected:"boolean",code:"invalid_type",input:U,inst:$}),K}}),k0=V("$ZodBigInt",($,v)=>{C.init($,v),$._zod.pattern=q2,$._zod.parse=(K,_)=>{if(v.coerce)try{K.value=BigInt(K.value)}catch(U){}if(typeof K.value==="bigint")return K;return K.issues.push({expected:"bigint",code:"invalid_type",input:K.value,inst:$}),K}}),q9=V("$ZodBigIntFormat",($,v)=>{V2.init($,v),k0.init($,v)}),G9=V("$ZodSymbol",($,v)=>{C.init($,v),$._zod.parse=(K,_)=>{let U=K.value;if(typeof U==="symbol")return K;return K.issues.push({expected:"symbol",code:"invalid_type",input:U,inst:$}),K}}),W9=V("$ZodUndefined",($,v)=>{C.init($,v),$._zod.pattern=Y2,$._zod.values=new Set([void 0]),$._zod.optin="optional",$._zod.optout="optional",$._zod.parse=(K,_)=>{let U=K.value;if(typeof U>"u")return K;return K.issues.push({expected:"undefined",code:"invalid_type",input:U,inst:$}),K}}),j9=V("$ZodNull",($,v)=>{C.init($,v),$._zod.pattern=j2,$._zod.values=new Set([null]),$._zod.parse=(K,_)=>{let U=K.value;if(U===null)return K;return K.issues.push({expected:"null",code:"invalid_type",input:U,inst:$}),K}}),Y9=V("$ZodAny",($,v)=>{C.init($,v),$._zod.parse=(K)=>K}),J9=V("$ZodUnknown",($,v)=>{C.init($,v),$._zod.parse=(K)=>K}),X9=V("$ZodNever",($,v)=>{C.init($,v),$._zod.parse=(K,_)=>{return K.issues.push({expected:"never",code:"invalid_type",input:K.value,inst:$}),K}}),H9=V("$ZodVoid",($,v)=>{C.init($,v),$._zod.parse=(K,_)=>{let U=K.value;if(typeof U>"u")return K;return K.issues.push({expected:"void",code:"invalid_type",input:U,inst:$}),K}}),P9=V("$ZodDate",($,v)=>{C.init($,v),$._zod.parse=(K,_)=>{if(v.coerce)try{K.value=new Date(K.value)}catch(G){}let U=K.value,Q=U instanceof Date;if(Q&&!Number.isNaN(U.getTime()))return K;return K.issues.push({expected:"date",code:"invalid_type",input:U,...Q?{received:"Invalid Date"}:{},inst:$}),K}});function cq($,v,K){if($.issues.length)v.issues.push(...Z$(K,$.issues));v.value[K]=$.value}var V9=V("$ZodArray",($,v)=>{C.init($,v),$._zod.parse=(K,_)=>{let U=K.value;if(!Array.isArray(U))return K.issues.push({expected:"array",code:"invalid_type",input:U,inst:$}),K;K.value=Array(U.length);let Q=[];for(let q=0;q<U.length;q++){let G=U[q],j=v.element._zod.run({value:G,issues:[]},_);if(j instanceof Promise)Q.push(j.then((Y)=>cq(Y,K,q)));else cq(j,K,q)}if(Q.length)return Promise.all(Q).then(()=>K);return K}});function D0($,v,K,_,U){if($.issues.length){if(U&&!(K in _))return;v.issues.push(...Z$(K,$.issues))}if($.value===void 0){if(K in _)v.value[K]=void 0}else v.value[K]=$.value}function vG($){let v=Object.keys($.shape);for(let _ of v)if(!$.shape?.[_]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${_}": expected a Zod schema`);let K=SU($.shape);return{...$,keys:v,keySet:new Set(v),numKeys:v.length,optionalKeys:new Set(K)}}function UG($,v,K,_,U,Q){let q=[],G=U.keySet,j=U.catchall._zod,Y=j.def.type,X=j.optout==="optional";for(let P in v){if(G.has(P))continue;if(Y==="never"){q.push(P);continue}let B=j.run({value:v[P],issues:[]},_);if(B instanceof Promise)$.push(B.then((N)=>D0(N,K,P,v,X)));else D0(B,K,P,v,X)}if(q.length)K.issues.push({code:"unrecognized_keys",keys:q,input:v,inst:Q});if(!$.length)return K;return Promise.all($).then(()=>{return K})}var KG=V("$ZodObject",($,v)=>{if(C.init($,v),!Object.getOwnPropertyDescriptor(v,"shape")?.get){let G=v.shape;Object.defineProperty(v,"shape",{get:()=>{let j={...G};return Object.defineProperty(v,"shape",{value:j}),j}})}let _=$4(()=>vG(v));h($._zod,"propValues",()=>{let G=v.shape,j={};for(let Y in G){let X=G[Y]._zod;if(X.values){j[Y]??(j[Y]=new Set);for(let P of X.values)j[Y].add(P)}}return j});let U=u1,Q=v.catchall,q;$._zod.parse=(G,j)=>{q??(q=_.value);let Y=G.value;if(!U(Y))return G.issues.push({expected:"object",code:"invalid_type",input:Y,inst:$}),G;G.value={};let X=[],P=q.shape;for(let B of q.keys){let N=P[B],S=N._zod.optout==="optional",f=N._zod.run({value:Y[B],issues:[]},j);if(f instanceof Promise)X.push(f.then((p)=>D0(p,G,B,Y,S)));else D0(f,G,B,Y,S)}if(!Q)return X.length?Promise.all(X).then(()=>G):G;return UG(X,Y,G,j,_.value,$)}}),B9=V("$ZodObjectJIT",($,v)=>{KG.init($,v);let K=$._zod.parse,_=$4(()=>vG(v)),U=(B)=>{let N=new X0(["shape","payload","ctx"]),S=_.value,f=(A$)=>{let b$=a6(A$);return`shape[${b$}]._zod.run({ value: input[${b$}], issues: [] }, ctx)`};N.write("const input = payload.value;");let p=Object.create(null),D$=0;for(let A$ of S.keys)p[A$]=`key_${D$++}`;N.write("const newResult = {};");for(let A$ of S.keys){let b$=p[A$],S$=a6(A$),Ij=B[A$]?._zod?.optout==="optional";if(N.write(`const ${b$} = ${f(A$)};`),Ij)N.write(`
|
|
63
|
-
if (${b$}.issues.length) {
|
|
64
|
-
if (${S$} in input) {
|
|
65
|
-
payload.issues = payload.issues.concat(${b$}.issues.map(iss => ({
|
|
30
|
+
Current URL: ${U||"(not set)"} (change with: niva config set url <url>)`;if(Q.includes("enotfound")||Q.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 jM($){let U=M$($);if(U==null)return` • ${String($)}`;let Q=U.path,q=Array.isArray(Q)?Q.join("."):"",K=U.messageKey??U.code??"invalid",W;if(typeof U.message==="string")W=U.message;else if(typeof K==="string")W=K;else W=JSON.stringify(K);return` ✗ ${q?`${q}: `:""}${W}`}function J6($){return $ instanceof Error&&"defined"in $&&"code"in $}function Y0($){let U=String(M$($)?.code);if(U==="NOT_FOUND"&&M$($)?.defined===!1)return YM();return{code:U,message:$.message,data:M$(M$($)?.data),hint:JM[U],exitCode:qM(U),retryable:WM(U)}}function YM(){let $=f8();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 ${u8}`:`Run: npx @sippulse/niva@${$} <command>`} (the server's NIVA version does not offer this procedure).`,exitCode:A.USAGE_ERROR,retryable:!1}}function H0($){x(`Error: ${$.code} — ${$.message}`);let U=$.data?.issues;if(Array.isArray(U))for(let Q of U)x(jM(Q));if($.hint!=null)w(` ${$.hint}`)}function HM($){if(n8==="json")P({error:$.code,message:$.message,data:$.data,hint:$.hint,retryable:$.retryable});else H0($);process.exit($.exitCode)}function i8($){return $ instanceof Error?GM($,QM):String($)}function h1($){if(J6($))HM(Y0($));let U=i8($);if(n8==="json")P({error:"CONNECTION_ERROR",message:$ instanceof Error?$.message:String($),retryable:!0});else x(U);process.exit(A.GENERAL_ERROR)}function Z4($){if(J6($))h1($);let U=$ instanceof Error?$.message:String($);if(n8==="json")P({error:"STREAM_ERROR",message:U,retryable:!0});else x(`Stream error: ${U}`);process.exit(A.GENERAL_ERROR)}async function _($){try{return await $}catch(U){h1(U)}}function d$($="Not yet implemented."){w($),process.exit(A.USAGE_ERROR)}function dW($,U){$.command("ai").description("AI module resources").command("agents").description("List AI agents available for voice interactions").action(async()=>{let{format:q,fields:K}=F($.opts()),W=await _(U().ai.listAgents());if(q==="json"){let J=K?W.map((G)=>C(G,K)):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??"—"})))})}import{readFile as MJ,writeFile as VJ}from"node:fs/promises";import{basename as DJ}from"node:path";function XM($,U){let Q=U.toLowerCase();if(Q.endsWith(".wav"))return BM($);if(Q.endsWith(".mp3"))return vM($);return}function X0($){if(!Number.isFinite($)||$<=0)return;let U=Math.round($);if(U<=0||U>86400000)return;return U}function pW($,U,Q){let q="";for(let K=0;K<Q;K+=1)q+=String.fromCharCode($[U+K]??0);return q}function G6($,U,Q){if(U+Q.length>$.byteLength)return!1;return pW($,U,Q.length)===Q}function tW($){return new DataView($.buffer,$.byteOffset,$.byteLength)}function BM($){let U=$.byteLength;if(U<12||!G6($,0,"RIFF")||!G6($,8,"WAVE"))return;let Q=tW($),q,K,W=12;while(W+8<=U){let J=pW($,W,4),G=Q.getUint32(W+4,!0),Y=W+8;if(J==="fmt "&&G>=16&&Y+16<=U){let B=Q.getUint16(Y+2,!0),M=Q.getUint32(Y+4,!0),V=Q.getUint32(Y+8,!0),L=Q.getUint16(Y+14,!0);q=V>0?V:M*B*L/8}else if(J==="data"){K=Math.min(G,U-Y);break}let H=Y+G+G%2;if(H<=W)return;W=H}if(q===void 0||q<=0||K===void 0)return;return X0(K/q*1000)}var ZM=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320,0],MM=[0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,0],VM=[44100,48000,32000,0],DM=[22050,24000,16000,0],NM=[11025,12000,8000,0];function PM($){if($===3)return VM;if($===2)return DM;return NM}function IM($,U){if($)return U?17:32;return U?9:17}function _M($,U){let Q=$[U+1],q=$[U+2],K=$[U+3];if(Q===void 0||q===void 0||K===void 0)return;let W=Q>>3&3,J=Q>>1&3;if(W===1||J!==1)return;let G=W===3,Y=(G?ZM:MM)[q>>4&15]??0,H=PM(W)[q>>2&3]??0;if(Y===0||H===0)return;let B=(K>>6&3)===3;return{bitrate:Y*1000,sampleRate:H,samplesPerFrame:G?1152:576,sideInfoSize:IM(G,B)}}function LM($,U,Q){let q=U+4+Q;if(!G6($,q,"Xing")&&!G6($,q,"Info"))return;if(q+12>$.byteLength)return;let K=tW($);if((K.getUint32(q+4,!1)&1)===0)return;let J=K.getUint32(q+8,!1);return J>0?J:void 0}function FM($){if(!G6($,0,"ID3")||$.byteLength<10)return 0;let U=$[5]??0,Q=0;for(let K=6;K<=9;K+=1)Q=Q<<7|($[K]??0)&127;let q=(U&16)!==0?10:0;return 10+Q+q}function vM($){let U=$.byteLength,Q=FM($);for(let q=Q;q+4<=U;q+=1){if($[q]!==255||(($[q+1]??0)&224)!==224)continue;let K=_M($,q);if(K===void 0)continue;let W=LM($,q,K.sideInfoSize);if(W!==void 0)return X0(W*K.samplesPerFrame*1000/K.sampleRate);return X0((U-q)*8*1000/K.bitrate)}return}async function zM($,U){let Q=[U,"-v","error","-show_entries","format=duration","-of","csv=p=0",$],q;try{q=Bun.spawn(Q,{stdout:"pipe",stderr:"ignore"})}catch{return}let K=kM(q).catch(()=>{return}),W,J=new Promise((G)=>{W=setTimeout(()=>{q.kill(),setTimeout(()=>q.kill("SIGKILL"),250).unref(),G(void 0)},3000)});try{let G=await Promise.race([K,J]);if(G?.exitCode!==0)return;return X0(Number(G.stdout.trim())*1000)}finally{if(W!==void 0)clearTimeout(W)}}async function kM($){let[U,Q]=await Promise.all([new Response($.stdout).text(),$.exited]);return{stdout:U,exitCode:Q}}async function aW($){let U=XM($.bytes,$.filePath);if(U!==void 0)return{durationMs:U,source:"header"};if($.noProbe===!0)return{source:"none"};let Q=await zM($.filePath,$.ffprobePath??"ffprobe");if(Q!==void 0)return{durationMs:Q,source:"ffprobe"};return{source:"none"}}import{createInterface as $J}from"node:readline/promises";function UJ(){return process.stdin.isTTY===!0}var sW=5;async function eW($,U,Q){let q=$[U].value;for(let K=0;K<sW;K++){let W=(await Q(`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 ${sW} attempts — using the default.`),q}async function KJ($,U,Q={}){let q=Q.defaultIndex??0;console.log($);for(let[W,J]of U.entries())console.log(` ${W+1}) ${J.label}`);if(console.log(""),Q.ask!=null)return eW(U,q,Q.ask);let K=$J({input:process.stdin,output:process.stdout});try{return await eW(U,q,async(W)=>K.question(W))}finally{K.close()}}async function I1($,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(A.USAGE_ERROR);let Q=$J({input:process.stdin,output:process.stdout});try{let q=await Q.question(`${$} [y/N] `);if(!/^y(?:es)?$/i.test(q.trim()))x("Aborted."),process.exit(A.USAGE_ERROR)}finally{Q.close()}}var QJ=/^(?:[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 wM($){return typeof $==="string"&&QJ.test($)}var qJ=wM;var D$=[];for(let $=0;$<256;++$)D$.push(($+256).toString(16).slice(1));function o8($,U=0){return(D$[$[U+0]]+D$[$[U+1]]+D$[$[U+2]]+D$[$[U+3]]+"-"+D$[$[U+4]]+D$[$[U+5]]+"-"+D$[$[U+6]]+D$[$[U+7]]+"-"+D$[$[U+8]]+D$[$[U+9]]+"-"+D$[$[U+10]]+D$[$[U+11]]+D$[$[U+12]]+D$[$[U+13]]+D$[$[U+14]]+D$[$[U+15]]).toLowerCase()}function xM($,U=0){let Q=o8($,U);if(!qJ(Q))throw TypeError("Stringified UUID is invalid");return Q}var B0=xM;var AM=new Uint8Array(16);function Z0(){return crypto.getRandomValues(AM)}var d8={};function bM($,U,Q){let q;if($)q=WJ($.random??$.rng?.()??Z0(),$.msecs,$.seq,U,Q);else{let K=Date.now(),W=Z0();OM(d8,K,W),q=WJ(W,d8.msecs,d8.seq,U,Q)}return U??o8(q)}function OM($,U,Q){if($.msecs??=-1/0,$.seq??=0,U>$.msecs)$.seq=Q[6]<<23|Q[7]<<16|Q[8]<<8|Q[9],$.msecs=U;else if($.seq=$.seq+1|0,$.seq===0)$.msecs++;return $}function WJ($,U,Q,q,K=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!q)q=new Uint8Array(16),K=0;else if(K<0||K+16>q.length)throw RangeError(`UUID byte range ${K}:${K+15} is out of buffer bounds`);return U??=Date.now(),Q??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],q[K++]=U/1099511627776&255,q[K++]=U/4294967296&255,q[K++]=U/16777216&255,q[K++]=U/65536&255,q[K++]=U/256&255,q[K++]=U&255,q[K++]=112|Q>>>28&15,q[K++]=Q>>>20&255,q[K++]=128|Q>>>14&63,q[K++]=Q>>>6&255,q[K++]=Q<<2&255|$[10]&3,q[K++]=$[11],q[K++]=$[12],q[K++]=$[13],q[K++]=$[14],q[K++]=$[15],q}var p8=bM;function RM($){let U,Q=new Uint8Array(16);return Q[0]=(U=parseInt($.slice(0,8),16))>>>24,Q[1]=U>>>16&255,Q[2]=U>>>8&255,Q[3]=U&255,Q[4]=(U=parseInt($.slice(9,13),16))>>>8,Q[5]=U&255,Q[6]=(U=parseInt($.slice(14,18),16))>>>8,Q[7]=U&255,Q[8]=(U=parseInt($.slice(19,23),16))>>>8,Q[9]=U&255,Q[10]=(U=parseInt($.slice(24,36),16))/1099511627776&255,Q[11]=U/4294967296&255,Q[12]=U>>>24&255,Q[13]=U>>>16&255,Q[14]=U>>>8&255,Q[15]=U&255,Q}var K$="0123456789abcdefghjkmnpqrstvwxyz",S=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 t8($){let U=Array(26).fill("");if($.length!==16)throw Error(`Invalid length. Expected 16 bytes, got ${$.length}. Input: ${$}`);return U[0]=K$[($[0]&224)>>5],U[1]=K$[$[0]&31],U[2]=K$[($[1]&248)>>3],U[3]=K$[($[1]&7)<<2|($[2]&192)>>6],U[4]=K$[($[2]&62)>>1],U[5]=K$[($[2]&1)<<4|($[3]&240)>>4],U[6]=K$[($[3]&15)<<1|($[4]&128)>>7],U[7]=K$[($[4]&124)>>2],U[8]=K$[($[4]&3)<<3|($[5]&224)>>5],U[9]=K$[$[5]&31],U[10]=K$[($[6]&248)>>3],U[11]=K$[($[6]&7)<<2|($[7]&192)>>6],U[12]=K$[($[7]&62)>>1],U[13]=K$[($[7]&1)<<4|($[8]&240)>>4],U[14]=K$[($[8]&15)<<1|($[9]&128)>>7],U[15]=K$[($[9]&124)>>2],U[16]=K$[($[9]&3)<<3|($[10]&224)>>5],U[17]=K$[$[10]&31],U[18]=K$[($[11]&248)>>3],U[19]=K$[($[11]&7)<<2|($[12]&192)>>6],U[20]=K$[($[12]&62)>>1],U[21]=K$[($[12]&1)<<4|($[13]&240)>>4],U[22]=K$[($[13]&15)<<1|($[14]&128)>>7],U[23]=K$[($[14]&124)>>2],U[24]=K$[($[14]&3)<<3|($[15]&224)>>5],U[25]=K$[$[15]&31],U.join("")}function jJ($){if($.length!==26)throw Error(`Invalid length. Expected 26 bytes, got ${$.length}. Input: ${$}`);let Q=new TextEncoder().encode($);if(S[Q[0]]===255||S[Q[1]]===255||S[Q[2]]===255||S[Q[3]]===255||S[Q[4]]===255||S[Q[5]]===255||S[Q[6]]===255||S[Q[7]]===255||S[Q[8]]===255||S[Q[9]]===255||S[Q[10]]===255||S[Q[11]]===255||S[Q[12]]===255||S[Q[13]]===255||S[Q[14]]===255||S[Q[15]]===255||S[Q[16]]===255||S[Q[17]]===255||S[Q[18]]===255||S[Q[19]]===255||S[Q[20]]===255||S[Q[21]]===255||S[Q[22]]===255||S[Q[23]]===255||S[Q[24]]===255||S[Q[25]]===255)throw Error("Invalid base32 character");let q=new Uint8Array(16);return q[0]=S[Q[0]]<<5|S[Q[1]],q[1]=S[Q[2]]<<3|S[Q[3]]>>2,q[2]=(S[Q[3]]&3)<<6|S[Q[4]]<<1|S[Q[5]]>>4,q[3]=(S[Q[5]]&15)<<4|S[Q[6]]>>1,q[4]=(S[Q[6]]&1)<<7|S[Q[7]]<<2|S[Q[8]]>>3,q[5]=(S[Q[8]]&7)<<5|S[Q[9]],q[6]=S[Q[10]]<<3|S[Q[11]]>>2,q[7]=(S[Q[11]]&3)<<6|S[Q[12]]<<1|S[Q[13]]>>4,q[8]=(S[Q[13]]&15)<<4|S[Q[14]]>>1,q[9]=(S[Q[14]]&1)<<7|S[Q[15]]<<2|S[Q[16]]>>3,q[10]=(S[Q[16]]&7)<<5|S[Q[17]],q[11]=S[Q[18]]<<3|S[Q[19]]>>2,q[12]=(S[Q[19]]&3)<<6|S[Q[20]]<<1|S[Q[21]]>>4,q[13]=(S[Q[21]]&15)<<4|S[Q[22]]>>1,q[14]=(S[Q[22]]&1)<<7|S[Q[23]]<<2|S[Q[24]]>>3,q[15]=(S[Q[24]]&7)<<5|S[Q[25]],q}function TM($){if($.length>63)return!1;let U,Q,q;for(Q=0,q=$.length;Q<q;Q+=1){U=$.charCodeAt(Q);let K=U>96&&U<123,W=U===95;if((Q===0||Q===q-1)&&!K)return!1;if(!(K||W))return!1}return!0}var SM=class extends Error{constructor($){super(`Invalid prefix "${$}". Must be at most 63 ASCII letters [a-z_]`);this.name="InvalidPrefixError"}},CM=class extends Error{constructor($,U){super(`Invalid TypeId. Prefix mismatch. Expected ${$}, got ${U}`);this.name="PrefixMismatchError"}},EM=class extends Error{constructor($){super(`Invalid TypeId. Prefix cannot be empty when there's a separator: ${$}`);this.name="EmptyPrefixError"}},YJ=class extends Error{constructor($){super(`Invalid length. Suffix should have 26 characters, got ${$}`);this.name="InvalidSuffixLengthError"}},gM=class extends Error{constructor($){super(`Invalid suffix. First character "${$}" must be in the range [0-7]`);this.name="InvalidSuffixCharacterError"}},yM=class extends Error{constructor($,U){super(`Cannot convert TypeID of type ${$} to type ${U}`);this.name="TypeIDConversionError"}};function HJ($="",U=""){if(!TM($))throw new SM($);let Q;if(U)Q=U;else{let q=new Uint8Array(16);p8(void 0,q),Q=t8(q)}if(Q.length!==26)throw new YJ(Q.length);if(Q[0]>"7")throw new gM(Q[0]);if(jJ(Q),$==="")return Q;else return`${$}_${Q}`}function uM($,U){let Q,q,K=$.lastIndexOf("_");if(K===-1)Q="",q=$;else if(Q=$.substring(0,K),q=$.substring(K+1),!Q)throw new EM($);if(!q)throw new YJ(0);if(U&&Q!==U)throw new CM(U,Q);return HJ(Q,q)}function JJ($){let U=$.lastIndexOf("_");if(U===-1)return"";return $.substring(0,U)}function GJ($){let U=$.lastIndexOf("_");if(U===-1)return $;return $.substring(U+1)}var M4=class{constructor($,U=""){this.prefix=$,this.suffix=U;let Q=HJ($,U);this.prefix=JJ(Q),this.suffix=GJ(Q)}getType(){return this.prefix}getSuffix(){return this.suffix}asType($){let U=this;if(U.prefix!==$)throw new yM(U.prefix,$);return U}toUUIDBytes(){return jJ(this.suffix)}toUUID(){return B0(this.toUUIDBytes())}toString(){if(this.prefix==="")return this.suffix;return`${this.prefix}_${this.suffix}`}static fromString($,U){let Q=uM($,U);return new M4(JJ(Q),GJ(Q))}static fromUUIDBytes($,U){let Q=t8(U);return new M4($,Q)}static fromUUID($,U){let Q=t8(RM(U));return new M4($,Q)}};var m={acl_rules:"acl",organizations:"org",users:"usr",org_memberships:"mem",visual_plans:"vp",visual_plan_versions:"vpv",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",notification_channels:"nchan",dialer_campaigns:"dcamp",dialer_contacts:"dct",dialer_attempts:"datt",dialer_dnc:"dnc",dialer_import_jobs:"dimp",org_secrets:"sec",oauth_clients:"oac",oauth_grants:"oag",signals:"sig",signal_versions:"sigv",call_signals:"csig",call_signal_timelines:"cstl"};function M0($,U){return M4.fromUUID(m[$],U).toString()}var fM=new Map(Object.keys(m).map(($)=>[m[$],$]));function j6($){return fM.get($)}var hM=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function m1($){if(hM.test($))return{kind:"uuid",uuid:$};let U=$.lastIndexOf("_");if(U<=0||U===$.length-1)return{kind:"invalid",reason:"not-an-id"};let Q=$.slice(0,U),q=j6(Q);if(q===void 0)return{kind:"invalid",reason:"unknown-prefix"};try{return{kind:"typeid",entity:q,prefix:Q,uuid:M4.fromString($,Q).toUUID()}}catch{return{kind:"invalid",reason:"malformed-suffix"}}}function p$($){return $}function mM($){return`a ${m[$]}_... TypeID for ${$}, or the raw UUID of that row`}function XJ($,U,Q){x(`Invalid id "${U}": ${Q}`),w(` Expected ${mM($)}.`),w(" Convert between the two forms with: niva id <value> [--as <entity>]"),process.exit(A.USAGE_ERROR)}function cM($){let U=$.lastIndexOf("_");return U>0?$.slice(0,U):""}function BJ($,U){let Q=m1(U);if(Q.kind==="uuid")return M0($,Q.uuid);let q=j6(cM(U));if(q===$)return U;if(q!==void 0)XJ($,U,`it is a ${q} id`);XJ($,U,"it is neither a UUID nor an id of a known entity")}function b($,U){let Q;if(Array.isArray(U))Q=U.map((q)=>BJ($,q));else if(U!==void 0)Q=BJ($,U);return Q}import{Buffer as lM}from"node:buffer";async function G1(){return new Promise(($,U)=>{let Q=[];process.stdin.on("data",(q)=>Q.push(q)),process.stdin.on("end",()=>$(lM.concat(Q).toString("utf-8"))),process.stdin.on("error",U)})}var rM=10,nM=new Set(["UNAUTHORIZED","FORBIDDEN","API_KEY_INVALID","ADMIN_REQUIRED","INSUFFICIENT_SCOPE"]);function NJ($,U){let Q=$.command("audio-files").description("Audio file library");Q.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:K,fields:W}=F($.opts()),J=await _(U().audioFiles.list({page:Number(q.page),limit:Number(q.limit),search:q.search}));if(K==="json"){let G=W?J.items.map((Y)=>C(Y,W)):J;P(G);return}y(["ID","Name","Type","Duration"],J.items.map((G)=>({ID:G.id,Name:G.name,Type:G.type,Duration:PJ(G.duration_ms)}))),j$(J)}),Q.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,K)=>{let{format:W}=F($.opts()),J=$.opts().yes===!0;if(K.name!=null&&q.length>1)x("--name names a single audio file; drop it when uploading several at once."),process.exit(A.USAGE_ERROR);if(K.durationMs!=null&&q.length>1)x("--duration-ms describes a single audio file; drop it when uploading several at once."),process.exit(A.USAGE_ERROR);let G=oM(K.durationMs);if(q.length>rM)await I1(`Upload ${q.length} audio files to the library?`,{yes:J});let Y=[],H=A.SUCCESS;for(let B of q){let M=await dM(U(),B,{format:W,overrideMs:G,noProbe:K.probe===!1,...K.name!=null&&{name:K.name}});if(Y.push(M),M.exitCode>H)H=M.exitCode;if(M.abort)break}if(eM(Y,W),H!==A.SUCCESS)process.exit(H)}),Q.command("show <audio_file_id>").description("Show an audio file's metadata").action(async(q)=>{let{format:K,fields:W}=F($.opts()),J=await _(U().audioFiles.getById({audio_file_id:b("audio_files",q)}));if(J==null)x("Audio file not found"),process.exit(A.NOT_FOUND);if(K==="json"){P(W?C(J,W):J);return}t(V0(J))}),Q.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,K)=>{let{format:W}=F($.opts()),J=$.opts(),G=J.json===!0||J.output==="json";if(K.out==="-"&&G)x("--out - streams binary audio to stdout and cannot be combined with --json."),process.exit(A.USAGE_ERROR);let Y=U(),H=await _(Y.audioFiles.content({audio_file_id:b("audio_files",q)})),B=new Uint8Array(await H.arrayBuffer());if(K.out==="-"){process.stdout.write(B);return}let M;if(K.out!=null)M=K.out,await VJ(M,B);else M=await aM(Y,q,H.name),await sM(M,B,K.force===!0);if(W==="json"){P({path:M,bytes:B.length});return}E(`Saved ${M} (${B.length} bytes)`)}),Q.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,K)=>{let{format:W}=F($.opts());if(K.name==null&&K.description==null)x("Nothing to update — pass --name and/or --description."),process.exit(A.USAGE_ERROR);let J=await _(U().audioFiles.update({audio_file_id:b("audio_files",q),...K.name!=null&&{name:K.name},...K.description!=null&&{description:K.description}}));if(W==="json"){P(J);return}E(`Audio file updated: ${J.name}`),t(V0(J))}),Q.command("delete <audio_file_id>").description("Delete an audio file from the library").action(async(q)=>{let{format:K}=F($.opts()),W=$.opts().yes===!0;await I1(`Delete audio file ${q}?`,{yes:W});try{await U().audioFiles.delete({audio_file_id:b("audio_files",q)})}catch(J){$V(J,K)}if(K==="json"){P({id:q,deleted:!0});return}E(`Audio file deleted: ${q}`)}),Q.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:K}=F($.opts()),W=await ZJ(q),J=await _(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(K==="json"){P(J);return}E(`TTS audio generated: ${J.id}`),t(V0(J))}),Q.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,K)=>{let{format:W}=F($.opts()),J=$.opts().yes===!0,G=await ZJ(K);await I1(`Overwrite the audio content of ${q}?`,{yes:J});let Y=await _(U().audioFiles.regenerateTts({audio_file_id:b("audio_files",q),text:G,...K.voice!=null&&{voice:K.voice},...K.model!=null&&{model:K.model}}));if(W==="json"){P(Y);return}E(`TTS audio regenerated: ${Y.id}`),t(V0(Y))})}var iM="FILE_UNREADABLE";function PJ($){if($==null)return"—";if($<60000)return`${($/1000).toFixed(1)}s`;return C$($)}function oM($){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(A.USAGE_ERROR);return U}async function dM($,U,Q){let q;try{q=await MJ(U)}catch(W){let J=W instanceof Error?W.message:String(W);if(Q.format!=="json")x(`Cannot read ${U}: ${J}`);return{file:U,ok:!1,id:void 0,durationSource:"none",error:iM,message:J,exitCode:A.USAGE_ERROR,abort:!1}}let K=await pM(U,q,Q);try{let W=await $.audioFiles.upload({file:new File([q],DJ(U)),...Q.name!=null&&{name:Q.name},...K.durationMs!=null&&{duration_ms:K.durationMs}});return{file:U,ok:!0,id:W.id,durationSource:K.source,error:void 0,message:void 0,exitCode:A.SUCCESS,abort:!1}}catch(W){return tM(W,U,K.source,Q.format)}}async function pM($,U,Q){if(Q.overrideMs!=null)return{durationMs:Q.overrideMs,source:"flag"};let q=process.env.NIVA_FFPROBE,K=await aW({filePath:$,bytes:U,noProbe:Q.noProbe,...q!=null&&q!==""&&{ffprobePath:q}});if(K.source==="none"&&Q.format!=="json")w(`duration unknown for ${$} — install ffmpeg or pass --duration-ms`);return K}function tM($,U,Q,q){let K={file:U,ok:!1,id:void 0,durationSource:Q};if(!J6($)){let J=i8($);if(q!=="json")x(J);return{...K,error:"CONNECTION_ERROR",message:J,exitCode:A.GENERAL_ERROR,abort:!0}}let W=Y0($);if(q!=="json")H0(W);return{...K,error:W.code,message:W.message,exitCode:W.exitCode,abort:nM.has(W.code)}}async function aM($,U,Q){let K=[(await _($.audioFiles.getById({audio_file_id:b("audio_files",U)})))?.filename,Q,U];return DJ(K.find((W)=>W!=null&&W!=="")??U)}async function sM($,U,Q){try{await VJ($,U,Q?{}:{flag:"wx"})}catch(q){if(M$(q)?.code!=="EEXIST")throw q;x(`${$} already exists — pass --out <path> to write elsewhere, or --force to overwrite it.`),process.exit(A.CONFLICT)}}function eM($,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 Q=$.filter((q)=>!q.ok).length;E(`${$.length-Q} uploaded, ${Q} failed`)}function $V($,U){if(!J6($))h1($);let Q=Y0($),q=UV(Q);if(q==null)h1($);if(U==="json")P({error:Q.code,message:Q.message,plans:q,hint:Q.hint,retryable:Q.retryable});else H0(Q),w(` Referenced by: ${q.join(", ")}`);process.exit(Q.exitCode)}function UV($){if($.code!=="AUDIO_FILE_IN_USE")return;let U=$.data?.plans;if(!Array.isArray(U))return;return U.map(String)}async function ZJ($){if($.text!=null&&$.textFile!=null)x("--text and --text-file are mutually exclusive."),process.exit(A.USAGE_ERROR);if($.text!=null)return $.text;if($.textFile==null)x("No text to synthesize — pass --text <text> or --text-file <path|->."),process.exit(A.USAGE_ERROR);let Q=($.textFile==="-"?await G1():await MJ($.textFile,"utf-8")).trim();if(Q==="")x(`No text to synthesize: ${$.textFile==="-"?"stdin":$.textFile} is empty.`),process.exit(A.USAGE_ERROR);return Q}function V0($){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:PJ($.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 IJ($){return $[0]??{}}function l1($){return Array.isArray($)?$:$===void 0||$===null?[]:[$]}var a8="orpc",KV="@orpc/shared",QV="1.15.0";class s8 extends Error{constructor(...$){super(...$);this.name="AbortError"}}function D0($){let U;return()=>{if(U)return U.result;let Q=$();return U={result:Q},Q}}function qV($){let U=Promise.resolve();return(...Q)=>{return U=U.catch(()=>{}).then(()=>{return $(...Q)})}}var WV=2,JV=`__${KV}@${QV}/otel/config__`;function Y6(){return globalThis[JV]}function N0($,U={},Q){return Y6()?.tracer?.startSpan($,U,Q)}function _1($,U,Q={}){if(!$)return;let q=GV(U);if($.recordException(q),!Q.signal?.aborted||Q.signal.reason!==U)$.setStatus({code:WV,message:q.message})}function GV($){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 r1({name:$,context:U,...Q},q){let K=Y6()?.tracer;if(!K)return q();let W=async(J)=>{try{return await q(J)}catch(G){throw _1(J,G,Q),G}finally{J.end()}};if(U)return K.startActiveSpan($,Q,U,W);else return K.startActiveSpan($,Q,W)}async function c1($,U){let Q=Y6();if(!$||!Q)return U();let q=Q.trace.setSpan(Q.context.active(),$);return Q.context.with(q,U)}function j1($){if(!$||typeof $!=="object")return!1;return"next"in $&&typeof $.next==="function"&&Symbol.asyncIterator in $&&typeof $[Symbol.asyncIterator]==="function"}var jV=Symbol.for("asyncDispose"),YV=Symbol.asyncDispose??jV;class L1{#$=!1;#U=!1;#K;#Q;constructor($,U){this.#K=U,this.#Q=qV(async()=>{if(this.#$)return{done:!0,value:void 0};try{let Q=await $();if(Q.done)this.#$=!0;return Q}catch(Q){throw this.#$=!0,Q}finally{if(this.#$&&!this.#U)this.#U=!0,await this.#K("next")}})}next(){return this.#Q()}async return($){if(this.#$=!0,!this.#U)this.#U=!0,await this.#K("return");return{done:!0,value:$}}async throw($){if(this.#$=!0,!this.#U)this.#U=!0,await this.#K("throw");throw $}async[YV](){if(this.#$=!0,!this.#U)this.#U=!0,await this.#K("dispose")}[Symbol.asyncIterator](){return this}}function e8({name:$,...U},Q){let q;return new L1(async()=>{q??=N0($);try{let K=await c1(q,()=>Q.next());return q?.addEvent(K.done?"completed":"yielded"),K}catch(K){throw _1(q,K,U),K}},async(K)=>{try{if(K!=="next")await c1(q,()=>Q.return?.())}catch(W){throw _1(q,W,U),W}finally{q?.end()}})}class HV{#$=new Map;#U;constructor($={}){this.#U=$.maxBufferedEvents??100}get size(){return this.#$.size}publish($,U){let Q=this.#$.get($);if(!Q)return;for(let q of Q)q(U)}subscribe($,U){if(typeof U==="function"){let Y=this.#$.get($);if(!Y)this.#$.set($,Y=[]);return Y.push(U),D0(()=>{if(Y.splice(Y.indexOf(U),1),Y.length===0)this.#$.delete($)})}let Q=U?.signal,q=U?.maxBufferedEvents??this.#U;Q?.throwIfAborted();let K=[],W=[],J=this.subscribe($,(Y)=>{let H=W.shift();if(H)H[0]({done:!1,value:Y});else if(K.push(Y),K.length>q)K.shift()}),G=(Y)=>{J(),W.forEach((H)=>H[1](Y.target.reason)),W.length=0,K.length=0};return Q?.addEventListener("abort",G,{once:!0}),new L1(async()=>{if(Q?.aborted)throw Q.reason;if(K.length>0)return{done:!1,value:K.shift()};return new Promise((Y,H)=>{W.push([Y,H])})},async()=>{J(),Q?.removeEventListener("abort",G),W.forEach((Y)=>Y[0]({done:!0,value:void 0})),W.length=0,K.length=0})}}class XV{index=BigInt(1);generate(){let $=this.index.toString(36);return this.index++,$}}function H6($,U,Q){let q=(K,W)=>{let J=$[W];if(!J)return Q(K);return J({...K,next:(G=K)=>q(G,W+1)})};return q(U,0)}function X6($){if(!$)return;return JSON.parse($)}function n1($){return JSON.stringify($)}function _J($){if(!s$($))return null;return Object.getPrototypeOf($)?.constructor}function P0($){if(!$||typeof $!=="object")return!1;let U=Object.getPrototypeOf($);return U===Object.prototype||!U||!U.constructor}function s$($){return!!$&&(typeof $==="object"||typeof $==="function")}function B6($,...U){if(typeof $==="function")return $(...U);return $}function $U($){return new Proxy($,{get(U,Q,q){let K=Reflect.get(U,Q,q);if(Q!=="then"||typeof K!=="function")return K;return new Proxy(K,{apply(W,J,G){if(G.length!==2||G.some((H)=>!ZV(H)))return Reflect.apply(W,J,G);let Y=!0;G[0].call(J,$U(new Proxy(U,{get:(H,B,M)=>{if(Y&&B==="then"){Y=!1;return}return Reflect.get(H,B,M)}})))}})}})}var BV=/^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;function ZV($){return typeof $==="function"&&BV.test($.toString())}function LJ($){try{return decodeURIComponent($)}catch{return $}}var MV="@orpc/client",VV="1.15.0",FJ=new Set(["bind","valueOf","toString","toJSON"]),_0={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 DV($,U){return U??_0[$]?.status??500}function NV($,U){return U||_0[$]?.message||$}var I0;class i1 extends Error{defined;code;status;data;static{let $=Symbol.for(`__${MV}@${VV}/error/ORPC_ERROR_CONSTRUCTORS__`);globalThis[$]??=new WeakSet,I0=globalThis[$],I0.add(i1)}constructor($,...U){let Q=IJ(U);if(Q.status!==void 0&&!L0(Q.status))throw Error("[ORPCError] Invalid error status code.");let q=NV($,Q.message);super(q,Q);this.code=$,this.status=DV($,Q.status),this.defined=Q.defined??!1,this.data=Q.data}toJSON(){return{defined:this.defined,code:this.code,status:this.status,message:this.message,data:this.data}}static[Symbol.hasInstance]($){if(I0.has(this)){let U=_J($);if(U&&I0.has(U))return!0}return super[Symbol.hasInstance]($)}}function vJ($){return $ instanceof i1?$:new i1("INTERNAL_SERVER_ERROR",{message:"Internal server error",cause:$})}function L0($){return $<200||$>=400}function UU($){if(!P0($))return!1;let U=["defined","code","status","message","data"];if(Object.keys($).some((Q)=>!U.includes(Q)))return!1;return"defined"in $&&typeof $.defined==="boolean"&&"code"in $&&typeof $.code==="string"&&"status"in $&&typeof $.status==="number"&&L0($.status)&&"message"in $&&typeof $.message==="string"}function KU($,U={}){return new i1($.code,{...U,...$})}class Z6 extends TypeError{}class zJ extends TypeError{}class Y1 extends Error{data;constructor($){super($?.message??"An error event was received",$);this.data=$?.data}}var PV=/\r\n|\r(?!\n)|\n/,IV=/(?:\r\n|\r(?!\n)|\n){2}/,_V=/(?:\r\n|\r(?!\n)|\n){2}/g,LV=13,FV=10,vV=32;function zV($){let U={data:void 0,event:void 0,id:void 0,retry:void 0,comments:[]};for(let Q of $.split(PV)){if(Q==="")continue;let q=Q.indexOf(":"),K=q===-1?"":Q.slice(Q.charCodeAt(q+1)===vV?q+2:q+1);if(q===0){U.comments.push(K);continue}switch(q===-1?Q:Q.slice(0,q)){case"data":U.data=U.data===void 0?K:`${U.data}
|
|
32
|
+
${K}`;break;case"event":U.event=K;break;case"id":U.id=K;break;case"retry":{let W=Number.parseInt(K,10);if(W>=0&&W.toString()===K)U.retry=W;break}}}return U}class kJ{constructor($={}){this.options=$}pending=[];tail="";discardLeadingLF=!1;feed($){if($==="")return;if(this.discardLeadingLF){if(this.discardLeadingLF=!1,$.charCodeAt(0)===FV){if($=$.slice(1),$==="")return}}let U=this.tail+$;if(!IV.test(U)){this.pending.push($),this.tail=U.slice(-3);return}this.pending.push($);let Q=this.pending.length===1?$:this.pending.join(""),q=Q.length-U.length,K=[],W=0;for(let G of U.matchAll(_V))K.push(Q.slice(W,q+G.index)),W=q+G.index+G[0].length;let J=Q.slice(W);if(this.pending.length=0,this.tail=J.slice(-3),J==="")this.discardLeadingLF=$.charCodeAt($.length-1)===LV;else this.pending.push(J);for(let G of K){let Y=zV(G);if(this.options.onEvent)this.options.onEvent(Y)}}end(){if(this.pending.length!==0)throw new zJ("Event Iterator ended before complete")}}class QU extends TransformStream{constructor(){let $;super({start(U){$=new kJ({onEvent:(Q)=>{U.enqueue(Q)}})},transform(U){$.feed(U)},flush(){$.end()}})}}var kV=/\r\n|[\n\r]/,wV=/\r\n|[\n\r]/g;function qU($){return kV.test($)}function wJ($){if(qU($))throw new Z6("Event's id must not contain a carriage return or newline character")}function xV($){if(qU($))throw new Z6("Event's event must not contain a carriage return or newline character")}function xJ($){if(!Number.isInteger($)||$<0)throw new Z6("Event's retry must be a integer and >= 0")}function AJ($){if(qU($))throw new Z6("Event's comment must not contain a carriage return or newline character")}function AV($){if($===void 0)return"";return`data: ${$.replace(wV,`
|
|
33
|
+
data: `)}
|
|
34
|
+
`}function bV($){let U="";for(let Q of $??[])AJ(Q),U+=`: ${Q}
|
|
35
|
+
`;return U}function M6($){let U="";if(U+=bV($.comments),$.event!==void 0)xV($.event),U+=`event: ${$.event}
|
|
36
|
+
`;if($.retry!==void 0)xJ($.retry),U+=`retry: ${$.retry}
|
|
37
|
+
`;if($.id!==void 0)wJ($.id),U+=`id: ${$.id}
|
|
38
|
+
`;return U+=AV($.data),U+=`
|
|
39
|
+
`,U}var bJ=Symbol("ORPC_EVENT_SOURCE_META");function o1($,U){if(U.id===void 0&&U.retry===void 0&&!U.comments?.length)return $;if(U.id!==void 0)wJ(U.id);if(U.retry!==void 0)xJ(U.retry);if(U.comments!==void 0)for(let Q of U.comments)AJ(Q);return new Proxy($,{get(Q,q,K){if(q===bJ)return U;return Reflect.get(Q,q,K)}})}function V4($){return s$($)?Reflect.get($,bJ):void 0}function OJ($,U="inline"){let Q=$.replace(/[^\x20-\x7E]/g,"_").replace(/"/g,"\\\""),q=encodeURIComponent($).replace(/['()*]/g,(K)=>`%${K.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(7C|60|5E)/g,(K,W)=>String.fromCharCode(Number.parseInt(W,16)));return`${U}; filename="${Q}"; filename*=utf-8''${q}`}function RJ($){let U=$.match(/filename\*=(UTF-8'')?([^;]*)/i);if(U&&typeof U[2]==="string")return LJ(U[2]);let Q=$.match(/filename="((?:\\"|[^"])*)"/i);if(Q&&typeof Q[1]==="string")return Q[1].replace(/\\"/g,'"')}function TJ($,U){let Q={...$};for(let q in U)if(Array.isArray(U[q]))Q[q]=[...l1(Q[q]),...U[q]];else if(U[q]!==void 0)if(Array.isArray(Q[q]))Q[q]=[...Q[q],U[q]];else if(Q[q]!==void 0)Q[q]=[Q[q],U[q]];else Q[q]=U[q];return Q}function WU($,U){let Q=async(q)=>{let K=await U.error(q);if(K!==q){let W=V4(q);if(W&&s$(K))K=o1(K,W)}return K};return new L1(async()=>{let{done:q,value:K}=await(async()=>{try{return await $.next()}catch(J){throw await Q(J)}})(),W=await U.value(K,q);if(W!==K){let J=V4(K);if(J&&s$(W))W=o1(W,J)}return{done:q,value:W}},async()=>{try{await $.return?.()}catch(q){throw await Q(q)}})}function OV($){return{...$,context:$.context??{}}}function F1($,U){return(async()=>{let Q;try{let q=await $;while(!0){let{done:K,value:W}=await q.next();if(K){let J=W;Q=[null,J,!0],U.onSuccess?.(J);break}U.onEvent(W)}}catch(q){if(Q=[q,void 0,!1],!U.onError&&!U.onFinish)throw q;U.onError?.(q)}finally{U.onFinish?.(Q)}})(),async()=>{await(await $)?.return?.()}}function d1($,U={}){let Q=U.path??[],K=new Proxy(async(...[W,J={}])=>{return await $.call(Q,W,OV(J))},{get(W,J){if(typeof J!=="string"||FJ.has(J))return Reflect.get(W,J);return d1($,{...U,path:[...Q,J]})}});return $U(K)}function RV($,U={}){let q=$?.pipeThrough(new TextDecoderStream).pipeThrough(new QU)?.getReader(),K,W=!1;return new L1(async()=>{K??=N0("consume_event_iterator_stream");try{while(!0){if(q===void 0)return{done:!0,value:void 0};let{done:J,value:G}=await c1(K,()=>q.read());if(J){if(W)throw new s8("Stream was cancelled");return{done:!0,value:void 0}}switch(G.event){case"message":{let Y=X6(G.data);if(s$(Y))Y=o1(Y,G);return K?.addEvent("message"),{done:!1,value:Y}}case"error":{let Y=new Y1({data:X6(G.data)});throw Y=o1(Y,G),K?.addEvent("error"),Y}case"done":{let Y=X6(G.data);if(s$(Y))Y=o1(Y,G);return K?.addEvent("done"),{done:!0,value:Y}}default:K?.addEvent("maybe_keepalive")}}}catch(J){if(!(J instanceof Y1))_1(K,J,U);throw J}},async(J)=>{try{if(J!=="next")W=!0,K?.addEvent("cancelled");await c1(K,()=>q?.cancel())}catch(G){throw _1(K,G,U),G}finally{K?.end()}})}function TV($,U={}){let Q=U.eventIteratorKeepAliveEnabled??!0,q=U.eventIteratorKeepAliveInterval??5000,K=U.eventIteratorKeepAliveComment??"",W=U.eventIteratorInitialCommentEnabled??!0,J=U.eventIteratorInitialComment??"",G=!1,Y,H;return new ReadableStream({start(M){if(H=N0("stream_event_iterator"),W)M.enqueue(M6({comments:[J]}))},async pull(M){try{if(Q)Y=setInterval(()=>{M.enqueue(M6({comments:[K]})),H?.addEvent("keepalive")},q);let V=await c1(H,()=>$.next());if(clearInterval(Y),G)return;let L=V4(V.value);if(!V.done||V.value!==void 0||L!==void 0){let T=V.done?"done":"message";M.enqueue(M6({...L,event:T,data:n1(V.value)})),H?.addEvent(T)}if(V.done)M.close(),H?.end()}catch(V){if(clearInterval(Y),G)return;if(V instanceof Y1)M.enqueue(M6({...V4(V),event:"error",data:n1(V.data)})),H?.addEvent("error"),M.close();else _1(H,V),M.error(V);H?.end()}},async cancel(){try{G=!0,clearInterval(Y),H?.addEvent("cancelled"),await c1(H,()=>$.return?.())}catch(M){throw _1(H,M),M}finally{H?.end()}}}).pipeThrough(new TextEncoderStream)}function SV($,U={}){return r1({name:"parse_standard_body",signal:U.signal},async()=>{let Q=$.headers.get("content-disposition");if(typeof Q==="string"){let W=RJ(Q)??"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 X6(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 RV($.body,U);if(q.startsWith("text/plain"))return await $.text();let K=await $.blob();return new File([K],"blob",{type:K.type})})}function CV($,U,Q={}){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??OJ($ instanceof File?$.name:"blob")),$;if($ instanceof FormData)return $;if($ instanceof URLSearchParams)return $;if(j1($))return U.set("content-type","text/event-stream"),TV($,Q);return U.set("content-type","application/json"),n1($)}function JU($,U={}){return $.forEach((Q,q)=>{if(Array.isArray(U[q]))U[q].push(Q);else if(U[q]!==void 0)U[q]=[U[q],Q];else U[q]=Q}),U}function EV($,U=new Headers){for(let[Q,q]of Object.entries($))if(Array.isArray(q))for(let K of q)U.append(Q,K);else if(q!==void 0)U.append(Q,q);return U}function SJ($,U={}){let Q=EV($.headers),q=CV($.body,Q,U);return new Request($.url,{signal:$.signal,method:$.method,headers:Q,body:q})}function CJ($,U={}){return{body:D0(()=>SV($,U)),status:$.status,get headers(){let Q=JU($.headers);return Object.defineProperty(this,"headers",{value:Q,writable:!0}),Q},set headers(Q){Object.defineProperty(this,"headers",{value:Q,writable:!0})}}}class F0{plugins;constructor($=[]){this.plugins=[...$].sort((U,Q)=>(U.order??0)-(Q.order??0))}init($){for(let U of this.plugins)U.init?.($)}}class EJ{constructor($,U,Q={}){this.codec=$,this.sender=U,new F0(Q.plugins).init(Q),this.interceptors=l1(Q.interceptors),this.clientInterceptors=l1(Q.clientInterceptors)}interceptors;clientInterceptors;call($,U,Q){return r1({name:`${a8}.${$.join("/")}`,signal:Q.signal},(q)=>{if(q?.setAttribute("rpc.system",a8),q?.setAttribute("rpc.method",$.join(".")),j1(U))U=e8({name:"consume_event_iterator_input",signal:Q.signal},U);return H6(this.interceptors,{...Q,path:$,input:U},async({path:K,input:W,...J})=>{let G=Y6(),Y,H=G?.trace.getActiveSpan()??q;if(H&&G)Y=G?.trace.setSpan(G.context.active(),H);let B=await r1({name:"encode_request",context:Y},()=>this.codec.encode(K,W,J)),M=await H6(this.clientInterceptors,{...J,input:W,path:K,request:B},({input:L,path:T,request:f,...U$})=>{return r1({name:"send_request",signal:U$.signal,context:Y},()=>this.sender.call(f,U$,T,L))}),V=await r1({name:"decode_response",context:Y},()=>this.codec.decode(M,J,K,W));if(j1(V))return e8({name:"consume_event_iterator_output",signal:J.signal},V);return V})})}}var I$={BIGINT:0,DATE:1,NAN:2,UNDEFINED:3,URL:4,REGEXP:5,SET:6,MAP:7};class gJ{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=[],Q=[],q=[],K=[]){for(let W of this.customSerializers)if(W.condition($)){let J=this.serialize(W.serialize($),U,Q,q,K);return Q.push([W.type,...U]),J}if($ instanceof Blob)return q.push(U),K.push($),[$,Q,q,K];if(typeof $==="bigint")return Q.push([I$.BIGINT,...U]),[$.toString(),Q,q,K];if($ instanceof Date){if(Q.push([I$.DATE,...U]),Number.isNaN($.getTime()))return[null,Q,q,K];return[$.toISOString(),Q,q,K]}if(Number.isNaN($))return Q.push([I$.NAN,...U]),[null,Q,q,K];if($ instanceof URL)return Q.push([I$.URL,...U]),[$.toString(),Q,q,K];if($ instanceof RegExp)return Q.push([I$.REGEXP,...U]),[$.toString(),Q,q,K];if($ instanceof Set){let W=this.serialize(Array.from($),U,Q,q,K);return Q.push([I$.SET,...U]),W}if($ instanceof Map){let W=this.serialize(Array.from($.entries()),U,Q,q,K);return Q.push([I$.MAP,...U]),W}if(Array.isArray($))return[$.map((J,G)=>{if(J===void 0)return Q.push([I$.UNDEFINED,...U,G]),null;return this.serialize(J,[...U,G],Q,q,K)[0]}),Q,q,K];if(P0($)){let W={};for(let J in $){if(J==="toJSON"&&typeof $[J]==="function")continue;W[J]=this.serialize($[J],[...U,J],Q,q,K)[0]}return[W,Q,q,K]}return[$,Q,q,K]}deserialize($,U,Q,q){let K={data:$};if(Q&&q)Q.forEach((W,J)=>{let G=K,Y="data";W.forEach((H)=>{if(G=G[Y],Y=H,!Object.hasOwn(G,Y))throw Error(`Security error: accessing non-existent path during deserialization. Path segment: ${Y}`)}),G[Y]=q(J)});for(let W of U){let J=W[0],G=K,Y="data";for(let H=1;H<W.length;H++)if(G=G[Y],Y=W[H],!Object.hasOwn(G,Y))throw Error(`Security error: accessing non-existent path during deserialization. Path segment: ${Y}`);for(let H of this.customSerializers)if(H.type===J){G[Y]=H.deserialize(G[Y]);break}switch(J){case I$.BIGINT:G[Y]=BigInt(G[Y]);break;case I$.DATE:G[Y]=new Date(G[Y]??"Invalid Date");break;case I$.NAN:G[Y]=Number.NaN;break;case I$.UNDEFINED:G[Y]=void 0;break;case I$.URL:G[Y]=new URL(G[Y]);break;case I$.REGEXP:{let[,H,B]=G[Y].match(/^\/(.*)\/([a-z]*)$/);G[Y]=new RegExp(H,B);break}case I$.SET:G[Y]=new Set(G[Y]);break;case I$.MAP:G[Y]=new Map(G[Y]);break}}return K.data}}function gV($){return`/${$.map(encodeURIComponent).join("/")}`}function yV($){if(typeof $.forEach==="function")return JU($);return $}function uV($){return Object.entries(_0).find(([,U])=>U.status===$)?.[0]??"MALFORMED_ORPC_ERROR_RESPONSE"}class yJ{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,Q){let q=yV(await B6(this.headers,Q,$,U));if(Q.lastEventId!==void 0)q=TJ(q,{"last-event-id":Q.lastEventId});let K=await B6(this.expectedMethod,Q,$,U),W=await B6(this.baseUrl,Q,$,U),J=new URL(W);J.pathname=`${J.pathname.replace(/\/$/,"")}${gV($)}`;let G=this.serializer.serialize(U);if(K==="GET"&&!(G instanceof FormData)&&!j1(G)){let Y=await B6(this.maxUrlLength,Q,$,U),H=new URL(J);if(H.searchParams.append("data",n1(G)),H.toString().length<=Y)return{body:void 0,method:K,headers:q,url:H,signal:Q.signal}}return{url:J,method:K==="GET"?this.fallbackMethod:K,headers:q,body:G,signal:Q.signal}}async decode($){let U=!L0($.status),Q=await(async()=>{let q=!1;try{let K=await $.body();return q=!0,this.serializer.deserialize(K)}catch(K){if(!q)throw Error("Cannot parse response body, please check the response body and content-type.",{cause:K});throw Error("Invalid RPC response format.",{cause:K})}})();if(!U){if(UU(Q))throw KU(Q);throw new i1(uV($.status),{status:$.status,data:{...$,body:Q}})}return Q}}class uJ{constructor($){this.jsonSerializer=$}serialize($){if(j1($))return WU($,{value:async(U)=>this.#$(U,!1),error:async(U)=>{return new Y1({data:this.#$(vJ(U).toJSON(),!1),cause:U})}});return this.#$($,!0)}#$($,U){let[Q,q,K,W]=this.jsonSerializer.serialize($),J=q.length===0?void 0:q;if(!U||W.length===0)return{json:Q,meta:J};let G=new FormData;return G.set("data",n1({json:Q,meta:J,maps:K})),W.forEach((Y,H)=>{G.set(H.toString(),Y)}),G}deserialize($){if(j1($))return WU($,{value:async(U)=>this.#U(U),error:async(U)=>{if(!(U instanceof Y1))return U;let Q=this.#U(U.data);if(UU(Q))return KU(Q,{cause:U});return new Y1({data:Q,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,(Q)=>$.get(Q.toString()))}}class GU extends EJ{constructor($,U){let Q=new gJ(U),q=new uJ(Q),K=new yJ(q,U);super(K,$,U)}}class fJ extends F0{initRuntimeAdapter($){for(let U of this.plugins)U.initRuntimeAdapter?.($)}}class hJ{fetch;toFetchRequestOptions;adapterInterceptors;constructor($){new fJ($.plugins).initRuntimeAdapter($),this.fetch=$.fetch??globalThis.fetch.bind(globalThis),this.toFetchRequestOptions=$,this.adapterInterceptors=l1($.adapterInterceptors)}async call($,U,Q,q){let K=SJ($,this.toFetchRequestOptions),W=await H6(this.adapterInterceptors,{...U,request:K,path:Q,input:q,init:{redirect:"manual"}},({request:G,path:Y,input:H,init:B,...M})=>this.fetch(G,B,M,Y,H));return CJ(W,{signal:K.signal})}}class p1 extends GU{constructor($){let U=new hJ($);super(U,$)}}import{chmodSync as jU,mkdirSync as mJ,readFileSync as fV,writeFileSync as YU}from"node:fs";import{homedir as hV}from"node:os";import{join as cJ}from"node:path";var HU=cJ(hV(),".niva"),t1=cJ(HU,"config.json");function V6(){try{let $=JSON.parse(fV(t1,"utf-8"));return G$($)?$:{}}catch{return{}}}function lJ($,U){mJ(HU,{recursive:!0});let q={...V6(),[$]:U};YU(t1,`${JSON.stringify(q,null,2)}
|
|
40
|
+
`,{mode:384}),jU(t1,384)}function XU(){return V6()}function D4($){return $.replace(/\/+$/,"")}function mV($){let U=G$($)?{...$}:void 0;if(U==null)return!1;let Q=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(Q)&&Q.every((q)=>typeof q==="string")}function BU(){let $=V6().auth;return G$($)?$:{}}function rJ(){let $={};for(let[U,Q]of Object.entries(BU()))if(mV(Q))$[U]=Q;return $}function N4($,U){mJ(HU,{recursive:!0});let Q={...V6(),auth:{...BU(),[D4($)]:U}};YU(t1,`${JSON.stringify(Q,null,2)}
|
|
41
|
+
`,{mode:384}),jU(t1,384)}function nJ($){let U=BU(),Q=D4($);if(!(Q in U))return;delete U[Q];let q={...V6(),auth:U};YU(t1,`${JSON.stringify(q,null,2)}
|
|
42
|
+
`,{mode:384}),jU(t1,384)}import{createHash as cV,randomBytes as oJ}from"node:crypto";import{createServer as lV}from"node:http";var rV=600000,nV=120,iV=5;class N$ extends Error{code;constructor($,U){super(U);this.code=$}}function oV($){let U=M$($),Q=i(U?.access_token),q=u1(U?.expires_in);if(U==null||Q==null||q==null)return null;let K=i(U.refresh_token),W=i(U.scope);return{access_token:Q,expires_in:q,...K!=null?{refresh_token:K}:{},...W!=null?{scope:W}:{}}}function dJ($,U){let Q=M$($),q=i(Q?.error)??`http_${String(U)}`,K=i(Q?.error_description)??q;return new N$(q,K)}function dV(){return oJ(32).toString("base64url")}function pV($){return cV("sha256").update($).digest("base64url")}function pJ($,U){if($.NIVA_NO_BROWSER==="1")return!1;let Q=$.CI;if(Q==="true"||Q==="1")return!1;if(U==="linux")return $.DISPLAY!=null||$.WAYLAND_DISPLAY!=null;return!0}function ZU($){let U;if(process.platform==="darwin")U=[["open",$]];else if(process.platform==="win32")U=[["cmd","/c","start","",$]];else U=[["xdg-open",$]];for(let Q of U){let[q,...K]=Q;if(q==null)continue;try{return Bun.spawn([q,...K],{stdout:"ignore",stderr:"ignore"}).exited.then((J)=>{if(J!==0)iJ($)}),!0}catch{continue}}return iJ($),!1}function iJ($){console.error(`Open this URL to continue: ${$}`)}async function MU($){let U=new URL("/.well-known/oauth-authorization-server",$.replace(/\/+$/,"")),Q=await fetch(U),q=await Q.json().catch(()=>({})),K=M$(q),W=i(K?.issuer),J=i(K?.authorization_endpoint),G=i(K?.token_endpoint);if(!Q.ok||K==null||W==null||J==null||G==null)throw new N$("discovery_failed",`Could not read OAuth metadata from ${$}`);let Y=i(K.device_authorization_endpoint);return{issuer:W,authorization_endpoint:J,token_endpoint:G,...Y!=null?{device_authorization_endpoint:Y}:{}}}async function VU($,U){let Q=await fetch($,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(U).toString()}),q=await Q.json().catch(()=>({}));if(!Q.ok)throw dJ(q,Q.status);let K=oV(q);if(K==null)throw new N$("invalid_response","The token endpoint answered an unexpected body");return K}function tV($){return(U,Q)=>{let q=new URL(U.url??"/","http://127.0.0.1");if(q.pathname!=="/callback"){Q.writeHead(404).end();return}Q.writeHead(200,{"content-type":"text/html; charset=utf-8"}),Q.end("<html><body><p>Login complete. You can close this tab and go back to the terminal.</p></body></html>");let K=q.searchParams.get("code"),W=q.searchParams.get("state"),J=q.searchParams.get("iss")??void 0,G=q.searchParams.get("error");if(G!=null)$({error:G});else if(K!=null&&W!=null)$({code:K,state:W,iss:J});else $({error:"invalid_request"})}}function aV($,U){return new Promise((Q,q)=>{let K=setTimeout(()=>{$.current=null,U(),q(new N$("timeout","Timed out waiting for the browser callback"))},rV);$.current=(W)=>{if(clearTimeout(K),U(),"error"in W)q(new N$(W.error,`Authorization failed: ${W.error}`));else Q(W)}})}function sV(){return new Promise(($,U)=>{let Q={current:null},q=lV(tV((W)=>Q.current?.(W))),K=async()=>aV(Q,()=>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:K,close:()=>q.close()})})})}async function tJ($,U){let Q=await sV(),q=dV(),K=oJ(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",Q.redirectUri),W.searchParams.set("scope",U.scopes.join(" ")),W.searchParams.set("state",K),W.searchParams.set("code_challenge",pV(q)),W.searchParams.set("code_challenge_method","S256"),W.searchParams.set("resource",U.resource);try{ZU(W.href);let J=await Q.waitForCode();if(J.state!==K)throw new N$("state_mismatch","The state returned by the server does not match");if(J.iss!=null&&J.iss!==$.issuer)throw new N$("issuer_mismatch","The issuer returned by the server does not match");return await VU($.token_endpoint,{grant_type:"authorization_code",code:J.code,redirect_uri:Q.redirectUri,client_id:U.clientId,code_verifier:q})}finally{Q.close()}}function eV($){let U=M$($);if(U==null)return null;let Q=["device_code","user_code","verification_uri","verification_uri_complete"].map((K)=>i(U[K])),q=["expires_in","interval"].map((K)=>u1(U[K]));if(Q.some((K)=>K==null)||q.some((K)=>K==null))return null;return{device_code:Q[0],user_code:Q[1],verification_uri:Q[2],verification_uri_complete:Q[3],expires_in:q[0],interval:q[1]}}async function aJ($,U){let Q=$.device_authorization_endpoint;if(Q==null)throw new N$("unsupported_grant_type","This server does not support the device flow");let q=await fetch(Q,{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()}),K=await q.json().catch(()=>({})),W=q.ok?eV(K):null;if(W==null)throw q.ok?new N$("invalid_response","The device authorization endpoint answered an unexpected body"):dJ(K,q.status);return W}async function sJ($,U,Q){let q=U.interval*1000,K=Date.now()+U.expires_in*1000;while(Date.now()<K){await Bun.sleep(q);try{return await VU($,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:U.device_code,client_id:Q})}catch(W){if(W instanceof N$){if(W.code==="authorization_pending")continue;if(W.code==="slow_down"){q+=iV*1000;continue}}throw W}}throw new N$("expired_token","The device code expired before authorization completed")}function v0($,U=Math.floor(Date.now()/1000)){return $.expires_at-U<nV}async function z0($,U){let Q=await MU($),q=await VU(Q.token_endpoint,{grant_type:"refresh_token",refresh_token:U.refresh_token,client_id:"niva-cli"});if(q.refresh_token==null)throw new N$("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((K)=>K!==""):U.scopes}}function DU($){try{let{hostname:U}=new URL($);return U.endsWith(".orb.local")||process.env.NIVA_INSECURE==="true"}catch{return!1}}class eJ extends Error{constructor(){super("Your session has expired. Run 'niva login' to authenticate again.")}}function $D($){let U=$.fetchImpl??fetch,Q=async()=>{try{return await $.refresh()}catch(q){if(q instanceof N$)throw new eJ;throw q}};return async(q)=>{let K=$.getSession();if(v0(K))K=await Q();let W=new Request(q);W.headers.set("authorization",`Bearer ${K.access_token}`);let J=await U(W);if(J.status===401){K=await Q();let G=new Request(q);G.headers.set("authorization",`Bearer ${K.access_token}`),J=await U(G)}return J}}function NU($,U,Q){if(DU($))process.env.NODE_TLS_REJECT_UNAUTHORIZED="0";if(U.kind!=="oauth"){let W=new p1({url:new URL("/api/rpc",$).href,headers:()=>U.kind==="api-key"?{"X-API-Key":U.apiKey}:{}});return d1(W)}let q=U.session,K=new p1({url:new URL("/api/rpc",$).href,fetch:$D({getSession:()=>q,refresh:async()=>{return q=await z0(Q,q),N4(Q,q),q}})});return d1(K)}var PU="niva-cli",UD=["*:read","*:write","offline_access"],KD=["*:read","offline_access"];function $G($,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((Q)=>Q!==""):[]}}async function QD($,U){return(await NU($,{kind:"oauth",session:$G(U,"")},$).oauth.whoami()).organization?.id??""}function UG($,U,Q){$.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 K=D4(U().url);if(!K.startsWith("https://"))J1("Server URL is not https: tokens travel unencrypted on this network.");let W=q.readOnly===!0?KD:UD,J=`${K}/api`,G=await MU(K),Y={scopes:W,resource:J,clientId:PU},H,B=pJ(process.env,process.platform);if(q.device===!0||!B){let V=await aJ(G,Y);if(w(`Open ${V.verification_uri} and enter the code: ${V.user_code}`),B)ZU(V.verification_uri_complete);H=await sJ(G.token_endpoint,V,PU)}else H=await tJ(G,Y);let M=await QD(K,H);N4(K,$G(H,M)),E(`Logged in to ${K}`)}),$.command("logout").description("Revoke the saved session and remove it from the config file").action(async()=>{let q=D4(U().url),K=rJ()[q];if(K==null){w(`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:K.refresh_token,client_id:PU}).toString()})}catch{J1("Could not reach the server to revoke the token; clearing the local session anyway.")}nJ(q),E(`Logged out of ${q}`)}),$.command("whoami").description("Show the authenticated user, organization, scopes and token expiry").action(async()=>{let q=D4(U().url),K=Q();if(K.kind==="none"){x(`No credential configured for ${q}. Run 'niva login' first.`),process.exitCode=1;return}let J=await NU(q,K,q).oauth.whoami();P({url:q,user:J.user.email,organization:J.organization?.name,scopes:J.scopes,credential:J.credential,...K.kind==="oauth"?{expires_at:new Date(K.session.expires_at*1000).toISOString()}:{}})})}var a=M1(D1(),1);var qD=/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i,KG=4;async function k0($,U){if(qD.test(U))return U;if(U.length<KG)x(`UUID prefix too short — provide at least ${KG} characters.`),process.exit(A.USAGE_ERROR);let Q=await _($.dashboard.activeCalls()),q=U.toLowerCase(),K=Q.filter((W)=>W.uuid.toLowerCase().startsWith(q));if(K.length===0)x(`No active call matching "${U}".`),process.exit(A.NOT_FOUND);if(K.length>1){x(`Ambiguous UUID prefix "${U}" — matches ${K.length} calls. Be more specific.`);for(let W of K)w(` ${W.uuid} ${W.callerId}`);process.exit(A.USAGE_ERROR)}return K[0].uuid}var WD={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 JD($){let U=Math.max(0,Math.floor($)),Q=Math.floor(U/60),q=U%60;return`${String(Q).padStart(2,"0")}:${String(q).padStart(2,"0")}`}function GD($){if($==null)return"—";return`${JD($.at_seconds)}${$.late?" (late)":""}`}function WG($,U){let Q=$.command("calls").description("Manage calls");Q.command("list").description("List active calls").action(async()=>{let{format:q,fields:K}=F($.opts()),W=await _(U().dashboard.activeCalls());if(q==="json"){let J=K?W.map((G)=>C(G,K)):W;P(J);return}if(W.length===0){w("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`:"—"})))}),Q.command("show <call_record_id>").description("Show call details from CDR (rich detail view)").action(async(q)=>{let{format:K,fields:W}=F($.opts()),J=await _(U().callRecords.getById({call_record_id:b("call_records",q)}));if(K==="json"){let G=W&&J!=null?C(J,W):J;P(G);return}if(J==null){w("Call record not found.");return}t([{title:"Call Record",rows:YD(J)}])}),Q.command("hangup <call>").description("Hang up an active call by TypeID (call_...), full channel UUID, or UUID prefix").action(async(q)=>{let{format:K}=F($.opts()),W=U(),J=q,G;if(q.startsWith("call_"))G=await _(W.calls.hangupCall({call_id:b("call_records",q)}));else J=await k0(W,q),G=await _(W.calls.hangupActiveCall({uuid:J}));if(K==="json"){P(G);return}E(`Call ${J} terminated.`)}),Q.command("signals <call_record_id>").description("Show the signal results of a recorded call").action(async(q)=>{let{format:K,fields:W}=F($.opts()),J=await _(U().signals.callSignals({call_id:b("call_records",q)}));if(K==="json"){let G=W?J.map((Y)=>C(Y,W)):J;P(G);return}if(J.length===0){w("No signal results for this call.");return}y(["Signal","Value","Confidence","Triggered at","Severity"],J.map((G)=>({Signal:G.signal.name,Value:G.value_label??"—",Confidence:G.confidence==null?"—":`${Math.round(G.confidence*100)}%`,"Triggered at":GD(G.trigger),Severity:G.definition.alert?.severity??"—"})))}),Q.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:K,fields:W}=F($.opts()),J=await _(U().callRecords.list({page:Number(q.page),limit:Number(q.limit),search:q.caller}));if(K==="json"){let G=W?J.items.map((Y)=>C(Y,W)):J;P(G);return}y(["ID","Caller","Callee","Duration","Disposition","Date"],J.items.map((G)=>({ID:G.id,Caller:G.caller_id??"—",Callee:G.callee_id??"—",Duration:C$(G.duration_ms),Disposition:G.hangup_disposition??"—",Date:new Date(G.started_at).toLocaleString()}))),j$(J)}),Q.command("follow <uuid>").description("Follow live transcription of an active call").action(async(q)=>{let{format:K}=F($.opts()),W=U(),J=await k0(W,q),G=new AbortController;process.on("SIGINT",()=>{G.abort()});let Y=!1,H=!1;function B(V){M();let L=JG(V);process.stdout.write(a.default.dim(L)),H=!0}function M(){if(!H)return;process.stdout.clearLine(0),process.stdout.cursorTo(0),H=!1}await new Promise((V,L)=>{F1(W.dashboard.watchLiveTranscription({uuid:J},{signal:G.signal}),{onEvent:(T)=>{if(Y=!0,K==="json"){P(T);return}switch(T.type){case"starting":w("Connecting...");break;case"started":w("Transcription started.");break;case"caught_up":break;case"unavailable":w(WD[T.reason]),V();break;case"ended":M(),w("Transcription ended."),V();break;case"error":console.error(a.default.red(`Error: ${T.message}`));break;case"history":for(let f of T.segments)QG(f);for(let f of T.signals??[])qG(f);break;case"signal_value":case"signal_triggered":qG(T);break;case"segment":if(T.segment.isFinal)M(),QG(T.segment);else B(T.segment);break}},onError:(T)=>{if(T instanceof DOMException&&T.name==="AbortError"){M(),V();return}L(T)},onSuccess:()=>{if(!Y)w("Live transcription not available for this call.");V()}})}).catch((V)=>{M(),Z4(V)})}),Q.command("transfer <uuid> <destination>").description("Transfer an active call").action(()=>d$()),Q.command("spy <uuid>").description("Spy on an active call").action(()=>d$()),Q.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:K,fields:W}=F($.opts()),J=await _(U().callRecords.list({page:Number(q.page),limit:Number(q.limit),date_from:q.from,date_to:q.to,visual_plan_id:b("visual_plans",q.plan),channel_id:b("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(K==="json"){if(W)P(J.items.map((G)=>C(G,W)));else P(J);return}if(J.items.length===0){w("No call records found.");return}y(["ID","Caller","Direction","Duration","Status","Sentiment","Plan","Date"],J.items.map((G)=>{let Y=G.sentiment_score!=null?Number(G.sentiment_score):null;return{ID:G.id,Caller:G.caller_id??"—",Direction:G.direction??"—",Duration:C$(G.duration_ms),Status:c8(G.hangup_disposition),Sentiment:G.sentiment_label!=null?l8(G.sentiment_label,Y):"—",Plan:G.visual_plan_name??"—",Date:a$(G.started_at)}})),j$(J)}),Q.command("trace <call_record_id>").description("Show node-by-node execution trace for a call").action(async(q)=>{let{format:K,fields:W}=F($.opts()),J=await _(U().callRecords.getTrace({call_record_id:b("call_records",q)}));if(K==="json"){let V=W&&J!=null?C(J,W):J;P(V);return}if(J==null){w("Call trace not found.");return}let G=J.callRecord;if(console.log(`${a.default.bold("Call Trace")} — ${q} (${C$(G.duration_ms)}, ${G.hangup_disposition??"unknown"})`),G.visual_plan_name!=null)console.log(`Plan: ${G.visual_plan_name}`);console.log("");let Y=J.events;if(Y.length===0){w(" No events recorded (0 nodes visited).");return}let H=Y.map((V,L)=>{let T=V.duration_ms!=null?`${(V.duration_ms/1000).toFixed(1)}s`:"—",f=`${a.default.cyan(V.node_type)}`;if(V.node_label!=null){let x$=a.default.bold(`"${V.node_label}"`);f+=` ${x$}`}if(f+=a.default.dim(` (${T})`),V.digit!=null)f+=` → digit: ${a.default.yellow(V.digit)}`;let U$=[];if(V.handle_used!=null)U$.push(a.default.dim(`└─→ ${V.handle_used}`));if(G$(V.data)){let x$=Object.entries(V.data).filter(([,B4])=>B4!=null&&typeof B4!=="object").map(([B4,h$])=>`${B4}: ${String(h$)}`);if(x$.length>0)U$.push(a.default.dim(`└─ ${x$.join(", ")}`))}return{label:f,children:U$.length>0?U$:void 0}});r8(H),console.log("");let B=Y.at(-1),M=B.node_label??B.node_type;w(` ${Y.length} nodes visited · Last: ${B.node_type} "${M}" · Hangup: ${G.hangup_cause??"—"}`)}),Q.command("transcript <call_record_id>").description("Show call transcription with speech analytics").action(async(q)=>{let{format:K,fields:W}=F($.opts()),J=await _(U().ai.getTranscription({call_record_id:b("call_records",q)}));if(K==="json"){let H=W&&J!=null?C(J,W):J;P(H);return}console.log(`${a.default.bold("Transcript")} — ${q}`),console.log("");let G=XD(J?.segments);if(G.length===0||J?.status==="disabled")w(" No transcript available.");else oW(G);let Y=J!=null?BD(J):[];if(Y.length>0)console.log(""),t([{title:"Speech Analytics",rows:Y}])}),Q.command("purge-voice <call_record_id>").description("Permanently erase a call's voice content (recording, transcription, embeddings)").action(async(q)=>{let{format:K}=F($.opts()),W=$.opts().yes===!0;if(K!=="json")console.log(`${a.default.bold("Erase voice content")} — ${q}`),w(" Deletes: recording file, transcription and its semantic-search embeddings."),w(" Keeps: the call record (CDR), its event timeline and existing analyses."),w(" This is irreversible."),console.log("");await I1("Erase the voice content of this call?",{yes:W});let J=await _(U().callRecords.purgeVoiceContent({call_record_id:b("call_records",q)}));if(K==="json"){P(J);return}E("Voice content erased"),t([{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)}]}])}),Q.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,K)=>{let{format:W,fields:J}=F($.opts()),G=await _(U().ai.searchTranscriptions({query:q,limit:Number(K.limit),threshold:Number(K.threshold),date_from:K.from,date_to:K.to,visual_plan_id:b("visual_plans",K.plan)}));if(W==="json"){let H=J?G.map((B)=>C(B,J)):G;P(H);return}let Y=G;if(console.log(`${a.default.bold("Semantic Search")}: "${q}"`),console.log(`${Y.length} result${Y.length!==1?"s":""} (threshold: ${K.threshold})`),Y.length===0){w(`
|
|
43
|
+
No results found.`);return}console.log("");for(let H of Y){let B=`${Math.round(H.similarity*100)}%`,M=H.call_record_id,V=a$(H.started_at),L=C$(H.duration_ms);console.log(` ${a.default.bold(B.padStart(4))} │ ${M} │ ${V} │ ${H.caller_id??"—"} │ ${H.direction} │ ${L} │ ${H.visual_plan_name??"—"}`);let T=String(H.chunk_text).replaceAll(/\s+/g," ").trim(),f=120,U$=T.length>f?`${T.slice(0,f)}...`:T;console.log(a.default.dim(` │ "${U$}"`)),console.log("")}}),Q.command("inspect <uuid>").description("Inspect an active call: current node, variables, execution path").action(async(q)=>{let{format:K,fields:W}=F($.opts()),J=U(),G=await k0(J,q),Y=await _(J.dashboard.activeCallTrace({uuid:G}));if(K==="json"){let M=W?C(Y,W):Y;P(M);return}t([{title:"Active Call",rows:[{label:"UUID",value:G},{label:"Current",value:Y.currentNodeId??"—"}]}]);let H=Y.variables;if(Object.keys(H).length>0){let M=Object.entries(H).map(([V,L])=>({label:V,value:L}));t([{title:`Variables (${Object.keys(H).length})`,rows:M}])}let B=Y.events;if(B.length>0){console.log(""),console.log(a.default.bold("Execution Path:"));let M=B.map((V)=>{let L=V.duration_ms!=null?`${(V.duration_ms/1000).toFixed(1)}s`:"waiting...",T=V.node_id===Y.currentNodeId,U$=`${T?a.default.yellow("●"):a.default.green("✓")} ${a.default.cyan(V.node_type)}`;if(V.node_label!=null){let x$=a.default.bold(`"${V.node_label}"`);U$+=` ${x$}`}if(U$+=a.default.dim(` (${L})`),T)U$+=a.default.yellow(" ← current");return{label:U$}});r8(M)}})}function jD($){if($.has_recording)return"yes";if($.was_recorded)return"processing";return"no"}function w0($){return $!=null&&$!==""}function YD($){let U=$.answered_at!=null?new Date($.answered_at):null,Q=new Date($.started_at),q=U!=null?`${Math.round((U.getTime()-Q.getTime())/1000)}s ring`:null,K=w0(q)?` (${q})`:"",W=$.visual_plan_version_number!=null?` v${$.visual_plan_version_number}`:"",J=w0($.visual_plan_name)?`${$.visual_plan_name}${W}`:null,G=w0($.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:Q.toLocaleString()},{label:"Answered",value:U!=null?`${U.toLocaleString()}${K}`:null},{label:"Ended",value:$.ended_at!=null?new Date($.ended_at).toLocaleString():null},{label:"Duration",value:C$($.duration_ms)},{label:"Status",value:c8($.hangup_disposition)},{label:"Recording",value:jD($)},{label:"Transcribed",value:Y},{label:"Machine type",value:$.answer_recognition_results?.machine_type},{label:"Hangup",value:w0($.hangup_cause)?`${$.hangup_cause}${G}`:null}]}function HD($){let U=u1($.confidence),Q=U!=null?` (${U.toFixed(2)})`:"";return`${i($.topic)??i($.label)??"?"}${Q}`}function XD($){let U=[];for(let Q of m$($)){let q=i(Q.speaker),K=i(Q.text),W=u1(Q.initial_time);if(q!=null&&K!=null&&W!=null)U.push({speaker:q,text:K,initial_time:W})}return U}function BD($){let U=[],Q=M$($.sentiment_overall);if(Q!=null)U.push({label:"Sentiment",value:l8(i(Q.label),u1(Q.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(`
|
|
44
|
+
│ `)});let K=m$($.topics);if(K.length>0)U.push({label:"Topics",value:K.map((W)=>HD(W)).join(" · ")});return U}function JG($){let U=Math.floor($.start/60),Q=Math.floor($.start%60),q=`${String(U).padStart(2,"0")}:${String(Q).padStart(2,"0")}`,K=$.channel===0?a.default.blue("Caller"):a.default.green("System");return`${a.default.dim(`[${q}]`)} ${K} ${a.default.dim(">")} ${$.text}`}function QG($){console.log(JG($))}function qG($){let U=`${Math.round($.confidence*100)}%`;if($.type==="signal_value"){w(` ↳ ${$.signal.name}: ${$.value_label} (${U})`);return}let Q=$.node!=null?` · ${$.node.label}`:"",q=$.late?" (late)":"";console.log(a.default.bold(a.default.yellow(` \uD83D\uDD14 ${$.signal.name}: ${$.value_label} (${U})${Q}${q}`)))}import{readFile as ZD}from"node:fs/promises";async function GG($){let U=$==="-"?await G1():await ZD($,"utf-8"),Q=JSON.parse(U);if(!G$(Q))x(`Invalid campaign file "${$}": expected a JSON object`),process.exit(A.USAGE_ERROR);return Q}function MD($){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 VD($){let U=$.retryOn!=null?new Set($.retryOn.split(",").map((Q)=>Q.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 jG($){return{...MD($),...VD($)}}function P4($){if($==null)return"inherit (org default)";if(typeof $==="boolean")return $?"yes":"no";return String($)}function YG($){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 HG($,U){let Q=$.command("campaigns").description("Manage dialer campaigns");Q.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:K,fields:W}=F($.opts()),J=await _(U().dialerCampaigns.list({page:Number(q.page),limit:Number(q.limit),search:q.search,status:p$(q.status)}));if(K==="json"){let G=W?J.items.map((Y)=>C(Y,W)):J;P(G);return}y(["ID","Name","Status","Contacts","Answered","Created"],J.items.map((G)=>({ID:G.id,Name:G.name,Status:G.status,Contacts:G.total_contacts,Answered:G.answered_count,Created:a$(G.created_at)}))),j$(J)}),Q.command("show <campaign_id>").description("Show campaign details").action(async(q)=>{let{format:K,fields:W}=F($.opts()),J=await _(U().dialerCampaigns.get({campaign_id:b("dialer_campaigns",q)}));if(J==null){if(K==="json")P(null),process.exit(A.NOT_FOUND);x("Campaign not found"),process.exit(A.NOT_FOUND)}if(K==="json"){let G=W?C(J,W):J;P(G);return}t([{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:P4(J.amd_block_after_all_machine)},{label:"Block Min Attempts",value:P4(J.amd_block_min_attempts)},{label:"On Voicemail",value:P4(J.amd_action_voicemail)},{label:"On Announcement",value:P4(J.amd_action_announcement)},{label:"On IVR",value:P4(J.amd_action_ivr)},{label:"On Screening",value:P4(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}]}])}),Q.command("stats <campaign_id>").description("Show campaign statistics").action(async(q)=>{let{format:K,fields:W}=F($.opts()),J=await _(U().dialerCampaigns.stats({campaign_id:b("dialer_campaigns",q)}));if(K==="json"){let H=W?C(J,W):J;P(H);return}let G=J.capacity_context;t([{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:G!=null?G.used:null},{label:"Capacity",value:G!=null?G.capacity:null},{label:"Reserve",value:G!=null?G.reserve:null},{label:"Module Disabled",value:J.module_disabled?"yes":"no"}]}]);let Y=Number(J.total_contacts);if(Y>0)console.log(""),o$("Answered",Number(J.answered_count),Y),o$("Busy",Number(J.busy_count),Y),o$("No Answer",Number(J.no_answer_count),Y),o$("Failed",Number(J.failed_count),Y)}),Q.command("summary").description("Show running-campaign summary").action(async()=>{let{format:q,fields:K}=F($.opts()),W=await _(U().dialerCampaigns.summary());if(q==="json"){let J=K?C(W,K):W;P(J);return}t([{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}]}])}),YG(Q.command("create <name>").description("Create a dialer campaign").requiredOption("--plan <plan_id>","Visual plan ID to dial")).action(async(q,K)=>{let{format:W}=F($.opts()),J=K.file!=null?await GG(K.file):{},G=jG(K),Y=await _(U().dialerCampaigns.create({...J,...G,name:q,plan_id:b("visual_plans",K.plan)}));if(W==="json"){P(Y);return}E(`Campaign created: ${Y.id} — ${Y.name}`)}),YG(Q.command("edit <campaign_id>").description("Update a dialer campaign").option("--name <name>","Campaign name")).action(async(q,K)=>{let{format:W}=F($.opts()),J=K.file!=null?await GG(K.file):{},G=jG(K),Y=await _(U().dialerCampaigns.update({campaign_id:b("dialer_campaigns",q),...J,...G}));if(W==="json"){P(Y);return}E(`Campaign updated: ${Y.name}`)}),Q.command("delete <campaign_id>").description("Delete a dialer campaign").action(async(q)=>{let{format:K}=F($.opts());if(await _(U().dialerCampaigns.delete({campaign_id:b("dialer_campaigns",q)})),K==="json"){P({success:!0});return}E("Campaign deleted")});for(let q of["start","pause","resume","stop"])Q.command(`${q} <campaign_id>`).description(`${q[0].toUpperCase()}${q.slice(1)} a campaign`).action(async(K)=>{let{format:W}=F($.opts()),J=await _(U().dialerCampaigns.control({campaign_id:b("dialer_campaigns",K),action:q}));if(W==="json"){P(J);return}E(`Campaign "${J.name}" → ${J.status}`)});Q.command("watch <campaign_id>").description("Watch live campaign stats (streams until Ctrl-C)").action(async(q)=>{let{format:K}=F($.opts()),W=U(),J=new AbortController;process.on("SIGINT",()=>{J.abort()}),await new Promise((G,Y)=>{F1(W.dialerCampaigns.liveStats({campaign_id:b("dialer_campaigns",q)},{signal:J.signal}),{onEvent:(H)=>{if(K==="json"){console.log(JSON.stringify(H));return}let B=new Date().toLocaleTimeString(),M=H.counters,V=H.waiting_capacity?"yes":"no";console.log(`${B} status=${H.status} calling=${H.calling} pending_retry=${H.pending_retry} answered=${M.answered_count} busy=${M.busy_count} failed=${M.failed_count} waiting_capacity=${V}`)},onError:(H)=>{if(H instanceof DOMException&&H.name==="AbortError"){G();return}Y(H)},onSuccess:()=>{G()}})}).catch(Z4)}),Q.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,K)=>{let{format:W,fields:J}=F($.opts()),G=await _(U().dialerAttempts.list({campaign_id:b("dialer_campaigns",q),status:p$(K.status),contact_id:b("dialer_contacts",K.contact),page:Number(K.page),limit:Number(K.limit)}));if(W==="json"){let Y=J?G.items.map((H)=>C(H,J)):G;P(Y);return}y(["ID","#","Phone","Name","Status","Machine","Cause","Started","Duration","Record"],G.items.map((Y)=>({ID:Y.id,"#":Y.attempt_number,Phone:Y.phone_number??"—",Name:Y.contact_name??"—",Status:Y.status??"—",Machine:j0(Y.machine_type),Cause:Y.hangup_cause??"—",Started:Y.started_at?a$(Y.started_at):"—",Duration:Y.duration_s!=null?C$(Y.duration_s*1000):"—",Record:Y.call_record_id??"—"}))),j$(G)})}import{readFile as LD}from"node:fs/promises";var v$=M1(D1(),1);async function x0($){w(`Connecting to ${$}`);let U=DU($)?{tls:{rejectUnauthorized:!1}}:void 0,Q=new WebSocket($,U),q=!1;throw Q.onopen=()=>{q=!0},Q.onmessage=(K)=>{let W=JSON.parse(typeof K.data==="string"?K.data:String(K.data)),J=M$(W)??{},G=i(J.type)??"";switch(G){case"connected":console.log(v$.default.green(` Connected. Type a message and press Enter. Ctrl+C or /quit to exit.
|
|
45
|
+
`)),_D(Q);break;case"message":{let Y=M$(J.message)??{};for(let H of ID(Y))console.log(H);break}case"typing":{if(J.active===!0)process.stdout.write(v$.default.dim(" bot is typing...\r"));else process.stdout.write(" \r");break}case"state":{if(J.status==="ended")console.log(v$.default.dim(`
|
|
46
|
+
Session ended.`)),process.exit(0);break}case"error":console.log(v$.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)w(` Replayed ${Y.length} missed message(s)`);break}default:console.log(v$.default.dim(` [${G}] ${JSON.stringify(J)}`))}},Q.onclose=(K)=>{if(q)w(`
|
|
47
|
+
Disconnected (code=${K.code})`);else x("Failed to connect");process.exit(q?0:1)},Q.onerror=()=>{x("WebSocket error"),process.exit(1)},await new Promise(()=>{}),Error("unreachable")}function I4($,U){return $.replace(/^http/,"ws")+U}var a1=v$.default.cyan(" bot");function DD($,U){let Q=[`${a1} ${$}`];for(let q of m$(U.buttons)){let K=v$.default.dim(`[${String(q.id)}]`);Q.push(` ${K} ${String(q.label)}`)}return Q}function ND($,U){let Q=[`${a1} ${$}`];for(let q of m$(U.sections)){Q.push(` ${v$.default.bold(String(q.title))}`);for(let K of m$(q.items)){let W=v$.default.dim(`[${String(K.id)}]`);Q.push(` ${W} ${String(K.title)}`)}}return Q}function PD($){return m$($.cards).map((U)=>{let Q=i(U.description),q=Q!=null?` — ${Q}`:"";return`${a1} ${v$.default.bold(String(U.title))}${q}`})}function ID($){let U=i($.type)??"",Q=i($.text)??"";switch(U){case"text":return[`${a1} ${Q}`];case"buttons":return DD(Q,$);case"list":return ND(Q,$);case"media":{let q=v$.default.dim(`[${String($.mediaType)}]`),K=typeof $.caption==="string"?` — ${$.caption}`:"";return[`${a1} ${q} ${String($.url)}${K}`]}case"location":{let q=typeof $.label==="string"?` (${$.label})`:"";return[`${a1} ${v$.default.dim("[location]")} ${String($.lat)},${String($.lng)}${q}`]}case"carousel":return PD($);default:{let q=v$.default.dim(`[${U}]`);return[`${a1} ${q} ${JSON.stringify($)}`]}}}function _D($){let U=process.stdin;U.setEncoding("utf-8"),U.resume();let Q="";U.on("data",(q)=>{Q+=q;let K=Q.split(`
|
|
48
|
+
`);Q=K.pop();for(let W of K){let J=W.trim();if(J==="")continue;if(J==="/ping"){$.send(JSON.stringify({type:"ping"})),w(" → ping");continue}if(J==="/quit"||J==="/exit"){$.close();return}console.log(`${v$.default.blue(" you")} ${J}`),$.send(JSON.stringify({type:"message",message:{type:"text",text:J}}))}}),process.once("SIGINT",()=>{w(`
|
|
49
|
+
Closing...`),$.close()})}function XG($,U,Q){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(K,W)=>{let J=f1($.opts()),G=Q(),Y;if(W.editorState!=null){let B=await LD(W.editorState,"utf-8");Y=JSON.parse(B)}if(J!=="json")w("Creating test chat session...");let H=await _(U().testChat.createSession({planId:b("visual_plans",K),editor_state:Y}));if(J==="json"){P({...H,ws_url:I4(G.url,H.wsUrl)});return}E(`Session created: ${H.sessionId}`),await x0(I4(G.url,H.wsUrl))}),q.command("stop <sessionId>").description("Stop an active test chat session").action(async(K)=>{let W=f1($.opts());if(await _(U().testChat.stop({sessionId:K})),W==="json"){P({session_id:K,stopped:!0});return}E(`Session ${K} stopped.`)})}function BG($){let U=$.command("config").description("Manage CLI configuration");U.command("set <key> <value>").description("Set a config value (url, api-key)").action((Q,q)=>{lJ(Q==="api-key"?"apiKey":Q,q),E(`Set ${Q} = ${q}`)}),U.command("get <key>").description("Get a config value (url, api-key)").action((Q)=>{let q=Q==="api-key"?"apiKey":Q,W=XU()[q];if(W==null){w(`(${Q} not set)`);return}console.log(typeof W==="string"?W:JSON.stringify(W))}),U.command("show").description("Show current configuration").action(()=>{let Q=XU();P(Q)})}var c$=M1(D1(),1);function D6($){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 FD($,U){if($>U)return"↑";if($<U)return"↓";return"→"}function vD($){let U=$.avg_score!=null?Number($.avg_score):null,Q=$.previous_avg_score!=null?Number($.previous_avg_score):null,q=U!=null&&U>0?"+":"",K=U!=null?`${q}${U.toFixed(2)}`:"—",W="";if(Q!=null&&U!=null){let J=FD(U,Q);W=` (prev: ${Q>0?"+":""}${Q.toFixed(2)} ${J})`}return` Avg Score: ${K}${W}`}function ZG($,U){let Q=$.command("dashboard").description("Dashboard and monitoring");Q.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:K,fields:W}=F($.opts()),{date_from:J,date_to:G}=P1(q),Y=await _(U().dashboard.metrics({date_from:J,date_to:G}));if(K==="json"){let H=W?C(Y,W):Y;P(H);return}if(console.log(`Period: ${J} → ${G}`),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: ${C$(Y.current.avg_duration_ms)}`)}),D6(Q.command("sentiment").description("Show sentiment distribution for calls")).action(async(q)=>{let{format:K,fields:W}=F($.opts()),{date_from:J,date_to:G}=P1(q),Y=await _(U().dashboard.speechSentiment({date_from:J,date_to:G,visual_plan_id:b("visual_plans",q.plan),channel_id:b("channels",q.phone)}));if(K==="json"){let M=W?C(Y,W):Y;P(M);return}if(console.log(c$.default.bold("Sentiment Overview")),console.log(`Analyzed: ${Y.analyzed_count} calls`),!Y.has_enough_data){w(`
|
|
50
|
+
Not enough data (need ${Y.minimum_required}, have ${Y.analyzed_count})`);return}console.log("");let H=Y.distribution,B=Math.max(H.positive,H.neutral,H.negative,H.mixed);o$(c$.default.green("positive"),H.positive,B),o$(c$.default.yellow("neutral"),H.neutral,B),o$(c$.default.red("negative"),H.negative,B),o$(c$.default.blue("mixed"),H.mixed,B),console.log(""),console.log(vD(Y))}),D6(Q.command("topics").description("Show top discussed topics from call transcriptions")).option("--limit <n>","Max topics to show","15").action(async(q)=>{let{format:K,fields:W}=F($.opts()),{date_from:J,date_to:G}=P1(q),Y=await _(U().dashboard.speechTopics({date_from:J,date_to:G,limit:Number(q.limit),visual_plan_id:b("visual_plans",q.plan),channel_id:b("channels",q.phone)}));if(K==="json"){let B=W?C(Y,W):Y;P(B);return}if(console.log(`${c$.default.bold("Top Topics")} (${Y.analyzed_count} analyzed)`),!Y.has_enough_data||Y.topics.length===0){w(`
|
|
51
|
+
Not enough data.`);return}console.log("");let H=Math.max(...Y.topics.map((B)=>B.call_count));for(let B of Y.topics){let M=Y.analyzed_count>0?Math.round(B.call_count/Y.analyzed_count*100):0,V=N1(B.call_count,H);console.log(` ${B.label.padEnd(16)} ${V} ${B.call_count} calls (${M}%) confidence: ${B.avg_confidence.toFixed(2)}`)}}),D6(Q.command("intents").description("Show detected intents from call transcriptions")).option("--limit <n>","Max intents to show","10").action(async(q)=>{let{format:K,fields:W}=F($.opts()),{date_from:J,date_to:G}=P1(q),Y=await _(U().dashboard.speechIntents({date_from:J,date_to:G,limit:Number(q.limit),visual_plan_id:b("visual_plans",q.plan),channel_id:b("channels",q.phone)}));if(K==="json"){let B=W?C(Y,W):Y;P(B);return}if(console.log(`${c$.default.bold("Detected Intents")} (${Y.analyzed_count} analyzed)`),!Y.has_enough_data||Y.intents.length===0){w(`
|
|
52
|
+
Not enough data.`);return}console.log("");let H=Math.max(...Y.intents.map((B)=>B.call_count));for(let B of Y.intents)o$(B.label,B.call_count,H)}),D6(Q.command("trend").description("Show sentiment trend over time")).option("--granularity <g>","Granularity: hour or day","day").action(async(q)=>{let{format:K}=F($.opts()),{date_from:W,date_to:J}=P1(q,7),G=await _(U().dashboard.speechSentimentTrend({date_from:W,date_to:J,granularity:p$(q.granularity),visual_plan_id:b("visual_plans",q.plan),channel_id:b("channels",q.phone)}));if(K==="json"){P(G);return}if(console.log(c$.default.bold("Sentiment Trend")),G.length===0){w(`
|
|
53
|
+
No data available.`);return}console.log(""),y(["Date","Analyzed","Positive","Neutral","Negative","Avg Score"],G.map((Y)=>{let H=new Date(Y.bucket),B=`${String(H.getDate()).padStart(2,"0")}/${String(H.getMonth()+1).padStart(2,"0")}`,M=Y.avg_score!=null&&Y.avg_score>0?"+":"",V=Y.avg_score!=null?`${M}${Y.avg_score.toFixed(2)}`:"—";return{Date:B,Analyzed:Y.analyzed,Positive:Y.positive,Neutral:Y.neutral,Negative:Y.negative,"Avg Score":V}}))}),D6(Q.command("hourly").description("Show call volume distribution by hour of day")).action(async(q)=>{let{format:K}=F($.opts()),{date_from:W,date_to:J}=P1(q),G=await _(U().dashboard.hourlyDistribution({date_from:W,date_to:J,visual_plan_id:b("visual_plans",q.plan),channel_id:b("channels",q.phone)}));if(K==="json"){P(G);return}if(console.log(c$.default.bold("Hourly Distribution")),G.length===0){w(`
|
|
54
|
+
No data available.`);return}console.log("");let Y=Math.max(...G.map((H)=>H.total));for(let H of G){let B=`${String(H.hour).padStart(2,"0")}:00`,M=N1(H.total,Y),V=H.total===Y?c$.default.yellow(" ← peak"):"";console.log(` ${B} ${M} ${H.total}${V}`)}}),Q.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:K,fields:W}=F($.opts()),{date_from:J,date_to:G}=P1(q),Y=await _(U().dashboard.topPlans({date_from:J,date_to:G,limit:Number(q.limit)}));if(K==="json"){let H=W?Y.map((B)=>C(B,W)):Y;P(H);return}if(console.log(c$.default.bold("Top Plans")),Y.length===0){w(`
|
|
55
|
+
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":C$(H.avg_duration_ms)})))})}function MG($,U){let Q=$.command("channels").description("Channels (SIP, Telegram, etc.)");Q.command("list").description("List channels").option("--limit <n>","Items per page","20").option("--page <n>","Page number","1").option("--type <type>","Filter by channel type").action(async(q)=>{let{format:K,fields:W}=F($.opts()),J=await _(U().channels.list({page:Number(q.page),limit:Number(q.limit),...q.type!=null?{channel_type:q.type}:{}}));if(K==="json"){let G=W?J.items.map((Y)=>C(Y,W)):J;P(G);return}y(["ID","Type","Name","Identifier","Active"],J.items.map((G)=>({ID:G.id,Type:G.channel_type,Name:G.name,Identifier:G.identifier??"—",Active:G.is_active?"yes":"no"}))),j$(J)}),Q.command("assign <channel_id>").description("Assign a channel to a plan").option("--plan <plan_id>","Plan ID to assign").action(()=>d$())}import{readFile as zD}from"node:fs/promises";var VG=1e4;function DG($,U){let Q=$.command("dnc").description("Manage the do-not-call list");Q.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:K,fields:W}=F($.opts()),J=await _(U().dialerDnc.list({page:Number(q.page),limit:Number(q.limit),search:q.search}));if(K==="json"){P(W?J.items.map((G)=>C(G,W)):J);return}y(["ID","Phone","Reason","Added"],J.items.map((G)=>({ID:G.id,Phone:G.phone_number,Reason:G.reason??"—",Added:a$(G.created_at)}))),j$(J)}),Q.command("add <phone>").description("Add a number to the do-not-call list").option("--reason <r>","Reason for the block").action(async(q,K)=>{let{format:W}=F($.opts()),J=await _(U().dialerDnc.add({phone_number:q,reason:K.reason}));if(W==="json"){P(J);return}E(`Added ${J.phone_number} to DNC`)}),Q.command("remove <ids...>").description("Remove do-not-call entries").action(async(q)=>{let{format:K}=F($.opts());if(q.length===1){let J=await _(U().dialerDnc.remove({dnc_id:b("dialer_dnc",q[0])}));if(K==="json"){P(J);return}E("Removed DNC entry");return}let W=await _(U().dialerDnc.bulkRemove({ids:b("dialer_dnc",q)}));if(K==="json"){P(W);return}E(`Removed ${W.removed}`)}),Q.command("check <phone>").description("Check if a number is on the DNC list (exit 0 = listed, 3 = not listed)").action(async(q)=>{let{format:K}=F($.opts()),W=await _(U().dialerDnc.list({page:1,limit:20,search:q})),J=q.replaceAll(/\D/g,""),G=J===""?void 0:W.items.find((Y)=>{let H=String(Y.phone_number).replaceAll(/\D/g,"");return H===J||H.endsWith(J)});if(G!=null){if(K==="json")P(G);else t([{title:"DNC entry",rows:[{label:"ID",value:G.id},{label:"Phone",value:G.phone_number},{label:"Reason",value:G.reason??"—"},{label:"Added",value:new Date(G.created_at).toLocaleString()}]}]);return}if(K==="json")P({listed:!1});else w("Not in DNC list.");process.exit(A.NOT_FOUND)}),Q.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,K)=>{let{format:W}=F($.opts()),G=(await zD(q,"utf-8")).split(/\r\n|\n|\r/).map((B)=>B.trim()).filter((B)=>B.length>0&&!B.startsWith("#"));if(G.length===0)x("No phone numbers found in file"),process.exit(A.USAGE_ERROR);let Y=0,H=0;for(let B=0;B<G.length;B+=VG){let M=G.slice(B,B+VG),V=await _(U().dialerDnc.bulkImport({numbers:M,reason:K.reason}));Y+=V.added,H+=V.skipped}if(W==="json"){P({added:Y,skipped:H});return}E(`Added ${Y}, skipped ${H}`)})}var NG={"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":{},"organization.created":{},"organization.updated":{},"organization.deleted":{},"oauth.authorized":{},"oauth.denied":{},"oauth_grant.revoked":{},"secret.created":{},"secret.updated":{},"secret.deleted":{},"signal.created":{},"signal.updated":{},"signal.deleted":{},"signal.restored":{},"signal.purged":{},"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.role_changed":{},"user.suspended":{},"user.activated":{},"user.removed":{},"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":{},"platform_settings.updated":{},"storage_config.updated":{},"recording_storage.updated":{},"storage_cache.purged":{},"platform_admin.assigned":{},"platform_admin.revoked":{},"platform_admin.owner_transferred":{},"org_settings.updated":{},"org_settings.limits_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":{},"screen_pop.fetched":{retention:"operational"}},kD=Object.keys(NG);var j={};q1(j,{xor:()=>rj,xid:()=>Zj,void:()=>uj,uuidv7:()=>Wj,uuidv6:()=>qj,uuidv4:()=>Qj,uuid:()=>Kj,util:()=>k,url:()=>Jj,uppercase:()=>R4,unknown:()=>W4,union:()=>U8,undefined:()=>gj,ulid:()=>Bj,uint64:()=>Cj,uint32:()=>Rj,tuple:()=>EK,trim:()=>y4,treeifyError:()=>OU,transform:()=>Q8,toUpperCase:()=>f4,toLowerCase:()=>u4,toJSONSchema:()=>A2,templateLiteral:()=>QY,symbol:()=>Ej,superRefine:()=>jQ,success:()=>$Y,stringbool:()=>XY,stringFormat:()=>zj,string:()=>C2,strictObject:()=>cj,startsWith:()=>S4,slugify:()=>h4,size:()=>K4,setErrorMap:()=>KI,set:()=>pj,safeParseAsync:()=>YK,safeParse:()=>jK,safeEncodeAsync:()=>DK,safeEncode:()=>MK,safeDecodeAsync:()=>NK,safeDecode:()=>VK,registry:()=>e0,regexes:()=>r$,regex:()=>b4,refine:()=>GQ,record:()=>gK,readonly:()=>UQ,property:()=>z2,promise:()=>qY,prettifyError:()=>RU,preprocess:()=>ZY,prefault:()=>dK,positive:()=>_2,pipe:()=>r6,partialRecord:()=>ij,parseAsync:()=>GK,parse:()=>JK,overwrite:()=>t$,optional:()=>c6,object:()=>mj,number:()=>IK,nullish:()=>ej,nullable:()=>l6,null:()=>zK,normalize:()=>g4,nonpositive:()=>F2,nonoptional:()=>pK,nonnegative:()=>v2,never:()=>$8,negative:()=>L2,nativeEnum:()=>tj,nanoid:()=>Yj,nan:()=>UY,multipleOf:()=>x1,minSize:()=>K1,minLength:()=>X1,mime:()=>E4,meta:()=>YY,maxSize:()=>A1,maxLength:()=>Q4,map:()=>dj,mac:()=>Dj,lte:()=>g$,lt:()=>$1,lowercase:()=>O4,looseRecord:()=>oj,looseObject:()=>lj,locales:()=>y6,literal:()=>aj,length:()=>q4,lazy:()=>qQ,ksuid:()=>Mj,keyof:()=>hj,jwt:()=>vj,json:()=>BY,iso:()=>l4,ipv6:()=>Nj,ipv4:()=>Vj,intersection:()=>SK,int64:()=>Sj,int32:()=>Oj,int:()=>E2,instanceof:()=>HY,includes:()=>T4,httpUrl:()=>Gj,hostname:()=>kj,hex:()=>wj,hash:()=>xj,guid:()=>Uj,gte:()=>k$,gt:()=>U1,globalRegistry:()=>P$,getErrorMap:()=>QI,function:()=>WY,fromJSONSchema:()=>VY,formatError:()=>w6,float64:()=>bj,float32:()=>Aj,flattenError:()=>k6,file:()=>sj,exactOptional:()=>lK,enum:()=>K8,endsWith:()=>C4,encodeAsync:()=>BK,encode:()=>HK,emoji:()=>jj,email:()=>$j,e164:()=>Fj,discriminatedUnion:()=>nj,describe:()=>jY,decodeAsync:()=>ZK,decode:()=>XK,date:()=>fj,custom:()=>GY,cuid2:()=>Xj,cuid:()=>Hj,core:()=>B1,config:()=>H$,coerce:()=>HQ,codec:()=>KY,clone:()=>z$,cidrv6:()=>Ij,cidrv4:()=>Pj,check:()=>JY,catch:()=>sK,boolean:()=>_K,bigint:()=>Tj,base64url:()=>Lj,base64:()=>_j,array:()=>o6,any:()=>yj,_function:()=>WY,_default:()=>iK,_ZodString:()=>g2,ZodXor:()=>OK,ZodXID:()=>l2,ZodVoid:()=>AK,ZodUnknown:()=>wK,ZodUnion:()=>p6,ZodUndefined:()=>FK,ZodUUID:()=>Q1,ZodURL:()=>n6,ZodULID:()=>c2,ZodType:()=>c,ZodTuple:()=>CK,ZodTransform:()=>mK,ZodTemplateLiteral:()=>KQ,ZodSymbol:()=>LK,ZodSuccess:()=>tK,ZodStringFormat:()=>e,ZodString:()=>n4,ZodSet:()=>uK,ZodRecord:()=>t6,ZodRealError:()=>R$,ZodReadonly:()=>$Q,ZodPromise:()=>WQ,ZodPrefault:()=>oK,ZodPipe:()=>J8,ZodOptional:()=>q8,ZodObject:()=>d6,ZodNumberFormat:()=>J4,ZodNumber:()=>o4,ZodNullable:()=>rK,ZodNull:()=>vK,ZodNonOptional:()=>W8,ZodNever:()=>xK,ZodNanoID:()=>f2,ZodNaN:()=>eK,ZodMap:()=>yK,ZodMAC:()=>PK,ZodLiteral:()=>fK,ZodLazy:()=>QQ,ZodKSUID:()=>r2,ZodJWT:()=>s2,ZodIssueCode:()=>UI,ZodIntersection:()=>TK,ZodISOTime:()=>T2,ZodISODuration:()=>S2,ZodISODateTime:()=>O2,ZodISODate:()=>R2,ZodIPv6:()=>i2,ZodIPv4:()=>n2,ZodGUID:()=>m6,ZodFunction:()=>JQ,ZodFirstPartyTypeKind:()=>YQ,ZodFile:()=>hK,ZodExactOptional:()=>cK,ZodError:()=>eP,ZodEnum:()=>r4,ZodEmoji:()=>u2,ZodEmail:()=>y2,ZodE164:()=>a2,ZodDiscriminatedUnion:()=>RK,ZodDefault:()=>nK,ZodDate:()=>i6,ZodCustomStringFormat:()=>i4,ZodCustom:()=>a6,ZodCodec:()=>G8,ZodCatch:()=>aK,ZodCUID2:()=>m2,ZodCUID:()=>h2,ZodCIDRv6:()=>d2,ZodCIDRv4:()=>o2,ZodBoolean:()=>d4,ZodBigIntFormat:()=>e2,ZodBigInt:()=>p4,ZodBase64URL:()=>t2,ZodBase64:()=>p2,ZodArray:()=>bK,ZodAny:()=>kK,TimePrecision:()=>E7,NEVER:()=>IU,$output:()=>b7,$input:()=>O7,$brand:()=>_U});var B1={};q1(B1,{version:()=>w3,util:()=>k,treeifyError:()=>OU,toJSONSchema:()=>A2,toDotPath:()=>vG,safeParseAsync:()=>SU,safeParse:()=>TU,safeEncodeAsync:()=>qN,safeEncode:()=>KN,safeDecodeAsync:()=>WN,safeDecode:()=>QN,registry:()=>e0,regexes:()=>r$,process:()=>p,prettifyError:()=>RU,parseAsync:()=>R0,parse:()=>O0,meta:()=>V5,locales:()=>y6,isValidJWT:()=>cG,isValidBase64URL:()=>mG,isValidBase64:()=>d3,initializeContext:()=>b1,globalRegistry:()=>P$,globalConfig:()=>N6,formatError:()=>w6,flattenError:()=>k6,finalize:()=>R1,extractDefs:()=>O1,encodeAsync:()=>$N,encode:()=>sD,describe:()=>M5,decodeAsync:()=>UN,decode:()=>eD,createToJSONSchemaMethod:()=>N5,createStandardJSONSchemaMethod:()=>c4,config:()=>H$,clone:()=>z$,_xor:()=>bP,_xid:()=>H2,_void:()=>W5,_uuidv7:()=>q2,_uuidv6:()=>Q2,_uuidv4:()=>K2,_uuid:()=>U2,_url:()=>f6,_uppercase:()=>R4,_unknown:()=>Q5,_union:()=>AP,_undefined:()=>$5,_ulid:()=>Y2,_uint64:()=>s7,_uint32:()=>i7,_tuple:()=>TP,_trim:()=>y4,_transform:()=>fP,_toUpperCase:()=>f4,_toLowerCase:()=>u4,_templateLiteral:()=>dP,_symbol:()=>e7,_superRefine:()=>Z5,_success:()=>rP,_stringbool:()=>D5,_stringFormat:()=>m4,_string:()=>T7,_startsWith:()=>S4,_slugify:()=>h4,_size:()=>K4,_set:()=>EP,_safeParseAsync:()=>w4,_safeParse:()=>k4,_safeEncodeAsync:()=>u0,_safeEncode:()=>g0,_safeDecodeAsync:()=>f0,_safeDecode:()=>y0,_regex:()=>b4,_refine:()=>B5,_record:()=>SP,_readonly:()=>oP,_property:()=>z2,_promise:()=>tP,_positive:()=>_2,_pipe:()=>iP,_parseAsync:()=>z4,_parse:()=>v4,_overwrite:()=>t$,_optional:()=>hP,_number:()=>h7,_nullable:()=>mP,_null:()=>U5,_normalize:()=>g4,_nonpositive:()=>F2,_nonoptional:()=>lP,_nonnegative:()=>v2,_never:()=>q5,_negative:()=>L2,_nativeEnum:()=>yP,_nanoid:()=>J2,_nan:()=>j5,_multipleOf:()=>x1,_minSize:()=>K1,_minLength:()=>X1,_min:()=>k$,_mime:()=>E4,_maxSize:()=>A1,_maxLength:()=>Q4,_max:()=>g$,_map:()=>CP,_mac:()=>C7,_lte:()=>g$,_lt:()=>$1,_lowercase:()=>O4,_literal:()=>uP,_length:()=>q4,_lazy:()=>pP,_ksuid:()=>X2,_jwt:()=>I2,_isoTime:()=>u7,_isoDuration:()=>f7,_isoDateTime:()=>g7,_isoDate:()=>y7,_ipv6:()=>Z2,_ipv4:()=>B2,_intersection:()=>RP,_int64:()=>a7,_int32:()=>n7,_int:()=>c7,_includes:()=>T4,_guid:()=>u6,_gte:()=>k$,_gt:()=>U1,_float64:()=>r7,_float32:()=>l7,_file:()=>H5,_enum:()=>gP,_endsWith:()=>C4,_encodeAsync:()=>C0,_encode:()=>T0,_emoji:()=>W2,_email:()=>$2,_e164:()=>P2,_discriminatedUnion:()=>OP,_default:()=>cP,_decodeAsync:()=>E0,_decode:()=>S0,_date:()=>J5,_custom:()=>X5,_cuid2:()=>j2,_cuid:()=>G2,_coercedString:()=>S7,_coercedNumber:()=>m7,_coercedDate:()=>G5,_coercedBoolean:()=>d7,_coercedBigint:()=>t7,_cidrv6:()=>V2,_cidrv4:()=>M2,_check:()=>aG,_catch:()=>nP,_boolean:()=>o7,_bigint:()=>p7,_base64url:()=>N2,_base64:()=>D2,_array:()=>Y5,_any:()=>K5,TimePrecision:()=>E7,NEVER:()=>IU,JSONSchemaGenerator:()=>UK,JSONSchema:()=>sG,Doc:()=>l0,$output:()=>b7,$input:()=>O7,$constructor:()=>D,$brand:()=>_U,$ZodXor:()=>B9,$ZodXID:()=>y3,$ZodVoid:()=>j9,$ZodUnknown:()=>J9,$ZodUnion:()=>R6,$ZodUndefined:()=>Q9,$ZodUUID:()=>b3,$ZodURL:()=>R3,$ZodULID:()=>g3,$ZodType:()=>u,$ZodTuple:()=>a0,$ZodTransform:()=>L9,$ZodTemplateLiteral:()=>T9,$ZodSymbol:()=>K9,$ZodSuccess:()=>x9,$ZodStringFormat:()=>s,$ZodString:()=>U4,$ZodSet:()=>N9,$ZodRegistry:()=>R7,$ZodRecord:()=>V9,$ZodRealError:()=>O$,$ZodReadonly:()=>R9,$ZodPromise:()=>C9,$ZodPrefault:()=>k9,$ZodPipe:()=>O9,$ZodOptional:()=>s0,$ZodObjectJIT:()=>X9,$ZodObject:()=>nG,$ZodNumberFormat:()=>$9,$ZodNumber:()=>p0,$ZodNullable:()=>v9,$ZodNull:()=>q9,$ZodNonOptional:()=>w9,$ZodNever:()=>G9,$ZodNanoID:()=>S3,$ZodNaN:()=>b9,$ZodMap:()=>D9,$ZodMAC:()=>n3,$ZodLiteral:()=>I9,$ZodLazy:()=>E9,$ZodKSUID:()=>u3,$ZodJWT:()=>s3,$ZodIntersection:()=>M9,$ZodISOTime:()=>m3,$ZodISODuration:()=>c3,$ZodISODateTime:()=>f3,$ZodISODate:()=>h3,$ZodIPv6:()=>r3,$ZodIPv4:()=>l3,$ZodGUID:()=>A3,$ZodFunction:()=>S9,$ZodFile:()=>_9,$ZodExactOptional:()=>F9,$ZodError:()=>z6,$ZodEnum:()=>P9,$ZodEncodeError:()=>s1,$ZodEmoji:()=>T3,$ZodEmail:()=>O3,$ZodE164:()=>a3,$ZodDiscriminatedUnion:()=>Z9,$ZodDefault:()=>z9,$ZodDate:()=>Y9,$ZodCustomStringFormat:()=>e3,$ZodCustom:()=>g9,$ZodCodec:()=>T6,$ZodCheckUpperCase:()=>I3,$ZodCheckStringFormat:()=>x4,$ZodCheckStartsWith:()=>L3,$ZodCheckSizeEquals:()=>Z3,$ZodCheckRegex:()=>N3,$ZodCheckProperty:()=>v3,$ZodCheckOverwrite:()=>k3,$ZodCheckNumberFormat:()=>Y3,$ZodCheckMultipleOf:()=>j3,$ZodCheckMinSize:()=>B3,$ZodCheckMinLength:()=>V3,$ZodCheckMimeType:()=>z3,$ZodCheckMaxSize:()=>X3,$ZodCheckMaxLength:()=>M3,$ZodCheckLowerCase:()=>P3,$ZodCheckLessThan:()=>m0,$ZodCheckLengthEquals:()=>D3,$ZodCheckIncludes:()=>_3,$ZodCheckGreaterThan:()=>c0,$ZodCheckEndsWith:()=>F3,$ZodCheckBigIntFormat:()=>H3,$ZodCheck:()=>$$,$ZodCatch:()=>A9,$ZodCUID2:()=>E3,$ZodCUID:()=>C3,$ZodCIDRv6:()=>o3,$ZodCIDRv4:()=>i3,$ZodBoolean:()=>O6,$ZodBigIntFormat:()=>U9,$ZodBigInt:()=>t0,$ZodBase64URL:()=>t3,$ZodBase64:()=>p3,$ZodAsyncError:()=>e$,$ZodArray:()=>H9,$ZodAny:()=>W9});var IU=Object.freeze({status:"aborted"});function D($,U,Q){function q(G,Y){if(!G._zod)Object.defineProperty(G,"_zod",{value:{def:Y,constr:J,traits:new Set},enumerable:!1});if(G._zod.traits.has($))return;G._zod.traits.add($),U(G,Y);let H=J.prototype,B=Object.keys(H);for(let M=0;M<B.length;M++){let V=B[M];if(!(V in G))G[V]=H[V].bind(G)}}let K=Q?.Parent??Object;class W extends K{}Object.defineProperty(W,"name",{value:$});function J(G){var Y;let H=Q?.Parent?new W:this;q(H,G),(Y=H._zod).deferred??(Y.deferred=[]);for(let B of H._zod.deferred)B();return H}return Object.defineProperty(J,"init",{value:q}),Object.defineProperty(J,Symbol.hasInstance,{value:(G)=>{if(Q?.Parent&&G instanceof Q.Parent)return!0;return G?._zod?.traits?.has($)}}),Object.defineProperty(J,"name",{value:$}),J}var _U=Symbol("zod_brand");class e$ extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class s1 extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}}var N6={};function H$($){if($)Object.assign(N6,$);return N6}var k={};q1(k,{unwrapMessage:()=>P6,uint8ArrayToHex:()=>tD,uint8ArrayToBase64url:()=>dD,uint8ArrayToBase64:()=>_G,stringifyPrimitive:()=>v,slugify:()=>vU,shallowClone:()=>kU,safeExtend:()=>cD,required:()=>nD,randomString:()=>ED,propertyKeyTypes:()=>L6,promiseAllObject:()=>CD,primitiveTypes:()=>wU,prefixIssues:()=>E$,pick:()=>fD,partial:()=>rD,parsedType:()=>z,optionalKeys:()=>xU,omit:()=>hD,objectClone:()=>RD,numKeys:()=>gD,nullish:()=>v1,normalizeParams:()=>O,mergeDefs:()=>H1,merge:()=>lD,jsonStringifyReplacer:()=>_4,joinValues:()=>N,issue:()=>F4,isPlainObject:()=>k1,isObject:()=>e1,hexToUint8Array:()=>pD,getSizableOrigin:()=>F6,getParsedType:()=>yD,getLengthableOrigin:()=>v6,getEnumValues:()=>I6,getElementAtPath:()=>SD,floatSafeRemainder:()=>FU,finalizeIssue:()=>b$,extend:()=>mD,escapeRegex:()=>l$,esc:()=>A0,defineLazy:()=>l,createTransparentProxy:()=>uD,cloneDef:()=>TD,clone:()=>z$,cleanRegex:()=>_6,cleanEnum:()=>iD,captureStackTrace:()=>b0,cached:()=>L4,base64urlToUint8Array:()=>oD,base64ToUint8Array:()=>IG,assignProp:()=>z1,assertNotEqual:()=>xD,assertNever:()=>bD,assertIs:()=>AD,assertEqual:()=>wD,assert:()=>OD,allowsEval:()=>zU,aborted:()=>w1,NUMBER_FORMAT_RANGES:()=>AU,Class:()=>LG,BIGINT_FORMAT_RANGES:()=>bU});function wD($){return $}function xD($){return $}function AD($){}function bD($){throw Error("Unexpected value in exhaustive check")}function OD($){}function I6($){let U=Object.values($).filter((q)=>typeof q==="number");return Object.entries($).filter(([q,K])=>U.indexOf(+q)===-1).map(([q,K])=>K)}function N($,U="|"){return $.map((Q)=>v(Q)).join(U)}function _4($,U){if(typeof U==="bigint")return U.toString();return U}function L4($){return{get value(){{let Q=$();return Object.defineProperty(this,"value",{value:Q}),Q}throw Error("cached value already set")}}}function v1($){return $===null||$===void 0}function _6($){let U=$.startsWith("^")?1:0,Q=$.endsWith("$")?$.length-1:$.length;return $.slice(U,Q)}function FU($,U){let Q=($.toString().split(".")[1]||"").length,q=U.toString(),K=(q.split(".")[1]||"").length;if(K===0&&/\d?e-\d?/.test(q)){let Y=q.match(/\d?e-(\d?)/);if(Y?.[1])K=Number.parseInt(Y[1])}let W=Q>K?Q:K,J=Number.parseInt($.toFixed(W).replace(".","")),G=Number.parseInt(U.toFixed(W).replace(".",""));return J%G/10**W}var PG=Symbol("evaluating");function l($,U,Q){let q=void 0;Object.defineProperty($,U,{get(){if(q===PG)return;if(q===void 0)q=PG,q=Q();return q},set(K){Object.defineProperty($,U,{value:K})},configurable:!0})}function RD($){return Object.create(Object.getPrototypeOf($),Object.getOwnPropertyDescriptors($))}function z1($,U,Q){Object.defineProperty($,U,{value:Q,writable:!0,enumerable:!0,configurable:!0})}function H1(...$){let U={};for(let Q of $){let q=Object.getOwnPropertyDescriptors(Q);Object.assign(U,q)}return Object.defineProperties({},U)}function TD($){return H1($._zod.def)}function SD($,U){if(!U)return $;return U.reduce((Q,q)=>Q?.[q],$)}function CD($){let U=Object.keys($),Q=U.map((q)=>$[q]);return Promise.all(Q).then((q)=>{let K={};for(let W=0;W<U.length;W++)K[U[W]]=q[W];return K})}function ED($=10){let Q="";for(let q=0;q<$;q++)Q+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return Q}function A0($){return JSON.stringify($)}function vU($){return $.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var b0="captureStackTrace"in Error?Error.captureStackTrace:(...$)=>{};function e1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var zU=L4(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});function k1($){if(e1($)===!1)return!1;let U=$.constructor;if(U===void 0)return!0;if(typeof U!=="function")return!0;let Q=U.prototype;if(e1(Q)===!1)return!1;if(Object.prototype.hasOwnProperty.call(Q,"isPrototypeOf")===!1)return!1;return!0}function kU($){if(k1($))return{...$};if(Array.isArray($))return[...$];return $}function gD($){let U=0;for(let Q in $)if(Object.prototype.hasOwnProperty.call($,Q))U++;return U}var yD=($)=>{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}`)}},L6=new Set(["string","number","symbol"]),wU=new Set(["string","number","bigint","boolean","symbol","undefined"]);function l$($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function z$($,U,Q){let q=new $._zod.constr(U??$._zod.def);if(!U||Q?.parent)q._zod.parent=$;return q}function O($){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 uD($){let U;return new Proxy({},{get(Q,q,K){return U??(U=$()),Reflect.get(U,q,K)},set(Q,q,K,W){return U??(U=$()),Reflect.set(U,q,K,W)},has(Q,q){return U??(U=$()),Reflect.has(U,q)},deleteProperty(Q,q){return U??(U=$()),Reflect.deleteProperty(U,q)},ownKeys(Q){return U??(U=$()),Reflect.ownKeys(U)},getOwnPropertyDescriptor(Q,q){return U??(U=$()),Reflect.getOwnPropertyDescriptor(U,q)},defineProperty(Q,q,K){return U??(U=$()),Reflect.defineProperty(U,q,K)}})}function v($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function xU($){return Object.keys($).filter((U)=>{return $[U]._zod.optin==="optional"&&$[U]._zod.optout==="optional"})}var AU={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]},bU={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function fD($,U){let Q=$._zod.def,q=Q.checks;if(q&&q.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let W=H1($._zod.def,{get shape(){let J={};for(let G in U){if(!(G in Q.shape))throw Error(`Unrecognized key: "${G}"`);if(!U[G])continue;J[G]=Q.shape[G]}return z1(this,"shape",J),J},checks:[]});return z$($,W)}function hD($,U){let Q=$._zod.def,q=Q.checks;if(q&&q.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let W=H1($._zod.def,{get shape(){let J={...$._zod.def.shape};for(let G in U){if(!(G in Q.shape))throw Error(`Unrecognized key: "${G}"`);if(!U[G])continue;delete J[G]}return z1(this,"shape",J),J},checks:[]});return z$($,W)}function mD($,U){if(!k1(U))throw Error("Invalid input to extend: expected a plain object");let Q=$._zod.def.checks;if(Q&&Q.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 K=H1($._zod.def,{get shape(){let W={...$._zod.def.shape,...U};return z1(this,"shape",W),W}});return z$($,K)}function cD($,U){if(!k1(U))throw Error("Invalid input to safeExtend: expected a plain object");let Q=H1($._zod.def,{get shape(){let q={...$._zod.def.shape,...U};return z1(this,"shape",q),q}});return z$($,Q)}function lD($,U){let Q=H1($._zod.def,{get shape(){let q={...$._zod.def.shape,...U._zod.def.shape};return z1(this,"shape",q),q},get catchall(){return U._zod.def.catchall},checks:[]});return z$($,Q)}function rD($,U,Q){let K=U._zod.def.checks;if(K&&K.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let J=H1(U._zod.def,{get shape(){let G=U._zod.def.shape,Y={...G};if(Q)for(let H in Q){if(!(H in G))throw Error(`Unrecognized key: "${H}"`);if(!Q[H])continue;Y[H]=$?new $({type:"optional",innerType:G[H]}):G[H]}else for(let H in G)Y[H]=$?new $({type:"optional",innerType:G[H]}):G[H];return z1(this,"shape",Y),Y},checks:[]});return z$(U,J)}function nD($,U,Q){let q=H1(U._zod.def,{get shape(){let K=U._zod.def.shape,W={...K};if(Q)for(let J in Q){if(!(J in W))throw Error(`Unrecognized key: "${J}"`);if(!Q[J])continue;W[J]=new $({type:"nonoptional",innerType:K[J]})}else for(let J in K)W[J]=new $({type:"nonoptional",innerType:K[J]});return z1(this,"shape",W),W}});return z$(U,q)}function w1($,U=0){if($.aborted===!0)return!0;for(let Q=U;Q<$.issues.length;Q++)if($.issues[Q]?.continue!==!0)return!0;return!1}function E$($,U){return U.map((Q)=>{var q;return(q=Q).path??(q.path=[]),Q.path.unshift($),Q})}function P6($){return typeof $==="string"?$:$?.message}function b$($,U,Q){let q={...$,path:$.path??[]};if(!$.message){let K=P6($.inst?._zod.def?.error?.($))??P6(U?.error?.($))??P6(Q.customError?.($))??P6(Q.localeError?.($))??"Invalid input";q.message=K}if(delete q.inst,delete q.continue,!U?.reportInput)delete q.input;return q}function F6($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function v6($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function z($){let U=typeof $;switch(U){case"number":return Number.isNaN($)?"nan":"number";case"object":{if($===null)return"null";if(Array.isArray($))return"array";let Q=$;if(Q&&Object.getPrototypeOf(Q)!==Object.prototype&&"constructor"in Q&&Q.constructor)return Q.constructor.name}}return U}function F4(...$){let[U,Q,q]=$;if(typeof U==="string")return{message:U,code:"custom",input:Q,inst:q};return{...U}}function iD($){return Object.entries($).filter(([U,Q])=>{return Number.isNaN(Number.parseInt(U,10))}).map((U)=>U[1])}function IG($){let U=atob($),Q=new Uint8Array(U.length);for(let q=0;q<U.length;q++)Q[q]=U.charCodeAt(q);return Q}function _G($){let U="";for(let Q=0;Q<$.length;Q++)U+=String.fromCharCode($[Q]);return btoa(U)}function oD($){let U=$.replace(/-/g,"+").replace(/_/g,"/"),Q="=".repeat((4-U.length%4)%4);return IG(U+Q)}function dD($){return _G($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function pD($){let U=$.replace(/^0x/,"");if(U.length%2!==0)throw Error("Invalid hex string length");let Q=new Uint8Array(U.length/2);for(let q=0;q<U.length;q+=2)Q[q/2]=Number.parseInt(U.slice(q,q+2),16);return Q}function tD($){return Array.from($).map((U)=>U.toString(16).padStart(2,"0")).join("")}class LG{constructor(...$){}}var FG=($,U)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:U,enumerable:!1}),$.message=JSON.stringify(U,_4,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},z6=D("$ZodError",FG),O$=D("$ZodError",FG,{Parent:Error});function k6($,U=(Q)=>Q.message){let Q={},q=[];for(let K of $.issues)if(K.path.length>0)Q[K.path[0]]=Q[K.path[0]]||[],Q[K.path[0]].push(U(K));else q.push(U(K));return{formErrors:q,fieldErrors:Q}}function w6($,U=(Q)=>Q.message){let Q={_errors:[]},q=(K)=>{for(let W of K.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)Q._errors.push(U(W));else{let J=Q,G=0;while(G<W.path.length){let Y=W.path[G];if(G!==W.path.length-1)J[Y]=J[Y]||{_errors:[]};else J[Y]=J[Y]||{_errors:[]},J[Y]._errors.push(U(W));J=J[Y],G++}}};return q($),Q}function OU($,U=(Q)=>Q.message){let Q={errors:[]},q=(K,W=[])=>{var J,G;for(let Y of K.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){Q.errors.push(U(Y));continue}let B=Q,M=0;while(M<H.length){let V=H[M],L=M===H.length-1;if(typeof V==="string")B.properties??(B.properties={}),(J=B.properties)[V]??(J[V]={errors:[]}),B=B.properties[V];else B.items??(B.items=[]),(G=B.items)[V]??(G[V]={errors:[]}),B=B.items[V];if(L)B.errors.push(U(Y));M++}}};return q($),Q}function vG($){let U=[],Q=$.map((q)=>typeof q==="object"?q.key:q);for(let q of Q)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 RU($){let U=[],Q=[...$.issues].sort((q,K)=>(q.path??[]).length-(K.path??[]).length);for(let q of Q)if(U.push(`✖ ${q.message}`),q.path?.length)U.push(` → at ${vG(q.path)}`);return U.join(`
|
|
56
|
+
`)}var v4=($)=>(U,Q,q,K)=>{let W=q?Object.assign(q,{async:!1}):{async:!1},J=U._zod.run({value:Q,issues:[]},W);if(J instanceof Promise)throw new e$;if(J.issues.length){let G=new(K?.Err??$)(J.issues.map((Y)=>b$(Y,W,H$())));throw b0(G,K?.callee),G}return J.value},O0=v4(O$),z4=($)=>async(U,Q,q,K)=>{let W=q?Object.assign(q,{async:!0}):{async:!0},J=U._zod.run({value:Q,issues:[]},W);if(J instanceof Promise)J=await J;if(J.issues.length){let G=new(K?.Err??$)(J.issues.map((Y)=>b$(Y,W,H$())));throw b0(G,K?.callee),G}return J.value},R0=z4(O$),k4=($)=>(U,Q,q)=>{let K=q?{...q,async:!1}:{async:!1},W=U._zod.run({value:Q,issues:[]},K);if(W instanceof Promise)throw new e$;return W.issues.length?{success:!1,error:new($??z6)(W.issues.map((J)=>b$(J,K,H$())))}:{success:!0,data:W.value}},TU=k4(O$),w4=($)=>async(U,Q,q)=>{let K=q?Object.assign(q,{async:!0}):{async:!0},W=U._zod.run({value:Q,issues:[]},K);if(W instanceof Promise)W=await W;return W.issues.length?{success:!1,error:new $(W.issues.map((J)=>b$(J,K,H$())))}:{success:!0,data:W.value}},SU=w4(O$),T0=($)=>(U,Q,q)=>{let K=q?Object.assign(q,{direction:"backward"}):{direction:"backward"};return v4($)(U,Q,K)},sD=T0(O$),S0=($)=>(U,Q,q)=>{return v4($)(U,Q,q)},eD=S0(O$),C0=($)=>async(U,Q,q)=>{let K=q?Object.assign(q,{direction:"backward"}):{direction:"backward"};return z4($)(U,Q,K)},$N=C0(O$),E0=($)=>async(U,Q,q)=>{return z4($)(U,Q,q)},UN=E0(O$),g0=($)=>(U,Q,q)=>{let K=q?Object.assign(q,{direction:"backward"}):{direction:"backward"};return k4($)(U,Q,K)},KN=g0(O$),y0=($)=>(U,Q,q)=>{return k4($)(U,Q,q)},QN=y0(O$),u0=($)=>async(U,Q,q)=>{let K=q?Object.assign(q,{direction:"backward"}):{direction:"backward"};return w4($)(U,Q,K)},qN=u0(O$),f0=($)=>async(U,Q,q)=>{return w4($)(U,Q,q)},WN=f0(O$);var r$={};q1(r$,{xid:()=>yU,uuid7:()=>YN,uuid6:()=>jN,uuid4:()=>GN,uuid:()=>$4,uppercase:()=>G3,unicodeEmail:()=>zG,undefined:()=>W3,ulid:()=>gU,time:()=>sU,string:()=>$3,sha512_hex:()=>ON,sha512_base64url:()=>TN,sha512_base64:()=>RN,sha384_hex:()=>xN,sha384_base64url:()=>bN,sha384_base64:()=>AN,sha256_hex:()=>zN,sha256_base64url:()=>wN,sha256_base64:()=>kN,sha1_hex:()=>LN,sha1_base64url:()=>vN,sha1_base64:()=>FN,rfc5322Email:()=>XN,number:()=>x6,null:()=>q3,nanoid:()=>fU,md5_hex:()=>PN,md5_base64url:()=>_N,md5_base64:()=>IN,mac:()=>iU,lowercase:()=>J3,ksuid:()=>uU,ipv6:()=>nU,ipv4:()=>rU,integer:()=>K3,idnEmail:()=>BN,html5Email:()=>HN,hostname:()=>VN,hex:()=>NN,guid:()=>mU,extendedDuration:()=>JN,emoji:()=>lU,email:()=>cU,e164:()=>tU,duration:()=>hU,domain:()=>DN,datetime:()=>eU,date:()=>aU,cuid2:()=>EU,cuid:()=>CU,cidrv6:()=>dU,cidrv4:()=>oU,browserEmail:()=>ZN,boolean:()=>Q3,bigint:()=>U3,base64url:()=>h0,base64:()=>pU});var CU=/^[cC][^\s-]{8,}$/,EU=/^[0-9a-z]+$/,gU=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,yU=/^[0-9a-vA-V]{20}$/,uU=/^[A-Za-z0-9]{27}$/,fU=/^[a-zA-Z0-9_-]{21}$/,hU=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,JN=/^[-+]?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)?)??$/,mU=/^([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})$/,$4=($)=>{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})$`)},GN=$4(4),jN=$4(6),YN=$4(7),cU=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,HN=/^[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])?)*$/,XN=/^(([^<>()\[\]\\.,;:\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,}))$/,zG=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,BN=zG,ZN=/^[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])?)*$/,MN="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function lU(){return new RegExp(MN,"u")}var rU=/^(?:(?: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])$/,nU=/^(([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}|:))$/,iU=($)=>{let U=l$($??":");return new RegExp(`^(?:[0-9A-F]{2}${U}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${U}){5}[0-9a-f]{2}$`)},oU=/^((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])$/,dU=/^(([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])$/,pU=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,h0=/^[A-Za-z0-9_-]*$/,VN=/^(?=.{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])?)*\.?$/,DN=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,tU=/^\+[1-9]\d{6,14}$/,kG="(?:(?:\\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])))",aU=new RegExp(`^${kG}$`);function wG($){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(`^${wG($)}$`)}function eU($){let U=wG({precision:$.precision}),Q=["Z"];if($.local)Q.push("");if($.offset)Q.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let q=`${U}(?:${Q.join("|")})`;return new RegExp(`^${kG}T(?:${q})$`)}var $3=($)=>{let U=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${U}$`)},U3=/^-?\d+n?$/,K3=/^-?\d+$/,x6=/^-?\d+(?:\.\d+)?$/,Q3=/^(?:true|false)$/i,q3=/^null$/i;var W3=/^undefined$/i;var J3=/^[^A-Z]*$/,G3=/^[^a-z]*$/,NN=/^[0-9a-fA-F]*$/;function A6($,U){return new RegExp(`^[A-Za-z0-9+/]{${$}}${U}$`)}function b6($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var PN=/^[0-9a-fA-F]{32}$/,IN=A6(22,"=="),_N=b6(22),LN=/^[0-9a-fA-F]{40}$/,FN=A6(27,"="),vN=b6(27),zN=/^[0-9a-fA-F]{64}$/,kN=A6(43,"="),wN=b6(43),xN=/^[0-9a-fA-F]{96}$/,AN=A6(64,""),bN=b6(64),ON=/^[0-9a-fA-F]{128}$/,RN=A6(86,"=="),TN=b6(86);var $$=D("$ZodCheck",($,U)=>{var Q;$._zod??($._zod={}),$._zod.def=U,(Q=$._zod).onattach??(Q.onattach=[])}),AG={number:"number",bigint:"bigint",object:"date"},m0=D("$ZodCheckLessThan",($,U)=>{$$.init($,U);let Q=AG[typeof U.value];$._zod.onattach.push((q)=>{let K=q._zod.bag,W=(U.inclusive?K.maximum:K.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(U.value<W)if(U.inclusive)K.maximum=U.value;else K.exclusiveMaximum=U.value}),$._zod.check=(q)=>{if(U.inclusive?q.value<=U.value:q.value<U.value)return;q.issues.push({origin:Q,code:"too_big",maximum:typeof U.value==="object"?U.value.getTime():U.value,input:q.value,inclusive:U.inclusive,inst:$,continue:!U.abort})}}),c0=D("$ZodCheckGreaterThan",($,U)=>{$$.init($,U);let Q=AG[typeof U.value];$._zod.onattach.push((q)=>{let K=q._zod.bag,W=(U.inclusive?K.minimum:K.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(U.value>W)if(U.inclusive)K.minimum=U.value;else K.exclusiveMinimum=U.value}),$._zod.check=(q)=>{if(U.inclusive?q.value>=U.value:q.value>U.value)return;q.issues.push({origin:Q,code:"too_small",minimum:typeof U.value==="object"?U.value.getTime():U.value,input:q.value,inclusive:U.inclusive,inst:$,continue:!U.abort})}}),j3=D("$ZodCheckMultipleOf",($,U)=>{$$.init($,U),$._zod.onattach.push((Q)=>{var q;(q=Q._zod.bag).multipleOf??(q.multipleOf=U.value)}),$._zod.check=(Q)=>{if(typeof Q.value!==typeof U.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof Q.value==="bigint"?Q.value%U.value===BigInt(0):FU(Q.value,U.value)===0)return;Q.issues.push({origin:typeof Q.value,code:"not_multiple_of",divisor:U.value,input:Q.value,inst:$,continue:!U.abort})}}),Y3=D("$ZodCheckNumberFormat",($,U)=>{$$.init($,U),U.format=U.format||"float64";let Q=U.format?.includes("int"),q=Q?"int":"number",[K,W]=AU[U.format];$._zod.onattach.push((J)=>{let G=J._zod.bag;if(G.format=U.format,G.minimum=K,G.maximum=W,Q)G.pattern=K3}),$._zod.check=(J)=>{let G=J.value;if(Q){if(!Number.isInteger(G)){J.issues.push({expected:q,format:U.format,code:"invalid_type",continue:!1,input:G,inst:$});return}if(!Number.isSafeInteger(G)){if(G>0)J.issues.push({input:G,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:G,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(G<K)J.issues.push({origin:"number",input:G,code:"too_small",minimum:K,inclusive:!0,inst:$,continue:!U.abort});if(G>W)J.issues.push({origin:"number",input:G,code:"too_big",maximum:W,inclusive:!0,inst:$,continue:!U.abort})}}),H3=D("$ZodCheckBigIntFormat",($,U)=>{$$.init($,U);let[Q,q]=bU[U.format];$._zod.onattach.push((K)=>{let W=K._zod.bag;W.format=U.format,W.minimum=Q,W.maximum=q}),$._zod.check=(K)=>{let W=K.value;if(W<Q)K.issues.push({origin:"bigint",input:W,code:"too_small",minimum:Q,inclusive:!0,inst:$,continue:!U.abort});if(W>q)K.issues.push({origin:"bigint",input:W,code:"too_big",maximum:q,inclusive:!0,inst:$,continue:!U.abort})}}),X3=D("$ZodCheckMaxSize",($,U)=>{var Q;$$.init($,U),(Q=$._zod.def).when??(Q.when=(q)=>{let K=q.value;return!v1(K)&&K.size!==void 0}),$._zod.onattach.push((q)=>{let K=q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(U.maximum<K)q._zod.bag.maximum=U.maximum}),$._zod.check=(q)=>{let K=q.value;if(K.size<=U.maximum)return;q.issues.push({origin:F6(K),code:"too_big",maximum:U.maximum,inclusive:!0,input:K,inst:$,continue:!U.abort})}}),B3=D("$ZodCheckMinSize",($,U)=>{var Q;$$.init($,U),(Q=$._zod.def).when??(Q.when=(q)=>{let K=q.value;return!v1(K)&&K.size!==void 0}),$._zod.onattach.push((q)=>{let K=q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(U.minimum>K)q._zod.bag.minimum=U.minimum}),$._zod.check=(q)=>{let K=q.value;if(K.size>=U.minimum)return;q.issues.push({origin:F6(K),code:"too_small",minimum:U.minimum,inclusive:!0,input:K,inst:$,continue:!U.abort})}}),Z3=D("$ZodCheckSizeEquals",($,U)=>{var Q;$$.init($,U),(Q=$._zod.def).when??(Q.when=(q)=>{let K=q.value;return!v1(K)&&K.size!==void 0}),$._zod.onattach.push((q)=>{let K=q._zod.bag;K.minimum=U.size,K.maximum=U.size,K.size=U.size}),$._zod.check=(q)=>{let K=q.value,W=K.size;if(W===U.size)return;let J=W>U.size;q.issues.push({origin:F6(K),...J?{code:"too_big",maximum:U.size}:{code:"too_small",minimum:U.size},inclusive:!0,exact:!0,input:q.value,inst:$,continue:!U.abort})}}),M3=D("$ZodCheckMaxLength",($,U)=>{var Q;$$.init($,U),(Q=$._zod.def).when??(Q.when=(q)=>{let K=q.value;return!v1(K)&&K.length!==void 0}),$._zod.onattach.push((q)=>{let K=q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(U.maximum<K)q._zod.bag.maximum=U.maximum}),$._zod.check=(q)=>{let K=q.value;if(K.length<=U.maximum)return;let J=v6(K);q.issues.push({origin:J,code:"too_big",maximum:U.maximum,inclusive:!0,input:K,inst:$,continue:!U.abort})}}),V3=D("$ZodCheckMinLength",($,U)=>{var Q;$$.init($,U),(Q=$._zod.def).when??(Q.when=(q)=>{let K=q.value;return!v1(K)&&K.length!==void 0}),$._zod.onattach.push((q)=>{let K=q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(U.minimum>K)q._zod.bag.minimum=U.minimum}),$._zod.check=(q)=>{let K=q.value;if(K.length>=U.minimum)return;let J=v6(K);q.issues.push({origin:J,code:"too_small",minimum:U.minimum,inclusive:!0,input:K,inst:$,continue:!U.abort})}}),D3=D("$ZodCheckLengthEquals",($,U)=>{var Q;$$.init($,U),(Q=$._zod.def).when??(Q.when=(q)=>{let K=q.value;return!v1(K)&&K.length!==void 0}),$._zod.onattach.push((q)=>{let K=q._zod.bag;K.minimum=U.length,K.maximum=U.length,K.length=U.length}),$._zod.check=(q)=>{let K=q.value,W=K.length;if(W===U.length)return;let J=v6(K),G=W>U.length;q.issues.push({origin:J,...G?{code:"too_big",maximum:U.length}:{code:"too_small",minimum:U.length},inclusive:!0,exact:!0,input:q.value,inst:$,continue:!U.abort})}}),x4=D("$ZodCheckStringFormat",($,U)=>{var Q,q;if($$.init($,U),$._zod.onattach.push((K)=>{let W=K._zod.bag;if(W.format=U.format,U.pattern)W.patterns??(W.patterns=new Set),W.patterns.add(U.pattern)}),U.pattern)(Q=$._zod).check??(Q.check=(K)=>{if(U.pattern.lastIndex=0,U.pattern.test(K.value))return;K.issues.push({origin:"string",code:"invalid_format",format:U.format,input:K.value,...U.pattern?{pattern:U.pattern.toString()}:{},inst:$,continue:!U.abort})});else(q=$._zod).check??(q.check=()=>{})}),N3=D("$ZodCheckRegex",($,U)=>{x4.init($,U),$._zod.check=(Q)=>{if(U.pattern.lastIndex=0,U.pattern.test(Q.value))return;Q.issues.push({origin:"string",code:"invalid_format",format:"regex",input:Q.value,pattern:U.pattern.toString(),inst:$,continue:!U.abort})}}),P3=D("$ZodCheckLowerCase",($,U)=>{U.pattern??(U.pattern=J3),x4.init($,U)}),I3=D("$ZodCheckUpperCase",($,U)=>{U.pattern??(U.pattern=G3),x4.init($,U)}),_3=D("$ZodCheckIncludes",($,U)=>{$$.init($,U);let Q=l$(U.includes),q=new RegExp(typeof U.position==="number"?`^.{${U.position}}${Q}`:Q);U.pattern=q,$._zod.onattach.push((K)=>{let W=K._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add(q)}),$._zod.check=(K)=>{if(K.value.includes(U.includes,U.position))return;K.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:U.includes,input:K.value,inst:$,continue:!U.abort})}}),L3=D("$ZodCheckStartsWith",($,U)=>{$$.init($,U);let Q=new RegExp(`^${l$(U.prefix)}.*`);U.pattern??(U.pattern=Q),$._zod.onattach.push((q)=>{let K=q._zod.bag;K.patterns??(K.patterns=new Set),K.patterns.add(Q)}),$._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})}}),F3=D("$ZodCheckEndsWith",($,U)=>{$$.init($,U);let Q=new RegExp(`.*${l$(U.suffix)}$`);U.pattern??(U.pattern=Q),$._zod.onattach.push((q)=>{let K=q._zod.bag;K.patterns??(K.patterns=new Set),K.patterns.add(Q)}),$._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 xG($,U,Q){if($.issues.length)U.issues.push(...E$(Q,$.issues))}var v3=D("$ZodCheckProperty",($,U)=>{$$.init($,U),$._zod.check=(Q)=>{let q=U.schema._zod.run({value:Q.value[U.property],issues:[]},{});if(q instanceof Promise)return q.then((K)=>xG(K,Q,U.property));xG(q,Q,U.property);return}}),z3=D("$ZodCheckMimeType",($,U)=>{$$.init($,U);let Q=new Set(U.mime);$._zod.onattach.push((q)=>{q._zod.bag.mime=U.mime}),$._zod.check=(q)=>{if(Q.has(q.value.type))return;q.issues.push({code:"invalid_value",values:U.mime,input:q.value.type,inst:$,continue:!U.abort})}}),k3=D("$ZodCheckOverwrite",($,U)=>{$$.init($,U),$._zod.check=(Q)=>{Q.value=U.tx(Q.value)}});class l0{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 Q=$.split(`
|
|
57
|
+
`).filter((W)=>W),q=Math.min(...Q.map((W)=>W.length-W.trimStart().length)),K=Q.map((W)=>W.slice(q)).map((W)=>" ".repeat(this.indent*2)+W);for(let W of K)this.content.push(W)}compile(){let $=Function,U=this?.args,q=[...(this?.content??[""]).map((K)=>` ${K}`)];return new $(...U,q.join(`
|
|
58
|
+
`))}}var w3={major:4,minor:3,patch:6};var u=D("$ZodType",($,U)=>{var Q;$??($={}),$._zod.def=U,$._zod.bag=$._zod.bag||{},$._zod.version=w3;let q=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))q.unshift($);for(let K of q)for(let W of K._zod.onattach)W($);if(q.length===0)(Q=$._zod).deferred??(Q.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let K=(J,G,Y)=>{let H=w1(J),B;for(let M of G){if(M._zod.def.when){if(!M._zod.def.when(J))continue}else if(H)continue;let V=J.issues.length,L=M._zod.check(J);if(L instanceof Promise&&Y?.async===!1)throw new e$;if(B||L instanceof Promise)B=(B??Promise.resolve()).then(async()=>{if(await L,J.issues.length===V)return;if(!H)H=w1(J,V)});else{if(J.issues.length===V)continue;if(!H)H=w1(J,V)}}if(B)return B.then(()=>{return J});return J},W=(J,G,Y)=>{if(w1(J))return J.aborted=!0,J;let H=K(G,q,Y);if(H instanceof Promise){if(Y.async===!1)throw new e$;return H.then((B)=>$._zod.parse(B,Y))}return $._zod.parse(H,Y)};$._zod.run=(J,G)=>{if(G.skipChecks)return $._zod.parse(J,G);if(G.direction==="backward"){let H=$._zod.parse({value:J.value,issues:[]},{...G,skipChecks:!0});if(H instanceof Promise)return H.then((B)=>{return W(B,J,G)});return W(H,J,G)}let Y=$._zod.parse(J,G);if(Y instanceof Promise){if(G.async===!1)throw new e$;return Y.then((H)=>K(H,q,G))}return K(Y,q,G)}}l($,"~standard",()=>({validate:(K)=>{try{let W=TU($,K);return W.success?{value:W.data}:{issues:W.error?.issues}}catch(W){return SU($,K).then((J)=>J.success?{value:J.data}:{issues:J.error?.issues})}},vendor:"zod",version:1}))}),U4=D("$ZodString",($,U)=>{u.init($,U),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??$3($._zod.bag),$._zod.parse=(Q,q)=>{if(U.coerce)try{Q.value=String(Q.value)}catch(K){}if(typeof Q.value==="string")return Q;return Q.issues.push({expected:"string",code:"invalid_type",input:Q.value,inst:$}),Q}}),s=D("$ZodStringFormat",($,U)=>{x4.init($,U),U4.init($,U)}),A3=D("$ZodGUID",($,U)=>{U.pattern??(U.pattern=mU),s.init($,U)}),b3=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=$4(q))}else U.pattern??(U.pattern=$4());s.init($,U)}),O3=D("$ZodEmail",($,U)=>{U.pattern??(U.pattern=cU),s.init($,U)}),R3=D("$ZodURL",($,U)=>{s.init($,U),$._zod.check=(Q)=>{try{let q=Q.value.trim(),K=new URL(q);if(U.hostname){if(U.hostname.lastIndex=0,!U.hostname.test(K.hostname))Q.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:U.hostname.source,input:Q.value,inst:$,continue:!U.abort})}if(U.protocol){if(U.protocol.lastIndex=0,!U.protocol.test(K.protocol.endsWith(":")?K.protocol.slice(0,-1):K.protocol))Q.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:U.protocol.source,input:Q.value,inst:$,continue:!U.abort})}if(U.normalize)Q.value=K.href;else Q.value=q;return}catch(q){Q.issues.push({code:"invalid_format",format:"url",input:Q.value,inst:$,continue:!U.abort})}}}),T3=D("$ZodEmoji",($,U)=>{U.pattern??(U.pattern=lU()),s.init($,U)}),S3=D("$ZodNanoID",($,U)=>{U.pattern??(U.pattern=fU),s.init($,U)}),C3=D("$ZodCUID",($,U)=>{U.pattern??(U.pattern=CU),s.init($,U)}),E3=D("$ZodCUID2",($,U)=>{U.pattern??(U.pattern=EU),s.init($,U)}),g3=D("$ZodULID",($,U)=>{U.pattern??(U.pattern=gU),s.init($,U)}),y3=D("$ZodXID",($,U)=>{U.pattern??(U.pattern=yU),s.init($,U)}),u3=D("$ZodKSUID",($,U)=>{U.pattern??(U.pattern=uU),s.init($,U)}),f3=D("$ZodISODateTime",($,U)=>{U.pattern??(U.pattern=eU(U)),s.init($,U)}),h3=D("$ZodISODate",($,U)=>{U.pattern??(U.pattern=aU),s.init($,U)}),m3=D("$ZodISOTime",($,U)=>{U.pattern??(U.pattern=sU(U)),s.init($,U)}),c3=D("$ZodISODuration",($,U)=>{U.pattern??(U.pattern=hU),s.init($,U)}),l3=D("$ZodIPv4",($,U)=>{U.pattern??(U.pattern=rU),s.init($,U),$._zod.bag.format="ipv4"}),r3=D("$ZodIPv6",($,U)=>{U.pattern??(U.pattern=nU),s.init($,U),$._zod.bag.format="ipv6",$._zod.check=(Q)=>{try{new URL(`http://[${Q.value}]`)}catch{Q.issues.push({code:"invalid_format",format:"ipv6",input:Q.value,inst:$,continue:!U.abort})}}}),n3=D("$ZodMAC",($,U)=>{U.pattern??(U.pattern=iU(U.delimiter)),s.init($,U),$._zod.bag.format="mac"}),i3=D("$ZodCIDRv4",($,U)=>{U.pattern??(U.pattern=oU),s.init($,U)}),o3=D("$ZodCIDRv6",($,U)=>{U.pattern??(U.pattern=dU),s.init($,U),$._zod.check=(Q)=>{let q=Q.value.split("/");try{if(q.length!==2)throw Error();let[K,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://[${K}]`)}catch{Q.issues.push({code:"invalid_format",format:"cidrv6",input:Q.value,inst:$,continue:!U.abort})}}});function d3($){if($==="")return!0;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}var p3=D("$ZodBase64",($,U)=>{U.pattern??(U.pattern=pU),s.init($,U),$._zod.bag.contentEncoding="base64",$._zod.check=(Q)=>{if(d3(Q.value))return;Q.issues.push({code:"invalid_format",format:"base64",input:Q.value,inst:$,continue:!U.abort})}});function mG($){if(!h0.test($))return!1;let U=$.replace(/[-_]/g,(q)=>q==="-"?"+":"/"),Q=U.padEnd(Math.ceil(U.length/4)*4,"=");return d3(Q)}var t3=D("$ZodBase64URL",($,U)=>{U.pattern??(U.pattern=h0),s.init($,U),$._zod.bag.contentEncoding="base64url",$._zod.check=(Q)=>{if(mG(Q.value))return;Q.issues.push({code:"invalid_format",format:"base64url",input:Q.value,inst:$,continue:!U.abort})}}),a3=D("$ZodE164",($,U)=>{U.pattern??(U.pattern=tU),s.init($,U)});function cG($,U=null){try{let Q=$.split(".");if(Q.length!==3)return!1;let[q]=Q;if(!q)return!1;let K=JSON.parse(atob(q));if("typ"in K&&K?.typ!=="JWT")return!1;if(!K.alg)return!1;if(U&&(!("alg"in K)||K.alg!==U))return!1;return!0}catch{return!1}}var s3=D("$ZodJWT",($,U)=>{s.init($,U),$._zod.check=(Q)=>{if(cG(Q.value,U.alg))return;Q.issues.push({code:"invalid_format",format:"jwt",input:Q.value,inst:$,continue:!U.abort})}}),e3=D("$ZodCustomStringFormat",($,U)=>{s.init($,U),$._zod.check=(Q)=>{if(U.fn(Q.value))return;Q.issues.push({code:"invalid_format",format:U.format,input:Q.value,inst:$,continue:!U.abort})}}),p0=D("$ZodNumber",($,U)=>{u.init($,U),$._zod.pattern=$._zod.bag.pattern??x6,$._zod.parse=(Q,q)=>{if(U.coerce)try{Q.value=Number(Q.value)}catch(J){}let K=Q.value;if(typeof K==="number"&&!Number.isNaN(K)&&Number.isFinite(K))return Q;let W=typeof K==="number"?Number.isNaN(K)?"NaN":!Number.isFinite(K)?"Infinity":void 0:void 0;return Q.issues.push({expected:"number",code:"invalid_type",input:K,inst:$,...W?{received:W}:{}}),Q}}),$9=D("$ZodNumberFormat",($,U)=>{Y3.init($,U),p0.init($,U)}),O6=D("$ZodBoolean",($,U)=>{u.init($,U),$._zod.pattern=Q3,$._zod.parse=(Q,q)=>{if(U.coerce)try{Q.value=Boolean(Q.value)}catch(W){}let K=Q.value;if(typeof K==="boolean")return Q;return Q.issues.push({expected:"boolean",code:"invalid_type",input:K,inst:$}),Q}}),t0=D("$ZodBigInt",($,U)=>{u.init($,U),$._zod.pattern=U3,$._zod.parse=(Q,q)=>{if(U.coerce)try{Q.value=BigInt(Q.value)}catch(K){}if(typeof Q.value==="bigint")return Q;return Q.issues.push({expected:"bigint",code:"invalid_type",input:Q.value,inst:$}),Q}}),U9=D("$ZodBigIntFormat",($,U)=>{H3.init($,U),t0.init($,U)}),K9=D("$ZodSymbol",($,U)=>{u.init($,U),$._zod.parse=(Q,q)=>{let K=Q.value;if(typeof K==="symbol")return Q;return Q.issues.push({expected:"symbol",code:"invalid_type",input:K,inst:$}),Q}}),Q9=D("$ZodUndefined",($,U)=>{u.init($,U),$._zod.pattern=W3,$._zod.values=new Set([void 0]),$._zod.optin="optional",$._zod.optout="optional",$._zod.parse=(Q,q)=>{let K=Q.value;if(typeof K>"u")return Q;return Q.issues.push({expected:"undefined",code:"invalid_type",input:K,inst:$}),Q}}),q9=D("$ZodNull",($,U)=>{u.init($,U),$._zod.pattern=q3,$._zod.values=new Set([null]),$._zod.parse=(Q,q)=>{let K=Q.value;if(K===null)return Q;return Q.issues.push({expected:"null",code:"invalid_type",input:K,inst:$}),Q}}),W9=D("$ZodAny",($,U)=>{u.init($,U),$._zod.parse=(Q)=>Q}),J9=D("$ZodUnknown",($,U)=>{u.init($,U),$._zod.parse=(Q)=>Q}),G9=D("$ZodNever",($,U)=>{u.init($,U),$._zod.parse=(Q,q)=>{return Q.issues.push({expected:"never",code:"invalid_type",input:Q.value,inst:$}),Q}}),j9=D("$ZodVoid",($,U)=>{u.init($,U),$._zod.parse=(Q,q)=>{let K=Q.value;if(typeof K>"u")return Q;return Q.issues.push({expected:"void",code:"invalid_type",input:K,inst:$}),Q}}),Y9=D("$ZodDate",($,U)=>{u.init($,U),$._zod.parse=(Q,q)=>{if(U.coerce)try{Q.value=new Date(Q.value)}catch(G){}let K=Q.value,W=K instanceof Date;if(W&&!Number.isNaN(K.getTime()))return Q;return Q.issues.push({expected:"date",code:"invalid_type",input:K,...W?{received:"Invalid Date"}:{},inst:$}),Q}});function OG($,U,Q){if($.issues.length)U.issues.push(...E$(Q,$.issues));U.value[Q]=$.value}var H9=D("$ZodArray",($,U)=>{u.init($,U),$._zod.parse=(Q,q)=>{let K=Q.value;if(!Array.isArray(K))return Q.issues.push({expected:"array",code:"invalid_type",input:K,inst:$}),Q;Q.value=Array(K.length);let W=[];for(let J=0;J<K.length;J++){let G=K[J],Y=U.element._zod.run({value:G,issues:[]},q);if(Y instanceof Promise)W.push(Y.then((H)=>OG(H,Q,J)));else OG(Y,Q,J)}if(W.length)return Promise.all(W).then(()=>Q);return Q}});function d0($,U,Q,q,K){if($.issues.length){if(K&&!(Q in q))return;U.issues.push(...E$(Q,$.issues))}if($.value===void 0){if(Q in q)U.value[Q]=void 0}else U.value[Q]=$.value}function lG($){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 Q=xU($.shape);return{...$,keys:U,keySet:new Set(U),numKeys:U.length,optionalKeys:new Set(Q)}}function rG($,U,Q,q,K,W){let J=[],G=K.keySet,Y=K.catchall._zod,H=Y.def.type,B=Y.optout==="optional";for(let M in U){if(G.has(M))continue;if(H==="never"){J.push(M);continue}let V=Y.run({value:U[M],issues:[]},q);if(V instanceof Promise)$.push(V.then((L)=>d0(L,Q,M,U,B)));else d0(V,Q,M,U,B)}if(J.length)Q.issues.push({code:"unrecognized_keys",keys:J,input:U,inst:W});if(!$.length)return Q;return Promise.all($).then(()=>{return Q})}var nG=D("$ZodObject",($,U)=>{if(u.init($,U),!Object.getOwnPropertyDescriptor(U,"shape")?.get){let G=U.shape;Object.defineProperty(U,"shape",{get:()=>{let Y={...G};return Object.defineProperty(U,"shape",{value:Y}),Y}})}let q=L4(()=>lG(U));l($._zod,"propValues",()=>{let G=U.shape,Y={};for(let H in G){let B=G[H]._zod;if(B.values){Y[H]??(Y[H]=new Set);for(let M of B.values)Y[H].add(M)}}return Y});let K=e1,W=U.catchall,J;$._zod.parse=(G,Y)=>{J??(J=q.value);let H=G.value;if(!K(H))return G.issues.push({expected:"object",code:"invalid_type",input:H,inst:$}),G;G.value={};let B=[],M=J.shape;for(let V of J.keys){let L=M[V],T=L._zod.optout==="optional",f=L._zod.run({value:H[V],issues:[]},Y);if(f instanceof Promise)B.push(f.then((U$)=>d0(U$,G,V,H,T)));else d0(f,G,V,H,T)}if(!W)return B.length?Promise.all(B).then(()=>G):G;return rG(B,H,G,Y,q.value,$)}}),X9=D("$ZodObjectJIT",($,U)=>{nG.init($,U);let Q=$._zod.parse,q=L4(()=>lG(U)),K=(V)=>{let L=new l0(["shape","payload","ctx"]),T=q.value,f=(h$)=>{let A$=A0(h$);return`shape[${A$}]._zod.run({ value: input[${A$}], issues: [] }, ctx)`};L.write("const input = payload.value;");let U$=Object.create(null),x$=0;for(let h$ of T.keys)U$[h$]=`key_${x$++}`;L.write("const newResult = {};");for(let h$ of T.keys){let A$=U$[h$],i$=A0(h$),yB=V[h$]?._zod?.optout==="optional";if(L.write(`const ${A$} = ${f(h$)};`),yB)L.write(`
|
|
59
|
+
if (${A$}.issues.length) {
|
|
60
|
+
if (${i$} in input) {
|
|
61
|
+
payload.issues = payload.issues.concat(${A$}.issues.map(iss => ({
|
|
66
62
|
...iss,
|
|
67
|
-
path: iss.path ? [${
|
|
63
|
+
path: iss.path ? [${i$}, ...iss.path] : [${i$}]
|
|
68
64
|
})));
|
|
69
65
|
}
|
|
70
66
|
}
|
|
71
67
|
|
|
72
|
-
if (${
|
|
73
|
-
if (${
|
|
74
|
-
newResult[${
|
|
68
|
+
if (${A$}.value === undefined) {
|
|
69
|
+
if (${i$} in input) {
|
|
70
|
+
newResult[${i$}] = undefined;
|
|
75
71
|
}
|
|
76
72
|
} else {
|
|
77
|
-
newResult[${
|
|
73
|
+
newResult[${i$}] = ${A$}.value;
|
|
78
74
|
}
|
|
79
75
|
|
|
80
|
-
`);else
|
|
81
|
-
if (${
|
|
82
|
-
payload.issues = payload.issues.concat(${
|
|
76
|
+
`);else L.write(`
|
|
77
|
+
if (${A$}.issues.length) {
|
|
78
|
+
payload.issues = payload.issues.concat(${A$}.issues.map(iss => ({
|
|
83
79
|
...iss,
|
|
84
|
-
path: iss.path ? [${
|
|
80
|
+
path: iss.path ? [${i$}, ...iss.path] : [${i$}]
|
|
85
81
|
})));
|
|
86
82
|
}
|
|
87
83
|
|
|
88
|
-
if (${
|
|
89
|
-
if (${
|
|
90
|
-
newResult[${
|
|
84
|
+
if (${A$}.value === undefined) {
|
|
85
|
+
if (${i$} in input) {
|
|
86
|
+
newResult[${i$}] = undefined;
|
|
91
87
|
}
|
|
92
88
|
} else {
|
|
93
|
-
newResult[${
|
|
89
|
+
newResult[${i$}] = ${A$}.value;
|
|
94
90
|
}
|
|
95
91
|
|
|
96
|
-
`)}N.write("payload.value = newResult;"),N.write("return payload;");let l1=N.compile();return(A$,b$)=>l1(B,A$,b$)},Q,q=u1,G=!r4.jitless,Y=G&&OU.value,X=v.catchall,P;$._zod.parse=(B,N)=>{P??(P=_.value);let S=B.value;if(!q(S))return B.issues.push({expected:"object",code:"invalid_type",input:S,inst:$}),B;if(G&&Y&&N?.async===!1&&N.jitless!==!0){if(!Q)Q=U(v.shape);if(B=Q(B,N),!X)return B;return UG([],S,B,N,P,$)}return K(B,N)}});function rq($,v,K,_){for(let Q of $)if(Q.issues.length===0)return v.value=Q.value,v;let U=$.filter((Q)=>!V1(Q));if(U.length===1)return v.value=U[0].value,U[0];return v.issues.push({code:"invalid_union",input:v.value,inst:K,errors:$.map((Q)=>Q.issues.map((q)=>N$(q,_,K$())))}),v}var K6=V("$ZodUnion",($,v)=>{C.init($,v),h($._zod,"optin",()=>v.options.some((U)=>U._zod.optin==="optional")?"optional":void 0),h($._zod,"optout",()=>v.options.some((U)=>U._zod.optout==="optional")?"optional":void 0),h($._zod,"values",()=>{if(v.options.every((U)=>U._zod.values))return new Set(v.options.flatMap((U)=>Array.from(U._zod.values)));return}),h($._zod,"pattern",()=>{if(v.options.every((U)=>U._zod.pattern)){let U=v.options.map((Q)=>Q._zod.pattern);return new RegExp(`^(${U.map((Q)=>l4(Q.source)).join("|")})$`)}return});let K=v.options.length===1,_=v.options[0]._zod.run;$._zod.parse=(U,Q)=>{if(K)return _(U,Q);let q=!1,G=[];for(let j of v.options){let Y=j._zod.run({value:U.value,issues:[]},Q);if(Y instanceof Promise)G.push(Y),q=!0;else{if(Y.issues.length===0)return Y;G.push(Y)}}if(!q)return rq(G,U,$,Q);return Promise.all(G).then((j)=>{return rq(j,U,$,Q)})}});function iq($,v,K,_){let U=$.filter((Q)=>Q.issues.length===0);if(U.length===1)return v.value=U[0].value,v;if(U.length===0)v.issues.push({code:"invalid_union",input:v.value,inst:K,errors:$.map((Q)=>Q.issues.map((q)=>N$(q,_,K$())))});else v.issues.push({code:"invalid_union",input:v.value,inst:K,errors:[],inclusive:!1});return v}var D9=V("$ZodXor",($,v)=>{K6.init($,v),v.inclusive=!1;let K=v.options.length===1,_=v.options[0]._zod.run;$._zod.parse=(U,Q)=>{if(K)return _(U,Q);let q=!1,G=[];for(let j of v.options){let Y=j._zod.run({value:U.value,issues:[]},Q);if(Y instanceof Promise)G.push(Y),q=!0;else G.push(Y)}if(!q)return iq(G,U,$,Q);return Promise.all(G).then((j)=>{return iq(j,U,$,Q)})}}),b9=V("$ZodDiscriminatedUnion",($,v)=>{v.inclusive=!1,K6.init($,v);let K=$._zod.parse;h($._zod,"propValues",()=>{let U={};for(let Q of v.options){let q=Q._zod.propValues;if(!q||Object.keys(q).length===0)throw Error(`Invalid discriminated union option at index "${v.options.indexOf(Q)}"`);for(let[G,j]of Object.entries(q)){if(!U[G])U[G]=new Set;for(let Y of j)U[G].add(Y)}}return U});let _=$4(()=>{let U=v.options,Q=new Map;for(let q of U){let G=q._zod.propValues?.[v.discriminator];if(!G||G.size===0)throw Error(`Invalid discriminated union option at index "${v.options.indexOf(q)}"`);for(let j of G){if(Q.has(j))throw Error(`Duplicate discriminator value "${String(j)}"`);Q.set(j,q)}}return Q});$._zod.parse=(U,Q)=>{let q=U.value;if(!u1(q))return U.issues.push({code:"invalid_type",expected:"object",input:q,inst:$}),U;let G=_.value.get(q?.[v.discriminator]);if(G)return G._zod.run(U,Q);if(v.unionFallback)return K(U,Q);return U.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:v.discriminator,input:q,path:[v.discriminator],inst:$}),U}}),k9=V("$ZodIntersection",($,v)=>{C.init($,v),$._zod.parse=(K,_)=>{let U=K.value,Q=v.left._zod.run({value:U,issues:[]},_),q=v.right._zod.run({value:U,issues:[]},_);if(Q instanceof Promise||q instanceof Promise)return Promise.all([Q,q]).then(([j,Y])=>{return nq(K,j,Y)});return nq(K,Q,q)}});function S2($,v){if($===v)return{valid:!0,data:$};if($ instanceof Date&&v instanceof Date&&+$===+v)return{valid:!0,data:$};if(P1($)&&P1(v)){let K=Object.keys(v),_=Object.keys($).filter((Q)=>K.indexOf(Q)!==-1),U={...$,...v};for(let Q of _){let q=S2($[Q],v[Q]);if(!q.valid)return{valid:!1,mergeErrorPath:[Q,...q.mergeErrorPath]};U[Q]=q.data}return{valid:!0,data:U}}if(Array.isArray($)&&Array.isArray(v)){if($.length!==v.length)return{valid:!1,mergeErrorPath:[]};let K=[];for(let _=0;_<$.length;_++){let U=$[_],Q=v[_],q=S2(U,Q);if(!q.valid)return{valid:!1,mergeErrorPath:[_,...q.mergeErrorPath]};K.push(q.data)}return{valid:!0,data:K}}return{valid:!1,mergeErrorPath:[]}}function nq($,v,K){let _=new Map,U;for(let G of v.issues)if(G.code==="unrecognized_keys"){U??(U=G);for(let j of G.keys){if(!_.has(j))_.set(j,{});_.get(j).l=!0}}else $.issues.push(G);for(let G of K.issues)if(G.code==="unrecognized_keys")for(let j of G.keys){if(!_.has(j))_.set(j,{});_.get(j).r=!0}else $.issues.push(G);let Q=[..._].filter(([,G])=>G.l&&G.r).map(([G])=>G);if(Q.length&&U)$.issues.push({...U,keys:Q});if(V1($))return $;let q=S2(v.value,K.value);if(!q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(q.mergeErrorPath)}`);return $.value=q.data,$}var N0=V("$ZodTuple",($,v)=>{C.init($,v);let K=v.items;$._zod.parse=(_,U)=>{let Q=_.value;if(!Array.isArray(Q))return _.issues.push({input:Q,inst:$,expected:"tuple",code:"invalid_type"}),_;_.value=[];let q=[],G=[...K].reverse().findIndex((X)=>X._zod.optin!=="optional"),j=G===-1?0:K.length-G;if(!v.rest){let X=Q.length>K.length,P=Q.length<j-1;if(X||P)return _.issues.push({...X?{code:"too_big",maximum:K.length,inclusive:!0}:{code:"too_small",minimum:K.length},input:Q,inst:$,origin:"array"}),_}let Y=-1;for(let X of K){if(Y++,Y>=Q.length){if(Y>=j)continue}let P=X._zod.run({value:Q[Y],issues:[]},U);if(P instanceof Promise)q.push(P.then((B)=>H0(B,_,Y)));else H0(P,_,Y)}if(v.rest){let X=Q.slice(K.length);for(let P of X){Y++;let B=v.rest._zod.run({value:P,issues:[]},U);if(B instanceof Promise)q.push(B.then((N)=>H0(N,_,Y)));else H0(B,_,Y)}}if(q.length)return Promise.all(q).then(()=>_);return _}});function H0($,v,K){if($.issues.length)v.issues.push(...Z$(K,$.issues));v.value[K]=$.value}var N9=V("$ZodRecord",($,v)=>{C.init($,v),$._zod.parse=(K,_)=>{let U=K.value;if(!P1(U))return K.issues.push({expected:"record",code:"invalid_type",input:U,inst:$}),K;let Q=[],q=v.keyType._zod.values;if(q){K.value={};let G=new Set;for(let Y of q)if(typeof Y==="string"||typeof Y==="number"||typeof Y==="symbol"){G.add(typeof Y==="number"?Y.toString():Y);let X=v.valueType._zod.run({value:U[Y],issues:[]},_);if(X instanceof Promise)Q.push(X.then((P)=>{if(P.issues.length)K.issues.push(...Z$(Y,P.issues));K.value[Y]=P.value}));else{if(X.issues.length)K.issues.push(...Z$(Y,X.issues));K.value[Y]=X.value}}let j;for(let Y in U)if(!G.has(Y))j=j??[],j.push(Y);if(j&&j.length>0)K.issues.push({code:"unrecognized_keys",input:U,inst:$,keys:j})}else{K.value={};for(let G of Reflect.ownKeys(U)){if(G==="__proto__")continue;let j=v.keyType._zod.run({value:G,issues:[]},_);if(j instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof G==="string"&&s4.test(G)&&j.issues.length){let P=v.keyType._zod.run({value:Number(G),issues:[]},_);if(P instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(P.issues.length===0)j=P}if(j.issues.length){if(v.mode==="loose")K.value[G]=U[G];else K.issues.push({code:"invalid_key",origin:"record",issues:j.issues.map((P)=>N$(P,_,K$())),input:G,path:[G],inst:$});continue}let X=v.valueType._zod.run({value:U[G],issues:[]},_);if(X instanceof Promise)Q.push(X.then((P)=>{if(P.issues.length)K.issues.push(...Z$(G,P.issues));K.value[j.value]=P.value}));else{if(X.issues.length)K.issues.push(...Z$(G,X.issues));K.value[j.value]=X.value}}}if(Q.length)return Promise.all(Q).then(()=>K);return K}}),w9=V("$ZodMap",($,v)=>{C.init($,v),$._zod.parse=(K,_)=>{let U=K.value;if(!(U instanceof Map))return K.issues.push({expected:"map",code:"invalid_type",input:U,inst:$}),K;let Q=[];K.value=new Map;for(let[q,G]of U){let j=v.keyType._zod.run({value:q,issues:[]},_),Y=v.valueType._zod.run({value:G,issues:[]},_);if(j instanceof Promise||Y instanceof Promise)Q.push(Promise.all([j,Y]).then(([X,P])=>{lq(X,P,K,q,U,$,_)}));else lq(j,Y,K,q,U,$,_)}if(Q.length)return Promise.all(Q).then(()=>K);return K}});function lq($,v,K,_,U,Q,q){if($.issues.length)if(o4.has(typeof _))K.issues.push(...Z$(_,$.issues));else K.issues.push({code:"invalid_key",origin:"map",input:U,inst:Q,issues:$.issues.map((G)=>N$(G,q,K$()))});if(v.issues.length)if(o4.has(typeof _))K.issues.push(...Z$(_,v.issues));else K.issues.push({origin:"map",code:"invalid_element",input:U,inst:Q,key:_,issues:v.issues.map((G)=>N$(G,q,K$()))});K.value.set($.value,v.value)}var M9=V("$ZodSet",($,v)=>{C.init($,v),$._zod.parse=(K,_)=>{let U=K.value;if(!(U instanceof Set))return K.issues.push({input:U,inst:$,expected:"set",code:"invalid_type"}),K;let Q=[];K.value=new Set;for(let q of U){let G=v.valueType._zod.run({value:q,issues:[]},_);if(G instanceof Promise)Q.push(G.then((j)=>oq(j,K)));else oq(G,K)}if(Q.length)return Promise.all(Q).then(()=>K);return K}});function oq($,v){if($.issues.length)v.issues.push(...$.issues);v.value.add($.value)}var I9=V("$ZodEnum",($,v)=>{C.init($,v);let K=n4(v.entries),_=new Set(K);$._zod.values=_,$._zod.pattern=new RegExp(`^(${K.filter((U)=>o4.has(typeof U)).map((U)=>typeof U==="string"?O$(U):U.toString()).join("|")})$`),$._zod.parse=(U,Q)=>{let q=U.value;if(_.has(q))return U;return U.issues.push({code:"invalid_value",values:K,input:q,inst:$}),U}}),Z9=V("$ZodLiteral",($,v)=>{if(C.init($,v),v.values.length===0)throw Error("Cannot create literal schema with no valid values");let K=new Set(v.values);$._zod.values=K,$._zod.pattern=new RegExp(`^(${v.values.map((_)=>typeof _==="string"?O$(_):_?O$(_.toString()):String(_)).join("|")})$`),$._zod.parse=(_,U)=>{let Q=_.value;if(K.has(Q))return _;return _.issues.push({code:"invalid_value",values:v.values,input:Q,inst:$}),_}}),z9=V("$ZodFile",($,v)=>{C.init($,v),$._zod.parse=(K,_)=>{let U=K.value;if(U instanceof File)return K;return K.issues.push({expected:"file",code:"invalid_type",input:U,inst:$}),K}}),L9=V("$ZodTransform",($,v)=>{C.init($,v),$._zod.parse=(K,_)=>{if(_.direction==="backward")throw new S1($.constructor.name);let U=v.transform(K.value,K);if(_.async)return(U instanceof Promise?U:Promise.resolve(U)).then((q)=>{return K.value=q,K});if(U instanceof Promise)throw new c$;return K.value=U,K}});function dq($,v){if($.issues.length&&v===void 0)return{issues:[],value:void 0};return $}var w0=V("$ZodOptional",($,v)=>{C.init($,v),$._zod.optin="optional",$._zod.optout="optional",h($._zod,"values",()=>{return v.innerType._zod.values?new Set([...v.innerType._zod.values,void 0]):void 0}),h($._zod,"pattern",()=>{let K=v.innerType._zod.pattern;return K?new RegExp(`^(${l4(K.source)})?$`):void 0}),$._zod.parse=(K,_)=>{if(v.innerType._zod.optin==="optional"){let U=v.innerType._zod.run(K,_);if(U instanceof Promise)return U.then((Q)=>dq(Q,K.value));return dq(U,K.value)}if(K.value===void 0)return K;return v.innerType._zod.run(K,_)}}),A9=V("$ZodExactOptional",($,v)=>{w0.init($,v),h($._zod,"values",()=>v.innerType._zod.values),h($._zod,"pattern",()=>v.innerType._zod.pattern),$._zod.parse=(K,_)=>{return v.innerType._zod.run(K,_)}}),F9=V("$ZodNullable",($,v)=>{C.init($,v),h($._zod,"optin",()=>v.innerType._zod.optin),h($._zod,"optout",()=>v.innerType._zod.optout),h($._zod,"pattern",()=>{let K=v.innerType._zod.pattern;return K?new RegExp(`^(${l4(K.source)}|null)$`):void 0}),h($._zod,"values",()=>{return v.innerType._zod.values?new Set([...v.innerType._zod.values,null]):void 0}),$._zod.parse=(K,_)=>{if(K.value===null)return K;return v.innerType._zod.run(K,_)}}),O9=V("$ZodDefault",($,v)=>{C.init($,v),$._zod.optin="optional",h($._zod,"values",()=>v.innerType._zod.values),$._zod.parse=(K,_)=>{if(_.direction==="backward")return v.innerType._zod.run(K,_);if(K.value===void 0)return K.value=v.defaultValue,K;let U=v.innerType._zod.run(K,_);if(U instanceof Promise)return U.then((Q)=>tq(Q,v));return tq(U,v)}});function tq($,v){if($.value===void 0)$.value=v.defaultValue;return $}var x9=V("$ZodPrefault",($,v)=>{C.init($,v),$._zod.optin="optional",h($._zod,"values",()=>v.innerType._zod.values),$._zod.parse=(K,_)=>{if(_.direction==="backward")return v.innerType._zod.run(K,_);if(K.value===void 0)K.value=v.defaultValue;return v.innerType._zod.run(K,_)}}),R9=V("$ZodNonOptional",($,v)=>{C.init($,v),h($._zod,"values",()=>{let K=v.innerType._zod.values;return K?new Set([...K].filter((_)=>_!==void 0)):void 0}),$._zod.parse=(K,_)=>{let U=v.innerType._zod.run(K,_);if(U instanceof Promise)return U.then((Q)=>pq(Q,$));return pq(U,$)}});function pq($,v){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:v});return $}var S9=V("$ZodSuccess",($,v)=>{C.init($,v),$._zod.parse=(K,_)=>{if(_.direction==="backward")throw new S1("ZodSuccess");let U=v.innerType._zod.run(K,_);if(U instanceof Promise)return U.then((Q)=>{return K.value=Q.issues.length===0,K});return K.value=U.issues.length===0,K}}),u9=V("$ZodCatch",($,v)=>{C.init($,v),h($._zod,"optin",()=>v.innerType._zod.optin),h($._zod,"optout",()=>v.innerType._zod.optout),h($._zod,"values",()=>v.innerType._zod.values),$._zod.parse=(K,_)=>{if(_.direction==="backward")return v.innerType._zod.run(K,_);let U=v.innerType._zod.run(K,_);if(U instanceof Promise)return U.then((Q)=>{if(K.value=Q.value,Q.issues.length)K.value=v.catchValue({...K,error:{issues:Q.issues.map((q)=>N$(q,_,K$()))},input:K.value}),K.issues=[];return K});if(K.value=U.value,U.issues.length)K.value=v.catchValue({...K,error:{issues:U.issues.map((Q)=>N$(Q,_,K$()))},input:K.value}),K.issues=[];return K}}),T9=V("$ZodNaN",($,v)=>{C.init($,v),$._zod.parse=(K,_)=>{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}}),g9=V("$ZodPipe",($,v)=>{C.init($,v),h($._zod,"values",()=>v.in._zod.values),h($._zod,"optin",()=>v.in._zod.optin),h($._zod,"optout",()=>v.out._zod.optout),h($._zod,"propValues",()=>v.in._zod.propValues),$._zod.parse=(K,_)=>{if(_.direction==="backward"){let Q=v.out._zod.run(K,_);if(Q instanceof Promise)return Q.then((q)=>P0(q,v.in,_));return P0(Q,v.in,_)}let U=v.in._zod.run(K,_);if(U instanceof Promise)return U.then((Q)=>P0(Q,v.out,_));return P0(U,v.out,_)}});function P0($,v,K){if($.issues.length)return $.aborted=!0,$;return v._zod.run({value:$.value,issues:$.issues},K)}var _6=V("$ZodCodec",($,v)=>{C.init($,v),h($._zod,"values",()=>v.in._zod.values),h($._zod,"optin",()=>v.in._zod.optin),h($._zod,"optout",()=>v.out._zod.optout),h($._zod,"propValues",()=>v.in._zod.propValues),$._zod.parse=(K,_)=>{if((_.direction||"forward")==="forward"){let Q=v.in._zod.run(K,_);if(Q instanceof Promise)return Q.then((q)=>V0(q,v,_));return V0(Q,v,_)}else{let Q=v.out._zod.run(K,_);if(Q instanceof Promise)return Q.then((q)=>V0(q,v,_));return V0(Q,v,_)}}});function V0($,v,K){if($.issues.length)return $.aborted=!0,$;if((K.direction||"forward")==="forward"){let U=v.transform($.value,$);if(U instanceof Promise)return U.then((Q)=>B0($,Q,v.out,K));return B0($,U,v.out,K)}else{let U=v.reverseTransform($.value,$);if(U instanceof Promise)return U.then((Q)=>B0($,Q,v.in,K));return B0($,U,v.in,K)}}function B0($,v,K,_){if($.issues.length)return $.aborted=!0,$;return K._zod.run({value:v,issues:$.issues},_)}var E9=V("$ZodReadonly",($,v)=>{C.init($,v),h($._zod,"propValues",()=>v.innerType._zod.propValues),h($._zod,"values",()=>v.innerType._zod.values),h($._zod,"optin",()=>v.innerType?._zod?.optin),h($._zod,"optout",()=>v.innerType?._zod?.optout),$._zod.parse=(K,_)=>{if(_.direction==="backward")return v.innerType._zod.run(K,_);let U=v.innerType._zod.run(K,_);if(U instanceof Promise)return U.then(aq);return aq(U)}});function aq($){return $.value=Object.freeze($.value),$}var C9=V("$ZodTemplateLiteral",($,v)=>{C.init($,v);let K=[];for(let _ of v.parts)if(typeof _==="object"&&_!==null){if(!_._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[..._._zod.traits].shift()}`);let U=_._zod.pattern instanceof RegExp?_._zod.pattern.source:_._zod.pattern;if(!U)throw Error(`Invalid template literal part: ${_._zod.traits}`);let Q=U.startsWith("^")?1:0,q=U.endsWith("$")?U.length-1:U.length;K.push(U.slice(Q,q))}else if(_===null||RU.has(typeof _))K.push(O$(`${_}`));else throw Error(`Invalid template literal part: ${_}`);$._zod.pattern=new RegExp(`^${K.join("")}$`),$._zod.parse=(_,U)=>{if(typeof _.value!=="string")return _.issues.push({input:_.value,inst:$,expected:"string",code:"invalid_type"}),_;if($._zod.pattern.lastIndex=0,!$._zod.pattern.test(_.value))return _.issues.push({input:_.value,inst:$,code:"invalid_format",format:v.format??"template_literal",pattern:$._zod.pattern.source}),_;return _}}),y9=V("$ZodFunction",($,v)=>{return C.init($,v),$._def=v,$._zod.def=v,$.implement=(K)=>{if(typeof K!=="function")throw Error("implement() must be called with a function");return function(..._){let U=$._def.input?s6($._def.input,_):_,Q=Reflect.apply(K,this,U);if($._def.output)return s6($._def.output,Q);return Q}},$.implementAsync=(K)=>{if(typeof K!=="function")throw Error("implementAsync() must be called with a function");return async function(..._){let U=$._def.input?await $0($._def.input,_):_,Q=await Reflect.apply(K,this,U);if($._def.output)return await $0($._def.output,Q);return Q}},$._zod.parse=(K,_)=>{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 _=$.constructor;if(Array.isArray(K[0]))return new _({type:"function",input:new N0({type:"tuple",items:K[0],rest:K[1]}),output:$._def.output});return new _({type:"function",input:K[0],output:$._def.output})},$.output=(K)=>{return new $.constructor({type:"function",input:$._def.input,output:K})},$}),f9=V("$ZodPromise",($,v)=>{C.init($,v),$._zod.parse=(K,_)=>{return Promise.resolve(K.value).then((U)=>v.innerType._zod.run({value:U,issues:[]},_))}}),m9=V("$ZodLazy",($,v)=>{C.init($,v),h($._zod,"innerType",()=>v.getter()),h($._zod,"pattern",()=>$._zod.innerType?._zod?.pattern),h($._zod,"propValues",()=>$._zod.innerType?._zod?.propValues),h($._zod,"optin",()=>$._zod.innerType?._zod?.optin??void 0),h($._zod,"optout",()=>$._zod.innerType?._zod?.optout??void 0),$._zod.parse=(K,_)=>{return $._zod.innerType._zod.run(K,_)}}),h9=V("$ZodCustom",($,v)=>{t.init($,v),C.init($,v),$._zod.parse=(K,_)=>{return K},$._zod.check=(K)=>{let _=K.value,U=v.fn(_);if(U instanceof Promise)return U.then((Q)=>eq(Q,K,_,$));eq(U,K,_,$);return}});function eq($,v,K,_){if(!$){let U={code:"custom",input:K,inst:_,path:[..._._zod.def.path??[]],continue:!_._zod.def.abort};if(_._zod.def.params)U.params=_._zod.def.params;v.issues.push(v4(U))}}var j6={};o$(j6,{zhTW:()=>SK,zhCN:()=>RK,yo:()=>uK,vi:()=>xK,uz:()=>OK,ur:()=>FK,uk:()=>W6,ua:()=>AK,tr:()=>LK,th:()=>zK,ta:()=>ZK,sv:()=>IK,sl:()=>MK,ru:()=>wK,pt:()=>NK,ps:()=>bK,pl:()=>kK,ota:()=>DK,no:()=>BK,nl:()=>VK,ms:()=>PK,mk:()=>HK,lt:()=>XK,ko:()=>JK,km:()=>q6,kh:()=>YK,ka:()=>jK,ja:()=>WK,it:()=>GK,is:()=>qK,id:()=>QK,hy:()=>_K,hu:()=>KK,he:()=>UK,frCA:()=>vK,fr:()=>$K,fi:()=>s9,fa:()=>e9,es:()=>a9,eo:()=>p9,en:()=>Q6,de:()=>t9,da:()=>d9,cs:()=>o9,ca:()=>l9,bg:()=>n9,be:()=>i9,az:()=>r9,ar:()=>c9});var cH=()=>{let $={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function v(U){return $[U]??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:"مدخل"},_={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`مدخلات غير مقبولة: يفترض إدخال instanceof ${U.expected}، ولكن تم إدخال ${G}`;return`مدخلات غير مقبولة: يفترض إدخال ${Q}، ولكن تم إدخال ${G}`}case"invalid_value":if(U.values.length===1)return`مدخلات غير مقبولة: يفترض إدخال ${I(U.values[0])}`;return`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return` أكبر من اللازم: يفترض أن تكون ${U.origin??"القيمة"} ${Q} ${U.maximum.toString()} ${q.unit??"عنصر"}`;return`أكبر من اللازم: يفترض أن تكون ${U.origin??"القيمة"} ${Q} ${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`أصغر من اللازم: يفترض لـ ${U.origin} أن يكون ${Q} ${U.minimum.toString()} ${q.unit}`;return`أصغر من اللازم: يفترض لـ ${U.origin} أن يكون ${Q} ${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`نَص غير مقبول: يجب أن يبدأ بـ "${U.prefix}"`;if(Q.format==="ends_with")return`نَص غير مقبول: يجب أن ينتهي بـ "${Q.suffix}"`;if(Q.format==="includes")return`نَص غير مقبول: يجب أن يتضمَّن "${Q.includes}"`;if(Q.format==="regex")return`نَص غير مقبول: يجب أن يطابق النمط ${Q.pattern}`;return`${K[Q.format]??U.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${U.divisor}`;case"unrecognized_keys":return`معرف${U.keys.length>1?"ات":""} غريب${U.keys.length>1?"ة":""}: ${D(U.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${U.origin}`;case"invalid_union":return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${U.origin}`;default:return"مدخل غير مقبول"}}};function c9(){return{localeError:cH()}}var rH=()=>{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 v(U){return $[U]??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"},_={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Yanlış dəyər: gözlənilən instanceof ${U.expected}, daxil olan ${G}`;return`Yanlış dəyər: gözlənilən ${Q}, daxil olan ${G}`}case"invalid_value":if(U.values.length===1)return`Yanlış dəyər: gözlənilən ${I(U.values[0])}`;return`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Çox böyük: gözlənilən ${U.origin??"dəyər"} ${Q}${U.maximum.toString()} ${q.unit??"element"}`;return`Çox böyük: gözlənilən ${U.origin??"dəyər"} ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Çox kiçik: gözlənilən ${U.origin} ${Q}${U.minimum.toString()} ${q.unit}`;return`Çox kiçik: gözlənilən ${U.origin} ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Yanlış mətn: "${Q.prefix}" ilə başlamalıdır`;if(Q.format==="ends_with")return`Yanlış mətn: "${Q.suffix}" ilə bitməlidir`;if(Q.format==="includes")return`Yanlış mətn: "${Q.includes}" daxil olmalıdır`;if(Q.format==="regex")return`Yanlış mətn: ${Q.pattern} şablonuna uyğun olmalıdır`;return`Yanlış ${K[Q.format]??U.format}`}case"not_multiple_of":return`Yanlış ədəd: ${U.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${U.keys.length>1?"lar":""}: ${D(U.keys,", ")}`;case"invalid_key":return`${U.origin} daxilində yanlış açar`;case"invalid_union":return"Yanlış dəyər";case"invalid_element":return`${U.origin} daxilində yanlış dəyər`;default:return"Yanlış dəyər"}}};function r9(){return{localeError:rH()}}function _G($,v,K,_){let U=Math.abs($),Q=U%10,q=U%100;if(q>=11&&q<=19)return _;if(Q===1)return v;if(Q>=2&&Q<=4)return K;return _}var iH=()=>{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 v(U){return $[U]??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:"увод"},_={nan:"NaN",number:"лік",array:"масіў"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Няправільны ўвод: чакаўся instanceof ${U.expected}, атрымана ${G}`;return`Няправільны ўвод: чакаўся ${Q}, атрымана ${G}`}case"invalid_value":if(U.values.length===1)return`Няправільны ўвод: чакалася ${I(U.values[0])}`;return`Няправільны варыянт: чакаўся адзін з ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q){let G=Number(U.maximum),j=_G(G,q.unit.one,q.unit.few,q.unit.many);return`Занадта вялікі: чакалася, што ${U.origin??"значэнне"} павінна ${q.verb} ${Q}${U.maximum.toString()} ${j}`}return`Занадта вялікі: чакалася, што ${U.origin??"значэнне"} павінна быць ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q){let G=Number(U.minimum),j=_G(G,q.unit.one,q.unit.few,q.unit.many);return`Занадта малы: чакалася, што ${U.origin} павінна ${q.verb} ${Q}${U.minimum.toString()} ${j}`}return`Занадта малы: чакалася, што ${U.origin} павінна быць ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Няправільны радок: павінен пачынацца з "${Q.prefix}"`;if(Q.format==="ends_with")return`Няправільны радок: павінен заканчвацца на "${Q.suffix}"`;if(Q.format==="includes")return`Няправільны радок: павінен змяшчаць "${Q.includes}"`;if(Q.format==="regex")return`Няправільны радок: павінен адпавядаць шаблону ${Q.pattern}`;return`Няправільны ${K[Q.format]??U.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${U.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${U.keys.length>1?"ключы":"ключ"}: ${D(U.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${U.origin}`;case"invalid_union":return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${U.origin}`;default:return"Няправільны ўвод"}}};function i9(){return{localeError:iH()}}var nH=()=>{let $={string:{unit:"символа",verb:"да съдържа"},file:{unit:"байта",verb:"да съдържа"},array:{unit:"елемента",verb:"да съдържа"},set:{unit:"елемента",verb:"да съдържа"}};function v(U){return $[U]??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:"вход"},_={nan:"NaN",number:"число",array:"масив"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Невалиден вход: очакван instanceof ${U.expected}, получен ${G}`;return`Невалиден вход: очакван ${Q}, получен ${G}`}case"invalid_value":if(U.values.length===1)return`Невалиден вход: очакван ${I(U.values[0])}`;return`Невалидна опция: очаквано едно от ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Твърде голямо: очаква се ${U.origin??"стойност"} да съдържа ${Q}${U.maximum.toString()} ${q.unit??"елемента"}`;return`Твърде голямо: очаква се ${U.origin??"стойност"} да бъде ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Твърде малко: очаква се ${U.origin} да съдържа ${Q}${U.minimum.toString()} ${q.unit}`;return`Твърде малко: очаква се ${U.origin} да бъде ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Невалиден низ: трябва да започва с "${Q.prefix}"`;if(Q.format==="ends_with")return`Невалиден низ: трябва да завършва с "${Q.suffix}"`;if(Q.format==="includes")return`Невалиден низ: трябва да включва "${Q.includes}"`;if(Q.format==="regex")return`Невалиден низ: трябва да съвпада с ${Q.pattern}`;let q="Невалиден";if(Q.format==="emoji")q="Невалидно";if(Q.format==="datetime")q="Невалидно";if(Q.format==="date")q="Невалидна";if(Q.format==="time")q="Невалидно";if(Q.format==="duration")q="Невалидна";return`${q} ${K[Q.format]??U.format}`}case"not_multiple_of":return`Невалидно число: трябва да бъде кратно на ${U.divisor}`;case"unrecognized_keys":return`Неразпознат${U.keys.length>1?"и":""} ключ${U.keys.length>1?"ове":""}: ${D(U.keys,", ")}`;case"invalid_key":return`Невалиден ключ в ${U.origin}`;case"invalid_union":return"Невалиден вход";case"invalid_element":return`Невалидна стойност в ${U.origin}`;default:return"Невалиден вход"}}};function n9(){return{localeError:nH()}}var lH=()=>{let $={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function v(U){return $[U]??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"},_={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Tipus invàlid: s'esperava instanceof ${U.expected}, s'ha rebut ${G}`;return`Tipus invàlid: s'esperava ${Q}, s'ha rebut ${G}`}case"invalid_value":if(U.values.length===1)return`Valor invàlid: s'esperava ${I(U.values[0])}`;return`Opció invàlida: s'esperava una de ${D(U.values," o ")}`;case"too_big":{let Q=U.inclusive?"com a màxim":"menys de",q=v(U.origin);if(q)return`Massa gran: s'esperava que ${U.origin??"el valor"} contingués ${Q} ${U.maximum.toString()} ${q.unit??"elements"}`;return`Massa gran: s'esperava que ${U.origin??"el valor"} fos ${Q} ${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?"com a mínim":"més de",q=v(U.origin);if(q)return`Massa petit: s'esperava que ${U.origin} contingués ${Q} ${U.minimum.toString()} ${q.unit}`;return`Massa petit: s'esperava que ${U.origin} fos ${Q} ${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Format invàlid: ha de començar amb "${Q.prefix}"`;if(Q.format==="ends_with")return`Format invàlid: ha d'acabar amb "${Q.suffix}"`;if(Q.format==="includes")return`Format invàlid: ha d'incloure "${Q.includes}"`;if(Q.format==="regex")return`Format invàlid: ha de coincidir amb el patró ${Q.pattern}`;return`Format invàlid per a ${K[Q.format]??U.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${U.divisor}`;case"unrecognized_keys":return`Clau${U.keys.length>1?"s":""} no reconeguda${U.keys.length>1?"s":""}: ${D(U.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${U.origin}`;case"invalid_union":return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${U.origin}`;default:return"Entrada invàlida"}}};function l9(){return{localeError:lH()}}var oH=()=>{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 v(U){return $[U]??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"},_={nan:"NaN",number:"číslo",string:"řetězec",function:"funkce",array:"pole"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Neplatný vstup: očekáváno instanceof ${U.expected}, obdrženo ${G}`;return`Neplatný vstup: očekáváno ${Q}, obdrženo ${G}`}case"invalid_value":if(U.values.length===1)return`Neplatný vstup: očekáváno ${I(U.values[0])}`;return`Neplatná možnost: očekávána jedna z hodnot ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Hodnota je příliš velká: ${U.origin??"hodnota"} musí mít ${Q}${U.maximum.toString()} ${q.unit??"prvků"}`;return`Hodnota je příliš velká: ${U.origin??"hodnota"} musí být ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Hodnota je příliš malá: ${U.origin??"hodnota"} musí mít ${Q}${U.minimum.toString()} ${q.unit??"prvků"}`;return`Hodnota je příliš malá: ${U.origin??"hodnota"} musí být ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Neplatný řetězec: musí začínat na "${Q.prefix}"`;if(Q.format==="ends_with")return`Neplatný řetězec: musí končit na "${Q.suffix}"`;if(Q.format==="includes")return`Neplatný řetězec: musí obsahovat "${Q.includes}"`;if(Q.format==="regex")return`Neplatný řetězec: musí odpovídat vzoru ${Q.pattern}`;return`Neplatný formát ${K[Q.format]??U.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${U.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${D(U.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${U.origin}`;case"invalid_union":return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${U.origin}`;default:return"Neplatný vstup"}}};function o9(){return{localeError:oH()}}var dH=()=>{let $={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function v(U){return $[U]??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"},_={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Ugyldigt input: forventede instanceof ${U.expected}, fik ${G}`;return`Ugyldigt input: forventede ${Q}, fik ${G}`}case"invalid_value":if(U.values.length===1)return`Ugyldig værdi: forventede ${I(U.values[0])}`;return`Ugyldigt valg: forventede en af følgende ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin),G=_[U.origin]??U.origin;if(q)return`For stor: forventede ${G??"value"} ${q.verb} ${Q} ${U.maximum.toString()} ${q.unit??"elementer"}`;return`For stor: forventede ${G??"value"} havde ${Q} ${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin),G=_[U.origin]??U.origin;if(q)return`For lille: forventede ${G} ${q.verb} ${Q} ${U.minimum.toString()} ${q.unit}`;return`For lille: forventede ${G} havde ${Q} ${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Ugyldig streng: skal starte med "${Q.prefix}"`;if(Q.format==="ends_with")return`Ugyldig streng: skal ende med "${Q.suffix}"`;if(Q.format==="includes")return`Ugyldig streng: skal indeholde "${Q.includes}"`;if(Q.format==="regex")return`Ugyldig streng: skal matche mønsteret ${Q.pattern}`;return`Ugyldig ${K[Q.format]??U.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${U.divisor}`;case"unrecognized_keys":return`${U.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${D(U.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${U.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${U.origin}`;default:return"Ugyldigt input"}}};function d9(){return{localeError:dH()}}var tH=()=>{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 v(U){return $[U]??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"},_={nan:"NaN",number:"Zahl",array:"Array"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Ungültige Eingabe: erwartet instanceof ${U.expected}, erhalten ${G}`;return`Ungültige Eingabe: erwartet ${Q}, erhalten ${G}`}case"invalid_value":if(U.values.length===1)return`Ungültige Eingabe: erwartet ${I(U.values[0])}`;return`Ungültige Option: erwartet eine von ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Zu groß: erwartet, dass ${U.origin??"Wert"} ${Q}${U.maximum.toString()} ${q.unit??"Elemente"} hat`;return`Zu groß: erwartet, dass ${U.origin??"Wert"} ${Q}${U.maximum.toString()} ist`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Zu klein: erwartet, dass ${U.origin} ${Q}${U.minimum.toString()} ${q.unit} hat`;return`Zu klein: erwartet, dass ${U.origin} ${Q}${U.minimum.toString()} ist`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Ungültiger String: muss mit "${Q.prefix}" beginnen`;if(Q.format==="ends_with")return`Ungültiger String: muss mit "${Q.suffix}" enden`;if(Q.format==="includes")return`Ungültiger String: muss "${Q.includes}" enthalten`;if(Q.format==="regex")return`Ungültiger String: muss dem Muster ${Q.pattern} entsprechen`;return`Ungültig: ${K[Q.format]??U.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${U.divisor} sein`;case"unrecognized_keys":return`${U.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${D(U.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${U.origin}`;case"invalid_union":return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${U.origin}`;default:return"Ungültige Eingabe"}}};function t9(){return{localeError:tH()}}var pH=()=>{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 v(U){return $[U]??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"},_={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;return`Invalid input: expected ${Q}, received ${G}`}case"invalid_value":if(U.values.length===1)return`Invalid input: expected ${I(U.values[0])}`;return`Invalid option: expected one of ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Too big: expected ${U.origin??"value"} to have ${Q}${U.maximum.toString()} ${q.unit??"elements"}`;return`Too big: expected ${U.origin??"value"} to be ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Too small: expected ${U.origin} to have ${Q}${U.minimum.toString()} ${q.unit}`;return`Too small: expected ${U.origin} to be ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Invalid string: must start with "${Q.prefix}"`;if(Q.format==="ends_with")return`Invalid string: must end with "${Q.suffix}"`;if(Q.format==="includes")return`Invalid string: must include "${Q.includes}"`;if(Q.format==="regex")return`Invalid string: must match pattern ${Q.pattern}`;return`Invalid ${K[Q.format]??U.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${U.divisor}`;case"unrecognized_keys":return`Unrecognized key${U.keys.length>1?"s":""}: ${D(U.keys,", ")}`;case"invalid_key":return`Invalid key in ${U.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${U.origin}`;default:return"Invalid input"}}};function Q6(){return{localeError:pH()}}var aH=()=>{let $={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function v(U){return $[U]??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"},_={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Nevalida enigo: atendiĝis instanceof ${U.expected}, riceviĝis ${G}`;return`Nevalida enigo: atendiĝis ${Q}, riceviĝis ${G}`}case"invalid_value":if(U.values.length===1)return`Nevalida enigo: atendiĝis ${I(U.values[0])}`;return`Nevalida opcio: atendiĝis unu el ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Tro granda: atendiĝis ke ${U.origin??"valoro"} havu ${Q}${U.maximum.toString()} ${q.unit??"elementojn"}`;return`Tro granda: atendiĝis ke ${U.origin??"valoro"} havu ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Tro malgranda: atendiĝis ke ${U.origin} havu ${Q}${U.minimum.toString()} ${q.unit}`;return`Tro malgranda: atendiĝis ke ${U.origin} estu ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Nevalida karaktraro: devas komenciĝi per "${Q.prefix}"`;if(Q.format==="ends_with")return`Nevalida karaktraro: devas finiĝi per "${Q.suffix}"`;if(Q.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${Q.includes}"`;if(Q.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${Q.pattern}`;return`Nevalida ${K[Q.format]??U.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${U.divisor}`;case"unrecognized_keys":return`Nekonata${U.keys.length>1?"j":""} ŝlosilo${U.keys.length>1?"j":""}: ${D(U.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${U.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${U.origin}`;default:return"Nevalida enigo"}}};function p9(){return{localeError:aH()}}var eH=()=>{let $={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function v(U){return $[U]??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"},_={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(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Entrada inválida: se esperaba instanceof ${U.expected}, recibido ${G}`;return`Entrada inválida: se esperaba ${Q}, recibido ${G}`}case"invalid_value":if(U.values.length===1)return`Entrada inválida: se esperaba ${I(U.values[0])}`;return`Opción inválida: se esperaba una de ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin),G=_[U.origin]??U.origin;if(q)return`Demasiado grande: se esperaba que ${G??"valor"} tuviera ${Q}${U.maximum.toString()} ${q.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${G??"valor"} fuera ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin),G=_[U.origin]??U.origin;if(q)return`Demasiado pequeño: se esperaba que ${G} tuviera ${Q}${U.minimum.toString()} ${q.unit}`;return`Demasiado pequeño: se esperaba que ${G} fuera ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Cadena inválida: debe comenzar con "${Q.prefix}"`;if(Q.format==="ends_with")return`Cadena inválida: debe terminar en "${Q.suffix}"`;if(Q.format==="includes")return`Cadena inválida: debe incluir "${Q.includes}"`;if(Q.format==="regex")return`Cadena inválida: debe coincidir con el patrón ${Q.pattern}`;return`Inválido ${K[Q.format]??U.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${U.divisor}`;case"unrecognized_keys":return`Llave${U.keys.length>1?"s":""} desconocida${U.keys.length>1?"s":""}: ${D(U.keys,", ")}`;case"invalid_key":return`Llave inválida en ${_[U.origin]??U.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido en ${_[U.origin]??U.origin}`;default:return"Entrada inválida"}}};function a9(){return{localeError:eH()}}var sH=()=>{let $={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function v(U){return $[U]??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:"ورودی"},_={nan:"NaN",number:"عدد",array:"آرایه"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`ورودی نامعتبر: میبایست instanceof ${U.expected} میبود، ${G} دریافت شد`;return`ورودی نامعتبر: میبایست ${Q} میبود، ${G} دریافت شد`}case"invalid_value":if(U.values.length===1)return`ورودی نامعتبر: میبایست ${I(U.values[0])} میبود`;return`گزینه نامعتبر: میبایست یکی از ${D(U.values,"|")} میبود`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`خیلی بزرگ: ${U.origin??"مقدار"} باید ${Q}${U.maximum.toString()} ${q.unit??"عنصر"} باشد`;return`خیلی بزرگ: ${U.origin??"مقدار"} باید ${Q}${U.maximum.toString()} باشد`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`خیلی کوچک: ${U.origin} باید ${Q}${U.minimum.toString()} ${q.unit} باشد`;return`خیلی کوچک: ${U.origin} باید ${Q}${U.minimum.toString()} باشد`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`رشته نامعتبر: باید با "${Q.prefix}" شروع شود`;if(Q.format==="ends_with")return`رشته نامعتبر: باید با "${Q.suffix}" تمام شود`;if(Q.format==="includes")return`رشته نامعتبر: باید شامل "${Q.includes}" باشد`;if(Q.format==="regex")return`رشته نامعتبر: باید با الگوی ${Q.pattern} مطابقت داشته باشد`;return`${K[Q.format]??U.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${U.divisor} باشد`;case"unrecognized_keys":return`کلید${U.keys.length>1?"های":""} ناشناس: ${D(U.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${U.origin}`;case"invalid_union":return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${U.origin}`;default:return"ورودی نامعتبر"}}};function e9(){return{localeError:sH()}}var $P=()=>{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 v(U){return $[U]??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"},_={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Virheellinen tyyppi: odotettiin instanceof ${U.expected}, oli ${G}`;return`Virheellinen tyyppi: odotettiin ${Q}, oli ${G}`}case"invalid_value":if(U.values.length===1)return`Virheellinen syöte: täytyy olla ${I(U.values[0])}`;return`Virheellinen valinta: täytyy olla yksi seuraavista: ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Liian suuri: ${q.subject} täytyy olla ${Q}${U.maximum.toString()} ${q.unit}`.trim();return`Liian suuri: arvon täytyy olla ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Liian pieni: ${q.subject} täytyy olla ${Q}${U.minimum.toString()} ${q.unit}`.trim();return`Liian pieni: arvon täytyy olla ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Virheellinen syöte: täytyy alkaa "${Q.prefix}"`;if(Q.format==="ends_with")return`Virheellinen syöte: täytyy loppua "${Q.suffix}"`;if(Q.format==="includes")return`Virheellinen syöte: täytyy sisältää "${Q.includes}"`;if(Q.format==="regex")return`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${Q.pattern}`;return`Virheellinen ${K[Q.format]??U.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${U.divisor} monikerta`;case"unrecognized_keys":return`${U.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${D(U.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 s9(){return{localeError:$P()}}var vP=()=>{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 v(U){return $[U]??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"},_={nan:"NaN",number:"nombre",array:"tableau"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Entrée invalide : instanceof ${U.expected} attendu, ${G} reçu`;return`Entrée invalide : ${Q} attendu, ${G} reçu`}case"invalid_value":if(U.values.length===1)return`Entrée invalide : ${I(U.values[0])} attendu`;return`Option invalide : une valeur parmi ${D(U.values,"|")} attendue`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Trop grand : ${U.origin??"valeur"} doit ${q.verb} ${Q}${U.maximum.toString()} ${q.unit??"élément(s)"}`;return`Trop grand : ${U.origin??"valeur"} doit être ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Trop petit : ${U.origin} doit ${q.verb} ${Q}${U.minimum.toString()} ${q.unit}`;return`Trop petit : ${U.origin} doit être ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Chaîne invalide : doit commencer par "${Q.prefix}"`;if(Q.format==="ends_with")return`Chaîne invalide : doit se terminer par "${Q.suffix}"`;if(Q.format==="includes")return`Chaîne invalide : doit inclure "${Q.includes}"`;if(Q.format==="regex")return`Chaîne invalide : doit correspondre au modèle ${Q.pattern}`;return`${K[Q.format]??U.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${U.divisor}`;case"unrecognized_keys":return`Clé${U.keys.length>1?"s":""} non reconnue${U.keys.length>1?"s":""} : ${D(U.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${U.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${U.origin}`;default:return"Entrée invalide"}}};function $K(){return{localeError:vP()}}var UP=()=>{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 v(U){return $[U]??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"},_={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Entrée invalide : attendu instanceof ${U.expected}, reçu ${G}`;return`Entrée invalide : attendu ${Q}, reçu ${G}`}case"invalid_value":if(U.values.length===1)return`Entrée invalide : attendu ${I(U.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"≤":"<",q=v(U.origin);if(q)return`Trop grand : attendu que ${U.origin??"la valeur"} ait ${Q}${U.maximum.toString()} ${q.unit}`;return`Trop grand : attendu que ${U.origin??"la valeur"} soit ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?"≥":">",q=v(U.origin);if(q)return`Trop petit : attendu que ${U.origin} ait ${Q}${U.minimum.toString()} ${q.unit}`;return`Trop petit : attendu que ${U.origin} soit ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Chaîne invalide : doit commencer par "${Q.prefix}"`;if(Q.format==="ends_with")return`Chaîne invalide : doit se terminer par "${Q.suffix}"`;if(Q.format==="includes")return`Chaîne invalide : doit inclure "${Q.includes}"`;if(Q.format==="regex")return`Chaîne invalide : doit correspondre au motif ${Q.pattern}`;return`${K[Q.format]??U.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${U.divisor}`;case"unrecognized_keys":return`Clé${U.keys.length>1?"s":""} non reconnue${U.keys.length>1?"s":""} : ${D(U.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${U.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${U.origin}`;default:return"Entrée invalide"}}};function vK(){return{localeError:UP()}}var KP=()=>{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"}},v={string:{unit:"תווים",shortLabel:"קצר",longLabel:"ארוך"},file:{unit:"בייטים",shortLabel:"קטן",longLabel:"גדול"},array:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},set:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},number:{unit:"",shortLabel:"קטן",longLabel:"גדול"}},K=(Y)=>Y?$[Y]:void 0,_=(Y)=>{let X=K(Y);if(X)return X.label;return Y??$.unknown.label},U=(Y)=>`ה${_(Y)}`,Q=(Y)=>{return(K(Y)?.gender??"m")==="f"?"צריכה להיות":"צריך להיות"},q=(Y)=>{if(!Y)return null;return v[Y]??null},G={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"}},j={nan:"NaN"};return(Y)=>{switch(Y.code){case"invalid_type":{let X=Y.expected,P=j[X??""]??_(X),B=Z(Y.input),N=j[B]??$[B]?.label??B;if(/^[A-Z]/.test(Y.expected))return`קלט לא תקין: צריך להיות instanceof ${Y.expected}, התקבל ${N}`;return`קלט לא תקין: צריך להיות ${P}, התקבל ${N}`}case"invalid_value":{if(Y.values.length===1)return`ערך לא תקין: הערך חייב להיות ${I(Y.values[0])}`;let X=Y.values.map((N)=>I(N));if(Y.values.length===2)return`ערך לא תקין: האפשרויות המתאימות הן ${X[0]} או ${X[1]}`;let P=X[X.length-1];return`ערך לא תקין: האפשרויות המתאימות הן ${X.slice(0,-1).join(", ")} או ${P}`}case"too_big":{let X=q(Y.origin),P=U(Y.origin??"value");if(Y.origin==="string")return`${X?.longLabel??"ארוך"} מדי: ${P} צריכה להכיל ${Y.maximum.toString()} ${X?.unit??""} ${Y.inclusive?"או פחות":"לכל היותר"}`.trim();if(Y.origin==="number"){let S=Y.inclusive?`קטן או שווה ל-${Y.maximum}`:`קטן מ-${Y.maximum}`;return`גדול מדי: ${P} צריך להיות ${S}`}if(Y.origin==="array"||Y.origin==="set"){let S=Y.origin==="set"?"צריכה":"צריך",f=Y.inclusive?`${Y.maximum} ${X?.unit??""} או פחות`:`פחות מ-${Y.maximum} ${X?.unit??""}`;return`גדול מדי: ${P} ${S} להכיל ${f}`.trim()}let B=Y.inclusive?"<=":"<",N=Q(Y.origin??"value");if(X?.unit)return`${X.longLabel} מדי: ${P} ${N} ${B}${Y.maximum.toString()} ${X.unit}`;return`${X?.longLabel??"גדול"} מדי: ${P} ${N} ${B}${Y.maximum.toString()}`}case"too_small":{let X=q(Y.origin),P=U(Y.origin??"value");if(Y.origin==="string")return`${X?.shortLabel??"קצר"} מדי: ${P} צריכה להכיל ${Y.minimum.toString()} ${X?.unit??""} ${Y.inclusive?"או יותר":"לפחות"}`.trim();if(Y.origin==="number"){let S=Y.inclusive?`גדול או שווה ל-${Y.minimum}`:`גדול מ-${Y.minimum}`;return`קטן מדי: ${P} צריך להיות ${S}`}if(Y.origin==="array"||Y.origin==="set"){let S=Y.origin==="set"?"צריכה":"צריך";if(Y.minimum===1&&Y.inclusive){let p=Y.origin==="set"?"לפחות פריט אחד":"לפחות פריט אחד";return`קטן מדי: ${P} ${S} להכיל ${p}`}let f=Y.inclusive?`${Y.minimum} ${X?.unit??""} או יותר`:`יותר מ-${Y.minimum} ${X?.unit??""}`;return`קטן מדי: ${P} ${S} להכיל ${f}`.trim()}let B=Y.inclusive?">=":">",N=Q(Y.origin??"value");if(X?.unit)return`${X.shortLabel} מדי: ${P} ${N} ${B}${Y.minimum.toString()} ${X.unit}`;return`${X?.shortLabel??"קטן"} מדי: ${P} ${N} ${B}${Y.minimum.toString()}`}case"invalid_format":{let X=Y;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 P=G[X.format],B=P?.label??X.format,S=(P?.gender??"m")==="f"?"תקינה":"תקין";return`${B} לא ${S}`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${Y.divisor}`;case"unrecognized_keys":return`מפתח${Y.keys.length>1?"ות":""} לא מזוה${Y.keys.length>1?"ים":"ה"}: ${D(Y.keys,", ")}`;case"invalid_key":return"שדה לא תקין באובייקט";case"invalid_union":return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${U(Y.origin??"array")}`;default:return"קלט לא תקין"}}};function UK(){return{localeError:KP()}}var _P=()=>{let $={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function v(U){return $[U]??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"},_={nan:"NaN",number:"szám",array:"tömb"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Érvénytelen bemenet: a várt érték instanceof ${U.expected}, a kapott érték ${G}`;return`Érvénytelen bemenet: a várt érték ${Q}, a kapott érték ${G}`}case"invalid_value":if(U.values.length===1)return`Érvénytelen bemenet: a várt érték ${I(U.values[0])}`;return`Érvénytelen opció: valamelyik érték várt ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Túl nagy: ${U.origin??"érték"} mérete túl nagy ${Q}${U.maximum.toString()} ${q.unit??"elem"}`;return`Túl nagy: a bemeneti érték ${U.origin??"érték"} túl nagy: ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Túl kicsi: a bemeneti érték ${U.origin} mérete túl kicsi ${Q}${U.minimum.toString()} ${q.unit}`;return`Túl kicsi: a bemeneti érték ${U.origin} túl kicsi ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Érvénytelen string: "${Q.prefix}" értékkel kell kezdődnie`;if(Q.format==="ends_with")return`Érvénytelen string: "${Q.suffix}" értékkel kell végződnie`;if(Q.format==="includes")return`Érvénytelen string: "${Q.includes}" értéket kell tartalmaznia`;if(Q.format==="regex")return`Érvénytelen string: ${Q.pattern} mintának kell megfelelnie`;return`Érvénytelen ${K[Q.format]??U.format}`}case"not_multiple_of":return`Érvénytelen szám: ${U.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${U.keys.length>1?"s":""}: ${D(U.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${U.origin}`;case"invalid_union":return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${U.origin}`;default:return"Érvénytelen bemenet"}}};function KK(){return{localeError:_P()}}function QG($,v,K){return Math.abs($)===1?v:K}function G4($){if(!$)return"";let v=["ա","ե","ը","ի","ո","ու","օ"],K=$[$.length-1];return $+(v.includes(K)?"ն":"ը")}var QP=()=>{let $={string:{unit:{one:"նշան",many:"նշաններ"},verb:"ունենալ"},file:{unit:{one:"բայթ",many:"բայթեր"},verb:"ունենալ"},array:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"},set:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"}};function v(U){return $[U]??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:"մուտք"},_={nan:"NaN",number:"թիվ",array:"զանգված"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Սխալ մուտքագրում․ սպասվում էր instanceof ${U.expected}, ստացվել է ${G}`;return`Սխալ մուտքագրում․ սպասվում էր ${Q}, ստացվել է ${G}`}case"invalid_value":if(U.values.length===1)return`Սխալ մուտքագրում․ սպասվում էր ${I(U.values[1])}`;return`Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q){let G=Number(U.maximum),j=QG(G,q.unit.one,q.unit.many);return`Չափազանց մեծ արժեք․ սպասվում է, որ ${G4(U.origin??"արժեք")} կունենա ${Q}${U.maximum.toString()} ${j}`}return`Չափազանց մեծ արժեք․ սպասվում է, որ ${G4(U.origin??"արժեք")} լինի ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q){let G=Number(U.minimum),j=QG(G,q.unit.one,q.unit.many);return`Չափազանց փոքր արժեք․ սպասվում է, որ ${G4(U.origin)} կունենա ${Q}${U.minimum.toString()} ${j}`}return`Չափազանց փոքր արժեք․ սպասվում է, որ ${G4(U.origin)} լինի ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Սխալ տող․ պետք է սկսվի "${Q.prefix}"-ով`;if(Q.format==="ends_with")return`Սխալ տող․ պետք է ավարտվի "${Q.suffix}"-ով`;if(Q.format==="includes")return`Սխալ տող․ պետք է պարունակի "${Q.includes}"`;if(Q.format==="regex")return`Սխալ տող․ պետք է համապատասխանի ${Q.pattern} ձևաչափին`;return`Սխալ ${K[Q.format]??U.format}`}case"not_multiple_of":return`Սխալ թիվ․ պետք է բազմապատիկ լինի ${U.divisor}-ի`;case"unrecognized_keys":return`Չճանաչված բանալի${U.keys.length>1?"ներ":""}. ${D(U.keys,", ")}`;case"invalid_key":return`Սխալ բանալի ${G4(U.origin)}-ում`;case"invalid_union":return"Սխալ մուտքագրում";case"invalid_element":return`Սխալ արժեք ${G4(U.origin)}-ում`;default:return"Սխալ մուտքագրում"}}};function _K(){return{localeError:QP()}}var qP=()=>{let $={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function v(U){return $[U]??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"},_={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Input tidak valid: diharapkan instanceof ${U.expected}, diterima ${G}`;return`Input tidak valid: diharapkan ${Q}, diterima ${G}`}case"invalid_value":if(U.values.length===1)return`Input tidak valid: diharapkan ${I(U.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Terlalu besar: diharapkan ${U.origin??"value"} memiliki ${Q}${U.maximum.toString()} ${q.unit??"elemen"}`;return`Terlalu besar: diharapkan ${U.origin??"value"} menjadi ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Terlalu kecil: diharapkan ${U.origin} memiliki ${Q}${U.minimum.toString()} ${q.unit}`;return`Terlalu kecil: diharapkan ${U.origin} menjadi ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`String tidak valid: harus dimulai dengan "${Q.prefix}"`;if(Q.format==="ends_with")return`String tidak valid: harus berakhir dengan "${Q.suffix}"`;if(Q.format==="includes")return`String tidak valid: harus menyertakan "${Q.includes}"`;if(Q.format==="regex")return`String tidak valid: harus sesuai pola ${Q.pattern}`;return`${K[Q.format]??U.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${U.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${U.keys.length>1?"s":""}: ${D(U.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${U.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${U.origin}`;default:return"Input tidak valid"}}};function QK(){return{localeError:qP()}}var GP=()=>{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 v(U){return $[U]??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"},_={nan:"NaN",number:"númer",array:"fylki"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Rangt gildi: Þú slóst inn ${G} þar sem á að vera instanceof ${U.expected}`;return`Rangt gildi: Þú slóst inn ${G} þar sem á að vera ${Q}`}case"invalid_value":if(U.values.length===1)return`Rangt gildi: gert ráð fyrir ${I(U.values[0])}`;return`Ógilt val: má vera eitt af eftirfarandi ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Of stórt: gert er ráð fyrir að ${U.origin??"gildi"} hafi ${Q}${U.maximum.toString()} ${q.unit??"hluti"}`;return`Of stórt: gert er ráð fyrir að ${U.origin??"gildi"} sé ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Of lítið: gert er ráð fyrir að ${U.origin} hafi ${Q}${U.minimum.toString()} ${q.unit}`;return`Of lítið: gert er ráð fyrir að ${U.origin} sé ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Ógildur strengur: verður að byrja á "${Q.prefix}"`;if(Q.format==="ends_with")return`Ógildur strengur: verður að enda á "${Q.suffix}"`;if(Q.format==="includes")return`Ógildur strengur: verður að innihalda "${Q.includes}"`;if(Q.format==="regex")return`Ógildur strengur: verður að fylgja mynstri ${Q.pattern}`;return`Rangt ${K[Q.format]??U.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${U.divisor}`;case"unrecognized_keys":return`Óþekkt ${U.keys.length>1?"ir lyklar":"ur lykill"}: ${D(U.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${U.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${U.origin}`;default:return"Rangt gildi"}}};function qK(){return{localeError:GP()}}var WP=()=>{let $={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function v(U){return $[U]??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"},_={nan:"NaN",number:"numero",array:"vettore"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Input non valido: atteso instanceof ${U.expected}, ricevuto ${G}`;return`Input non valido: atteso ${Q}, ricevuto ${G}`}case"invalid_value":if(U.values.length===1)return`Input non valido: atteso ${I(U.values[0])}`;return`Opzione non valida: atteso uno tra ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Troppo grande: ${U.origin??"valore"} deve avere ${Q}${U.maximum.toString()} ${q.unit??"elementi"}`;return`Troppo grande: ${U.origin??"valore"} deve essere ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Troppo piccolo: ${U.origin} deve avere ${Q}${U.minimum.toString()} ${q.unit}`;return`Troppo piccolo: ${U.origin} deve essere ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Stringa non valida: deve iniziare con "${Q.prefix}"`;if(Q.format==="ends_with")return`Stringa non valida: deve terminare con "${Q.suffix}"`;if(Q.format==="includes")return`Stringa non valida: deve includere "${Q.includes}"`;if(Q.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${Q.pattern}`;return`Invalid ${K[Q.format]??U.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${U.divisor}`;case"unrecognized_keys":return`Chiav${U.keys.length>1?"i":"e"} non riconosciut${U.keys.length>1?"e":"a"}: ${D(U.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${U.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${U.origin}`;default:return"Input non valido"}}};function GK(){return{localeError:WP()}}var jP=()=>{let $={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function v(U){return $[U]??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:"入力値"},_={nan:"NaN",number:"数値",array:"配列"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`無効な入力: instanceof ${U.expected}が期待されましたが、${G}が入力されました`;return`無効な入力: ${Q}が期待されましたが、${G}が入力されました`}case"invalid_value":if(U.values.length===1)return`無効な入力: ${I(U.values[0])}が期待されました`;return`無効な選択: ${D(U.values,"、")}のいずれかである必要があります`;case"too_big":{let Q=U.inclusive?"以下である":"より小さい",q=v(U.origin);if(q)return`大きすぎる値: ${U.origin??"値"}は${U.maximum.toString()}${q.unit??"要素"}${Q}必要があります`;return`大きすぎる値: ${U.origin??"値"}は${U.maximum.toString()}${Q}必要があります`}case"too_small":{let Q=U.inclusive?"以上である":"より大きい",q=v(U.origin);if(q)return`小さすぎる値: ${U.origin}は${U.minimum.toString()}${q.unit}${Q}必要があります`;return`小さすぎる値: ${U.origin}は${U.minimum.toString()}${Q}必要があります`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`無効な文字列: "${Q.prefix}"で始まる必要があります`;if(Q.format==="ends_with")return`無効な文字列: "${Q.suffix}"で終わる必要があります`;if(Q.format==="includes")return`無効な文字列: "${Q.includes}"を含む必要があります`;if(Q.format==="regex")return`無効な文字列: パターン${Q.pattern}に一致する必要があります`;return`無効な${K[Q.format]??U.format}`}case"not_multiple_of":return`無効な数値: ${U.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${U.keys.length>1?"群":""}: ${D(U.keys,"、")}`;case"invalid_key":return`${U.origin}内の無効なキー`;case"invalid_union":return"無効な入力";case"invalid_element":return`${U.origin}内の無効な値`;default:return"無効な入力"}}};function WK(){return{localeError:jP()}}var YP=()=>{let $={string:{unit:"სიმბოლო",verb:"უნდა შეიცავდეს"},file:{unit:"ბაიტი",verb:"უნდა შეიცავდეს"},array:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},set:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"}};function v(U){return $[U]??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:"შეყვანა"},_={nan:"NaN",number:"რიცხვი",string:"სტრინგი",boolean:"ბულეანი",function:"ფუნქცია",array:"მასივი"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`არასწორი შეყვანა: მოსალოდნელი instanceof ${U.expected}, მიღებული ${G}`;return`არასწორი შეყვანა: მოსალოდნელი ${Q}, მიღებული ${G}`}case"invalid_value":if(U.values.length===1)return`არასწორი შეყვანა: მოსალოდნელი ${I(U.values[0])}`;return`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${D(U.values,"|")}-დან`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`ზედმეტად დიდი: მოსალოდნელი ${U.origin??"მნიშვნელობა"} ${q.verb} ${Q}${U.maximum.toString()} ${q.unit}`;return`ზედმეტად დიდი: მოსალოდნელი ${U.origin??"მნიშვნელობა"} იყოს ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`ზედმეტად პატარა: მოსალოდნელი ${U.origin} ${q.verb} ${Q}${U.minimum.toString()} ${q.unit}`;return`ზედმეტად პატარა: მოსალოდნელი ${U.origin} იყოს ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`არასწორი სტრინგი: უნდა იწყებოდეს "${Q.prefix}"-ით`;if(Q.format==="ends_with")return`არასწორი სტრინგი: უნდა მთავრდებოდეს "${Q.suffix}"-ით`;if(Q.format==="includes")return`არასწორი სტრინგი: უნდა შეიცავდეს "${Q.includes}"-ს`;if(Q.format==="regex")return`არასწორი სტრინგი: უნდა შეესაბამებოდეს შაბლონს ${Q.pattern}`;return`არასწორი ${K[Q.format]??U.format}`}case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${U.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${U.keys.length>1?"ები":"ი"}: ${D(U.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${U.origin}-ში`;case"invalid_union":return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${U.origin}-ში`;default:return"არასწორი შეყვანა"}}};function jK(){return{localeError:YP()}}var JP=()=>{let $={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function v(U){return $[U]??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:"ទិន្នន័យបញ្ចូល"},_={nan:"NaN",number:"លេខ",array:"អារេ (Array)",null:"គ្មានតម្លៃ (null)"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${U.expected} ប៉ុន្តែទទួលបាន ${G}`;return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${Q} ប៉ុន្តែទទួលបាន ${G}`}case"invalid_value":if(U.values.length===1)return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${I(U.values[0])}`;return`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`ធំពេក៖ ត្រូវការ ${U.origin??"តម្លៃ"} ${Q} ${U.maximum.toString()} ${q.unit??"ធាតុ"}`;return`ធំពេក៖ ត្រូវការ ${U.origin??"តម្លៃ"} ${Q} ${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`តូចពេក៖ ត្រូវការ ${U.origin} ${Q} ${U.minimum.toString()} ${q.unit}`;return`តូចពេក៖ ត្រូវការ ${U.origin} ${Q} ${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${Q.prefix}"`;if(Q.format==="ends_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${Q.suffix}"`;if(Q.format==="includes")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${Q.includes}"`;if(Q.format==="regex")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${Q.pattern}`;return`មិនត្រឹមត្រូវ៖ ${K[Q.format]??U.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${U.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${D(U.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${U.origin}`;case"invalid_union":return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${U.origin}`;default:return"ទិន្នន័យមិនត្រឹមត្រូវ"}}};function q6(){return{localeError:JP()}}function YK(){return q6()}var XP=()=>{let $={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function v(U){return $[U]??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:"입력"},_={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`잘못된 입력: 예상 타입은 instanceof ${U.expected}, 받은 타입은 ${G}입니다`;return`잘못된 입력: 예상 타입은 ${Q}, 받은 타입은 ${G}입니다`}case"invalid_value":if(U.values.length===1)return`잘못된 입력: 값은 ${I(U.values[0])} 이어야 합니다`;return`잘못된 옵션: ${D(U.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{let Q=U.inclusive?"이하":"미만",q=Q==="미만"?"이어야 합니다":"여야 합니다",G=v(U.origin),j=G?.unit??"요소";if(G)return`${U.origin??"값"}이 너무 큽니다: ${U.maximum.toString()}${j} ${Q}${q}`;return`${U.origin??"값"}이 너무 큽니다: ${U.maximum.toString()} ${Q}${q}`}case"too_small":{let Q=U.inclusive?"이상":"초과",q=Q==="이상"?"이어야 합니다":"여야 합니다",G=v(U.origin),j=G?.unit??"요소";if(G)return`${U.origin??"값"}이 너무 작습니다: ${U.minimum.toString()}${j} ${Q}${q}`;return`${U.origin??"값"}이 너무 작습니다: ${U.minimum.toString()} ${Q}${q}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`잘못된 문자열: "${Q.prefix}"(으)로 시작해야 합니다`;if(Q.format==="ends_with")return`잘못된 문자열: "${Q.suffix}"(으)로 끝나야 합니다`;if(Q.format==="includes")return`잘못된 문자열: "${Q.includes}"을(를) 포함해야 합니다`;if(Q.format==="regex")return`잘못된 문자열: 정규식 ${Q.pattern} 패턴과 일치해야 합니다`;return`잘못된 ${K[Q.format]??U.format}`}case"not_multiple_of":return`잘못된 숫자: ${U.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${D(U.keys,", ")}`;case"invalid_key":return`잘못된 키: ${U.origin}`;case"invalid_union":return"잘못된 입력";case"invalid_element":return`잘못된 값: ${U.origin}`;default:return"잘못된 입력"}}};function JK(){return{localeError:XP()}}var G6=($)=>{return $.charAt(0).toUpperCase()+$.slice(1)};function qG($){let v=Math.abs($),K=v%10,_=v%100;if(_>=11&&_<=19||K===0)return"many";if(K===1)return"one";return"few"}var HP=()=>{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 v(U,Q,q,G){let j=$[U]??null;if(j===null)return j;return{unit:j.unit[Q],verb:j.verb[G][q?"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"},_={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(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Gautas tipas ${G}, o tikėtasi - instanceof ${U.expected}`;return`Gautas tipas ${G}, o tikėtasi - ${Q}`}case"invalid_value":if(U.values.length===1)return`Privalo būti ${I(U.values[0])}`;return`Privalo būti vienas iš ${D(U.values,"|")} pasirinkimų`;case"too_big":{let Q=_[U.origin]??U.origin,q=v(U.origin,qG(Number(U.maximum)),U.inclusive??!1,"smaller");if(q?.verb)return`${G6(Q??U.origin??"reikšmė")} ${q.verb} ${U.maximum.toString()} ${q.unit??"elementų"}`;let G=U.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${G6(Q??U.origin??"reikšmė")} turi būti ${G} ${U.maximum.toString()} ${q?.unit}`}case"too_small":{let Q=_[U.origin]??U.origin,q=v(U.origin,qG(Number(U.minimum)),U.inclusive??!1,"bigger");if(q?.verb)return`${G6(Q??U.origin??"reikšmė")} ${q.verb} ${U.minimum.toString()} ${q.unit??"elementų"}`;let G=U.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${G6(Q??U.origin??"reikšmė")} turi būti ${G} ${U.minimum.toString()} ${q?.unit}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Eilutė privalo prasidėti "${Q.prefix}"`;if(Q.format==="ends_with")return`Eilutė privalo pasibaigti "${Q.suffix}"`;if(Q.format==="includes")return`Eilutė privalo įtraukti "${Q.includes}"`;if(Q.format==="regex")return`Eilutė privalo atitikti ${Q.pattern}`;return`Neteisingas ${K[Q.format]??U.format}`}case"not_multiple_of":return`Skaičius privalo būti ${U.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpažint${U.keys.length>1?"i":"as"} rakt${U.keys.length>1?"ai":"as"}: ${D(U.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga įvestis";case"invalid_element":{let Q=_[U.origin]??U.origin;return`${G6(Q??U.origin??"reikšmė")} turi klaidingą įvestį`}default:return"Klaidinga įvestis"}}};function XK(){return{localeError:HP()}}var PP=()=>{let $={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function v(U){return $[U]??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:"внес"},_={nan:"NaN",number:"број",array:"низа"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Грешен внес: се очекува instanceof ${U.expected}, примено ${G}`;return`Грешен внес: се очекува ${Q}, примено ${G}`}case"invalid_value":if(U.values.length===1)return`Invalid input: expected ${I(U.values[0])}`;return`Грешана опција: се очекува една ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Премногу голем: се очекува ${U.origin??"вредноста"} да има ${Q}${U.maximum.toString()} ${q.unit??"елементи"}`;return`Премногу голем: се очекува ${U.origin??"вредноста"} да биде ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Премногу мал: се очекува ${U.origin} да има ${Q}${U.minimum.toString()} ${q.unit}`;return`Премногу мал: се очекува ${U.origin} да биде ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Неважечка низа: мора да започнува со "${Q.prefix}"`;if(Q.format==="ends_with")return`Неважечка низа: мора да завршува со "${Q.suffix}"`;if(Q.format==="includes")return`Неважечка низа: мора да вклучува "${Q.includes}"`;if(Q.format==="regex")return`Неважечка низа: мора да одгоара на патернот ${Q.pattern}`;return`Invalid ${K[Q.format]??U.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${U.divisor}`;case"unrecognized_keys":return`${U.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${D(U.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${U.origin}`;case"invalid_union":return"Грешен внес";case"invalid_element":return`Грешна вредност во ${U.origin}`;default:return"Грешен внес"}}};function HK(){return{localeError:PP()}}var VP=()=>{let $={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function v(U){return $[U]??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"},_={nan:"NaN",number:"nombor"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Input tidak sah: dijangka instanceof ${U.expected}, diterima ${G}`;return`Input tidak sah: dijangka ${Q}, diterima ${G}`}case"invalid_value":if(U.values.length===1)return`Input tidak sah: dijangka ${I(U.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Terlalu besar: dijangka ${U.origin??"nilai"} ${q.verb} ${Q}${U.maximum.toString()} ${q.unit??"elemen"}`;return`Terlalu besar: dijangka ${U.origin??"nilai"} adalah ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Terlalu kecil: dijangka ${U.origin} ${q.verb} ${Q}${U.minimum.toString()} ${q.unit}`;return`Terlalu kecil: dijangka ${U.origin} adalah ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`String tidak sah: mesti bermula dengan "${Q.prefix}"`;if(Q.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${Q.suffix}"`;if(Q.format==="includes")return`String tidak sah: mesti mengandungi "${Q.includes}"`;if(Q.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${Q.pattern}`;return`${K[Q.format]??U.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${U.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${D(U.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${U.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${U.origin}`;default:return"Input tidak sah"}}};function PK(){return{localeError:VP()}}var BP=()=>{let $={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function v(U){return $[U]??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"},_={nan:"NaN",number:"getal"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Ongeldige invoer: verwacht instanceof ${U.expected}, ontving ${G}`;return`Ongeldige invoer: verwacht ${Q}, ontving ${G}`}case"invalid_value":if(U.values.length===1)return`Ongeldige invoer: verwacht ${I(U.values[0])}`;return`Ongeldige optie: verwacht één van ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin),G=U.origin==="date"?"laat":U.origin==="string"?"lang":"groot";if(q)return`Te ${G}: verwacht dat ${U.origin??"waarde"} ${Q}${U.maximum.toString()} ${q.unit??"elementen"} ${q.verb}`;return`Te ${G}: verwacht dat ${U.origin??"waarde"} ${Q}${U.maximum.toString()} is`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin),G=U.origin==="date"?"vroeg":U.origin==="string"?"kort":"klein";if(q)return`Te ${G}: verwacht dat ${U.origin} ${Q}${U.minimum.toString()} ${q.unit} ${q.verb}`;return`Te ${G}: verwacht dat ${U.origin} ${Q}${U.minimum.toString()} is`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Ongeldige tekst: moet met "${Q.prefix}" beginnen`;if(Q.format==="ends_with")return`Ongeldige tekst: moet op "${Q.suffix}" eindigen`;if(Q.format==="includes")return`Ongeldige tekst: moet "${Q.includes}" bevatten`;if(Q.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${Q.pattern}`;return`Ongeldig: ${K[Q.format]??U.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${U.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${U.keys.length>1?"s":""}: ${D(U.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${U.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${U.origin}`;default:return"Ongeldige invoer"}}};function VK(){return{localeError:BP()}}var DP=()=>{let $={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function v(U){return $[U]??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"},_={nan:"NaN",number:"tall",array:"liste"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Ugyldig input: forventet instanceof ${U.expected}, fikk ${G}`;return`Ugyldig input: forventet ${Q}, fikk ${G}`}case"invalid_value":if(U.values.length===1)return`Ugyldig verdi: forventet ${I(U.values[0])}`;return`Ugyldig valg: forventet en av ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`For stor(t): forventet ${U.origin??"value"} til å ha ${Q}${U.maximum.toString()} ${q.unit??"elementer"}`;return`For stor(t): forventet ${U.origin??"value"} til å ha ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`For lite(n): forventet ${U.origin} til å ha ${Q}${U.minimum.toString()} ${q.unit}`;return`For lite(n): forventet ${U.origin} til å ha ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Ugyldig streng: må starte med "${Q.prefix}"`;if(Q.format==="ends_with")return`Ugyldig streng: må ende med "${Q.suffix}"`;if(Q.format==="includes")return`Ugyldig streng: må inneholde "${Q.includes}"`;if(Q.format==="regex")return`Ugyldig streng: må matche mønsteret ${Q.pattern}`;return`Ugyldig ${K[Q.format]??U.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${U.divisor}`;case"unrecognized_keys":return`${U.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${D(U.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${U.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${U.origin}`;default:return"Ugyldig input"}}};function BK(){return{localeError:DP()}}var bP=()=>{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 v(U){return $[U]??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"},_={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Fâsit giren: umulan instanceof ${U.expected}, alınan ${G}`;return`Fâsit giren: umulan ${Q}, alınan ${G}`}case"invalid_value":if(U.values.length===1)return`Fâsit giren: umulan ${I(U.values[0])}`;return`Fâsit tercih: mûteberler ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Fazla büyük: ${U.origin??"value"}, ${Q}${U.maximum.toString()} ${q.unit??"elements"} sahip olmalıydı.`;return`Fazla büyük: ${U.origin??"value"}, ${Q}${U.maximum.toString()} olmalıydı.`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Fazla küçük: ${U.origin}, ${Q}${U.minimum.toString()} ${q.unit} sahip olmalıydı.`;return`Fazla küçük: ${U.origin}, ${Q}${U.minimum.toString()} olmalıydı.`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Fâsit metin: "${Q.prefix}" ile başlamalı.`;if(Q.format==="ends_with")return`Fâsit metin: "${Q.suffix}" ile bitmeli.`;if(Q.format==="includes")return`Fâsit metin: "${Q.includes}" ihtivâ etmeli.`;if(Q.format==="regex")return`Fâsit metin: ${Q.pattern} nakşına uymalı.`;return`Fâsit ${K[Q.format]??U.format}`}case"not_multiple_of":return`Fâsit sayı: ${U.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${U.keys.length>1?"s":""}: ${D(U.keys,", ")}`;case"invalid_key":return`${U.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${U.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};function DK(){return{localeError:bP()}}var kP=()=>{let $={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function v(U){return $[U]??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:"ورودي"},_={nan:"NaN",number:"عدد",array:"ارې"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`ناسم ورودي: باید instanceof ${U.expected} وای, مګر ${G} ترلاسه شو`;return`ناسم ورودي: باید ${Q} وای, مګر ${G} ترلاسه شو`}case"invalid_value":if(U.values.length===1)return`ناسم ورودي: باید ${I(U.values[0])} وای`;return`ناسم انتخاب: باید یو له ${D(U.values,"|")} څخه وای`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`ډیر لوی: ${U.origin??"ارزښت"} باید ${Q}${U.maximum.toString()} ${q.unit??"عنصرونه"} ولري`;return`ډیر لوی: ${U.origin??"ارزښت"} باید ${Q}${U.maximum.toString()} وي`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`ډیر کوچنی: ${U.origin} باید ${Q}${U.minimum.toString()} ${q.unit} ولري`;return`ډیر کوچنی: ${U.origin} باید ${Q}${U.minimum.toString()} وي`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`ناسم متن: باید د "${Q.prefix}" سره پیل شي`;if(Q.format==="ends_with")return`ناسم متن: باید د "${Q.suffix}" سره پای ته ورسيږي`;if(Q.format==="includes")return`ناسم متن: باید "${Q.includes}" ولري`;if(Q.format==="regex")return`ناسم متن: باید د ${Q.pattern} سره مطابقت ولري`;return`${K[Q.format]??U.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${U.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${U.keys.length>1?"کلیډونه":"کلیډ"}: ${D(U.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${U.origin} کې`;case"invalid_union":return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${U.origin} کې`;default:return"ناسمه ورودي"}}};function bK(){return{localeError:kP()}}var NP=()=>{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 v(U){return $[U]??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"},_={nan:"NaN",number:"liczba",array:"tablica"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Nieprawidłowe dane wejściowe: oczekiwano instanceof ${U.expected}, otrzymano ${G}`;return`Nieprawidłowe dane wejściowe: oczekiwano ${Q}, otrzymano ${G}`}case"invalid_value":if(U.values.length===1)return`Nieprawidłowe dane wejściowe: oczekiwano ${I(U.values[0])}`;return`Nieprawidłowa opcja: oczekiwano jednej z wartości ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Za duża wartość: oczekiwano, że ${U.origin??"wartość"} będzie mieć ${Q}${U.maximum.toString()} ${q.unit??"elementów"}`;return`Zbyt duż(y/a/e): oczekiwano, że ${U.origin??"wartość"} będzie wynosić ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Za mała wartość: oczekiwano, że ${U.origin??"wartość"} będzie mieć ${Q}${U.minimum.toString()} ${q.unit??"elementów"}`;return`Zbyt mał(y/a/e): oczekiwano, że ${U.origin??"wartość"} będzie wynosić ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Nieprawidłowy ciąg znaków: musi zaczynać się od "${Q.prefix}"`;if(Q.format==="ends_with")return`Nieprawidłowy ciąg znaków: musi kończyć się na "${Q.suffix}"`;if(Q.format==="includes")return`Nieprawidłowy ciąg znaków: musi zawierać "${Q.includes}"`;if(Q.format==="regex")return`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${Q.pattern}`;return`Nieprawidłow(y/a/e) ${K[Q.format]??U.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${U.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${U.keys.length>1?"s":""}: ${D(U.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${U.origin}`;case"invalid_union":return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${U.origin}`;default:return"Nieprawidłowe dane wejściowe"}}};function kK(){return{localeError:NP()}}var wP=()=>{let $={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function v(U){return $[U]??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"},_={nan:"NaN",number:"número",null:"nulo"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Tipo inválido: esperado instanceof ${U.expected}, recebido ${G}`;return`Tipo inválido: esperado ${Q}, recebido ${G}`}case"invalid_value":if(U.values.length===1)return`Entrada inválida: esperado ${I(U.values[0])}`;return`Opção inválida: esperada uma das ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Muito grande: esperado que ${U.origin??"valor"} tivesse ${Q}${U.maximum.toString()} ${q.unit??"elementos"}`;return`Muito grande: esperado que ${U.origin??"valor"} fosse ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Muito pequeno: esperado que ${U.origin} tivesse ${Q}${U.minimum.toString()} ${q.unit}`;return`Muito pequeno: esperado que ${U.origin} fosse ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Texto inválido: deve começar com "${Q.prefix}"`;if(Q.format==="ends_with")return`Texto inválido: deve terminar com "${Q.suffix}"`;if(Q.format==="includes")return`Texto inválido: deve incluir "${Q.includes}"`;if(Q.format==="regex")return`Texto inválido: deve corresponder ao padrão ${Q.pattern}`;return`${K[Q.format]??U.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${U.divisor}`;case"unrecognized_keys":return`Chave${U.keys.length>1?"s":""} desconhecida${U.keys.length>1?"s":""}: ${D(U.keys,", ")}`;case"invalid_key":return`Chave inválida em ${U.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${U.origin}`;default:return"Campo inválido"}}};function NK(){return{localeError:wP()}}function GG($,v,K,_){let U=Math.abs($),Q=U%10,q=U%100;if(q>=11&&q<=19)return _;if(Q===1)return v;if(Q>=2&&Q<=4)return K;return _}var MP=()=>{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 v(U){return $[U]??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:"ввод"},_={nan:"NaN",number:"число",array:"массив"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Неверный ввод: ожидалось instanceof ${U.expected}, получено ${G}`;return`Неверный ввод: ожидалось ${Q}, получено ${G}`}case"invalid_value":if(U.values.length===1)return`Неверный ввод: ожидалось ${I(U.values[0])}`;return`Неверный вариант: ожидалось одно из ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q){let G=Number(U.maximum),j=GG(G,q.unit.one,q.unit.few,q.unit.many);return`Слишком большое значение: ожидалось, что ${U.origin??"значение"} будет иметь ${Q}${U.maximum.toString()} ${j}`}return`Слишком большое значение: ожидалось, что ${U.origin??"значение"} будет ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q){let G=Number(U.minimum),j=GG(G,q.unit.one,q.unit.few,q.unit.many);return`Слишком маленькое значение: ожидалось, что ${U.origin} будет иметь ${Q}${U.minimum.toString()} ${j}`}return`Слишком маленькое значение: ожидалось, что ${U.origin} будет ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Неверная строка: должна начинаться с "${Q.prefix}"`;if(Q.format==="ends_with")return`Неверная строка: должна заканчиваться на "${Q.suffix}"`;if(Q.format==="includes")return`Неверная строка: должна содержать "${Q.includes}"`;if(Q.format==="regex")return`Неверная строка: должна соответствовать шаблону ${Q.pattern}`;return`Неверный ${K[Q.format]??U.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${U.divisor}`;case"unrecognized_keys":return`Нераспознанн${U.keys.length>1?"ые":"ый"} ключ${U.keys.length>1?"и":""}: ${D(U.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${U.origin}`;case"invalid_union":return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${U.origin}`;default:return"Неверные входные данные"}}};function wK(){return{localeError:MP()}}var IP=()=>{let $={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function v(U){return $[U]??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"},_={nan:"NaN",number:"število",array:"tabela"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Neveljaven vnos: pričakovano instanceof ${U.expected}, prejeto ${G}`;return`Neveljaven vnos: pričakovano ${Q}, prejeto ${G}`}case"invalid_value":if(U.values.length===1)return`Neveljaven vnos: pričakovano ${I(U.values[0])}`;return`Neveljavna možnost: pričakovano eno izmed ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Preveliko: pričakovano, da bo ${U.origin??"vrednost"} imelo ${Q}${U.maximum.toString()} ${q.unit??"elementov"}`;return`Preveliko: pričakovano, da bo ${U.origin??"vrednost"} ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Premajhno: pričakovano, da bo ${U.origin} imelo ${Q}${U.minimum.toString()} ${q.unit}`;return`Premajhno: pričakovano, da bo ${U.origin} ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Neveljaven niz: mora se začeti z "${Q.prefix}"`;if(Q.format==="ends_with")return`Neveljaven niz: mora se končati z "${Q.suffix}"`;if(Q.format==="includes")return`Neveljaven niz: mora vsebovati "${Q.includes}"`;if(Q.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${Q.pattern}`;return`Neveljaven ${K[Q.format]??U.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${U.divisor}`;case"unrecognized_keys":return`Neprepoznan${U.keys.length>1?"i ključi":" ključ"}: ${D(U.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${U.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${U.origin}`;default:return"Neveljaven vnos"}}};function MK(){return{localeError:IP()}}var ZP=()=>{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 v(U){return $[U]??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"},_={nan:"NaN",number:"antal",array:"lista"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Ogiltig inmatning: förväntat instanceof ${U.expected}, fick ${G}`;return`Ogiltig inmatning: förväntat ${Q}, fick ${G}`}case"invalid_value":if(U.values.length===1)return`Ogiltig inmatning: förväntat ${I(U.values[0])}`;return`Ogiltigt val: förväntade en av ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`För stor(t): förväntade ${U.origin??"värdet"} att ha ${Q}${U.maximum.toString()} ${q.unit??"element"}`;return`För stor(t): förväntat ${U.origin??"värdet"} att ha ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`För lite(t): förväntade ${U.origin??"värdet"} att ha ${Q}${U.minimum.toString()} ${q.unit}`;return`För lite(t): förväntade ${U.origin??"värdet"} att ha ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Ogiltig sträng: måste börja med "${Q.prefix}"`;if(Q.format==="ends_with")return`Ogiltig sträng: måste sluta med "${Q.suffix}"`;if(Q.format==="includes")return`Ogiltig sträng: måste innehålla "${Q.includes}"`;if(Q.format==="regex")return`Ogiltig sträng: måste matcha mönstret "${Q.pattern}"`;return`Ogiltig(t) ${K[Q.format]??U.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${U.divisor}`;case"unrecognized_keys":return`${U.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${D(U.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${U.origin??"värdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${U.origin??"värdet"}`;default:return"Ogiltig input"}}};function IK(){return{localeError:ZP()}}var zP=()=>{let $={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function v(U){return $[U]??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"},_={nan:"NaN",number:"எண்",array:"அணி",null:"வெறுமை"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${U.expected}, பெறப்பட்டது ${G}`;return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${Q}, பெறப்பட்டது ${G}`}case"invalid_value":if(U.values.length===1)return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${I(U.values[0])}`;return`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${D(U.values,"|")} இல் ஒன்று`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${U.origin??"மதிப்பு"} ${Q}${U.maximum.toString()} ${q.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`;return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${U.origin??"மதிப்பு"} ${Q}${U.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${U.origin} ${Q}${U.minimum.toString()} ${q.unit} ஆக இருக்க வேண்டும்`;return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${U.origin} ${Q}${U.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`தவறான சரம்: "${Q.prefix}" இல் தொடங்க வேண்டும்`;if(Q.format==="ends_with")return`தவறான சரம்: "${Q.suffix}" இல் முடிவடைய வேண்டும்`;if(Q.format==="includes")return`தவறான சரம்: "${Q.includes}" ஐ உள்ளடக்க வேண்டும்`;if(Q.format==="regex")return`தவறான சரம்: ${Q.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`;return`தவறான ${K[Q.format]??U.format}`}case"not_multiple_of":return`தவறான எண்: ${U.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${U.keys.length>1?"கள்":""}: ${D(U.keys,", ")}`;case"invalid_key":return`${U.origin} இல் தவறான விசை`;case"invalid_union":return"தவறான உள்ளீடு";case"invalid_element":return`${U.origin} இல் தவறான மதிப்பு`;default:return"தவறான உள்ளீடு"}}};function ZK(){return{localeError:zP()}}var LP=()=>{let $={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function v(U){return $[U]??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:"ข้อมูลที่ป้อน"},_={nan:"NaN",number:"ตัวเลข",array:"อาร์เรย์ (Array)",null:"ไม่มีค่า (null)"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${U.expected} แต่ได้รับ ${G}`;return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${Q} แต่ได้รับ ${G}`}case"invalid_value":if(U.values.length===1)return`ค่าไม่ถูกต้อง: ควรเป็น ${I(U.values[0])}`;return`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"ไม่เกิน":"น้อยกว่า",q=v(U.origin);if(q)return`เกินกำหนด: ${U.origin??"ค่า"} ควรมี${Q} ${U.maximum.toString()} ${q.unit??"รายการ"}`;return`เกินกำหนด: ${U.origin??"ค่า"} ควรมี${Q} ${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?"อย่างน้อย":"มากกว่า",q=v(U.origin);if(q)return`น้อยกว่ากำหนด: ${U.origin} ควรมี${Q} ${U.minimum.toString()} ${q.unit}`;return`น้อยกว่ากำหนด: ${U.origin} ควรมี${Q} ${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${Q.prefix}"`;if(Q.format==="ends_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${Q.suffix}"`;if(Q.format==="includes")return`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${Q.includes}" อยู่ในข้อความ`;if(Q.format==="regex")return`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${Q.pattern}`;return`รูปแบบไม่ถูกต้อง: ${K[Q.format]??U.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${U.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${D(U.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${U.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${U.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};function zK(){return{localeError:LP()}}var AP=()=>{let $={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function v(U){return $[U]??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"},_={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Geçersiz değer: beklenen instanceof ${U.expected}, alınan ${G}`;return`Geçersiz değer: beklenen ${Q}, alınan ${G}`}case"invalid_value":if(U.values.length===1)return`Geçersiz değer: beklenen ${I(U.values[0])}`;return`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Çok büyük: beklenen ${U.origin??"değer"} ${Q}${U.maximum.toString()} ${q.unit??"öğe"}`;return`Çok büyük: beklenen ${U.origin??"değer"} ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Çok küçük: beklenen ${U.origin} ${Q}${U.minimum.toString()} ${q.unit}`;return`Çok küçük: beklenen ${U.origin} ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Geçersiz metin: "${Q.prefix}" ile başlamalı`;if(Q.format==="ends_with")return`Geçersiz metin: "${Q.suffix}" ile bitmeli`;if(Q.format==="includes")return`Geçersiz metin: "${Q.includes}" içermeli`;if(Q.format==="regex")return`Geçersiz metin: ${Q.pattern} desenine uymalı`;return`Geçersiz ${K[Q.format]??U.format}`}case"not_multiple_of":return`Geçersiz sayı: ${U.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${U.keys.length>1?"lar":""}: ${D(U.keys,", ")}`;case"invalid_key":return`${U.origin} içinde geçersiz anahtar`;case"invalid_union":return"Geçersiz değer";case"invalid_element":return`${U.origin} içinde geçersiz değer`;default:return"Geçersiz değer"}}};function LK(){return{localeError:AP()}}var FP=()=>{let $={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function v(U){return $[U]??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:"вхідні дані"},_={nan:"NaN",number:"число",array:"масив"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Неправильні вхідні дані: очікується instanceof ${U.expected}, отримано ${G}`;return`Неправильні вхідні дані: очікується ${Q}, отримано ${G}`}case"invalid_value":if(U.values.length===1)return`Неправильні вхідні дані: очікується ${I(U.values[0])}`;return`Неправильна опція: очікується одне з ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Занадто велике: очікується, що ${U.origin??"значення"} ${q.verb} ${Q}${U.maximum.toString()} ${q.unit??"елементів"}`;return`Занадто велике: очікується, що ${U.origin??"значення"} буде ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Занадто мале: очікується, що ${U.origin} ${q.verb} ${Q}${U.minimum.toString()} ${q.unit}`;return`Занадто мале: очікується, що ${U.origin} буде ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Неправильний рядок: повинен починатися з "${Q.prefix}"`;if(Q.format==="ends_with")return`Неправильний рядок: повинен закінчуватися на "${Q.suffix}"`;if(Q.format==="includes")return`Неправильний рядок: повинен містити "${Q.includes}"`;if(Q.format==="regex")return`Неправильний рядок: повинен відповідати шаблону ${Q.pattern}`;return`Неправильний ${K[Q.format]??U.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${U.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${U.keys.length>1?"і":""}: ${D(U.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${U.origin}`;case"invalid_union":return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${U.origin}`;default:return"Неправильні вхідні дані"}}};function W6(){return{localeError:FP()}}function AK(){return W6()}var OP=()=>{let $={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function v(U){return $[U]??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:"ان پٹ"},_={nan:"NaN",number:"نمبر",array:"آرے",null:"نل"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`غلط ان پٹ: instanceof ${U.expected} متوقع تھا، ${G} موصول ہوا`;return`غلط ان پٹ: ${Q} متوقع تھا، ${G} موصول ہوا`}case"invalid_value":if(U.values.length===1)return`غلط ان پٹ: ${I(U.values[0])} متوقع تھا`;return`غلط آپشن: ${D(U.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`بہت بڑا: ${U.origin??"ویلیو"} کے ${Q}${U.maximum.toString()} ${q.unit??"عناصر"} ہونے متوقع تھے`;return`بہت بڑا: ${U.origin??"ویلیو"} کا ${Q}${U.maximum.toString()} ہونا متوقع تھا`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`بہت چھوٹا: ${U.origin} کے ${Q}${U.minimum.toString()} ${q.unit} ہونے متوقع تھے`;return`بہت چھوٹا: ${U.origin} کا ${Q}${U.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`غلط سٹرنگ: "${Q.prefix}" سے شروع ہونا چاہیے`;if(Q.format==="ends_with")return`غلط سٹرنگ: "${Q.suffix}" پر ختم ہونا چاہیے`;if(Q.format==="includes")return`غلط سٹرنگ: "${Q.includes}" شامل ہونا چاہیے`;if(Q.format==="regex")return`غلط سٹرنگ: پیٹرن ${Q.pattern} سے میچ ہونا چاہیے`;return`غلط ${K[Q.format]??U.format}`}case"not_multiple_of":return`غلط نمبر: ${U.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${U.keys.length>1?"ز":""}: ${D(U.keys,"، ")}`;case"invalid_key":return`${U.origin} میں غلط کی`;case"invalid_union":return"غلط ان پٹ";case"invalid_element":return`${U.origin} میں غلط ویلیو`;default:return"غلط ان پٹ"}}};function FK(){return{localeError:OP()}}var xP=()=>{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 v(U){return $[U]??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"},_={nan:"NaN",number:"raqam",array:"massiv"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Noto‘g‘ri kirish: kutilgan instanceof ${U.expected}, qabul qilingan ${G}`;return`Noto‘g‘ri kirish: kutilgan ${Q}, qabul qilingan ${G}`}case"invalid_value":if(U.values.length===1)return`Noto‘g‘ri kirish: kutilgan ${I(U.values[0])}`;return`Noto‘g‘ri variant: quyidagilardan biri kutilgan ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Juda katta: kutilgan ${U.origin??"qiymat"} ${Q}${U.maximum.toString()} ${q.unit} ${q.verb}`;return`Juda katta: kutilgan ${U.origin??"qiymat"} ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Juda kichik: kutilgan ${U.origin} ${Q}${U.minimum.toString()} ${q.unit} ${q.verb}`;return`Juda kichik: kutilgan ${U.origin} ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Noto‘g‘ri satr: "${Q.prefix}" bilan boshlanishi kerak`;if(Q.format==="ends_with")return`Noto‘g‘ri satr: "${Q.suffix}" bilan tugashi kerak`;if(Q.format==="includes")return`Noto‘g‘ri satr: "${Q.includes}" ni o‘z ichiga olishi kerak`;if(Q.format==="regex")return`Noto‘g‘ri satr: ${Q.pattern} shabloniga mos kelishi kerak`;return`Noto‘g‘ri ${K[Q.format]??U.format}`}case"not_multiple_of":return`Noto‘g‘ri raqam: ${U.divisor} ning karralisi bo‘lishi kerak`;case"unrecognized_keys":return`Noma’lum kalit${U.keys.length>1?"lar":""}: ${D(U.keys,", ")}`;case"invalid_key":return`${U.origin} dagi kalit noto‘g‘ri`;case"invalid_union":return"Noto‘g‘ri kirish";case"invalid_element":return`${U.origin} da noto‘g‘ri qiymat`;default:return"Noto‘g‘ri kirish"}}};function OK(){return{localeError:xP()}}var RP=()=>{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 v(U){return $[U]??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"},_={nan:"NaN",number:"số",array:"mảng"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Đầu vào không hợp lệ: mong đợi instanceof ${U.expected}, nhận được ${G}`;return`Đầu vào không hợp lệ: mong đợi ${Q}, nhận được ${G}`}case"invalid_value":if(U.values.length===1)return`Đầu vào không hợp lệ: mong đợi ${I(U.values[0])}`;return`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Quá lớn: mong đợi ${U.origin??"giá trị"} ${q.verb} ${Q}${U.maximum.toString()} ${q.unit??"phần tử"}`;return`Quá lớn: mong đợi ${U.origin??"giá trị"} ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Quá nhỏ: mong đợi ${U.origin} ${q.verb} ${Q}${U.minimum.toString()} ${q.unit}`;return`Quá nhỏ: mong đợi ${U.origin} ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Chuỗi không hợp lệ: phải bắt đầu bằng "${Q.prefix}"`;if(Q.format==="ends_with")return`Chuỗi không hợp lệ: phải kết thúc bằng "${Q.suffix}"`;if(Q.format==="includes")return`Chuỗi không hợp lệ: phải bao gồm "${Q.includes}"`;if(Q.format==="regex")return`Chuỗi không hợp lệ: phải khớp với mẫu ${Q.pattern}`;return`${K[Q.format]??U.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 ${U.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${D(U.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${U.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 ${U.origin}`;default:return"Đầu vào không hợp lệ"}}};function xK(){return{localeError:RP()}}var SP=()=>{let $={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function v(U){return $[U]??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:"输入"},_={nan:"NaN",number:"数字",array:"数组",null:"空值(null)"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`无效输入:期望 instanceof ${U.expected},实际接收 ${G}`;return`无效输入:期望 ${Q},实际接收 ${G}`}case"invalid_value":if(U.values.length===1)return`无效输入:期望 ${I(U.values[0])}`;return`无效选项:期望以下之一 ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`数值过大:期望 ${U.origin??"值"} ${Q}${U.maximum.toString()} ${q.unit??"个元素"}`;return`数值过大:期望 ${U.origin??"值"} ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`数值过小:期望 ${U.origin} ${Q}${U.minimum.toString()} ${q.unit}`;return`数值过小:期望 ${U.origin} ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`无效字符串:必须以 "${Q.prefix}" 开头`;if(Q.format==="ends_with")return`无效字符串:必须以 "${Q.suffix}" 结尾`;if(Q.format==="includes")return`无效字符串:必须包含 "${Q.includes}"`;if(Q.format==="regex")return`无效字符串:必须满足正则表达式 ${Q.pattern}`;return`无效${K[Q.format]??U.format}`}case"not_multiple_of":return`无效数字:必须是 ${U.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${D(U.keys,", ")}`;case"invalid_key":return`${U.origin} 中的键(key)无效`;case"invalid_union":return"无效输入";case"invalid_element":return`${U.origin} 中包含无效值(value)`;default:return"无效输入"}}};function RK(){return{localeError:SP()}}var uP=()=>{let $={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function v(U){return $[U]??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:"輸入"},_={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`無效的輸入值:預期為 instanceof ${U.expected},但收到 ${G}`;return`無效的輸入值:預期為 ${Q},但收到 ${G}`}case"invalid_value":if(U.values.length===1)return`無效的輸入值:預期為 ${I(U.values[0])}`;return`無效的選項:預期為以下其中之一 ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`數值過大:預期 ${U.origin??"值"} 應為 ${Q}${U.maximum.toString()} ${q.unit??"個元素"}`;return`數值過大:預期 ${U.origin??"值"} 應為 ${Q}${U.maximum.toString()}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`數值過小:預期 ${U.origin} 應為 ${Q}${U.minimum.toString()} ${q.unit}`;return`數值過小:預期 ${U.origin} 應為 ${Q}${U.minimum.toString()}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`無效的字串:必須以 "${Q.prefix}" 開頭`;if(Q.format==="ends_with")return`無效的字串:必須以 "${Q.suffix}" 結尾`;if(Q.format==="includes")return`無效的字串:必須包含 "${Q.includes}"`;if(Q.format==="regex")return`無效的字串:必須符合格式 ${Q.pattern}`;return`無效的 ${K[Q.format]??U.format}`}case"not_multiple_of":return`無效的數字:必須為 ${U.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${U.keys.length>1?"們":""}:${D(U.keys,"、")}`;case"invalid_key":return`${U.origin} 中有無效的鍵值`;case"invalid_union":return"無效的輸入值";case"invalid_element":return`${U.origin} 中有無效的值`;default:return"無效的輸入值"}}};function SK(){return{localeError:uP()}}var TP=()=>{let $={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function v(U){return $[U]??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é"},_={nan:"NaN",number:"nọ́mbà",array:"akopọ"};return(U)=>{switch(U.code){case"invalid_type":{let Q=_[U.expected]??U.expected,q=Z(U.input),G=_[q]??q;if(/^[A-Z]/.test(U.expected))return`Ìbáwọlé aṣìṣe: a ní láti fi instanceof ${U.expected}, àmọ̀ a rí ${G}`;return`Ìbáwọlé aṣìṣe: a ní láti fi ${Q}, àmọ̀ a rí ${G}`}case"invalid_value":if(U.values.length===1)return`Ìbáwọlé aṣìṣe: a ní láti fi ${I(U.values[0])}`;return`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${D(U.values,"|")}`;case"too_big":{let Q=U.inclusive?"<=":"<",q=v(U.origin);if(q)return`Tó pọ̀ jù: a ní láti jẹ́ pé ${U.origin??"iye"} ${q.verb} ${Q}${U.maximum} ${q.unit}`;return`Tó pọ̀ jù: a ní láti jẹ́ ${Q}${U.maximum}`}case"too_small":{let Q=U.inclusive?">=":">",q=v(U.origin);if(q)return`Kéré ju: a ní láti jẹ́ pé ${U.origin} ${q.verb} ${Q}${U.minimum} ${q.unit}`;return`Kéré ju: a ní láti jẹ́ ${Q}${U.minimum}`}case"invalid_format":{let Q=U;if(Q.format==="starts_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${Q.prefix}"`;if(Q.format==="ends_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${Q.suffix}"`;if(Q.format==="includes")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${Q.includes}"`;if(Q.format==="regex")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${Q.pattern}`;return`Aṣìṣe: ${K[Q.format]??U.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${U.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${D(U.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${U.origin}`;case"invalid_union":return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${U.origin}`;default:return"Ìbáwọlé aṣìṣe"}}};function uK(){return{localeError:TP()}}var WG,TK=Symbol("ZodOutput"),gK=Symbol("ZodInput");class EK{constructor(){this._map=new WeakMap,this._idmap=new Map}add($,...v){let K=v[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 v=this._map.get($);if(v&&typeof v==="object"&&"id"in v)this._idmap.delete(v.id);return this._map.delete($),this}get($){let v=$._zod.parent;if(v){let K={...this.get(v)??{}};delete K.id;let _={...K,...this._map.get($)};return Object.keys(_).length?_:void 0}return this._map.get($)}has($){return this._map.has($)}}function M0(){return new EK}(WG=globalThis).__zod_globalRegistry??(WG.__zod_globalRegistry=M0());var W$=globalThis.__zod_globalRegistry;function CK($,v){return new $({type:"string",...L(v)})}function yK($,v){return new $({type:"string",coerce:!0,...L(v)})}function I0($,v){return new $({type:"string",format:"email",check:"string_format",abort:!1,...L(v)})}function Y6($,v){return new $({type:"string",format:"guid",check:"string_format",abort:!1,...L(v)})}function Z0($,v){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,...L(v)})}function z0($,v){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...L(v)})}function L0($,v){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...L(v)})}function A0($,v){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...L(v)})}function J6($,v){return new $({type:"string",format:"url",check:"string_format",abort:!1,...L(v)})}function F0($,v){return new $({type:"string",format:"emoji",check:"string_format",abort:!1,...L(v)})}function O0($,v){return new $({type:"string",format:"nanoid",check:"string_format",abort:!1,...L(v)})}function x0($,v){return new $({type:"string",format:"cuid",check:"string_format",abort:!1,...L(v)})}function R0($,v){return new $({type:"string",format:"cuid2",check:"string_format",abort:!1,...L(v)})}function S0($,v){return new $({type:"string",format:"ulid",check:"string_format",abort:!1,...L(v)})}function u0($,v){return new $({type:"string",format:"xid",check:"string_format",abort:!1,...L(v)})}function T0($,v){return new $({type:"string",format:"ksuid",check:"string_format",abort:!1,...L(v)})}function g0($,v){return new $({type:"string",format:"ipv4",check:"string_format",abort:!1,...L(v)})}function E0($,v){return new $({type:"string",format:"ipv6",check:"string_format",abort:!1,...L(v)})}function fK($,v){return new $({type:"string",format:"mac",check:"string_format",abort:!1,...L(v)})}function C0($,v){return new $({type:"string",format:"cidrv4",check:"string_format",abort:!1,...L(v)})}function y0($,v){return new $({type:"string",format:"cidrv6",check:"string_format",abort:!1,...L(v)})}function f0($,v){return new $({type:"string",format:"base64",check:"string_format",abort:!1,...L(v)})}function m0($,v){return new $({type:"string",format:"base64url",check:"string_format",abort:!1,...L(v)})}function h0($,v){return new $({type:"string",format:"e164",check:"string_format",abort:!1,...L(v)})}function c0($,v){return new $({type:"string",format:"jwt",check:"string_format",abort:!1,...L(v)})}var mK={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function hK($,v){return new $({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...L(v)})}function cK($,v){return new $({type:"string",format:"date",check:"string_format",...L(v)})}function rK($,v){return new $({type:"string",format:"time",check:"string_format",precision:null,...L(v)})}function iK($,v){return new $({type:"string",format:"duration",check:"string_format",...L(v)})}function nK($,v){return new $({type:"number",checks:[],...L(v)})}function lK($,v){return new $({type:"number",coerce:!0,checks:[],...L(v)})}function oK($,v){return new $({type:"number",check:"number_format",abort:!1,format:"safeint",...L(v)})}function dK($,v){return new $({type:"number",check:"number_format",abort:!1,format:"float32",...L(v)})}function tK($,v){return new $({type:"number",check:"number_format",abort:!1,format:"float64",...L(v)})}function pK($,v){return new $({type:"number",check:"number_format",abort:!1,format:"int32",...L(v)})}function aK($,v){return new $({type:"number",check:"number_format",abort:!1,format:"uint32",...L(v)})}function eK($,v){return new $({type:"boolean",...L(v)})}function sK($,v){return new $({type:"boolean",coerce:!0,...L(v)})}function $8($,v){return new $({type:"bigint",...L(v)})}function v8($,v){return new $({type:"bigint",coerce:!0,...L(v)})}function U8($,v){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...L(v)})}function K8($,v){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...L(v)})}function _8($,v){return new $({type:"symbol",...L(v)})}function Q8($,v){return new $({type:"undefined",...L(v)})}function q8($,v){return new $({type:"null",...L(v)})}function G8($){return new $({type:"any"})}function W8($){return new $({type:"unknown"})}function j8($,v){return new $({type:"never",...L(v)})}function Y8($,v){return new $({type:"void",...L(v)})}function J8($,v){return new $({type:"date",...L(v)})}function X8($,v){return new $({type:"date",coerce:!0,...L(v)})}function H8($,v){return new $({type:"nan",...L(v)})}function r$($,v){return new Y0({check:"less_than",...L(v),value:$,inclusive:!1})}function z$($,v){return new Y0({check:"less_than",...L(v),value:$,inclusive:!0})}function i$($,v){return new J0({check:"greater_than",...L(v),value:$,inclusive:!1})}function V$($,v){return new J0({check:"greater_than",...L(v),value:$,inclusive:!0})}function r0($){return i$(0,$)}function i0($){return r$(0,$)}function n0($){return z$(0,$)}function l0($){return V$(0,$)}function B1($,v){return new H2({check:"multiple_of",...L(v),value:$})}function D1($,v){return new B2({check:"max_size",...L(v),maximum:$})}function n$($,v){return new D2({check:"min_size",...L(v),minimum:$})}function E1($,v){return new b2({check:"size_equals",...L(v),size:$})}function C1($,v){return new k2({check:"max_length",...L(v),maximum:$})}function s$($,v){return new N2({check:"min_length",...L(v),minimum:$})}function y1($,v){return new w2({check:"length_equals",...L(v),length:$})}function W4($,v){return new M2({check:"string_format",format:"regex",...L(v),pattern:$})}function j4($){return new I2({check:"string_format",format:"lowercase",...L($)})}function Y4($){return new Z2({check:"string_format",format:"uppercase",...L($)})}function J4($,v){return new z2({check:"string_format",format:"includes",...L(v),includes:$})}function X4($,v){return new L2({check:"string_format",format:"starts_with",...L(v),prefix:$})}function H4($,v){return new A2({check:"string_format",format:"ends_with",...L(v),suffix:$})}function o0($,v,K){return new F2({check:"property",property:$,schema:v,...L(K)})}function P4($,v){return new O2({check:"mime_type",mime:$,...L(v)})}function C$($){return new x2({check:"overwrite",tx:$})}function V4($){return C$((v)=>v.normalize($))}function B4(){return C$(($)=>$.trim())}function D4(){return C$(($)=>$.toLowerCase())}function b4(){return C$(($)=>$.toUpperCase())}function k4(){return C$(($)=>FU($))}function P8($,v,K){return new $({type:"array",element:v,...L(K)})}function EP($,v,K){return new $({type:"union",options:v,...L(K)})}function CP($,v,K){return new $({type:"union",options:v,inclusive:!1,...L(K)})}function yP($,v,K,_){return new $({type:"union",options:K,discriminator:v,...L(_)})}function fP($,v,K){return new $({type:"intersection",left:v,right:K})}function mP($,v,K,_){let U=K instanceof C;return new $({type:"tuple",items:v,rest:U?K:null,...L(U?_:K)})}function hP($,v,K,_){return new $({type:"record",keyType:v,valueType:K,...L(_)})}function cP($,v,K,_){return new $({type:"map",keyType:v,valueType:K,...L(_)})}function rP($,v,K){return new $({type:"set",valueType:v,...L(K)})}function iP($,v,K){let _=Array.isArray(v)?Object.fromEntries(v.map((U)=>[U,U])):v;return new $({type:"enum",entries:_,...L(K)})}function nP($,v,K){return new $({type:"enum",entries:v,...L(K)})}function lP($,v,K){return new $({type:"literal",values:Array.isArray(v)?v:[v],...L(K)})}function V8($,v){return new $({type:"file",...L(v)})}function oP($,v){return new $({type:"transform",transform:v})}function dP($,v){return new $({type:"optional",innerType:v})}function tP($,v){return new $({type:"nullable",innerType:v})}function pP($,v,K){return new $({type:"default",innerType:v,get defaultValue(){return typeof K==="function"?K():xU(K)}})}function aP($,v,K){return new $({type:"nonoptional",innerType:v,...L(K)})}function eP($,v){return new $({type:"success",innerType:v})}function sP($,v,K){return new $({type:"catch",innerType:v,catchValue:typeof K==="function"?K:()=>K})}function $V($,v,K){return new $({type:"pipe",in:v,out:K})}function vV($,v){return new $({type:"readonly",innerType:v})}function UV($,v,K){return new $({type:"template_literal",parts:v,...L(K)})}function KV($,v){return new $({type:"lazy",getter:v})}function _V($,v){return new $({type:"promise",innerType:v})}function B8($,v,K){let _=L(K);return _.abort??(_.abort=!0),new $({type:"custom",check:"custom",fn:v,..._})}function D8($,v,K){return new $({type:"custom",check:"custom",fn:v,...L(K)})}function b8($){let v=jG((K)=>{return K.addIssue=(_)=>{if(typeof _==="string")K.issues.push(v4(_,K.value,v._zod.def));else{let U=_;if(U.fatal)U.continue=!1;U.code??(U.code="custom"),U.input??(U.input=K.value),U.inst??(U.inst=v),U.continue??(U.continue=!v._zod.def.abort),K.issues.push(v4(U))}},$(K.value,K)});return v}function jG($,v){let K=new t({check:"custom",...L(v)});return K._zod.check=$,K}function k8($){let v=new t({check:"describe"});return v._zod.onattach=[(K)=>{let _=W$.get(K)??{};W$.add(K,{..._,description:$})}],v._zod.check=()=>{},v}function N8($){let v=new t({check:"meta"});return v._zod.onattach=[(K)=>{let _=W$.get(K)??{};W$.add(K,{..._,...$})}],v._zod.check=()=>{},v}function w8($,v){let K=L(v),_=K.truthy??["true","1","yes","on","y","enabled"],U=K.falsy??["false","0","no","off","n","disabled"];if(K.case!=="sensitive")_=_.map((N)=>typeof N==="string"?N.toLowerCase():N),U=U.map((N)=>typeof N==="string"?N.toLowerCase():N);let Q=new Set(_),q=new Set(U),G=$.Codec??_6,j=$.Boolean??U6,X=new($.String??g1)({type:"string",error:K.error}),P=new j({type:"boolean",error:K.error}),B=new G({type:"pipe",in:X,out:P,transform:(N,S)=>{let f=N;if(K.case!=="sensitive")f=f.toLowerCase();if(Q.has(f))return!0;else if(q.has(f))return!1;else return S.issues.push({code:"invalid_value",expected:"stringbool",values:[...Q,...q],input:S.value,inst:B,continue:!1}),{}},reverseTransform:(N,S)=>{if(N===!0)return _[0]||"true";else return U[0]||"false"},error:K.error});return B}function N4($,v,K,_={}){let U=L(_),Q={...L(_),check:"string_format",type:"string",format:v,fn:typeof K==="function"?K:(G)=>K.test(G),...U};if(K instanceof RegExp)Q.pattern=K;return new $(Q)}function b1($){let v=$?.target??"draft-2020-12";if(v==="draft-4")v="draft-04";if(v==="draft-7")v="draft-07";return{processors:$.processors??{},metadataRegistry:$?.metadata??W$,target:v,unrepresentable:$?.unrepresentable??"throw",override:$?.override??(()=>{}),io:$?.io??"output",counter:0,seen:new Map,cycles:$?.cycles??"ref",reused:$?.reused??"inline",external:$?.external??void 0}}function n($,v,K={path:[],schemaPath:[]}){var _;let U=$._zod.def,Q=v.seen.get($);if(Q){if(Q.count++,K.schemaPath.includes($))Q.cycle=K.path;return Q.schema}let q={schema:{},count:1,cycle:void 0,path:K.path};v.seen.set($,q);let G=$._zod.toJSONSchema?.();if(G)q.schema=G;else{let X={...K,schemaPath:[...K.schemaPath,$],path:K.path};if($._zod.processJSONSchema)$._zod.processJSONSchema(v,q.schema,X);else{let B=q.schema,N=v.processors[U.type];if(!N)throw Error(`[toJSONSchema]: Non-representable type encountered: ${U.type}`);N($,v,B,X)}let P=$._zod.parent;if(P){if(!q.ref)q.ref=P;n(P,v,X),v.seen.get(P).isParent=!0}}let j=v.metadataRegistry.get($);if(j)Object.assign(q.schema,j);if(v.io==="input"&&B$($))delete q.schema.examples,delete q.schema.default;if(v.io==="input"&&q.schema._prefault)(_=q.schema).default??(_.default=q.schema._prefault);return delete q.schema._prefault,v.seen.get($).schema}function k1($,v){let K=$.seen.get(v);if(!K)throw Error("Unprocessed schema. This is a bug in Zod.");let _=new Map;for(let q of $.seen.entries()){let G=$.metadataRegistry.get(q[0])?.id;if(G){let j=_.get(G);if(j&&j!==q[0])throw Error(`Duplicate schema id "${G}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);_.set(G,q[0])}}let U=(q)=>{let G=$.target==="draft-2020-12"?"$defs":"definitions";if($.external){let P=$.external.registry.get(q[0])?.id,B=$.external.uri??((S)=>S);if(P)return{ref:B(P)};let N=q[1].defId??q[1].schema.id??`schema${$.counter++}`;return q[1].defId=N,{defId:N,ref:`${B("__shared")}#/${G}/${N}`}}if(q[1]===K)return{ref:"#"};let Y=`${"#"}/${G}/`,X=q[1].schema.id??`__schema${$.counter++}`;return{defId:X,ref:Y+X}},Q=(q)=>{if(q[1].schema.$ref)return;let G=q[1],{ref:j,defId:Y}=U(q);if(G.def={...G.schema},Y)G.defId=Y;let X=G.schema;for(let P in X)delete X[P];X.$ref=j};if($.cycles==="throw")for(let q of $.seen.entries()){let G=q[1];if(G.cycle)throw Error(`Cycle detected: #/${G.cycle?.join("/")}/<root>
|
|
92
|
+
`)}L.write("payload.value = newResult;"),L.write("return payload;");let B4=L.compile();return(h$,A$)=>B4(V,h$,A$)},W,J=e1,G=!N6.jitless,H=G&&zU.value,B=U.catchall,M;$._zod.parse=(V,L)=>{M??(M=q.value);let T=V.value;if(!J(T))return V.issues.push({expected:"object",code:"invalid_type",input:T,inst:$}),V;if(G&&H&&L?.async===!1&&L.jitless!==!0){if(!W)W=K(U.shape);if(V=W(V,L),!B)return V;return rG([],T,V,L,M,$)}return Q(V,L)}});function RG($,U,Q,q){for(let W of $)if(W.issues.length===0)return U.value=W.value,U;let K=$.filter((W)=>!w1(W));if(K.length===1)return U.value=K[0].value,K[0];return U.issues.push({code:"invalid_union",input:U.value,inst:Q,errors:$.map((W)=>W.issues.map((J)=>b$(J,q,H$())))}),U}var R6=D("$ZodUnion",($,U)=>{u.init($,U),l($._zod,"optin",()=>U.options.some((K)=>K._zod.optin==="optional")?"optional":void 0),l($._zod,"optout",()=>U.options.some((K)=>K._zod.optout==="optional")?"optional":void 0),l($._zod,"values",()=>{if(U.options.every((K)=>K._zod.values))return new Set(U.options.flatMap((K)=>Array.from(K._zod.values)));return}),l($._zod,"pattern",()=>{if(U.options.every((K)=>K._zod.pattern)){let K=U.options.map((W)=>W._zod.pattern);return new RegExp(`^(${K.map((W)=>_6(W.source)).join("|")})$`)}return});let Q=U.options.length===1,q=U.options[0]._zod.run;$._zod.parse=(K,W)=>{if(Q)return q(K,W);let J=!1,G=[];for(let Y of U.options){let H=Y._zod.run({value:K.value,issues:[]},W);if(H instanceof Promise)G.push(H),J=!0;else{if(H.issues.length===0)return H;G.push(H)}}if(!J)return RG(G,K,$,W);return Promise.all(G).then((Y)=>{return RG(Y,K,$,W)})}});function TG($,U,Q,q){let K=$.filter((W)=>W.issues.length===0);if(K.length===1)return U.value=K[0].value,U;if(K.length===0)U.issues.push({code:"invalid_union",input:U.value,inst:Q,errors:$.map((W)=>W.issues.map((J)=>b$(J,q,H$())))});else U.issues.push({code:"invalid_union",input:U.value,inst:Q,errors:[],inclusive:!1});return U}var B9=D("$ZodXor",($,U)=>{R6.init($,U),U.inclusive=!1;let Q=U.options.length===1,q=U.options[0]._zod.run;$._zod.parse=(K,W)=>{if(Q)return q(K,W);let J=!1,G=[];for(let Y of U.options){let H=Y._zod.run({value:K.value,issues:[]},W);if(H instanceof Promise)G.push(H),J=!0;else G.push(H)}if(!J)return TG(G,K,$,W);return Promise.all(G).then((Y)=>{return TG(Y,K,$,W)})}}),Z9=D("$ZodDiscriminatedUnion",($,U)=>{U.inclusive=!1,R6.init($,U);let Q=$._zod.parse;l($._zod,"propValues",()=>{let K={};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[G,Y]of Object.entries(J)){if(!K[G])K[G]=new Set;for(let H of Y)K[G].add(H)}}return K});let q=L4(()=>{let K=U.options,W=new Map;for(let J of K){let G=J._zod.propValues?.[U.discriminator];if(!G||G.size===0)throw Error(`Invalid discriminated union option at index "${U.options.indexOf(J)}"`);for(let Y of G){if(W.has(Y))throw Error(`Duplicate discriminator value "${String(Y)}"`);W.set(Y,J)}}return W});$._zod.parse=(K,W)=>{let J=K.value;if(!e1(J))return K.issues.push({code:"invalid_type",expected:"object",input:J,inst:$}),K;let G=q.value.get(J?.[U.discriminator]);if(G)return G._zod.run(K,W);if(U.unionFallback)return Q(K,W);return K.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:U.discriminator,input:J,path:[U.discriminator],inst:$}),K}}),M9=D("$ZodIntersection",($,U)=>{u.init($,U),$._zod.parse=(Q,q)=>{let K=Q.value,W=U.left._zod.run({value:K,issues:[]},q),J=U.right._zod.run({value:K,issues:[]},q);if(W instanceof Promise||J instanceof Promise)return Promise.all([W,J]).then(([Y,H])=>{return SG(Q,Y,H)});return SG(Q,W,J)}});function x3($,U){if($===U)return{valid:!0,data:$};if($ instanceof Date&&U instanceof Date&&+$===+U)return{valid:!0,data:$};if(k1($)&&k1(U)){let Q=Object.keys(U),q=Object.keys($).filter((W)=>Q.indexOf(W)!==-1),K={...$,...U};for(let W of q){let J=x3($[W],U[W]);if(!J.valid)return{valid:!1,mergeErrorPath:[W,...J.mergeErrorPath]};K[W]=J.data}return{valid:!0,data:K}}if(Array.isArray($)&&Array.isArray(U)){if($.length!==U.length)return{valid:!1,mergeErrorPath:[]};let Q=[];for(let q=0;q<$.length;q++){let K=$[q],W=U[q],J=x3(K,W);if(!J.valid)return{valid:!1,mergeErrorPath:[q,...J.mergeErrorPath]};Q.push(J.data)}return{valid:!0,data:Q}}return{valid:!1,mergeErrorPath:[]}}function SG($,U,Q){let q=new Map,K;for(let G of U.issues)if(G.code==="unrecognized_keys"){K??(K=G);for(let Y of G.keys){if(!q.has(Y))q.set(Y,{});q.get(Y).l=!0}}else $.issues.push(G);for(let G of Q.issues)if(G.code==="unrecognized_keys")for(let Y of G.keys){if(!q.has(Y))q.set(Y,{});q.get(Y).r=!0}else $.issues.push(G);let W=[...q].filter(([,G])=>G.l&&G.r).map(([G])=>G);if(W.length&&K)$.issues.push({...K,keys:W});if(w1($))return $;let J=x3(U.value,Q.value);if(!J.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(J.mergeErrorPath)}`);return $.value=J.data,$}var a0=D("$ZodTuple",($,U)=>{u.init($,U);let Q=U.items;$._zod.parse=(q,K)=>{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=[],G=[...Q].reverse().findIndex((B)=>B._zod.optin!=="optional"),Y=G===-1?0:Q.length-G;if(!U.rest){let B=W.length>Q.length,M=W.length<Y-1;if(B||M)return q.issues.push({...B?{code:"too_big",maximum:Q.length,inclusive:!0}:{code:"too_small",minimum:Q.length},input:W,inst:$,origin:"array"}),q}let H=-1;for(let B of Q){if(H++,H>=W.length){if(H>=Y)continue}let M=B._zod.run({value:W[H],issues:[]},K);if(M instanceof Promise)J.push(M.then((V)=>r0(V,q,H)));else r0(M,q,H)}if(U.rest){let B=W.slice(Q.length);for(let M of B){H++;let V=U.rest._zod.run({value:M,issues:[]},K);if(V instanceof Promise)J.push(V.then((L)=>r0(L,q,H)));else r0(V,q,H)}}if(J.length)return Promise.all(J).then(()=>q);return q}});function r0($,U,Q){if($.issues.length)U.issues.push(...E$(Q,$.issues));U.value[Q]=$.value}var V9=D("$ZodRecord",($,U)=>{u.init($,U),$._zod.parse=(Q,q)=>{let K=Q.value;if(!k1(K))return Q.issues.push({expected:"record",code:"invalid_type",input:K,inst:$}),Q;let W=[],J=U.keyType._zod.values;if(J){Q.value={};let G=new Set;for(let H of J)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){G.add(typeof H==="number"?H.toString():H);let B=U.valueType._zod.run({value:K[H],issues:[]},q);if(B instanceof Promise)W.push(B.then((M)=>{if(M.issues.length)Q.issues.push(...E$(H,M.issues));Q.value[H]=M.value}));else{if(B.issues.length)Q.issues.push(...E$(H,B.issues));Q.value[H]=B.value}}let Y;for(let H in K)if(!G.has(H))Y=Y??[],Y.push(H);if(Y&&Y.length>0)Q.issues.push({code:"unrecognized_keys",input:K,inst:$,keys:Y})}else{Q.value={};for(let G of Reflect.ownKeys(K)){if(G==="__proto__")continue;let Y=U.keyType._zod.run({value:G,issues:[]},q);if(Y instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof G==="string"&&x6.test(G)&&Y.issues.length){let M=U.keyType._zod.run({value:Number(G),issues:[]},q);if(M instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(M.issues.length===0)Y=M}if(Y.issues.length){if(U.mode==="loose")Q.value[G]=K[G];else Q.issues.push({code:"invalid_key",origin:"record",issues:Y.issues.map((M)=>b$(M,q,H$())),input:G,path:[G],inst:$});continue}let B=U.valueType._zod.run({value:K[G],issues:[]},q);if(B instanceof Promise)W.push(B.then((M)=>{if(M.issues.length)Q.issues.push(...E$(G,M.issues));Q.value[Y.value]=M.value}));else{if(B.issues.length)Q.issues.push(...E$(G,B.issues));Q.value[Y.value]=B.value}}}if(W.length)return Promise.all(W).then(()=>Q);return Q}}),D9=D("$ZodMap",($,U)=>{u.init($,U),$._zod.parse=(Q,q)=>{let K=Q.value;if(!(K instanceof Map))return Q.issues.push({expected:"map",code:"invalid_type",input:K,inst:$}),Q;let W=[];Q.value=new Map;for(let[J,G]of K){let Y=U.keyType._zod.run({value:J,issues:[]},q),H=U.valueType._zod.run({value:G,issues:[]},q);if(Y instanceof Promise||H instanceof Promise)W.push(Promise.all([Y,H]).then(([B,M])=>{CG(B,M,Q,J,K,$,q)}));else CG(Y,H,Q,J,K,$,q)}if(W.length)return Promise.all(W).then(()=>Q);return Q}});function CG($,U,Q,q,K,W,J){if($.issues.length)if(L6.has(typeof q))Q.issues.push(...E$(q,$.issues));else Q.issues.push({code:"invalid_key",origin:"map",input:K,inst:W,issues:$.issues.map((G)=>b$(G,J,H$()))});if(U.issues.length)if(L6.has(typeof q))Q.issues.push(...E$(q,U.issues));else Q.issues.push({origin:"map",code:"invalid_element",input:K,inst:W,key:q,issues:U.issues.map((G)=>b$(G,J,H$()))});Q.value.set($.value,U.value)}var N9=D("$ZodSet",($,U)=>{u.init($,U),$._zod.parse=(Q,q)=>{let K=Q.value;if(!(K instanceof Set))return Q.issues.push({input:K,inst:$,expected:"set",code:"invalid_type"}),Q;let W=[];Q.value=new Set;for(let J of K){let G=U.valueType._zod.run({value:J,issues:[]},q);if(G instanceof Promise)W.push(G.then((Y)=>EG(Y,Q)));else EG(G,Q)}if(W.length)return Promise.all(W).then(()=>Q);return Q}});function EG($,U){if($.issues.length)U.issues.push(...$.issues);U.value.add($.value)}var P9=D("$ZodEnum",($,U)=>{u.init($,U);let Q=I6(U.entries),q=new Set(Q);$._zod.values=q,$._zod.pattern=new RegExp(`^(${Q.filter((K)=>L6.has(typeof K)).map((K)=>typeof K==="string"?l$(K):K.toString()).join("|")})$`),$._zod.parse=(K,W)=>{let J=K.value;if(q.has(J))return K;return K.issues.push({code:"invalid_value",values:Q,input:J,inst:$}),K}}),I9=D("$ZodLiteral",($,U)=>{if(u.init($,U),U.values.length===0)throw Error("Cannot create literal schema with no valid values");let Q=new Set(U.values);$._zod.values=Q,$._zod.pattern=new RegExp(`^(${U.values.map((q)=>typeof q==="string"?l$(q):q?l$(q.toString()):String(q)).join("|")})$`),$._zod.parse=(q,K)=>{let W=q.value;if(Q.has(W))return q;return q.issues.push({code:"invalid_value",values:U.values,input:W,inst:$}),q}}),_9=D("$ZodFile",($,U)=>{u.init($,U),$._zod.parse=(Q,q)=>{let K=Q.value;if(K instanceof File)return Q;return Q.issues.push({expected:"file",code:"invalid_type",input:K,inst:$}),Q}}),L9=D("$ZodTransform",($,U)=>{u.init($,U),$._zod.parse=(Q,q)=>{if(q.direction==="backward")throw new s1($.constructor.name);let K=U.transform(Q.value,Q);if(q.async)return(K instanceof Promise?K:Promise.resolve(K)).then((J)=>{return Q.value=J,Q});if(K instanceof Promise)throw new e$;return Q.value=K,Q}});function gG($,U){if($.issues.length&&U===void 0)return{issues:[],value:void 0};return $}var s0=D("$ZodOptional",($,U)=>{u.init($,U),$._zod.optin="optional",$._zod.optout="optional",l($._zod,"values",()=>{return U.innerType._zod.values?new Set([...U.innerType._zod.values,void 0]):void 0}),l($._zod,"pattern",()=>{let Q=U.innerType._zod.pattern;return Q?new RegExp(`^(${_6(Q.source)})?$`):void 0}),$._zod.parse=(Q,q)=>{if(U.innerType._zod.optin==="optional"){let K=U.innerType._zod.run(Q,q);if(K instanceof Promise)return K.then((W)=>gG(W,Q.value));return gG(K,Q.value)}if(Q.value===void 0)return Q;return U.innerType._zod.run(Q,q)}}),F9=D("$ZodExactOptional",($,U)=>{s0.init($,U),l($._zod,"values",()=>U.innerType._zod.values),l($._zod,"pattern",()=>U.innerType._zod.pattern),$._zod.parse=(Q,q)=>{return U.innerType._zod.run(Q,q)}}),v9=D("$ZodNullable",($,U)=>{u.init($,U),l($._zod,"optin",()=>U.innerType._zod.optin),l($._zod,"optout",()=>U.innerType._zod.optout),l($._zod,"pattern",()=>{let Q=U.innerType._zod.pattern;return Q?new RegExp(`^(${_6(Q.source)}|null)$`):void 0}),l($._zod,"values",()=>{return U.innerType._zod.values?new Set([...U.innerType._zod.values,null]):void 0}),$._zod.parse=(Q,q)=>{if(Q.value===null)return Q;return U.innerType._zod.run(Q,q)}}),z9=D("$ZodDefault",($,U)=>{u.init($,U),$._zod.optin="optional",l($._zod,"values",()=>U.innerType._zod.values),$._zod.parse=(Q,q)=>{if(q.direction==="backward")return U.innerType._zod.run(Q,q);if(Q.value===void 0)return Q.value=U.defaultValue,Q;let K=U.innerType._zod.run(Q,q);if(K instanceof Promise)return K.then((W)=>yG(W,U));return yG(K,U)}});function yG($,U){if($.value===void 0)$.value=U.defaultValue;return $}var k9=D("$ZodPrefault",($,U)=>{u.init($,U),$._zod.optin="optional",l($._zod,"values",()=>U.innerType._zod.values),$._zod.parse=(Q,q)=>{if(q.direction==="backward")return U.innerType._zod.run(Q,q);if(Q.value===void 0)Q.value=U.defaultValue;return U.innerType._zod.run(Q,q)}}),w9=D("$ZodNonOptional",($,U)=>{u.init($,U),l($._zod,"values",()=>{let Q=U.innerType._zod.values;return Q?new Set([...Q].filter((q)=>q!==void 0)):void 0}),$._zod.parse=(Q,q)=>{let K=U.innerType._zod.run(Q,q);if(K instanceof Promise)return K.then((W)=>uG(W,$));return uG(K,$)}});function uG($,U){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:U});return $}var x9=D("$ZodSuccess",($,U)=>{u.init($,U),$._zod.parse=(Q,q)=>{if(q.direction==="backward")throw new s1("ZodSuccess");let K=U.innerType._zod.run(Q,q);if(K instanceof Promise)return K.then((W)=>{return Q.value=W.issues.length===0,Q});return Q.value=K.issues.length===0,Q}}),A9=D("$ZodCatch",($,U)=>{u.init($,U),l($._zod,"optin",()=>U.innerType._zod.optin),l($._zod,"optout",()=>U.innerType._zod.optout),l($._zod,"values",()=>U.innerType._zod.values),$._zod.parse=(Q,q)=>{if(q.direction==="backward")return U.innerType._zod.run(Q,q);let K=U.innerType._zod.run(Q,q);if(K instanceof Promise)return K.then((W)=>{if(Q.value=W.value,W.issues.length)Q.value=U.catchValue({...Q,error:{issues:W.issues.map((J)=>b$(J,q,H$()))},input:Q.value}),Q.issues=[];return Q});if(Q.value=K.value,K.issues.length)Q.value=U.catchValue({...Q,error:{issues:K.issues.map((W)=>b$(W,q,H$()))},input:Q.value}),Q.issues=[];return Q}}),b9=D("$ZodNaN",($,U)=>{u.init($,U),$._zod.parse=(Q,q)=>{if(typeof Q.value!=="number"||!Number.isNaN(Q.value))return Q.issues.push({input:Q.value,inst:$,expected:"nan",code:"invalid_type"}),Q;return Q}}),O9=D("$ZodPipe",($,U)=>{u.init($,U),l($._zod,"values",()=>U.in._zod.values),l($._zod,"optin",()=>U.in._zod.optin),l($._zod,"optout",()=>U.out._zod.optout),l($._zod,"propValues",()=>U.in._zod.propValues),$._zod.parse=(Q,q)=>{if(q.direction==="backward"){let W=U.out._zod.run(Q,q);if(W instanceof Promise)return W.then((J)=>n0(J,U.in,q));return n0(W,U.in,q)}let K=U.in._zod.run(Q,q);if(K instanceof Promise)return K.then((W)=>n0(W,U.out,q));return n0(K,U.out,q)}});function n0($,U,Q){if($.issues.length)return $.aborted=!0,$;return U._zod.run({value:$.value,issues:$.issues},Q)}var T6=D("$ZodCodec",($,U)=>{u.init($,U),l($._zod,"values",()=>U.in._zod.values),l($._zod,"optin",()=>U.in._zod.optin),l($._zod,"optout",()=>U.out._zod.optout),l($._zod,"propValues",()=>U.in._zod.propValues),$._zod.parse=(Q,q)=>{if((q.direction||"forward")==="forward"){let W=U.in._zod.run(Q,q);if(W instanceof Promise)return W.then((J)=>i0(J,U,q));return i0(W,U,q)}else{let W=U.out._zod.run(Q,q);if(W instanceof Promise)return W.then((J)=>i0(J,U,q));return i0(W,U,q)}}});function i0($,U,Q){if($.issues.length)return $.aborted=!0,$;if((Q.direction||"forward")==="forward"){let K=U.transform($.value,$);if(K instanceof Promise)return K.then((W)=>o0($,W,U.out,Q));return o0($,K,U.out,Q)}else{let K=U.reverseTransform($.value,$);if(K instanceof Promise)return K.then((W)=>o0($,W,U.in,Q));return o0($,K,U.in,Q)}}function o0($,U,Q,q){if($.issues.length)return $.aborted=!0,$;return Q._zod.run({value:U,issues:$.issues},q)}var R9=D("$ZodReadonly",($,U)=>{u.init($,U),l($._zod,"propValues",()=>U.innerType._zod.propValues),l($._zod,"values",()=>U.innerType._zod.values),l($._zod,"optin",()=>U.innerType?._zod?.optin),l($._zod,"optout",()=>U.innerType?._zod?.optout),$._zod.parse=(Q,q)=>{if(q.direction==="backward")return U.innerType._zod.run(Q,q);let K=U.innerType._zod.run(Q,q);if(K instanceof Promise)return K.then(fG);return fG(K)}});function fG($){return $.value=Object.freeze($.value),$}var T9=D("$ZodTemplateLiteral",($,U)=>{u.init($,U);let Q=[];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 K=q._zod.pattern instanceof RegExp?q._zod.pattern.source:q._zod.pattern;if(!K)throw Error(`Invalid template literal part: ${q._zod.traits}`);let W=K.startsWith("^")?1:0,J=K.endsWith("$")?K.length-1:K.length;Q.push(K.slice(W,J))}else if(q===null||wU.has(typeof q))Q.push(l$(`${q}`));else throw Error(`Invalid template literal part: ${q}`);$._zod.pattern=new RegExp(`^${Q.join("")}$`),$._zod.parse=(q,K)=>{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}}),S9=D("$ZodFunction",($,U)=>{return u.init($,U),$._def=U,$._zod.def=U,$.implement=(Q)=>{if(typeof Q!=="function")throw Error("implement() must be called with a function");return function(...q){let K=$._def.input?O0($._def.input,q):q,W=Reflect.apply(Q,this,K);if($._def.output)return O0($._def.output,W);return W}},$.implementAsync=(Q)=>{if(typeof Q!=="function")throw Error("implementAsync() must be called with a function");return async function(...q){let K=$._def.input?await R0($._def.input,q):q,W=await Reflect.apply(Q,this,K);if($._def.output)return await R0($._def.output,W);return W}},$._zod.parse=(Q,q)=>{if(typeof Q.value!=="function")return Q.issues.push({code:"invalid_type",expected:"function",input:Q.value,inst:$}),Q;if($._def.output&&$._def.output._zod.def.type==="promise")Q.value=$.implementAsync(Q.value);else Q.value=$.implement(Q.value);return Q},$.input=(...Q)=>{let q=$.constructor;if(Array.isArray(Q[0]))return new q({type:"function",input:new a0({type:"tuple",items:Q[0],rest:Q[1]}),output:$._def.output});return new q({type:"function",input:Q[0],output:$._def.output})},$.output=(Q)=>{return new $.constructor({type:"function",input:$._def.input,output:Q})},$}),C9=D("$ZodPromise",($,U)=>{u.init($,U),$._zod.parse=(Q,q)=>{return Promise.resolve(Q.value).then((K)=>U.innerType._zod.run({value:K,issues:[]},q))}}),E9=D("$ZodLazy",($,U)=>{u.init($,U),l($._zod,"innerType",()=>U.getter()),l($._zod,"pattern",()=>$._zod.innerType?._zod?.pattern),l($._zod,"propValues",()=>$._zod.innerType?._zod?.propValues),l($._zod,"optin",()=>$._zod.innerType?._zod?.optin??void 0),l($._zod,"optout",()=>$._zod.innerType?._zod?.optout??void 0),$._zod.parse=(Q,q)=>{return $._zod.innerType._zod.run(Q,q)}}),g9=D("$ZodCustom",($,U)=>{$$.init($,U),u.init($,U),$._zod.parse=(Q,q)=>{return Q},$._zod.check=(Q)=>{let q=Q.value,K=U.fn(q);if(K instanceof Promise)return K.then((W)=>hG(W,Q,q,$));hG(K,Q,q,$);return}});function hG($,U,Q,q){if(!$){let K={code:"custom",input:Q,inst:q,path:[...q._zod.def.path??[]],continue:!q._zod.def.abort};if(q._zod.def.params)K.params=q._zod.def.params;U.issues.push(F4(K))}}var y6={};q1(y6,{zhTW:()=>x7,zhCN:()=>w7,yo:()=>A7,vi:()=>k7,uz:()=>z7,ur:()=>v7,uk:()=>g6,ua:()=>F7,tr:()=>L7,th:()=>_7,ta:()=>I7,sv:()=>P7,sl:()=>N7,ru:()=>D7,pt:()=>V7,ps:()=>Z7,pl:()=>M7,ota:()=>B7,no:()=>X7,nl:()=>H7,ms:()=>Y7,mk:()=>j7,lt:()=>G7,ko:()=>J7,km:()=>C6,kh:()=>W7,ka:()=>q7,ja:()=>Q7,it:()=>K7,is:()=>U7,id:()=>$7,hy:()=>e9,hu:()=>s9,he:()=>a9,frCA:()=>t9,fr:()=>p9,fi:()=>d9,fa:()=>o9,es:()=>i9,eo:()=>n9,en:()=>S6,de:()=>r9,da:()=>l9,cs:()=>c9,ca:()=>m9,bg:()=>h9,be:()=>f9,az:()=>u9,ar:()=>y9});var CN=()=>{let $={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`مدخلات غير مقبولة: يفترض إدخال instanceof ${K.expected}، ولكن تم إدخال ${G}`;return`مدخلات غير مقبولة: يفترض إدخال ${W}، ولكن تم إدخال ${G}`}case"invalid_value":if(K.values.length===1)return`مدخلات غير مقبولة: يفترض إدخال ${v(K.values[0])}`;return`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return` أكبر من اللازم: يفترض أن تكون ${K.origin??"القيمة"} ${W} ${K.maximum.toString()} ${J.unit??"عنصر"}`;return`أكبر من اللازم: يفترض أن تكون ${K.origin??"القيمة"} ${W} ${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`أصغر من اللازم: يفترض لـ ${K.origin} أن يكون ${W} ${K.minimum.toString()} ${J.unit}`;return`أصغر من اللازم: يفترض لـ ${K.origin} أن يكون ${W} ${K.minimum.toString()}`}case"invalid_format":{let W=K;if(W.format==="starts_with")return`نَص غير مقبول: يجب أن يبدأ بـ "${K.prefix}"`;if(W.format==="ends_with")return`نَص غير مقبول: يجب أن ينتهي بـ "${W.suffix}"`;if(W.format==="includes")return`نَص غير مقبول: يجب أن يتضمَّن "${W.includes}"`;if(W.format==="regex")return`نَص غير مقبول: يجب أن يطابق النمط ${W.pattern}`;return`${Q[W.format]??K.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${K.divisor}`;case"unrecognized_keys":return`معرف${K.keys.length>1?"ات":""} غريب${K.keys.length>1?"ة":""}: ${N(K.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${K.origin}`;case"invalid_union":return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${K.origin}`;default:return"مدخل غير مقبول"}}};function y9(){return{localeError:CN()}}var EN=()=>{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(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Yanlış dəyər: gözlənilən instanceof ${K.expected}, daxil olan ${G}`;return`Yanlış dəyər: gözlənilən ${W}, daxil olan ${G}`}case"invalid_value":if(K.values.length===1)return`Yanlış dəyər: gözlənilən ${v(K.values[0])}`;return`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Çox böyük: gözlənilən ${K.origin??"dəyər"} ${W}${K.maximum.toString()} ${J.unit??"element"}`;return`Çox böyük: gözlənilən ${K.origin??"dəyər"} ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Çox kiçik: gözlənilən ${K.origin} ${W}${K.minimum.toString()} ${J.unit}`;return`Çox kiçik: gözlənilən ${K.origin} ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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ış ${Q[W.format]??K.format}`}case"not_multiple_of":return`Yanlış ədəd: ${K.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${K.keys.length>1?"lar":""}: ${N(K.keys,", ")}`;case"invalid_key":return`${K.origin} daxilində yanlış açar`;case"invalid_union":return"Yanlış dəyər";case"invalid_element":return`${K.origin} daxilində yanlış dəyər`;default:return"Yanlış dəyər"}}};function u9(){return{localeError:EN()}}function iG($,U,Q,q){let K=Math.abs($),W=K%10,J=K%100;if(J>=11&&J<=19)return q;if(W===1)return U;if(W>=2&&W<=4)return Q;return q}var gN=()=>{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(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Няправільны ўвод: чакаўся instanceof ${K.expected}, атрымана ${G}`;return`Няправільны ўвод: чакаўся ${W}, атрымана ${G}`}case"invalid_value":if(K.values.length===1)return`Няправільны ўвод: чакалася ${v(K.values[0])}`;return`Няправільны варыянт: чакаўся адзін з ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J){let G=Number(K.maximum),Y=iG(G,J.unit.one,J.unit.few,J.unit.many);return`Занадта вялікі: чакалася, што ${K.origin??"значэнне"} павінна ${J.verb} ${W}${K.maximum.toString()} ${Y}`}return`Занадта вялікі: чакалася, што ${K.origin??"значэнне"} павінна быць ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J){let G=Number(K.minimum),Y=iG(G,J.unit.one,J.unit.few,J.unit.many);return`Занадта малы: чакалася, што ${K.origin} павінна ${J.verb} ${W}${K.minimum.toString()} ${Y}`}return`Занадта малы: чакалася, што ${K.origin} павінна быць ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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`Няправільны ${Q[W.format]??K.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${K.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${K.keys.length>1?"ключы":"ключ"}: ${N(K.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${K.origin}`;case"invalid_union":return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${K.origin}`;default:return"Няправільны ўвод"}}};function f9(){return{localeError:gN()}}var yN=()=>{let $={string:{unit:"символа",verb:"да съдържа"},file:{unit:"байта",verb:"да съдържа"},array:{unit:"елемента",verb:"да съдържа"},set:{unit:"елемента",verb:"да съдържа"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Невалиден вход: очакван instanceof ${K.expected}, получен ${G}`;return`Невалиден вход: очакван ${W}, получен ${G}`}case"invalid_value":if(K.values.length===1)return`Невалиден вход: очакван ${v(K.values[0])}`;return`Невалидна опция: очаквано едно от ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Твърде голямо: очаква се ${K.origin??"стойност"} да съдържа ${W}${K.maximum.toString()} ${J.unit??"елемента"}`;return`Твърде голямо: очаква се ${K.origin??"стойност"} да бъде ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Твърде малко: очаква се ${K.origin} да съдържа ${W}${K.minimum.toString()} ${J.unit}`;return`Твърде малко: очаква се ${K.origin} да бъде ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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} ${Q[W.format]??K.format}`}case"not_multiple_of":return`Невалидно число: трябва да бъде кратно на ${K.divisor}`;case"unrecognized_keys":return`Неразпознат${K.keys.length>1?"и":""} ключ${K.keys.length>1?"ове":""}: ${N(K.keys,", ")}`;case"invalid_key":return`Невалиден ключ в ${K.origin}`;case"invalid_union":return"Невалиден вход";case"invalid_element":return`Невалидна стойност в ${K.origin}`;default:return"Невалиден вход"}}};function h9(){return{localeError:yN()}}var uN=()=>{let $={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Tipus invàlid: s'esperava instanceof ${K.expected}, s'ha rebut ${G}`;return`Tipus invàlid: s'esperava ${W}, s'ha rebut ${G}`}case"invalid_value":if(K.values.length===1)return`Valor invàlid: s'esperava ${v(K.values[0])}`;return`Opció invàlida: s'esperava una de ${N(K.values," o ")}`;case"too_big":{let W=K.inclusive?"com a màxim":"menys de",J=U(K.origin);if(J)return`Massa gran: s'esperava que ${K.origin??"el valor"} contingués ${W} ${K.maximum.toString()} ${J.unit??"elements"}`;return`Massa gran: s'esperava que ${K.origin??"el valor"} fos ${W} ${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?"com a mínim":"més de",J=U(K.origin);if(J)return`Massa petit: s'esperava que ${K.origin} contingués ${W} ${K.minimum.toString()} ${J.unit}`;return`Massa petit: s'esperava que ${K.origin} fos ${W} ${K.minimum.toString()}`}case"invalid_format":{let W=K;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 ${Q[W.format]??K.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${K.divisor}`;case"unrecognized_keys":return`Clau${K.keys.length>1?"s":""} no reconeguda${K.keys.length>1?"s":""}: ${N(K.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${K.origin}`;case"invalid_union":return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${K.origin}`;default:return"Entrada invàlida"}}};function m9(){return{localeError:uN()}}var fN=()=>{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(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Neplatný vstup: očekáváno instanceof ${K.expected}, obdrženo ${G}`;return`Neplatný vstup: očekáváno ${W}, obdrženo ${G}`}case"invalid_value":if(K.values.length===1)return`Neplatný vstup: očekáváno ${v(K.values[0])}`;return`Neplatná možnost: očekávána jedna z hodnot ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Hodnota je příliš velká: ${K.origin??"hodnota"} musí mít ${W}${K.maximum.toString()} ${J.unit??"prvků"}`;return`Hodnota je příliš velká: ${K.origin??"hodnota"} musí být ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Hodnota je příliš malá: ${K.origin??"hodnota"} musí mít ${W}${K.minimum.toString()} ${J.unit??"prvků"}`;return`Hodnota je příliš malá: ${K.origin??"hodnota"} musí být ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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 ${Q[W.format]??K.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${K.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${N(K.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${K.origin}`;case"invalid_union":return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${K.origin}`;default:return"Neplatný vstup"}}};function c9(){return{localeError:fN()}}var hN=()=>{let $={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Ugyldigt input: forventede instanceof ${K.expected}, fik ${G}`;return`Ugyldigt input: forventede ${W}, fik ${G}`}case"invalid_value":if(K.values.length===1)return`Ugyldig værdi: forventede ${v(K.values[0])}`;return`Ugyldigt valg: forventede en af følgende ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin),G=q[K.origin]??K.origin;if(J)return`For stor: forventede ${G??"value"} ${J.verb} ${W} ${K.maximum.toString()} ${J.unit??"elementer"}`;return`For stor: forventede ${G??"value"} havde ${W} ${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin),G=q[K.origin]??K.origin;if(J)return`For lille: forventede ${G} ${J.verb} ${W} ${K.minimum.toString()} ${J.unit}`;return`For lille: forventede ${G} havde ${W} ${K.minimum.toString()}`}case"invalid_format":{let W=K;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 ${Q[W.format]??K.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${K.divisor}`;case"unrecognized_keys":return`${K.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${N(K.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${K.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${K.origin}`;default:return"Ugyldigt input"}}};function l9(){return{localeError:hN()}}var mN=()=>{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(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Ungültige Eingabe: erwartet instanceof ${K.expected}, erhalten ${G}`;return`Ungültige Eingabe: erwartet ${W}, erhalten ${G}`}case"invalid_value":if(K.values.length===1)return`Ungültige Eingabe: erwartet ${v(K.values[0])}`;return`Ungültige Option: erwartet eine von ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Zu groß: erwartet, dass ${K.origin??"Wert"} ${W}${K.maximum.toString()} ${J.unit??"Elemente"} hat`;return`Zu groß: erwartet, dass ${K.origin??"Wert"} ${W}${K.maximum.toString()} ist`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Zu klein: erwartet, dass ${K.origin} ${W}${K.minimum.toString()} ${J.unit} hat`;return`Zu klein: erwartet, dass ${K.origin} ${W}${K.minimum.toString()} ist`}case"invalid_format":{let W=K;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: ${Q[W.format]??K.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${K.divisor} sein`;case"unrecognized_keys":return`${K.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${N(K.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${K.origin}`;case"invalid_union":return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${K.origin}`;default:return"Ungültige Eingabe"}}};function r9(){return{localeError:mN()}}var cN=()=>{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(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;return`Invalid input: expected ${W}, received ${G}`}case"invalid_value":if(K.values.length===1)return`Invalid input: expected ${v(K.values[0])}`;return`Invalid option: expected one of ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Too big: expected ${K.origin??"value"} to have ${W}${K.maximum.toString()} ${J.unit??"elements"}`;return`Too big: expected ${K.origin??"value"} to be ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Too small: expected ${K.origin} to have ${W}${K.minimum.toString()} ${J.unit}`;return`Too small: expected ${K.origin} to be ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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 ${Q[W.format]??K.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${K.divisor}`;case"unrecognized_keys":return`Unrecognized key${K.keys.length>1?"s":""}: ${N(K.keys,", ")}`;case"invalid_key":return`Invalid key in ${K.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${K.origin}`;default:return"Invalid input"}}};function S6(){return{localeError:cN()}}var lN=()=>{let $={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Nevalida enigo: atendiĝis instanceof ${K.expected}, riceviĝis ${G}`;return`Nevalida enigo: atendiĝis ${W}, riceviĝis ${G}`}case"invalid_value":if(K.values.length===1)return`Nevalida enigo: atendiĝis ${v(K.values[0])}`;return`Nevalida opcio: atendiĝis unu el ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Tro granda: atendiĝis ke ${K.origin??"valoro"} havu ${W}${K.maximum.toString()} ${J.unit??"elementojn"}`;return`Tro granda: atendiĝis ke ${K.origin??"valoro"} havu ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Tro malgranda: atendiĝis ke ${K.origin} havu ${W}${K.minimum.toString()} ${J.unit}`;return`Tro malgranda: atendiĝis ke ${K.origin} estu ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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 ${Q[W.format]??K.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${K.divisor}`;case"unrecognized_keys":return`Nekonata${K.keys.length>1?"j":""} ŝlosilo${K.keys.length>1?"j":""}: ${N(K.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${K.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${K.origin}`;default:return"Nevalida enigo"}}};function n9(){return{localeError:lN()}}var rN=()=>{let $={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Entrada inválida: se esperaba instanceof ${K.expected}, recibido ${G}`;return`Entrada inválida: se esperaba ${W}, recibido ${G}`}case"invalid_value":if(K.values.length===1)return`Entrada inválida: se esperaba ${v(K.values[0])}`;return`Opción inválida: se esperaba una de ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin),G=q[K.origin]??K.origin;if(J)return`Demasiado grande: se esperaba que ${G??"valor"} tuviera ${W}${K.maximum.toString()} ${J.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${G??"valor"} fuera ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin),G=q[K.origin]??K.origin;if(J)return`Demasiado pequeño: se esperaba que ${G} tuviera ${W}${K.minimum.toString()} ${J.unit}`;return`Demasiado pequeño: se esperaba que ${G} fuera ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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 ${Q[W.format]??K.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${K.divisor}`;case"unrecognized_keys":return`Llave${K.keys.length>1?"s":""} desconocida${K.keys.length>1?"s":""}: ${N(K.keys,", ")}`;case"invalid_key":return`Llave inválida en ${q[K.origin]??K.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido en ${q[K.origin]??K.origin}`;default:return"Entrada inválida"}}};function i9(){return{localeError:rN()}}var nN=()=>{let $={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`ورودی نامعتبر: میبایست instanceof ${K.expected} میبود، ${G} دریافت شد`;return`ورودی نامعتبر: میبایست ${W} میبود، ${G} دریافت شد`}case"invalid_value":if(K.values.length===1)return`ورودی نامعتبر: میبایست ${v(K.values[0])} میبود`;return`گزینه نامعتبر: میبایست یکی از ${N(K.values,"|")} میبود`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`خیلی بزرگ: ${K.origin??"مقدار"} باید ${W}${K.maximum.toString()} ${J.unit??"عنصر"} باشد`;return`خیلی بزرگ: ${K.origin??"مقدار"} باید ${W}${K.maximum.toString()} باشد`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`خیلی کوچک: ${K.origin} باید ${W}${K.minimum.toString()} ${J.unit} باشد`;return`خیلی کوچک: ${K.origin} باید ${W}${K.minimum.toString()} باشد`}case"invalid_format":{let W=K;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`${Q[W.format]??K.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${K.divisor} باشد`;case"unrecognized_keys":return`کلید${K.keys.length>1?"های":""} ناشناس: ${N(K.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${K.origin}`;case"invalid_union":return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${K.origin}`;default:return"ورودی نامعتبر"}}};function o9(){return{localeError:nN()}}var iN=()=>{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(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Virheellinen tyyppi: odotettiin instanceof ${K.expected}, oli ${G}`;return`Virheellinen tyyppi: odotettiin ${W}, oli ${G}`}case"invalid_value":if(K.values.length===1)return`Virheellinen syöte: täytyy olla ${v(K.values[0])}`;return`Virheellinen valinta: täytyy olla yksi seuraavista: ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Liian suuri: ${J.subject} täytyy olla ${W}${K.maximum.toString()} ${J.unit}`.trim();return`Liian suuri: arvon täytyy olla ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Liian pieni: ${J.subject} täytyy olla ${W}${K.minimum.toString()} ${J.unit}`.trim();return`Liian pieni: arvon täytyy olla ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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 ${Q[W.format]??K.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${K.divisor} monikerta`;case"unrecognized_keys":return`${K.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${N(K.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 d9(){return{localeError:iN()}}var oN=()=>{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(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Entrée invalide : instanceof ${K.expected} attendu, ${G} reçu`;return`Entrée invalide : ${W} attendu, ${G} reçu`}case"invalid_value":if(K.values.length===1)return`Entrée invalide : ${v(K.values[0])} attendu`;return`Option invalide : une valeur parmi ${N(K.values,"|")} attendue`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Trop grand : ${K.origin??"valeur"} doit ${J.verb} ${W}${K.maximum.toString()} ${J.unit??"élément(s)"}`;return`Trop grand : ${K.origin??"valeur"} doit être ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Trop petit : ${K.origin} doit ${J.verb} ${W}${K.minimum.toString()} ${J.unit}`;return`Trop petit : ${K.origin} doit être ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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`${Q[W.format]??K.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${K.divisor}`;case"unrecognized_keys":return`Clé${K.keys.length>1?"s":""} non reconnue${K.keys.length>1?"s":""} : ${N(K.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${K.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${K.origin}`;default:return"Entrée invalide"}}};function p9(){return{localeError:oN()}}var dN=()=>{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(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Entrée invalide : attendu instanceof ${K.expected}, reçu ${G}`;return`Entrée invalide : attendu ${W}, reçu ${G}`}case"invalid_value":if(K.values.length===1)return`Entrée invalide : attendu ${v(K.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"≤":"<",J=U(K.origin);if(J)return`Trop grand : attendu que ${K.origin??"la valeur"} ait ${W}${K.maximum.toString()} ${J.unit}`;return`Trop grand : attendu que ${K.origin??"la valeur"} soit ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?"≥":">",J=U(K.origin);if(J)return`Trop petit : attendu que ${K.origin} ait ${W}${K.minimum.toString()} ${J.unit}`;return`Trop petit : attendu que ${K.origin} soit ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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`${Q[W.format]??K.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${K.divisor}`;case"unrecognized_keys":return`Clé${K.keys.length>1?"s":""} non reconnue${K.keys.length>1?"s":""} : ${N(K.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${K.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${K.origin}`;default:return"Entrée invalide"}}};function t9(){return{localeError:dN()}}var pN=()=>{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:"גדול"}},Q=(H)=>H?$[H]:void 0,q=(H)=>{let B=Q(H);if(B)return B.label;return H??$.unknown.label},K=(H)=>`ה${q(H)}`,W=(H)=>{return(Q(H)?.gender??"m")==="f"?"צריכה להיות":"צריך להיות"},J=(H)=>{if(!H)return null;return U[H]??null},G={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 B=H.expected,M=Y[B??""]??q(B),V=z(H.input),L=Y[V]??$[V]?.label??V;if(/^[A-Z]/.test(H.expected))return`קלט לא תקין: צריך להיות instanceof ${H.expected}, התקבל ${L}`;return`קלט לא תקין: צריך להיות ${M}, התקבל ${L}`}case"invalid_value":{if(H.values.length===1)return`ערך לא תקין: הערך חייב להיות ${v(H.values[0])}`;let B=H.values.map((L)=>v(L));if(H.values.length===2)return`ערך לא תקין: האפשרויות המתאימות הן ${B[0]} או ${B[1]}`;let M=B[B.length-1];return`ערך לא תקין: האפשרויות המתאימות הן ${B.slice(0,-1).join(", ")} או ${M}`}case"too_big":{let B=J(H.origin),M=K(H.origin??"value");if(H.origin==="string")return`${B?.longLabel??"ארוך"} מדי: ${M} צריכה להכיל ${H.maximum.toString()} ${B?.unit??""} ${H.inclusive?"או פחות":"לכל היותר"}`.trim();if(H.origin==="number"){let T=H.inclusive?`קטן או שווה ל-${H.maximum}`:`קטן מ-${H.maximum}`;return`גדול מדי: ${M} צריך להיות ${T}`}if(H.origin==="array"||H.origin==="set"){let T=H.origin==="set"?"צריכה":"צריך",f=H.inclusive?`${H.maximum} ${B?.unit??""} או פחות`:`פחות מ-${H.maximum} ${B?.unit??""}`;return`גדול מדי: ${M} ${T} להכיל ${f}`.trim()}let V=H.inclusive?"<=":"<",L=W(H.origin??"value");if(B?.unit)return`${B.longLabel} מדי: ${M} ${L} ${V}${H.maximum.toString()} ${B.unit}`;return`${B?.longLabel??"גדול"} מדי: ${M} ${L} ${V}${H.maximum.toString()}`}case"too_small":{let B=J(H.origin),M=K(H.origin??"value");if(H.origin==="string")return`${B?.shortLabel??"קצר"} מדי: ${M} צריכה להכיל ${H.minimum.toString()} ${B?.unit??""} ${H.inclusive?"או יותר":"לפחות"}`.trim();if(H.origin==="number"){let T=H.inclusive?`גדול או שווה ל-${H.minimum}`:`גדול מ-${H.minimum}`;return`קטן מדי: ${M} צריך להיות ${T}`}if(H.origin==="array"||H.origin==="set"){let T=H.origin==="set"?"צריכה":"צריך";if(H.minimum===1&&H.inclusive){let U$=H.origin==="set"?"לפחות פריט אחד":"לפחות פריט אחד";return`קטן מדי: ${M} ${T} להכיל ${U$}`}let f=H.inclusive?`${H.minimum} ${B?.unit??""} או יותר`:`יותר מ-${H.minimum} ${B?.unit??""}`;return`קטן מדי: ${M} ${T} להכיל ${f}`.trim()}let V=H.inclusive?">=":">",L=W(H.origin??"value");if(B?.unit)return`${B.shortLabel} מדי: ${M} ${L} ${V}${H.minimum.toString()} ${B.unit}`;return`${B?.shortLabel??"קטן"} מדי: ${M} ${L} ${V}${H.minimum.toString()}`}case"invalid_format":{let B=H;if(B.format==="starts_with")return`המחרוזת חייבת להתחיל ב "${B.prefix}"`;if(B.format==="ends_with")return`המחרוזת חייבת להסתיים ב "${B.suffix}"`;if(B.format==="includes")return`המחרוזת חייבת לכלול "${B.includes}"`;if(B.format==="regex")return`המחרוזת חייבת להתאים לתבנית ${B.pattern}`;let M=G[B.format],V=M?.label??B.format,T=(M?.gender??"m")==="f"?"תקינה":"תקין";return`${V} לא ${T}`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${H.divisor}`;case"unrecognized_keys":return`מפתח${H.keys.length>1?"ות":""} לא מזוה${H.keys.length>1?"ים":"ה"}: ${N(H.keys,", ")}`;case"invalid_key":return"שדה לא תקין באובייקט";case"invalid_union":return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${K(H.origin??"array")}`;default:return"קלט לא תקין"}}};function a9(){return{localeError:pN()}}var tN=()=>{let $={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Érvénytelen bemenet: a várt érték instanceof ${K.expected}, a kapott érték ${G}`;return`Érvénytelen bemenet: a várt érték ${W}, a kapott érték ${G}`}case"invalid_value":if(K.values.length===1)return`Érvénytelen bemenet: a várt érték ${v(K.values[0])}`;return`Érvénytelen opció: valamelyik érték várt ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Túl nagy: ${K.origin??"érték"} mérete túl nagy ${W}${K.maximum.toString()} ${J.unit??"elem"}`;return`Túl nagy: a bemeneti érték ${K.origin??"érték"} túl nagy: ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Túl kicsi: a bemeneti érték ${K.origin} mérete túl kicsi ${W}${K.minimum.toString()} ${J.unit}`;return`Túl kicsi: a bemeneti érték ${K.origin} túl kicsi ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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 ${Q[W.format]??K.format}`}case"not_multiple_of":return`Érvénytelen szám: ${K.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${K.keys.length>1?"s":""}: ${N(K.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${K.origin}`;case"invalid_union":return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${K.origin}`;default:return"Érvénytelen bemenet"}}};function s9(){return{localeError:tN()}}function oG($,U,Q){return Math.abs($)===1?U:Q}function A4($){if(!$)return"";let U=["ա","ե","ը","ի","ո","ու","օ"],Q=$[$.length-1];return $+(U.includes(Q)?"ն":"ը")}var aN=()=>{let $={string:{unit:{one:"նշան",many:"նշաններ"},verb:"ունենալ"},file:{unit:{one:"բայթ",many:"բայթեր"},verb:"ունենալ"},array:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"},set:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Սխալ մուտքագրում․ սպասվում էր instanceof ${K.expected}, ստացվել է ${G}`;return`Սխալ մուտքագրում․ սպասվում էր ${W}, ստացվել է ${G}`}case"invalid_value":if(K.values.length===1)return`Սխալ մուտքագրում․ սպասվում էր ${v(K.values[1])}`;return`Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J){let G=Number(K.maximum),Y=oG(G,J.unit.one,J.unit.many);return`Չափազանց մեծ արժեք․ սպասվում է, որ ${A4(K.origin??"արժեք")} կունենա ${W}${K.maximum.toString()} ${Y}`}return`Չափազանց մեծ արժեք․ սպասվում է, որ ${A4(K.origin??"արժեք")} լինի ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J){let G=Number(K.minimum),Y=oG(G,J.unit.one,J.unit.many);return`Չափազանց փոքր արժեք․ սպասվում է, որ ${A4(K.origin)} կունենա ${W}${K.minimum.toString()} ${Y}`}return`Չափազանց փոքր արժեք․ սպասվում է, որ ${A4(K.origin)} լինի ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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`Սխալ ${Q[W.format]??K.format}`}case"not_multiple_of":return`Սխալ թիվ․ պետք է բազմապատիկ լինի ${K.divisor}-ի`;case"unrecognized_keys":return`Չճանաչված բանալի${K.keys.length>1?"ներ":""}. ${N(K.keys,", ")}`;case"invalid_key":return`Սխալ բանալի ${A4(K.origin)}-ում`;case"invalid_union":return"Սխալ մուտքագրում";case"invalid_element":return`Սխալ արժեք ${A4(K.origin)}-ում`;default:return"Սխալ մուտքագրում"}}};function e9(){return{localeError:aN()}}var sN=()=>{let $={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Input tidak valid: diharapkan instanceof ${K.expected}, diterima ${G}`;return`Input tidak valid: diharapkan ${W}, diterima ${G}`}case"invalid_value":if(K.values.length===1)return`Input tidak valid: diharapkan ${v(K.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Terlalu besar: diharapkan ${K.origin??"value"} memiliki ${W}${K.maximum.toString()} ${J.unit??"elemen"}`;return`Terlalu besar: diharapkan ${K.origin??"value"} menjadi ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Terlalu kecil: diharapkan ${K.origin} memiliki ${W}${K.minimum.toString()} ${J.unit}`;return`Terlalu kecil: diharapkan ${K.origin} menjadi ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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`${Q[W.format]??K.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${K.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${K.keys.length>1?"s":""}: ${N(K.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${K.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${K.origin}`;default:return"Input tidak valid"}}};function $7(){return{localeError:sN()}}var eN=()=>{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(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Rangt gildi: Þú slóst inn ${G} þar sem á að vera instanceof ${K.expected}`;return`Rangt gildi: Þú slóst inn ${G} þar sem á að vera ${W}`}case"invalid_value":if(K.values.length===1)return`Rangt gildi: gert ráð fyrir ${v(K.values[0])}`;return`Ógilt val: má vera eitt af eftirfarandi ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Of stórt: gert er ráð fyrir að ${K.origin??"gildi"} hafi ${W}${K.maximum.toString()} ${J.unit??"hluti"}`;return`Of stórt: gert er ráð fyrir að ${K.origin??"gildi"} sé ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Of lítið: gert er ráð fyrir að ${K.origin} hafi ${W}${K.minimum.toString()} ${J.unit}`;return`Of lítið: gert er ráð fyrir að ${K.origin} sé ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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 ${Q[W.format]??K.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${K.divisor}`;case"unrecognized_keys":return`Óþekkt ${K.keys.length>1?"ir lyklar":"ur lykill"}: ${N(K.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${K.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${K.origin}`;default:return"Rangt gildi"}}};function U7(){return{localeError:eN()}}var $P=()=>{let $={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Input non valido: atteso instanceof ${K.expected}, ricevuto ${G}`;return`Input non valido: atteso ${W}, ricevuto ${G}`}case"invalid_value":if(K.values.length===1)return`Input non valido: atteso ${v(K.values[0])}`;return`Opzione non valida: atteso uno tra ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Troppo grande: ${K.origin??"valore"} deve avere ${W}${K.maximum.toString()} ${J.unit??"elementi"}`;return`Troppo grande: ${K.origin??"valore"} deve essere ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Troppo piccolo: ${K.origin} deve avere ${W}${K.minimum.toString()} ${J.unit}`;return`Troppo piccolo: ${K.origin} deve essere ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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 ${Q[W.format]??K.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${K.divisor}`;case"unrecognized_keys":return`Chiav${K.keys.length>1?"i":"e"} non riconosciut${K.keys.length>1?"e":"a"}: ${N(K.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${K.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${K.origin}`;default:return"Input non valido"}}};function K7(){return{localeError:$P()}}var UP=()=>{let $={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`無効な入力: instanceof ${K.expected}が期待されましたが、${G}が入力されました`;return`無効な入力: ${W}が期待されましたが、${G}が入力されました`}case"invalid_value":if(K.values.length===1)return`無効な入力: ${v(K.values[0])}が期待されました`;return`無効な選択: ${N(K.values,"、")}のいずれかである必要があります`;case"too_big":{let W=K.inclusive?"以下である":"より小さい",J=U(K.origin);if(J)return`大きすぎる値: ${K.origin??"値"}は${K.maximum.toString()}${J.unit??"要素"}${W}必要があります`;return`大きすぎる値: ${K.origin??"値"}は${K.maximum.toString()}${W}必要があります`}case"too_small":{let W=K.inclusive?"以上である":"より大きい",J=U(K.origin);if(J)return`小さすぎる値: ${K.origin}は${K.minimum.toString()}${J.unit}${W}必要があります`;return`小さすぎる値: ${K.origin}は${K.minimum.toString()}${W}必要があります`}case"invalid_format":{let W=K;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`無効な${Q[W.format]??K.format}`}case"not_multiple_of":return`無効な数値: ${K.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${K.keys.length>1?"群":""}: ${N(K.keys,"、")}`;case"invalid_key":return`${K.origin}内の無効なキー`;case"invalid_union":return"無効な入力";case"invalid_element":return`${K.origin}内の無効な値`;default:return"無効な入力"}}};function Q7(){return{localeError:UP()}}var KP=()=>{let $={string:{unit:"სიმბოლო",verb:"უნდა შეიცავდეს"},file:{unit:"ბაიტი",verb:"უნდა შეიცავდეს"},array:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},set:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`არასწორი შეყვანა: მოსალოდნელი instanceof ${K.expected}, მიღებული ${G}`;return`არასწორი შეყვანა: მოსალოდნელი ${W}, მიღებული ${G}`}case"invalid_value":if(K.values.length===1)return`არასწორი შეყვანა: მოსალოდნელი ${v(K.values[0])}`;return`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${N(K.values,"|")}-დან`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`ზედმეტად დიდი: მოსალოდნელი ${K.origin??"მნიშვნელობა"} ${J.verb} ${W}${K.maximum.toString()} ${J.unit}`;return`ზედმეტად დიდი: მოსალოდნელი ${K.origin??"მნიშვნელობა"} იყოს ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`ზედმეტად პატარა: მოსალოდნელი ${K.origin} ${J.verb} ${W}${K.minimum.toString()} ${J.unit}`;return`ზედმეტად პატარა: მოსალოდნელი ${K.origin} იყოს ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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`არასწორი ${Q[W.format]??K.format}`}case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${K.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${K.keys.length>1?"ები":"ი"}: ${N(K.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${K.origin}-ში`;case"invalid_union":return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${K.origin}-ში`;default:return"არასწორი შეყვანა"}}};function q7(){return{localeError:KP()}}var QP=()=>{let $={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${K.expected} ប៉ុន្តែទទួលបាន ${G}`;return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${W} ប៉ុន្តែទទួលបាន ${G}`}case"invalid_value":if(K.values.length===1)return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${v(K.values[0])}`;return`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`ធំពេក៖ ត្រូវការ ${K.origin??"តម្លៃ"} ${W} ${K.maximum.toString()} ${J.unit??"ធាតុ"}`;return`ធំពេក៖ ត្រូវការ ${K.origin??"តម្លៃ"} ${W} ${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`តូចពេក៖ ត្រូវការ ${K.origin} ${W} ${K.minimum.toString()} ${J.unit}`;return`តូចពេក៖ ត្រូវការ ${K.origin} ${W} ${K.minimum.toString()}`}case"invalid_format":{let W=K;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`មិនត្រឹមត្រូវ៖ ${Q[W.format]??K.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${K.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${N(K.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${K.origin}`;case"invalid_union":return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${K.origin}`;default:return"ទិន្នន័យមិនត្រឹមត្រូវ"}}};function C6(){return{localeError:QP()}}function W7(){return C6()}var qP=()=>{let $={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`잘못된 입력: 예상 타입은 instanceof ${K.expected}, 받은 타입은 ${G}입니다`;return`잘못된 입력: 예상 타입은 ${W}, 받은 타입은 ${G}입니다`}case"invalid_value":if(K.values.length===1)return`잘못된 입력: 값은 ${v(K.values[0])} 이어야 합니다`;return`잘못된 옵션: ${N(K.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{let W=K.inclusive?"이하":"미만",J=W==="미만"?"이어야 합니다":"여야 합니다",G=U(K.origin),Y=G?.unit??"요소";if(G)return`${K.origin??"값"}이 너무 큽니다: ${K.maximum.toString()}${Y} ${W}${J}`;return`${K.origin??"값"}이 너무 큽니다: ${K.maximum.toString()} ${W}${J}`}case"too_small":{let W=K.inclusive?"이상":"초과",J=W==="이상"?"이어야 합니다":"여야 합니다",G=U(K.origin),Y=G?.unit??"요소";if(G)return`${K.origin??"값"}이 너무 작습니다: ${K.minimum.toString()}${Y} ${W}${J}`;return`${K.origin??"값"}이 너무 작습니다: ${K.minimum.toString()} ${W}${J}`}case"invalid_format":{let W=K;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`잘못된 ${Q[W.format]??K.format}`}case"not_multiple_of":return`잘못된 숫자: ${K.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${N(K.keys,", ")}`;case"invalid_key":return`잘못된 키: ${K.origin}`;case"invalid_union":return"잘못된 입력";case"invalid_element":return`잘못된 값: ${K.origin}`;default:return"잘못된 입력"}}};function J7(){return{localeError:qP()}}var E6=($)=>{return $.charAt(0).toUpperCase()+$.slice(1)};function dG($){let U=Math.abs($),Q=U%10,q=U%100;if(q>=11&&q<=19||Q===0)return"many";if(Q===1)return"one";return"few"}var WP=()=>{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(K,W,J,G){let Y=$[K]??null;if(Y===null)return Y;return{unit:Y.unit[W],verb:Y.verb[G][J?"inclusive":"notInclusive"]}}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Gautas tipas ${G}, o tikėtasi - instanceof ${K.expected}`;return`Gautas tipas ${G}, o tikėtasi - ${W}`}case"invalid_value":if(K.values.length===1)return`Privalo būti ${v(K.values[0])}`;return`Privalo būti vienas iš ${N(K.values,"|")} pasirinkimų`;case"too_big":{let W=q[K.origin]??K.origin,J=U(K.origin,dG(Number(K.maximum)),K.inclusive??!1,"smaller");if(J?.verb)return`${E6(W??K.origin??"reikšmė")} ${J.verb} ${K.maximum.toString()} ${J.unit??"elementų"}`;let G=K.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${E6(W??K.origin??"reikšmė")} turi būti ${G} ${K.maximum.toString()} ${J?.unit}`}case"too_small":{let W=q[K.origin]??K.origin,J=U(K.origin,dG(Number(K.minimum)),K.inclusive??!1,"bigger");if(J?.verb)return`${E6(W??K.origin??"reikšmė")} ${J.verb} ${K.minimum.toString()} ${J.unit??"elementų"}`;let G=K.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${E6(W??K.origin??"reikšmė")} turi būti ${G} ${K.minimum.toString()} ${J?.unit}`}case"invalid_format":{let W=K;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 ${Q[W.format]??K.format}`}case"not_multiple_of":return`Skaičius privalo būti ${K.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpažint${K.keys.length>1?"i":"as"} rakt${K.keys.length>1?"ai":"as"}: ${N(K.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga įvestis";case"invalid_element":{let W=q[K.origin]??K.origin;return`${E6(W??K.origin??"reikšmė")} turi klaidingą įvestį`}default:return"Klaidinga įvestis"}}};function G7(){return{localeError:WP()}}var JP=()=>{let $={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Грешен внес: се очекува instanceof ${K.expected}, примено ${G}`;return`Грешен внес: се очекува ${W}, примено ${G}`}case"invalid_value":if(K.values.length===1)return`Invalid input: expected ${v(K.values[0])}`;return`Грешана опција: се очекува една ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Премногу голем: се очекува ${K.origin??"вредноста"} да има ${W}${K.maximum.toString()} ${J.unit??"елементи"}`;return`Премногу голем: се очекува ${K.origin??"вредноста"} да биде ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Премногу мал: се очекува ${K.origin} да има ${W}${K.minimum.toString()} ${J.unit}`;return`Премногу мал: се очекува ${K.origin} да биде ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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 ${Q[W.format]??K.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${K.divisor}`;case"unrecognized_keys":return`${K.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${N(K.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${K.origin}`;case"invalid_union":return"Грешен внес";case"invalid_element":return`Грешна вредност во ${K.origin}`;default:return"Грешен внес"}}};function j7(){return{localeError:JP()}}var GP=()=>{let $={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Input tidak sah: dijangka instanceof ${K.expected}, diterima ${G}`;return`Input tidak sah: dijangka ${W}, diterima ${G}`}case"invalid_value":if(K.values.length===1)return`Input tidak sah: dijangka ${v(K.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Terlalu besar: dijangka ${K.origin??"nilai"} ${J.verb} ${W}${K.maximum.toString()} ${J.unit??"elemen"}`;return`Terlalu besar: dijangka ${K.origin??"nilai"} adalah ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Terlalu kecil: dijangka ${K.origin} ${J.verb} ${W}${K.minimum.toString()} ${J.unit}`;return`Terlalu kecil: dijangka ${K.origin} adalah ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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`${Q[W.format]??K.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${K.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${N(K.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${K.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${K.origin}`;default:return"Input tidak sah"}}};function Y7(){return{localeError:GP()}}var jP=()=>{let $={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Ongeldige invoer: verwacht instanceof ${K.expected}, ontving ${G}`;return`Ongeldige invoer: verwacht ${W}, ontving ${G}`}case"invalid_value":if(K.values.length===1)return`Ongeldige invoer: verwacht ${v(K.values[0])}`;return`Ongeldige optie: verwacht één van ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin),G=K.origin==="date"?"laat":K.origin==="string"?"lang":"groot";if(J)return`Te ${G}: verwacht dat ${K.origin??"waarde"} ${W}${K.maximum.toString()} ${J.unit??"elementen"} ${J.verb}`;return`Te ${G}: verwacht dat ${K.origin??"waarde"} ${W}${K.maximum.toString()} is`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin),G=K.origin==="date"?"vroeg":K.origin==="string"?"kort":"klein";if(J)return`Te ${G}: verwacht dat ${K.origin} ${W}${K.minimum.toString()} ${J.unit} ${J.verb}`;return`Te ${G}: verwacht dat ${K.origin} ${W}${K.minimum.toString()} is`}case"invalid_format":{let W=K;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: ${Q[W.format]??K.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${K.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${K.keys.length>1?"s":""}: ${N(K.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${K.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${K.origin}`;default:return"Ongeldige invoer"}}};function H7(){return{localeError:jP()}}var YP=()=>{let $={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Ugyldig input: forventet instanceof ${K.expected}, fikk ${G}`;return`Ugyldig input: forventet ${W}, fikk ${G}`}case"invalid_value":if(K.values.length===1)return`Ugyldig verdi: forventet ${v(K.values[0])}`;return`Ugyldig valg: forventet en av ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`For stor(t): forventet ${K.origin??"value"} til å ha ${W}${K.maximum.toString()} ${J.unit??"elementer"}`;return`For stor(t): forventet ${K.origin??"value"} til å ha ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`For lite(n): forventet ${K.origin} til å ha ${W}${K.minimum.toString()} ${J.unit}`;return`For lite(n): forventet ${K.origin} til å ha ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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 ${Q[W.format]??K.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${K.divisor}`;case"unrecognized_keys":return`${K.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${N(K.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${K.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${K.origin}`;default:return"Ugyldig input"}}};function X7(){return{localeError:YP()}}var HP=()=>{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(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Fâsit giren: umulan instanceof ${K.expected}, alınan ${G}`;return`Fâsit giren: umulan ${W}, alınan ${G}`}case"invalid_value":if(K.values.length===1)return`Fâsit giren: umulan ${v(K.values[0])}`;return`Fâsit tercih: mûteberler ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Fazla büyük: ${K.origin??"value"}, ${W}${K.maximum.toString()} ${J.unit??"elements"} sahip olmalıydı.`;return`Fazla büyük: ${K.origin??"value"}, ${W}${K.maximum.toString()} olmalıydı.`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Fazla küçük: ${K.origin}, ${W}${K.minimum.toString()} ${J.unit} sahip olmalıydı.`;return`Fazla küçük: ${K.origin}, ${W}${K.minimum.toString()} olmalıydı.`}case"invalid_format":{let W=K;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 ${Q[W.format]??K.format}`}case"not_multiple_of":return`Fâsit sayı: ${K.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${K.keys.length>1?"s":""}: ${N(K.keys,", ")}`;case"invalid_key":return`${K.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${K.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};function B7(){return{localeError:HP()}}var XP=()=>{let $={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`ناسم ورودي: باید instanceof ${K.expected} وای, مګر ${G} ترلاسه شو`;return`ناسم ورودي: باید ${W} وای, مګر ${G} ترلاسه شو`}case"invalid_value":if(K.values.length===1)return`ناسم ورودي: باید ${v(K.values[0])} وای`;return`ناسم انتخاب: باید یو له ${N(K.values,"|")} څخه وای`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`ډیر لوی: ${K.origin??"ارزښت"} باید ${W}${K.maximum.toString()} ${J.unit??"عنصرونه"} ولري`;return`ډیر لوی: ${K.origin??"ارزښت"} باید ${W}${K.maximum.toString()} وي`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`ډیر کوچنی: ${K.origin} باید ${W}${K.minimum.toString()} ${J.unit} ولري`;return`ډیر کوچنی: ${K.origin} باید ${W}${K.minimum.toString()} وي`}case"invalid_format":{let W=K;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`${Q[W.format]??K.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${K.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${K.keys.length>1?"کلیډونه":"کلیډ"}: ${N(K.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${K.origin} کې`;case"invalid_union":return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${K.origin} کې`;default:return"ناسمه ورودي"}}};function Z7(){return{localeError:XP()}}var BP=()=>{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(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Nieprawidłowe dane wejściowe: oczekiwano instanceof ${K.expected}, otrzymano ${G}`;return`Nieprawidłowe dane wejściowe: oczekiwano ${W}, otrzymano ${G}`}case"invalid_value":if(K.values.length===1)return`Nieprawidłowe dane wejściowe: oczekiwano ${v(K.values[0])}`;return`Nieprawidłowa opcja: oczekiwano jednej z wartości ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Za duża wartość: oczekiwano, że ${K.origin??"wartość"} będzie mieć ${W}${K.maximum.toString()} ${J.unit??"elementów"}`;return`Zbyt duż(y/a/e): oczekiwano, że ${K.origin??"wartość"} będzie wynosić ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Za mała wartość: oczekiwano, że ${K.origin??"wartość"} będzie mieć ${W}${K.minimum.toString()} ${J.unit??"elementów"}`;return`Zbyt mał(y/a/e): oczekiwano, że ${K.origin??"wartość"} będzie wynosić ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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) ${Q[W.format]??K.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${K.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${K.keys.length>1?"s":""}: ${N(K.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${K.origin}`;case"invalid_union":return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${K.origin}`;default:return"Nieprawidłowe dane wejściowe"}}};function M7(){return{localeError:BP()}}var ZP=()=>{let $={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Tipo inválido: esperado instanceof ${K.expected}, recebido ${G}`;return`Tipo inválido: esperado ${W}, recebido ${G}`}case"invalid_value":if(K.values.length===1)return`Entrada inválida: esperado ${v(K.values[0])}`;return`Opção inválida: esperada uma das ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Muito grande: esperado que ${K.origin??"valor"} tivesse ${W}${K.maximum.toString()} ${J.unit??"elementos"}`;return`Muito grande: esperado que ${K.origin??"valor"} fosse ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Muito pequeno: esperado que ${K.origin} tivesse ${W}${K.minimum.toString()} ${J.unit}`;return`Muito pequeno: esperado que ${K.origin} fosse ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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`${Q[W.format]??K.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${K.divisor}`;case"unrecognized_keys":return`Chave${K.keys.length>1?"s":""} desconhecida${K.keys.length>1?"s":""}: ${N(K.keys,", ")}`;case"invalid_key":return`Chave inválida em ${K.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${K.origin}`;default:return"Campo inválido"}}};function V7(){return{localeError:ZP()}}function pG($,U,Q,q){let K=Math.abs($),W=K%10,J=K%100;if(J>=11&&J<=19)return q;if(W===1)return U;if(W>=2&&W<=4)return Q;return q}var MP=()=>{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(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Неверный ввод: ожидалось instanceof ${K.expected}, получено ${G}`;return`Неверный ввод: ожидалось ${W}, получено ${G}`}case"invalid_value":if(K.values.length===1)return`Неверный ввод: ожидалось ${v(K.values[0])}`;return`Неверный вариант: ожидалось одно из ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J){let G=Number(K.maximum),Y=pG(G,J.unit.one,J.unit.few,J.unit.many);return`Слишком большое значение: ожидалось, что ${K.origin??"значение"} будет иметь ${W}${K.maximum.toString()} ${Y}`}return`Слишком большое значение: ожидалось, что ${K.origin??"значение"} будет ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J){let G=Number(K.minimum),Y=pG(G,J.unit.one,J.unit.few,J.unit.many);return`Слишком маленькое значение: ожидалось, что ${K.origin} будет иметь ${W}${K.minimum.toString()} ${Y}`}return`Слишком маленькое значение: ожидалось, что ${K.origin} будет ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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`Неверный ${Q[W.format]??K.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${K.divisor}`;case"unrecognized_keys":return`Нераспознанн${K.keys.length>1?"ые":"ый"} ключ${K.keys.length>1?"и":""}: ${N(K.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${K.origin}`;case"invalid_union":return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${K.origin}`;default:return"Неверные входные данные"}}};function D7(){return{localeError:MP()}}var VP=()=>{let $={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Neveljaven vnos: pričakovano instanceof ${K.expected}, prejeto ${G}`;return`Neveljaven vnos: pričakovano ${W}, prejeto ${G}`}case"invalid_value":if(K.values.length===1)return`Neveljaven vnos: pričakovano ${v(K.values[0])}`;return`Neveljavna možnost: pričakovano eno izmed ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Preveliko: pričakovano, da bo ${K.origin??"vrednost"} imelo ${W}${K.maximum.toString()} ${J.unit??"elementov"}`;return`Preveliko: pričakovano, da bo ${K.origin??"vrednost"} ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Premajhno: pričakovano, da bo ${K.origin} imelo ${W}${K.minimum.toString()} ${J.unit}`;return`Premajhno: pričakovano, da bo ${K.origin} ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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 ${Q[W.format]??K.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${K.divisor}`;case"unrecognized_keys":return`Neprepoznan${K.keys.length>1?"i ključi":" ključ"}: ${N(K.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${K.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${K.origin}`;default:return"Neveljaven vnos"}}};function N7(){return{localeError:VP()}}var DP=()=>{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(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Ogiltig inmatning: förväntat instanceof ${K.expected}, fick ${G}`;return`Ogiltig inmatning: förväntat ${W}, fick ${G}`}case"invalid_value":if(K.values.length===1)return`Ogiltig inmatning: förväntat ${v(K.values[0])}`;return`Ogiltigt val: förväntade en av ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`För stor(t): förväntade ${K.origin??"värdet"} att ha ${W}${K.maximum.toString()} ${J.unit??"element"}`;return`För stor(t): förväntat ${K.origin??"värdet"} att ha ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`För lite(t): förväntade ${K.origin??"värdet"} att ha ${W}${K.minimum.toString()} ${J.unit}`;return`För lite(t): förväntade ${K.origin??"värdet"} att ha ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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) ${Q[W.format]??K.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${K.divisor}`;case"unrecognized_keys":return`${K.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${N(K.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${K.origin??"värdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${K.origin??"värdet"}`;default:return"Ogiltig input"}}};function P7(){return{localeError:DP()}}var NP=()=>{let $={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${K.expected}, பெறப்பட்டது ${G}`;return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${W}, பெறப்பட்டது ${G}`}case"invalid_value":if(K.values.length===1)return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${v(K.values[0])}`;return`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${N(K.values,"|")} இல் ஒன்று`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${K.origin??"மதிப்பு"} ${W}${K.maximum.toString()} ${J.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`;return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${K.origin??"மதிப்பு"} ${W}${K.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${K.origin} ${W}${K.minimum.toString()} ${J.unit} ஆக இருக்க வேண்டும்`;return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${K.origin} ${W}${K.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{let W=K;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`தவறான ${Q[W.format]??K.format}`}case"not_multiple_of":return`தவறான எண்: ${K.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${K.keys.length>1?"கள்":""}: ${N(K.keys,", ")}`;case"invalid_key":return`${K.origin} இல் தவறான விசை`;case"invalid_union":return"தவறான உள்ளீடு";case"invalid_element":return`${K.origin} இல் தவறான மதிப்பு`;default:return"தவறான உள்ளீடு"}}};function I7(){return{localeError:NP()}}var PP=()=>{let $={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${K.expected} แต่ได้รับ ${G}`;return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${W} แต่ได้รับ ${G}`}case"invalid_value":if(K.values.length===1)return`ค่าไม่ถูกต้อง: ควรเป็น ${v(K.values[0])}`;return`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"ไม่เกิน":"น้อยกว่า",J=U(K.origin);if(J)return`เกินกำหนด: ${K.origin??"ค่า"} ควรมี${W} ${K.maximum.toString()} ${J.unit??"รายการ"}`;return`เกินกำหนด: ${K.origin??"ค่า"} ควรมี${W} ${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?"อย่างน้อย":"มากกว่า",J=U(K.origin);if(J)return`น้อยกว่ากำหนด: ${K.origin} ควรมี${W} ${K.minimum.toString()} ${J.unit}`;return`น้อยกว่ากำหนด: ${K.origin} ควรมี${W} ${K.minimum.toString()}`}case"invalid_format":{let W=K;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`รูปแบบไม่ถูกต้อง: ${Q[W.format]??K.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${K.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${N(K.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${K.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${K.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};function _7(){return{localeError:PP()}}var IP=()=>{let $={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Geçersiz değer: beklenen instanceof ${K.expected}, alınan ${G}`;return`Geçersiz değer: beklenen ${W}, alınan ${G}`}case"invalid_value":if(K.values.length===1)return`Geçersiz değer: beklenen ${v(K.values[0])}`;return`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Çok büyük: beklenen ${K.origin??"değer"} ${W}${K.maximum.toString()} ${J.unit??"öğe"}`;return`Çok büyük: beklenen ${K.origin??"değer"} ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Çok küçük: beklenen ${K.origin} ${W}${K.minimum.toString()} ${J.unit}`;return`Çok küçük: beklenen ${K.origin} ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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 ${Q[W.format]??K.format}`}case"not_multiple_of":return`Geçersiz sayı: ${K.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${K.keys.length>1?"lar":""}: ${N(K.keys,", ")}`;case"invalid_key":return`${K.origin} içinde geçersiz anahtar`;case"invalid_union":return"Geçersiz değer";case"invalid_element":return`${K.origin} içinde geçersiz değer`;default:return"Geçersiz değer"}}};function L7(){return{localeError:IP()}}var _P=()=>{let $={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Неправильні вхідні дані: очікується instanceof ${K.expected}, отримано ${G}`;return`Неправильні вхідні дані: очікується ${W}, отримано ${G}`}case"invalid_value":if(K.values.length===1)return`Неправильні вхідні дані: очікується ${v(K.values[0])}`;return`Неправильна опція: очікується одне з ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Занадто велике: очікується, що ${K.origin??"значення"} ${J.verb} ${W}${K.maximum.toString()} ${J.unit??"елементів"}`;return`Занадто велике: очікується, що ${K.origin??"значення"} буде ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Занадто мале: очікується, що ${K.origin} ${J.verb} ${W}${K.minimum.toString()} ${J.unit}`;return`Занадто мале: очікується, що ${K.origin} буде ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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`Неправильний ${Q[W.format]??K.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${K.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${K.keys.length>1?"і":""}: ${N(K.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${K.origin}`;case"invalid_union":return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${K.origin}`;default:return"Неправильні вхідні дані"}}};function g6(){return{localeError:_P()}}function F7(){return g6()}var LP=()=>{let $={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`غلط ان پٹ: instanceof ${K.expected} متوقع تھا، ${G} موصول ہوا`;return`غلط ان پٹ: ${W} متوقع تھا، ${G} موصول ہوا`}case"invalid_value":if(K.values.length===1)return`غلط ان پٹ: ${v(K.values[0])} متوقع تھا`;return`غلط آپشن: ${N(K.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`بہت بڑا: ${K.origin??"ویلیو"} کے ${W}${K.maximum.toString()} ${J.unit??"عناصر"} ہونے متوقع تھے`;return`بہت بڑا: ${K.origin??"ویلیو"} کا ${W}${K.maximum.toString()} ہونا متوقع تھا`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`بہت چھوٹا: ${K.origin} کے ${W}${K.minimum.toString()} ${J.unit} ہونے متوقع تھے`;return`بہت چھوٹا: ${K.origin} کا ${W}${K.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{let W=K;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`غلط ${Q[W.format]??K.format}`}case"not_multiple_of":return`غلط نمبر: ${K.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${K.keys.length>1?"ز":""}: ${N(K.keys,"، ")}`;case"invalid_key":return`${K.origin} میں غلط کی`;case"invalid_union":return"غلط ان پٹ";case"invalid_element":return`${K.origin} میں غلط ویلیو`;default:return"غلط ان پٹ"}}};function v7(){return{localeError:LP()}}var FP=()=>{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(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Noto‘g‘ri kirish: kutilgan instanceof ${K.expected}, qabul qilingan ${G}`;return`Noto‘g‘ri kirish: kutilgan ${W}, qabul qilingan ${G}`}case"invalid_value":if(K.values.length===1)return`Noto‘g‘ri kirish: kutilgan ${v(K.values[0])}`;return`Noto‘g‘ri variant: quyidagilardan biri kutilgan ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Juda katta: kutilgan ${K.origin??"qiymat"} ${W}${K.maximum.toString()} ${J.unit} ${J.verb}`;return`Juda katta: kutilgan ${K.origin??"qiymat"} ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Juda kichik: kutilgan ${K.origin} ${W}${K.minimum.toString()} ${J.unit} ${J.verb}`;return`Juda kichik: kutilgan ${K.origin} ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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 ${Q[W.format]??K.format}`}case"not_multiple_of":return`Noto‘g‘ri raqam: ${K.divisor} ning karralisi bo‘lishi kerak`;case"unrecognized_keys":return`Noma’lum kalit${K.keys.length>1?"lar":""}: ${N(K.keys,", ")}`;case"invalid_key":return`${K.origin} dagi kalit noto‘g‘ri`;case"invalid_union":return"Noto‘g‘ri kirish";case"invalid_element":return`${K.origin} da noto‘g‘ri qiymat`;default:return"Noto‘g‘ri kirish"}}};function z7(){return{localeError:FP()}}var vP=()=>{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(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Đầu vào không hợp lệ: mong đợi instanceof ${K.expected}, nhận được ${G}`;return`Đầu vào không hợp lệ: mong đợi ${W}, nhận được ${G}`}case"invalid_value":if(K.values.length===1)return`Đầu vào không hợp lệ: mong đợi ${v(K.values[0])}`;return`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Quá lớn: mong đợi ${K.origin??"giá trị"} ${J.verb} ${W}${K.maximum.toString()} ${J.unit??"phần tử"}`;return`Quá lớn: mong đợi ${K.origin??"giá trị"} ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Quá nhỏ: mong đợi ${K.origin} ${J.verb} ${W}${K.minimum.toString()} ${J.unit}`;return`Quá nhỏ: mong đợi ${K.origin} ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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`${Q[W.format]??K.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 ${K.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${N(K.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${K.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 ${K.origin}`;default:return"Đầu vào không hợp lệ"}}};function k7(){return{localeError:vP()}}var zP=()=>{let $={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`无效输入:期望 instanceof ${K.expected},实际接收 ${G}`;return`无效输入:期望 ${W},实际接收 ${G}`}case"invalid_value":if(K.values.length===1)return`无效输入:期望 ${v(K.values[0])}`;return`无效选项:期望以下之一 ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`数值过大:期望 ${K.origin??"值"} ${W}${K.maximum.toString()} ${J.unit??"个元素"}`;return`数值过大:期望 ${K.origin??"值"} ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`数值过小:期望 ${K.origin} ${W}${K.minimum.toString()} ${J.unit}`;return`数值过小:期望 ${K.origin} ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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`无效${Q[W.format]??K.format}`}case"not_multiple_of":return`无效数字:必须是 ${K.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${N(K.keys,", ")}`;case"invalid_key":return`${K.origin} 中的键(key)无效`;case"invalid_union":return"无效输入";case"invalid_element":return`${K.origin} 中包含无效值(value)`;default:return"无效输入"}}};function w7(){return{localeError:zP()}}var kP=()=>{let $={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`無效的輸入值:預期為 instanceof ${K.expected},但收到 ${G}`;return`無效的輸入值:預期為 ${W},但收到 ${G}`}case"invalid_value":if(K.values.length===1)return`無效的輸入值:預期為 ${v(K.values[0])}`;return`無效的選項:預期為以下其中之一 ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`數值過大:預期 ${K.origin??"值"} 應為 ${W}${K.maximum.toString()} ${J.unit??"個元素"}`;return`數值過大:預期 ${K.origin??"值"} 應為 ${W}${K.maximum.toString()}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`數值過小:預期 ${K.origin} 應為 ${W}${K.minimum.toString()} ${J.unit}`;return`數值過小:預期 ${K.origin} 應為 ${W}${K.minimum.toString()}`}case"invalid_format":{let W=K;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`無效的 ${Q[W.format]??K.format}`}case"not_multiple_of":return`無效的數字:必須為 ${K.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${K.keys.length>1?"們":""}:${N(K.keys,"、")}`;case"invalid_key":return`${K.origin} 中有無效的鍵值`;case"invalid_union":return"無效的輸入值";case"invalid_element":return`${K.origin} 中有無效的值`;default:return"無效的輸入值"}}};function x7(){return{localeError:kP()}}var wP=()=>{let $={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function U(K){return $[K]??null}let Q={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(K)=>{switch(K.code){case"invalid_type":{let W=q[K.expected]??K.expected,J=z(K.input),G=q[J]??J;if(/^[A-Z]/.test(K.expected))return`Ìbáwọlé aṣìṣe: a ní láti fi instanceof ${K.expected}, àmọ̀ a rí ${G}`;return`Ìbáwọlé aṣìṣe: a ní láti fi ${W}, àmọ̀ a rí ${G}`}case"invalid_value":if(K.values.length===1)return`Ìbáwọlé aṣìṣe: a ní láti fi ${v(K.values[0])}`;return`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${N(K.values,"|")}`;case"too_big":{let W=K.inclusive?"<=":"<",J=U(K.origin);if(J)return`Tó pọ̀ jù: a ní láti jẹ́ pé ${K.origin??"iye"} ${J.verb} ${W}${K.maximum} ${J.unit}`;return`Tó pọ̀ jù: a ní láti jẹ́ ${W}${K.maximum}`}case"too_small":{let W=K.inclusive?">=":">",J=U(K.origin);if(J)return`Kéré ju: a ní láti jẹ́ pé ${K.origin} ${J.verb} ${W}${K.minimum} ${J.unit}`;return`Kéré ju: a ní láti jẹ́ ${W}${K.minimum}`}case"invalid_format":{let W=K;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: ${Q[W.format]??K.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${K.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${N(K.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${K.origin}`;case"invalid_union":return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${K.origin}`;default:return"Ìbáwọlé aṣìṣe"}}};function A7(){return{localeError:wP()}}var tG,b7=Symbol("ZodOutput"),O7=Symbol("ZodInput");class R7{constructor(){this._map=new WeakMap,this._idmap=new Map}add($,...U){let Q=U[0];if(this._map.set($,Q),Q&&typeof Q==="object"&&"id"in Q)this._idmap.set(Q.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 Q={...this.get(U)??{}};delete Q.id;let q={...Q,...this._map.get($)};return Object.keys(q).length?q:void 0}return this._map.get($)}has($){return this._map.has($)}}function e0(){return new R7}(tG=globalThis).__zod_globalRegistry??(tG.__zod_globalRegistry=e0());var P$=globalThis.__zod_globalRegistry;function T7($,U){return new $({type:"string",...O(U)})}function S7($,U){return new $({type:"string",coerce:!0,...O(U)})}function $2($,U){return new $({type:"string",format:"email",check:"string_format",abort:!1,...O(U)})}function u6($,U){return new $({type:"string",format:"guid",check:"string_format",abort:!1,...O(U)})}function U2($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,...O(U)})}function K2($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...O(U)})}function Q2($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...O(U)})}function q2($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...O(U)})}function f6($,U){return new $({type:"string",format:"url",check:"string_format",abort:!1,...O(U)})}function W2($,U){return new $({type:"string",format:"emoji",check:"string_format",abort:!1,...O(U)})}function J2($,U){return new $({type:"string",format:"nanoid",check:"string_format",abort:!1,...O(U)})}function G2($,U){return new $({type:"string",format:"cuid",check:"string_format",abort:!1,...O(U)})}function j2($,U){return new $({type:"string",format:"cuid2",check:"string_format",abort:!1,...O(U)})}function Y2($,U){return new $({type:"string",format:"ulid",check:"string_format",abort:!1,...O(U)})}function H2($,U){return new $({type:"string",format:"xid",check:"string_format",abort:!1,...O(U)})}function X2($,U){return new $({type:"string",format:"ksuid",check:"string_format",abort:!1,...O(U)})}function B2($,U){return new $({type:"string",format:"ipv4",check:"string_format",abort:!1,...O(U)})}function Z2($,U){return new $({type:"string",format:"ipv6",check:"string_format",abort:!1,...O(U)})}function C7($,U){return new $({type:"string",format:"mac",check:"string_format",abort:!1,...O(U)})}function M2($,U){return new $({type:"string",format:"cidrv4",check:"string_format",abort:!1,...O(U)})}function V2($,U){return new $({type:"string",format:"cidrv6",check:"string_format",abort:!1,...O(U)})}function D2($,U){return new $({type:"string",format:"base64",check:"string_format",abort:!1,...O(U)})}function N2($,U){return new $({type:"string",format:"base64url",check:"string_format",abort:!1,...O(U)})}function P2($,U){return new $({type:"string",format:"e164",check:"string_format",abort:!1,...O(U)})}function I2($,U){return new $({type:"string",format:"jwt",check:"string_format",abort:!1,...O(U)})}var E7={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function g7($,U){return new $({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...O(U)})}function y7($,U){return new $({type:"string",format:"date",check:"string_format",...O(U)})}function u7($,U){return new $({type:"string",format:"time",check:"string_format",precision:null,...O(U)})}function f7($,U){return new $({type:"string",format:"duration",check:"string_format",...O(U)})}function h7($,U){return new $({type:"number",checks:[],...O(U)})}function m7($,U){return new $({type:"number",coerce:!0,checks:[],...O(U)})}function c7($,U){return new $({type:"number",check:"number_format",abort:!1,format:"safeint",...O(U)})}function l7($,U){return new $({type:"number",check:"number_format",abort:!1,format:"float32",...O(U)})}function r7($,U){return new $({type:"number",check:"number_format",abort:!1,format:"float64",...O(U)})}function n7($,U){return new $({type:"number",check:"number_format",abort:!1,format:"int32",...O(U)})}function i7($,U){return new $({type:"number",check:"number_format",abort:!1,format:"uint32",...O(U)})}function o7($,U){return new $({type:"boolean",...O(U)})}function d7($,U){return new $({type:"boolean",coerce:!0,...O(U)})}function p7($,U){return new $({type:"bigint",...O(U)})}function t7($,U){return new $({type:"bigint",coerce:!0,...O(U)})}function a7($,U){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...O(U)})}function s7($,U){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...O(U)})}function e7($,U){return new $({type:"symbol",...O(U)})}function $5($,U){return new $({type:"undefined",...O(U)})}function U5($,U){return new $({type:"null",...O(U)})}function K5($){return new $({type:"any"})}function Q5($){return new $({type:"unknown"})}function q5($,U){return new $({type:"never",...O(U)})}function W5($,U){return new $({type:"void",...O(U)})}function J5($,U){return new $({type:"date",...O(U)})}function G5($,U){return new $({type:"date",coerce:!0,...O(U)})}function j5($,U){return new $({type:"nan",...O(U)})}function $1($,U){return new m0({check:"less_than",...O(U),value:$,inclusive:!1})}function g$($,U){return new m0({check:"less_than",...O(U),value:$,inclusive:!0})}function U1($,U){return new c0({check:"greater_than",...O(U),value:$,inclusive:!1})}function k$($,U){return new c0({check:"greater_than",...O(U),value:$,inclusive:!0})}function _2($){return U1(0,$)}function L2($){return $1(0,$)}function F2($){return g$(0,$)}function v2($){return k$(0,$)}function x1($,U){return new j3({check:"multiple_of",...O(U),value:$})}function A1($,U){return new X3({check:"max_size",...O(U),maximum:$})}function K1($,U){return new B3({check:"min_size",...O(U),minimum:$})}function K4($,U){return new Z3({check:"size_equals",...O(U),size:$})}function Q4($,U){return new M3({check:"max_length",...O(U),maximum:$})}function X1($,U){return new V3({check:"min_length",...O(U),minimum:$})}function q4($,U){return new D3({check:"length_equals",...O(U),length:$})}function b4($,U){return new N3({check:"string_format",format:"regex",...O(U),pattern:$})}function O4($){return new P3({check:"string_format",format:"lowercase",...O($)})}function R4($){return new I3({check:"string_format",format:"uppercase",...O($)})}function T4($,U){return new _3({check:"string_format",format:"includes",...O(U),includes:$})}function S4($,U){return new L3({check:"string_format",format:"starts_with",...O(U),prefix:$})}function C4($,U){return new F3({check:"string_format",format:"ends_with",...O(U),suffix:$})}function z2($,U,Q){return new v3({check:"property",property:$,schema:U,...O(Q)})}function E4($,U){return new z3({check:"mime_type",mime:$,...O(U)})}function t$($){return new k3({check:"overwrite",tx:$})}function g4($){return t$((U)=>U.normalize($))}function y4(){return t$(($)=>$.trim())}function u4(){return t$(($)=>$.toLowerCase())}function f4(){return t$(($)=>$.toUpperCase())}function h4(){return t$(($)=>vU($))}function Y5($,U,Q){return new $({type:"array",element:U,...O(Q)})}function AP($,U,Q){return new $({type:"union",options:U,...O(Q)})}function bP($,U,Q){return new $({type:"union",options:U,inclusive:!1,...O(Q)})}function OP($,U,Q,q){return new $({type:"union",options:Q,discriminator:U,...O(q)})}function RP($,U,Q){return new $({type:"intersection",left:U,right:Q})}function TP($,U,Q,q){let K=Q instanceof u;return new $({type:"tuple",items:U,rest:K?Q:null,...O(K?q:Q)})}function SP($,U,Q,q){return new $({type:"record",keyType:U,valueType:Q,...O(q)})}function CP($,U,Q,q){return new $({type:"map",keyType:U,valueType:Q,...O(q)})}function EP($,U,Q){return new $({type:"set",valueType:U,...O(Q)})}function gP($,U,Q){let q=Array.isArray(U)?Object.fromEntries(U.map((K)=>[K,K])):U;return new $({type:"enum",entries:q,...O(Q)})}function yP($,U,Q){return new $({type:"enum",entries:U,...O(Q)})}function uP($,U,Q){return new $({type:"literal",values:Array.isArray(U)?U:[U],...O(Q)})}function H5($,U){return new $({type:"file",...O(U)})}function fP($,U){return new $({type:"transform",transform:U})}function hP($,U){return new $({type:"optional",innerType:U})}function mP($,U){return new $({type:"nullable",innerType:U})}function cP($,U,Q){return new $({type:"default",innerType:U,get defaultValue(){return typeof Q==="function"?Q():kU(Q)}})}function lP($,U,Q){return new $({type:"nonoptional",innerType:U,...O(Q)})}function rP($,U){return new $({type:"success",innerType:U})}function nP($,U,Q){return new $({type:"catch",innerType:U,catchValue:typeof Q==="function"?Q:()=>Q})}function iP($,U,Q){return new $({type:"pipe",in:U,out:Q})}function oP($,U){return new $({type:"readonly",innerType:U})}function dP($,U,Q){return new $({type:"template_literal",parts:U,...O(Q)})}function pP($,U){return new $({type:"lazy",getter:U})}function tP($,U){return new $({type:"promise",innerType:U})}function X5($,U,Q){let q=O(Q);return q.abort??(q.abort=!0),new $({type:"custom",check:"custom",fn:U,...q})}function B5($,U,Q){return new $({type:"custom",check:"custom",fn:U,...O(Q)})}function Z5($){let U=aG((Q)=>{return Q.addIssue=(q)=>{if(typeof q==="string")Q.issues.push(F4(q,Q.value,U._zod.def));else{let K=q;if(K.fatal)K.continue=!1;K.code??(K.code="custom"),K.input??(K.input=Q.value),K.inst??(K.inst=U),K.continue??(K.continue=!U._zod.def.abort),Q.issues.push(F4(K))}},$(Q.value,Q)});return U}function aG($,U){let Q=new $$({check:"custom",...O(U)});return Q._zod.check=$,Q}function M5($){let U=new $$({check:"describe"});return U._zod.onattach=[(Q)=>{let q=P$.get(Q)??{};P$.add(Q,{...q,description:$})}],U._zod.check=()=>{},U}function V5($){let U=new $$({check:"meta"});return U._zod.onattach=[(Q)=>{let q=P$.get(Q)??{};P$.add(Q,{...q,...$})}],U._zod.check=()=>{},U}function D5($,U){let Q=O(U),q=Q.truthy??["true","1","yes","on","y","enabled"],K=Q.falsy??["false","0","no","off","n","disabled"];if(Q.case!=="sensitive")q=q.map((L)=>typeof L==="string"?L.toLowerCase():L),K=K.map((L)=>typeof L==="string"?L.toLowerCase():L);let W=new Set(q),J=new Set(K),G=$.Codec??T6,Y=$.Boolean??O6,B=new($.String??U4)({type:"string",error:Q.error}),M=new Y({type:"boolean",error:Q.error}),V=new G({type:"pipe",in:B,out:M,transform:(L,T)=>{let f=L;if(Q.case!=="sensitive")f=f.toLowerCase();if(W.has(f))return!0;else if(J.has(f))return!1;else return T.issues.push({code:"invalid_value",expected:"stringbool",values:[...W,...J],input:T.value,inst:V,continue:!1}),{}},reverseTransform:(L,T)=>{if(L===!0)return q[0]||"true";else return K[0]||"false"},error:Q.error});return V}function m4($,U,Q,q={}){let K=O(q),W={...O(q),check:"string_format",type:"string",format:U,fn:typeof Q==="function"?Q:(G)=>Q.test(G),...K};if(Q instanceof RegExp)W.pattern=Q;return new $(W)}function b1($){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??P$,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 p($,U,Q={path:[],schemaPath:[]}){var q;let K=$._zod.def,W=U.seen.get($);if(W){if(W.count++,Q.schemaPath.includes($))W.cycle=Q.path;return W.schema}let J={schema:{},count:1,cycle:void 0,path:Q.path};U.seen.set($,J);let G=$._zod.toJSONSchema?.();if(G)J.schema=G;else{let B={...Q,schemaPath:[...Q.schemaPath,$],path:Q.path};if($._zod.processJSONSchema)$._zod.processJSONSchema(U,J.schema,B);else{let V=J.schema,L=U.processors[K.type];if(!L)throw Error(`[toJSONSchema]: Non-representable type encountered: ${K.type}`);L($,U,V,B)}let M=$._zod.parent;if(M){if(!J.ref)J.ref=M;p(M,U,B),U.seen.get(M).isParent=!0}}let Y=U.metadataRegistry.get($);if(Y)Object.assign(J.schema,Y);if(U.io==="input"&&w$($))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 O1($,U){let Q=$.seen.get(U);if(!Q)throw Error("Unprocessed schema. This is a bug in Zod.");let q=new Map;for(let J of $.seen.entries()){let G=$.metadataRegistry.get(J[0])?.id;if(G){let Y=q.get(G);if(Y&&Y!==J[0])throw Error(`Duplicate schema id "${G}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);q.set(G,J[0])}}let K=(J)=>{let G=$.target==="draft-2020-12"?"$defs":"definitions";if($.external){let M=$.external.registry.get(J[0])?.id,V=$.external.uri??((T)=>T);if(M)return{ref:V(M)};let L=J[1].defId??J[1].schema.id??`schema${$.counter++}`;return J[1].defId=L,{defId:L,ref:`${V("__shared")}#/${G}/${L}`}}if(J[1]===Q)return{ref:"#"};let H=`${"#"}/${G}/`,B=J[1].schema.id??`__schema${$.counter++}`;return{defId:B,ref:H+B}},W=(J)=>{if(J[1].schema.$ref)return;let G=J[1],{ref:Y,defId:H}=K(J);if(G.def={...G.schema},H)G.defId=H;let B=G.schema;for(let M in B)delete B[M];B.$ref=Y};if($.cycles==="throw")for(let J of $.seen.entries()){let G=J[1];if(G.cycle)throw Error(`Cycle detected: #/${G.cycle?.join("/")}/<root>
|
|
97
93
|
|
|
98
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let q of $.seen.entries()){let G=q[1];if(v===q[0]){Q(q);continue}if($.external){let Y=$.external.registry.get(q[0])?.id;if(v!==q[0]&&Y){Q(q);continue}}if($.metadataRegistry.get(q[0])?.id){Q(q);continue}if(G.cycle){Q(q);continue}if(G.count>1){if($.reused==="ref"){Q(q);continue}}}}function N1($,v){let K=$.seen.get(v);if(!K)throw Error("Unprocessed schema. This is a bug in Zod.");let _=(q)=>{let G=$.seen.get(q);if(G.ref===null)return;let j=G.def??G.schema,Y={...j},X=G.ref;if(G.ref=null,X){_(X);let B=$.seen.get(X),N=B.schema;if(N.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))j.allOf=j.allOf??[],j.allOf.push(N);else Object.assign(j,N);if(Object.assign(j,Y),q._zod.parent===X)for(let f in j){if(f==="$ref"||f==="allOf")continue;if(!(f in Y))delete j[f]}if(N.$ref&&B.def)for(let f in j){if(f==="$ref"||f==="allOf")continue;if(f in B.def&&JSON.stringify(j[f])===JSON.stringify(B.def[f]))delete j[f]}}let P=q._zod.parent;if(P&&P!==X){_(P);let B=$.seen.get(P);if(B?.schema.$ref){if(j.$ref=B.schema.$ref,B.def)for(let N in j){if(N==="$ref"||N==="allOf")continue;if(N in B.def&&JSON.stringify(j[N])===JSON.stringify(B.def[N]))delete j[N]}}}$.override({zodSchema:q,jsonSchema:j,path:G.path??[]})};for(let q of[...$.seen.entries()].reverse())_(q[0]);let U={};if($.target==="draft-2020-12")U.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")U.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")U.$schema="http://json-schema.org/draft-04/schema#";else if($.target==="openapi-3.0");if($.external?.uri){let q=$.external.registry.get(v)?.id;if(!q)throw Error("Schema is missing an `id` property");U.$id=$.external.uri(q)}Object.assign(U,K.def??K.schema);let Q=$.external?.defs??{};for(let q of $.seen.entries()){let G=q[1];if(G.def&&G.defId)Q[G.defId]=G.def}if($.external);else if(Object.keys(Q).length>0)if($.target==="draft-2020-12")U.$defs=Q;else U.definitions=Q;try{let q=JSON.parse(JSON.stringify(U));return Object.defineProperty(q,"~standard",{value:{...v["~standard"],jsonSchema:{input:w4(v,"input",$.processors),output:w4(v,"output",$.processors)}},enumerable:!1,writable:!1}),q}catch(q){throw Error("Error converting schema to JSON.")}}function B$($,v){let K=v??{seen:new Set};if(K.seen.has($))return!1;K.seen.add($);let _=$._zod.def;if(_.type==="transform")return!0;if(_.type==="array")return B$(_.element,K);if(_.type==="set")return B$(_.valueType,K);if(_.type==="lazy")return B$(_.getter(),K);if(_.type==="promise"||_.type==="optional"||_.type==="nonoptional"||_.type==="nullable"||_.type==="readonly"||_.type==="default"||_.type==="prefault")return B$(_.innerType,K);if(_.type==="intersection")return B$(_.left,K)||B$(_.right,K);if(_.type==="record"||_.type==="map")return B$(_.keyType,K)||B$(_.valueType,K);if(_.type==="pipe")return B$(_.in,K)||B$(_.out,K);if(_.type==="object"){for(let U in _.shape)if(B$(_.shape[U],K))return!0;return!1}if(_.type==="union"){for(let U of _.options)if(B$(U,K))return!0;return!1}if(_.type==="tuple"){for(let U of _.items)if(B$(U,K))return!0;if(_.rest&&B$(_.rest,K))return!0;return!1}return!1}var M8=($,v={})=>(K)=>{let _=b1({...K,processors:v});return n($,_),k1(_,$),N1(_,$)},w4=($,v,K={})=>(_)=>{let{libraryOptions:U,target:Q}=_??{},q=b1({...U??{},target:Q,io:v,processors:K});return n($,q),k1(q,$),N1(q,$)};var QV={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},I8=($,v,K,_)=>{let U=K;U.type="string";let{minimum:Q,maximum:q,format:G,patterns:j,contentEncoding:Y}=$._zod.bag;if(typeof Q==="number")U.minLength=Q;if(typeof q==="number")U.maxLength=q;if(G){if(U.format=QV[G]??G,U.format==="")delete U.format;if(G==="time")delete U.format}if(Y)U.contentEncoding=Y;if(j&&j.size>0){let X=[...j];if(X.length===1)U.pattern=X[0].source;else if(X.length>1)U.allOf=[...X.map((P)=>({...v.target==="draft-07"||v.target==="draft-04"||v.target==="openapi-3.0"?{type:"string"}:{},pattern:P.source}))]}},Z8=($,v,K,_)=>{let U=K,{minimum:Q,maximum:q,format:G,multipleOf:j,exclusiveMaximum:Y,exclusiveMinimum:X}=$._zod.bag;if(typeof G==="string"&&G.includes("int"))U.type="integer";else U.type="number";if(typeof X==="number")if(v.target==="draft-04"||v.target==="openapi-3.0")U.minimum=X,U.exclusiveMinimum=!0;else U.exclusiveMinimum=X;if(typeof Q==="number"){if(U.minimum=Q,typeof X==="number"&&v.target!=="draft-04")if(X>=Q)delete U.minimum;else delete U.exclusiveMinimum}if(typeof Y==="number")if(v.target==="draft-04"||v.target==="openapi-3.0")U.maximum=Y,U.exclusiveMaximum=!0;else U.exclusiveMaximum=Y;if(typeof q==="number"){if(U.maximum=q,typeof Y==="number"&&v.target!=="draft-04")if(Y<=q)delete U.maximum;else delete U.exclusiveMaximum}if(typeof j==="number")U.multipleOf=j},z8=($,v,K,_)=>{K.type="boolean"},L8=($,v,K,_)=>{if(v.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},A8=($,v,K,_)=>{if(v.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},F8=($,v,K,_)=>{if(v.target==="openapi-3.0")K.type="string",K.nullable=!0,K.enum=[null];else K.type="null"},O8=($,v,K,_)=>{if(v.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},x8=($,v,K,_)=>{if(v.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},R8=($,v,K,_)=>{K.not={}},S8=($,v,K,_)=>{},u8=($,v,K,_)=>{},T8=($,v,K,_)=>{if(v.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},g8=($,v,K,_)=>{let U=$._zod.def,Q=n4(U.entries);if(Q.every((q)=>typeof q==="number"))K.type="number";if(Q.every((q)=>typeof q==="string"))K.type="string";K.enum=Q},E8=($,v,K,_)=>{let U=$._zod.def,Q=[];for(let q of U.values)if(q===void 0){if(v.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof q==="bigint")if(v.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else Q.push(Number(q));else Q.push(q);if(Q.length===0);else if(Q.length===1){let q=Q[0];if(K.type=q===null?"null":typeof q,v.target==="draft-04"||v.target==="openapi-3.0")K.enum=[q];else K.const=q}else{if(Q.every((q)=>typeof q==="number"))K.type="number";if(Q.every((q)=>typeof q==="string"))K.type="string";if(Q.every((q)=>typeof q==="boolean"))K.type="boolean";if(Q.every((q)=>q===null))K.type="null";K.enum=Q}},C8=($,v,K,_)=>{if(v.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},y8=($,v,K,_)=>{let U=K,Q=$._zod.pattern;if(!Q)throw Error("Pattern not found in template literal");U.type="string",U.pattern=Q.source},f8=($,v,K,_)=>{let U=K,Q={type:"string",format:"binary",contentEncoding:"binary"},{minimum:q,maximum:G,mime:j}=$._zod.bag;if(q!==void 0)Q.minLength=q;if(G!==void 0)Q.maxLength=G;if(j)if(j.length===1)Q.contentMediaType=j[0],Object.assign(U,Q);else Object.assign(U,Q),U.anyOf=j.map((Y)=>({contentMediaType:Y}));else Object.assign(U,Q)},m8=($,v,K,_)=>{K.type="boolean"},h8=($,v,K,_)=>{if(v.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},c8=($,v,K,_)=>{if(v.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},r8=($,v,K,_)=>{if(v.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},i8=($,v,K,_)=>{if(v.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},n8=($,v,K,_)=>{if(v.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},l8=($,v,K,_)=>{let U=K,Q=$._zod.def,{minimum:q,maximum:G}=$._zod.bag;if(typeof q==="number")U.minItems=q;if(typeof G==="number")U.maxItems=G;U.type="array",U.items=n(Q.element,v,{..._,path:[..._.path,"items"]})},o8=($,v,K,_)=>{let U=K,Q=$._zod.def;U.type="object",U.properties={};let q=Q.shape;for(let Y in q)U.properties[Y]=n(q[Y],v,{..._,path:[..._.path,"properties",Y]});let G=new Set(Object.keys(q)),j=new Set([...G].filter((Y)=>{let X=Q.shape[Y]._zod;if(v.io==="input")return X.optin===void 0;else return X.optout===void 0}));if(j.size>0)U.required=Array.from(j);if(Q.catchall?._zod.def.type==="never")U.additionalProperties=!1;else if(!Q.catchall){if(v.io==="output")U.additionalProperties=!1}else if(Q.catchall)U.additionalProperties=n(Q.catchall,v,{..._,path:[..._.path,"additionalProperties"]})},t0=($,v,K,_)=>{let U=$._zod.def,Q=U.inclusive===!1,q=U.options.map((G,j)=>n(G,v,{..._,path:[..._.path,Q?"oneOf":"anyOf",j]}));if(Q)K.oneOf=q;else K.anyOf=q},d8=($,v,K,_)=>{let U=$._zod.def,Q=n(U.left,v,{..._,path:[..._.path,"allOf",0]}),q=n(U.right,v,{..._,path:[..._.path,"allOf",1]}),G=(Y)=>("allOf"in Y)&&Object.keys(Y).length===1,j=[...G(Q)?Q.allOf:[Q],...G(q)?q.allOf:[q]];K.allOf=j},t8=($,v,K,_)=>{let U=K,Q=$._zod.def;U.type="array";let q=v.target==="draft-2020-12"?"prefixItems":"items",G=v.target==="draft-2020-12"?"items":v.target==="openapi-3.0"?"items":"additionalItems",j=Q.items.map((B,N)=>n(B,v,{..._,path:[..._.path,q,N]})),Y=Q.rest?n(Q.rest,v,{..._,path:[..._.path,G,...v.target==="openapi-3.0"?[Q.items.length]:[]]}):null;if(v.target==="draft-2020-12"){if(U.prefixItems=j,Y)U.items=Y}else if(v.target==="openapi-3.0"){if(U.items={anyOf:j},Y)U.items.anyOf.push(Y);if(U.minItems=j.length,!Y)U.maxItems=j.length}else if(U.items=j,Y)U.additionalItems=Y;let{minimum:X,maximum:P}=$._zod.bag;if(typeof X==="number")U.minItems=X;if(typeof P==="number")U.maxItems=P},p8=($,v,K,_)=>{let U=K,Q=$._zod.def;U.type="object";let q=Q.keyType,j=q._zod.bag?.patterns;if(Q.mode==="loose"&&j&&j.size>0){let X=n(Q.valueType,v,{..._,path:[..._.path,"patternProperties","*"]});U.patternProperties={};for(let P of j)U.patternProperties[P.source]=X}else{if(v.target==="draft-07"||v.target==="draft-2020-12")U.propertyNames=n(Q.keyType,v,{..._,path:[..._.path,"propertyNames"]});U.additionalProperties=n(Q.valueType,v,{..._,path:[..._.path,"additionalProperties"]})}let Y=q._zod.values;if(Y){let X=[...Y].filter((P)=>typeof P==="string"||typeof P==="number");if(X.length>0)U.required=X}},a8=($,v,K,_)=>{let U=$._zod.def,Q=n(U.innerType,v,_),q=v.seen.get($);if(v.target==="openapi-3.0")q.ref=U.innerType,K.nullable=!0;else K.anyOf=[Q,{type:"null"}]},e8=($,v,K,_)=>{let U=$._zod.def;n(U.innerType,v,_);let Q=v.seen.get($);Q.ref=U.innerType},s8=($,v,K,_)=>{let U=$._zod.def;n(U.innerType,v,_);let Q=v.seen.get($);Q.ref=U.innerType,K.default=JSON.parse(JSON.stringify(U.defaultValue))},$3=($,v,K,_)=>{let U=$._zod.def;n(U.innerType,v,_);let Q=v.seen.get($);if(Q.ref=U.innerType,v.io==="input")K._prefault=JSON.parse(JSON.stringify(U.defaultValue))},v3=($,v,K,_)=>{let U=$._zod.def;n(U.innerType,v,_);let Q=v.seen.get($);Q.ref=U.innerType;let q;try{q=U.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}K.default=q},U3=($,v,K,_)=>{let U=$._zod.def,Q=v.io==="input"?U.in._zod.def.type==="transform"?U.out:U.in:U.out;n(Q,v,_);let q=v.seen.get($);q.ref=Q},K3=($,v,K,_)=>{let U=$._zod.def;n(U.innerType,v,_);let Q=v.seen.get($);Q.ref=U.innerType,K.readOnly=!0},_3=($,v,K,_)=>{let U=$._zod.def;n(U.innerType,v,_);let Q=v.seen.get($);Q.ref=U.innerType},p0=($,v,K,_)=>{let U=$._zod.def;n(U.innerType,v,_);let Q=v.seen.get($);Q.ref=U.innerType},Q3=($,v,K,_)=>{let U=$._zod.innerType;n(U,v,_);let Q=v.seen.get($);Q.ref=U},d0={string:I8,number:Z8,boolean:z8,bigint:L8,symbol:A8,null:F8,undefined:O8,void:x8,never:R8,any:S8,unknown:u8,date:T8,enum:g8,literal:E8,nan:C8,template_literal:y8,file:f8,success:m8,custom:h8,function:c8,transform:r8,map:i8,set:n8,array:l8,object:o8,union:t0,intersection:d8,tuple:t8,record:p8,nullable:a8,nonoptional:e8,default:s8,prefault:$3,catch:v3,pipe:U3,readonly:K3,promise:_3,optional:p0,lazy:Q3};function a0($,v){if("_idmap"in $){let _=$,U=b1({...v,processors:d0}),Q={};for(let j of _._idmap.entries()){let[Y,X]=j;n(X,U)}let q={},G={registry:_,uri:v?.uri,defs:Q};U.external=G;for(let j of _._idmap.entries()){let[Y,X]=j;k1(U,X),q[Y]=N1(U,X)}if(Object.keys(Q).length>0){let j=U.target==="draft-2020-12"?"$defs":"definitions";q.__shared={[j]:Q}}return{schemas:q}}let K=b1({...v,processors:d0});return n($,K),k1(K,$),N1(K,$)}class q3{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 v=$?.target??"draft-2020-12";if(v==="draft-4")v="draft-04";if(v==="draft-7")v="draft-07";this.ctx=b1({processors:d0,target:v,...$?.metadata&&{metadata:$.metadata},...$?.unrepresentable&&{unrepresentable:$.unrepresentable},...$?.override&&{override:$.override},...$?.io&&{io:$.io}})}process($,v={path:[],schemaPath:[]}){return n($,this.ctx,v)}emit($,v){if(v){if(v.cycles)this.ctx.cycles=v.cycles;if(v.reused)this.ctx.reused=v.reused;if(v.external)this.ctx.external=v.external}k1(this.ctx,$);let K=N1(this.ctx,$),{"~standard":_,...U}=K;return U}}var YG={};var X6={};o$(X6,{xor:()=>U5,xid:()=>zG,void:()=>pG,uuidv7:()=>DG,uuidv6:()=>BG,uuidv4:()=>VG,uuid:()=>PG,url:()=>bG,unknown:()=>f1,union:()=>Zv,undefined:()=>dG,ulid:()=>ZG,uint64:()=>lG,uint32:()=>rG,tuple:()=>m3,transform:()=>Lv,templateLiteral:()=>V5,symbol:()=>oG,superRefine:()=>H_,success:()=>X5,stringbool:()=>I5,stringFormat:()=>EG,string:()=>Kv,strictObject:()=>$5,set:()=>G5,refine:()=>X_,record:()=>h3,readonly:()=>q_,promise:()=>B5,preprocess:()=>z5,prefault:()=>s3,pipe:()=>B6,partialRecord:()=>_5,optional:()=>P6,object:()=>sG,number:()=>Z3,nullish:()=>J5,nullable:()=>V6,null:()=>O3,nonoptional:()=>$_,never:()=>Iv,nativeEnum:()=>W5,nanoid:()=>wG,nan:()=>H5,meta:()=>w5,map:()=>q5,mac:()=>FG,looseRecord:()=>Q5,looseObject:()=>v5,literal:()=>j5,lazy:()=>j_,ksuid:()=>LG,keyof:()=>eG,jwt:()=>gG,json:()=>Z5,ipv6:()=>OG,ipv4:()=>AG,intersection:()=>y3,int64:()=>nG,int32:()=>cG,int:()=>_v,instanceof:()=>M5,httpUrl:()=>kG,hostname:()=>CG,hex:()=>yG,hash:()=>fG,guid:()=>HG,function:()=>D5,float64:()=>hG,float32:()=>mG,file:()=>Y5,exactOptional:()=>d3,enum:()=>zv,emoji:()=>NG,email:()=>XG,e164:()=>TG,discriminatedUnion:()=>K5,describe:()=>N5,date:()=>aG,custom:()=>k5,cuid2:()=>IG,cuid:()=>MG,codec:()=>P5,cidrv6:()=>RG,cidrv4:()=>xG,check:()=>b5,catch:()=>K_,boolean:()=>z3,bigint:()=>iG,base64url:()=>uG,base64:()=>SG,array:()=>k6,any:()=>tG,_function:()=>D5,_default:()=>a3,_ZodString:()=>Qv,ZodXor:()=>g3,ZodXID:()=>Xv,ZodVoid:()=>u3,ZodUnknown:()=>R3,ZodUnion:()=>w6,ZodUndefined:()=>A3,ZodUUID:()=>l$,ZodURL:()=>D6,ZodULID:()=>Jv,ZodType:()=>m,ZodTuple:()=>f3,ZodTransform:()=>l3,ZodTemplateLiteral:()=>G_,ZodSymbol:()=>L3,ZodSuccess:()=>v_,ZodStringFormat:()=>o,ZodString:()=>Z4,ZodSet:()=>r3,ZodRecord:()=>M6,ZodReadonly:()=>Q_,ZodPromise:()=>Y_,ZodPrefault:()=>e3,ZodPipe:()=>Ov,ZodOptional:()=>Av,ZodObject:()=>N6,ZodNumberFormat:()=>m1,ZodNumber:()=>L4,ZodNullable:()=>t3,ZodNull:()=>F3,ZodNonOptional:()=>Fv,ZodNever:()=>S3,ZodNanoID:()=>Wv,ZodNaN:()=>__,ZodMap:()=>c3,ZodMAC:()=>I3,ZodLiteral:()=>i3,ZodLazy:()=>W_,ZodKSUID:()=>Hv,ZodJWT:()=>wv,ZodIntersection:()=>C3,ZodIPv6:()=>Vv,ZodIPv4:()=>Pv,ZodGUID:()=>H6,ZodFunction:()=>J_,ZodFile:()=>n3,ZodExactOptional:()=>o3,ZodEnum:()=>I4,ZodEmoji:()=>Gv,ZodEmail:()=>qv,ZodE164:()=>Nv,ZodDiscriminatedUnion:()=>E3,ZodDefault:()=>p3,ZodDate:()=>b6,ZodCustomStringFormat:()=>z4,ZodCustom:()=>I6,ZodCodec:()=>xv,ZodCatch:()=>U_,ZodCUID2:()=>Yv,ZodCUID:()=>jv,ZodCIDRv6:()=>Dv,ZodCIDRv4:()=>Bv,ZodBoolean:()=>A4,ZodBigIntFormat:()=>Mv,ZodBigInt:()=>F4,ZodBase64URL:()=>kv,ZodBase64:()=>bv,ZodArray:()=>T3,ZodAny:()=>x3});var e0={};o$(e0,{uppercase:()=>Y4,trim:()=>B4,toUpperCase:()=>b4,toLowerCase:()=>D4,startsWith:()=>X4,slugify:()=>k4,size:()=>E1,regex:()=>W4,property:()=>o0,positive:()=>r0,overwrite:()=>C$,normalize:()=>V4,nonpositive:()=>n0,nonnegative:()=>l0,negative:()=>i0,multipleOf:()=>B1,minSize:()=>n$,minLength:()=>s$,mime:()=>P4,maxSize:()=>D1,maxLength:()=>C1,lte:()=>z$,lt:()=>r$,lowercase:()=>j4,length:()=>y1,includes:()=>J4,gte:()=>V$,gt:()=>i$,endsWith:()=>H4});var M4={};o$(M4,{time:()=>j3,duration:()=>Y3,datetime:()=>G3,date:()=>W3,ZodISOTime:()=>vv,ZodISODuration:()=>Uv,ZodISODateTime:()=>s0,ZodISODate:()=>$v});var s0=V("ZodISODateTime",($,v)=>{i2.init($,v),o.init($,v)});function G3($){return hK(s0,$)}var $v=V("ZodISODate",($,v)=>{n2.init($,v),o.init($,v)});function W3($){return cK($v,$)}var vv=V("ZodISOTime",($,v)=>{l2.init($,v),o.init($,v)});function j3($){return rK(vv,$)}var Uv=V("ZodISODuration",($,v)=>{o2.init($,v),o.init($,v)});function Y3($){return iK(Uv,$)}var JG=($,v)=>{p4.init($,v),$.name="ZodError",Object.defineProperties($,{format:{value:(K)=>e4($,K)},flatten:{value:(K)=>a4($,K)},addIssue:{value:(K)=>{$.issues.push(K),$.message=JSON.stringify($.issues,s1,2)}},addIssues:{value:(K)=>{$.issues.push(...K),$.message=JSON.stringify($.issues,s1,2)}},isEmpty:{get(){return $.issues.length===0}}})},GV=V("ZodError",JG),M$=V("ZodError",JG,{Parent:Error});var J3=U4(M$),X3=K4(M$),H3=_4(M$),P3=Q4(M$),V3=v0(M$),B3=U0(M$),D3=K0(M$),b3=_0(M$),k3=Q0(M$),N3=q0(M$),w3=G0(M$),M3=W0(M$);var m=V("ZodType",($,v)=>{return C.init($,v),Object.assign($["~standard"],{jsonSchema:{input:w4($,"input"),output:w4($,"output")}}),$.toJSONSchema=M8($,{}),$.def=v,$.type=v.type,Object.defineProperty($,"_def",{value:v}),$.check=(...K)=>{return $.clone(z.mergeDefs(v,{checks:[...v.checks??[],...K.map((_)=>typeof _==="function"?{_zod:{check:_,def:{check:"custom"},onattach:[]}}:_)]}),{parent:!0})},$.with=$.check,$.clone=(K,_)=>P$($,K,_),$.brand=()=>$,$.register=(K,_)=>{return K.add($,_),$},$.parse=(K,_)=>J3($,K,_,{callee:$.parse}),$.safeParse=(K,_)=>H3($,K,_),$.parseAsync=async(K,_)=>X3($,K,_,{callee:$.parseAsync}),$.safeParseAsync=async(K,_)=>P3($,K,_),$.spa=$.safeParseAsync,$.encode=(K,_)=>V3($,K,_),$.decode=(K,_)=>B3($,K,_),$.encodeAsync=async(K,_)=>D3($,K,_),$.decodeAsync=async(K,_)=>b3($,K,_),$.safeEncode=(K,_)=>k3($,K,_),$.safeDecode=(K,_)=>N3($,K,_),$.safeEncodeAsync=async(K,_)=>w3($,K,_),$.safeDecodeAsync=async(K,_)=>M3($,K,_),$.refine=(K,_)=>$.check(X_(K,_)),$.superRefine=(K)=>$.check(H_(K)),$.overwrite=(K)=>$.check(C$(K)),$.optional=()=>P6($),$.exactOptional=()=>d3($),$.nullable=()=>V6($),$.nullish=()=>P6(V6($)),$.nonoptional=(K)=>$_($,K),$.array=()=>k6($),$.or=(K)=>Zv([$,K]),$.and=(K)=>y3($,K),$.transform=(K)=>B6($,Lv(K)),$.default=(K)=>a3($,K),$.prefault=(K)=>s3($,K),$.catch=(K)=>K_($,K),$.pipe=(K)=>B6($,K),$.readonly=()=>q_($),$.describe=(K)=>{let _=$.clone();return W$.add(_,{description:K}),_},Object.defineProperty($,"description",{get(){return W$.get($)?.description},configurable:!0}),$.meta=(...K)=>{if(K.length===0)return W$.get($);let _=$.clone();return W$.add(_,K[0]),_},$.isOptional=()=>$.safeParse(void 0).success,$.isNullable=()=>$.safeParse(null).success,$.apply=(K)=>K($),$}),Qv=V("_ZodString",($,v)=>{g1.init($,v),m.init($,v),$._zod.processJSONSchema=(_,U,Q)=>I8($,_,U,Q);let K=$._zod.bag;$.format=K.format??null,$.minLength=K.minimum??null,$.maxLength=K.maximum??null,$.regex=(..._)=>$.check(W4(..._)),$.includes=(..._)=>$.check(J4(..._)),$.startsWith=(..._)=>$.check(X4(..._)),$.endsWith=(..._)=>$.check(H4(..._)),$.min=(..._)=>$.check(s$(..._)),$.max=(..._)=>$.check(C1(..._)),$.length=(..._)=>$.check(y1(..._)),$.nonempty=(..._)=>$.check(s$(1,..._)),$.lowercase=(_)=>$.check(j4(_)),$.uppercase=(_)=>$.check(Y4(_)),$.trim=()=>$.check(B4()),$.normalize=(..._)=>$.check(V4(..._)),$.toLowerCase=()=>$.check(D4()),$.toUpperCase=()=>$.check(b4()),$.slugify=()=>$.check(k4())}),Z4=V("ZodString",($,v)=>{g1.init($,v),Qv.init($,v),$.email=(K)=>$.check(I0(qv,K)),$.url=(K)=>$.check(J6(D6,K)),$.jwt=(K)=>$.check(c0(wv,K)),$.emoji=(K)=>$.check(F0(Gv,K)),$.guid=(K)=>$.check(Y6(H6,K)),$.uuid=(K)=>$.check(Z0(l$,K)),$.uuidv4=(K)=>$.check(z0(l$,K)),$.uuidv6=(K)=>$.check(L0(l$,K)),$.uuidv7=(K)=>$.check(A0(l$,K)),$.nanoid=(K)=>$.check(O0(Wv,K)),$.guid=(K)=>$.check(Y6(H6,K)),$.cuid=(K)=>$.check(x0(jv,K)),$.cuid2=(K)=>$.check(R0(Yv,K)),$.ulid=(K)=>$.check(S0(Jv,K)),$.base64=(K)=>$.check(f0(bv,K)),$.base64url=(K)=>$.check(m0(kv,K)),$.xid=(K)=>$.check(u0(Xv,K)),$.ksuid=(K)=>$.check(T0(Hv,K)),$.ipv4=(K)=>$.check(g0(Pv,K)),$.ipv6=(K)=>$.check(E0(Vv,K)),$.cidrv4=(K)=>$.check(C0(Bv,K)),$.cidrv6=(K)=>$.check(y0(Dv,K)),$.e164=(K)=>$.check(h0(Nv,K)),$.datetime=(K)=>$.check(G3(K)),$.date=(K)=>$.check(W3(K)),$.time=(K)=>$.check(j3(K)),$.duration=(K)=>$.check(Y3(K))});function Kv($){return CK(Z4,$)}var o=V("ZodStringFormat",($,v)=>{l.init($,v),Qv.init($,v)}),qv=V("ZodEmail",($,v)=>{g2.init($,v),o.init($,v)});function XG($){return I0(qv,$)}var H6=V("ZodGUID",($,v)=>{u2.init($,v),o.init($,v)});function HG($){return Y6(H6,$)}var l$=V("ZodUUID",($,v)=>{T2.init($,v),o.init($,v)});function PG($){return Z0(l$,$)}function VG($){return z0(l$,$)}function BG($){return L0(l$,$)}function DG($){return A0(l$,$)}var D6=V("ZodURL",($,v)=>{E2.init($,v),o.init($,v)});function bG($){return J6(D6,$)}function kG($){return J6(D6,{protocol:/^https?$/,hostname:x$.domain,...z.normalizeParams($)})}var Gv=V("ZodEmoji",($,v)=>{C2.init($,v),o.init($,v)});function NG($){return F0(Gv,$)}var Wv=V("ZodNanoID",($,v)=>{y2.init($,v),o.init($,v)});function wG($){return O0(Wv,$)}var jv=V("ZodCUID",($,v)=>{f2.init($,v),o.init($,v)});function MG($){return x0(jv,$)}var Yv=V("ZodCUID2",($,v)=>{m2.init($,v),o.init($,v)});function IG($){return R0(Yv,$)}var Jv=V("ZodULID",($,v)=>{h2.init($,v),o.init($,v)});function ZG($){return S0(Jv,$)}var Xv=V("ZodXID",($,v)=>{c2.init($,v),o.init($,v)});function zG($){return u0(Xv,$)}var Hv=V("ZodKSUID",($,v)=>{r2.init($,v),o.init($,v)});function LG($){return T0(Hv,$)}var Pv=V("ZodIPv4",($,v)=>{d2.init($,v),o.init($,v)});function AG($){return g0(Pv,$)}var I3=V("ZodMAC",($,v)=>{p2.init($,v),o.init($,v)});function FG($){return fK(I3,$)}var Vv=V("ZodIPv6",($,v)=>{t2.init($,v),o.init($,v)});function OG($){return E0(Vv,$)}var Bv=V("ZodCIDRv4",($,v)=>{a2.init($,v),o.init($,v)});function xG($){return C0(Bv,$)}var Dv=V("ZodCIDRv6",($,v)=>{e2.init($,v),o.init($,v)});function RG($){return y0(Dv,$)}var bv=V("ZodBase64",($,v)=>{$9.init($,v),o.init($,v)});function SG($){return f0(bv,$)}var kv=V("ZodBase64URL",($,v)=>{v9.init($,v),o.init($,v)});function uG($){return m0(kv,$)}var Nv=V("ZodE164",($,v)=>{U9.init($,v),o.init($,v)});function TG($){return h0(Nv,$)}var wv=V("ZodJWT",($,v)=>{K9.init($,v),o.init($,v)});function gG($){return c0(wv,$)}var z4=V("ZodCustomStringFormat",($,v)=>{_9.init($,v),o.init($,v)});function EG($,v,K={}){return N4(z4,$,v,K)}function CG($){return N4(z4,"hostname",x$.hostname,$)}function yG($){return N4(z4,"hex",x$.hex,$)}function fG($,v){let K=v?.enc??"hex",_=`${$}_${K}`,U=x$[_];if(!U)throw Error(`Unrecognized hash format: ${_}`);return N4(z4,_,U,v)}var L4=V("ZodNumber",($,v)=>{b0.init($,v),m.init($,v),$._zod.processJSONSchema=(_,U,Q)=>Z8($,_,U,Q),$.gt=(_,U)=>$.check(i$(_,U)),$.gte=(_,U)=>$.check(V$(_,U)),$.min=(_,U)=>$.check(V$(_,U)),$.lt=(_,U)=>$.check(r$(_,U)),$.lte=(_,U)=>$.check(z$(_,U)),$.max=(_,U)=>$.check(z$(_,U)),$.int=(_)=>$.check(_v(_)),$.safe=(_)=>$.check(_v(_)),$.positive=(_)=>$.check(i$(0,_)),$.nonnegative=(_)=>$.check(V$(0,_)),$.negative=(_)=>$.check(r$(0,_)),$.nonpositive=(_)=>$.check(z$(0,_)),$.multipleOf=(_,U)=>$.check(B1(_,U)),$.step=(_,U)=>$.check(B1(_,U)),$.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 Z3($){return nK(L4,$)}var m1=V("ZodNumberFormat",($,v)=>{Q9.init($,v),L4.init($,v)});function _v($){return oK(m1,$)}function mG($){return dK(m1,$)}function hG($){return tK(m1,$)}function cG($){return pK(m1,$)}function rG($){return aK(m1,$)}var A4=V("ZodBoolean",($,v)=>{U6.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>z8($,K,_,U)});function z3($){return eK(A4,$)}var F4=V("ZodBigInt",($,v)=>{k0.init($,v),m.init($,v),$._zod.processJSONSchema=(_,U,Q)=>L8($,_,U,Q),$.gte=(_,U)=>$.check(V$(_,U)),$.min=(_,U)=>$.check(V$(_,U)),$.gt=(_,U)=>$.check(i$(_,U)),$.gte=(_,U)=>$.check(V$(_,U)),$.min=(_,U)=>$.check(V$(_,U)),$.lt=(_,U)=>$.check(r$(_,U)),$.lte=(_,U)=>$.check(z$(_,U)),$.max=(_,U)=>$.check(z$(_,U)),$.positive=(_)=>$.check(i$(BigInt(0),_)),$.negative=(_)=>$.check(r$(BigInt(0),_)),$.nonpositive=(_)=>$.check(z$(BigInt(0),_)),$.nonnegative=(_)=>$.check(V$(BigInt(0),_)),$.multipleOf=(_,U)=>$.check(B1(_,U));let K=$._zod.bag;$.minValue=K.minimum??null,$.maxValue=K.maximum??null,$.format=K.format??null});function iG($){return $8(F4,$)}var Mv=V("ZodBigIntFormat",($,v)=>{q9.init($,v),F4.init($,v)});function nG($){return U8(Mv,$)}function lG($){return K8(Mv,$)}var L3=V("ZodSymbol",($,v)=>{G9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>A8($,K,_,U)});function oG($){return _8(L3,$)}var A3=V("ZodUndefined",($,v)=>{W9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>O8($,K,_,U)});function dG($){return Q8(A3,$)}var F3=V("ZodNull",($,v)=>{j9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>F8($,K,_,U)});function O3($){return q8(F3,$)}var x3=V("ZodAny",($,v)=>{Y9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>S8($,K,_,U)});function tG(){return G8(x3)}var R3=V("ZodUnknown",($,v)=>{J9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>u8($,K,_,U)});function f1(){return W8(R3)}var S3=V("ZodNever",($,v)=>{X9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>R8($,K,_,U)});function Iv($){return j8(S3,$)}var u3=V("ZodVoid",($,v)=>{H9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>x8($,K,_,U)});function pG($){return Y8(u3,$)}var b6=V("ZodDate",($,v)=>{P9.init($,v),m.init($,v),$._zod.processJSONSchema=(_,U,Q)=>T8($,_,U,Q),$.min=(_,U)=>$.check(V$(_,U)),$.max=(_,U)=>$.check(z$(_,U));let K=$._zod.bag;$.minDate=K.minimum?new Date(K.minimum):null,$.maxDate=K.maximum?new Date(K.maximum):null});function aG($){return J8(b6,$)}var T3=V("ZodArray",($,v)=>{V9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>l8($,K,_,U),$.element=v.element,$.min=(K,_)=>$.check(s$(K,_)),$.nonempty=(K)=>$.check(s$(1,K)),$.max=(K,_)=>$.check(C1(K,_)),$.length=(K,_)=>$.check(y1(K,_)),$.unwrap=()=>$.element});function k6($,v){return P8(T3,$,v)}function eG($){let v=$._zod.def.shape;return zv(Object.keys(v))}var N6=V("ZodObject",($,v)=>{B9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>o8($,K,_,U),z.defineLazy($,"shape",()=>{return v.shape}),$.keyof=()=>zv(Object.keys($._zod.def.shape)),$.catchall=(K)=>$.clone({...$._zod.def,catchall:K}),$.passthrough=()=>$.clone({...$._zod.def,catchall:f1()}),$.loose=()=>$.clone({...$._zod.def,catchall:f1()}),$.strict=()=>$.clone({...$._zod.def,catchall:Iv()}),$.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(Av,$,K[0]),$.required=(...K)=>z.required(Fv,$,K[0])});function sG($,v){let K={type:"object",shape:$??{},...z.normalizeParams(v)};return new N6(K)}function $5($,v){return new N6({type:"object",shape:$,catchall:Iv(),...z.normalizeParams(v)})}function v5($,v){return new N6({type:"object",shape:$,catchall:f1(),...z.normalizeParams(v)})}var w6=V("ZodUnion",($,v)=>{K6.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>t0($,K,_,U),$.options=v.options});function Zv($,v){return new w6({type:"union",options:$,...z.normalizeParams(v)})}var g3=V("ZodXor",($,v)=>{w6.init($,v),D9.init($,v),$._zod.processJSONSchema=(K,_,U)=>t0($,K,_,U),$.options=v.options});function U5($,v){return new g3({type:"union",options:$,inclusive:!1,...z.normalizeParams(v)})}var E3=V("ZodDiscriminatedUnion",($,v)=>{w6.init($,v),b9.init($,v)});function K5($,v,K){return new E3({type:"union",options:v,discriminator:$,...z.normalizeParams(K)})}var C3=V("ZodIntersection",($,v)=>{k9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>d8($,K,_,U)});function y3($,v){return new C3({type:"intersection",left:$,right:v})}var f3=V("ZodTuple",($,v)=>{N0.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>t8($,K,_,U),$.rest=(K)=>$.clone({...$._zod.def,rest:K})});function m3($,v,K){let _=v instanceof C,U=_?K:v;return new f3({type:"tuple",items:$,rest:_?v:null,...z.normalizeParams(U)})}var M6=V("ZodRecord",($,v)=>{N9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>p8($,K,_,U),$.keyType=v.keyType,$.valueType=v.valueType});function h3($,v,K){return new M6({type:"record",keyType:$,valueType:v,...z.normalizeParams(K)})}function _5($,v,K){let _=P$($);return _._zod.values=void 0,new M6({type:"record",keyType:_,valueType:v,...z.normalizeParams(K)})}function Q5($,v,K){return new M6({type:"record",keyType:$,valueType:v,mode:"loose",...z.normalizeParams(K)})}var c3=V("ZodMap",($,v)=>{w9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>i8($,K,_,U),$.keyType=v.keyType,$.valueType=v.valueType,$.min=(...K)=>$.check(n$(...K)),$.nonempty=(K)=>$.check(n$(1,K)),$.max=(...K)=>$.check(D1(...K)),$.size=(...K)=>$.check(E1(...K))});function q5($,v,K){return new c3({type:"map",keyType:$,valueType:v,...z.normalizeParams(K)})}var r3=V("ZodSet",($,v)=>{M9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>n8($,K,_,U),$.min=(...K)=>$.check(n$(...K)),$.nonempty=(K)=>$.check(n$(1,K)),$.max=(...K)=>$.check(D1(...K)),$.size=(...K)=>$.check(E1(...K))});function G5($,v){return new r3({type:"set",valueType:$,...z.normalizeParams(v)})}var I4=V("ZodEnum",($,v)=>{I9.init($,v),m.init($,v),$._zod.processJSONSchema=(_,U,Q)=>g8($,_,U,Q),$.enum=v.entries,$.options=Object.values(v.entries);let K=new Set(Object.keys(v.entries));$.extract=(_,U)=>{let Q={};for(let q of _)if(K.has(q))Q[q]=v.entries[q];else throw Error(`Key ${q} not found in enum`);return new I4({...v,checks:[],...z.normalizeParams(U),entries:Q})},$.exclude=(_,U)=>{let Q={...v.entries};for(let q of _)if(K.has(q))delete Q[q];else throw Error(`Key ${q} not found in enum`);return new I4({...v,checks:[],...z.normalizeParams(U),entries:Q})}});function zv($,v){let K=Array.isArray($)?Object.fromEntries($.map((_)=>[_,_])):$;return new I4({type:"enum",entries:K,...z.normalizeParams(v)})}function W5($,v){return new I4({type:"enum",entries:$,...z.normalizeParams(v)})}var i3=V("ZodLiteral",($,v)=>{Z9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>E8($,K,_,U),$.values=new Set(v.values),Object.defineProperty($,"value",{get(){if(v.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return v.values[0]}})});function j5($,v){return new i3({type:"literal",values:Array.isArray($)?$:[$],...z.normalizeParams(v)})}var n3=V("ZodFile",($,v)=>{z9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>f8($,K,_,U),$.min=(K,_)=>$.check(n$(K,_)),$.max=(K,_)=>$.check(D1(K,_)),$.mime=(K,_)=>$.check(P4(Array.isArray(K)?K:[K],_))});function Y5($){return V8(n3,$)}var l3=V("ZodTransform",($,v)=>{L9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>r8($,K,_,U),$._zod.parse=(K,_)=>{if(_.direction==="backward")throw new S1($.constructor.name);K.addIssue=(Q)=>{if(typeof Q==="string")K.issues.push(z.issue(Q,K.value,v));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=$),K.issues.push(z.issue(q))}};let U=v.transform(K.value,K);if(U instanceof Promise)return U.then((Q)=>{return K.value=Q,K});return K.value=U,K}});function Lv($){return new l3({type:"transform",transform:$})}var Av=V("ZodOptional",($,v)=>{w0.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>p0($,K,_,U),$.unwrap=()=>$._zod.def.innerType});function P6($){return new Av({type:"optional",innerType:$})}var o3=V("ZodExactOptional",($,v)=>{A9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>p0($,K,_,U),$.unwrap=()=>$._zod.def.innerType});function d3($){return new o3({type:"optional",innerType:$})}var t3=V("ZodNullable",($,v)=>{F9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>a8($,K,_,U),$.unwrap=()=>$._zod.def.innerType});function V6($){return new t3({type:"nullable",innerType:$})}function J5($){return P6(V6($))}var p3=V("ZodDefault",($,v)=>{O9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>s8($,K,_,U),$.unwrap=()=>$._zod.def.innerType,$.removeDefault=$.unwrap});function a3($,v){return new p3({type:"default",innerType:$,get defaultValue(){return typeof v==="function"?v():z.shallowClone(v)}})}var e3=V("ZodPrefault",($,v)=>{x9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>$3($,K,_,U),$.unwrap=()=>$._zod.def.innerType});function s3($,v){return new e3({type:"prefault",innerType:$,get defaultValue(){return typeof v==="function"?v():z.shallowClone(v)}})}var Fv=V("ZodNonOptional",($,v)=>{R9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>e8($,K,_,U),$.unwrap=()=>$._zod.def.innerType});function $_($,v){return new Fv({type:"nonoptional",innerType:$,...z.normalizeParams(v)})}var v_=V("ZodSuccess",($,v)=>{S9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>m8($,K,_,U),$.unwrap=()=>$._zod.def.innerType});function X5($){return new v_({type:"success",innerType:$})}var U_=V("ZodCatch",($,v)=>{u9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>v3($,K,_,U),$.unwrap=()=>$._zod.def.innerType,$.removeCatch=$.unwrap});function K_($,v){return new U_({type:"catch",innerType:$,catchValue:typeof v==="function"?v:()=>v})}var __=V("ZodNaN",($,v)=>{T9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>C8($,K,_,U)});function H5($){return H8(__,$)}var Ov=V("ZodPipe",($,v)=>{g9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>U3($,K,_,U),$.in=v.in,$.out=v.out});function B6($,v){return new Ov({type:"pipe",in:$,out:v})}var xv=V("ZodCodec",($,v)=>{Ov.init($,v),_6.init($,v)});function P5($,v,K){return new xv({type:"pipe",in:$,out:v,transform:K.decode,reverseTransform:K.encode})}var Q_=V("ZodReadonly",($,v)=>{E9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>K3($,K,_,U),$.unwrap=()=>$._zod.def.innerType});function q_($){return new Q_({type:"readonly",innerType:$})}var G_=V("ZodTemplateLiteral",($,v)=>{C9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>y8($,K,_,U)});function V5($,v){return new G_({type:"template_literal",parts:$,...z.normalizeParams(v)})}var W_=V("ZodLazy",($,v)=>{m9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>Q3($,K,_,U),$.unwrap=()=>$._zod.def.getter()});function j_($){return new W_({type:"lazy",getter:$})}var Y_=V("ZodPromise",($,v)=>{f9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>_3($,K,_,U),$.unwrap=()=>$._zod.def.innerType});function B5($){return new Y_({type:"promise",innerType:$})}var J_=V("ZodFunction",($,v)=>{y9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>c8($,K,_,U)});function D5($){return new J_({type:"function",input:Array.isArray($?.input)?m3($?.input):$?.input??k6(f1()),output:$?.output??f1()})}var I6=V("ZodCustom",($,v)=>{h9.init($,v),m.init($,v),$._zod.processJSONSchema=(K,_,U)=>h8($,K,_,U)});function b5($){let v=new t({check:"custom"});return v._zod.check=$,v}function k5($,v){return B8(I6,$??(()=>!0),v)}function X_($,v={}){return D8(I6,$,v)}function H_($){return b8($)}var N5=k8,w5=N8;function M5($,v={}){let K=new I6({type:"custom",check:"custom",fn:(_)=>_ instanceof $,abort:!0,...z.normalizeParams(v)});return K._zod.bag.Class=$,K._zod.check=(_)=>{if(!(_.value instanceof $))_.issues.push({code:"invalid_type",expected:$.name,input:_.value,inst:K,path:[...K._zod.def.path??[]]})},K}var I5=(...$)=>w8({Codec:xv,Boolean:A4,String:Z4},...$);function Z5($){let v=j_(()=>{return Zv([Kv($),Z3(),z3(),O3(),k6(v),h3(Kv(),v)])});return v}function z5($,v){return B6(Lv($),v)}var jV={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 YV($){K$({customError:$})}function JV(){return K$().customError}var P_;(function($){})(P_||(P_={}));var O={...X6,...e0,iso:M4},XV=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 HV($,v){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 v??"draft-2020-12"}function PV($,v){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 v.rootSchema;let _=v.version==="draft-2020-12"?"$defs":"definitions";if(K[0]===_){let U=K[1];if(!U||!v.defs[U])throw Error(`Reference not found: ${$}`);return v.defs[U]}throw Error(`Reference not found: ${$}`)}function L5($,v){if($.not!==void 0){if(typeof $.not==="object"&&Object.keys($.not).length===0)return O.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 U=$.$ref;if(v.refs.has(U))return v.refs.get(U);if(v.processing.has(U))return O.lazy(()=>{if(!v.refs.has(U))throw Error(`Circular reference not resolved: ${U}`);return v.refs.get(U)});v.processing.add(U);let Q=PV(U,v),q=J$(Q,v);return v.refs.set(U,q),v.processing.delete(U),q}if($.enum!==void 0){let U=$.enum;if(v.version==="openapi-3.0"&&$.nullable===!0&&U.length===1&&U[0]===null)return O.null();if(U.length===0)return O.never();if(U.length===1)return O.literal(U[0]);if(U.every((q)=>typeof q==="string"))return O.enum(U);let Q=U.map((q)=>O.literal(q));if(Q.length<2)return Q[0];return O.union([Q[0],Q[1],...Q.slice(2)])}if($.const!==void 0)return O.literal($.const);let K=$.type;if(Array.isArray(K)){let U=K.map((Q)=>{let q={...$,type:Q};return L5(q,v)});if(U.length===0)return O.never();if(U.length===1)return U[0];return O.union(U)}if(!K)return O.any();let _;switch(K){case"string":{let U=O.string();if($.format){let Q=$.format;if(Q==="email")U=U.check(O.email());else if(Q==="uri"||Q==="uri-reference")U=U.check(O.url());else if(Q==="uuid"||Q==="guid")U=U.check(O.uuid());else if(Q==="date-time")U=U.check(O.iso.datetime());else if(Q==="date")U=U.check(O.iso.date());else if(Q==="time")U=U.check(O.iso.time());else if(Q==="duration")U=U.check(O.iso.duration());else if(Q==="ipv4")U=U.check(O.ipv4());else if(Q==="ipv6")U=U.check(O.ipv6());else if(Q==="mac")U=U.check(O.mac());else if(Q==="cidr")U=U.check(O.cidrv4());else if(Q==="cidr-v6")U=U.check(O.cidrv6());else if(Q==="base64")U=U.check(O.base64());else if(Q==="base64url")U=U.check(O.base64url());else if(Q==="e164")U=U.check(O.e164());else if(Q==="jwt")U=U.check(O.jwt());else if(Q==="emoji")U=U.check(O.emoji());else if(Q==="nanoid")U=U.check(O.nanoid());else if(Q==="cuid")U=U.check(O.cuid());else if(Q==="cuid2")U=U.check(O.cuid2());else if(Q==="ulid")U=U.check(O.ulid());else if(Q==="xid")U=U.check(O.xid());else if(Q==="ksuid")U=U.check(O.ksuid())}if(typeof $.minLength==="number")U=U.min($.minLength);if(typeof $.maxLength==="number")U=U.max($.maxLength);if($.pattern)U=U.regex(new RegExp($.pattern));_=U;break}case"number":case"integer":{let U=K==="integer"?O.number().int():O.number();if(typeof $.minimum==="number")U=U.min($.minimum);if(typeof $.maximum==="number")U=U.max($.maximum);if(typeof $.exclusiveMinimum==="number")U=U.gt($.exclusiveMinimum);else if($.exclusiveMinimum===!0&&typeof $.minimum==="number")U=U.gt($.minimum);if(typeof $.exclusiveMaximum==="number")U=U.lt($.exclusiveMaximum);else if($.exclusiveMaximum===!0&&typeof $.maximum==="number")U=U.lt($.maximum);if(typeof $.multipleOf==="number")U=U.multipleOf($.multipleOf);_=U;break}case"boolean":{_=O.boolean();break}case"null":{_=O.null();break}case"object":{let U={},Q=$.properties||{},q=new Set($.required||[]);for(let[j,Y]of Object.entries(Q)){let X=J$(Y,v);U[j]=q.has(j)?X:X.optional()}if($.propertyNames){let j=J$($.propertyNames,v),Y=$.additionalProperties&&typeof $.additionalProperties==="object"?J$($.additionalProperties,v):O.any();if(Object.keys(U).length===0){_=O.record(j,Y);break}let X=O.object(U).passthrough(),P=O.looseRecord(j,Y);_=O.intersection(X,P);break}if($.patternProperties){let j=$.patternProperties,Y=Object.keys(j),X=[];for(let B of Y){let N=J$(j[B],v),S=O.string().regex(new RegExp(B));X.push(O.looseRecord(S,N))}let P=[];if(Object.keys(U).length>0)P.push(O.object(U).passthrough());if(P.push(...X),P.length===0)_=O.object({}).passthrough();else if(P.length===1)_=P[0];else{let B=O.intersection(P[0],P[1]);for(let N=2;N<P.length;N++)B=O.intersection(B,P[N]);_=B}break}let G=O.object(U);if($.additionalProperties===!1)_=G.strict();else if(typeof $.additionalProperties==="object")_=G.catchall(J$($.additionalProperties,v));else _=G.passthrough();break}case"array":{let{prefixItems:U,items:Q}=$;if(U&&Array.isArray(U)){let q=U.map((j)=>J$(j,v)),G=Q&&typeof Q==="object"&&!Array.isArray(Q)?J$(Q,v):void 0;if(G)_=O.tuple(q).rest(G);else _=O.tuple(q);if(typeof $.minItems==="number")_=_.check(O.minLength($.minItems));if(typeof $.maxItems==="number")_=_.check(O.maxLength($.maxItems))}else if(Array.isArray(Q)){let q=Q.map((j)=>J$(j,v)),G=$.additionalItems&&typeof $.additionalItems==="object"?J$($.additionalItems,v):void 0;if(G)_=O.tuple(q).rest(G);else _=O.tuple(q);if(typeof $.minItems==="number")_=_.check(O.minLength($.minItems));if(typeof $.maxItems==="number")_=_.check(O.maxLength($.maxItems))}else if(Q!==void 0){let q=J$(Q,v),G=O.array(q);if(typeof $.minItems==="number")G=G.min($.minItems);if(typeof $.maxItems==="number")G=G.max($.maxItems);_=G}else _=O.array(O.any());break}default:throw Error(`Unsupported type: ${K}`)}if($.description)_=_.describe($.description);if($.default!==void 0)_=_.default($.default);return _}function J$($,v){if(typeof $==="boolean")return $?O.any():O.never();let K=L5($,v),_=$.type||$.enum!==void 0||$.const!==void 0;if($.anyOf&&Array.isArray($.anyOf)){let G=$.anyOf.map((Y)=>J$(Y,v)),j=O.union(G);K=_?O.intersection(K,j):j}if($.oneOf&&Array.isArray($.oneOf)){let G=$.oneOf.map((Y)=>J$(Y,v)),j=O.xor(G);K=_?O.intersection(K,j):j}if($.allOf&&Array.isArray($.allOf))if($.allOf.length===0)K=_?K:O.any();else{let G=_?K:J$($.allOf[0],v),j=_?0:1;for(let Y=j;Y<$.allOf.length;Y++)G=O.intersection(G,J$($.allOf[Y],v));K=G}if($.nullable===!0&&v.version==="openapi-3.0")K=O.nullable(K);if($.readOnly===!0)K=O.readonly(K);let U={},Q=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let G of Q)if(G in $)U[G]=$[G];let q=["contentEncoding","contentMediaType","contentSchema"];for(let G of q)if(G in $)U[G]=$[G];for(let G of Object.keys($))if(!XV.has(G))U[G]=$[G];if(Object.keys(U).length>0)v.registry.add(K,U);return K}function A5($,v){if(typeof $==="boolean")return $?O.any():O.never();let K=HV($,v?.defaultTarget),_=$.$defs||$.definitions||{},U={version:K,defs:_,refs:new Map,processing:new Set,rootSchema:$,registry:v?.registry??W$};return J$($,U)}var V_={};o$(V_,{string:()=>VV,number:()=>BV,date:()=>kV,boolean:()=>DV,bigint:()=>bV});function VV($){return yK(Z4,$)}function BV($){return lK(L4,$)}function DV($){return sK(A4,$)}function bV($){return v8(F4,$)}function kV($){return X8(b6,$)}K$(Q6());var B_=W.enum(["pending","synced","failed"]),D_=W.object({}).default({}),b_=W.object({phoneNumberId:W.string().min(1),voiceEnabled:W.boolean().default(!0),chatEnabled:W.boolean().default(!0),sipUsername:W.string().optional(),sipPasswordEncrypted:W.string().optional(),sipPasswordIv:W.string().optional(),sessionTimeoutMinutes:W.number().int().min(5).max(10080).default(1440),wabaId:W.string().optional(),businessName:W.string().optional(),displayPhoneNumber:W.string().optional(),webhookSyncStatus:B_.default("pending"),webhookSyncError:W.string().optional(),webhookSyncedAt:W.iso.datetime().optional(),webhookCallbackUrl:W.string().optional(),lastWebhookReceivedAt:W.iso.datetime().optional(),lastWebhookMessageId:W.string().optional(),lastWebhookStatusId:W.string().optional(),lastWebhookPhoneNumberId:W.string().optional(),lastWebhookError:W.string().optional()}),k_=W.object({botToken:W.string().min(1),webhookSecret:W.string().min(1),allowGroups:W.boolean().default(!1),sessionTimeoutMinutes:W.number().int().min(5).max(10080).default(1440),botUsername:W.string().optional()}),F5={sip:D_,telegram:k_,whatsapp:b_,webchat:W.object({}).default({}),sms:W.object({}).default({}),rcs:W.object({}).default({})};var O4=["sip"],Z6=["telegram","webchat","sms","rcs"],x4=["whatsapp"],N_=[...O4,...Z6,...x4],O5=[...O4,...x4],NV=[...Z6,...x4];var zz=new Set(O4),Lz=new Set(x4);var x5=String.raw`(?:25[0-5]|2[0-4]\d|[01]?\d\d?)`,R5=String.raw`(?:${x5}\.){3}${x5}`,MV=String.raw`${R5}(?:\/(?:3[0-2]|[12]?\d))?`,uz=new RegExp(`^${R5}$`);var X$="[0-9a-fA-F]{1,4}",IV=[`(?:${X$}:){7}${X$}`,`(?:${X$}:){1,7}:`,`(?:${X$}:){1,6}:${X$}`,`(?:${X$}:){1,5}(?::${X$}){1,2}`,`(?:${X$}:){1,4}(?::${X$}){1,3}`,`(?:${X$}:){1,3}(?::${X$}){1,4}`,`(?:${X$}:){1,2}(?::${X$}){1,5}`,`${X$}:(?::${X$}){1,6}`,`:(?::${X$}){1,7}`,"::(?:ffff(?::0{1,4})?:)?"],ZV=`(?:${IV.join("|")})`,zV=String.raw`${ZV}(?:\/(?:12[0-8]|1[01]\d|[1-9]?\d))?`,Tz=new RegExp(`^(?:${MV}|${zV})$`);function LV($){let v=$;if(v==null||typeof v!=="object")throw Error("Execution plan must be a JSON object with { version, startNodeId, nodes, adjacency }");if(!("nodes"in v)||v.nodes==null||typeof v.nodes!=="object"){let K;if(!("nodes"in v))K="missing";else if(Array.isArray(v.nodes))K="an array";else K=typeof v.nodes;throw Error(`Execution plan "nodes" must be an object keyed by node ID, not ${K}`)}if(!("adjacency"in v)||v.adjacency==null||typeof v.adjacency!=="object")throw Error('Execution plan "adjacency" must be an object mapping source → { handle → target }')}function w_($){LV($);let v=Object.entries($.nodes).map(([_,U])=>({id:_,type:U.type,label:U.label,varName:U.varName,position:{x:0,y:0},config:U.config})),K=[];for(let[_,U]of Object.entries($.adjacency))for(let[Q,q]of Object.entries(U))K.push({id:`${_}-${Q}-${q}`,source:_,sourceHandle:Q,target:q,targetHandle:"in"});return{nodes:v,edges:K,viewport:{x:0,y:0,zoom:1}}}function E($){let v=$.producedVariables;return{meta:{...$.meta,inputs:$.meta.type==="start"?[]:[{key:"in",labelKey:"editor:handles.in"}],producedVariables:typeof v==="function"?(_)=>v(_):v,defaultConfig:$.configSchema.parse({})},configSchema:$.configSchema,producedVariables:$.producedVariables}}var AV=W.object({id:W.string(),type:W.string(),x:W.number(),y:W.number()}),FV=W.object({source:W.string(),target:W.string()}),OV=W.object({nodes:W.array(AV),edges:W.array(FV)});var S5=["voice","chat","both"];var z6=["channels","calls","registrations","codecs","modules","aliases"];var xV=new Set(["phone","telephone","telefone","fone","celular","cel","mobile","movel","numero","number","num","tel","msisdn","whatsapp","telefone celular","numero de telefone"]),RV=new Set(["name","nome","cliente","contato","contact","nome completo","razao social","full name"]);function SV($){return $.normalize("NFD").replaceAll(/[\u0300-\u036F]/g,"").toLowerCase().replaceAll(/[\s\-_]+/g," ").trim()}function uV($){return $.normalize("NFD").replaceAll(/[\u0300-\u036F]/g,"").toLowerCase().replaceAll(/[^a-z0-9]+/g,"_").replace(/^_/,"").replace(/_$/,"")}function u5($){return xV.has($)||$.includes("telefone")||$.includes("phone")||$.includes("celular")}function TV($){return RV.has($)}function M_($){let v={},K={},_=new Set,U=!1,Q=!1;function q(G){let j=G,Y=2;while(_.has(j))j=`${G}_${String(Y)}`,Y+=1;return _.add(j),j}for(let G of $){let j=SV(G);if(j===""){v[G]="ignore";continue}if(u5(j)&&!U){v[G]="phone",U=!0;continue}if(TV(j)&&!Q&&!u5(j)){v[G]="name",Q=!0;continue}let Y=uV(G);if(Y===""){v[G]="ignore";continue}v[G]="custom",K[G]=q(Y)}return{roles:v,customNames:K}}var h1={_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 flow 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"},setVariable:{name:"Set Variable",description:"Saves a value to reuse later — scoped to call, session, or cache"},sequence:{name:"Sequence",description:"Generates sequential numbers for protocols, tickets, or any identifier — DB-backed, never regresses"},httpRequest:{name:"HTTP Request",description:"Calls a REST API and stores the response for downstream nodes"},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"},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 flow 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 mid-flow with sampling and analysis options (legacy)"},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."}},start:{autoAnswer:"Auto-answer incoming call before processing. Disable for pre-answer routing.",channelType:"Plan channel type. Synced automatically from plan metadata."},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>'."},setVariable:{assignments:"List of variable assignments. At least one required."},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."},subPlan:{planId:"ID of a published visual plan to execute as a sub-flow. 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."},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 or pre-recorded file. 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)."},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 Rv={_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 fluxo"},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"},setVariable:{name:"Definir Variável",description:"Salva um valor para reusar depois — escopo de chamada, sessão ou cache"},sequence:{name:"Sequência",description:"Gera números sequenciais para protocolos, tickets ou qualquer identificador — durável em banco, nunca regride"},httpRequest:{name:"Requisição HTTP",description:"Chama uma API REST e armazena a resposta para os blocos seguintes"},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"},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 fluxo 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 no meio do fluxo com amostragem e análise (legado)"},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."}},start:{autoAnswer:"Atender chamada automaticamente antes de processar. Desabilite para roteamento pré-atendimento.",channelType:"Tipo de canal do plano. Sincronizado automaticamente do metadata 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>'."},setVariable:{assignments:"Lista de atribuições de variáveis. Pelo menos uma obrigatória."},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."},subPlan:{planId:"ID de um plano visual publicado para executar como sub-fluxo. 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."},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 ou arquivo pré-gravado. 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)."},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 gV={en:h1,"pt-BR":Rv};function I_($,v="en"){return gV[v]._nodes?.[$]}function c1($,v){return typeof $.outputs==="function"?$.outputs(v):$.outputs}var T5={integration:{order:0},basic:{order:1},routing:{order:2},data:{order:3},legacy:{order:99}},EV=Object.entries(T5).sort(([,$],[,v])=>$.order-v.order).map(([$])=>$);var Z_=W.object({reason:W.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:W.string().default("").describe("Optional number/template to add instead of the auto-resolved one. Supports {{variables}}. Empty = auto-resolve (dialer contact, then caller ID).")}),z_=E({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:5,outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:Z_,producedVariables:[{name:"dnc_added",type:"string",descriptionKey:"editor:vars.dncAdded"},{name:"dnc_phone",type:"string",descriptionKey:"editor:vars.dncPhone"}]});var L_=W.object({agent_id:W.string().default("").describe("SipPulse AI agent ID to invoke. Required for execution."),agent_name:W.string().default("").describe("Display name for the AI agent (used in logs and UI)."),additional_instructions:W.string().default("").describe("Extra instructions appended to the agent's system prompt."),variables:W.record(W.string(),W.unknown()).default({}).describe("Key-value pairs passed to the agent as context variables."),initial_message:W.string().default("").describe("First message the agent speaks when the conversation starts."),max_duration_minutes:W.number().min(1).max(60).default(10).describe("Maximum conversation duration in minutes (1-60). Call ends on timeout.")}),A_=E({meta:{type:"aiAgent",module:"ai",nameKey:"editor:nodes.aiAgent.name",descriptionKey:"editor:nodes.aiAgent.description",color:"iris",icon:"BotMessageSquare",category:"integration",order:2,nature:"composite",display:"full",channel:"both",outputs:[{key:"completed",labelKey:"editor:handles.completed"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:L_,producedVariables:[{name:"duration_ms",type:"number",descriptionKey:"editor:vars.aiAgent.durationMs"},{name:"turns",type:"number",descriptionKey:"editor:vars.aiAgent.turns"},{name:"output.*",type:"string",descriptionKey:"editor:vars.aiAgent.output"}]});var U$=W.union([W.object({tts:W.object({text:W.string().min(1,{error:"editor:validation.emptyTtsText"}).describe("Text to synthesize into speech."),voice:W.string().optional().describe("TTS voice ID (e.g., 'pt-BR-FranciscaNeural'). Resolved dynamically when absent."),model:W.string().optional().describe("TTS model ID (e.g., 'pulse-tts'). Resolved dynamically when absent.")}).describe("Text-to-speech audio source.")}),W.object({file:W.object({id:W.string().min(1,{error:"editor:validation.noAudioFile"}).describe("Audio file ID from the audio library."),name:W.string().describe("Display name of the audio file."),path:W.string().describe("Storage path of the audio file.")}).describe("Pre-recorded audio file source.")})]),CV=U$.optional().catch(void 0);var Sv=W.string().refine(($)=>$.trim()!=="",{error:"editor:validation.urlRequired"}).refine(($)=>!/\s/.test($.trim()),{error:"editor:validation.urlHasSpace"}).default("");var yV=W.object({value:W.string().min(1,{error:"editor:validation.caseValueRequired"}).default("").describe("Attribute value to match. Creates a 'match:<value>' output.")}),F_=W.object({audio:U$.optional().describe("Audio prompt played before collecting digits."),chatText:W.string().default("").describe("Text prompt for chat mode. Supports {{variables}}."),timeout:W.number().int().min(1).max(60).default(5).describe("Seconds to wait for digit input (1-60)."),maxAttempts:W.number().int().min(1).max(10).default(3).describe("Maximum retry attempts for digit collection (1-10)."),digitRegex:W.string().default("").describe("Regex to validate DTMF input. Empty means accept any."),method:W.enum(["GET","POST","PUT"]).default("GET").describe("HTTP method for the API request."),url:Sv.describe("API endpoint URL. Supports {{variables}} including collected digits as {{digits}}."),headers:W.record(W.string(),W.string()).optional().describe("HTTP headers as key-value pairs."),body:W.string().optional().describe("Request body (JSON). Supports {{variables}}. Only for POST/PUT."),requestTimeout:W.number().int().min(1000).max(60000).default(1e4).describe("HTTP request timeout in milliseconds."),attribute:W.string().default("").describe("JSON attribute name from the API response to match against cases."),cases:W.array(yV).default([]).describe("Possible attribute values. Each creates a dynamic output handle 'match:<value>'.")}),O_=E({meta:{type:"apiSwitch",module:"core",nameKey:"editor:nodes.apiSwitch.name",descriptionKey:"editor:nodes.apiSwitch.description",color:"teal",icon:"Globe",category:"data",nature:"composite",display:"full",channel:"both",order:99,legacy:!0,replacedBy:"httpRequest + switchCase",outputs:($)=>{return[...($.cases??[]).map((_)=>typeof _==="string"?_:_.value).filter((_)=>typeof _==="string"&&_!=="").map((_)=>({key:`match:${_}`,labelKey:_})),{key:"noInput",labelKey:"editor:handles.noInput"},{key:"error",labelKey:"editor:handles.error"}]}},configSchema:F_,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"}]});var fV=W.object({language:W.string().optional().describe("BCP 47 language code for speech recognition (e.g., 'pt-BR'). Omit for plan default."),initial_timeout_s:W.number().min(3).max(60).default(10).describe("Maximum seconds to wait for speech to begin (3-60)."),timeout_s:W.number().min(1).max(30).default(3).describe("Seconds of post-speech silence before stopping recording (1-30)."),max_duration_s:W.number().min(1).max(60).default(15).describe("Maximum recording duration in seconds (1-60)."),beep:W.boolean().default(!1).describe("Play a beep sound before starting to listen.")}),x_=W.object({maxAttempts:W.number().min(1).max(10).default(3).describe("Maximum retry attempts for invalid or empty input (1-10)."),audio:U$.optional().describe("Audio prompt played before collecting input in voice mode."),voiceMethod:W.enum(["dtmf","speech"]).default("dtmf").describe("Voice input method: 'dtmf' for digits, 'speech' for ASR transcription (requires AI)."),minDigits:W.number().min(1).max(20).default(1).describe("Minimum number of DTMF digits required (1-20)."),maxDigits:W.number().min(1).max(20).default(1).describe("Maximum number of DTMF digits to collect (1-20)."),terminators:W.string().default("#").describe("Key that terminates digit collection (e.g., '#')."),voiceTimeout:W.number().min(1).max(60).default(5).describe("Seconds to wait for input in voice mode (1-60)."),listen:fV.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:U$.optional().describe("Audio played while ASR processes the speech. Optional."),retryAudio:U$.optional().describe("Audio played on retry instead of main prompt. Falls back to main if not set."),text:W.string().default("").describe("Chat prompt message sent before waiting for user input. Supports {{variables}}."),validation:W.string().optional().describe("Regex pattern to validate chat text input. Invalid input triggers retry."),invalidMessage:W.string().optional().describe("Chat message sent when input fails validation. Supports {{variables}}.")}),R_=E({meta:{type:"capture",module:"core",nameKey:"editor:nodes.capture.name",descriptionKey:"editor:nodes.capture.description",color:"cyan",icon:"TextCursorInput",category:"basic",order:2,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:x_,producedVariables:[{name:"text",type:"string",descriptionKey:"editor:vars.capturedText"},{name:"attempts",type:"number",descriptionKey:"editor:vars.captureAttempts"}]});var S_=W.object({}),u_=E({meta:{type:"channelRouter",module:"core",nameKey:"editor:nodes.channelRouter.name",descriptionKey:"editor:nodes.channelRouter.description",color:"lime",icon:"Router",category:"routing",order:2,nature:"routing",display:"full",channel:"both",outputs:[{key:"voice",labelKey:"editor:handles.voice"},{key:"chat",labelKey:"editor:handles.chat"}]},configSchema:S_,producedVariables:[{name:"channelType",type:"string",descriptionKey:"editor:vars.channelType"}]});var T_=W.object({audio:U$.default({tts:{text:""}}).describe("Audio prompt played before collecting digits."),minDigits:W.number().min(1,{error:"editor:validation.minDigitsMin"}).max(20,{error:"editor:validation.minDigitsMax"}).default(1).describe("Minimum number of digits required (1-20)."),maxDigits:W.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:W.string().max(1).default("#").describe("Key that terminates digit collection (e.g., '#'). Single character."),timeout:W.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:W.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:W.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:U$.optional().describe("Audio played when input fails regex validation. Optional."),regex:W.string().default("").describe("Regex pattern to validate collected digits. Empty means accept any."),resetDigit:W.string().max(1).default("").describe("Key that clears collected digits and restarts. Single character. Empty to disable.")}),g_=E({meta:{type:"collectDigits",module:"core",nameKey:"editor:nodes.collectDigits.name",descriptionKey:"editor:nodes.collectDigits.description",color:"sky",icon:"Keyboard",category:"basic",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:T_,producedVariables:[{name:"digits",type:"string",descriptionKey:"editor:vars.collectedDigits"},{name:"attempts",type:"number",descriptionKey:"editor:vars.collectAttempts"}]});var E_=W.object({percentage:W.number().int().min(0).max(100).default(100).describe("Percentage of calls to record (0-100). 100 records all calls."),minDuration:W.number().int().min(0).default(0).describe("Minimum call duration in seconds before recording starts. 0 for immediate."),analyzeCalls:W.boolean().default(!1).describe("Enable post-call AI analysis (requires AI module).")}),C_=E({meta:{type:"enableRecord",module:"core",nameKey:"editor:nodes.enableRecord.name",descriptionKey:"editor:nodes.enableRecord.description",color:"red",icon:"CircleDot",category:"integration",nature:"sideEffect",display:"compact",channel:"both",order:99,legacy:!0,outputs:[{key:"next",labelKey:"editor:handles.next"},{key:"skipped",labelKey:"editor:handles.skipped"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:E_,producedVariables:[{name:"recording",type:"string",descriptionKey:"editor:vars.recordingStatus"}]});var y_=W.object({cause:W.string().optional().describe("SIP hangup cause code (e.g., 'NORMAL_CLEARING'). Omit for default.")}),f_=E({meta:{type:"hangup",module:"core",nameKey:"editor:nodes.hangup.name",descriptionKey:"editor:nodes.hangup.description",color:"red",icon:"PhoneOff",category:"integration",order:4,nature:"flow",display:"full",channel:"both",outputs:[]},configSchema:y_,producedVariables:[]});var m_=W.object({method:W.enum(["GET","POST","PUT","PATCH","DELETE"]).default("GET").describe("HTTP method for the request."),url:Sv.describe("Request URL. Supports template expressions, e.g., 'https://api.example.com/{{Start.callerid}}'."),headers:W.record(W.string(),W.string()).optional().describe("HTTP headers as key-value pairs. Values support template expressions."),body:W.string().optional().describe("Request body (JSON string). Template expressions allowed. Only for POST/PUT/PATCH."),timeout:W.number().optional().describe("Request timeout in milliseconds. Omit for default.")}),h_=E({meta:{type:"httpRequest",module:"core",nameKey:"editor:nodes.httpRequest.name",descriptionKey:"editor:nodes.httpRequest.description",color:"indigo",icon:"Globe",category:"data",order:1,nature:"sideEffect",display:"compact",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:m_,producedVariables:[{name:"status_code",type:"number",descriptionKey:"editor:vars.statusCode"},{name:"response",type:"object",descriptionKey:"editor:vars.response"}]});var c_=W.object({audio:U$.default({tts:{text:""}}).describe("Audio prompt played before collecting DTMF input."),timeout:W.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:W.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).")}),r_=E({meta:{type:"ivr",module:"core",nameKey:"editor:nodes.ivr.name",descriptionKey:"editor:nodes.ivr.description",color:"violet",icon:"Grid3x3",category:"basic",nature:"composite",display:"full",channel:"voice",order:99,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:c_,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 i_=W.object({id:W.string().min(1).default("").describe("Unique option identifier. Used as button ID in chat and output handle suffix."),label:W.string().min(1).default("").describe("Display label shown to the user. Button text in chat, spoken in voice prompt."),digit:W.string().default("").describe("DTMF digit for voice mode (0-9, *, #). Leave empty to skip voice for this option.")}),n_=W.object({options:W.array(i_).default([]).describe("Menu options. Each creates a dynamic output handle."),maxAttempts:W.number().min(1).max(10).default(3).describe("Maximum retry attempts for invalid input before following noMatch (1-10)."),audio:U$.optional().describe("Voice audio prompt played before collecting DTMF input. If omitted, caller hears nothing before digit collection."),voiceTimeout:W.number().min(1).max(60).default(5).describe("Seconds to wait for DTMF input in voice mode (1-60)."),text:W.string().default("").describe("Chat message text displayed above buttons. Supports template expressions."),invalidMessage:W.string().optional().describe("Chat message sent when input doesn't match any option. Supports template expressions.")}),l_=E({meta:{type:"menu",module:"core",nameKey:"editor:nodes.menu.name",descriptionKey:"editor:nodes.menu.description",color:"violet",icon:"ListOrdered",category:"basic",order:1,nature:"composite",display:"full",channel:"both",outputs:($)=>{return[...($.options??[]).map((_)=>typeof _==="object"&&_!=null?_:null).filter((_)=>_!=null&&typeof _.id==="string"&&_.id!=="").map((_)=>({key:`option:${_.id}`,labelKey:_.label})),{key:"noMatch",labelKey:"editor:handles.noMatch"},{key:"error",labelKey:"editor:handles.error"}]}},configSchema:n_,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 o_=W.object({audio:U$.default({tts:{text:""}}).describe("Audio to play. Use TTS (text-to-speech) or a pre-recorded audio file.")}),d_=E({meta:{type:"playback",module:"core",nameKey:"editor:nodes.playback.name",descriptionKey:"editor:nodes.playback.description",color:"blue",icon:"Volume2",category:"basic",nature:"action",display:"full",channel:"voice",order:99,deprecated:!0,replacedBy:"tell",outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:o_,producedVariables:[]});var mV=W.object({label:W.string().min(1).describe("Intent name. Creates a dynamic output handle 'intent:<label>'."),description:W.string().default("").describe("Description of what this intent means, used for LLM classification.")}),t_=W.object({input:W.string().default("").describe("Template expression to evaluate, e.g. '{{resposta}}'. The resolved text is classified by AI."),intents:W.array(mV).default([]).describe("List of intents the LLM should classify the input into. Each creates a dynamic output handle."),instructions:W.string().default("").describe("Additional instructions for the LLM intent classifier.")}),p_=E({meta:{type:"routeAi",module:"ai",nameKey:"editor:nodes.routeAi.name",descriptionKey:"editor:nodes.routeAi.description",color:"plum",icon:"BrainCircuit",category:"routing",order:3,nature:"routing",display:"full",channel:"both",outputs:($)=>{return[...($.intents??[]).map((_)=>_.label).filter((_)=>typeof _==="string"&&_!=="").map((_)=>({key:`intent:${_}`,labelKey:_})),{key:"notApplicable",labelKey:"editor:handles.notApplicable"},{key:"error",labelKey:"editor:handles.error"}]}},configSchema:t_,producedVariables:[{name:"intent",type:"string",descriptionKey:"editor:vars.routeAi.intent"},{name:"confidence",type:"number",descriptionKey:"editor:vars.routeAi.confidence"}]});var a_=W.object({digits:W.string().min(1,{error:"editor:validation.digitsRequired"}).default("").describe("DTMF digits to send (0-9, *, #). Supports template expressions.")}),e_=E({meta:{type:"sendDtmf",module:"core",nameKey:"editor:nodes.sendDtmf.name",descriptionKey:"editor:nodes.sendDtmf.description",color:"bronze",icon:"Hash",category:"data",order:3,nature:"sideEffect",display:"compact",channel:"voice",outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:a_,producedVariables:[{name:"dtmf",type:"string",descriptionKey:"editor:vars.dtmf"}]});var s_=W.object({prefix:W.string().max(16,{error:"editor:validation.prefixMaxLength"}).default("").describe("Short prefix prepended to the sequence (e.g. 'SAC', '200')."),dateFormat:W.enum(["none","yyyyMMdd","yyMMdd","yyyyMM","ddMMyyyy","yyyyMMddHHmmss"]).default("yyyyMMdd").describe("Date format inserted between prefix and counter."),padding:W.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:W.enum(["daily","monthly","never"]).default("daily").describe("When the counter resets to 1. Uses org timezone for boundary.")}),$7=E({meta:{type:"sequence",module:"core",nameKey:"editor:nodes.sequence.name",descriptionKey:"editor:nodes.sequence.description",color:"mint",icon:"Hash",category:"data",order:1,nature:"sideEffect",display:"compact",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:s_,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 hV=W.object({key:W.string().describe("Variable name. Used as '{{NodeLabel.key}}' in templates."),value:W.string().describe("Value to assign. Supports template expressions like '{{Start.callerid}}'."),scope:W.enum(["call","session","cache"]).describe("Variable scope: 'call' (current call), 'session' (persistent), 'cache' (Redis TTL).")}),v7=W.object({assignments:W.array(hV).min(1,{error:"editor:validation.noAssignments"}).default([]).describe("List of variable assignments. At least one required.")}),U7=E({meta:{type:"setVariable",module:"core",nameKey:"editor:nodes.setVariable.name",descriptionKey:"editor:nodes.setVariable.description",color:"teal",icon:"Variable",category:"data",order:0,nature:"sideEffect",display:"compact",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:v7,producedVariables:($)=>$.assignments.map((v)=>({name:v.key,type:"string",descriptionKey:"editor:vars.custom"}))});var K7=W.object({autoAnswer:W.boolean().optional().describe("Auto-answer incoming call before processing. Disable for pre-answer routing."),channelType:W.enum(S5).default("both").describe("Plan channel type. Synced automatically from plan metadata.")}),_7=E({meta:{type:"start",module:"core",nameKey:"editor:nodes.start.name",descriptionKey:"editor:nodes.start.description",color:"jade",icon:"Play",category:"integration",order:0,nature:"flow",display:"full",channel:"both",outputs:($)=>{let v=$.channelType;if((typeof v==="string"?v:"voice")==="both")return[{key:"voice",labelKey:"editor:handles.voice"},{key:"chat",labelKey:"editor:handles.chat"}];return[{key:"next",labelKey:"editor:handles.next"}]}},configSchema:K7,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"}]});var Q7=W.object({planId:W.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:W.record(W.string().regex(/^[A-Z_]\w*$/i).max(64),W.string().max(512)).default({}),endCallOnChildHangup:W.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.")}),q7=E({meta:{type:"subPlan",module:"core",nameKey:"editor:nodes.subPlan.name",descriptionKey:"editor:nodes.subPlan.description",color:"purple",icon:"Layers",category:"integration",order:3,nature:"flow",display:"full",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:Q7,producedVariables:()=>[{name:"*",type:"string",descriptionKey:"editor:vars.subPlanOutput"}]});var cV=W.object({pattern:W.string().min(1,{error:"editor:validation.casePatternRequired"}).default("").describe("Value to match against the expression. Creates a 'match:<pattern>' output.")}),G7=W.object({expression:W.string().min(1,{error:"editor:validation.expressionRequired"}).default("").describe("Template expression to evaluate, e.g., '{{IVR.digits}}'. Matched against case patterns."),cases:W.array(cV).default([]).describe("List of patterns to match. Each creates a dynamic output handle 'match:<pattern>'.")}),W7=E({meta:{type:"switchCase",module:"core",nameKey:"editor:nodes.switchCase.name",descriptionKey:"editor:nodes.switchCase.description",color:"orange",icon:"GitBranch",category:"routing",order:1,nature:"routing",display:"full",channel:"both",outputs:($)=>{return[...($.cases??[]).map((_)=>typeof _==="string"?_:_.pattern).filter((_)=>typeof _==="string"&&_!=="").map((_)=>({key:`match:${_}`,labelKey:_})),{key:"fallback",labelKey:"editor:handles.fallback"},{key:"error",labelKey:"editor:handles.error"}]}},configSchema:G7,producedVariables:[{name:"destination",type:"string",descriptionKey:"editor:vars.switchDestination"}]});var rV=W.object({type:W.literal("text"),text:W.string().min(1)}),iV=W.object({type:W.literal("media"),mediaType:W.enum(["image","audio","video","document"]),url:W.string().min(1),caption:W.string().optional()}),nV=W.object({type:W.literal("location"),lat:W.number(),lng:W.number()}),lV=W.object({type:W.literal("button_reply"),buttonId:W.string().min(1),buttonText:W.string()}),oV=W.object({type:W.literal("list_reply"),listId:W.string().min(1),listTitle:W.string()}),dV=W.object({type:W.literal("command"),command:W.string().min(1),args:W.string().optional()}),j7=W.discriminatedUnion("type",[rV,iV,nV,lV,oV,dV]),Y7=W.object({id:W.string().min(1),label:W.string().min(1)}),tV=W.object({id:W.string().min(1),title:W.string().min(1),description:W.string().optional()}),g5=W.object({title:W.string().min(1),items:W.array(tV).min(1)}),E5=W.object({title:W.string().min(1),description:W.string().optional(),imageUrl:W.string().optional(),buttons:W.array(Y7).default([])}),pV=W.object({type:W.literal("text"),text:W.string().min(1),markdown:W.boolean().optional()}),aV=W.object({type:W.literal("media"),mediaType:W.enum(["image","audio","video","document"]),url:W.string().min(1),caption:W.string().optional()}),eV=W.object({type:W.literal("location"),lat:W.number(),lng:W.number(),label:W.string().optional()}),sV=W.object({type:W.literal("buttons"),text:W.string().min(1),buttons:W.array(Y7).min(1)}),$B=W.object({type:W.literal("list"),text:W.string().min(1),buttonText:W.string().min(1),sections:W.array(g5).min(1)}),vB=W.object({type:W.literal("carousel"),cards:W.array(E5).min(1)}),UB=W.object({type:W.literal("template"),templateId:W.string().min(1),params:W.record(W.string(),W.string()).default({})}),R4=W.discriminatedUnion("type",[pV,aV,eV,sV,$B,vB,UB]),KB=R4.optional().catch(void 0);var J7=W.object({audio:U$.optional().describe("Audio to play via TTS or pre-recorded file. Used in voice plans."),content:R4.optional().describe("Message content to send in chat. Used in chat plans.")}),X7=E({meta:{type:"tell",module:"core",nameKey:"editor:nodes.tell.name",descriptionKey:"editor:nodes.tell.description",color:"blue",icon:"Volume2",category:"basic",order:0,nature:"action",display:"full",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:J7,producedVariables:[]});var H7=W.object({scheduleId:W.string().optional().describe("Schedule ID for time-based routing. Routes to onHours/offHours/holiday outputs.")}),P7=E({meta:{type:"timeRouting",module:"core",nameKey:"editor:nodes.timeRouting.name",descriptionKey:"editor:nodes.timeRouting.description",color:"gold",icon:"Clock",category:"routing",order:0,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:H7,producedVariables:[{name:"result",type:"string",descriptionKey:"editor:vars.timeResult"},{name:"holiday",type:"string",descriptionKey:"editor:vars.holiday"}]});var _B=W.object({key:W.string().describe("Attached-data field name shown to the agent / CRM (e.g. 'Nome')."),value:W.string().default("").describe("Field value. Supports template expressions like '{{cliente.nome}}'.")}),V7=W.object({method:W.enum(["bridge","transfer"]).default("bridge").describe("Transfer method. 'bridge' keeps call control; 'transfer' hands off completely."),destinations:W.array(W.string()).default([]).describe("SIP URIs or phone numbers to dial. At least one required. Tried in order."),timeout:W.number().min(5).max(120).optional().describe("Ring timeout in seconds per destination (5-120). Omit for carrier default."),attachedData:W.array(_B).default([]).describe("Key/value pairs delivered to the agent at transfer time (screen-pop). Values support templates.").superRefine(($,v)=>{let K=new Set;$.forEach((_,U)=>{let Q=_.key.trim();if(Q===""){v.addIssue({code:"custom",message:"editor:validation.attachedKeyRequired",path:[U,"key"]});return}if(K.has(Q))v.addIssue({code:"custom",message:"editor:validation.duplicateAttachedKey",path:[U,"key"]});K.add(Q)})})}),B7=E({meta:{type:"transfer",module:"core",nameKey:"editor:nodes.transfer.name",descriptionKey:"editor:nodes.transfer.description",color:"amber",icon:"PhoneForwarded",category:"integration",order:1,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:V7,producedVariables:[{name:"status",type:"string",descriptionKey:"editor:vars.transferStatus"}]});var QB=W.object({label:W.string().min(1).describe("Intent name. Creates a dynamic output handle 'intent:<label>'."),description:W.string().default("").describe("Description of what this intent means, used for LLM classification.")}),qB=W.object({language:W.string().optional().describe("BCP 47 language code for speech recognition (e.g., 'pt-BR'). Omit for plan default."),initial_timeout_s:W.number().min(3).max(60).default(10).describe("Maximum seconds to wait for speech to begin (3-60)."),timeout_s:W.number().min(1).max(30).default(3).describe("Seconds of post-speech silence before stopping recording (1-30)."),max_duration_s:W.number().min(1).max(60).default(15).describe("Maximum recording duration in seconds (1-60)."),beep:W.boolean().default(!1).describe("Play a beep sound before starting to listen.")}),GB=W.object({max_retries:W.number().min(0).max(5).default(2).describe("Maximum retries when speech is not recognized (0-5)."),prompt:U$.optional().describe("Audio played when retrying after unrecognized speech. Falls back to main prompt if not set.")});var D7=W.object({mode:W.enum(["intent","capture"]).default("intent").describe("'intent' classifies speech into configured intents; 'capture' transcribes speech without classification."),prompt:U$.default({tts:{text:""}}).describe("Audio prompt played before listening for speech."),intents:W.array(QB).default([]).describe("List of intents the LLM should classify speech into. Only used when mode is 'intent'."),classification_instructions:W.string().default("").describe("Additional instructions for the LLM intent classifier. Only used when mode is 'intent'."),listen:qB.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:U$.optional().describe("Audio played while the AI processes the speech. Optional."),retry:GB.default({max_retries:2}).describe("Retry behavior when speech is not recognized.")}),b7=E({meta:{type:"voiceRecognition",module:"ai",nameKey:"editor:nodes.voiceRecognition.name",descriptionKey:"editor:nodes.voiceRecognition.description",color:"cyan",icon:"Mic",category:"integration",nature:"composite",display:"full",channel:"voice",order:99,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((U)=>typeof U==="string"?U:U.label).filter((U)=>typeof U==="string"&&U!=="").map((U)=>({key:`intent:${U}`,labelKey:U})),{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:D7,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 y$={start:_7,playback:d_,ivr:r_,collectDigits:g_,transfer:B7,hangup:f_,timeRouting:P7,switchCase:W7,setVariable:U7,sequence:$7,httpRequest:h_,subPlan:q7,sendDtmf:e_,aiAgent:A_,voiceRecognition:b7,tell:X7,menu:l_,capture:R_,routeAi:p_,channelRouter:u_,addToDnc:z_,apiSwitch:O_,enableRecord:C_},w1=Object.fromEntries(Object.entries(y$).map(([$,v])=>[$,v.meta]));var iF=Number.MAX_SAFE_INTEGER;var C5=["active","expired","suspended","poc"],BB=W.object({enabled:W.boolean(),limits:W.record(W.string(),W.union([W.number(),W.string(),W.boolean(),W.array(W.string())])).default({})}),DB=W.object({voice:W.number().int().default(0),chat:W.number().int().default(0)}).optional(),bB=W.object({customer_id:W.string().min(1),customer_name:W.string().min(1).optional(),serial:W.string().min(1),status:W.enum(C5),issued_at:W.coerce.date(),expires_at:W.coerce.date().nullable().default(null),grace_period_days:W.number().int().min(0).default(0),max_concurrent_channels:DB,modules:W.record(W.string(),BB)});var uv=W.object({channel:W.union([W.literal(0),W.literal(1)]),text:W.string(),isFinal:W.boolean(),confidence:W.number(),start:W.number(),end:W.number(),timestamp:W.string(),nodeId:W.string().optional(),nodeLabel:W.string().optional(),nodeType:W.string().optional()}),kB=W.discriminatedUnion("type",[W.object({type:W.literal("segment"),segment:uv}),W.object({type:W.literal("started")}),W.object({type:W.literal("ended")}),W.object({type:W.literal("error"),message:W.string()})]),NB=W.discriminatedUnion("type",[W.object({type:W.literal("segment"),segment:uv}),W.object({type:W.literal("history"),segments:W.array(uv)}),W.object({type:W.literal("starting")}),W.object({type:W.literal("started")}),W.object({type:W.literal("ended")}),W.object({type:W.literal("error"),message:W.string()})]),wB=W.object({uuid:W.string(),action:W.enum(["start","stop"])});var y5={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:["originate"],dashboard:["read"],test_call:["execute"],tts:["read"],org_settings:["read","update"],user:["read","invite","update_role","suspend","remove"],api_key:["read","create","revoke"],acl:["read","create","update","delete"],audit:["read"],webhook:["read","create","update","delete"],ai:["read","execute","update_settings"],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"],role:["read","create","update","delete"],license:["read"],organization:["list","create","update","delete"],integration:["read","update"],tenant_module:["read","update"],platform_admin:["read","manage"],platform_storage:["manage"],system:["logs"]},f5={visual_plan:"organization",channel:"organization",destination:"organization",schedule:"organization",holiday:"organization",audio_file:"organization",call_record:"organization",call:"organization",dashboard:"organization",test_call:"organization",tts:"organization",org_settings:"organization",user:"organization",api_key:"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",role:"organization",license:"organization",organization:"platform",integration:"platform",tenant_module:"platform",platform_admin:"platform",platform_storage:"platform",system:"platform"},m5=Object.entries(y5).flatMap(([$,v])=>v.map((K)=>`${$}:${K}`));var h5={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","dashboard:read","call_record:read","call_record:export","tts:read","ai:read","ai:execute","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","license:read","user:read","role:read","webhook:read","api_key:read"],supervisor:["visual_plan:read","channel:read","destination:read","schedule:read","holiday:read","audio_file:read","dashboard:read","call_record:read","call_record:export","test_call:execute","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","acl:read","audit:read","archive:read","license:read"],operator:["visual_plan:read","channel:read","destination:read","schedule:read","holiday:read","audio_file:read","dashboard:read","call_record:read","test_call:execute","tts:read","contact:read","contact:update","dialer_campaign:read","dialer_dnc:read","user:read","license: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","acl:read","audit:read","ai:read","analysis_template:read","contact:read","dialer_campaign:read","dialer_dnc:read","archive:read","license:read"]},MB=Object.keys(h5);var UO=m5.filter(($)=>{return f5[$.split(":")[0]]==="organization"});var k7=W.object({version:W.literal(1),startNodeId:W.string().min(1),nodes:W.record(W.string(),W.object({type:W.string().min(1),label:W.string(),varName:W.string(),config:W.record(W.string(),W.unknown())})),adjacency:W.record(W.string(),W.record(W.string(),W.string()))});function w7($,v,K,_,U){let Q=v.channelType,q=typeof Q==="string"?Q:"voice";if(q!=="both")return IB($,K,_,q==="voice"?"voice-only":"chat-only");return zB($,K,_,U)}function IB($,v,K,_){let U=N7($,v),Q={};for(let q of K)Q[q]=U.has(q)?_:"unreachable";return Q[$]=_,Q}function ZB($,v){if($&&v)return"converged";if($)return"voice-only";if(v)return"chat-only";return"unreachable"}function zB($,v,K,_){let U=v.get($)?.get("voice"),Q=v.get($)?.get("chat"),q=U!=null?N7(U,v,_,"voice"):new Set,G=Q!=null?N7(Q,v,_,"chat"):new Set;if(U!=null)q.add(U);if(Q!=null)G.add(Q);let j={};for(let Y of K)j[Y]=Y===$?"converged":ZB(q.has(Y),G.has(Y));return j}function N7($,v,K,_){let U=new Set,Q=[$];U.add($);let q=0;while(q<Q.length){let G=Q[q++],j=v.get(G);if(j==null)continue;if(_!=null&&K?.has(G)){let Y=j.get(_);if(Y!=null&&!U.has(Y))U.add(Y),Q.push(Y);continue}for(let Y of j.values())if(!U.has(Y))U.add(Y),Q.push(Y)}return U}function d(){return($,v)=>({key:v,prefix:`${$}:`})}var LB={call:d()("call",($)=>`call:${$}`),testPlan:d()("test-plan",($)=>`test-plan:${$}`),testChatPlan:d()("test-chat-plan",($)=>`test-chat-plan:${$}`),testEditorState:d()("test-editor-state",($)=>`test-editor-state:${$}`),testExecutionTrace:d()("test-execution-trace",($)=>`test-execution-trace:${$}`),refreshToken:d()("rt",($)=>`rt:${$}`),revokedToken:d()("revoked",($)=>`revoked:${$}`),channels:d()("niva:channels",($)=>`niva:channels:${$}`),concurrentChannels:d()("niva:concurrent_channels",($,v)=>`niva:concurrent_channels:${$}:${v}`),peakConcurrentChannels:d()("niva:peak_concurrent",($,v)=>`niva:peak_concurrent:${$}:${v}`),dialerCampaignActive:d()("niva:dialer_campaign_active",($)=>`niva:dialer_campaign_active:${$}`),mcpSession:d()("mcp:session",($)=>`mcp:session:${$}`),rateLimit:d()("rl",($,v)=>`rl:${$}:${v}`),liveTranscriptionSegments:d()("live-ts",($)=>`live-ts:${$}`),transcriptionWatchers:d()("ts-watchers",($)=>`ts-watchers:${$}`),chatSession:d()("chat-session",($)=>`chat-session:${$}`),chatLookup:d()("chat-lookup",($,v,K)=>`chat-lookup:${$}:${v}:${K}`),chatLock:d()("chat-lock",($,v)=>`chat-lock:${$}:${v}`),chatInboundMessage:d()("chat-inbound-message",($,v,K,_)=>`chat-inbound-message:${$}:${v}:${K}:${_}`),wsSession:d()("ws:session",($)=>`ws:session:${$}`),wsMessageLog:d()("ws:log",($)=>`ws:log:${$}`),wsSeq:d()("ws:seq",($)=>`ws:seq:${$}`),healthStatus:d()("health-status",($)=>`health-status:${$}`),alertCooldown:d()("alert-cd",($,v)=>`alert-cd:${$}:${v}`),recordingDownloadAudit:d()("rec-dl-audit",($,v)=>`rec-dl-audit:${$}:${v}`),screenPop:d()("screenpop",($,v)=>`screenpop:${$}:${v}`),screenPopLegacy:d()("call_info",($)=>`call_info_${$}`),engineHeartbeat:d()("engine:heartbeat",()=>"engine:heartbeat")};var Tv="secrets",AB="secrets".replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);function c5(){return new RegExp(String.raw`\{\{\s*${AB}\.([A-Z][A-Z0-9_]*)\s*\}\}`,"g")}function r5($){if(!$.includes("{{"))return[];let v=new Set;for(let K of $.matchAll(c5()))v.add(K[1]);return[...v]}var i5={httpRequest:new Set(["url","headers","body"]),apiSwitch:new Set(["url","headers","body"])};function n5($,v){return i5[$]?.has(v)===!0}function M7($,v,K){if(typeof $==="string"){K(v,$);return}if(Array.isArray($)){$.forEach((_,U)=>M7(_,`${v}.${U}`,K));return}if($!=null&&typeof $==="object")for(let[_,U]of Object.entries($))M7(U,v===""?_:`${v}.${_}`,K)}function gv($){let v=new Set,K=[];return M7($.config,"",(_,U)=>{let Q=r5(U);if(Q.length===0)return;let q=_.split(".")[0]??"";if(n5($.type,q)){for(let G of Q)v.add(G);return}for(let G of Q)K.push({nodeId:$.id,label:$.label,field:_,name:G})}),{allowed:[...v],misplaced:K}}function Ev($){let v=new Set,K=[];for(let _ of $){let U=gv(_);for(let Q of U.allowed)v.add(Q);for(let Q of U.misplaced)v.add(Q.name),K.push(Q)}return{names:v,misplaced:K}}function I7($,v){return typeof $==="string"&&$!==""&&!v.has($)}function Z7($,v){return{nodeId:$.id,severity:"error",messageKey:v,params:{label:$.label}}}function OB($,v){if($.type!=="timeRouting"||v==null)return null;if(!I7($.config.scheduleId,v))return null;return Z7($,"editor:validation.danglingSchedule")}function xB($,v){if($.type!=="subPlan"||v==null)return null;if(!I7($.config.planId,v))return null;return Z7($,"editor:validation.danglingPlan")}function RB($,v){if(v==null)return null;let K=$.config.audio;if(K==null||typeof K!=="object"||!("file"in K))return null;let _=K.file;if(!I7(_.id,v))return null;return Z7($,"editor:validation.danglingAudioFile")}function SB($,v){if(v==null)return[];return gv($).allowed.filter((K)=>!v.has(K)).map((K)=>({nodeId:$.id,severity:"error",messageKey:"editor:validation.danglingSecret",params:{label:$.label,secret:K}}))}function z7($,v){let K=[];for(let _ of $){let U=OB(_,v.schedules);if(U!=null)K.push(U);let Q=xB(_,v.publishedPlans);if(Q!=null)K.push(Q);let q=RB(_,v.audioFiles);if(q!=null)K.push(q);K.push(...SB(_,v.secrets))}return K}function L7($,v){let K=[];for(let _ of $){if(_.type!=="aiAgent"||v.aiAgents==null)continue;let U=_.config.agent_id;if(typeof U==="string"&&U!==""&&!v.aiAgents.has(U))K.push({nodeId:_.id,severity:"warning",messageKey:"editor:validation.danglingAiAgent",params:{label:_.label}})}return K}var f$={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"],errors:["has_error","error_count","last_error_code"],origin:["origin_type","origin_name"],variables:["variables"]},A7=[...f$.basic,...f$.details,...f$.media,...f$.errors,...f$.origin,...f$.variables],l5=["sip_call_id","remote_addr","user_agent"],uB=new Set(l5),TB=A7.filter(($)=>!uB.has($)),gB=[...f$.basic];var EB={basic:[...f$.basic],full:[...A7],ai_audit:[...f$.basic,"transcription_status","transcription","analysis","sentiment_label",...f$.errors,"variables"]};var F7=["call.started","call.answered","call.hangup","call.rejected","call.node_entered","call.node_error","call.transcribed","call.transferred","call.recording_available","call.intent_matched","plan.published","message.sent","dialer.attempt.finished","alert.fired","alert.resolved","service.down","service.up"];var o5=[1,5,30,120,300,600],CB=o5.length,d5=W.enum(["inbound","outbound"]),q$=W.iso.datetime(),t5=W.strictObject({call_id:W.string().min(1),caller_id:W.string(),callee_id:W.string(),direction:d5,visual_plan_id:W.string().min(1),visual_plan_name:W.string(),started_at:q$}),p5=W.strictObject({call_id:W.string().min(1),caller_id:W.string(),callee_id:W.string(),answered_at:q$}),a5=W.strictObject({call_id:W.string().min(1),caller_id:W.string(),callee_id:W.string(),direction:d5,visual_plan_id:W.string().min(1),visual_plan_name:W.string(),started_at:q$,answered_at:q$.nullable(),ended_at:q$,duration_ms:W.number().nonnegative(),hangup_cause:W.string(),hangup_disposition:W.string(),was_recorded:W.boolean(),variables:W.record(W.string(),W.string()),sip_code:W.string().nullable(),billsec:W.number().nonnegative().nullable(),amd_verdict:W.enum(["machine","human"]).nullable()}),e5=["not_found","channel_inactive","channel_deleted","plan_deleted","no_published_version","org_deleted","acl_denied","capacity_global","capacity_org"],s5=W.enum(e5),$W=W.strictObject({caller:W.string(),destination:W.string(),reason:s5,hangup_cause:W.string()}),vW=W.strictObject({call_id:W.string().min(1),caller_id:W.string(),callee_id:W.string(),node_id:W.string().min(1),node_type:W.string(),node_label:W.string(),handle_used:W.string(),digit:W.string().nullable(),entered_at:q$,exited_at:q$,duration_ms:W.number().nonnegative(),visual_plan_id:W.string().min(1)}),UW=W.strictObject({call_id:W.string().min(1),caller_id:W.string(),callee_id:W.string(),node_id:W.string().min(1),node_type:W.string(),node_label:W.string(),error_code:W.string(),error_message:W.string(),visual_plan_id:W.string().min(1),visual_plan_name:W.string(),occurred_at:q$}),KW=W.strictObject({call_record_id:W.string().min(1),transcription_id:W.string().min(1),full_text:W.string(),is_anonymized:W.boolean()}),_W=["answered","busy","noAnswer","failed"],QW=W.enum(_W),qW=W.strictObject({call_id:W.string().min(1),caller_id:W.string(),callee_id:W.string(),to_destination:W.string(),method:W.enum(["bridge","sip_message","blind"]),disposition:QW,status:W.string(),duration_ms:W.number().nonnegative().nullable(),transferred_at:q$}),GW=W.strictObject({call_id:W.string().min(1),call_record_id:W.string().min(1),recording_url:W.string(),storage_path:W.string(),duration_seconds:W.number().nonnegative().nullable(),format:W.string(),size_bytes:W.number().nonnegative().nullable(),available_at:q$}),yB=W.strictObject({intent:W.string(),confidence:W.number()}),WW=W.strictObject({call_id:W.string().min(1),caller_id:W.string(),callee_id:W.string(),node_id:W.string().min(1),visual_plan_id:W.string().min(1),transcript:W.string(),intent:W.string(),confidence:W.number(),alternatives:W.array(yB),language:W.string().nullable(),matched_at:q$}),jW=W.strictObject({plan_id:W.string().min(1),plan_name:W.string(),version_id:W.string().min(1),version_number:W.number().int().nonnegative(),published_by_user_id:W.string().min(1),notes:W.string().nullable(),published_at:q$}),YW=["text","media","audio","image","video","document","location","interactive"],JW=W.strictObject({session_id:W.string().min(1),channel_type:W.string(),to:W.string(),message_type:W.enum(YW),text:W.string().nullable(),media_url:W.string().nullable(),node_id:W.string().nullable(),sent_at:q$}),XW=["answered","machine","busy","no_answer","failed","originate_error","cancelled"],HW=W.enum(XW),PW=W.strictObject({campaign_id:W.string().min(1),campaign_name:W.string(),contact_id:W.string().min(1),phone_number:W.string(),attempt_number:W.number().int().nonnegative(),status:HW,hangup_cause:W.string().nullable(),sip_code:W.string().nullable(),call_uuid:W.string().nullable(),started_at:q$.nullable(),answered_at:q$.nullable(),ended_at:q$.nullable(),duration_s:W.number().nonnegative().nullable(),custom_fields:W.record(W.string(),W.string())}),VW=W.strictObject({alert_type:W.string(),severity:W.enum(["critical","warning","info"]),title:W.string(),body:W.string(),metric_value:W.number().optional(),threshold:W.number().optional()}),BW=W.strictObject({alert_type:W.string(),title:W.string(),body:W.string()}),DW=W.strictObject({component:W.string(),checked_at:q$}),bW=W.strictObject({component:W.string(),downtime_seconds:W.number().nonnegative().nullable(),recovered_at:q$}),O7={"call.started":t5,"call.answered":p5,"call.hangup":a5,"call.rejected":$W,"call.node_entered":vW,"call.node_error":UW,"call.transcribed":KW,"call.transferred":qW,"call.recording_available":GW,"call.intent_matched":WW,"plan.published":jW,"message.sent":JW,"dialer.attempt.finished":PW,"alert.fired":VW,"alert.resolved":BW,"service.down":DW,"service.up":bW};function j$($){return W.strictObject({event:W.literal($),event_id:W.string().min(1),org_id:W.string().min(1),timestamp:q$,data:O7[$]})}var fB=W.discriminatedUnion("event",[j$("call.started"),j$("call.answered"),j$("call.hangup"),j$("call.rejected"),j$("call.node_entered"),j$("call.node_error"),j$("call.transcribed"),j$("call.transferred"),j$("call.recording_available"),j$("call.intent_matched"),j$("plan.published"),j$("message.sent"),j$("dialer.attempt.finished"),j$("alert.fired"),j$("alert.resolved"),j$("service.down"),j$("service.up")]),v$="01kknxab29enebk2vhm0tz0yyd",kW={"call.started":{call_id:`call_${v$}`,caller_id:"+15551230001",callee_id:"+15551230002",direction:"inbound",visual_plan_id:`vp_${v$}`,visual_plan_name:"Support IVR",started_at:"2026-01-15T12:00:00.000Z"},"call.answered":{call_id:`call_${v$}`,caller_id:"+15551230001",callee_id:"+15551230002",answered_at:"2026-01-15T12:00:03.000Z"},"call.hangup":{call_id:`call_${v$}`,caller_id:"+15551230001",callee_id:"+15551230002",direction:"inbound",visual_plan_id:`vp_${v$}`,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,amd_verdict:null},"call.rejected":{caller:"+15551230001",destination:"+15551230002",reason:"channel_inactive",hangup_cause:"UNALLOCATED_NUMBER"},"call.node_entered":{call_id:`call_${v$}`,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_${v$}`},"call.node_error":{call_id:`call_${v$}`,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_${v$}`,visual_plan_name:"Support IVR",occurred_at:"2026-01-15T12:00:10.000Z"},"call.transcribed":{call_record_id:`call_${v$}`,transcription_id:`ctr_${v$}`,full_text:"Hello, I need help with my account.",is_anonymized:!0},"call.transferred":{call_id:`call_${v$}`,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"},"call.recording_available":{call_id:`call_${v$}`,call_record_id:`call_${v$}`,recording_url:`https://example.invalid/recordings/call_${v$}.wav`,storage_path:`recordings/example/call_${v$}.wav`,duration_seconds:57,format:"wav",size_bytes:912000,available_at:"2026-01-15T12:01:01.000Z"},"call.intent_matched":{call_id:`call_${v$}`,caller_id:"+15551230001",callee_id:"+15551230002",node_id:"node_intent",visual_plan_id:`vp_${v$}`,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"},"plan.published":{plan_id:`vp_${v$}`,plan_name:"Support IVR",version_id:`vpv_${v$}`,version_number:3,published_by_user_id:`usr_${v$}`,notes:"Updated support routing",published_at:"2026-01-15T11:00:00.000Z"},"message.sent":{session_id:`call_${v$}`,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_${v$}`,campaign_name:"January outreach",contact_id:`dct_${v$}`,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 L6($){let v=y$[$],K=w1[$],_=K.defaultConfig,U=c1(K,_),Q=typeof K.producedVariables==="function"?K.producedVariables(_):K.producedVariables,q=I_($,"en");return{type:$,name:q?.name??$,description:q?.description??"",nameKey:K.nameKey,descriptionKey:K.descriptionKey,module:K.module,category:K.category,channel:K.channel,nature:K.nature,configJsonSchema:W.toJSONSchema(v.configSchema,{unrepresentable:"any"}),outputs:U,producedVariables:Q,defaultConfig:_}}var hB=Object.keys(y$);function x7(){return hB.map(L6)}var cB=["string","number","boolean","object","array"],NW=W.strictObject({name:W.string(),type:W.enum(cB),required:W.boolean(),nullable:W.boolean()}),wW=W.strictObject({event:W.enum(F7),requiredModule:W.enum(["core","ai","queues","dialer","omnichannel","enterprise"]).nullable(),fields:W.array(NW),example:W.record(W.string(),W.unknown())}),rB=W.array(wW);var MW="edge";var iB=W.object({text:W.string().min(1).max(5000),voice:W.string().min(1),model:W.string().default(MW)});var nB=/\{\{(.+?)\}\}/g;function R7(){return/"?\{\{.+?\}\}"?/g}var IW=200;function ZW($,v){let K=$[v];if(K==="*"||K==="+")return 1;if(K==="{"){let _=$.indexOf("}",v);if(_!==-1&&/^\d+,$/.test($.slice(v+1,_)))return _-v+1}return 0}function lB($,v){let K=v+1;while(K<$.length&&$[K]!=="]")K+=$[K]==="\\"?2:1;return K+1}function oB($,v,K){let _=K.pop()??{repeat:!1},U=ZW($,v+1);if(U>0&&_.repeat)return{catastrophic:!0,next:v};if((_.repeat||U>0)&&K.length>0)K.at(-1).repeat=!0;return{catastrophic:!1,next:v+(U>0?1+U:1)}}function dB($,v,K){let _=$[v];if(_==="\\")return{catastrophic:!1,next:v+2};if(_==="[")return{catastrophic:!1,next:lB($,v)};if(_==="(")return K.push({repeat:!1}),{catastrophic:!1,next:v+1};if(_===")")return oB($,v,K);let U=ZW($,v);if(U>0&&K.length>0)K.at(-1).repeat=!0;return{catastrophic:!1,next:v+(U>0?U:1)}}function zW($){let v=[],K=0;while(K<$.length){let{catastrophic:_,next:U}=dB($,K,v);if(_)return!0;K=U}return!1}function tB($){let v=$.split("/");if(v.length<3)return null;return{key:v[0].trim(),pattern:v.slice(1,-1).join("/"),replacement:v.at(-1)}}function S7($){if(!$.includes("{{"))return{valid:!0};for(let v of $.matchAll(nB)){let K=tB(v[1].trim());if(K===null)continue;if(K.pattern.length>IW)return{valid:!1,error:`Regex pattern too long in "${v[0]}" (max ${IW})`};if(zW(K.pattern))return{valid:!1,error:`Unsafe regex (possible catastrophic backtracking) in "${v[0]}"`};try{new RegExp(K.pattern)}catch(_){let U=_ instanceof Error?_.message:String(_);return{valid:!1,error:`Invalid regex in "${v[0]}": ${U}`}}}return{valid:!0}}var u7=W.record(W.string(),W.string());var Cv=W.object({id:W.string(),sequence:W.number().int().nonnegative(),nodeId:W.string(),nodeType:W.string(),nodeLabel:W.string(),status:W.enum(["running","completed","error"]),enteredAt:W.string(),exitedAt:W.string().nullable(),durationMs:W.number().int().nonnegative().nullable(),handleUsed:W.string().nullable(),digit:W.string().nullable(),variablesBefore:u7,variablesAfter:u7.nullable(),resolvedConfig:W.record(W.string(),W.unknown()),resultData:W.record(W.string(),W.unknown()).nullable()}).superRefine(($,v)=>{let K=[$.exitedAt,$.durationMs,$.handleUsed,$.variablesAfter];if($.status==="running"?K.some((U)=>U!==null):K.includes(null))v.addIssue({code:"custom",path:["status"],message:"Running steps must have empty exit fields; terminal steps must have complete exit fields"})}),aB=W.object({orgId:W.string(),status:W.enum(["active","waiting_input","ended"]),currentNodeId:W.string(),variables:u7,steps:W.array(Cv),truncated:W.boolean()});function r1($){return{audio:{tts:{text:$}}}}function sB($){return{type:"text",text:$}}function b($){return{...r1($),content:sB($)}}function r($,v,K={},_){return{options:v,maxAttempts:3,audio:r1($).audio,text:_??$,...K}}function Q$($,v={}){return{audio:r1($).audio,text:$,...v}}function c($,v,K,_){return[J(`${$}a`,v,"answered",K),J(`${$}b`,v,"busy",_),J(`${$}n`,v,"noAnswer",_),J(`${$}e`,v,"error",_)]}var $D={x:0,y:0};function H($,v,K,_,U){return{id:$,type:v,label:K,varName:_,position:$D,config:U}}function J($,v,K,_){return{id:$,source:v,sourceHandle:K,target:_,targetHandle:"in"}}var vD={id:"atendente-virtual-ia",category:"ai",requiredModules:["ai"],channelType:"both",tags:["ia","agente","ai","virtual","conversacional"],editorState:{nodes:[H("s1","start","Início","inicio",{channelType:"both"}),H("t1","tell","Boas-vindas","boas_vindas",b("Olá! Sou o assistente virtual. Posso ajudar com diversas questões.")),H("ai1","aiAgent","Agente IA","agente_ia",{agent_id:"",agent_name:"",additional_instructions:"",variables:{},initial_message:"Olá, como posso ajudar?",max_duration_minutes:10}),H("m1","menu","Satisfação","satisfacao",r("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:")),H("t2","tell","Agradecimento","agradecimento",b("Obrigado pelo contato. Tenha um bom dia!")),H("t3","tell","Transferindo","transferindo",b("Vou transferir para um atendente humano.")),H("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["1000"],timeout:45}),H("t4","tell","Erro IA","erro_ia",b("Houve um problema com o assistente. Vou transferir para um atendente.")),H("t5","tell","Transferência Falhou","transferencia_falhou",b("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),H("h1","hangup","Desligamento","desligamento",{})],edges:[J("e1v","s1","voice","t1"),J("e1c","s1","chat","t1"),J("e2","t1","next","ai1"),J("e3","ai1","completed","m1"),J("e4","ai1","error","t4"),J("e5","m1","option:satisfeito","t2"),J("e6","m1","option:atendente","t3"),J("e7","m1","noMatch","t3"),J("e8","m1","error","t3"),J("e9","t2","next","h1"),J("e10","t3","next","x1"),J("e11","t4","next","x1"),...c("ex1","x1","h1","t5"),J("e12","t5","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var UD={id:"atendimento-agente-ia",category:"ai",requiredModules:["ai"],channelType:"both",tags:["ia","ai","agente","atendimento","intencao","classificacao","transferencia"],editorState:{nodes:[H("s1","start","Início","inicio",{channelType:"both"}),H("t1","tell","Boas-vindas","boas_vindas",b("Olá! Você ligou para a nossa central. Em poucas palavras, me diga como posso ajudar.")),H("c1","capture","Captura","captura",Q$("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:r1("Um momento enquanto analiso o seu pedido.").audio})),H("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."}),H("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}),H("sw1","switchCase","Decidir","decidir",{expression:"{{agente.output.resultado}}",cases:[{pattern:"^resolvido$"}]}),H("t2","tell","Despedida","despedida",b("Obrigado pelo contato. Tenha um ótimo dia!")),H("t3","tell","Não Entendi","nao_entendeu",b("Não consegui entender o motivo do contato. Vou transferir para um atendente.")),H("t4","tell","Erro Técnico","erro_tecnico",b("Tivemos um problema no atendimento automático. Vou transferir para um atendente.")),H("x1","transfer","Transferência Humana","transfer_humano",{method:"bridge",destinations:["1000"]}),H("t5","tell","Transferência Falhou","transfer_falhou",b("Não conseguimos completar a transferência. Por favor, ligue novamente mais tarde.")),H("h1","hangup","Desligamento","desligamento",{})],edges:[J("e1v","s1","voice","t1"),J("e1c","s1","chat","t1"),J("e2","t1","next","c1"),J("e3","c1","collected","ra1"),J("e4","c1","noInput","t3"),J("e5","c1","error","t4"),J("e6","ra1","intent:suporte","ai1"),J("e7","ra1","intent:financeiro","x1"),J("e8","ra1","notApplicable","t3"),J("e9","ra1","error","t4"),J("e10","ai1","completed","sw1"),J("e11","ai1","error","t4"),J("e12","sw1","match:^resolvido$","t2"),J("e13","sw1","fallback","x1"),J("e14","sw1","error","t4"),J("e15","t3","next","x1"),J("e16","t4","next","x1"),J("e17","t2","next","h1"),J("e18","x1","answered","t2"),J("e19","x1","busy","t5"),J("e20","x1","noAnswer","t5"),J("e21","x1","error","t5"),J("e22","t5","next","h1")],viewport:{x:0,y:0,zoom:0.75}}};var KD={id:"atendimento-setores",category:"core",requiredModules:[],channelType:"both",tags:["menu","transfer","setores","departamentos","ura"],editorState:{nodes:[H("s1","start","Início","inicio",{channelType:"both"}),H("t1","tell","Boas-vindas","boas_vindas",b("Bem-vindo. Escolha entre financeiro, suporte, vendas ou ouvidoria.")),H("m1","menu","Menu Principal","menu_principal",r("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:")),H("t2","tell","Transferindo Financeiro","transferindo_financeiro",b("Aguarde, transferindo para o financeiro.")),H("t3","tell","Transferindo Suporte","transferindo_suporte",b("Aguarde, transferindo para o suporte técnico.")),H("t4","tell","Transferindo Vendas","transferindo_vendas",b("Aguarde, transferindo para vendas.")),H("t5","tell","Transferindo Ouvidoria","transferindo_ouvidoria",b("Aguarde, transferindo para a ouvidoria.")),H("x1","transfer","Financeiro","financeiro",{method:"bridge",destinations:["1001"],timeout:30}),H("x2","transfer","Suporte","suporte",{method:"bridge",destinations:["1002"],timeout:30}),H("x3","transfer","Vendas","vendas",{method:"bridge",destinations:["1003"],timeout:30}),H("x4","transfer","Ouvidoria","ouvidoria",{method:"bridge",destinations:["1004"],timeout:30}),H("t6","tell","Opção Inválida","opcao_invalida",b("Não entendi sua escolha. Por favor, ligue novamente.")),H("t7","tell","Transferência Falhou","transferencia_falhou",b("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),H("h1","hangup","Desligamento","desligamento",{})],edges:[J("e1v","s1","voice","t1"),J("e1c","s1","chat","t1"),J("e2","t1","next","m1"),J("e3","m1","option:financeiro","t2"),J("e4","m1","option:suporte","t3"),J("e5","m1","option:vendas","t4"),J("e6","m1","option:ouvidoria","t5"),J("e7","t2","next","x1"),J("e8","t3","next","x2"),J("e9","t4","next","x3"),J("e10","t5","next","x4"),J("e11","m1","noMatch","t6"),J("e12","m1","error","t6"),J("e13","t6","next","h1"),...c("ex1","x1","h1","t7"),...c("ex2","x2","h1","t7"),...c("ex3","x3","h1","t7"),...c("ex4","x4","h1","t7"),J("e14","t7","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var _D={id:"banco-sac",category:"industry",requiredModules:[],channelType:"both",tags:["banco","financeiro","sac","saldo","extrato","cartao"],editorState:{nodes:[H("s1","start","Início","inicio",{channelType:"both"}),H("c1","capture","CPF do Cliente","cpf_cliente",Q$("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:"})),H("m1","menu","Menu Serviços","menu_servicos",r("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:")),H("http1","httpRequest","Consultar Saldo","consultar_saldo",{method:"GET",url:"https://api.example.com/accounts/{{cpf_cliente.text}}/balance",headers:{},body:"",timeout:10}),H("t1","tell","Saldo Informado","saldo_informado",b("O seu saldo é: {{consultar_saldo.response}}. Obrigado pelo contato.")),H("t2","tell","Extrato","extrato",b("Seu extrato será enviado por SMS em instantes.")),H("t3","tell","Cartões","cartoes",b("Para informações sobre cartões, vou transferir para um especialista.")),H("t4","tell","Transferindo Atendente","transferindo_atendente",b("Aguarde, vou transferir para um atendente.")),H("t5","tell","Erro Consulta","erro_consulta",b("Não foi possível realizar a consulta agora. Vou transferir para um atendente.")),H("t6","tell","Sem Identificação","sem_identificacao",b("Não consegui identificar o seu CPF. Vou transferir para um atendente.")),H("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["5001"],timeout:45}),H("t7","tell","Transferência Falhou","transferencia_falhou",b("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),H("h1","hangup","Desligamento","desligamento",{})],edges:[J("e1v","s1","voice","c1"),J("e1c","s1","chat","c1"),J("e2","c1","collected","m1"),J("e3","c1","noInput","t6"),J("e4","c1","error","t6"),J("e5","m1","option:saldo","http1"),J("e6","m1","option:extrato","t2"),J("e7","m1","option:cartao","t3"),J("e8","m1","option:atendente","t4"),J("e9","m1","noMatch","t6"),J("e10","m1","error","t6"),J("e11","http1","next","t1"),J("e12","http1","error","t5"),J("e13","t1","next","h1"),J("e14","t2","next","h1"),J("e15","t3","next","x1"),J("e16","t4","next","x1"),J("e17","t5","next","x1"),J("e18","t6","next","x1"),...c("ex1","x1","h1","t7"),J("e19","t7","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var QD={id:"clinica-agendamento",category:"industry",requiredModules:[],channelType:"both",tags:["clinica","saude","agendamento","consulta","medico"],editorState:{nodes:[H("s1","start","Início","inicio",{channelType:"both"}),H("t1","tell","Boas-vindas","boas_vindas",b("Bem-vindo à central de agendamentos.")),H("m1","menu","Especialidade","especialidade",r("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:")),H("c1","capture","CPF do Paciente","cpf_paciente",Q$("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:"})),H("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}),H("t2","tell","Resultado da Consulta","resultado_consulta",b("{{consultar_agenda.response}}")),H("t3","tell","Erro na Consulta","erro_consulta",b("Não conseguimos consultar a agenda no momento. Por favor, tente novamente mais tarde.")),H("t4","tell","Sem Dados","sem_dados",b("Não consegui capturar as informações necessárias. Por favor, tente novamente mais tarde.")),H("h1","hangup","Desligamento","desligamento",{})],edges:[J("e1v","s1","voice","t1"),J("e1c","s1","chat","t1"),J("e2","t1","next","m1"),J("e3","m1","option:clinico","c1"),J("e4","m1","option:cardio","c1"),J("e5","m1","option:orto","c1"),J("e6","m1","noMatch","t4"),J("e7","m1","error","t4"),J("e8","c1","collected","http1"),J("e9","c1","noInput","t4"),J("e10","c1","error","t4"),J("e11","http1","next","t2"),J("e12","http1","error","t3"),J("e13","t2","next","h1"),J("e14","t3","next","h1"),J("e15","t4","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var qD={id:"cobranca-automatizada",category:"capture",requiredModules:[],channelType:"both",tags:["cobranca","debito","pagamento","boleto","pix","negociacao"],editorState:{nodes:[H("s1","start","Início","inicio",{channelType:"both"}),H("t1","tell","Intro Cobrança","intro_cobranca",b("Olá, identificamos um débito em aberto na sua conta.")),H("m1","menu","Opções de Pagamento","opcoes_pagamento",r("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:")),H("c1","capture","Identificação","identificacao",Q$("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:"})),H("t2","tell","Transferindo Negociação","transferindo_negociacao",b("Recebi sua identificação. Vou transferir para um especialista em negociação.")),H("x1","transfer","Negociação","negociacao",{method:"bridge",destinations:["2001"],timeout:45}),H("t3","tell","Boleto Enviado","boleto_enviado",b("O boleto atualizado será enviado para seu contato cadastrado em até 5 minutos.")),H("t4","tell","Chave Pix","chave_pix",b("Nossa chave Pix é o CNPJ da empresa. Após o pagamento, a baixa será automática em até 2 horas.")),H("t5","tell","Opção Inválida","opcao_invalida",b("Não entendi sua escolha. Por favor, ligue novamente.")),H("t6","tell","Sem Identificação","sem_identificacao",b("Não recebi sua identificação. Por favor, ligue novamente com os dados em mãos.")),H("t7","tell","Transferência Falhou","transferencia_falhou",b("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),H("h1","hangup","Desligamento","desligamento",{})],edges:[J("e1v","s1","voice","t1"),J("e1c","s1","chat","t1"),J("e2","t1","next","m1"),J("e3","m1","option:negociar","c1"),J("e4","m1","option:boleto","t3"),J("e5","m1","option:pix","t4"),J("e6","m1","noMatch","t5"),J("e7","m1","error","t5"),J("e8","c1","collected","t2"),J("e9","c1","noInput","t6"),J("e10","c1","error","t6"),J("e11","t2","next","x1"),J("e12","t3","next","h1"),J("e13","t4","next","h1"),J("e14","t5","next","h1"),J("e15","t6","next","h1"),...c("ex1","x1","h1","t7"),J("e16","t7","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var GD={id:"coleta-dados-api",category:"capture",requiredModules:[],channelType:"both",tags:["capture","api","http","dados","integracao"],editorState:{nodes:[H("s1","start","Início","inicio",{channelType:"both"}),H("t1","tell","Boas-vindas","boas_vindas",b("Olá. Vou consultar uma informação para você.")),H("c1","capture","Identificação","identificacao",Q$("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:"})),H("http1","httpRequest","Consultar API","consultar_api",{method:"GET",url:"https://api.example.com/lookup/{{identificacao.text}}",headers:{},body:"",timeout:10}),H("sw1","switchCase","Tipo de Falha","tipo_falha",{expression:"{{consultar_api.status_code}}",cases:[{pattern:"^404$"}]}),H("t2","tell","Resultado Encontrado","resultado_encontrado",b("Encontrei as informações solicitadas: {{consultar_api.response}}. Obrigado pelo contato.")),H("t3","tell","Não Encontrado","nao_encontrado",b("Não encontrei registros para essa identificação. Verifique o número e tente novamente.")),H("t4","tell","Erro de Consulta","erro_consulta",b("Houve um erro na consulta. Tente novamente mais tarde.")),H("t5","tell","Sem Identificação","sem_identificacao",b("Não consegui capturar sua identificação. Por favor, ligue novamente com o número em mãos.")),H("h1","hangup","Desligamento","desligamento",{})],edges:[J("e1v","s1","voice","t1"),J("e1c","s1","chat","t1"),J("e2","t1","next","c1"),J("e3","c1","collected","http1"),J("e4","c1","noInput","t5"),J("e5","c1","error","t5"),J("e6","http1","next","t2"),J("e7","http1","error","sw1"),J("e8","sw1","match:^404$","t3"),J("e9","sw1","fallback","t4"),J("e10","sw1","error","t4"),J("e11","t2","next","h1"),J("e12","t3","next","h1"),J("e13","t4","next","h1"),J("e14","t5","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var WD={id:"faq-ia-escalacao",category:"ai",requiredModules:["ai"],channelType:"both",tags:["faq","ia","escalacao","ai","agente"],editorState:{nodes:[H("s1","start","Início","inicio",{channelType:"both"}),H("t1","tell","Boas-vindas","boas_vindas",b("Olá! Sou o assistente virtual. Posso tirar dúvidas sobre nossos serviços.")),H("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}),H("m1","menu","Resolveu?","resolveu",r("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:")),H("t2","tell","Agradecimento","agradecimento",b("Ótimo! Se precisar de algo mais, é só entrar em contato.")),H("t3","tell","Transferindo","transferindo",b("Aguarde, vou transferir para um atendente.")),H("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["1000"],timeout:45}),H("t4","tell","Transferência Falhou","transferencia_falhou",b("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),H("h1","hangup","Desligamento","desligamento",{})],edges:[J("e1v","s1","voice","t1"),J("e1c","s1","chat","t1"),J("e2","t1","next","ai1"),J("e3","ai1","completed","m1"),J("e4","ai1","error","t3"),J("e5","m1","option:resolvido","t2"),J("e6","m1","option:atendente","t3"),J("e7","m1","noMatch","t3"),J("e8","m1","error","t3"),J("e9","t2","next","h1"),J("e10","t3","next","x1"),...c("ex1","x1","h1","t4"),J("e11","t4","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var jD={id:"faq-informacoes",category:"core",requiredModules:[],channelType:"both",tags:["faq","informacoes","autoatendimento","info"],editorState:{nodes:[H("s1","start","Início","inicio",{channelType:"both"}),H("t1","tell","Boas-vindas","boas_vindas",b("Olá, sou o assistente virtual. Posso ajudar com suporte, financeiro, vendas ou horários de atendimento.")),H("m1","menu","Menu FAQ","menu_faq",r("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:")),H("t2","tell","Info Suporte","info_suporte",b("Nossa equipe de suporte está disponível 24 horas por dia. Você também pode abrir um chamado pelo nosso portal.")),H("t3","tell","Info Financeiro","info_financeiro",b("Para boletos, notas fiscais e negociações, acesse nosso portal financeiro ou fale com atendimento em horário comercial.")),H("t4","tell","Info Vendas","info_vendas",b("Conheça nossos planos e promoções no nosso site. Para falar com um consultor, ligue em horário comercial.")),H("t5","tell","Info Horários","info_horarios",b("Nosso atendimento funciona de segunda a sexta, das 8h às 20h. Aos sábados, das 8h às 14h.")),H("t6","tell","Opção Inválida","opcao_invalida",b("Não entendi sua escolha. Encerrando o atendimento. Até logo.")),H("h1","hangup","Fim","fim",{})],edges:[J("e1v","s1","voice","t1"),J("e1c","s1","chat","t1"),J("e2","t1","next","m1"),J("e3","m1","option:suporte","t2"),J("e4","m1","option:financeiro","t3"),J("e5","m1","option:vendas","t4"),J("e6","m1","option:horarios","t5"),J("e7","t2","next","m1"),J("e8","t3","next","m1"),J("e9","t4","next","m1"),J("e10","t5","next","m1"),J("e11","m1","noMatch","t6"),J("e12","m1","error","t6"),J("e13","t6","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var YD={id:"horario-comercial",category:"core",requiredModules:[],channelType:"both",tags:["horario","schedule","tempo","comercial","expediente"],editorState:{nodes:[H("s1","start","Início","inicio",{channelType:"both"}),H("tr1","timeRouting","Horário Atendimento","horario_atendimento",{}),H("t1","tell","Boas-vindas","boas_vindas",b("Bem-vindo. Como posso ajudar?")),H("m1","menu","Menu Principal","menu_principal",r("Para suporte, tecle 1. Para vendas, tecle 2.",[{id:"suporte",label:"Suporte",digit:"1"},{id:"vendas",label:"Vendas",digit:"2"}],{},"Escolha uma opção:")),H("t2","tell","Transferindo Suporte","transferindo_suporte",b("Transferindo para o suporte.")),H("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),H("t3","tell","Transferindo Vendas","transferindo_vendas",b("Transferindo para vendas.")),H("x2","transfer","Vendas","vendas",{method:"bridge",destinations:["1002"],timeout:30}),H("t4","tell","Fora do Horário","fora_horario",b("Nosso horário de atendimento é de segunda a sexta, das 8h às 18h. Ligue novamente no próximo dia útil.")),H("t5","tell","Opção Não Reconhecida","opcao_nao_reconhecida",b("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),H("t6","tell","Transferência Falhou","transferencia_falhou",b("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),H("h1","hangup","Desligamento","desligamento",{})],edges:[J("e1v","s1","voice","tr1"),J("e1c","s1","chat","tr1"),J("e2","tr1","onHours","t1"),J("e3","tr1","offHours","t4"),J("e4","tr1","holiday","t4"),J("e5","t1","next","m1"),J("e6","m1","option:suporte","t2"),J("e7","m1","option:vendas","t3"),J("e8","t2","next","x1"),J("e9","t3","next","x2"),J("e10","m1","noMatch","t5"),J("e11","m1","error","t5"),J("e12","t5","next","x1"),...c("ex1","x1","h1","t6"),...c("ex2","x2","h1","t6"),J("e13","t4","next","h1"),J("e14","t6","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var JD={id:"isp-suporte-tecnico",category:"industry",requiredModules:[],channelType:"both",tags:["isp","provedor","internet","suporte","tecnico","telecom"],editorState:{nodes:[H("s1","start","Início","inicio",{channelType:"both"}),H("t1","tell","Boas-vindas","boas_vindas",b("Bem-vindo ao suporte técnico.")),H("m1","menu","Tipo de Serviço","tipo_servico",r("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:")),H("c1","capture","Contrato Internet","contrato_internet",Q$("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:"})),H("c2","capture","Contrato Telefonia","contrato_telefonia",Q$("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:"})),H("http1","httpRequest","Status Internet","status_internet",{method:"GET",url:"https://api.example.com/contracts/{{contrato_internet.text}}/status?service=internet",headers:{},body:"",timeout:10}),H("http2","httpRequest","Status Telefonia","status_telefonia",{method:"GET",url:"https://api.example.com/contracts/{{contrato_telefonia.text}}/status?service=telefonia",headers:{},body:"",timeout:10}),H("t2","tell","Status Internet","status_internet_info",b("Sobre sua conexão de internet: {{status_internet.response}}")),H("t3","tell","Status Telefonia","status_telefonia_info",b("Sobre seu serviço de telefonia: {{status_telefonia.response}}")),H("sw1","switchCase","Falha Internet","falha_internet",{expression:"{{status_internet.status_code}}",cases:[{pattern:"^404$"}]}),H("sw2","switchCase","Falha Telefonia","falha_telefonia",{expression:"{{status_telefonia.status_code}}",cases:[{pattern:"^404$"}]}),H("t4","tell","Contrato Não Encontrado","contrato_nao_encontrado",b("Não encontrei esse contrato. Vou transferir para um atendente.")),H("t5","tell","Erro de Consulta","erro_consulta",b("Não foi possível consultar o status agora. Vou transferir para um atendente.")),H("t6","tell","Sem Contrato","sem_contrato",b("Não consegui capturar o número do contrato. Vou transferir para um atendente.")),H("t7","tell","Opção Não Reconhecida","opcao_nao_reconhecida",b("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),H("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["3001"],timeout:60}),H("t8","tell","Transferência Falhou","transferencia_falhou",b("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),H("h1","hangup","Desligamento","desligamento",{})],edges:[J("e1v","s1","voice","t1"),J("e1c","s1","chat","t1"),J("e2","t1","next","m1"),J("e3","m1","option:internet","c1"),J("e4","m1","option:telefonia","c2"),J("e5","m1","noMatch","t7"),J("e5e","m1","error","t7"),J("e6","c1","collected","http1"),J("e7","c1","noInput","t6"),J("e7e","c1","error","t6"),J("e8","http1","next","t2"),J("e9","http1","error","sw1"),J("e10","sw1","match:^404$","t4"),J("e11","sw1","fallback","t5"),J("e11e","sw1","error","t5"),J("e12","t2","next","h1"),J("e13","c2","collected","http2"),J("e14","c2","noInput","t6"),J("e14e","c2","error","t6"),J("e15","http2","next","t3"),J("e16","http2","error","sw2"),J("e17","sw2","match:^404$","t4"),J("e18","sw2","fallback","t5"),J("e18e","sw2","error","t5"),J("e19","t3","next","h1"),J("e20","t4","next","x1"),J("e21","t5","next","x1"),J("e22","t6","next","x1"),J("e23","t7","next","x1"),...c("ex1","x1","h1","t8"),J("e24","t8","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var XD={id:"mensagem-simples",category:"core",requiredModules:[],channelType:"both",tags:["mensagem","simples","aviso","anuncio","basico"],editorState:{nodes:[H("s1","start","Início","inicio",{channelType:"both"}),H("t1","tell","Mensagem","mensagem",b("Obrigado por ligar. No momento não estamos disponíveis. Por favor, tente novamente mais tarde.")),H("h1","hangup","Desligamento","desligamento",{})],edges:[J("e1v","s1","voice","t1"),J("e1c","s1","chat","t1"),J("e2","t1","next","h1")],viewport:{x:0,y:0,zoom:1}}};var HD={id:"menu-multinivel",category:"advanced",requiredModules:[],channelType:"both",tags:["menu","multinivel","departamento","hierarquia","complexo"],editorState:{nodes:[H("s1","start","Início","inicio",{channelType:"both"}),H("t1","tell","Boas-vindas","boas_vindas",b("Bem-vindo. Escolha o setor desejado.")),H("m1","menu","Menu Principal","menu_principal",r("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:")),H("m2","menu","Atendimento","atendimento",r("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:")),H("m3","menu","Comercial","comercial",r("Para vendas, tecle 1. Para parcerias, tecle 2.",[{id:"vendas",label:"Vendas",digit:"1"},{id:"parcerias",label:"Parcerias",digit:"2"}],{},"Escolha uma opção:")),H("m4","menu","Administrativo","administrativo",r("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:")),H("t2","tell","Transferindo Suporte","transferindo_suporte",b("Transferindo para suporte técnico.")),H("t3","tell","Transferindo Financeiro","transferindo_financeiro",b("Transferindo para financeiro.")),H("t4","tell","Transferindo Vendas","transferindo_vendas",b("Transferindo para vendas.")),H("t5","tell","Transferindo Parcerias","transferindo_parcerias",b("Transferindo para parcerias.")),H("t6","tell","Transferindo RH","transferindo_rh",b("Transferindo para RH.")),H("t7","tell","Transferindo Jurídico","transferindo_juridico",b("Transferindo para jurídico.")),H("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),H("x2","transfer","Financeiro","financeiro",{method:"bridge",destinations:["1002"],timeout:45}),H("x3","transfer","Vendas","vendas",{method:"bridge",destinations:["2001"],timeout:30}),H("x4","transfer","Parcerias","parcerias",{method:"bridge",destinations:["2002"],timeout:30}),H("x5","transfer","RH","rh",{method:"bridge",destinations:["3001"],timeout:30}),H("x6","transfer","Jurídico","juridico",{method:"bridge",destinations:["3002"],timeout:30}),H("t8","tell","Opção Não Reconhecida","opcao_nao_reconhecida",b("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),H("t9","tell","Transferência Falhou","transferencia_falhou",b("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),H("h1","hangup","Desligamento","desligamento",{})],edges:[J("e1v","s1","voice","t1"),J("e1c","s1","chat","t1"),J("e2","t1","next","m1"),J("e3","m1","option:atendimento","m2"),J("e4","m1","option:comercial","m3"),J("e5","m1","option:administrativo","m4"),J("e6","m1","noMatch","t8"),J("e6e","m1","error","t8"),J("e7","m2","option:suporte","t2"),J("e8","m2","option:financeiro","t3"),J("e9","m2","noMatch","t8"),J("e9e","m2","error","t8"),J("e10","m3","option:vendas","t4"),J("e11","m3","option:parcerias","t5"),J("e12","m3","noMatch","t8"),J("e12e","m3","error","t8"),J("e13","m4","option:rh","t6"),J("e14","m4","option:juridico","t7"),J("e15","m4","noMatch","t8"),J("e15e","m4","error","t8"),J("e16","t2","next","x1"),J("e17","t3","next","x2"),J("e18","t4","next","x3"),J("e19","t5","next","x4"),J("e20","t6","next","x5"),J("e21","t7","next","x6"),J("e28","t8","next","x1"),...c("ex1","x1","h1","t9"),...c("ex2","x2","h1","t9"),...c("ex3","x3","h1","t9"),...c("ex4","x4","h1","t9"),...c("ex5","x5","h1","t9"),...c("ex6","x6","h1","t9"),J("e29","t9","next","h1")],viewport:{x:0,y:0,zoom:0.7}}};var PD={id:"notificacao-atendimento",category:"core",requiredModules:[],channelType:"both",tags:["notificacao","aviso","atendimento","callback"],editorState:{nodes:[H("s1","start","Início","inicio",{channelType:"both"}),H("t1","tell","Notificação","notificacao",b("Olá, temos uma informação importante sobre sua conta.")),H("m1","menu","Precisa de Ajuda?","precisa_ajuda",r("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?")),H("t2","tell","Transferindo","transferindo",b("Aguarde, vou transferir para um atendente.")),H("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["1000"],timeout:45}),H("t3","tell","Agradecimento","agradecimento",b("Obrigado pelo seu tempo. Tenha um bom dia!")),H("t4","tell","Transferência Falhou","transferencia_falhou",b("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),H("h1","hangup","Desligamento","desligamento",{})],edges:[J("e1v","s1","voice","t1"),J("e1c","s1","chat","t1"),J("e2","t1","next","m1"),J("e3","m1","option:sim","t2"),J("e4","m1","option:nao","t3"),J("e5","m1","noMatch","t3"),J("e6","m1","error","t3"),J("e7","t2","next","x1"),...c("ex1","x1","h1","t4"),J("e8","t3","next","h1"),J("e9","t4","next","h1")],viewport:{x:0,y:0,zoom:0.9}}};var VD={id:"pesquisa-nps",category:"advanced",requiredModules:["ai"],channelType:"both",tags:["nps","pesquisa","promotor","detrator","feedback","avaliacao"],editorState:{nodes:[H("s1","start","Início","inicio",{channelType:"both"}),H("t1","tell","Intro NPS","intro_nps",b("Gostaríamos de saber sua opinião sobre nosso atendimento.")),H("c1","capture","Nota NPS","nota_nps",Q$("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:"})),H("sw1","switchCase","Classificar NPS","classificar_nps",{expression:"{{nota_nps.text}}",cases:[{pattern:"^9$"},{pattern:"^10$"},{pattern:"^7$"},{pattern:"^8$"}]}),H("t2","tell","Promotor","promotor",b("Que ótimo! Ficamos muito felizes com sua avaliação.")),H("t3","tell","Neutro","neutro",b("Obrigado pela avaliação. Vamos trabalhar para melhorar.")),H("t4","tell","Detrator","detrator",b("Lamentamos que sua experiência não tenha sido satisfatória.")),H("c2","capture","Feedback","feedback",Q$("Pode nos dizer o que podemos melhorar? Fale após o sinal.",{voiceMethod:"speech",text:"Pode nos dizer o que podemos melhorar?"})),H("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}),H("t5","tell","Agradecimento","agradecimento",b("Obrigado pelo seu feedback. Ele é muito importante para nós.")),H("h1","hangup","Desligamento","desligamento",{})],edges:[J("e1v","s1","voice","t1"),J("e1c","s1","chat","t1"),J("e2","t1","next","c1"),J("e3","c1","collected","sw1"),J("e4","c1","noInput","t5"),J("e4e","c1","error","t5"),J("e5","sw1","match:^9$","t2"),J("e6","sw1","match:^10$","t2"),J("e7","sw1","match:^7$","t3"),J("e8","sw1","match:^8$","t3"),J("e9","sw1","fallback","t4"),J("e9e","sw1","error","t4"),J("e10","t2","next","c2"),J("e11","t3","next","c2"),J("e12","t4","next","c2"),J("e13","c2","collected","http1"),J("e14","c2","noInput","http1"),J("e14e","c2","error","http1"),J("e15","http1","next","t5"),J("e16","http1","error","t5"),J("e17","t5","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var BD={id:"pesquisa-satisfacao",category:"core",requiredModules:[],channelType:"both",tags:["pesquisa","satisfacao","csat","avaliacao","nota"],editorState:{nodes:[H("s1","start","Início","inicio",{channelType:"both"}),H("t1","tell","Intro Pesquisa","intro_pesquisa",b("Gostaríamos de avaliar o atendimento que você recebeu.")),H("m1","menu","Nota de Satisfação","nota_satisfacao",r("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?")),H("t2","tell","Agradecimento","agradecimento",b("Você avaliou nosso atendimento como: {{nota_satisfacao.selectedLabel}}. Obrigado, sua opinião nos ajuda a melhorar.")),H("t3","tell","Sem Resposta","sem_resposta",b("Não conseguimos registrar sua avaliação. Agradecemos o contato.")),H("h1","hangup","Desligamento","desligamento",{}),H("h2","hangup","Desligamento Timeout","desligamento_timeout",{})],edges:[J("e1v","s1","voice","t1"),J("e1c","s1","chat","t1"),J("e2","t1","next","m1"),J("e3","m1","option:nota_1","t2"),J("e4","m1","option:nota_2","t2"),J("e5","m1","option:nota_3","t2"),J("e6","m1","option:nota_4","t2"),J("e7","m1","option:nota_5","t2"),J("e8","t2","next","h1"),J("e9","m1","noMatch","t3"),J("e10","m1","error","t3"),J("e11","t3","next","h2")],viewport:{x:0,y:0,zoom:0.9}}};var DD={id:"roteamento-canal",category:"omnichannel",requiredModules:[],channelType:"both",tags:["canal","omnichannel","voz","chat","roteamento"],editorState:{nodes:[H("s1","start","Início","inicio",{channelType:"both"}),H("cr1","channelRouter","Roteador de Canal","roteador_canal",{}),H("t1","tell","Boas-vindas Voz","boas_vindas_voz",b("Bem-vindo ao nosso atendimento por telefone.")),H("m1","menu","Menu Voz","menu_voz",r("Para suporte, tecle 1. Para vendas, tecle 2.",[{id:"suporte",label:"Suporte",digit:"1"},{id:"vendas",label:"Vendas",digit:"2"}])),H("t2","tell","Boas-vindas Chat","boas_vindas_chat",b("Olá! Bem-vindo ao nosso atendimento por chat.")),H("m2","menu","Menu Chat","menu_chat",r("Para suporte, tecle 1. Para vendas, tecle 2.",[{id:"suporte",label:"Suporte",digit:"1"},{id:"vendas",label:"Vendas",digit:"2"}],{},"Escolha uma opção:")),H("t3","tell","Transferindo Suporte","transferindo_suporte",b("Transferindo para o suporte.")),H("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),H("t4","tell","Transferindo Vendas","transferindo_vendas",b("Transferindo para vendas.")),H("x2","transfer","Vendas","vendas",{method:"bridge",destinations:["1002"],timeout:30}),H("t5","tell","Opção Não Reconhecida","opcao_nao_reconhecida",b("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),H("t6","tell","Transferência Falhou","transferencia_falhou",b("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),H("h1","hangup","Desligamento","desligamento",{})],edges:[J("e1v","s1","voice","cr1"),J("e1c","s1","chat","cr1"),J("e2","cr1","voice","t1"),J("e3","cr1","chat","t2"),J("e4","t1","next","m1"),J("e5","t2","next","m2"),J("e6","m1","option:suporte","t3"),J("e7","m1","option:vendas","t4"),J("e8","m2","option:suporte","t3"),J("e9","m2","option:vendas","t4"),J("e10","t3","next","x1"),J("e11","t4","next","x2"),...c("ex1","x1","h1","t6"),...c("ex2","x2","h1","t6"),J("e12","m1","noMatch","t5"),J("e13","m1","error","t5"),J("e14","m2","noMatch","t5"),J("e15","m2","error","t5"),J("e16","t5","next","x1"),J("e17","t6","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var bD={id:"status-pedido",category:"capture",requiredModules:[],channelType:"both",tags:["pedido","status","rastreio","ecommerce","api"],editorState:{nodes:[H("s1","start","Início","inicio",{channelType:"both"}),H("t1","tell","Boas-vindas","boas_vindas",b("Olá. Vou consultar o status do seu pedido.")),H("c1","capture","Número do Pedido","numero_pedido",Q$("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:"})),H("http1","httpRequest","Consultar Pedido","consultar_pedido",{method:"GET",url:"https://api.example.com/orders/{{numero_pedido.text}}",headers:{},body:"",timeout:10}),H("sw1","switchCase","Tipo de Falha","tipo_falha",{expression:"{{consultar_pedido.status_code}}",cases:[{pattern:"^404$"}]}),H("t2","tell","Status do Pedido","status_do_pedido",b("O status do seu pedido é: {{consultar_pedido.response}}")),H("t3","tell","Pedido Não Encontrado","pedido_nao_encontrado",b("Não encontrei esse número de pedido. Verifique e tente novamente.")),H("t4","tell","Erro de Consulta","erro_consulta",b("Houve um erro ao consultar o pedido. Tente novamente mais tarde.")),H("t5","tell","Sem Número","sem_numero",b("Não consegui capturar o número do pedido. Por favor, ligue novamente com o número em mãos.")),H("h1","hangup","Desligamento","desligamento",{})],edges:[J("e1v","s1","voice","t1"),J("e1c","s1","chat","t1"),J("e2","t1","next","c1"),J("e3","c1","collected","http1"),J("e4","c1","noInput","t5"),J("e5","c1","error","t5"),J("e6","http1","next","t2"),J("e7","http1","error","sw1"),J("e8","sw1","match:^404$","t3"),J("e9","sw1","fallback","t4"),J("e10","sw1","error","t4"),J("e11","t2","next","h1"),J("e12","t3","next","h1"),J("e13","t4","next","h1"),J("e14","t5","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var kD={id:"triagem-inteligente",category:"ai",requiredModules:["ai"],channelType:"both",tags:["triagem","intencao","intent","ia","roteamento","ai"],editorState:{nodes:[H("s1","start","Início","inicio",{channelType:"both"}),H("t1","tell","Boas-vindas","boas_vindas",b("Olá! Vou te direcionar para o setor correto.")),H("c1","capture","Motivo do Contato","motivo_contato",Q$("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:r1("Um momento enquanto identifico o setor correto.").audio,text:"Descreva em poucas palavras com o que você precisa de ajuda:"})),H("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."}),H("t2","tell","Direcionando Suporte","direcionando_suporte",b("Entendi, vou transferir para o suporte técnico.")),H("t3","tell","Direcionando Financeiro","direcionando_financeiro",b("Entendi, vou transferir para o financeiro.")),H("t4","tell","Direcionando Vendas","direcionando_vendas",b("Entendi, vou transferir para vendas.")),H("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),H("x2","transfer","Financeiro","financeiro",{method:"bridge",destinations:["1002"],timeout:45}),H("x3","transfer","Vendas","vendas",{method:"bridge",destinations:["1003"],timeout:30}),H("t5","tell","Não Identificado","nao_identificado",b("Não consegui identificar sua necessidade. Vou transferir para um atendente.")),H("x4","transfer","Atendente Geral","atendente_geral",{method:"bridge",destinations:["1000"],timeout:45}),H("t6","tell","Transferência Falhou","transferencia_falhou",b("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),H("h1","hangup","Desligamento","desligamento",{})],edges:[J("e1v","s1","voice","t1"),J("e1c","s1","chat","t1"),J("e2","t1","next","c1"),J("e3","c1","collected","ra1"),J("e4","c1","noInput","t5"),J("e5","c1","error","t5"),J("e6","ra1","intent:suporte","t2"),J("e7","ra1","intent:financeiro","t3"),J("e8","ra1","intent:vendas","t4"),J("e9","ra1","notApplicable","t5"),J("e10","ra1","error","t5"),J("e11","t2","next","x1"),J("e12","t3","next","x2"),J("e13","t4","next","x3"),J("e14","t5","next","x4"),...c("ex1","x1","h1","t6"),...c("ex2","x2","h1","t6"),...c("ex3","x3","h1","t6"),...c("ex4","x4","h1","t6"),J("e15","t6","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var ND={id:"ura-reversa-spot",category:"core",requiredModules:[],channelType:"both",tags:["spot","ura reversa","campanha","outbound","discagem","tecla"],editorState:{nodes:[H("s1","start","Início","inicio",{channelType:"both"}),H("m1","menu","Spot","spot",r("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.")),H("t1","tell","Agradecimento","agradecimento",b("Obrigado! Em instantes um atendente entrará em contato.")),H("t2","tell","Encerramento","encerramento",b("Obrigado pela atenção. Até logo!")),H("h1","hangup","Desligamento","desligamento",{})],edges:[J("e1v","s1","voice","m1"),J("e1c","s1","chat","m1"),J("e2","m1","option:interesse","t1"),J("e3","m1","noMatch","t2"),J("e4","m1","error","t2"),J("e5","t1","next","h1"),J("e6","t2","next","h1")],viewport:{x:0,y:0,zoom:0.9}}};var LW=[{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"}]}],T7=new Set([...LW.map(($)=>$.nodeVarName),Tv].map(($)=>$.split(".")[0]));function g7($){return T7.has($)}var LD={tell:new Set(["audio"]),menu:new Set(["audio","voiceTimeout"]),capture:new Set(["audio","voiceMethod","minDigits","maxDigits","terminators","voiceTimeout","listen","processing_audio","retryAudio"])},AD={tell:new Set(["content"]),menu:new Set(["text","invalidMessage"]),capture:new Set(["text","validation","invalidMessage"])};function E7($,v,K,_){let U=$.filter((Y)=>Y.type==="start"),Q=OD(v),q=U[0]?.id,G=cD($,v),j=[...FD(U),...xD($,Q,q),...RD($),...SD($),...uD($),...TD($),...gD($),...ED($),...CD($,v,K),...yD($,Q,q),...fD($),...mD($),...hD($,K,_?.disabledModules),..._?.entities!=null?z7($,_.entities):[],..._?.externalEntities!=null?L7($,_.externalEntities):[],...rD($,K,G)];if(G!=null)return iD(j,$,G);return j}function FD($){if($.length===0)return[{nodeId:"",severity:"error",messageKey:"editor:validation.noStart"}];return $.slice(1).map((v)=>({nodeId:v.id,severity:"error",messageKey:"editor:validation.multipleStart"}))}function OD($){let v=new Map;for(let K of $){let _=v.get(K.source)??[];_.push(K.target),v.set(K.source,_)}return v}function xD($,v,K){if(K===void 0)return[];let _=new Set([K]),U=[K];while(U.length>0){let q=U.pop();for(let G of v.get(q)??[])if(!_.has(G))_.add(G),U.push(G)}let Q=[];for(let q of $)if(q.type!=="start"&&!_.has(q.id))Q.push({nodeId:q.id,severity:"warning",messageKey:"editor:validation.unreachable",params:{label:q.label}});return Q}function RD($){let v=[];for(let K of $){let _=y$[K.type],U=_.configSchema.safeParse(K.config),Q=U.success?U.data:K.config,q=U.success?_.configSchema.safeParse(Q):U;if(q.success)continue;for(let G of q.error.issues){let j=G.message.startsWith("editor:")?G.message:"editor:validation.invalidField";v.push({nodeId:K.id,severity:"error",messageKey:j,params:{label:K.label,field:G.path.join(".")}})}}return v}function C7($){let v=[];for(let K of $){if(K.type!=="transfer")continue;let _=y$.transfer.configSchema.safeParse(K.config);if(!_.success)continue;v.push({node:K,destinations:_.data.destinations,attachedData:_.data.attachedData})}return v}function SD($){let v=[];for(let{node:K,destinations:_}of C7($)){if(_.some((U)=>U.trim()!==""))continue;v.push({nodeId:K.id,severity:"error",messageKey:"editor:validation.noDestinations",params:{label:K.label}})}return v}function uD($){let v=[];for(let{node:K,destinations:_,attachedData:U}of C7($)){let Q=[..._.map((q,G)=>({field:`destinations.${G}`,template:q})),...U.map((q)=>({field:q.key,template:q.value}))];for(let{field:q,template:G}of Q){if(S7(G).valid)continue;v.push({nodeId:K.id,severity:"error",messageKey:"editor:validation.invalidTemplateSyntax",params:{label:K.label,field:q}})}}return v}function TD($){let v=[];for(let{node:K,destinations:_}of C7($))_.forEach((U,Q)=>{if(!/\s/.test(U.trim()))return;v.push({nodeId:K.id,severity:"error",messageKey:"editor:validation.destinationHasSpace",params:{label:K.label,field:`destinations.${Q}`}})});return v}function gD($){let v=[];for(let K of $){if(K.type!=="httpRequest")continue;let _=typeof K.config.body==="string"?K.config.body:"";if(_.trim()==="")continue;let U=_.replace(R7(),'"__tpl__"');try{JSON.parse(U)}catch{v.push({nodeId:K.id,severity:"warning",messageKey:"editor:validation.invalidJson",params:{label:K.label}})}}return v}function ED($){return Ev($).misplaced.map((v)=>({nodeId:v.nodeId,severity:"error",messageKey:"editor:validation.secretFieldNotAllowed",params:{label:v.label,field:v.field,secret:v.name}}))}function CD($,v,K){let _=new Set(v.map((Q)=>Q.source)),U=[];for(let Q of $){let q=K[Q.type];if(c1(q,Q.config).length===0)continue;if(_.has(Q.id))continue;U.push({nodeId:Q.id,severity:"warning",messageKey:"editor:validation.noOutputConnection",params:{label:Q.label}})}return U}function yD($,v,K){if(K===void 0)return[];let _=0,U=1,Q=2,q=new Map;for(let X of $)q.set(X.id,_);let G=new Set;function j(X){q.set(X,U);for(let P of v.get(X)??[])if(q.get(P)===U)G.add(P);else if(q.get(P)===_)j(P);q.set(X,Q)}j(K);let Y=[];for(let X of G){let P=$.find((N)=>N.id===X);if(P===void 0)continue;if(!(typeof P.config.maxAttempts==="number"&&P.config.maxAttempts>0))Y.push({nodeId:X,severity:"error",messageKey:"editor:validation.infiniteCycle",params:{label:P.label}})}return Y}function fD($){let v=new Map,K=[];for(let _ of $)if(v.get(_.varName)!==void 0)K.push({nodeId:_.id,severity:"error",messageKey:"editor:validation.duplicateVarName",params:{label:_.label,varName:_.varName}});else v.set(_.varName,_.id);return K}function mD($){return $.filter((v)=>g7(v.varName)).map((v)=>({nodeId:v.id,severity:"error",messageKey:"editor:validation.reservedVarName",params:{label:v.label,varName:v.varName}}))}function hD($,v,K){if(K==null||K.size===0)return[];let _=[];for(let U of $){let Q=v[U.type];if(Q.module!=="core"&&K.has(Q.module))_.push({nodeId:U.id,severity:"warning",messageKey:"editor:validation.moduleDisabled",params:{label:U.label,module:Q.module}})}return _}function cD($,v){let K=$.find((G)=>G.type==="start");if(K==null)return null;let _=K.config.channelType;if((typeof _==="string"?_:"voice")!=="both")return null;let Q=new Map;for(let G of v){let j=Q.get(G.source);if(j==null)j=new Map,Q.set(G.source,j);j.set(G.sourceHandle,G.target)}let q=new Set;for(let G of $)if(G.type==="channelRouter")q.add(G.id);return w7(K.id,K.config,Q,$.map((G)=>G.id),q.size>0?q:void 0)}function rD($,v,K){if(K==null)return[];let _=[];for(let U of $){if(U.type==="start")continue;let Q=v[U.type],q=K[U.id];if(q==null||q==="unreachable"||q==="converged")continue;if(Q.channel==="voice"&&q==="chat-only")_.push({nodeId:U.id,severity:"error",messageKey:"editor:validation.voiceNodeInChatBranch",params:{label:U.label}});if(Q.channel==="chat"&&q==="voice-only")_.push({nodeId:U.id,severity:"error",messageKey:"editor:validation.chatNodeInVoiceBranch",params:{label:U.label}})}return _}function iD($,v,K){let _=new Map(v.map((U)=>[U.id,U.type]));return $.filter((U)=>{let Q=U.params?.field;if(Q==null||U.nodeId==="")return!0;let q=_.get(U.nodeId);if(q==null)return!0;let G=K[U.nodeId];if(G==null||G==="converged"||G==="unreachable")return!0;let j=Q.split(".")[0];if(G==="chat-only"&&LD[q]?.has(j))return!1;if(G==="voice-only"&&AD[q]?.has(j))return!1;return!0})}function y7($){return $.every((v)=>v.severity!=="error")}var oD=W.object({type:W.literal("message"),message:j7}),dD=W.object({type:W.literal("typing")}),tD=W.object({type:W.literal("ping")}),pD=W.object({type:W.literal("resume"),lastSeq:W.number().int().min(0)}),aD=W.object({type:W.literal("start")}),eD=W.discriminatedUnion("type",[oD,dD,tD,pD,aD]),AW=W.object({type:W.literal("connected"),seq:W.number().int(),ts:W.number(),sessionId:W.string()}),FW=W.object({type:W.literal("message"),seq:W.number().int(),ts:W.number(),id:W.string(),message:R4}),OW=W.object({type:W.literal("typing"),seq:W.number().int(),ts:W.number(),active:W.boolean()}),xW=W.object({type:W.literal("state"),seq:W.number().int(),ts:W.number(),status:W.enum(["active","waiting_input","ended"])}),RW=W.object({type:W.literal("trace"),seq:W.number().int(),ts:W.number(),currentNodeId:W.string(),variables:W.record(W.string(),W.string()),status:W.enum(["active","waiting_input","ended"]),truncated:W.boolean(),step:Cv.optional()}),SW=W.object({type:W.literal("error"),seq:W.number().int(),ts:W.number(),code:W.string(),message:W.string()}),uW=W.object({type:W.literal("pong"),seq:W.number().int(),ts:W.number()}),sD=W.discriminatedUnion("type",[AW,FW,OW,xW,RW,SW,uW]),$b=W.object({type:W.literal("replay"),seq:W.number().int(),ts:W.number(),messages:W.array(sD)}),vb=W.discriminatedUnion("type",[AW,FW,OW,xW,RW,SW,uW,$b]);var L$=v1(Q1(),1);var Ub=new Set(z6);function Kb($){return Ub.has($)}var yv=($)=>$==="online"?L$.default.green($):L$.default.red($);function _b($){let v;if($.isExpired)v=L$.default.red("expired");else if($.isInGracePeriod)v=L$.default.yellow("grace period");else v=L$.default.green($.status);let K=$.daysUntilExpiry!=null?` (${$.daysUntilExpiry}d remaining)`:"";return` License: ${v}${K}`}var TW=10,Qb="unlimited".padEnd(TW);function fv($,v,K,_,U){let Q=` ${$.padEnd(11)}`;if(K==null)return`${Q}${L$.default.dim(Qb)} ${v}${_}`;return`${Q}${q1(v,K,TW)} ${v}/${K}${_} (${Math.round(U)}%)`}function qb($){let v=[L$.default.bold(" AI Usage:")],{stt:K,tts:_,llm:U}=$;if(K)v.push(fv("STT:",Math.round(K.current),K.limit," min",K.percentage));if(_)v.push(fv("TTS:",_.current,_.limit," chars",_.percentage));if(U)v.push(fv("LLM:",U.current,U.limit," tokens",U.percentage));return v}function gW($,v){let K=$.command("fs").description("FreeSWITCH status and debug");K.command("status").description("Check system health (server, DB, Redis, FreeSWITCH)").action(async()=>{let{format:_,fields:U}=M($.opts()),Q=await w(v().dashboard.health());if(_==="json"){let q=U?T(Q,U):Q;k(q);return}if(console.log(`Server: ${yv(Q.server)}`),console.log(`PostgreSQL: ${yv(Q.postgres)}`),console.log(`Redis: ${yv(Q.redis)}`),console.log(`FreeSWITCH: ${yv(Q.freeswitch.status)}`),Q.freeswitch.uptime!=null&&Q.freeswitch.uptime!=="")console.log(` Uptime: ${Q.freeswitch.uptime}`);if(Q.freeswitch.sessions)console.log(` Sessions: ${Q.freeswitch.sessions.active}/${Q.freeswitch.sessions.limit}`);if(Q.freeswitch.cps)console.log(` CPS: ${Q.freeswitch.cps.current}/${Q.freeswitch.cps.limit}`);if(Q.freeswitch.idleCpu!=null)console.log(` Idle CPU: ${Q.freeswitch.idleCpu}%`)}),K.command("channels").description("List active FreeSWITCH channels").action(async()=>{let{format:_,fields:U}=M($.opts()),Q=await w(v().dashboard.activeCalls());if(_==="json"){let q=U?Q.map((G)=>T(G,U)):Q;k(q);return}if(Q.length===0){A("No active channels.");return}y(["UUID","Caller","Plan","Node","Duration"],Q.map((q)=>({UUID:q.uuid,Caller:q.callerId,Plan:q.planName??"—",Node:q.currentNodeLabel??"—",Duration:q.startedAt?`${Math.round((Date.now()-new Date(q.startedAt).getTime())/1000)}s`:"—"}))),A(`${Q.length} active channel(s)`)}),K.command("registrations").description("List SIP registrations").action(async()=>{let{format:_,fields:U}=M($.opts()),Q=await w(v().testCall.registrations());if(_==="json"){let q=U?Q.map((G)=>T(G,U)):Q;k(q);return}if(Q.length===0){A("No SIP registrations.");return}y(["Extension","Agent"],Q.map((q)=>({Extension:q.extension,Agent:q.agent??"—"})))}),K.command("dump <uuid>").description("Dump all channel variables for an active call").action(async(_)=>{let{format:U}=M($.opts()),Q=await w(v().dashboard.fsDumpChannel({uuid:_}));if(Object.keys(Q).length===0){if(U==="json")k({});else x(`Channel ${_} not found.`);process.exit(R.NOT_FOUND)}if(U==="json"){k(Q);return}console.log(L$.default.bold(`Channel Variables — ${_}`)),console.log("");for(let[q,G]of Object.entries(Q))console.log(` ${L$.default.cyan(q.padEnd(40))} ${G}`)}),K.command("sofia").description("Show SIP profile status").action(async()=>{let{format:_}=M($.opts()),U=await w(v().dashboard.fsSofiaStatus());if(_==="json"){k(U);return}if(U.length===0){A("No Sofia profiles configured.");return}console.log(L$.default.bold("Sofia SIP Profiles")),console.log(""),y(["Name","Type","Data","State"],U.map((Q)=>({Name:Q.name,Type:Q.type,Data:Q.data,State:Q.state})))}),K.command("show <entity>").description(`Show FreeSWITCH data (${z6.join(", ")})`).action(async(_)=>{if(!Kb(_))x(`Unknown entity "${_}". Allowed: ${z6.join(", ")}`),process.exit(R.USAGE_ERROR);let{format:U}=M($.opts()),Q=await w(v().dashboard.fsShow({entity:_}));if(U==="json"){k(Q);return}console.log(L$.default.bold(`FreeSWITCH: show ${_}`)),console.log(""),console.log(JSON.stringify(Q,null,2))}),K.command("capacity").description("Show system capacity: channels, license, AI usage").action(async()=>{let{format:_,fields:U}=M($.opts()),Q=await w(v().dashboard.capacityStatus());if(_==="json"){let G=U?T(Q,U):Q;k(G);return}console.log(L$.default.bold("System Capacity")),console.log("");let q=Q.channels.total;if(console.log(fv("Channels:",q.active,q.limit,"",q.percentage??0)),console.log(_b(Q.license)),Q.aiUsage){console.log("");for(let G of qb(Q.aiUsage))console.log(G)}})}function Gb(){return Object.entries(t$).map(([$,v])=>`${$} (${v}_)`).sort(($,v)=>$.localeCompare(v))}function Wb($){return Object.hasOwn(t$,$)}function EW($){x($),A(" Valid entities:");for(let v of Gb())A(` ${v}`);process.exit(R.USAGE_ERROR)}function CW($,v,K){return{input:$,entity:v,prefix:t$[v],typeid:y6(v,K),uuid:K,sql:`'${K}'::uuid`}}function jb($,v){if(v!=null&&!Wb(v))EW(`Unknown entity "${v}".`);let K=f6($);if(K.kind==="typeid"){if(v!=null&&v!==K.entity)x(`"${$}" is a ${K.entity} id, but --as says ${v}.`),A(" Drop --as: a TypeID already carries its entity."),process.exit(R.USAGE_ERROR);return CW($,K.entity,K.uuid)}if(K.kind==="uuid"){if(v==null)EW(`"${$}" is a UUID, which does not carry an entity - pass --as <entity>.`);return CW($,v,K.uuid)}x(`Cannot read "${$}" as an id: ${Yb[K.reason]}.`),A(" A TypeID looks like vp_01k3vbk6hxe008000000000001; a UUID like 0198f6b9-9a3d-7000-8000-000000000001."),process.exit(R.USAGE_ERROR)}var Yb={"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 yW($){$.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((v,K)=>{let{format:_,fields:U}=M($.opts()),Q=jb(v,K.as);if(K.sql===!0){console.log(Q.sql);return}if(_==="json"){k(T(Q,U));return}a([{title:"Id",rows:[{label:"TypeID",value:Q.typeid},{label:"UUID",value:Q.uuid},{label:"Entity",value:Q.entity},{label:"Prefix",value:Q.prefix}]}])})}import{existsSync as Jb,lstatSync as Xb,mkdirSync as Hb,readFileSync as Pb,realpathSync as hW,statSync as Vb,writeFileSync as f7}from"node:fs";import{homedir as Bb}from"node:os";import{isAbsolute as Db,join as i1,relative as bb}from"node:path";function fW(){return{skill:`---
|
|
94
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let J of $.seen.entries()){let G=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(G.cycle){W(J);continue}if(G.count>1){if($.reused==="ref"){W(J);continue}}}}function R1($,U){let Q=$.seen.get(U);if(!Q)throw Error("Unprocessed schema. This is a bug in Zod.");let q=(J)=>{let G=$.seen.get(J);if(G.ref===null)return;let Y=G.def??G.schema,H={...Y},B=G.ref;if(G.ref=null,B){q(B);let V=$.seen.get(B),L=V.schema;if(L.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))Y.allOf=Y.allOf??[],Y.allOf.push(L);else Object.assign(Y,L);if(Object.assign(Y,H),J._zod.parent===B)for(let f in Y){if(f==="$ref"||f==="allOf")continue;if(!(f in H))delete Y[f]}if(L.$ref&&V.def)for(let f in Y){if(f==="$ref"||f==="allOf")continue;if(f in V.def&&JSON.stringify(Y[f])===JSON.stringify(V.def[f]))delete Y[f]}}let M=J._zod.parent;if(M&&M!==B){q(M);let V=$.seen.get(M);if(V?.schema.$ref){if(Y.$ref=V.schema.$ref,V.def)for(let L in Y){if(L==="$ref"||L==="allOf")continue;if(L in V.def&&JSON.stringify(Y[L])===JSON.stringify(V.def[L]))delete Y[L]}}}$.override({zodSchema:J,jsonSchema:Y,path:G.path??[]})};for(let J of[...$.seen.entries()].reverse())q(J[0]);let K={};if($.target==="draft-2020-12")K.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")K.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")K.$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");K.$id=$.external.uri(J)}Object.assign(K,Q.def??Q.schema);let W=$.external?.defs??{};for(let J of $.seen.entries()){let G=J[1];if(G.def&&G.defId)W[G.defId]=G.def}if($.external);else if(Object.keys(W).length>0)if($.target==="draft-2020-12")K.$defs=W;else K.definitions=W;try{let J=JSON.parse(JSON.stringify(K));return Object.defineProperty(J,"~standard",{value:{...U["~standard"],jsonSchema:{input:c4(U,"input",$.processors),output:c4(U,"output",$.processors)}},enumerable:!1,writable:!1}),J}catch(J){throw Error("Error converting schema to JSON.")}}function w$($,U){let Q=U??{seen:new Set};if(Q.seen.has($))return!1;Q.seen.add($);let q=$._zod.def;if(q.type==="transform")return!0;if(q.type==="array")return w$(q.element,Q);if(q.type==="set")return w$(q.valueType,Q);if(q.type==="lazy")return w$(q.getter(),Q);if(q.type==="promise"||q.type==="optional"||q.type==="nonoptional"||q.type==="nullable"||q.type==="readonly"||q.type==="default"||q.type==="prefault")return w$(q.innerType,Q);if(q.type==="intersection")return w$(q.left,Q)||w$(q.right,Q);if(q.type==="record"||q.type==="map")return w$(q.keyType,Q)||w$(q.valueType,Q);if(q.type==="pipe")return w$(q.in,Q)||w$(q.out,Q);if(q.type==="object"){for(let K in q.shape)if(w$(q.shape[K],Q))return!0;return!1}if(q.type==="union"){for(let K of q.options)if(w$(K,Q))return!0;return!1}if(q.type==="tuple"){for(let K of q.items)if(w$(K,Q))return!0;if(q.rest&&w$(q.rest,Q))return!0;return!1}return!1}var N5=($,U={})=>(Q)=>{let q=b1({...Q,processors:U});return p($,q),O1(q,$),R1(q,$)},c4=($,U,Q={})=>(q)=>{let{libraryOptions:K,target:W}=q??{},J=b1({...K??{},target:W,io:U,processors:Q});return p($,J),O1(J,$),R1(J,$)};var aP={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},P5=($,U,Q,q)=>{let K=Q;K.type="string";let{minimum:W,maximum:J,format:G,patterns:Y,contentEncoding:H}=$._zod.bag;if(typeof W==="number")K.minLength=W;if(typeof J==="number")K.maxLength=J;if(G){if(K.format=aP[G]??G,K.format==="")delete K.format;if(G==="time")delete K.format}if(H)K.contentEncoding=H;if(Y&&Y.size>0){let B=[...Y];if(B.length===1)K.pattern=B[0].source;else if(B.length>1)K.allOf=[...B.map((M)=>({...U.target==="draft-07"||U.target==="draft-04"||U.target==="openapi-3.0"?{type:"string"}:{},pattern:M.source}))]}},I5=($,U,Q,q)=>{let K=Q,{minimum:W,maximum:J,format:G,multipleOf:Y,exclusiveMaximum:H,exclusiveMinimum:B}=$._zod.bag;if(typeof G==="string"&&G.includes("int"))K.type="integer";else K.type="number";if(typeof B==="number")if(U.target==="draft-04"||U.target==="openapi-3.0")K.minimum=B,K.exclusiveMinimum=!0;else K.exclusiveMinimum=B;if(typeof W==="number"){if(K.minimum=W,typeof B==="number"&&U.target!=="draft-04")if(B>=W)delete K.minimum;else delete K.exclusiveMinimum}if(typeof H==="number")if(U.target==="draft-04"||U.target==="openapi-3.0")K.maximum=H,K.exclusiveMaximum=!0;else K.exclusiveMaximum=H;if(typeof J==="number"){if(K.maximum=J,typeof H==="number"&&U.target!=="draft-04")if(H<=J)delete K.maximum;else delete K.exclusiveMaximum}if(typeof Y==="number")K.multipleOf=Y},_5=($,U,Q,q)=>{Q.type="boolean"},L5=($,U,Q,q)=>{if(U.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},F5=($,U,Q,q)=>{if(U.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},v5=($,U,Q,q)=>{if(U.target==="openapi-3.0")Q.type="string",Q.nullable=!0,Q.enum=[null];else Q.type="null"},z5=($,U,Q,q)=>{if(U.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},k5=($,U,Q,q)=>{if(U.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},w5=($,U,Q,q)=>{Q.not={}},x5=($,U,Q,q)=>{},A5=($,U,Q,q)=>{},b5=($,U,Q,q)=>{if(U.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},O5=($,U,Q,q)=>{let K=$._zod.def,W=I6(K.entries);if(W.every((J)=>typeof J==="number"))Q.type="number";if(W.every((J)=>typeof J==="string"))Q.type="string";Q.enum=W},R5=($,U,Q,q)=>{let K=$._zod.def,W=[];for(let J of K.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(Q.type=J===null?"null":typeof J,U.target==="draft-04"||U.target==="openapi-3.0")Q.enum=[J];else Q.const=J}else{if(W.every((J)=>typeof J==="number"))Q.type="number";if(W.every((J)=>typeof J==="string"))Q.type="string";if(W.every((J)=>typeof J==="boolean"))Q.type="boolean";if(W.every((J)=>J===null))Q.type="null";Q.enum=W}},T5=($,U,Q,q)=>{if(U.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},S5=($,U,Q,q)=>{let K=Q,W=$._zod.pattern;if(!W)throw Error("Pattern not found in template literal");K.type="string",K.pattern=W.source},C5=($,U,Q,q)=>{let K=Q,W={type:"string",format:"binary",contentEncoding:"binary"},{minimum:J,maximum:G,mime:Y}=$._zod.bag;if(J!==void 0)W.minLength=J;if(G!==void 0)W.maxLength=G;if(Y)if(Y.length===1)W.contentMediaType=Y[0],Object.assign(K,W);else Object.assign(K,W),K.anyOf=Y.map((H)=>({contentMediaType:H}));else Object.assign(K,W)},E5=($,U,Q,q)=>{Q.type="boolean"},g5=($,U,Q,q)=>{if(U.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},y5=($,U,Q,q)=>{if(U.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},u5=($,U,Q,q)=>{if(U.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},f5=($,U,Q,q)=>{if(U.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},h5=($,U,Q,q)=>{if(U.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},m5=($,U,Q,q)=>{let K=Q,W=$._zod.def,{minimum:J,maximum:G}=$._zod.bag;if(typeof J==="number")K.minItems=J;if(typeof G==="number")K.maxItems=G;K.type="array",K.items=p(W.element,U,{...q,path:[...q.path,"items"]})},c5=($,U,Q,q)=>{let K=Q,W=$._zod.def;K.type="object",K.properties={};let J=W.shape;for(let H in J)K.properties[H]=p(J[H],U,{...q,path:[...q.path,"properties",H]});let G=new Set(Object.keys(J)),Y=new Set([...G].filter((H)=>{let B=W.shape[H]._zod;if(U.io==="input")return B.optin===void 0;else return B.optout===void 0}));if(Y.size>0)K.required=Array.from(Y);if(W.catchall?._zod.def.type==="never")K.additionalProperties=!1;else if(!W.catchall){if(U.io==="output")K.additionalProperties=!1}else if(W.catchall)K.additionalProperties=p(W.catchall,U,{...q,path:[...q.path,"additionalProperties"]})},w2=($,U,Q,q)=>{let K=$._zod.def,W=K.inclusive===!1,J=K.options.map((G,Y)=>p(G,U,{...q,path:[...q.path,W?"oneOf":"anyOf",Y]}));if(W)Q.oneOf=J;else Q.anyOf=J},l5=($,U,Q,q)=>{let K=$._zod.def,W=p(K.left,U,{...q,path:[...q.path,"allOf",0]}),J=p(K.right,U,{...q,path:[...q.path,"allOf",1]}),G=(H)=>("allOf"in H)&&Object.keys(H).length===1,Y=[...G(W)?W.allOf:[W],...G(J)?J.allOf:[J]];Q.allOf=Y},r5=($,U,Q,q)=>{let K=Q,W=$._zod.def;K.type="array";let J=U.target==="draft-2020-12"?"prefixItems":"items",G=U.target==="draft-2020-12"?"items":U.target==="openapi-3.0"?"items":"additionalItems",Y=W.items.map((V,L)=>p(V,U,{...q,path:[...q.path,J,L]})),H=W.rest?p(W.rest,U,{...q,path:[...q.path,G,...U.target==="openapi-3.0"?[W.items.length]:[]]}):null;if(U.target==="draft-2020-12"){if(K.prefixItems=Y,H)K.items=H}else if(U.target==="openapi-3.0"){if(K.items={anyOf:Y},H)K.items.anyOf.push(H);if(K.minItems=Y.length,!H)K.maxItems=Y.length}else if(K.items=Y,H)K.additionalItems=H;let{minimum:B,maximum:M}=$._zod.bag;if(typeof B==="number")K.minItems=B;if(typeof M==="number")K.maxItems=M},n5=($,U,Q,q)=>{let K=Q,W=$._zod.def;K.type="object";let J=W.keyType,Y=J._zod.bag?.patterns;if(W.mode==="loose"&&Y&&Y.size>0){let B=p(W.valueType,U,{...q,path:[...q.path,"patternProperties","*"]});K.patternProperties={};for(let M of Y)K.patternProperties[M.source]=B}else{if(U.target==="draft-07"||U.target==="draft-2020-12")K.propertyNames=p(W.keyType,U,{...q,path:[...q.path,"propertyNames"]});K.additionalProperties=p(W.valueType,U,{...q,path:[...q.path,"additionalProperties"]})}let H=J._zod.values;if(H){let B=[...H].filter((M)=>typeof M==="string"||typeof M==="number");if(B.length>0)K.required=B}},i5=($,U,Q,q)=>{let K=$._zod.def,W=p(K.innerType,U,q),J=U.seen.get($);if(U.target==="openapi-3.0")J.ref=K.innerType,Q.nullable=!0;else Q.anyOf=[W,{type:"null"}]},o5=($,U,Q,q)=>{let K=$._zod.def;p(K.innerType,U,q);let W=U.seen.get($);W.ref=K.innerType},d5=($,U,Q,q)=>{let K=$._zod.def;p(K.innerType,U,q);let W=U.seen.get($);W.ref=K.innerType,Q.default=JSON.parse(JSON.stringify(K.defaultValue))},p5=($,U,Q,q)=>{let K=$._zod.def;p(K.innerType,U,q);let W=U.seen.get($);if(W.ref=K.innerType,U.io==="input")Q._prefault=JSON.parse(JSON.stringify(K.defaultValue))},t5=($,U,Q,q)=>{let K=$._zod.def;p(K.innerType,U,q);let W=U.seen.get($);W.ref=K.innerType;let J;try{J=K.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}Q.default=J},a5=($,U,Q,q)=>{let K=$._zod.def,W=U.io==="input"?K.in._zod.def.type==="transform"?K.out:K.in:K.out;p(W,U,q);let J=U.seen.get($);J.ref=W},s5=($,U,Q,q)=>{let K=$._zod.def;p(K.innerType,U,q);let W=U.seen.get($);W.ref=K.innerType,Q.readOnly=!0},e5=($,U,Q,q)=>{let K=$._zod.def;p(K.innerType,U,q);let W=U.seen.get($);W.ref=K.innerType},x2=($,U,Q,q)=>{let K=$._zod.def;p(K.innerType,U,q);let W=U.seen.get($);W.ref=K.innerType},$K=($,U,Q,q)=>{let K=$._zod.innerType;p(K,U,q);let W=U.seen.get($);W.ref=K},k2={string:P5,number:I5,boolean:_5,bigint:L5,symbol:F5,null:v5,undefined:z5,void:k5,never:w5,any:x5,unknown:A5,date:b5,enum:O5,literal:R5,nan:T5,template_literal:S5,file:C5,success:E5,custom:g5,function:y5,transform:u5,map:f5,set:h5,array:m5,object:c5,union:w2,intersection:l5,tuple:r5,record:n5,nullable:i5,nonoptional:o5,default:d5,prefault:p5,catch:t5,pipe:a5,readonly:s5,promise:e5,optional:x2,lazy:$K};function A2($,U){if("_idmap"in $){let q=$,K=b1({...U,processors:k2}),W={};for(let Y of q._idmap.entries()){let[H,B]=Y;p(B,K)}let J={},G={registry:q,uri:U?.uri,defs:W};K.external=G;for(let Y of q._idmap.entries()){let[H,B]=Y;O1(K,B),J[H]=R1(K,B)}if(Object.keys(W).length>0){let Y=K.target==="draft-2020-12"?"$defs":"definitions";J.__shared={[Y]:W}}return{schemas:J}}let Q=b1({...U,processors:k2});return p($,Q),O1(Q,$),R1(Q,$)}class UK{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=b1({processors:k2,target:U,...$?.metadata&&{metadata:$.metadata},...$?.unrepresentable&&{unrepresentable:$.unrepresentable},...$?.override&&{override:$.override},...$?.io&&{io:$.io}})}process($,U={path:[],schemaPath:[]}){return p($,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}O1(this.ctx,$);let Q=R1(this.ctx,$),{"~standard":q,...K}=Q;return K}}var sG={};var h6={};q1(h6,{xor:()=>rj,xid:()=>Zj,void:()=>uj,uuidv7:()=>Wj,uuidv6:()=>qj,uuidv4:()=>Qj,uuid:()=>Kj,url:()=>Jj,unknown:()=>W4,union:()=>U8,undefined:()=>gj,ulid:()=>Bj,uint64:()=>Cj,uint32:()=>Rj,tuple:()=>EK,transform:()=>Q8,templateLiteral:()=>QY,symbol:()=>Ej,superRefine:()=>jQ,success:()=>$Y,stringbool:()=>XY,stringFormat:()=>zj,string:()=>C2,strictObject:()=>cj,set:()=>pj,refine:()=>GQ,record:()=>gK,readonly:()=>UQ,promise:()=>qY,preprocess:()=>ZY,prefault:()=>dK,pipe:()=>r6,partialRecord:()=>ij,optional:()=>c6,object:()=>mj,number:()=>IK,nullish:()=>ej,nullable:()=>l6,null:()=>zK,nonoptional:()=>pK,never:()=>$8,nativeEnum:()=>tj,nanoid:()=>Yj,nan:()=>UY,meta:()=>YY,map:()=>dj,mac:()=>Dj,looseRecord:()=>oj,looseObject:()=>lj,literal:()=>aj,lazy:()=>qQ,ksuid:()=>Mj,keyof:()=>hj,jwt:()=>vj,json:()=>BY,ipv6:()=>Nj,ipv4:()=>Vj,intersection:()=>SK,int64:()=>Sj,int32:()=>Oj,int:()=>E2,instanceof:()=>HY,httpUrl:()=>Gj,hostname:()=>kj,hex:()=>wj,hash:()=>xj,guid:()=>Uj,function:()=>WY,float64:()=>bj,float32:()=>Aj,file:()=>sj,exactOptional:()=>lK,enum:()=>K8,emoji:()=>jj,email:()=>$j,e164:()=>Fj,discriminatedUnion:()=>nj,describe:()=>jY,date:()=>fj,custom:()=>GY,cuid2:()=>Xj,cuid:()=>Hj,codec:()=>KY,cidrv6:()=>Ij,cidrv4:()=>Pj,check:()=>JY,catch:()=>sK,boolean:()=>_K,bigint:()=>Tj,base64url:()=>Lj,base64:()=>_j,array:()=>o6,any:()=>yj,_function:()=>WY,_default:()=>iK,_ZodString:()=>g2,ZodXor:()=>OK,ZodXID:()=>l2,ZodVoid:()=>AK,ZodUnknown:()=>wK,ZodUnion:()=>p6,ZodUndefined:()=>FK,ZodUUID:()=>Q1,ZodURL:()=>n6,ZodULID:()=>c2,ZodType:()=>c,ZodTuple:()=>CK,ZodTransform:()=>mK,ZodTemplateLiteral:()=>KQ,ZodSymbol:()=>LK,ZodSuccess:()=>tK,ZodStringFormat:()=>e,ZodString:()=>n4,ZodSet:()=>uK,ZodRecord:()=>t6,ZodReadonly:()=>$Q,ZodPromise:()=>WQ,ZodPrefault:()=>oK,ZodPipe:()=>J8,ZodOptional:()=>q8,ZodObject:()=>d6,ZodNumberFormat:()=>J4,ZodNumber:()=>o4,ZodNullable:()=>rK,ZodNull:()=>vK,ZodNonOptional:()=>W8,ZodNever:()=>xK,ZodNanoID:()=>f2,ZodNaN:()=>eK,ZodMap:()=>yK,ZodMAC:()=>PK,ZodLiteral:()=>fK,ZodLazy:()=>QQ,ZodKSUID:()=>r2,ZodJWT:()=>s2,ZodIntersection:()=>TK,ZodIPv6:()=>i2,ZodIPv4:()=>n2,ZodGUID:()=>m6,ZodFunction:()=>JQ,ZodFile:()=>hK,ZodExactOptional:()=>cK,ZodEnum:()=>r4,ZodEmoji:()=>u2,ZodEmail:()=>y2,ZodE164:()=>a2,ZodDiscriminatedUnion:()=>RK,ZodDefault:()=>nK,ZodDate:()=>i6,ZodCustomStringFormat:()=>i4,ZodCustom:()=>a6,ZodCodec:()=>G8,ZodCatch:()=>aK,ZodCUID2:()=>m2,ZodCUID:()=>h2,ZodCIDRv6:()=>d2,ZodCIDRv4:()=>o2,ZodBoolean:()=>d4,ZodBigIntFormat:()=>e2,ZodBigInt:()=>p4,ZodBase64URL:()=>t2,ZodBase64:()=>p2,ZodArray:()=>bK,ZodAny:()=>kK});var b2={};q1(b2,{uppercase:()=>R4,trim:()=>y4,toUpperCase:()=>f4,toLowerCase:()=>u4,startsWith:()=>S4,slugify:()=>h4,size:()=>K4,regex:()=>b4,property:()=>z2,positive:()=>_2,overwrite:()=>t$,normalize:()=>g4,nonpositive:()=>F2,nonnegative:()=>v2,negative:()=>L2,multipleOf:()=>x1,minSize:()=>K1,minLength:()=>X1,mime:()=>E4,maxSize:()=>A1,maxLength:()=>Q4,lte:()=>g$,lt:()=>$1,lowercase:()=>O4,length:()=>q4,includes:()=>T4,gte:()=>k$,gt:()=>U1,endsWith:()=>C4});var l4={};q1(l4,{time:()=>qK,duration:()=>WK,datetime:()=>KK,date:()=>QK,ZodISOTime:()=>T2,ZodISODuration:()=>S2,ZodISODateTime:()=>O2,ZodISODate:()=>R2});var O2=D("ZodISODateTime",($,U)=>{f3.init($,U),e.init($,U)});function KK($){return g7(O2,$)}var R2=D("ZodISODate",($,U)=>{h3.init($,U),e.init($,U)});function QK($){return y7(R2,$)}var T2=D("ZodISOTime",($,U)=>{m3.init($,U),e.init($,U)});function qK($){return u7(T2,$)}var S2=D("ZodISODuration",($,U)=>{c3.init($,U),e.init($,U)});function WK($){return f7(S2,$)}var eG=($,U)=>{z6.init($,U),$.name="ZodError",Object.defineProperties($,{format:{value:(Q)=>w6($,Q)},flatten:{value:(Q)=>k6($,Q)},addIssue:{value:(Q)=>{$.issues.push(Q),$.message=JSON.stringify($.issues,_4,2)}},addIssues:{value:(Q)=>{$.issues.push(...Q),$.message=JSON.stringify($.issues,_4,2)}},isEmpty:{get(){return $.issues.length===0}}})},eP=D("ZodError",eG),R$=D("ZodError",eG,{Parent:Error});var JK=v4(R$),GK=z4(R$),jK=k4(R$),YK=w4(R$),HK=T0(R$),XK=S0(R$),BK=C0(R$),ZK=E0(R$),MK=g0(R$),VK=y0(R$),DK=u0(R$),NK=f0(R$);var c=D("ZodType",($,U)=>{return u.init($,U),Object.assign($["~standard"],{jsonSchema:{input:c4($,"input"),output:c4($,"output")}}),$.toJSONSchema=N5($,{}),$.def=U,$.type=U.type,Object.defineProperty($,"_def",{value:U}),$.check=(...Q)=>{return $.clone(k.mergeDefs(U,{checks:[...U.checks??[],...Q.map((q)=>typeof q==="function"?{_zod:{check:q,def:{check:"custom"},onattach:[]}}:q)]}),{parent:!0})},$.with=$.check,$.clone=(Q,q)=>z$($,Q,q),$.brand=()=>$,$.register=(Q,q)=>{return Q.add($,q),$},$.parse=(Q,q)=>JK($,Q,q,{callee:$.parse}),$.safeParse=(Q,q)=>jK($,Q,q),$.parseAsync=async(Q,q)=>GK($,Q,q,{callee:$.parseAsync}),$.safeParseAsync=async(Q,q)=>YK($,Q,q),$.spa=$.safeParseAsync,$.encode=(Q,q)=>HK($,Q,q),$.decode=(Q,q)=>XK($,Q,q),$.encodeAsync=async(Q,q)=>BK($,Q,q),$.decodeAsync=async(Q,q)=>ZK($,Q,q),$.safeEncode=(Q,q)=>MK($,Q,q),$.safeDecode=(Q,q)=>VK($,Q,q),$.safeEncodeAsync=async(Q,q)=>DK($,Q,q),$.safeDecodeAsync=async(Q,q)=>NK($,Q,q),$.refine=(Q,q)=>$.check(GQ(Q,q)),$.superRefine=(Q)=>$.check(jQ(Q)),$.overwrite=(Q)=>$.check(t$(Q)),$.optional=()=>c6($),$.exactOptional=()=>lK($),$.nullable=()=>l6($),$.nullish=()=>c6(l6($)),$.nonoptional=(Q)=>pK($,Q),$.array=()=>o6($),$.or=(Q)=>U8([$,Q]),$.and=(Q)=>SK($,Q),$.transform=(Q)=>r6($,Q8(Q)),$.default=(Q)=>iK($,Q),$.prefault=(Q)=>dK($,Q),$.catch=(Q)=>sK($,Q),$.pipe=(Q)=>r6($,Q),$.readonly=()=>UQ($),$.describe=(Q)=>{let q=$.clone();return P$.add(q,{description:Q}),q},Object.defineProperty($,"description",{get(){return P$.get($)?.description},configurable:!0}),$.meta=(...Q)=>{if(Q.length===0)return P$.get($);let q=$.clone();return P$.add(q,Q[0]),q},$.isOptional=()=>$.safeParse(void 0).success,$.isNullable=()=>$.safeParse(null).success,$.apply=(Q)=>Q($),$}),g2=D("_ZodString",($,U)=>{U4.init($,U),c.init($,U),$._zod.processJSONSchema=(q,K,W)=>P5($,q,K,W);let Q=$._zod.bag;$.format=Q.format??null,$.minLength=Q.minimum??null,$.maxLength=Q.maximum??null,$.regex=(...q)=>$.check(b4(...q)),$.includes=(...q)=>$.check(T4(...q)),$.startsWith=(...q)=>$.check(S4(...q)),$.endsWith=(...q)=>$.check(C4(...q)),$.min=(...q)=>$.check(X1(...q)),$.max=(...q)=>$.check(Q4(...q)),$.length=(...q)=>$.check(q4(...q)),$.nonempty=(...q)=>$.check(X1(1,...q)),$.lowercase=(q)=>$.check(O4(q)),$.uppercase=(q)=>$.check(R4(q)),$.trim=()=>$.check(y4()),$.normalize=(...q)=>$.check(g4(...q)),$.toLowerCase=()=>$.check(u4()),$.toUpperCase=()=>$.check(f4()),$.slugify=()=>$.check(h4())}),n4=D("ZodString",($,U)=>{U4.init($,U),g2.init($,U),$.email=(Q)=>$.check($2(y2,Q)),$.url=(Q)=>$.check(f6(n6,Q)),$.jwt=(Q)=>$.check(I2(s2,Q)),$.emoji=(Q)=>$.check(W2(u2,Q)),$.guid=(Q)=>$.check(u6(m6,Q)),$.uuid=(Q)=>$.check(U2(Q1,Q)),$.uuidv4=(Q)=>$.check(K2(Q1,Q)),$.uuidv6=(Q)=>$.check(Q2(Q1,Q)),$.uuidv7=(Q)=>$.check(q2(Q1,Q)),$.nanoid=(Q)=>$.check(J2(f2,Q)),$.guid=(Q)=>$.check(u6(m6,Q)),$.cuid=(Q)=>$.check(G2(h2,Q)),$.cuid2=(Q)=>$.check(j2(m2,Q)),$.ulid=(Q)=>$.check(Y2(c2,Q)),$.base64=(Q)=>$.check(D2(p2,Q)),$.base64url=(Q)=>$.check(N2(t2,Q)),$.xid=(Q)=>$.check(H2(l2,Q)),$.ksuid=(Q)=>$.check(X2(r2,Q)),$.ipv4=(Q)=>$.check(B2(n2,Q)),$.ipv6=(Q)=>$.check(Z2(i2,Q)),$.cidrv4=(Q)=>$.check(M2(o2,Q)),$.cidrv6=(Q)=>$.check(V2(d2,Q)),$.e164=(Q)=>$.check(P2(a2,Q)),$.datetime=(Q)=>$.check(KK(Q)),$.date=(Q)=>$.check(QK(Q)),$.time=(Q)=>$.check(qK(Q)),$.duration=(Q)=>$.check(WK(Q))});function C2($){return T7(n4,$)}var e=D("ZodStringFormat",($,U)=>{s.init($,U),g2.init($,U)}),y2=D("ZodEmail",($,U)=>{O3.init($,U),e.init($,U)});function $j($){return $2(y2,$)}var m6=D("ZodGUID",($,U)=>{A3.init($,U),e.init($,U)});function Uj($){return u6(m6,$)}var Q1=D("ZodUUID",($,U)=>{b3.init($,U),e.init($,U)});function Kj($){return U2(Q1,$)}function Qj($){return K2(Q1,$)}function qj($){return Q2(Q1,$)}function Wj($){return q2(Q1,$)}var n6=D("ZodURL",($,U)=>{R3.init($,U),e.init($,U)});function Jj($){return f6(n6,$)}function Gj($){return f6(n6,{protocol:/^https?$/,hostname:r$.domain,...k.normalizeParams($)})}var u2=D("ZodEmoji",($,U)=>{T3.init($,U),e.init($,U)});function jj($){return W2(u2,$)}var f2=D("ZodNanoID",($,U)=>{S3.init($,U),e.init($,U)});function Yj($){return J2(f2,$)}var h2=D("ZodCUID",($,U)=>{C3.init($,U),e.init($,U)});function Hj($){return G2(h2,$)}var m2=D("ZodCUID2",($,U)=>{E3.init($,U),e.init($,U)});function Xj($){return j2(m2,$)}var c2=D("ZodULID",($,U)=>{g3.init($,U),e.init($,U)});function Bj($){return Y2(c2,$)}var l2=D("ZodXID",($,U)=>{y3.init($,U),e.init($,U)});function Zj($){return H2(l2,$)}var r2=D("ZodKSUID",($,U)=>{u3.init($,U),e.init($,U)});function Mj($){return X2(r2,$)}var n2=D("ZodIPv4",($,U)=>{l3.init($,U),e.init($,U)});function Vj($){return B2(n2,$)}var PK=D("ZodMAC",($,U)=>{n3.init($,U),e.init($,U)});function Dj($){return C7(PK,$)}var i2=D("ZodIPv6",($,U)=>{r3.init($,U),e.init($,U)});function Nj($){return Z2(i2,$)}var o2=D("ZodCIDRv4",($,U)=>{i3.init($,U),e.init($,U)});function Pj($){return M2(o2,$)}var d2=D("ZodCIDRv6",($,U)=>{o3.init($,U),e.init($,U)});function Ij($){return V2(d2,$)}var p2=D("ZodBase64",($,U)=>{p3.init($,U),e.init($,U)});function _j($){return D2(p2,$)}var t2=D("ZodBase64URL",($,U)=>{t3.init($,U),e.init($,U)});function Lj($){return N2(t2,$)}var a2=D("ZodE164",($,U)=>{a3.init($,U),e.init($,U)});function Fj($){return P2(a2,$)}var s2=D("ZodJWT",($,U)=>{s3.init($,U),e.init($,U)});function vj($){return I2(s2,$)}var i4=D("ZodCustomStringFormat",($,U)=>{e3.init($,U),e.init($,U)});function zj($,U,Q={}){return m4(i4,$,U,Q)}function kj($){return m4(i4,"hostname",r$.hostname,$)}function wj($){return m4(i4,"hex",r$.hex,$)}function xj($,U){let Q=U?.enc??"hex",q=`${$}_${Q}`,K=r$[q];if(!K)throw Error(`Unrecognized hash format: ${q}`);return m4(i4,q,K,U)}var o4=D("ZodNumber",($,U)=>{p0.init($,U),c.init($,U),$._zod.processJSONSchema=(q,K,W)=>I5($,q,K,W),$.gt=(q,K)=>$.check(U1(q,K)),$.gte=(q,K)=>$.check(k$(q,K)),$.min=(q,K)=>$.check(k$(q,K)),$.lt=(q,K)=>$.check($1(q,K)),$.lte=(q,K)=>$.check(g$(q,K)),$.max=(q,K)=>$.check(g$(q,K)),$.int=(q)=>$.check(E2(q)),$.safe=(q)=>$.check(E2(q)),$.positive=(q)=>$.check(U1(0,q)),$.nonnegative=(q)=>$.check(k$(0,q)),$.negative=(q)=>$.check($1(0,q)),$.nonpositive=(q)=>$.check(g$(0,q)),$.multipleOf=(q,K)=>$.check(x1(q,K)),$.step=(q,K)=>$.check(x1(q,K)),$.finite=()=>$;let Q=$._zod.bag;$.minValue=Math.max(Q.minimum??Number.NEGATIVE_INFINITY,Q.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,$.maxValue=Math.min(Q.maximum??Number.POSITIVE_INFINITY,Q.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,$.isInt=(Q.format??"").includes("int")||Number.isSafeInteger(Q.multipleOf??0.5),$.isFinite=!0,$.format=Q.format??null});function IK($){return h7(o4,$)}var J4=D("ZodNumberFormat",($,U)=>{$9.init($,U),o4.init($,U)});function E2($){return c7(J4,$)}function Aj($){return l7(J4,$)}function bj($){return r7(J4,$)}function Oj($){return n7(J4,$)}function Rj($){return i7(J4,$)}var d4=D("ZodBoolean",($,U)=>{O6.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>_5($,Q,q,K)});function _K($){return o7(d4,$)}var p4=D("ZodBigInt",($,U)=>{t0.init($,U),c.init($,U),$._zod.processJSONSchema=(q,K,W)=>L5($,q,K,W),$.gte=(q,K)=>$.check(k$(q,K)),$.min=(q,K)=>$.check(k$(q,K)),$.gt=(q,K)=>$.check(U1(q,K)),$.gte=(q,K)=>$.check(k$(q,K)),$.min=(q,K)=>$.check(k$(q,K)),$.lt=(q,K)=>$.check($1(q,K)),$.lte=(q,K)=>$.check(g$(q,K)),$.max=(q,K)=>$.check(g$(q,K)),$.positive=(q)=>$.check(U1(BigInt(0),q)),$.negative=(q)=>$.check($1(BigInt(0),q)),$.nonpositive=(q)=>$.check(g$(BigInt(0),q)),$.nonnegative=(q)=>$.check(k$(BigInt(0),q)),$.multipleOf=(q,K)=>$.check(x1(q,K));let Q=$._zod.bag;$.minValue=Q.minimum??null,$.maxValue=Q.maximum??null,$.format=Q.format??null});function Tj($){return p7(p4,$)}var e2=D("ZodBigIntFormat",($,U)=>{U9.init($,U),p4.init($,U)});function Sj($){return a7(e2,$)}function Cj($){return s7(e2,$)}var LK=D("ZodSymbol",($,U)=>{K9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>F5($,Q,q,K)});function Ej($){return e7(LK,$)}var FK=D("ZodUndefined",($,U)=>{Q9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>z5($,Q,q,K)});function gj($){return $5(FK,$)}var vK=D("ZodNull",($,U)=>{q9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>v5($,Q,q,K)});function zK($){return U5(vK,$)}var kK=D("ZodAny",($,U)=>{W9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>x5($,Q,q,K)});function yj(){return K5(kK)}var wK=D("ZodUnknown",($,U)=>{J9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>A5($,Q,q,K)});function W4(){return Q5(wK)}var xK=D("ZodNever",($,U)=>{G9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>w5($,Q,q,K)});function $8($){return q5(xK,$)}var AK=D("ZodVoid",($,U)=>{j9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>k5($,Q,q,K)});function uj($){return W5(AK,$)}var i6=D("ZodDate",($,U)=>{Y9.init($,U),c.init($,U),$._zod.processJSONSchema=(q,K,W)=>b5($,q,K,W),$.min=(q,K)=>$.check(k$(q,K)),$.max=(q,K)=>$.check(g$(q,K));let Q=$._zod.bag;$.minDate=Q.minimum?new Date(Q.minimum):null,$.maxDate=Q.maximum?new Date(Q.maximum):null});function fj($){return J5(i6,$)}var bK=D("ZodArray",($,U)=>{H9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>m5($,Q,q,K),$.element=U.element,$.min=(Q,q)=>$.check(X1(Q,q)),$.nonempty=(Q)=>$.check(X1(1,Q)),$.max=(Q,q)=>$.check(Q4(Q,q)),$.length=(Q,q)=>$.check(q4(Q,q)),$.unwrap=()=>$.element});function o6($,U){return Y5(bK,$,U)}function hj($){let U=$._zod.def.shape;return K8(Object.keys(U))}var d6=D("ZodObject",($,U)=>{X9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>c5($,Q,q,K),k.defineLazy($,"shape",()=>{return U.shape}),$.keyof=()=>K8(Object.keys($._zod.def.shape)),$.catchall=(Q)=>$.clone({...$._zod.def,catchall:Q}),$.passthrough=()=>$.clone({...$._zod.def,catchall:W4()}),$.loose=()=>$.clone({...$._zod.def,catchall:W4()}),$.strict=()=>$.clone({...$._zod.def,catchall:$8()}),$.strip=()=>$.clone({...$._zod.def,catchall:void 0}),$.extend=(Q)=>{return k.extend($,Q)},$.safeExtend=(Q)=>{return k.safeExtend($,Q)},$.merge=(Q)=>k.merge($,Q),$.pick=(Q)=>k.pick($,Q),$.omit=(Q)=>k.omit($,Q),$.partial=(...Q)=>k.partial(q8,$,Q[0]),$.required=(...Q)=>k.required(W8,$,Q[0])});function mj($,U){let Q={type:"object",shape:$??{},...k.normalizeParams(U)};return new d6(Q)}function cj($,U){return new d6({type:"object",shape:$,catchall:$8(),...k.normalizeParams(U)})}function lj($,U){return new d6({type:"object",shape:$,catchall:W4(),...k.normalizeParams(U)})}var p6=D("ZodUnion",($,U)=>{R6.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>w2($,Q,q,K),$.options=U.options});function U8($,U){return new p6({type:"union",options:$,...k.normalizeParams(U)})}var OK=D("ZodXor",($,U)=>{p6.init($,U),B9.init($,U),$._zod.processJSONSchema=(Q,q,K)=>w2($,Q,q,K),$.options=U.options});function rj($,U){return new OK({type:"union",options:$,inclusive:!1,...k.normalizeParams(U)})}var RK=D("ZodDiscriminatedUnion",($,U)=>{p6.init($,U),Z9.init($,U)});function nj($,U,Q){return new RK({type:"union",options:U,discriminator:$,...k.normalizeParams(Q)})}var TK=D("ZodIntersection",($,U)=>{M9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>l5($,Q,q,K)});function SK($,U){return new TK({type:"intersection",left:$,right:U})}var CK=D("ZodTuple",($,U)=>{a0.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>r5($,Q,q,K),$.rest=(Q)=>$.clone({...$._zod.def,rest:Q})});function EK($,U,Q){let q=U instanceof u,K=q?Q:U;return new CK({type:"tuple",items:$,rest:q?U:null,...k.normalizeParams(K)})}var t6=D("ZodRecord",($,U)=>{V9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>n5($,Q,q,K),$.keyType=U.keyType,$.valueType=U.valueType});function gK($,U,Q){return new t6({type:"record",keyType:$,valueType:U,...k.normalizeParams(Q)})}function ij($,U,Q){let q=z$($);return q._zod.values=void 0,new t6({type:"record",keyType:q,valueType:U,...k.normalizeParams(Q)})}function oj($,U,Q){return new t6({type:"record",keyType:$,valueType:U,mode:"loose",...k.normalizeParams(Q)})}var yK=D("ZodMap",($,U)=>{D9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>f5($,Q,q,K),$.keyType=U.keyType,$.valueType=U.valueType,$.min=(...Q)=>$.check(K1(...Q)),$.nonempty=(Q)=>$.check(K1(1,Q)),$.max=(...Q)=>$.check(A1(...Q)),$.size=(...Q)=>$.check(K4(...Q))});function dj($,U,Q){return new yK({type:"map",keyType:$,valueType:U,...k.normalizeParams(Q)})}var uK=D("ZodSet",($,U)=>{N9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>h5($,Q,q,K),$.min=(...Q)=>$.check(K1(...Q)),$.nonempty=(Q)=>$.check(K1(1,Q)),$.max=(...Q)=>$.check(A1(...Q)),$.size=(...Q)=>$.check(K4(...Q))});function pj($,U){return new uK({type:"set",valueType:$,...k.normalizeParams(U)})}var r4=D("ZodEnum",($,U)=>{P9.init($,U),c.init($,U),$._zod.processJSONSchema=(q,K,W)=>O5($,q,K,W),$.enum=U.entries,$.options=Object.values(U.entries);let Q=new Set(Object.keys(U.entries));$.extract=(q,K)=>{let W={};for(let J of q)if(Q.has(J))W[J]=U.entries[J];else throw Error(`Key ${J} not found in enum`);return new r4({...U,checks:[],...k.normalizeParams(K),entries:W})},$.exclude=(q,K)=>{let W={...U.entries};for(let J of q)if(Q.has(J))delete W[J];else throw Error(`Key ${J} not found in enum`);return new r4({...U,checks:[],...k.normalizeParams(K),entries:W})}});function K8($,U){let Q=Array.isArray($)?Object.fromEntries($.map((q)=>[q,q])):$;return new r4({type:"enum",entries:Q,...k.normalizeParams(U)})}function tj($,U){return new r4({type:"enum",entries:$,...k.normalizeParams(U)})}var fK=D("ZodLiteral",($,U)=>{I9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>R5($,Q,q,K),$.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 aj($,U){return new fK({type:"literal",values:Array.isArray($)?$:[$],...k.normalizeParams(U)})}var hK=D("ZodFile",($,U)=>{_9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>C5($,Q,q,K),$.min=(Q,q)=>$.check(K1(Q,q)),$.max=(Q,q)=>$.check(A1(Q,q)),$.mime=(Q,q)=>$.check(E4(Array.isArray(Q)?Q:[Q],q))});function sj($){return H5(hK,$)}var mK=D("ZodTransform",($,U)=>{L9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>u5($,Q,q,K),$._zod.parse=(Q,q)=>{if(q.direction==="backward")throw new s1($.constructor.name);Q.addIssue=(W)=>{if(typeof W==="string")Q.issues.push(k.issue(W,Q.value,U));else{let J=W;if(J.fatal)J.continue=!1;J.code??(J.code="custom"),J.input??(J.input=Q.value),J.inst??(J.inst=$),Q.issues.push(k.issue(J))}};let K=U.transform(Q.value,Q);if(K instanceof Promise)return K.then((W)=>{return Q.value=W,Q});return Q.value=K,Q}});function Q8($){return new mK({type:"transform",transform:$})}var q8=D("ZodOptional",($,U)=>{s0.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>x2($,Q,q,K),$.unwrap=()=>$._zod.def.innerType});function c6($){return new q8({type:"optional",innerType:$})}var cK=D("ZodExactOptional",($,U)=>{F9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>x2($,Q,q,K),$.unwrap=()=>$._zod.def.innerType});function lK($){return new cK({type:"optional",innerType:$})}var rK=D("ZodNullable",($,U)=>{v9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>i5($,Q,q,K),$.unwrap=()=>$._zod.def.innerType});function l6($){return new rK({type:"nullable",innerType:$})}function ej($){return c6(l6($))}var nK=D("ZodDefault",($,U)=>{z9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>d5($,Q,q,K),$.unwrap=()=>$._zod.def.innerType,$.removeDefault=$.unwrap});function iK($,U){return new nK({type:"default",innerType:$,get defaultValue(){return typeof U==="function"?U():k.shallowClone(U)}})}var oK=D("ZodPrefault",($,U)=>{k9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>p5($,Q,q,K),$.unwrap=()=>$._zod.def.innerType});function dK($,U){return new oK({type:"prefault",innerType:$,get defaultValue(){return typeof U==="function"?U():k.shallowClone(U)}})}var W8=D("ZodNonOptional",($,U)=>{w9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>o5($,Q,q,K),$.unwrap=()=>$._zod.def.innerType});function pK($,U){return new W8({type:"nonoptional",innerType:$,...k.normalizeParams(U)})}var tK=D("ZodSuccess",($,U)=>{x9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>E5($,Q,q,K),$.unwrap=()=>$._zod.def.innerType});function $Y($){return new tK({type:"success",innerType:$})}var aK=D("ZodCatch",($,U)=>{A9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>t5($,Q,q,K),$.unwrap=()=>$._zod.def.innerType,$.removeCatch=$.unwrap});function sK($,U){return new aK({type:"catch",innerType:$,catchValue:typeof U==="function"?U:()=>U})}var eK=D("ZodNaN",($,U)=>{b9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>T5($,Q,q,K)});function UY($){return j5(eK,$)}var J8=D("ZodPipe",($,U)=>{O9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>a5($,Q,q,K),$.in=U.in,$.out=U.out});function r6($,U){return new J8({type:"pipe",in:$,out:U})}var G8=D("ZodCodec",($,U)=>{J8.init($,U),T6.init($,U)});function KY($,U,Q){return new G8({type:"pipe",in:$,out:U,transform:Q.decode,reverseTransform:Q.encode})}var $Q=D("ZodReadonly",($,U)=>{R9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>s5($,Q,q,K),$.unwrap=()=>$._zod.def.innerType});function UQ($){return new $Q({type:"readonly",innerType:$})}var KQ=D("ZodTemplateLiteral",($,U)=>{T9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>S5($,Q,q,K)});function QY($,U){return new KQ({type:"template_literal",parts:$,...k.normalizeParams(U)})}var QQ=D("ZodLazy",($,U)=>{E9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>$K($,Q,q,K),$.unwrap=()=>$._zod.def.getter()});function qQ($){return new QQ({type:"lazy",getter:$})}var WQ=D("ZodPromise",($,U)=>{C9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>e5($,Q,q,K),$.unwrap=()=>$._zod.def.innerType});function qY($){return new WQ({type:"promise",innerType:$})}var JQ=D("ZodFunction",($,U)=>{S9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>y5($,Q,q,K)});function WY($){return new JQ({type:"function",input:Array.isArray($?.input)?EK($?.input):$?.input??o6(W4()),output:$?.output??W4()})}var a6=D("ZodCustom",($,U)=>{g9.init($,U),c.init($,U),$._zod.processJSONSchema=(Q,q,K)=>g5($,Q,q,K)});function JY($){let U=new $$({check:"custom"});return U._zod.check=$,U}function GY($,U){return X5(a6,$??(()=>!0),U)}function GQ($,U={}){return B5(a6,$,U)}function jQ($){return Z5($)}var jY=M5,YY=V5;function HY($,U={}){let Q=new a6({type:"custom",check:"custom",fn:(q)=>q instanceof $,abort:!0,...k.normalizeParams(U)});return Q._zod.bag.Class=$,Q._zod.check=(q)=>{if(!(q.value instanceof $))q.issues.push({code:"invalid_type",expected:$.name,input:q.value,inst:Q,path:[...Q._zod.def.path??[]]})},Q}var XY=(...$)=>D5({Codec:G8,Boolean:d4,String:n4},...$);function BY($){let U=qQ(()=>{return U8([C2($),IK(),_K(),zK(),o6(U),gK(C2(),U)])});return U}function ZY($,U){return r6(Q8($),U)}var UI={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 KI($){H$({customError:$})}function QI(){return H$().customError}var YQ;(function($){})(YQ||(YQ={}));var R={...h6,...b2,iso:l4},qI=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 WI($,U){let Q=$.$schema;if(Q==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if(Q==="http://json-schema.org/draft-07/schema#")return"draft-7";if(Q==="http://json-schema.org/draft-04/schema#")return"draft-4";return U??"draft-2020-12"}function JI($,U){if(!$.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let Q=$.slice(1).split("/").filter(Boolean);if(Q.length===0)return U.rootSchema;let q=U.version==="draft-2020-12"?"$defs":"definitions";if(Q[0]===q){let K=Q[1];if(!K||!U.defs[K])throw Error(`Reference not found: ${$}`);return U.defs[K]}throw Error(`Reference not found: ${$}`)}function MY($,U){if($.not!==void 0){if(typeof $.not==="object"&&Object.keys($.not).length===0)return R.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 K=$.$ref;if(U.refs.has(K))return U.refs.get(K);if(U.processing.has(K))return R.lazy(()=>{if(!U.refs.has(K))throw Error(`Circular reference not resolved: ${K}`);return U.refs.get(K)});U.processing.add(K);let W=JI(K,U),J=_$(W,U);return U.refs.set(K,J),U.processing.delete(K),J}if($.enum!==void 0){let K=$.enum;if(U.version==="openapi-3.0"&&$.nullable===!0&&K.length===1&&K[0]===null)return R.null();if(K.length===0)return R.never();if(K.length===1)return R.literal(K[0]);if(K.every((J)=>typeof J==="string"))return R.enum(K);let W=K.map((J)=>R.literal(J));if(W.length<2)return W[0];return R.union([W[0],W[1],...W.slice(2)])}if($.const!==void 0)return R.literal($.const);let Q=$.type;if(Array.isArray(Q)){let K=Q.map((W)=>{let J={...$,type:W};return MY(J,U)});if(K.length===0)return R.never();if(K.length===1)return K[0];return R.union(K)}if(!Q)return R.any();let q;switch(Q){case"string":{let K=R.string();if($.format){let W=$.format;if(W==="email")K=K.check(R.email());else if(W==="uri"||W==="uri-reference")K=K.check(R.url());else if(W==="uuid"||W==="guid")K=K.check(R.uuid());else if(W==="date-time")K=K.check(R.iso.datetime());else if(W==="date")K=K.check(R.iso.date());else if(W==="time")K=K.check(R.iso.time());else if(W==="duration")K=K.check(R.iso.duration());else if(W==="ipv4")K=K.check(R.ipv4());else if(W==="ipv6")K=K.check(R.ipv6());else if(W==="mac")K=K.check(R.mac());else if(W==="cidr")K=K.check(R.cidrv4());else if(W==="cidr-v6")K=K.check(R.cidrv6());else if(W==="base64")K=K.check(R.base64());else if(W==="base64url")K=K.check(R.base64url());else if(W==="e164")K=K.check(R.e164());else if(W==="jwt")K=K.check(R.jwt());else if(W==="emoji")K=K.check(R.emoji());else if(W==="nanoid")K=K.check(R.nanoid());else if(W==="cuid")K=K.check(R.cuid());else if(W==="cuid2")K=K.check(R.cuid2());else if(W==="ulid")K=K.check(R.ulid());else if(W==="xid")K=K.check(R.xid());else if(W==="ksuid")K=K.check(R.ksuid())}if(typeof $.minLength==="number")K=K.min($.minLength);if(typeof $.maxLength==="number")K=K.max($.maxLength);if($.pattern)K=K.regex(new RegExp($.pattern));q=K;break}case"number":case"integer":{let K=Q==="integer"?R.number().int():R.number();if(typeof $.minimum==="number")K=K.min($.minimum);if(typeof $.maximum==="number")K=K.max($.maximum);if(typeof $.exclusiveMinimum==="number")K=K.gt($.exclusiveMinimum);else if($.exclusiveMinimum===!0&&typeof $.minimum==="number")K=K.gt($.minimum);if(typeof $.exclusiveMaximum==="number")K=K.lt($.exclusiveMaximum);else if($.exclusiveMaximum===!0&&typeof $.maximum==="number")K=K.lt($.maximum);if(typeof $.multipleOf==="number")K=K.multipleOf($.multipleOf);q=K;break}case"boolean":{q=R.boolean();break}case"null":{q=R.null();break}case"object":{let K={},W=$.properties||{},J=new Set($.required||[]);for(let[Y,H]of Object.entries(W)){let B=_$(H,U);K[Y]=J.has(Y)?B:B.optional()}if($.propertyNames){let Y=_$($.propertyNames,U),H=$.additionalProperties&&typeof $.additionalProperties==="object"?_$($.additionalProperties,U):R.any();if(Object.keys(K).length===0){q=R.record(Y,H);break}let B=R.object(K).passthrough(),M=R.looseRecord(Y,H);q=R.intersection(B,M);break}if($.patternProperties){let Y=$.patternProperties,H=Object.keys(Y),B=[];for(let V of H){let L=_$(Y[V],U),T=R.string().regex(new RegExp(V));B.push(R.looseRecord(T,L))}let M=[];if(Object.keys(K).length>0)M.push(R.object(K).passthrough());if(M.push(...B),M.length===0)q=R.object({}).passthrough();else if(M.length===1)q=M[0];else{let V=R.intersection(M[0],M[1]);for(let L=2;L<M.length;L++)V=R.intersection(V,M[L]);q=V}break}let G=R.object(K);if($.additionalProperties===!1)q=G.strict();else if(typeof $.additionalProperties==="object")q=G.catchall(_$($.additionalProperties,U));else q=G.passthrough();break}case"array":{let{prefixItems:K,items:W}=$;if(K&&Array.isArray(K)){let J=K.map((Y)=>_$(Y,U)),G=W&&typeof W==="object"&&!Array.isArray(W)?_$(W,U):void 0;if(G)q=R.tuple(J).rest(G);else q=R.tuple(J);if(typeof $.minItems==="number")q=q.check(R.minLength($.minItems));if(typeof $.maxItems==="number")q=q.check(R.maxLength($.maxItems))}else if(Array.isArray(W)){let J=W.map((Y)=>_$(Y,U)),G=$.additionalItems&&typeof $.additionalItems==="object"?_$($.additionalItems,U):void 0;if(G)q=R.tuple(J).rest(G);else q=R.tuple(J);if(typeof $.minItems==="number")q=q.check(R.minLength($.minItems));if(typeof $.maxItems==="number")q=q.check(R.maxLength($.maxItems))}else if(W!==void 0){let J=_$(W,U),G=R.array(J);if(typeof $.minItems==="number")G=G.min($.minItems);if(typeof $.maxItems==="number")G=G.max($.maxItems);q=G}else q=R.array(R.any());break}default:throw Error(`Unsupported type: ${Q}`)}if($.description)q=q.describe($.description);if($.default!==void 0)q=q.default($.default);return q}function _$($,U){if(typeof $==="boolean")return $?R.any():R.never();let Q=MY($,U),q=$.type||$.enum!==void 0||$.const!==void 0;if($.anyOf&&Array.isArray($.anyOf)){let G=$.anyOf.map((H)=>_$(H,U)),Y=R.union(G);Q=q?R.intersection(Q,Y):Y}if($.oneOf&&Array.isArray($.oneOf)){let G=$.oneOf.map((H)=>_$(H,U)),Y=R.xor(G);Q=q?R.intersection(Q,Y):Y}if($.allOf&&Array.isArray($.allOf))if($.allOf.length===0)Q=q?Q:R.any();else{let G=q?Q:_$($.allOf[0],U),Y=q?0:1;for(let H=Y;H<$.allOf.length;H++)G=R.intersection(G,_$($.allOf[H],U));Q=G}if($.nullable===!0&&U.version==="openapi-3.0")Q=R.nullable(Q);if($.readOnly===!0)Q=R.readonly(Q);let K={},W=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let G of W)if(G in $)K[G]=$[G];let J=["contentEncoding","contentMediaType","contentSchema"];for(let G of J)if(G in $)K[G]=$[G];for(let G of Object.keys($))if(!qI.has(G))K[G]=$[G];if(Object.keys(K).length>0)U.registry.add(Q,K);return Q}function VY($,U){if(typeof $==="boolean")return $?R.any():R.never();let Q=WI($,U?.defaultTarget),q=$.$defs||$.definitions||{},K={version:Q,defs:q,refs:new Map,processing:new Set,rootSchema:$,registry:U?.registry??P$};return _$($,K)}var HQ={};q1(HQ,{string:()=>GI,number:()=>jI,date:()=>XI,boolean:()=>YI,bigint:()=>HI});function GI($){return S7(n4,$)}function jI($){return m7(o4,$)}function YI($){return d7(d4,$)}function HI($){return t7(p4,$)}function XI($){return G5(i6,$)}H$(S6());var XQ=j.enum(["pending","synced","failed"]),BQ=j.object({}).default({}),ZQ=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),waba_id:j.string().optional(),business_name:j.string().optional(),display_phone_number:j.string().optional(),webhook_sync_status:XQ.default("pending"),webhook_sync_error:j.string().optional(),webhook_synced_at:j.iso.datetime().optional(),webhook_callback_url: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()}),MQ=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()}),DY={sip:BQ,telegram:MQ,whatsapp:ZQ,webchat:j.object({}).default({}),sms:j.object({}).default({}),rcs:j.object({}).default({})};var t4=["sip"],s6=["telegram","webchat","sms","rcs"],a4=["whatsapp"],VQ=[...t4,...s6,...a4],NY=[...t4,...a4],PY=[...s6,...a4];var yR=new Set(t4),uR=new Set(a4);var IY=String.raw`(?:25[0-5]|2[0-4]\d|[01]?\d\d?)`,_Y=String.raw`(?:${IY}\.){3}${IY}`,ZI=String.raw`${_Y}(?:\/(?:3[0-2]|[12]?\d))?`,nR=new RegExp(`^${_Y}$`);var L$="[0-9a-fA-F]{1,4}",MI=[`(?:${L$}:){7}${L$}`,`(?:${L$}:){1,7}:`,`(?:${L$}:){1,6}:${L$}`,`(?:${L$}:){1,5}(?::${L$}){1,2}`,`(?:${L$}:){1,4}(?::${L$}){1,3}`,`(?:${L$}:){1,3}(?::${L$}){1,4}`,`(?:${L$}:){1,2}(?::${L$}){1,5}`,`${L$}:(?::${L$}){1,6}`,`:(?::${L$}){1,7}`,"::(?:ffff(?::0{1,4})?:)?"],VI=`(?:${MI.join("|")})`,DI=String.raw`${VI}(?:\/(?:12[0-8]|1[01]\d|[1-9]?\d))?`,iR=new RegExp(`^(?:${ZI}|${DI})$`);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 Q;if(!("nodes"in U))Q="missing";else if(Array.isArray(U.nodes))Q="an array";else Q=typeof U.nodes;throw Error(`Execution plan "nodes" must be an object keyed by node ID, not ${Q}`)}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 DQ($){NI($);let U=Object.entries($.nodes).map(([q,K])=>({id:q,type:K.type,label:K.label,varName:K.varName,position:{x:0,y:0},config:K.config})),Q=[];for(let[q,K]of Object.entries($.adjacency))for(let[W,J]of Object.entries(K))Q.push({id:`${q}-${W}-${J}`,source:q,sourceHandle:W,target:J,targetHandle:"in"});return LY({nodes:U,edges:Q,viewport:{x:0,y:0,zoom:1}})}function LY($){let U=$.nodes.find((K)=>K.type==="start");if(U==null||typeof U.config.channelType==="string")return $;let q=$.edges.some((K)=>K.source===U.id&&K.sourceHandle==="next")?"voice":"both";return{...$,nodes:$.nodes.map((K)=>K===U?{...K,config:{...K.config,channelType:q}}:K)}}var G4=3600;var Z1=["none","both","caller"],NQ=j.object({callerSpeechMs:j.number().int().min(0),ivrSpeechMs:j.number().int().min(0),version:j.number().int().min(1)});var T1=["post_call","live"],PQ=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"]}),FY=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())}),vY=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(G4).describe("Minimum transcription duration"),transcriptionSpeechRequirement:j.enum(Z1).default("none").describe("Which sides must have spoken for automatic transcription"),transcriptionType:j.enum(T1).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"),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")}),PI=j.object({speechAnalyticsEnabled:j.boolean(),topicDetectionTopics:j.array(j.string()),intentDetectionIntents:j.array(j.string()),autoAnalysisEnabled:j.boolean(),autoAnalysisIds:j.array(j.string())});var II=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(G4).default(0).describe("Minimum transcription duration"),transcriptionSpeechRequirement:j.enum(Z1).default("none").describe("Which sides must have spoken for automatic transcription"),transcriptionType:j.enum(T1).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"),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")}),zY=j.object({sampleRate:j.number().int().positive(),channels:j.number().int().positive(),bitsPerSample:j.number().int().positive()});var _I=j.object({sampled:j.boolean(),transcriptionSampled:j.boolean().optional(),profile:vY,recordingFormat:zY.optional(),recordingIntervals:PQ.array().default([]),transcriptionWindows:PQ.array().default([]),directives:FY.array().default([]),voiceActivity:NQ.optional()});var LI=["recordingEnabled","samplingPercentage","transcriptionSamplingPercentage","transcriptionEnabled","transcriptionLanguage","transcriptionMinDurationSeconds","transcriptionSpeechRequirement","transcriptionType","anonymizeEnabled","speechAnalyticsEnabled","topicDetectionTopics","intentDetectionIntents","structuredAnalysisEnabled","structuredAnalysisIds"];function _Q($,U,Q,q,K=!1){let W=FI(q),J=new Map(Q.map((H)=>[H.id,H])),G=xI(U,K),Y={};return vI({startNodeId:$,planState:G,nodesById:J,adjacency:q,incoming:W,result:Y}),Y}function FI($){let U=new Map;for(let[Q,q]of $)for(let K of q.values()){let W=U.get(K)??[];U.set(K,[...W,Q])}return U}function vI($){let{startNodeId:U,planState:Q,nodesById:q,adjacency:K,incoming:W,result:J}=$,G=[U],Y=new Set(G),H=0,B=Math.max(20,q.size*q.size*4);while(G.length>0&&H++<B){let M=G.shift();if(M===void 0)continue;Y.delete(M);let V=q.get(M);if(V===void 0)continue;let L=zI(M,Q,V,W,J);if(fI(J[M],L))continue;J[M]=L,wI(G,Y,K.get(M)?.values()??[])}}function zI($,U,Q,q,K){let W=(q.get($)??[]).map((G)=>K[G]).filter((G)=>G!==void 0),J=kI(W,U);return AI(J,Q)}function kI($,U){let Q=$[0];return Q===void 0?U:$.slice(1).reduce((q,K)=>yI(q,K),Q)}function wI($,U,Q){for(let q of Q){if(U.has(q))continue;$.push(q),U.add(q)}}function xI($,U){let Q={kind:"plan"};return{recordingEnabled:F$(U,Q),samplingPercentage:F$($.samplingPercentage,Q),transcriptionSamplingPercentage:F$($.transcriptionSamplingPercentage,Q),transcriptionEnabled:F$($.transcriptionEnabled,Q),transcriptionLanguage:F$($.transcriptionLanguage,Q),transcriptionMinDurationSeconds:F$($.transcriptionMinDurationSeconds,Q),transcriptionSpeechRequirement:F$($.transcriptionSpeechRequirement,Q),transcriptionType:F$($.transcriptionType,Q),anonymizeEnabled:F$($.anonymizeEnabled,Q),speechAnalyticsEnabled:F$($.speechAnalyticsEnabled,Q),topicDetectionTopics:F$([...$.topicDetectionTopics],Q),intentDetectionIntents:F$([...$.intentDetectionIntents],Q),structuredAnalysisEnabled:F$($.autoAnalysisEnabled,Q),structuredAnalysisIds:F$([...$.autoAnalysisIds],Q)}}function AI($,U){let Q=bI(U),q={kind:"node",nodeId:U.id,nodeLabel:U.label};return{recordingEnabled:T$($.recordingEnabled,Q.recordingEnabled,q),samplingPercentage:T$($.samplingPercentage,Q.samplingPercentage,q),transcriptionSamplingPercentage:T$($.transcriptionSamplingPercentage,Q.transcriptionSamplingPercentage,q),transcriptionEnabled:T$($.transcriptionEnabled,Q.transcriptionEnabled,q),transcriptionLanguage:T$($.transcriptionLanguage,Q.transcriptionLanguage,q),transcriptionMinDurationSeconds:T$($.transcriptionMinDurationSeconds,Q.transcriptionMinDurationSeconds,q),transcriptionSpeechRequirement:T$($.transcriptionSpeechRequirement,Q.transcriptionSpeechRequirement,q),transcriptionType:T$($.transcriptionType,Q.transcriptionType,q),anonymizeEnabled:T$($.anonymizeEnabled,Q.anonymizeEnabled,q),speechAnalyticsEnabled:T$($.speechAnalyticsEnabled,Q.speechAnalyticsEnabled,q),topicDetectionTopics:T$($.topicDetectionTopics,Q.topicDetectionTopics,q),intentDetectionIntents:T$($.intentDetectionIntents,Q.intentDetectionIntents,q),structuredAnalysisEnabled:T$($.structuredAnalysisEnabled,Q.structuredAnalysisEnabled,q),structuredAnalysisIds:T$($.structuredAnalysisIds,Q.structuredAnalysisIds,q)}}function bI($){if($.type==="recording")return OI($.config);if($.type==="transcription")return RI($.config);if($.type==="analysis")return TI($.config);return{}}function OI($){let U={},Q=$.enabled;if(typeof Q==="boolean")U.recordingEnabled=Q;let q=$.samplingPercentage;if(typeof q==="number")U.samplingPercentage=q;return U}function RI($){let U={},Q=$.enabled;if(typeof Q==="boolean")U.transcriptionEnabled=Q;let q=$.samplingPercentage;if(typeof q==="number")U.transcriptionSamplingPercentage=q;let K=$.language;if(typeof K==="string")U.transcriptionLanguage=K.trim()||null;let W=$.minDurationSeconds;if(typeof W==="number")U.transcriptionMinDurationSeconds=W;let J=$.speechRequirement;if(CI(J))U.transcriptionSpeechRequirement=J;let G=$.transcriptionType;if(gI(G))U.transcriptionType=G;let Y=$.anonymizeEnabled;if(typeof Y==="boolean")U.anonymizeEnabled=Y;return U}function TI($){let U={},Q=$.speechAnalyticsEnabled;if(typeof Q==="boolean")U.speechAnalyticsEnabled=Q;let q=$.topicDetectionTopics;if(IQ(q))U.topicDetectionTopics=q;let K=$.intentDetectionIntents;if(IQ(K))U.intentDetectionIntents=K;let W=$.structuredAnalysisEnabled;if(typeof W==="boolean")U.structuredAnalysisEnabled=W;let J=$.structuredAnalysisIds;if(IQ(J))U.structuredAnalysisIds=J;return U}var SI=Z1;function CI($){return typeof $==="string"&&SI.includes($)}var EI=T1;function gI($){return typeof $==="string"&&EI.includes($)}function IQ($){return Array.isArray($)&&$.every((U)=>typeof U==="string")}function T$($,U,Q){return U===void 0?$:F$(U,Q)}function F$($,U){return{kind:"known",value:$,origin:U}}function yI($,U){return{recordingEnabled:S$($.recordingEnabled,U.recordingEnabled),samplingPercentage:S$($.samplingPercentage,U.samplingPercentage),transcriptionSamplingPercentage:S$($.transcriptionSamplingPercentage,U.transcriptionSamplingPercentage),transcriptionEnabled:S$($.transcriptionEnabled,U.transcriptionEnabled),transcriptionLanguage:S$($.transcriptionLanguage,U.transcriptionLanguage),transcriptionMinDurationSeconds:S$($.transcriptionMinDurationSeconds,U.transcriptionMinDurationSeconds),transcriptionSpeechRequirement:S$($.transcriptionSpeechRequirement,U.transcriptionSpeechRequirement),transcriptionType:S$($.transcriptionType,U.transcriptionType),anonymizeEnabled:S$($.anonymizeEnabled,U.anonymizeEnabled),speechAnalyticsEnabled:S$($.speechAnalyticsEnabled,U.speechAnalyticsEnabled),topicDetectionTopics:S$($.topicDetectionTopics,U.topicDetectionTopics),intentDetectionIntents:S$($.intentDetectionIntents,U.intentDetectionIntents),structuredAnalysisEnabled:S$($.structuredAnalysisEnabled,U.structuredAnalysisEnabled),structuredAnalysisIds:S$($.structuredAnalysisIds,U.structuredAnalysisIds)}}function S$($,U){let Q=[...kY($),...kY(U)],q=[];for(let K of Q)if(!q.some((W)=>wY(W.value,K.value)))q.push(K);if(q.length===1){let K=uI($,U,q[0].viaNodeLabel);return F$(q[0].value,K)}return{kind:"indeterminate",branches:q}}function uI($,U,Q){if($.kind==="known")return $.origin;if(U.kind==="known")return U.origin;return{kind:"node",nodeId:"",nodeLabel:Q}}function kY($){if($.kind==="indeterminate")return $.branches;let U=$.origin.kind==="plan"?"__plan__":$.origin.nodeLabel;return[{value:$.value,viaNodeLabel:U}]}function wY($,U){return JSON.stringify($)===JSON.stringify(U)}function fI($,U){if($===void 0)return!1;return LI.every((Q)=>wY($[Q],U[Q]))}function g($){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 hI=j.object({id:j.string(),type:j.string(),x:j.number(),y:j.number()}),mI=j.object({source:j.string(),target:j.string()}),cI=j.object({nodes:j.array(hI),edges:j.array(mI)});var xY=["voice","chat","both"];var AY=["pre","post"];var bY=["voicemail","announcement","ivr","screening","unknown"];var e6=["channels","calls","registrations","codecs","modules","aliases"];var lI=new Set(["phone","telephone","telefone","fone","celular","cel","mobile","movel","numero","number","num","tel","msisdn","whatsapp","telefone celular","numero de telefone"]),rI=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 iI($){return $.normalize("NFD").replaceAll(/[\u0300-\u036F]/g,"").toLowerCase().replaceAll(/[^a-z0-9]+/g,"_").replace(/^_/,"").replace(/_$/,"")}function OY($){return lI.has($)||$.includes("telefone")||$.includes("phone")||$.includes("celular")}function oI($){return rI.has($)}function LQ($){let U={},Q={},q=new Set,K=!1,W=!1;function J(G){let Y=G,H=2;while(q.has(Y))Y=`${G}_${String(H)}`,H+=1;return q.add(Y),Y}for(let G of $){let Y=nI(G);if(Y===""){U[G]="ignore";continue}if(OY(Y)&&!K){U[G]="phone",K=!0;continue}if(oI(Y)&&!W&&!OY(Y)){U[G]="name",W=!0;continue}let H=iI(G);if(H===""){U[G]="ignore";continue}U[G]="custom",Q[G]=J(H)}return{roles:U,customNames:Q}}var j4={_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"},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"},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."},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",transcriptionType:"Transcription type: 'post_call' transcribes when the call ends; 'live' also transcribes during the call, billed per recorded minute"},analysis:{speechAnalyticsEnabled:"Enable speech analytics 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"},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 j8={_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"},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"},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."},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",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 análise de fala 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"},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 dI={en:j4,"pt-BR":j8};function FQ($,U="en"){return dI[U]._nodes?.[$]}function Y4($,U){return typeof $.outputs==="function"?$.outputs(U):$.outputs}var RY={interaction:{order:0},handling:{order:1},routing:{order:2},media:{order:3},data:{order:4},legacy:{order:5}},pI=Object.entries(RY).sort(([,$],[,U])=>$.order-U.order).map(([$])=>$);var vQ=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).")}),zQ=g({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:vQ,producedVariables:[{name:"dnc_added",type:"string",descriptionKey:"editor:vars.dncAdded"},{name:"dnc_phone",type:"string",descriptionKey:"editor:vars.dncPhone"}]});var kQ=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.")}),wQ=g({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:kQ,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 xQ=j.string().min(1).max(255).regex(/^[A-Za-z0-9_-]+$/,{error:"Invalid structured analysis id"});var AQ=j.object({speechAnalyticsEnabled:j.boolean().optional(),topicDetectionTopics:j.array(j.string()).optional(),intentDetectionIntents:j.array(j.string()).optional(),structuredAnalysisEnabled:j.boolean().optional(),structuredAnalysisIds:j.array(xQ).max(100).optional()}),bQ=g({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:AQ,producedVariables:[{name:"selected",type:"number",descriptionKey:"editor:vars.analysisSelected"}]});var sI=/\{\{[^{}]*\}\}/g,eI=/^\{\{[^{}]*\}\}$/,$_=new Set(["http:","https:"]);function TY($){if(!URL.canParse($))return!1;return $_.has(new URL($).protocol)}function SY($){let U=$.trim();if(U==="")return"empty";if(eI.test(U))return"from-variable";let Q=0,q=U.replaceAll(sI,()=>{return Q+=1,`v${Q}`});return TY(q)?"valid":"malformed"}function OQ($){return SY($)!=="malformed"}var CY=["postgres","redis","freeswitch","engine","server"],pT=new Set(CY);var RQ=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:RQ.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(OQ,{error:"editor:validation.malformedAudioUrl"}).describe("Audio URL fetched at call time. Supports {{variables}}; secrets are not allowed."),fallbackTts:RQ.optional().describe("Spoken when the URL fails. Absent means take the error output.")}).describe("Remote audio source fetched at call time.")})]),U_=J$.optional().catch(void 0);var s4=j.string().refine(($)=>$.trim()!=="",{error:"editor:validation.urlRequired"}).refine(($)=>!/\s/.test($.trim()),{error:"editor:validation.urlHasSpace"}).default("");var K_=j.object({value:j.string().min(1,{error:"editor:validation.caseValueRequired"}).default("").describe("Attribute value to match. Creates a 'match:<value>' output.")}),TQ=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:s4.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(K_).default([]).describe("Possible attribute values. Each creates a dynamic output handle 'match:<value>'.")}),SQ=g({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:TQ,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 Q_=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.")}),CQ=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:Q_.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}}.")}),EQ=g({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:CQ,producedVariables:[{name:"text",type:"string",descriptionKey:"editor:vars.capturedText"},{name:"attempts",type:"number",descriptionKey:"editor:vars.captureAttempts"}]});var gQ=j.object({}),yQ=g({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:gQ,producedVariables:[{name:"channelType",type:"string",descriptionKey:"editor:vars.channelType"}]});var uQ=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.")}),fQ=g({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:uQ,producedVariables:[{name:"digits",type:"string",descriptionKey:"editor:vars.collectedDigits"},{name:"attempts",type:"number",descriptionKey:"editor:vars.collectAttempts"}]});var hQ=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.")}),mQ=g({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:hQ,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 uS=new Intl.NumberFormat("en-US",{useGrouping:!1,maximumFractionDigits:10});var Y8="secrets",G_="secrets".replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);function EY(){return new RegExp(String.raw`\{\{\s*${G_}\.([A-Z][A-Z0-9_]*)\s*\}\}`,"g")}function gY($){if(!$.includes("{{"))return[];let U=new Set;for(let Q of $.matchAll(EY()))U.add(Q[1]);return[...U]}var yY={httpRequest:new Set(["url","headers","body"]),apiSwitch:new Set(["url","headers","body"]),webhook:new Set(["url","headers","body"])};function uY($,U){return yY[$]?.has(U)===!0}function cQ($,U,Q){if(typeof $==="string"){Q(U,$);return}if(Array.isArray($)){$.forEach((q,K)=>cQ(q,`${U}.${K}`,Q));return}if($!=null&&typeof $==="object")for(let[q,K]of Object.entries($))cQ(K,U===""?q:`${U}.${q}`,Q)}function H8($){let U=new Set,Q=[];return cQ($.config,"",(q,K)=>{let W=gY(K);if(W.length===0)return;let J=q.split(".")[0]??"";if(uY($.type,J)){for(let G of W)U.add(G);return}for(let G of W)Q.push({nodeId:$.id,label:$.label,field:q,name:G})}),{allowed:[...U],misplaced:Q}}function X8($){let U=new Set,Q=[];for(let q of $){let K=H8(q);for(let W of K.allowed)U.add(W);for(let W of K.misplaced)U.add(W.name),Q.push(W)}return{names:U,misplaced:Q}}var j_=/\{\{(.+?)\}\}/g;function lQ(){return/"?\{\{.+?\}\}"?/g}var B8=200;function fY($,U){let Q=$[U];if(Q==="*"||Q==="+")return 1;if(Q==="{"){let q=$.indexOf("}",U);if(q!==-1&&/^\d+,$/.test($.slice(U+1,q)))return q-U+1}return 0}function Y_($,U){let Q=U+1;while(Q<$.length&&$[Q]!=="]")Q+=$[Q]==="\\"?2:1;return Q+1}function H_($,U,Q){let q=Q.pop()??{repeat:!1},K=fY($,U+1);if(K>0&&q.repeat)return{catastrophic:!0,next:U};if((q.repeat||K>0)&&Q.length>0)Q.at(-1).repeat=!0;return{catastrophic:!1,next:U+(K>0?1+K:1)}}function X_($,U,Q){let q=$[U];if(q==="\\")return{catastrophic:!1,next:U+2};if(q==="[")return{catastrophic:!1,next:Y_($,U)};if(q==="(")return Q.push({repeat:!1}),{catastrophic:!1,next:U+1};if(q===")")return H_($,U,Q);let K=fY($,U);if(K>0&&Q.length>0)Q.at(-1).repeat=!0;return{catastrophic:!1,next:U+(K>0?K:1)}}function rQ($){let U=[],Q=0;while(Q<$.length){let{catastrophic:q,next:K}=X_($,Q,U);if(q)return!0;Q=K}return!1}function B_($){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 nQ($){if(!$.includes("{{"))return{valid:!0};for(let U of $.matchAll(j_)){let Q=B_(U[1].trim());if(Q===null)continue;if(Q.pattern.length>B8)return{valid:!1,error:`Regex pattern too long in "${U[0]}" (max ${B8})`};if(rQ(Q.pattern))return{valid:!1,error:`Unsafe regex (possible catastrophic backtracking) in "${U[0]}"`};try{new RegExp(Q.pattern)}catch(q){let K=q instanceof Error?q.message:String(q);return{valid:!1,error:`Invalid regex in "${U[0]}": ${K}`}}}return{valid:!0}}var hY={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 F_=new Set(["error_code","error_message","error_step","error_var"]),v_=j.string().refine(($)=>$.trim()!=="",{error:"editor:validation.emptySaveAs"}).refine(($)=>!F_.has($.trim()),{error:"editor:validation.reservedSaveAs"}).describe("Name the result is saved under. Readable by later steps and by other nodes."),q$=($)=>j.literal($).describe("Operation this step applies to the source."),mY=j.enum(["minutes","hours","days","months","years"]).describe("Time unit used by the step: minutes, hours, days, months, or years."),W$=j.object({source:j.string().describe("Value the step transforms. Literal text or a template like '{{start.callerid}}'."),saveAs:v_}),z_=j.discriminatedUnion("op",[W$.extend({op:q$("uppercase")}),W$.extend({op:q$("lowercase")}),W$.extend({op:q$("capitalize")}),W$.extend({op:q$("trim")}),W$.extend({op:q$("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.")}),W$.extend({op:q$("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'.")}),W$.extend({op:q$("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.")}),W$.extend({op:q$("add"),operand:j.string().describe("Number added to the source. Literal value or template.")}),W$.extend({op:q$("subtract"),operand:j.string().describe("Number subtracted from the source. Literal value or template.")}),W$.extend({op:q$("multiply"),operand:j.string().describe("Number the source is multiplied by. Literal value or template.")}),W$.extend({op:q$("divide"),operand:j.string().describe("Number the source is divided by. Literal value or template. Zero fails with 'divide_by_zero'.")}),W$.extend({op:q$("round"),decimals:j.number().int().min(0).max(10).default(0).describe("Decimal places to keep (0-10). Rounds half away from zero.")}),W$.extend({op:q$("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'.")}),W$.extend({op:q$("dateOffset"),amount:j.number().int().describe("How many units to add to the date. Negative subtracts."),unit:mY}),W$.extend({op:q$("dateDiff"),operand:j.string().describe("Date compared against the source. The result is operand minus source. Literal or template."),unit:mY}),W$.extend({op:q$("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'.")}),W$.extend({op:q$("normalizePhone"),country:j.string().default("BR").describe("ISO 3166-1 alpha-2 country code used for national numbers. Defaults to 'BR'.")}),W$.extend({op:q$("count")}),W$.extend({op:q$("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.")}),W$.extend({op:q$("item"),index:j.number().int().describe("Zero-based index of the item to keep. Negative counts from the end.")}),W$.extend({op:q$("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.")}),W$.extend({op:q$("spellOut")}),W$.extend({op:q$("inWords")}),W$.extend({op:q$("default"),operand:j.string().describe("Value used when the source is empty. Literal value or template.")})]),iQ=j.object({steps:j.array(z_).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.")}),oQ=g({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:iQ,producedVariables:($)=>{let U=new Map;for(let Q of $.steps){if(Q.saveAs==="")continue;U.set(Q.saveAs,{name:Q.saveAs,type:hY[Q.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 dQ=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).")}),pQ=g({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:dQ,producedVariables:[{name:"recording",type:"string",descriptionKey:"editor:vars.recordingStatus"}]});var tQ=j.object({cause:j.string().optional().describe("SIP hangup cause code (e.g., 'NORMAL_CLEARING'). Omit for default.")}),aQ=g({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:tQ,producedVariables:[]});var sQ=j.object({method:j.enum(["GET","POST","PUT","PATCH","DELETE"]).default("GET").describe("HTTP method for the request."),url:s4.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.")}),eQ=g({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:sQ,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 $q=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=g({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:$q,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 Kq=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.")}),Qq=j.object({options:j.array(Kq).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.")}),qq=g({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:Qq,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 Wq=j.object({audio:J$.default({tts:{text:""}}).describe("Audio to play. Use TTS (text-to-speech) or a pre-recorded audio file.")}),Jq=g({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:Wq,producedVariables:[]});var Gq=j.object({enabled:j.boolean().optional(),samplingPercentage:j.number().int().min(0).max(100).optional()}),jq=g({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:Gq,producedVariables:[{name:"status",type:"string",descriptionKey:"editor:vars.recordingStatus"}]});var k_=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.")}),Yq=j.object({input:j.string().default("").describe("Template expression to evaluate, e.g. '{{resposta}}'. The resolved text is classified by AI."),intents:j.array(k_).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.")}),Hq=g({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:Yq,producedVariables:[{name:"intent",type:"string",descriptionKey:"editor:vars.routeAi.intent"},{name:"confidence",type:"number",descriptionKey:"editor:vars.routeAi.confidence"}]});var Xq=j.object({digits:j.string().min(1,{error:"editor:validation.digitsRequired"}).default("").describe("DTMF digits to send (0-9, *, #). Supports template expressions.")}),Bq=g({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:Xq,producedVariables:[{name:"dtmf",type:"string",descriptionKey:"editor:vars.dtmf"}]});var Zq=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.")}),Mq=g({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:Zq,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 w_=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}}'.")}),Vq=j.object({assignments:j.array(w_).min(1,{error:"editor:validation.noAssignments"}).default([]).describe("List of variable assignments. At least one required.")}),Dq=g({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:Vq,producedVariables:($)=>$.assignments.map((U)=>({name:U.key,type:"string",descriptionKey:"editor:vars.custom"}))});var Nq=j.object({autoAnswer:j.boolean().optional().describe("Auto-answer incoming call before processing. Disable for pre-answer routing."),channelType:j.enum(xY).default("both").describe("Plan channel type.")}),Pq=g({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:Nq,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 Iq=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.")}),_q=g({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:Iq,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 x_=j.object({pattern:j.string().min(1,{error:"editor:validation.casePatternRequired"}).default("").describe("Value to match against the expression. Creates a 'match:<pattern>' output.")}),Lq=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(x_).default([]).describe("List of patterns to match. Each creates a dynamic output handle 'match:<pattern>'.")}),Fq=g({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:Lq,producedVariables:[{name:"destination",type:"string",descriptionKey:"editor:vars.switchDestination"}]});var A_=j.object({type:j.literal("text"),text:j.string().min(1)}),b_=j.object({type:j.literal("media"),mediaType:j.enum(["image","audio","video","document"]),url:j.string().min(1),caption:j.string().optional()}),O_=j.object({type:j.literal("location"),lat:j.number(),lng:j.number()}),R_=j.object({type:j.literal("button_reply"),buttonId:j.string().min(1),buttonText:j.string()}),T_=j.object({type:j.literal("list_reply"),listId:j.string().min(1),listTitle:j.string()}),S_=j.object({type:j.literal("command"),command:j.string().min(1),args:j.string().optional()}),vq=j.discriminatedUnion("type",[A_,b_,O_,R_,T_,S_]),zq=j.object({id:j.string().min(1),label:j.string().min(1)}),C_=j.object({id:j.string().min(1),title:j.string().min(1),description:j.string().optional()}),cY=j.object({title:j.string().min(1),items:j.array(C_).min(1)}),lY=j.object({title:j.string().min(1),description:j.string().optional(),imageUrl:j.string().optional(),buttons:j.array(zq).default([])}),E_=j.object({type:j.literal("text"),text:j.string().min(1),markdown:j.boolean().optional()}),g_=j.object({type:j.literal("media"),mediaType:j.enum(["image","audio","video","document"]),url:j.string().min(1),caption:j.string().optional()}),y_=j.object({type:j.literal("location"),lat:j.number(),lng:j.number(),label:j.string().optional()}),u_=j.object({type:j.literal("buttons"),text:j.string().min(1),buttons:j.array(zq).min(1)}),f_=j.object({type:j.literal("list"),text:j.string().min(1),buttonText:j.string().min(1),sections:j.array(cY).min(1)}),h_=j.object({type:j.literal("carousel"),cards:j.array(lY).min(1)}),m_=j.object({type:j.literal("template"),templateId:j.string().min(1),params:j.record(j.string(),j.string()).default({})}),e4=j.discriminatedUnion("type",[E_,g_,y_,u_,f_,h_,m_]),c_=e4.optional().catch(void 0);var kq=j.object({audio:J$.optional().describe("Audio to play via TTS, a pre-recorded file, or a remote URL. Used in voice plans."),content:e4.optional().describe("Message content to send in chat. Used in chat plans.")});function rY($){return typeof $==="object"&&$!==null&&"url"in $}var wq=g({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:($)=>rY($.audio)?[{key:"next",labelKey:"editor:handles.next"},{key:"error",labelKey:"editor:handles.error"}]:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:kq,producedVariables:($)=>rY($.audio)?[{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"}]:[]});var xq=j.object({scheduleId:j.string().optional().describe("Schedule ID for time-based routing. Routes to onHours/offHours/holiday outputs.")}),Aq=g({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:xq,producedVariables:[{name:"result",type:"string",descriptionKey:"editor:vars.timeResult"},{name:"holiday",type:"string",descriptionKey:"editor:vars.holiday"}]});var bq=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.")}),Oq=j.object({paths:j.array(bq).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.")}),Rq=g({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??[],Q=[],q=new Set;for(let K of U){let W=typeof K==="object"&&K!=null?K.name:void 0;if(typeof W!=="string"||W===""||q.has(W))continue;q.add(W),Q.push(W)}return[...Q.map((K)=>({key:`path:${K}`,labelKey:K})),{key:"error",labelKey:"editor:handles.error"}]}},configSchema:Oq,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 Tq=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(G4).optional(),speechRequirement:j.enum(Z1).optional(),anonymizeEnabled:j.boolean().optional(),transcriptionType:j.enum(T1).optional()}),Sq=g({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:Tq,producedVariables:[{name:"status",type:"string",descriptionKey:"editor:vars.transcriptionStatus"}]});var l_=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}}'.")}),Cq=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(l_).default([]).describe("Key/value pairs delivered to the agent at transfer time (screen-pop). Values support templates.").superRefine(($,U)=>{let Q=new Set;$.forEach((q,K)=>{let W=q.key.trim();if(W===""){U.addIssue({code:"custom",message:"editor:validation.attachedKeyRequired",path:[K,"key"]});return}if(Q.has(W))U.addIssue({code:"custom",message:"editor:validation.duplicateAttachedKey",path:[K,"key"]});Q.add(W)})})}),Eq=g({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:Cq,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 r_=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.")}),n_=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.")}),i_=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 gq=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(r_).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:n_.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:i_.default({max_retries:2}).describe("Retry behavior when speech is not recognized.")}),yq=g({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((K)=>typeof K==="string"?K:K.label).filter((K)=>typeof K==="string"&&K!=="").map((K)=>({key:`intent:${K}`,labelKey:K})),{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:gq,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 uq=j.object({method:j.enum(["POST","PUT","PATCH","GET","DELETE"]).default("POST").describe("HTTP method for the request."),url:s4.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.")}),fq=g({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:uq,producedVariables:[]});var n$={start:Pq,playback:Jq,ivr:Uq,collectDigits:fQ,transfer:Eq,hangup:aQ,timeRouting:Aq,switchCase:Fq,trafficSplit:Rq,setVariable:Dq,sequence:Mq,counter:mQ,httpRequest:eQ,webhook:fq,dataTransform:oQ,subPlan:_q,sendDtmf:Bq,aiAgent:wQ,voiceRecognition:yq,tell:wq,menu:qq,capture:EQ,routeAi:Hq,channelRouter:yQ,addToDnc:zQ,apiSwitch:SQ,enableRecord:pQ,recording:jq,transcription:Sq,analysis:bQ},C1=Object.fromEntries(Object.entries(n$).map(([$,U])=>[$,U.meta]));var Vy=Number.MAX_SAFE_INTEGER;var hq=["active","expired","suspended","poc"],nY=j.object({enabled:j.boolean(),limits:j.record(j.string(),j.union([j.number(),j.string(),j.boolean(),j.array(j.string())])).default({})}),UL=j.object({customerId:j.string(),customerName:j.string().optional(),serial:j.string(),status:j.enum(hq),issuedAt:j.coerce.date(),expiresAt:j.coerce.date().nullable(),gracePeriodDays:j.number().int().min(0),modules:j.record(j.string(),nY),isExpired:j.boolean(),isInGracePeriod:j.boolean(),daysUntilExpiry:j.number().nullable()}),KL=j.object({voice:j.number().int().default(0),chat:j.number().int().default(0)}).optional(),QL=j.object({customer_id:j.string().min(1),customer_name:j.string().min(1).optional(),serial:j.string().min(1),status:j.enum(hq),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:KL,modules:j.record(j.string(),nY)});var $6=["yes_no","choice","scale"],iY=["caller","agent","both"],U6=["info","warning","critical"],qL=/^[a-z][a-z0-9_]{0,63}$/,WL=/^[a-z0-9][a-z0-9_]{0,47}$/,oY=j.object({key:j.string().regex(WL),label:j.string().min(1).max(80),description:j.string().max(240).optional(),archived:j.boolean().default(!1)}),JL=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()})]),GL=j.object({when:JL,severity:j.enum(U6),bell:j.boolean().default(!1)}),jL=j.object({slug:j.string().regex(qL),name:j.string().trim().min(1).max(80),question:j.string().trim().min(1).max(500),kind:j.enum($6),options:j.array(oY).min(2).max(12).optional(),levels:j.array(j.string().min(1).max(40)).min(3).max(5).optional(),speaker:j.enum(iY),scope:j.object({node_types:j.array(j.string().min(1)).min(1).max(20)}).nullable(),live:j.boolean(),alert:GL.nullable()});function YL($,U){if($.kind==="choice"){if($.options===void 0){U.addIssue({code:"custom",message:"signals:validation.optionsRequired",path:["options"]});return}let Q=$.options.map((q)=>q.key);if(new Set(Q).size!==Q.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 HL($,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"]})}function XL($){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((Q)=>$.options?.some((q)=>q.key===Q&&!q.archived)===!0);case"scale":return"level_at_least"in U&&$.levels!==void 0&&Number.isInteger(U.level_at_least)&&U.level_at_least>=1&&U.level_at_least<=$.levels.length-1}}function dY($,U){if(YL($,U),HL($,U),!XL($))U.addIssue({code:"custom",message:"signals:validation.whenMustMatchKind",path:["alert","when"]})}var K6=jL.superRefine(dY);var Z8=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()}),aY={signal:j.object({id:j.string().min(1),slug:j.string().min(1),name:j.string(),kind:j.enum($6),severity:j.enum(U6).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()},M8=j.object({type:j.literal("signal_value"),...aY}),V8=j.object({type:j.literal("signal_triggered"),...aY}),sY=j.discriminatedUnion("type",[M8,V8]),ZL=j.discriminatedUnion("type",[j.object({type:j.literal("segment"),segment:Z8}),M8,V8,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()})]),ML=j.discriminatedUnion("type",[j.object({type:j.literal("segment"),segment:Z8}),j.object({type:j.literal("history"),segments:j.array(Z8),signals:j.array(sY).optional()}),M8,V8,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"])})]),VL=j.object({uuid:j.string(),action:j.enum(["start","stop"])}),eY=["not_live","provider_error","drain_timeout","redact_mid_call"],$H=j.object({startByte:j.number().int().min(0),endByte:j.number().int().min(0)}),DL=j.object({complete:j.boolean(),reason:j.enum(eY).optional(),model:j.string(),redact:j.boolean(),coveredRanges:j.array($H)});var UH="urn:ietf:params:oauth:grant-type:device_code",KH=["authorization_code","refresh_token",UH],mq="ABCDEFGHJKLMNPQRSTUVWXYZ",NL=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()}),PL=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())}),IL=j.string().refine(($)=>{try{return new URL($).protocol==="https:"}catch{return!1}},"must be an https URL"),_L=j.object({client_id:IL,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(LL,{error:'client must support the "none" token endpoint auth method',path:["token_endpoint_auth_method"]});function LL($){let U=$.token_endpoint_auth_methods_supported;if(U!=null)return U.includes("none");let Q=$.token_endpoint_auth_method;return Q==null||Q==="none"}var FL=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(KH)).optional(),response_types:j.array(j.literal("code")).optional(),token_endpoint_auth_method:j.literal("none").optional(),application_type:j.enum(["native","web"]).optional()}),vL=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()}),zL=j.object({client_id:j.string().min(1).max(2048),scope:j.string().max(2000).default(""),resource:j.string().min(1).max(2048)}),kL=j.object({device_code:j.string().min(1),user_code:j.string().regex(new RegExp(`^[${mq}]{4}-[${mq}]{4}$`)),verification_uri:j.string(),verification_uri_complete:j.string().optional(),expires_in:j.number().int().positive(),interval:j.number().int().positive()});var D8={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:["originate","hangup"],dashboard:["read"],notification:["read"],notification_channel:["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","update_settings"],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"],role:["read","create","update","delete"],license:["read"],organization:["list","create","update","delete"],integration:["read","update"],tenant_module:["read","update"],platform_admin:["read","manage"],platform_storage:["manage"],system:["logs","diagnostics","operate"]},QH={visual_plan:"organization",channel:"organization",destination:"organization",schedule:"organization",holiday:"organization",audio_file:"organization",call_record:"organization",call:"organization",dashboard:"organization",notification:"organization",notification_channel:"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",role:"organization",license:"organization",organization:"platform",integration:"platform",tenant_module:"platform",platform_admin:"platform",platform_storage:"platform",system:"platform"},qH=Object.entries(D8),wL=qH.flatMap(([$,U])=>U.map((Q)=>`${$}:${Q}`));var WH={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","notification:read","call_record:read","call_record:export","tts:read","ai:read","ai:execute","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","license: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","notification:read","call_record:read","call_record:export","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","license:read"],operator:["visual_plan:read","channel:read","destination:read","schedule:read","holiday:read","audio_file:read","dashboard:read","notification:read","call_record:read","test_call:execute","call:hangup","tts:read","contact:read","contact:update","dialer_campaign:read","dialer_dnc:read","user:read","license:read","archive:read"],viewer:["visual_plan:read","channel:read","destination:read","schedule:read","holiday:read","audio_file:read","dashboard:read","notification: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","license:read"]},xL=Object.keys(WH);var Sy=qH.filter(([$])=>QH[$]==="organization").flatMap(([$,U])=>U.map((Q)=>`${$}:${Q}`));var cq={plans:{entities:["visual_plan","audio_file","tts","analysis_template","test_call"]},telephony:{entities:["channel","destination","schedule","holiday","acl"]},calls:{entities:["call","call_record","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","notification_channel","audit","secret","license"]},platform:{entities:["organization","integration","tenant_module","platform_admin","platform_storage","system"],platformOnly:!0}},bL=Object.keys(cq),OL=new Map;for(let $ of bL)for(let U of cq[$].entities)OL.set(U,$);var JH=new Set(["*:read","*:write","offline_access"]);for(let $ of Object.keys(D8))JH.add(`${$}:read`),JH.add(`${$}:write`);var lq=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 nq($,U,Q,q,K){let W=U.channelType,J=typeof W==="string"?W:"voice";if(J!=="both")return RL($,Q,q,J==="voice"?"voice-only":"chat-only");return SL($,Q,q,K)}function RL($,U,Q,q){let K=rq($,U),W={};for(let J of Q)W[J]=K.has(J)?q:"unreachable";return W[$]=q,W}function TL($,U){if($&&U)return"converged";if($)return"voice-only";if(U)return"chat-only";return"unreachable"}function SL($,U,Q,q){let K=U.get($)?.get("voice"),W=U.get($)?.get("chat"),J=K!=null?rq(K,U,q,"voice"):new Set,G=W!=null?rq(W,U,q,"chat"):new Set;if(K!=null)J.add(K);if(W!=null)G.add(W);let Y={};for(let H of Q)Y[H]=H===$?"converged":TL(J.has(H),G.has(H));return Y}function rq($,U,Q,q){let K=new Set,W=[$];K.add($);let J=0;while(J<W.length){let G=W[J++],Y=U.get(G);if(Y==null)continue;if(q!=null&&Q?.has(G)){let H=Y.get(q);if(H!=null&&!K.has(H))K.add(H),W.push(H);continue}for(let H of Y.values())if(!K.has(H))K.add(H),W.push(H)}return K}function h(){return($,U)=>({key:U,prefix:`${$}:`})}var GH={call:h()("call",($)=>`call:${$}`),testPlan:h()("test-plan",($)=>`test-plan:${$}`),testChatPlan:h()("test-chat-plan",($)=>`test-chat-plan:${$}`),testEditorState:h()("test-editor-state",($)=>`test-editor-state:${$}`),testExecutionTrace:h()("test-execution-trace",($)=>`test-execution-trace:${$}`),refreshToken:h()("rt",($)=>`rt:${$}`),hostActionConfirmation:h()("host-action-confirmation",($)=>`host-action-confirmation:${$}`),revokedToken:h()("revoked",($)=>`revoked:${$}`),oauthCode:h()("oauth:code",($)=>`oauth:code:${$}`),oauthCimd:h()("oauth:cimd",($)=>`oauth:cimd:${$}`),oauthDevice:h()("oauth:device",($)=>`oauth:device:${$}`),oauthUsercode:h()("oauth:usercode",($)=>`oauth:usercode:${$}`),oauthUsercodeAttempts:h()("oauth:usercode-attempts",($)=>`oauth:usercode-attempts:${$}`),channels:h()("niva:channels",($)=>`niva:channels:${$}`),concurrentChannels:h()("niva:concurrent_channels",($,U)=>`niva:concurrent_channels:${$}:${U}`),peakConcurrentChannels:h()("niva:peak_concurrent",($,U)=>`niva:peak_concurrent:${$}:${U}`),dialerCampaignActive:h()("niva:dialer_campaign_active",($)=>`niva:dialer_campaign_active:${$}`),capacityReservation:h()("niva:capacity_reservation",($)=>`niva:capacity_reservation:${$}`),capacityReservationData:h()("niva:capacity_reservation_data",()=>"niva:capacity_reservation_data"),capacityReservationExpiry:h()("niva:capacity_reservation_expiry",()=>"niva:capacity_reservation_expiry"),capacityReservationHandoff:h()("niva:capacity_reservation_handoff",($)=>`niva:capacity_reservation_handoff:${$}`),counterByPlan:h()("niva:counter:plan",($,U,Q)=>`niva:counter:plan:${$}:${U}:${Q}`),counterByOrg:h()("niva:counter:org",($,U)=>`niva:counter:org:${$}:${U}`),trafficSplitRotation:h()("niva:traffic_split",($,U,Q,q)=>`niva:traffic_split:${$}:${U}:${Q}:${q}`),rateLimit:h()("rl",($,U)=>`rl:${$}:${U}`),liveTranscriptionSegments:h()("live-ts",($)=>`live-ts:${$}`),liveSignalEvents:h()("live-sig",($)=>`live-sig:${$}`),liveTranscriptionSummary:h()("live-ts-summary",($)=>`live-ts-summary:${$}`),transcriptionWatchers:h()("ts-watchers",($)=>`ts-watchers:${$}`),chatSession:h()("chat-session",($)=>`chat-session:${$}`),chatLookup:h()("chat-lookup",($,U,Q)=>`chat-lookup:${$}:${U}:${Q}`),chatLock:h()("chat-lock",($,U)=>`chat-lock:${$}:${U}`),chatInboundMessage:h()("chat-inbound-message",($,U,Q,q)=>`chat-inbound-message:${$}:${U}:${Q}:${q}`),wsSession:h()("ws:session",($)=>`ws:session:${$}`),wsMessageLog:h()("ws:log",($)=>`ws:log:${$}`),wsSeq:h()("ws:seq",($)=>`ws:seq:${$}`),healthStatus:h()("health-status",($)=>`health-status:${$}`),alertCooldown:h()("alert-cd",($,U)=>`alert-cd:${$}:${U}`),auditRetentionOverCap:h()("audit-retention",()=>"audit-retention:over-cap"),storageCleanup:h()("storage:cleanup",($)=>`storage:cleanup:${$}`),recordingDownloadAudit:h()("rec-dl-audit",($,U)=>`rec-dl-audit:${$}:${U}`),screenPop:h()("screenpop",($,U)=>`screenpop:${$}:${U}`),screenPopLegacy:h()("call_info",($)=>`call_info_${$}`),engineHeartbeat:h()("engine:heartbeat",()=>"engine:heartbeat")};function iq($,U){return typeof $==="string"&&$!==""&&!U.has($)}function oq($,U){return{nodeId:$.id,severity:"error",messageKey:U,params:{label:$.label}}}function EL($,U){if($.type!=="timeRouting"||U==null)return null;if(!iq($.config.scheduleId,U))return null;return oq($,"editor:validation.danglingSchedule")}function gL($,U){if($.type!=="subPlan"||U==null)return null;if(!iq($.config.planId,U))return null;return oq($,"editor:validation.danglingPlan")}function yL($,U){if(U==null)return null;let Q=$.config.audio;if(Q==null||typeof Q!=="object"||!("file"in Q))return null;let q=Q.file;if(q==null||typeof q!=="object"||!("id"in q))return null;if(!iq(q.id,U))return null;return oq($,"editor:validation.danglingAudioFile")}function uL($,U){if(U==null)return[];return H8($).allowed.filter((Q)=>!U.has(Q)).map((Q)=>({nodeId:$.id,severity:"error",messageKey:"editor:validation.danglingSecret",params:{label:$.label,secret:Q}}))}function dq($,U){let Q=[];for(let q of $){let K=EL(q,U.schedules);if(K!=null)Q.push(K);let W=gL(q,U.publishedPlans);if(W!=null)Q.push(W);let J=yL(q,U.audioFiles);if(J!=null)Q.push(J);Q.push(...uL(q,U.secrets))}return Q}function pq($,U){let Q=[];for(let q of $){if(q.type!=="aiAgent"||U.aiAgents==null)continue;let K=q.config.agent_id;if(typeof K==="string"&&K!==""&&!U.aiAgents.has(K))Q.push({nodeId:q.id,severity:"warning",messageKey:"editor:validation.danglingAiAgent",params:{label:q.label}})}return Q}var y$={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"]},tq=[...y$.basic,...y$.details,...y$.media,...y$.errors,...y$.origin,...y$.metadata,...y$.variables],jH=/^analysis:[a-z0-9][a-z0-9-]*\.[A-Za-z0-9_-]+(?:\[\])?(?:\.[A-Za-z0-9_-]+(?:\[\])?)*$/,fL=j.string().regex(jH,{error:"Invalid structured-analysis export column"}).refine(($)=>YH($),{error:"Invalid structured-analysis export column"});function YH($){return jH.test($)}var HH=/^signal:[a-z][a-z0-9_]*(?:\.triggered_at)?$/;function XH($){return HH.test($)}var hL=j.string().regex(HH,{error:"Invalid signal export column"}).refine(($)=>XH($),{error:"Invalid signal export column"}),BH=["sip_call_id","remote_addr","user_agent"],mL=new Set(BH),cL=tq.filter(($)=>!mL.has($)),lL=[...y$.basic];var rL={basic:[...y$.basic],full:[...tq],ai_audit:[...y$.basic,"transcription_status","transcription","analysis","sentiment_label","ai_agent_price","ai_agent_currency",...y$.errors,...y$.metadata,"variables"]};var aq=["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 ZH=[1,5,30,120,300,600],nL=ZH.length,MH=j.enum(["inbound","outbound"]),Y$=j.iso.datetime(),u$=j.record(j.string(),j.string()),iL=j.strictObject({amd:j.literal(!0),machine_type:j.literal(!0).optional(),mode:j.enum(AY).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"})}),VH=j.strictObject({call_id:j.string().min(1).meta({"x-niva-typeid":m.call_records}),caller_id:j.string(),callee_id:j.string(),direction:MH,visual_plan_id:j.string().min(1).meta({"x-niva-typeid":m.visual_plans}),visual_plan_name:j.string(),started_at:Y$,answer_recognition:iL.optional(),metadata:u$}),DH=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:Y$,metadata:u$}),sq=j.enum(["machine","human","silence","unknown"]),NH=j.enum(bY),PH=j.strictObject({call_id:j.string().min(1).meta({"x-niva-typeid":m.call_records}),channel_uuid:j.string().min(1),result:sq,machine_type:NH.optional(),completed_at:Y$,metadata:u$}).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"})}),IH=j.strictObject({call_id:j.string().min(1).meta({"x-niva-typeid":m.call_records}),caller_id:j.string(),callee_id:j.string(),direction:MH,visual_plan_id:j.string().min(1).meta({"x-niva-typeid":m.visual_plans}),visual_plan_name:j.string(),started_at:Y$,answered_at:Y$.nullable(),ended_at:Y$,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:sq}).optional(),metadata:u$}),_H=["not_found","channel_inactive","channel_deleted","plan_deleted","no_published_version","org_deleted","acl_denied","capacity_global","capacity_org","capacity_campaign","capacity_reservation"],LH=j.enum(_H),FH=j.strictObject({caller:j.string(),destination:j.string(),reason:LH,hangup_cause:j.string()}),vH=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:Y$,exited_at:Y$,duration_ms:j.number().nonnegative(),visual_plan_id:j.string().min(1).meta({"x-niva-typeid":m.visual_plans}),metadata:u$}),eq=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:Y$,metadata:u$}),zH=eq,kH=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:u$}),wH=["native","local","sippulse_ai"],oL=j.enum(wH),xH=j.strictObject({source:j.literal("native"),id:j.null(),template_id:j.null(),name:j.string(),category:j.null()}),AH=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()}),bH=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()}),ey=j.discriminatedUnion("source",[xH,AH,bH]),$W={status:j.enum(["completed","failed"]),result:j.record(j.string(),j.unknown()).nullable(),error_message:j.string().nullable(),error_code:j.string().nullable()},dL=j.strictObject({...xH.shape,...$W}),pL=j.strictObject({...AH.shape,...$W}),tL=j.strictObject({...bH.shape,...$W}),aL=j.discriminatedUnion("source",[dL,pL,tL]).superRefine(($,U)=>{if($.status==="failed"&&$.result!==null)U.addIssue({code:"custom",path:["result"],message:"Failed analyses must have a null result"})}),OH=j.enum(["caller","agent"]),RH=j.strictObject({id:j.string().min(1).meta({"x-niva-typeid":m.signals}),slug:j.string().min(1),name:j.string(),kind:j.enum($6),version:j.number().int().positive()}),sL=j.strictObject({signal:RH,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()}),TH=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:aL.array(),signals:sL.array(),analyzed_at:Y$,metadata:u$}),SH=["answered","busy","noAnswer","failed"],CH=j.enum(SH),EH=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:CH,status:j.string(),duration_ms:j.number().nonnegative().nullable(),transferred_at:Y$,metadata:u$}),gH=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:Y$,metadata:u$}),eL=j.strictObject({intent:j.string(),confidence:j.number()}),yH=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(eL),language:j.string().nullable(),matched_at:Y$,metadata:u$}),$F=j.strictObject({speaker:OH,text:j.string(),start_seconds:j.number()}),UF=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:RH,value:j.union([j.boolean(),j.string(),j.number(),j.null()]),value_label:j.string(),confidence:j.number(),severity:j.enum(U6),speaker:OH,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($F),is_anonymized:j.boolean(),trace_url:j.string().nullable(),metadata:u$}),uH=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:Y$}),fH=["text","media","audio","image","video","document","location","interactive"],hH=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(fH),text:j.string().nullable(),media_url:j.string().nullable(),node_id:j.string().nullable(),sent_at:Y$}),mH=["answered","machine","silence","busy","no_answer","failed","originate_error","cancelled"],cH=j.enum(mH),lH=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:cH,hangup_cause:j.string().nullable(),sip_code:j.string().nullable(),call_uuid:j.string().nullable(),started_at:Y$.nullable(),answered_at:Y$.nullable(),ended_at:Y$.nullable(),duration_s:j.number().nonnegative().nullable(),custom_fields:j.record(j.string(),j.string())}),rH=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()}),nH=j.strictObject({alert_type:j.string(),title:j.string(),body:j.string()}),iH=j.strictObject({component:j.string(),checked_at:Y$}),oH=j.strictObject({component:j.string(),downtime_seconds:j.number().nonnegative().nullable(),recovered_at:Y$}),N8={"call.started":VH,"call.answered":DH,"call.amd_completed":PH,"call.hangup":IH,"call.rejected":FH,"call.node_entered":vH,"call.node_error":eq,"call.node_warning":zH,"call.transcribed":kH,"call.analysis_completed":TH,"call.transferred":EH,"call.recording_available":gH,"call.intent_matched":yH,"call.signal_triggered":UF,"plan.published":uH,"message.sent":hH,"dialer.attempt.finished":lH,"alert.fired":rH,"alert.resolved":nH,"service.down":iH,"service.up":oH};function X$($){return j.strictObject({event:j.literal($),event_id:j.string().min(1),org_id:j.string().min(1),timestamp:Y$,data:N8[$]})}var KF=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.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")]);function B$($){return j.strictObject({event:j.literal($),event_id:j.string().min(1),timestamp:Y$,data:N8[$]})}var QF=j.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")]),r="01kknxab29enebk2vhm0tz0yyd",dH={"call.started":{call_id:`call_${r}`,caller_id:"+15551230001",callee_id:"+15551230002",direction:"inbound",visual_plan_id:`vp_${r}`,visual_plan_name:"Support IVR",started_at:"2026-01-15T12:00:00.000Z",metadata:{}},"call.answered":{call_id:`call_${r}`,caller_id:"+15551230001",callee_id:"+15551230002",answered_at:"2026-01-15T12:00:03.000Z",metadata:{}},"call.amd_completed":{call_id:`call_${r}`,channel_uuid:"freeswitch-channel-example",result:"machine",machine_type:"voicemail",completed_at:"2026-01-15T12:00:05.000Z",metadata:{}},"call.hangup":{call_id:`call_${r}`,caller_id:"+15551230001",callee_id:"+15551230002",direction:"inbound",visual_plan_id:`vp_${r}`,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_${r}`,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_${r}`,metadata:{}},"call.node_error":{call_id:`call_${r}`,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_${r}`,visual_plan_name:"Support IVR",occurred_at:"2026-01-15T12:00:10.000Z",metadata:{}},"call.node_warning":{call_id:`call_${r}`,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_${r}`,visual_plan_name:"Support IVR",occurred_at:"2026-01-15T12:00:10.000Z",metadata:{}},"call.transcribed":{call_record_id:`call_${r}`,transcription_id:`ctr_${r}`,full_text:"Hello, I need help with my account.",is_anonymized:!0,metadata:{}},"call.analysis_completed":{call_id:`call_${r}`,call_record_id:`call_${r}`,transcription_id:`ctr_${r}`,visual_plan_id:`vp_${r}`,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_${r}`,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_${r}`,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_${r}`,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_${r}`,call_record_id:`call_${r}`,recording_url:`https://example.invalid/recordings/call_${r}.wav`,storage_path:`recordings/example/call_${r}.wav`,duration_seconds:57,format:"wav",size_bytes:912000,available_at:"2026-01-15T12:01:01.000Z",metadata:{}},"call.intent_matched":{call_id:`call_${r}`,caller_id:"+15551230001",callee_id:"+15551230002",node_id:"node_intent",visual_plan_id:`vp_${r}`,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_${r}`,visual_plan_id:`vp_${r}`,signal:{id:`sig_${r}`,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_${r}`,metadata:{}},"plan.published":{plan_id:`vp_${r}`,plan_name:"Support IVR",version_id:`vpv_${r}`,version_number:3,published_by_user_id:`usr_${r}`,notes:"Updated support routing",published_at:"2026-01-15T11:00:00.000Z"},"message.sent":{session_id:`call_${r}`,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_${r}`,campaign_name:"January outreach",contact_id:`dct_${r}`,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 $0($){let U=n$[$],Q=C1[$],q=Q.defaultConfig,K=Y4(Q,q),W=typeof Q.producedVariables==="function"?Q.producedVariables(q):Q.producedVariables,J=FQ($,"en");return{type:$,name:J?.name??$,description:J?.description??"",nameKey:Q.nameKey,descriptionKey:Q.descriptionKey,module:Q.module,category:Q.category,channel:Q.channel,nature:Q.nature,configJsonSchema:j.toJSONSchema(U.configSchema,{unrepresentable:"any"}),outputs:K,producedVariables:W,defaultConfig:q}}var WF=Object.keys(n$);function UW(){return WF.map(($)=>$0($))}var JF=["string","number","boolean","object","array"],pH=j.strictObject({name:j.string(),type:j.enum(JF),required:j.boolean(),nullable:j.boolean()}),tH=j.strictObject({event:j.enum(aq),required_module:j.enum(["core","ai","queues","dialer","omnichannel","enterprise"]).nullable(),fields:j.array(pH),example:j.record(j.string(),j.unknown())}),GF=j.array(tH);var aH="edge";var jF=j.object({text:j.string().min(1).max(5000),voice:j.string().min(1),model:j.string().default(aH)});var YF=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 KW($){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 P8=[{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 QW($,U){let Q=$.texts[U];return K6.parse({slug:KW(Q.name),name:Q.name,question:Q.question,kind:$.kind,...$.kind==="choice"?{options:(Q.options??[]).map((q,K)=>({key:$.option_keys?.[K]??`option_${K}`,label:q.label,...q.description!==void 0?{description:q.description}:{}}))}:{},...$.kind==="scale"?{levels:Q.levels??[]}:{},speaker:$.speaker,scope:$.scope,live:$.live,alert:$.alert})}var sH=["not_applicable","disabled","waiting","pending","processing","completed","failed","skipped","purged","expired"];var eu=new Set(sH);var qW=j.record(j.string(),j.string());var I8=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:qW,variablesAfter:qW.nullable(),resolvedConfig:j.record(j.string(),j.unknown()),resultData:j.record(j.string(),j.unknown()).nullable()}).superRefine(($,U)=>{let Q=[$.exitedAt,$.durationMs,$.handleUsed,$.variablesAfter];if($.status==="running"?Q.some((K)=>K!==null):Q.includes(null))U.addIssue({code:"custom",path:["status"],message:"Running steps must have empty exit fields; terminal steps must have complete exit fields"})}),XF=j.object({orgId:j.string(),status:j.enum(["active","waiting_input","ended"]),currentNodeId:j.string(),variables:qW,steps:j.array(I8),truncated:j.boolean()});function H4($){return{audio:{tts:{text:$}}}}function ZF($){return{type:"text",text:$}}function I($){return{...H4($),content:ZF($)}}function o($,U,Q={},q){return{options:U,maxAttempts:3,audio:H4($).audio,text:q??$,...Q}}function V$($,U={}){return{audio:H4($).audio,text:$,...U}}function n($,U,Q,q){return[X(`${$}a`,U,"answered",Q),X(`${$}b`,U,"busy",q),X(`${$}n`,U,"noAnswer",q),X(`${$}e`,U,"error",q)]}var MF={x:0,y:0};function Z($,U,Q,q,K){return{id:$,type:U,label:Q,varName:q,position:MF,config:K}}function X($,U,Q,q){return{id:$,source:U,sourceHandle:Q,target:q,targetHandle:"in"}}var eH={id:"atendente-virtual-ia",category:"ai",requiredModules:["ai"],tags:["ia","agente","ai","virtual","conversacional"],editorState:{nodes:[Z("s1","start","Início","inicio",{channelType:"both"}),Z("t1","tell","Boas-vindas","boas_vindas",I("Olá! Sou o assistente virtual. Posso ajudar com diversas questões.")),Z("ai1","aiAgent","Agente IA","agente_ia",{agent_id:"",agent_name:"",additional_instructions:"",variables:{},initial_message:"Olá, como posso ajudar?",max_duration_minutes:10}),Z("m1","menu","Satisfação","satisfacao",o("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:")),Z("t2","tell","Agradecimento","agradecimento",I("Obrigado pelo contato. Tenha um bom dia!")),Z("t3","tell","Transferindo","transferindo",I("Vou transferir para um atendente humano.")),Z("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["1000"],timeout:45}),Z("t4","tell","Erro IA","erro_ia",I("Houve um problema com o assistente. Vou transferir para um atendente.")),Z("t5","tell","Transferência Falhou","transferencia_falhou",I("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),Z("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"),...n("ex1","x1","h1","t5"),X("e12","t5","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var $X={id:"atendimento-agente-ia",category:"ai",requiredModules:["ai"],tags:["ia","ai","agente","atendimento","intencao","classificacao","transferencia"],editorState:{nodes:[Z("s1","start","Início","inicio",{channelType:"both"}),Z("t1","tell","Boas-vindas","boas_vindas",I("Olá! Você ligou para a nossa central. Em poucas palavras, me diga como posso ajudar.")),Z("c1","capture","Captura","captura",V$("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:H4("Um momento enquanto analiso o seu pedido.").audio})),Z("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."}),Z("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}),Z("sw1","switchCase","Decidir","decidir",{expression:"{{agente.output.resultado}}",cases:[{pattern:"^resolvido$"}]}),Z("t2","tell","Despedida","despedida",I("Obrigado pelo contato. Tenha um ótimo dia!")),Z("t3","tell","Não Entendi","nao_entendeu",I("Não consegui entender o motivo do contato. Vou transferir para um atendente.")),Z("t4","tell","Erro Técnico","erro_tecnico",I("Tivemos um problema no atendimento automático. Vou transferir para um atendente.")),Z("x1","transfer","Transferência Humana","transfer_humano",{method:"bridge",destinations:["1000"]}),Z("t5","tell","Transferência Falhou","transfer_falhou",I("Não conseguimos completar a transferência. Por favor, ligue novamente mais tarde.")),Z("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 UX={id:"atendimento-setores",category:"core",requiredModules:[],tags:["menu","transfer","setores","departamentos","ura"],editorState:{nodes:[Z("s1","start","Início","inicio",{channelType:"both"}),Z("t1","tell","Boas-vindas","boas_vindas",I("Bem-vindo. Escolha entre financeiro, suporte, vendas ou ouvidoria.")),Z("m1","menu","Menu Principal","menu_principal",o("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:")),Z("t2","tell","Transferindo Financeiro","transferindo_financeiro",I("Aguarde, transferindo para o financeiro.")),Z("t3","tell","Transferindo Suporte","transferindo_suporte",I("Aguarde, transferindo para o suporte técnico.")),Z("t4","tell","Transferindo Vendas","transferindo_vendas",I("Aguarde, transferindo para vendas.")),Z("t5","tell","Transferindo Ouvidoria","transferindo_ouvidoria",I("Aguarde, transferindo para a ouvidoria.")),Z("x1","transfer","Financeiro","financeiro",{method:"bridge",destinations:["1001"],timeout:30}),Z("x2","transfer","Suporte","suporte",{method:"bridge",destinations:["1002"],timeout:30}),Z("x3","transfer","Vendas","vendas",{method:"bridge",destinations:["1003"],timeout:30}),Z("x4","transfer","Ouvidoria","ouvidoria",{method:"bridge",destinations:["1004"],timeout:30}),Z("t6","tell","Opção Inválida","opcao_invalida",I("Não entendi sua escolha. Por favor, ligue novamente.")),Z("t7","tell","Transferência Falhou","transferencia_falhou",I("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),Z("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"),...n("ex1","x1","h1","t7"),...n("ex2","x2","h1","t7"),...n("ex3","x3","h1","t7"),...n("ex4","x4","h1","t7"),X("e14","t7","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var KX={id:"banco-sac",category:"industry",requiredModules:[],tags:["banco","financeiro","sac","saldo","extrato","cartao"],editorState:{nodes:[Z("s1","start","Início","inicio",{channelType:"both"}),Z("c1","capture","CPF do Cliente","cpf_cliente",V$("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:"})),Z("m1","menu","Menu Serviços","menu_servicos",o("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:")),Z("http1","httpRequest","Consultar Saldo","consultar_saldo",{method:"GET",url:"https://api.example.com/accounts/{{cpf_cliente.text}}/balance",headers:{},body:"",timeout:10}),Z("t1","tell","Saldo Informado","saldo_informado",I("O seu saldo é: {{consultar_saldo.response}}. Obrigado pelo contato.")),Z("t2","tell","Extrato","extrato",I("Seu extrato será enviado por SMS em instantes.")),Z("t3","tell","Cartões","cartoes",I("Para informações sobre cartões, vou transferir para um especialista.")),Z("t4","tell","Transferindo Atendente","transferindo_atendente",I("Aguarde, vou transferir para um atendente.")),Z("t5","tell","Erro Consulta","erro_consulta",I("Não foi possível realizar a consulta agora. Vou transferir para um atendente.")),Z("t6","tell","Sem Identificação","sem_identificacao",I("Não consegui identificar o seu CPF. Vou transferir para um atendente.")),Z("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["5001"],timeout:45}),Z("t7","tell","Transferência Falhou","transferencia_falhou",I("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),Z("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"),...n("ex1","x1","h1","t7"),X("e19","t7","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var QX={id:"clinica-agendamento",category:"industry",requiredModules:[],tags:["clinica","saude","agendamento","consulta","medico"],editorState:{nodes:[Z("s1","start","Início","inicio",{channelType:"both"}),Z("t1","tell","Boas-vindas","boas_vindas",I("Bem-vindo à central de agendamentos.")),Z("m1","menu","Especialidade","especialidade",o("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:")),Z("c1","capture","CPF do Paciente","cpf_paciente",V$("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:"})),Z("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}),Z("t2","tell","Resultado da Consulta","resultado_consulta",I("{{consultar_agenda.response}}")),Z("t3","tell","Erro na Consulta","erro_consulta",I("Não conseguimos consultar a agenda no momento. Por favor, tente novamente mais tarde.")),Z("t4","tell","Sem Dados","sem_dados",I("Não consegui capturar as informações necessárias. Por favor, tente novamente mais tarde.")),Z("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 qX={id:"cobranca-automatizada",category:"capture",requiredModules:[],tags:["cobranca","debito","pagamento","boleto","pix","negociacao"],editorState:{nodes:[Z("s1","start","Início","inicio",{channelType:"both"}),Z("t1","tell","Intro Cobrança","intro_cobranca",I("Olá, identificamos um débito em aberto na sua conta.")),Z("m1","menu","Opções de Pagamento","opcoes_pagamento",o("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:")),Z("c1","capture","Identificação","identificacao",V$("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:"})),Z("t2","tell","Transferindo Negociação","transferindo_negociacao",I("Recebi sua identificação. Vou transferir para um especialista em negociação.")),Z("x1","transfer","Negociação","negociacao",{method:"bridge",destinations:["2001"],timeout:45}),Z("t3","tell","Boleto Enviado","boleto_enviado",I("O boleto atualizado será enviado para seu contato cadastrado em até 5 minutos.")),Z("t4","tell","Chave Pix","chave_pix",I("Nossa chave Pix é o CNPJ da empresa. Após o pagamento, a baixa será automática em até 2 horas.")),Z("t5","tell","Opção Inválida","opcao_invalida",I("Não entendi sua escolha. Por favor, ligue novamente.")),Z("t6","tell","Sem Identificação","sem_identificacao",I("Não recebi sua identificação. Por favor, ligue novamente com os dados em mãos.")),Z("t7","tell","Transferência Falhou","transferencia_falhou",I("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),Z("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"),...n("ex1","x1","h1","t7"),X("e16","t7","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var WX={id:"coleta-dados-api",category:"capture",requiredModules:[],tags:["capture","api","http","dados","integracao"],editorState:{nodes:[Z("s1","start","Início","inicio",{channelType:"both"}),Z("t1","tell","Boas-vindas","boas_vindas",I("Olá. Vou consultar uma informação para você.")),Z("c1","capture","Identificação","identificacao",V$("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:"})),Z("http1","httpRequest","Consultar API","consultar_api",{method:"GET",url:"https://api.example.com/lookup/{{identificacao.text}}",headers:{},body:"",timeout:10}),Z("sw1","switchCase","Tipo de Falha","tipo_falha",{expression:"{{consultar_api.status_code}}",cases:[{pattern:"^404$"}]}),Z("t2","tell","Resultado Encontrado","resultado_encontrado",I("Encontrei as informações solicitadas: {{consultar_api.response}}. Obrigado pelo contato.")),Z("t3","tell","Não Encontrado","nao_encontrado",I("Não encontrei registros para essa identificação. Verifique o número e tente novamente.")),Z("t4","tell","Erro de Consulta","erro_consulta",I("Houve um erro na consulta. Tente novamente mais tarde.")),Z("t5","tell","Sem Identificação","sem_identificacao",I("Não consegui capturar sua identificação. Por favor, ligue novamente com o número em mãos.")),Z("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 JX={id:"faq-ia-escalacao",category:"ai",requiredModules:["ai"],tags:["faq","ia","escalacao","ai","agente"],editorState:{nodes:[Z("s1","start","Início","inicio",{channelType:"both"}),Z("t1","tell","Boas-vindas","boas_vindas",I("Olá! Sou o assistente virtual. Posso tirar dúvidas sobre nossos serviços.")),Z("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}),Z("m1","menu","Resolveu?","resolveu",o("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:")),Z("t2","tell","Agradecimento","agradecimento",I("Ótimo! Se precisar de algo mais, é só entrar em contato.")),Z("t3","tell","Transferindo","transferindo",I("Aguarde, vou transferir para um atendente.")),Z("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["1000"],timeout:45}),Z("t4","tell","Transferência Falhou","transferencia_falhou",I("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),Z("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"),...n("ex1","x1","h1","t4"),X("e11","t4","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var GX={id:"faq-informacoes",category:"core",requiredModules:[],tags:["faq","informacoes","autoatendimento","info"],editorState:{nodes:[Z("s1","start","Início","inicio",{channelType:"both"}),Z("t1","tell","Boas-vindas","boas_vindas",I("Olá, sou o assistente virtual. Posso ajudar com suporte, financeiro, vendas ou horários de atendimento.")),Z("m1","menu","Menu FAQ","menu_faq",o("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:")),Z("t2","tell","Info Suporte","info_suporte",I("Nossa equipe de suporte está disponível 24 horas por dia. Você também pode abrir um chamado pelo nosso portal.")),Z("t3","tell","Info Financeiro","info_financeiro",I("Para boletos, notas fiscais e negociações, acesse nosso portal financeiro ou fale com atendimento em horário comercial.")),Z("t4","tell","Info Vendas","info_vendas",I("Conheça nossos planos e promoções no nosso site. Para falar com um consultor, ligue em horário comercial.")),Z("t5","tell","Info Horários","info_horarios",I("Nosso atendimento funciona de segunda a sexta, das 8h às 20h. Aos sábados, das 8h às 14h.")),Z("t6","tell","Opção Inválida","opcao_invalida",I("Não entendi sua escolha. Encerrando o atendimento. Até logo.")),Z("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 jX={id:"horario-comercial",category:"core",requiredModules:[],tags:["horario","schedule","tempo","comercial","expediente"],editorState:{nodes:[Z("s1","start","Início","inicio",{channelType:"both"}),Z("tr1","timeRouting","Horário Atendimento","horario_atendimento",{}),Z("t1","tell","Boas-vindas","boas_vindas",I("Bem-vindo. Como posso ajudar?")),Z("m1","menu","Menu Principal","menu_principal",o("Para suporte, tecle 1. Para vendas, tecle 2.",[{id:"suporte",label:"Suporte",digit:"1"},{id:"vendas",label:"Vendas",digit:"2"}],{},"Escolha uma opção:")),Z("t2","tell","Transferindo Suporte","transferindo_suporte",I("Transferindo para o suporte.")),Z("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),Z("t3","tell","Transferindo Vendas","transferindo_vendas",I("Transferindo para vendas.")),Z("x2","transfer","Vendas","vendas",{method:"bridge",destinations:["1002"],timeout:30}),Z("t4","tell","Fora do Horário","fora_horario",I("Nosso horário de atendimento é de segunda a sexta, das 8h às 18h. Ligue novamente no próximo dia útil.")),Z("t5","tell","Opção Não Reconhecida","opcao_nao_reconhecida",I("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),Z("t6","tell","Transferência Falhou","transferencia_falhou",I("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),Z("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"),...n("ex1","x1","h1","t6"),...n("ex2","x2","h1","t6"),X("e13","t4","next","h1"),X("e14","t6","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var YX={id:"isp-suporte-tecnico",category:"industry",requiredModules:[],tags:["isp","provedor","internet","suporte","tecnico","telecom"],editorState:{nodes:[Z("s1","start","Início","inicio",{channelType:"both"}),Z("t1","tell","Boas-vindas","boas_vindas",I("Bem-vindo ao suporte técnico.")),Z("m1","menu","Tipo de Serviço","tipo_servico",o("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:")),Z("c1","capture","Contrato Internet","contrato_internet",V$("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:"})),Z("c2","capture","Contrato Telefonia","contrato_telefonia",V$("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:"})),Z("http1","httpRequest","Status Internet","status_internet",{method:"GET",url:"https://api.example.com/contracts/{{contrato_internet.text}}/status?service=internet",headers:{},body:"",timeout:10}),Z("http2","httpRequest","Status Telefonia","status_telefonia",{method:"GET",url:"https://api.example.com/contracts/{{contrato_telefonia.text}}/status?service=telefonia",headers:{},body:"",timeout:10}),Z("t2","tell","Status Internet","status_internet_info",I("Sobre sua conexão de internet: {{status_internet.response}}")),Z("t3","tell","Status Telefonia","status_telefonia_info",I("Sobre seu serviço de telefonia: {{status_telefonia.response}}")),Z("sw1","switchCase","Falha Internet","falha_internet",{expression:"{{status_internet.status_code}}",cases:[{pattern:"^404$"}]}),Z("sw2","switchCase","Falha Telefonia","falha_telefonia",{expression:"{{status_telefonia.status_code}}",cases:[{pattern:"^404$"}]}),Z("t4","tell","Contrato Não Encontrado","contrato_nao_encontrado",I("Não encontrei esse contrato. Vou transferir para um atendente.")),Z("t5","tell","Erro de Consulta","erro_consulta",I("Não foi possível consultar o status agora. Vou transferir para um atendente.")),Z("t6","tell","Sem Contrato","sem_contrato",I("Não consegui capturar o número do contrato. Vou transferir para um atendente.")),Z("t7","tell","Opção Não Reconhecida","opcao_nao_reconhecida",I("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),Z("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["3001"],timeout:60}),Z("t8","tell","Transferência Falhou","transferencia_falhou",I("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),Z("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"),...n("ex1","x1","h1","t8"),X("e24","t8","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var HX={id:"mensagem-simples",category:"core",requiredModules:[],tags:["mensagem","simples","aviso","anuncio","basico"],editorState:{nodes:[Z("s1","start","Início","inicio",{channelType:"both"}),Z("t1","tell","Mensagem","mensagem",I("Obrigado por ligar. No momento não estamos disponíveis. Por favor, tente novamente mais tarde.")),Z("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 XX={id:"menu-multinivel",category:"advanced",requiredModules:[],tags:["menu","multinivel","departamento","hierarquia","complexo"],editorState:{nodes:[Z("s1","start","Início","inicio",{channelType:"both"}),Z("t1","tell","Boas-vindas","boas_vindas",I("Bem-vindo. Escolha o setor desejado.")),Z("m1","menu","Menu Principal","menu_principal",o("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:")),Z("m2","menu","Atendimento","atendimento",o("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:")),Z("m3","menu","Comercial","comercial",o("Para vendas, tecle 1. Para parcerias, tecle 2.",[{id:"vendas",label:"Vendas",digit:"1"},{id:"parcerias",label:"Parcerias",digit:"2"}],{},"Escolha uma opção:")),Z("m4","menu","Administrativo","administrativo",o("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:")),Z("t2","tell","Transferindo Suporte","transferindo_suporte",I("Transferindo para suporte técnico.")),Z("t3","tell","Transferindo Financeiro","transferindo_financeiro",I("Transferindo para financeiro.")),Z("t4","tell","Transferindo Vendas","transferindo_vendas",I("Transferindo para vendas.")),Z("t5","tell","Transferindo Parcerias","transferindo_parcerias",I("Transferindo para parcerias.")),Z("t6","tell","Transferindo RH","transferindo_rh",I("Transferindo para RH.")),Z("t7","tell","Transferindo Jurídico","transferindo_juridico",I("Transferindo para jurídico.")),Z("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),Z("x2","transfer","Financeiro","financeiro",{method:"bridge",destinations:["1002"],timeout:45}),Z("x3","transfer","Vendas","vendas",{method:"bridge",destinations:["2001"],timeout:30}),Z("x4","transfer","Parcerias","parcerias",{method:"bridge",destinations:["2002"],timeout:30}),Z("x5","transfer","RH","rh",{method:"bridge",destinations:["3001"],timeout:30}),Z("x6","transfer","Jurídico","juridico",{method:"bridge",destinations:["3002"],timeout:30}),Z("t8","tell","Opção Não Reconhecida","opcao_nao_reconhecida",I("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),Z("t9","tell","Transferência Falhou","transferencia_falhou",I("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),Z("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"),...n("ex1","x1","h1","t9"),...n("ex2","x2","h1","t9"),...n("ex3","x3","h1","t9"),...n("ex4","x4","h1","t9"),...n("ex5","x5","h1","t9"),...n("ex6","x6","h1","t9"),X("e29","t9","next","h1")],viewport:{x:0,y:0,zoom:0.7}}};var BX={id:"notificacao-atendimento",category:"core",requiredModules:[],tags:["notificacao","aviso","atendimento","callback"],editorState:{nodes:[Z("s1","start","Início","inicio",{channelType:"both"}),Z("t1","tell","Notificação","notificacao",I("Olá, temos uma informação importante sobre sua conta.")),Z("m1","menu","Precisa de Ajuda?","precisa_ajuda",o("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?")),Z("t2","tell","Transferindo","transferindo",I("Aguarde, vou transferir para um atendente.")),Z("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["1000"],timeout:45}),Z("t3","tell","Agradecimento","agradecimento",I("Obrigado pelo seu tempo. Tenha um bom dia!")),Z("t4","tell","Transferência Falhou","transferencia_falhou",I("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),Z("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"),...n("ex1","x1","h1","t4"),X("e8","t3","next","h1"),X("e9","t4","next","h1")],viewport:{x:0,y:0,zoom:0.9}}};var ZX={id:"pesquisa-nps",category:"advanced",requiredModules:["ai"],tags:["nps","pesquisa","promotor","detrator","feedback","avaliacao"],editorState:{nodes:[Z("s1","start","Início","inicio",{channelType:"both"}),Z("t1","tell","Intro NPS","intro_nps",I("Gostaríamos de saber sua opinião sobre nosso atendimento.")),Z("c1","capture","Nota NPS","nota_nps",V$("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:"})),Z("sw1","switchCase","Classificar NPS","classificar_nps",{expression:"{{nota_nps.text}}",cases:[{pattern:"^9$"},{pattern:"^10$"},{pattern:"^7$"},{pattern:"^8$"}]}),Z("t2","tell","Promotor","promotor",I("Que ótimo! Ficamos muito felizes com sua avaliação.")),Z("t3","tell","Neutro","neutro",I("Obrigado pela avaliação. Vamos trabalhar para melhorar.")),Z("t4","tell","Detrator","detrator",I("Lamentamos que sua experiência não tenha sido satisfatória.")),Z("c2","capture","Feedback","feedback",V$("Pode nos dizer o que podemos melhorar? Fale após o sinal.",{voiceMethod:"speech",text:"Pode nos dizer o que podemos melhorar?"})),Z("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}),Z("t5","tell","Agradecimento","agradecimento",I("Obrigado pelo seu feedback. Ele é muito importante para nós.")),Z("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 MX={id:"pesquisa-satisfacao",category:"core",requiredModules:[],tags:["pesquisa","satisfacao","csat","avaliacao","nota"],editorState:{nodes:[Z("s1","start","Início","inicio",{channelType:"both"}),Z("t1","tell","Intro Pesquisa","intro_pesquisa",I("Gostaríamos de avaliar o atendimento que você recebeu.")),Z("m1","menu","Nota de Satisfação","nota_satisfacao",o("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?")),Z("t2","tell","Agradecimento","agradecimento",I("Você avaliou nosso atendimento como: {{nota_satisfacao.selectedLabel}}. Obrigado, sua opinião nos ajuda a melhorar.")),Z("t3","tell","Sem Resposta","sem_resposta",I("Não conseguimos registrar sua avaliação. Agradecemos o contato.")),Z("h1","hangup","Desligamento","desligamento",{}),Z("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 VX={id:"roteamento-canal",category:"omnichannel",requiredModules:[],tags:["canal","omnichannel","voz","chat","roteamento"],editorState:{nodes:[Z("s1","start","Início","inicio",{channelType:"both"}),Z("cr1","channelRouter","Roteador de Canal","roteador_canal",{}),Z("t1","tell","Boas-vindas Voz","boas_vindas_voz",I("Bem-vindo ao nosso atendimento por telefone.")),Z("m1","menu","Menu Voz","menu_voz",o("Para suporte, tecle 1. Para vendas, tecle 2.",[{id:"suporte",label:"Suporte",digit:"1"},{id:"vendas",label:"Vendas",digit:"2"}])),Z("t2","tell","Boas-vindas Chat","boas_vindas_chat",I("Olá! Bem-vindo ao nosso atendimento por chat.")),Z("m2","menu","Menu Chat","menu_chat",o("Para suporte, tecle 1. Para vendas, tecle 2.",[{id:"suporte",label:"Suporte",digit:"1"},{id:"vendas",label:"Vendas",digit:"2"}],{},"Escolha uma opção:")),Z("t3","tell","Transferindo Suporte","transferindo_suporte",I("Transferindo para o suporte.")),Z("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),Z("t4","tell","Transferindo Vendas","transferindo_vendas",I("Transferindo para vendas.")),Z("x2","transfer","Vendas","vendas",{method:"bridge",destinations:["1002"],timeout:30}),Z("t5","tell","Opção Não Reconhecida","opcao_nao_reconhecida",I("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),Z("t6","tell","Transferência Falhou","transferencia_falhou",I("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),Z("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"),...n("ex1","x1","h1","t6"),...n("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 DX={id:"status-pedido",category:"capture",requiredModules:[],tags:["pedido","status","rastreio","ecommerce","api"],editorState:{nodes:[Z("s1","start","Início","inicio",{channelType:"both"}),Z("t1","tell","Boas-vindas","boas_vindas",I("Olá. Vou consultar o status do seu pedido.")),Z("c1","capture","Número do Pedido","numero_pedido",V$("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:"})),Z("http1","httpRequest","Consultar Pedido","consultar_pedido",{method:"GET",url:"https://api.example.com/orders/{{numero_pedido.text}}",headers:{},body:"",timeout:10}),Z("sw1","switchCase","Tipo de Falha","tipo_falha",{expression:"{{consultar_pedido.status_code}}",cases:[{pattern:"^404$"}]}),Z("t2","tell","Status do Pedido","status_do_pedido",I("O status do seu pedido é: {{consultar_pedido.response}}")),Z("t3","tell","Pedido Não Encontrado","pedido_nao_encontrado",I("Não encontrei esse número de pedido. Verifique e tente novamente.")),Z("t4","tell","Erro de Consulta","erro_consulta",I("Houve um erro ao consultar o pedido. Tente novamente mais tarde.")),Z("t5","tell","Sem Número","sem_numero",I("Não consegui capturar o número do pedido. Por favor, ligue novamente com o número em mãos.")),Z("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 NX={id:"triagem-inteligente",category:"ai",requiredModules:["ai"],tags:["triagem","intencao","intent","ia","roteamento","ai"],editorState:{nodes:[Z("s1","start","Início","inicio",{channelType:"both"}),Z("t1","tell","Boas-vindas","boas_vindas",I("Olá! Vou te direcionar para o setor correto.")),Z("c1","capture","Motivo do Contato","motivo_contato",V$("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:H4("Um momento enquanto identifico o setor correto.").audio,text:"Descreva em poucas palavras com o que você precisa de ajuda:"})),Z("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."}),Z("t2","tell","Direcionando Suporte","direcionando_suporte",I("Entendi, vou transferir para o suporte técnico.")),Z("t3","tell","Direcionando Financeiro","direcionando_financeiro",I("Entendi, vou transferir para o financeiro.")),Z("t4","tell","Direcionando Vendas","direcionando_vendas",I("Entendi, vou transferir para vendas.")),Z("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),Z("x2","transfer","Financeiro","financeiro",{method:"bridge",destinations:["1002"],timeout:45}),Z("x3","transfer","Vendas","vendas",{method:"bridge",destinations:["1003"],timeout:30}),Z("t5","tell","Não Identificado","nao_identificado",I("Não consegui identificar sua necessidade. Vou transferir para um atendente.")),Z("x4","transfer","Atendente Geral","atendente_geral",{method:"bridge",destinations:["1000"],timeout:45}),Z("t6","tell","Transferência Falhou","transferencia_falhou",I("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),Z("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"),...n("ex1","x1","h1","t6"),...n("ex2","x2","h1","t6"),...n("ex3","x3","h1","t6"),...n("ex4","x4","h1","t6"),X("e15","t6","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var PX={id:"ura-reversa-spot",category:"core",requiredModules:[],tags:["spot","ura reversa","campanha","outbound","discagem","tecla"],editorState:{nodes:[Z("s1","start","Início","inicio",{channelType:"both"}),Z("m1","menu","Spot","spot",o("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.")),Z("t1","tell","Agradecimento","agradecimento",I("Obrigado! Em instantes um atendente entrará em contato.")),Z("t2","tell","Encerramento","encerramento",I("Obrigado pela atenção. Até logo!")),Z("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 IX={"atendente-virtual-ia":{ai1:{x:704,y:153},h1:{x:2488,y:210},m1:{x:1080,y:0},s1:{x:0,y:96},t1:{x:376,y:184},t2:{x:1808,y:40},t3:{x:1456,y:111},t4:{x:1456,y:241},t5:{x:2160,y:281},x1:{x:1784,y:170}},"atendimento-agente-ia":{ai1:{x:1456,y:44},c1:{x:704,y:201},h1:{x:3240,y:66},ra1:{x:1080,y:97},s1:{x:0,y:158},sw1:{x:1832,y:0},t1:{x:376,y:246},t2:{x:2912,y:66},t3:{x:1480,y:247},t4:{x:2208,y:176},t5:{x:2912,y:196},x1:{x:2536,y:117}},"atendimento-setores":{h1:{x:2112,y:790},m1:{x:704,y:447},s1:{x:0,y:446},t1:{x:376,y:534},t2:{x:1080,y:59},t3:{x:1080,y:307},t4:{x:1080,y:555},t5:{x:1080,y:685},t6:{x:1080,y:815},t7:{x:1784,y:575},x1:{x:1408,y:0},x2:{x:1408,y:248},x3:{x:1408,y:496},x4:{x:1408,y:744}},"banco-sac":{c1:{x:376,y:348},h1:{x:2536,y:247},http1:{x:1128,y:0},m1:{x:752,y:170},s1:{x:0,y:305},t1:{x:1856,y:177},t2:{x:1504,y:247},t3:{x:1504,y:377},t4:{x:1152,y:334},t5:{x:1504,y:117},t6:{x:1152,y:464},t7:{x:2208,y:429},x1:{x:1832,y:318}},"clinica-agendamento":{c1:{x:1080,y:40},h1:{x:2160,y:130},http1:{x:1456,y:8},m1:{x:704,y:28},s1:{x:0,y:13},t1:{x:376,y:101},t2:{x:1832,y:0},t3:{x:1832,y:130},t4:{x:1480,y:200}},"cobranca-automatizada":{c1:{x:1080,y:99},h1:{x:2488,y:188},m1:{x:704,y:220},s1:{x:0,y:205},t1:{x:376,y:293},t2:{x:1456,y:59},t3:{x:1808,y:259},t4:{x:2160,y:329},t5:{x:1104,y:400},t6:{x:1456,y:189},t7:{x:2160,y:118},x1:{x:1784,y:0}},"coleta-dados-api":{c1:{x:704,y:174},h1:{x:2160,y:90},http1:{x:1080,y:87},s1:{x:0,y:131},sw1:{x:1456,y:130},t1:{x:376,y:219},t2:{x:1480,y:0},t3:{x:1832,y:90},t4:{x:1832,y:220},t5:{x:1104,y:290}},"faq-ia-escalacao":{ai1:{x:704,y:100},h1:{x:2488,y:216},m1:{x:1080,y:0},s1:{x:0,y:43},t1:{x:376,y:131},t2:{x:1808,y:46},t3:{x:1456,y:144},t4:{x:2160,y:287},x1:{x:1784,y:176}},"faq-informacoes":{h1:{x:1408,y:530},m1:{x:704,y:63},s1:{x:0,y:62},t1:{x:376,y:150},t2:{x:1080,y:0},t3:{x:1080,y:140},t4:{x:1080,y:270},t5:{x:1080,y:400},t6:{x:1080,y:530}},"horario-comercial":{h1:{x:2488,y:436},m1:{x:1080,y:222},s1:{x:0,y:277},t1:{x:752,y:281},t2:{x:1456,y:59},t3:{x:1456,y:236},t4:{x:752,y:436},t5:{x:1456,y:366},t6:{x:2160,y:327},tr1:{x:376,y:320},x1:{x:1784,y:0},x2:{x:1784,y:248}},"isp-suporte-tecnico":{c1:{x:1080,y:57},c2:{x:1080,y:277},h1:{x:3240,y:333},http1:{x:1456,y:0},http2:{x:1456,y:365},m1:{x:704,y:243},s1:{x:0,y:214},sw1:{x:1832,y:117},sw2:{x:1832,y:337},t1:{x:376,y:302},t2:{x:2560,y:195},t3:{x:2912,y:534},t4:{x:2208,y:288},t5:{x:2208,y:418},t6:{x:1480,y:235},t7:{x:1104,y:497},t8:{x:2912,y:404},x1:{x:2536,y:325}},"mensagem-simples":{h1:{x:704,y:88},s1:{x:0,y:0},t1:{x:376,y:88}},"menu-multinivel":{h1:{x:2488,y:569},m1:{x:704,y:655},m2:{x:1080,y:391},m3:{x:1080,y:639},m4:{x:1080,y:898},s1:{x:0,y:640},t1:{x:376,y:728},t2:{x:1456,y:307},t3:{x:1456,y:437},t4:{x:1456,y:567},t5:{x:1456,y:697},t6:{x:1456,y:1051},t7:{x:1456,y:1299},t8:{x:1456,y:827},t9:{x:2160,y:640},x1:{x:1784,y:248},x2:{x:1784,y:0},x3:{x:1784,y:496},x4:{x:1784,y:744},x5:{x:1784,y:992},x6:{x:1784,y:1240}},"notificacao-atendimento":{h1:{x:2112,y:117},m1:{x:704,y:44},s1:{x:0,y:15},t1:{x:376,y:103},t2:{x:1080,y:58},t3:{x:1080,y:188},t4:{x:1784,y:117},x1:{x:1408,y:0}},"pesquisa-nps":{c1:{x:704,y:214},c2:{x:1784,y:148},h1:{x:2864,y:330},http1:{x:2160,y:198},s1:{x:0,y:171},sw1:{x:1080,y:22},t1:{x:376,y:259},t2:{x:1456,y:0},t3:{x:1456,y:130},t4:{x:1456,y:260},t5:{x:2536,y:330}},"pesquisa-satisfacao":{h1:{x:1408,y:98},h2:{x:1408,y:228},m1:{x:704,y:0},s1:{x:0,y:13},t1:{x:376,y:101},t2:{x:1080,y:98},t3:{x:1080,y:228}},"roteamento-canal":{cr1:{x:376,y:57},h1:{x:2488,y:175},m1:{x:1080,y:44},m2:{x:1080,y:292},s1:{x:0,y:0},t1:{x:752,y:103},t2:{x:752,y:351},t3:{x:1456,y:90},t4:{x:1456,y:220},t5:{x:1456,y:350},t6:{x:2160,y:175},x1:{x:1784,y:31},x2:{x:1784,y:279}},"status-pedido":{c1:{x:704,y:174},h1:{x:2160,y:90},http1:{x:1080,y:87},s1:{x:0,y:131},sw1:{x:1456,y:130},t1:{x:376,y:219},t2:{x:1480,y:0},t3:{x:1832,y:90},t4:{x:1832,y:220},t5:{x:1104,y:290}},"triagem-inteligente":{c1:{x:704,y:451},h1:{x:2488,y:392},ra1:{x:1080,y:351},s1:{x:0,y:408},t1:{x:376,y:496},t2:{x:1456,y:59},t3:{x:1456,y:307},t4:{x:1456,y:437},t5:{x:1456,y:567},t6:{x:2160,y:392},x1:{x:1784,y:0},x2:{x:1784,y:248},x3:{x:1784,y:496},x4:{x:1784,y:744}},"ura-reversa-spot":{h1:{x:1080,y:29},m1:{x:376,y:43},s1:{x:0,y:0},t1:{x:752,y:29},t2:{x:752,y:159}}};function VF($){let U=IX[$.id];if(U==null)return $;return{...$,editorState:{...$.editorState,nodes:$.editorState.nodes.map((Q)=>{let q=U[Q.id];return q==null?Q:{...Q,position:{...q}}})}}}var _X=[UX,jX,MX,GX,HX,PX,WX,qX,DX,eH,NX,JX,$X,VX,BX,QX,YX,KX,XX,ZX].map(($)=>VF($));var LX=[{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"}]}],FX="vars",vX="counters",WW=new Set([...LX.map(($)=>$.nodeVarName),Y8,FX,vX].map(($)=>$.split(".")[0]));function JW($){return WW.has($)}var zX={tell:new Set(["audio"]),menu:new Set(["audio","voiceTimeout"]),capture:new Set(["audio","voiceMethod","minDigits","maxDigits","terminators","voiceTimeout","listen","processing_audio","retryAudio"])},kX={tell:new Set(["content"]),menu:new Set(["text","invalidMessage"]),capture:new Set(["text","validation","invalidMessage"])};function GW($,U,Q,q){let K=$.filter((H)=>H.type==="start"),W=wF(U),J=K[0]?.id,G=hF($,U),Y=[...kF(K),...xF($,W,J),...AF($),...bF($),...OF($),...RF($),...SF($),...CF($),...EF($,U,Q),...gF($,W,J),...yF($),...uF($),...fF($,Q,q?.disabledModules),...q?.entities!=null?dq($,q.entities):[],...q?.externalEntities!=null?pq($,q.externalEntities):[],...mF($,Q,G),...q?.mediaProfile!=null?LF($,U,q.mediaProfile):[]];if(G!=null)return cF(Y,$,G);return Y}function LF($,U,Q){let q=$.find((G)=>G.type==="start");if(q==null)return[];let K=new Map;for(let G of U){let Y=K.get(G.source)??new Map;Y.set(G.sourceHandle,G.target),K.set(G.source,Y)}let W=_Q(q.id,Q.profile,$,K,Q.recordingEnabled),J=[];for(let G of $){let Y=W[G.id];if(Y==null||!FF(G.type))continue;let B=vF(G.type,Y).filter((M)=>M.value.kind==="indeterminate");if(B.length>0)J.push({nodeId:G.id,severity:"warning",messageKey:"editor:validation.mediaStateIndeterminate",params:{label:G.label,fields:B.map((M)=>M.name).join(", "),paths:B.map((M)=>zF(M.value)).join("; ")}});if(G.type==="transcription"&&Y.transcriptionEnabled.kind==="known"&&Y.transcriptionEnabled.value&&Y.recordingEnabled.kind==="known"&&!Y.recordingEnabled.value)J.push({nodeId:G.id,severity:"warning",messageKey:"editor:validation.transcriptionWithoutRecording",params:{label:G.label}})}return J}function FF($){return $==="recording"||$==="transcription"||$==="analysis"}function vF($,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:"topics",value:U.topicDetectionTopics},{name:"intents",value:U.intentDetectionIntents},{name:"structured_analysis",value:U.structuredAnalysisEnabled},{name:"analysis_ids",value:U.structuredAnalysisIds}]}function zF($){if($.kind==="known")return"";return $.branches.map((U)=>U.viaNodeLabel).join(", ")}function kF($){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 wF($){let U=new Map;for(let Q of $){let q=U.get(Q.source)??[];q.push(Q.target),U.set(Q.source,q)}return U}function xF($,U,Q){if(Q===void 0)return[];let q=new Set([Q]),K=[Q];while(K.length>0){let J=K.pop();for(let G of U.get(J)??[])if(!q.has(G))q.add(G),K.push(G)}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 AF($){let U=[];for(let Q of $){if(!Object.hasOwn(n$,Q.type)){U.push({nodeId:Q.id,severity:"error",messageKey:"editor:validation.unknownNodeType",params:{label:Q.label,type:Q.type}});continue}let q=n$[Q.type],K=q.configSchema.safeParse(Q.config),W=K.success?K.data:Q.config,J=K.success?q.configSchema.safeParse(W):K;if(J.success)continue;for(let G of J.error.issues){let Y=G.message.startsWith("editor:")?G.message:"editor:validation.invalidField";U.push({nodeId:Q.id,severity:"error",messageKey:Y,params:{label:Q.label,field:G.path.join(".")}})}}return U}function jW($){let U=[];for(let Q of $){if(Q.type!=="transfer")continue;let q=n$.transfer.configSchema.safeParse(Q.config);if(!q.success)continue;U.push({node:Q,destinations:q.data.destinations,attachedData:q.data.attachedData})}return U}function bF($){let U=[];for(let{node:Q,destinations:q}of jW($)){if(q.some((K)=>K.trim()!==""))continue;U.push({nodeId:Q.id,severity:"error",messageKey:"editor:validation.noDestinations",params:{label:Q.label}})}return U}function OF($){let U=[];for(let{node:Q,destinations:q,attachedData:K}of jW($)){let W=[...q.map((J,G)=>({field:`destinations.${G}`,template:J})),...K.map((J)=>({field:J.key,template:J.value}))];for(let{field:J,template:G}of W){if(nQ(G).valid)continue;U.push({nodeId:Q.id,severity:"error",messageKey:"editor:validation.invalidTemplateSyntax",params:{label:Q.label,field:J}})}}return U}function RF($){let U=[];for(let{node:Q,destinations:q}of jW($))q.forEach((K,W)=>{if(!/\s/.test(K.trim()))return;U.push({nodeId:Q.id,severity:"error",messageKey:"editor:validation.destinationHasSpace",params:{label:Q.label,field:`destinations.${W}`}})});return U}var TF=new Set(["httpRequest","webhook"]);function SF($){let U=[];for(let Q of $){if(!TF.has(Q.type))continue;let q=typeof Q.config.body==="string"?Q.config.body:"";if(q.trim()==="")continue;let K=q.replace(lQ(),'"__tpl__"');try{JSON.parse(K)}catch{U.push({nodeId:Q.id,severity:"warning",messageKey:"editor:validation.invalidJson",params:{label:Q.label}})}}return U}function CF($){return X8($).misplaced.map((U)=>({nodeId:U.nodeId,severity:"error",messageKey:"editor:validation.secretFieldNotAllowed",params:{label:U.label,field:U.field,secret:U.name}}))}function EF($,U,Q){let q=new Set(U.map((W)=>W.source)),K=[];for(let W of $){if(!Object.hasOwn(Q,W.type))continue;let J=Q[W.type];if(Y4(J,W.config).length===0)continue;if(q.has(W.id))continue;K.push({nodeId:W.id,severity:"warning",messageKey:"editor:validation.noOutputConnection",params:{label:W.label}})}return K}function gF($,U,Q){if(Q===void 0)return[];let q=0,K=1,W=2,J=new Map;for(let B of $)J.set(B.id,q);let G=new Set;function Y(B){J.set(B,K);for(let M of U.get(B)??[])if(J.get(M)===K)G.add(M);else if(J.get(M)===q)Y(M);J.set(B,W)}Y(Q);let H=[];for(let B of G){let M=$.find((L)=>L.id===B);if(M===void 0)continue;if(!(typeof M.config.maxAttempts==="number"&&M.config.maxAttempts>0))H.push({nodeId:B,severity:"error",messageKey:"editor:validation.infiniteCycle",params:{label:M.label}})}return H}function yF($){let U=new Map,Q=[];for(let q of $)if(U.get(q.varName)!==void 0)Q.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 Q}function uF($){return $.filter((U)=>JW(U.varName)).map((U)=>({nodeId:U.id,severity:"error",messageKey:"editor:validation.reservedVarName",params:{label:U.label,varName:U.varName}}))}function fF($,U,Q){if(Q==null||Q.size===0)return[];let q=[];for(let K of $){if(!Object.hasOwn(U,K.type))continue;let W=U[K.type];if(W.module!=="core"&&Q.has(W.module))q.push({nodeId:K.id,severity:"warning",messageKey:"editor:validation.moduleDisabled",params:{label:K.label,module:W.module}})}return q}function hF($,U){let Q=$.find((G)=>G.type==="start");if(Q==null)return null;let q=Q.config.channelType;if((typeof q==="string"?q:"voice")!=="both")return null;let W=new Map;for(let G of U){let Y=W.get(G.source);if(Y==null)Y=new Map,W.set(G.source,Y);Y.set(G.sourceHandle,G.target)}let J=new Set;for(let G of $)if(G.type==="channelRouter")J.add(G.id);return nq(Q.id,Q.config,W,$.map((G)=>G.id),J.size>0?J:void 0)}function mF($,U,Q){if(Q==null)return[];let q=[];for(let K of $){if(K.type==="start")continue;if(!Object.hasOwn(U,K.type))continue;let W=U[K.type],J=Q[K.id];if(J==null||J==="unreachable"||J==="converged")continue;if(W.channel==="voice"&&J==="chat-only")q.push({nodeId:K.id,severity:"error",messageKey:"editor:validation.voiceNodeInChatBranch",params:{label:K.label}});if(W.channel==="chat"&&J==="voice-only")q.push({nodeId:K.id,severity:"error",messageKey:"editor:validation.chatNodeInVoiceBranch",params:{label:K.label}})}return q}function cF($,U,Q){let q=new Map(U.map((K)=>[K.id,K.type]));return $.filter((K)=>{let W=K.params?.field;if(W==null||K.nodeId==="")return!0;let J=q.get(K.nodeId);if(J==null)return!0;let G=Q[K.nodeId];if(G==null||G==="converged"||G==="unreachable")return!0;let Y=W.split(".")[0];if(G==="chat-only"&&zX[J]?.has(Y))return!1;if(G==="voice-only"&&kX[J]?.has(Y))return!1;return!0})}function YW($){return $.every((U)=>U.severity!=="error")}var nF=j.object({type:j.literal("message"),message:vq}),iF=j.object({type:j.literal("typing")}),oF=j.object({type:j.literal("ping")}),dF=j.object({type:j.literal("resume"),lastSeq:j.number().int().min(0)}),pF=j.object({type:j.literal("start")}),tF=j.discriminatedUnion("type",[nF,iF,oF,dF,pF]),wX=j.object({type:j.literal("connected"),seq:j.number().int(),ts:j.number(),sessionId:j.string()}),xX=j.object({type:j.literal("message"),seq:j.number().int(),ts:j.number(),id:j.string(),message:e4}),AX=j.object({type:j.literal("typing"),seq:j.number().int(),ts:j.number(),active:j.boolean()}),bX=j.object({type:j.literal("state"),seq:j.number().int(),ts:j.number(),status:j.enum(["active","waiting_input","ended"])}),OX=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:I8.optional()}),RX=j.object({type:j.literal("error"),seq:j.number().int(),ts:j.number(),code:j.string(),message:j.string()}),TX=j.object({type:j.literal("pong"),seq:j.number().int(),ts:j.number()}),aF=j.discriminatedUnion("type",[wX,xX,AX,bX,OX,RX,TX]),sF=j.object({type:j.literal("replay"),seq:j.number().int(),ts:j.number(),messages:j.array(aF)}),eF=j.discriminatedUnion("type",[wX,xX,AX,bX,OX,RX,TX,sF]);var f$=M1(D1(),1);var $v=new Set(e6);function Uv($){return $v.has($)}var _8=($)=>$==="online"?f$.default.green($):f$.default.red($);function Kv($){let U;if($.is_expired)U=f$.default.red("expired");else if($.is_in_grace_period)U=f$.default.yellow("grace period");else U=f$.default.green($.status);let Q=$.days_until_expiry!=null?` (${$.days_until_expiry}d remaining)`:"";return` License: ${U}${Q}`}var SX=10,Qv="unlimited".padEnd(SX);function L8($,U,Q,q,K){let W=` ${$.padEnd(11)}`;if(Q==null)return`${W}${f$.default.dim(Qv)} ${U}${q}`;return`${W}${N1(U,Q,SX)} ${U}/${Q}${q} (${Math.round(K)}%)`}function qv($){let U=[f$.default.bold(" AI Usage:")],{stt:Q,tts:q,llm:K}=$;if(Q)U.push(L8("STT:",Math.round(Q.current),Q.limit," min",Q.percentage));if(q)U.push(L8("TTS:",q.current,q.limit," chars",q.percentage));if(K)U.push(L8("LLM:",K.current,K.limit," tokens",K.percentage));return U}function CX($,U){let Q=$.command("fs").description("FreeSWITCH status and debug");Q.command("status").description("Check system health (server, DB, Redis, FreeSWITCH)").action(async()=>{let{format:q,fields:K}=F($.opts()),W=await _(U().dashboard.health());if(q==="json"){let J=K?C(W,K):W;P(J);return}if(console.log(`Server: ${_8(W.server)}`),console.log(`PostgreSQL: ${_8(W.postgres)}`),console.log(`Redis: ${_8(W.redis)}`),console.log(`FreeSWITCH: ${_8(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}%`)}),Q.command("channels").description("List active FreeSWITCH channels").action(async()=>{let{format:q,fields:K}=F($.opts()),W=await _(U().dashboard.activeCalls());if(q==="json"){let J=K?W.map((G)=>C(G,K)):W;P(J);return}if(W.length===0){w("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`:"—"}))),w(`${W.length} active channel(s)`)}),Q.command("registrations").description("List SIP registrations").action(async()=>{let{format:q,fields:K}=F($.opts()),W=await _(U().testCall.registrations());if(q==="json"){let J=K?W.map((G)=>C(G,K)):W;P(J);return}if(W.length===0){w("No SIP registrations.");return}y(["Extension","Agent"],W.map((J)=>({Extension:J.extension,Agent:J.agent??"—"})))}),Q.command("dump <uuid>").description("Dump all channel variables for an active call").action(async(q)=>{let{format:K}=F($.opts()),W=await _(U().dashboard.fsDumpChannel({uuid:q}));if(Object.keys(W).length===0){if(K==="json")P({});else x(`Channel ${q} not found.`);process.exit(A.NOT_FOUND)}if(K==="json"){P(W);return}console.log(f$.default.bold(`Channel Variables — ${q}`)),console.log("");for(let[J,G]of Object.entries(W))console.log(` ${f$.default.cyan(J.padEnd(40))} ${G}`)}),Q.command("sofia").description("Show SIP profile status").action(async()=>{let{format:q}=F($.opts()),K=await _(U().dashboard.fsSofiaStatus());if(q==="json"){P(K);return}if(K.length===0){w("No Sofia profiles configured.");return}console.log(f$.default.bold("Sofia SIP Profiles")),console.log(""),y(["Name","Type","Data","State"],K.map((W)=>({Name:W.name,Type:W.type,Data:W.data,State:W.state})))}),Q.command("show <entity>").description(`Show FreeSWITCH data (${e6.join(", ")})`).action(async(q)=>{if(!Uv(q))x(`Unknown entity "${q}". Allowed: ${e6.join(", ")}`),process.exit(A.USAGE_ERROR);let{format:K}=F($.opts()),W=await _(U().dashboard.fsShow({entity:q}));if(K==="json"){P(W);return}console.log(f$.default.bold(`FreeSWITCH: show ${q}`)),console.log(""),console.log(JSON.stringify(W,null,2))}),Q.command("capacity").description("Show system capacity: channels, license, AI usage").action(async()=>{let{format:q,fields:K}=F($.opts()),W=await _(U().dashboard.capacityStatus());if(q==="json"){let G=K?C(W,K):W;P(G);return}console.log(f$.default.bold("System Capacity")),console.log("");let J=W.channels.total;if(console.log(L8("Channels:",J.active,J.limit,"",J.percentage??0)),console.log(Kv(W.license)),W.ai_usage){console.log("");for(let G of qv(W.ai_usage))console.log(G)}})}function Wv(){return Object.entries(m).map(([$,U])=>`${$} (${U}_)`).sort(($,U)=>$.localeCompare(U))}function Jv($){return Object.hasOwn(m,$)}function EX($){x($),w(" Valid entities:");for(let U of Wv())w(` ${U}`);process.exit(A.USAGE_ERROR)}function gX($,U,Q){return{input:$,entity:U,prefix:m[U],typeid:M0(U,Q),uuid:Q,sql:`'${Q}'::uuid`}}function Gv($,U){if(U!=null&&!Jv(U))EX(`Unknown entity "${U}".`);let Q=m1($);if(Q.kind==="typeid"){if(U!=null&&U!==Q.entity)x(`"${$}" is a ${Q.entity} id, but --as says ${U}.`),w(" Drop --as: a TypeID already carries its entity."),process.exit(A.USAGE_ERROR);return gX($,Q.entity,Q.uuid)}if(Q.kind==="uuid"){if(U==null)EX(`"${$}" is a UUID, which does not carry an entity - pass --as <entity>.`);return gX($,U,Q.uuid)}x(`Cannot read "${$}" as an id: ${jv[Q.reason]}.`),w(" A TypeID looks like vp_01k3vbk6hxe008000000000001; a UUID like 0198f6b9-9a3d-7000-8000-000000000001."),process.exit(A.USAGE_ERROR)}var jv={"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 yX($){$.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,Q)=>{let{format:q,fields:K}=F($.opts()),W=Gv(U,Q.as);if(Q.sql===!0){console.log(W.sql);return}if(q==="json"){P(C(W,K));return}t([{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 Yv,lstatSync as Hv,mkdirSync as Xv,readFileSync as Bv,realpathSync as fX,statSync as Zv,writeFileSync as F8}from"node:fs";import{homedir as Mv}from"node:os";import{isAbsolute as Vv,join as E1,relative as Dv}from"node:path";function uX(){return{skill:`---
|
|
99
95
|
name: niva-cli
|
|
100
96
|
description: >
|
|
101
97
|
NIVA CLI tool for IVR platform management, call debugging, and monitoring.
|
|
102
98
|
Use when: (1) debugging why a call failed, (2) monitoring system health/capacity,
|
|
103
99
|
(3) inspecting active calls, (4) searching call transcriptions,
|
|
104
100
|
(5) viewing call traces and speech analytics, (6) checking FreeSWITCH status,
|
|
105
|
-
(7) creating/editing/publishing visual plans, (8) discovering IVR node types,
|
|
101
|
+
(7) creating/editing/importing/publishing visual plans, (8) discovering IVR node types,
|
|
106
102
|
(9) testing a visual plan via chat (omnichannel), (10) any task involving the
|
|
107
103
|
\`niva\` CLI command.
|
|
108
104
|
---
|
|
@@ -113,15 +109,15 @@ CLI for managing and debugging the NIVA IVR platform. Installed via \`npm i -g @
|
|
|
113
109
|
|
|
114
110
|
All commands support \`--json\` for structured output and \`--fields x,y\` for field filtering.
|
|
115
111
|
|
|
116
|
-
The CLI
|
|
112
|
+
The CLI authenticates with \`niva login\` (browser OAuth, or device flow on headless machines). CI and automation keep working with an API key. All FreeSWITCH diagnostics are proxied through the server.
|
|
117
113
|
|
|
118
114
|
## Setup
|
|
119
115
|
|
|
120
116
|
\`\`\`bash
|
|
121
|
-
niva
|
|
117
|
+
niva login # opens the browser; on SSH/VM add --device
|
|
122
118
|
niva config set url https://niva.yourcompany.com
|
|
123
119
|
|
|
124
|
-
#
|
|
120
|
+
# CI / scripts: API key instead of a session
|
|
125
121
|
export NIVA_URL=https://niva.yourcompany.com NIVA_API_KEY=niva_xxx
|
|
126
122
|
\`\`\`
|
|
127
123
|
|
|
@@ -215,6 +211,17 @@ niva plans test <planId> --extension 1001
|
|
|
215
211
|
niva plans publish <planId> --notes "Initial release"
|
|
216
212
|
\`\`\`
|
|
217
213
|
|
|
214
|
+
## Workflow: Import an Exported Plan
|
|
215
|
+
|
|
216
|
+
The destination plan must already exist. Create an empty plan first, then import the browser or CLI export into its draft:
|
|
217
|
+
|
|
218
|
+
\`\`\`bash
|
|
219
|
+
niva plans create "Destination Plan" --description "Imported plan"
|
|
220
|
+
niva plans import <planId> plan.json
|
|
221
|
+
\`\`\`
|
|
222
|
+
|
|
223
|
+
Import replaces the destination draft and does not publish it. Do not use \`--execution-plan\` exports here: that format contains only the published execution plan.
|
|
224
|
+
|
|
218
225
|
## Execution Plan JSON Format
|
|
219
226
|
|
|
220
227
|
Plans use \`{ version, startNodeId, nodes, adjacency }\` — NOT React Flow arrays.
|
|
@@ -265,6 +272,92 @@ Rules:
|
|
|
265
272
|
|
|
266
273
|
For output handles per node type: [references/node-handles.md](references/node-handles.md)
|
|
267
274
|
|
|
275
|
+
## Media nodes
|
|
276
|
+
|
|
277
|
+
Use the plan settings for the default media profile. The \`recording\`, \`transcription\`
|
|
278
|
+
and \`analysis\` nodes apply sparse changes at the point where the flow reaches them;
|
|
279
|
+
omitted fields keep the effective value inherited from the plan or an earlier node.
|
|
280
|
+
\`--no-recording\` disables automatic recording at answer time, but a later \`recording\`
|
|
281
|
+
node can still open a capture window.
|
|
282
|
+
|
|
283
|
+
\`\`\`json
|
|
284
|
+
{
|
|
285
|
+
"ask": {
|
|
286
|
+
"type": "ivr",
|
|
287
|
+
"label": "Ask permission",
|
|
288
|
+
"varName": "ask",
|
|
289
|
+
"config": {
|
|
290
|
+
"audio": { "tts": { "text": "Press 1 to continue", "voice": "pt-BR-FranciscaNeural", "model": "edge" } },
|
|
291
|
+
"timeout": 5,
|
|
292
|
+
"maxAttempts": 3
|
|
293
|
+
}
|
|
294
|
+
},
|
|
295
|
+
"record": {
|
|
296
|
+
"type": "recording",
|
|
297
|
+
"label": "Record this section",
|
|
298
|
+
"varName": "record",
|
|
299
|
+
"config": { "enabled": true }
|
|
300
|
+
},
|
|
301
|
+
"stop": {
|
|
302
|
+
"type": "recording",
|
|
303
|
+
"label": "Stop recording for this section",
|
|
304
|
+
"varName": "stop",
|
|
305
|
+
"config": { "enabled": false }
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
\`\`\`
|
|
309
|
+
|
|
310
|
+
All three media nodes have only the \`next\` output. Media failures are warnings and
|
|
311
|
+
do not interrupt the call. Transcription only sends its active windows to ASR, and
|
|
312
|
+
analysis selection is applied after transcription.
|
|
313
|
+
|
|
314
|
+
The recording and transcription nodes expose \`status\`; recording also updates the
|
|
315
|
+
reserved \`recording\` status (\`active\`, \`inactive\` or \`not_applicable\`). It is system
|
|
316
|
+
state, not a user-created variable. Chat executions have \`not_applicable\` recording
|
|
317
|
+
state.
|
|
318
|
+
|
|
319
|
+
## Data Transform node
|
|
320
|
+
|
|
321
|
+
Use \`dataTransform\` for ordered, no-code transformations inside an execution plan. Discover the exact config schema before writing the node:
|
|
322
|
+
|
|
323
|
+
\`\`\`bash
|
|
324
|
+
niva nodes schema dataTransform --json
|
|
325
|
+
\`\`\`
|
|
326
|
+
|
|
327
|
+
Example: strip punctuation from a phone number, then normalize it to E.164:
|
|
328
|
+
|
|
329
|
+
\`\`\`json
|
|
330
|
+
{
|
|
331
|
+
"type": "dataTransform",
|
|
332
|
+
"label": "Normalize contact",
|
|
333
|
+
"varName": "contactTransform",
|
|
334
|
+
"config": {
|
|
335
|
+
"steps": [
|
|
336
|
+
{
|
|
337
|
+
"source": "{{args.phone}}",
|
|
338
|
+
"op": "regexReplace",
|
|
339
|
+
"pattern": "\\\\D+",
|
|
340
|
+
"replacement": "",
|
|
341
|
+
"saveAs": "digits"
|
|
342
|
+
},
|
|
343
|
+
{
|
|
344
|
+
"source": "{{contactTransform.digits}}",
|
|
345
|
+
"op": "normalizePhone",
|
|
346
|
+
"country": "BR",
|
|
347
|
+
"saveAs": "e164"
|
|
348
|
+
}
|
|
349
|
+
],
|
|
350
|
+
"onError": "error"
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
\`\`\`
|
|
354
|
+
|
|
355
|
+
- \`regexReplace\` replaces every match and supports JavaScript backreferences such as \`$1\`. Patterns longer than 200 characters or rejected for catastrophic backtracking return \`invalid_regex\`.
|
|
356
|
+
- \`normalizePhone\` returns E.164, defaults \`country\` to \`BR\`, and returns \`not_a_phone\` when the value cannot be normalized. \`country\` is an ISO 3166-1 alpha-2 code.
|
|
357
|
+
- \`source\` can be a template. \`pattern\`, \`replacement\`, and \`country\` are literal step settings; chain dynamic values through \`source\` and \`saveAs\`.
|
|
358
|
+
- Regex in the template form \`{{value/pattern/replacement}}\` replaces only the first match for backward compatibility; use \`regexReplace\` when every match must be replaced.
|
|
359
|
+
- \`onError\` is \`error\` (follow the node error output) or \`empty\` (continue with the operation's empty value).
|
|
360
|
+
|
|
268
361
|
## Workflow: Search Transcriptions
|
|
269
362
|
|
|
270
363
|
\`\`\`bash
|
|
@@ -340,11 +433,34 @@ niva dashboard hourly
|
|
|
340
433
|
niva dashboard top-plans
|
|
341
434
|
\`\`\`
|
|
342
435
|
|
|
436
|
+
## Workflow: Configure signals
|
|
437
|
+
|
|
438
|
+
A signal is one narrow, typed question about the call (yes/no, one option, one level). It lives in the organization's library and is linked to plans. **Be consultive:** test first, show the result, and ask before linking to a live plan - live signals need live transcription, which costs money per evaluated turn.
|
|
439
|
+
|
|
440
|
+
\`\`\`bash
|
|
441
|
+
# 1. Find a model and test it on the plan's last recorded calls
|
|
442
|
+
niva signals presets --json
|
|
443
|
+
niva signals test --preset asked_for_human --plan <planId> --last 5
|
|
444
|
+
|
|
445
|
+
# 2. Show the result, ask for confirmation, then write and link it
|
|
446
|
+
niva signals apply --file signal.json
|
|
447
|
+
niva plans configure <planId> --signals +pediu_atendente_humano
|
|
448
|
+
|
|
449
|
+
# 3. Subscribe the webhook (when the person asked for an integration)
|
|
450
|
+
niva webhooks create --url https://crm.example.com/hook --events call.signal_triggered
|
|
451
|
+
|
|
452
|
+
# 4. Explain how to check: after a real call, or during it
|
|
453
|
+
niva calls signals <callId>
|
|
454
|
+
niva calls follow <uuid>
|
|
455
|
+
\`\`\`
|
|
456
|
+
|
|
457
|
+
Pitfalls: a \`live: true\` signal only runs during the call when the plan uses **live** transcription (post-call runs it at the end) - ask before switching. Test calls are never recorded, so they never run signals; verify with a real call or \`signals test --call\`. See [references/signals.md](references/signals.md) for how to write the question, the mandatory order and the ten recipes.
|
|
458
|
+
|
|
343
459
|
## Command Groups
|
|
344
460
|
|
|
345
461
|
| Group | Purpose | Key commands |
|
|
346
462
|
|-------|---------|-------------|
|
|
347
|
-
| \`calls\` | Call debug & management | history, show, trace, transcript, purge-voice, search-text, inspect, follow, hangup |
|
|
463
|
+
| \`calls\` | Call debug & management | history, show, trace, transcript, purge-voice, search-text, inspect, follow, signals, hangup |
|
|
348
464
|
| \`logs\` | Appliance service logs (super-admin) | server, engine, freeswitch, traefik, redis, postgres, client, docs, errors, all |
|
|
349
465
|
| \`plans\` | Visual IVR plans | list, show, create, edit, configure, validate, test, publish, versions, export |
|
|
350
466
|
| \`campaigns\` | Dialer campaigns | list, show, stats, summary, create, edit, delete, start, pause, resume, stop, watch, attempts |
|
|
@@ -357,6 +473,7 @@ niva dashboard top-plans
|
|
|
357
473
|
| \`originate\` | Outbound calls | start |
|
|
358
474
|
| \`tts\` | TTS resources | voices, models, languages |
|
|
359
475
|
| \`ai\` | AI module | agents |
|
|
476
|
+
| \`signals\` | Signal library & testing | presets, list, show, test, apply, archive, unarchive |
|
|
360
477
|
| \`nodes\` | IVR node reference | list, show, schema |
|
|
361
478
|
| \`config\` | CLI configuration | set, get, show |
|
|
362
479
|
|
|
@@ -381,26 +498,316 @@ For complete command reference with all options: [references/cli-reference.md](r
|
|
|
381
498
|
- \`niva plans validate\` returns \`{ valid, issues }\` in JSON
|
|
382
499
|
- Partial UUIDs work for active call commands (hangup, inspect, follow)
|
|
383
500
|
- \`calls trace\` shows per-node error data — key for debugging
|
|
384
|
-
- All FreeSWITCH commands are server-proxied —
|
|
501
|
+
- All FreeSWITCH commands are server-proxied — authenticate with \`niva login\` (or an API key in CI)
|
|
385
502
|
- Pipe-friendly: \`niva calls history --json | jq '.items[].sentiment_label'\`
|
|
386
503
|
- \`niva campaigns watch <id> --json\` emits NDJSON (one stats event per line) — pipe into \`jq\`
|
|
387
504
|
- \`niva mailing import\` requires \`--yes\` in non-interactive mode (no TTY) — it refuses the mapping prompt otherwise
|
|
388
505
|
- \`niva dnc check <phone>\` scripting exit codes: \`0\` = on the DNC list, \`3\` = not listed
|
|
389
506
|
- \`--from\`/\`--to\`: always use ISO 8601 (\`YYYY-MM-DDT00:00:00Z\`) — works across all commands
|
|
390
507
|
- Exit codes: \`0\` ok, \`2\` usage error, \`3\` not-found, \`4\` permission denied
|
|
391
|
-
`,cliReference:"# NIVA CLI — Command Reference\n\n## Global Options\n\n| Option | Description | Default |\n|--------|-------------|---------|\n| `--url <url>` | Server URL | `http://localhost:3000` |\n| `--api-key <key>` | API key | — |\n| `--output <format>` | `json`, `table`, `plain` | Auto (TTY=table, pipe=json) |\n| `--json` | Shorthand for `--output json` | — |\n| `--fields <list>` | Comma-separated fields for JSON | All |\n| `--yes` | Skip confirmation prompts | — |\n| `--no-color` | Disable colors | — |\n\n---\n\n## calls\n\n### `niva calls list`\nList active calls.\n\n### `niva calls show <callRecordId>`\nShow CDR detail.\n\n### `niva calls hangup <uuid>`\nHang up an active call. Accepts partial UUID.\n\n### `niva calls search`\nSearch CDR records.\n- `--caller <caller>` — Filter by caller ID\n- `--page <n>` (default: 1), `--limit <n>` (default: 20)\n\n### `niva calls history`\nRich CDR listing with all filters.\n- `--from <date>` — Start date (YYYY-MM-DD)\n- `--to <date>` — End date\n- `--plan <id>` — Filter by visual plan ID\n- `--phone <id>` — Filter by phone number ID\n- `--status <status>` — answered, missed, failed, busy\n- `--caller <search>` — Search caller ID\n- `--min-duration <s>` — Min duration (seconds)\n- `--max-duration <s>` — Max duration (seconds)\n- `--has-recording` — Only with recording\n- `--has-transcription` — Only with transcription\n- `--page <n>` (default: 1), `--limit <n>` (default: 20)\n\n### `niva calls trace <callRecordId>`\nNode-by-node execution trace with timing and error data.\n\n### `niva calls transcript <callRecordId>`\nSpeaker-diarized transcript with speech analytics (sentiment, intent, summary, topics).\n\n### `niva calls purge-voice <callRecordId>`\nPermanently erase a call's voice content (LGPD right to erasure): recording file, transcription and its embeddings. The CDR, the event timeline and existing analyses are kept. Irreversible.\n- `--yes` — Skip the confirmation prompt (required in non-interactive shells)\n\n### `niva calls search-text <query>`\nSemantic search across call transcriptions.\n- `--from <date>`, `--to <date>` — Date range\n- `--plan <id>` — Filter by plan\n- `--limit <n>` (default: 20)\n- `--threshold <n>` — Similarity 0-1 (default: 0.35)\n\n### `niva calls inspect <uuid>`\nInspect active call: current node, variables, execution path. Accepts partial UUID.\n\n### `niva calls follow <uuid>`\nStream live transcription. Accepts partial UUID. Ctrl+C to stop.\n\n---\n\n## logs\n\nReads appliance service logs from the systemd journal. **Requires a platform-admin (super admin) API key** and an appliance with NIVA-125 applied (journald + gateway). Non-appliance deployments return `LOGS_UNAVAILABLE`.\n\nCommon options (all log subcommands except `calls`):\n- `--since <v>` — Start time: relative (`45s`, `30m`, `2h`, `7d`) or ISO date\n- `--until <v>` — End time: relative or ISO date\n- `--level <error|warn|info|debug>` — **Minimum** severity (`warn` → warn + error). Not available on `errors` (fixed to error).\n- `--grep <regex>` — Case-insensitive message filter\n- `--limit <n>` — Max entries per page (default: 200, max: 1000)\n- `--cursor <c>` — Pagination cursor from a previous page's `nextCursor`\n- `--follow` — Stream new entries in real time (Ctrl+C to stop). Not supported for `postgres` (`LOGS_INVALID_FILTER`).\n\nOutput:\n- Table/plain: `HH:MM:SS [service] LEVEL message` (level colored); `meta.error.message` appended when present. A `nextCursor` line closes a page when more data exists.\n- `--json`: **NDJSON** — one log object per line, plus a trailing `{ \"nextCursor\": ... }` line when a page is truncated. Pipe-friendly for `jq`.\n\n### `niva logs <service>`\nPer-service logs. `<service>` ∈ `server`, `engine`, `freeswitch`, `traefik`, `redis`, `postgres`, `client`, `docs`.\n\n### `niva logs errors`\nError-level logs merged across all services (`--level` fixed to `error`).\n\n### `niva logs all`\nMerged timeline across all services at any level.\n\n### `niva logs calls`\nView call events (DB event timeline).\n- `--uuid <uuid>` — Call record UUID\n- `--follow` — Not available here; use `niva calls follow <uuid>` for a call's live transcription.\n\n---\n\n## plans\n\n### `niva plans list`\nList visual plans. `--limit`, `--page`, `--search <term>`.\n\n### `niva plans show <planId>`\nPlan details with settings.\n\n### `niva plans create <name>`\nCreate a new visual plan.\n- `--language <code>` — Language code (e.g. pt-BR)\n- `--description <text>` — Plan description\n- `--execution-plan <file|->` — JSON file or stdin\n- `--recording` — Enable recording\n- `--transcription` — Enable transcription\n\n### `niva plans edit <planId>`\nUpdate draft execution plan.\n- `--execution-plan <file|->` (default: stdin)\n- `--expected-revision <n>` — Optimistic locking\n\n### `niva plans configure <planId>`\nConfigure settings, metadata, and DIDs.\n- `--name`, `--description` — Metadata\n- `--recording/--no-recording` — Recording toggle\n- `--transcription/--no-transcription`, `--transcription-language`, `--anonymize/--no-anonymize` — Transcription\n- `--speech-analytics/--no-speech-analytics`, `--topics <list>` — Analytics\n- `--assign-did <id>`, `--unassign-did <id>`, `--list-dids` — Phone numbers\n\n### `niva plans scaffold`\nOutput a minimal valid execution plan JSON template. `--channel <voice|chat|both>` (default: both).\n\n### `niva plans validate [planId]`\nValidate a plan. `--file <path>` for local file. Exit code 0=valid, 1=errors.\n\n### `niva plans test <planId>`\nStart a test call. `--extension <ext>` (required).\n\n### `niva plans publish <planId>`\nPublish the current draft. `--notes <text>`.\n\n### `niva plans versions <planId>`\nList version history.\n\n### `niva plans export <planId>`\nExport plan as JSON to stdout. `--execution-plan` for execution plan only.\n\n### `niva plans delete <planId>`\nDelete a visual plan.\n\n---\n\n## campaigns\n\nOutbound dialer campaigns. Requires the `dialer` module license (else `MODULE_DISABLED`) and `dialer_campaign:*` permissions.\n\nThe create/edit **field flags** are shared — only flags you pass are written:\n- `--description <text>`\n- `--caller-id <id>` — Caller ID for outbound calls\n- `--trunk-override <trunk>` — Default: org trunk\n- `--max-concurrent <n>` — Max concurrent calls\n- `--max-duration <s>` — Max call duration (seconds)\n- `--retry-attempts <n>` — Max retry attempts\n- `--retry-interval <min>` — Retry interval (minutes)\n- `--retry-on <list>` — Comma list of `busy,no_answer,failed`\n- `--window-start <HH:MM>`, `--window-end <HH:MM>` — Call window\n- `--window-days <list>` — Comma ints, 0=Sun..6=Sat — e.g. `1,2,3,4,5` = Mon–Fri\n- `--priority <n>` — 0-100\n- `--recurring` — Enable recurring dialing\n- `--auto-start-at <iso>`, `--auto-stop-at <iso>` — ISO 8601\n- `--file <path>` — JSON payload (`-` for stdin); explicit flags override file values\n\n### `niva campaigns list`\nList campaigns. `--status <s>`, `--search <term>`, `--page <n>` (default: 1), `--limit <n>` (default: 20).\n\n### `niva campaigns show <campaignId>`\nCampaign details (dialing, retry, window & schedule).\n\n### `niva campaigns stats <campaignId>`\nCounters, capacity context, and outcome bars.\n\n### `niva campaigns summary`\nRunning-campaign summary.\n\n### `niva campaigns create <name>`\nCreate a campaign. `--plan <planId>` **required** (published plan to dial) + shared field flags.\n\n### `niva campaigns edit <campaignId>`\nUpdate a campaign. `--name <name>` + shared field flags.\n\n### `niva campaigns delete <campaignId>`\nDelete a campaign.\n\n### `niva campaigns start | pause | resume | stop <campaignId>`\nControl run state. **`start` begins dialing real numbers.**\n\n### `niva campaigns watch <campaignId>`\nWatch live stats via SSE until Ctrl-C. `--json` emits NDJSON (one event per line).\n\n### `niva campaigns attempts <campaignId>`\nPer-attempt outcomes (status, hangup cause, duration). `--status <s>`, `--contact <contactId>`, `--page <n>` (default: 1), `--limit <n>` (default: 20).\n\n---\n\n## mailing\n\nCampaign mailing contacts and CSV imports. Requires the `dialer` module license.\n\n### `niva mailing list <campaignId>`\nList contacts. `--status <s>`, `--search <t>`, `--page <n>` (default: 1), `--limit <n>` (default: 20).\n\n### `niva mailing show <campaignId> <contactId>`\nShow a contact with its custom fields.\n\n### `niva mailing add <campaignId> <phone>`\nAdd a contact. `--name <n>`, `--field <key=value>` (repeatable).\n\n### `niva mailing edit <campaignId> <contactId>`\nEdit a pending contact. `--phone <p>`, `--name <n>`, `--field <key=value>` (repeatable).\n\n### `niva mailing remove <campaignId> <contactIds...>`\nRemove (soft-delete) contacts.\n\n### `niva mailing cancel <campaignId> <contactIds...>`\nCancel pending contacts.\n\n### `niva mailing requeue <campaignId> [contactIds...]`\nRequeue terminal contacts (lead recycling — re-dials people). Pass IDs, or `--all`. `--status <terminal>` restricts `--all`. IDs + `--all` together (or neither) → exit `2`.\n\n### `niva mailing import <campaignId> <file>`\nImport a CSV mailing. `phone`/`name` columns auto-guessed from pt/en synonyms; other columns become `custom:<snake_case>` fields (usable as `{{args.<field>}}`). Mapping is printed and confirmed first.\n- `--map <Column>=<role>` — override (repeatable). Roles: `phone|name|ignore|custom:<field>`.\n- `--separator <, | ;>` — separator; sniffed when omitted.\n- `--watch` — follow progress (SSE) until done/failed.\n- Non-interactive (no TTY) refuses the confirmation unless global `--yes` is passed.\n\n### `niva mailing import-status <importJobId>`\nShow an import job's status (total/processed/imported/skipped/invalid).\n\n### `niva mailing invalid-rows <importJobId>`\nOutput the CSV of rejected rows (stdout). `-o, --out <file>` writes to a file.\n\n### `niva mailing export <campaignId>`\nExport a mailing to CSV (stdout). `--status <s>`, `--search <t>`, `-o, --out <file>`. Raw field-name headers for import symmetry.\n\n---\n\n## dnc\n\nDo-not-call list. Requires the `dialer` module license and `dialer_dnc:read|manage` permissions.\n\n### `niva dnc list`\nList DNC entries. `--search <t>`, `--page <n>` (default: 1), `--limit <n>` (default: 20).\n\n### `niva dnc add <phone>`\nAdd a number. `--reason <r>`.\n\n### `niva dnc remove <ids...>`\nRemove entries by ID.\n\n### `niva dnc check <phone>`\nCheck if a number is listed (matches by digit suffix). **Exit `0` = listed, `3` = not listed.**\n\n### `niva dnc import <file>`\nBulk-import numbers, one per line (blank / `#` lines skipped). `--reason <r>` applied to all. Chunked at 10000.\n\n---\n\n## fs\n\n### `niva fs status`\nSystem health: server, PostgreSQL, Redis, FreeSWITCH.\n\n### `niva fs capacity`\nChannel usage, license status, AI usage (STT/TTS/LLM).\n\n### `niva fs channels`\nActive FreeSWITCH channels.\n\n### `niva fs registrations`\nSIP registrations (extension + user agent).\n\n### `niva fs dump <uuid>`\nDump all channel variables for an active call.\n\n### `niva fs sofia`\nSIP profile status.\n\n### `niva fs show <entity>`\nFreeSWITCH show command. Entities: `channels`, `calls`, `registrations`, `codecs`, `modules`, `aliases`.\n\n---\n\n## dashboard\n\nAll commands support: `--from <date>`, `--to <date>`, `--plan <id>`, `--phone <id>`.\n\n### `niva dashboard metrics`\nCall metrics: total, answered, missed, avg duration.\n\n### `niva dashboard sentiment`\nSentiment distribution (positive/neutral/negative/mixed).\n\n### `niva dashboard topics`\nTop discussed topics. `--limit <n>` (default: 15).\n\n### `niva dashboard intents`\nDetected intents. `--limit <n>` (default: 10).\n\n### `niva dashboard trend`\nSentiment trend. `--granularity <hour|day>` (default: day).\n\n### `niva dashboard hourly`\nCall volume by hour of day.\n\n### `niva dashboard top-plans`\nTop IVR plans by volume. `--limit <n>` (default: 5).\n\n---\n\n## chat\n\n### `niva chat test <planId>`\nInteractive test chat session (isolated from production).\n- `--editor-state <file>` — Test unpublished draft\n- `--json` — Emit `{ sessionId, wsUrl }` only\n\n### `niva chat stop <sessionId>`\nStop a test chat session.\n\n---\n\n## ws\n\n### `niva ws chat <planId>`\nInteractive chat with published plan (production endpoint).\n\n### `niva ws session <planId>`\nCreate session without interactive loop — prints `{ sessionId, wsUrl }`.\n\n---\n\n## originate\n\n### `niva originate start`\nStart an outbound call.\n- `--plan <id>` (required) — Visual plan ID\n- `--destination <target>` (required) — Phone number or SIP URI\n- `--caller-id <number>` — Caller ID\n- `--caller-id-name <name>` — Caller name\n- `--timeout <seconds>` — Ring timeout\n- `--var <key=value>` — Call variable (repeatable)\n\n---\n\n## audio-files\n\n### `niva audio-files list`\nList audio files. `--limit`, `--page`, `--search`.\n\n### `niva audio-files upload <file...>`\nUpload one or more audio files into the library. Accepted extensions: wav, mp3, ogg, flac, m4a; 10 MB each.\n\n- `--name <name>` — Library name; single file only (defaults to the filename)\n- `--duration-ms <n>` — Known duration; skips detection entirely\n- `--no-probe` — Do not fall back to `ffprobe` when the header carries no duration\n\nFiles upload one at a time. Above 10 files the command asks to confirm (`--yes` to skip). A bad file does not stop the rest: the summary lists each outcome and the exit code is the worst one, and a failure that would repeat for every file (revoked key, insufficient scope, dead connection) aborts the batch but still prints what already went in. Duration comes from the file header (wav exact, mp3 best-effort), then from `ffprobe` if it is installed, then stays empty; `NIVA_FFPROBE` points at an ffprobe outside `PATH`.\n\nUnder `--json` each file becomes `{ file, ok, id?, durationSource, error?, message? }`, where `error` is always a stable code (`FILE_UNREADABLE` for a local read failure).\n\n### `niva audio-files show <audioFileId>`\nAudio file metadata. Exits 3 when the id does not exist.\n\n### `niva audio-files download <audioFileId>`\nDownload the stored bytes. `-o, --out <path>` (`-` writes to stdout; refused only with an explicit `--json`). Without `--out` it writes to the current directory under the library filename and exits 5 rather than overwriting an existing file; `--force` overwrites on purpose. An explicit `--out` is the caller's own path and always overwrites.\n\n### `niva audio-files update <audioFileId>`\nChange `--name` and/or `--description`. Exits 2 when neither is given.\n\n### `niva audio-files delete <audioFileId>`\nDelete the audio file. Asks to confirm (`--yes` to skip). Exits 5 listing the plans that still reference it.\n\n### `niva audio-files generate-tts`\nSynthesize a new audio file from text.\n\n- `--name <name>` (required) — Library name\n- `--text <text>` / `--text-file <path>` — Text to synthesize (`-` reads stdin); mutually exclusive, one required\n- `--voice <voice>`, `--model <model>` — Defaults resolved from the organization\n- `--description <text>`\n\n### `niva audio-files regenerate-tts <audioFileId>`\nRe-synthesize an existing TTS audio file. Same text options; `--voice`, `--model`. Asks to confirm, since it overwrites the stored audio. Fails with `AUDIO_FILE_NOT_TTS` for an uploaded file.\n\n---\n\n## tts\n\n### `niva tts voices`\nList TTS voices. `--language <code>`, `--model <model>`.\n\n### `niva tts models`\nList TTS models.\n\n### `niva tts languages`\nList TTS languages.\n\n---\n\n## Other\n\n### `niva ai agents`\nList AI agents.\n\n### `niva schedules list`\nList routing schedules. `--limit`, `--page`, `--search`.\n\n### `niva secrets list`\nList the organization's secrets: name, description, the last 4 characters of the value, and how many plans reference each one (published and draft counted apart). `--limit`, `--page`, `--search`. Read-only - values are never returned, and there is no command to create, rotate or delete a secret; that happens in Settings > Secrets.\n\n### `niva channels list`\nList channels. `--limit`, `--page`, `--type`.\n\n### `niva storage usage`\nStorage usage breakdown.\n\n### `niva nodes list`\nList IVR node types. `--module`, `--category`, `--channel`.\n\n### `niva nodes show <type>`\nNode type details.\n\n### `niva nodes schema <type>`\nJSON Schema for node config.\n\n---\n\n## config\n\n### `niva config set <key> <value>`\nSet config value. Keys: `url`, `api-key`. File: `~/.niva/config.json`.\n\n### `niva config get <key>`\nGet a config value.\n\n### `niva config show`\nShow current config.\n\n---\n\n## Environment Variables\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `NIVA_URL` | Server URL | `http://localhost:3000` |\n| `NIVA_API_KEY` | API key | — |\n| `NIVA_INSECURE` | Skip TLS verification | — |\n\nPriority: CLI flags > env vars > config file > defaults.\n",nodeHandles:"# Node Output Handles (Adjacency Keys)\n\nEach node type defines which output handles can be used as adjacency keys.\n\n## Static Handles\n\n| Node Type | Handles | Notes |\n|-----------|---------|-------|\n| `tell` | `next` | |\n| `playback` | `next` | Legacy — prefer `tell` |\n| `setVariable` | `next` | |\n| `sendDtmf` | `next` | |\n| `subPlan` | `next` | |\n| `hangup` | _(none — terminal)_ | |\n| `capture` | `collected`, `noInput`, `error` | `{{varName.text}}` has captured text |\n| `collectDigits` | `collected`, `noInput`, `error` | `{{varName.digits}}` has digits |\n| `transfer` | `answered`, `busy`, `noAnswer`, `failed` | |\n| `timeRouting` | `onHours`, `offHours`, `holiday` | |\n| `aiAgent` | `completed`, `error` | `{{varName.output.*}}` for agent outputs |\n| `channelRouter` | `voice`, `chat` | |\n| `httpRequest` | `next`, `error` | |\n| `enableRecord` | `next`, `skipped`, `error` | |\n\n## Dynamic Handles (depend on config)\n\n| Node Type | Pattern | Example |\n|-----------|---------|---------|\n| `start` | `voice`, `chat` when `channelType: \"both\"` / `next` otherwise | `{ \"voice\": \"nodeA\", \"chat\": \"nodeB\" }` |\n| `switchCase` | `match:<pattern>` per case + `fallback` + `error` | `{ \"match:^[0-6]$\": \"detractor\", \"fallback\": \"unknown\" }` |\n| `menu` | `option:<id>` per option + `noMatch` + `error` | `{ \"option:sales\": \"salesNode\", \"noMatch\": \"retry\" }` |\n| `routeAi` | `intent:<label>` per intent + `notApplicable` + `error` | `{ \"intent:buy\": \"buyFlow\", \"notApplicable\": \"fallback\" }` |\n| `apiSwitch` | `match:<value>` per case + `fallback` + `error` | Legacy — prefer `switchCase` |\n"}}function mW(){return"0.2.0"}var cW=["claude","agents","both"],kb={claude:[".claude"],agents:[".agents"],both:[".agents",".claude"]},Nb=new Set(cW);function wb($){return Nb.has($)}function Mb(){let $=process.env.HOME;return $!=null&&$!==""?$:Bb()}var Ib="Install the skill for which agent?",Zb=[{label:"All (recommended)",value:"both"},{label:"Claude Code",value:"claude"},{label:"Codex / Cursor / Copilot / Gemini CLI / opencode",value:"agents"}];async function zb($){if($.target!=null){if(!wb($.target))x(`Error: invalid --target "${$.target}" — expected one of: ${cW.join(", ")}`),process.exit(R.USAGE_ERROR);return $.target}if($.yes)return"both";if($.interactive!==!0)return A("Non-interactive shell — installing for all agents. Pass --target to choose."),"both";return AQ(Ib,Zb,$.ask==null?{}:{ask:$.ask})}var rW=/^---\r?\n([\s\S]*?)\r?\n---/,Lb=/^[\w.+-]+$/;function m7($){return Lb.test($)}function Ab($){let v=rW.exec($)?.[1];if(v==null)return;let _=/^[ \t]+cli_version:(.*)$/m.exec(v)?.[1]?.trim().replaceAll(/^"|"$/g,"").trim();return _==null||!m7(_)?void 0:_}function Fb($,v){let K=$.split(`
|
|
392
|
-
|
|
508
|
+
`,cliReference:"# NIVA CLI — Command Reference\n\n## Global Options\n\n| Option | Description | Default |\n|--------|-------------|---------|\n| `--url <url>` | Server URL | `http://localhost:3000` |\n| `--api-key <key>` | API key | — |\n| `--output <format>` | `json`, `table`, `plain` | Auto (TTY=table, pipe=json) |\n| `--json` | Shorthand for `--output json` | — |\n| `--fields <list>` | Comma-separated fields for JSON | All |\n| `--yes` | Skip confirmation prompts | — |\n| `--no-color` | Disable colors | — |\n\n---\n\n## calls\n\n### `niva calls list`\nList active calls.\n\n### `niva calls show <callRecordId>`\nShow CDR detail.\n\n### `niva calls hangup <uuid>`\nHang up an active call. Accepts partial UUID.\n\n### `niva calls search`\nSearch CDR records.\n- `--caller <caller>` — Filter by caller ID\n- `--page <n>` (default: 1), `--limit <n>` (default: 20)\n\n### `niva calls history`\nRich CDR listing with all filters.\n- `--from <date>` — Start date (YYYY-MM-DD)\n- `--to <date>` — End date\n- `--plan <id>` — Filter by visual plan ID\n- `--phone <id>` — Filter by phone number ID\n- `--status <status>` — answered, missed, failed, busy\n- `--caller <search>` — Search caller ID\n- `--min-duration <s>` — Min duration (seconds)\n- `--max-duration <s>` — Max duration (seconds)\n- `--has-recording` — Only with recording\n- `--has-transcription` — Only with transcription\n- `--page <n>` (default: 1), `--limit <n>` (default: 20)\n\n### `niva calls trace <callRecordId>`\nNode-by-node execution trace with timing and error data.\n\n### `niva calls transcript <callRecordId>`\nSpeaker-diarized transcript with speech analytics (sentiment, intent, summary, topics).\n\n### `niva calls purge-voice <callRecordId>`\nPermanently erase a call's voice content (LGPD right to erasure): recording file, transcription and its embeddings. The CDR, the event timeline and existing analyses are kept. Irreversible.\n- `--yes` — Skip the confirmation prompt (required in non-interactive shells)\n\n### `niva calls search-text <query>`\nSemantic search across call transcriptions.\n- `--from <date>`, `--to <date>` — Date range\n- `--plan <id>` — Filter by plan\n- `--limit <n>` (default: 20)\n- `--threshold <n>` — Similarity 0-1 (default: 0.35)\n\n### `niva calls signals <callRecordId>`\nShow the signal results of a recorded call: signal name, value, confidence, trigger time (with `(late)` when the evaluation arrived after the call, e.g. STT catch-up) and severity. Empty when the call was never evaluated.\n\n### `niva calls inspect <uuid>`\nInspect active call: current node, variables, execution path. Accepts partial UUID.\n\n### `niva calls follow <uuid>`\nStream live transcription. Accepts partial UUID. Ctrl+C to stop. When unavailable, reports whether the call is not being recorded, is an editor test call (never recorded) or the platform has no transcription credential.\n\n---\n\n## logs\n\nReads appliance service logs from the systemd journal. **Requires a platform-admin (super admin) API key** and an appliance with NIVA-125 applied (journald + gateway). Non-appliance deployments return `LOGS_UNAVAILABLE`.\n\nCommon options (all log subcommands except `calls`):\n- `--since <v>` — Start time: relative (`45s`, `30m`, `2h`, `7d`) or ISO date\n- `--until <v>` — End time: relative or ISO date\n- `--level <error|warn|info|debug>` — **Minimum** severity (`warn` → warn + error). Not available on `errors` (fixed to error).\n- `--grep <regex>` — Case-insensitive message filter\n- `--limit <n>` — Max entries per page (default: 200, max: 1000)\n- `--cursor <c>` — Pagination cursor from a previous page's `nextCursor`\n- `--follow` — Stream new entries in real time (Ctrl+C to stop). Not supported for `postgres` (`LOGS_INVALID_FILTER`).\n\nOutput:\n- Table/plain: `HH:MM:SS [service] LEVEL message` (level colored); `meta.error.message` appended when present. A `nextCursor` line closes a page when more data exists.\n- `--json`: **NDJSON** — one log object per line, plus a trailing `{ \"nextCursor\": ... }` line when a page is truncated. Pipe-friendly for `jq`.\n\n### `niva logs <service>`\nPer-service logs. `<service>` ∈ `server`, `engine`, `freeswitch`, `traefik`, `redis`, `postgres`, `client`, `docs`.\n\n### `niva logs errors`\nError-level logs merged across all services (`--level` fixed to `error`).\n\n### `niva logs all`\nMerged timeline across all services at any level.\n\n### `niva logs calls`\nView call events (DB event timeline).\n- `--uuid <uuid>` — Call record UUID\n- `--follow` — Not available here; use `niva calls follow <uuid>` for a call's live transcription.\n\n---\n\n## plans\n\n### `niva plans list`\nList visual plans. `--limit`, `--page`, `--search <term>`.\n\n### `niva plans show <planId>`\nPlan details with settings.\n\n### `niva plans create <name>`\nCreate a new visual plan.\n- `--language <code>` — Language code (e.g. pt-BR)\n- `--description <text>` — Plan description\n- `--execution-plan <file|->` — JSON file or stdin\n- `--recording` — Enable recording\n- `--transcription` — Enable transcription\n\n### `niva plans edit <planId>`\nUpdate draft execution plan.\n- `--execution-plan <file|->` (default: stdin)\n- `--expected-revision <n>` — Optimistic locking\n\n### `niva plans configure <planId>`\nConfigure settings, metadata, and DIDs.\n- `--name`, `--description` — Metadata\n- `--recording/--no-recording` — Recording toggle\n- `--transcription/--no-transcription`, `--transcription-language`, `--anonymize/--no-anonymize` — Transcription\n- `--speech-analytics/--no-speech-analytics`, `--topics <list>` — Analytics\n- `--signals <list>` — Link signals: comma-separated `+slug` (add), `-slug` (remove) or bare `slug` (add). Sends the full sorted list; a plan that follows the organization is switched to its own list, seeded with the org defaults.\n- `--signals-inherit` / `--no-signals-inherit` — Follow the organization's signal library, or own the plan's list. `--signals-inherit` cannot be combined with `--signals`.\n- `--assign-did <id>`, `--unassign-did <id>`, `--list-dids` — Phone numbers\n\n### `niva plans scaffold`\nOutput a minimal valid execution plan JSON template. `--channel <voice|chat|both>` (default: both).\n\n### `niva plans validate [planId]`\nValidate a plan. `--file <path>` for local file. Exit code 0=valid, 1=errors.\n\n### `niva plans import <planId> <file>`\nImport a browser or CLI plan export as the draft of an existing destination plan. The command accepts `-` for stdin and does not publish the plan.\n\n### `niva plans test <planId>`\nStart a test call. `--extension <ext>` (required).\n\n### `niva plans publish <planId>`\nPublish the current draft. `--notes <text>`.\n\n### `niva plans versions <planId>`\nList version history.\n\n### `niva plans export <planId>`\nExport plan as JSON to stdout. `--execution-plan` for execution plan only.\n\n### `niva plans delete <planId>`\nDelete a visual plan.\n\n---\n\n## signals\n\nTyped questions about the call, in the organization's library and linked to plans. Requires the `ai` module and the `ai:read` / `ai:update_settings` / `ai:execute` scopes.\n\n### `niva signals presets`\nList the ten models. `--locale pt-BR|en` (default: pt-BR). `--json` prints the definitions.\n\n### `niva signals list`\nList the library. `--search <term>`, `--include-archived`, `--page <n>` (default: 1), `--limit <n>` (default: 20).\n\n### `niva signals show <slug|sig_id>`\nOne definition plus its usage (published/draft plans, triggers and evaluated calls in 7 days). Accepts the slug or the `sig_...` TypeID.\n\n### `niva signals test`\nTest one definition against one evaluation source. Exactly one of `--file`, `--preset`, `--slug` and exactly one of `--text`, `--call`, `--plan`.\n- `--file <path>` — Definition JSON (`-` for stdin); the slug is optional here.\n- `--preset <id>` — Build the definition from a model (`asked_for_human`, `wants_to_cancel`, ...).\n- `--slug <slug>` — Use a saved signal from the library.\n- `--text <text>` — Evaluate a single caller utterance.\n- `--call <call_id>` — Replay a recorded call turn by turn.\n- `--plan <plan_id>` — Replay the plan's last transcribed calls. `--last <n>` (1-5).\n- `--locale pt-BR|en` (default: pt-BR).\n\nText output marks the first turn that would trigger (`<- would trigger`) and prints the final value (`Fim da chamada`). `--json` prints the raw result.\n\n### `niva signals apply --file <path> [--dry-run]`\nCreate or update by slug (idempotent): the same body twice returns `unchanged`. Prints `created`, `updated (changed: question, options)` or `unchanged`. `--dry-run` asks the server for the same outcome with no write and no audit entry; a would-be create carries a prospective `sig_...` id that is never persisted.\n\n### `niva signals delete <slug|sig_id>`\nMove the signal to the trash: out of the plans' effective lists, keeping its history. Restore it from Settings > Archive. A signal referenced by call history cannot be permanently deleted.\n\n## campaigns\n\nOutbound dialer campaigns. Requires the `dialer` module license (else `MODULE_DISABLED`) and `dialer_campaign:*` permissions.\n\nThe create/edit **field flags** are shared — only flags you pass are written:\n- `--description <text>`\n- `--caller-id <id>` — Caller ID for outbound calls\n- `--trunk-override <trunk>` — Default: org trunk\n- `--max-concurrent <n>` — Max concurrent calls\n- `--max-duration <s>` — Max call duration (seconds)\n- `--retry-attempts <n>` — Max retry attempts\n- `--retry-interval <min>` — Retry interval (minutes)\n- `--retry-on <list>` — Comma list of `busy,no_answer,failed`\n- `--window-start <HH:MM>`, `--window-end <HH:MM>` — Call window\n- `--window-days <list>` — Comma ints, 0=Sun..6=Sat — e.g. `1,2,3,4,5` = Mon–Fri\n- `--priority <n>` — 0-100\n- `--recurring` — Enable recurring dialing\n- `--auto-start-at <iso>`, `--auto-stop-at <iso>` — ISO 8601\n- `--file <path>` — JSON payload (`-` for stdin); explicit flags override file values\n\n### `niva campaigns list`\nList campaigns. `--status <s>`, `--search <term>`, `--page <n>` (default: 1), `--limit <n>` (default: 20).\n\n### `niva campaigns show <campaignId>`\nCampaign details (dialing, retry, window & schedule).\n\n### `niva campaigns stats <campaignId>`\nCounters, capacity context, and outcome bars.\n\n### `niva campaigns summary`\nRunning-campaign summary.\n\n### `niva campaigns create <name>`\nCreate a campaign. `--plan <planId>` **required** (published plan to dial) + shared field flags.\n\n### `niva campaigns edit <campaignId>`\nUpdate a campaign. `--name <name>` + shared field flags.\n\n### `niva campaigns delete <campaignId>`\nDelete a campaign.\n\n### `niva campaigns start | pause | resume | stop <campaignId>`\nControl run state. **`start` begins dialing real numbers.**\n\n### `niva campaigns watch <campaignId>`\nWatch live stats via SSE until Ctrl-C. `--json` emits NDJSON (one event per line).\n\n### `niva campaigns attempts <campaignId>`\nPer-attempt outcomes (status, hangup cause, duration). `--status <s>`, `--contact <contactId>`, `--page <n>` (default: 1), `--limit <n>` (default: 20).\n\n---\n\n## mailing\n\nCampaign mailing contacts and CSV imports. Requires the `dialer` module license.\n\n### `niva mailing list <campaignId>`\nList contacts. `--status <s>`, `--search <t>`, `--page <n>` (default: 1), `--limit <n>` (default: 20).\n\n### `niva mailing show <campaignId> <contactId>`\nShow a contact with its custom fields.\n\n### `niva mailing add <campaignId> <phone>`\nAdd a contact. `--name <n>`, `--field <key=value>` (repeatable).\n\n### `niva mailing edit <campaignId> <contactId>`\nEdit a pending contact. `--phone <p>`, `--name <n>`, `--field <key=value>` (repeatable).\n\n### `niva mailing remove <campaignId> <contactIds...>`\nRemove (soft-delete) contacts.\n\n### `niva mailing cancel <campaignId> <contactIds...>`\nCancel pending contacts.\n\n### `niva mailing requeue <campaignId> [contactIds...]`\nRequeue terminal contacts (lead recycling — re-dials people). Pass IDs, or `--all`. `--status <terminal>` restricts `--all`. IDs + `--all` together (or neither) → exit `2`.\n\n### `niva mailing import <campaignId> <file>`\nImport a CSV mailing. `phone`/`name` columns auto-guessed from pt/en synonyms; other columns become `custom:<snake_case>` fields (usable as `{{args.<field>}}`). Mapping is printed and confirmed first.\n- `--map <Column>=<role>` — override (repeatable). Roles: `phone|name|ignore|custom:<field>`.\n- `--separator <, | ;>` — separator; sniffed when omitted.\n- `--watch` — follow progress (SSE) until done/failed.\n- Non-interactive (no TTY) refuses the confirmation unless global `--yes` is passed.\n\n### `niva mailing import-status <importJobId>`\nShow an import job's status (total/processed/imported/skipped/invalid).\n\n### `niva mailing invalid-rows <importJobId>`\nOutput the CSV of rejected rows (stdout). `-o, --out <file>` writes to a file.\n\n### `niva mailing export <campaignId>`\nExport a mailing to CSV (stdout). `--status <s>`, `--search <t>`, `-o, --out <file>`. Raw field-name headers for import symmetry.\n\n---\n\n## dnc\n\nDo-not-call list. Requires the `dialer` module license and `dialer_dnc:read|manage` permissions.\n\n### `niva dnc list`\nList DNC entries. `--search <t>`, `--page <n>` (default: 1), `--limit <n>` (default: 20).\n\n### `niva dnc add <phone>`\nAdd a number. `--reason <r>`.\n\n### `niva dnc remove <ids...>`\nRemove entries by ID.\n\n### `niva dnc check <phone>`\nCheck if a number is listed (matches by digit suffix). **Exit `0` = listed, `3` = not listed.**\n\n### `niva dnc import <file>`\nBulk-import numbers, one per line (blank / `#` lines skipped). `--reason <r>` applied to all. Chunked at 10000.\n\n---\n\n## fs\n\n### `niva fs status`\nSystem health: server, PostgreSQL, Redis, FreeSWITCH.\n\n### `niva fs capacity`\nChannel usage, license status, AI usage (STT/TTS/LLM).\n\n### `niva fs channels`\nActive FreeSWITCH channels.\n\n### `niva fs registrations`\nSIP registrations (extension + user agent).\n\n### `niva fs dump <uuid>`\nDump all channel variables for an active call.\n\n### `niva fs sofia`\nSIP profile status.\n\n### `niva fs show <entity>`\nFreeSWITCH show command. Entities: `channels`, `calls`, `registrations`, `codecs`, `modules`, `aliases`.\n\n---\n\n## dashboard\n\nAll commands support: `--from <date>`, `--to <date>`, `--plan <id>`, `--phone <id>`.\n\n### `niva dashboard metrics`\nCall metrics: total, answered, missed, avg duration.\n\n### `niva dashboard sentiment`\nSentiment distribution (positive/neutral/negative/mixed).\n\n### `niva dashboard topics`\nTop discussed topics. `--limit <n>` (default: 15).\n\n### `niva dashboard intents`\nDetected intents. `--limit <n>` (default: 10).\n\n### `niva dashboard trend`\nSentiment trend. `--granularity <hour|day>` (default: day).\n\n### `niva dashboard hourly`\nCall volume by hour of day.\n\n### `niva dashboard top-plans`\nTop IVR plans by volume. `--limit <n>` (default: 5).\n\n---\n\n## chat\n\n### `niva chat test <planId>`\nInteractive test chat session (isolated from production).\n- `--editor-state <file>` — Test unpublished draft\n- `--json` — Emit `{ sessionId, wsUrl }` only\n\n### `niva chat stop <sessionId>`\nStop a test chat session.\n\n---\n\n## ws\n\n### `niva ws chat <planId>`\nInteractive chat with published plan (production endpoint).\n\n### `niva ws session <planId>`\nCreate session without interactive loop — prints `{ sessionId, wsUrl }`.\n\n---\n\n## originate\n\n### `niva originate start`\nStart an outbound call.\n- `--plan <id>` (required) — Visual plan ID\n- `--destination <target>` (required) — Phone number or SIP URI\n- `--caller-id <number>` — Caller ID\n- `--caller-id-name <name>` — Caller name\n- `--amd` - Beta: classify the answer as machine, human, or unknown; requires `ENABLE_ORIGINATE_ANSWER_RECOGNITION=true` and emits `call.amd_completed`\n- `--machine-type` - Beta: enable AMD and, after a machine result, persist its type and include `machine_type` in the same `call.amd_completed`; requires licensed AI and a resolvable SipPulse AI key\n- `--timeout <seconds>` — Ring timeout\n- `--var <key=value>` — Call variable (repeatable)\n\n---\n\n## audio-files\n\n### `niva audio-files list`\nList audio files. `--limit`, `--page`, `--search`.\n\n### `niva audio-files upload <file...>`\nUpload one or more audio files into the library. Accepted extensions: wav, mp3, ogg, flac, m4a; 10 MB each.\n\n- `--name <name>` — Library name; single file only (defaults to the filename)\n- `--duration-ms <n>` — Known duration; skips detection entirely\n- `--no-probe` — Do not fall back to `ffprobe` when the header carries no duration\n\nFiles upload one at a time. Above 10 files the command asks to confirm (`--yes` to skip). A bad file does not stop the rest: the summary lists each outcome and the exit code is the worst one, and a failure that would repeat for every file (revoked key, insufficient scope, dead connection) aborts the batch but still prints what already went in. Duration comes from the file header (wav exact, mp3 best-effort), then from `ffprobe` if it is installed, then stays empty; `NIVA_FFPROBE` points at an ffprobe outside `PATH`.\n\nUnder `--json` each file becomes `{ file, ok, id?, durationSource, error?, message? }`, where `error` is always a stable code (`FILE_UNREADABLE` for a local read failure).\n\n### `niva audio-files show <audioFileId>`\nAudio file metadata. Exits 3 when the id does not exist.\n\n### `niva audio-files download <audioFileId>`\nDownload the stored bytes. `-o, --out <path>` (`-` writes to stdout; refused only with an explicit `--json`). Without `--out` it writes to the current directory under the library filename and exits 5 rather than overwriting an existing file; `--force` overwrites on purpose. An explicit `--out` is the caller's own path and always overwrites.\n\n### `niva audio-files update <audioFileId>`\nChange `--name` and/or `--description`. Exits 2 when neither is given.\n\n### `niva audio-files delete <audioFileId>`\nDelete the audio file. Asks to confirm (`--yes` to skip). Exits 5 listing the plans that still reference it.\n\n### `niva audio-files generate-tts`\nSynthesize a new audio file from text.\n\n- `--name <name>` (required) — Library name\n- `--text <text>` / `--text-file <path>` — Text to synthesize (`-` reads stdin); mutually exclusive, one required\n- `--voice <voice>`, `--model <model>` — Defaults resolved from the organization\n- `--description <text>`\n\n### `niva audio-files regenerate-tts <audioFileId>`\nRe-synthesize an existing TTS audio file. Same text options; `--voice`, `--model`. Asks to confirm, since it overwrites the stored audio. Fails with `AUDIO_FILE_NOT_TTS` for an uploaded file.\n\n---\n\n## tts\n\n### `niva tts voices`\nList TTS voices. `--language <code>`, `--model <model>`.\n\n### `niva tts models`\nList TTS models.\n\n### `niva tts languages`\nList TTS languages.\n\n---\n\n## Other\n\n### `niva ai agents`\nList AI agents.\n\n### `niva webhooks events`\nList the webhook event catalog, required module, exact fields, nullability, and the shared example payload. In JSON mode, the `example` field includes the aggregate `call.analysis_completed` contract with successful and failed analysis items. `--fields` filters the top-level catalog fields.\n\n### `niva schedules list`\nList routing schedules. `--limit`, `--page`, `--search`.\n\n### `niva secrets list`\nList the organization's secrets: name, description, the last 4 characters of the value, and how many plans reference each one (published and draft counted apart). `--limit`, `--page`, `--search`. Read-only - values are never returned, and there is no command to create, rotate or delete a secret; that happens in Settings > Secrets.\n\n### `niva channels list`\nList channels. `--limit`, `--page`, `--type`.\n\n### `niva storage usage`\nStorage usage breakdown.\n\n### `niva nodes list`\nList IVR node types. `--module`, `--category`, `--channel`.\n\n### `niva nodes show <type>`\nNode type details.\n\n### `niva nodes schema <type>`\nJSON Schema for node config.\n\n### Media nodes\n\n`recording` changes capture state, `transcription` selects ASR windows, and `analysis`\nselects post-transcription analyses. All three use sparse configs and only expose\n`next`; a media failure is a warning that does not interrupt the call.\n\n```json\n{\n \"type\": \"recording\",\n \"label\": \"Record this section\",\n \"varName\": \"record\",\n \"config\": { \"enabled\": true }\n}\n```\n\nUse `niva nodes schema recording --json`, `niva nodes schema transcription --json`,\nor `niva nodes schema analysis --json` for the complete schemas.\n\n### `dataTransform` node config\nThe `dataTransform` node runs ordered steps and saves each result under `saveAs`. `source` supports templates; `pattern`, `replacement`, and `country` are literal step settings.\n\n```json\n{\n \"steps\": [\n { \"source\": \"{{args.phone}}\", \"op\": \"regexReplace\", \"pattern\": \"\\\\D+\", \"replacement\": \"\", \"saveAs\": \"digits\" },\n { \"source\": \"{{contactTransform.digits}}\", \"op\": \"normalizePhone\", \"country\": \"BR\", \"saveAs\": \"e164\" }\n ],\n \"onError\": \"error\"\n}\n```\n\n- `regexReplace` replaces all matches, supports JavaScript backreferences such as `$1`, and returns `invalid_regex` for malformed, over-200-character, or unsafe patterns.\n- `normalizePhone` returns E.164 and defaults `country` to `BR` (ISO 3166-1 alpha-2). An unrecoverable value returns `not_a_phone`.\n- Template regex syntax replaces only the first match; use this node operation for a global replacement.\n- Use `niva nodes schema dataTransform --json` for the complete operation union and constraints.\n\n---\n\n## config\n\n### `niva config set <key> <value>`\nSet config value. Keys: `url`, `api-key`. File: `~/.niva/config.json`.\n\n### `niva config get <key>`\nGet a config value.\n\n### `niva config show`\nShow current config.\n\n---\n\n## auth\n\n### `niva login [--device] [--read-only]`\nAuthenticate via browser (OAuth 2.1 with PKCE). On machines without a browser (SSH, VM) — or with `--device` — uses the device flow: open the printed URL on any device and enter the code. The session is stored in `~/.niva/config.json`, keyed by server.\n\n### `niva logout`\nRevokes the session on the server and removes it from the config file.\n\n### `niva whoami`\nShows the authenticated user, organization, granted scopes and token expiry.\n\n---\n\n## Environment Variables\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `NIVA_URL` | Server URL | `http://localhost:3000` |\n| `NIVA_API_KEY` | API key (overrides an OAuth session) | — |\n| `NIVA_INSECURE` | Skip TLS verification | — |\n| `NIVA_NO_BROWSER` | Set to `1` to force the device flow | — |\n\nPriority: `--api-key` flag > `NIVA_API_KEY` > OAuth session (`niva login`) > `api-key` in the config file.\n",nodeHandles:"# Node Output Handles (Adjacency Keys)\n\nEach node type defines which output handles can be used as adjacency keys.\n\n## Static Handles\n\n| Node Type | Handles | Notes |\n|-----------|---------|-------|\n| `tell` | `next` | |\n| `playback` | `next` | Legacy — prefer `tell` |\n| `setVariable` | `next` | |\n| `sendDtmf` | `next` | |\n| `subPlan` | `next` | |\n| `hangup` | _(none — terminal)_ | |\n| `capture` | `collected`, `noInput`, `error` | `{{varName.text}}` has captured text |\n| `collectDigits` | `collected`, `noInput`, `error` | `{{varName.digits}}` has digits |\n| `transfer` | `answered`, `busy`, `noAnswer`, `failed` | |\n| `timeRouting` | `onHours`, `offHours`, `holiday` | |\n| `aiAgent` | `completed`, `error` | `{{varName.output.*}}` for agent outputs |\n| `channelRouter` | `voice`, `chat` | |\n| `httpRequest` | `next`, `error` | |\n| `webhook` | `next` | Fire-and-forget — no response, no variables, no error handle |\n| `enableRecord` | `next`, `skipped`, `error` | |\n| `recording` | `next` | Sparse capture patch; media failures are warnings and the call continues |\n| `transcription` | `next` | Opens or closes an ASR window; only selected windows are sent |\n| `analysis` | `next` | Sparse speech, topic, and structured-analysis patch |\n\n## Dynamic Handles (depend on config)\n\n| Node Type | Pattern | Example |\n|-----------|---------|---------|\n| `start` | `voice`, `chat` when `channelType: \"both\"` / `next` otherwise | `{ \"voice\": \"nodeA\", \"chat\": \"nodeB\" }` |\n| `switchCase` | `match:<pattern>` per case + `fallback` + `error` | `{ \"match:^[0-6]$\": \"detractor\", \"fallback\": \"unknown\" }` |\n| `menu` | `option:<id>` per option + `noMatch` + `error` | `{ \"option:sales\": \"salesNode\", \"noMatch\": \"retry\" }` |\n| `routeAi` | `intent:<label>` per intent + `notApplicable` + `error` | `{ \"intent:buy\": \"buyFlow\", \"notApplicable\": \"fallback\" }` |\n| `apiSwitch` | `match:<value>` per case + `fallback` + `error` | Legacy — prefer `switchCase` |\n",signals:`# Signals — typed questions about the call
|
|
509
|
+
|
|
510
|
+
A signal is one narrow, typed question about a conversation: yes/no, one option from
|
|
511
|
+
a list, or one level on a scale. It is answered by the AI at the end of every call,
|
|
512
|
+
and also during the call when the signal is marked live. Signals live in the
|
|
513
|
+
organization's library and are linked to plans; the same signal used in five plans is
|
|
514
|
+
one identity in the webhook and in the BI.
|
|
515
|
+
|
|
516
|
+
\`niva signals --help\` lists the commands. The library page is **Configurações >
|
|
517
|
+
Signals**; the agent configures it through this CLI.
|
|
518
|
+
|
|
519
|
+
## How to write the question
|
|
520
|
+
|
|
521
|
+
- **One narrow question per signal.** "Did the customer ask for a human *or* complain?"
|
|
522
|
+
is two signals, not one. A signal that asks two things cannot be counted, and the
|
|
523
|
+
answer becomes ambiguous.
|
|
524
|
+
- **Short description per option** on a list signal. The description ("Customer wants
|
|
525
|
+
a bill or invoice copy") is what lets the AI tell options apart; it does not show in
|
|
526
|
+
the report.
|
|
527
|
+
- **Scale labels from the lowest to the highest**, 3 to 5 levels. The alert condition
|
|
528
|
+
is a level, so "calm / impatient / irritated / furious" is readable; "A / B / C / D"
|
|
529
|
+
is not.
|
|
530
|
+
- **The slug is stable.** It is the key in the webhook, the CSV and the BI. It derives
|
|
531
|
+
from the name on first save and never changes; rename the name freely, not the slug.
|
|
532
|
+
|
|
533
|
+
## The mandatory order
|
|
534
|
+
|
|
535
|
+
Do not skip a step. The person owns the decision to run signals on real calls.
|
|
536
|
+
|
|
537
|
+
1. **Find a preset.** \`niva signals presets\` lists the ten models. Start from the one
|
|
538
|
+
closest to the question; adjust the name and question afterwards. Never write a
|
|
539
|
+
signal from nothing when a preset exists.
|
|
540
|
+
2. **Test on 3 to 5 recorded calls of the plan.**
|
|
541
|
+
\`niva signals test --preset <id> --plan <plan_id> --last 5\`
|
|
542
|
+
Show where it would have triggered, turn by turn.
|
|
543
|
+
3. **Show the result to the person.** Name the calls, the turns and the trigger. This
|
|
544
|
+
is the evidence that the question works before it runs on production calls.
|
|
545
|
+
4. **Ask for confirmation before linking to a live plan.** A signal on a live plan
|
|
546
|
+
costs money per evaluated turn and can page people. Wait for an explicit yes.
|
|
547
|
+
5. **Link it.** \`niva signals apply --file signal.json\` writes the definition, then
|
|
548
|
+
\`niva plans configure <plan_id> --signals +<slug>\` links it. On a plan that follows
|
|
549
|
+
the organization this switches it to its own list, seeded with the org defaults;
|
|
550
|
+
\`--signals-inherit\` together with \`--signals\` is a usage error.
|
|
551
|
+
6. **Subscribe the webhook.** \`niva webhooks create --url <url> --events call.signal_triggered\`
|
|
552
|
+
is what makes the signal actionable outside NIVA. Do this when the person asked for
|
|
553
|
+
an integration, not by default.
|
|
554
|
+
7. **Explain how to check.** After a real call: \`niva calls signals <call_id>\` shows
|
|
555
|
+
the final value and the trigger. During the call, \`niva calls follow <uuid>\` shows
|
|
556
|
+
the live transcription.
|
|
557
|
+
|
|
558
|
+
## Pitfalls
|
|
559
|
+
|
|
560
|
+
- **A live signal needs live transcription.** \`signals.live = true\` only runs during
|
|
561
|
+
the call when the plan's transcription type is **live**; with **post-call**
|
|
562
|
+
transcription it still runs, but only at the end. Switching transcription to live
|
|
563
|
+
has a real cost, so **ask before switching**. The CLI
|
|
564
|
+
prints a warning when you link a live signal to a post-call plan.
|
|
565
|
+
- **Test calls never run signals.** The editor's test call is not recorded (\`test_call\`
|
|
566
|
+
reason), so nothing evaluates. Verify with a real call or with
|
|
567
|
+
\`niva signals test --call <call_id>\` against a recorded call.
|
|
568
|
+
- **Removing an option that the alert uses is refused.** Adjust the alert in the same
|
|
569
|
+
edit before removing the option, so an alert is never silently disabled.
|
|
570
|
+
- **Deleting goes to the trash.** \`signals delete\` takes the signal out of the plans'
|
|
571
|
+
effective lists and keeps its history. Restore it from Settings > Archive.
|
|
572
|
+
A signal referenced by call history cannot be permanently deleted.
|
|
573
|
+
|
|
574
|
+
## The ten recipes
|
|
575
|
+
|
|
576
|
+
Each recipe is the preset, a test command against the plan's last calls, and the
|
|
577
|
+
\`signals apply\` body. Replace \`<plan_id>\` and the slug when the person renamed the
|
|
578
|
+
signal.
|
|
579
|
+
|
|
580
|
+
### 1. \`asked_for_human\` — Did the customer ask for a human agent?
|
|
581
|
+
|
|
582
|
+
\`\`\`bash
|
|
583
|
+
niva signals test --preset asked_for_human --plan <plan_id> --last 5
|
|
584
|
+
\`\`\`
|
|
585
|
+
|
|
586
|
+
\`\`\`json
|
|
587
|
+
{
|
|
588
|
+
"slug": "pediu_atendente_humano",
|
|
589
|
+
"name": "Pediu atendente humano",
|
|
590
|
+
"question": "O cliente pediu para falar com um atendente humano?",
|
|
591
|
+
"kind": "yes_no",
|
|
592
|
+
"speaker": "caller",
|
|
593
|
+
"scope": null,
|
|
594
|
+
"live": true,
|
|
595
|
+
"alert": { "when": { "answer": "yes" }, "severity": "warning", "bell": true }
|
|
596
|
+
}
|
|
597
|
+
\`\`\`
|
|
598
|
+
|
|
599
|
+
### 2. \`wants_to_cancel\` — Did the customer say they want to cancel or switch?
|
|
600
|
+
|
|
601
|
+
\`\`\`bash
|
|
602
|
+
niva signals test --preset wants_to_cancel --plan <plan_id> --last 5
|
|
603
|
+
\`\`\`
|
|
604
|
+
|
|
605
|
+
\`\`\`json
|
|
606
|
+
{
|
|
607
|
+
"slug": "quer_cancelar",
|
|
608
|
+
"name": "Quer cancelar",
|
|
609
|
+
"question": "O cliente disse que quer cancelar o serviço ou trocar de operadora?",
|
|
610
|
+
"kind": "yes_no",
|
|
611
|
+
"speaker": "caller",
|
|
612
|
+
"scope": null,
|
|
613
|
+
"live": true,
|
|
614
|
+
"alert": { "when": { "answer": "yes" }, "severity": "warning", "bell": false }
|
|
615
|
+
}
|
|
616
|
+
\`\`\`
|
|
617
|
+
|
|
618
|
+
### 3. \`caller_irritation\` — How irritated is the caller?
|
|
619
|
+
|
|
620
|
+
\`\`\`bash
|
|
621
|
+
niva signals test --preset caller_irritation --plan <plan_id> --last 5
|
|
622
|
+
\`\`\`
|
|
623
|
+
|
|
624
|
+
\`\`\`json
|
|
625
|
+
{
|
|
626
|
+
"slug": "irritacao_do_cliente",
|
|
627
|
+
"name": "Irritação do cliente",
|
|
628
|
+
"question": "Quão irritado está o cliente?",
|
|
629
|
+
"kind": "scale",
|
|
630
|
+
"levels": ["calmo", "impaciente", "irritado", "furioso"],
|
|
631
|
+
"speaker": "caller",
|
|
632
|
+
"scope": null,
|
|
633
|
+
"live": true,
|
|
634
|
+
"alert": { "when": { "level_at_least": 3 }, "severity": "critical", "bell": true }
|
|
635
|
+
}
|
|
636
|
+
\`\`\`
|
|
637
|
+
|
|
638
|
+
### 4. \`contact_reason\` — What is the main reason for the call?
|
|
639
|
+
|
|
640
|
+
\`\`\`bash
|
|
641
|
+
niva signals test --preset contact_reason --plan <plan_id> --last 5
|
|
642
|
+
\`\`\`
|
|
643
|
+
|
|
644
|
+
\`\`\`json
|
|
645
|
+
{
|
|
646
|
+
"slug": "motivo_do_contato",
|
|
647
|
+
"name": "Motivo do contato",
|
|
648
|
+
"question": "Qual é o motivo principal da ligação?",
|
|
649
|
+
"kind": "choice",
|
|
650
|
+
"options": [
|
|
651
|
+
{ "key": "second_copy", "label": "segunda via", "description": "Cliente quer boleto ou fatura" },
|
|
652
|
+
{ "key": "bill_dispute", "label": "contestação de conta", "description": "Cliente discorda de um valor cobrado" },
|
|
653
|
+
{ "key": "tech_support", "label": "suporte técnico", "description": "Internet, sinal ou equipamento com problema" },
|
|
654
|
+
{ "key": "cancellation", "label": "cancelamento", "description": "Cliente quer encerrar o serviço" }
|
|
655
|
+
],
|
|
656
|
+
"speaker": "caller",
|
|
657
|
+
"scope": null,
|
|
658
|
+
"live": true,
|
|
659
|
+
"alert": null
|
|
660
|
+
}
|
|
661
|
+
\`\`\`
|
|
662
|
+
|
|
663
|
+
### 5. \`formal_complaint\` — Did the customer threaten a formal complaint?
|
|
664
|
+
|
|
665
|
+
\`\`\`bash
|
|
666
|
+
niva signals test --preset formal_complaint --plan <plan_id> --last 5
|
|
667
|
+
\`\`\`
|
|
668
|
+
|
|
669
|
+
\`\`\`json
|
|
670
|
+
{
|
|
671
|
+
"slug": "ameaca_de_reclamacao_formal",
|
|
672
|
+
"name": "Ameaça de reclamação formal",
|
|
673
|
+
"question": "O cliente ameaçou reclamar no Procon, no Reclame Aqui ou na Justiça?",
|
|
674
|
+
"kind": "yes_no",
|
|
675
|
+
"speaker": "caller",
|
|
676
|
+
"scope": null,
|
|
677
|
+
"live": true,
|
|
678
|
+
"alert": { "when": { "answer": "yes" }, "severity": "critical", "bell": true }
|
|
679
|
+
}
|
|
680
|
+
\`\`\`
|
|
681
|
+
|
|
682
|
+
### 6. \`emergency_symptom\` — Did the patient describe an emergency symptom?
|
|
683
|
+
|
|
684
|
+
\`\`\`bash
|
|
685
|
+
niva signals test --preset emergency_symptom --plan <plan_id> --last 5
|
|
686
|
+
\`\`\`
|
|
687
|
+
|
|
688
|
+
\`\`\`json
|
|
689
|
+
{
|
|
690
|
+
"slug": "sintoma_de_emergencia",
|
|
691
|
+
"name": "Sintoma de emergência",
|
|
692
|
+
"question": "O paciente descreveu sintoma de emergência, como dor no peito, falta de ar ou desmaio?",
|
|
693
|
+
"kind": "yes_no",
|
|
694
|
+
"speaker": "caller",
|
|
695
|
+
"scope": null,
|
|
696
|
+
"live": true,
|
|
697
|
+
"alert": { "when": { "answer": "yes" }, "severity": "critical", "bell": true }
|
|
698
|
+
}
|
|
699
|
+
\`\`\`
|
|
700
|
+
|
|
701
|
+
### 7. \`fraud_risk\` — How likely is this call a scam attempt?
|
|
702
|
+
|
|
703
|
+
\`\`\`bash
|
|
704
|
+
niva signals test --preset fraud_risk --plan <plan_id> --last 5
|
|
705
|
+
\`\`\`
|
|
706
|
+
|
|
707
|
+
\`\`\`json
|
|
708
|
+
{
|
|
709
|
+
"slug": "risco_de_golpe",
|
|
710
|
+
"name": "Risco de golpe",
|
|
711
|
+
"question": "Qual é o risco de a ligação ser uma tentativa de golpe?",
|
|
712
|
+
"kind": "scale",
|
|
713
|
+
"levels": ["baixo", "médio", "alto"],
|
|
714
|
+
"speaker": "caller",
|
|
715
|
+
"scope": null,
|
|
716
|
+
"live": true,
|
|
717
|
+
"alert": { "when": { "level_at_least": 2 }, "severity": "critical", "bell": false }
|
|
718
|
+
}
|
|
719
|
+
\`\`\`
|
|
720
|
+
|
|
721
|
+
### 8. \`protocol_given\` — Did the agent give the protocol number?
|
|
722
|
+
|
|
723
|
+
\`\`\`bash
|
|
724
|
+
niva signals test --preset protocol_given --plan <plan_id> --last 5
|
|
725
|
+
\`\`\`
|
|
726
|
+
|
|
727
|
+
\`\`\`json
|
|
728
|
+
{
|
|
729
|
+
"slug": "protocolo_informado",
|
|
730
|
+
"name": "Protocolo informado",
|
|
731
|
+
"question": "O atendente informou o número de protocolo ao cliente?",
|
|
732
|
+
"kind": "yes_no",
|
|
733
|
+
"speaker": "agent",
|
|
734
|
+
"scope": { "node_types": ["transfer"] },
|
|
735
|
+
"live": false,
|
|
736
|
+
"alert": { "when": { "answer": "no" }, "severity": "info", "bell": false }
|
|
737
|
+
}
|
|
738
|
+
\`\`\`
|
|
739
|
+
|
|
740
|
+
### 9. \`collection_outcome\` — What was the outcome of the collection?
|
|
741
|
+
|
|
742
|
+
\`\`\`bash
|
|
743
|
+
niva signals test --preset collection_outcome --plan <plan_id> --last 5
|
|
744
|
+
\`\`\`
|
|
745
|
+
|
|
746
|
+
\`\`\`json
|
|
747
|
+
{
|
|
748
|
+
"slug": "desfecho_da_cobranca",
|
|
749
|
+
"name": "Desfecho da cobrança",
|
|
750
|
+
"question": "Qual foi o desfecho da cobrança?",
|
|
751
|
+
"kind": "choice",
|
|
752
|
+
"options": [
|
|
753
|
+
{ "key": "promised_to_pay", "label": "prometeu pagar" },
|
|
754
|
+
{ "key": "refused", "label": "recusou" },
|
|
755
|
+
{ "key": "disputed", "label": "contestou a dívida", "description": "Cliente diz que não deve ou que o valor está errado" },
|
|
756
|
+
{ "key": "call_back_later", "label": "pediu para ligar depois" }
|
|
757
|
+
],
|
|
758
|
+
"speaker": "both",
|
|
759
|
+
"scope": null,
|
|
760
|
+
"live": false,
|
|
761
|
+
"alert": { "when": { "options": ["disputed"] }, "severity": "info", "bell": false }
|
|
762
|
+
}
|
|
763
|
+
\`\`\`
|
|
764
|
+
|
|
765
|
+
### 10. \`off_script_offer\` — Did the agent offer terms outside the script?
|
|
766
|
+
|
|
767
|
+
\`\`\`bash
|
|
768
|
+
niva signals test --preset off_script_offer --plan <plan_id> --last 5
|
|
769
|
+
\`\`\`
|
|
770
|
+
|
|
771
|
+
\`\`\`json
|
|
772
|
+
{
|
|
773
|
+
"slug": "oferta_fora_do_script",
|
|
774
|
+
"name": "Oferta fora do script",
|
|
775
|
+
"question": "O agente ofereceu desconto ou condição fora do que foi combinado?",
|
|
776
|
+
"kind": "yes_no",
|
|
777
|
+
"speaker": "agent",
|
|
778
|
+
"scope": { "node_types": ["aiAgent"] },
|
|
779
|
+
"live": true,
|
|
780
|
+
"alert": { "when": { "answer": "yes" }, "severity": "warning", "bell": true }
|
|
781
|
+
}
|
|
782
|
+
\`\`\`
|
|
783
|
+
|
|
784
|
+
## Commands
|
|
785
|
+
|
|
786
|
+
| Command | What it does |
|
|
787
|
+
|---|---|
|
|
788
|
+
| \`niva signals presets [--locale pt-BR\\|en]\` | The ten models with their localized definitions. \`--json\` prints the definitions. |
|
|
789
|
+
| \`niva signals list [--search] [--include-archived] [--limit] [--page]\` | The library: slug, name, kind, live, org default, usage, triggers in 7 days, version, archived. |
|
|
790
|
+
| \`niva signals show <slug\\|sig_id>\` | One definition plus its usage. Accepts the slug or the \`sig_...\` TypeID. |
|
|
791
|
+
| \`niva signals test (--file \\| --preset \\| --slug) (--text \\| --call \\| --plan [--last N])\` | Exactly one definition source and one evaluation source. \`--json\` prints the raw result. |
|
|
792
|
+
| \`niva signals apply --file <json> [--dry-run]\` | Create or update by slug (idempotent). Prints \`created\`, \`updated (changed: ...)\` or \`unchanged\`; \`--dry-run\` writes nothing. |
|
|
793
|
+
| \`niva signals delete <slug\\|sig_id>\` | Move the signal to the trash, out of the plans' effective lists, keeping history. Restore it from Settings > Archive. |
|
|
794
|
+
| \`niva plans configure <plan_id> --signals +slug,-slug\` | Link (\`+\` or bare) and unlink (\`-\`) signals. Sends the full list; on a plan that follows the organization it switches the plan to its own list, seeded with the org defaults. |
|
|
795
|
+
| \`niva plans configure <plan_id> --signals-inherit \\| --no-signals-inherit\` | Follow the organization's library, or own the plan's list. \`--signals-inherit\` cannot be combined with \`--signals\`. |
|
|
796
|
+
| \`niva calls signals <call_id>\` | A recorded call's values and triggers: value, confidence, trigger time (with \`(late)\`), severity. |
|
|
797
|
+
`}}var hX=["claude","agents","both"],Nv={claude:[".claude"],agents:[".agents"],both:[".agents",".claude"]},Pv=new Set(hX);function Iv($){return Pv.has($)}function _v(){let $=process.env.HOME;return $!=null&&$!==""?$:Mv()}var Lv="Install the skill for which agent?",Fv=[{label:"All (recommended)",value:"both"},{label:"Claude Code",value:"claude"},{label:"Codex / Cursor / Copilot / Gemini CLI / opencode",value:"agents"}];async function vv($){if($.target!=null){if(!Iv($.target))x(`Error: invalid --target "${$.target}" — expected one of: ${hX.join(", ")}`),process.exit(A.USAGE_ERROR);return $.target}if($.yes)return"both";if($.interactive!==!0)return w("Non-interactive shell — installing for all agents. Pass --target to choose."),"both";return KJ(Lv,Fv,$.ask==null?{}:{ask:$.ask})}var mX=/^---\r?\n([\s\S]*?)\r?\n---/,zv=/^[\w.+-]+$/;function HW($){return zv.test($)}function kv($){let U=mX.exec($)?.[1];if(U==null)return;let q=/^[ \t]+cli_version:(.*)$/m.exec(U)?.[1]?.trim().replaceAll(/^"|"$/g,"").trim();return q==null||!HW(q)?void 0:q}function wv($,U){let Q=$.split(`
|
|
798
|
+
`),q=Q.findIndex((K)=>K.startsWith("metadata:"));if(q===-1)return`${$}
|
|
393
799
|
metadata:
|
|
394
|
-
cli_version: "${
|
|
395
|
-
`)}return
|
|
396
|
-
`)}function
|
|
397
|
-
${
|
|
398
|
-
---${$.slice(
|
|
399
|
-
Next page: --cursor ${
|
|
400
|
-
`)}function tW($){let v=0,K=0,_=!1;for(let U=0;U<$.length;U+=1){let Q=$[U];if(Q==='"'){if(_&&$[U+1]==='"'){U+=1;continue}_=!_}else if(!_){if(Q===",")v+=1;else if(Q===";")K+=1}}return K>v?";":","}function hb($,v){let K="",_=v;for(;_<$.length;_+=1){let U=$[_];if(U!=='"')K+=U;else if($[_+1]==='"')K+='"',_+=1;else return{value:K,end:_}}return{value:K,end:_}}function pW($,v){let K=[],_="",U=!1,Q=0;while(Q<$.length){let q=$[Q];if(q==='"'){let G=hb($,Q+1);_+=G.value,Q=G.end,U=!0}else if(q===v)K.push(U?_:_.trim()),_="",U=!1;else _+=q;Q+=1}return K.push(U?_:_.trim()),K}var i7=["phone_number","name","status","attempt_count","machine_attempts","machine_type","last_attempt_at"],ib=new Set(i7);function r7($,v){return[...v,$]}function eW($){let v={};for(let K of $){let _=K.indexOf("=");if(_<=0)x(`Invalid --field "${K}" (expected key=value)`),process.exit(R.USAGE_ERROR);v[K.slice(0,_)]=K.slice(_+1)}return v}function nb($){return $==="phone"||$==="name"||$==="ignore"||/^custom:.+$/.test($)}function lb($,v){if(v==null)return tW($);if(v!==","&&v!==";")x(`Invalid --separator "${v}" (must be , or ;)`),process.exit(R.USAGE_ERROR);return v}function ob($,v){let K=M_($),_={};for(let U of $){let Q=K.roles[U]??"ignore";if(Q!=="custom"){_[U]=Q;continue}let q=K.customNames[U];_[U]=q!=null&&q.length>0?`custom:${q}`:"ignore"}for(let U of v){let Q=U.indexOf("=");if(Q<=0)x(`Invalid --map "${U}" (expected <Column>=<role>)`),process.exit(R.USAGE_ERROR);let q=U.slice(0,Q),G=U.slice(Q+1);if(!$.includes(q))x(`Unknown column "${q}". Available: ${$.join(", ")}`),process.exit(R.USAGE_ERROR);if(!nb(G))x(`Invalid role "${G}" for column "${q}" (phone|name|ignore|custom:<field>)`),process.exit(R.USAGE_ERROR);_[q]=G}return _}function db($){if($==null)return"—";if(typeof $==="string")return $;if(typeof $==="number"||typeof $==="boolean")return String($);return JSON.stringify($)}async function tb($,v,K){let _=new AbortController;process.on("SIGINT",()=>_.abort());let U="",Q=0;if(await new Promise((q,G)=>{J1($.dialerImports.progress({importJobId:F("dialer_import_jobs",v)},{signal:_.signal}),{onEvent:(j)=>{if(U=j.status,Q=j.invalid,K==="json")console.log(JSON.stringify(j));else{let Y=j.total_rows!=null?String(j.total_rows):"-";A(`[${j.status}] processed ${j.processed_rows}/${Y} · imported ${j.imported} · skipped ${j.skipped} · invalid ${j.invalid}`)}if(j.status==="done"||j.status==="failed")q()},onError:(j)=>{if(j instanceof DOMException&&j.name==="AbortError"){q();return}G(j)},onSuccess:()=>q()})}).catch(o1),U==="failed")return R.GENERAL_ERROR;if(U==="done"&&Q>0&&K!=="json")A(`${Q} invalid row(s). Inspect with: niva mailing invalid-rows ${v}`);return R.SUCCESS}function sW($,v){let K=$.command("mailing").description("Manage campaign mailing (contacts & imports)");K.command("list <campaignId>").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(_,U)=>{let{format:Q,fields:q}=M($.opts()),G=await w(v().dialerContacts.list({campaignId:F("dialer_campaigns",_),page:Number(U.page),limit:Number(U.limit),status:E$(U.status),search:U.search}));if(Q==="json"){k(q?G.items.map((j)=>T(j,q)):G);return}y(["ID","Phone","Name","Status","Attempts","Machine","Last attempt"],G.items.map((j)=>({ID:j.id,Phone:j.phone_number,Name:j.name??"—",Status:j.status,Attempts:j.attempt_count,Machine:S6(j.machine_type),"Last attempt":j.last_attempt_at!=null?m$(j.last_attempt_at):"—"}))),_$(G)}),K.command("show <campaignId> <contactId>").description("Show a mailing contact with its custom fields").action(async(_,U)=>{let{format:Q,fields:q}=M($.opts()),G=await w(v().dialerContacts.get({campaignId:F("dialer_campaigns",_),contactId:F("dialer_contacts",U)}));if(Q==="json"){k(q?T(G,q):G);return}let j=[{title:"Contact",rows:[{label:"ID",value:G.id},{label:"Phone",value:G.phone_number},{label:"Name",value:G.name??"—"},{label:"Status",value:G.status},{label:"Attempts",value:G.attempt_count},{label:"Last attempt",value:G.last_attempt_at!=null?new Date(G.last_attempt_at).toLocaleString():"—"},{label:"Next attempt",value:G.next_attempt_at!=null?new Date(G.next_attempt_at).toLocaleString():"—"},{label:"Created",value:new Date(G.created_at).toLocaleString()}]}],Y=G.custom_fields;if(Y!=null&&typeof Y==="object"&&!Array.isArray(Y)&&Object.keys(Y).length>0)j.push({title:"Custom fields",rows:Object.entries(Y).map(([X,P])=>({label:X,value:db(P)}))});a(j)}),K.command("add <campaignId> <phone>").description("Add a single contact to a campaign mailing").option("--name <n>","Contact name").option("--field <pair>","Custom field key=value (repeatable)",r7,[]).action(async(_,U,Q)=>{let{format:q}=M($.opts()),G=eW(Q.field),j=await w(v().dialerContacts.add({campaignId:F("dialer_campaigns",_),phone_number:U,name:Q.name,custom_fields:Object.keys(G).length>0?G:void 0}));if(q==="json"){k(j);return}g(`Contact added: ${j.id}`)}),K.command("edit <campaignId> <contactId>").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)",r7,[]).action(async(_,U,Q)=>{let{format:q}=M($.opts()),G=await w(v().dialerContacts.update({campaignId:F("dialer_campaigns",_),contactId:F("dialer_contacts",U),...Q.phone!=null&&{phone_number:Q.phone},...Q.name!=null&&{name:Q.name},...Q.field.length>0&&{custom_fields:eW(Q.field)}}));if(q==="json"){k(G);return}g("Contact updated")}),K.command("remove <campaignId> <contactIds...>").description("Remove (soft-delete) mailing contacts").action(async(_,U)=>{let{format:Q}=M($.opts()),q=await w(v().dialerContacts.remove({campaignId:F("dialer_campaigns",_),ids:F("dialer_contacts",U)}));if(Q==="json"){k(q);return}g(`Removed ${q.removed}, skipped ${q.skipped}`)}),K.command("cancel <campaignId> <contactIds...>").description("Cancel pending mailing contacts").action(async(_,U)=>{let{format:Q}=M($.opts()),q=await w(v().dialerContacts.bulkCancel({campaignId:F("dialer_campaigns",_),ids:F("dialer_contacts",U)}));if(Q==="json"){k(q);return}g(`Cancelled ${q.cancelled}, skipped ${q.skipped}`)}),K.command("requeue <campaignId> [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(_,U,Q)=>{let{format:q}=M($.opts()),G=U.length>0;if(G&&Q.all===!0)x("Use either <contactIds...> or --all, not both"),process.exit(R.USAGE_ERROR);if(!G&&Q.all!==!0)x("Provide contact IDs or --all to requeue"),process.exit(R.USAGE_ERROR);if(G){let Y=await w(v().dialerContacts.bulkRequeue({campaignId:F("dialer_campaigns",_),ids:F("dialer_contacts",U)}));if(q==="json"){k(Y);return}g(`Requeued ${Y.requeued}, skipped ${Y.skipped}`);return}let j=await w(v().dialerContacts.requeueAll({campaignId:F("dialer_campaigns",_),status:E$(Q.status)}));if(q==="json"){k(j);return}g(`Requeued ${j.requeued}`)}),K.command("import <campaignId> <file>").description("Import a CSV mailing into a campaign").option("--map <pair>","Column mapping override <Column>=<role> (repeatable)",r7,[]).option("--separator <sep>","CSV separator (, or ;) — sniffed when omitted").option("--watch","Follow import progress until it finishes").action(async(_,U,Q)=>{let{format:q}=M($.opts()),G=$.opts().yes===!0,j=await cb(U),Y=j.toString("utf-8"),X=Y.search(/\r\n|\n|\r/),P=X===-1?Y:Y.slice(0,X);if(P.trim()==="")x("File is empty or has no header row"),process.exit(R.USAGE_ERROR);let B=lb(P,Q.separator),N=pW(P,B),S=ob(N,Q.map);if(q!=="json")y(["Column","Role"],N.map((D$)=>({Column:D$,Role:S[D$]??"ignore"})));await W1("Import with this mapping?",{yes:G});let f=v(),p=await w(f.dialerImports.create({campaignId:F("dialer_campaigns",_),column_mapping:S,file:new File([j],rb(U))}));if(q!=="json")g(`Import started: ${p.id} (${p.status})`);else if(Q.watch!==!0)k(p);if(Q.watch===!0){let D$=await tb(f,p.id,q);if(D$!==R.SUCCESS)process.exit(D$)}}),K.command("import-status <importJobId>").description("Show the status of a mailing import job").action(async(_)=>{let{format:U,fields:Q}=M($.opts()),q=await w(v().dialerImports.get({importJobId:F("dialer_import_jobs",_)}));if(U==="json"){k(Q?T(q,Q):q);return}a([{title:"Import job",rows:[{label:"ID",value:q.id},{label:"Status",value:q.status},{label:"Total rows",value:q.total_rows??"—"},{label:"Processed",value:q.processed_rows},{label:"Imported",value:q.imported},{label:"Skipped",value:q.skipped},{label:"Invalid",value:q.invalid},{label:"Has invalid rows",value:q.has_invalid_rows?"yes":"no"},{label:"Created",value:new Date(q.created_at).toLocaleString()}]}])}),K.command("invalid-rows <importJobId>").description("Output the CSV of rows an import rejected").option("-o, --out <file>","Write the CSV to a file instead of stdout").action(async(_,U)=>{let Q=await w(v().dialerImports.invalidRows({importJobId:F("dialer_import_jobs",_)}));if(Q==null){A("No invalid rows.");return}if(U.out!=null){await aW(U.out,Q.csv,"utf-8"),g(`Wrote invalid rows to ${U.out}`);return}process.stdout.write(Q.csv)}),K.command("export <campaignId>").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(_,U)=>{let Q=await w(v().dialerContacts.exportCsv({campaignId:F("dialer_campaigns",_),status:E$(U.status),search:U.search})),q=[],G=new Set;for await(let B of Q){q.push(B);for(let N of Object.keys(B))if(!ib.has(N))G.add(N)}if(q.length===0){A("No contacts to export.");return}let j=[...G].sort((B,N)=>B.localeCompare(N)),Y=[...i7,...j],X=q.map((B)=>[...i7.map((N)=>B[N]??""),...j.map((N)=>B[N]??"")]),P=dW(Y,X);if(U.out!=null){await aW(U.out,P,"utf-8"),g(`Wrote ${q.length} contacts to ${U.out}`);return}process.stdout.write(P)})}function $j($){if(!($ in y$))console.error(`Unknown node type: ${$}`),console.error(`Available: ${Object.keys(y$).join(", ")}`),process.exit(2)}function pb($){return $ in h1}function vj($){let v=$.command("nodes").description("IVR node types reference");v.command("list").description("List available node types").option("--module <module>","Filter by module (core, ai)").option("--category <cat>","Filter by category (basic, routing, data, integration, ai)").option("--channel <ch>","Filter by channel (voice, chat, both)").action((K)=>{let{format:_,fields:U}=M($.opts()),Q=x7();if(K.module!=null)Q=Q.filter((q)=>q.module===K.module);if(K.category!=null)Q=Q.filter((q)=>q.category===K.category);if(K.channel!=null)Q=Q.filter((q)=>q.channel===K.channel);if(_==="json"){k(U?Q.map((q)=>T(q,U)):Q);return}y(["Type","Name","Description","Module","Channel"],Q.map((q)=>({Type:q.type,Name:q.name,Description:q.description,Module:q.module,Channel:q.channel})))}),v.command("show <type>").description("Show detailed info for a node type").action((K)=>{let{format:_}=M($.opts());$j(K);let U=L6(K);if(_==="json"){k(U);return}let Q=pb(K)?h1[K]:void 0,q=Q!=null?Object.entries(Q).map(([G,j])=>({label:G,value:String(j)})):[{label:"(no fields)",value:""}];a([{title:`${U.name} (${U.type})`,rows:[{label:"Description",value:U.description},{label:"Module",value:U.module},{label:"Category",value:U.category},{label:"Channel",value:U.channel},{label:"Nature",value:U.nature}]},{title:"Config Fields",rows:q},{title:"Outputs",rows:U.outputs.map((G)=>({label:G.key,value:G.labelKey}))},{title:"Produced Variables",rows:U.producedVariables.length>0?U.producedVariables.map((G)=>({label:`${G.name} (${G.type})`,value:G.descriptionKey})):[{label:"(none)",value:""}]}])}),v.command("schema <type>").description("Output JSON Schema for a node's config (agent-friendly)").action((K)=>{$j(K);let _=L6(K);k(_.configJsonSchema)})}function ab($,v){let K=$.indexOf("=");if(K===-1)throw Error(`--var expects key=value (got: ${$})`);let _=$.slice(0,K),U=$.slice(K+1);if(_==="")throw Error(`--var expects key=value (got: ${$})`);return v[_]=U,v}function Uj($,v){$.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("--timeout <seconds>","Ring timeout in seconds (10-120)","30").option("--var <key=value>","Custom variable injected into the plan context — repeatable",ab,{}).action(async(_)=>{let{format:U}=M($.opts()),Q=Object.entries(_.var),q={planId:F("visual_plans",_.plan),destination:_.destination,timeout:Number(_.timeout),..._.callerId!==void 0?{callerId:_.callerId}:{},..._.callerIdName!==void 0?{callerIdName:_.callerIdName}:{},...Q.length>0?{variables:_.var}:{}},G=await w(v().originate.start(q));if(U==="json"){k(G);return}g(`Originated: callId=${G.callId} uuid=${G.uuid}`)})}import{readFile as eb}from"node:fs/promises";async function n7($){let v=$==="-"?await t1():await eb($,"utf-8"),K=k7.safeParse(JSON.parse(v));if(!K.success){x(`Invalid execution plan in "${$}":`);for(let _ of K.error.issues)x(` ✗ ${_.path.join(".")||"(root)"}: ${_.message}`);process.exit(R.GENERAL_ERROR)}return K.data}function l7($){let v=$.severity==="error"?"✗":"⚠",K=$.nodeId!=null?` [${$.nodeId}]`:"";return` ${v}${K} ${$.messageKey}`}var sb="! 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 Kj($){try{let v=w_($),K=E7(v.nodes,v.edges,w1);if(!y7(K)){for(let _ of K)x(l7(_));return!1}return DQ(sb),!0}catch(v){return x(v instanceof Error?v.message:String(v)),!1}}async function $k($,v,K,_){if(await w($.channels.update({channelId:F("channels",v),visual_plan_id:F("visual_plans",K),reassign:!0})),_!=="json")g(`Channel ${v} assigned to plan`)}async function vk($,v,K){if(await w($.channels.update({channelId:F("channels",v),visual_plan_id:null})),K!=="json")g(`Channel ${v} unassigned from plan`)}async function Uk($,v,K){let _=F("visual_plans",v),U=await w($.channels.list({page:1,limit:100})),Q=U.items.filter((G)=>G.visual_plan_id===_),q=U.items.filter((G)=>G.visual_plan_id==null);if(K==="json"){k({assigned:Q,available:q});return}if(Q.length>0)console.log(`
|
|
401
|
-
Assigned to this plan:`),y(["ID","Type","Name","Identifier","Active"],
|
|
402
|
-
Available (unassigned):`),y(["ID","Type","Name","Identifier"],q.map((G)=>({ID:G.id,Type:G.channel_type,Name:G.name,Identifier:G.identifier??"—"})))}function Kk($,v){return{planId:F("visual_plans",$),...v.name!=null&&{name:v.name},...v.description!=null&&{description:v.description},...v.recording!==void 0&&{recording_enabled:v.recording},...v.transcription!==void 0&&{transcription_enabled:v.transcription},...v.transcriptionLanguage!=null&&{transcription_language:v.transcriptionLanguage},...v.anonymize!==void 0&&{anonymize_enabled:v.anonymize},...v.speechAnalytics!==void 0&&{speech_analytics_enabled:v.speechAnalytics},...v.topics!=null&&{topic_detection_topics:v.topics.split(",").map((K)=>K.trim())}}}function Qj($,v){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(_)=>{let{format:U,fields:Q}=M($.opts()),q=await w(v().visualPlans.list({page:Number(_.page),limit:Number(_.limit),search:_.search}));if(U==="json"){let G=Q?q.items.map((j)=>T(j,Q)):q;k(G);return}y(["ID","Name","Channel","Status","Created"],q.items.map((G)=>({ID:G.id,Name:G.name,Channel:G.channel_type,Status:G.published_version_id!=null?"published":"draft",Created:new Date(G.created_at).toLocaleDateString()}))),_$(q)}),K.command("show <planId>").description("Show plan details with settings").action(async(_)=>{let{format:U,fields:Q}=M($.opts()),q=await w(v().visualPlans.getById({planId:F("visual_plans",_)}));if(U==="json"){let G=Q?T(q,Q):q;k(G);return}a([{title:"Plan",rows:[{label:"ID",value:q.id},{label:"Name",value:q.name},{label:"Channel",value:q.channel_type},{label:"Status",value:q.published_version_id!=null?"published":"draft"},{label:"Created",value:new Date(q.created_at).toLocaleString()},{label:"Updated",value:new Date(q.updated_at).toLocaleString()}]},{title:"Settings",rows:[{label:"Recording",value:q.recording_enabled?"enabled":"disabled"},{label:"Transcription",value:q.transcription_enabled?"enabled":"disabled"},{label:"Language",value:q.transcription_language??"—"},{label:"Anonymize",value:q.anonymize_enabled?"enabled":"disabled"},{label:"Speech Analytics",value:q.speech_analytics_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(_,U)=>{let{format:Q}=M($.opts()),q;if(U.executionPlan!=null){if(q=await n7(U.executionPlan),!Kj(q))process.exit(1)}let G=await w(v().visualPlans.create({name:_,language:U.language,description:U.description,recording_enabled:U.recording??!1,transcription_enabled:U.transcription??!1,executionPlan:q}));if(Q==="json"){k(G);return}g(`Plan created: ${G.id}`)}),K.command("edit <planId>").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(_,U)=>{let{format:Q}=M($.opts()),q=await n7(U.executionPlan);if(!Kj(q))process.exit(1);let G=await w(v().visualPlans.saveDraft({planId:F("visual_plans",_),executionPlan:q,expectedRevision:U.expectedRevision!=null?Number(U.expectedRevision):void 0}));if(Q==="json"){k(G);return}g(`Draft updated (revision ${G.revision})`)}),K.command("configure <planId>").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 speech analytics").option("--no-speech-analytics","Disable speech analytics").option("--topics <list>","Topic detection topics (comma-separated)").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(_,U)=>{let{format:Q}=M($.opts()),q=v();if(U.assignDid!=null)await $k(q,U.assignDid,_,Q);if(U.unassignDid!=null)await vk(q,U.unassignDid,Q);if(U.listDids===!0){await Uk(q,_,Q);return}let G=Kk(_,U);if(Object.keys(G).length>1){let j=await w(q.visualPlans.update(G));if(Q==="json"){k(j);return}g("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((_)=>{let U=["voice","chat","both"];if(!U.includes(_.channel))x(`Invalid channel type: ${_.channel}. Must be one of: ${U.join(", ")}`),process.exit(2);let Q=_.channel;k({version:1,startNodeId:"start",nodes:{start:{type:"start",label:"Start",varName:"start",config:{channelType:Q}},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:Q==="both"?{voice:"greeting",chat:"greeting"}:{next:"greeting"},greeting:{next:"end"}}})}),K.command("delete <planId>").description("Delete a visual plan").action(async(_)=>{let{format:U}=M($.opts());if(await w(v().visualPlans.delete({planId:F("visual_plans",_)})),U==="json"){k({success:!0});return}g("Plan deleted")}),K.command("validate [planId]").description("Validate a plan (saved draft or local file)").option("--file <path>","Validate a local execution plan JSON file").action(async(_,U)=>{let{format:Q}=M($.opts());if(U.file!=null){let G=await n7(U.file),j=await w(v().visualPlans.validate({executionPlan:G}));if(Q==="json"){k(j);return}_j(j),process.exit(j.valid?0:1)}if(_==null)x("Provide a plan ID or --file <path>"),process.exit(2);let q=await w(v().visualPlans.validate({planId:F("visual_plans",_)}));if(Q==="json"){k(q);return}_j(q),process.exit(q.valid?0:1)}),K.command("test <planId>").description("Start a test call for a plan").requiredOption("--extension <ext>","SIP extension to call").action(async(_,U)=>{let{format:Q}=M($.opts()),q=await w(v().testCall.start({planId:F("visual_plans",_),extension:U.extension}));if(Q==="json"){k(q);return}g(`Test call started: uuid=${q.uuid}`),A(`Test ID: ${q.testId}`),A("Use 'niva calls follow <uuid>' to watch the call")}),K.command("publish <planId>").description("Publish the current draft").option("--notes <text>","Publication notes").action(async(_,U)=>{let{format:Q}=M($.opts()),q=await w(v().visualPlans.publish({planId:F("visual_plans",_),notes:U.notes}));if(Q==="json"){k(q);return}g(`Plan published (version ${q.version})`)}),K.command("versions <planId>").description("List version history").action(async(_)=>{let{format:U}=M($.opts()),Q=await w(v().visualPlans.listVersions({planId:F("visual_plans",_)}));if(U==="json"){k(Q);return}y(["Version","Status","Published By","Published At","Notes"],Q.items.map((q)=>({Version:q.version,Status:q.status,"Published By":q.last_edited_by_name??"—","Published At":q.published_at!=null?new Date(q.published_at).toLocaleString():"—",Notes:q.notes??"—"})))}),K.command("export <planId>").description("Export plan as JSON to stdout (pipe-friendly)").option("--execution-plan","Export only the execution plan (if published)").action(async(_,U)=>{if(U.executionPlan===!0){let G=(await w(v().visualPlans.listVersions({planId:F("visual_plans",_)}))).items.find((j)=>j.status==="published"&&j.execution_plan!=null);if(G!=null)k(G.execution_plan);else x("No published version with execution plan found"),process.exit(1);return}let Q=await w(v().visualPlans.getById({planId:F("visual_plans",_)}));k(Q)})}function _j($){if($.valid){g("✓ Plan is valid");return}let v=$.issues.filter((_)=>_.severity==="error"),K=$.issues.filter((_)=>_.severity==="warning");if(v.length>0){x(`✗ ${v.length} error(s):`);for(let _ of v)x(l7(_))}if(K.length>0){A(` ${K.length} warning(s):`);for(let _ of K)A(l7(_))}}function qj($,v){$.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(_)=>{let{format:U,fields:Q}=M($.opts()),q=await w(v().schedules.list({page:Number(_.page),limit:Number(_.limit),search:_.search}));if(U==="json"){let G=Q?q.items.map((j)=>T(j,Q)):q;k(G);return}y(["ID","Name","Description"],q.items.map((G)=>({ID:G.id,Name:G.name,Description:G.description??"—"}))),_$(q)})}var _k="···";function Qk($){return $===""?"—":`${_k}${$}`}function Gj($,v){$.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(_)=>{let{format:U,fields:Q}=M($.opts()),q=await w(v().secrets.list({page:Number(_.page),limit:Number(_.limit),search:_.search}));if(U==="json"){let G=Q?q.items.map((j)=>T(j,Q)):q;k(G);return}y(["ID","Name","Description","Value","Published","Draft","Updated"],q.items.map((G)=>({ID:G.id,Name:G.name,Description:G.description??"—",Value:Qk(G.value_suffix),Published:G.usage_count.published,Draft:G.usage_count.draft,Updated:new Date(G.updated_at).toLocaleString()}))),_$(q)})}var R$=v1(Q1(),1);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 qk($){if($==="critical")return R$.default.red($.toUpperCase());if($==="warning")return R$.default.yellow($.toUpperCase());return R$.default.green($.toUpperCase())}function Wj($,v){$.command("storage").description("Storage observability and cache stats").command("usage").description("Show storage usage breakdown").action(async()=>{let{format:_}=M($.opts()),U=await w(v().dashboard.storageUsage({}));if(_==="json"){k(U);return}let Q=Math.round(U.disk.usagePercent);console.log(`
|
|
403
|
-
${
|
|
404
|
-
${
|
|
405
|
-
${
|
|
406
|
-
${
|
|
800
|
+
cli_version: "${U}"`;if(Q[q]!=="metadata:")return $;for(let K=q+1;K<Q.length;K++){let W=Q[K];if(!/^\s+\S/.test(W))break;if(/^\s+cli_version:/.test(W))return Q[K]=` cli_version: "${U}"`,Q.join(`
|
|
801
|
+
`)}return Q.splice(q+1,0,` cli_version: "${U}"`),Q.join(`
|
|
802
|
+
`)}function xv($,U){if(!HW(U))throw Error(`Refusing to stamp a malformed CLI version: ${JSON.stringify(U)}`);let Q=mX.exec($),q=Q?.[1];if(Q==null||q==null)return $;return`---
|
|
803
|
+
${wv(q,U)}
|
|
804
|
+
---${$.slice(Q.index+Q[0].length)}`}var Av=["skills","niva-cli","references"];function bv($,U){let Q=Dv(U,$);return Q===""||!Q.startsWith("..")&&!Vv(Q)}function Ov($,U){let Q;try{Q=fX($)}catch{return`${$} does not exist or cannot be resolved.`}let q=$;for(let K of[U,...Av]){q=E1(q,K);let W=Hv(q,{throwIfNoEntry:!1});if(W==null)return;if(W.isSymbolicLink()){let J;try{J=fX(q)}catch{return`${q} is a broken symlink — remove it and retry.`}if(!bv(J,Q))return`${q} is a symlink pointing outside ${Q} (${J}) — refusing to write through it.`}if(!Zv(q).isDirectory())return`${q} already exists and is not a directory — remove it and retry.`}return}function Rv($){try{return kv(Bv($,"utf-8"))}catch{return}}function Tv($,U,Q){if(!Yv($))return;let q=Rv($);if(q==null)w(`Existing skill found in ${U} (version unknown) — overwriting.`);else if(q===Q)w(`Existing skill found in ${U} — overwriting.`);else w(`Updating skill in ${U} from ${q} to ${Q}.`)}function Sv($,U,Q,q){let K=E1($,"references");try{Xv(K,{recursive:!0}),F8(E1($,"SKILL.md"),Q),F8(E1(K,"cli-reference.md"),q.cliReference),F8(E1(K,"node-handles.md"),q.nodeHandles),F8(E1(K,"signals.md"),q.signals)}catch(W){x(`Error: could not write ${U} — ${W instanceof Error?W.message:String(W)}`),process.exit(A.GENERAL_ERROR)}}function cX($){$.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 Q=await vv({target:U.target,yes:$.opts().yes===!0,interactive:UJ()}),q=W6();if(!HW(q))x(`Error: CLI_VERSION is not a plain version string (${JSON.stringify(q)}) — refusing to write the skill.`),process.exit(A.USAGE_ERROR);let K=U.global===!0,W=K?_v():process.cwd(),J=K?"~/":"",G=Nv[Q],Y=G.map((V)=>Ov(W,V)).filter((V)=>V!=null);if(Y.length>0){for(let V of Y)x(`Error: ${V}`);w("Nothing was installed."),process.exit(A.GENERAL_ERROR)}let H=uX(),B=xv(H.skill,q),M=[];for(let V of G){let L=E1(W,V,"skills","niva-cli"),T=`${J}${V}/skills/niva-cli/`;Tv(E1(L,"SKILL.md"),T,q),Sv(L,T,B,H),M.push(T)}E(`NIVA CLI skill v${q} installed to:`);for(let V of M)E(` ${V}`);w("Your coding agent will now use the NIVA CLI for IVR management tasks.")})}var g1=M1(D1(),1);var Cv=["server","engine","freeswitch","traefik","redis","postgres","client","docs"],Ev={error:g1.default.red,warn:g1.default.yellow,info:g1.default.green,debug:g1.default.dim};function gv($){if($==null)return;let U=$.error;if(U!=null&&typeof U==="object"&&"message"in U){let Q=U.message;if(typeof Q==="string")return Q}return}function lX($){let U=new Date($.ts),Q=Number.isNaN(U.getTime())?$.ts:`${String(U.getHours()).padStart(2,"0")}:${String(U.getMinutes()).padStart(2,"0")}:${String(U.getSeconds()).padStart(2,"0")}`,K=(Ev[$.level]??((Y)=>Y))($.level.toUpperCase().padEnd(5)),W=g1.default.cyan(`[${$.service}]`),J=`${g1.default.dim(Q)} ${W} ${K} ${$.message}`,G=gv($.meta);if(G!=null)J+=g1.default.red(` — ${G}`);return J}function XW($,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 yv($,U){return new Promise((Q,q)=>{F1($,{onEvent:(K)=>{if(U==="json")console.log(JSON.stringify(K));else console.log(lX(K))},onError:(K)=>{if(K instanceof DOMException&&K.name==="AbortError"){Q();return}q(K)},onSuccess:()=>Q()})})}async function uv($,U,Q){let q=new AbortController;process.on("SIGINT",()=>{q.abort()});try{await yv($.system.watchLogs(U,{signal:q.signal}),Q)}catch(K){h1(K)}}async function BW($,U,Q,q,K){let{format:W,fields:J}=F(Q.opts()),G=p$(K??U.level);if(U.follow===!0){await uv(q(),{service:$,level:G,grep:U.grep},W);return}let Y={service:$,since:U.since,until:U.until,level:G,grep:U.grep,limit:U.limit!=null?Number(U.limit):void 0,cursor:U.cursor},H=await _(q().system.logs(Y));if(W==="json"){for(let B of H.entries){let M=J?C(B,J):B;console.log(JSON.stringify(M))}if(H.nextCursor!=null)console.log(JSON.stringify({nextCursor:H.nextCursor}));return}if(H.entries.length===0){w("No log entries.");return}for(let B of H.entries)console.log(lX(B));if(H.nextCursor!=null)w(`
|
|
805
|
+
Next page: --cursor ${H.nextCursor}`)}function rX($,U){let Q=$.command("logs").description("View service logs and call events");Q.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)d$("Live call-event streaming is not available here. Use `niva calls follow <uuid>` to stream a call's live transcription.");let J=W.callRecord??W.uuid;if(J==null)d$("Please provide --call-record or --follow.");let{format:G,fields:Y}=F($.opts()),H=await _(U().callRecords.getEvents({call_record_id:b("call_records",J)}));if(G==="json"){let B=Y?H.map((M)=>C(M,Y)):H;P(B);return}if(H.length===0){w("No events found.");return}y(["Timestamp","Event","Details"],H.map((B)=>({Timestamp:new Date(B.entered_at).toLocaleString(),Event:B.node_type,Details:B.data!=null?JSON.stringify(B.data):"—"})))});for(let W of Cv){let J=Q.command(W).description(`View ${W} service logs from the appliance journal`);XW(J),J.action(async(G)=>BW(W,G,$,U))}let q=Q.command("errors").description("View error-level logs across all services (merged timeline)");XW(q,{fixedLevel:!0}),q.action(async(W)=>BW("all",W,$,U,"error"));let K=Q.command("all").description("View a merged timeline of logs from all services");XW(K),K.action(async(W)=>BW("all",W,$,U))}import{readFile as hv,writeFile as pX}from"node:fs/promises";import{basename as mv}from"node:path";function nX($){if($==null)return'""';return`"${String($).replaceAll('"','""')}"`}function iX($,U,Q=","){let q=[$.map((K)=>nX(K)).join(Q)];for(let K of U)q.push(K.map((W)=>nX(W)).join(Q));return q.join(`\r
|
|
806
|
+
`)}function oX($){let U=0,Q=0,q=!1;for(let K=0;K<$.length;K+=1){let W=$[K];if(W==='"'){if(q&&$[K+1]==='"'){K+=1;continue}q=!q}else if(!q){if(W===",")U+=1;else if(W===";")Q+=1}}return Q>U?";":","}function fv($,U){let Q="",q=U;for(;q<$.length;q+=1){let K=$[q];if(K!=='"')Q+=K;else if($[q+1]==='"')Q+='"',q+=1;else return{value:Q,end:q}}return{value:Q,end:q}}function dX($,U){let Q=[],q="",K=!1,W=0;while(W<$.length){let J=$[W];if(J==='"'){let G=fv($,W+1);q+=G.value,W=G.end,K=!0}else if(J===U)Q.push(K?q:q.trim()),q="",K=!1;else q+=J;W+=1}return Q.push(K?q:q.trim()),Q}var MW=["phone_number","name","status","attempt_count","machine_attempts","machine_type","last_attempt_at"],cv=new Set(MW);function ZW($,U){return[...U,$]}function tX($){let U={};for(let Q of $){let q=Q.indexOf("=");if(q<=0)x(`Invalid --field "${Q}" (expected key=value)`),process.exit(A.USAGE_ERROR);U[Q.slice(0,q)]=Q.slice(q+1)}return U}function lv($){return $==="phone"||$==="name"||$==="ignore"||/^custom:.+$/.test($)}function rv($,U){if(U==null)return oX($);if(U!==","&&U!==";")x(`Invalid --separator "${U}" (must be , or ;)`),process.exit(A.USAGE_ERROR);return U}function nv($,U){let Q=LQ($),q={};for(let K of $){let W=Q.roles[K]??"ignore";if(W!=="custom"){q[K]=W;continue}let J=Q.customNames[K];q[K]=J!=null&&J.length>0?`custom:${J}`:"ignore"}for(let K of U){let W=K.indexOf("=");if(W<=0)x(`Invalid --map "${K}" (expected <Column>=<role>)`),process.exit(A.USAGE_ERROR);let J=K.slice(0,W),G=K.slice(W+1);if(!$.includes(J))x(`Unknown column "${J}". Available: ${$.join(", ")}`),process.exit(A.USAGE_ERROR);if(!lv(G))x(`Invalid role "${G}" for column "${J}" (phone|name|ignore|custom:<field>)`),process.exit(A.USAGE_ERROR);q[J]=G}return q}function iv($){if($==null)return"—";if(typeof $==="string")return $;if(typeof $==="number"||typeof $==="boolean")return String($);return JSON.stringify($)}async function ov($,U,Q){let q=new AbortController;process.on("SIGINT",()=>q.abort());let K="",W=0;if(await new Promise((J,G)=>{F1($.dialerImports.progress({import_job_id:b("dialer_import_jobs",U)},{signal:q.signal}),{onEvent:(Y)=>{if(K=Y.status,W=Y.invalid,Q==="json")console.log(JSON.stringify(Y));else{let H=Y.total_rows!=null?String(Y.total_rows):"-";w(`[${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}G(Y)},onSuccess:()=>J()})}).catch(Z4),K==="failed")return A.GENERAL_ERROR;if(K==="done"&&W>0&&Q!=="json")w(`${W} invalid row(s). Inspect with: niva mailing invalid-rows ${U}`);return A.SUCCESS}function aX($,U){let Q=$.command("mailing").description("Manage campaign mailing (contacts & imports)");Q.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,K)=>{let{format:W,fields:J}=F($.opts()),G=await _(U().dialerContacts.list({campaign_id:b("dialer_campaigns",q),page:Number(K.page),limit:Number(K.limit),status:p$(K.status),search:K.search}));if(W==="json"){P(J?G.items.map((Y)=>C(Y,J)):G);return}y(["ID","Phone","Name","Status","Attempts","Machine","Last attempt"],G.items.map((Y)=>({ID:Y.id,Phone:Y.phone_number,Name:Y.name??"—",Status:Y.status,Attempts:Y.attempt_count,Machine:j0(Y.machine_type),"Last attempt":Y.last_attempt_at!=null?a$(Y.last_attempt_at):"—"}))),j$(G)}),Q.command("show <campaign_id> <contact_id>").description("Show a mailing contact with its custom fields").action(async(q,K)=>{let{format:W,fields:J}=F($.opts()),G=await _(U().dialerContacts.get({campaign_id:b("dialer_campaigns",q),contact_id:b("dialer_contacts",K)}));if(W==="json"){P(J?C(G,J):G);return}let Y=[{title:"Contact",rows:[{label:"ID",value:G.id},{label:"Phone",value:G.phone_number},{label:"Name",value:G.name??"—"},{label:"Status",value:G.status},{label:"Attempts",value:G.attempt_count},{label:"Last attempt",value:G.last_attempt_at!=null?new Date(G.last_attempt_at).toLocaleString():"—"},{label:"Next attempt",value:G.next_attempt_at!=null?new Date(G.next_attempt_at).toLocaleString():"—"},{label:"Created",value:new Date(G.created_at).toLocaleString()}]}],H=G.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(([B,M])=>({label:B,value:iv(M)}))});t(Y)}),Q.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)",ZW,[]).action(async(q,K,W)=>{let{format:J}=F($.opts()),G=tX(W.field),Y=await _(U().dialerContacts.add({campaign_id:b("dialer_campaigns",q),phone_number:K,name:W.name,custom_fields:Object.keys(G).length>0?G:void 0}));if(J==="json"){P(Y);return}E(`Contact added: ${Y.id}`)}),Q.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)",ZW,[]).action(async(q,K,W)=>{let{format:J}=F($.opts()),G=await _(U().dialerContacts.update({campaign_id:b("dialer_campaigns",q),contact_id:b("dialer_contacts",K),...W.phone!=null&&{phone_number:W.phone},...W.name!=null&&{name:W.name},...W.field.length>0&&{custom_fields:tX(W.field)}}));if(J==="json"){P(G);return}E("Contact updated")}),Q.command("remove <campaign_id> <contactIds...>").description("Remove (soft-delete) mailing contacts").action(async(q,K)=>{let{format:W}=F($.opts()),J=await _(U().dialerContacts.remove({campaign_id:b("dialer_campaigns",q),ids:b("dialer_contacts",K)}));if(W==="json"){P(J);return}E(`Removed ${J.removed}, skipped ${J.skipped}`)}),Q.command("cancel <campaign_id> <contactIds...>").description("Cancel pending mailing contacts").action(async(q,K)=>{let{format:W}=F($.opts()),J=await _(U().dialerContacts.bulkCancel({campaign_id:b("dialer_campaigns",q),ids:b("dialer_contacts",K)}));if(W==="json"){P(J);return}E(`Cancelled ${J.cancelled}, skipped ${J.skipped}`)}),Q.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,K,W)=>{let{format:J}=F($.opts()),G=K.length>0;if(G&&W.all===!0)x("Use either <contactIds...> or --all, not both"),process.exit(A.USAGE_ERROR);if(!G&&W.all!==!0)x("Provide contact IDs or --all to requeue"),process.exit(A.USAGE_ERROR);if(G){let H=await _(U().dialerContacts.bulkRequeue({campaign_id:b("dialer_campaigns",q),ids:b("dialer_contacts",K)}));if(J==="json"){P(H);return}E(`Requeued ${H.requeued}, skipped ${H.skipped}`);return}let Y=await _(U().dialerContacts.requeueAll({campaign_id:b("dialer_campaigns",q),status:p$(W.status)}));if(J==="json"){P(Y);return}E(`Requeued ${Y.requeued}`)}),Q.command("import <campaign_id> <file>").description("Import a CSV mailing into a campaign").option("--map <pair>","Column mapping override <Column>=<role> (repeatable)",ZW,[]).option("--separator <sep>","CSV separator (, or ;) — sniffed when omitted").option("--watch","Follow import progress until it finishes").action(async(q,K,W)=>{let{format:J}=F($.opts()),G=$.opts().yes===!0,Y=await hv(K),H=Y.toString("utf-8"),B=H.search(/\r\n|\n|\r/),M=B===-1?H:H.slice(0,B);if(M.trim()==="")x("File is empty or has no header row"),process.exit(A.USAGE_ERROR);let V=rv(M,W.separator),L=dX(M,V),T=nv(L,W.map);if(J!=="json")y(["Column","Role"],L.map((x$)=>({Column:x$,Role:T[x$]??"ignore"})));await I1("Import with this mapping?",{yes:G});let f=U(),U$=await _(f.dialerImports.create({campaign_id:b("dialer_campaigns",q),column_mapping:T,file:new File([Y],mv(K))}));if(J!=="json")E(`Import started: ${U$.id} (${U$.status})`);else if(W.watch!==!0)P(U$);if(W.watch===!0){let x$=await ov(f,U$.id,J);if(x$!==A.SUCCESS)process.exit(x$)}}),Q.command("import-status <import_job_id>").description("Show the status of a mailing import job").action(async(q)=>{let{format:K,fields:W}=F($.opts()),J=await _(U().dialerImports.get({import_job_id:b("dialer_import_jobs",q)}));if(K==="json"){P(W?C(J,W):J);return}t([{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()}]}])}),Q.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,K)=>{let W=await _(U().dialerImports.invalidRows({import_job_id:b("dialer_import_jobs",q)}));if(W==null){w("No invalid rows.");return}if(K.out!=null){await pX(K.out,W.csv,"utf-8"),E(`Wrote invalid rows to ${K.out}`);return}process.stdout.write(W.csv)}),Q.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,K)=>{let W=await _(U().dialerContacts.exportCsv({campaign_id:b("dialer_campaigns",q),status:p$(K.status),search:K.search})),J=[],G=new Set;for await(let V of W){J.push(V);for(let L of Object.keys(V))if(!cv.has(L))G.add(L)}if(J.length===0){w("No contacts to export.");return}let Y=[...G].sort((V,L)=>V.localeCompare(L)),H=[...MW,...Y],B=J.map((V)=>[...MW.map((L)=>V[L]??""),...Y.map((L)=>V[L]??"")]),M=iX(H,B);if(K.out!=null){await pX(K.out,M,"utf-8"),E(`Wrote ${J.length} contacts to ${K.out}`);return}process.stdout.write(M)})}function sX($){if(!($ in n$))console.error(`Unknown node type: ${$}`),console.error(`Available: ${Object.keys(n$).join(", ")}`),process.exit(2)}function dv($){return $ in j4}function eX($){let U=$.command("nodes").description("IVR node types reference");U.command("list").description("List available node types").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((Q)=>{let{format:q,fields:K}=F($.opts()),W=UW();if(Q.module!=null)W=W.filter((J)=>J.module===Q.module);if(Q.category!=null)W=W.filter((J)=>J.category===Q.category);if(Q.channel!=null)W=W.filter((J)=>J.channel===Q.channel);if(q==="json"){P(K?W.map((J)=>C(J,K)):W);return}y(["Type","Name","Description","Module","Channel"],W.map((J)=>({Type:J.type,Name:J.name,Description:J.description,Module:J.module,Channel:J.channel})))}),U.command("show <type>").description("Show detailed info for a node type").action((Q)=>{let{format:q}=F($.opts());sX(Q);let K=$0(Q);if(q==="json"){P(K);return}let W=dv(Q)?j4[Q]:void 0,J=W!=null?Object.entries(W).map(([G,Y])=>({label:G,value:String(Y)})):[{label:"(no fields)",value:""}];t([{title:`${K.name} (${K.type})`,rows:[{label:"Description",value:K.description},{label:"Module",value:K.module},{label:"Category",value:K.category},{label:"Channel",value:K.channel},{label:"Nature",value:K.nature}]},{title:"Config Fields",rows:J},{title:"Outputs",rows:K.outputs.map((G)=>({label:G.key,value:G.labelKey}))},{title:"Produced Variables",rows:K.producedVariables.length>0?K.producedVariables.map((G)=>({label:`${G.name} (${G.type})`,value:G.descriptionKey})):[{label:"(none)",value:""}]}])}),U.command("schema <type>").description("Output JSON Schema for a node's config (agent-friendly)").action((Q)=>{sX(Q);let q=$0(Q);P(q.configJsonSchema)})}function $B($,U,Q){let q=$.indexOf("=");if(q===-1)throw Error(`${Q} expects key=value (got: ${$})`);let K=$.slice(0,q),W=$.slice(q+1);if(K==="")throw Error(`${Q} expects key=value (got: ${$})`);return U[K]=W,U}function pv($,U){return $B($,U,"--var")}function tv($,U){return $B($,U,"--metadata")}function av($){return $==="pre"||$==="post"}function sv($){let U=$.amd===!0||$.machineType===!0;if($.amdMode!==void 0&&!U)x("--amd-mode requires --amd or --machine-type"),process.exit(A.USAGE_ERROR);if($.amdMaxWait!==void 0&&$.amdMode!=="pre")x("--amd-max-wait requires --amd-mode pre"),process.exit(A.USAGE_ERROR);let Q;if($.amdMode!==void 0){if(!av($.amdMode))x(`Invalid --amd-mode "${$.amdMode}": expected pre or post`),process.exit(A.USAGE_ERROR);Q=$.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(A.USAGE_ERROR);if(!U)return;let K=$.machineType===!0?{amd:!0,machine_type:!0}:{amd:!0};if(Q==="pre")return{...K,mode:Q,max_wait_seconds:q??6};if(Q==="post")return{...K,mode:Q};return K}function UB($,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",pv,{}).option("--metadata <key=value>","Opaque call metadata persisted with the CDR; repeatable",tv,{}).action(async(q)=>{let{format:K}=F($.opts()),W=Object.entries(q.var),J=Object.entries(q.metadata),G=sv(q),Y={plan_id:b("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}:{},...G!==void 0?{answer_recognition:G}:{},...W.length>0?{variables:q.var}:{},...J.length>0?{metadata:q.metadata}:{}},H=await _(U().calls.originate(Y));if(K==="json")P(H);else if(H.status==="failed")J1(`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 E(`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(A.GENERAL_ERROR)})}import{readFile as HB}from"node:fs/promises";import{readFile as ev}from"node:fs/promises";function $z($){return"usage_count"in $}function Uz($){let U=Math.max(0,Math.floor($)),Q=Math.floor(U/60),q=U%60;return`${String(Q).padStart(2,"0")}:${String(q).padStart(2,"0")}`}function Kz($){return $==="caller"?"Cliente":"Atendimento"}function KB($){if($==null||$==="pt-BR")return"pt-BR";if($==="en")return"en";x(`Error: invalid --locale "${$}" — expected one of: pt-BR, en`),process.exit(A.USAGE_ERROR)}async function WB($){let U=$==="-"?await G1():await ev($,"utf-8"),Q;try{Q=JSON.parse(U)}catch{x(`Invalid JSON in "${$}"`),process.exit(A.USAGE_ERROR)}if(!G$(Q))x(`Invalid signal file "${$}": expected a JSON object`),process.exit(A.USAGE_ERROR);return Q}function JB($,U){let Q=$.slug==null&&U!=null?{...$,slug:U}:$,q=K6.safeParse(Q);if(!q.success){x("Invalid signal definition:");for(let K of q.error.issues)x(` ✗ ${K.path.join(".")||"(root)"}: ${K.message}`);process.exit(A.USAGE_ERROR)}return q.data}function Qz($){return K6.parse({slug:$.slug,name:$.name,question:$.question,kind:$.kind,...$.options!==void 0?{options:$.options}:{},...$.levels!==void 0?{levels:$.levels}:{},speaker:$.speaker,scope:$.scope,live:$.live,alert:$.alert})}async function U0($,U){return(await _($.signals.list({search:U,limit:100,page:1,include_archived:!0}))).items.find((q)=>q.slug===U)}function qz($){if(m1($).kind==="uuid")return!0;let U=$.lastIndexOf("_");return U>0&&j6($.slice(0,U))==="signals"}async function QB($,U){if(!qz(U))return U0($,U);let Q=await _($.signals.get({signal_id:b("signals",U)}));return await U0($,Q.slug)??Q}function Wz($){if("answer"in $)return $.answer==="yes"?"for Sim":"for Não";if("options"in $)return`for ${$.options.join(", ")}`;return`reaching level ${$.level_at_least}`}function Jz($){let U=$.description!=null?` — ${$.description}`:"",Q=$.archived?" (archived)":"";return`${$.label}${U}${Q}`}function qB($){for(let U of $.turns){let Q=U.index===$.first_trigger_index?" <- would trigger":"";console.log(`${Uz(U.start)} ${Kz(U.speaker)} ${U.value_label}${Q}`)}console.log(`Fim da chamada ${$.final==null?"ninguém falou no trecho que o signal escuta":$.final.value_label}`)}async function Gz($,U,Q){if(U.file!=null)return JB(await WB(U.file),"test_signal");if(U.preset!=null){let K=P8.find((W)=>W.id===U.preset);if(K==null)x(`Error: unknown preset "${U.preset}".`),w(` Valid presets: ${P8.map((W)=>W.id).join(", ")}`),process.exit(A.USAGE_ERROR);return QW(K,Q)}let q=await U0($,U.slug??"");if(q==null)x(`Signal "${U.slug}" not found.`),process.exit(A.NOT_FOUND);return Qz(q)}function jz($,U,Q){if($.text!=null)return{definition:U,text:$.text,locale:Q};if($.call!=null)return{definition:U,call_id:b("call_records",$.call),locale:Q};return{definition:U,visual_plan_id:b("visual_plans",$.plan??""),last:$.last!=null?Number($.last):void 0,locale:Q}}function GB($,U){let Q=$.command("signals").description("Signal library and testing");Q.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:K,fields:W}=F($.opts()),J=KB(q.locale),G=await _(U().signals.presets({locale:J}));if(K==="json"){P(W?G.map((Y)=>C(Y,W)):G);return}y(["ID","Name","Kind","Speaker","Live","Severity"],G.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??"—"})))}),Q.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:K,fields:W}=F($.opts()),J=await _(U().signals.list({page:Number(q.page),limit:Number(q.limit),search:q.search,include_archived:q.includeArchived===!0}));if(K==="json"){let G=W?J.items.map((Y)=>C(Y,W)):J;P(G);return}y(["Slug","Name","Kind","Live","Org default","Usage","Fires 7d","Version","Archived"],J.items.map((G)=>({Slug:G.slug,Name:G.name,Kind:G.kind,Live:G.live?"yes":"no","Org default":G.is_org_default?"yes":"no",Usage:`${G.usage_count.published}/${G.usage_count.draft}`,"Fires 7d":G.fires_last_7_days.reduce((Y,H)=>Y+H,0),Version:G.version,Archived:G.archived_at!=null?"yes":"no"}))),j$(J)}),Q.command("show <slug_or_id>").description("Show one signal (slug or sig_... TypeID) with its usage").action(async(q)=>{let{format:K,fields:W}=F($.opts()),J=await QB(U(),q);if(J==null)x(`Signal "${q}" not found.`),process.exit(A.NOT_FOUND);if(K==="json"){P(W?C(J,W):J);return}let G=[{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},{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:Wz(J.alert.when)},{label:"Severity",value:J.alert.severity},{label:"Bell",value:J.alert.bell?"yes":"no"}]}];if(J.options!==void 0)G.push({title:"Options",rows:J.options.map((Y)=>({label:Y.key,value:Jz(Y)}))});if(J.levels!==void 0)G.push({title:"Levels",rows:J.levels.map((Y,H)=>({label:String(H+1),value:Y}))});if($z(J))G.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)}]});t(G)}),Q.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:K}=F($.opts()),W=U(),J=KB(q.locale),G=[q.file,q.preset,q.slug].filter((V)=>V!=null).length,Y=[q.text,q.call,q.plan].filter((V)=>V!=null).length;if(G!==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(A.USAGE_ERROR);if(q.last!=null&&q.plan==null)x("Error: --last only applies with --plan."),process.exit(A.USAGE_ERROR);let H=await Gz(W,q,J),B=jz(q,H,J),M=await _(W.signals.test(B));if(K==="json"){P(M);return}if("calls"in M)M.calls.forEach((V,L)=>{if(L>0)console.log("");console.log(`Call ${V.call_id}`),qB(V)});else if("turns"in M)qB(M);else console.log(`${M.value_label}${M.would_trigger?" <- would trigger":""}`)}),Q.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:K}=F($.opts()),W=U(),J=await WB(q.file),G=JB(J),Y=typeof J.is_org_default==="boolean"?J.is_org_default:void 0,H=await _(W.signals.upsertBySlug({...G,...Y!==void 0?{is_org_default:Y}:{},dry_run:q.dryRun===!0}));if(K==="json"){P(H);return}Yz(H.status,H.changed_fields,H.signal.slug,q.dryRun===!0)}),Q.command("delete <slug_or_id>").description("Move a signal to the trash (slug or sig_... TypeID)").action(async(q)=>{let{format:K}=F($.opts()),W=await QB(U(),q);if(W==null)x(`Signal "${q}" not found.`),process.exit(A.NOT_FOUND);let J=await _(U().signals.delete({signal_id:b("signals",W.id)}));if(K==="json"){P(J);return}E(`Signal moved to the trash: ${J.slug}. Restore it from Settings > Archive.`)})}function Yz($,U,Q,q){if($==="created"){E(q?`would create: ${Q}`:`created: ${Q}`);return}if($==="unchanged"){w(`unchanged: ${Q}`);return}E(q?`would update: ${Q} (changed: ${U.join(", ")})`:`updated: ${Q} (changed: ${U.join(", ")})`)}async function VW($){let U=$==="-"?await G1():await HB($,"utf-8"),Q=lq.safeParse(JSON.parse(U));if(!Q.success){x(`Invalid execution plan in "${$}":`);for(let q of Q.error.issues)x(` ✗ ${q.path.join(".")||"(root)"}: ${q.message}`);process.exit(A.GENERAL_ERROR)}return Q.data}function X4($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function Hz($){if(!X4($)||!Array.isArray($.nodes)||!Array.isArray($.edges))return!1;let U=$.viewport;return X4(U)&&typeof U.x==="number"&&typeof U.y==="number"&&typeof U.zoom==="number"}async function Xz($){let U=$==="-"?await G1():await HB($,"utf-8"),Q;try{Q=JSON.parse(U)}catch{x(`Invalid JSON in plan export "${$}"`),process.exit(A.GENERAL_ERROR)}let q;if(X4(Q)&&Q.format==="niva-plan-v1")q=Q.state;else if(X4(Q)&&X4(Q.draft)&&Q.draft.editor_state!=null)q=Q.draft.editor_state;else if(X4(Q)&&Q.published_editor_state!=null)q=Q.published_editor_state;else if(X4(Q)&&Array.isArray(Q.nodes)&&Array.isArray(Q.edges))q=Q;else x(`Invalid plan export in "${$}"`),process.exit(A.GENERAL_ERROR);if(!Hz(q))x(`Invalid editor state in plan export "${$}"`),process.exit(A.GENERAL_ERROR);return q}function DW($){let U=$.severity==="error"?"✗":"⚠",Q=$.node_id!=null?` [${$.node_id}]`:"";return` ${U}${Q} ${$.message_key}`}var Bz="! 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 jB($){try{let U=DQ($),Q=GW(U.nodes,U.edges,C1);if(!YW(Q)){for(let q of Q)x(DW({node_id:q.nodeId,severity:q.severity,message_key:q.messageKey}));return!1}return J1(Bz),!0}catch(U){return x(U instanceof Error?U.message:String(U)),!1}}async function Zz($,U,Q,q){if(await _($.channels.update({channel_id:b("channels",U),visual_plan_id:b("visual_plans",Q),reassign:!0})),q!=="json")E(`Channel ${U} assigned to plan`)}async function Mz($,U,Q){if(await _($.channels.update({channel_id:b("channels",U),visual_plan_id:null})),Q!=="json")E(`Channel ${U} unassigned from plan`)}async function Vz($,U,Q){let q=b("visual_plans",U),K=await _($.channels.list({page:1,limit:100})),W=K.items.filter((G)=>G.visual_plan_id===q),J=K.items.filter((G)=>G.visual_plan_id==null);if(Q==="json"){P({assigned:W,available:J});return}if(W.length>0)console.log(`
|
|
807
|
+
Assigned to this plan:`),y(["ID","Type","Name","Identifier","Active"],W.map((G)=>({ID:G.id,Type:G.channel_type,Name:G.name,Identifier:G.identifier??"—",Active:G.is_active?"yes":"no"})));if(J.length>0)console.log(`
|
|
808
|
+
Available (unassigned):`),y(["ID","Type","Name","Identifier"],J.map((G)=>({ID:G.id,Type:G.channel_type,Name:G.name,Identifier:G.identifier??"—"})))}function Dz($,U){return{plan_id:b("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.topics!=null&&{topic_detection_topics:U.topics.split(",").map((Q)=>Q.trim())},...U.intents!=null&&{intent_detection_intents:U.intents.split(",").map((Q)=>Q.trim())},...U.signalsInherit!==void 0&&{signals_inherit_org:U.signalsInherit}}}async function Nz($,U,Q,q,K,W){let J=U.startsWith("-")?"-":"+",G=U.startsWith("+")||U.startsWith("-")?U.slice(1):U,Y=await U0($,G);if(Y==null){K.push(G);return}if(J==="-"){q.delete(Y.id);return}if(q.add(Y.id),Y.live===!0&&Q.transcription_type!=="live")W.push(`Signal "${Y.name}" runs live, but this plan uses ${Q.transcription_type} transcription: it only runs at the end of the call until the plan switches to live transcription.`)}async function Pz($,U,Q){let q=await _($.visualPlans.getById({plan_id:b("visual_plans",U)})),K=q.signals_inherit_org===!0,W=new Set(K?await Iz($):q.signal_ids),J=[],G=[];for(let Y of Q.split(",")){let H=Y.trim();if(H==="")continue;await Nz($,H,q,W,J,G)}if(J.length>0)x(`Unknown signal slug(s): ${J.join(", ")}`),w("List the library with: niva signals list"),process.exit(A.USAGE_ERROR);return{signal_ids:[...W].sort((Y,H)=>Y.localeCompare(H)),warnings:G,switchedToCustom:K}}async function Iz($){let U=[],Q=1;for(;;){let q=await _($.signals.list({page:Q,limit:100,include_archived:!1}));for(let K of q.items)if(K.is_org_default)U.push(K.id);if(q.page>=q.total_pages)break;Q+=1}return U}function XB($,U){let Q=$.command("plans").description("Manage visual plans");Q.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:K,fields:W}=F($.opts()),J=await _(U().visualPlans.list({page:Number(q.page),limit:Number(q.limit),search:q.search}));if(K==="json"){let G=W?J.items.map((Y)=>C(Y,W)):J;P(G);return}y(["ID","Name","Status","Created"],J.items.map((G)=>({ID:G.id,Name:G.name,Status:G.published_version_id!=null?"published":"draft",Created:new Date(G.created_at).toLocaleDateString()}))),j$(J)}),Q.command("show <plan_id>").description("Show plan details with settings").action(async(q)=>{let{format:K,fields:W}=F($.opts()),J=await _(U().visualPlans.getById({plan_id:b("visual_plans",q)}));if(K==="json"){let G=W?C(J,W):J;P(G);return}t([{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:"Speech Analytics",value:J.speech_analytics_enabled?"enabled":"disabled"}]}])}),Q.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,K)=>{let{format:W}=F($.opts()),J;if(K.executionPlan!=null){if(J=await VW(K.executionPlan),!jB(J))process.exit(1)}let G=await _(U().visualPlans.create({name:q,language:K.language,description:K.description,recording_enabled:K.recording??!1,transcription_enabled:K.transcription??!1,execution_plan:J}));if(W==="json"){P(G);return}E(`Plan created: ${G.id}`)}),Q.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,K)=>{let{format:W}=F($.opts()),J=await VW(K.executionPlan);if(!jB(J))process.exit(1);let G=await _(U().visualPlans.saveDraft({plan_id:b("visual_plans",q),execution_plan:J,expected_revision:K.expectedRevision!=null?Number(K.expectedRevision):void 0}));if(W==="json"){P(G);return}E(`Draft updated (revision ${G.revision})`)}),Q.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,K)=>{let{format:W}=F($.opts()),J=await Xz(K),G=await _(U().visualPlans.importDraft({plan_id:b("visual_plans",q),editor_state:J}));if(W==="json"){P(G);return}E(`Draft imported (revision ${G.revision})`)}),Q.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 speech analytics").option("--no-speech-analytics","Disable speech analytics").option("--topics <list>","Topic detection topics (comma-separated)").option("--intents <list>","Intent detection intents (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,K)=>{let{format:W}=F($.opts()),J=U();if(K.assignDid!=null)await Zz(J,K.assignDid,q,W);if(K.unassignDid!=null)await Mz(J,K.unassignDid,W);if(K.listDids===!0){await Vz(J,q,W);return}let G=Dz(q,K);if(K.signals!=null){if(K.signalsInherit===!0)x("Error: --signals cannot be combined with --signals-inherit: the plan follows the organization and would ignore the list."),process.exit(A.USAGE_ERROR);let{signal_ids:Y,warnings:H,switchedToCustom:B}=await Pz(J,q,K.signals);if(G.signal_ids=Y,B)G.signals_inherit_org=!1,J1("This plan now chooses its own signals instead of following the organization.");for(let M of H)J1(M)}if(Object.keys(G).length>1){let Y=await _(J.visualPlans.update(G));if(W==="json"){P(Y);return}E("Plan configuration updated")}}),Q.command("scaffold").description("Output a minimal valid execution plan JSON template").option("--channel <type>","Channel type: voice, chat, both","both").action((q)=>{let K=["voice","chat","both"];if(!K.includes(q.channel))x(`Invalid channel type: ${q.channel}. Must be one of: ${K.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"}}})}),Q.command("delete <plan_id>").description("Delete a visual plan").action(async(q)=>{let{format:K}=F($.opts());if(await _(U().visualPlans.delete({plan_id:b("visual_plans",q)})),K==="json"){P({success:!0});return}E("Plan deleted")}),Q.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,K)=>{let{format:W}=F($.opts());if(K.file!=null){let G=await VW(K.file),Y=await _(U().visualPlans.validate({execution_plan:G}));if(W==="json"){P(Y);return}YB(Y),process.exit(Y.valid?0:1)}if(q==null)x("Provide a plan ID or --file <path>"),process.exit(2);let J=await _(U().visualPlans.validate({plan_id:b("visual_plans",q)}));if(W==="json"){P(J);return}YB(J),process.exit(J.valid?0:1)}),Q.command("test <plan_id>").description("Start a test call for a plan").requiredOption("--extension <ext>","SIP extension to call").action(async(q,K)=>{let{format:W}=F($.opts()),J=await _(U().testCall.start({planId:b("visual_plans",q),extension:K.extension}));if(W==="json"){P(J);return}E(`Test call started: uuid=${J.uuid}`),w(`Test ID: ${J.testId}`),w("Use 'niva calls follow <uuid>' to watch the call")}),Q.command("publish <plan_id>").description("Publish the current draft").option("--notes <text>","Publication notes").action(async(q,K)=>{let{format:W}=F($.opts()),J=await _(U().visualPlans.publish({plan_id:b("visual_plans",q),notes:K.notes}));if(W==="json"){P(J);return}E(`Plan published (version ${J.version})`)}),Q.command("versions <plan_id>").description("List version history").action(async(q)=>{let{format:K}=F($.opts()),W=await _(U().visualPlans.listVersions({plan_id:b("visual_plans",q)}));if(K==="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??"—"})))}),Q.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,K)=>{if(K.executionPlan===!0){let G=(await _(U().visualPlans.listVersions({plan_id:b("visual_plans",q)}))).items.find((Y)=>Y.status==="published"&&Y.execution_plan!=null);if(G!=null)P(G.execution_plan);else x("No published version with execution plan found"),process.exit(1);return}let W=await _(U().visualPlans.getById({plan_id:b("visual_plans",q)}));P(W)})}function YB($){if($.valid){E("✓ Plan is valid");return}let U=$.issues.filter((q)=>q.severity==="error"),Q=$.issues.filter((q)=>q.severity==="warning");if(U.length>0){x(`✗ ${U.length} error(s):`);for(let q of U)x(DW(q))}if(Q.length>0){w(` ${Q.length} warning(s):`);for(let q of Q)w(DW(q))}}function BB($,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:K,fields:W}=F($.opts()),J=await _(U().schedules.list({page:Number(q.page),limit:Number(q.limit),search:q.search}));if(K==="json"){let G=W?J.items.map((Y)=>C(Y,W)):J;P(G);return}y(["ID","Name","Description"],J.items.map((G)=>({ID:G.id,Name:G.name,Description:G.description??"—"}))),j$(J)})}var _z="···";function Lz($){return $===""?"—":`${_z}${$}`}function ZB($,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:K,fields:W}=F($.opts()),J=await _(U().secrets.list({page:Number(q.page),limit:Number(q.limit),search:q.search}));if(K==="json"){let G=W?J.items.map((Y)=>C(Y,W)):J;P(G);return}y(["ID","Name","Description","Value","Published","Draft","Updated"],J.items.map((G)=>({ID:G.id,Name:G.name,Description:G.description??"—",Value:Lz(G.value_suffix),Published:G.usage_count.published,Draft:G.usage_count.draft,Updated:new Date(G.updated_at).toLocaleString()}))),j$(J)})}var Z$=M1(D1(),1);var Fz=[{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 y1($){if($<1024)return`${$} B`;if($<1048576)return`${($/1024).toFixed(1)} KB`;if($<1073741824)return`${($/1048576).toFixed(1)} MB`;return`${($/1073741824).toFixed(1)} GB`}function vz($){if($==="critical")return Z$.default.red($.toUpperCase());if($==="warning")return Z$.default.yellow($.toUpperCase());return Z$.default.green($.toUpperCase())}function zz($){if($>0)return"+";if($<0)return"-";return""}function kz($){if($===void 0)return"not available";return $.bytes==null?"not measured":y1($.bytes)}function MB($){if($?.bytesPerDay==null)return"-";return`${zz($.bytesPerDay)}${y1(Math.abs($.bytesPerDay))}/day`}function wz($){if($?.fileCount==null)return"-";return`${$.fileCount} files`}function xz($){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 Az($){if($==="webhook")return"webhook";if($==="audit")return"audit";if($==="other")return null;return"call"}function bz($,U){let Q=Az(U);if(Q==null)return"-";let q=$.cleanups.find((K)=>K.name===Q);if(q==null)return"no data";if(!q.ok)return Z$.default.red("failed");return q.backlog==null?"not reported":`${q.backlog} pending`}function Oz($){if($.collecting)return`${Z$.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 Rz($){let U=Math.round($.disk.usagePercent);if(console.log(`
|
|
809
|
+
${Z$.default.bold("Disk")} ${vz($.status)}`),console.log(` Total: ${y1($.disk.totalBytes)}`),console.log(` Used: ${y1($.disk.usedBytes)} (${U}%)`),console.log(` Available: ${y1($.disk.availableBytes)}`),console.log(` ${N1(U,100,30)}`),console.log(` ${Oz($)}`),$.retentionStartsInDays!=null)console.log(` Retention starts acting in ${$.retentionStartsInDays} days.`);if($.sampledAt!=null)console.log(` Categories measured at ${$.sampledAt}`)}function Tz($){console.log(`
|
|
810
|
+
${Z$.default.bold("Categories")}`);for(let{key:U,label:Q}of Fz){let q=$.categories[U];console.log(` ${Q.padEnd(16)} ${Z$.default.cyan(kz(q).padEnd(20))} ${MB(q).padEnd(14)} ${wz(q)}`)}}function Sz($,U){let Q=U.retentionDays==null?U.retentionSource:`${U.retentionDays}d (${U.retentionSource})`;console.log(` ${xz(U.class).padEnd(22)} ${y1(U.bytes).padEnd(10)} ${String(U.rows).padEnd(11)} ${(U.oldestAt?.slice(0,10)??"-").padEnd(11)} ${MB(U).padEnd(13)} ${Q.padEnd(18)} ${y1(U.reclaimableBytes).padEnd(18)} ${bz($,U.class)}`)}function Cz($){if(console.log(`
|
|
811
|
+
${Z$.default.bold("Database")}`),$.databaseClasses===void 0){console.log(` ${Z$.default.dim("Not available - requires platform_storage:manage.")}`);return}if($.databaseClasses.length===0){console.log(` ${Z$.default.yellow("Collecting")} - no sample yet.`);return}let U=$.databaseClasses.reduce((Q,q)=>Q+q.bytes,0);console.log(` Sum by class: ${Z$.default.cyan(y1(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 Q of $.databaseClasses)Sz($,Q);console.log(` ${Z$.default.dim("Rows and reclaimable are estimates from pg_stat_user_tables (updated after ANALYZE).")}`),console.log(` ${Z$.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(` ${Z$.default.dim("Retention frees space for reuse inside PostgreSQL; returning it to disk needs VACUUM FULL or pg_repack.")}`)}function Ez($){if(console.log(`
|
|
812
|
+
${Z$.default.bold("Cleanups")}`),$.cleanups.length===0){console.log(` ${Z$.default.dim("No data - no pass has been recorded yet.")}`);return}for(let U of $.cleanups){let Q=U.ok?Z$.default.green("ok".padEnd(16)):Z$.default.red("failed".padEnd(16)),q=U.backlog==null?"not reported":`${U.backlog} pending`;console.log(` ${U.name.padEnd(10)} ${Q} deleted ${U.deleted} backlog ${q}`)}}function gz($){console.log(`
|
|
813
|
+
${Z$.default.bold("Thresholds")}`),console.log(` Warning: ${$.thresholds.warning}%`),console.log(` Critical: ${$.thresholds.critical}%`)}function VB($,U){$.command("storage").description("Storage observability and cache stats").command("usage").description("Show storage usage breakdown").action(async()=>{let{format:q}=F($.opts()),K=await _(U().dashboard.storageUsage({}));if(q==="json"){P(K);return}Rz(K),Tz(K),Cz(K),Ez(K),gz(K),console.log()})}function DB($,U){let Q=$.command("tenants").description("Manage tenants");Q.command("list").description("List tenants").action(()=>d$()),Q.command("create").description("Create a tenant").action(()=>d$())}function NB($,U){let Q=$.command("tts").description("Text-to-speech resources (to synthesize audio, see: niva audio-files generate-tts)");Q.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:K,fields:W}=F($.opts()),J=await _(U().tts.listVoices({language:q.language,model:q.model}));if(K==="json"){let G=W?J.map((Y)=>C(Y,W)):J;P(G);return}y(["ID","Name","Gender","Languages","Model"],J.map((G)=>({ID:G.id,Name:G.name,Gender:G.gender??"-",Languages:G.languages.join(", "),Model:G.model})))}),Q.command("models").description("List available TTS models").action(async()=>{let{format:q,fields:K}=F($.opts()),W=await _(U().tts.listModels());if(q==="json"){let J=K?W.map((G)=>C(G,K)):W;P(J);return}y(["ID","Name","Provider"],W.map((J)=>({ID:J.id,Name:J.name,Provider:J.provider})))}),Q.command("languages").description("List available TTS languages").action(async()=>{let{format:q}=F($.opts()),K=await _(U().tts.listLanguages());if(q==="json"){P(K);return}y(["Language"],K.map((W)=>({Language:W})))})}function yz($){return $.fields.map((U)=>`${U.name}${U.required?"":"?"}${U.nullable?"|null":""}`).join(", ")}function PB($,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:K}=F($.opts()),W=await _(U().webhooks.events.list());if(q==="json"){P(K?W.map((J)=>C(J,K)):W);return}y(["Event","Module","Fields"],W.map((J)=>({Event:J.event,Module:J.required_module??"core",Fields:yz(J)})))})}function IB($,U,Q){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(K)=>{let W=f1($.opts()),J=Q();w("Creating WebSocket session...");let G=await _(U().ws.createSession({planId:b("visual_plans",K)}));if(W==="json"){P(G);return}E(`Session created: ${G.sessionId}`),await x0(I4(J.url,G.wsUrl))}),q.command("session <plan_id>").description("Create a WebSocket session (returns sessionId + wsUrl)").action(async(K)=>{let W=f1($.opts()),J=await _(U().ws.createSession({planId:b("visual_plans",K)})),G=Q(),Y=I4(G.url,J.wsUrl);if(W==="json"){P({...J,ws_url:Y});return}E(`Session: ${J.sessionId}`),console.log(` WebSocket URL: ${Y}`),console.log(` Connect with: websocat ${Y}`)})}function _B($,U,Q,q){BG($),UG($,Q,q),eX($),yX($),dW($,U),NJ($,U),WG($,U),UB($,U),XB($,U),MG($,U),aX($,U),DG($,U),CX($,U),rX($,U),ZG($,U),HG($,U),BB($,U),ZB($,U),GB($,U),VB($,U),DB($,U),NB($,U),IB($,U,Q),XG($,U,Q),PB($,U),cX($)}function uz($){try{let{hostname:U}=new URL($);return U.endsWith(".orb.local")||process.env.NIVA_INSECURE==="true"}catch{return!1}}class LB extends Error{constructor(){super("Your session has expired. Run 'niva login' to authenticate again.")}}function fz($){let U=$.fetchImpl??fetch,Q=async()=>{try{return await $.refresh()}catch(q){if(q instanceof N$)throw new LB;throw q}};return async(q)=>{let K=$.getSession();if(v0(K))K=await Q();let W=new Request(q);W.headers.set("authorization",`Bearer ${K.access_token}`);let J=await U(W);if(J.status===401){K=await Q();let G=new Request(q);G.headers.set("authorization",`Bearer ${K.access_token}`),J=await U(G)}return J}}function FB($,U,Q){if(uz($))process.env.NODE_TLS_REJECT_UNAUTHORIZED="0";if(U.kind!=="oauth"){let W=new p1({url:new URL("/api/rpc",$).href,headers:()=>U.kind==="api-key"?{"X-API-Key":U.apiKey}:{}});return d1(W)}let q=U.session,K=new p1({url:new URL("/api/rpc",$).href,fetch:fz({getSession:()=>q,refresh:async()=>{return q=await z0(Q,q),N4(Q,q),q}})});return d1(K)}import{readFileSync as hz}from"node:fs";var mz=1500,cz="/cli/compatibilidade",v8=null;function lz(){if(v8!=null)return v8;let $='[{"niva_min":"2.0.0","niva_max":null,"dist_tag":"niva-2.0"}]',U='{"min":"2.0.0","max":null}',Q=null;if(typeof U==="string"&&typeof $==="string"){let q=JSON.parse(U),K=JSON.parse($);Q=vB(q,K)}else{let q=JSON.parse(rz()),K=G$(q)?q.supported_niva:void 0,W=G$(q)?q.compat_table:void 0;Q=vB(K,W)}if(Q==null)throw Error("Invalid apps/cli/compat.json, fix the compat table");return v8=Q,v8}function vB($,U){if(!G$($)||!Array.isArray(U))return null;let Q=i($.min);if(Q==null)return null;let q=i($.max)??null,K=[];for(let W of m$(U)){let J=i(W.niva_min),G=i(W.dist_tag);if(J==null||G==null)return null;K.push({niva_min:J,niva_max:i(W.niva_max)??null,dist_tag:G})}return{supported_niva:{min:Q,max:q},compat_table:K}}function rz(){return hz(new URL("../../compat.json",import.meta.url),"utf-8")}function NW($){let Q=($.split("-")[0]?.split("+")[0]??"").split(".");if(Q.length!==3)return null;let q=Q.map((K)=>Number.parseInt(K,10));if(q.some((K)=>!Number.isFinite(K)||K<0))return null;return[q[0],q[1],q[2]]}function z8($,U){let Q=NW($),q=NW(U);if(Q===null||q===null)return 0;for(let K=0;K<3;K++)if(Q[K]!==q[K])return Q[K]-q[K];return 0}function nz($,U){let{min:Q,max:q}=U.supported_niva;if(z8($,Q)<0)return!1;if(q!=null&&z8($,q)>0)return!1;return!0}function iz($,U){for(let Q of U.compat_table){if(z8($,Q.niva_min)<0)continue;if(Q.niva_max!=null&&z8($,Q.niva_max)>0)continue;return Q.dist_tag}return null}function oz($,U,Q){let{min:q,max:K}=Q.supported_niva,W=K==null?`>= ${q}`:`>= ${q} <= ${K}`,J=iz($,Q),G=J==null?`See ${cz}`:`For the compatible release: npx @sippulse/niva@${J} <command>`;return`warning: this CLI (${W6()}) supports NIVA ${W}; ${U} reports ${$}. Some commands may not exist. ${G}`}async function dz($,U=fetch){let Q=new AbortController,q=setTimeout(()=>Q.abort(),mz);try{let K=await U(new URL("/api/version",$).href,{signal:Q.signal,headers:{accept:"application/json"}});if(!K.ok)return null;let W=await K.json();if(W===null||typeof W!=="object"||!("niva_version"in W))return null;let J=W.niva_version;if(typeof J!=="string"||NW(J)===null)return null;return J}catch{return null}finally{clearTimeout(q)}}var pz=null;async function zB($,U={}){if(!$)return;let Q=U.config??lz(),q=await dz($,U.fetchImpl);if(q===null)return;if(pz=q,nz(q,Q))return;console.error(oz(q,$,Q))}import{chmodSync as ko,mkdirSync as wo,readFileSync as tz,writeFileSync as xo}from"node:fs";import{homedir as az}from"node:os";import{join as xB}from"node:path";var sz=xB(az(),".niva"),ez=xB(sz,"config.json"),kB={url:"http://localhost:3000",apiKey:""};function wB($,U){let Q=$[U];return typeof Q==="string"?Q:void 0}function PW(){try{let $=JSON.parse(tz(ez,"utf-8"));return G$($)?$:{}}catch{return{}}}function AB(){return PW()}function bB($){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 $k($){let U=G$($)?{...$}:void 0;if(U==null)return!1;let Q=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(Q)&&Q.every((q)=>typeof q==="string")}function Uk(){let $=PW().auth;return G$($)?$:{}}function OB(){let $={};for(let[U,Q]of Object.entries(Uk()))if($k(Q))$[U]=Q;return $}function RB($){let U=PW();return{url:$.url??process.env.NIVA_URL??wB(U,"url")??kB.url,apiKey:$.apiKey??process.env.NIVA_API_KEY??wB(U,"apiKey")??kB.apiKey}}var Kk="table",Qk="";function TB($){Kk=$}function SB($){Qk=$}var qk=new Set(["json","table","plain"]);function Wk($){return qk.has($)}function Jk(){return process.stdout.isTTY===!0&&process.env.NO_COLOR==null}function CB($){if($.output!=null)return Wk($.output)?$.output:"table";if($.json===!0)return"json";return Jk()?"table":"json"}function EB(){return"0.3.1-rc.0"}var K0=new gW("niva").description("NIVA CLI \u2014 manage your IVR platform").version(EB()).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 $=K0.opts(),U=CB({json:$.json===!0,output:typeof $.output==="string"?$.output:void 0});TB(U)}).hook("preAction",async()=>{await zB(A8().url)}),k8;function A8(){if(k8!=null)return k8;let $=K0.opts();return k8=RB({url:typeof $.url==="string"?$.url:void 0,apiKey:typeof $.apiKey==="string"?$.apiKey:void 0}),k8}var w8;function gB(){if(w8!=null)return w8;let $=A8(),U=AB(),Q=K0.opts().apiKey;return w8=bB({flagApiKey:typeof Q==="string"?Q:void 0,envApiKey:process.env.NIVA_API_KEY,fileApiKey:typeof U.apiKey==="string"?U.apiKey:void 0,session:OB()[$.url.replace(/\/+$/,"")]}),w8}var x8;function Gk(){if(x8!=null)return x8;let $=A8();SB($.url);let U=gB();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 x8=FB($.url,U,$.url.replace(/\/+$/,"")),x8}_B(K0,Gk,A8,gB);K0.parseAsync().catch(($)=>{console.error($ instanceof Error?$.message:String($)),process.exit(1)});
|