@sippulse/niva 0.3.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.
Files changed (2) hide show
  1. package/index.js +395 -81
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -1,97 +1,97 @@
1
1
  #!/usr/bin/env node
2
2
  // @bun
3
- import{createRequire as YB}from"node:module";var sH=Object.create;var{getPrototypeOf:$B,defineProperty:vU,getOwnPropertyNames:UB}=Object;var KB=Object.prototype.hasOwnProperty;function QB($){return this[$]}var GB,JB,H1=($,U,Q)=>{var G=$!=null&&typeof $==="object";if(G){var K=U?GB??=new WeakMap:JB??=new WeakMap,J=K.get($);if(J)return J}Q=$!=null?sH($B($)):{};let W=U||!$||!$.__esModule?vU(Q,"default",{value:$,enumerable:!0}):Q;for(let q of UB($))if(!KB.call(W,q))vU(W,q,{get:QB.bind($,q),enumerable:!0});if(G)K.set($,W);return W};var B1=($,U)=>()=>(U||$((U={exports:{}}).exports,U),U.exports);var WB=($)=>$;function qB($,U){this[$]=WB.bind(null,U)}var K1=($,U)=>{for(var Q in U)vU($,Q,{get:U[Q],enumerable:!0,configurable:!0,set:qB.bind(U,Q)})};var a4=YB(import.meta.url);var e4=B1((jB)=>{class DU 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 JJ extends DU{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}jB.CommanderError=DU;jB.InvalidArgumentError=JJ});var t6=B1((ZB)=>{var{InvalidArgumentError:BB}=e4();class WJ{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 BB(`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 MB($){let U=$.name()+($.variadic===!0?"...":"");return $.required?"<"+U+">":"["+U+"]"}ZB.Argument=WJ;ZB.humanReadableArgName=MB});var PU=B1((PB)=>{var{humanReadableArgName:DB}=t6();class qJ{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((G)=>!G._hidden),Q=$._getHelpCommand();if(Q&&!Q._hidden)U.push(Q);if(this.sortSubcommands)U.sort((G,K)=>{return G.name().localeCompare(K.name())});return U}compareOptions($,U){let Q=(G)=>{return G.short?G.short.replace(/^-/,""):G.long.replace(/^--/,"")};return Q($).localeCompare(Q(U))}visibleOptions($){let U=$.options.filter((G)=>!G.hidden),Q=$._getHelpOption();if(Q&&!Q.hidden){let G=Q.short&&$._findOption(Q.short),K=Q.long&&$._findOption(Q.long);if(!G&&!K)U.push(Q);else if(Q.long&&!K)U.push($.createOption(Q.long,Q.description));else if(Q.short&&!G)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 G=Q.options.filter((K)=>!K.hidden);U.push(...G)}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)=>DB(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,G)=>{return Math.max(Q,this.displayWidth(U.styleSubcommandTerm(U.subcommandTerm(G))))},0)}longestOptionTermLength($,U){return U.visibleOptions($).reduce((Q,G)=>{return Math.max(Q,this.displayWidth(U.styleOptionTerm(U.optionTerm(G))))},0)}longestGlobalOptionTermLength($,U){return U.visibleGlobalOptions($).reduce((Q,G)=>{return Math.max(Q,this.displayWidth(U.styleOptionTerm(U.optionTerm(G))))},0)}longestArgumentTermLength($,U){return U.visibleArguments($).reduce((Q,G)=>{return Math.max(Q,this.displayWidth(U.styleArgumentTerm(U.argumentTerm(G))))},0)}commandUsage($){let U=$._name;if($._aliases[0])U=U+"|"+$._aliases[0];let Q="";for(let G=$.parent;G;G=G.parent)Q=G.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),G=U.helpWidth??80;function K(B,Z){return U.formatItem(B,Q,Z,U)}let J=[`${U.styleTitle("Usage:")} ${U.styleUsage(U.commandUsage($))}`,""],W=U.commandDescription($);if(W.length>0)J=J.concat([U.boxWrap(U.styleCommandDescription(W),G),""]);let q=U.visibleArguments($).map((B)=>{return K(U.styleArgumentTerm(U.argumentTerm(B)),U.styleArgumentDescription(U.argumentDescription(B)))});if(q.length>0)J=J.concat([U.styleTitle("Arguments:"),...q,""]);let j=U.visibleOptions($).map((B)=>{return K(U.styleOptionTerm(U.optionTerm(B)),U.styleOptionDescription(U.optionDescription(B)))});if(j.length>0)J=J.concat([U.styleTitle("Options:"),...j,""]);if(U.showGlobalOptions){let B=U.visibleGlobalOptions($).map((Z)=>{return K(U.styleOptionTerm(U.optionTerm(Z)),U.styleOptionDescription(U.optionDescription(Z)))});if(B.length>0)J=J.concat([U.styleTitle("Global Options:"),...B,""])}let X=U.visibleCommands($).map((B)=>{return K(U.styleSubcommandTerm(U.subcommandTerm(B)),U.styleSubcommandDescription(U.subcommandDescription(B)))});if(X.length>0)J=J.concat([U.styleTitle("Commands:"),...X,""]);return J.join(`
4
- `)}displayWidth($){return YJ($).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,G){let J=" ".repeat(2);if(!Q)return J+$;let W=$.padEnd(U+$.length-G.displayWidth($)),q=2,X=(this.helpWidth??80)-U-q-2,B;if(X<this.minWidthToWrap||G.preformatted(Q))B=Q;else B=G.boxWrap(Q,X).replace(/\n/g,`
5
- `+" ".repeat(U+q));return J+W+" ".repeat(q)+B.replace(/\n/g,`
6
- ${J}`)}boxWrap($,U){if(U<this.minWidthToWrap)return $;let Q=$.split(/\r\n|\n/),G=/[\s]*[^\s]+/g,K=[];return Q.forEach((J)=>{let W=J.match(G);if(W===null){K.push("");return}let q=[W.shift()],j=this.displayWidth(q[0]);W.forEach((X)=>{let B=this.displayWidth(X);if(j+B<=U){q.push(X),j+=B;return}K.push(q.join(""));let Z=X.trimStart();q=[Z],j=this.displayWidth(Z)}),K.push(q.join(""))}),K.join(`
7
- `)}}function YJ($){let U=/\x1b\[\d*(;\d*)*m/g;return $.replace(U,"")}PB.Help=qJ;PB.stripColor=YJ});var IU=B1((kB)=>{var{InvalidArgumentError:_B}=e4();class XJ{constructor($,U){this.flags=$,this.description=U||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let Q=wB($);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 _B(`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 jJ(this.name().replace(/^no-/,""));return jJ(this.name())}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class HJ{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 G=this.negativeOptions.get(Q).presetArg,K=G!==void 0?G:!1;return U.negate===(K===$)}}function jJ($){return $.split("-").reduce((U,Q)=>{return U+Q[0].toUpperCase()+Q.slice(1)})}function wB($){let U,Q,G=/^-[^-]$/,K=/^--[^-]/,J=$.split(/[ |,]+/).concat("guard");if(G.test(J[0]))U=J.shift();if(K.test(J[0]))Q=J.shift();if(!U&&G.test(J[0]))U=J.shift();if(!U&&K.test(J[0]))U=Q,Q=J.shift();if(J[0].startsWith("-")){let W=J[0],q=`option creation failed due to '${W}' in option flags '${$}'`;if(/^-[^-][^-]/.test(W))throw Error(`${q}
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(G.test(W))throw Error(`${q}
11
- - too many short flags`);if(K.test(W))throw Error(`${q}
12
- - too many long flags`);throw Error(`${q}
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}}kB.Option=XJ;kB.DualOptions=HJ});var BJ=B1((bB)=>{function LB($,U){if(Math.abs($.length-U.length)>3)return Math.max($.length,U.length);let Q=[];for(let G=0;G<=$.length;G++)Q[G]=[G];for(let G=0;G<=U.length;G++)Q[0][G]=G;for(let G=1;G<=U.length;G++)for(let K=1;K<=$.length;K++){let J=1;if($[K-1]===U[G-1])J=0;else J=1;if(Q[K][G]=Math.min(Q[K-1][G]+1,Q[K][G-1]+1,Q[K-1][G-1]+J),K>1&&G>1&&$[K-1]===U[G-2]&&$[K-2]===U[G-1])Q[K][G]=Math.min(Q[K][G],Q[K-2][G-2]+1)}return Q[$.length][U.length]}function zB($,U){if(!U||U.length===0)return"";U=Array.from(new Set(U));let Q=$.startsWith("--");if(Q)$=$.slice(2),U=U.map((W)=>W.slice(2));let G=[],K=3,J=0.4;if(U.forEach((W)=>{if(W.length<=1)return;let q=LB($,W),j=Math.max($.length,W.length);if((j-q)/j>J){if(q<K)K=q,G=[W];else if(q===K)G.push(W)}}),G.sort((W,q)=>W.localeCompare(q)),Q)G=G.map((W)=>`--${W}`);if(G.length>1)return`
14
- (Did you mean one of ${G.join(", ")}?)`;if(G.length===1)return`
15
- (Did you mean ${G[0]}?)`;return""}bB.suggestSimilar=zB});var vJ=B1((EB)=>{var OB=a4("node:events").EventEmitter,NU=a4("node:child_process"),Q1=a4("node:path"),a6=a4("node:fs"),o=a4("node:process"),{Argument:RB,humanReadableArgName:TB}=t6(),{CommanderError:_U}=e4(),{Help:SB,stripColor:CB}=PU(),{Option:MJ,DualOptions:gB}=IU(),{suggestSimilar:ZJ}=BJ();class kU extends OB{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)=>o.stdout.write(U),writeErr:(U)=>o.stderr.write(U),outputError:(U,Q)=>Q(U),getOutHelpWidth:()=>o.stdout.isTTY?o.stdout.columns:void 0,getErrHelpWidth:()=>o.stderr.isTTY?o.stderr.columns:void 0,getOutHasColors:()=>wU()??(o.stdout.isTTY&&o.stdout.hasColors?.()),getErrHasColors:()=>wU()??(o.stderr.isTTY&&o.stderr.hasColors?.()),stripColor:(U)=>CB(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 G=U,K=Q;if(typeof G==="object"&&G!==null)K=G,G=null;K=K||{};let[,J,W]=$.match(/([^ ]+) *(.*)/),q=this.createCommand(J);if(G)q.description(G),q._executableHandler=!0;if(K.isDefault)this._defaultCommandName=q._name;if(q._hidden=!!(K.noHelp||K.hidden),q._executableFile=K.executableFile||null,W)q.arguments(W);if(this._registerCommand(q),q.parent=this,q.copyInheritedSettings(this),G)return this;return q}createCommand($){return new kU($)}createHelp(){return Object.assign(new SB,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 RB($,U)}argument($,U,Q,G){let K=this.createArgument($,U);if(typeof Q==="function")K.default(G).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,G]=$.match(/([^ ]+) *(.*)/),K=U??"display help for command",J=this.createCommand(Q);if(J.helpOption(!1),G)J.arguments(G);if(K)J.description(K);return this._addImplicitHelpCommand=!0,this._helpCommand=J,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 _U($,U,Q));o.exit($)}action($){let U=(Q)=>{let G=this.registeredArguments.length,K=Q.slice(0,G);if(this._storeOptionsAsProperties)K[G]=this;else K[G]=this.opts();return K.push(this),$.apply(this,K)};return this._actionHandler=U,this}createOption($,U){return new MJ($,U)}_callParseArg($,U,Q,G){try{return $.parseArg(U,Q)}catch(K){if(K.code==="commander.invalidArgument"){let J=`${G} ${K.message}`;this.error(J,{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=(G)=>{return[G.name()].concat(G.aliases())},Q=U($).find((G)=>this._findCommand(G));if(Q){let G=U(this._findCommand(Q)).join("|"),K=U($).join("|");throw Error(`cannot add command '${K}' as already have command '${G}'`)}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 G=(K,J,W)=>{if(K==null&&$.presetArg!==void 0)K=$.presetArg;let q=this.getOptionValue(Q);if(K!==null&&$.parseArg)K=this._callParseArg($,K,q,J);else if(K!==null&&$.variadic)K=$._concatValue(K,q);if(K==null)if($.negate)K=!1;else if($.isBoolean()||$.optional)K=!0;else K="";this.setOptionValueWithSource(Q,K,W)};if(this.on("option:"+U,(K)=>{let J=`error: option '${$.flags}' argument '${K}' is invalid.`;G(K,J,"cli")}),$.envVar)this.on("optionEnv:"+U,(K)=>{let J=`error: option '${$.flags}' value '${K}' from env '${$.envVar}' is invalid.`;G(K,J,"env")});return this}_optionEx($,U,Q,G,K){if(typeof U==="object"&&U instanceof MJ)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let J=this.createOption(U,Q);if(J.makeOptionMandatory(!!$.mandatory),typeof G==="function")J.default(K).argParser(G);else if(G instanceof RegExp){let W=G;G=(q,j)=>{let X=W.exec(q);return X?X[0]:j},J.default(K).argParser(G)}else J.default(G);return this.addOption(J)}option($,U,Q,G){return this._optionEx({},$,U,Q,G)}requiredOption($,U,Q,G){return this._optionEx({mandatory:!0},$,U,Q,G)}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(o.versions?.electron)U.from="electron";let G=o.execArgv??[];if(G.includes("-e")||G.includes("--eval")||G.includes("-p")||G.includes("--print"))U.from="eval"}if($===void 0)$=o.argv;this.rawArgs=$.slice();let Q;switch(U.from){case void 0:case"node":this._scriptPath=$[1],Q=$.slice(2);break;case"electron":if(o.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(a6.existsSync($))return;let G=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
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
+ - too many long flags`);throw Error(`${G}
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
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
- - ${G}`;throw Error(K)}_executeSubCommand($,U){U=U.slice();let Q=!1,G=[".js",".ts",".tsx",".mjs",".cjs"];function K(X,B){let Z=Q1.resolve(X,B);if(a6.existsSync(Z))return Z;if(G.includes(Q1.extname(B)))return;let V=G.find((N)=>a6.existsSync(`${Z}${N}`));if(V)return`${Z}${V}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let J=$._executableFile||`${this._name}-${$._name}`,W=this._executableDir||"";if(this._scriptPath){let X;try{X=a6.realpathSync(this._scriptPath)}catch{X=this._scriptPath}W=Q1.resolve(Q1.dirname(X),W)}if(W){let X=K(W,J);if(!X&&!$._executableFile&&this._scriptPath){let B=Q1.basename(this._scriptPath,Q1.extname(this._scriptPath));if(B!==this._name)X=K(W,`${B}-${$._name}`)}J=X||J}Q=G.includes(Q1.extname(J));let q;if(o.platform!=="win32")if(Q)U.unshift(J),U=VJ(o.execArgv).concat(U),q=NU.spawn(o.argv[0],U,{stdio:"inherit"});else q=NU.spawn(J,U,{stdio:"inherit"});else this._checkForMissingExecutable(J,W,$._name),U.unshift(J),U=VJ(o.execArgv).concat(U),q=NU.spawn(o.execPath,U,{stdio:"inherit"});if(!q.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((B)=>{o.on(B,()=>{if(q.killed===!1&&q.exitCode===null)q.kill(B)})});let j=this._exitCallback;q.on("close",(X)=>{if(X=X??1,!j)o.exit(X);else j(new _U(X,"commander.executeSubCommandAsync","(close)"))}),q.on("error",(X)=>{if(X.code==="ENOENT")this._checkForMissingExecutable(J,W,$._name);else if(X.code==="EACCES")throw Error(`'${J}' not executable`);if(!j)o.exit(1);else{let B=new _U(1,"commander.executeSubCommandAsync","(error)");B.nestedError=X,j(B)}}),this.runningCommand=q}_dispatchSubcommand($,U,Q){let G=this._findCommand($);if(!G)this.help({error:!0});G._prepareForParse();let K;return K=this._chainOrCallSubCommandHook(K,G,"preSubcommand"),K=this._chainOrCall(K,()=>{if(G._executableHandler)this._executeSubCommand(G,U.concat(Q));else return G._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,G,K)=>{let J=G;if(G!==null&&Q.parseArg){let W=`error: command-argument value '${G}' is invalid for argument '${Q.name()}'.`;J=this._callParseArg(Q,G,K,W)}return J};this._checkNumberOfArguments();let U=[];this.registeredArguments.forEach((Q,G)=>{let K=Q.defaultValue;if(Q.variadic){if(G<this.args.length){if(K=this.args.slice(G),Q.parseArg)K=K.reduce((J,W)=>{return $(Q,W,J)},Q.defaultValue)}else if(K===void 0)K=[]}else if(G<this.args.length){if(K=this.args[G],Q.parseArg)K=$(Q,K,Q.defaultValue)}U[G]=K}),this.processedArgs=U}_chainOrCall($,U){if($&&$.then&&typeof $.then==="function")return $.then(()=>U());return U()}_chainOrCallHooks($,U){let Q=$,G=[];if(this._getCommandAndAncestors().reverse().filter((K)=>K._lifeCycleHooks[U]!==void 0).forEach((K)=>{K._lifeCycleHooks[U].forEach((J)=>{G.push({hookedCommand:K,callback:J})})}),U==="postAction")G.reverse();return G.forEach((K)=>{Q=this._chainOrCall(Q,()=>{return K.callback(K.hookedCommand,this)})}),Q}_chainOrCallSubCommandHook($,U,Q){let G=$;if(this._lifeCycleHooks[Q]!==void 0)this._lifeCycleHooks[Q].forEach((K)=>{G=this._chainOrCall(G,()=>{return K(this,U)})});return G}_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 G=()=>{if(Q.unknown.length>0)this.unknownOption(Q.unknown[0])},K=`command:${this.name()}`;if(this._actionHandler){G(),this._processArguments();let J;if(J=this._chainOrCallHooks(J,"preAction"),J=this._chainOrCall(J,()=>this._actionHandler(this.processedArgs)),this.parent)J=this._chainOrCall(J,()=>{this.parent.emit(K,$,U)});return J=this._chainOrCallHooks(J,"postAction"),J}if(this.parent&&this.parent.listenerCount(K))G(),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 G(),this._processArguments()}else if(this.commands.length)G(),this.help({error:!0});else G(),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 G=Q.attributeName();if(this.getOptionValue(G)===void 0)return!1;return this.getOptionValueSource(G)!=="default"});$.filter((Q)=>Q.conflictsWith.length>0).forEach((Q)=>{let G=$.find((K)=>Q.conflictsWith.includes(K.attributeName()));if(G)this._conflictingOption(Q,G)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(($)=>{$._checkForConflictingLocalOptions()})}parseOptions($){let U=[],Q=[],G=U,K=$.slice();function J(q){return q.length>1&&q[0]==="-"}let W=null;while(K.length){let q=K.shift();if(q==="--"){if(G===Q)G.push(q);G.push(...K);break}if(W&&!J(q)){this.emit(`option:${W.name()}`,q);continue}if(W=null,J(q)){let j=this._findOption(q);if(j){if(j.required){let X=K.shift();if(X===void 0)this.optionMissingArgument(j);this.emit(`option:${j.name()}`,X)}else if(j.optional){let X=null;if(K.length>0&&!J(K[0]))X=K.shift();this.emit(`option:${j.name()}`,X)}else this.emit(`option:${j.name()}`);W=j.variadic?j:null;continue}}if(q.length>2&&q[0]==="-"&&q[1]!=="-"){let j=this._findOption(`-${q[1]}`);if(j){if(j.required||j.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${j.name()}`,q.slice(2));else this.emit(`option:${j.name()}`),K.unshift(`-${q.slice(2)}`);continue}}if(/^--[^=]+=/.test(q)){let j=q.indexOf("="),X=this._findOption(q.slice(0,j));if(X&&(X.required||X.optional)){this.emit(`option:${X.name()}`,q.slice(j+1));continue}}if(J(q))G=Q;if((this._enablePositionalOptions||this._passThroughOptions)&&U.length===0&&Q.length===0){if(this._findCommand(q)){if(U.push(q),K.length>0)Q.push(...K);break}else if(this._getHelpCommand()&&q===this._getHelpCommand().name()){if(U.push(q),K.length>0)U.push(...K);break}else if(this._defaultCommandName){if(Q.push(q),K.length>0)Q.push(...K);break}}if(this._passThroughOptions){if(G.push(q),K.length>0)G.push(...K);break}G.push(q)}return{operands:U,unknown:Q}}opts(){if(this._storeOptionsAsProperties){let $={},U=this.options.length;for(let Q=0;Q<U;Q++){let G=this.options[Q].attributeName();$[G]=G===this._versionOptionName?this._version:this[G]}return $}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce(($,U)=>Object.assign($,U.opts()),{})}error($,U){if(this._outputConfiguration.outputError(`${$}
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 Q=U||{},G=Q.exitCode||1,K=Q.code||"commander.error";this._exit(G,K,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in o.env){let U=$.attributeName();if(this.getOptionValue(U)===void 0||["default","config","env"].includes(this.getOptionValueSource(U)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,o.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new gB(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((G)=>!U(G)).forEach((G)=>{this.setOptionValueWithSource(G,Q.implied[G],"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=(J)=>{let W=J.attributeName(),q=this.getOptionValue(W),j=this.options.find((B)=>B.negate&&W===B.attributeName()),X=this.options.find((B)=>!B.negate&&W===B.attributeName());if(j&&(j.presetArg===void 0&&q===!1||j.presetArg!==void 0&&q===j.presetArg))return j;return X||J},G=(J)=>{let W=Q(J),q=W.attributeName();if(this.getOptionValueSource(q)==="env")return`environment variable '${W.envVar}'`;return`option '${W.flags}'`},K=`error: ${G($)} cannot be used with ${G(U)}`;this.error(K,{code:"commander.conflictingOption"})}unknownOption($){if(this._allowUnknownOption)return;let U="";if($.startsWith("--")&&this._showSuggestionAfterError){let G=[],K=this;do{let J=K.createHelp().visibleOptions(K).filter((W)=>W.long).map((W)=>W.long);G=G.concat(J),K=K.parent}while(K&&!K._enablePositionalOptions);U=ZJ($,G)}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 G=[];this.createHelp().visibleCommands(this).forEach((K)=>{if(G.push(K.name()),K.alias())G.push(K.alias())}),U=ZJ($,G)}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 G=this.createOption(U,Q);return this._versionOptionName=G.attributeName(),this._registerOption(G),this.on("option:"+G.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 G=[Q.name()].concat(Q.aliases()).join("|");throw Error(`cannot add alias '${$}' to command '${this.name()}' as already have command '${G}'`)}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 TB(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=Q1.basename($,Q1.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 G=U.formatHelp(this,U);if(Q.hasColors)return G;return this._outputConfiguration.stripColor(G)}_getOutputContext($){$=$||{};let U=!!$.error,Q,G,K;if(U)Q=(W)=>this._outputConfiguration.writeErr(W),G=this._outputConfiguration.getErrHasColors(),K=this._outputConfiguration.getErrHelpWidth();else Q=(W)=>this._outputConfiguration.writeOut(W),G=this._outputConfiguration.getOutHasColors(),K=this._outputConfiguration.getOutHelpWidth();return{error:U,write:(W)=>{if(!G)W=this._outputConfiguration.stripColor(W);return Q(W)},hasColors:G,helpWidth:K}}outputHelp($){let U;if(typeof $==="function")U=$,$=void 0;let Q=this._getOutputContext($),G={error:Q.error,write:Q.write,command:this};this._getCommandAndAncestors().reverse().forEach((J)=>J.emit("beforeAllHelp",G)),this.emit("beforeHelp",G);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",G),this._getCommandAndAncestors().forEach((J)=>J.emit("afterAllHelp",G))}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(o.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 G=`${$}Help`;return this.on(G,(K)=>{let J;if(typeof U==="function")J=U({error:K.error,command:K.command});else J=U;if(J)K.write(`${J}
28
- `)}),this}_outputHelpIfRequested($){let U=this._getHelpOption();if(U&&$.find((G)=>U.is(G)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function VJ($){return $.map((U)=>{if(!U.startsWith("--inspect"))return U;let Q,G="127.0.0.1",K="9229",J;if((J=U.match(/^(--inspect(-brk)?)$/))!==null)Q=J[1];else if((J=U.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(Q=J[1],/^\d+$/.test(J[3]))K=J[3];else G=J[3];else if((J=U.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)Q=J[1],G=J[3],K=J[4];if(Q&&K!=="0")return`${Q}=${G}:${parseInt(K)+1}`;return U})}function wU(){if(o.env.NO_COLOR||o.env.FORCE_COLOR==="0"||o.env.FORCE_COLOR==="false")return!1;if(o.env.FORCE_COLOR||o.env.CLICOLOR_FORCE!==void 0)return!0;return}EB.Command=kU;EB.useColor=wU});var NJ=B1((hB)=>{var{Argument:DJ}=t6(),{Command:xU}=vJ(),{CommanderError:fB,InvalidArgumentError:PJ}=e4(),{Help:mB}=PU(),{Option:IJ}=IU();hB.program=new xU;hB.createCommand=($)=>new xU($);hB.createOption=($,U)=>new IJ($,U);hB.createArgument=($,U)=>new DJ($,U);hB.Command=xU;hB.Option=IJ;hB.Argument=DJ;hB.Help=mB;hB.CommanderError=fB;hB.InvalidArgumentError=PJ;hB.InvalidOptionArgumentError=PJ});var M1=B1((Ux,zU)=>{var $0=process||{},zJ=$0.argv||[],s6=$0.env||{},GM=!(!!s6.NO_COLOR||zJ.includes("--no-color"))&&(!!s6.FORCE_COLOR||zJ.includes("--color")||$0.platform==="win32"||($0.stdout||{}).isTTY&&s6.TERM!=="dumb"||!!s6.CI),JM=($,U,Q=$)=>(G)=>{let K=""+G,J=K.indexOf(U,$.length);return~J?$+WM(K,U,Q,J)+U:$+K+U},WM=($,U,Q,G)=>{let K="",J=0;do K+=$.substring(J,G)+Q,J=G+U.length,G=$.indexOf(U,J);while(~G);return K+$.substring(J)},bJ=($=GM)=>{let U=$?JM:()=>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")}};zU.exports=bJ();zU.exports.createColors=bJ});var _J=H1(NJ(),1),{program:uk,createCommand:fk,createArgument:mk,createOption:hk,CommanderError:ck,InvalidArgumentError:lk,InvalidOptionArgumentError:rk,Command:wJ,Argument:nk,Option:ik,Help:ok}=_J.default;import{readFileSync as sB}from"node:fs";function Y$($){return typeof $==="object"&&$!=null&&!Array.isArray($)}function j$($){return typeof $==="object"&&$!=null?{...$}:void 0}function r($){return typeof $==="string"?$:void 0}function T1($){return typeof $==="number"?$:void 0}function g$($){if(!Array.isArray($))return[];return $.map((U)=>j$(U)).filter((U)=>U!=null)}function s4(){return"0.3.0"}var FU="/cli/compatibilidade",e6=null;function $M(){if(e6!=null)return e6;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 G=JSON.parse(U),K=JSON.parse($);Q=kJ(G,K)}else{let G=JSON.parse(UM()),K=Y$(G)?G.supported_niva:void 0,J=Y$(G)?G.compat_table:void 0;Q=kJ(K,J)}if(Q==null)throw Error("Invalid apps/cli/compat.json, fix the compat table");return e6=Q,e6}function kJ($,U){if(!Y$($)||!Array.isArray(U))return null;let Q=r($.min);if(Q==null)return null;let G=r($.max)??null,K=[];for(let J of g$(U)){let W=r(J.niva_min),q=r(J.dist_tag);if(W==null||q==null)return null;K.push({niva_min:W,niva_max:r(J.niva_max)??null,dist_tag:q})}return{supported_niva:{min:Q,max:G},compat_table:K}}function UM(){return sB(new URL("../../compat.json",import.meta.url),"utf-8")}function xJ($){let Q=($.split("-")[0]?.split("+")[0]??"").split(".");if(Q.length!==3)return null;let G=Q.map((K)=>Number.parseInt(K,10));if(G.some((K)=>!Number.isFinite(K)||K<0))return null;return[G[0],G[1],G[2]]}function FJ($,U){let Q=xJ($),G=xJ(U);if(Q===null||G===null)return 0;for(let K=0;K<3;K++)if(Q[K]!==G[K])return Q[K]-G[K];return 0}function LJ($,U){for(let Q of U.compat_table){if(FJ($,Q.niva_min)<0)continue;if(Q.niva_max!=null&&FJ($,Q.niva_max)>0)continue;return Q.dist_tag}return null}var KM=null;function QM(){return KM}function LU(){let $=$M(),U=QM();if(U!=null)return LJ(U,$);return LJ($.supported_niva.min,$)}var K$=H1(M1(),1),qM=new Set(["json","table","plain"]);function YM($){return qM.has($)}function jM(){return process.stdout.isTTY===!0&&process.env.NO_COLOR==null}function S1($){if($.output!=null)return YM($.output)?$.output:"table";if($.json===!0)return"json";return jM()?"table":"json"}function XM($,U){return U in $}function g($,U){if(U==null)return $;let Q={};for(let G of U)if(XM($,G))Q[G]=$[G];return Q}function P($){console.log(JSON.stringify($,null,2))}var HM=/\x1B\[[0-9;]*m/g;function BM($){return $.replaceAll(HM,"")}var MM=[[128512,128591],[127744,128511],[128640,128767],[129280,129535],[129536,129791],[9728,10175],[127456,127487]],ZM=[[65024,65039],[8205,8205]];function AJ($,U){for(let[Q,G]of U)if($>=Q&&$<=G)return!0;return!1}function VM($){if(AJ($,MM))return 2;if(AJ($,ZM))return 0;return 1}function TJ($){let U=BM($),Q=0;for(let G of U)Q+=VM(G.codePointAt(0));return Q}function bU($,U){let Q=TJ($);if(Q>=U)return $;return $+" ".repeat(U-Q)}function OJ($){if($==null)return"";return typeof $==="string"?$:JSON.stringify($)}function u($,U){if(U.length===0){console.log(K$.default.dim("No results."));return}let Q=$.map((K)=>{let J=K.length,W=Math.max(...U.map((q)=>TJ(OJ(q[K]))));return Math.max(J,W)}),G=$.map((K,J)=>K.padEnd(Q[J])).join(" ");console.log(K$.default.bold(G)),console.log(K$.default.dim(Q.map((K)=>"─".repeat(K)).join("──")));for(let K of U){let J=$.map((W,q)=>bU(OJ(K[W]),Q[q])).join(" ");console.log(J)}}function E($){console.log(K$.default.green($))}function A($){console.error(K$.default.red($))}function z($){console.log(K$.default.dim($))}function C1($){console.error(K$.default.yellow($))}function w($){let{output:U,fields:Q}=$,G=S1({json:$.json===!0,output:typeof U==="string"?U:void 0}),K=typeof Q==="string"?Q.split(",").map((J)=>J.trim()):void 0;return{format:G,fields:K}}function X$($){if($.page==null)return;if($.total_pages==null||$.total==null){z(`Page ${$.page}`);return}z(`Page ${$.page}/${$.total_pages} (${$.total} total)`)}function A$($){if($==null)return"—";let U=Math.ceil($/1000);if(U===0)return"0s";let Q=Math.floor(U/3600),G=Math.floor(U%3600/60),K=U%60;if(Q>0)return G>0?`${Q}h ${G}m`:`${Q}h`;if(G>0)return K>0?`${G}m ${K}s`:`${G}m`;return`${K}s`}function AU($){if($==null)return"—";switch($){case"answered":return K$.default.green(`✓ ${$}`);case"missed":return K$.default.red(`✗ ${$}`);case"busy":return K$.default.yellow(`● ${$}`);case"failed":return K$.default.dim(`✗ ${$}`);default:return $}}function OU($,U){if($==null)return"—";let Q=U!=null&&U>0?"+":"",G=U!=null?` (${Q}${U})`:"";switch($){case"positive":return K$.default.green(`\uD83D\uDE0A ${$}${G}`);case"negative":return K$.default.red(`\uD83D\uDE1E ${$}${G}`);case"neutral":return K$.default.yellow(`\uD83D\uDE10 ${$}${G}`);case"mixed":return K$.default.blue(`\uD83D\uDD00 ${$}${G}`);default:return`${$}${G}`}}var vM={voicemail:"Voicemail",announcement:"Carrier announcement",ivr:"IVR / switchboard",screening:"Call screening",human:"Human",unknown:"Unclassified"};function U0($){return $==null?"—":vM[$]}function Z1($,U,Q=20){let G=U>0?$/U:0,K=Math.round(G*Q),J=Q-K;return"█".repeat(K)+"░".repeat(J)}function r$($,U,Q,G=20){let K=Z1(U,Q,G),J=Q>0?Math.round(U/Q*100):0;console.log(` ${bU($,14)} ${K} ${U} (${J}%)`)}function s($){for(let U=0;U<$.length;U++){let Q=$[U],G=Math.max(...Q.rows.map((J)=>J.label.length)),K=Math.max(G+4+30,Q.title.length+4);console.log(K$.default.dim(`┌─ ${Q.title} ${"─".repeat(Math.max(0,K-Q.title.length-4))}`));for(let J of Q.rows){let W=J.value==null?"—":String(J.value);console.log(`${K$.default.dim("│")} ${bU(J.label,G)} ${W}`)}if(console.log(K$.default.dim(`└${"─".repeat(K)}`)),U<$.length-1)console.log("")}}function RU($){for(let U=0;U<$.length;U++){let Q=$[U],G=U===$.length-1,K=G?"└──":"├──",J=Q.detail!=null?K$.default.dim(` (${Q.detail})`):"";if(console.log(` ${K} ${Q.label}${J}`),Q.children!=null){let W=G?" ":"│ ";for(let q of Q.children)console.log(K$.default.dim(` ${W}${q}`))}}}function DM($){let U=$.toLowerCase();return U==="caller"||U==="speaker_l"||U==="speaker_01"}function SJ($){if($.length===0){z(" No transcript available.");return}for(let U of $){let Q=Math.floor(U.initial_time/60),G=Math.floor(U.initial_time%60),K=`${String(Q).padStart(2,"0")}:${String(G).padStart(2,"0")}`,J=DM(U.speaker)?K$.default.blue("Caller"):K$.default.green("Agent "),W=K$.default.dim(`[${K}]`);console.log(` ${W} ${J} ${K$.default.dim(">")} ${U.text}`)}}function RJ($,U){if(/^\d{4}-\d{2}-\d{2}$/.test($))return U?`${$}T23:59:59.999Z`:`${$}T00:00:00.000Z`;return $}function V1($,U=0){let Q=new Date,G=$.from!=null?RJ($.from,!1):new Date(Q.getFullYear(),Q.getMonth(),Q.getDate()-U).toISOString(),K=$.to!=null?RJ($.to,!0):Q.toISOString();return{date_from:G,date_to:K}}function p$($){let U=typeof $==="string"?new Date($):$,Q=String(U.getDate()).padStart(2,"0"),G=String(U.getMonth()+1).padStart(2,"0"),K=String(U.getHours()).padStart(2,"0"),J=String(U.getMinutes()).padStart(2,"0");return`${Q}/${G} ${K}:${J}`}var O={SUCCESS:0,GENERAL_ERROR:1,USAGE_ERROR:2,NOT_FOUND:3,PERMISSION_DENIED:4,CONFLICT:5},TU="table",PM="";function IM($){if($.endsWith("_NOT_FOUND")||$==="NOT_FOUND"||$==="AUDIO_FILE_CONTENT_MISSING")return O.NOT_FOUND;if($==="UNAUTHORIZED"||$==="FORBIDDEN"||$==="ADMIN_REQUIRED"||$==="API_KEY_INVALID"||$==="INSUFFICIENT_SCOPE")return O.PERMISSION_DENIED;if($==="UNPROCESSABLE_CONTENT"||$==="BAD_REQUEST")return O.USAGE_ERROR;if($==="AUDIO_FILE_TOO_LARGE"||$==="AUDIO_FILE_INVALID_FORMAT"||$==="AUDIO_FILE_NOT_TTS"||$==="TTS_VOICE_UNAVAILABLE")return O.USAGE_ERROR;if($==="CONFLICT"||$.startsWith("DUPLICATE_")||$.endsWith("_IN_USE"))return O.CONFLICT;if($==="MODULE_DISABLED")return O.PERMISSION_DENIED;return O.GENERAL_ERROR}function NM($){return $==="INTERNAL_SERVER_ERROR"||$==="SERVICE_UNAVAILABLE"}var _M={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 wM($,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"}
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
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 kM($){let U=j$($);if(U==null)return` • ${String($)}`;let Q=U.path,G=Array.isArray(Q)?Q.join("."):"",K=U.messageKey??U.code??"invalid",J;if(typeof U.message==="string")J=U.message;else if(typeof K==="string")J=K;else J=JSON.stringify(K);return` ✗ ${G?`${G}: `:""}${J}`}function $6($){return $ instanceof Error&&"defined"in $&&"code"in $}function K0($){let U=String(j$($)?.code);if(U==="NOT_FOUND"&&j$($)?.defined===!1)return xM();return{code:U,message:$.message,data:j$(j$($)?.data),hint:_M[U],exitCode:IM(U),retryable:NM(U)}}function xM(){let $=LU();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 ${FU}`:`Run: npx @sippulse/niva@${$} <command>`} (the server's NIVA version does not offer this procedure).`,exitCode:O.USAGE_ERROR,retryable:!1}}function Q0($){A(`Error: ${$.code} — ${$.message}`);let U=$.data?.issues;if(Array.isArray(U))for(let Q of U)A(kM(Q));if($.hint!=null)z(` ${$.hint}`)}function FM($){if(TU==="json")P({error:$.code,message:$.message,data:$.data,hint:$.hint,retryable:$.retryable});else Q0($);process.exit($.exitCode)}function SU($){return $ instanceof Error?wM($,PM):String($)}function g1($){if($6($))FM(K0($));let U=SU($);if(TU==="json")P({error:"CONNECTION_ERROR",message:$ instanceof Error?$.message:String($),retryable:!0});else A(U);process.exit(O.GENERAL_ERROR)}function X4($){if($6($))g1($);let U=$ instanceof Error?$.message:String($);if(TU==="json")P({error:"STREAM_ERROR",message:U,retryable:!0});else A(`Stream error: ${U}`);process.exit(O.GENERAL_ERROR)}async function _($){try{return await $}catch(U){g1(U)}}function n$($="Not yet implemented."){z($),process.exit(O.USAGE_ERROR)}function CJ($,U){$.command("ai").description("AI module resources").command("agents").description("List AI agents available for voice interactions").action(async()=>{let{format:G,fields:K}=w($.opts()),J=await _(U().ai.listAgents());if(G==="json"){let W=K?J.map((q)=>g(q,K)):J;P(W);return}u(["ID","Name","Language","SIP Inbound","Description"],J.map((W)=>({ID:W.id,Name:W.name,Language:W.language,"SIP Inbound":W.sip_inbound_enabled?"enabled":"disabled",Description:W.description??"—"})))})}import{readFile as $W,writeFile as UW}from"node:fs/promises";import{basename as KW}from"node:path";function LM($,U){let Q=U.toLowerCase();if(Q.endsWith(".wav"))return zM($);if(Q.endsWith(".mp3"))return uM($);return}function G0($){if(!Number.isFinite($)||$<=0)return;let U=Math.round($);if(U<=0||U>86400000)return;return U}function gJ($,U,Q){let G="";for(let K=0;K<Q;K+=1)G+=String.fromCharCode($[U+K]??0);return G}function U6($,U,Q){if(U+Q.length>$.byteLength)return!1;return gJ($,U,Q.length)===Q}function EJ($){return new DataView($.buffer,$.byteOffset,$.byteLength)}function zM($){let U=$.byteLength;if(U<12||!U6($,0,"RIFF")||!U6($,8,"WAVE"))return;let Q=EJ($),G,K,J=12;while(J+8<=U){let W=gJ($,J,4),q=Q.getUint32(J+4,!0),j=J+8;if(W==="fmt "&&q>=16&&j+16<=U){let B=Q.getUint16(j+2,!0),Z=Q.getUint32(j+4,!0),V=Q.getUint32(j+8,!0),N=Q.getUint16(j+14,!0);G=V>0?V:Z*B*N/8}else if(W==="data"){K=Math.min(q,U-j);break}let X=j+q+q%2;if(X<=J)return;J=X}if(G===void 0||G<=0||K===void 0)return;return G0(K/G*1000)}var bM=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320,0],AM=[0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,0],OM=[44100,48000,32000,0],RM=[22050,24000,16000,0],TM=[11025,12000,8000,0];function SM($){if($===3)return OM;if($===2)return RM;return TM}function CM($,U){if($)return U?17:32;return U?9:17}function gM($,U){let Q=$[U+1],G=$[U+2],K=$[U+3];if(Q===void 0||G===void 0||K===void 0)return;let J=Q>>3&3,W=Q>>1&3;if(J===1||W!==1)return;let q=J===3,j=(q?bM:AM)[G>>4&15]??0,X=SM(J)[G>>2&3]??0;if(j===0||X===0)return;let B=(K>>6&3)===3;return{bitrate:j*1000,sampleRate:X,samplesPerFrame:q?1152:576,sideInfoSize:CM(q,B)}}function EM($,U,Q){let G=U+4+Q;if(!U6($,G,"Xing")&&!U6($,G,"Info"))return;if(G+12>$.byteLength)return;let K=EJ($);if((K.getUint32(G+4,!1)&1)===0)return;let W=K.getUint32(G+8,!1);return W>0?W:void 0}function yM($){if(!U6($,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 G=(U&16)!==0?10:0;return 10+Q+G}function uM($){let U=$.byteLength,Q=yM($);for(let G=Q;G+4<=U;G+=1){if($[G]!==255||(($[G+1]??0)&224)!==224)continue;let K=gM($,G);if(K===void 0)continue;let J=EM($,G,K.sideInfoSize);if(J!==void 0)return G0(J*K.samplesPerFrame*1000/K.sampleRate);return G0((U-G)*8*1000/K.bitrate)}return}async function fM($,U){let Q=[U,"-v","error","-show_entries","format=duration","-of","csv=p=0",$],G;try{G=Bun.spawn(Q,{stdout:"pipe",stderr:"ignore"})}catch{return}let K=mM(G).catch(()=>{return}),J,W=new Promise((q)=>{J=setTimeout(()=>{G.kill(),setTimeout(()=>G.kill("SIGKILL"),250).unref(),q(void 0)},3000)});try{let q=await Promise.race([K,W]);if(q?.exitCode!==0)return;return G0(Number(q.stdout.trim())*1000)}finally{if(J!==void 0)clearTimeout(J)}}async function mM($){let[U,Q]=await Promise.all([new Response($.stdout).text(),$.exited]);return{stdout:U,exitCode:Q}}async function yJ($){let U=LM($.bytes,$.filePath);if(U!==void 0)return{durationMs:U,source:"header"};if($.noProbe===!0)return{source:"none"};let Q=await fM($.filePath,$.ffprobePath??"ffprobe");if(Q!==void 0)return{durationMs:Q,source:"ffprobe"};return{source:"none"}}import{createInterface as mJ}from"node:readline/promises";function hJ(){return process.stdin.isTTY===!0}var uJ=5;async function fJ($,U,Q){let G=$[U].value;for(let K=0;K<uJ;K++){let J=(await Q(`Choice [${U+1}]: `)).trim();if(J==="")return G;let W=/^\d+$/.test(J)?$[Number(J)-1]:void 0;if(W!=null)return W.value;A(`Invalid choice — enter a number between 1 and ${$.length}.`)}return A(`No valid choice after ${uJ} attempts — using the default.`),G}async function cJ($,U,Q={}){let G=Q.defaultIndex??0;console.log($);for(let[J,W]of U.entries())console.log(` ${J+1}) ${W.label}`);if(console.log(""),Q.ask!=null)return fJ(U,G,Q.ask);let K=mJ({input:process.stdin,output:process.stdout});try{return await fJ(U,G,async(J)=>K.question(J))}finally{K.close()}}async function v1($,U){if(U.yes)return;if(process.stdin.isTTY!==!0)A("Refusing to prompt in non-interactive mode. Re-run with --yes to confirm."),process.exit(O.USAGE_ERROR);let Q=mJ({input:process.stdin,output:process.stdout});try{let G=await Q.question(`${$} [y/N] `);if(!/^y(?:es)?$/i.test(G.trim()))A("Aborted."),process.exit(O.USAGE_ERROR)}finally{Q.close()}}var lJ=/^(?:[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 hM($){return typeof $==="string"&&lJ.test($)}var rJ=hM;var M$=[];for(let $=0;$<256;++$)M$.push(($+256).toString(16).slice(1));function CU($,U=0){return(M$[$[U+0]]+M$[$[U+1]]+M$[$[U+2]]+M$[$[U+3]]+"-"+M$[$[U+4]]+M$[$[U+5]]+"-"+M$[$[U+6]]+M$[$[U+7]]+"-"+M$[$[U+8]]+M$[$[U+9]]+"-"+M$[$[U+10]]+M$[$[U+11]]+M$[$[U+12]]+M$[$[U+13]]+M$[$[U+14]]+M$[$[U+15]]).toLowerCase()}function cM($,U=0){let Q=CU($,U);if(!rJ(Q))throw TypeError("Stringified UUID is invalid");return Q}var J0=cM;var lM=new Uint8Array(16);function W0(){return crypto.getRandomValues(lM)}var gU={};function rM($,U,Q){let G;if($)G=nJ($.random??$.rng?.()??W0(),$.msecs,$.seq,U,Q);else{let K=Date.now(),J=W0();nM(gU,K,J),G=nJ(J,gU.msecs,gU.seq,U,Q)}return U??CU(G)}function nM($,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 nJ($,U,Q,G,K=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!G)G=new Uint8Array(16),K=0;else if(K<0||K+16>G.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],G[K++]=U/1099511627776&255,G[K++]=U/4294967296&255,G[K++]=U/16777216&255,G[K++]=U/65536&255,G[K++]=U/256&255,G[K++]=U&255,G[K++]=112|Q>>>28&15,G[K++]=Q>>>20&255,G[K++]=128|Q>>>14&63,G[K++]=Q>>>6&255,G[K++]=Q<<2&255|$[10]&3,G[K++]=$[11],G[K++]=$[12],G[K++]=$[13],G[K++]=$[14],G[K++]=$[15],G}var EU=rM;function iM($){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 $$="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 yU($){let U=Array(26).fill("");if($.length!==16)throw Error(`Invalid length. Expected 16 bytes, got ${$.length}. Input: ${$}`);return U[0]=$$[($[0]&224)>>5],U[1]=$$[$[0]&31],U[2]=$$[($[1]&248)>>3],U[3]=$$[($[1]&7)<<2|($[2]&192)>>6],U[4]=$$[($[2]&62)>>1],U[5]=$$[($[2]&1)<<4|($[3]&240)>>4],U[6]=$$[($[3]&15)<<1|($[4]&128)>>7],U[7]=$$[($[4]&124)>>2],U[8]=$$[($[4]&3)<<3|($[5]&224)>>5],U[9]=$$[$[5]&31],U[10]=$$[($[6]&248)>>3],U[11]=$$[($[6]&7)<<2|($[7]&192)>>6],U[12]=$$[($[7]&62)>>1],U[13]=$$[($[7]&1)<<4|($[8]&240)>>4],U[14]=$$[($[8]&15)<<1|($[9]&128)>>7],U[15]=$$[($[9]&124)>>2],U[16]=$$[($[9]&3)<<3|($[10]&224)>>5],U[17]=$$[$[10]&31],U[18]=$$[($[11]&248)>>3],U[19]=$$[($[11]&7)<<2|($[12]&192)>>6],U[20]=$$[($[12]&62)>>1],U[21]=$$[($[12]&1)<<4|($[13]&240)>>4],U[22]=$$[($[13]&15)<<1|($[14]&128)>>7],U[23]=$$[($[14]&124)>>2],U[24]=$$[($[14]&3)<<3|($[15]&224)>>5],U[25]=$$[$[15]&31],U.join("")}function dJ($){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 G=new Uint8Array(16);return G[0]=S[Q[0]]<<5|S[Q[1]],G[1]=S[Q[2]]<<3|S[Q[3]]>>2,G[2]=(S[Q[3]]&3)<<6|S[Q[4]]<<1|S[Q[5]]>>4,G[3]=(S[Q[5]]&15)<<4|S[Q[6]]>>1,G[4]=(S[Q[6]]&1)<<7|S[Q[7]]<<2|S[Q[8]]>>3,G[5]=(S[Q[8]]&7)<<5|S[Q[9]],G[6]=S[Q[10]]<<3|S[Q[11]]>>2,G[7]=(S[Q[11]]&3)<<6|S[Q[12]]<<1|S[Q[13]]>>4,G[8]=(S[Q[13]]&15)<<4|S[Q[14]]>>1,G[9]=(S[Q[14]]&1)<<7|S[Q[15]]<<2|S[Q[16]]>>3,G[10]=(S[Q[16]]&7)<<5|S[Q[17]],G[11]=S[Q[18]]<<3|S[Q[19]]>>2,G[12]=(S[Q[19]]&3)<<6|S[Q[20]]<<1|S[Q[21]]>>4,G[13]=(S[Q[21]]&15)<<4|S[Q[22]]>>1,G[14]=(S[Q[22]]&1)<<7|S[Q[23]]<<2|S[Q[24]]>>3,G[15]=(S[Q[24]]&7)<<5|S[Q[25]],G}function oM($){if($.length>63)return!1;let U,Q,G;for(Q=0,G=$.length;Q<G;Q+=1){U=$.charCodeAt(Q);let K=U>96&&U<123,J=U===95;if((Q===0||Q===G-1)&&!K)return!1;if(!(K||J))return!1}return!0}var dM=class extends Error{constructor($){super(`Invalid prefix "${$}". Must be at most 63 ASCII letters [a-z_]`);this.name="InvalidPrefixError"}},pM=class extends Error{constructor($,U){super(`Invalid TypeId. Prefix mismatch. Expected ${$}, got ${U}`);this.name="PrefixMismatchError"}},tM=class extends Error{constructor($){super(`Invalid TypeId. Prefix cannot be empty when there's a separator: ${$}`);this.name="EmptyPrefixError"}},pJ=class extends Error{constructor($){super(`Invalid length. Suffix should have 26 characters, got ${$}`);this.name="InvalidSuffixLengthError"}},aM=class extends Error{constructor($){super(`Invalid suffix. First character "${$}" must be in the range [0-7]`);this.name="InvalidSuffixCharacterError"}},eM=class extends Error{constructor($,U){super(`Cannot convert TypeID of type ${$} to type ${U}`);this.name="TypeIDConversionError"}};function tJ($="",U=""){if(!oM($))throw new dM($);let Q;if(U)Q=U;else{let G=new Uint8Array(16);EU(void 0,G),Q=yU(G)}if(Q.length!==26)throw new pJ(Q.length);if(Q[0]>"7")throw new aM(Q[0]);if(dJ(Q),$==="")return Q;else return`${$}_${Q}`}function sM($,U){let Q,G,K=$.lastIndexOf("_");if(K===-1)Q="",G=$;else if(Q=$.substring(0,K),G=$.substring(K+1),!Q)throw new tM($);if(!G)throw new pJ(0);if(U&&Q!==U)throw new pM(U,Q);return tJ(Q,G)}function iJ($){let U=$.lastIndexOf("_");if(U===-1)return"";return $.substring(0,U)}function oJ($){let U=$.lastIndexOf("_");if(U===-1)return $;return $.substring(U+1)}var H4=class{constructor($,U=""){this.prefix=$,this.suffix=U;let Q=tJ($,U);this.prefix=iJ(Q),this.suffix=oJ(Q)}getType(){return this.prefix}getSuffix(){return this.suffix}asType($){let U=this;if(U.prefix!==$)throw new eM(U.prefix,$);return U}toUUIDBytes(){return dJ(this.suffix)}toUUID(){return J0(this.toUUIDBytes())}toString(){if(this.prefix==="")return this.suffix;return`${this.prefix}_${this.suffix}`}static fromString($,U){let Q=sM($,U);return new H4(iJ(Q),oJ(Q))}static fromUUIDBytes($,U){let Q=yU(U);return new H4($,Q)}static fromUUID($,U){let Q=yU(iM(U));return new H4($,Q)}};var G1={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"};function q0($,U){return H4.fromUUID(G1[$],U).toString()}var $Z=new Map(Object.keys(G1).map(($)=>[G1[$],$]));function uU($){return $Z.get($)}var UZ=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function K6($){if(UZ.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),G=uU(Q);if(G===void 0)return{kind:"invalid",reason:"unknown-prefix"};try{return{kind:"typeid",entity:G,prefix:Q,uuid:H4.fromString($,Q).toUUID()}}catch{return{kind:"invalid",reason:"malformed-suffix"}}}function i$($){return $}function KZ($){return`a ${G1[$]}_... TypeID for ${$}, or the raw UUID of that row`}function aJ($,U,Q){A(`Invalid id "${U}": ${Q}`),z(` Expected ${KZ($)}.`),z(" Convert between the two forms with: niva id <value> [--as <entity>]"),process.exit(O.USAGE_ERROR)}function QZ($){let U=$.lastIndexOf("_");return U>0?$.slice(0,U):""}function eJ($,U){let Q=K6(U);if(Q.kind==="uuid")return q0($,Q.uuid);let G=uU(QZ(U));if(G===$)return U;if(G!==void 0)aJ($,U,`it is a ${G} id`);aJ($,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((G)=>eJ($,G));else if(U!==void 0)Q=eJ($,U);return Q}import{Buffer as GZ}from"node:buffer";async function E1(){return new Promise(($,U)=>{let Q=[];process.stdin.on("data",(G)=>Q.push(G)),process.stdin.on("end",()=>$(GZ.concat(Q).toString("utf-8"))),process.stdin.on("error",U)})}var JZ=10,WZ=new Set(["UNAUTHORIZED","FORBIDDEN","API_KEY_INVALID","ADMIN_REQUIRED","INSUFFICIENT_SCOPE"]);function QW($,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(G)=>{let{format:K,fields:J}=w($.opts()),W=await _(U().audioFiles.list({page:Number(G.page),limit:Number(G.limit),search:G.search}));if(K==="json"){let q=J?W.items.map((j)=>g(j,J)):W;P(q);return}u(["ID","Name","Type","Duration"],W.items.map((q)=>({ID:q.id,Name:q.name,Type:q.type,Duration:GW(q.duration_ms)}))),X$(W)}),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(G,K)=>{let{format:J}=w($.opts()),W=$.opts().yes===!0;if(K.name!=null&&G.length>1)A("--name names a single audio file; drop it when uploading several at once."),process.exit(O.USAGE_ERROR);if(K.durationMs!=null&&G.length>1)A("--duration-ms describes a single audio file; drop it when uploading several at once."),process.exit(O.USAGE_ERROR);let q=YZ(K.durationMs);if(G.length>JZ)await v1(`Upload ${G.length} audio files to the library?`,{yes:W});let j=[],X=O.SUCCESS;for(let B of G){let Z=await jZ(U(),B,{format:J,overrideMs:q,noProbe:K.probe===!1,...K.name!=null&&{name:K.name}});if(j.push(Z),Z.exitCode>X)X=Z.exitCode;if(Z.abort)break}if(ZZ(j,J),X!==O.SUCCESS)process.exit(X)}),Q.command("show <audio_file_id>").description("Show an audio file's metadata").action(async(G)=>{let{format:K,fields:J}=w($.opts()),W=await _(U().audioFiles.getById({audio_file_id:b("audio_files",G)}));if(W==null)A("Audio file not found"),process.exit(O.NOT_FOUND);if(K==="json"){P(J?g(W,J):W);return}s(Y0(W))}),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(G,K)=>{let{format:J}=w($.opts()),W=$.opts(),q=W.json===!0||W.output==="json";if(K.out==="-"&&q)A("--out - streams binary audio to stdout and cannot be combined with --json."),process.exit(O.USAGE_ERROR);let j=U(),X=await _(j.audioFiles.content({audio_file_id:b("audio_files",G)})),B=new Uint8Array(await X.arrayBuffer());if(K.out==="-"){process.stdout.write(B);return}let Z;if(K.out!=null)Z=K.out,await UW(Z,B);else Z=await BZ(j,G,X.name),await MZ(Z,B,K.force===!0);if(J==="json"){P({path:Z,bytes:B.length});return}E(`Saved ${Z} (${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(G,K)=>{let{format:J}=w($.opts());if(K.name==null&&K.description==null)A("Nothing to update — pass --name and/or --description."),process.exit(O.USAGE_ERROR);let W=await _(U().audioFiles.update({audio_file_id:b("audio_files",G),...K.name!=null&&{name:K.name},...K.description!=null&&{description:K.description}}));if(J==="json"){P(W);return}E(`Audio file updated: ${W.name}`),s(Y0(W))}),Q.command("delete <audio_file_id>").description("Delete an audio file from the library").action(async(G)=>{let{format:K}=w($.opts()),J=$.opts().yes===!0;await v1(`Delete audio file ${G}?`,{yes:J});try{await U().audioFiles.delete({audio_file_id:b("audio_files",G)})}catch(W){VZ(W,K)}if(K==="json"){P({id:G,deleted:!0});return}E(`Audio file deleted: ${G}`)}),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(G)=>{let{format:K}=w($.opts()),J=await sJ(G),W=await _(U().audioFiles.generateTts({name:G.name,text:J,...G.description!=null&&{description:G.description},...G.voice!=null&&{voice:G.voice},...G.model!=null&&{model:G.model}}));if(K==="json"){P(W);return}E(`TTS audio generated: ${W.id}`),s(Y0(W))}),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(G,K)=>{let{format:J}=w($.opts()),W=$.opts().yes===!0,q=await sJ(K);await v1(`Overwrite the audio content of ${G}?`,{yes:W});let j=await _(U().audioFiles.regenerateTts({audio_file_id:b("audio_files",G),text:q,...K.voice!=null&&{voice:K.voice},...K.model!=null&&{model:K.model}}));if(J==="json"){P(j);return}E(`TTS audio regenerated: ${j.id}`),s(Y0(j))})}var qZ="FILE_UNREADABLE";function GW($){if($==null)return"—";if($<60000)return`${($/1000).toFixed(1)}s`;return A$($)}function YZ($){if($==null)return;let U=Number($);if(!Number.isInteger(U)||U<=0)A(`Invalid --duration-ms "${$}": expected a positive whole number of milliseconds.`),process.exit(O.USAGE_ERROR);return U}async function jZ($,U,Q){let G;try{G=await $W(U)}catch(J){let W=J instanceof Error?J.message:String(J);if(Q.format!=="json")A(`Cannot read ${U}: ${W}`);return{file:U,ok:!1,id:void 0,durationSource:"none",error:qZ,message:W,exitCode:O.USAGE_ERROR,abort:!1}}let K=await XZ(U,G,Q);try{let J=await $.audioFiles.upload({file:new File([G],KW(U)),...Q.name!=null&&{name:Q.name},...K.durationMs!=null&&{duration_ms:K.durationMs}});return{file:U,ok:!0,id:J.id,durationSource:K.source,error:void 0,message:void 0,exitCode:O.SUCCESS,abort:!1}}catch(J){return HZ(J,U,K.source,Q.format)}}async function XZ($,U,Q){if(Q.overrideMs!=null)return{durationMs:Q.overrideMs,source:"flag"};let G=process.env.NIVA_FFPROBE,K=await yJ({filePath:$,bytes:U,noProbe:Q.noProbe,...G!=null&&G!==""&&{ffprobePath:G}});if(K.source==="none"&&Q.format!=="json")z(`duration unknown for ${$} — install ffmpeg or pass --duration-ms`);return K}function HZ($,U,Q,G){let K={file:U,ok:!1,id:void 0,durationSource:Q};if(!$6($)){let W=SU($);if(G!=="json")A(W);return{...K,error:"CONNECTION_ERROR",message:W,exitCode:O.GENERAL_ERROR,abort:!0}}let J=K0($);if(G!=="json")Q0(J);return{...K,error:J.code,message:J.message,exitCode:J.exitCode,abort:WZ.has(J.code)}}async function BZ($,U,Q){let K=[(await _($.audioFiles.getById({audio_file_id:b("audio_files",U)})))?.filename,Q,U];return KW(K.find((J)=>J!=null&&J!=="")??U)}async function MZ($,U,Q){try{await UW($,U,Q?{}:{flag:"wx"})}catch(G){if(j$(G)?.code!=="EEXIST")throw G;A(`${$} already exists — pass --out <path> to write elsewhere, or --force to overwrite it.`),process.exit(O.CONFLICT)}}function ZZ($,U){if(U==="json"){P($.map((G)=>({file:G.file,ok:G.ok,...G.id!=null&&{id:G.id},durationSource:G.durationSource,...G.error!=null&&{error:G.error},...G.message!=null&&{message:G.message}})));return}u(["File","ID","Status"],$.map((G)=>({File:G.file,ID:G.id??"—",Status:G.ok?"uploaded":G.error??"failed"})));let Q=$.filter((G)=>!G.ok).length;E(`${$.length-Q} uploaded, ${Q} failed`)}function VZ($,U){if(!$6($))g1($);let Q=K0($),G=vZ(Q);if(G==null)g1($);if(U==="json")P({error:Q.code,message:Q.message,plans:G,hint:Q.hint,retryable:Q.retryable});else Q0(Q),z(` Referenced by: ${G.join(", ")}`);process.exit(Q.exitCode)}function vZ($){if($.code!=="AUDIO_FILE_IN_USE")return;let U=$.data?.plans;if(!Array.isArray(U))return;return U.map(String)}async function sJ($){if($.text!=null&&$.textFile!=null)A("--text and --text-file are mutually exclusive."),process.exit(O.USAGE_ERROR);if($.text!=null)return $.text;if($.textFile==null)A("No text to synthesize — pass --text <text> or --text-file <path|->."),process.exit(O.USAGE_ERROR);let Q=($.textFile==="-"?await E1():await $W($.textFile,"utf-8")).trim();if(Q==="")A(`No text to synthesize: ${$.textFile==="-"?"stdin":$.textFile} is empty.`),process.exit(O.USAGE_ERROR);return Q}function Y0($){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:GW($.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 JW($){return $[0]??{}}function u1($){return Array.isArray($)?$:$===void 0||$===null?[]:[$]}var fU="orpc",DZ="@orpc/shared",PZ="1.15.0";class mU extends Error{constructor(...$){super(...$);this.name="AbortError"}}function j0($){let U;return()=>{if(U)return U.result;let Q=$();return U={result:Q},Q}}function IZ($){let U=Promise.resolve();return(...Q)=>{return U=U.catch(()=>{}).then(()=>{return $(...Q)})}}var NZ=2,_Z=`__${DZ}@${PZ}/otel/config__`;function Q6(){return globalThis[_Z]}function X0($,U={},Q){return Q6()?.tracer?.startSpan($,U,Q)}function D1($,U,Q={}){if(!$)return;let G=wZ(U);if($.recordException(G),!Q.signal?.aborted||Q.signal.reason!==U)$.setStatus({code:NZ,message:G.message})}function wZ($){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 f1({name:$,context:U,...Q},G){let K=Q6()?.tracer;if(!K)return G();let J=async(W)=>{try{return await G(W)}catch(q){throw D1(W,q,Q),q}finally{W.end()}};if(U)return K.startActiveSpan($,Q,U,J);else return K.startActiveSpan($,Q,J)}async function y1($,U){let Q=Q6();if(!$||!Q)return U();let G=Q.trace.setSpan(Q.context.active(),$);return Q.context.with(G,U)}function J1($){if(!$||typeof $!=="object")return!1;return"next"in $&&typeof $.next==="function"&&Symbol.asyncIterator in $&&typeof $[Symbol.asyncIterator]==="function"}var kZ=Symbol.for("asyncDispose"),xZ=Symbol.asyncDispose??kZ;class P1{#$=!1;#U=!1;#K;#Q;constructor($,U){this.#K=U,this.#Q=IZ(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[xZ](){if(this.#$=!0,!this.#U)this.#U=!0,await this.#K("dispose")}[Symbol.asyncIterator](){return this}}function hU({name:$,...U},Q){let G;return new P1(async()=>{G??=X0($);try{let K=await y1(G,()=>Q.next());return G?.addEvent(K.done?"completed":"yielded"),K}catch(K){throw D1(G,K,U),K}},async(K)=>{try{if(K!=="next")await y1(G,()=>Q.return?.())}catch(J){throw D1(G,J,U),J}finally{G?.end()}})}class FZ{#$=new Map;#U;constructor($={}){this.#U=$.maxBufferedEvents??100}get size(){return this.#$.size}publish($,U){let Q=this.#$.get($);if(!Q)return;for(let G of Q)G(U)}subscribe($,U){if(typeof U==="function"){let j=this.#$.get($);if(!j)this.#$.set($,j=[]);return j.push(U),j0(()=>{if(j.splice(j.indexOf(U),1),j.length===0)this.#$.delete($)})}let Q=U?.signal,G=U?.maxBufferedEvents??this.#U;Q?.throwIfAborted();let K=[],J=[],W=this.subscribe($,(j)=>{let X=J.shift();if(X)X[0]({done:!1,value:j});else if(K.push(j),K.length>G)K.shift()}),q=(j)=>{W(),J.forEach((X)=>X[1](j.target.reason)),J.length=0,K.length=0};return Q?.addEventListener("abort",q,{once:!0}),new P1(async()=>{if(Q?.aborted)throw Q.reason;if(K.length>0)return{done:!1,value:K.shift()};return new Promise((j,X)=>{J.push([j,X])})},async()=>{W(),Q?.removeEventListener("abort",q),J.forEach((j)=>j[0]({done:!0,value:void 0})),J.length=0,K.length=0})}}class LZ{index=BigInt(1);generate(){let $=this.index.toString(36);return this.index++,$}}function G6($,U,Q){let G=(K,J)=>{let W=$[J];if(!W)return Q(K);return W({...K,next:(q=K)=>G(q,J+1)})};return G(U,0)}function J6($){if(!$)return;return JSON.parse($)}function m1($){return JSON.stringify($)}function WW($){if(!t$($))return null;return Object.getPrototypeOf($)?.constructor}function H0($){if(!$||typeof $!=="object")return!1;let U=Object.getPrototypeOf($);return U===Object.prototype||!U||!U.constructor}function t$($){return!!$&&(typeof $==="object"||typeof $==="function")}function W6($,...U){if(typeof $==="function")return $(...U);return $}function cU($){return new Proxy($,{get(U,Q,G){let K=Reflect.get(U,Q,G);if(Q!=="then"||typeof K!=="function")return K;return new Proxy(K,{apply(J,W,q){if(q.length!==2||q.some((X)=>!bZ(X)))return Reflect.apply(J,W,q);let j=!0;q[0].call(W,cU(new Proxy(U,{get:(X,B,Z)=>{if(j&&B==="then"){j=!1;return}return Reflect.get(X,B,Z)}})))}})}})}var zZ=/^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;function bZ($){return typeof $==="function"&&zZ.test($.toString())}function qW($){try{return decodeURIComponent($)}catch{return $}}var AZ="@orpc/client",OZ="1.15.0",YW=new Set(["bind","valueOf","toString","toJSON"]),M0={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 RZ($,U){return U??M0[$]?.status??500}function TZ($,U){return U||M0[$]?.message||$}var B0;class h1 extends Error{defined;code;status;data;static{let $=Symbol.for(`__${AZ}@${OZ}/error/ORPC_ERROR_CONSTRUCTORS__`);globalThis[$]??=new WeakSet,B0=globalThis[$],B0.add(h1)}constructor($,...U){let Q=JW(U);if(Q.status!==void 0&&!Z0(Q.status))throw Error("[ORPCError] Invalid error status code.");let G=TZ($,Q.message);super(G,Q);this.code=$,this.status=RZ($,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(B0.has(this)){let U=WW($);if(U&&B0.has(U))return!0}return super[Symbol.hasInstance]($)}}function jW($){return $ instanceof h1?$:new h1("INTERNAL_SERVER_ERROR",{message:"Internal server error",cause:$})}function Z0($){return $<200||$>=400}function lU($){if(!H0($))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"&&Z0($.status)&&"message"in $&&typeof $.message==="string"}function rU($,U={}){return new h1($.code,{...U,...$})}class q6 extends TypeError{}class XW extends TypeError{}class W1 extends Error{data;constructor($){super($?.message??"An error event was received",$);this.data=$?.data}}var SZ=/\r\n|\r(?!\n)|\n/,CZ=/(?:\r\n|\r(?!\n)|\n){2}/,gZ=/(?:\r\n|\r(?!\n)|\n){2}/g,EZ=13,yZ=10,uZ=32;function fZ($){let U={data:void 0,event:void 0,id:void 0,retry:void 0,comments:[]};for(let Q of $.split(SZ)){if(Q==="")continue;let G=Q.indexOf(":"),K=G===-1?"":Q.slice(Q.charCodeAt(G+1)===uZ?G+2:G+1);if(G===0){U.comments.push(K);continue}switch(G===-1?Q:Q.slice(0,G)){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 J=Number.parseInt(K,10);if(J>=0&&J.toString()===K)U.retry=J;break}}}return U}class HW{constructor($={}){this.options=$}pending=[];tail="";discardLeadingLF=!1;feed($){if($==="")return;if(this.discardLeadingLF){if(this.discardLeadingLF=!1,$.charCodeAt(0)===yZ){if($=$.slice(1),$==="")return}}let U=this.tail+$;if(!CZ.test(U)){this.pending.push($),this.tail=U.slice(-3);return}this.pending.push($);let Q=this.pending.length===1?$:this.pending.join(""),G=Q.length-U.length,K=[],J=0;for(let q of U.matchAll(gZ))K.push(Q.slice(J,G+q.index)),J=G+q.index+q[0].length;let W=Q.slice(J);if(this.pending.length=0,this.tail=W.slice(-3),W==="")this.discardLeadingLF=$.charCodeAt($.length-1)===EZ;else this.pending.push(W);for(let q of K){let j=fZ(q);if(this.options.onEvent)this.options.onEvent(j)}}end(){if(this.pending.length!==0)throw new XW("Event Iterator ended before complete")}}class nU extends TransformStream{constructor(){let $;super({start(U){$=new HW({onEvent:(Q)=>{U.enqueue(Q)}})},transform(U){$.feed(U)},flush(){$.end()}})}}var mZ=/\r\n|[\n\r]/,hZ=/\r\n|[\n\r]/g;function iU($){return mZ.test($)}function BW($){if(iU($))throw new q6("Event's id must not contain a carriage return or newline character")}function cZ($){if(iU($))throw new q6("Event's event must not contain a carriage return or newline character")}function MW($){if(!Number.isInteger($)||$<0)throw new q6("Event's retry must be a integer and >= 0")}function ZW($){if(iU($))throw new q6("Event's comment must not contain a carriage return or newline character")}function lZ($){if($===void 0)return"";return`data: ${$.replace(hZ,`
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
33
  data: `)}
34
- `}function rZ($){let U="";for(let Q of $??[])ZW(Q),U+=`: ${Q}
35
- `;return U}function Y6($){let U="";if(U+=rZ($.comments),$.event!==void 0)cZ($.event),U+=`event: ${$.event}
36
- `;if($.retry!==void 0)MW($.retry),U+=`retry: ${$.retry}
37
- `;if($.id!==void 0)BW($.id),U+=`id: ${$.id}
38
- `;return U+=lZ($.data),U+=`
39
- `,U}var VW=Symbol("ORPC_EVENT_SOURCE_META");function c1($,U){if(U.id===void 0&&U.retry===void 0&&!U.comments?.length)return $;if(U.id!==void 0)BW(U.id);if(U.retry!==void 0)MW(U.retry);if(U.comments!==void 0)for(let Q of U.comments)ZW(Q);return new Proxy($,{get(Q,G,K){if(G===VW)return U;return Reflect.get(Q,G,K)}})}function B4($){return t$($)?Reflect.get($,VW):void 0}function vW($,U="inline"){let Q=$.replace(/[^\x20-\x7E]/g,"_").replace(/"/g,"\\\""),G=encodeURIComponent($).replace(/['()*]/g,(K)=>`%${K.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(7C|60|5E)/g,(K,J)=>String.fromCharCode(Number.parseInt(J,16)));return`${U}; filename="${Q}"; filename*=utf-8''${G}`}function DW($){let U=$.match(/filename\*=(UTF-8'')?([^;]*)/i);if(U&&typeof U[2]==="string")return qW(U[2]);let Q=$.match(/filename="((?:\\"|[^"])*)"/i);if(Q&&typeof Q[1]==="string")return Q[1].replace(/\\"/g,'"')}function PW($,U){let Q={...$};for(let G in U)if(Array.isArray(U[G]))Q[G]=[...u1(Q[G]),...U[G]];else if(U[G]!==void 0)if(Array.isArray(Q[G]))Q[G]=[...Q[G],U[G]];else if(Q[G]!==void 0)Q[G]=[Q[G],U[G]];else Q[G]=U[G];return Q}function oU($,U){let Q=async(G)=>{let K=await U.error(G);if(K!==G){let J=B4(G);if(J&&t$(K))K=c1(K,J)}return K};return new P1(async()=>{let{done:G,value:K}=await(async()=>{try{return await $.next()}catch(W){throw await Q(W)}})(),J=await U.value(K,G);if(J!==K){let W=B4(K);if(W&&t$(J))J=c1(J,W)}return{done:G,value:J}},async()=>{try{await $.return?.()}catch(G){throw await Q(G)}})}function nZ($){return{...$,context:$.context??{}}}function I1($,U){return(async()=>{let Q;try{let G=await $;while(!0){let{done:K,value:J}=await G.next();if(K){let W=J;Q=[null,W,!0],U.onSuccess?.(W);break}U.onEvent(J)}}catch(G){if(Q=[G,void 0,!1],!U.onError&&!U.onFinish)throw G;U.onError?.(G)}finally{U.onFinish?.(Q)}})(),async()=>{await(await $)?.return?.()}}function l1($,U={}){let Q=U.path??[],K=new Proxy(async(...[J,W={}])=>{return await $.call(Q,J,nZ(W))},{get(J,W){if(typeof W!=="string"||YW.has(W))return Reflect.get(J,W);return l1($,{...U,path:[...Q,W]})}});return cU(K)}function iZ($,U={}){let G=$?.pipeThrough(new TextDecoderStream).pipeThrough(new nU)?.getReader(),K,J=!1;return new P1(async()=>{K??=X0("consume_event_iterator_stream");try{while(!0){if(G===void 0)return{done:!0,value:void 0};let{done:W,value:q}=await y1(K,()=>G.read());if(W){if(J)throw new mU("Stream was cancelled");return{done:!0,value:void 0}}switch(q.event){case"message":{let j=J6(q.data);if(t$(j))j=c1(j,q);return K?.addEvent("message"),{done:!1,value:j}}case"error":{let j=new W1({data:J6(q.data)});throw j=c1(j,q),K?.addEvent("error"),j}case"done":{let j=J6(q.data);if(t$(j))j=c1(j,q);return K?.addEvent("done"),{done:!0,value:j}}default:K?.addEvent("maybe_keepalive")}}}catch(W){if(!(W instanceof W1))D1(K,W,U);throw W}},async(W)=>{try{if(W!=="next")J=!0,K?.addEvent("cancelled");await y1(K,()=>G?.cancel())}catch(q){throw D1(K,q,U),q}finally{K?.end()}})}function oZ($,U={}){let Q=U.eventIteratorKeepAliveEnabled??!0,G=U.eventIteratorKeepAliveInterval??5000,K=U.eventIteratorKeepAliveComment??"",J=U.eventIteratorInitialCommentEnabled??!0,W=U.eventIteratorInitialComment??"",q=!1,j,X;return new ReadableStream({start(Z){if(X=X0("stream_event_iterator"),J)Z.enqueue(Y6({comments:[W]}))},async pull(Z){try{if(Q)j=setInterval(()=>{Z.enqueue(Y6({comments:[K]})),X?.addEvent("keepalive")},G);let V=await y1(X,()=>$.next());if(clearInterval(j),q)return;let N=B4(V.value);if(!V.done||V.value!==void 0||N!==void 0){let T=V.done?"done":"message";Z.enqueue(Y6({...N,event:T,data:m1(V.value)})),X?.addEvent(T)}if(V.done)Z.close(),X?.end()}catch(V){if(clearInterval(j),q)return;if(V instanceof W1)Z.enqueue(Y6({...B4(V),event:"error",data:m1(V.data)})),X?.addEvent("error"),Z.close();else D1(X,V),Z.error(V);X?.end()}},async cancel(){try{q=!0,clearInterval(j),X?.addEvent("cancelled"),await y1(X,()=>$.return?.())}catch(Z){throw D1(X,Z),Z}finally{X?.end()}}}).pipeThrough(new TextEncoderStream)}function dZ($,U={}){return f1({name:"parse_standard_body",signal:U.signal},async()=>{let Q=$.headers.get("content-disposition");if(typeof Q==="string"){let J=DW(Q)??"blob",W=await $.blob();return new File([W],J,{type:W.type})}let G=$.headers.get("content-type");if(!G||G.startsWith("application/json")){let J=await $.text();return J6(J)}if(G.startsWith("multipart/form-data"))return await $.formData();if(G.startsWith("application/x-www-form-urlencoded")){let J=await $.text();return new URLSearchParams(J)}if(G.startsWith("text/event-stream"))return iZ($.body,U);if(G.startsWith("text/plain"))return await $.text();let K=await $.blob();return new File([K],"blob",{type:K.type})})}function pZ($,U,Q={}){if($ instanceof ReadableStream)return $;let G=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",G??vW($ instanceof File?$.name:"blob")),$;if($ instanceof FormData)return $;if($ instanceof URLSearchParams)return $;if(J1($))return U.set("content-type","text/event-stream"),oZ($,Q);return U.set("content-type","application/json"),m1($)}function dU($,U={}){return $.forEach((Q,G)=>{if(Array.isArray(U[G]))U[G].push(Q);else if(U[G]!==void 0)U[G]=[U[G],Q];else U[G]=Q}),U}function tZ($,U=new Headers){for(let[Q,G]of Object.entries($))if(Array.isArray(G))for(let K of G)U.append(Q,K);else if(G!==void 0)U.append(Q,G);return U}function IW($,U={}){let Q=tZ($.headers),G=pZ($.body,Q,U);return new Request($.url,{signal:$.signal,method:$.method,headers:Q,body:G})}function NW($,U={}){return{body:j0(()=>dZ($,U)),status:$.status,get headers(){let Q=dU($.headers);return Object.defineProperty(this,"headers",{value:Q,writable:!0}),Q},set headers(Q){Object.defineProperty(this,"headers",{value:Q,writable:!0})}}}class V0{plugins;constructor($=[]){this.plugins=[...$].sort((U,Q)=>(U.order??0)-(Q.order??0))}init($){for(let U of this.plugins)U.init?.($)}}class _W{constructor($,U,Q={}){this.codec=$,this.sender=U,new V0(Q.plugins).init(Q),this.interceptors=u1(Q.interceptors),this.clientInterceptors=u1(Q.clientInterceptors)}interceptors;clientInterceptors;call($,U,Q){return f1({name:`${fU}.${$.join("/")}`,signal:Q.signal},(G)=>{if(G?.setAttribute("rpc.system",fU),G?.setAttribute("rpc.method",$.join(".")),J1(U))U=hU({name:"consume_event_iterator_input",signal:Q.signal},U);return G6(this.interceptors,{...Q,path:$,input:U},async({path:K,input:J,...W})=>{let q=Q6(),j,X=q?.trace.getActiveSpan()??G;if(X&&q)j=q?.trace.setSpan(q.context.active(),X);let B=await f1({name:"encode_request",context:j},()=>this.codec.encode(K,J,W)),Z=await G6(this.clientInterceptors,{...W,input:J,path:K,request:B},({input:N,path:T,request:f,...e})=>{return f1({name:"send_request",signal:e.signal,context:j},()=>this.sender.call(f,e,T,N))}),V=await f1({name:"decode_response",context:j},()=>this.codec.decode(Z,W,K,J));if(J1(V))return hU({name:"consume_event_iterator_output",signal:W.signal},V);return V})})}}var v$={BIGINT:0,DATE:1,NAN:2,UNDEFINED:3,URL:4,REGEXP:5,SET:6,MAP:7};class wW{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=[],G=[],K=[]){for(let J of this.customSerializers)if(J.condition($)){let W=this.serialize(J.serialize($),U,Q,G,K);return Q.push([J.type,...U]),W}if($ instanceof Blob)return G.push(U),K.push($),[$,Q,G,K];if(typeof $==="bigint")return Q.push([v$.BIGINT,...U]),[$.toString(),Q,G,K];if($ instanceof Date){if(Q.push([v$.DATE,...U]),Number.isNaN($.getTime()))return[null,Q,G,K];return[$.toISOString(),Q,G,K]}if(Number.isNaN($))return Q.push([v$.NAN,...U]),[null,Q,G,K];if($ instanceof URL)return Q.push([v$.URL,...U]),[$.toString(),Q,G,K];if($ instanceof RegExp)return Q.push([v$.REGEXP,...U]),[$.toString(),Q,G,K];if($ instanceof Set){let J=this.serialize(Array.from($),U,Q,G,K);return Q.push([v$.SET,...U]),J}if($ instanceof Map){let J=this.serialize(Array.from($.entries()),U,Q,G,K);return Q.push([v$.MAP,...U]),J}if(Array.isArray($))return[$.map((W,q)=>{if(W===void 0)return Q.push([v$.UNDEFINED,...U,q]),null;return this.serialize(W,[...U,q],Q,G,K)[0]}),Q,G,K];if(H0($)){let J={};for(let W in $){if(W==="toJSON"&&typeof $[W]==="function")continue;J[W]=this.serialize($[W],[...U,W],Q,G,K)[0]}return[J,Q,G,K]}return[$,Q,G,K]}deserialize($,U,Q,G){let K={data:$};if(Q&&G)Q.forEach((J,W)=>{let q=K,j="data";J.forEach((X)=>{if(q=q[j],j=X,!Object.hasOwn(q,j))throw Error(`Security error: accessing non-existent path during deserialization. Path segment: ${j}`)}),q[j]=G(W)});for(let J of U){let W=J[0],q=K,j="data";for(let X=1;X<J.length;X++)if(q=q[j],j=J[X],!Object.hasOwn(q,j))throw Error(`Security error: accessing non-existent path during deserialization. Path segment: ${j}`);for(let X of this.customSerializers)if(X.type===W){q[j]=X.deserialize(q[j]);break}switch(W){case v$.BIGINT:q[j]=BigInt(q[j]);break;case v$.DATE:q[j]=new Date(q[j]??"Invalid Date");break;case v$.NAN:q[j]=Number.NaN;break;case v$.UNDEFINED:q[j]=void 0;break;case v$.URL:q[j]=new URL(q[j]);break;case v$.REGEXP:{let[,X,B]=q[j].match(/^\/(.*)\/([a-z]*)$/);q[j]=new RegExp(X,B);break}case v$.SET:q[j]=new Set(q[j]);break;case v$.MAP:q[j]=new Map(q[j]);break}}return K.data}}function aZ($){return`/${$.map(encodeURIComponent).join("/")}`}function eZ($){if(typeof $.forEach==="function")return dU($);return $}function sZ($){return Object.entries(M0).find(([,U])=>U.status===$)?.[0]??"MALFORMED_ORPC_ERROR_RESPONSE"}class kW{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 G=eZ(await W6(this.headers,Q,$,U));if(Q.lastEventId!==void 0)G=PW(G,{"last-event-id":Q.lastEventId});let K=await W6(this.expectedMethod,Q,$,U),J=await W6(this.baseUrl,Q,$,U),W=new URL(J);W.pathname=`${W.pathname.replace(/\/$/,"")}${aZ($)}`;let q=this.serializer.serialize(U);if(K==="GET"&&!(q instanceof FormData)&&!J1(q)){let j=await W6(this.maxUrlLength,Q,$,U),X=new URL(W);if(X.searchParams.append("data",m1(q)),X.toString().length<=j)return{body:void 0,method:K,headers:G,url:X,signal:Q.signal}}return{url:W,method:K==="GET"?this.fallbackMethod:K,headers:G,body:q,signal:Q.signal}}async decode($){let U=!Z0($.status),Q=await(async()=>{let G=!1;try{let K=await $.body();return G=!0,this.serializer.deserialize(K)}catch(K){if(!G)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(lU(Q))throw rU(Q);throw new h1(sZ($.status),{status:$.status,data:{...$,body:Q}})}return Q}}class xW{constructor($){this.jsonSerializer=$}serialize($){if(J1($))return oU($,{value:async(U)=>this.#$(U,!1),error:async(U)=>{return new W1({data:this.#$(jW(U).toJSON(),!1),cause:U})}});return this.#$($,!0)}#$($,U){let[Q,G,K,J]=this.jsonSerializer.serialize($),W=G.length===0?void 0:G;if(!U||J.length===0)return{json:Q,meta:W};let q=new FormData;return q.set("data",m1({json:Q,meta:W,maps:K})),J.forEach((j,X)=>{q.set(X.toString(),j)}),q}deserialize($){if(J1($))return oU($,{value:async(U)=>this.#U(U),error:async(U)=>{if(!(U instanceof W1))return U;let Q=this.#U(U.data);if(lU(Q))return rU(Q,{cause:U});return new W1({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 pU extends _W{constructor($,U){let Q=new wW(U),G=new xW(Q),K=new kW(G,U);super(K,$,U)}}class FW extends V0{initRuntimeAdapter($){for(let U of this.plugins)U.initRuntimeAdapter?.($)}}class LW{fetch;toFetchRequestOptions;adapterInterceptors;constructor($){new FW($.plugins).initRuntimeAdapter($),this.fetch=$.fetch??globalThis.fetch.bind(globalThis),this.toFetchRequestOptions=$,this.adapterInterceptors=u1($.adapterInterceptors)}async call($,U,Q,G){let K=IW($,this.toFetchRequestOptions),J=await G6(this.adapterInterceptors,{...U,request:K,path:Q,input:G,init:{redirect:"manual"}},({request:q,path:j,input:X,init:B,...Z})=>this.fetch(q,B,Z,j,X));return NW(J,{signal:K.signal})}}class r1 extends pU{constructor($){let U=new LW($);super(U,$)}}import{chmodSync as tU,mkdirSync as zW,readFileSync as $V,writeFileSync as aU}from"node:fs";import{homedir as UV}from"node:os";import{join as bW}from"node:path";var eU=bW(UV(),".niva"),n1=bW(eU,"config.json");function j6(){try{let $=JSON.parse($V(n1,"utf-8"));return Y$($)?$:{}}catch{return{}}}function AW($,U){zW(eU,{recursive:!0});let G={...j6(),[$]:U};aU(n1,`${JSON.stringify(G,null,2)}
40
- `,{mode:384}),tU(n1,384)}function sU(){return j6()}function M4($){return $.replace(/\/+$/,"")}function KV($){let U=Y$($)?{...$}: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((G)=>typeof G==="string")}function $8(){let $=j6().auth;return Y$($)?$:{}}function OW(){let $={};for(let[U,Q]of Object.entries($8()))if(KV(Q))$[U]=Q;return $}function Z4($,U){zW(eU,{recursive:!0});let Q={...j6(),auth:{...$8(),[M4($)]:U}};aU(n1,`${JSON.stringify(Q,null,2)}
41
- `,{mode:384}),tU(n1,384)}function RW($){let U=$8(),Q=M4($);if(!(Q in U))return;delete U[Q];let G={...j6(),auth:U};aU(n1,`${JSON.stringify(G,null,2)}
42
- `,{mode:384}),tU(n1,384)}import{createHash as QV,randomBytes as SW}from"node:crypto";import{createServer as GV}from"node:http";var JV=600000,WV=120,qV=5;class Z$ extends Error{code;constructor($,U){super(U);this.code=$}}function YV($){let U=j$($),Q=r(U?.access_token),G=T1(U?.expires_in);if(U==null||Q==null||G==null)return null;let K=r(U.refresh_token),J=r(U.scope);return{access_token:Q,expires_in:G,...K!=null?{refresh_token:K}:{},...J!=null?{scope:J}:{}}}function CW($,U){let Q=j$($),G=r(Q?.error)??`http_${String(U)}`,K=r(Q?.error_description)??G;return new Z$(G,K)}function jV(){return SW(32).toString("base64url")}function XV($){return QV("sha256").update($).digest("base64url")}function gW($,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 U8($){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[G,...K]=Q;if(G==null)continue;try{return Bun.spawn([G,...K],{stdout:"ignore",stderr:"ignore"}).exited.then((W)=>{if(W!==0)TW($)}),!0}catch{continue}}return TW($),!1}function TW($){console.error(`Open this URL to continue: ${$}`)}async function K8($){let U=new URL("/.well-known/oauth-authorization-server",$.replace(/\/+$/,"")),Q=await fetch(U),G=await Q.json().catch(()=>({})),K=j$(G),J=r(K?.issuer),W=r(K?.authorization_endpoint),q=r(K?.token_endpoint);if(!Q.ok||K==null||J==null||W==null||q==null)throw new Z$("discovery_failed",`Could not read OAuth metadata from ${$}`);let j=r(K.device_authorization_endpoint);return{issuer:J,authorization_endpoint:W,token_endpoint:q,...j!=null?{device_authorization_endpoint:j}:{}}}async function Q8($,U){let Q=await fetch($,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(U).toString()}),G=await Q.json().catch(()=>({}));if(!Q.ok)throw CW(G,Q.status);let K=YV(G);if(K==null)throw new Z$("invalid_response","The token endpoint answered an unexpected body");return K}function HV($){return(U,Q)=>{let G=new URL(U.url??"/","http://127.0.0.1");if(G.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=G.searchParams.get("code"),J=G.searchParams.get("state"),W=G.searchParams.get("iss")??void 0,q=G.searchParams.get("error");if(q!=null)$({error:q});else if(K!=null&&J!=null)$({code:K,state:J,iss:W});else $({error:"invalid_request"})}}function BV($,U){return new Promise((Q,G)=>{let K=setTimeout(()=>{$.current=null,U(),G(new Z$("timeout","Timed out waiting for the browser callback"))},JV);$.current=(J)=>{if(clearTimeout(K),U(),"error"in J)G(new Z$(J.error,`Authorization failed: ${J.error}`));else Q(J)}})}function MV(){return new Promise(($,U)=>{let Q={current:null},G=GV(HV((J)=>Q.current?.(J))),K=async()=>BV(Q,()=>G.close());G.on("error",U),G.listen(0,"127.0.0.1",()=>{let J=G.address();if(J==null||typeof J==="string"){U(Error("Could not bind the loopback listener"));return}$({redirectUri:`http://127.0.0.1:${J.port}/callback`,waitForCode:K,close:()=>G.close()})})})}async function EW($,U){let Q=await MV(),G=jV(),K=SW(16).toString("base64url"),J=new URL($.authorization_endpoint);J.searchParams.set("response_type","code"),J.searchParams.set("client_id",U.clientId),J.searchParams.set("redirect_uri",Q.redirectUri),J.searchParams.set("scope",U.scopes.join(" ")),J.searchParams.set("state",K),J.searchParams.set("code_challenge",XV(G)),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("resource",U.resource);try{U8(J.href);let W=await Q.waitForCode();if(W.state!==K)throw new Z$("state_mismatch","The state returned by the server does not match");if(W.iss!=null&&W.iss!==$.issuer)throw new Z$("issuer_mismatch","The issuer returned by the server does not match");return await Q8($.token_endpoint,{grant_type:"authorization_code",code:W.code,redirect_uri:Q.redirectUri,client_id:U.clientId,code_verifier:G})}finally{Q.close()}}function ZV($){let U=j$($);if(U==null)return null;let Q=["device_code","user_code","verification_uri","verification_uri_complete"].map((K)=>r(U[K])),G=["expires_in","interval"].map((K)=>T1(U[K]));if(Q.some((K)=>K==null)||G.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:G[0],interval:G[1]}}async function yW($,U){let Q=$.device_authorization_endpoint;if(Q==null)throw new Z$("unsupported_grant_type","This server does not support the device flow");let G=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 G.json().catch(()=>({})),J=G.ok?ZV(K):null;if(J==null)throw G.ok?new Z$("invalid_response","The device authorization endpoint answered an unexpected body"):CW(K,G.status);return J}async function uW($,U,Q){let G=U.interval*1000,K=Date.now()+U.expires_in*1000;while(Date.now()<K){await Bun.sleep(G);try{return await Q8($,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:U.device_code,client_id:Q})}catch(J){if(J instanceof Z$){if(J.code==="authorization_pending")continue;if(J.code==="slow_down"){G+=qV*1000;continue}}throw J}}throw new Z$("expired_token","The device code expired before authorization completed")}function v0($,U=Math.floor(Date.now()/1000)){return $.expires_at-U<WV}async function D0($,U){let Q=await K8($),G=await Q8(Q.token_endpoint,{grant_type:"refresh_token",refresh_token:U.refresh_token,client_id:"niva-cli"});if(G.refresh_token==null)throw new Z$("invalid_grant","The server did not return a refresh token");return{access_token:G.access_token,refresh_token:G.refresh_token,expires_at:Math.floor(Date.now()/1000)+G.expires_in,org_id:U.org_id,scopes:G.scope!=null?G.scope.split(" ").filter((K)=>K!==""):U.scopes}}function G8($){try{let{hostname:U}=new URL($);return U.endsWith(".orb.local")||process.env.NIVA_INSECURE==="true"}catch{return!1}}class fW extends Error{constructor(){super("Your session has expired. Run 'niva login' to authenticate again.")}}function VV($){let U=$.fetchImpl??fetch,Q=async()=>{try{return await $.refresh()}catch(G){if(G instanceof Z$)throw new fW;throw G}};return async(G)=>{let K=$.getSession();if(v0(K))K=await Q();let J=new Request(G);J.headers.set("authorization",`Bearer ${K.access_token}`);let W=await U(J);if(W.status===401){K=await Q();let q=new Request(G);q.headers.set("authorization",`Bearer ${K.access_token}`),W=await U(q)}return W}}function J8($,U,Q){if(G8($))process.env.NODE_TLS_REJECT_UNAUTHORIZED="0";if(U.kind!=="oauth"){let J=new r1({url:new URL("/api/rpc",$).href,headers:()=>U.kind==="api-key"?{"X-API-Key":U.apiKey}:{}});return l1(J)}let G=U.session,K=new r1({url:new URL("/api/rpc",$).href,fetch:VV({getSession:()=>G,refresh:async()=>{return G=await D0(Q,G),Z4(Q,G),G}})});return l1(K)}var W8="niva-cli",vV=["*:read","*:write","offline_access"],DV=["*:read","offline_access"];function mW($,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 PV($,U){return(await J8($,{kind:"oauth",session:mW(U,"")},$).oauth.whoami()).organization?.id??""}function hW($,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(G)=>{let K=M4(U().url);if(!K.startsWith("https://"))C1("Server URL is not https: tokens travel unencrypted on this network.");let J=G.readOnly===!0?DV:vV,W=`${K}/api`,q=await K8(K),j={scopes:J,resource:W,clientId:W8},X,B=gW(process.env,process.platform);if(G.device===!0||!B){let V=await yW(q,j);if(z(`Open ${V.verification_uri} and enter the code: ${V.user_code}`),B)U8(V.verification_uri_complete);X=await uW(q.token_endpoint,V,W8)}else X=await EW(q,j);let Z=await PV(K,X);Z4(K,mW(X,Z)),E(`Logged in to ${K}`)}),$.command("logout").description("Revoke the saved session and remove it from the config file").action(async()=>{let G=M4(U().url),K=OW()[G];if(K==null){z(`No saved session for ${G}`);return}try{await fetch(new URL("/oauth/revoke",G),{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:K.refresh_token,client_id:W8}).toString()})}catch{C1("Could not reach the server to revoke the token; clearing the local session anyway.")}RW(G),E(`Logged out of ${G}`)}),$.command("whoami").description("Show the authenticated user, organization, scopes and token expiry").action(async()=>{let G=M4(U().url),K=Q();if(K.kind==="none"){A(`No credential configured for ${G}. Run 'niva login' first.`),process.exitCode=1;return}let W=await J8(G,K,G).oauth.whoami();P({url:G,user:W.user.email,organization:W.organization?.name,scopes:W.scopes,credential:W.credential,...K.kind==="oauth"?{expires_at:new Date(K.session.expires_at*1000).toISOString()}:{}})})}var U$=H1(M1(),1);var IV=/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i,cW=4;async function P0($,U){if(IV.test(U))return U;if(U.length<cW)A(`UUID prefix too short — provide at least ${cW} characters.`),process.exit(O.USAGE_ERROR);let Q=await _($.dashboard.activeCalls()),G=U.toLowerCase(),K=Q.filter((J)=>J.uuid.toLowerCase().startsWith(G));if(K.length===0)A(`No active call matching "${U}".`),process.exit(O.NOT_FOUND);if(K.length>1){A(`Ambiguous UUID prefix "${U}" — matches ${K.length} calls. Be more specific.`);for(let J of K)z(` ${J.uuid} ${J.callerId}`);process.exit(O.USAGE_ERROR)}return K[0].uuid}function rW($,U){let Q=$.command("calls").description("Manage calls");Q.command("list").description("List active calls").action(async()=>{let{format:G,fields:K}=w($.opts()),J=await _(U().dashboard.activeCalls());if(G==="json"){let W=K?J.map((q)=>g(q,K)):J;P(W);return}if(J.length===0){z("No active calls.");return}u(["UUID","Caller","Plan","Duration"],J.map((W)=>({UUID:W.uuid,Caller:W.callerId,Plan:W.planName??"—",Duration:W.startedAt?`${Math.round((Date.now()-new Date(W.startedAt).getTime())/1000)}s`:"—"})))}),Q.command("show <call_record_id>").description("Show call details from CDR (rich detail view)").action(async(G)=>{let{format:K,fields:J}=w($.opts()),W=await _(U().callRecords.getById({call_record_id:b("call_records",G)}));if(K==="json"){let q=J&&W!=null?g(W,J):W;P(q);return}if(W==null){z("Call record not found.");return}s([{title:"Call Record",rows:_V(W)}])}),Q.command("hangup <call>").description("Hang up an active call by TypeID (call_...), full channel UUID, or UUID prefix").action(async(G)=>{let{format:K}=w($.opts()),J=U(),W=G,q;if(G.startsWith("call_"))q=await _(J.calls.hangupCall({call_id:b("call_records",G)}));else W=await P0(J,G),q=await _(J.calls.hangupActiveCall({uuid:W}));if(K==="json"){P(q);return}E(`Call ${W} terminated.`)}),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(G)=>{let{format:K,fields:J}=w($.opts()),W=await _(U().callRecords.list({page:Number(G.page),limit:Number(G.limit),search:G.caller}));if(K==="json"){let q=J?W.items.map((j)=>g(j,J)):W;P(q);return}u(["ID","Caller","Callee","Duration","Disposition","Date"],W.items.map((q)=>({ID:q.id,Caller:q.caller_id??"—",Callee:q.callee_id??"—",Duration:A$(q.duration_ms),Disposition:q.hangup_disposition??"—",Date:new Date(q.started_at).toLocaleString()}))),X$(W)}),Q.command("follow <uuid>").description("Follow live transcription of an active call").action(async(G)=>{let{format:K}=w($.opts()),J=U(),W=await P0(J,G),q=new AbortController;process.on("SIGINT",()=>{q.abort()});let j=!1,X=!1;function B(V){Z();let N=nW(V);process.stdout.write(U$.default.dim(N)),X=!0}function Z(){if(!X)return;process.stdout.clearLine(0),process.stdout.cursorTo(0),X=!1}await new Promise((V,N)=>{I1(J.dashboard.watchLiveTranscription({uuid:W},{signal:q.signal}),{onEvent:(T)=>{if(j=!0,K==="json"){P(T);return}switch(T.type){case"starting":z("Connecting...");break;case"started":z("Transcription started.");break;case"ended":Z(),z("Transcription ended."),V();break;case"error":console.error(U$.default.red(`Error: ${T.message}`));break;case"history":for(let f of T.segments)lW(f);break;case"segment":if(T.segment.isFinal)Z(),lW(T.segment);else B(T.segment);break}},onError:(T)=>{if(T instanceof DOMException&&T.name==="AbortError"){Z(),V();return}N(T)},onSuccess:()=>{if(!j)z("Live transcription not available for this call.");V()}})}).catch((V)=>{Z(),X4(V)})}),Q.command("transfer <uuid> <destination>").description("Transfer an active call").action(()=>n$()),Q.command("spy <uuid>").description("Spy on an active call").action(()=>n$()),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(G)=>{let{format:K,fields:J}=w($.opts()),W=await _(U().callRecords.list({page:Number(G.page),limit:Number(G.limit),date_from:G.from,date_to:G.to,visual_plan_id:b("visual_plans",G.plan),channel_id:b("channels",G.phone),status:G.status,caller_search:G.caller,min_duration:G.minDuration!=null?Number(G.minDuration):void 0,max_duration:G.maxDuration!=null?Number(G.maxDuration):void 0,has_recording:G.hasRecording,has_transcription:G.hasTranscription}));if(K==="json"){if(J)P(W.items.map((q)=>g(q,J)));else P(W);return}if(W.items.length===0){z("No call records found.");return}u(["ID","Caller","Direction","Duration","Status","Sentiment","Plan","Date"],W.items.map((q)=>{let j=q.sentiment_score!=null?Number(q.sentiment_score):null;return{ID:q.id,Caller:q.caller_id??"—",Direction:q.direction??"—",Duration:A$(q.duration_ms),Status:AU(q.hangup_disposition),Sentiment:q.sentiment_label!=null?OU(q.sentiment_label,j):"—",Plan:q.visual_plan_name??"—",Date:p$(q.started_at)}})),X$(W)}),Q.command("trace <call_record_id>").description("Show node-by-node execution trace for a call").action(async(G)=>{let{format:K,fields:J}=w($.opts()),W=await _(U().callRecords.getTrace({call_record_id:b("call_records",G)}));if(K==="json"){let V=J&&W!=null?g(W,J):W;P(V);return}if(W==null){z("Call trace not found.");return}let q=W.callRecord;if(console.log(`${U$.default.bold("Call Trace")} — ${G} (${A$(q.duration_ms)}, ${q.hangup_disposition??"unknown"})`),q.visual_plan_name!=null)console.log(`Plan: ${q.visual_plan_name}`);console.log("");let j=W.events;if(j.length===0){z(" No events recorded (0 nodes visited).");return}let X=j.map((V,N)=>{let T=V.duration_ms!=null?`${(V.duration_ms/1000).toFixed(1)}s`:"—",f=`${U$.default.cyan(V.node_type)}`;if(V.node_label!=null){let k$=U$.default.bold(`"${V.node_label}"`);f+=` ${k$}`}if(f+=U$.default.dim(` (${T})`),V.digit!=null)f+=` → digit: ${U$.default.yellow(V.digit)}`;let e=[];if(V.handle_used!=null)e.push(U$.default.dim(`└─→ ${V.handle_used}`));if(Y$(V.data)){let k$=Object.entries(V.data).filter(([,j4])=>j4!=null&&typeof j4!=="object").map(([j4,C$])=>`${j4}: ${String(C$)}`);if(k$.length>0)e.push(U$.default.dim(`└─ ${k$.join(", ")}`))}return{label:f,children:e.length>0?e:void 0}});RU(X),console.log("");let B=j.at(-1),Z=B.node_label??B.node_type;z(` ${j.length} nodes visited · Last: ${B.node_type} "${Z}" · Hangup: ${q.hangup_cause??"—"}`)}),Q.command("transcript <call_record_id>").description("Show call transcription with speech analytics").action(async(G)=>{let{format:K,fields:J}=w($.opts()),W=await _(U().ai.getTranscription({call_record_id:b("call_records",G)}));if(K==="json"){let X=J&&W!=null?g(W,J):W;P(X);return}console.log(`${U$.default.bold("Transcript")} — ${G}`),console.log("");let q=kV(W?.segments);if(q.length===0||W?.status==="disabled")z(" No transcript available.");else SJ(q);let j=W!=null?xV(W):[];if(j.length>0)console.log(""),s([{title:"Speech Analytics",rows:j}])}),Q.command("purge-voice <call_record_id>").description("Permanently erase a call's voice content (recording, transcription, embeddings)").action(async(G)=>{let{format:K}=w($.opts()),J=$.opts().yes===!0;if(K!=="json")console.log(`${U$.default.bold("Erase voice content")} — ${G}`),z(" Deletes: recording file, transcription and its semantic-search embeddings."),z(" Keeps: the call record (CDR), its event timeline and existing analyses."),z(" This is irreversible."),console.log("");await v1("Erase the voice content of this call?",{yes:J});let W=await _(U().callRecords.purgeVoiceContent({call_record_id:b("call_records",G)}));if(K==="json"){P(W);return}E("Voice content erased"),s([{title:"Deleted",rows:[{label:"Recording",value:String(W.deleted.recording)},{label:"Transcriptions",value:String(W.deleted.transcriptions)},{label:"Embeddings",value:String(W.deleted.embeddings)},{label:"Analyses detached",value:String(W.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(G,K)=>{let{format:J,fields:W}=w($.opts()),q=await _(U().ai.searchTranscriptions({query:G,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(J==="json"){let X=W?q.map((B)=>g(B,W)):q;P(X);return}let j=q;if(console.log(`${U$.default.bold("Semantic Search")}: "${G}"`),console.log(`${j.length} result${j.length!==1?"s":""} (threshold: ${K.threshold})`),j.length===0){z(`
43
- No results found.`);return}console.log("");for(let X of j){let B=`${Math.round(X.similarity*100)}%`,Z=X.call_record_id,V=p$(X.started_at),N=A$(X.duration_ms);console.log(` ${U$.default.bold(B.padStart(4))} │ ${Z} │ ${V} │ ${X.caller_id??"—"} │ ${X.direction} │ ${N} │ ${X.visual_plan_name??"—"}`);let T=String(X.chunk_text).replaceAll(/\s+/g," ").trim(),f=120,e=T.length>f?`${T.slice(0,f)}...`:T;console.log(U$.default.dim(` │ "${e}"`)),console.log("")}}),Q.command("inspect <uuid>").description("Inspect an active call: current node, variables, execution path").action(async(G)=>{let{format:K,fields:J}=w($.opts()),W=U(),q=await P0(W,G),j=await _(W.dashboard.activeCallTrace({uuid:q}));if(K==="json"){let Z=J?g(j,J):j;P(Z);return}s([{title:"Active Call",rows:[{label:"UUID",value:q},{label:"Current",value:j.currentNodeId??"—"}]}]);let X=j.variables;if(Object.keys(X).length>0){let Z=Object.entries(X).map(([V,N])=>({label:V,value:N}));s([{title:`Variables (${Object.keys(X).length})`,rows:Z}])}let B=j.events;if(B.length>0){console.log(""),console.log(U$.default.bold("Execution Path:"));let Z=B.map((V)=>{let N=V.duration_ms!=null?`${(V.duration_ms/1000).toFixed(1)}s`:"waiting...",T=V.node_id===j.currentNodeId,e=`${T?U$.default.yellow("●"):U$.default.green("✓")} ${U$.default.cyan(V.node_type)}`;if(V.node_label!=null){let k$=U$.default.bold(`"${V.node_label}"`);e+=` ${k$}`}if(e+=U$.default.dim(` (${N})`),T)e+=U$.default.yellow(" ← current");return{label:e}});RU(Z)}})}function NV($){if($.has_recording)return"yes";if($.was_recorded)return"processing";return"no"}function I0($){return $!=null&&$!==""}function _V($){let U=$.answered_at!=null?new Date($.answered_at):null,Q=new Date($.started_at),G=U!=null?`${Math.round((U.getTime()-Q.getTime())/1000)}s ring`:null,K=I0(G)?` (${G})`:"",J=$.visual_plan_version_number!=null?` v${$.visual_plan_version_number}`:"",W=I0($.visual_plan_name)?`${$.visual_plan_name}${J}`:null,q=I0($.sip_hangup_disposition)?` (${$.sip_hangup_disposition})`:"",j=$.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:W},{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:A$($.duration_ms)},{label:"Status",value:AU($.hangup_disposition)},{label:"Recording",value:NV($)},{label:"Transcribed",value:j},{label:"Machine type",value:$.answer_recognition_results?.machine_type},{label:"Hangup",value:I0($.hangup_cause)?`${$.hangup_cause}${q}`:null}]}function wV($){let U=T1($.confidence),Q=U!=null?` (${U.toFixed(2)})`:"";return`${r($.topic)??r($.label)??"?"}${Q}`}function kV($){let U=[];for(let Q of g$($)){let G=r(Q.speaker),K=r(Q.text),J=T1(Q.initial_time);if(G!=null&&K!=null&&J!=null)U.push({speaker:G,text:K,initial_time:J})}return U}function xV($){let U=[],Q=j$($.sentiment_overall);if(Q!=null)U.push({label:"Sentiment",value:OU(r(Q.label),T1(Q.score))});if($.intent!=null)U.push({label:"Intent",value:$.intent});if($.summary!=null)U.push({label:"Summary",value:$.summary});let G=Array.isArray($.key_points)?$.key_points.filter((J)=>typeof J==="string"):[];if(G.length>0)U.push({label:"Key Points",value:G.map((J)=>`• ${J}`).join(`
44
- │ `)});let K=g$($.topics);if(K.length>0)U.push({label:"Topics",value:K.map((J)=>wV(J)).join(" · ")});return U}function nW($){let U=Math.floor($.start/60),Q=Math.floor($.start%60),G=`${String(U).padStart(2,"0")}:${String(Q).padStart(2,"0")}`,K=$.channel===0?U$.default.blue("Caller"):U$.default.green("System");return`${U$.default.dim(`[${G}]`)} ${K} ${U$.default.dim(">")} ${$.text}`}function lW($){console.log(nW($))}import{readFile as FV}from"node:fs/promises";async function iW($){let U=$==="-"?await E1():await FV($,"utf-8"),Q=JSON.parse(U);if(!Y$(Q))A(`Invalid campaign file "${$}": expected a JSON object`),process.exit(O.USAGE_ERROR);return Q}function LV($){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 zV($){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 oW($){return{...LV($),...zV($)}}function V4($){if($==null)return"inherit (org default)";if(typeof $==="boolean")return $?"yes":"no";return String($)}function dW($){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 pW($,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(G)=>{let{format:K,fields:J}=w($.opts()),W=await _(U().dialerCampaigns.list({page:Number(G.page),limit:Number(G.limit),search:G.search,status:i$(G.status)}));if(K==="json"){let q=J?W.items.map((j)=>g(j,J)):W;P(q);return}u(["ID","Name","Status","Contacts","Answered","Created"],W.items.map((q)=>({ID:q.id,Name:q.name,Status:q.status,Contacts:q.total_contacts,Answered:q.answered_count,Created:p$(q.created_at)}))),X$(W)}),Q.command("show <campaign_id>").description("Show campaign details").action(async(G)=>{let{format:K,fields:J}=w($.opts()),W=await _(U().dialerCampaigns.get({campaign_id:b("dialer_campaigns",G)}));if(W==null){if(K==="json")P(null),process.exit(O.NOT_FOUND);A("Campaign not found"),process.exit(O.NOT_FOUND)}if(K==="json"){let q=J?g(W,J):W;P(q);return}s([{title:"Campaign",rows:[{label:"ID",value:W.id},{label:"Name",value:W.name},{label:"Description",value:W.description},{label:"Status",value:W.status},{label:"Plan",value:W.plan_id},{label:"Channel",value:W.channel_type},{label:"Priority",value:W.priority},{label:"Created",value:new Date(W.created_at).toLocaleString()},{label:"Updated",value:new Date(W.updated_at).toLocaleString()}]},{title:"Dialing",rows:[{label:"Caller ID",value:W.caller_id},{label:"Trunk",value:W.trunk_override},{label:"Max Concurrent",value:W.max_concurrent_calls},{label:"Ring Timeout",value:`${W.ring_timeout_s}s`},{label:"Max Duration",value:`${W.max_call_duration_s}s`}]},{title:"Retry",rows:[{label:"Max Attempts",value:W.retry_max_attempts},{label:"Interval",value:`${W.retry_interval_min}min`},{label:"On Busy",value:W.retry_on_busy?"yes":"no"},{label:"On No Answer",value:W.retry_on_no_answer?"yes":"no"},{label:"On Failed",value:W.retry_on_failed?"yes":"no"}]},{title:"Answering machine",rows:[{label:"Detection",value:W.amd_enabled?"on":"off"},{label:"Retry On Machine",value:W.retry_on_machine?"yes":"no"},{label:"Block After All",value:V4(W.amd_block_after_all_machine)},{label:"Block Min Attempts",value:V4(W.amd_block_min_attempts)},{label:"On Voicemail",value:V4(W.amd_action_voicemail)},{label:"On Announcement",value:V4(W.amd_action_announcement)},{label:"On IVR",value:V4(W.amd_action_ivr)},{label:"On Screening",value:V4(W.amd_action_screening)}]},{title:"Window & schedule",rows:[{label:"Window Start",value:W.call_window_start},{label:"Window End",value:W.call_window_end},{label:"Window Days",value:W.call_window_days},{label:"Recurring",value:W.recurring?"yes":"no"},{label:"Recurrence",value:W.recurrence_mode},{label:"Auto Start",value:W.auto_start_at?new Date(W.auto_start_at).toLocaleString():null},{label:"Auto Stop",value:W.auto_stop_at?new Date(W.auto_stop_at).toLocaleString():null}]}])}),Q.command("stats <campaign_id>").description("Show campaign statistics").action(async(G)=>{let{format:K,fields:J}=w($.opts()),W=await _(U().dialerCampaigns.stats({campaign_id:b("dialer_campaigns",G)}));if(K==="json"){let X=J?g(W,J):W;P(X);return}let q=W.capacity_context;s([{title:"Stats",rows:[{label:"Status",value:W.status},{label:"Total",value:W.total_contacts},{label:"Pending",value:W.pending_count},{label:"Calling",value:W.calling_count},{label:"Answered",value:W.answered_count},{label:"Machine",value:W.machine_count},{label:"Busy",value:W.busy_count},{label:"No Answer",value:W.no_answer_count},{label:"Failed",value:W.failed_count},{label:"DNC Skipped",value:W.dnc_skipped_count},{label:"Cancelled",value:W.cancelled_count}]},{title:"Capacity",rows:[{label:"Waiting",value:W.waiting_capacity?"yes":"no"},{label:"Used",value:q!=null?q.used:null},{label:"Capacity",value:q!=null?q.capacity:null},{label:"Reserve",value:q!=null?q.reserve:null},{label:"Module Disabled",value:W.module_disabled?"yes":"no"}]}]);let j=Number(W.total_contacts);if(j>0)console.log(""),r$("Answered",Number(W.answered_count),j),r$("Busy",Number(W.busy_count),j),r$("No Answer",Number(W.no_answer_count),j),r$("Failed",Number(W.failed_count),j)}),Q.command("summary").description("Show running-campaign summary").action(async()=>{let{format:G,fields:K}=w($.opts()),J=await _(U().dialerCampaigns.summary());if(G==="json"){let W=K?g(J,K):J;P(W);return}s([{title:"Summary",rows:[{label:"Running",value:J.running},{label:"Calling",value:J.calling},{label:"Campaign",value:J.campaign!=null?`${J.campaign.name} (${J.campaign.id})`:null}]}])}),dW(Q.command("create <name>").description("Create a dialer campaign").requiredOption("--plan <plan_id>","Visual plan ID to dial")).action(async(G,K)=>{let{format:J}=w($.opts()),W=K.file!=null?await iW(K.file):{},q=oW(K),j=await _(U().dialerCampaigns.create({...W,...q,name:G,plan_id:b("visual_plans",K.plan)}));if(J==="json"){P(j);return}E(`Campaign created: ${j.id} — ${j.name}`)}),dW(Q.command("edit <campaign_id>").description("Update a dialer campaign").option("--name <name>","Campaign name")).action(async(G,K)=>{let{format:J}=w($.opts()),W=K.file!=null?await iW(K.file):{},q=oW(K),j=await _(U().dialerCampaigns.update({campaign_id:b("dialer_campaigns",G),...W,...q}));if(J==="json"){P(j);return}E(`Campaign updated: ${j.name}`)}),Q.command("delete <campaign_id>").description("Delete a dialer campaign").action(async(G)=>{let{format:K}=w($.opts());if(await _(U().dialerCampaigns.delete({campaign_id:b("dialer_campaigns",G)})),K==="json"){P({success:!0});return}E("Campaign deleted")});for(let G of["start","pause","resume","stop"])Q.command(`${G} <campaign_id>`).description(`${G[0].toUpperCase()}${G.slice(1)} a campaign`).action(async(K)=>{let{format:J}=w($.opts()),W=await _(U().dialerCampaigns.control({campaign_id:b("dialer_campaigns",K),action:G}));if(J==="json"){P(W);return}E(`Campaign "${W.name}" → ${W.status}`)});Q.command("watch <campaign_id>").description("Watch live campaign stats (streams until Ctrl-C)").action(async(G)=>{let{format:K}=w($.opts()),J=U(),W=new AbortController;process.on("SIGINT",()=>{W.abort()}),await new Promise((q,j)=>{I1(J.dialerCampaigns.liveStats({campaign_id:b("dialer_campaigns",G)},{signal:W.signal}),{onEvent:(X)=>{if(K==="json"){console.log(JSON.stringify(X));return}let B=new Date().toLocaleTimeString(),Z=X.counters,V=X.waiting_capacity?"yes":"no";console.log(`${B} status=${X.status} calling=${X.calling} pending_retry=${X.pending_retry} answered=${Z.answered_count} busy=${Z.busy_count} failed=${Z.failed_count} waiting_capacity=${V}`)},onError:(X)=>{if(X instanceof DOMException&&X.name==="AbortError"){q();return}j(X)},onSuccess:()=>{q()}})}).catch(X4)}),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(G,K)=>{let{format:J,fields:W}=w($.opts()),q=await _(U().dialerAttempts.list({campaign_id:b("dialer_campaigns",G),status:i$(K.status),contact_id:b("dialer_contacts",K.contact),page:Number(K.page),limit:Number(K.limit)}));if(J==="json"){let j=W?q.items.map((X)=>g(X,W)):q;P(j);return}u(["ID","#","Phone","Name","Status","Machine","Cause","Started","Duration","Record"],q.items.map((j)=>({ID:j.id,"#":j.attempt_number,Phone:j.phone_number??"—",Name:j.contact_name??"—",Status:j.status??"—",Machine:U0(j.machine_type),Cause:j.hangup_cause??"—",Started:j.started_at?p$(j.started_at):"—",Duration:j.duration_s!=null?A$(j.duration_s*1000):"—",Record:j.call_record_id??"—"}))),X$(q)})}import{readFile as SV}from"node:fs/promises";var I$=H1(M1(),1);async function N0($){z(`Connecting to ${$}`);let U=G8($)?{tls:{rejectUnauthorized:!1}}:void 0,Q=new WebSocket($,U),G=!1;throw Q.onopen=()=>{G=!0},Q.onmessage=(K)=>{let J=JSON.parse(typeof K.data==="string"?K.data:String(K.data)),W=j$(J)??{},q=r(W.type)??"";switch(q){case"connected":console.log(I$.default.green(` Connected. Type a message and press Enter. Ctrl+C or /quit to exit.
45
- `)),TV(Q);break;case"message":{let j=j$(W.message)??{};for(let X of RV(j))console.log(X);break}case"typing":{if(W.active===!0)process.stdout.write(I$.default.dim(" bot is typing...\r"));else process.stdout.write(" \r");break}case"state":{if(W.status==="ended")console.log(I$.default.dim(`
46
- Session ended.`)),process.exit(0);break}case"error":console.log(I$.default.red(` error: [${String(W.code)}] ${String(W.message)}`));break;case"pong":break;case"replay":{let j=Array.isArray(W.messages)?W.messages:[];if(j.length>0)z(` Replayed ${j.length} missed message(s)`);break}default:console.log(I$.default.dim(` [${q}] ${JSON.stringify(W)}`))}},Q.onclose=(K)=>{if(G)z(`
47
- Disconnected (code=${K.code})`);else A("Failed to connect");process.exit(G?0:1)},Q.onerror=()=>{A("WebSocket error"),process.exit(1)},await new Promise(()=>{}),Error("unreachable")}function v4($,U){return $.replace(/^http/,"ws")+U}var i1=I$.default.cyan(" bot");function bV($,U){let Q=[`${i1} ${$}`];for(let G of g$(U.buttons)){let K=I$.default.dim(`[${String(G.id)}]`);Q.push(` ${K} ${String(G.label)}`)}return Q}function AV($,U){let Q=[`${i1} ${$}`];for(let G of g$(U.sections)){Q.push(` ${I$.default.bold(String(G.title))}`);for(let K of g$(G.items)){let J=I$.default.dim(`[${String(K.id)}]`);Q.push(` ${J} ${String(K.title)}`)}}return Q}function OV($){return g$($.cards).map((U)=>{let Q=r(U.description),G=Q!=null?` — ${Q}`:"";return`${i1} ${I$.default.bold(String(U.title))}${G}`})}function RV($){let U=r($.type)??"",Q=r($.text)??"";switch(U){case"text":return[`${i1} ${Q}`];case"buttons":return bV(Q,$);case"list":return AV(Q,$);case"media":{let G=I$.default.dim(`[${String($.mediaType)}]`),K=typeof $.caption==="string"?` — ${$.caption}`:"";return[`${i1} ${G} ${String($.url)}${K}`]}case"location":{let G=typeof $.label==="string"?` (${$.label})`:"";return[`${i1} ${I$.default.dim("[location]")} ${String($.lat)},${String($.lng)}${G}`]}case"carousel":return OV($);default:{let G=I$.default.dim(`[${U}]`);return[`${i1} ${G} ${JSON.stringify($)}`]}}}function TV($){let U=process.stdin;U.setEncoding("utf-8"),U.resume();let Q="";U.on("data",(G)=>{Q+=G;let K=Q.split(`
48
- `);Q=K.pop();for(let J of K){let W=J.trim();if(W==="")continue;if(W==="/ping"){$.send(JSON.stringify({type:"ping"})),z(" → ping");continue}if(W==="/quit"||W==="/exit"){$.close();return}console.log(`${I$.default.blue(" you")} ${W}`),$.send(JSON.stringify({type:"message",message:{type:"text",text:W}}))}}),process.once("SIGINT",()=>{z(`
49
- Closing...`),$.close()})}function tW($,U,Q){let G=$.command("chat").description("Test chat — interactive session against a visual plan (draft or published)");G.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,J)=>{let W=S1($.opts()),q=Q(),j;if(J.editorState!=null){let B=await SV(J.editorState,"utf-8");j=JSON.parse(B)}if(W!=="json")z("Creating test chat session...");let X=await _(U().testChat.createSession({planId:b("visual_plans",K),editor_state:j}));if(W==="json"){P({...X,ws_url:v4(q.url,X.wsUrl)});return}E(`Session created: ${X.sessionId}`),await N0(v4(q.url,X.wsUrl))}),G.command("stop <sessionId>").description("Stop an active test chat session").action(async(K)=>{let J=S1($.opts());if(await _(U().testChat.stop({sessionId:K})),J==="json"){P({session_id:K,stopped:!0});return}E(`Session ${K} stopped.`)})}function aW($){let U=$.command("config").description("Manage CLI configuration");U.command("set <key> <value>").description("Set a config value (url, api-key)").action((Q,G)=>{AW(Q==="api-key"?"apiKey":Q,G),E(`Set ${Q} = ${G}`)}),U.command("get <key>").description("Get a config value (url, api-key)").action((Q)=>{let G=Q==="api-key"?"apiKey":Q,J=sU()[G];if(J==null){z(`(${Q} not set)`);return}console.log(typeof J==="string"?J:JSON.stringify(J))}),U.command("show").description("Show current configuration").action(()=>{let Q=sU();P(Q)})}var E$=H1(M1(),1);function X6($){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 CV($,U){if($>U)return"↑";if($<U)return"↓";return"→"}function gV($){let U=$.avg_score!=null?Number($.avg_score):null,Q=$.previous_avg_score!=null?Number($.previous_avg_score):null,G=U!=null&&U>0?"+":"",K=U!=null?`${G}${U.toFixed(2)}`:"—",J="";if(Q!=null&&U!=null){let W=CV(U,Q);J=` (prev: ${Q>0?"+":""}${Q.toFixed(2)} ${W})`}return` Avg Score: ${K}${J}`}function eW($,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(G)=>{let{format:K,fields:J}=w($.opts()),{date_from:W,date_to:q}=V1(G),j=await _(U().dashboard.metrics({date_from:W,date_to:q}));if(K==="json"){let X=J?g(j,J):j;P(X);return}if(console.log(`Period: ${W} → ${q}`),console.log(`Total calls: ${j.current.total_calls}`),console.log(`Answered: ${j.current.answered}`),console.log(`Missed: ${j.current.missed}`),j.current.avg_duration_ms!=null)console.log(`Avg duration: ${A$(j.current.avg_duration_ms)}`)}),X6(Q.command("sentiment").description("Show sentiment distribution for calls")).action(async(G)=>{let{format:K,fields:J}=w($.opts()),{date_from:W,date_to:q}=V1(G),j=await _(U().dashboard.speechSentiment({date_from:W,date_to:q,visual_plan_id:b("visual_plans",G.plan),channel_id:b("channels",G.phone)}));if(K==="json"){let Z=J?g(j,J):j;P(Z);return}if(console.log(E$.default.bold("Sentiment Overview")),console.log(`Analyzed: ${j.analyzed_count} calls`),!j.has_enough_data){z(`
50
- Not enough data (need ${j.minimum_required}, have ${j.analyzed_count})`);return}console.log("");let X=j.distribution,B=Math.max(X.positive,X.neutral,X.negative,X.mixed);r$(E$.default.green("positive"),X.positive,B),r$(E$.default.yellow("neutral"),X.neutral,B),r$(E$.default.red("negative"),X.negative,B),r$(E$.default.blue("mixed"),X.mixed,B),console.log(""),console.log(gV(j))}),X6(Q.command("topics").description("Show top discussed topics from call transcriptions")).option("--limit <n>","Max topics to show","15").action(async(G)=>{let{format:K,fields:J}=w($.opts()),{date_from:W,date_to:q}=V1(G),j=await _(U().dashboard.speechTopics({date_from:W,date_to:q,limit:Number(G.limit),visual_plan_id:b("visual_plans",G.plan),channel_id:b("channels",G.phone)}));if(K==="json"){let B=J?g(j,J):j;P(B);return}if(console.log(`${E$.default.bold("Top Topics")} (${j.analyzed_count} analyzed)`),!j.has_enough_data||j.topics.length===0){z(`
51
- Not enough data.`);return}console.log("");let X=Math.max(...j.topics.map((B)=>B.call_count));for(let B of j.topics){let Z=j.analyzed_count>0?Math.round(B.call_count/j.analyzed_count*100):0,V=Z1(B.call_count,X);console.log(` ${B.label.padEnd(16)} ${V} ${B.call_count} calls (${Z}%) confidence: ${B.avg_confidence.toFixed(2)}`)}}),X6(Q.command("intents").description("Show detected intents from call transcriptions")).option("--limit <n>","Max intents to show","10").action(async(G)=>{let{format:K,fields:J}=w($.opts()),{date_from:W,date_to:q}=V1(G),j=await _(U().dashboard.speechIntents({date_from:W,date_to:q,limit:Number(G.limit),visual_plan_id:b("visual_plans",G.plan),channel_id:b("channels",G.phone)}));if(K==="json"){let B=J?g(j,J):j;P(B);return}if(console.log(`${E$.default.bold("Detected Intents")} (${j.analyzed_count} analyzed)`),!j.has_enough_data||j.intents.length===0){z(`
52
- Not enough data.`);return}console.log("");let X=Math.max(...j.intents.map((B)=>B.call_count));for(let B of j.intents)r$(B.label,B.call_count,X)}),X6(Q.command("trend").description("Show sentiment trend over time")).option("--granularity <g>","Granularity: hour or day","day").action(async(G)=>{let{format:K}=w($.opts()),{date_from:J,date_to:W}=V1(G,7),q=await _(U().dashboard.speechSentimentTrend({date_from:J,date_to:W,granularity:i$(G.granularity),visual_plan_id:b("visual_plans",G.plan),channel_id:b("channels",G.phone)}));if(K==="json"){P(q);return}if(console.log(E$.default.bold("Sentiment Trend")),q.length===0){z(`
53
- No data available.`);return}console.log(""),u(["Date","Analyzed","Positive","Neutral","Negative","Avg Score"],q.map((j)=>{let X=new Date(j.bucket),B=`${String(X.getDate()).padStart(2,"0")}/${String(X.getMonth()+1).padStart(2,"0")}`,Z=j.avg_score!=null&&j.avg_score>0?"+":"",V=j.avg_score!=null?`${Z}${j.avg_score.toFixed(2)}`:"—";return{Date:B,Analyzed:j.analyzed,Positive:j.positive,Neutral:j.neutral,Negative:j.negative,"Avg Score":V}}))}),X6(Q.command("hourly").description("Show call volume distribution by hour of day")).action(async(G)=>{let{format:K}=w($.opts()),{date_from:J,date_to:W}=V1(G),q=await _(U().dashboard.hourlyDistribution({date_from:J,date_to:W,visual_plan_id:b("visual_plans",G.plan),channel_id:b("channels",G.phone)}));if(K==="json"){P(q);return}if(console.log(E$.default.bold("Hourly Distribution")),q.length===0){z(`
54
- No data available.`);return}console.log("");let j=Math.max(...q.map((X)=>X.total));for(let X of q){let B=`${String(X.hour).padStart(2,"0")}:00`,Z=Z1(X.total,j),V=X.total===j?E$.default.yellow(" ← peak"):"";console.log(` ${B} ${Z} ${X.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(G)=>{let{format:K,fields:J}=w($.opts()),{date_from:W,date_to:q}=V1(G),j=await _(U().dashboard.topPlans({date_from:W,date_to:q,limit:Number(G.limit)}));if(K==="json"){let X=J?j.map((B)=>g(B,J)):j;P(X);return}if(console.log(E$.default.bold("Top Plans")),j.length===0){z(`
55
- No data available.`);return}console.log(""),u(["Plan","Total","Answered","Avg Duration"],j.map((X)=>({Plan:X.visual_plan_name??"—",Total:X.total,Answered:`${X.answered} (${X.total>0?Math.round(X.answered/X.total*100):0}%)`,"Avg Duration":A$(X.avg_duration_ms)})))})}function sW($,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(G)=>{let{format:K,fields:J}=w($.opts()),W=await _(U().channels.list({page:Number(G.page),limit:Number(G.limit),...G.type!=null?{channel_type:G.type}:{}}));if(K==="json"){let q=J?W.items.map((j)=>g(j,J)):W;P(q);return}u(["ID","Type","Name","Identifier","Active"],W.items.map((q)=>({ID:q.id,Type:q.channel_type,Name:q.name,Identifier:q.identifier??"—",Active:q.is_active?"yes":"no"}))),X$(W)}),Q.command("assign <channel_id>").description("Assign a channel to a plan").option("--plan <plan_id>","Plan ID to assign").action(()=>n$())}import{readFile as EV}from"node:fs/promises";var $q=1e4;function Uq($,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(G)=>{let{format:K,fields:J}=w($.opts()),W=await _(U().dialerDnc.list({page:Number(G.page),limit:Number(G.limit),search:G.search}));if(K==="json"){P(J?W.items.map((q)=>g(q,J)):W);return}u(["ID","Phone","Reason","Added"],W.items.map((q)=>({ID:q.id,Phone:q.phone_number,Reason:q.reason??"—",Added:p$(q.created_at)}))),X$(W)}),Q.command("add <phone>").description("Add a number to the do-not-call list").option("--reason <r>","Reason for the block").action(async(G,K)=>{let{format:J}=w($.opts()),W=await _(U().dialerDnc.add({phone_number:G,reason:K.reason}));if(J==="json"){P(W);return}E(`Added ${W.phone_number} to DNC`)}),Q.command("remove <ids...>").description("Remove do-not-call entries").action(async(G)=>{let{format:K}=w($.opts());if(G.length===1){let W=await _(U().dialerDnc.remove({dnc_id:b("dialer_dnc",G[0])}));if(K==="json"){P(W);return}E("Removed DNC entry");return}let J=await _(U().dialerDnc.bulkRemove({ids:b("dialer_dnc",G)}));if(K==="json"){P(J);return}E(`Removed ${J.removed}`)}),Q.command("check <phone>").description("Check if a number is on the DNC list (exit 0 = listed, 3 = not listed)").action(async(G)=>{let{format:K}=w($.opts()),J=await _(U().dialerDnc.list({page:1,limit:20,search:G})),W=G.replaceAll(/\D/g,""),q=W===""?void 0:J.items.find((j)=>{let X=String(j.phone_number).replaceAll(/\D/g,"");return X===W||X.endsWith(W)});if(q!=null){if(K==="json")P(q);else s([{title:"DNC entry",rows:[{label:"ID",value:q.id},{label:"Phone",value:q.phone_number},{label:"Reason",value:q.reason??"—"},{label:"Added",value:new Date(q.created_at).toLocaleString()}]}]);return}if(K==="json")P({listed:!1});else z("Not in DNC list.");process.exit(O.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(G,K)=>{let{format:J}=w($.opts()),q=(await EV(G,"utf-8")).split(/\r\n|\n|\r/).map((B)=>B.trim()).filter((B)=>B.length>0&&!B.startsWith("#"));if(q.length===0)A("No phone numbers found in file"),process.exit(O.USAGE_ERROR);let j=0,X=0;for(let B=0;B<q.length;B+=$q){let Z=q.slice(B,B+$q),V=await _(U().dialerDnc.bulkImport({numbers:Z,reason:K.reason}));j+=V.added,X+=V.skipped}if(J==="json"){P({added:j,skipped:X});return}E(`Added ${j}, skipped ${X}`)})}var Kq={"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":{},"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":{},"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":{},"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"}},yV=Object.keys(Kq);var Y={};K1(Y,{xor:()=>AY,xid:()=>eq,void:()=>kY,uuidv7:()=>rq,uuidv6:()=>lq,uuidv4:()=>cq,uuid:()=>hq,util:()=>F,url:()=>nq,uppercase:()=>b4,unknown:()=>$4,union:()=>d2,undefined:()=>_Y,ulid:()=>aq,uint64:()=>IY,uint32:()=>vY,tuple:()=>kK,trim:()=>C4,treeifyError:()=>P8,transform:()=>t2,toUpperCase:()=>E4,toLowerCase:()=>g4,toJSONSchema:()=>_2,templateLiteral:()=>cY,symbol:()=>NY,superRefine:()=>tK,success:()=>fY,stringbool:()=>tY,stringFormat:()=>jY,string:()=>z2,strictObject:()=>zY,startsWith:()=>O4,slugify:()=>y4,size:()=>a1,setErrorMap:()=>ZP,set:()=>CY,safeParseAsync:()=>a5,safeParse:()=>t5,safeEncodeAsync:()=>GK,safeEncode:()=>KK,safeDecodeAsync:()=>JK,safeDecode:()=>QK,registry:()=>i0,regexes:()=>u$,regex:()=>L4,refine:()=>pK,record:()=>xK,readonly:()=>lK,property:()=>D2,promise:()=>lY,prettifyError:()=>I8,preprocess:()=>eY,prefault:()=>EK,positive:()=>M2,pipe:()=>u6,partialRecord:()=>RY,parseAsync:()=>p5,parse:()=>d5,overwrite:()=>o$,optional:()=>E6,object:()=>LY,number:()=>qK,nullish:()=>uY,nullable:()=>y6,null:()=>BK,normalize:()=>S4,nonpositive:()=>V2,nonoptional:()=>yK,nonnegative:()=>v2,never:()=>o2,negative:()=>Z2,nativeEnum:()=>gY,nanoid:()=>dq,nan:()=>mY,multipleOf:()=>x1,minSize:()=>$1,minLength:()=>Y1,mime:()=>T4,meta:()=>dY,maxSize:()=>F1,maxLength:()=>e1,map:()=>SY,mac:()=>UY,lte:()=>R$,lt:()=>e$,lowercase:()=>z4,looseRecord:()=>TY,looseObject:()=>bY,locales:()=>R6,literal:()=>EY,length:()=>s1,lazy:()=>iK,ksuid:()=>sq,keyof:()=>FY,jwt:()=>YY,json:()=>aY,iso:()=>m4,ipv6:()=>KY,ipv4:()=>$Y,intersection:()=>_K,int64:()=>PY,int32:()=>VY,int:()=>b2,instanceof:()=>pY,includes:()=>A4,httpUrl:()=>iq,hostname:()=>XY,hex:()=>HY,hash:()=>BY,guid:()=>mq,gte:()=>_$,gt:()=>s$,globalRegistry:()=>V$,getErrorMap:()=>VP,function:()=>rY,fromJSONSchema:()=>$j,formatError:()=>N6,float64:()=>ZY,float32:()=>MY,flattenError:()=>I6,file:()=>yY,exactOptional:()=>RK,enum:()=>p2,endsWith:()=>R4,encodeAsync:()=>$K,encode:()=>e5,emoji:()=>oq,email:()=>fq,e164:()=>qY,discriminatedUnion:()=>OY,describe:()=>oY,decodeAsync:()=>UK,decode:()=>s5,date:()=>xY,custom:()=>iY,cuid2:()=>tq,cuid:()=>pq,core:()=>j1,config:()=>W$,coerce:()=>eK,codec:()=>hY,clone:()=>N$,cidrv6:()=>GY,cidrv4:()=>QY,check:()=>nY,catch:()=>mK,boolean:()=>YK,bigint:()=>DY,base64url:()=>WY,base64:()=>JY,array:()=>h6,any:()=>wY,_function:()=>rY,_default:()=>CK,_ZodString:()=>A2,ZodXor:()=>PK,ZodXID:()=>E2,ZodVoid:()=>vK,ZodUnknown:()=>ZK,ZodUnion:()=>l6,ZodUndefined:()=>XK,ZodUUID:()=>U1,ZodURL:()=>f6,ZodULID:()=>g2,ZodType:()=>m,ZodTuple:()=>wK,ZodTransform:()=>AK,ZodTemplateLiteral:()=>rK,ZodSymbol:()=>jK,ZodSuccess:()=>uK,ZodStringFormat:()=>t,ZodString:()=>c4,ZodSet:()=>LK,ZodRecord:()=>r6,ZodRealError:()=>z$,ZodReadonly:()=>cK,ZodPromise:()=>oK,ZodPrefault:()=>gK,ZodPipe:()=>s2,ZodOptional:()=>a2,ZodObject:()=>c6,ZodNumberFormat:()=>U4,ZodNumber:()=>r4,ZodNullable:()=>TK,ZodNull:()=>HK,ZodNonOptional:()=>e2,ZodNever:()=>VK,ZodNanoID:()=>T2,ZodNaN:()=>hK,ZodMap:()=>FK,ZodMAC:()=>WK,ZodLiteral:()=>zK,ZodLazy:()=>nK,ZodKSUID:()=>y2,ZodJWT:()=>n2,ZodIssueCode:()=>MP,ZodIntersection:()=>NK,ZodISOTime:()=>F2,ZodISODuration:()=>L2,ZodISODateTime:()=>k2,ZodISODate:()=>x2,ZodIPv6:()=>f2,ZodIPv4:()=>u2,ZodGUID:()=>g6,ZodFunction:()=>dK,ZodFirstPartyTypeKind:()=>aK,ZodFile:()=>bK,ZodExactOptional:()=>OK,ZodError:()=>HP,ZodEnum:()=>h4,ZodEmoji:()=>R2,ZodEmail:()=>O2,ZodE164:()=>r2,ZodDiscriminatedUnion:()=>IK,ZodDefault:()=>SK,ZodDate:()=>m6,ZodCustomStringFormat:()=>l4,ZodCustom:()=>n6,ZodCodec:()=>$U,ZodCatch:()=>fK,ZodCUID2:()=>C2,ZodCUID:()=>S2,ZodCIDRv6:()=>h2,ZodCIDRv4:()=>m2,ZodBoolean:()=>n4,ZodBigIntFormat:()=>i2,ZodBigInt:()=>i4,ZodBase64URL:()=>l2,ZodBase64:()=>c2,ZodArray:()=>DK,ZodAny:()=>MK,TimePrecision:()=>k7,NEVER:()=>q8,$output:()=>D7,$input:()=>P7,$brand:()=>Y8});var j1={};K1(j1,{version:()=>Z3,util:()=>F,treeifyError:()=>P8,toJSONSchema:()=>_2,toDotPath:()=>Yq,safeParseAsync:()=>_8,safeParse:()=>N8,safeEncodeAsync:()=>vv,safeEncode:()=>Zv,safeDecodeAsync:()=>Dv,safeDecode:()=>Vv,registry:()=>i0,regexes:()=>u$,process:()=>d,prettifyError:()=>I8,parseAsync:()=>x0,parse:()=>k0,meta:()=>Q5,locales:()=>R6,isValidJWT:()=>zq,isValidBase64URL:()=>Lq,isValidBase64:()=>E3,initializeContext:()=>L1,globalRegistry:()=>V$,globalConfig:()=>H6,formatError:()=>N6,flattenError:()=>I6,finalize:()=>b1,extractDefs:()=>z1,encodeAsync:()=>Bv,encode:()=>Xv,describe:()=>K5,decodeAsync:()=>Mv,decode:()=>Hv,createToJSONSchemaMethod:()=>J5,createStandardJSONSchemaMethod:()=>f4,config:()=>W$,clone:()=>N$,_xor:()=>hD,_xid:()=>Q2,_void:()=>o7,_uuidv7:()=>a0,_uuidv6:()=>t0,_uuidv4:()=>p0,_uuid:()=>d0,_url:()=>S6,_uppercase:()=>b4,_unknown:()=>n7,_union:()=>mD,_undefined:()=>c7,_ulid:()=>K2,_uint64:()=>m7,_uint32:()=>C7,_tuple:()=>rD,_trim:()=>C4,_transform:()=>aD,_toUpperCase:()=>E4,_toLowerCase:()=>g4,_templateLiteral:()=>WP,_symbol:()=>h7,_superRefine:()=>U5,_success:()=>KP,_stringbool:()=>G5,_stringFormat:()=>u4,_string:()=>N7,_startsWith:()=>O4,_slugify:()=>y4,_size:()=>a1,_set:()=>oD,_safeParseAsync:()=>k4,_safeParse:()=>w4,_safeEncodeAsync:()=>R0,_safeEncode:()=>A0,_safeDecodeAsync:()=>T0,_safeDecode:()=>O0,_regex:()=>L4,_refine:()=>$5,_record:()=>nD,_readonly:()=>JP,_property:()=>D2,_promise:()=>YP,_positive:()=>M2,_pipe:()=>GP,_parseAsync:()=>_4,_parse:()=>N4,_overwrite:()=>o$,_optional:()=>eD,_number:()=>b7,_nullable:()=>sD,_null:()=>l7,_normalize:()=>S4,_nonpositive:()=>V2,_nonoptional:()=>UP,_nonnegative:()=>v2,_never:()=>i7,_negative:()=>Z2,_nativeEnum:()=>pD,_nanoid:()=>s0,_nan:()=>t7,_multipleOf:()=>x1,_minSize:()=>$1,_minLength:()=>Y1,_min:()=>_$,_mime:()=>T4,_maxSize:()=>F1,_maxLength:()=>e1,_max:()=>R$,_map:()=>iD,_mac:()=>w7,_lte:()=>R$,_lt:()=>e$,_lowercase:()=>z4,_literal:()=>tD,_length:()=>s1,_lazy:()=>qP,_ksuid:()=>G2,_jwt:()=>B2,_isoTime:()=>L7,_isoDuration:()=>z7,_isoDateTime:()=>x7,_isoDate:()=>F7,_ipv6:()=>W2,_ipv4:()=>J2,_intersection:()=>lD,_int64:()=>f7,_int32:()=>S7,_int:()=>O7,_includes:()=>A4,_guid:()=>T6,_gte:()=>_$,_gt:()=>s$,_float64:()=>T7,_float32:()=>R7,_file:()=>e7,_enum:()=>dD,_endsWith:()=>R4,_encodeAsync:()=>z0,_encode:()=>F0,_emoji:()=>e0,_email:()=>o0,_e164:()=>H2,_discriminatedUnion:()=>cD,_default:()=>$P,_decodeAsync:()=>b0,_decode:()=>L0,_date:()=>d7,_custom:()=>s7,_cuid2:()=>U2,_cuid:()=>$2,_coercedString:()=>_7,_coercedNumber:()=>A7,_coercedDate:()=>p7,_coercedBoolean:()=>E7,_coercedBigint:()=>u7,_cidrv6:()=>Y2,_cidrv4:()=>q2,_check:()=>Eq,_catch:()=>QP,_boolean:()=>g7,_bigint:()=>y7,_base64url:()=>X2,_base64:()=>j2,_array:()=>a7,_any:()=>r7,TimePrecision:()=>k7,NEVER:()=>q8,JSONSchemaGenerator:()=>l5,JSONSchema:()=>yq,Doc:()=>E0,$output:()=>D7,$input:()=>P7,$constructor:()=>v,$brand:()=>Y8,$ZodXor:()=>$9,$ZodXID:()=>F3,$ZodVoid:()=>t3,$ZodUnknown:()=>d3,$ZodUnion:()=>F6,$ZodUndefined:()=>n3,$ZodUUID:()=>D3,$ZodURL:()=>I3,$ZodULID:()=>x3,$ZodType:()=>y,$ZodTuple:()=>r0,$ZodTransform:()=>j9,$ZodTemplateLiteral:()=>N9,$ZodSymbol:()=>r3,$ZodSuccess:()=>V9,$ZodStringFormat:()=>p,$ZodString:()=>t1,$ZodSet:()=>J9,$ZodRegistry:()=>I7,$ZodRecord:()=>Q9,$ZodRealError:()=>L$,$ZodReadonly:()=>I9,$ZodPromise:()=>w9,$ZodPrefault:()=>M9,$ZodPipe:()=>P9,$ZodOptional:()=>n0,$ZodObjectJIT:()=>s3,$ZodObject:()=>Oq,$ZodNumberFormat:()=>c3,$ZodNumber:()=>c0,$ZodNullable:()=>H9,$ZodNull:()=>i3,$ZodNonOptional:()=>Z9,$ZodNever:()=>p3,$ZodNanoID:()=>_3,$ZodNaN:()=>D9,$ZodMap:()=>G9,$ZodMAC:()=>S3,$ZodLiteral:()=>q9,$ZodLazy:()=>k9,$ZodKSUID:()=>L3,$ZodJWT:()=>m3,$ZodIntersection:()=>K9,$ZodISOTime:()=>A3,$ZodISODuration:()=>O3,$ZodISODateTime:()=>z3,$ZodISODate:()=>b3,$ZodIPv6:()=>T3,$ZodIPv4:()=>R3,$ZodGUID:()=>v3,$ZodFunction:()=>_9,$ZodFile:()=>Y9,$ZodExactOptional:()=>X9,$ZodError:()=>P6,$ZodEnum:()=>W9,$ZodEncodeError:()=>o1,$ZodEmoji:()=>N3,$ZodEmail:()=>P3,$ZodE164:()=>f3,$ZodDiscriminatedUnion:()=>U9,$ZodDefault:()=>B9,$ZodDate:()=>a3,$ZodCustomStringFormat:()=>h3,$ZodCustom:()=>x9,$ZodCodec:()=>L6,$ZodCheckUpperCase:()=>q3,$ZodCheckStringFormat:()=>x4,$ZodCheckStartsWith:()=>j3,$ZodCheckSizeEquals:()=>U3,$ZodCheckRegex:()=>J3,$ZodCheckProperty:()=>H3,$ZodCheckOverwrite:()=>M3,$ZodCheckNumberFormat:()=>a8,$ZodCheckMultipleOf:()=>t8,$ZodCheckMinSize:()=>$3,$ZodCheckMinLength:()=>Q3,$ZodCheckMimeType:()=>B3,$ZodCheckMaxSize:()=>s8,$ZodCheckMaxLength:()=>K3,$ZodCheckLowerCase:()=>W3,$ZodCheckLessThan:()=>C0,$ZodCheckLengthEquals:()=>G3,$ZodCheckIncludes:()=>Y3,$ZodCheckGreaterThan:()=>g0,$ZodCheckEndsWith:()=>X3,$ZodCheckBigIntFormat:()=>e8,$ZodCheck:()=>a,$ZodCatch:()=>v9,$ZodCUID2:()=>k3,$ZodCUID:()=>w3,$ZodCIDRv6:()=>g3,$ZodCIDRv4:()=>C3,$ZodBoolean:()=>x6,$ZodBigIntFormat:()=>l3,$ZodBigInt:()=>l0,$ZodBase64URL:()=>u3,$ZodBase64:()=>y3,$ZodAsyncError:()=>a$,$ZodArray:()=>e3,$ZodAny:()=>o3});var q8=Object.freeze({status:"aborted"});function v($,U,Q){function G(q,j){if(!q._zod)Object.defineProperty(q,"_zod",{value:{def:j,constr:W,traits:new Set},enumerable:!1});if(q._zod.traits.has($))return;q._zod.traits.add($),U(q,j);let X=W.prototype,B=Object.keys(X);for(let Z=0;Z<B.length;Z++){let V=B[Z];if(!(V in q))q[V]=X[V].bind(q)}}let K=Q?.Parent??Object;class J extends K{}Object.defineProperty(J,"name",{value:$});function W(q){var j;let X=Q?.Parent?new J:this;G(X,q),(j=X._zod).deferred??(j.deferred=[]);for(let B of X._zod.deferred)B();return X}return Object.defineProperty(W,"init",{value:G}),Object.defineProperty(W,Symbol.hasInstance,{value:(q)=>{if(Q?.Parent&&q instanceof Q.Parent)return!0;return q?._zod?.traits?.has($)}}),Object.defineProperty(W,"name",{value:$}),W}var Y8=Symbol("zod_brand");class a$ extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class o1 extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}}var H6={};function W$($){if($)Object.assign(H6,$);return H6}var F={};K1(F,{unwrapMessage:()=>B6,uint8ArrayToHex:()=>Yv,uint8ArrayToBase64url:()=>Wv,uint8ArrayToBase64:()=>Jq,stringifyPrimitive:()=>k,slugify:()=>H8,shallowClone:()=>M8,safeExtend:()=>$v,required:()=>Qv,randomString:()=>oV,propertyKeyTypes:()=>V6,promiseAllObject:()=>iV,primitiveTypes:()=>Z8,prefixIssues:()=>O$,pick:()=>aV,partial:()=>Kv,parsedType:()=>x,optionalKeys:()=>V8,omit:()=>eV,objectClone:()=>lV,numKeys:()=>dV,nullish:()=>N1,normalizeParams:()=>L,mergeDefs:()=>q1,merge:()=>Uv,jsonStringifyReplacer:()=>D4,joinValues:()=>D,issue:()=>I4,isPlainObject:()=>w1,isObject:()=>d1,hexToUint8Array:()=>qv,getSizableOrigin:()=>v6,getParsedType:()=>pV,getLengthableOrigin:()=>D6,getEnumValues:()=>M6,getElementAtPath:()=>nV,floatSafeRemainder:()=>X8,finalizeIssue:()=>F$,extend:()=>sV,escapeRegex:()=>y$,esc:()=>_0,defineLazy:()=>h,createTransparentProxy:()=>tV,cloneDef:()=>rV,clone:()=>N$,cleanRegex:()=>Z6,cleanEnum:()=>Gv,captureStackTrace:()=>w0,cached:()=>P4,base64urlToUint8Array:()=>Jv,base64ToUint8Array:()=>Gq,assignProp:()=>_1,assertNotEqual:()=>fV,assertNever:()=>hV,assertIs:()=>mV,assertEqual:()=>uV,assert:()=>cV,allowsEval:()=>B8,aborted:()=>k1,NUMBER_FORMAT_RANGES:()=>v8,Class:()=>Wq,BIGINT_FORMAT_RANGES:()=>D8});function uV($){return $}function fV($){return $}function mV($){}function hV($){throw Error("Unexpected value in exhaustive check")}function cV($){}function M6($){let U=Object.values($).filter((G)=>typeof G==="number");return Object.entries($).filter(([G,K])=>U.indexOf(+G)===-1).map(([G,K])=>K)}function D($,U="|"){return $.map((Q)=>k(Q)).join(U)}function D4($,U){if(typeof U==="bigint")return U.toString();return U}function P4($){return{get value(){{let Q=$();return Object.defineProperty(this,"value",{value:Q}),Q}throw Error("cached value already set")}}}function N1($){return $===null||$===void 0}function Z6($){let U=$.startsWith("^")?1:0,Q=$.endsWith("$")?$.length-1:$.length;return $.slice(U,Q)}function X8($,U){let Q=($.toString().split(".")[1]||"").length,G=U.toString(),K=(G.split(".")[1]||"").length;if(K===0&&/\d?e-\d?/.test(G)){let j=G.match(/\d?e-(\d?)/);if(j?.[1])K=Number.parseInt(j[1])}let J=Q>K?Q:K,W=Number.parseInt($.toFixed(J).replace(".","")),q=Number.parseInt(U.toFixed(J).replace(".",""));return W%q/10**J}var Qq=Symbol("evaluating");function h($,U,Q){let G=void 0;Object.defineProperty($,U,{get(){if(G===Qq)return;if(G===void 0)G=Qq,G=Q();return G},set(K){Object.defineProperty($,U,{value:K})},configurable:!0})}function lV($){return Object.create(Object.getPrototypeOf($),Object.getOwnPropertyDescriptors($))}function _1($,U,Q){Object.defineProperty($,U,{value:Q,writable:!0,enumerable:!0,configurable:!0})}function q1(...$){let U={};for(let Q of $){let G=Object.getOwnPropertyDescriptors(Q);Object.assign(U,G)}return Object.defineProperties({},U)}function rV($){return q1($._zod.def)}function nV($,U){if(!U)return $;return U.reduce((Q,G)=>Q?.[G],$)}function iV($){let U=Object.keys($),Q=U.map((G)=>$[G]);return Promise.all(Q).then((G)=>{let K={};for(let J=0;J<U.length;J++)K[U[J]]=G[J];return K})}function oV($=10){let Q="";for(let G=0;G<$;G++)Q+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return Q}function _0($){return JSON.stringify($)}function H8($){return $.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var w0="captureStackTrace"in Error?Error.captureStackTrace:(...$)=>{};function d1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var B8=P4(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});function w1($){if(d1($)===!1)return!1;let U=$.constructor;if(U===void 0)return!0;if(typeof U!=="function")return!0;let Q=U.prototype;if(d1(Q)===!1)return!1;if(Object.prototype.hasOwnProperty.call(Q,"isPrototypeOf")===!1)return!1;return!0}function M8($){if(w1($))return{...$};if(Array.isArray($))return[...$];return $}function dV($){let U=0;for(let Q in $)if(Object.prototype.hasOwnProperty.call($,Q))U++;return U}var pV=($)=>{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}`)}},V6=new Set(["string","number","symbol"]),Z8=new Set(["string","number","bigint","boolean","symbol","undefined"]);function y$($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function N$($,U,Q){let G=new $._zod.constr(U??$._zod.def);if(!U||Q?.parent)G._zod.parent=$;return G}function L($){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 tV($){let U;return new Proxy({},{get(Q,G,K){return U??(U=$()),Reflect.get(U,G,K)},set(Q,G,K,J){return U??(U=$()),Reflect.set(U,G,K,J)},has(Q,G){return U??(U=$()),Reflect.has(U,G)},deleteProperty(Q,G){return U??(U=$()),Reflect.deleteProperty(U,G)},ownKeys(Q){return U??(U=$()),Reflect.ownKeys(U)},getOwnPropertyDescriptor(Q,G){return U??(U=$()),Reflect.getOwnPropertyDescriptor(U,G)},defineProperty(Q,G,K){return U??(U=$()),Reflect.defineProperty(U,G,K)}})}function k($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function V8($){return Object.keys($).filter((U)=>{return $[U]._zod.optin==="optional"&&$[U]._zod.optout==="optional"})}var v8={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]},D8={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function aV($,U){let Q=$._zod.def,G=Q.checks;if(G&&G.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let J=q1($._zod.def,{get shape(){let W={};for(let q in U){if(!(q in Q.shape))throw Error(`Unrecognized key: "${q}"`);if(!U[q])continue;W[q]=Q.shape[q]}return _1(this,"shape",W),W},checks:[]});return N$($,J)}function eV($,U){let Q=$._zod.def,G=Q.checks;if(G&&G.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let J=q1($._zod.def,{get shape(){let W={...$._zod.def.shape};for(let q in U){if(!(q in Q.shape))throw Error(`Unrecognized key: "${q}"`);if(!U[q])continue;delete W[q]}return _1(this,"shape",W),W},checks:[]});return N$($,J)}function sV($,U){if(!w1(U))throw Error("Invalid input to extend: expected a plain object");let Q=$._zod.def.checks;if(Q&&Q.length>0){let J=$._zod.def.shape;for(let W in U)if(Object.getOwnPropertyDescriptor(J,W)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let K=q1($._zod.def,{get shape(){let J={...$._zod.def.shape,...U};return _1(this,"shape",J),J}});return N$($,K)}function $v($,U){if(!w1(U))throw Error("Invalid input to safeExtend: expected a plain object");let Q=q1($._zod.def,{get shape(){let G={...$._zod.def.shape,...U};return _1(this,"shape",G),G}});return N$($,Q)}function Uv($,U){let Q=q1($._zod.def,{get shape(){let G={...$._zod.def.shape,...U._zod.def.shape};return _1(this,"shape",G),G},get catchall(){return U._zod.def.catchall},checks:[]});return N$($,Q)}function Kv($,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 W=q1(U._zod.def,{get shape(){let q=U._zod.def.shape,j={...q};if(Q)for(let X in Q){if(!(X in q))throw Error(`Unrecognized key: "${X}"`);if(!Q[X])continue;j[X]=$?new $({type:"optional",innerType:q[X]}):q[X]}else for(let X in q)j[X]=$?new $({type:"optional",innerType:q[X]}):q[X];return _1(this,"shape",j),j},checks:[]});return N$(U,W)}function Qv($,U,Q){let G=q1(U._zod.def,{get shape(){let K=U._zod.def.shape,J={...K};if(Q)for(let W in Q){if(!(W in J))throw Error(`Unrecognized key: "${W}"`);if(!Q[W])continue;J[W]=new $({type:"nonoptional",innerType:K[W]})}else for(let W in K)J[W]=new $({type:"nonoptional",innerType:K[W]});return _1(this,"shape",J),J}});return N$(U,G)}function k1($,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 O$($,U){return U.map((Q)=>{var G;return(G=Q).path??(G.path=[]),Q.path.unshift($),Q})}function B6($){return typeof $==="string"?$:$?.message}function F$($,U,Q){let G={...$,path:$.path??[]};if(!$.message){let K=B6($.inst?._zod.def?.error?.($))??B6(U?.error?.($))??B6(Q.customError?.($))??B6(Q.localeError?.($))??"Invalid input";G.message=K}if(delete G.inst,delete G.continue,!U?.reportInput)delete G.input;return G}function v6($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function D6($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function x($){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 I4(...$){let[U,Q,G]=$;if(typeof U==="string")return{message:U,code:"custom",input:Q,inst:G};return{...U}}function Gv($){return Object.entries($).filter(([U,Q])=>{return Number.isNaN(Number.parseInt(U,10))}).map((U)=>U[1])}function Gq($){let U=atob($),Q=new Uint8Array(U.length);for(let G=0;G<U.length;G++)Q[G]=U.charCodeAt(G);return Q}function Jq($){let U="";for(let Q=0;Q<$.length;Q++)U+=String.fromCharCode($[Q]);return btoa(U)}function Jv($){let U=$.replace(/-/g,"+").replace(/_/g,"/"),Q="=".repeat((4-U.length%4)%4);return Gq(U+Q)}function Wv($){return Jq($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function qv($){let U=$.replace(/^0x/,"");if(U.length%2!==0)throw Error("Invalid hex string length");let Q=new Uint8Array(U.length/2);for(let G=0;G<U.length;G+=2)Q[G/2]=Number.parseInt(U.slice(G,G+2),16);return Q}function Yv($){return Array.from($).map((U)=>U.toString(16).padStart(2,"0")).join("")}class Wq{constructor(...$){}}var qq=($,U)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:U,enumerable:!1}),$.message=JSON.stringify(U,D4,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},P6=v("$ZodError",qq),L$=v("$ZodError",qq,{Parent:Error});function I6($,U=(Q)=>Q.message){let Q={},G=[];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 G.push(U(K));return{formErrors:G,fieldErrors:Q}}function N6($,U=(Q)=>Q.message){let Q={_errors:[]},G=(K)=>{for(let J of K.issues)if(J.code==="invalid_union"&&J.errors.length)J.errors.map((W)=>G({issues:W}));else if(J.code==="invalid_key")G({issues:J.issues});else if(J.code==="invalid_element")G({issues:J.issues});else if(J.path.length===0)Q._errors.push(U(J));else{let W=Q,q=0;while(q<J.path.length){let j=J.path[q];if(q!==J.path.length-1)W[j]=W[j]||{_errors:[]};else W[j]=W[j]||{_errors:[]},W[j]._errors.push(U(J));W=W[j],q++}}};return G($),Q}function P8($,U=(Q)=>Q.message){let Q={errors:[]},G=(K,J=[])=>{var W,q;for(let j of K.issues)if(j.code==="invalid_union"&&j.errors.length)j.errors.map((X)=>G({issues:X},j.path));else if(j.code==="invalid_key")G({issues:j.issues},j.path);else if(j.code==="invalid_element")G({issues:j.issues},j.path);else{let X=[...J,...j.path];if(X.length===0){Q.errors.push(U(j));continue}let B=Q,Z=0;while(Z<X.length){let V=X[Z],N=Z===X.length-1;if(typeof V==="string")B.properties??(B.properties={}),(W=B.properties)[V]??(W[V]={errors:[]}),B=B.properties[V];else B.items??(B.items=[]),(q=B.items)[V]??(q[V]={errors:[]}),B=B.items[V];if(N)B.errors.push(U(j));Z++}}};return G($),Q}function Yq($){let U=[],Q=$.map((G)=>typeof G==="object"?G.key:G);for(let G of Q)if(typeof G==="number")U.push(`[${G}]`);else if(typeof G==="symbol")U.push(`[${JSON.stringify(String(G))}]`);else if(/[^\w$]/.test(G))U.push(`[${JSON.stringify(G)}]`);else{if(U.length)U.push(".");U.push(G)}return U.join("")}function I8($){let U=[],Q=[...$.issues].sort((G,K)=>(G.path??[]).length-(K.path??[]).length);for(let G of Q)if(U.push(`✖ ${G.message}`),G.path?.length)U.push(` → at ${Yq(G.path)}`);return U.join(`
56
- `)}var N4=($)=>(U,Q,G,K)=>{let J=G?Object.assign(G,{async:!1}):{async:!1},W=U._zod.run({value:Q,issues:[]},J);if(W instanceof Promise)throw new a$;if(W.issues.length){let q=new(K?.Err??$)(W.issues.map((j)=>F$(j,J,W$())));throw w0(q,K?.callee),q}return W.value},k0=N4(L$),_4=($)=>async(U,Q,G,K)=>{let J=G?Object.assign(G,{async:!0}):{async:!0},W=U._zod.run({value:Q,issues:[]},J);if(W instanceof Promise)W=await W;if(W.issues.length){let q=new(K?.Err??$)(W.issues.map((j)=>F$(j,J,W$())));throw w0(q,K?.callee),q}return W.value},x0=_4(L$),w4=($)=>(U,Q,G)=>{let K=G?{...G,async:!1}:{async:!1},J=U._zod.run({value:Q,issues:[]},K);if(J instanceof Promise)throw new a$;return J.issues.length?{success:!1,error:new($??P6)(J.issues.map((W)=>F$(W,K,W$())))}:{success:!0,data:J.value}},N8=w4(L$),k4=($)=>async(U,Q,G)=>{let K=G?Object.assign(G,{async:!0}):{async:!0},J=U._zod.run({value:Q,issues:[]},K);if(J instanceof Promise)J=await J;return J.issues.length?{success:!1,error:new $(J.issues.map((W)=>F$(W,K,W$())))}:{success:!0,data:J.value}},_8=k4(L$),F0=($)=>(U,Q,G)=>{let K=G?Object.assign(G,{direction:"backward"}):{direction:"backward"};return N4($)(U,Q,K)},Xv=F0(L$),L0=($)=>(U,Q,G)=>{return N4($)(U,Q,G)},Hv=L0(L$),z0=($)=>async(U,Q,G)=>{let K=G?Object.assign(G,{direction:"backward"}):{direction:"backward"};return _4($)(U,Q,K)},Bv=z0(L$),b0=($)=>async(U,Q,G)=>{return _4($)(U,Q,G)},Mv=b0(L$),A0=($)=>(U,Q,G)=>{let K=G?Object.assign(G,{direction:"backward"}):{direction:"backward"};return w4($)(U,Q,K)},Zv=A0(L$),O0=($)=>(U,Q,G)=>{return w4($)(U,Q,G)},Vv=O0(L$),R0=($)=>async(U,Q,G)=>{let K=G?Object.assign(G,{direction:"backward"}):{direction:"backward"};return k4($)(U,Q,K)},vv=R0(L$),T0=($)=>async(U,Q,G)=>{return k4($)(U,Q,G)},Dv=T0(L$);var u$={};K1(u$,{xid:()=>F8,uuid7:()=>_v,uuid6:()=>Nv,uuid4:()=>Iv,uuid:()=>p1,uppercase:()=>p8,unicodeEmail:()=>jq,undefined:()=>o8,ulid:()=>x8,time:()=>m8,string:()=>c8,sha512_hex:()=>cv,sha512_base64url:()=>rv,sha512_base64:()=>lv,sha384_hex:()=>fv,sha384_base64url:()=>hv,sha384_base64:()=>mv,sha256_hex:()=>Ev,sha256_base64url:()=>uv,sha256_base64:()=>yv,sha1_hex:()=>Sv,sha1_base64url:()=>gv,sha1_base64:()=>Cv,rfc5322Email:()=>kv,number:()=>_6,null:()=>i8,nanoid:()=>z8,md5_hex:()=>Ov,md5_base64url:()=>Tv,md5_base64:()=>Rv,mac:()=>C8,lowercase:()=>d8,ksuid:()=>L8,ipv6:()=>S8,ipv4:()=>T8,integer:()=>r8,idnEmail:()=>xv,html5Email:()=>wv,hostname:()=>zv,hex:()=>Av,guid:()=>A8,extendedDuration:()=>Pv,emoji:()=>R8,email:()=>O8,e164:()=>u8,duration:()=>b8,domain:()=>bv,datetime:()=>h8,date:()=>f8,cuid2:()=>k8,cuid:()=>w8,cidrv6:()=>E8,cidrv4:()=>g8,browserEmail:()=>Fv,boolean:()=>n8,bigint:()=>l8,base64url:()=>S0,base64:()=>y8});var w8=/^[cC][^\s-]{8,}$/,k8=/^[0-9a-z]+$/,x8=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,F8=/^[0-9a-vA-V]{20}$/,L8=/^[A-Za-z0-9]{27}$/,z8=/^[a-zA-Z0-9_-]{21}$/,b8=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Pv=/^[-+]?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)?)??$/,A8=/^([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})$/,p1=($)=>{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})$`)},Iv=p1(4),Nv=p1(6),_v=p1(7),O8=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,wv=/^[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])?)*$/,kv=/^(([^<>()\[\]\\.,;:\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,}))$/,jq=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,xv=jq,Fv=/^[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])?)*$/,Lv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function R8(){return new RegExp(Lv,"u")}var T8=/^(?:(?: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])$/,S8=/^(([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}|:))$/,C8=($)=>{let U=y$($??":");return new RegExp(`^(?:[0-9A-F]{2}${U}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${U}){5}[0-9a-f]{2}$`)},g8=/^((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])$/,E8=/^(([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])$/,y8=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,S0=/^[A-Za-z0-9_-]*$/,zv=/^(?=.{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])?)*\.?$/,bv=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,u8=/^\+[1-9]\d{6,14}$/,Xq="(?:(?:\\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])))",f8=new RegExp(`^${Xq}$`);function Hq($){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 m8($){return new RegExp(`^${Hq($)}$`)}function h8($){let U=Hq({precision:$.precision}),Q=["Z"];if($.local)Q.push("");if($.offset)Q.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let G=`${U}(?:${Q.join("|")})`;return new RegExp(`^${Xq}T(?:${G})$`)}var c8=($)=>{let U=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${U}$`)},l8=/^-?\d+n?$/,r8=/^-?\d+$/,_6=/^-?\d+(?:\.\d+)?$/,n8=/^(?:true|false)$/i,i8=/^null$/i;var o8=/^undefined$/i;var d8=/^[^A-Z]*$/,p8=/^[^a-z]*$/,Av=/^[0-9a-fA-F]*$/;function w6($,U){return new RegExp(`^[A-Za-z0-9+/]{${$}}${U}$`)}function k6($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var Ov=/^[0-9a-fA-F]{32}$/,Rv=w6(22,"=="),Tv=k6(22),Sv=/^[0-9a-fA-F]{40}$/,Cv=w6(27,"="),gv=k6(27),Ev=/^[0-9a-fA-F]{64}$/,yv=w6(43,"="),uv=k6(43),fv=/^[0-9a-fA-F]{96}$/,mv=w6(64,""),hv=k6(64),cv=/^[0-9a-fA-F]{128}$/,lv=w6(86,"=="),rv=k6(86);var a=v("$ZodCheck",($,U)=>{var Q;$._zod??($._zod={}),$._zod.def=U,(Q=$._zod).onattach??(Q.onattach=[])}),Mq={number:"number",bigint:"bigint",object:"date"},C0=v("$ZodCheckLessThan",($,U)=>{a.init($,U);let Q=Mq[typeof U.value];$._zod.onattach.push((G)=>{let K=G._zod.bag,J=(U.inclusive?K.maximum:K.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(U.value<J)if(U.inclusive)K.maximum=U.value;else K.exclusiveMaximum=U.value}),$._zod.check=(G)=>{if(U.inclusive?G.value<=U.value:G.value<U.value)return;G.issues.push({origin:Q,code:"too_big",maximum:typeof U.value==="object"?U.value.getTime():U.value,input:G.value,inclusive:U.inclusive,inst:$,continue:!U.abort})}}),g0=v("$ZodCheckGreaterThan",($,U)=>{a.init($,U);let Q=Mq[typeof U.value];$._zod.onattach.push((G)=>{let K=G._zod.bag,J=(U.inclusive?K.minimum:K.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(U.value>J)if(U.inclusive)K.minimum=U.value;else K.exclusiveMinimum=U.value}),$._zod.check=(G)=>{if(U.inclusive?G.value>=U.value:G.value>U.value)return;G.issues.push({origin:Q,code:"too_small",minimum:typeof U.value==="object"?U.value.getTime():U.value,input:G.value,inclusive:U.inclusive,inst:$,continue:!U.abort})}}),t8=v("$ZodCheckMultipleOf",($,U)=>{a.init($,U),$._zod.onattach.push((Q)=>{var G;(G=Q._zod.bag).multipleOf??(G.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):X8(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})}}),a8=v("$ZodCheckNumberFormat",($,U)=>{a.init($,U),U.format=U.format||"float64";let Q=U.format?.includes("int"),G=Q?"int":"number",[K,J]=v8[U.format];$._zod.onattach.push((W)=>{let q=W._zod.bag;if(q.format=U.format,q.minimum=K,q.maximum=J,Q)q.pattern=r8}),$._zod.check=(W)=>{let q=W.value;if(Q){if(!Number.isInteger(q)){W.issues.push({expected:G,format:U.format,code:"invalid_type",continue:!1,input:q,inst:$});return}if(!Number.isSafeInteger(q)){if(q>0)W.issues.push({input:q,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:G,inclusive:!0,continue:!U.abort});else W.issues.push({input:q,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:G,inclusive:!0,continue:!U.abort});return}}if(q<K)W.issues.push({origin:"number",input:q,code:"too_small",minimum:K,inclusive:!0,inst:$,continue:!U.abort});if(q>J)W.issues.push({origin:"number",input:q,code:"too_big",maximum:J,inclusive:!0,inst:$,continue:!U.abort})}}),e8=v("$ZodCheckBigIntFormat",($,U)=>{a.init($,U);let[Q,G]=D8[U.format];$._zod.onattach.push((K)=>{let J=K._zod.bag;J.format=U.format,J.minimum=Q,J.maximum=G}),$._zod.check=(K)=>{let J=K.value;if(J<Q)K.issues.push({origin:"bigint",input:J,code:"too_small",minimum:Q,inclusive:!0,inst:$,continue:!U.abort});if(J>G)K.issues.push({origin:"bigint",input:J,code:"too_big",maximum:G,inclusive:!0,inst:$,continue:!U.abort})}}),s8=v("$ZodCheckMaxSize",($,U)=>{var Q;a.init($,U),(Q=$._zod.def).when??(Q.when=(G)=>{let K=G.value;return!N1(K)&&K.size!==void 0}),$._zod.onattach.push((G)=>{let K=G._zod.bag.maximum??Number.POSITIVE_INFINITY;if(U.maximum<K)G._zod.bag.maximum=U.maximum}),$._zod.check=(G)=>{let K=G.value;if(K.size<=U.maximum)return;G.issues.push({origin:v6(K),code:"too_big",maximum:U.maximum,inclusive:!0,input:K,inst:$,continue:!U.abort})}}),$3=v("$ZodCheckMinSize",($,U)=>{var Q;a.init($,U),(Q=$._zod.def).when??(Q.when=(G)=>{let K=G.value;return!N1(K)&&K.size!==void 0}),$._zod.onattach.push((G)=>{let K=G._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(U.minimum>K)G._zod.bag.minimum=U.minimum}),$._zod.check=(G)=>{let K=G.value;if(K.size>=U.minimum)return;G.issues.push({origin:v6(K),code:"too_small",minimum:U.minimum,inclusive:!0,input:K,inst:$,continue:!U.abort})}}),U3=v("$ZodCheckSizeEquals",($,U)=>{var Q;a.init($,U),(Q=$._zod.def).when??(Q.when=(G)=>{let K=G.value;return!N1(K)&&K.size!==void 0}),$._zod.onattach.push((G)=>{let K=G._zod.bag;K.minimum=U.size,K.maximum=U.size,K.size=U.size}),$._zod.check=(G)=>{let K=G.value,J=K.size;if(J===U.size)return;let W=J>U.size;G.issues.push({origin:v6(K),...W?{code:"too_big",maximum:U.size}:{code:"too_small",minimum:U.size},inclusive:!0,exact:!0,input:G.value,inst:$,continue:!U.abort})}}),K3=v("$ZodCheckMaxLength",($,U)=>{var Q;a.init($,U),(Q=$._zod.def).when??(Q.when=(G)=>{let K=G.value;return!N1(K)&&K.length!==void 0}),$._zod.onattach.push((G)=>{let K=G._zod.bag.maximum??Number.POSITIVE_INFINITY;if(U.maximum<K)G._zod.bag.maximum=U.maximum}),$._zod.check=(G)=>{let K=G.value;if(K.length<=U.maximum)return;let W=D6(K);G.issues.push({origin:W,code:"too_big",maximum:U.maximum,inclusive:!0,input:K,inst:$,continue:!U.abort})}}),Q3=v("$ZodCheckMinLength",($,U)=>{var Q;a.init($,U),(Q=$._zod.def).when??(Q.when=(G)=>{let K=G.value;return!N1(K)&&K.length!==void 0}),$._zod.onattach.push((G)=>{let K=G._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(U.minimum>K)G._zod.bag.minimum=U.minimum}),$._zod.check=(G)=>{let K=G.value;if(K.length>=U.minimum)return;let W=D6(K);G.issues.push({origin:W,code:"too_small",minimum:U.minimum,inclusive:!0,input:K,inst:$,continue:!U.abort})}}),G3=v("$ZodCheckLengthEquals",($,U)=>{var Q;a.init($,U),(Q=$._zod.def).when??(Q.when=(G)=>{let K=G.value;return!N1(K)&&K.length!==void 0}),$._zod.onattach.push((G)=>{let K=G._zod.bag;K.minimum=U.length,K.maximum=U.length,K.length=U.length}),$._zod.check=(G)=>{let K=G.value,J=K.length;if(J===U.length)return;let W=D6(K),q=J>U.length;G.issues.push({origin:W,...q?{code:"too_big",maximum:U.length}:{code:"too_small",minimum:U.length},inclusive:!0,exact:!0,input:G.value,inst:$,continue:!U.abort})}}),x4=v("$ZodCheckStringFormat",($,U)=>{var Q,G;if(a.init($,U),$._zod.onattach.push((K)=>{let J=K._zod.bag;if(J.format=U.format,U.pattern)J.patterns??(J.patterns=new Set),J.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(G=$._zod).check??(G.check=()=>{})}),J3=v("$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})}}),W3=v("$ZodCheckLowerCase",($,U)=>{U.pattern??(U.pattern=d8),x4.init($,U)}),q3=v("$ZodCheckUpperCase",($,U)=>{U.pattern??(U.pattern=p8),x4.init($,U)}),Y3=v("$ZodCheckIncludes",($,U)=>{a.init($,U);let Q=y$(U.includes),G=new RegExp(typeof U.position==="number"?`^.{${U.position}}${Q}`:Q);U.pattern=G,$._zod.onattach.push((K)=>{let J=K._zod.bag;J.patterns??(J.patterns=new Set),J.patterns.add(G)}),$._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})}}),j3=v("$ZodCheckStartsWith",($,U)=>{a.init($,U);let Q=new RegExp(`^${y$(U.prefix)}.*`);U.pattern??(U.pattern=Q),$._zod.onattach.push((G)=>{let K=G._zod.bag;K.patterns??(K.patterns=new Set),K.patterns.add(Q)}),$._zod.check=(G)=>{if(G.value.startsWith(U.prefix))return;G.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:U.prefix,input:G.value,inst:$,continue:!U.abort})}}),X3=v("$ZodCheckEndsWith",($,U)=>{a.init($,U);let Q=new RegExp(`.*${y$(U.suffix)}$`);U.pattern??(U.pattern=Q),$._zod.onattach.push((G)=>{let K=G._zod.bag;K.patterns??(K.patterns=new Set),K.patterns.add(Q)}),$._zod.check=(G)=>{if(G.value.endsWith(U.suffix))return;G.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:U.suffix,input:G.value,inst:$,continue:!U.abort})}});function Bq($,U,Q){if($.issues.length)U.issues.push(...O$(Q,$.issues))}var H3=v("$ZodCheckProperty",($,U)=>{a.init($,U),$._zod.check=(Q)=>{let G=U.schema._zod.run({value:Q.value[U.property],issues:[]},{});if(G instanceof Promise)return G.then((K)=>Bq(K,Q,U.property));Bq(G,Q,U.property);return}}),B3=v("$ZodCheckMimeType",($,U)=>{a.init($,U);let Q=new Set(U.mime);$._zod.onattach.push((G)=>{G._zod.bag.mime=U.mime}),$._zod.check=(G)=>{if(Q.has(G.value.type))return;G.issues.push({code:"invalid_value",values:U.mime,input:G.value.type,inst:$,continue:!U.abort})}}),M3=v("$ZodCheckOverwrite",($,U)=>{a.init($,U),$._zod.check=(Q)=>{Q.value=U.tx(Q.value)}});class E0{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((J)=>J),G=Math.min(...Q.map((J)=>J.length-J.trimStart().length)),K=Q.map((J)=>J.slice(G)).map((J)=>" ".repeat(this.indent*2)+J);for(let J of K)this.content.push(J)}compile(){let $=Function,U=this?.args,G=[...(this?.content??[""]).map((K)=>` ${K}`)];return new $(...U,G.join(`
58
- `))}}var Z3={major:4,minor:3,patch:6};var y=v("$ZodType",($,U)=>{var Q;$??($={}),$._zod.def=U,$._zod.bag=$._zod.bag||{},$._zod.version=Z3;let G=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))G.unshift($);for(let K of G)for(let J of K._zod.onattach)J($);if(G.length===0)(Q=$._zod).deferred??(Q.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let K=(W,q,j)=>{let X=k1(W),B;for(let Z of q){if(Z._zod.def.when){if(!Z._zod.def.when(W))continue}else if(X)continue;let V=W.issues.length,N=Z._zod.check(W);if(N instanceof Promise&&j?.async===!1)throw new a$;if(B||N instanceof Promise)B=(B??Promise.resolve()).then(async()=>{if(await N,W.issues.length===V)return;if(!X)X=k1(W,V)});else{if(W.issues.length===V)continue;if(!X)X=k1(W,V)}}if(B)return B.then(()=>{return W});return W},J=(W,q,j)=>{if(k1(W))return W.aborted=!0,W;let X=K(q,G,j);if(X instanceof Promise){if(j.async===!1)throw new a$;return X.then((B)=>$._zod.parse(B,j))}return $._zod.parse(X,j)};$._zod.run=(W,q)=>{if(q.skipChecks)return $._zod.parse(W,q);if(q.direction==="backward"){let X=$._zod.parse({value:W.value,issues:[]},{...q,skipChecks:!0});if(X instanceof Promise)return X.then((B)=>{return J(B,W,q)});return J(X,W,q)}let j=$._zod.parse(W,q);if(j instanceof Promise){if(q.async===!1)throw new a$;return j.then((X)=>K(X,G,q))}return K(j,G,q)}}h($,"~standard",()=>({validate:(K)=>{try{let J=N8($,K);return J.success?{value:J.data}:{issues:J.error?.issues}}catch(J){return _8($,K).then((W)=>W.success?{value:W.data}:{issues:W.error?.issues})}},vendor:"zod",version:1}))}),t1=v("$ZodString",($,U)=>{y.init($,U),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??c8($._zod.bag),$._zod.parse=(Q,G)=>{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}}),p=v("$ZodStringFormat",($,U)=>{x4.init($,U),t1.init($,U)}),v3=v("$ZodGUID",($,U)=>{U.pattern??(U.pattern=A8),p.init($,U)}),D3=v("$ZodUUID",($,U)=>{if(U.version){let G={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[U.version];if(G===void 0)throw Error(`Invalid UUID version: "${U.version}"`);U.pattern??(U.pattern=p1(G))}else U.pattern??(U.pattern=p1());p.init($,U)}),P3=v("$ZodEmail",($,U)=>{U.pattern??(U.pattern=O8),p.init($,U)}),I3=v("$ZodURL",($,U)=>{p.init($,U),$._zod.check=(Q)=>{try{let G=Q.value.trim(),K=new URL(G);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=G;return}catch(G){Q.issues.push({code:"invalid_format",format:"url",input:Q.value,inst:$,continue:!U.abort})}}}),N3=v("$ZodEmoji",($,U)=>{U.pattern??(U.pattern=R8()),p.init($,U)}),_3=v("$ZodNanoID",($,U)=>{U.pattern??(U.pattern=z8),p.init($,U)}),w3=v("$ZodCUID",($,U)=>{U.pattern??(U.pattern=w8),p.init($,U)}),k3=v("$ZodCUID2",($,U)=>{U.pattern??(U.pattern=k8),p.init($,U)}),x3=v("$ZodULID",($,U)=>{U.pattern??(U.pattern=x8),p.init($,U)}),F3=v("$ZodXID",($,U)=>{U.pattern??(U.pattern=F8),p.init($,U)}),L3=v("$ZodKSUID",($,U)=>{U.pattern??(U.pattern=L8),p.init($,U)}),z3=v("$ZodISODateTime",($,U)=>{U.pattern??(U.pattern=h8(U)),p.init($,U)}),b3=v("$ZodISODate",($,U)=>{U.pattern??(U.pattern=f8),p.init($,U)}),A3=v("$ZodISOTime",($,U)=>{U.pattern??(U.pattern=m8(U)),p.init($,U)}),O3=v("$ZodISODuration",($,U)=>{U.pattern??(U.pattern=b8),p.init($,U)}),R3=v("$ZodIPv4",($,U)=>{U.pattern??(U.pattern=T8),p.init($,U),$._zod.bag.format="ipv4"}),T3=v("$ZodIPv6",($,U)=>{U.pattern??(U.pattern=S8),p.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})}}}),S3=v("$ZodMAC",($,U)=>{U.pattern??(U.pattern=C8(U.delimiter)),p.init($,U),$._zod.bag.format="mac"}),C3=v("$ZodCIDRv4",($,U)=>{U.pattern??(U.pattern=g8),p.init($,U)}),g3=v("$ZodCIDRv6",($,U)=>{U.pattern??(U.pattern=E8),p.init($,U),$._zod.check=(Q)=>{let G=Q.value.split("/");try{if(G.length!==2)throw Error();let[K,J]=G;if(!J)throw Error();let W=Number(J);if(`${W}`!==J)throw Error();if(W<0||W>128)throw Error();new URL(`http://[${K}]`)}catch{Q.issues.push({code:"invalid_format",format:"cidrv6",input:Q.value,inst:$,continue:!U.abort})}}});function E3($){if($==="")return!0;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}var y3=v("$ZodBase64",($,U)=>{U.pattern??(U.pattern=y8),p.init($,U),$._zod.bag.contentEncoding="base64",$._zod.check=(Q)=>{if(E3(Q.value))return;Q.issues.push({code:"invalid_format",format:"base64",input:Q.value,inst:$,continue:!U.abort})}});function Lq($){if(!S0.test($))return!1;let U=$.replace(/[-_]/g,(G)=>G==="-"?"+":"/"),Q=U.padEnd(Math.ceil(U.length/4)*4,"=");return E3(Q)}var u3=v("$ZodBase64URL",($,U)=>{U.pattern??(U.pattern=S0),p.init($,U),$._zod.bag.contentEncoding="base64url",$._zod.check=(Q)=>{if(Lq(Q.value))return;Q.issues.push({code:"invalid_format",format:"base64url",input:Q.value,inst:$,continue:!U.abort})}}),f3=v("$ZodE164",($,U)=>{U.pattern??(U.pattern=u8),p.init($,U)});function zq($,U=null){try{let Q=$.split(".");if(Q.length!==3)return!1;let[G]=Q;if(!G)return!1;let K=JSON.parse(atob(G));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 m3=v("$ZodJWT",($,U)=>{p.init($,U),$._zod.check=(Q)=>{if(zq(Q.value,U.alg))return;Q.issues.push({code:"invalid_format",format:"jwt",input:Q.value,inst:$,continue:!U.abort})}}),h3=v("$ZodCustomStringFormat",($,U)=>{p.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})}}),c0=v("$ZodNumber",($,U)=>{y.init($,U),$._zod.pattern=$._zod.bag.pattern??_6,$._zod.parse=(Q,G)=>{if(U.coerce)try{Q.value=Number(Q.value)}catch(W){}let K=Q.value;if(typeof K==="number"&&!Number.isNaN(K)&&Number.isFinite(K))return Q;let J=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:$,...J?{received:J}:{}}),Q}}),c3=v("$ZodNumberFormat",($,U)=>{a8.init($,U),c0.init($,U)}),x6=v("$ZodBoolean",($,U)=>{y.init($,U),$._zod.pattern=n8,$._zod.parse=(Q,G)=>{if(U.coerce)try{Q.value=Boolean(Q.value)}catch(J){}let K=Q.value;if(typeof K==="boolean")return Q;return Q.issues.push({expected:"boolean",code:"invalid_type",input:K,inst:$}),Q}}),l0=v("$ZodBigInt",($,U)=>{y.init($,U),$._zod.pattern=l8,$._zod.parse=(Q,G)=>{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}}),l3=v("$ZodBigIntFormat",($,U)=>{e8.init($,U),l0.init($,U)}),r3=v("$ZodSymbol",($,U)=>{y.init($,U),$._zod.parse=(Q,G)=>{let K=Q.value;if(typeof K==="symbol")return Q;return Q.issues.push({expected:"symbol",code:"invalid_type",input:K,inst:$}),Q}}),n3=v("$ZodUndefined",($,U)=>{y.init($,U),$._zod.pattern=o8,$._zod.values=new Set([void 0]),$._zod.optin="optional",$._zod.optout="optional",$._zod.parse=(Q,G)=>{let K=Q.value;if(typeof K>"u")return Q;return Q.issues.push({expected:"undefined",code:"invalid_type",input:K,inst:$}),Q}}),i3=v("$ZodNull",($,U)=>{y.init($,U),$._zod.pattern=i8,$._zod.values=new Set([null]),$._zod.parse=(Q,G)=>{let K=Q.value;if(K===null)return Q;return Q.issues.push({expected:"null",code:"invalid_type",input:K,inst:$}),Q}}),o3=v("$ZodAny",($,U)=>{y.init($,U),$._zod.parse=(Q)=>Q}),d3=v("$ZodUnknown",($,U)=>{y.init($,U),$._zod.parse=(Q)=>Q}),p3=v("$ZodNever",($,U)=>{y.init($,U),$._zod.parse=(Q,G)=>{return Q.issues.push({expected:"never",code:"invalid_type",input:Q.value,inst:$}),Q}}),t3=v("$ZodVoid",($,U)=>{y.init($,U),$._zod.parse=(Q,G)=>{let K=Q.value;if(typeof K>"u")return Q;return Q.issues.push({expected:"void",code:"invalid_type",input:K,inst:$}),Q}}),a3=v("$ZodDate",($,U)=>{y.init($,U),$._zod.parse=(Q,G)=>{if(U.coerce)try{Q.value=new Date(Q.value)}catch(q){}let K=Q.value,J=K instanceof Date;if(J&&!Number.isNaN(K.getTime()))return Q;return Q.issues.push({expected:"date",code:"invalid_type",input:K,...J?{received:"Invalid Date"}:{},inst:$}),Q}});function Vq($,U,Q){if($.issues.length)U.issues.push(...O$(Q,$.issues));U.value[Q]=$.value}var e3=v("$ZodArray",($,U)=>{y.init($,U),$._zod.parse=(Q,G)=>{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 J=[];for(let W=0;W<K.length;W++){let q=K[W],j=U.element._zod.run({value:q,issues:[]},G);if(j instanceof Promise)J.push(j.then((X)=>Vq(X,Q,W)));else Vq(j,Q,W)}if(J.length)return Promise.all(J).then(()=>Q);return Q}});function h0($,U,Q,G,K){if($.issues.length){if(K&&!(Q in G))return;U.issues.push(...O$(Q,$.issues))}if($.value===void 0){if(Q in G)U.value[Q]=void 0}else U.value[Q]=$.value}function bq($){let U=Object.keys($.shape);for(let G of U)if(!$.shape?.[G]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${G}": expected a Zod schema`);let Q=V8($.shape);return{...$,keys:U,keySet:new Set(U),numKeys:U.length,optionalKeys:new Set(Q)}}function Aq($,U,Q,G,K,J){let W=[],q=K.keySet,j=K.catchall._zod,X=j.def.type,B=j.optout==="optional";for(let Z in U){if(q.has(Z))continue;if(X==="never"){W.push(Z);continue}let V=j.run({value:U[Z],issues:[]},G);if(V instanceof Promise)$.push(V.then((N)=>h0(N,Q,Z,U,B)));else h0(V,Q,Z,U,B)}if(W.length)Q.issues.push({code:"unrecognized_keys",keys:W,input:U,inst:J});if(!$.length)return Q;return Promise.all($).then(()=>{return Q})}var Oq=v("$ZodObject",($,U)=>{if(y.init($,U),!Object.getOwnPropertyDescriptor(U,"shape")?.get){let q=U.shape;Object.defineProperty(U,"shape",{get:()=>{let j={...q};return Object.defineProperty(U,"shape",{value:j}),j}})}let G=P4(()=>bq(U));h($._zod,"propValues",()=>{let q=U.shape,j={};for(let X in q){let B=q[X]._zod;if(B.values){j[X]??(j[X]=new Set);for(let Z of B.values)j[X].add(Z)}}return j});let K=d1,J=U.catchall,W;$._zod.parse=(q,j)=>{W??(W=G.value);let X=q.value;if(!K(X))return q.issues.push({expected:"object",code:"invalid_type",input:X,inst:$}),q;q.value={};let B=[],Z=W.shape;for(let V of W.keys){let N=Z[V],T=N._zod.optout==="optional",f=N._zod.run({value:X[V],issues:[]},j);if(f instanceof Promise)B.push(f.then((e)=>h0(e,q,V,X,T)));else h0(f,q,V,X,T)}if(!J)return B.length?Promise.all(B).then(()=>q):q;return Aq(B,X,q,j,G.value,$)}}),s3=v("$ZodObjectJIT",($,U)=>{Oq.init($,U);let Q=$._zod.parse,G=P4(()=>bq(U)),K=(V)=>{let N=new E0(["shape","payload","ctx"]),T=G.value,f=(C$)=>{let x$=_0(C$);return`shape[${x$}]._zod.run({ value: input[${x$}], issues: [] }, ctx)`};N.write("const input = payload.value;");let e=Object.create(null),k$=0;for(let C$ of T.keys)e[C$]=`key_${k$++}`;N.write("const newResult = {};");for(let C$ of T.keys){let x$=e[C$],l$=_0(C$),eH=V[C$]?._zod?.optout==="optional";if(N.write(`const ${x$} = ${f(C$)};`),eH)N.write(`
59
- if (${x$}.issues.length) {
60
- if (${l$} in input) {
61
- payload.issues = payload.issues.concat(${x$}.issues.map(iss => ({
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 => ({
62
62
  ...iss,
63
- path: iss.path ? [${l$}, ...iss.path] : [${l$}]
63
+ path: iss.path ? [${i$}, ...iss.path] : [${i$}]
64
64
  })));
65
65
  }
66
66
  }
67
67
 
68
- if (${x$}.value === undefined) {
69
- if (${l$} in input) {
70
- newResult[${l$}] = undefined;
68
+ if (${A$}.value === undefined) {
69
+ if (${i$} in input) {
70
+ newResult[${i$}] = undefined;
71
71
  }
72
72
  } else {
73
- newResult[${l$}] = ${x$}.value;
73
+ newResult[${i$}] = ${A$}.value;
74
74
  }
75
75
 
76
- `);else N.write(`
77
- if (${x$}.issues.length) {
78
- payload.issues = payload.issues.concat(${x$}.issues.map(iss => ({
76
+ `);else L.write(`
77
+ if (${A$}.issues.length) {
78
+ payload.issues = payload.issues.concat(${A$}.issues.map(iss => ({
79
79
  ...iss,
80
- path: iss.path ? [${l$}, ...iss.path] : [${l$}]
80
+ path: iss.path ? [${i$}, ...iss.path] : [${i$}]
81
81
  })));
82
82
  }
83
83
 
84
- if (${x$}.value === undefined) {
85
- if (${l$} in input) {
86
- newResult[${l$}] = undefined;
84
+ if (${A$}.value === undefined) {
85
+ if (${i$} in input) {
86
+ newResult[${i$}] = undefined;
87
87
  }
88
88
  } else {
89
- newResult[${l$}] = ${x$}.value;
89
+ newResult[${i$}] = ${A$}.value;
90
90
  }
91
91
 
92
- `)}N.write("payload.value = newResult;"),N.write("return payload;");let j4=N.compile();return(C$,x$)=>j4(V,C$,x$)},J,W=d1,q=!H6.jitless,X=q&&B8.value,B=U.catchall,Z;$._zod.parse=(V,N)=>{Z??(Z=G.value);let T=V.value;if(!W(T))return V.issues.push({expected:"object",code:"invalid_type",input:T,inst:$}),V;if(q&&X&&N?.async===!1&&N.jitless!==!0){if(!J)J=K(U.shape);if(V=J(V,N),!B)return V;return Aq([],T,V,N,Z,$)}return Q(V,N)}});function vq($,U,Q,G){for(let J of $)if(J.issues.length===0)return U.value=J.value,U;let K=$.filter((J)=>!k1(J));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((J)=>J.issues.map((W)=>F$(W,G,W$())))}),U}var F6=v("$ZodUnion",($,U)=>{y.init($,U),h($._zod,"optin",()=>U.options.some((K)=>K._zod.optin==="optional")?"optional":void 0),h($._zod,"optout",()=>U.options.some((K)=>K._zod.optout==="optional")?"optional":void 0),h($._zod,"values",()=>{if(U.options.every((K)=>K._zod.values))return new Set(U.options.flatMap((K)=>Array.from(K._zod.values)));return}),h($._zod,"pattern",()=>{if(U.options.every((K)=>K._zod.pattern)){let K=U.options.map((J)=>J._zod.pattern);return new RegExp(`^(${K.map((J)=>Z6(J.source)).join("|")})$`)}return});let Q=U.options.length===1,G=U.options[0]._zod.run;$._zod.parse=(K,J)=>{if(Q)return G(K,J);let W=!1,q=[];for(let j of U.options){let X=j._zod.run({value:K.value,issues:[]},J);if(X instanceof Promise)q.push(X),W=!0;else{if(X.issues.length===0)return X;q.push(X)}}if(!W)return vq(q,K,$,J);return Promise.all(q).then((j)=>{return vq(j,K,$,J)})}});function Dq($,U,Q,G){let K=$.filter((J)=>J.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((J)=>J.issues.map((W)=>F$(W,G,W$())))});else U.issues.push({code:"invalid_union",input:U.value,inst:Q,errors:[],inclusive:!1});return U}var $9=v("$ZodXor",($,U)=>{F6.init($,U),U.inclusive=!1;let Q=U.options.length===1,G=U.options[0]._zod.run;$._zod.parse=(K,J)=>{if(Q)return G(K,J);let W=!1,q=[];for(let j of U.options){let X=j._zod.run({value:K.value,issues:[]},J);if(X instanceof Promise)q.push(X),W=!0;else q.push(X)}if(!W)return Dq(q,K,$,J);return Promise.all(q).then((j)=>{return Dq(j,K,$,J)})}}),U9=v("$ZodDiscriminatedUnion",($,U)=>{U.inclusive=!1,F6.init($,U);let Q=$._zod.parse;h($._zod,"propValues",()=>{let K={};for(let J of U.options){let W=J._zod.propValues;if(!W||Object.keys(W).length===0)throw Error(`Invalid discriminated union option at index "${U.options.indexOf(J)}"`);for(let[q,j]of Object.entries(W)){if(!K[q])K[q]=new Set;for(let X of j)K[q].add(X)}}return K});let G=P4(()=>{let K=U.options,J=new Map;for(let W of K){let q=W._zod.propValues?.[U.discriminator];if(!q||q.size===0)throw Error(`Invalid discriminated union option at index "${U.options.indexOf(W)}"`);for(let j of q){if(J.has(j))throw Error(`Duplicate discriminator value "${String(j)}"`);J.set(j,W)}}return J});$._zod.parse=(K,J)=>{let W=K.value;if(!d1(W))return K.issues.push({code:"invalid_type",expected:"object",input:W,inst:$}),K;let q=G.value.get(W?.[U.discriminator]);if(q)return q._zod.run(K,J);if(U.unionFallback)return Q(K,J);return K.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:U.discriminator,input:W,path:[U.discriminator],inst:$}),K}}),K9=v("$ZodIntersection",($,U)=>{y.init($,U),$._zod.parse=(Q,G)=>{let K=Q.value,J=U.left._zod.run({value:K,issues:[]},G),W=U.right._zod.run({value:K,issues:[]},G);if(J instanceof Promise||W instanceof Promise)return Promise.all([J,W]).then(([j,X])=>{return Pq(Q,j,X)});return Pq(Q,J,W)}});function V3($,U){if($===U)return{valid:!0,data:$};if($ instanceof Date&&U instanceof Date&&+$===+U)return{valid:!0,data:$};if(w1($)&&w1(U)){let Q=Object.keys(U),G=Object.keys($).filter((J)=>Q.indexOf(J)!==-1),K={...$,...U};for(let J of G){let W=V3($[J],U[J]);if(!W.valid)return{valid:!1,mergeErrorPath:[J,...W.mergeErrorPath]};K[J]=W.data}return{valid:!0,data:K}}if(Array.isArray($)&&Array.isArray(U)){if($.length!==U.length)return{valid:!1,mergeErrorPath:[]};let Q=[];for(let G=0;G<$.length;G++){let K=$[G],J=U[G],W=V3(K,J);if(!W.valid)return{valid:!1,mergeErrorPath:[G,...W.mergeErrorPath]};Q.push(W.data)}return{valid:!0,data:Q}}return{valid:!1,mergeErrorPath:[]}}function Pq($,U,Q){let G=new Map,K;for(let q of U.issues)if(q.code==="unrecognized_keys"){K??(K=q);for(let j of q.keys){if(!G.has(j))G.set(j,{});G.get(j).l=!0}}else $.issues.push(q);for(let q of Q.issues)if(q.code==="unrecognized_keys")for(let j of q.keys){if(!G.has(j))G.set(j,{});G.get(j).r=!0}else $.issues.push(q);let J=[...G].filter(([,q])=>q.l&&q.r).map(([q])=>q);if(J.length&&K)$.issues.push({...K,keys:J});if(k1($))return $;let W=V3(U.value,Q.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return $.value=W.data,$}var r0=v("$ZodTuple",($,U)=>{y.init($,U);let Q=U.items;$._zod.parse=(G,K)=>{let J=G.value;if(!Array.isArray(J))return G.issues.push({input:J,inst:$,expected:"tuple",code:"invalid_type"}),G;G.value=[];let W=[],q=[...Q].reverse().findIndex((B)=>B._zod.optin!=="optional"),j=q===-1?0:Q.length-q;if(!U.rest){let B=J.length>Q.length,Z=J.length<j-1;if(B||Z)return G.issues.push({...B?{code:"too_big",maximum:Q.length,inclusive:!0}:{code:"too_small",minimum:Q.length},input:J,inst:$,origin:"array"}),G}let X=-1;for(let B of Q){if(X++,X>=J.length){if(X>=j)continue}let Z=B._zod.run({value:J[X],issues:[]},K);if(Z instanceof Promise)W.push(Z.then((V)=>y0(V,G,X)));else y0(Z,G,X)}if(U.rest){let B=J.slice(Q.length);for(let Z of B){X++;let V=U.rest._zod.run({value:Z,issues:[]},K);if(V instanceof Promise)W.push(V.then((N)=>y0(N,G,X)));else y0(V,G,X)}}if(W.length)return Promise.all(W).then(()=>G);return G}});function y0($,U,Q){if($.issues.length)U.issues.push(...O$(Q,$.issues));U.value[Q]=$.value}var Q9=v("$ZodRecord",($,U)=>{y.init($,U),$._zod.parse=(Q,G)=>{let K=Q.value;if(!w1(K))return Q.issues.push({expected:"record",code:"invalid_type",input:K,inst:$}),Q;let J=[],W=U.keyType._zod.values;if(W){Q.value={};let q=new Set;for(let X of W)if(typeof X==="string"||typeof X==="number"||typeof X==="symbol"){q.add(typeof X==="number"?X.toString():X);let B=U.valueType._zod.run({value:K[X],issues:[]},G);if(B instanceof Promise)J.push(B.then((Z)=>{if(Z.issues.length)Q.issues.push(...O$(X,Z.issues));Q.value[X]=Z.value}));else{if(B.issues.length)Q.issues.push(...O$(X,B.issues));Q.value[X]=B.value}}let j;for(let X in K)if(!q.has(X))j=j??[],j.push(X);if(j&&j.length>0)Q.issues.push({code:"unrecognized_keys",input:K,inst:$,keys:j})}else{Q.value={};for(let q of Reflect.ownKeys(K)){if(q==="__proto__")continue;let j=U.keyType._zod.run({value:q,issues:[]},G);if(j instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof q==="string"&&_6.test(q)&&j.issues.length){let Z=U.keyType._zod.run({value:Number(q),issues:[]},G);if(Z instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(Z.issues.length===0)j=Z}if(j.issues.length){if(U.mode==="loose")Q.value[q]=K[q];else Q.issues.push({code:"invalid_key",origin:"record",issues:j.issues.map((Z)=>F$(Z,G,W$())),input:q,path:[q],inst:$});continue}let B=U.valueType._zod.run({value:K[q],issues:[]},G);if(B instanceof Promise)J.push(B.then((Z)=>{if(Z.issues.length)Q.issues.push(...O$(q,Z.issues));Q.value[j.value]=Z.value}));else{if(B.issues.length)Q.issues.push(...O$(q,B.issues));Q.value[j.value]=B.value}}}if(J.length)return Promise.all(J).then(()=>Q);return Q}}),G9=v("$ZodMap",($,U)=>{y.init($,U),$._zod.parse=(Q,G)=>{let K=Q.value;if(!(K instanceof Map))return Q.issues.push({expected:"map",code:"invalid_type",input:K,inst:$}),Q;let J=[];Q.value=new Map;for(let[W,q]of K){let j=U.keyType._zod.run({value:W,issues:[]},G),X=U.valueType._zod.run({value:q,issues:[]},G);if(j instanceof Promise||X instanceof Promise)J.push(Promise.all([j,X]).then(([B,Z])=>{Iq(B,Z,Q,W,K,$,G)}));else Iq(j,X,Q,W,K,$,G)}if(J.length)return Promise.all(J).then(()=>Q);return Q}});function Iq($,U,Q,G,K,J,W){if($.issues.length)if(V6.has(typeof G))Q.issues.push(...O$(G,$.issues));else Q.issues.push({code:"invalid_key",origin:"map",input:K,inst:J,issues:$.issues.map((q)=>F$(q,W,W$()))});if(U.issues.length)if(V6.has(typeof G))Q.issues.push(...O$(G,U.issues));else Q.issues.push({origin:"map",code:"invalid_element",input:K,inst:J,key:G,issues:U.issues.map((q)=>F$(q,W,W$()))});Q.value.set($.value,U.value)}var J9=v("$ZodSet",($,U)=>{y.init($,U),$._zod.parse=(Q,G)=>{let K=Q.value;if(!(K instanceof Set))return Q.issues.push({input:K,inst:$,expected:"set",code:"invalid_type"}),Q;let J=[];Q.value=new Set;for(let W of K){let q=U.valueType._zod.run({value:W,issues:[]},G);if(q instanceof Promise)J.push(q.then((j)=>Nq(j,Q)));else Nq(q,Q)}if(J.length)return Promise.all(J).then(()=>Q);return Q}});function Nq($,U){if($.issues.length)U.issues.push(...$.issues);U.value.add($.value)}var W9=v("$ZodEnum",($,U)=>{y.init($,U);let Q=M6(U.entries),G=new Set(Q);$._zod.values=G,$._zod.pattern=new RegExp(`^(${Q.filter((K)=>V6.has(typeof K)).map((K)=>typeof K==="string"?y$(K):K.toString()).join("|")})$`),$._zod.parse=(K,J)=>{let W=K.value;if(G.has(W))return K;return K.issues.push({code:"invalid_value",values:Q,input:W,inst:$}),K}}),q9=v("$ZodLiteral",($,U)=>{if(y.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((G)=>typeof G==="string"?y$(G):G?y$(G.toString()):String(G)).join("|")})$`),$._zod.parse=(G,K)=>{let J=G.value;if(Q.has(J))return G;return G.issues.push({code:"invalid_value",values:U.values,input:J,inst:$}),G}}),Y9=v("$ZodFile",($,U)=>{y.init($,U),$._zod.parse=(Q,G)=>{let K=Q.value;if(K instanceof File)return Q;return Q.issues.push({expected:"file",code:"invalid_type",input:K,inst:$}),Q}}),j9=v("$ZodTransform",($,U)=>{y.init($,U),$._zod.parse=(Q,G)=>{if(G.direction==="backward")throw new o1($.constructor.name);let K=U.transform(Q.value,Q);if(G.async)return(K instanceof Promise?K:Promise.resolve(K)).then((W)=>{return Q.value=W,Q});if(K instanceof Promise)throw new a$;return Q.value=K,Q}});function _q($,U){if($.issues.length&&U===void 0)return{issues:[],value:void 0};return $}var n0=v("$ZodOptional",($,U)=>{y.init($,U),$._zod.optin="optional",$._zod.optout="optional",h($._zod,"values",()=>{return U.innerType._zod.values?new Set([...U.innerType._zod.values,void 0]):void 0}),h($._zod,"pattern",()=>{let Q=U.innerType._zod.pattern;return Q?new RegExp(`^(${Z6(Q.source)})?$`):void 0}),$._zod.parse=(Q,G)=>{if(U.innerType._zod.optin==="optional"){let K=U.innerType._zod.run(Q,G);if(K instanceof Promise)return K.then((J)=>_q(J,Q.value));return _q(K,Q.value)}if(Q.value===void 0)return Q;return U.innerType._zod.run(Q,G)}}),X9=v("$ZodExactOptional",($,U)=>{n0.init($,U),h($._zod,"values",()=>U.innerType._zod.values),h($._zod,"pattern",()=>U.innerType._zod.pattern),$._zod.parse=(Q,G)=>{return U.innerType._zod.run(Q,G)}}),H9=v("$ZodNullable",($,U)=>{y.init($,U),h($._zod,"optin",()=>U.innerType._zod.optin),h($._zod,"optout",()=>U.innerType._zod.optout),h($._zod,"pattern",()=>{let Q=U.innerType._zod.pattern;return Q?new RegExp(`^(${Z6(Q.source)}|null)$`):void 0}),h($._zod,"values",()=>{return U.innerType._zod.values?new Set([...U.innerType._zod.values,null]):void 0}),$._zod.parse=(Q,G)=>{if(Q.value===null)return Q;return U.innerType._zod.run(Q,G)}}),B9=v("$ZodDefault",($,U)=>{y.init($,U),$._zod.optin="optional",h($._zod,"values",()=>U.innerType._zod.values),$._zod.parse=(Q,G)=>{if(G.direction==="backward")return U.innerType._zod.run(Q,G);if(Q.value===void 0)return Q.value=U.defaultValue,Q;let K=U.innerType._zod.run(Q,G);if(K instanceof Promise)return K.then((J)=>wq(J,U));return wq(K,U)}});function wq($,U){if($.value===void 0)$.value=U.defaultValue;return $}var M9=v("$ZodPrefault",($,U)=>{y.init($,U),$._zod.optin="optional",h($._zod,"values",()=>U.innerType._zod.values),$._zod.parse=(Q,G)=>{if(G.direction==="backward")return U.innerType._zod.run(Q,G);if(Q.value===void 0)Q.value=U.defaultValue;return U.innerType._zod.run(Q,G)}}),Z9=v("$ZodNonOptional",($,U)=>{y.init($,U),h($._zod,"values",()=>{let Q=U.innerType._zod.values;return Q?new Set([...Q].filter((G)=>G!==void 0)):void 0}),$._zod.parse=(Q,G)=>{let K=U.innerType._zod.run(Q,G);if(K instanceof Promise)return K.then((J)=>kq(J,$));return kq(K,$)}});function kq($,U){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:U});return $}var V9=v("$ZodSuccess",($,U)=>{y.init($,U),$._zod.parse=(Q,G)=>{if(G.direction==="backward")throw new o1("ZodSuccess");let K=U.innerType._zod.run(Q,G);if(K instanceof Promise)return K.then((J)=>{return Q.value=J.issues.length===0,Q});return Q.value=K.issues.length===0,Q}}),v9=v("$ZodCatch",($,U)=>{y.init($,U),h($._zod,"optin",()=>U.innerType._zod.optin),h($._zod,"optout",()=>U.innerType._zod.optout),h($._zod,"values",()=>U.innerType._zod.values),$._zod.parse=(Q,G)=>{if(G.direction==="backward")return U.innerType._zod.run(Q,G);let K=U.innerType._zod.run(Q,G);if(K instanceof Promise)return K.then((J)=>{if(Q.value=J.value,J.issues.length)Q.value=U.catchValue({...Q,error:{issues:J.issues.map((W)=>F$(W,G,W$()))},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((J)=>F$(J,G,W$()))},input:Q.value}),Q.issues=[];return Q}}),D9=v("$ZodNaN",($,U)=>{y.init($,U),$._zod.parse=(Q,G)=>{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}}),P9=v("$ZodPipe",($,U)=>{y.init($,U),h($._zod,"values",()=>U.in._zod.values),h($._zod,"optin",()=>U.in._zod.optin),h($._zod,"optout",()=>U.out._zod.optout),h($._zod,"propValues",()=>U.in._zod.propValues),$._zod.parse=(Q,G)=>{if(G.direction==="backward"){let J=U.out._zod.run(Q,G);if(J instanceof Promise)return J.then((W)=>u0(W,U.in,G));return u0(J,U.in,G)}let K=U.in._zod.run(Q,G);if(K instanceof Promise)return K.then((J)=>u0(J,U.out,G));return u0(K,U.out,G)}});function u0($,U,Q){if($.issues.length)return $.aborted=!0,$;return U._zod.run({value:$.value,issues:$.issues},Q)}var L6=v("$ZodCodec",($,U)=>{y.init($,U),h($._zod,"values",()=>U.in._zod.values),h($._zod,"optin",()=>U.in._zod.optin),h($._zod,"optout",()=>U.out._zod.optout),h($._zod,"propValues",()=>U.in._zod.propValues),$._zod.parse=(Q,G)=>{if((G.direction||"forward")==="forward"){let J=U.in._zod.run(Q,G);if(J instanceof Promise)return J.then((W)=>f0(W,U,G));return f0(J,U,G)}else{let J=U.out._zod.run(Q,G);if(J instanceof Promise)return J.then((W)=>f0(W,U,G));return f0(J,U,G)}}});function f0($,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((J)=>m0($,J,U.out,Q));return m0($,K,U.out,Q)}else{let K=U.reverseTransform($.value,$);if(K instanceof Promise)return K.then((J)=>m0($,J,U.in,Q));return m0($,K,U.in,Q)}}function m0($,U,Q,G){if($.issues.length)return $.aborted=!0,$;return Q._zod.run({value:U,issues:$.issues},G)}var I9=v("$ZodReadonly",($,U)=>{y.init($,U),h($._zod,"propValues",()=>U.innerType._zod.propValues),h($._zod,"values",()=>U.innerType._zod.values),h($._zod,"optin",()=>U.innerType?._zod?.optin),h($._zod,"optout",()=>U.innerType?._zod?.optout),$._zod.parse=(Q,G)=>{if(G.direction==="backward")return U.innerType._zod.run(Q,G);let K=U.innerType._zod.run(Q,G);if(K instanceof Promise)return K.then(xq);return xq(K)}});function xq($){return $.value=Object.freeze($.value),$}var N9=v("$ZodTemplateLiteral",($,U)=>{y.init($,U);let Q=[];for(let G of U.parts)if(typeof G==="object"&&G!==null){if(!G._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...G._zod.traits].shift()}`);let K=G._zod.pattern instanceof RegExp?G._zod.pattern.source:G._zod.pattern;if(!K)throw Error(`Invalid template literal part: ${G._zod.traits}`);let J=K.startsWith("^")?1:0,W=K.endsWith("$")?K.length-1:K.length;Q.push(K.slice(J,W))}else if(G===null||Z8.has(typeof G))Q.push(y$(`${G}`));else throw Error(`Invalid template literal part: ${G}`);$._zod.pattern=new RegExp(`^${Q.join("")}$`),$._zod.parse=(G,K)=>{if(typeof G.value!=="string")return G.issues.push({input:G.value,inst:$,expected:"string",code:"invalid_type"}),G;if($._zod.pattern.lastIndex=0,!$._zod.pattern.test(G.value))return G.issues.push({input:G.value,inst:$,code:"invalid_format",format:U.format??"template_literal",pattern:$._zod.pattern.source}),G;return G}}),_9=v("$ZodFunction",($,U)=>{return y.init($,U),$._def=U,$._zod.def=U,$.implement=(Q)=>{if(typeof Q!=="function")throw Error("implement() must be called with a function");return function(...G){let K=$._def.input?k0($._def.input,G):G,J=Reflect.apply(Q,this,K);if($._def.output)return k0($._def.output,J);return J}},$.implementAsync=(Q)=>{if(typeof Q!=="function")throw Error("implementAsync() must be called with a function");return async function(...G){let K=$._def.input?await x0($._def.input,G):G,J=await Reflect.apply(Q,this,K);if($._def.output)return await x0($._def.output,J);return J}},$._zod.parse=(Q,G)=>{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 G=$.constructor;if(Array.isArray(Q[0]))return new G({type:"function",input:new r0({type:"tuple",items:Q[0],rest:Q[1]}),output:$._def.output});return new G({type:"function",input:Q[0],output:$._def.output})},$.output=(Q)=>{return new $.constructor({type:"function",input:$._def.input,output:Q})},$}),w9=v("$ZodPromise",($,U)=>{y.init($,U),$._zod.parse=(Q,G)=>{return Promise.resolve(Q.value).then((K)=>U.innerType._zod.run({value:K,issues:[]},G))}}),k9=v("$ZodLazy",($,U)=>{y.init($,U),h($._zod,"innerType",()=>U.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=(Q,G)=>{return $._zod.innerType._zod.run(Q,G)}}),x9=v("$ZodCustom",($,U)=>{a.init($,U),y.init($,U),$._zod.parse=(Q,G)=>{return Q},$._zod.check=(Q)=>{let G=Q.value,K=U.fn(G);if(K instanceof Promise)return K.then((J)=>Fq(J,Q,G,$));Fq(K,Q,G,$);return}});function Fq($,U,Q,G){if(!$){let K={code:"custom",input:Q,inst:G,path:[...G._zod.def.path??[]],continue:!G._zod.def.abort};if(G._zod.def.params)K.params=G._zod.def.params;U.issues.push(I4(K))}}var R6={};K1(R6,{zhTW:()=>V7,zhCN:()=>Z7,yo:()=>v7,vi:()=>M7,uz:()=>B7,ur:()=>H7,uk:()=>O6,ua:()=>X7,tr:()=>j7,th:()=>Y7,ta:()=>q7,sv:()=>W7,sl:()=>J7,ru:()=>G7,pt:()=>Q7,ps:()=>U7,pl:()=>K7,ota:()=>$7,no:()=>s9,nl:()=>e9,ms:()=>a9,mk:()=>t9,lt:()=>p9,ko:()=>d9,km:()=>b6,kh:()=>o9,ka:()=>i9,ja:()=>n9,it:()=>r9,is:()=>l9,id:()=>c9,hy:()=>h9,hu:()=>m9,he:()=>f9,frCA:()=>u9,fr:()=>y9,fi:()=>E9,fa:()=>g9,es:()=>C9,eo:()=>S9,en:()=>z6,de:()=>T9,da:()=>R9,cs:()=>O9,ca:()=>A9,bg:()=>b9,be:()=>z9,az:()=>L9,ar:()=>F9});var iv=()=>{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:"مدخل"},G={nan:"NaN"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`مدخلات غير مقبولة: يفترض إدخال instanceof ${K.expected}، ولكن تم إدخال ${q}`;return`مدخلات غير مقبولة: يفترض إدخال ${J}، ولكن تم إدخال ${q}`}case"invalid_value":if(K.values.length===1)return`مدخلات غير مقبولة: يفترض إدخال ${k(K.values[0])}`;return`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return` أكبر من اللازم: يفترض أن تكون ${K.origin??"القيمة"} ${J} ${K.maximum.toString()} ${W.unit??"عنصر"}`;return`أكبر من اللازم: يفترض أن تكون ${K.origin??"القيمة"} ${J} ${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`أصغر من اللازم: يفترض لـ ${K.origin} أن يكون ${J} ${K.minimum.toString()} ${W.unit}`;return`أصغر من اللازم: يفترض لـ ${K.origin} أن يكون ${J} ${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`نَص غير مقبول: يجب أن يبدأ بـ "${K.prefix}"`;if(J.format==="ends_with")return`نَص غير مقبول: يجب أن ينتهي بـ "${J.suffix}"`;if(J.format==="includes")return`نَص غير مقبول: يجب أن يتضمَّن "${J.includes}"`;if(J.format==="regex")return`نَص غير مقبول: يجب أن يطابق النمط ${J.pattern}`;return`${Q[J.format]??K.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${K.divisor}`;case"unrecognized_keys":return`معرف${K.keys.length>1?"ات":""} غريب${K.keys.length>1?"ة":""}: ${D(K.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${K.origin}`;case"invalid_union":return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${K.origin}`;default:return"مدخل غير مقبول"}}};function F9(){return{localeError:iv()}}var ov=()=>{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"},G={nan:"NaN"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Yanlış dəyər: gözlənilən instanceof ${K.expected}, daxil olan ${q}`;return`Yanlış dəyər: gözlənilən ${J}, daxil olan ${q}`}case"invalid_value":if(K.values.length===1)return`Yanlış dəyər: gözlənilən ${k(K.values[0])}`;return`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Çox böyük: gözlənilən ${K.origin??"dəyər"} ${J}${K.maximum.toString()} ${W.unit??"element"}`;return`Çox böyük: gözlənilən ${K.origin??"dəyər"} ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Çox kiçik: gözlənilən ${K.origin} ${J}${K.minimum.toString()} ${W.unit}`;return`Çox kiçik: gözlənilən ${K.origin} ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Yanlış mətn: "${J.prefix}" ilə başlamalıdır`;if(J.format==="ends_with")return`Yanlış mətn: "${J.suffix}" ilə bitməlidir`;if(J.format==="includes")return`Yanlış mətn: "${J.includes}" daxil olmalıdır`;if(J.format==="regex")return`Yanlış mətn: ${J.pattern} şablonuna uyğun olmalıdır`;return`Yanlış ${Q[J.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":""}: ${D(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 L9(){return{localeError:ov()}}function Rq($,U,Q,G){let K=Math.abs($),J=K%10,W=K%100;if(W>=11&&W<=19)return G;if(J===1)return U;if(J>=2&&J<=4)return Q;return G}var dv=()=>{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:"увод"},G={nan:"NaN",number:"лік",array:"масіў"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Няправільны ўвод: чакаўся instanceof ${K.expected}, атрымана ${q}`;return`Няправільны ўвод: чакаўся ${J}, атрымана ${q}`}case"invalid_value":if(K.values.length===1)return`Няправільны ўвод: чакалася ${k(K.values[0])}`;return`Няправільны варыянт: чакаўся адзін з ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W){let q=Number(K.maximum),j=Rq(q,W.unit.one,W.unit.few,W.unit.many);return`Занадта вялікі: чакалася, што ${K.origin??"значэнне"} павінна ${W.verb} ${J}${K.maximum.toString()} ${j}`}return`Занадта вялікі: чакалася, што ${K.origin??"значэнне"} павінна быць ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W){let q=Number(K.minimum),j=Rq(q,W.unit.one,W.unit.few,W.unit.many);return`Занадта малы: чакалася, што ${K.origin} павінна ${W.verb} ${J}${K.minimum.toString()} ${j}`}return`Занадта малы: чакалася, што ${K.origin} павінна быць ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Няправільны радок: павінен пачынацца з "${J.prefix}"`;if(J.format==="ends_with")return`Няправільны радок: павінен заканчвацца на "${J.suffix}"`;if(J.format==="includes")return`Няправільны радок: павінен змяшчаць "${J.includes}"`;if(J.format==="regex")return`Няправільны радок: павінен адпавядаць шаблону ${J.pattern}`;return`Няправільны ${Q[J.format]??K.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${K.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${K.keys.length>1?"ключы":"ключ"}: ${D(K.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${K.origin}`;case"invalid_union":return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${K.origin}`;default:return"Няправільны ўвод"}}};function z9(){return{localeError:dv()}}var pv=()=>{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:"вход"},G={nan:"NaN",number:"число",array:"масив"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Невалиден вход: очакван instanceof ${K.expected}, получен ${q}`;return`Невалиден вход: очакван ${J}, получен ${q}`}case"invalid_value":if(K.values.length===1)return`Невалиден вход: очакван ${k(K.values[0])}`;return`Невалидна опция: очаквано едно от ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Твърде голямо: очаква се ${K.origin??"стойност"} да съдържа ${J}${K.maximum.toString()} ${W.unit??"елемента"}`;return`Твърде голямо: очаква се ${K.origin??"стойност"} да бъде ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Твърде малко: очаква се ${K.origin} да съдържа ${J}${K.minimum.toString()} ${W.unit}`;return`Твърде малко: очаква се ${K.origin} да бъде ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Невалиден низ: трябва да започва с "${J.prefix}"`;if(J.format==="ends_with")return`Невалиден низ: трябва да завършва с "${J.suffix}"`;if(J.format==="includes")return`Невалиден низ: трябва да включва "${J.includes}"`;if(J.format==="regex")return`Невалиден низ: трябва да съвпада с ${J.pattern}`;let W="Невалиден";if(J.format==="emoji")W="Невалидно";if(J.format==="datetime")W="Невалидно";if(J.format==="date")W="Невалидна";if(J.format==="time")W="Невалидно";if(J.format==="duration")W="Невалидна";return`${W} ${Q[J.format]??K.format}`}case"not_multiple_of":return`Невалидно число: трябва да бъде кратно на ${K.divisor}`;case"unrecognized_keys":return`Неразпознат${K.keys.length>1?"и":""} ключ${K.keys.length>1?"ове":""}: ${D(K.keys,", ")}`;case"invalid_key":return`Невалиден ключ в ${K.origin}`;case"invalid_union":return"Невалиден вход";case"invalid_element":return`Невалидна стойност в ${K.origin}`;default:return"Невалиден вход"}}};function b9(){return{localeError:pv()}}var tv=()=>{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"},G={nan:"NaN"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Tipus invàlid: s'esperava instanceof ${K.expected}, s'ha rebut ${q}`;return`Tipus invàlid: s'esperava ${J}, s'ha rebut ${q}`}case"invalid_value":if(K.values.length===1)return`Valor invàlid: s'esperava ${k(K.values[0])}`;return`Opció invàlida: s'esperava una de ${D(K.values," o ")}`;case"too_big":{let J=K.inclusive?"com a màxim":"menys de",W=U(K.origin);if(W)return`Massa gran: s'esperava que ${K.origin??"el valor"} contingués ${J} ${K.maximum.toString()} ${W.unit??"elements"}`;return`Massa gran: s'esperava que ${K.origin??"el valor"} fos ${J} ${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?"com a mínim":"més de",W=U(K.origin);if(W)return`Massa petit: s'esperava que ${K.origin} contingués ${J} ${K.minimum.toString()} ${W.unit}`;return`Massa petit: s'esperava que ${K.origin} fos ${J} ${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Format invàlid: ha de començar amb "${J.prefix}"`;if(J.format==="ends_with")return`Format invàlid: ha d'acabar amb "${J.suffix}"`;if(J.format==="includes")return`Format invàlid: ha d'incloure "${J.includes}"`;if(J.format==="regex")return`Format invàlid: ha de coincidir amb el patró ${J.pattern}`;return`Format invàlid per a ${Q[J.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":""}: ${D(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 A9(){return{localeError:tv()}}var av=()=>{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"},G={nan:"NaN",number:"číslo",string:"řetězec",function:"funkce",array:"pole"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Neplatný vstup: očekáváno instanceof ${K.expected}, obdrženo ${q}`;return`Neplatný vstup: očekáváno ${J}, obdrženo ${q}`}case"invalid_value":if(K.values.length===1)return`Neplatný vstup: očekáváno ${k(K.values[0])}`;return`Neplatná možnost: očekávána jedna z hodnot ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Hodnota je příliš velká: ${K.origin??"hodnota"} musí mít ${J}${K.maximum.toString()} ${W.unit??"prvků"}`;return`Hodnota je příliš velká: ${K.origin??"hodnota"} musí být ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Hodnota je příliš malá: ${K.origin??"hodnota"} musí mít ${J}${K.minimum.toString()} ${W.unit??"prvků"}`;return`Hodnota je příliš malá: ${K.origin??"hodnota"} musí být ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Neplatný řetězec: musí začínat na "${J.prefix}"`;if(J.format==="ends_with")return`Neplatný řetězec: musí končit na "${J.suffix}"`;if(J.format==="includes")return`Neplatný řetězec: musí obsahovat "${J.includes}"`;if(J.format==="regex")return`Neplatný řetězec: musí odpovídat vzoru ${J.pattern}`;return`Neplatný formát ${Q[J.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: ${D(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 O9(){return{localeError:av()}}var ev=()=>{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"},G={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 J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Ugyldigt input: forventede instanceof ${K.expected}, fik ${q}`;return`Ugyldigt input: forventede ${J}, fik ${q}`}case"invalid_value":if(K.values.length===1)return`Ugyldig værdi: forventede ${k(K.values[0])}`;return`Ugyldigt valg: forventede en af følgende ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin),q=G[K.origin]??K.origin;if(W)return`For stor: forventede ${q??"value"} ${W.verb} ${J} ${K.maximum.toString()} ${W.unit??"elementer"}`;return`For stor: forventede ${q??"value"} havde ${J} ${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin),q=G[K.origin]??K.origin;if(W)return`For lille: forventede ${q} ${W.verb} ${J} ${K.minimum.toString()} ${W.unit}`;return`For lille: forventede ${q} havde ${J} ${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Ugyldig streng: skal starte med "${J.prefix}"`;if(J.format==="ends_with")return`Ugyldig streng: skal ende med "${J.suffix}"`;if(J.format==="includes")return`Ugyldig streng: skal indeholde "${J.includes}"`;if(J.format==="regex")return`Ugyldig streng: skal matche mønsteret ${J.pattern}`;return`Ugyldig ${Q[J.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"}: ${D(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 R9(){return{localeError:ev()}}var sv=()=>{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"},G={nan:"NaN",number:"Zahl",array:"Array"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Ungültige Eingabe: erwartet instanceof ${K.expected}, erhalten ${q}`;return`Ungültige Eingabe: erwartet ${J}, erhalten ${q}`}case"invalid_value":if(K.values.length===1)return`Ungültige Eingabe: erwartet ${k(K.values[0])}`;return`Ungültige Option: erwartet eine von ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Zu groß: erwartet, dass ${K.origin??"Wert"} ${J}${K.maximum.toString()} ${W.unit??"Elemente"} hat`;return`Zu groß: erwartet, dass ${K.origin??"Wert"} ${J}${K.maximum.toString()} ist`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Zu klein: erwartet, dass ${K.origin} ${J}${K.minimum.toString()} ${W.unit} hat`;return`Zu klein: erwartet, dass ${K.origin} ${J}${K.minimum.toString()} ist`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Ungültiger String: muss mit "${J.prefix}" beginnen`;if(J.format==="ends_with")return`Ungültiger String: muss mit "${J.suffix}" enden`;if(J.format==="includes")return`Ungültiger String: muss "${J.includes}" enthalten`;if(J.format==="regex")return`Ungültiger String: muss dem Muster ${J.pattern} entsprechen`;return`Ungültig: ${Q[J.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"}: ${D(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 T9(){return{localeError:sv()}}var $D=()=>{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"},G={nan:"NaN"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;return`Invalid input: expected ${J}, received ${q}`}case"invalid_value":if(K.values.length===1)return`Invalid input: expected ${k(K.values[0])}`;return`Invalid option: expected one of ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Too big: expected ${K.origin??"value"} to have ${J}${K.maximum.toString()} ${W.unit??"elements"}`;return`Too big: expected ${K.origin??"value"} to be ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Too small: expected ${K.origin} to have ${J}${K.minimum.toString()} ${W.unit}`;return`Too small: expected ${K.origin} to be ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Invalid string: must start with "${J.prefix}"`;if(J.format==="ends_with")return`Invalid string: must end with "${J.suffix}"`;if(J.format==="includes")return`Invalid string: must include "${J.includes}"`;if(J.format==="regex")return`Invalid string: must match pattern ${J.pattern}`;return`Invalid ${Q[J.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":""}: ${D(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 z6(){return{localeError:$D()}}var UD=()=>{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"},G={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Nevalida enigo: atendiĝis instanceof ${K.expected}, riceviĝis ${q}`;return`Nevalida enigo: atendiĝis ${J}, riceviĝis ${q}`}case"invalid_value":if(K.values.length===1)return`Nevalida enigo: atendiĝis ${k(K.values[0])}`;return`Nevalida opcio: atendiĝis unu el ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Tro granda: atendiĝis ke ${K.origin??"valoro"} havu ${J}${K.maximum.toString()} ${W.unit??"elementojn"}`;return`Tro granda: atendiĝis ke ${K.origin??"valoro"} havu ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Tro malgranda: atendiĝis ke ${K.origin} havu ${J}${K.minimum.toString()} ${W.unit}`;return`Tro malgranda: atendiĝis ke ${K.origin} estu ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Nevalida karaktraro: devas komenciĝi per "${J.prefix}"`;if(J.format==="ends_with")return`Nevalida karaktraro: devas finiĝi per "${J.suffix}"`;if(J.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${J.includes}"`;if(J.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${J.pattern}`;return`Nevalida ${Q[J.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":""}: ${D(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 S9(){return{localeError:UD()}}var KD=()=>{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"},G={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 J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Entrada inválida: se esperaba instanceof ${K.expected}, recibido ${q}`;return`Entrada inválida: se esperaba ${J}, recibido ${q}`}case"invalid_value":if(K.values.length===1)return`Entrada inválida: se esperaba ${k(K.values[0])}`;return`Opción inválida: se esperaba una de ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin),q=G[K.origin]??K.origin;if(W)return`Demasiado grande: se esperaba que ${q??"valor"} tuviera ${J}${K.maximum.toString()} ${W.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${q??"valor"} fuera ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin),q=G[K.origin]??K.origin;if(W)return`Demasiado pequeño: se esperaba que ${q} tuviera ${J}${K.minimum.toString()} ${W.unit}`;return`Demasiado pequeño: se esperaba que ${q} fuera ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Cadena inválida: debe comenzar con "${J.prefix}"`;if(J.format==="ends_with")return`Cadena inválida: debe terminar en "${J.suffix}"`;if(J.format==="includes")return`Cadena inválida: debe incluir "${J.includes}"`;if(J.format==="regex")return`Cadena inválida: debe coincidir con el patrón ${J.pattern}`;return`Inválido ${Q[J.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":""}: ${D(K.keys,", ")}`;case"invalid_key":return`Llave inválida en ${G[K.origin]??K.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido en ${G[K.origin]??K.origin}`;default:return"Entrada inválida"}}};function C9(){return{localeError:KD()}}var QD=()=>{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:"ورودی"},G={nan:"NaN",number:"عدد",array:"آرایه"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`ورودی نامعتبر: می‌بایست instanceof ${K.expected} می‌بود، ${q} دریافت شد`;return`ورودی نامعتبر: می‌بایست ${J} می‌بود، ${q} دریافت شد`}case"invalid_value":if(K.values.length===1)return`ورودی نامعتبر: می‌بایست ${k(K.values[0])} می‌بود`;return`گزینه نامعتبر: می‌بایست یکی از ${D(K.values,"|")} می‌بود`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`خیلی بزرگ: ${K.origin??"مقدار"} باید ${J}${K.maximum.toString()} ${W.unit??"عنصر"} باشد`;return`خیلی بزرگ: ${K.origin??"مقدار"} باید ${J}${K.maximum.toString()} باشد`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`خیلی کوچک: ${K.origin} باید ${J}${K.minimum.toString()} ${W.unit} باشد`;return`خیلی کوچک: ${K.origin} باید ${J}${K.minimum.toString()} باشد`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`رشته نامعتبر: باید با "${J.prefix}" شروع شود`;if(J.format==="ends_with")return`رشته نامعتبر: باید با "${J.suffix}" تمام شود`;if(J.format==="includes")return`رشته نامعتبر: باید شامل "${J.includes}" باشد`;if(J.format==="regex")return`رشته نامعتبر: باید با الگوی ${J.pattern} مطابقت داشته باشد`;return`${Q[J.format]??K.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${K.divisor} باشد`;case"unrecognized_keys":return`کلید${K.keys.length>1?"های":""} ناشناس: ${D(K.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${K.origin}`;case"invalid_union":return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${K.origin}`;default:return"ورودی نامعتبر"}}};function g9(){return{localeError:QD()}}var GD=()=>{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"},G={nan:"NaN"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Virheellinen tyyppi: odotettiin instanceof ${K.expected}, oli ${q}`;return`Virheellinen tyyppi: odotettiin ${J}, oli ${q}`}case"invalid_value":if(K.values.length===1)return`Virheellinen syöte: täytyy olla ${k(K.values[0])}`;return`Virheellinen valinta: täytyy olla yksi seuraavista: ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Liian suuri: ${W.subject} täytyy olla ${J}${K.maximum.toString()} ${W.unit}`.trim();return`Liian suuri: arvon täytyy olla ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Liian pieni: ${W.subject} täytyy olla ${J}${K.minimum.toString()} ${W.unit}`.trim();return`Liian pieni: arvon täytyy olla ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Virheellinen syöte: täytyy alkaa "${J.prefix}"`;if(J.format==="ends_with")return`Virheellinen syöte: täytyy loppua "${J.suffix}"`;if(J.format==="includes")return`Virheellinen syöte: täytyy sisältää "${J.includes}"`;if(J.format==="regex")return`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${J.pattern}`;return`Virheellinen ${Q[J.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"}: ${D(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 E9(){return{localeError:GD()}}var JD=()=>{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"},G={nan:"NaN",number:"nombre",array:"tableau"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Entrée invalide : instanceof ${K.expected} attendu, ${q} reçu`;return`Entrée invalide : ${J} attendu, ${q} reçu`}case"invalid_value":if(K.values.length===1)return`Entrée invalide : ${k(K.values[0])} attendu`;return`Option invalide : une valeur parmi ${D(K.values,"|")} attendue`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Trop grand : ${K.origin??"valeur"} doit ${W.verb} ${J}${K.maximum.toString()} ${W.unit??"élément(s)"}`;return`Trop grand : ${K.origin??"valeur"} doit être ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Trop petit : ${K.origin} doit ${W.verb} ${J}${K.minimum.toString()} ${W.unit}`;return`Trop petit : ${K.origin} doit être ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Chaîne invalide : doit commencer par "${J.prefix}"`;if(J.format==="ends_with")return`Chaîne invalide : doit se terminer par "${J.suffix}"`;if(J.format==="includes")return`Chaîne invalide : doit inclure "${J.includes}"`;if(J.format==="regex")return`Chaîne invalide : doit correspondre au modèle ${J.pattern}`;return`${Q[J.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":""} : ${D(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 y9(){return{localeError:JD()}}var WD=()=>{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"},G={nan:"NaN"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Entrée invalide : attendu instanceof ${K.expected}, reçu ${q}`;return`Entrée invalide : attendu ${J}, reçu ${q}`}case"invalid_value":if(K.values.length===1)return`Entrée invalide : attendu ${k(K.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"≤":"<",W=U(K.origin);if(W)return`Trop grand : attendu que ${K.origin??"la valeur"} ait ${J}${K.maximum.toString()} ${W.unit}`;return`Trop grand : attendu que ${K.origin??"la valeur"} soit ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?"≥":">",W=U(K.origin);if(W)return`Trop petit : attendu que ${K.origin} ait ${J}${K.minimum.toString()} ${W.unit}`;return`Trop petit : attendu que ${K.origin} soit ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Chaîne invalide : doit commencer par "${J.prefix}"`;if(J.format==="ends_with")return`Chaîne invalide : doit se terminer par "${J.suffix}"`;if(J.format==="includes")return`Chaîne invalide : doit inclure "${J.includes}"`;if(J.format==="regex")return`Chaîne invalide : doit correspondre au motif ${J.pattern}`;return`${Q[J.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":""} : ${D(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 u9(){return{localeError:WD()}}var qD=()=>{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=(X)=>X?$[X]:void 0,G=(X)=>{let B=Q(X);if(B)return B.label;return X??$.unknown.label},K=(X)=>`ה${G(X)}`,J=(X)=>{return(Q(X)?.gender??"m")==="f"?"צריכה להיות":"צריך להיות"},W=(X)=>{if(!X)return null;return U[X]??null},q={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(X)=>{switch(X.code){case"invalid_type":{let B=X.expected,Z=j[B??""]??G(B),V=x(X.input),N=j[V]??$[V]?.label??V;if(/^[A-Z]/.test(X.expected))return`קלט לא תקין: צריך להיות instanceof ${X.expected}, התקבל ${N}`;return`קלט לא תקין: צריך להיות ${Z}, התקבל ${N}`}case"invalid_value":{if(X.values.length===1)return`ערך לא תקין: הערך חייב להיות ${k(X.values[0])}`;let B=X.values.map((N)=>k(N));if(X.values.length===2)return`ערך לא תקין: האפשרויות המתאימות הן ${B[0]} או ${B[1]}`;let Z=B[B.length-1];return`ערך לא תקין: האפשרויות המתאימות הן ${B.slice(0,-1).join(", ")} או ${Z}`}case"too_big":{let B=W(X.origin),Z=K(X.origin??"value");if(X.origin==="string")return`${B?.longLabel??"ארוך"} מדי: ${Z} צריכה להכיל ${X.maximum.toString()} ${B?.unit??""} ${X.inclusive?"או פחות":"לכל היותר"}`.trim();if(X.origin==="number"){let T=X.inclusive?`קטן או שווה ל-${X.maximum}`:`קטן מ-${X.maximum}`;return`גדול מדי: ${Z} צריך להיות ${T}`}if(X.origin==="array"||X.origin==="set"){let T=X.origin==="set"?"צריכה":"צריך",f=X.inclusive?`${X.maximum} ${B?.unit??""} או פחות`:`פחות מ-${X.maximum} ${B?.unit??""}`;return`גדול מדי: ${Z} ${T} להכיל ${f}`.trim()}let V=X.inclusive?"<=":"<",N=J(X.origin??"value");if(B?.unit)return`${B.longLabel} מדי: ${Z} ${N} ${V}${X.maximum.toString()} ${B.unit}`;return`${B?.longLabel??"גדול"} מדי: ${Z} ${N} ${V}${X.maximum.toString()}`}case"too_small":{let B=W(X.origin),Z=K(X.origin??"value");if(X.origin==="string")return`${B?.shortLabel??"קצר"} מדי: ${Z} צריכה להכיל ${X.minimum.toString()} ${B?.unit??""} ${X.inclusive?"או יותר":"לפחות"}`.trim();if(X.origin==="number"){let T=X.inclusive?`גדול או שווה ל-${X.minimum}`:`גדול מ-${X.minimum}`;return`קטן מדי: ${Z} צריך להיות ${T}`}if(X.origin==="array"||X.origin==="set"){let T=X.origin==="set"?"צריכה":"צריך";if(X.minimum===1&&X.inclusive){let e=X.origin==="set"?"לפחות פריט אחד":"לפחות פריט אחד";return`קטן מדי: ${Z} ${T} להכיל ${e}`}let f=X.inclusive?`${X.minimum} ${B?.unit??""} או יותר`:`יותר מ-${X.minimum} ${B?.unit??""}`;return`קטן מדי: ${Z} ${T} להכיל ${f}`.trim()}let V=X.inclusive?">=":">",N=J(X.origin??"value");if(B?.unit)return`${B.shortLabel} מדי: ${Z} ${N} ${V}${X.minimum.toString()} ${B.unit}`;return`${B?.shortLabel??"קטן"} מדי: ${Z} ${N} ${V}${X.minimum.toString()}`}case"invalid_format":{let B=X;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 Z=q[B.format],V=Z?.label??B.format,T=(Z?.gender??"m")==="f"?"תקינה":"תקין";return`${V} לא ${T}`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${X.divisor}`;case"unrecognized_keys":return`מפתח${X.keys.length>1?"ות":""} לא מזוה${X.keys.length>1?"ים":"ה"}: ${D(X.keys,", ")}`;case"invalid_key":return"שדה לא תקין באובייקט";case"invalid_union":return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${K(X.origin??"array")}`;default:return"קלט לא תקין"}}};function f9(){return{localeError:qD()}}var YD=()=>{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"},G={nan:"NaN",number:"szám",array:"tömb"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Érvénytelen bemenet: a várt érték instanceof ${K.expected}, a kapott érték ${q}`;return`Érvénytelen bemenet: a várt érték ${J}, a kapott érték ${q}`}case"invalid_value":if(K.values.length===1)return`Érvénytelen bemenet: a várt érték ${k(K.values[0])}`;return`Érvénytelen opció: valamelyik érték várt ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Túl nagy: ${K.origin??"érték"} mérete túl nagy ${J}${K.maximum.toString()} ${W.unit??"elem"}`;return`Túl nagy: a bemeneti érték ${K.origin??"érték"} túl nagy: ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Túl kicsi: a bemeneti érték ${K.origin} mérete túl kicsi ${J}${K.minimum.toString()} ${W.unit}`;return`Túl kicsi: a bemeneti érték ${K.origin} túl kicsi ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Érvénytelen string: "${J.prefix}" értékkel kell kezdődnie`;if(J.format==="ends_with")return`Érvénytelen string: "${J.suffix}" értékkel kell végződnie`;if(J.format==="includes")return`Érvénytelen string: "${J.includes}" értéket kell tartalmaznia`;if(J.format==="regex")return`Érvénytelen string: ${J.pattern} mintának kell megfelelnie`;return`Érvénytelen ${Q[J.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":""}: ${D(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 m9(){return{localeError:YD()}}function Tq($,U,Q){return Math.abs($)===1?U:Q}function F4($){if(!$)return"";let U=["ա","ե","ը","ի","ո","ու","օ"],Q=$[$.length-1];return $+(U.includes(Q)?"ն":"ը")}var jD=()=>{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:"մուտք"},G={nan:"NaN",number:"թիվ",array:"զանգված"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Սխալ մուտքագրում․ սպասվում էր instanceof ${K.expected}, ստացվել է ${q}`;return`Սխալ մուտքագրում․ սպասվում էր ${J}, ստացվել է ${q}`}case"invalid_value":if(K.values.length===1)return`Սխալ մուտքագրում․ սպասվում էր ${k(K.values[1])}`;return`Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W){let q=Number(K.maximum),j=Tq(q,W.unit.one,W.unit.many);return`Չափազանց մեծ արժեք․ սպասվում է, որ ${F4(K.origin??"արժեք")} կունենա ${J}${K.maximum.toString()} ${j}`}return`Չափազանց մեծ արժեք․ սպասվում է, որ ${F4(K.origin??"արժեք")} լինի ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W){let q=Number(K.minimum),j=Tq(q,W.unit.one,W.unit.many);return`Չափազանց փոքր արժեք․ սպասվում է, որ ${F4(K.origin)} կունենա ${J}${K.minimum.toString()} ${j}`}return`Չափազանց փոքր արժեք․ սպասվում է, որ ${F4(K.origin)} լինի ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Սխալ տող․ պետք է սկսվի "${J.prefix}"-ով`;if(J.format==="ends_with")return`Սխալ տող․ պետք է ավարտվի "${J.suffix}"-ով`;if(J.format==="includes")return`Սխալ տող․ պետք է պարունակի "${J.includes}"`;if(J.format==="regex")return`Սխալ տող․ պետք է համապատասխանի ${J.pattern} ձևաչափին`;return`Սխալ ${Q[J.format]??K.format}`}case"not_multiple_of":return`Սխալ թիվ․ պետք է բազմապատիկ լինի ${K.divisor}-ի`;case"unrecognized_keys":return`Չճանաչված բանալի${K.keys.length>1?"ներ":""}. ${D(K.keys,", ")}`;case"invalid_key":return`Սխալ բանալի ${F4(K.origin)}-ում`;case"invalid_union":return"Սխալ մուտքագրում";case"invalid_element":return`Սխալ արժեք ${F4(K.origin)}-ում`;default:return"Սխալ մուտքագրում"}}};function h9(){return{localeError:jD()}}var XD=()=>{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"},G={nan:"NaN"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Input tidak valid: diharapkan instanceof ${K.expected}, diterima ${q}`;return`Input tidak valid: diharapkan ${J}, diterima ${q}`}case"invalid_value":if(K.values.length===1)return`Input tidak valid: diharapkan ${k(K.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Terlalu besar: diharapkan ${K.origin??"value"} memiliki ${J}${K.maximum.toString()} ${W.unit??"elemen"}`;return`Terlalu besar: diharapkan ${K.origin??"value"} menjadi ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Terlalu kecil: diharapkan ${K.origin} memiliki ${J}${K.minimum.toString()} ${W.unit}`;return`Terlalu kecil: diharapkan ${K.origin} menjadi ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`String tidak valid: harus dimulai dengan "${J.prefix}"`;if(J.format==="ends_with")return`String tidak valid: harus berakhir dengan "${J.suffix}"`;if(J.format==="includes")return`String tidak valid: harus menyertakan "${J.includes}"`;if(J.format==="regex")return`String tidak valid: harus sesuai pola ${J.pattern}`;return`${Q[J.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":""}: ${D(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 c9(){return{localeError:XD()}}var HD=()=>{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"},G={nan:"NaN",number:"númer",array:"fylki"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Rangt gildi: Þú slóst inn ${q} þar sem á að vera instanceof ${K.expected}`;return`Rangt gildi: Þú slóst inn ${q} þar sem á að vera ${J}`}case"invalid_value":if(K.values.length===1)return`Rangt gildi: gert ráð fyrir ${k(K.values[0])}`;return`Ógilt val: má vera eitt af eftirfarandi ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Of stórt: gert er ráð fyrir að ${K.origin??"gildi"} hafi ${J}${K.maximum.toString()} ${W.unit??"hluti"}`;return`Of stórt: gert er ráð fyrir að ${K.origin??"gildi"} sé ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Of lítið: gert er ráð fyrir að ${K.origin} hafi ${J}${K.minimum.toString()} ${W.unit}`;return`Of lítið: gert er ráð fyrir að ${K.origin} sé ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Ógildur strengur: verður að byrja á "${J.prefix}"`;if(J.format==="ends_with")return`Ógildur strengur: verður að enda á "${J.suffix}"`;if(J.format==="includes")return`Ógildur strengur: verður að innihalda "${J.includes}"`;if(J.format==="regex")return`Ógildur strengur: verður að fylgja mynstri ${J.pattern}`;return`Rangt ${Q[J.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"}: ${D(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 l9(){return{localeError:HD()}}var BD=()=>{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"},G={nan:"NaN",number:"numero",array:"vettore"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Input non valido: atteso instanceof ${K.expected}, ricevuto ${q}`;return`Input non valido: atteso ${J}, ricevuto ${q}`}case"invalid_value":if(K.values.length===1)return`Input non valido: atteso ${k(K.values[0])}`;return`Opzione non valida: atteso uno tra ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Troppo grande: ${K.origin??"valore"} deve avere ${J}${K.maximum.toString()} ${W.unit??"elementi"}`;return`Troppo grande: ${K.origin??"valore"} deve essere ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Troppo piccolo: ${K.origin} deve avere ${J}${K.minimum.toString()} ${W.unit}`;return`Troppo piccolo: ${K.origin} deve essere ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Stringa non valida: deve iniziare con "${J.prefix}"`;if(J.format==="ends_with")return`Stringa non valida: deve terminare con "${J.suffix}"`;if(J.format==="includes")return`Stringa non valida: deve includere "${J.includes}"`;if(J.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${J.pattern}`;return`Invalid ${Q[J.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"}: ${D(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 r9(){return{localeError:BD()}}var MD=()=>{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:"入力値"},G={nan:"NaN",number:"数値",array:"配列"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`無効な入力: instanceof ${K.expected}が期待されましたが、${q}が入力されました`;return`無効な入力: ${J}が期待されましたが、${q}が入力されました`}case"invalid_value":if(K.values.length===1)return`無効な入力: ${k(K.values[0])}が期待されました`;return`無効な選択: ${D(K.values,"、")}のいずれかである必要があります`;case"too_big":{let J=K.inclusive?"以下である":"より小さい",W=U(K.origin);if(W)return`大きすぎる値: ${K.origin??"値"}は${K.maximum.toString()}${W.unit??"要素"}${J}必要があります`;return`大きすぎる値: ${K.origin??"値"}は${K.maximum.toString()}${J}必要があります`}case"too_small":{let J=K.inclusive?"以上である":"より大きい",W=U(K.origin);if(W)return`小さすぎる値: ${K.origin}は${K.minimum.toString()}${W.unit}${J}必要があります`;return`小さすぎる値: ${K.origin}は${K.minimum.toString()}${J}必要があります`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`無効な文字列: "${J.prefix}"で始まる必要があります`;if(J.format==="ends_with")return`無効な文字列: "${J.suffix}"で終わる必要があります`;if(J.format==="includes")return`無効な文字列: "${J.includes}"を含む必要があります`;if(J.format==="regex")return`無効な文字列: パターン${J.pattern}に一致する必要があります`;return`無効な${Q[J.format]??K.format}`}case"not_multiple_of":return`無効な数値: ${K.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${K.keys.length>1?"群":""}: ${D(K.keys,"、")}`;case"invalid_key":return`${K.origin}内の無効なキー`;case"invalid_union":return"無効な入力";case"invalid_element":return`${K.origin}内の無効な値`;default:return"無効な入力"}}};function n9(){return{localeError:MD()}}var ZD=()=>{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:"შეყვანა"},G={nan:"NaN",number:"რიცხვი",string:"სტრინგი",boolean:"ბულეანი",function:"ფუნქცია",array:"მასივი"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`არასწორი შეყვანა: მოსალოდნელი instanceof ${K.expected}, მიღებული ${q}`;return`არასწორი შეყვანა: მოსალოდნელი ${J}, მიღებული ${q}`}case"invalid_value":if(K.values.length===1)return`არასწორი შეყვანა: მოსალოდნელი ${k(K.values[0])}`;return`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${D(K.values,"|")}-დან`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`ზედმეტად დიდი: მოსალოდნელი ${K.origin??"მნიშვნელობა"} ${W.verb} ${J}${K.maximum.toString()} ${W.unit}`;return`ზედმეტად დიდი: მოსალოდნელი ${K.origin??"მნიშვნელობა"} იყოს ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`ზედმეტად პატარა: მოსალოდნელი ${K.origin} ${W.verb} ${J}${K.minimum.toString()} ${W.unit}`;return`ზედმეტად პატარა: მოსალოდნელი ${K.origin} იყოს ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`არასწორი სტრინგი: უნდა იწყებოდეს "${J.prefix}"-ით`;if(J.format==="ends_with")return`არასწორი სტრინგი: უნდა მთავრდებოდეს "${J.suffix}"-ით`;if(J.format==="includes")return`არასწორი სტრინგი: უნდა შეიცავდეს "${J.includes}"-ს`;if(J.format==="regex")return`არასწორი სტრინგი: უნდა შეესაბამებოდეს შაბლონს ${J.pattern}`;return`არასწორი ${Q[J.format]??K.format}`}case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${K.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${K.keys.length>1?"ები":"ი"}: ${D(K.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${K.origin}-ში`;case"invalid_union":return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${K.origin}-ში`;default:return"არასწორი შეყვანა"}}};function i9(){return{localeError:ZD()}}var VD=()=>{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:"ទិន្នន័យបញ្ចូល"},G={nan:"NaN",number:"លេខ",array:"អារេ (Array)",null:"គ្មានតម្លៃ (null)"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${K.expected} ប៉ុន្តែទទួលបាន ${q}`;return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${J} ប៉ុន្តែទទួលបាន ${q}`}case"invalid_value":if(K.values.length===1)return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${k(K.values[0])}`;return`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`ធំពេក៖ ត្រូវការ ${K.origin??"តម្លៃ"} ${J} ${K.maximum.toString()} ${W.unit??"ធាតុ"}`;return`ធំពេក៖ ត្រូវការ ${K.origin??"តម្លៃ"} ${J} ${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`តូចពេក៖ ត្រូវការ ${K.origin} ${J} ${K.minimum.toString()} ${W.unit}`;return`តូចពេក៖ ត្រូវការ ${K.origin} ${J} ${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${J.prefix}"`;if(J.format==="ends_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${J.suffix}"`;if(J.format==="includes")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${J.includes}"`;if(J.format==="regex")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${J.pattern}`;return`មិនត្រឹមត្រូវ៖ ${Q[J.format]??K.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${K.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${D(K.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${K.origin}`;case"invalid_union":return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${K.origin}`;default:return"ទិន្នន័យមិនត្រឹមត្រូវ"}}};function b6(){return{localeError:VD()}}function o9(){return b6()}var vD=()=>{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:"입력"},G={nan:"NaN"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`잘못된 입력: 예상 타입은 instanceof ${K.expected}, 받은 타입은 ${q}입니다`;return`잘못된 입력: 예상 타입은 ${J}, 받은 타입은 ${q}입니다`}case"invalid_value":if(K.values.length===1)return`잘못된 입력: 값은 ${k(K.values[0])} 이어야 합니다`;return`잘못된 옵션: ${D(K.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{let J=K.inclusive?"이하":"미만",W=J==="미만"?"이어야 합니다":"여야 합니다",q=U(K.origin),j=q?.unit??"요소";if(q)return`${K.origin??"값"}이 너무 큽니다: ${K.maximum.toString()}${j} ${J}${W}`;return`${K.origin??"값"}이 너무 큽니다: ${K.maximum.toString()} ${J}${W}`}case"too_small":{let J=K.inclusive?"이상":"초과",W=J==="이상"?"이어야 합니다":"여야 합니다",q=U(K.origin),j=q?.unit??"요소";if(q)return`${K.origin??"값"}이 너무 작습니다: ${K.minimum.toString()}${j} ${J}${W}`;return`${K.origin??"값"}이 너무 작습니다: ${K.minimum.toString()} ${J}${W}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`잘못된 문자열: "${J.prefix}"(으)로 시작해야 합니다`;if(J.format==="ends_with")return`잘못된 문자열: "${J.suffix}"(으)로 끝나야 합니다`;if(J.format==="includes")return`잘못된 문자열: "${J.includes}"을(를) 포함해야 합니다`;if(J.format==="regex")return`잘못된 문자열: 정규식 ${J.pattern} 패턴과 일치해야 합니다`;return`잘못된 ${Q[J.format]??K.format}`}case"not_multiple_of":return`잘못된 숫자: ${K.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${D(K.keys,", ")}`;case"invalid_key":return`잘못된 키: ${K.origin}`;case"invalid_union":return"잘못된 입력";case"invalid_element":return`잘못된 값: ${K.origin}`;default:return"잘못된 입력"}}};function d9(){return{localeError:vD()}}var A6=($)=>{return $.charAt(0).toUpperCase()+$.slice(1)};function Sq($){let U=Math.abs($),Q=U%10,G=U%100;if(G>=11&&G<=19||Q===0)return"many";if(Q===1)return"one";return"few"}var DD=()=>{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,J,W,q){let j=$[K]??null;if(j===null)return j;return{unit:j.unit[J],verb:j.verb[q][W?"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"},G={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 J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Gautas tipas ${q}, o tikėtasi - instanceof ${K.expected}`;return`Gautas tipas ${q}, o tikėtasi - ${J}`}case"invalid_value":if(K.values.length===1)return`Privalo būti ${k(K.values[0])}`;return`Privalo būti vienas iš ${D(K.values,"|")} pasirinkimų`;case"too_big":{let J=G[K.origin]??K.origin,W=U(K.origin,Sq(Number(K.maximum)),K.inclusive??!1,"smaller");if(W?.verb)return`${A6(J??K.origin??"reikšmė")} ${W.verb} ${K.maximum.toString()} ${W.unit??"elementų"}`;let q=K.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${A6(J??K.origin??"reikšmė")} turi būti ${q} ${K.maximum.toString()} ${W?.unit}`}case"too_small":{let J=G[K.origin]??K.origin,W=U(K.origin,Sq(Number(K.minimum)),K.inclusive??!1,"bigger");if(W?.verb)return`${A6(J??K.origin??"reikšmė")} ${W.verb} ${K.minimum.toString()} ${W.unit??"elementų"}`;let q=K.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${A6(J??K.origin??"reikšmė")} turi būti ${q} ${K.minimum.toString()} ${W?.unit}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Eilutė privalo prasidėti "${J.prefix}"`;if(J.format==="ends_with")return`Eilutė privalo pasibaigti "${J.suffix}"`;if(J.format==="includes")return`Eilutė privalo įtraukti "${J.includes}"`;if(J.format==="regex")return`Eilutė privalo atitikti ${J.pattern}`;return`Neteisingas ${Q[J.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"}: ${D(K.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga įvestis";case"invalid_element":{let J=G[K.origin]??K.origin;return`${A6(J??K.origin??"reikšmė")} turi klaidingą įvestį`}default:return"Klaidinga įvestis"}}};function p9(){return{localeError:DD()}}var PD=()=>{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:"внес"},G={nan:"NaN",number:"број",array:"низа"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Грешен внес: се очекува instanceof ${K.expected}, примено ${q}`;return`Грешен внес: се очекува ${J}, примено ${q}`}case"invalid_value":if(K.values.length===1)return`Invalid input: expected ${k(K.values[0])}`;return`Грешана опција: се очекува една ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Премногу голем: се очекува ${K.origin??"вредноста"} да има ${J}${K.maximum.toString()} ${W.unit??"елементи"}`;return`Премногу голем: се очекува ${K.origin??"вредноста"} да биде ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Премногу мал: се очекува ${K.origin} да има ${J}${K.minimum.toString()} ${W.unit}`;return`Премногу мал: се очекува ${K.origin} да биде ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Неважечка низа: мора да започнува со "${J.prefix}"`;if(J.format==="ends_with")return`Неважечка низа: мора да завршува со "${J.suffix}"`;if(J.format==="includes")return`Неважечка низа: мора да вклучува "${J.includes}"`;if(J.format==="regex")return`Неважечка низа: мора да одгоара на патернот ${J.pattern}`;return`Invalid ${Q[J.format]??K.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${K.divisor}`;case"unrecognized_keys":return`${K.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${D(K.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${K.origin}`;case"invalid_union":return"Грешен внес";case"invalid_element":return`Грешна вредност во ${K.origin}`;default:return"Грешен внес"}}};function t9(){return{localeError:PD()}}var ID=()=>{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"},G={nan:"NaN",number:"nombor"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Input tidak sah: dijangka instanceof ${K.expected}, diterima ${q}`;return`Input tidak sah: dijangka ${J}, diterima ${q}`}case"invalid_value":if(K.values.length===1)return`Input tidak sah: dijangka ${k(K.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Terlalu besar: dijangka ${K.origin??"nilai"} ${W.verb} ${J}${K.maximum.toString()} ${W.unit??"elemen"}`;return`Terlalu besar: dijangka ${K.origin??"nilai"} adalah ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Terlalu kecil: dijangka ${K.origin} ${W.verb} ${J}${K.minimum.toString()} ${W.unit}`;return`Terlalu kecil: dijangka ${K.origin} adalah ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`String tidak sah: mesti bermula dengan "${J.prefix}"`;if(J.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${J.suffix}"`;if(J.format==="includes")return`String tidak sah: mesti mengandungi "${J.includes}"`;if(J.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${J.pattern}`;return`${Q[J.format]??K.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${K.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${D(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 a9(){return{localeError:ID()}}var ND=()=>{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"},G={nan:"NaN",number:"getal"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Ongeldige invoer: verwacht instanceof ${K.expected}, ontving ${q}`;return`Ongeldige invoer: verwacht ${J}, ontving ${q}`}case"invalid_value":if(K.values.length===1)return`Ongeldige invoer: verwacht ${k(K.values[0])}`;return`Ongeldige optie: verwacht één van ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin),q=K.origin==="date"?"laat":K.origin==="string"?"lang":"groot";if(W)return`Te ${q}: verwacht dat ${K.origin??"waarde"} ${J}${K.maximum.toString()} ${W.unit??"elementen"} ${W.verb}`;return`Te ${q}: verwacht dat ${K.origin??"waarde"} ${J}${K.maximum.toString()} is`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin),q=K.origin==="date"?"vroeg":K.origin==="string"?"kort":"klein";if(W)return`Te ${q}: verwacht dat ${K.origin} ${J}${K.minimum.toString()} ${W.unit} ${W.verb}`;return`Te ${q}: verwacht dat ${K.origin} ${J}${K.minimum.toString()} is`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Ongeldige tekst: moet met "${J.prefix}" beginnen`;if(J.format==="ends_with")return`Ongeldige tekst: moet op "${J.suffix}" eindigen`;if(J.format==="includes")return`Ongeldige tekst: moet "${J.includes}" bevatten`;if(J.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${J.pattern}`;return`Ongeldig: ${Q[J.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":""}: ${D(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 e9(){return{localeError:ND()}}var _D=()=>{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"},G={nan:"NaN",number:"tall",array:"liste"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Ugyldig input: forventet instanceof ${K.expected}, fikk ${q}`;return`Ugyldig input: forventet ${J}, fikk ${q}`}case"invalid_value":if(K.values.length===1)return`Ugyldig verdi: forventet ${k(K.values[0])}`;return`Ugyldig valg: forventet en av ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`For stor(t): forventet ${K.origin??"value"} til å ha ${J}${K.maximum.toString()} ${W.unit??"elementer"}`;return`For stor(t): forventet ${K.origin??"value"} til å ha ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`For lite(n): forventet ${K.origin} til å ha ${J}${K.minimum.toString()} ${W.unit}`;return`For lite(n): forventet ${K.origin} til å ha ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Ugyldig streng: må starte med "${J.prefix}"`;if(J.format==="ends_with")return`Ugyldig streng: må ende med "${J.suffix}"`;if(J.format==="includes")return`Ugyldig streng: må inneholde "${J.includes}"`;if(J.format==="regex")return`Ugyldig streng: må matche mønsteret ${J.pattern}`;return`Ugyldig ${Q[J.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"}: ${D(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 s9(){return{localeError:_D()}}var wD=()=>{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"},G={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Fâsit giren: umulan instanceof ${K.expected}, alınan ${q}`;return`Fâsit giren: umulan ${J}, alınan ${q}`}case"invalid_value":if(K.values.length===1)return`Fâsit giren: umulan ${k(K.values[0])}`;return`Fâsit tercih: mûteberler ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Fazla büyük: ${K.origin??"value"}, ${J}${K.maximum.toString()} ${W.unit??"elements"} sahip olmalıydı.`;return`Fazla büyük: ${K.origin??"value"}, ${J}${K.maximum.toString()} olmalıydı.`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Fazla küçük: ${K.origin}, ${J}${K.minimum.toString()} ${W.unit} sahip olmalıydı.`;return`Fazla küçük: ${K.origin}, ${J}${K.minimum.toString()} olmalıydı.`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Fâsit metin: "${J.prefix}" ile başlamalı.`;if(J.format==="ends_with")return`Fâsit metin: "${J.suffix}" ile bitmeli.`;if(J.format==="includes")return`Fâsit metin: "${J.includes}" ihtivâ etmeli.`;if(J.format==="regex")return`Fâsit metin: ${J.pattern} nakşına uymalı.`;return`Fâsit ${Q[J.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":""}: ${D(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 $7(){return{localeError:wD()}}var kD=()=>{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:"ورودي"},G={nan:"NaN",number:"عدد",array:"ارې"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`ناسم ورودي: باید instanceof ${K.expected} وای, مګر ${q} ترلاسه شو`;return`ناسم ورودي: باید ${J} وای, مګر ${q} ترلاسه شو`}case"invalid_value":if(K.values.length===1)return`ناسم ورودي: باید ${k(K.values[0])} وای`;return`ناسم انتخاب: باید یو له ${D(K.values,"|")} څخه وای`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`ډیر لوی: ${K.origin??"ارزښت"} باید ${J}${K.maximum.toString()} ${W.unit??"عنصرونه"} ولري`;return`ډیر لوی: ${K.origin??"ارزښت"} باید ${J}${K.maximum.toString()} وي`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`ډیر کوچنی: ${K.origin} باید ${J}${K.minimum.toString()} ${W.unit} ولري`;return`ډیر کوچنی: ${K.origin} باید ${J}${K.minimum.toString()} وي`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`ناسم متن: باید د "${J.prefix}" سره پیل شي`;if(J.format==="ends_with")return`ناسم متن: باید د "${J.suffix}" سره پای ته ورسيږي`;if(J.format==="includes")return`ناسم متن: باید "${J.includes}" ولري`;if(J.format==="regex")return`ناسم متن: باید د ${J.pattern} سره مطابقت ولري`;return`${Q[J.format]??K.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${K.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${K.keys.length>1?"کلیډونه":"کلیډ"}: ${D(K.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${K.origin} کې`;case"invalid_union":return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${K.origin} کې`;default:return"ناسمه ورودي"}}};function U7(){return{localeError:kD()}}var xD=()=>{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"},G={nan:"NaN",number:"liczba",array:"tablica"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Nieprawidłowe dane wejściowe: oczekiwano instanceof ${K.expected}, otrzymano ${q}`;return`Nieprawidłowe dane wejściowe: oczekiwano ${J}, otrzymano ${q}`}case"invalid_value":if(K.values.length===1)return`Nieprawidłowe dane wejściowe: oczekiwano ${k(K.values[0])}`;return`Nieprawidłowa opcja: oczekiwano jednej z wartości ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Za duża wartość: oczekiwano, że ${K.origin??"wartość"} będzie mieć ${J}${K.maximum.toString()} ${W.unit??"elementów"}`;return`Zbyt duż(y/a/e): oczekiwano, że ${K.origin??"wartość"} będzie wynosić ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Za mała wartość: oczekiwano, że ${K.origin??"wartość"} będzie mieć ${J}${K.minimum.toString()} ${W.unit??"elementów"}`;return`Zbyt mał(y/a/e): oczekiwano, że ${K.origin??"wartość"} będzie wynosić ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Nieprawidłowy ciąg znaków: musi zaczynać się od "${J.prefix}"`;if(J.format==="ends_with")return`Nieprawidłowy ciąg znaków: musi kończyć się na "${J.suffix}"`;if(J.format==="includes")return`Nieprawidłowy ciąg znaków: musi zawierać "${J.includes}"`;if(J.format==="regex")return`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${J.pattern}`;return`Nieprawidłow(y/a/e) ${Q[J.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":""}: ${D(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 K7(){return{localeError:xD()}}var FD=()=>{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"},G={nan:"NaN",number:"número",null:"nulo"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Tipo inválido: esperado instanceof ${K.expected}, recebido ${q}`;return`Tipo inválido: esperado ${J}, recebido ${q}`}case"invalid_value":if(K.values.length===1)return`Entrada inválida: esperado ${k(K.values[0])}`;return`Opção inválida: esperada uma das ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Muito grande: esperado que ${K.origin??"valor"} tivesse ${J}${K.maximum.toString()} ${W.unit??"elementos"}`;return`Muito grande: esperado que ${K.origin??"valor"} fosse ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Muito pequeno: esperado que ${K.origin} tivesse ${J}${K.minimum.toString()} ${W.unit}`;return`Muito pequeno: esperado que ${K.origin} fosse ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Texto inválido: deve começar com "${J.prefix}"`;if(J.format==="ends_with")return`Texto inválido: deve terminar com "${J.suffix}"`;if(J.format==="includes")return`Texto inválido: deve incluir "${J.includes}"`;if(J.format==="regex")return`Texto inválido: deve corresponder ao padrão ${J.pattern}`;return`${Q[J.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":""}: ${D(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 Q7(){return{localeError:FD()}}function Cq($,U,Q,G){let K=Math.abs($),J=K%10,W=K%100;if(W>=11&&W<=19)return G;if(J===1)return U;if(J>=2&&J<=4)return Q;return G}var LD=()=>{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:"ввод"},G={nan:"NaN",number:"число",array:"массив"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Неверный ввод: ожидалось instanceof ${K.expected}, получено ${q}`;return`Неверный ввод: ожидалось ${J}, получено ${q}`}case"invalid_value":if(K.values.length===1)return`Неверный ввод: ожидалось ${k(K.values[0])}`;return`Неверный вариант: ожидалось одно из ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W){let q=Number(K.maximum),j=Cq(q,W.unit.one,W.unit.few,W.unit.many);return`Слишком большое значение: ожидалось, что ${K.origin??"значение"} будет иметь ${J}${K.maximum.toString()} ${j}`}return`Слишком большое значение: ожидалось, что ${K.origin??"значение"} будет ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W){let q=Number(K.minimum),j=Cq(q,W.unit.one,W.unit.few,W.unit.many);return`Слишком маленькое значение: ожидалось, что ${K.origin} будет иметь ${J}${K.minimum.toString()} ${j}`}return`Слишком маленькое значение: ожидалось, что ${K.origin} будет ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Неверная строка: должна начинаться с "${J.prefix}"`;if(J.format==="ends_with")return`Неверная строка: должна заканчиваться на "${J.suffix}"`;if(J.format==="includes")return`Неверная строка: должна содержать "${J.includes}"`;if(J.format==="regex")return`Неверная строка: должна соответствовать шаблону ${J.pattern}`;return`Неверный ${Q[J.format]??K.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${K.divisor}`;case"unrecognized_keys":return`Нераспознанн${K.keys.length>1?"ые":"ый"} ключ${K.keys.length>1?"и":""}: ${D(K.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${K.origin}`;case"invalid_union":return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${K.origin}`;default:return"Неверные входные данные"}}};function G7(){return{localeError:LD()}}var zD=()=>{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"},G={nan:"NaN",number:"število",array:"tabela"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Neveljaven vnos: pričakovano instanceof ${K.expected}, prejeto ${q}`;return`Neveljaven vnos: pričakovano ${J}, prejeto ${q}`}case"invalid_value":if(K.values.length===1)return`Neveljaven vnos: pričakovano ${k(K.values[0])}`;return`Neveljavna možnost: pričakovano eno izmed ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Preveliko: pričakovano, da bo ${K.origin??"vrednost"} imelo ${J}${K.maximum.toString()} ${W.unit??"elementov"}`;return`Preveliko: pričakovano, da bo ${K.origin??"vrednost"} ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Premajhno: pričakovano, da bo ${K.origin} imelo ${J}${K.minimum.toString()} ${W.unit}`;return`Premajhno: pričakovano, da bo ${K.origin} ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Neveljaven niz: mora se začeti z "${J.prefix}"`;if(J.format==="ends_with")return`Neveljaven niz: mora se končati z "${J.suffix}"`;if(J.format==="includes")return`Neveljaven niz: mora vsebovati "${J.includes}"`;if(J.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${J.pattern}`;return`Neveljaven ${Q[J.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č"}: ${D(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 J7(){return{localeError:zD()}}var bD=()=>{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"},G={nan:"NaN",number:"antal",array:"lista"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Ogiltig inmatning: förväntat instanceof ${K.expected}, fick ${q}`;return`Ogiltig inmatning: förväntat ${J}, fick ${q}`}case"invalid_value":if(K.values.length===1)return`Ogiltig inmatning: förväntat ${k(K.values[0])}`;return`Ogiltigt val: förväntade en av ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`För stor(t): förväntade ${K.origin??"värdet"} att ha ${J}${K.maximum.toString()} ${W.unit??"element"}`;return`För stor(t): förväntat ${K.origin??"värdet"} att ha ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`För lite(t): förväntade ${K.origin??"värdet"} att ha ${J}${K.minimum.toString()} ${W.unit}`;return`För lite(t): förväntade ${K.origin??"värdet"} att ha ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Ogiltig sträng: måste börja med "${J.prefix}"`;if(J.format==="ends_with")return`Ogiltig sträng: måste sluta med "${J.suffix}"`;if(J.format==="includes")return`Ogiltig sträng: måste innehålla "${J.includes}"`;if(J.format==="regex")return`Ogiltig sträng: måste matcha mönstret "${J.pattern}"`;return`Ogiltig(t) ${Q[J.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"}: ${D(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 W7(){return{localeError:bD()}}var AD=()=>{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"},G={nan:"NaN",number:"எண்",array:"அணி",null:"வெறுமை"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${K.expected}, பெறப்பட்டது ${q}`;return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${J}, பெறப்பட்டது ${q}`}case"invalid_value":if(K.values.length===1)return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${k(K.values[0])}`;return`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${D(K.values,"|")} இல் ஒன்று`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${K.origin??"மதிப்பு"} ${J}${K.maximum.toString()} ${W.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`;return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${K.origin??"மதிப்பு"} ${J}${K.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${K.origin} ${J}${K.minimum.toString()} ${W.unit} ஆக இருக்க வேண்டும்`;return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${K.origin} ${J}${K.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`தவறான சரம்: "${J.prefix}" இல் தொடங்க வேண்டும்`;if(J.format==="ends_with")return`தவறான சரம்: "${J.suffix}" இல் முடிவடைய வேண்டும்`;if(J.format==="includes")return`தவறான சரம்: "${J.includes}" ஐ உள்ளடக்க வேண்டும்`;if(J.format==="regex")return`தவறான சரம்: ${J.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`;return`தவறான ${Q[J.format]??K.format}`}case"not_multiple_of":return`தவறான எண்: ${K.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${K.keys.length>1?"கள்":""}: ${D(K.keys,", ")}`;case"invalid_key":return`${K.origin} இல் தவறான விசை`;case"invalid_union":return"தவறான உள்ளீடு";case"invalid_element":return`${K.origin} இல் தவறான மதிப்பு`;default:return"தவறான உள்ளீடு"}}};function q7(){return{localeError:AD()}}var OD=()=>{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:"ข้อมูลที่ป้อน"},G={nan:"NaN",number:"ตัวเลข",array:"อาร์เรย์ (Array)",null:"ไม่มีค่า (null)"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${K.expected} แต่ได้รับ ${q}`;return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${J} แต่ได้รับ ${q}`}case"invalid_value":if(K.values.length===1)return`ค่าไม่ถูกต้อง: ควรเป็น ${k(K.values[0])}`;return`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"ไม่เกิน":"น้อยกว่า",W=U(K.origin);if(W)return`เกินกำหนด: ${K.origin??"ค่า"} ควรมี${J} ${K.maximum.toString()} ${W.unit??"รายการ"}`;return`เกินกำหนด: ${K.origin??"ค่า"} ควรมี${J} ${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?"อย่างน้อย":"มากกว่า",W=U(K.origin);if(W)return`น้อยกว่ากำหนด: ${K.origin} ควรมี${J} ${K.minimum.toString()} ${W.unit}`;return`น้อยกว่ากำหนด: ${K.origin} ควรมี${J} ${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${J.prefix}"`;if(J.format==="ends_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${J.suffix}"`;if(J.format==="includes")return`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${J.includes}" อยู่ในข้อความ`;if(J.format==="regex")return`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${J.pattern}`;return`รูปแบบไม่ถูกต้อง: ${Q[J.format]??K.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${K.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${D(K.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${K.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${K.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};function Y7(){return{localeError:OD()}}var RD=()=>{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"},G={nan:"NaN"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Geçersiz değer: beklenen instanceof ${K.expected}, alınan ${q}`;return`Geçersiz değer: beklenen ${J}, alınan ${q}`}case"invalid_value":if(K.values.length===1)return`Geçersiz değer: beklenen ${k(K.values[0])}`;return`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Çok büyük: beklenen ${K.origin??"değer"} ${J}${K.maximum.toString()} ${W.unit??"öğe"}`;return`Çok büyük: beklenen ${K.origin??"değer"} ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Çok küçük: beklenen ${K.origin} ${J}${K.minimum.toString()} ${W.unit}`;return`Çok küçük: beklenen ${K.origin} ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Geçersiz metin: "${J.prefix}" ile başlamalı`;if(J.format==="ends_with")return`Geçersiz metin: "${J.suffix}" ile bitmeli`;if(J.format==="includes")return`Geçersiz metin: "${J.includes}" içermeli`;if(J.format==="regex")return`Geçersiz metin: ${J.pattern} desenine uymalı`;return`Geçersiz ${Q[J.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":""}: ${D(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 j7(){return{localeError:RD()}}var TD=()=>{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:"вхідні дані"},G={nan:"NaN",number:"число",array:"масив"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Неправильні вхідні дані: очікується instanceof ${K.expected}, отримано ${q}`;return`Неправильні вхідні дані: очікується ${J}, отримано ${q}`}case"invalid_value":if(K.values.length===1)return`Неправильні вхідні дані: очікується ${k(K.values[0])}`;return`Неправильна опція: очікується одне з ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Занадто велике: очікується, що ${K.origin??"значення"} ${W.verb} ${J}${K.maximum.toString()} ${W.unit??"елементів"}`;return`Занадто велике: очікується, що ${K.origin??"значення"} буде ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Занадто мале: очікується, що ${K.origin} ${W.verb} ${J}${K.minimum.toString()} ${W.unit}`;return`Занадто мале: очікується, що ${K.origin} буде ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Неправильний рядок: повинен починатися з "${J.prefix}"`;if(J.format==="ends_with")return`Неправильний рядок: повинен закінчуватися на "${J.suffix}"`;if(J.format==="includes")return`Неправильний рядок: повинен містити "${J.includes}"`;if(J.format==="regex")return`Неправильний рядок: повинен відповідати шаблону ${J.pattern}`;return`Неправильний ${Q[J.format]??K.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${K.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${K.keys.length>1?"і":""}: ${D(K.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${K.origin}`;case"invalid_union":return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${K.origin}`;default:return"Неправильні вхідні дані"}}};function O6(){return{localeError:TD()}}function X7(){return O6()}var SD=()=>{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:"ان پٹ"},G={nan:"NaN",number:"نمبر",array:"آرے",null:"نل"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`غلط ان پٹ: instanceof ${K.expected} متوقع تھا، ${q} موصول ہوا`;return`غلط ان پٹ: ${J} متوقع تھا، ${q} موصول ہوا`}case"invalid_value":if(K.values.length===1)return`غلط ان پٹ: ${k(K.values[0])} متوقع تھا`;return`غلط آپشن: ${D(K.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`بہت بڑا: ${K.origin??"ویلیو"} کے ${J}${K.maximum.toString()} ${W.unit??"عناصر"} ہونے متوقع تھے`;return`بہت بڑا: ${K.origin??"ویلیو"} کا ${J}${K.maximum.toString()} ہونا متوقع تھا`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`بہت چھوٹا: ${K.origin} کے ${J}${K.minimum.toString()} ${W.unit} ہونے متوقع تھے`;return`بہت چھوٹا: ${K.origin} کا ${J}${K.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`غلط سٹرنگ: "${J.prefix}" سے شروع ہونا چاہیے`;if(J.format==="ends_with")return`غلط سٹرنگ: "${J.suffix}" پر ختم ہونا چاہیے`;if(J.format==="includes")return`غلط سٹرنگ: "${J.includes}" شامل ہونا چاہیے`;if(J.format==="regex")return`غلط سٹرنگ: پیٹرن ${J.pattern} سے میچ ہونا چاہیے`;return`غلط ${Q[J.format]??K.format}`}case"not_multiple_of":return`غلط نمبر: ${K.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${K.keys.length>1?"ز":""}: ${D(K.keys,"، ")}`;case"invalid_key":return`${K.origin} میں غلط کی`;case"invalid_union":return"غلط ان پٹ";case"invalid_element":return`${K.origin} میں غلط ویلیو`;default:return"غلط ان پٹ"}}};function H7(){return{localeError:SD()}}var CD=()=>{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"},G={nan:"NaN",number:"raqam",array:"massiv"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Noto‘g‘ri kirish: kutilgan instanceof ${K.expected}, qabul qilingan ${q}`;return`Noto‘g‘ri kirish: kutilgan ${J}, qabul qilingan ${q}`}case"invalid_value":if(K.values.length===1)return`Noto‘g‘ri kirish: kutilgan ${k(K.values[0])}`;return`Noto‘g‘ri variant: quyidagilardan biri kutilgan ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Juda katta: kutilgan ${K.origin??"qiymat"} ${J}${K.maximum.toString()} ${W.unit} ${W.verb}`;return`Juda katta: kutilgan ${K.origin??"qiymat"} ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Juda kichik: kutilgan ${K.origin} ${J}${K.minimum.toString()} ${W.unit} ${W.verb}`;return`Juda kichik: kutilgan ${K.origin} ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Noto‘g‘ri satr: "${J.prefix}" bilan boshlanishi kerak`;if(J.format==="ends_with")return`Noto‘g‘ri satr: "${J.suffix}" bilan tugashi kerak`;if(J.format==="includes")return`Noto‘g‘ri satr: "${J.includes}" ni o‘z ichiga olishi kerak`;if(J.format==="regex")return`Noto‘g‘ri satr: ${J.pattern} shabloniga mos kelishi kerak`;return`Noto‘g‘ri ${Q[J.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":""}: ${D(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 B7(){return{localeError:CD()}}var gD=()=>{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"},G={nan:"NaN",number:"số",array:"mảng"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Đầu vào không hợp lệ: mong đợi instanceof ${K.expected}, nhận được ${q}`;return`Đầu vào không hợp lệ: mong đợi ${J}, nhận được ${q}`}case"invalid_value":if(K.values.length===1)return`Đầu vào không hợp lệ: mong đợi ${k(K.values[0])}`;return`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Quá lớn: mong đợi ${K.origin??"giá trị"} ${W.verb} ${J}${K.maximum.toString()} ${W.unit??"phần tử"}`;return`Quá lớn: mong đợi ${K.origin??"giá trị"} ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Quá nhỏ: mong đợi ${K.origin} ${W.verb} ${J}${K.minimum.toString()} ${W.unit}`;return`Quá nhỏ: mong đợi ${K.origin} ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Chuỗi không hợp lệ: phải bắt đầu bằng "${J.prefix}"`;if(J.format==="ends_with")return`Chuỗi không hợp lệ: phải kết thúc bằng "${J.suffix}"`;if(J.format==="includes")return`Chuỗi không hợp lệ: phải bao gồm "${J.includes}"`;if(J.format==="regex")return`Chuỗi không hợp lệ: phải khớp với mẫu ${J.pattern}`;return`${Q[J.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: ${D(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 M7(){return{localeError:gD()}}var ED=()=>{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:"输入"},G={nan:"NaN",number:"数字",array:"数组",null:"空值(null)"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`无效输入:期望 instanceof ${K.expected},实际接收 ${q}`;return`无效输入:期望 ${J},实际接收 ${q}`}case"invalid_value":if(K.values.length===1)return`无效输入:期望 ${k(K.values[0])}`;return`无效选项:期望以下之一 ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`数值过大:期望 ${K.origin??"值"} ${J}${K.maximum.toString()} ${W.unit??"个元素"}`;return`数值过大:期望 ${K.origin??"值"} ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`数值过小:期望 ${K.origin} ${J}${K.minimum.toString()} ${W.unit}`;return`数值过小:期望 ${K.origin} ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`无效字符串:必须以 "${J.prefix}" 开头`;if(J.format==="ends_with")return`无效字符串:必须以 "${J.suffix}" 结尾`;if(J.format==="includes")return`无效字符串:必须包含 "${J.includes}"`;if(J.format==="regex")return`无效字符串:必须满足正则表达式 ${J.pattern}`;return`无效${Q[J.format]??K.format}`}case"not_multiple_of":return`无效数字:必须是 ${K.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${D(K.keys,", ")}`;case"invalid_key":return`${K.origin} 中的键(key)无效`;case"invalid_union":return"无效输入";case"invalid_element":return`${K.origin} 中包含无效值(value)`;default:return"无效输入"}}};function Z7(){return{localeError:ED()}}var yD=()=>{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:"輸入"},G={nan:"NaN"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`無效的輸入值:預期為 instanceof ${K.expected},但收到 ${q}`;return`無效的輸入值:預期為 ${J},但收到 ${q}`}case"invalid_value":if(K.values.length===1)return`無效的輸入值:預期為 ${k(K.values[0])}`;return`無效的選項:預期為以下其中之一 ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`數值過大:預期 ${K.origin??"值"} 應為 ${J}${K.maximum.toString()} ${W.unit??"個元素"}`;return`數值過大:預期 ${K.origin??"值"} 應為 ${J}${K.maximum.toString()}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`數值過小:預期 ${K.origin} 應為 ${J}${K.minimum.toString()} ${W.unit}`;return`數值過小:預期 ${K.origin} 應為 ${J}${K.minimum.toString()}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`無效的字串:必須以 "${J.prefix}" 開頭`;if(J.format==="ends_with")return`無效的字串:必須以 "${J.suffix}" 結尾`;if(J.format==="includes")return`無效的字串:必須包含 "${J.includes}"`;if(J.format==="regex")return`無效的字串:必須符合格式 ${J.pattern}`;return`無效的 ${Q[J.format]??K.format}`}case"not_multiple_of":return`無效的數字:必須為 ${K.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${K.keys.length>1?"們":""}:${D(K.keys,"、")}`;case"invalid_key":return`${K.origin} 中有無效的鍵值`;case"invalid_union":return"無效的輸入值";case"invalid_element":return`${K.origin} 中有無效的值`;default:return"無效的輸入值"}}};function V7(){return{localeError:yD()}}var uD=()=>{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é"},G={nan:"NaN",number:"nọ́mbà",array:"akopọ"};return(K)=>{switch(K.code){case"invalid_type":{let J=G[K.expected]??K.expected,W=x(K.input),q=G[W]??W;if(/^[A-Z]/.test(K.expected))return`Ìbáwọlé aṣìṣe: a ní láti fi instanceof ${K.expected}, àmọ̀ a rí ${q}`;return`Ìbáwọlé aṣìṣe: a ní láti fi ${J}, àmọ̀ a rí ${q}`}case"invalid_value":if(K.values.length===1)return`Ìbáwọlé aṣìṣe: a ní láti fi ${k(K.values[0])}`;return`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${D(K.values,"|")}`;case"too_big":{let J=K.inclusive?"<=":"<",W=U(K.origin);if(W)return`Tó pọ̀ jù: a ní láti jẹ́ pé ${K.origin??"iye"} ${W.verb} ${J}${K.maximum} ${W.unit}`;return`Tó pọ̀ jù: a ní láti jẹ́ ${J}${K.maximum}`}case"too_small":{let J=K.inclusive?">=":">",W=U(K.origin);if(W)return`Kéré ju: a ní láti jẹ́ pé ${K.origin} ${W.verb} ${J}${K.minimum} ${W.unit}`;return`Kéré ju: a ní láti jẹ́ ${J}${K.minimum}`}case"invalid_format":{let J=K;if(J.format==="starts_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${J.prefix}"`;if(J.format==="ends_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${J.suffix}"`;if(J.format==="includes")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${J.includes}"`;if(J.format==="regex")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${J.pattern}`;return`Aṣìṣe: ${Q[J.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ọ̀: ${D(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 v7(){return{localeError:uD()}}var gq,D7=Symbol("ZodOutput"),P7=Symbol("ZodInput");class I7{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 G={...Q,...this._map.get($)};return Object.keys(G).length?G:void 0}return this._map.get($)}has($){return this._map.has($)}}function i0(){return new I7}(gq=globalThis).__zod_globalRegistry??(gq.__zod_globalRegistry=i0());var V$=globalThis.__zod_globalRegistry;function N7($,U){return new $({type:"string",...L(U)})}function _7($,U){return new $({type:"string",coerce:!0,...L(U)})}function o0($,U){return new $({type:"string",format:"email",check:"string_format",abort:!1,...L(U)})}function T6($,U){return new $({type:"string",format:"guid",check:"string_format",abort:!1,...L(U)})}function d0($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,...L(U)})}function p0($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...L(U)})}function t0($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...L(U)})}function a0($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...L(U)})}function S6($,U){return new $({type:"string",format:"url",check:"string_format",abort:!1,...L(U)})}function e0($,U){return new $({type:"string",format:"emoji",check:"string_format",abort:!1,...L(U)})}function s0($,U){return new $({type:"string",format:"nanoid",check:"string_format",abort:!1,...L(U)})}function $2($,U){return new $({type:"string",format:"cuid",check:"string_format",abort:!1,...L(U)})}function U2($,U){return new $({type:"string",format:"cuid2",check:"string_format",abort:!1,...L(U)})}function K2($,U){return new $({type:"string",format:"ulid",check:"string_format",abort:!1,...L(U)})}function Q2($,U){return new $({type:"string",format:"xid",check:"string_format",abort:!1,...L(U)})}function G2($,U){return new $({type:"string",format:"ksuid",check:"string_format",abort:!1,...L(U)})}function J2($,U){return new $({type:"string",format:"ipv4",check:"string_format",abort:!1,...L(U)})}function W2($,U){return new $({type:"string",format:"ipv6",check:"string_format",abort:!1,...L(U)})}function w7($,U){return new $({type:"string",format:"mac",check:"string_format",abort:!1,...L(U)})}function q2($,U){return new $({type:"string",format:"cidrv4",check:"string_format",abort:!1,...L(U)})}function Y2($,U){return new $({type:"string",format:"cidrv6",check:"string_format",abort:!1,...L(U)})}function j2($,U){return new $({type:"string",format:"base64",check:"string_format",abort:!1,...L(U)})}function X2($,U){return new $({type:"string",format:"base64url",check:"string_format",abort:!1,...L(U)})}function H2($,U){return new $({type:"string",format:"e164",check:"string_format",abort:!1,...L(U)})}function B2($,U){return new $({type:"string",format:"jwt",check:"string_format",abort:!1,...L(U)})}var k7={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function x7($,U){return new $({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...L(U)})}function F7($,U){return new $({type:"string",format:"date",check:"string_format",...L(U)})}function L7($,U){return new $({type:"string",format:"time",check:"string_format",precision:null,...L(U)})}function z7($,U){return new $({type:"string",format:"duration",check:"string_format",...L(U)})}function b7($,U){return new $({type:"number",checks:[],...L(U)})}function A7($,U){return new $({type:"number",coerce:!0,checks:[],...L(U)})}function O7($,U){return new $({type:"number",check:"number_format",abort:!1,format:"safeint",...L(U)})}function R7($,U){return new $({type:"number",check:"number_format",abort:!1,format:"float32",...L(U)})}function T7($,U){return new $({type:"number",check:"number_format",abort:!1,format:"float64",...L(U)})}function S7($,U){return new $({type:"number",check:"number_format",abort:!1,format:"int32",...L(U)})}function C7($,U){return new $({type:"number",check:"number_format",abort:!1,format:"uint32",...L(U)})}function g7($,U){return new $({type:"boolean",...L(U)})}function E7($,U){return new $({type:"boolean",coerce:!0,...L(U)})}function y7($,U){return new $({type:"bigint",...L(U)})}function u7($,U){return new $({type:"bigint",coerce:!0,...L(U)})}function f7($,U){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...L(U)})}function m7($,U){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...L(U)})}function h7($,U){return new $({type:"symbol",...L(U)})}function c7($,U){return new $({type:"undefined",...L(U)})}function l7($,U){return new $({type:"null",...L(U)})}function r7($){return new $({type:"any"})}function n7($){return new $({type:"unknown"})}function i7($,U){return new $({type:"never",...L(U)})}function o7($,U){return new $({type:"void",...L(U)})}function d7($,U){return new $({type:"date",...L(U)})}function p7($,U){return new $({type:"date",coerce:!0,...L(U)})}function t7($,U){return new $({type:"nan",...L(U)})}function e$($,U){return new C0({check:"less_than",...L(U),value:$,inclusive:!1})}function R$($,U){return new C0({check:"less_than",...L(U),value:$,inclusive:!0})}function s$($,U){return new g0({check:"greater_than",...L(U),value:$,inclusive:!1})}function _$($,U){return new g0({check:"greater_than",...L(U),value:$,inclusive:!0})}function M2($){return s$(0,$)}function Z2($){return e$(0,$)}function V2($){return R$(0,$)}function v2($){return _$(0,$)}function x1($,U){return new t8({check:"multiple_of",...L(U),value:$})}function F1($,U){return new s8({check:"max_size",...L(U),maximum:$})}function $1($,U){return new $3({check:"min_size",...L(U),minimum:$})}function a1($,U){return new U3({check:"size_equals",...L(U),size:$})}function e1($,U){return new K3({check:"max_length",...L(U),maximum:$})}function Y1($,U){return new Q3({check:"min_length",...L(U),minimum:$})}function s1($,U){return new G3({check:"length_equals",...L(U),length:$})}function L4($,U){return new J3({check:"string_format",format:"regex",...L(U),pattern:$})}function z4($){return new W3({check:"string_format",format:"lowercase",...L($)})}function b4($){return new q3({check:"string_format",format:"uppercase",...L($)})}function A4($,U){return new Y3({check:"string_format",format:"includes",...L(U),includes:$})}function O4($,U){return new j3({check:"string_format",format:"starts_with",...L(U),prefix:$})}function R4($,U){return new X3({check:"string_format",format:"ends_with",...L(U),suffix:$})}function D2($,U,Q){return new H3({check:"property",property:$,schema:U,...L(Q)})}function T4($,U){return new B3({check:"mime_type",mime:$,...L(U)})}function o$($){return new M3({check:"overwrite",tx:$})}function S4($){return o$((U)=>U.normalize($))}function C4(){return o$(($)=>$.trim())}function g4(){return o$(($)=>$.toLowerCase())}function E4(){return o$(($)=>$.toUpperCase())}function y4(){return o$(($)=>H8($))}function a7($,U,Q){return new $({type:"array",element:U,...L(Q)})}function mD($,U,Q){return new $({type:"union",options:U,...L(Q)})}function hD($,U,Q){return new $({type:"union",options:U,inclusive:!1,...L(Q)})}function cD($,U,Q,G){return new $({type:"union",options:Q,discriminator:U,...L(G)})}function lD($,U,Q){return new $({type:"intersection",left:U,right:Q})}function rD($,U,Q,G){let K=Q instanceof y;return new $({type:"tuple",items:U,rest:K?Q:null,...L(K?G:Q)})}function nD($,U,Q,G){return new $({type:"record",keyType:U,valueType:Q,...L(G)})}function iD($,U,Q,G){return new $({type:"map",keyType:U,valueType:Q,...L(G)})}function oD($,U,Q){return new $({type:"set",valueType:U,...L(Q)})}function dD($,U,Q){let G=Array.isArray(U)?Object.fromEntries(U.map((K)=>[K,K])):U;return new $({type:"enum",entries:G,...L(Q)})}function pD($,U,Q){return new $({type:"enum",entries:U,...L(Q)})}function tD($,U,Q){return new $({type:"literal",values:Array.isArray(U)?U:[U],...L(Q)})}function e7($,U){return new $({type:"file",...L(U)})}function aD($,U){return new $({type:"transform",transform:U})}function eD($,U){return new $({type:"optional",innerType:U})}function sD($,U){return new $({type:"nullable",innerType:U})}function $P($,U,Q){return new $({type:"default",innerType:U,get defaultValue(){return typeof Q==="function"?Q():M8(Q)}})}function UP($,U,Q){return new $({type:"nonoptional",innerType:U,...L(Q)})}function KP($,U){return new $({type:"success",innerType:U})}function QP($,U,Q){return new $({type:"catch",innerType:U,catchValue:typeof Q==="function"?Q:()=>Q})}function GP($,U,Q){return new $({type:"pipe",in:U,out:Q})}function JP($,U){return new $({type:"readonly",innerType:U})}function WP($,U,Q){return new $({type:"template_literal",parts:U,...L(Q)})}function qP($,U){return new $({type:"lazy",getter:U})}function YP($,U){return new $({type:"promise",innerType:U})}function s7($,U,Q){let G=L(Q);return G.abort??(G.abort=!0),new $({type:"custom",check:"custom",fn:U,...G})}function $5($,U,Q){return new $({type:"custom",check:"custom",fn:U,...L(Q)})}function U5($){let U=Eq((Q)=>{return Q.addIssue=(G)=>{if(typeof G==="string")Q.issues.push(I4(G,Q.value,U._zod.def));else{let K=G;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(I4(K))}},$(Q.value,Q)});return U}function Eq($,U){let Q=new a({check:"custom",...L(U)});return Q._zod.check=$,Q}function K5($){let U=new a({check:"describe"});return U._zod.onattach=[(Q)=>{let G=V$.get(Q)??{};V$.add(Q,{...G,description:$})}],U._zod.check=()=>{},U}function Q5($){let U=new a({check:"meta"});return U._zod.onattach=[(Q)=>{let G=V$.get(Q)??{};V$.add(Q,{...G,...$})}],U._zod.check=()=>{},U}function G5($,U){let Q=L(U),G=Q.truthy??["true","1","yes","on","y","enabled"],K=Q.falsy??["false","0","no","off","n","disabled"];if(Q.case!=="sensitive")G=G.map((N)=>typeof N==="string"?N.toLowerCase():N),K=K.map((N)=>typeof N==="string"?N.toLowerCase():N);let J=new Set(G),W=new Set(K),q=$.Codec??L6,j=$.Boolean??x6,B=new($.String??t1)({type:"string",error:Q.error}),Z=new j({type:"boolean",error:Q.error}),V=new q({type:"pipe",in:B,out:Z,transform:(N,T)=>{let f=N;if(Q.case!=="sensitive")f=f.toLowerCase();if(J.has(f))return!0;else if(W.has(f))return!1;else return T.issues.push({code:"invalid_value",expected:"stringbool",values:[...J,...W],input:T.value,inst:V,continue:!1}),{}},reverseTransform:(N,T)=>{if(N===!0)return G[0]||"true";else return K[0]||"false"},error:Q.error});return V}function u4($,U,Q,G={}){let K=L(G),J={...L(G),check:"string_format",type:"string",format:U,fn:typeof Q==="function"?Q:(q)=>Q.test(q),...K};if(Q instanceof RegExp)J.pattern=Q;return new $(J)}function L1($){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??V$,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 d($,U,Q={path:[],schemaPath:[]}){var G;let K=$._zod.def,J=U.seen.get($);if(J){if(J.count++,Q.schemaPath.includes($))J.cycle=Q.path;return J.schema}let W={schema:{},count:1,cycle:void 0,path:Q.path};U.seen.set($,W);let q=$._zod.toJSONSchema?.();if(q)W.schema=q;else{let B={...Q,schemaPath:[...Q.schemaPath,$],path:Q.path};if($._zod.processJSONSchema)$._zod.processJSONSchema(U,W.schema,B);else{let V=W.schema,N=U.processors[K.type];if(!N)throw Error(`[toJSONSchema]: Non-representable type encountered: ${K.type}`);N($,U,V,B)}let Z=$._zod.parent;if(Z){if(!W.ref)W.ref=Z;d(Z,U,B),U.seen.get(Z).isParent=!0}}let j=U.metadataRegistry.get($);if(j)Object.assign(W.schema,j);if(U.io==="input"&&w$($))delete W.schema.examples,delete W.schema.default;if(U.io==="input"&&W.schema._prefault)(G=W.schema).default??(G.default=W.schema._prefault);return delete W.schema._prefault,U.seen.get($).schema}function z1($,U){let Q=$.seen.get(U);if(!Q)throw Error("Unprocessed schema. This is a bug in Zod.");let G=new Map;for(let W of $.seen.entries()){let q=$.metadataRegistry.get(W[0])?.id;if(q){let j=G.get(q);if(j&&j!==W[0])throw Error(`Duplicate schema id "${q}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);G.set(q,W[0])}}let K=(W)=>{let q=$.target==="draft-2020-12"?"$defs":"definitions";if($.external){let Z=$.external.registry.get(W[0])?.id,V=$.external.uri??((T)=>T);if(Z)return{ref:V(Z)};let N=W[1].defId??W[1].schema.id??`schema${$.counter++}`;return W[1].defId=N,{defId:N,ref:`${V("__shared")}#/${q}/${N}`}}if(W[1]===Q)return{ref:"#"};let X=`${"#"}/${q}/`,B=W[1].schema.id??`__schema${$.counter++}`;return{defId:B,ref:X+B}},J=(W)=>{if(W[1].schema.$ref)return;let q=W[1],{ref:j,defId:X}=K(W);if(q.def={...q.schema},X)q.defId=X;let B=q.schema;for(let Z in B)delete B[Z];B.$ref=j};if($.cycles==="throw")for(let W of $.seen.entries()){let q=W[1];if(q.cycle)throw Error(`Cycle detected: #/${q.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>
93
93
 
94
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let W of $.seen.entries()){let q=W[1];if(U===W[0]){J(W);continue}if($.external){let X=$.external.registry.get(W[0])?.id;if(U!==W[0]&&X){J(W);continue}}if($.metadataRegistry.get(W[0])?.id){J(W);continue}if(q.cycle){J(W);continue}if(q.count>1){if($.reused==="ref"){J(W);continue}}}}function b1($,U){let Q=$.seen.get(U);if(!Q)throw Error("Unprocessed schema. This is a bug in Zod.");let G=(W)=>{let q=$.seen.get(W);if(q.ref===null)return;let j=q.def??q.schema,X={...j},B=q.ref;if(q.ref=null,B){G(B);let V=$.seen.get(B),N=V.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,X),W._zod.parent===B)for(let f in j){if(f==="$ref"||f==="allOf")continue;if(!(f in X))delete j[f]}if(N.$ref&&V.def)for(let f in j){if(f==="$ref"||f==="allOf")continue;if(f in V.def&&JSON.stringify(j[f])===JSON.stringify(V.def[f]))delete j[f]}}let Z=W._zod.parent;if(Z&&Z!==B){G(Z);let V=$.seen.get(Z);if(V?.schema.$ref){if(j.$ref=V.schema.$ref,V.def)for(let N in j){if(N==="$ref"||N==="allOf")continue;if(N in V.def&&JSON.stringify(j[N])===JSON.stringify(V.def[N]))delete j[N]}}}$.override({zodSchema:W,jsonSchema:j,path:q.path??[]})};for(let W of[...$.seen.entries()].reverse())G(W[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 W=$.external.registry.get(U)?.id;if(!W)throw Error("Schema is missing an `id` property");K.$id=$.external.uri(W)}Object.assign(K,Q.def??Q.schema);let J=$.external?.defs??{};for(let W of $.seen.entries()){let q=W[1];if(q.def&&q.defId)J[q.defId]=q.def}if($.external);else if(Object.keys(J).length>0)if($.target==="draft-2020-12")K.$defs=J;else K.definitions=J;try{let W=JSON.parse(JSON.stringify(K));return Object.defineProperty(W,"~standard",{value:{...U["~standard"],jsonSchema:{input:f4(U,"input",$.processors),output:f4(U,"output",$.processors)}},enumerable:!1,writable:!1}),W}catch(W){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 G=$._zod.def;if(G.type==="transform")return!0;if(G.type==="array")return w$(G.element,Q);if(G.type==="set")return w$(G.valueType,Q);if(G.type==="lazy")return w$(G.getter(),Q);if(G.type==="promise"||G.type==="optional"||G.type==="nonoptional"||G.type==="nullable"||G.type==="readonly"||G.type==="default"||G.type==="prefault")return w$(G.innerType,Q);if(G.type==="intersection")return w$(G.left,Q)||w$(G.right,Q);if(G.type==="record"||G.type==="map")return w$(G.keyType,Q)||w$(G.valueType,Q);if(G.type==="pipe")return w$(G.in,Q)||w$(G.out,Q);if(G.type==="object"){for(let K in G.shape)if(w$(G.shape[K],Q))return!0;return!1}if(G.type==="union"){for(let K of G.options)if(w$(K,Q))return!0;return!1}if(G.type==="tuple"){for(let K of G.items)if(w$(K,Q))return!0;if(G.rest&&w$(G.rest,Q))return!0;return!1}return!1}var J5=($,U={})=>(Q)=>{let G=L1({...Q,processors:U});return d($,G),z1(G,$),b1(G,$)},f4=($,U,Q={})=>(G)=>{let{libraryOptions:K,target:J}=G??{},W=L1({...K??{},target:J,io:U,processors:Q});return d($,W),z1(W,$),b1(W,$)};var jP={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},W5=($,U,Q,G)=>{let K=Q;K.type="string";let{minimum:J,maximum:W,format:q,patterns:j,contentEncoding:X}=$._zod.bag;if(typeof J==="number")K.minLength=J;if(typeof W==="number")K.maxLength=W;if(q){if(K.format=jP[q]??q,K.format==="")delete K.format;if(q==="time")delete K.format}if(X)K.contentEncoding=X;if(j&&j.size>0){let B=[...j];if(B.length===1)K.pattern=B[0].source;else if(B.length>1)K.allOf=[...B.map((Z)=>({...U.target==="draft-07"||U.target==="draft-04"||U.target==="openapi-3.0"?{type:"string"}:{},pattern:Z.source}))]}},q5=($,U,Q,G)=>{let K=Q,{minimum:J,maximum:W,format:q,multipleOf:j,exclusiveMaximum:X,exclusiveMinimum:B}=$._zod.bag;if(typeof q==="string"&&q.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 J==="number"){if(K.minimum=J,typeof B==="number"&&U.target!=="draft-04")if(B>=J)delete K.minimum;else delete K.exclusiveMinimum}if(typeof X==="number")if(U.target==="draft-04"||U.target==="openapi-3.0")K.maximum=X,K.exclusiveMaximum=!0;else K.exclusiveMaximum=X;if(typeof W==="number"){if(K.maximum=W,typeof X==="number"&&U.target!=="draft-04")if(X<=W)delete K.maximum;else delete K.exclusiveMaximum}if(typeof j==="number")K.multipleOf=j},Y5=($,U,Q,G)=>{Q.type="boolean"},j5=($,U,Q,G)=>{if(U.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},X5=($,U,Q,G)=>{if(U.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},H5=($,U,Q,G)=>{if(U.target==="openapi-3.0")Q.type="string",Q.nullable=!0,Q.enum=[null];else Q.type="null"},B5=($,U,Q,G)=>{if(U.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},M5=($,U,Q,G)=>{if(U.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},Z5=($,U,Q,G)=>{Q.not={}},V5=($,U,Q,G)=>{},v5=($,U,Q,G)=>{},D5=($,U,Q,G)=>{if(U.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},P5=($,U,Q,G)=>{let K=$._zod.def,J=M6(K.entries);if(J.every((W)=>typeof W==="number"))Q.type="number";if(J.every((W)=>typeof W==="string"))Q.type="string";Q.enum=J},I5=($,U,Q,G)=>{let K=$._zod.def,J=[];for(let W of K.values)if(W===void 0){if(U.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof W==="bigint")if(U.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else J.push(Number(W));else J.push(W);if(J.length===0);else if(J.length===1){let W=J[0];if(Q.type=W===null?"null":typeof W,U.target==="draft-04"||U.target==="openapi-3.0")Q.enum=[W];else Q.const=W}else{if(J.every((W)=>typeof W==="number"))Q.type="number";if(J.every((W)=>typeof W==="string"))Q.type="string";if(J.every((W)=>typeof W==="boolean"))Q.type="boolean";if(J.every((W)=>W===null))Q.type="null";Q.enum=J}},N5=($,U,Q,G)=>{if(U.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},_5=($,U,Q,G)=>{let K=Q,J=$._zod.pattern;if(!J)throw Error("Pattern not found in template literal");K.type="string",K.pattern=J.source},w5=($,U,Q,G)=>{let K=Q,J={type:"string",format:"binary",contentEncoding:"binary"},{minimum:W,maximum:q,mime:j}=$._zod.bag;if(W!==void 0)J.minLength=W;if(q!==void 0)J.maxLength=q;if(j)if(j.length===1)J.contentMediaType=j[0],Object.assign(K,J);else Object.assign(K,J),K.anyOf=j.map((X)=>({contentMediaType:X}));else Object.assign(K,J)},k5=($,U,Q,G)=>{Q.type="boolean"},x5=($,U,Q,G)=>{if(U.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},F5=($,U,Q,G)=>{if(U.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},L5=($,U,Q,G)=>{if(U.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},z5=($,U,Q,G)=>{if(U.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},b5=($,U,Q,G)=>{if(U.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},A5=($,U,Q,G)=>{let K=Q,J=$._zod.def,{minimum:W,maximum:q}=$._zod.bag;if(typeof W==="number")K.minItems=W;if(typeof q==="number")K.maxItems=q;K.type="array",K.items=d(J.element,U,{...G,path:[...G.path,"items"]})},O5=($,U,Q,G)=>{let K=Q,J=$._zod.def;K.type="object",K.properties={};let W=J.shape;for(let X in W)K.properties[X]=d(W[X],U,{...G,path:[...G.path,"properties",X]});let q=new Set(Object.keys(W)),j=new Set([...q].filter((X)=>{let B=J.shape[X]._zod;if(U.io==="input")return B.optin===void 0;else return B.optout===void 0}));if(j.size>0)K.required=Array.from(j);if(J.catchall?._zod.def.type==="never")K.additionalProperties=!1;else if(!J.catchall){if(U.io==="output")K.additionalProperties=!1}else if(J.catchall)K.additionalProperties=d(J.catchall,U,{...G,path:[...G.path,"additionalProperties"]})},I2=($,U,Q,G)=>{let K=$._zod.def,J=K.inclusive===!1,W=K.options.map((q,j)=>d(q,U,{...G,path:[...G.path,J?"oneOf":"anyOf",j]}));if(J)Q.oneOf=W;else Q.anyOf=W},R5=($,U,Q,G)=>{let K=$._zod.def,J=d(K.left,U,{...G,path:[...G.path,"allOf",0]}),W=d(K.right,U,{...G,path:[...G.path,"allOf",1]}),q=(X)=>("allOf"in X)&&Object.keys(X).length===1,j=[...q(J)?J.allOf:[J],...q(W)?W.allOf:[W]];Q.allOf=j},T5=($,U,Q,G)=>{let K=Q,J=$._zod.def;K.type="array";let W=U.target==="draft-2020-12"?"prefixItems":"items",q=U.target==="draft-2020-12"?"items":U.target==="openapi-3.0"?"items":"additionalItems",j=J.items.map((V,N)=>d(V,U,{...G,path:[...G.path,W,N]})),X=J.rest?d(J.rest,U,{...G,path:[...G.path,q,...U.target==="openapi-3.0"?[J.items.length]:[]]}):null;if(U.target==="draft-2020-12"){if(K.prefixItems=j,X)K.items=X}else if(U.target==="openapi-3.0"){if(K.items={anyOf:j},X)K.items.anyOf.push(X);if(K.minItems=j.length,!X)K.maxItems=j.length}else if(K.items=j,X)K.additionalItems=X;let{minimum:B,maximum:Z}=$._zod.bag;if(typeof B==="number")K.minItems=B;if(typeof Z==="number")K.maxItems=Z},S5=($,U,Q,G)=>{let K=Q,J=$._zod.def;K.type="object";let W=J.keyType,j=W._zod.bag?.patterns;if(J.mode==="loose"&&j&&j.size>0){let B=d(J.valueType,U,{...G,path:[...G.path,"patternProperties","*"]});K.patternProperties={};for(let Z of j)K.patternProperties[Z.source]=B}else{if(U.target==="draft-07"||U.target==="draft-2020-12")K.propertyNames=d(J.keyType,U,{...G,path:[...G.path,"propertyNames"]});K.additionalProperties=d(J.valueType,U,{...G,path:[...G.path,"additionalProperties"]})}let X=W._zod.values;if(X){let B=[...X].filter((Z)=>typeof Z==="string"||typeof Z==="number");if(B.length>0)K.required=B}},C5=($,U,Q,G)=>{let K=$._zod.def,J=d(K.innerType,U,G),W=U.seen.get($);if(U.target==="openapi-3.0")W.ref=K.innerType,Q.nullable=!0;else Q.anyOf=[J,{type:"null"}]},g5=($,U,Q,G)=>{let K=$._zod.def;d(K.innerType,U,G);let J=U.seen.get($);J.ref=K.innerType},E5=($,U,Q,G)=>{let K=$._zod.def;d(K.innerType,U,G);let J=U.seen.get($);J.ref=K.innerType,Q.default=JSON.parse(JSON.stringify(K.defaultValue))},y5=($,U,Q,G)=>{let K=$._zod.def;d(K.innerType,U,G);let J=U.seen.get($);if(J.ref=K.innerType,U.io==="input")Q._prefault=JSON.parse(JSON.stringify(K.defaultValue))},u5=($,U,Q,G)=>{let K=$._zod.def;d(K.innerType,U,G);let J=U.seen.get($);J.ref=K.innerType;let W;try{W=K.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}Q.default=W},f5=($,U,Q,G)=>{let K=$._zod.def,J=U.io==="input"?K.in._zod.def.type==="transform"?K.out:K.in:K.out;d(J,U,G);let W=U.seen.get($);W.ref=J},m5=($,U,Q,G)=>{let K=$._zod.def;d(K.innerType,U,G);let J=U.seen.get($);J.ref=K.innerType,Q.readOnly=!0},h5=($,U,Q,G)=>{let K=$._zod.def;d(K.innerType,U,G);let J=U.seen.get($);J.ref=K.innerType},N2=($,U,Q,G)=>{let K=$._zod.def;d(K.innerType,U,G);let J=U.seen.get($);J.ref=K.innerType},c5=($,U,Q,G)=>{let K=$._zod.innerType;d(K,U,G);let J=U.seen.get($);J.ref=K},P2={string:W5,number:q5,boolean:Y5,bigint:j5,symbol:X5,null:H5,undefined:B5,void:M5,never:Z5,any:V5,unknown:v5,date:D5,enum:P5,literal:I5,nan:N5,template_literal:_5,file:w5,success:k5,custom:x5,function:F5,transform:L5,map:z5,set:b5,array:A5,object:O5,union:I2,intersection:R5,tuple:T5,record:S5,nullable:C5,nonoptional:g5,default:E5,prefault:y5,catch:u5,pipe:f5,readonly:m5,promise:h5,optional:N2,lazy:c5};function _2($,U){if("_idmap"in $){let G=$,K=L1({...U,processors:P2}),J={};for(let j of G._idmap.entries()){let[X,B]=j;d(B,K)}let W={},q={registry:G,uri:U?.uri,defs:J};K.external=q;for(let j of G._idmap.entries()){let[X,B]=j;z1(K,B),W[X]=b1(K,B)}if(Object.keys(J).length>0){let j=K.target==="draft-2020-12"?"$defs":"definitions";W.__shared={[j]:J}}return{schemas:W}}let Q=L1({...U,processors:P2});return d($,Q),z1(Q,$),b1(Q,$)}class l5{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=L1({processors:P2,target:U,...$?.metadata&&{metadata:$.metadata},...$?.unrepresentable&&{unrepresentable:$.unrepresentable},...$?.override&&{override:$.override},...$?.io&&{io:$.io}})}process($,U={path:[],schemaPath:[]}){return d($,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}z1(this.ctx,$);let Q=b1(this.ctx,$),{"~standard":G,...K}=Q;return K}}var yq={};var C6={};K1(C6,{xor:()=>AY,xid:()=>eq,void:()=>kY,uuidv7:()=>rq,uuidv6:()=>lq,uuidv4:()=>cq,uuid:()=>hq,url:()=>nq,unknown:()=>$4,union:()=>d2,undefined:()=>_Y,ulid:()=>aq,uint64:()=>IY,uint32:()=>vY,tuple:()=>kK,transform:()=>t2,templateLiteral:()=>cY,symbol:()=>NY,superRefine:()=>tK,success:()=>fY,stringbool:()=>tY,stringFormat:()=>jY,string:()=>z2,strictObject:()=>zY,set:()=>CY,refine:()=>pK,record:()=>xK,readonly:()=>lK,promise:()=>lY,preprocess:()=>eY,prefault:()=>EK,pipe:()=>u6,partialRecord:()=>RY,optional:()=>E6,object:()=>LY,number:()=>qK,nullish:()=>uY,nullable:()=>y6,null:()=>BK,nonoptional:()=>yK,never:()=>o2,nativeEnum:()=>gY,nanoid:()=>dq,nan:()=>mY,meta:()=>dY,map:()=>SY,mac:()=>UY,looseRecord:()=>TY,looseObject:()=>bY,literal:()=>EY,lazy:()=>iK,ksuid:()=>sq,keyof:()=>FY,jwt:()=>YY,json:()=>aY,ipv6:()=>KY,ipv4:()=>$Y,intersection:()=>_K,int64:()=>PY,int32:()=>VY,int:()=>b2,instanceof:()=>pY,httpUrl:()=>iq,hostname:()=>XY,hex:()=>HY,hash:()=>BY,guid:()=>mq,function:()=>rY,float64:()=>ZY,float32:()=>MY,file:()=>yY,exactOptional:()=>RK,enum:()=>p2,emoji:()=>oq,email:()=>fq,e164:()=>qY,discriminatedUnion:()=>OY,describe:()=>oY,date:()=>xY,custom:()=>iY,cuid2:()=>tq,cuid:()=>pq,codec:()=>hY,cidrv6:()=>GY,cidrv4:()=>QY,check:()=>nY,catch:()=>mK,boolean:()=>YK,bigint:()=>DY,base64url:()=>WY,base64:()=>JY,array:()=>h6,any:()=>wY,_function:()=>rY,_default:()=>CK,_ZodString:()=>A2,ZodXor:()=>PK,ZodXID:()=>E2,ZodVoid:()=>vK,ZodUnknown:()=>ZK,ZodUnion:()=>l6,ZodUndefined:()=>XK,ZodUUID:()=>U1,ZodURL:()=>f6,ZodULID:()=>g2,ZodType:()=>m,ZodTuple:()=>wK,ZodTransform:()=>AK,ZodTemplateLiteral:()=>rK,ZodSymbol:()=>jK,ZodSuccess:()=>uK,ZodStringFormat:()=>t,ZodString:()=>c4,ZodSet:()=>LK,ZodRecord:()=>r6,ZodReadonly:()=>cK,ZodPromise:()=>oK,ZodPrefault:()=>gK,ZodPipe:()=>s2,ZodOptional:()=>a2,ZodObject:()=>c6,ZodNumberFormat:()=>U4,ZodNumber:()=>r4,ZodNullable:()=>TK,ZodNull:()=>HK,ZodNonOptional:()=>e2,ZodNever:()=>VK,ZodNanoID:()=>T2,ZodNaN:()=>hK,ZodMap:()=>FK,ZodMAC:()=>WK,ZodLiteral:()=>zK,ZodLazy:()=>nK,ZodKSUID:()=>y2,ZodJWT:()=>n2,ZodIntersection:()=>NK,ZodIPv6:()=>f2,ZodIPv4:()=>u2,ZodGUID:()=>g6,ZodFunction:()=>dK,ZodFile:()=>bK,ZodExactOptional:()=>OK,ZodEnum:()=>h4,ZodEmoji:()=>R2,ZodEmail:()=>O2,ZodE164:()=>r2,ZodDiscriminatedUnion:()=>IK,ZodDefault:()=>SK,ZodDate:()=>m6,ZodCustomStringFormat:()=>l4,ZodCustom:()=>n6,ZodCodec:()=>$U,ZodCatch:()=>fK,ZodCUID2:()=>C2,ZodCUID:()=>S2,ZodCIDRv6:()=>h2,ZodCIDRv4:()=>m2,ZodBoolean:()=>n4,ZodBigIntFormat:()=>i2,ZodBigInt:()=>i4,ZodBase64URL:()=>l2,ZodBase64:()=>c2,ZodArray:()=>DK,ZodAny:()=>MK});var w2={};K1(w2,{uppercase:()=>b4,trim:()=>C4,toUpperCase:()=>E4,toLowerCase:()=>g4,startsWith:()=>O4,slugify:()=>y4,size:()=>a1,regex:()=>L4,property:()=>D2,positive:()=>M2,overwrite:()=>o$,normalize:()=>S4,nonpositive:()=>V2,nonnegative:()=>v2,negative:()=>Z2,multipleOf:()=>x1,minSize:()=>$1,minLength:()=>Y1,mime:()=>T4,maxSize:()=>F1,maxLength:()=>e1,lte:()=>R$,lt:()=>e$,lowercase:()=>z4,length:()=>s1,includes:()=>A4,gte:()=>_$,gt:()=>s$,endsWith:()=>R4});var m4={};K1(m4,{time:()=>i5,duration:()=>o5,datetime:()=>r5,date:()=>n5,ZodISOTime:()=>F2,ZodISODuration:()=>L2,ZodISODateTime:()=>k2,ZodISODate:()=>x2});var k2=v("ZodISODateTime",($,U)=>{z3.init($,U),t.init($,U)});function r5($){return x7(k2,$)}var x2=v("ZodISODate",($,U)=>{b3.init($,U),t.init($,U)});function n5($){return F7(x2,$)}var F2=v("ZodISOTime",($,U)=>{A3.init($,U),t.init($,U)});function i5($){return L7(F2,$)}var L2=v("ZodISODuration",($,U)=>{O3.init($,U),t.init($,U)});function o5($){return z7(L2,$)}var uq=($,U)=>{P6.init($,U),$.name="ZodError",Object.defineProperties($,{format:{value:(Q)=>N6($,Q)},flatten:{value:(Q)=>I6($,Q)},addIssue:{value:(Q)=>{$.issues.push(Q),$.message=JSON.stringify($.issues,D4,2)}},addIssues:{value:(Q)=>{$.issues.push(...Q),$.message=JSON.stringify($.issues,D4,2)}},isEmpty:{get(){return $.issues.length===0}}})},HP=v("ZodError",uq),z$=v("ZodError",uq,{Parent:Error});var d5=N4(z$),p5=_4(z$),t5=w4(z$),a5=k4(z$),e5=F0(z$),s5=L0(z$),$K=z0(z$),UK=b0(z$),KK=A0(z$),QK=O0(z$),GK=R0(z$),JK=T0(z$);var m=v("ZodType",($,U)=>{return y.init($,U),Object.assign($["~standard"],{jsonSchema:{input:f4($,"input"),output:f4($,"output")}}),$.toJSONSchema=J5($,{}),$.def=U,$.type=U.type,Object.defineProperty($,"_def",{value:U}),$.check=(...Q)=>{return $.clone(F.mergeDefs(U,{checks:[...U.checks??[],...Q.map((G)=>typeof G==="function"?{_zod:{check:G,def:{check:"custom"},onattach:[]}}:G)]}),{parent:!0})},$.with=$.check,$.clone=(Q,G)=>N$($,Q,G),$.brand=()=>$,$.register=(Q,G)=>{return Q.add($,G),$},$.parse=(Q,G)=>d5($,Q,G,{callee:$.parse}),$.safeParse=(Q,G)=>t5($,Q,G),$.parseAsync=async(Q,G)=>p5($,Q,G,{callee:$.parseAsync}),$.safeParseAsync=async(Q,G)=>a5($,Q,G),$.spa=$.safeParseAsync,$.encode=(Q,G)=>e5($,Q,G),$.decode=(Q,G)=>s5($,Q,G),$.encodeAsync=async(Q,G)=>$K($,Q,G),$.decodeAsync=async(Q,G)=>UK($,Q,G),$.safeEncode=(Q,G)=>KK($,Q,G),$.safeDecode=(Q,G)=>QK($,Q,G),$.safeEncodeAsync=async(Q,G)=>GK($,Q,G),$.safeDecodeAsync=async(Q,G)=>JK($,Q,G),$.refine=(Q,G)=>$.check(pK(Q,G)),$.superRefine=(Q)=>$.check(tK(Q)),$.overwrite=(Q)=>$.check(o$(Q)),$.optional=()=>E6($),$.exactOptional=()=>RK($),$.nullable=()=>y6($),$.nullish=()=>E6(y6($)),$.nonoptional=(Q)=>yK($,Q),$.array=()=>h6($),$.or=(Q)=>d2([$,Q]),$.and=(Q)=>_K($,Q),$.transform=(Q)=>u6($,t2(Q)),$.default=(Q)=>CK($,Q),$.prefault=(Q)=>EK($,Q),$.catch=(Q)=>mK($,Q),$.pipe=(Q)=>u6($,Q),$.readonly=()=>lK($),$.describe=(Q)=>{let G=$.clone();return V$.add(G,{description:Q}),G},Object.defineProperty($,"description",{get(){return V$.get($)?.description},configurable:!0}),$.meta=(...Q)=>{if(Q.length===0)return V$.get($);let G=$.clone();return V$.add(G,Q[0]),G},$.isOptional=()=>$.safeParse(void 0).success,$.isNullable=()=>$.safeParse(null).success,$.apply=(Q)=>Q($),$}),A2=v("_ZodString",($,U)=>{t1.init($,U),m.init($,U),$._zod.processJSONSchema=(G,K,J)=>W5($,G,K,J);let Q=$._zod.bag;$.format=Q.format??null,$.minLength=Q.minimum??null,$.maxLength=Q.maximum??null,$.regex=(...G)=>$.check(L4(...G)),$.includes=(...G)=>$.check(A4(...G)),$.startsWith=(...G)=>$.check(O4(...G)),$.endsWith=(...G)=>$.check(R4(...G)),$.min=(...G)=>$.check(Y1(...G)),$.max=(...G)=>$.check(e1(...G)),$.length=(...G)=>$.check(s1(...G)),$.nonempty=(...G)=>$.check(Y1(1,...G)),$.lowercase=(G)=>$.check(z4(G)),$.uppercase=(G)=>$.check(b4(G)),$.trim=()=>$.check(C4()),$.normalize=(...G)=>$.check(S4(...G)),$.toLowerCase=()=>$.check(g4()),$.toUpperCase=()=>$.check(E4()),$.slugify=()=>$.check(y4())}),c4=v("ZodString",($,U)=>{t1.init($,U),A2.init($,U),$.email=(Q)=>$.check(o0(O2,Q)),$.url=(Q)=>$.check(S6(f6,Q)),$.jwt=(Q)=>$.check(B2(n2,Q)),$.emoji=(Q)=>$.check(e0(R2,Q)),$.guid=(Q)=>$.check(T6(g6,Q)),$.uuid=(Q)=>$.check(d0(U1,Q)),$.uuidv4=(Q)=>$.check(p0(U1,Q)),$.uuidv6=(Q)=>$.check(t0(U1,Q)),$.uuidv7=(Q)=>$.check(a0(U1,Q)),$.nanoid=(Q)=>$.check(s0(T2,Q)),$.guid=(Q)=>$.check(T6(g6,Q)),$.cuid=(Q)=>$.check($2(S2,Q)),$.cuid2=(Q)=>$.check(U2(C2,Q)),$.ulid=(Q)=>$.check(K2(g2,Q)),$.base64=(Q)=>$.check(j2(c2,Q)),$.base64url=(Q)=>$.check(X2(l2,Q)),$.xid=(Q)=>$.check(Q2(E2,Q)),$.ksuid=(Q)=>$.check(G2(y2,Q)),$.ipv4=(Q)=>$.check(J2(u2,Q)),$.ipv6=(Q)=>$.check(W2(f2,Q)),$.cidrv4=(Q)=>$.check(q2(m2,Q)),$.cidrv6=(Q)=>$.check(Y2(h2,Q)),$.e164=(Q)=>$.check(H2(r2,Q)),$.datetime=(Q)=>$.check(r5(Q)),$.date=(Q)=>$.check(n5(Q)),$.time=(Q)=>$.check(i5(Q)),$.duration=(Q)=>$.check(o5(Q))});function z2($){return N7(c4,$)}var t=v("ZodStringFormat",($,U)=>{p.init($,U),A2.init($,U)}),O2=v("ZodEmail",($,U)=>{P3.init($,U),t.init($,U)});function fq($){return o0(O2,$)}var g6=v("ZodGUID",($,U)=>{v3.init($,U),t.init($,U)});function mq($){return T6(g6,$)}var U1=v("ZodUUID",($,U)=>{D3.init($,U),t.init($,U)});function hq($){return d0(U1,$)}function cq($){return p0(U1,$)}function lq($){return t0(U1,$)}function rq($){return a0(U1,$)}var f6=v("ZodURL",($,U)=>{I3.init($,U),t.init($,U)});function nq($){return S6(f6,$)}function iq($){return S6(f6,{protocol:/^https?$/,hostname:u$.domain,...F.normalizeParams($)})}var R2=v("ZodEmoji",($,U)=>{N3.init($,U),t.init($,U)});function oq($){return e0(R2,$)}var T2=v("ZodNanoID",($,U)=>{_3.init($,U),t.init($,U)});function dq($){return s0(T2,$)}var S2=v("ZodCUID",($,U)=>{w3.init($,U),t.init($,U)});function pq($){return $2(S2,$)}var C2=v("ZodCUID2",($,U)=>{k3.init($,U),t.init($,U)});function tq($){return U2(C2,$)}var g2=v("ZodULID",($,U)=>{x3.init($,U),t.init($,U)});function aq($){return K2(g2,$)}var E2=v("ZodXID",($,U)=>{F3.init($,U),t.init($,U)});function eq($){return Q2(E2,$)}var y2=v("ZodKSUID",($,U)=>{L3.init($,U),t.init($,U)});function sq($){return G2(y2,$)}var u2=v("ZodIPv4",($,U)=>{R3.init($,U),t.init($,U)});function $Y($){return J2(u2,$)}var WK=v("ZodMAC",($,U)=>{S3.init($,U),t.init($,U)});function UY($){return w7(WK,$)}var f2=v("ZodIPv6",($,U)=>{T3.init($,U),t.init($,U)});function KY($){return W2(f2,$)}var m2=v("ZodCIDRv4",($,U)=>{C3.init($,U),t.init($,U)});function QY($){return q2(m2,$)}var h2=v("ZodCIDRv6",($,U)=>{g3.init($,U),t.init($,U)});function GY($){return Y2(h2,$)}var c2=v("ZodBase64",($,U)=>{y3.init($,U),t.init($,U)});function JY($){return j2(c2,$)}var l2=v("ZodBase64URL",($,U)=>{u3.init($,U),t.init($,U)});function WY($){return X2(l2,$)}var r2=v("ZodE164",($,U)=>{f3.init($,U),t.init($,U)});function qY($){return H2(r2,$)}var n2=v("ZodJWT",($,U)=>{m3.init($,U),t.init($,U)});function YY($){return B2(n2,$)}var l4=v("ZodCustomStringFormat",($,U)=>{h3.init($,U),t.init($,U)});function jY($,U,Q={}){return u4(l4,$,U,Q)}function XY($){return u4(l4,"hostname",u$.hostname,$)}function HY($){return u4(l4,"hex",u$.hex,$)}function BY($,U){let Q=U?.enc??"hex",G=`${$}_${Q}`,K=u$[G];if(!K)throw Error(`Unrecognized hash format: ${G}`);return u4(l4,G,K,U)}var r4=v("ZodNumber",($,U)=>{c0.init($,U),m.init($,U),$._zod.processJSONSchema=(G,K,J)=>q5($,G,K,J),$.gt=(G,K)=>$.check(s$(G,K)),$.gte=(G,K)=>$.check(_$(G,K)),$.min=(G,K)=>$.check(_$(G,K)),$.lt=(G,K)=>$.check(e$(G,K)),$.lte=(G,K)=>$.check(R$(G,K)),$.max=(G,K)=>$.check(R$(G,K)),$.int=(G)=>$.check(b2(G)),$.safe=(G)=>$.check(b2(G)),$.positive=(G)=>$.check(s$(0,G)),$.nonnegative=(G)=>$.check(_$(0,G)),$.negative=(G)=>$.check(e$(0,G)),$.nonpositive=(G)=>$.check(R$(0,G)),$.multipleOf=(G,K)=>$.check(x1(G,K)),$.step=(G,K)=>$.check(x1(G,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 qK($){return b7(r4,$)}var U4=v("ZodNumberFormat",($,U)=>{c3.init($,U),r4.init($,U)});function b2($){return O7(U4,$)}function MY($){return R7(U4,$)}function ZY($){return T7(U4,$)}function VY($){return S7(U4,$)}function vY($){return C7(U4,$)}var n4=v("ZodBoolean",($,U)=>{x6.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>Y5($,Q,G,K)});function YK($){return g7(n4,$)}var i4=v("ZodBigInt",($,U)=>{l0.init($,U),m.init($,U),$._zod.processJSONSchema=(G,K,J)=>j5($,G,K,J),$.gte=(G,K)=>$.check(_$(G,K)),$.min=(G,K)=>$.check(_$(G,K)),$.gt=(G,K)=>$.check(s$(G,K)),$.gte=(G,K)=>$.check(_$(G,K)),$.min=(G,K)=>$.check(_$(G,K)),$.lt=(G,K)=>$.check(e$(G,K)),$.lte=(G,K)=>$.check(R$(G,K)),$.max=(G,K)=>$.check(R$(G,K)),$.positive=(G)=>$.check(s$(BigInt(0),G)),$.negative=(G)=>$.check(e$(BigInt(0),G)),$.nonpositive=(G)=>$.check(R$(BigInt(0),G)),$.nonnegative=(G)=>$.check(_$(BigInt(0),G)),$.multipleOf=(G,K)=>$.check(x1(G,K));let Q=$._zod.bag;$.minValue=Q.minimum??null,$.maxValue=Q.maximum??null,$.format=Q.format??null});function DY($){return y7(i4,$)}var i2=v("ZodBigIntFormat",($,U)=>{l3.init($,U),i4.init($,U)});function PY($){return f7(i2,$)}function IY($){return m7(i2,$)}var jK=v("ZodSymbol",($,U)=>{r3.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>X5($,Q,G,K)});function NY($){return h7(jK,$)}var XK=v("ZodUndefined",($,U)=>{n3.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>B5($,Q,G,K)});function _Y($){return c7(XK,$)}var HK=v("ZodNull",($,U)=>{i3.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>H5($,Q,G,K)});function BK($){return l7(HK,$)}var MK=v("ZodAny",($,U)=>{o3.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>V5($,Q,G,K)});function wY(){return r7(MK)}var ZK=v("ZodUnknown",($,U)=>{d3.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>v5($,Q,G,K)});function $4(){return n7(ZK)}var VK=v("ZodNever",($,U)=>{p3.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>Z5($,Q,G,K)});function o2($){return i7(VK,$)}var vK=v("ZodVoid",($,U)=>{t3.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>M5($,Q,G,K)});function kY($){return o7(vK,$)}var m6=v("ZodDate",($,U)=>{a3.init($,U),m.init($,U),$._zod.processJSONSchema=(G,K,J)=>D5($,G,K,J),$.min=(G,K)=>$.check(_$(G,K)),$.max=(G,K)=>$.check(R$(G,K));let Q=$._zod.bag;$.minDate=Q.minimum?new Date(Q.minimum):null,$.maxDate=Q.maximum?new Date(Q.maximum):null});function xY($){return d7(m6,$)}var DK=v("ZodArray",($,U)=>{e3.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>A5($,Q,G,K),$.element=U.element,$.min=(Q,G)=>$.check(Y1(Q,G)),$.nonempty=(Q)=>$.check(Y1(1,Q)),$.max=(Q,G)=>$.check(e1(Q,G)),$.length=(Q,G)=>$.check(s1(Q,G)),$.unwrap=()=>$.element});function h6($,U){return a7(DK,$,U)}function FY($){let U=$._zod.def.shape;return p2(Object.keys(U))}var c6=v("ZodObject",($,U)=>{s3.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>O5($,Q,G,K),F.defineLazy($,"shape",()=>{return U.shape}),$.keyof=()=>p2(Object.keys($._zod.def.shape)),$.catchall=(Q)=>$.clone({...$._zod.def,catchall:Q}),$.passthrough=()=>$.clone({...$._zod.def,catchall:$4()}),$.loose=()=>$.clone({...$._zod.def,catchall:$4()}),$.strict=()=>$.clone({...$._zod.def,catchall:o2()}),$.strip=()=>$.clone({...$._zod.def,catchall:void 0}),$.extend=(Q)=>{return F.extend($,Q)},$.safeExtend=(Q)=>{return F.safeExtend($,Q)},$.merge=(Q)=>F.merge($,Q),$.pick=(Q)=>F.pick($,Q),$.omit=(Q)=>F.omit($,Q),$.partial=(...Q)=>F.partial(a2,$,Q[0]),$.required=(...Q)=>F.required(e2,$,Q[0])});function LY($,U){let Q={type:"object",shape:$??{},...F.normalizeParams(U)};return new c6(Q)}function zY($,U){return new c6({type:"object",shape:$,catchall:o2(),...F.normalizeParams(U)})}function bY($,U){return new c6({type:"object",shape:$,catchall:$4(),...F.normalizeParams(U)})}var l6=v("ZodUnion",($,U)=>{F6.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>I2($,Q,G,K),$.options=U.options});function d2($,U){return new l6({type:"union",options:$,...F.normalizeParams(U)})}var PK=v("ZodXor",($,U)=>{l6.init($,U),$9.init($,U),$._zod.processJSONSchema=(Q,G,K)=>I2($,Q,G,K),$.options=U.options});function AY($,U){return new PK({type:"union",options:$,inclusive:!1,...F.normalizeParams(U)})}var IK=v("ZodDiscriminatedUnion",($,U)=>{l6.init($,U),U9.init($,U)});function OY($,U,Q){return new IK({type:"union",options:U,discriminator:$,...F.normalizeParams(Q)})}var NK=v("ZodIntersection",($,U)=>{K9.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>R5($,Q,G,K)});function _K($,U){return new NK({type:"intersection",left:$,right:U})}var wK=v("ZodTuple",($,U)=>{r0.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>T5($,Q,G,K),$.rest=(Q)=>$.clone({...$._zod.def,rest:Q})});function kK($,U,Q){let G=U instanceof y,K=G?Q:U;return new wK({type:"tuple",items:$,rest:G?U:null,...F.normalizeParams(K)})}var r6=v("ZodRecord",($,U)=>{Q9.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>S5($,Q,G,K),$.keyType=U.keyType,$.valueType=U.valueType});function xK($,U,Q){return new r6({type:"record",keyType:$,valueType:U,...F.normalizeParams(Q)})}function RY($,U,Q){let G=N$($);return G._zod.values=void 0,new r6({type:"record",keyType:G,valueType:U,...F.normalizeParams(Q)})}function TY($,U,Q){return new r6({type:"record",keyType:$,valueType:U,mode:"loose",...F.normalizeParams(Q)})}var FK=v("ZodMap",($,U)=>{G9.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>z5($,Q,G,K),$.keyType=U.keyType,$.valueType=U.valueType,$.min=(...Q)=>$.check($1(...Q)),$.nonempty=(Q)=>$.check($1(1,Q)),$.max=(...Q)=>$.check(F1(...Q)),$.size=(...Q)=>$.check(a1(...Q))});function SY($,U,Q){return new FK({type:"map",keyType:$,valueType:U,...F.normalizeParams(Q)})}var LK=v("ZodSet",($,U)=>{J9.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>b5($,Q,G,K),$.min=(...Q)=>$.check($1(...Q)),$.nonempty=(Q)=>$.check($1(1,Q)),$.max=(...Q)=>$.check(F1(...Q)),$.size=(...Q)=>$.check(a1(...Q))});function CY($,U){return new LK({type:"set",valueType:$,...F.normalizeParams(U)})}var h4=v("ZodEnum",($,U)=>{W9.init($,U),m.init($,U),$._zod.processJSONSchema=(G,K,J)=>P5($,G,K,J),$.enum=U.entries,$.options=Object.values(U.entries);let Q=new Set(Object.keys(U.entries));$.extract=(G,K)=>{let J={};for(let W of G)if(Q.has(W))J[W]=U.entries[W];else throw Error(`Key ${W} not found in enum`);return new h4({...U,checks:[],...F.normalizeParams(K),entries:J})},$.exclude=(G,K)=>{let J={...U.entries};for(let W of G)if(Q.has(W))delete J[W];else throw Error(`Key ${W} not found in enum`);return new h4({...U,checks:[],...F.normalizeParams(K),entries:J})}});function p2($,U){let Q=Array.isArray($)?Object.fromEntries($.map((G)=>[G,G])):$;return new h4({type:"enum",entries:Q,...F.normalizeParams(U)})}function gY($,U){return new h4({type:"enum",entries:$,...F.normalizeParams(U)})}var zK=v("ZodLiteral",($,U)=>{q9.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>I5($,Q,G,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 EY($,U){return new zK({type:"literal",values:Array.isArray($)?$:[$],...F.normalizeParams(U)})}var bK=v("ZodFile",($,U)=>{Y9.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>w5($,Q,G,K),$.min=(Q,G)=>$.check($1(Q,G)),$.max=(Q,G)=>$.check(F1(Q,G)),$.mime=(Q,G)=>$.check(T4(Array.isArray(Q)?Q:[Q],G))});function yY($){return e7(bK,$)}var AK=v("ZodTransform",($,U)=>{j9.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>L5($,Q,G,K),$._zod.parse=(Q,G)=>{if(G.direction==="backward")throw new o1($.constructor.name);Q.addIssue=(J)=>{if(typeof J==="string")Q.issues.push(F.issue(J,Q.value,U));else{let W=J;if(W.fatal)W.continue=!1;W.code??(W.code="custom"),W.input??(W.input=Q.value),W.inst??(W.inst=$),Q.issues.push(F.issue(W))}};let K=U.transform(Q.value,Q);if(K instanceof Promise)return K.then((J)=>{return Q.value=J,Q});return Q.value=K,Q}});function t2($){return new AK({type:"transform",transform:$})}var a2=v("ZodOptional",($,U)=>{n0.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>N2($,Q,G,K),$.unwrap=()=>$._zod.def.innerType});function E6($){return new a2({type:"optional",innerType:$})}var OK=v("ZodExactOptional",($,U)=>{X9.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>N2($,Q,G,K),$.unwrap=()=>$._zod.def.innerType});function RK($){return new OK({type:"optional",innerType:$})}var TK=v("ZodNullable",($,U)=>{H9.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>C5($,Q,G,K),$.unwrap=()=>$._zod.def.innerType});function y6($){return new TK({type:"nullable",innerType:$})}function uY($){return E6(y6($))}var SK=v("ZodDefault",($,U)=>{B9.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>E5($,Q,G,K),$.unwrap=()=>$._zod.def.innerType,$.removeDefault=$.unwrap});function CK($,U){return new SK({type:"default",innerType:$,get defaultValue(){return typeof U==="function"?U():F.shallowClone(U)}})}var gK=v("ZodPrefault",($,U)=>{M9.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>y5($,Q,G,K),$.unwrap=()=>$._zod.def.innerType});function EK($,U){return new gK({type:"prefault",innerType:$,get defaultValue(){return typeof U==="function"?U():F.shallowClone(U)}})}var e2=v("ZodNonOptional",($,U)=>{Z9.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>g5($,Q,G,K),$.unwrap=()=>$._zod.def.innerType});function yK($,U){return new e2({type:"nonoptional",innerType:$,...F.normalizeParams(U)})}var uK=v("ZodSuccess",($,U)=>{V9.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>k5($,Q,G,K),$.unwrap=()=>$._zod.def.innerType});function fY($){return new uK({type:"success",innerType:$})}var fK=v("ZodCatch",($,U)=>{v9.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>u5($,Q,G,K),$.unwrap=()=>$._zod.def.innerType,$.removeCatch=$.unwrap});function mK($,U){return new fK({type:"catch",innerType:$,catchValue:typeof U==="function"?U:()=>U})}var hK=v("ZodNaN",($,U)=>{D9.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>N5($,Q,G,K)});function mY($){return t7(hK,$)}var s2=v("ZodPipe",($,U)=>{P9.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>f5($,Q,G,K),$.in=U.in,$.out=U.out});function u6($,U){return new s2({type:"pipe",in:$,out:U})}var $U=v("ZodCodec",($,U)=>{s2.init($,U),L6.init($,U)});function hY($,U,Q){return new $U({type:"pipe",in:$,out:U,transform:Q.decode,reverseTransform:Q.encode})}var cK=v("ZodReadonly",($,U)=>{I9.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>m5($,Q,G,K),$.unwrap=()=>$._zod.def.innerType});function lK($){return new cK({type:"readonly",innerType:$})}var rK=v("ZodTemplateLiteral",($,U)=>{N9.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>_5($,Q,G,K)});function cY($,U){return new rK({type:"template_literal",parts:$,...F.normalizeParams(U)})}var nK=v("ZodLazy",($,U)=>{k9.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>c5($,Q,G,K),$.unwrap=()=>$._zod.def.getter()});function iK($){return new nK({type:"lazy",getter:$})}var oK=v("ZodPromise",($,U)=>{w9.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>h5($,Q,G,K),$.unwrap=()=>$._zod.def.innerType});function lY($){return new oK({type:"promise",innerType:$})}var dK=v("ZodFunction",($,U)=>{_9.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>F5($,Q,G,K)});function rY($){return new dK({type:"function",input:Array.isArray($?.input)?kK($?.input):$?.input??h6($4()),output:$?.output??$4()})}var n6=v("ZodCustom",($,U)=>{x9.init($,U),m.init($,U),$._zod.processJSONSchema=(Q,G,K)=>x5($,Q,G,K)});function nY($){let U=new a({check:"custom"});return U._zod.check=$,U}function iY($,U){return s7(n6,$??(()=>!0),U)}function pK($,U={}){return $5(n6,$,U)}function tK($){return U5($)}var oY=K5,dY=Q5;function pY($,U={}){let Q=new n6({type:"custom",check:"custom",fn:(G)=>G instanceof $,abort:!0,...F.normalizeParams(U)});return Q._zod.bag.Class=$,Q._zod.check=(G)=>{if(!(G.value instanceof $))G.issues.push({code:"invalid_type",expected:$.name,input:G.value,inst:Q,path:[...Q._zod.def.path??[]]})},Q}var tY=(...$)=>G5({Codec:$U,Boolean:n4,String:c4},...$);function aY($){let U=iK(()=>{return d2([z2($),qK(),YK(),BK(),h6(U),xK(z2(),U)])});return U}function eY($,U){return u6(t2($),U)}var MP={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 ZP($){W$({customError:$})}function VP(){return W$().customError}var aK;(function($){})(aK||(aK={}));var R={...C6,...w2,iso:m4},vP=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 DP($,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 PP($,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 G=U.version==="draft-2020-12"?"$defs":"definitions";if(Q[0]===G){let K=Q[1];if(!K||!U.defs[K])throw Error(`Reference not found: ${$}`);return U.defs[K]}throw Error(`Reference not found: ${$}`)}function sY($,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 J=PP(K,U),W=D$(J,U);return U.refs.set(K,W),U.processing.delete(K),W}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((W)=>typeof W==="string"))return R.enum(K);let J=K.map((W)=>R.literal(W));if(J.length<2)return J[0];return R.union([J[0],J[1],...J.slice(2)])}if($.const!==void 0)return R.literal($.const);let Q=$.type;if(Array.isArray(Q)){let K=Q.map((J)=>{let W={...$,type:J};return sY(W,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 G;switch(Q){case"string":{let K=R.string();if($.format){let J=$.format;if(J==="email")K=K.check(R.email());else if(J==="uri"||J==="uri-reference")K=K.check(R.url());else if(J==="uuid"||J==="guid")K=K.check(R.uuid());else if(J==="date-time")K=K.check(R.iso.datetime());else if(J==="date")K=K.check(R.iso.date());else if(J==="time")K=K.check(R.iso.time());else if(J==="duration")K=K.check(R.iso.duration());else if(J==="ipv4")K=K.check(R.ipv4());else if(J==="ipv6")K=K.check(R.ipv6());else if(J==="mac")K=K.check(R.mac());else if(J==="cidr")K=K.check(R.cidrv4());else if(J==="cidr-v6")K=K.check(R.cidrv6());else if(J==="base64")K=K.check(R.base64());else if(J==="base64url")K=K.check(R.base64url());else if(J==="e164")K=K.check(R.e164());else if(J==="jwt")K=K.check(R.jwt());else if(J==="emoji")K=K.check(R.emoji());else if(J==="nanoid")K=K.check(R.nanoid());else if(J==="cuid")K=K.check(R.cuid());else if(J==="cuid2")K=K.check(R.cuid2());else if(J==="ulid")K=K.check(R.ulid());else if(J==="xid")K=K.check(R.xid());else if(J==="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));G=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);G=K;break}case"boolean":{G=R.boolean();break}case"null":{G=R.null();break}case"object":{let K={},J=$.properties||{},W=new Set($.required||[]);for(let[j,X]of Object.entries(J)){let B=D$(X,U);K[j]=W.has(j)?B:B.optional()}if($.propertyNames){let j=D$($.propertyNames,U),X=$.additionalProperties&&typeof $.additionalProperties==="object"?D$($.additionalProperties,U):R.any();if(Object.keys(K).length===0){G=R.record(j,X);break}let B=R.object(K).passthrough(),Z=R.looseRecord(j,X);G=R.intersection(B,Z);break}if($.patternProperties){let j=$.patternProperties,X=Object.keys(j),B=[];for(let V of X){let N=D$(j[V],U),T=R.string().regex(new RegExp(V));B.push(R.looseRecord(T,N))}let Z=[];if(Object.keys(K).length>0)Z.push(R.object(K).passthrough());if(Z.push(...B),Z.length===0)G=R.object({}).passthrough();else if(Z.length===1)G=Z[0];else{let V=R.intersection(Z[0],Z[1]);for(let N=2;N<Z.length;N++)V=R.intersection(V,Z[N]);G=V}break}let q=R.object(K);if($.additionalProperties===!1)G=q.strict();else if(typeof $.additionalProperties==="object")G=q.catchall(D$($.additionalProperties,U));else G=q.passthrough();break}case"array":{let{prefixItems:K,items:J}=$;if(K&&Array.isArray(K)){let W=K.map((j)=>D$(j,U)),q=J&&typeof J==="object"&&!Array.isArray(J)?D$(J,U):void 0;if(q)G=R.tuple(W).rest(q);else G=R.tuple(W);if(typeof $.minItems==="number")G=G.check(R.minLength($.minItems));if(typeof $.maxItems==="number")G=G.check(R.maxLength($.maxItems))}else if(Array.isArray(J)){let W=J.map((j)=>D$(j,U)),q=$.additionalItems&&typeof $.additionalItems==="object"?D$($.additionalItems,U):void 0;if(q)G=R.tuple(W).rest(q);else G=R.tuple(W);if(typeof $.minItems==="number")G=G.check(R.minLength($.minItems));if(typeof $.maxItems==="number")G=G.check(R.maxLength($.maxItems))}else if(J!==void 0){let W=D$(J,U),q=R.array(W);if(typeof $.minItems==="number")q=q.min($.minItems);if(typeof $.maxItems==="number")q=q.max($.maxItems);G=q}else G=R.array(R.any());break}default:throw Error(`Unsupported type: ${Q}`)}if($.description)G=G.describe($.description);if($.default!==void 0)G=G.default($.default);return G}function D$($,U){if(typeof $==="boolean")return $?R.any():R.never();let Q=sY($,U),G=$.type||$.enum!==void 0||$.const!==void 0;if($.anyOf&&Array.isArray($.anyOf)){let q=$.anyOf.map((X)=>D$(X,U)),j=R.union(q);Q=G?R.intersection(Q,j):j}if($.oneOf&&Array.isArray($.oneOf)){let q=$.oneOf.map((X)=>D$(X,U)),j=R.xor(q);Q=G?R.intersection(Q,j):j}if($.allOf&&Array.isArray($.allOf))if($.allOf.length===0)Q=G?Q:R.any();else{let q=G?Q:D$($.allOf[0],U),j=G?0:1;for(let X=j;X<$.allOf.length;X++)q=R.intersection(q,D$($.allOf[X],U));Q=q}if($.nullable===!0&&U.version==="openapi-3.0")Q=R.nullable(Q);if($.readOnly===!0)Q=R.readonly(Q);let K={},J=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let q of J)if(q in $)K[q]=$[q];let W=["contentEncoding","contentMediaType","contentSchema"];for(let q of W)if(q in $)K[q]=$[q];for(let q of Object.keys($))if(!vP.has(q))K[q]=$[q];if(Object.keys(K).length>0)U.registry.add(Q,K);return Q}function $j($,U){if(typeof $==="boolean")return $?R.any():R.never();let Q=DP($,U?.defaultTarget),G=$.$defs||$.definitions||{},K={version:Q,defs:G,refs:new Map,processing:new Set,rootSchema:$,registry:U?.registry??V$};return D$($,K)}var eK={};K1(eK,{string:()=>IP,number:()=>NP,date:()=>kP,boolean:()=>_P,bigint:()=>wP});function IP($){return _7(c4,$)}function NP($){return A7(r4,$)}function _P($){return E7(n4,$)}function wP($){return u7(i4,$)}function kP($){return p7(m6,$)}W$(z6());var sK=Y.enum(["pending","synced","failed"]),$Q=Y.object({}).default({}),UQ=Y.object({phone_number_id:Y.string().min(1),voice_enabled:Y.boolean().default(!0),chat_enabled:Y.boolean().default(!0),sip_username:Y.string().optional(),sip_password_encrypted:Y.string().optional(),sip_password_iv:Y.string().optional(),session_timeout_minutes:Y.number().int().min(5).max(10080).default(1440),waba_id:Y.string().optional(),business_name:Y.string().optional(),display_phone_number:Y.string().optional(),webhook_sync_status:sK.default("pending"),webhook_sync_error:Y.string().optional(),webhook_synced_at:Y.iso.datetime().optional(),webhook_callback_url:Y.string().optional(),last_webhook_received_at:Y.iso.datetime().optional(),last_webhook_message_id:Y.string().optional(),last_webhook_status_id:Y.string().optional(),last_webhook_phone_number_id:Y.string().optional(),last_webhook_error:Y.string().optional()}),KQ=Y.object({bot_token:Y.string().min(1),webhook_secret:Y.string().min(1),allow_groups:Y.boolean().default(!1),session_timeout_minutes:Y.number().int().min(5).max(10080).default(1440),bot_username:Y.string().optional()}),Uj={sip:$Q,telegram:KQ,whatsapp:UQ,webchat:Y.object({}).default({}),sms:Y.object({}).default({}),rcs:Y.object({}).default({})};var o4=["sip"],i6=["telegram","webchat","sms","rcs"],d4=["whatsapp"],QQ=[...o4,...i6,...d4],Kj=[...o4,...d4],xP=[...i6,...d4];var QO=new Set(o4),GO=new Set(d4);var Qj=String.raw`(?:25[0-5]|2[0-4]\d|[01]?\d\d?)`,Gj=String.raw`(?:${Qj}\.){3}${Qj}`,LP=String.raw`${Gj}(?:\/(?:3[0-2]|[12]?\d))?`,HO=new RegExp(`^${Gj}$`);var P$="[0-9a-fA-F]{1,4}",zP=[`(?:${P$}:){7}${P$}`,`(?:${P$}:){1,7}:`,`(?:${P$}:){1,6}:${P$}`,`(?:${P$}:){1,5}(?::${P$}){1,2}`,`(?:${P$}:){1,4}(?::${P$}){1,3}`,`(?:${P$}:){1,3}(?::${P$}){1,4}`,`(?:${P$}:){1,2}(?::${P$}){1,5}`,`${P$}:(?::${P$}){1,6}`,`:(?::${P$}){1,7}`,"::(?:ffff(?::0{1,4})?:)?"],bP=`(?:${zP.join("|")})`,AP=String.raw`${bP}(?:\/(?:12[0-8]|1[01]\d|[1-9]?\d))?`,BO=new RegExp(`^(?:${LP}|${AP})$`);function OP($){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 GQ($){OP($);let U=Object.entries($.nodes).map(([G,K])=>({id:G,type:K.type,label:K.label,varName:K.varName,position:{x:0,y:0},config:K.config})),Q=[];for(let[G,K]of Object.entries($.adjacency))for(let[J,W]of Object.entries(K))Q.push({id:`${G}-${J}-${W}`,source:G,sourceHandle:J,target:W,targetHandle:"in"});return{nodes:U,edges:Q,viewport:{x:0,y:0,zoom:1}}}var X1=["none","both","caller"],JQ=Y.object({callerSpeechMs:Y.number().int().min(0),ivrSpeechMs:Y.number().int().min(0),version:Y.number().int().min(1)});var RP=["recordingEnabled","samplingPercentage","transcriptionSamplingPercentage","transcriptionEnabled","transcriptionLanguage","transcriptionMinDurationSeconds","transcriptionSpeechRequirement","anonymizeEnabled","speechAnalyticsEnabled","topicDetectionTopics","structuredAnalysisEnabled","structuredAnalysisIds"];function WQ($,U,Q,G,K=!1){let J=TP(G),W=new Map(Q.map((X)=>[X.id,X])),q=yP(U,K),j={};return SP({startNodeId:$,planState:q,nodesById:W,adjacency:G,incoming:J,result:j}),j}function TP($){let U=new Map;for(let[Q,G]of $)for(let K of G.values()){let J=U.get(K)??[];U.set(K,[...J,Q])}return U}function SP($){let{startNodeId:U,planState:Q,nodesById:G,adjacency:K,incoming:J,result:W}=$,q=[U],j=new Set(q),X=0,B=Math.max(20,G.size*G.size*4);while(q.length>0&&X++<B){let Z=q.shift();if(Z===void 0)continue;j.delete(Z);let V=G.get(Z);if(V===void 0)continue;let N=CP(Z,Q,V,J,W);if(oP(W[Z],N))continue;W[Z]=N,EP(q,j,K.get(Z)?.values()??[])}}function CP($,U,Q,G,K){let J=(G.get($)??[]).map((q)=>K[q]).filter((q)=>q!==void 0),W=gP(J,U);return uP(W,Q)}function gP($,U){let Q=$[0];return Q===void 0?U:$.slice(1).reduce((G,K)=>nP(G,K),Q)}function EP($,U,Q){for(let G of Q){if(U.has(G))continue;$.push(G),U.add(G)}}function yP($,U){let Q={kind:"plan"};return{recordingEnabled:b$(U,Q),samplingPercentage:b$($.samplingPercentage,Q),transcriptionSamplingPercentage:b$($.transcriptionSamplingPercentage,Q),transcriptionEnabled:b$($.transcriptionEnabled,Q),transcriptionLanguage:b$($.transcriptionLanguage,Q),transcriptionMinDurationSeconds:b$($.transcriptionMinDurationSeconds,Q),transcriptionSpeechRequirement:b$($.transcriptionSpeechRequirement,Q),anonymizeEnabled:b$($.anonymizeEnabled,Q),speechAnalyticsEnabled:b$($.speechAnalyticsEnabled,Q),topicDetectionTopics:b$([...$.topicDetectionTopics],Q),structuredAnalysisEnabled:b$($.autoAnalysisEnabled,Q),structuredAnalysisIds:b$([...$.autoAnalysisIds],Q)}}function uP($,U){let Q=fP(U),G={kind:"node",nodeId:U.id,nodeLabel:U.label};return{recordingEnabled:f$($.recordingEnabled,Q.recordingEnabled,G),samplingPercentage:f$($.samplingPercentage,Q.samplingPercentage,G),transcriptionSamplingPercentage:f$($.transcriptionSamplingPercentage,Q.transcriptionSamplingPercentage,G),transcriptionEnabled:f$($.transcriptionEnabled,Q.transcriptionEnabled,G),transcriptionLanguage:f$($.transcriptionLanguage,Q.transcriptionLanguage,G),transcriptionMinDurationSeconds:f$($.transcriptionMinDurationSeconds,Q.transcriptionMinDurationSeconds,G),transcriptionSpeechRequirement:f$($.transcriptionSpeechRequirement,Q.transcriptionSpeechRequirement,G),anonymizeEnabled:f$($.anonymizeEnabled,Q.anonymizeEnabled,G),speechAnalyticsEnabled:f$($.speechAnalyticsEnabled,Q.speechAnalyticsEnabled,G),topicDetectionTopics:f$($.topicDetectionTopics,Q.topicDetectionTopics,G),structuredAnalysisEnabled:f$($.structuredAnalysisEnabled,Q.structuredAnalysisEnabled,G),structuredAnalysisIds:f$($.structuredAnalysisIds,Q.structuredAnalysisIds,G)}}function fP($){if($.type==="recording")return mP($.config);if($.type==="transcription")return hP($.config);if($.type==="analysis")return cP($.config);return{}}function mP($){let U={},Q=$.enabled;if(typeof Q==="boolean")U.recordingEnabled=Q;let G=$.samplingPercentage;if(typeof G==="number")U.samplingPercentage=G;return U}function hP($){let U={},Q=$.enabled;if(typeof Q==="boolean")U.transcriptionEnabled=Q;let G=$.samplingPercentage;if(typeof G==="number")U.transcriptionSamplingPercentage=G;let K=$.language;if(typeof K==="string")U.transcriptionLanguage=K.trim()||null;let J=$.minDurationSeconds;if(typeof J==="number")U.transcriptionMinDurationSeconds=J;let W=$.speechRequirement;if(rP(W))U.transcriptionSpeechRequirement=W;let q=$.anonymizeEnabled;if(typeof q==="boolean")U.anonymizeEnabled=q;return U}function cP($){let U={},Q=$.speechAnalyticsEnabled;if(typeof Q==="boolean")U.speechAnalyticsEnabled=Q;let G=$.topicDetectionTopics;if(Jj(G))U.topicDetectionTopics=G;let K=$.structuredAnalysisEnabled;if(typeof K==="boolean")U.structuredAnalysisEnabled=K;let J=$.structuredAnalysisIds;if(Jj(J))U.structuredAnalysisIds=J;return U}var lP=X1;function rP($){return typeof $==="string"&&lP.includes($)}function Jj($){return Array.isArray($)&&$.every((U)=>typeof U==="string")}function f$($,U,Q){return U===void 0?$:b$(U,Q)}function b$($,U){return{kind:"known",value:$,origin:U}}function nP($,U){return{recordingEnabled:m$($.recordingEnabled,U.recordingEnabled),samplingPercentage:m$($.samplingPercentage,U.samplingPercentage),transcriptionSamplingPercentage:m$($.transcriptionSamplingPercentage,U.transcriptionSamplingPercentage),transcriptionEnabled:m$($.transcriptionEnabled,U.transcriptionEnabled),transcriptionLanguage:m$($.transcriptionLanguage,U.transcriptionLanguage),transcriptionMinDurationSeconds:m$($.transcriptionMinDurationSeconds,U.transcriptionMinDurationSeconds),transcriptionSpeechRequirement:m$($.transcriptionSpeechRequirement,U.transcriptionSpeechRequirement),anonymizeEnabled:m$($.anonymizeEnabled,U.anonymizeEnabled),speechAnalyticsEnabled:m$($.speechAnalyticsEnabled,U.speechAnalyticsEnabled),topicDetectionTopics:m$($.topicDetectionTopics,U.topicDetectionTopics),structuredAnalysisEnabled:m$($.structuredAnalysisEnabled,U.structuredAnalysisEnabled),structuredAnalysisIds:m$($.structuredAnalysisIds,U.structuredAnalysisIds)}}function m$($,U){let Q=[...Wj($),...Wj(U)],G=[];for(let K of Q)if(!G.some((J)=>qj(J.value,K.value)))G.push(K);if(G.length===1){let K=iP($,U,G[0].viaNodeLabel);return b$(G[0].value,K)}return{kind:"indeterminate",branches:G}}function iP($,U,Q){if($.kind==="known")return $.origin;if(U.kind==="known")return U.origin;return{kind:"node",nodeId:"",nodeLabel:Q}}function Wj($){if($.kind==="indeterminate")return $.branches;let U=$.origin.kind==="plan"?"__plan__":$.origin.nodeLabel;return[{value:$.value,viaNodeLabel:U}]}function qj($,U){return JSON.stringify($)===JSON.stringify(U)}function oP($,U){if($===void 0)return!1;return RP.every((Q)=>qj($[Q],U[Q]))}var K4=3600;var qQ=Y.object({startByte:Y.number().int().min(0),endByte:Y.number().int().min(0),openedAtMs:Y.number().int().min(0)}).refine(($)=>$.endByte>=$.startByte,{message:"endByte must be greater than or equal to startByte",path:["endByte"]}),Yj=Y.object({nodeId:Y.string().min(1),kind:Y.enum(["recording","transcription","analysis"]),atByte:Y.number().int().min(0),atMs:Y.number().int().min(0),patch:Y.record(Y.string(),Y.unknown())}),jj=Y.object({samplingPercentage:Y.number().int().min(0).max(100).describe("Recording sampling percentage"),transcriptionSamplingPercentage:Y.number().int().min(0).max(100).default(100).describe("Transcription sampling percentage among selected recordings"),transcriptionEnabled:Y.boolean().describe("Enable transcription"),transcriptionLanguage:Y.string().nullable().describe("Transcription language"),transcriptionMinDurationSeconds:Y.number().int().min(0).max(K4).describe("Minimum transcription duration"),transcriptionSpeechRequirement:Y.enum(X1).default("none").describe("Which sides must have spoken for automatic transcription"),anonymizeEnabled:Y.boolean().describe("Anonymize the transcript"),speechAnalyticsEnabled:Y.boolean().describe("Enable speech analytics"),topicDetectionTopics:Y.array(Y.string()).describe("Topic detection topics"),autoAnalysisEnabled:Y.boolean().describe("Enable structured analyses"),autoAnalysisInheritOrg:Y.boolean().describe("Inherit structured analyses from the organization"),autoAnalysisIds:Y.array(Y.string()).describe("Structured analysis IDs")}),dP=Y.object({speechAnalyticsEnabled:Y.boolean(),topicDetectionTopics:Y.array(Y.string()),autoAnalysisEnabled:Y.boolean(),autoAnalysisIds:Y.array(Y.string())});var pP=Y.object({usePlan:Y.boolean().default(!0).describe("Use plan recording profile"),samplingPercentage:Y.number().int().min(0).max(100).default(100).describe("Recording sampling percentage"),transcriptionSamplingPercentage:Y.number().int().min(0).max(100).default(100).describe("Transcription sampling percentage"),transcriptionEnabled:Y.boolean().default(!1).describe("Enable transcription"),transcriptionLanguage:Y.string().default("").describe("Transcription language"),transcriptionMinDurationSeconds:Y.number().int().min(0).max(K4).default(0).describe("Minimum transcription duration"),transcriptionSpeechRequirement:Y.enum(X1).default("none").describe("Which sides must have spoken for automatic transcription"),anonymizeEnabled:Y.boolean().default(!1).describe("Anonymize the transcript"),speechAnalyticsEnabled:Y.boolean().default(!1).describe("Enable speech analytics"),topicDetectionTopics:Y.array(Y.string()).default([]).describe("Topic detection topics"),autoAnalysisEnabled:Y.boolean().default(!1).describe("Enable structured analyses"),autoAnalysisIds:Y.array(Y.string()).default([]).describe("Structured analysis IDs")}),Xj=Y.object({sampleRate:Y.number().int().positive(),channels:Y.number().int().positive(),bitsPerSample:Y.number().int().positive()});var tP=Y.object({sampled:Y.boolean(),transcriptionSampled:Y.boolean().optional(),profile:jj,recordingFormat:Xj.optional(),recordingIntervals:qQ.array().default([]),transcriptionWindows:qQ.array().default([]),directives:Yj.array().default([]),voiceActivity:JQ.optional()});function C($){let U=$.producedVariables;return{meta:{...$.meta,inputs:$.meta.type==="start"?[]:[{key:"in",labelKey:"editor:handles.in"}],producedVariables:typeof U==="function"?(G)=>U(G):U,defaultConfig:$.configSchema.parse({})},configSchema:$.configSchema,producedVariables:$.producedVariables}}var aP=Y.object({id:Y.string(),type:Y.string(),x:Y.number(),y:Y.number()}),eP=Y.object({source:Y.string(),target:Y.string()}),sP=Y.object({nodes:Y.array(aP),edges:Y.array(eP)});var Hj=["voice","chat","both"];var Bj=["pre","post"];var Mj=["voicemail","announcement","ivr","screening","unknown"];var o6=["channels","calls","registrations","codecs","modules","aliases"];var $I=new Set(["phone","telephone","telefone","fone","celular","cel","mobile","movel","numero","number","num","tel","msisdn","whatsapp","telefone celular","numero de telefone"]),UI=new Set(["name","nome","cliente","contato","contact","nome completo","razao social","full name"]);function KI($){return $.normalize("NFD").replaceAll(/[\u0300-\u036F]/g,"").toLowerCase().replaceAll(/[\s\-_]+/g," ").trim()}function QI($){return $.normalize("NFD").replaceAll(/[\u0300-\u036F]/g,"").toLowerCase().replaceAll(/[^a-z0-9]+/g,"_").replace(/^_/,"").replace(/_$/,"")}function Zj($){return $I.has($)||$.includes("telefone")||$.includes("phone")||$.includes("celular")}function GI($){return UI.has($)}function YQ($){let U={},Q={},G=new Set,K=!1,J=!1;function W(q){let j=q,X=2;while(G.has(j))j=`${q}_${String(X)}`,X+=1;return G.add(j),j}for(let q of $){let j=KI(q);if(j===""){U[q]="ignore";continue}if(Zj(j)&&!K){U[q]="phone",K=!0;continue}if(GI(j)&&!J&&!Zj(j)){U[q]="name",J=!0;continue}let X=QI(q);if(X===""){U[q]="ignore";continue}U[q]="custom",Q[q]=W(X)}return{roles:U,customNames:Q}}var Q4={_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"},analysis:{speechAnalyticsEnabled:"Enable speech analytics for all available transcription; omitted fields remain inherited",topicDetectionTopics:"Topics 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 UU={_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"},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",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 JI={en:Q4,"pt-BR":UU};function jQ($,U="en"){return JI[U]._nodes?.[$]}function G4($,U){return typeof $.outputs==="function"?$.outputs(U):$.outputs}var Vj={interaction:{order:0},handling:{order:1},routing:{order:2},media:{order:3},data:{order:4},legacy:{order:5}},WI=Object.entries(Vj).sort(([,$],[,U])=>$.order-U.order).map(([$])=>$);var XQ=Y.object({reason:Y.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:Y.string().default("").describe("Optional number/template to add instead of the auto-resolved one. Supports {{variables}}. Empty = auto-resolve (dialer contact, then caller ID).")}),HQ=C({meta:{type:"addToDnc",module:"dialer",nameKey:"editor:nodes.addToDnc.name",descriptionKey:"editor:nodes.addToDnc.description",color:"red",icon:"Ban",category:"data",nature:"sideEffect",display:"compact",channel:"voice",order:3,outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:XQ,producedVariables:[{name:"dnc_added",type:"string",descriptionKey:"editor:vars.dncAdded"},{name:"dnc_phone",type:"string",descriptionKey:"editor:vars.dncPhone"}]});var BQ=Y.object({agent_id:Y.string().default("").describe("SipPulse AI agent ID to invoke. Required for execution."),agent_name:Y.string().default("").describe("Display name for the AI agent (used in logs and UI)."),additional_instructions:Y.string().default("").describe("Extra instructions appended to the agent's system prompt."),variables:Y.record(Y.string(),Y.unknown()).default({}).describe("Key-value pairs passed to the agent as context variables."),initial_message:Y.string().default("").describe("First message the agent speaks when the conversation starts."),max_duration_minutes:Y.number().min(1).max(60).default(10).describe("Maximum conversation duration in minutes (1-60). Call ends on timeout.")}),MQ=C({meta:{type:"aiAgent",module:"ai",nameKey:"editor:nodes.aiAgent.name",descriptionKey:"editor:nodes.aiAgent.description",color:"iris",icon:"BotMessageSquare",category:"handling",order:1,nature:"composite",display:"full",channel:"both",outputs:[{key:"completed",labelKey:"editor:handles.completed"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:BQ,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 ZQ=Y.string().min(1).max(255).regex(/^[A-Za-z0-9_-]+$/,{error:"Invalid structured analysis id"});var VQ=Y.object({speechAnalyticsEnabled:Y.boolean().optional(),topicDetectionTopics:Y.array(Y.string()).optional(),structuredAnalysisEnabled:Y.boolean().optional(),structuredAnalysisIds:Y.array(ZQ).max(100).optional()}),vQ=C({meta:{type:"analysis",module:"ai",nameKey:"editor:nodes.analysis.name",descriptionKey:"editor:nodes.analysis.description",color:"orange",icon:"ChartNoAxesColumn",category:"media",nature:"sideEffect",display:"compact",channel:"both",order:2,outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:VQ,producedVariables:[{name:"selected",type:"number",descriptionKey:"editor:vars.analysisSelected"}]});var jI=/\{\{[^{}]*\}\}/g,XI=/^\{\{[^{}]*\}\}$/,HI=new Set(["http:","https:"]);function vj($){if(!URL.canParse($))return!1;return HI.has(new URL($).protocol)}function Dj($){let U=$.trim();if(U==="")return"empty";if(XI.test(U))return"from-variable";let Q=0,G=U.replaceAll(jI,()=>{return Q+=1,`v${Q}`});return vj(G)?"valid":"malformed"}function DQ($){return Dj($)!=="malformed"}var Pj=["postgres","redis","freeswitch","engine","server"],MR=new Set(Pj);var PQ=Y.object({text:Y.string().min(1,{error:"editor:validation.emptyTtsText"}).describe("Text to synthesize into speech."),voice:Y.string().optional().describe("TTS voice ID (e.g., 'pt-BR-FranciscaNeural'). Resolved dynamically when absent."),model:Y.string().optional().describe("TTS model ID (e.g., 'pulse-tts'). Resolved dynamically when absent.")}),J$=Y.union([Y.object({tts:PQ.describe("Text-to-speech audio source.")}),Y.object({file:Y.object({id:Y.string().min(1,{error:"editor:validation.noAudioFile"}).describe("Audio file ID from the audio library."),name:Y.string().describe("Display name of the audio file."),path:Y.string().describe("Storage path of the audio file.")}).describe("Pre-recorded audio file source.")}),Y.object({url:Y.object({value:Y.string().min(1,{error:"editor:validation.emptyAudioUrl"}).refine(DQ,{error:"editor:validation.malformedAudioUrl"}).describe("Audio URL fetched at call time. Supports {{variables}}; secrets are not allowed."),fallbackTts:PQ.optional().describe("Spoken when the URL fails. Absent means take the error output.")}).describe("Remote audio source fetched at call time.")})]),BI=J$.optional().catch(void 0);var p4=Y.string().refine(($)=>$.trim()!=="",{error:"editor:validation.urlRequired"}).refine(($)=>!/\s/.test($.trim()),{error:"editor:validation.urlHasSpace"}).default("");var MI=Y.object({value:Y.string().min(1,{error:"editor:validation.caseValueRequired"}).default("").describe("Attribute value to match. Creates a 'match:<value>' output.")}),IQ=Y.object({audio:J$.optional().describe("Audio prompt played before collecting digits."),chatText:Y.string().default("").describe("Text prompt for chat mode. Supports {{variables}}."),timeout:Y.number().int().min(1).max(60).default(5).describe("Seconds to wait for digit input (1-60)."),maxAttempts:Y.number().int().min(1).max(10).default(3).describe("Maximum retry attempts for digit collection (1-10)."),digitRegex:Y.string().default("").describe("Regex to validate DTMF input. Empty means accept any."),method:Y.enum(["GET","POST","PUT"]).default("GET").describe("HTTP method for the API request."),url:p4.describe("API endpoint URL. Supports {{variables}} including collected digits as {{digits}}."),headers:Y.record(Y.string(),Y.string()).optional().describe("HTTP headers as key-value pairs."),body:Y.string().optional().describe("Request body (JSON). Supports {{variables}}. Only for POST/PUT."),requestTimeout:Y.number().int().min(1000).max(60000).default(1e4).describe("HTTP request timeout in milliseconds."),attribute:Y.string().default("").describe("JSON attribute name from the API response to match against cases."),cases:Y.array(MI).default([]).describe("Possible attribute values. Each creates a dynamic output handle 'match:<value>'.")}),NQ=C({meta:{type:"apiSwitch",module:"core",nameKey:"editor:nodes.apiSwitch.name",descriptionKey:"editor:nodes.apiSwitch.description",color:"teal",icon:"Globe",category:"legacy",nature:"composite",display:"full",channel:"both",order:3,legacy:!0,replacedBy:"httpRequest + switchCase",outputs:($)=>{return[...($.cases??[]).map((G)=>typeof G==="string"?G:G.value).filter((G)=>typeof G==="string"&&G!=="").map((G)=>({key:`match:${G}`,labelKey:G})),{key:"noInput",labelKey:"editor:handles.noInput"},{key:"error",labelKey:"editor:handles.error"}]}},configSchema:IQ,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 ZI=Y.object({language:Y.string().optional().describe("BCP 47 language code for speech recognition (e.g., 'pt-BR'). Omit for plan default."),initial_timeout_s:Y.number().min(3).max(60).default(10).describe("Maximum seconds to wait for speech to begin (3-60)."),timeout_s:Y.number().min(1).max(30).default(3).describe("Seconds of post-speech silence before stopping recording (1-30)."),max_duration_s:Y.number().min(1).max(60).default(15).describe("Maximum recording duration in seconds (1-60)."),beep:Y.boolean().default(!1).describe("Play a beep sound before starting to listen.")}),_Q=Y.object({maxAttempts:Y.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:Y.enum(["dtmf","speech"]).default("dtmf").describe("Voice input method: 'dtmf' for digits, 'speech' for ASR transcription (requires AI)."),minDigits:Y.number().min(1).max(20).default(1).describe("Minimum number of DTMF digits required (1-20)."),maxDigits:Y.number().min(1).max(20).default(1).describe("Maximum number of DTMF digits to collect (1-20)."),terminators:Y.string().default("#").describe("Key that terminates digit collection (e.g., '#')."),voiceTimeout:Y.number().min(1).max(60).default(5).describe("Seconds to wait for input in voice mode (1-60)."),listen:ZI.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:Y.string().default("").describe("Chat prompt message sent before waiting for user input. Supports {{variables}}."),validation:Y.string().optional().describe("Regex pattern to validate chat text input. Invalid input triggers retry."),invalidMessage:Y.string().optional().describe("Chat message sent when input fails validation. Supports {{variables}}.")}),wQ=C({meta:{type:"capture",module:"core",nameKey:"editor:nodes.capture.name",descriptionKey:"editor:nodes.capture.description",color:"cyan",icon:"TextCursorInput",category:"interaction",order:3,nature:"composite",display:"full",channel:"both",outputs:[{key:"collected",labelKey:"editor:handles.collected"},{key:"noInput",labelKey:"editor:handles.noInput"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:_Q,producedVariables:[{name:"text",type:"string",descriptionKey:"editor:vars.capturedText"},{name:"attempts",type:"number",descriptionKey:"editor:vars.captureAttempts"}]});var kQ=Y.object({}),xQ=C({meta:{type:"channelRouter",module:"core",nameKey:"editor:nodes.channelRouter.name",descriptionKey:"editor:nodes.channelRouter.description",color:"lime",icon:"Router",category:"routing",order:3,nature:"routing",display:"full",channel:"both",outputs:[{key:"voice",labelKey:"editor:handles.voice"},{key:"chat",labelKey:"editor:handles.chat"}]},configSchema:kQ,producedVariables:[{name:"channelType",type:"string",descriptionKey:"editor:vars.channelType"}]});var FQ=Y.object({audio:J$.default({tts:{text:""}}).describe("Audio prompt played before collecting digits."),minDigits:Y.number().min(1,{error:"editor:validation.minDigitsMin"}).max(20,{error:"editor:validation.minDigitsMax"}).default(1).describe("Minimum number of digits required (1-20)."),maxDigits:Y.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:Y.string().max(1).default("#").describe("Key that terminates digit collection (e.g., '#'). Single character."),timeout:Y.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:Y.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:Y.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:Y.string().default("").describe("Regex pattern to validate collected digits. Empty means accept any."),resetDigit:Y.string().max(1).default("").describe("Key that clears collected digits and restarts. Single character. Empty to disable.")}),LQ=C({meta:{type:"collectDigits",module:"core",nameKey:"editor:nodes.collectDigits.name",descriptionKey:"editor:nodes.collectDigits.description",color:"sky",icon:"Keyboard",category:"interaction",order:4,nature:"composite",display:"full",channel:"voice",outputs:[{key:"collected",labelKey:"editor:handles.collected"},{key:"noInput",labelKey:"editor:handles.noInput"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:FQ,producedVariables:[{name:"digits",type:"string",descriptionKey:"editor:vars.collectedDigits"},{name:"attempts",type:"number",descriptionKey:"editor:vars.collectAttempts"}]});var zQ=Y.object({name:Y.string().min(1,{error:"editor:validation.counterNameRequired"}).default("").describe("Counter name. Supports templates, e.g. 'attempts_{{start.callerid}}'."),action:Y.enum(["increment","decrement","reset"]).default("increment").describe("Operation applied to the counter. 'reset' sets it to zero and ignores step."),step:Y.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:Y.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:Y.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:Y.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.")}),bQ=C({meta:{type:"counter",module:"core",nameKey:"editor:nodes.counter.name",descriptionKey:"editor:nodes.counter.description",color:"cyan",icon:"Tally5",category:"routing",order:5,nature:"routing",display:"compact",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"},{key:"limitReached",labelKey:"editor:handles.limitReached"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:zQ,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 KT=new Intl.NumberFormat("en-US",{useGrouping:!1,maximumFractionDigits:10});var KU="secrets",PI="secrets".replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);function Ij(){return new RegExp(String.raw`\{\{\s*${PI}\.([A-Z][A-Z0-9_]*)\s*\}\}`,"g")}function Nj($){if(!$.includes("{{"))return[];let U=new Set;for(let Q of $.matchAll(Ij()))U.add(Q[1]);return[...U]}var _j={httpRequest:new Set(["url","headers","body"]),apiSwitch:new Set(["url","headers","body"]),webhook:new Set(["url","headers","body"])};function wj($,U){return _j[$]?.has(U)===!0}function AQ($,U,Q){if(typeof $==="string"){Q(U,$);return}if(Array.isArray($)){$.forEach((G,K)=>AQ(G,`${U}.${K}`,Q));return}if($!=null&&typeof $==="object")for(let[G,K]of Object.entries($))AQ(K,U===""?G:`${U}.${G}`,Q)}function QU($){let U=new Set,Q=[];return AQ($.config,"",(G,K)=>{let J=Nj(K);if(J.length===0)return;let W=G.split(".")[0]??"";if(wj($.type,W)){for(let q of J)U.add(q);return}for(let q of J)Q.push({nodeId:$.id,label:$.label,field:G,name:q})}),{allowed:[...U],misplaced:Q}}function GU($){let U=new Set,Q=[];for(let G of $){let K=QU(G);for(let J of K.allowed)U.add(J);for(let J of K.misplaced)U.add(J.name),Q.push(J)}return{names:U,misplaced:Q}}var II=/\{\{(.+?)\}\}/g;function OQ(){return/"?\{\{.+?\}\}"?/g}var JU=200;function kj($,U){let Q=$[U];if(Q==="*"||Q==="+")return 1;if(Q==="{"){let G=$.indexOf("}",U);if(G!==-1&&/^\d+,$/.test($.slice(U+1,G)))return G-U+1}return 0}function NI($,U){let Q=U+1;while(Q<$.length&&$[Q]!=="]")Q+=$[Q]==="\\"?2:1;return Q+1}function _I($,U,Q){let G=Q.pop()??{repeat:!1},K=kj($,U+1);if(K>0&&G.repeat)return{catastrophic:!0,next:U};if((G.repeat||K>0)&&Q.length>0)Q.at(-1).repeat=!0;return{catastrophic:!1,next:U+(K>0?1+K:1)}}function wI($,U,Q){let G=$[U];if(G==="\\")return{catastrophic:!1,next:U+2};if(G==="[")return{catastrophic:!1,next:NI($,U)};if(G==="(")return Q.push({repeat:!1}),{catastrophic:!1,next:U+1};if(G===")")return _I($,U,Q);let K=kj($,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:G,next:K}=wI($,Q,U);if(G)return!0;Q=K}return!1}function kI($){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 TQ($){if(!$.includes("{{"))return{valid:!0};for(let U of $.matchAll(II)){let Q=kI(U[1].trim());if(Q===null)continue;if(Q.pattern.length>JU)return{valid:!1,error:`Regex pattern too long in "${U[0]}" (max ${JU})`};if(RQ(Q.pattern))return{valid:!1,error:`Unsafe regex (possible catastrophic backtracking) in "${U[0]}"`};try{new RegExp(Q.pattern)}catch(G){let K=G instanceof Error?G.message:String(G);return{valid:!1,error:`Invalid regex in "${U[0]}": ${K}`}}}return{valid:!0}}var xj={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 SI=new Set(["error_code","error_message","error_step","error_var"]),CI=Y.string().refine(($)=>$.trim()!=="",{error:"editor:validation.emptySaveAs"}).refine(($)=>!SI.has($.trim()),{error:"editor:validation.reservedSaveAs"}).describe("Name the result is saved under. Readable by later steps and by other nodes."),Q$=($)=>Y.literal($).describe("Operation this step applies to the source."),Fj=Y.enum(["minutes","hours","days","months","years"]).describe("Time unit used by the step: minutes, hours, days, months, or years."),G$=Y.object({source:Y.string().describe("Value the step transforms. Literal text or a template like '{{start.callerid}}'."),saveAs:CI}),gI=Y.discriminatedUnion("op",[G$.extend({op:Q$("uppercase")}),G$.extend({op:Q$("lowercase")}),G$.extend({op:Q$("capitalize")}),G$.extend({op:Q$("trim")}),G$.extend({op:Q$("replace"),search:Y.string().describe("Literal text to look for. Not a regular expression. Empty leaves the source untouched."),replacement:Y.string().describe("Text that replaces every occurrence of the searched text.")}),G$.extend({op:Q$("regexReplace"),pattern:Y.string().describe("Regular expression used to match text. Nested repetition and patterns over 200 characters are rejected."),replacement:Y.string().describe("Text that replaces every match. Supports JavaScript backreferences such as '$1'.")}),G$.extend({op:Q$("part"),separator:Y.string().describe("Text that splits the source into parts. Empty splits into single characters."),index:Y.number().int().describe("Zero-based index of the part to keep. Negative counts from the end.")}),G$.extend({op:Q$("add"),operand:Y.string().describe("Number added to the source. Literal value or template.")}),G$.extend({op:Q$("subtract"),operand:Y.string().describe("Number subtracted from the source. Literal value or template.")}),G$.extend({op:Q$("multiply"),operand:Y.string().describe("Number the source is multiplied by. Literal value or template.")}),G$.extend({op:Q$("divide"),operand:Y.string().describe("Number the source is divided by. Literal value or template. Zero fails with 'divide_by_zero'.")}),G$.extend({op:Q$("round"),decimals:Y.number().int().min(0).max(10).default(0).describe("Decimal places to keep (0-10). Rounds half away from zero.")}),G$.extend({op:Q$("currency"),currency:Y.string().default("BRL").describe("ISO 4217 currency code used to format the amount, e.g. 'BRL'."),locale:Y.string().default("pt-BR").describe("Locale used to format the amount, e.g. 'pt-BR'.")}),G$.extend({op:Q$("dateOffset"),amount:Y.number().int().describe("How many units to add to the date. Negative subtracts."),unit:Fj}),G$.extend({op:Q$("dateDiff"),operand:Y.string().describe("Date compared against the source. The result is operand minus source. Literal or template."),unit:Fj}),G$.extend({op:Q$("dateFormat"),format:Y.string().default("dd/MM/yyyy").describe("Output pattern, e.g. 'dd/MM/yyyy'. Text between single quotes is kept as written."),locale:Y.string().default("pt-BR").describe("Locale used for month and weekday names, e.g. 'pt-BR'.")}),G$.extend({op:Q$("normalizePhone"),country:Y.string().default("BR").describe("ISO 3166-1 alpha-2 country code used for national numbers. Defaults to 'BR'.")}),G$.extend({op:Q$("count")}),G$.extend({op:Q$("join"),separator:Y.string().default(", ").describe("Text placed between items, except before the last one."),lastSeparator:Y.string().default(" e ").describe("Text placed before the last item. Ignored when the list has a single item.")}),G$.extend({op:Q$("item"),index:Y.number().int().describe("Zero-based index of the item to keep. Negative counts from the end.")}),G$.extend({op:Q$("filter"),field:Y.string().default("").describe("Object field compared on each item. Empty compares the item itself."),operand:Y.string().describe("Value each item is compared against, as text. Literal or template.")}),G$.extend({op:Q$("spellOut")}),G$.extend({op:Q$("inWords")}),G$.extend({op:Q$("default"),operand:Y.string().describe("Value used when the source is empty. Literal value or template.")})]),SQ=Y.object({steps:Y.array(gI).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:Y.enum(["error","empty"]).default("error").describe("What to do when a step fails: 'error' follows the error output, 'empty' continues with an empty value.")}),CQ=C({meta:{type:"dataTransform",module:"core",nameKey:"editor:nodes.dataTransform.name",descriptionKey:"editor:nodes.dataTransform.description",color:"grass",icon:"Replace",category:"data",order:5,nature:"sideEffect",display:"compact",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:SQ,producedVariables:($)=>{let U=new Map;for(let Q of $.steps){if(Q.saveAs==="")continue;U.set(Q.saveAs,{name:Q.saveAs,type:xj[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 gQ=Y.object({percentage:Y.number().int().min(0).max(100).default(100).describe("Percentage of calls to record (0-100). 100 records all calls."),minDuration:Y.number().int().min(0).default(0).describe("Minimum call duration in seconds before recording starts. 0 for immediate."),analyzeCalls:Y.boolean().default(!1).describe("Enable post-call AI analysis (requires AI module).")}),EQ=C({meta:{type:"enableRecord",module:"core",nameKey:"editor:nodes.enableRecord.name",descriptionKey:"editor:nodes.enableRecord.description",color:"red",icon:"CircleDot",category:"legacy",nature:"sideEffect",display:"compact",channel:"both",order:4,legacy:!0,outputs:[{key:"next",labelKey:"editor:handles.next"},{key:"skipped",labelKey:"editor:handles.skipped"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:gQ,producedVariables:[{name:"recording",type:"string",descriptionKey:"editor:vars.recordingStatus"}]});var yQ=Y.object({cause:Y.string().optional().describe("SIP hangup cause code (e.g., 'NORMAL_CLEARING'). Omit for default.")}),uQ=C({meta:{type:"hangup",module:"core",nameKey:"editor:nodes.hangup.name",descriptionKey:"editor:nodes.hangup.description",color:"red",icon:"PhoneOff",category:"interaction",order:5,nature:"flow",display:"full",channel:"both",outputs:[]},configSchema:yQ,producedVariables:[]});var fQ=Y.object({method:Y.enum(["GET","POST","PUT","PATCH","DELETE"]).default("GET").describe("HTTP method for the request."),url:p4.describe("Request URL. Supports template expressions, e.g., 'https://api.example.com/{{start.callerid}}'."),headers:Y.record(Y.string(),Y.string()).optional().describe("HTTP headers as key-value pairs. Values support template expressions."),body:Y.string().optional().describe("Request body (JSON string). Template expressions allowed. Only for POST/PUT/PATCH."),timeout:Y.number().optional().describe("Request timeout in milliseconds. Omit for default.")}),mQ=C({meta:{type:"httpRequest",module:"core",nameKey:"editor:nodes.httpRequest.name",descriptionKey:"editor:nodes.httpRequest.description",color:"indigo",icon:"Globe",category:"data",order:0,nature:"sideEffect",display:"compact",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:fQ,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 hQ=Y.object({audio:J$.default({tts:{text:""}}).describe("Audio prompt played before collecting DTMF input."),timeout:Y.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:Y.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).")}),cQ=C({meta:{type:"ivr",module:"core",nameKey:"editor:nodes.ivr.name",descriptionKey:"editor:nodes.ivr.description",color:"violet",icon:"Grid3x3",category:"legacy",nature:"composite",display:"full",channel:"voice",order:1,deprecated:!0,replacedBy:"menu",outputs:[{key:"digit:0",labelKey:"0"},{key:"digit:1",labelKey:"1"},{key:"digit:2",labelKey:"2"},{key:"digit:3",labelKey:"3"},{key:"digit:4",labelKey:"4"},{key:"digit:5",labelKey:"5"},{key:"digit:6",labelKey:"6"},{key:"digit:7",labelKey:"7"},{key:"digit:8",labelKey:"8"},{key:"digit:9",labelKey:"9"},{key:"digit:*",labelKey:"*"},{key:"digit:#",labelKey:"#"},{key:"timeout",labelKey:"editor:handles.timeout"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:hQ,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 lQ=Y.object({id:Y.string().min(1).default("").describe("Unique option identifier. Used as button ID in chat and output handle suffix."),label:Y.string().min(1).default("").describe("Display label shown to the user. Button text in chat, spoken in voice prompt."),digit:Y.string().default("").describe("DTMF digit for voice mode (0-9, *, #). Leave empty to skip voice for this option.")}),rQ=Y.object({options:Y.array(lQ).default([]).describe("Menu options. Each creates a dynamic output handle."),maxAttempts:Y.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:Y.number().min(1).max(60).default(5).describe("Seconds to wait for DTMF input in voice mode (1-60)."),text:Y.string().default("").describe("Chat message text displayed above buttons. Supports template expressions."),invalidMessage:Y.string().optional().describe("Chat message sent when input doesn't match any option. Supports template expressions.")}),nQ=C({meta:{type:"menu",module:"core",nameKey:"editor:nodes.menu.name",descriptionKey:"editor:nodes.menu.description",color:"violet",icon:"ListOrdered",category:"interaction",order:2,nature:"composite",display:"full",channel:"both",outputs:($)=>{return[...($.options??[]).map((G)=>typeof G==="object"&&G!=null?G:null).filter((G)=>G!=null&&typeof G.id==="string"&&G.id!=="").map((G)=>({key:`option:${G.id}`,labelKey:G.label})),{key:"noMatch",labelKey:"editor:handles.noMatch"},{key:"error",labelKey:"editor:handles.error"}]}},configSchema:rQ,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 iQ=Y.object({audio:J$.default({tts:{text:""}}).describe("Audio to play. Use TTS (text-to-speech) or a pre-recorded audio file.")}),oQ=C({meta:{type:"playback",module:"core",nameKey:"editor:nodes.playback.name",descriptionKey:"editor:nodes.playback.description",color:"blue",icon:"Volume2",category:"legacy",nature:"action",display:"full",channel:"voice",order:0,deprecated:!0,replacedBy:"tell",outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:iQ,producedVariables:[]});var dQ=Y.object({enabled:Y.boolean().optional(),samplingPercentage:Y.number().int().min(0).max(100).optional()}),pQ=C({meta:{type:"recording",module:"core",nameKey:"editor:nodes.recording.name",descriptionKey:"editor:nodes.recording.description",color:"teal",icon:"Mic",category:"media",nature:"sideEffect",display:"compact",channel:"voice",order:0,outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:dQ,producedVariables:[{name:"status",type:"string",descriptionKey:"editor:vars.recordingStatus"}]});var EI=Y.object({label:Y.string().min(1).describe("Intent name. Creates a dynamic output handle 'intent:<label>'."),description:Y.string().default("").describe("Description of what this intent means, used for LLM classification.")}),tQ=Y.object({input:Y.string().default("").describe("Template expression to evaluate, e.g. '{{resposta}}'. The resolved text is classified by AI."),intents:Y.array(EI).default([]).describe("List of intents the LLM should classify the input into. Each creates a dynamic output handle."),instructions:Y.string().default("").describe("Additional instructions for the LLM intent classifier.")}),aQ=C({meta:{type:"routeAi",module:"ai",nameKey:"editor:nodes.routeAi.name",descriptionKey:"editor:nodes.routeAi.description",color:"plum",icon:"BrainCircuit",category:"routing",order:1,nature:"routing",display:"full",channel:"both",outputs:($)=>{return[...($.intents??[]).map((G)=>G.label).filter((G)=>typeof G==="string"&&G!=="").map((G)=>({key:`intent:${G}`,labelKey:G})),{key:"notApplicable",labelKey:"editor:handles.notApplicable"},{key:"error",labelKey:"editor:handles.error"}]}},configSchema:tQ,producedVariables:[{name:"intent",type:"string",descriptionKey:"editor:vars.routeAi.intent"},{name:"confidence",type:"number",descriptionKey:"editor:vars.routeAi.confidence"}]});var eQ=Y.object({digits:Y.string().min(1,{error:"editor:validation.digitsRequired"}).default("").describe("DTMF digits to send (0-9, *, #). Supports template expressions.")}),sQ=C({meta:{type:"sendDtmf",module:"core",nameKey:"editor:nodes.sendDtmf.name",descriptionKey:"editor:nodes.sendDtmf.description",color:"bronze",icon:"Hash",category:"handling",order:2,nature:"sideEffect",display:"compact",channel:"voice",outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:eQ,producedVariables:[{name:"dtmf",type:"string",descriptionKey:"editor:vars.dtmf"}]});var $G=Y.object({prefix:Y.string().max(16,{error:"editor:validation.prefixMaxLength"}).default("").describe("Short prefix prepended to the sequence (e.g. 'SAC', '200')."),dateFormat:Y.enum(["none","yyyyMMdd","yyMMdd","yyyyMM","ddMMyyyy","yyyyMMddHHmmss"]).default("yyyyMMdd").describe("Date format inserted between prefix and counter."),padding:Y.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:Y.enum(["daily","monthly","never"]).default("daily").describe("When the counter resets to 1. Uses org timezone for boundary.")}),UG=C({meta:{type:"sequence",module:"core",nameKey:"editor:nodes.sequence.name",descriptionKey:"editor:nodes.sequence.description",color:"mint",icon:"Hash",category:"data",order:6,nature:"sideEffect",display:"compact",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:$G,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 yI=Y.object({key:Y.string().describe("Variable name. Readable as '{{vars.key}}' and through the block's generated namespace."),value:Y.string().describe("Value to assign. Supports template expressions like '{{start.callerid}}'.")}),KG=Y.object({assignments:Y.array(yI).min(1,{error:"editor:validation.noAssignments"}).default([]).describe("List of variable assignments. At least one required.")}),QG=C({meta:{type:"setVariable",module:"core",nameKey:"editor:nodes.setVariable.name",descriptionKey:"editor:nodes.setVariable.description",color:"teal",icon:"Variable",category:"data",order:4,nature:"sideEffect",display:"compact",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:KG,producedVariables:($)=>$.assignments.map((U)=>({name:U.key,type:"string",descriptionKey:"editor:vars.custom"}))});var GG=Y.object({autoAnswer:Y.boolean().optional().describe("Auto-answer incoming call before processing. Disable for pre-answer routing."),channelType:Y.enum(Hj).default("both").describe("Plan channel type.")}),JG=C({meta:{type:"start",module:"core",nameKey:"editor:nodes.start.name",descriptionKey:"editor:nodes.start.description",color:"jade",icon:"Play",category:"interaction",order:0,nature:"flow",display:"full",channel:"both",outputs:($)=>{let U=$.channelType;if((typeof U==="string"?U:"voice")==="both")return[{key:"voice",labelKey:"editor:handles.voice"},{key:"chat",labelKey:"editor:handles.chat"}];return[{key:"next",labelKey:"editor:handles.next"}]}},configSchema:GG,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 WG=Y.object({planId:Y.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:Y.record(Y.string().regex(/^[A-Z_]\w*$/i).max(64),Y.string().max(512)).default({}),endCallOnChildHangup:Y.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.")}),qG=C({meta:{type:"subPlan",module:"core",nameKey:"editor:nodes.subPlan.name",descriptionKey:"editor:nodes.subPlan.description",color:"purple",icon:"Layers",category:"data",order:2,nature:"flow",display:"full",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:WG,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 uI=Y.object({pattern:Y.string().min(1,{error:"editor:validation.casePatternRequired"}).default("").describe("Value to match against the expression. Creates a 'match:<pattern>' output.")}),YG=Y.object({expression:Y.string().min(1,{error:"editor:validation.expressionRequired"}).default("").describe("Template expression to evaluate, e.g., '{{ivr.digits}}'. Matched against case patterns."),cases:Y.array(uI).default([]).describe("List of patterns to match. Each creates a dynamic output handle 'match:<pattern>'.")}),jG=C({meta:{type:"switchCase",module:"core",nameKey:"editor:nodes.switchCase.name",descriptionKey:"editor:nodes.switchCase.description",color:"orange",icon:"GitBranch",category:"routing",order:0,nature:"routing",display:"full",channel:"both",outputs:($)=>{return[...($.cases??[]).map((G)=>typeof G==="string"?G:G.pattern).filter((G)=>typeof G==="string"&&G!=="").map((G)=>({key:`match:${G}`,labelKey:G})),{key:"fallback",labelKey:"editor:handles.fallback"},{key:"error",labelKey:"editor:handles.error"}]}},configSchema:YG,producedVariables:[{name:"destination",type:"string",descriptionKey:"editor:vars.switchDestination"}]});var fI=Y.object({type:Y.literal("text"),text:Y.string().min(1)}),mI=Y.object({type:Y.literal("media"),mediaType:Y.enum(["image","audio","video","document"]),url:Y.string().min(1),caption:Y.string().optional()}),hI=Y.object({type:Y.literal("location"),lat:Y.number(),lng:Y.number()}),cI=Y.object({type:Y.literal("button_reply"),buttonId:Y.string().min(1),buttonText:Y.string()}),lI=Y.object({type:Y.literal("list_reply"),listId:Y.string().min(1),listTitle:Y.string()}),rI=Y.object({type:Y.literal("command"),command:Y.string().min(1),args:Y.string().optional()}),XG=Y.discriminatedUnion("type",[fI,mI,hI,cI,lI,rI]),HG=Y.object({id:Y.string().min(1),label:Y.string().min(1)}),nI=Y.object({id:Y.string().min(1),title:Y.string().min(1),description:Y.string().optional()}),Lj=Y.object({title:Y.string().min(1),items:Y.array(nI).min(1)}),zj=Y.object({title:Y.string().min(1),description:Y.string().optional(),imageUrl:Y.string().optional(),buttons:Y.array(HG).default([])}),iI=Y.object({type:Y.literal("text"),text:Y.string().min(1),markdown:Y.boolean().optional()}),oI=Y.object({type:Y.literal("media"),mediaType:Y.enum(["image","audio","video","document"]),url:Y.string().min(1),caption:Y.string().optional()}),dI=Y.object({type:Y.literal("location"),lat:Y.number(),lng:Y.number(),label:Y.string().optional()}),pI=Y.object({type:Y.literal("buttons"),text:Y.string().min(1),buttons:Y.array(HG).min(1)}),tI=Y.object({type:Y.literal("list"),text:Y.string().min(1),buttonText:Y.string().min(1),sections:Y.array(Lj).min(1)}),aI=Y.object({type:Y.literal("carousel"),cards:Y.array(zj).min(1)}),eI=Y.object({type:Y.literal("template"),templateId:Y.string().min(1),params:Y.record(Y.string(),Y.string()).default({})}),t4=Y.discriminatedUnion("type",[iI,oI,dI,pI,tI,aI,eI]),sI=t4.optional().catch(void 0);var BG=Y.object({audio:J$.optional().describe("Audio to play via TTS, a pre-recorded file, or a remote URL. Used in voice plans."),content:t4.optional().describe("Message content to send in chat. Used in chat plans.")});function bj($){return typeof $==="object"&&$!==null&&"url"in $}var MG=C({meta:{type:"tell",module:"core",nameKey:"editor:nodes.tell.name",descriptionKey:"editor:nodes.tell.description",color:"blue",icon:"Volume2",category:"interaction",order:1,nature:"action",display:"full",channel:"both",outputs:($)=>bj($.audio)?[{key:"next",labelKey:"editor:handles.next"},{key:"error",labelKey:"editor:handles.error"}]:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:BG,producedVariables:($)=>bj($.audio)?[{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"}]:[]});var ZG=Y.object({scheduleId:Y.string().optional().describe("Schedule ID for time-based routing. Routes to onHours/offHours/holiday outputs.")}),VG=C({meta:{type:"timeRouting",module:"core",nameKey:"editor:nodes.timeRouting.name",descriptionKey:"editor:nodes.timeRouting.description",color:"gold",icon:"Clock",category:"routing",order:2,nature:"routing",display:"full",channel:"both",outputs:[{key:"onHours",labelKey:"editor:handles.onHours"},{key:"offHours",labelKey:"editor:handles.offHours"},{key:"holiday",labelKey:"editor:handles.holiday"}]},configSchema:ZG,producedVariables:[{name:"result",type:"string",descriptionKey:"editor:vars.timeResult"},{name:"holiday",type:"string",descriptionKey:"editor:vars.holiday"}]});var vG=Y.object({name:Y.string().min(1,{error:"editor:validation.trafficSplitPathNameRequired"}).default("").describe("Path name. Creates a 'path:<name>' output handle."),weight:Y.number().int().min(0).max(100).default(1).describe("Relative share of this path (0-100). Zero disables it without deleting it.")}),DG=Y.object({paths:Y.array(vG).default([{name:"A",weight:50},{name:"B",weight:50}]).describe("Weighted paths. Each creates a dynamic output handle 'path:<name>'."),mode:Y.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.")}),PG=C({meta:{type:"trafficSplit",module:"core",nameKey:"editor:nodes.trafficSplit.name",descriptionKey:"editor:nodes.trafficSplit.description",color:"iris",icon:"Split",category:"routing",order:4,nature:"routing",display:"full",channel:"both",outputs:($)=>{let U=$.paths??[],Q=[],G=new Set;for(let K of U){let J=typeof K==="object"&&K!=null?K.name:void 0;if(typeof J!=="string"||J===""||G.has(J))continue;G.add(J),Q.push(J)}return[...Q.map((K)=>({key:`path:${K}`,labelKey:K})),{key:"error",labelKey:"editor:handles.error"}]}},configSchema:DG,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 IG=Y.object({enabled:Y.boolean().optional(),scope:Y.enum(["from_here","whole_recording"]).optional(),samplingPercentage:Y.number().int().min(0).max(100).optional(),language:Y.string().optional(),minDurationSeconds:Y.number().int().min(0).max(K4).optional(),speechRequirement:Y.enum(X1).optional(),anonymizeEnabled:Y.boolean().optional()}),NG=C({meta:{type:"transcription",module:"ai",nameKey:"editor:nodes.transcription.name",descriptionKey:"editor:nodes.transcription.description",color:"violet",icon:"Captions",category:"media",nature:"sideEffect",display:"compact",channel:"voice",order:1,outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:IG,producedVariables:[{name:"status",type:"string",descriptionKey:"editor:vars.transcriptionStatus"}]});var $N=Y.object({key:Y.string().describe("Attached-data field name shown to the agent / CRM (e.g. 'Nome')."),value:Y.string().default("").describe("Field value. Supports template expressions like '{{cliente.nome}}'.")}),_G=Y.object({method:Y.enum(["bridge","transfer"]).default("bridge").describe("Transfer method. 'bridge' keeps call control; 'transfer' hands off completely."),destinations:Y.array(Y.string()).default([]).describe("SIP URIs or phone numbers to dial. At least one required. Tried in order."),timeout:Y.number().min(5).max(120).optional().describe("Ring timeout in seconds per destination (5-120). Omit for carrier default."),attachedData:Y.array($N).default([]).describe("Key/value pairs delivered to the agent at transfer time (screen-pop). Values support templates.").superRefine(($,U)=>{let Q=new Set;$.forEach((G,K)=>{let J=G.key.trim();if(J===""){U.addIssue({code:"custom",message:"editor:validation.attachedKeyRequired",path:[K,"key"]});return}if(Q.has(J))U.addIssue({code:"custom",message:"editor:validation.duplicateAttachedKey",path:[K,"key"]});Q.add(J)})})}),wG=C({meta:{type:"transfer",module:"core",nameKey:"editor:nodes.transfer.name",descriptionKey:"editor:nodes.transfer.description",color:"amber",icon:"PhoneForwarded",category:"handling",order:0,nature:"action",display:"full",channel:"both",outputs:[{key:"answered",labelKey:"editor:handles.answered"},{key:"busy",labelKey:"editor:handles.busy"},{key:"noAnswer",labelKey:"editor:handles.noAnswer"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:_G,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 UN=Y.object({label:Y.string().min(1).describe("Intent name. Creates a dynamic output handle 'intent:<label>'."),description:Y.string().default("").describe("Description of what this intent means, used for LLM classification.")}),KN=Y.object({language:Y.string().optional().describe("BCP 47 language code for speech recognition (e.g., 'pt-BR'). Omit for plan default."),initial_timeout_s:Y.number().min(3).max(60).default(10).describe("Maximum seconds to wait for speech to begin (3-60)."),timeout_s:Y.number().min(1).max(30).default(3).describe("Seconds of post-speech silence before stopping recording (1-30)."),max_duration_s:Y.number().min(1).max(60).default(15).describe("Maximum recording duration in seconds (1-60)."),beep:Y.boolean().default(!1).describe("Play a beep sound before starting to listen.")}),QN=Y.object({max_retries:Y.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 kG=Y.object({mode:Y.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:Y.array(UN).default([]).describe("List of intents the LLM should classify speech into. Only used when mode is 'intent'."),classification_instructions:Y.string().default("").describe("Additional instructions for the LLM intent classifier. Only used when mode is 'intent'."),listen:KN.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:QN.default({max_retries:2}).describe("Retry behavior when speech is not recognized.")}),xG=C({meta:{type:"voiceRecognition",module:"ai",nameKey:"editor:nodes.voiceRecognition.name",descriptionKey:"editor:nodes.voiceRecognition.description",color:"cyan",icon:"Mic",category:"legacy",nature:"composite",display:"full",channel:"voice",order:2,deprecated:!0,replacedBy:"capture",outputs:($)=>{if(($.mode??"intent")==="capture")return[{key:"captured",labelKey:"editor:handles.captured"},{key:"noInput",labelKey:"editor:handles.noInput"},{key:"maxRetries",labelKey:"editor:handles.maxRetries"},{key:"error",labelKey:"editor:handles.error"}];return[...($.intents??[]).map((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:kG,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 FG=Y.object({method:Y.enum(["POST","PUT","PATCH","GET","DELETE"]).default("POST").describe("HTTP method for the request."),url:p4.describe("Destination URL. Supports template expressions, e.g., 'https://hooks.example.com/{{start.callerid}}'."),headers:Y.record(Y.string(),Y.string()).optional().describe("HTTP headers as key-value pairs. Values support template expressions."),body:Y.string().optional().describe("Request body (JSON string). Template expressions allowed. Only for POST/PUT/PATCH/DELETE.")}),LG=C({meta:{type:"webhook",module:"core",nameKey:"editor:nodes.webhook.name",descriptionKey:"editor:nodes.webhook.description",color:"violet",icon:"Webhook",category:"data",order:1,nature:"sideEffect",display:"compact",channel:"both",outputs:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:FG,producedVariables:[]});var d$={start:JG,playback:oQ,ivr:cQ,collectDigits:LQ,transfer:wG,hangup:uQ,timeRouting:VG,switchCase:jG,trafficSplit:PG,setVariable:QG,sequence:UG,counter:bQ,httpRequest:mQ,webhook:LG,dataTransform:CQ,subPlan:qG,sendDtmf:sQ,aiAgent:MQ,voiceRecognition:xG,tell:MG,menu:nQ,capture:wQ,routeAi:aQ,channelRouter:xQ,addToDnc:HQ,apiSwitch:NQ,enableRecord:EQ,recording:pQ,transcription:NG,analysis:vQ},O1=Object.fromEntries(Object.entries(d$).map(([$,U])=>[$,U.meta]));var Tg=Number.MAX_SAFE_INTEGER;var zG=["active","expired","suspended","poc"],Aj=Y.object({enabled:Y.boolean(),limits:Y.record(Y.string(),Y.union([Y.number(),Y.string(),Y.boolean(),Y.array(Y.string())])).default({})}),BN=Y.object({customerId:Y.string(),customerName:Y.string().optional(),serial:Y.string(),status:Y.enum(zG),issuedAt:Y.coerce.date(),expiresAt:Y.coerce.date().nullable(),gracePeriodDays:Y.number().int().min(0),modules:Y.record(Y.string(),Aj),isExpired:Y.boolean(),isInGracePeriod:Y.boolean(),daysUntilExpiry:Y.number().nullable()}),MN=Y.object({voice:Y.number().int().default(0),chat:Y.number().int().default(0)}).optional(),ZN=Y.object({customer_id:Y.string().min(1),customer_name:Y.string().min(1).optional(),serial:Y.string().min(1),status:Y.enum(zG),issued_at:Y.coerce.date(),expires_at:Y.coerce.date().nullable().default(null),grace_period_days:Y.number().int().min(0).default(0),max_concurrent_channels:MN,modules:Y.record(Y.string(),Aj)});var WU=Y.object({channel:Y.union([Y.literal(0),Y.literal(1)]),text:Y.string(),isFinal:Y.boolean(),confidence:Y.number(),start:Y.number(),end:Y.number(),timestamp:Y.string(),nodeId:Y.string().optional(),nodeLabel:Y.string().optional(),nodeType:Y.string().optional()}),VN=Y.discriminatedUnion("type",[Y.object({type:Y.literal("segment"),segment:WU}),Y.object({type:Y.literal("started")}),Y.object({type:Y.literal("ended")}),Y.object({type:Y.literal("error"),message:Y.string()})]),vN=Y.discriminatedUnion("type",[Y.object({type:Y.literal("segment"),segment:WU}),Y.object({type:Y.literal("history"),segments:Y.array(WU)}),Y.object({type:Y.literal("starting")}),Y.object({type:Y.literal("started")}),Y.object({type:Y.literal("ended")}),Y.object({type:Y.literal("error"),message:Y.string()})]),DN=Y.object({uuid:Y.string(),action:Y.enum(["start","stop"])});var Oj="urn:ietf:params:oauth:grant-type:device_code",Rj=["authorization_code","refresh_token",Oj],bG="ABCDEFGHJKLMNPQRSTUVWXYZ",PN=Y.object({resource:Y.string(),authorization_servers:Y.array(Y.string()).min(1),scopes_supported:Y.array(Y.string()),bearer_methods_supported:Y.array(Y.string()),resource_name:Y.string().optional()}),IN=Y.object({issuer:Y.string(),authorization_endpoint:Y.string(),token_endpoint:Y.string(),registration_endpoint:Y.string(),revocation_endpoint:Y.string(),device_authorization_endpoint:Y.string(),response_types_supported:Y.array(Y.string()),grant_types_supported:Y.array(Y.string()),code_challenge_methods_supported:Y.array(Y.string()),token_endpoint_auth_methods_supported:Y.array(Y.string()),client_id_metadata_document_supported:Y.literal(!0),authorization_response_iss_parameter_supported:Y.literal(!0),scopes_supported:Y.array(Y.string())}),NN=Y.string().refine(($)=>{try{return new URL($).protocol==="https:"}catch{return!1}},"must be an https URL"),_N=Y.object({client_id:NN,redirect_uris:Y.array(Y.string().min(1)).min(1),client_name:Y.string().optional(),client_uri:Y.string().optional(),logo_uri:Y.string().optional(),scope:Y.string().optional(),grant_types:Y.array(Y.string()).optional(),response_types:Y.array(Y.string()).optional(),token_endpoint_auth_method:Y.string().optional(),token_endpoint_auth_methods_supported:Y.array(Y.string()).optional(),application_type:Y.enum(["native","web"]).optional()}).refine(wN,{error:'client must support the "none" token endpoint auth method',path:["token_endpoint_auth_method"]});function wN($){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 kN=Y.object({redirect_uris:Y.array(Y.string().min(1)).min(1),client_name:Y.string().max(200).optional(),client_uri:Y.string().optional(),logo_uri:Y.string().optional(),scope:Y.string().optional(),grant_types:Y.array(Y.enum(Rj)).optional(),response_types:Y.array(Y.literal("code")).optional(),token_endpoint_auth_method:Y.literal("none").optional(),application_type:Y.enum(["native","web"]).optional()}),xN=Y.object({client_id:Y.string(),client_id_issued_at:Y.number().int(),redirect_uris:Y.array(Y.string()),client_name:Y.string().optional(),token_endpoint_auth_method:Y.literal("none"),grant_types:Y.array(Y.string()),response_types:Y.array(Y.string()),application_type:Y.enum(["native","web"]).optional(),scope:Y.string().optional()}),FN=Y.object({client_id:Y.string().min(1).max(2048),scope:Y.string().max(2000).default(""),resource:Y.string().min(1).max(2048)}),LN=Y.object({device_code:Y.string().min(1),user_code:Y.string().regex(new RegExp(`^[${bG}]{4}-[${bG}]{4}$`)),verification_uri:Y.string(),verification_uri_complete:Y.string().optional(),expires_in:Y.number().int().positive(),interval:Y.number().int().positive()});var Tj={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"]},Sj={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"},Cj=Object.entries(Tj),zN=Cj.flatMap(([$,U])=>U.map((Q)=>`${$}:${Q}`));var gj={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"]},bN=Object.keys(gj);var ng=Cj.filter(([$])=>Sj[$]==="organization").flatMap(([$,U])=>U.map((Q)=>`${$}:${Q}`));var AG=Y.object({version:Y.literal(1),startNodeId:Y.string().min(1),nodes:Y.record(Y.string(),Y.object({type:Y.string().min(1),label:Y.string(),varName:Y.string(),config:Y.record(Y.string(),Y.unknown())})),adjacency:Y.record(Y.string(),Y.record(Y.string(),Y.string()))});function RG($,U,Q,G,K){let J=U.channelType,W=typeof J==="string"?J:"voice";if(W!=="both")return AN($,Q,G,W==="voice"?"voice-only":"chat-only");return RN($,Q,G,K)}function AN($,U,Q,G){let K=OG($,U),J={};for(let W of Q)J[W]=K.has(W)?G:"unreachable";return J[$]=G,J}function ON($,U){if($&&U)return"converged";if($)return"voice-only";if(U)return"chat-only";return"unreachable"}function RN($,U,Q,G){let K=U.get($)?.get("voice"),J=U.get($)?.get("chat"),W=K!=null?OG(K,U,G,"voice"):new Set,q=J!=null?OG(J,U,G,"chat"):new Set;if(K!=null)W.add(K);if(J!=null)q.add(J);let j={};for(let X of Q)j[X]=X===$?"converged":ON(W.has(X),q.has(X));return j}function OG($,U,Q,G){let K=new Set,J=[$];K.add($);let W=0;while(W<J.length){let q=J[W++],j=U.get(q);if(j==null)continue;if(G!=null&&Q?.has(q)){let X=j.get(G);if(X!=null&&!K.has(X))K.add(X),J.push(X);continue}for(let X of j.values())if(!K.has(X))K.add(X),J.push(X)}return K}function c(){return($,U)=>({key:U,prefix:`${$}:`})}var TN={call:c()("call",($)=>`call:${$}`),testPlan:c()("test-plan",($)=>`test-plan:${$}`),testChatPlan:c()("test-chat-plan",($)=>`test-chat-plan:${$}`),testEditorState:c()("test-editor-state",($)=>`test-editor-state:${$}`),testExecutionTrace:c()("test-execution-trace",($)=>`test-execution-trace:${$}`),refreshToken:c()("rt",($)=>`rt:${$}`),revokedToken:c()("revoked",($)=>`revoked:${$}`),oauthCode:c()("oauth:code",($)=>`oauth:code:${$}`),oauthCimd:c()("oauth:cimd",($)=>`oauth:cimd:${$}`),oauthDevice:c()("oauth:device",($)=>`oauth:device:${$}`),oauthUsercode:c()("oauth:usercode",($)=>`oauth:usercode:${$}`),oauthUsercodeAttempts:c()("oauth:usercode-attempts",($)=>`oauth:usercode-attempts:${$}`),channels:c()("niva:channels",($)=>`niva:channels:${$}`),concurrentChannels:c()("niva:concurrent_channels",($,U)=>`niva:concurrent_channels:${$}:${U}`),peakConcurrentChannels:c()("niva:peak_concurrent",($,U)=>`niva:peak_concurrent:${$}:${U}`),dialerCampaignActive:c()("niva:dialer_campaign_active",($)=>`niva:dialer_campaign_active:${$}`),capacityReservation:c()("niva:capacity_reservation",($)=>`niva:capacity_reservation:${$}`),capacityReservationData:c()("niva:capacity_reservation_data",()=>"niva:capacity_reservation_data"),capacityReservationExpiry:c()("niva:capacity_reservation_expiry",()=>"niva:capacity_reservation_expiry"),capacityReservationHandoff:c()("niva:capacity_reservation_handoff",($)=>`niva:capacity_reservation_handoff:${$}`),counterByPlan:c()("niva:counter:plan",($,U,Q)=>`niva:counter:plan:${$}:${U}:${Q}`),counterByOrg:c()("niva:counter:org",($,U)=>`niva:counter:org:${$}:${U}`),trafficSplitRotation:c()("niva:traffic_split",($,U,Q,G)=>`niva:traffic_split:${$}:${U}:${Q}:${G}`),rateLimit:c()("rl",($,U)=>`rl:${$}:${U}`),liveTranscriptionSegments:c()("live-ts",($)=>`live-ts:${$}`),transcriptionWatchers:c()("ts-watchers",($)=>`ts-watchers:${$}`),chatSession:c()("chat-session",($)=>`chat-session:${$}`),chatLookup:c()("chat-lookup",($,U,Q)=>`chat-lookup:${$}:${U}:${Q}`),chatLock:c()("chat-lock",($,U)=>`chat-lock:${$}:${U}`),chatInboundMessage:c()("chat-inbound-message",($,U,Q,G)=>`chat-inbound-message:${$}:${U}:${Q}:${G}`),wsSession:c()("ws:session",($)=>`ws:session:${$}`),wsMessageLog:c()("ws:log",($)=>`ws:log:${$}`),wsSeq:c()("ws:seq",($)=>`ws:seq:${$}`),healthStatus:c()("health-status",($)=>`health-status:${$}`),alertCooldown:c()("alert-cd",($,U)=>`alert-cd:${$}:${U}`),auditRetentionOverCap:c()("audit-retention",()=>"audit-retention:over-cap"),recordingDownloadAudit:c()("rec-dl-audit",($,U)=>`rec-dl-audit:${$}:${U}`),screenPop:c()("screenpop",($,U)=>`screenpop:${$}:${U}`),screenPopLegacy:c()("call_info",($)=>`call_info_${$}`),engineHeartbeat:c()("engine:heartbeat",()=>"engine:heartbeat")};function TG($,U){return typeof $==="string"&&$!==""&&!U.has($)}function SG($,U){return{nodeId:$.id,severity:"error",messageKey:U,params:{label:$.label}}}function CN($,U){if($.type!=="timeRouting"||U==null)return null;if(!TG($.config.scheduleId,U))return null;return SG($,"editor:validation.danglingSchedule")}function gN($,U){if($.type!=="subPlan"||U==null)return null;if(!TG($.config.planId,U))return null;return SG($,"editor:validation.danglingPlan")}function EN($,U){if(U==null)return null;let Q=$.config.audio;if(Q==null||typeof Q!=="object"||!("file"in Q))return null;let G=Q.file;if(G==null||typeof G!=="object"||!("id"in G))return null;if(!TG(G.id,U))return null;return SG($,"editor:validation.danglingAudioFile")}function yN($,U){if(U==null)return[];return QU($).allowed.filter((Q)=>!U.has(Q)).map((Q)=>({nodeId:$.id,severity:"error",messageKey:"editor:validation.danglingSecret",params:{label:$.label,secret:Q}}))}function CG($,U){let Q=[];for(let G of $){let K=CN(G,U.schedules);if(K!=null)Q.push(K);let J=gN(G,U.publishedPlans);if(J!=null)Q.push(J);let W=EN(G,U.audioFiles);if(W!=null)Q.push(W);Q.push(...yN(G,U.secrets))}return Q}function gG($,U){let Q=[];for(let G of $){if(G.type!=="aiAgent"||U.aiAgents==null)continue;let K=G.config.agent_id;if(typeof K==="string"&&K!==""&&!U.aiAgents.has(K))Q.push({nodeId:G.id,severity:"warning",messageKey:"editor:validation.danglingAiAgent",params:{label:G.label}})}return Q}var T$={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"]},EG=[...T$.basic,...T$.details,...T$.media,...T$.errors,...T$.origin,...T$.metadata,...T$.variables],Ej=/^analysis:[a-z0-9][a-z0-9-]*\.[A-Za-z0-9_-]+(?:\[\])?(?:\.[A-Za-z0-9_-]+(?:\[\])?)*$/,uN=Y.string().regex(Ej,{error:"Invalid structured-analysis export column"}).refine(($)=>yj($),{error:"Invalid structured-analysis export column"});function yj($){return Ej.test($)}var uj=["sip_call_id","remote_addr","user_agent"],fN=new Set(uj),mN=EG.filter(($)=>!fN.has($)),hN=[...T$.basic];var cN={basic:[...T$.basic],full:[...EG],ai_audit:[...T$.basic,"transcription_status","transcription","analysis","sentiment_label","ai_agent_price","ai_agent_currency",...T$.errors,...T$.metadata,"variables"]};var yG=["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","plan.published","message.sent","dialer.attempt.finished","alert.fired","alert.resolved","service.down","service.up"];var fj=[1,5,30,120,300,600],lN=fj.length,mj=Y.enum(["inbound","outbound"]),q$=Y.iso.datetime(),h$=Y.record(Y.string(),Y.string()),rN=Y.strictObject({amd:Y.literal(!0),machine_type:Y.literal(!0).optional(),mode:Y.enum(Bj).optional(),max_wait_seconds:Y.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"})}),hj=Y.strictObject({call_id:Y.string().min(1),caller_id:Y.string(),callee_id:Y.string(),direction:mj,visual_plan_id:Y.string().min(1),visual_plan_name:Y.string(),started_at:q$,answer_recognition:rN.optional(),metadata:h$}),cj=Y.strictObject({call_id:Y.string().min(1),caller_id:Y.string(),callee_id:Y.string(),answered_at:q$,metadata:h$}),uG=Y.enum(["machine","human","unknown"]),lj=Y.enum(Mj),rj=Y.strictObject({call_id:Y.string().min(1),channel_uuid:Y.string().min(1),result:uG,machine_type:lj.optional(),completed_at:q$,metadata:h$}).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"})}),nj=Y.strictObject({call_id:Y.string().min(1),caller_id:Y.string(),callee_id:Y.string(),direction:mj,visual_plan_id:Y.string().min(1),visual_plan_name:Y.string(),started_at:q$,answered_at:q$.nullable(),ended_at:q$,duration_ms:Y.number().nonnegative(),hangup_cause:Y.string(),hangup_disposition:Y.string(),was_recorded:Y.boolean(),variables:Y.record(Y.string(),Y.string()),sip_code:Y.string().nullable(),billsec:Y.number().nonnegative().nullable(),answer_recognition_results:Y.strictObject({amd:uG}).optional(),metadata:h$}),ij=["not_found","channel_inactive","channel_deleted","plan_deleted","no_published_version","org_deleted","acl_denied","capacity_global","capacity_org","capacity_campaign","capacity_reservation"],oj=Y.enum(ij),dj=Y.strictObject({caller:Y.string(),destination:Y.string(),reason:oj,hangup_cause:Y.string()}),pj=Y.strictObject({call_id:Y.string().min(1),caller_id:Y.string(),callee_id:Y.string(),node_id:Y.string().min(1),node_type:Y.string(),node_label:Y.string(),handle_used:Y.string(),digit:Y.string().nullable(),entered_at:q$,exited_at:q$,duration_ms:Y.number().nonnegative(),visual_plan_id:Y.string().min(1),metadata:h$}),fG=Y.strictObject({call_id:Y.string().min(1),caller_id:Y.string(),callee_id:Y.string(),node_id:Y.string().min(1),node_type:Y.string(),node_label:Y.string(),error_code:Y.string(),error_message:Y.string(),visual_plan_id:Y.string().min(1),visual_plan_name:Y.string(),occurred_at:q$,metadata:h$}),tj=fG,aj=Y.strictObject({call_record_id:Y.string().min(1),transcription_id:Y.string().min(1),full_text:Y.string(),is_anonymized:Y.boolean(),metadata:h$}),ej=["native","local","sippulse_ai"],nN=Y.enum(ej),sj=Y.strictObject({source:Y.literal("native"),id:Y.null(),template_id:Y.null(),name:Y.string(),category:Y.null()}),$X=Y.strictObject({source:Y.literal("local"),id:Y.string().min(1),template_id:Y.string().min(1),name:Y.string(),category:Y.string().nullable()}),UX=Y.strictObject({source:Y.literal("sippulse_ai"),id:Y.string().min(1),template_id:Y.null(),external_id:Y.string().min(1),slug:Y.string().min(1),name:Y.string(),category:Y.null(),model:Y.string().nullable()}),JE=Y.discriminatedUnion("source",[sj,$X,UX]),mG={status:Y.enum(["completed","failed"]),result:Y.record(Y.string(),Y.unknown()).nullable(),error_message:Y.string().nullable(),error_code:Y.string().nullable()},iN=Y.strictObject({...sj.shape,...mG}),oN=Y.strictObject({...$X.shape,...mG}),dN=Y.strictObject({...UX.shape,...mG}),pN=Y.discriminatedUnion("source",[iN,oN,dN]).superRefine(($,U)=>{if($.status==="failed"&&$.result!==null)U.addIssue({code:"custom",path:["result"],message:"Failed analyses must have a null result"})}),KX=Y.strictObject({call_id:Y.string().min(1),call_record_id:Y.string().min(1),transcription_id:Y.string().min(1),visual_plan_id:Y.string().nullable(),analyses:pN.array().min(1),analyzed_at:q$,metadata:h$}),QX=["answered","busy","noAnswer","failed"],GX=Y.enum(QX),JX=Y.strictObject({call_id:Y.string().min(1),caller_id:Y.string(),callee_id:Y.string(),to_destination:Y.string(),method:Y.enum(["bridge","sip_message","blind"]),disposition:GX,status:Y.string(),duration_ms:Y.number().nonnegative().nullable(),transferred_at:q$,metadata:h$}),WX=Y.strictObject({call_id:Y.string().min(1),call_record_id:Y.string().min(1),recording_url:Y.string(),storage_path:Y.string(),duration_seconds:Y.number().nonnegative().nullable(),format:Y.string(),size_bytes:Y.number().nonnegative().nullable(),available_at:q$,metadata:h$}),tN=Y.strictObject({intent:Y.string(),confidence:Y.number()}),qX=Y.strictObject({call_id:Y.string().min(1),caller_id:Y.string(),callee_id:Y.string(),node_id:Y.string().min(1),visual_plan_id:Y.string().min(1),transcript:Y.string(),intent:Y.string(),confidence:Y.number(),alternatives:Y.array(tN),language:Y.string().nullable(),matched_at:q$,metadata:h$}),YX=Y.strictObject({plan_id:Y.string().min(1),plan_name:Y.string(),version_id:Y.string().min(1),version_number:Y.number().int().nonnegative(),published_by_user_id:Y.string().min(1),notes:Y.string().nullable(),published_at:q$}),jX=["text","media","audio","image","video","document","location","interactive"],XX=Y.strictObject({session_id:Y.string().min(1),channel_type:Y.string(),to:Y.string(),message_type:Y.enum(jX),text:Y.string().nullable(),media_url:Y.string().nullable(),node_id:Y.string().nullable(),sent_at:q$}),HX=["answered","machine","busy","no_answer","failed","originate_error","cancelled"],BX=Y.enum(HX),MX=Y.strictObject({campaign_id:Y.string().min(1),campaign_name:Y.string(),contact_id:Y.string().min(1),phone_number:Y.string(),attempt_number:Y.number().int().nonnegative(),status:BX,hangup_cause:Y.string().nullable(),sip_code:Y.string().nullable(),call_uuid:Y.string().nullable(),started_at:q$.nullable(),answered_at:q$.nullable(),ended_at:q$.nullable(),duration_s:Y.number().nonnegative().nullable(),custom_fields:Y.record(Y.string(),Y.string())}),ZX=Y.strictObject({alert_type:Y.string(),severity:Y.enum(["critical","warning","info"]),title:Y.string(),body:Y.string(),metric_value:Y.number().optional(),threshold:Y.number().optional()}),VX=Y.strictObject({alert_type:Y.string(),title:Y.string(),body:Y.string()}),vX=Y.strictObject({component:Y.string(),checked_at:q$}),DX=Y.strictObject({component:Y.string(),downtime_seconds:Y.number().nonnegative().nullable(),recovered_at:q$}),hG={"call.started":hj,"call.answered":cj,"call.amd_completed":rj,"call.hangup":nj,"call.rejected":dj,"call.node_entered":pj,"call.node_error":fG,"call.node_warning":tj,"call.transcribed":aj,"call.analysis_completed":KX,"call.transferred":JX,"call.recording_available":WX,"call.intent_matched":qX,"plan.published":YX,"message.sent":XX,"dialer.attempt.finished":MX,"alert.fired":ZX,"alert.resolved":VX,"service.down":vX,"service.up":DX};function H$($){return Y.strictObject({event:Y.literal($),event_id:Y.string().min(1),org_id:Y.string().min(1),timestamp:q$,data:hG[$]})}var aN=Y.discriminatedUnion("event",[H$("call.started"),H$("call.answered"),H$("call.amd_completed"),H$("call.hangup"),H$("call.rejected"),H$("call.node_entered"),H$("call.node_error"),H$("call.node_warning"),H$("call.transcribed"),H$("call.analysis_completed"),H$("call.transferred"),H$("call.recording_available"),H$("call.intent_matched"),H$("plan.published"),H$("message.sent"),H$("dialer.attempt.finished"),H$("alert.fired"),H$("alert.resolved"),H$("service.down"),H$("service.up")]),n="01kknxab29enebk2vhm0tz0yyd",PX={"call.started":{call_id:`call_${n}`,caller_id:"+15551230001",callee_id:"+15551230002",direction:"inbound",visual_plan_id:`vp_${n}`,visual_plan_name:"Support IVR",started_at:"2026-01-15T12:00:00.000Z",metadata:{}},"call.answered":{call_id:`call_${n}`,caller_id:"+15551230001",callee_id:"+15551230002",answered_at:"2026-01-15T12:00:03.000Z",metadata:{}},"call.amd_completed":{call_id:`call_${n}`,channel_uuid:"freeswitch-channel-example",result:"machine",machine_type:"voicemail",completed_at:"2026-01-15T12:00:05.000Z",metadata:{}},"call.hangup":{call_id:`call_${n}`,caller_id:"+15551230001",callee_id:"+15551230002",direction:"inbound",visual_plan_id:`vp_${n}`,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_${n}`,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_${n}`,metadata:{}},"call.node_error":{call_id:`call_${n}`,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_${n}`,visual_plan_name:"Support IVR",occurred_at:"2026-01-15T12:00:10.000Z",metadata:{}},"call.node_warning":{call_id:`call_${n}`,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_${n}`,visual_plan_name:"Support IVR",occurred_at:"2026-01-15T12:00:10.000Z",metadata:{}},"call.transcribed":{call_record_id:`call_${n}`,transcription_id:`ctr_${n}`,full_text:"Hello, I need help with my account.",is_anonymized:!0,metadata:{}},"call.analysis_completed":{call_id:`call_${n}`,call_record_id:`call_${n}`,transcription_id:`ctr_${n}`,visual_plan_id:`vp_${n}`,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_${n}`,template_id:null,external_id:"sa_quality",slug:"quality",name:"Executive Summary",category:null,model:"gpt-4o-mini",status:"failed",result:null,error_code:"upstream_failure",error_message:"Structured analysis service returned an error."}],analyzed_at:"2026-01-15T12:02:00.000Z",metadata:{}},"call.transferred":{call_id:`call_${n}`,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_${n}`,call_record_id:`call_${n}`,recording_url:`https://example.invalid/recordings/call_${n}.wav`,storage_path:`recordings/example/call_${n}.wav`,duration_seconds:57,format:"wav",size_bytes:912000,available_at:"2026-01-15T12:01:01.000Z",metadata:{}},"call.intent_matched":{call_id:`call_${n}`,caller_id:"+15551230001",callee_id:"+15551230002",node_id:"node_intent",visual_plan_id:`vp_${n}`,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:{}},"plan.published":{plan_id:`vp_${n}`,plan_name:"Support IVR",version_id:`vpv_${n}`,version_number:3,published_by_user_id:`usr_${n}`,notes:"Updated support routing",published_at:"2026-01-15T11:00:00.000Z"},"message.sent":{session_id:`call_${n}`,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_${n}`,campaign_name:"January outreach",contact_id:`dct_${n}`,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 d6($){let U=d$[$],Q=O1[$],G=Q.defaultConfig,K=G4(Q,G),J=typeof Q.producedVariables==="function"?Q.producedVariables(G):Q.producedVariables,W=jQ($,"en");return{type:$,name:W?.name??$,description:W?.description??"",nameKey:Q.nameKey,descriptionKey:Q.descriptionKey,module:Q.module,category:Q.category,channel:Q.channel,nature:Q.nature,configJsonSchema:Y.toJSONSchema(U.configSchema,{unrepresentable:"any"}),outputs:K,producedVariables:J,defaultConfig:G}}var sN=Object.keys(d$);function cG(){return sN.map(($)=>d6($))}var $_=["string","number","boolean","object","array"],IX=Y.strictObject({name:Y.string(),type:Y.enum($_),required:Y.boolean(),nullable:Y.boolean()}),NX=Y.strictObject({event:Y.enum(yG),required_module:Y.enum(["core","ai","queues","dialer","omnichannel","enterprise"]).nullable(),fields:Y.array(IX),example:Y.record(Y.string(),Y.unknown())}),U_=Y.array(NX);var _X="edge";var K_=Y.object({text:Y.string().min(1).max(5000),voice:Y.string().min(1),model:Y.string().default(_X)});var wX=["not_applicable","disabled","waiting","pending","processing","completed","failed","skipped","purged","expired"];var IE=new Set(wX);var lG=Y.record(Y.string(),Y.string());var qU=Y.object({id:Y.string(),sequence:Y.number().int().nonnegative(),nodeId:Y.string(),nodeType:Y.string(),nodeLabel:Y.string(),status:Y.enum(["running","completed","warning","error"]),enteredAt:Y.string(),exitedAt:Y.string().nullable(),durationMs:Y.number().int().nonnegative().nullable(),handleUsed:Y.string().nullable(),digit:Y.string().nullable(),variablesBefore:lG,variablesAfter:lG.nullable(),resolvedConfig:Y.record(Y.string(),Y.unknown()),resultData:Y.record(Y.string(),Y.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"})}),G_=Y.object({orgId:Y.string(),status:Y.enum(["active","waiting_input","ended"]),currentNodeId:Y.string(),variables:lG,steps:Y.array(qU),truncated:Y.boolean()});function J4($){return{audio:{tts:{text:$}}}}function W_($){return{type:"text",text:$}}function I($){return{...J4($),content:W_($)}}function i($,U,Q={},G){return{options:U,maxAttempts:3,audio:J4($).audio,text:G??$,...Q}}function B$($,U={}){return{audio:J4($).audio,text:$,...U}}function l($,U,Q,G){return[H(`${$}a`,U,"answered",Q),H(`${$}b`,U,"busy",G),H(`${$}n`,U,"noAnswer",G),H(`${$}e`,U,"error",G)]}var q_={x:0,y:0};function M($,U,Q,G,K){return{id:$,type:U,label:Q,varName:G,position:q_,config:K}}function H($,U,Q,G){return{id:$,source:U,sourceHandle:Q,target:G,targetHandle:"in"}}var kX={id:"atendente-virtual-ia",category:"ai",requiredModules:["ai"],tags:["ia","agente","ai","virtual","conversacional"],editorState:{nodes:[M("s1","start","Início","inicio",{channelType:"both"}),M("t1","tell","Boas-vindas","boas_vindas",I("Olá! Sou o assistente virtual. Posso ajudar com diversas questões.")),M("ai1","aiAgent","Agente IA","agente_ia",{agent_id:"",agent_name:"",additional_instructions:"",variables:{},initial_message:"Olá, como posso ajudar?",max_duration_minutes:10}),M("m1","menu","Satisfação","satisfacao",i("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:")),M("t2","tell","Agradecimento","agradecimento",I("Obrigado pelo contato. Tenha um bom dia!")),M("t3","tell","Transferindo","transferindo",I("Vou transferir para um atendente humano.")),M("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["1000"],timeout:45}),M("t4","tell","Erro IA","erro_ia",I("Houve um problema com o assistente. Vou transferir para um atendente.")),M("t5","tell","Transferência Falhou","transferencia_falhou",I("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),M("h1","hangup","Desligamento","desligamento",{})],edges:[H("e1v","s1","voice","t1"),H("e1c","s1","chat","t1"),H("e2","t1","next","ai1"),H("e3","ai1","completed","m1"),H("e4","ai1","error","t4"),H("e5","m1","option:satisfeito","t2"),H("e6","m1","option:atendente","t3"),H("e7","m1","noMatch","t3"),H("e8","m1","error","t3"),H("e9","t2","next","h1"),H("e10","t3","next","x1"),H("e11","t4","next","x1"),...l("ex1","x1","h1","t5"),H("e12","t5","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var xX={id:"atendimento-agente-ia",category:"ai",requiredModules:["ai"],tags:["ia","ai","agente","atendimento","intencao","classificacao","transferencia"],editorState:{nodes:[M("s1","start","Início","inicio",{channelType:"both"}),M("t1","tell","Boas-vindas","boas_vindas",I("Olá! Você ligou para a nossa central. Em poucas palavras, me diga como posso ajudar.")),M("c1","capture","Captura","captura",B$("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:J4("Um momento enquanto analiso o seu pedido.").audio})),M("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."}),M("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}),M("sw1","switchCase","Decidir","decidir",{expression:"{{agente.output.resultado}}",cases:[{pattern:"^resolvido$"}]}),M("t2","tell","Despedida","despedida",I("Obrigado pelo contato. Tenha um ótimo dia!")),M("t3","tell","Não Entendi","nao_entendeu",I("Não consegui entender o motivo do contato. Vou transferir para um atendente.")),M("t4","tell","Erro Técnico","erro_tecnico",I("Tivemos um problema no atendimento automático. Vou transferir para um atendente.")),M("x1","transfer","Transferência Humana","transfer_humano",{method:"bridge",destinations:["1000"]}),M("t5","tell","Transferência Falhou","transfer_falhou",I("Não conseguimos completar a transferência. Por favor, ligue novamente mais tarde.")),M("h1","hangup","Desligamento","desligamento",{})],edges:[H("e1v","s1","voice","t1"),H("e1c","s1","chat","t1"),H("e2","t1","next","c1"),H("e3","c1","collected","ra1"),H("e4","c1","noInput","t3"),H("e5","c1","error","t4"),H("e6","ra1","intent:suporte","ai1"),H("e7","ra1","intent:financeiro","x1"),H("e8","ra1","notApplicable","t3"),H("e9","ra1","error","t4"),H("e10","ai1","completed","sw1"),H("e11","ai1","error","t4"),H("e12","sw1","match:^resolvido$","t2"),H("e13","sw1","fallback","x1"),H("e14","sw1","error","t4"),H("e15","t3","next","x1"),H("e16","t4","next","x1"),H("e17","t2","next","h1"),H("e18","x1","answered","t2"),H("e19","x1","busy","t5"),H("e20","x1","noAnswer","t5"),H("e21","x1","error","t5"),H("e22","t5","next","h1")],viewport:{x:0,y:0,zoom:0.75}}};var FX={id:"atendimento-setores",category:"core",requiredModules:[],tags:["menu","transfer","setores","departamentos","ura"],editorState:{nodes:[M("s1","start","Início","inicio",{channelType:"both"}),M("t1","tell","Boas-vindas","boas_vindas",I("Bem-vindo. Escolha entre financeiro, suporte, vendas ou ouvidoria.")),M("m1","menu","Menu Principal","menu_principal",i("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:")),M("t2","tell","Transferindo Financeiro","transferindo_financeiro",I("Aguarde, transferindo para o financeiro.")),M("t3","tell","Transferindo Suporte","transferindo_suporte",I("Aguarde, transferindo para o suporte técnico.")),M("t4","tell","Transferindo Vendas","transferindo_vendas",I("Aguarde, transferindo para vendas.")),M("t5","tell","Transferindo Ouvidoria","transferindo_ouvidoria",I("Aguarde, transferindo para a ouvidoria.")),M("x1","transfer","Financeiro","financeiro",{method:"bridge",destinations:["1001"],timeout:30}),M("x2","transfer","Suporte","suporte",{method:"bridge",destinations:["1002"],timeout:30}),M("x3","transfer","Vendas","vendas",{method:"bridge",destinations:["1003"],timeout:30}),M("x4","transfer","Ouvidoria","ouvidoria",{method:"bridge",destinations:["1004"],timeout:30}),M("t6","tell","Opção Inválida","opcao_invalida",I("Não entendi sua escolha. Por favor, ligue novamente.")),M("t7","tell","Transferência Falhou","transferencia_falhou",I("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),M("h1","hangup","Desligamento","desligamento",{})],edges:[H("e1v","s1","voice","t1"),H("e1c","s1","chat","t1"),H("e2","t1","next","m1"),H("e3","m1","option:financeiro","t2"),H("e4","m1","option:suporte","t3"),H("e5","m1","option:vendas","t4"),H("e6","m1","option:ouvidoria","t5"),H("e7","t2","next","x1"),H("e8","t3","next","x2"),H("e9","t4","next","x3"),H("e10","t5","next","x4"),H("e11","m1","noMatch","t6"),H("e12","m1","error","t6"),H("e13","t6","next","h1"),...l("ex1","x1","h1","t7"),...l("ex2","x2","h1","t7"),...l("ex3","x3","h1","t7"),...l("ex4","x4","h1","t7"),H("e14","t7","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var LX={id:"banco-sac",category:"industry",requiredModules:[],tags:["banco","financeiro","sac","saldo","extrato","cartao"],editorState:{nodes:[M("s1","start","Início","inicio",{channelType:"both"}),M("c1","capture","CPF do Cliente","cpf_cliente",B$("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:"})),M("m1","menu","Menu Serviços","menu_servicos",i("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:")),M("http1","httpRequest","Consultar Saldo","consultar_saldo",{method:"GET",url:"https://api.example.com/accounts/{{cpf_cliente.text}}/balance",headers:{},body:"",timeout:10}),M("t1","tell","Saldo Informado","saldo_informado",I("O seu saldo é: {{consultar_saldo.response}}. Obrigado pelo contato.")),M("t2","tell","Extrato","extrato",I("Seu extrato será enviado por SMS em instantes.")),M("t3","tell","Cartões","cartoes",I("Para informações sobre cartões, vou transferir para um especialista.")),M("t4","tell","Transferindo Atendente","transferindo_atendente",I("Aguarde, vou transferir para um atendente.")),M("t5","tell","Erro Consulta","erro_consulta",I("Não foi possível realizar a consulta agora. Vou transferir para um atendente.")),M("t6","tell","Sem Identificação","sem_identificacao",I("Não consegui identificar o seu CPF. Vou transferir para um atendente.")),M("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["5001"],timeout:45}),M("t7","tell","Transferência Falhou","transferencia_falhou",I("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),M("h1","hangup","Desligamento","desligamento",{})],edges:[H("e1v","s1","voice","c1"),H("e1c","s1","chat","c1"),H("e2","c1","collected","m1"),H("e3","c1","noInput","t6"),H("e4","c1","error","t6"),H("e5","m1","option:saldo","http1"),H("e6","m1","option:extrato","t2"),H("e7","m1","option:cartao","t3"),H("e8","m1","option:atendente","t4"),H("e9","m1","noMatch","t6"),H("e10","m1","error","t6"),H("e11","http1","next","t1"),H("e12","http1","error","t5"),H("e13","t1","next","h1"),H("e14","t2","next","h1"),H("e15","t3","next","x1"),H("e16","t4","next","x1"),H("e17","t5","next","x1"),H("e18","t6","next","x1"),...l("ex1","x1","h1","t7"),H("e19","t7","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var zX={id:"clinica-agendamento",category:"industry",requiredModules:[],tags:["clinica","saude","agendamento","consulta","medico"],editorState:{nodes:[M("s1","start","Início","inicio",{channelType:"both"}),M("t1","tell","Boas-vindas","boas_vindas",I("Bem-vindo à central de agendamentos.")),M("m1","menu","Especialidade","especialidade",i("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:")),M("c1","capture","CPF do Paciente","cpf_paciente",B$("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:"})),M("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}),M("t2","tell","Resultado da Consulta","resultado_consulta",I("{{consultar_agenda.response}}")),M("t3","tell","Erro na Consulta","erro_consulta",I("Não conseguimos consultar a agenda no momento. Por favor, tente novamente mais tarde.")),M("t4","tell","Sem Dados","sem_dados",I("Não consegui capturar as informações necessárias. Por favor, tente novamente mais tarde.")),M("h1","hangup","Desligamento","desligamento",{})],edges:[H("e1v","s1","voice","t1"),H("e1c","s1","chat","t1"),H("e2","t1","next","m1"),H("e3","m1","option:clinico","c1"),H("e4","m1","option:cardio","c1"),H("e5","m1","option:orto","c1"),H("e6","m1","noMatch","t4"),H("e7","m1","error","t4"),H("e8","c1","collected","http1"),H("e9","c1","noInput","t4"),H("e10","c1","error","t4"),H("e11","http1","next","t2"),H("e12","http1","error","t3"),H("e13","t2","next","h1"),H("e14","t3","next","h1"),H("e15","t4","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var bX={id:"cobranca-automatizada",category:"capture",requiredModules:[],tags:["cobranca","debito","pagamento","boleto","pix","negociacao"],editorState:{nodes:[M("s1","start","Início","inicio",{channelType:"both"}),M("t1","tell","Intro Cobrança","intro_cobranca",I("Olá, identificamos um débito em aberto na sua conta.")),M("m1","menu","Opções de Pagamento","opcoes_pagamento",i("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:")),M("c1","capture","Identificação","identificacao",B$("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:"})),M("t2","tell","Transferindo Negociação","transferindo_negociacao",I("Recebi sua identificação. Vou transferir para um especialista em negociação.")),M("x1","transfer","Negociação","negociacao",{method:"bridge",destinations:["2001"],timeout:45}),M("t3","tell","Boleto Enviado","boleto_enviado",I("O boleto atualizado será enviado para seu contato cadastrado em até 5 minutos.")),M("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.")),M("t5","tell","Opção Inválida","opcao_invalida",I("Não entendi sua escolha. Por favor, ligue novamente.")),M("t6","tell","Sem Identificação","sem_identificacao",I("Não recebi sua identificação. Por favor, ligue novamente com os dados em mãos.")),M("t7","tell","Transferência Falhou","transferencia_falhou",I("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),M("h1","hangup","Desligamento","desligamento",{})],edges:[H("e1v","s1","voice","t1"),H("e1c","s1","chat","t1"),H("e2","t1","next","m1"),H("e3","m1","option:negociar","c1"),H("e4","m1","option:boleto","t3"),H("e5","m1","option:pix","t4"),H("e6","m1","noMatch","t5"),H("e7","m1","error","t5"),H("e8","c1","collected","t2"),H("e9","c1","noInput","t6"),H("e10","c1","error","t6"),H("e11","t2","next","x1"),H("e12","t3","next","h1"),H("e13","t4","next","h1"),H("e14","t5","next","h1"),H("e15","t6","next","h1"),...l("ex1","x1","h1","t7"),H("e16","t7","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var AX={id:"coleta-dados-api",category:"capture",requiredModules:[],tags:["capture","api","http","dados","integracao"],editorState:{nodes:[M("s1","start","Início","inicio",{channelType:"both"}),M("t1","tell","Boas-vindas","boas_vindas",I("Olá. Vou consultar uma informação para você.")),M("c1","capture","Identificação","identificacao",B$("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:"})),M("http1","httpRequest","Consultar API","consultar_api",{method:"GET",url:"https://api.example.com/lookup/{{identificacao.text}}",headers:{},body:"",timeout:10}),M("sw1","switchCase","Tipo de Falha","tipo_falha",{expression:"{{consultar_api.status_code}}",cases:[{pattern:"^404$"}]}),M("t2","tell","Resultado Encontrado","resultado_encontrado",I("Encontrei as informações solicitadas: {{consultar_api.response}}. Obrigado pelo contato.")),M("t3","tell","Não Encontrado","nao_encontrado",I("Não encontrei registros para essa identificação. Verifique o número e tente novamente.")),M("t4","tell","Erro de Consulta","erro_consulta",I("Houve um erro na consulta. Tente novamente mais tarde.")),M("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.")),M("h1","hangup","Desligamento","desligamento",{})],edges:[H("e1v","s1","voice","t1"),H("e1c","s1","chat","t1"),H("e2","t1","next","c1"),H("e3","c1","collected","http1"),H("e4","c1","noInput","t5"),H("e5","c1","error","t5"),H("e6","http1","next","t2"),H("e7","http1","error","sw1"),H("e8","sw1","match:^404$","t3"),H("e9","sw1","fallback","t4"),H("e10","sw1","error","t4"),H("e11","t2","next","h1"),H("e12","t3","next","h1"),H("e13","t4","next","h1"),H("e14","t5","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var OX={id:"faq-ia-escalacao",category:"ai",requiredModules:["ai"],tags:["faq","ia","escalacao","ai","agente"],editorState:{nodes:[M("s1","start","Início","inicio",{channelType:"both"}),M("t1","tell","Boas-vindas","boas_vindas",I("Olá! Sou o assistente virtual. Posso tirar dúvidas sobre nossos serviços.")),M("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}),M("m1","menu","Resolveu?","resolveu",i("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:")),M("t2","tell","Agradecimento","agradecimento",I("Ótimo! Se precisar de algo mais, é só entrar em contato.")),M("t3","tell","Transferindo","transferindo",I("Aguarde, vou transferir para um atendente.")),M("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["1000"],timeout:45}),M("t4","tell","Transferência Falhou","transferencia_falhou",I("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),M("h1","hangup","Desligamento","desligamento",{})],edges:[H("e1v","s1","voice","t1"),H("e1c","s1","chat","t1"),H("e2","t1","next","ai1"),H("e3","ai1","completed","m1"),H("e4","ai1","error","t3"),H("e5","m1","option:resolvido","t2"),H("e6","m1","option:atendente","t3"),H("e7","m1","noMatch","t3"),H("e8","m1","error","t3"),H("e9","t2","next","h1"),H("e10","t3","next","x1"),...l("ex1","x1","h1","t4"),H("e11","t4","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var RX={id:"faq-informacoes",category:"core",requiredModules:[],tags:["faq","informacoes","autoatendimento","info"],editorState:{nodes:[M("s1","start","Início","inicio",{channelType:"both"}),M("t1","tell","Boas-vindas","boas_vindas",I("Olá, sou o assistente virtual. Posso ajudar com suporte, financeiro, vendas ou horários de atendimento.")),M("m1","menu","Menu FAQ","menu_faq",i("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:")),M("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.")),M("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.")),M("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.")),M("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.")),M("t6","tell","Opção Inválida","opcao_invalida",I("Não entendi sua escolha. Encerrando o atendimento. Até logo.")),M("h1","hangup","Fim","fim",{})],edges:[H("e1v","s1","voice","t1"),H("e1c","s1","chat","t1"),H("e2","t1","next","m1"),H("e3","m1","option:suporte","t2"),H("e4","m1","option:financeiro","t3"),H("e5","m1","option:vendas","t4"),H("e6","m1","option:horarios","t5"),H("e7","t2","next","m1"),H("e8","t3","next","m1"),H("e9","t4","next","m1"),H("e10","t5","next","m1"),H("e11","m1","noMatch","t6"),H("e12","m1","error","t6"),H("e13","t6","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var TX={id:"horario-comercial",category:"core",requiredModules:[],tags:["horario","schedule","tempo","comercial","expediente"],editorState:{nodes:[M("s1","start","Início","inicio",{channelType:"both"}),M("tr1","timeRouting","Horário Atendimento","horario_atendimento",{}),M("t1","tell","Boas-vindas","boas_vindas",I("Bem-vindo. Como posso ajudar?")),M("m1","menu","Menu Principal","menu_principal",i("Para suporte, tecle 1. Para vendas, tecle 2.",[{id:"suporte",label:"Suporte",digit:"1"},{id:"vendas",label:"Vendas",digit:"2"}],{},"Escolha uma opção:")),M("t2","tell","Transferindo Suporte","transferindo_suporte",I("Transferindo para o suporte.")),M("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),M("t3","tell","Transferindo Vendas","transferindo_vendas",I("Transferindo para vendas.")),M("x2","transfer","Vendas","vendas",{method:"bridge",destinations:["1002"],timeout:30}),M("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.")),M("t5","tell","Opção Não Reconhecida","opcao_nao_reconhecida",I("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),M("t6","tell","Transferência Falhou","transferencia_falhou",I("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),M("h1","hangup","Desligamento","desligamento",{})],edges:[H("e1v","s1","voice","tr1"),H("e1c","s1","chat","tr1"),H("e2","tr1","onHours","t1"),H("e3","tr1","offHours","t4"),H("e4","tr1","holiday","t4"),H("e5","t1","next","m1"),H("e6","m1","option:suporte","t2"),H("e7","m1","option:vendas","t3"),H("e8","t2","next","x1"),H("e9","t3","next","x2"),H("e10","m1","noMatch","t5"),H("e11","m1","error","t5"),H("e12","t5","next","x1"),...l("ex1","x1","h1","t6"),...l("ex2","x2","h1","t6"),H("e13","t4","next","h1"),H("e14","t6","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var SX={id:"isp-suporte-tecnico",category:"industry",requiredModules:[],tags:["isp","provedor","internet","suporte","tecnico","telecom"],editorState:{nodes:[M("s1","start","Início","inicio",{channelType:"both"}),M("t1","tell","Boas-vindas","boas_vindas",I("Bem-vindo ao suporte técnico.")),M("m1","menu","Tipo de Serviço","tipo_servico",i("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:")),M("c1","capture","Contrato Internet","contrato_internet",B$("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:"})),M("c2","capture","Contrato Telefonia","contrato_telefonia",B$("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:"})),M("http1","httpRequest","Status Internet","status_internet",{method:"GET",url:"https://api.example.com/contracts/{{contrato_internet.text}}/status?service=internet",headers:{},body:"",timeout:10}),M("http2","httpRequest","Status Telefonia","status_telefonia",{method:"GET",url:"https://api.example.com/contracts/{{contrato_telefonia.text}}/status?service=telefonia",headers:{},body:"",timeout:10}),M("t2","tell","Status Internet","status_internet_info",I("Sobre sua conexão de internet: {{status_internet.response}}")),M("t3","tell","Status Telefonia","status_telefonia_info",I("Sobre seu serviço de telefonia: {{status_telefonia.response}}")),M("sw1","switchCase","Falha Internet","falha_internet",{expression:"{{status_internet.status_code}}",cases:[{pattern:"^404$"}]}),M("sw2","switchCase","Falha Telefonia","falha_telefonia",{expression:"{{status_telefonia.status_code}}",cases:[{pattern:"^404$"}]}),M("t4","tell","Contrato Não Encontrado","contrato_nao_encontrado",I("Não encontrei esse contrato. Vou transferir para um atendente.")),M("t5","tell","Erro de Consulta","erro_consulta",I("Não foi possível consultar o status agora. Vou transferir para um atendente.")),M("t6","tell","Sem Contrato","sem_contrato",I("Não consegui capturar o número do contrato. Vou transferir para um atendente.")),M("t7","tell","Opção Não Reconhecida","opcao_nao_reconhecida",I("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),M("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["3001"],timeout:60}),M("t8","tell","Transferência Falhou","transferencia_falhou",I("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),M("h1","hangup","Desligamento","desligamento",{})],edges:[H("e1v","s1","voice","t1"),H("e1c","s1","chat","t1"),H("e2","t1","next","m1"),H("e3","m1","option:internet","c1"),H("e4","m1","option:telefonia","c2"),H("e5","m1","noMatch","t7"),H("e5e","m1","error","t7"),H("e6","c1","collected","http1"),H("e7","c1","noInput","t6"),H("e7e","c1","error","t6"),H("e8","http1","next","t2"),H("e9","http1","error","sw1"),H("e10","sw1","match:^404$","t4"),H("e11","sw1","fallback","t5"),H("e11e","sw1","error","t5"),H("e12","t2","next","h1"),H("e13","c2","collected","http2"),H("e14","c2","noInput","t6"),H("e14e","c2","error","t6"),H("e15","http2","next","t3"),H("e16","http2","error","sw2"),H("e17","sw2","match:^404$","t4"),H("e18","sw2","fallback","t5"),H("e18e","sw2","error","t5"),H("e19","t3","next","h1"),H("e20","t4","next","x1"),H("e21","t5","next","x1"),H("e22","t6","next","x1"),H("e23","t7","next","x1"),...l("ex1","x1","h1","t8"),H("e24","t8","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var CX={id:"mensagem-simples",category:"core",requiredModules:[],tags:["mensagem","simples","aviso","anuncio","basico"],editorState:{nodes:[M("s1","start","Início","inicio",{channelType:"both"}),M("t1","tell","Mensagem","mensagem",I("Obrigado por ligar. No momento não estamos disponíveis. Por favor, tente novamente mais tarde.")),M("h1","hangup","Desligamento","desligamento",{})],edges:[H("e1v","s1","voice","t1"),H("e1c","s1","chat","t1"),H("e2","t1","next","h1")],viewport:{x:0,y:0,zoom:1}}};var gX={id:"menu-multinivel",category:"advanced",requiredModules:[],tags:["menu","multinivel","departamento","hierarquia","complexo"],editorState:{nodes:[M("s1","start","Início","inicio",{channelType:"both"}),M("t1","tell","Boas-vindas","boas_vindas",I("Bem-vindo. Escolha o setor desejado.")),M("m1","menu","Menu Principal","menu_principal",i("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:")),M("m2","menu","Atendimento","atendimento",i("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:")),M("m3","menu","Comercial","comercial",i("Para vendas, tecle 1. Para parcerias, tecle 2.",[{id:"vendas",label:"Vendas",digit:"1"},{id:"parcerias",label:"Parcerias",digit:"2"}],{},"Escolha uma opção:")),M("m4","menu","Administrativo","administrativo",i("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:")),M("t2","tell","Transferindo Suporte","transferindo_suporte",I("Transferindo para suporte técnico.")),M("t3","tell","Transferindo Financeiro","transferindo_financeiro",I("Transferindo para financeiro.")),M("t4","tell","Transferindo Vendas","transferindo_vendas",I("Transferindo para vendas.")),M("t5","tell","Transferindo Parcerias","transferindo_parcerias",I("Transferindo para parcerias.")),M("t6","tell","Transferindo RH","transferindo_rh",I("Transferindo para RH.")),M("t7","tell","Transferindo Jurídico","transferindo_juridico",I("Transferindo para jurídico.")),M("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),M("x2","transfer","Financeiro","financeiro",{method:"bridge",destinations:["1002"],timeout:45}),M("x3","transfer","Vendas","vendas",{method:"bridge",destinations:["2001"],timeout:30}),M("x4","transfer","Parcerias","parcerias",{method:"bridge",destinations:["2002"],timeout:30}),M("x5","transfer","RH","rh",{method:"bridge",destinations:["3001"],timeout:30}),M("x6","transfer","Jurídico","juridico",{method:"bridge",destinations:["3002"],timeout:30}),M("t8","tell","Opção Não Reconhecida","opcao_nao_reconhecida",I("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),M("t9","tell","Transferência Falhou","transferencia_falhou",I("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),M("h1","hangup","Desligamento","desligamento",{})],edges:[H("e1v","s1","voice","t1"),H("e1c","s1","chat","t1"),H("e2","t1","next","m1"),H("e3","m1","option:atendimento","m2"),H("e4","m1","option:comercial","m3"),H("e5","m1","option:administrativo","m4"),H("e6","m1","noMatch","t8"),H("e6e","m1","error","t8"),H("e7","m2","option:suporte","t2"),H("e8","m2","option:financeiro","t3"),H("e9","m2","noMatch","t8"),H("e9e","m2","error","t8"),H("e10","m3","option:vendas","t4"),H("e11","m3","option:parcerias","t5"),H("e12","m3","noMatch","t8"),H("e12e","m3","error","t8"),H("e13","m4","option:rh","t6"),H("e14","m4","option:juridico","t7"),H("e15","m4","noMatch","t8"),H("e15e","m4","error","t8"),H("e16","t2","next","x1"),H("e17","t3","next","x2"),H("e18","t4","next","x3"),H("e19","t5","next","x4"),H("e20","t6","next","x5"),H("e21","t7","next","x6"),H("e28","t8","next","x1"),...l("ex1","x1","h1","t9"),...l("ex2","x2","h1","t9"),...l("ex3","x3","h1","t9"),...l("ex4","x4","h1","t9"),...l("ex5","x5","h1","t9"),...l("ex6","x6","h1","t9"),H("e29","t9","next","h1")],viewport:{x:0,y:0,zoom:0.7}}};var EX={id:"notificacao-atendimento",category:"core",requiredModules:[],tags:["notificacao","aviso","atendimento","callback"],editorState:{nodes:[M("s1","start","Início","inicio",{channelType:"both"}),M("t1","tell","Notificação","notificacao",I("Olá, temos uma informação importante sobre sua conta.")),M("m1","menu","Precisa de Ajuda?","precisa_ajuda",i("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?")),M("t2","tell","Transferindo","transferindo",I("Aguarde, vou transferir para um atendente.")),M("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["1000"],timeout:45}),M("t3","tell","Agradecimento","agradecimento",I("Obrigado pelo seu tempo. Tenha um bom dia!")),M("t4","tell","Transferência Falhou","transferencia_falhou",I("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),M("h1","hangup","Desligamento","desligamento",{})],edges:[H("e1v","s1","voice","t1"),H("e1c","s1","chat","t1"),H("e2","t1","next","m1"),H("e3","m1","option:sim","t2"),H("e4","m1","option:nao","t3"),H("e5","m1","noMatch","t3"),H("e6","m1","error","t3"),H("e7","t2","next","x1"),...l("ex1","x1","h1","t4"),H("e8","t3","next","h1"),H("e9","t4","next","h1")],viewport:{x:0,y:0,zoom:0.9}}};var yX={id:"pesquisa-nps",category:"advanced",requiredModules:["ai"],tags:["nps","pesquisa","promotor","detrator","feedback","avaliacao"],editorState:{nodes:[M("s1","start","Início","inicio",{channelType:"both"}),M("t1","tell","Intro NPS","intro_nps",I("Gostaríamos de saber sua opinião sobre nosso atendimento.")),M("c1","capture","Nota NPS","nota_nps",B$("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:"})),M("sw1","switchCase","Classificar NPS","classificar_nps",{expression:"{{nota_nps.text}}",cases:[{pattern:"^9$"},{pattern:"^10$"},{pattern:"^7$"},{pattern:"^8$"}]}),M("t2","tell","Promotor","promotor",I("Que ótimo! Ficamos muito felizes com sua avaliação.")),M("t3","tell","Neutro","neutro",I("Obrigado pela avaliação. Vamos trabalhar para melhorar.")),M("t4","tell","Detrator","detrator",I("Lamentamos que sua experiência não tenha sido satisfatória.")),M("c2","capture","Feedback","feedback",B$("Pode nos dizer o que podemos melhorar? Fale após o sinal.",{voiceMethod:"speech",text:"Pode nos dizer o que podemos melhorar?"})),M("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}),M("t5","tell","Agradecimento","agradecimento",I("Obrigado pelo seu feedback. Ele é muito importante para nós.")),M("h1","hangup","Desligamento","desligamento",{})],edges:[H("e1v","s1","voice","t1"),H("e1c","s1","chat","t1"),H("e2","t1","next","c1"),H("e3","c1","collected","sw1"),H("e4","c1","noInput","t5"),H("e4e","c1","error","t5"),H("e5","sw1","match:^9$","t2"),H("e6","sw1","match:^10$","t2"),H("e7","sw1","match:^7$","t3"),H("e8","sw1","match:^8$","t3"),H("e9","sw1","fallback","t4"),H("e9e","sw1","error","t4"),H("e10","t2","next","c2"),H("e11","t3","next","c2"),H("e12","t4","next","c2"),H("e13","c2","collected","http1"),H("e14","c2","noInput","http1"),H("e14e","c2","error","http1"),H("e15","http1","next","t5"),H("e16","http1","error","t5"),H("e17","t5","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var uX={id:"pesquisa-satisfacao",category:"core",requiredModules:[],tags:["pesquisa","satisfacao","csat","avaliacao","nota"],editorState:{nodes:[M("s1","start","Início","inicio",{channelType:"both"}),M("t1","tell","Intro Pesquisa","intro_pesquisa",I("Gostaríamos de avaliar o atendimento que você recebeu.")),M("m1","menu","Nota de Satisfação","nota_satisfacao",i("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?")),M("t2","tell","Agradecimento","agradecimento",I("Você avaliou nosso atendimento como: {{nota_satisfacao.selectedLabel}}. Obrigado, sua opinião nos ajuda a melhorar.")),M("t3","tell","Sem Resposta","sem_resposta",I("Não conseguimos registrar sua avaliação. Agradecemos o contato.")),M("h1","hangup","Desligamento","desligamento",{}),M("h2","hangup","Desligamento Timeout","desligamento_timeout",{})],edges:[H("e1v","s1","voice","t1"),H("e1c","s1","chat","t1"),H("e2","t1","next","m1"),H("e3","m1","option:nota_1","t2"),H("e4","m1","option:nota_2","t2"),H("e5","m1","option:nota_3","t2"),H("e6","m1","option:nota_4","t2"),H("e7","m1","option:nota_5","t2"),H("e8","t2","next","h1"),H("e9","m1","noMatch","t3"),H("e10","m1","error","t3"),H("e11","t3","next","h2")],viewport:{x:0,y:0,zoom:0.9}}};var fX={id:"roteamento-canal",category:"omnichannel",requiredModules:[],tags:["canal","omnichannel","voz","chat","roteamento"],editorState:{nodes:[M("s1","start","Início","inicio",{channelType:"both"}),M("cr1","channelRouter","Roteador de Canal","roteador_canal",{}),M("t1","tell","Boas-vindas Voz","boas_vindas_voz",I("Bem-vindo ao nosso atendimento por telefone.")),M("m1","menu","Menu Voz","menu_voz",i("Para suporte, tecle 1. Para vendas, tecle 2.",[{id:"suporte",label:"Suporte",digit:"1"},{id:"vendas",label:"Vendas",digit:"2"}])),M("t2","tell","Boas-vindas Chat","boas_vindas_chat",I("Olá! Bem-vindo ao nosso atendimento por chat.")),M("m2","menu","Menu Chat","menu_chat",i("Para suporte, tecle 1. Para vendas, tecle 2.",[{id:"suporte",label:"Suporte",digit:"1"},{id:"vendas",label:"Vendas",digit:"2"}],{},"Escolha uma opção:")),M("t3","tell","Transferindo Suporte","transferindo_suporte",I("Transferindo para o suporte.")),M("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),M("t4","tell","Transferindo Vendas","transferindo_vendas",I("Transferindo para vendas.")),M("x2","transfer","Vendas","vendas",{method:"bridge",destinations:["1002"],timeout:30}),M("t5","tell","Opção Não Reconhecida","opcao_nao_reconhecida",I("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),M("t6","tell","Transferência Falhou","transferencia_falhou",I("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),M("h1","hangup","Desligamento","desligamento",{})],edges:[H("e1v","s1","voice","cr1"),H("e1c","s1","chat","cr1"),H("e2","cr1","voice","t1"),H("e3","cr1","chat","t2"),H("e4","t1","next","m1"),H("e5","t2","next","m2"),H("e6","m1","option:suporte","t3"),H("e7","m1","option:vendas","t4"),H("e8","m2","option:suporte","t3"),H("e9","m2","option:vendas","t4"),H("e10","t3","next","x1"),H("e11","t4","next","x2"),...l("ex1","x1","h1","t6"),...l("ex2","x2","h1","t6"),H("e12","m1","noMatch","t5"),H("e13","m1","error","t5"),H("e14","m2","noMatch","t5"),H("e15","m2","error","t5"),H("e16","t5","next","x1"),H("e17","t6","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var mX={id:"status-pedido",category:"capture",requiredModules:[],tags:["pedido","status","rastreio","ecommerce","api"],editorState:{nodes:[M("s1","start","Início","inicio",{channelType:"both"}),M("t1","tell","Boas-vindas","boas_vindas",I("Olá. Vou consultar o status do seu pedido.")),M("c1","capture","Número do Pedido","numero_pedido",B$("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:"})),M("http1","httpRequest","Consultar Pedido","consultar_pedido",{method:"GET",url:"https://api.example.com/orders/{{numero_pedido.text}}",headers:{},body:"",timeout:10}),M("sw1","switchCase","Tipo de Falha","tipo_falha",{expression:"{{consultar_pedido.status_code}}",cases:[{pattern:"^404$"}]}),M("t2","tell","Status do Pedido","status_do_pedido",I("O status do seu pedido é: {{consultar_pedido.response}}")),M("t3","tell","Pedido Não Encontrado","pedido_nao_encontrado",I("Não encontrei esse número de pedido. Verifique e tente novamente.")),M("t4","tell","Erro de Consulta","erro_consulta",I("Houve um erro ao consultar o pedido. Tente novamente mais tarde.")),M("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.")),M("h1","hangup","Desligamento","desligamento",{})],edges:[H("e1v","s1","voice","t1"),H("e1c","s1","chat","t1"),H("e2","t1","next","c1"),H("e3","c1","collected","http1"),H("e4","c1","noInput","t5"),H("e5","c1","error","t5"),H("e6","http1","next","t2"),H("e7","http1","error","sw1"),H("e8","sw1","match:^404$","t3"),H("e9","sw1","fallback","t4"),H("e10","sw1","error","t4"),H("e11","t2","next","h1"),H("e12","t3","next","h1"),H("e13","t4","next","h1"),H("e14","t5","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var hX={id:"triagem-inteligente",category:"ai",requiredModules:["ai"],tags:["triagem","intencao","intent","ia","roteamento","ai"],editorState:{nodes:[M("s1","start","Início","inicio",{channelType:"both"}),M("t1","tell","Boas-vindas","boas_vindas",I("Olá! Vou te direcionar para o setor correto.")),M("c1","capture","Motivo do Contato","motivo_contato",B$("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:J4("Um momento enquanto identifico o setor correto.").audio,text:"Descreva em poucas palavras com o que você precisa de ajuda:"})),M("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."}),M("t2","tell","Direcionando Suporte","direcionando_suporte",I("Entendi, vou transferir para o suporte técnico.")),M("t3","tell","Direcionando Financeiro","direcionando_financeiro",I("Entendi, vou transferir para o financeiro.")),M("t4","tell","Direcionando Vendas","direcionando_vendas",I("Entendi, vou transferir para vendas.")),M("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),M("x2","transfer","Financeiro","financeiro",{method:"bridge",destinations:["1002"],timeout:45}),M("x3","transfer","Vendas","vendas",{method:"bridge",destinations:["1003"],timeout:30}),M("t5","tell","Não Identificado","nao_identificado",I("Não consegui identificar sua necessidade. Vou transferir para um atendente.")),M("x4","transfer","Atendente Geral","atendente_geral",{method:"bridge",destinations:["1000"],timeout:45}),M("t6","tell","Transferência Falhou","transferencia_falhou",I("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),M("h1","hangup","Desligamento","desligamento",{})],edges:[H("e1v","s1","voice","t1"),H("e1c","s1","chat","t1"),H("e2","t1","next","c1"),H("e3","c1","collected","ra1"),H("e4","c1","noInput","t5"),H("e5","c1","error","t5"),H("e6","ra1","intent:suporte","t2"),H("e7","ra1","intent:financeiro","t3"),H("e8","ra1","intent:vendas","t4"),H("e9","ra1","notApplicable","t5"),H("e10","ra1","error","t5"),H("e11","t2","next","x1"),H("e12","t3","next","x2"),H("e13","t4","next","x3"),H("e14","t5","next","x4"),...l("ex1","x1","h1","t6"),...l("ex2","x2","h1","t6"),...l("ex3","x3","h1","t6"),...l("ex4","x4","h1","t6"),H("e15","t6","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var cX={id:"ura-reversa-spot",category:"core",requiredModules:[],tags:["spot","ura reversa","campanha","outbound","discagem","tecla"],editorState:{nodes:[M("s1","start","Início","inicio",{channelType:"both"}),M("m1","menu","Spot","spot",i("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.")),M("t1","tell","Agradecimento","agradecimento",I("Obrigado! Em instantes um atendente entrará em contato.")),M("t2","tell","Encerramento","encerramento",I("Obrigado pela atenção. Até logo!")),M("h1","hangup","Desligamento","desligamento",{})],edges:[H("e1v","s1","voice","m1"),H("e1c","s1","chat","m1"),H("e2","m1","option:interesse","t1"),H("e3","m1","noMatch","t2"),H("e4","m1","error","t2"),H("e5","t1","next","h1"),H("e6","t2","next","h1")],viewport:{x:0,y:0,zoom:0.9}}};var lX={"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 Y_($){let U=lX[$.id];if(U==null)return $;return{...$,editorState:{...$.editorState,nodes:$.editorState.nodes.map((Q)=>{let G=U[Q.id];return G==null?Q:{...Q,position:{...G}}})}}}var rX=[FX,TX,uX,RX,CX,cX,AX,bX,mX,kX,hX,OX,xX,fX,EX,zX,SX,LX,gX,yX].map(($)=>Y_($));var nX=[{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"}]}],iX="vars",oX="counters",rG=new Set([...nX.map(($)=>$.nodeVarName),KU,iX,oX].map(($)=>$.split(".")[0]));function nG($){return rG.has($)}var M_={tell:new Set(["audio"]),menu:new Set(["audio","voiceTimeout"]),capture:new Set(["audio","voiceMethod","minDigits","maxDigits","terminators","voiceTimeout","listen","processing_audio","retryAudio"])},Z_={tell:new Set(["content"]),menu:new Set(["text","invalidMessage"]),capture:new Set(["text","validation","invalidMessage"])};function iG($,U,Q,G){let K=$.filter((X)=>X.type==="start"),J=N_(U),W=K[0]?.id,q=C_($,U),j=[...I_(K),...__($,J,W),...w_($),...k_($),...x_($),...F_($),...z_($),...b_($),...A_($,U,Q),...O_($,J,W),...R_($),...T_($),...S_($,Q,G?.disabledModules),...G?.entities!=null?CG($,G.entities):[],...G?.externalEntities!=null?gG($,G.externalEntities):[],...g_($,Q,q),...G?.mediaProfile!=null?V_($,U,G.mediaProfile):[]];if(q!=null)return E_(j,$,q);return j}function V_($,U,Q){let G=$.find((q)=>q.type==="start");if(G==null)return[];let K=new Map;for(let q of U){let j=K.get(q.source)??new Map;j.set(q.sourceHandle,q.target),K.set(q.source,j)}let J=WQ(G.id,Q.profile,$,K,Q.recordingEnabled),W=[];for(let q of $){let j=J[q.id];if(j==null||!v_(q.type))continue;let B=D_(q.type,j).filter((Z)=>Z.value.kind==="indeterminate");if(B.length>0)W.push({nodeId:q.id,severity:"warning",messageKey:"editor:validation.mediaStateIndeterminate",params:{label:q.label,fields:B.map((Z)=>Z.name).join(", "),paths:B.map((Z)=>P_(Z.value)).join("; ")}});if(q.type==="transcription"&&j.transcriptionEnabled.kind==="known"&&j.transcriptionEnabled.value&&j.recordingEnabled.kind==="known"&&!j.recordingEnabled.value)W.push({nodeId:q.id,severity:"warning",messageKey:"editor:validation.transcriptionWithoutRecording",params:{label:q.label}})}return W}function v_($){return $==="recording"||$==="transcription"||$==="analysis"}function D_($,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:"structured_analysis",value:U.structuredAnalysisEnabled},{name:"analysis_ids",value:U.structuredAnalysisIds}]}function P_($){if($.kind==="known")return"";return $.branches.map((U)=>U.viaNodeLabel).join(", ")}function I_($){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 N_($){let U=new Map;for(let Q of $){let G=U.get(Q.source)??[];G.push(Q.target),U.set(Q.source,G)}return U}function __($,U,Q){if(Q===void 0)return[];let G=new Set([Q]),K=[Q];while(K.length>0){let W=K.pop();for(let q of U.get(W)??[])if(!G.has(q))G.add(q),K.push(q)}let J=[];for(let W of $)if(W.type!=="start"&&!G.has(W.id))J.push({nodeId:W.id,severity:"warning",messageKey:"editor:validation.unreachable",params:{label:W.label}});return J}function w_($){let U=[];for(let Q of $){let G=d$[Q.type],K=G.configSchema.safeParse(Q.config),J=K.success?K.data:Q.config,W=K.success?G.configSchema.safeParse(J):K;if(W.success)continue;for(let q of W.error.issues){let j=q.message.startsWith("editor:")?q.message:"editor:validation.invalidField";U.push({nodeId:Q.id,severity:"error",messageKey:j,params:{label:Q.label,field:q.path.join(".")}})}}return U}function oG($){let U=[];for(let Q of $){if(Q.type!=="transfer")continue;let G=d$.transfer.configSchema.safeParse(Q.config);if(!G.success)continue;U.push({node:Q,destinations:G.data.destinations,attachedData:G.data.attachedData})}return U}function k_($){let U=[];for(let{node:Q,destinations:G}of oG($)){if(G.some((K)=>K.trim()!==""))continue;U.push({nodeId:Q.id,severity:"error",messageKey:"editor:validation.noDestinations",params:{label:Q.label}})}return U}function x_($){let U=[];for(let{node:Q,destinations:G,attachedData:K}of oG($)){let J=[...G.map((W,q)=>({field:`destinations.${q}`,template:W})),...K.map((W)=>({field:W.key,template:W.value}))];for(let{field:W,template:q}of J){if(TQ(q).valid)continue;U.push({nodeId:Q.id,severity:"error",messageKey:"editor:validation.invalidTemplateSyntax",params:{label:Q.label,field:W}})}}return U}function F_($){let U=[];for(let{node:Q,destinations:G}of oG($))G.forEach((K,J)=>{if(!/\s/.test(K.trim()))return;U.push({nodeId:Q.id,severity:"error",messageKey:"editor:validation.destinationHasSpace",params:{label:Q.label,field:`destinations.${J}`}})});return U}var L_=new Set(["httpRequest","webhook"]);function z_($){let U=[];for(let Q of $){if(!L_.has(Q.type))continue;let G=typeof Q.config.body==="string"?Q.config.body:"";if(G.trim()==="")continue;let K=G.replace(OQ(),'"__tpl__"');try{JSON.parse(K)}catch{U.push({nodeId:Q.id,severity:"warning",messageKey:"editor:validation.invalidJson",params:{label:Q.label}})}}return U}function b_($){return GU($).misplaced.map((U)=>({nodeId:U.nodeId,severity:"error",messageKey:"editor:validation.secretFieldNotAllowed",params:{label:U.label,field:U.field,secret:U.name}}))}function A_($,U,Q){let G=new Set(U.map((J)=>J.source)),K=[];for(let J of $){let W=Q[J.type];if(G4(W,J.config).length===0)continue;if(G.has(J.id))continue;K.push({nodeId:J.id,severity:"warning",messageKey:"editor:validation.noOutputConnection",params:{label:J.label}})}return K}function O_($,U,Q){if(Q===void 0)return[];let G=0,K=1,J=2,W=new Map;for(let B of $)W.set(B.id,G);let q=new Set;function j(B){W.set(B,K);for(let Z of U.get(B)??[])if(W.get(Z)===K)q.add(Z);else if(W.get(Z)===G)j(Z);W.set(B,J)}j(Q);let X=[];for(let B of q){let Z=$.find((N)=>N.id===B);if(Z===void 0)continue;if(!(typeof Z.config.maxAttempts==="number"&&Z.config.maxAttempts>0))X.push({nodeId:B,severity:"error",messageKey:"editor:validation.infiniteCycle",params:{label:Z.label}})}return X}function R_($){let U=new Map,Q=[];for(let G of $)if(U.get(G.varName)!==void 0)Q.push({nodeId:G.id,severity:"error",messageKey:"editor:validation.duplicateVarName",params:{label:G.label,varName:G.varName}});else U.set(G.varName,G.id);return Q}function T_($){return $.filter((U)=>nG(U.varName)).map((U)=>({nodeId:U.id,severity:"error",messageKey:"editor:validation.reservedVarName",params:{label:U.label,varName:U.varName}}))}function S_($,U,Q){if(Q==null||Q.size===0)return[];let G=[];for(let K of $){let J=U[K.type];if(J.module!=="core"&&Q.has(J.module))G.push({nodeId:K.id,severity:"warning",messageKey:"editor:validation.moduleDisabled",params:{label:K.label,module:J.module}})}return G}function C_($,U){let Q=$.find((q)=>q.type==="start");if(Q==null)return null;let G=Q.config.channelType;if((typeof G==="string"?G:"voice")!=="both")return null;let J=new Map;for(let q of U){let j=J.get(q.source);if(j==null)j=new Map,J.set(q.source,j);j.set(q.sourceHandle,q.target)}let W=new Set;for(let q of $)if(q.type==="channelRouter")W.add(q.id);return RG(Q.id,Q.config,J,$.map((q)=>q.id),W.size>0?W:void 0)}function g_($,U,Q){if(Q==null)return[];let G=[];for(let K of $){if(K.type==="start")continue;let J=U[K.type],W=Q[K.id];if(W==null||W==="unreachable"||W==="converged")continue;if(J.channel==="voice"&&W==="chat-only")G.push({nodeId:K.id,severity:"error",messageKey:"editor:validation.voiceNodeInChatBranch",params:{label:K.label}});if(J.channel==="chat"&&W==="voice-only")G.push({nodeId:K.id,severity:"error",messageKey:"editor:validation.chatNodeInVoiceBranch",params:{label:K.label}})}return G}function E_($,U,Q){let G=new Map(U.map((K)=>[K.id,K.type]));return $.filter((K)=>{let J=K.params?.field;if(J==null||K.nodeId==="")return!0;let W=G.get(K.nodeId);if(W==null)return!0;let q=Q[K.nodeId];if(q==null||q==="converged"||q==="unreachable")return!0;let j=J.split(".")[0];if(q==="chat-only"&&M_[W]?.has(j))return!1;if(q==="voice-only"&&Z_[W]?.has(j))return!1;return!0})}function dG($){return $.every((U)=>U.severity!=="error")}var f_=Y.object({type:Y.literal("message"),message:XG}),m_=Y.object({type:Y.literal("typing")}),h_=Y.object({type:Y.literal("ping")}),c_=Y.object({type:Y.literal("resume"),lastSeq:Y.number().int().min(0)}),l_=Y.object({type:Y.literal("start")}),r_=Y.discriminatedUnion("type",[f_,m_,h_,c_,l_]),dX=Y.object({type:Y.literal("connected"),seq:Y.number().int(),ts:Y.number(),sessionId:Y.string()}),pX=Y.object({type:Y.literal("message"),seq:Y.number().int(),ts:Y.number(),id:Y.string(),message:t4}),tX=Y.object({type:Y.literal("typing"),seq:Y.number().int(),ts:Y.number(),active:Y.boolean()}),aX=Y.object({type:Y.literal("state"),seq:Y.number().int(),ts:Y.number(),status:Y.enum(["active","waiting_input","ended"])}),eX=Y.object({type:Y.literal("trace"),seq:Y.number().int(),ts:Y.number(),currentNodeId:Y.string(),variables:Y.record(Y.string(),Y.string()),status:Y.enum(["active","waiting_input","ended"]),truncated:Y.boolean(),step:qU.optional()}),sX=Y.object({type:Y.literal("error"),seq:Y.number().int(),ts:Y.number(),code:Y.string(),message:Y.string()}),$H=Y.object({type:Y.literal("pong"),seq:Y.number().int(),ts:Y.number()}),n_=Y.discriminatedUnion("type",[dX,pX,tX,aX,eX,sX,$H]),i_=Y.object({type:Y.literal("replay"),seq:Y.number().int(),ts:Y.number(),messages:Y.array(n_)}),o_=Y.discriminatedUnion("type",[dX,pX,tX,aX,eX,sX,$H,i_]);var S$=H1(M1(),1);var d_=new Set(o6);function p_($){return d_.has($)}var YU=($)=>$==="online"?S$.default.green($):S$.default.red($);function t_($){let U;if($.is_expired)U=S$.default.red("expired");else if($.is_in_grace_period)U=S$.default.yellow("grace period");else U=S$.default.green($.status);let Q=$.days_until_expiry!=null?` (${$.days_until_expiry}d remaining)`:"";return` License: ${U}${Q}`}var UH=10,a_="unlimited".padEnd(UH);function jU($,U,Q,G,K){let J=` ${$.padEnd(11)}`;if(Q==null)return`${J}${S$.default.dim(a_)} ${U}${G}`;return`${J}${Z1(U,Q,UH)} ${U}/${Q}${G} (${Math.round(K)}%)`}function e_($){let U=[S$.default.bold(" AI Usage:")],{stt:Q,tts:G,llm:K}=$;if(Q)U.push(jU("STT:",Math.round(Q.current),Q.limit," min",Q.percentage));if(G)U.push(jU("TTS:",G.current,G.limit," chars",G.percentage));if(K)U.push(jU("LLM:",K.current,K.limit," tokens",K.percentage));return U}function KH($,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:G,fields:K}=w($.opts()),J=await _(U().dashboard.health());if(G==="json"){let W=K?g(J,K):J;P(W);return}if(console.log(`Server: ${YU(J.server)}`),console.log(`PostgreSQL: ${YU(J.postgres)}`),console.log(`Redis: ${YU(J.redis)}`),console.log(`FreeSWITCH: ${YU(J.freeswitch.status)}`),J.freeswitch.uptime!=null&&J.freeswitch.uptime!=="")console.log(` Uptime: ${J.freeswitch.uptime}`);if(J.freeswitch.sessions)console.log(` Sessions: ${J.freeswitch.sessions.active}/${J.freeswitch.sessions.limit}`);if(J.freeswitch.cps)console.log(` CPS: ${J.freeswitch.cps.current}/${J.freeswitch.cps.limit}`);if(J.freeswitch.idleCpu!=null)console.log(` Idle CPU: ${J.freeswitch.idleCpu}%`)}),Q.command("channels").description("List active FreeSWITCH channels").action(async()=>{let{format:G,fields:K}=w($.opts()),J=await _(U().dashboard.activeCalls());if(G==="json"){let W=K?J.map((q)=>g(q,K)):J;P(W);return}if(J.length===0){z("No active channels.");return}u(["UUID","Caller","Plan","Node","Duration"],J.map((W)=>({UUID:W.uuid,Caller:W.callerId,Plan:W.planName??"—",Node:W.currentNodeLabel??"—",Duration:W.startedAt?`${Math.round((Date.now()-new Date(W.startedAt).getTime())/1000)}s`:"—"}))),z(`${J.length} active channel(s)`)}),Q.command("registrations").description("List SIP registrations").action(async()=>{let{format:G,fields:K}=w($.opts()),J=await _(U().testCall.registrations());if(G==="json"){let W=K?J.map((q)=>g(q,K)):J;P(W);return}if(J.length===0){z("No SIP registrations.");return}u(["Extension","Agent"],J.map((W)=>({Extension:W.extension,Agent:W.agent??"—"})))}),Q.command("dump <uuid>").description("Dump all channel variables for an active call").action(async(G)=>{let{format:K}=w($.opts()),J=await _(U().dashboard.fsDumpChannel({uuid:G}));if(Object.keys(J).length===0){if(K==="json")P({});else A(`Channel ${G} not found.`);process.exit(O.NOT_FOUND)}if(K==="json"){P(J);return}console.log(S$.default.bold(`Channel Variables — ${G}`)),console.log("");for(let[W,q]of Object.entries(J))console.log(` ${S$.default.cyan(W.padEnd(40))} ${q}`)}),Q.command("sofia").description("Show SIP profile status").action(async()=>{let{format:G}=w($.opts()),K=await _(U().dashboard.fsSofiaStatus());if(G==="json"){P(K);return}if(K.length===0){z("No Sofia profiles configured.");return}console.log(S$.default.bold("Sofia SIP Profiles")),console.log(""),u(["Name","Type","Data","State"],K.map((J)=>({Name:J.name,Type:J.type,Data:J.data,State:J.state})))}),Q.command("show <entity>").description(`Show FreeSWITCH data (${o6.join(", ")})`).action(async(G)=>{if(!p_(G))A(`Unknown entity "${G}". Allowed: ${o6.join(", ")}`),process.exit(O.USAGE_ERROR);let{format:K}=w($.opts()),J=await _(U().dashboard.fsShow({entity:G}));if(K==="json"){P(J);return}console.log(S$.default.bold(`FreeSWITCH: show ${G}`)),console.log(""),console.log(JSON.stringify(J,null,2))}),Q.command("capacity").description("Show system capacity: channels, license, AI usage").action(async()=>{let{format:G,fields:K}=w($.opts()),J=await _(U().dashboard.capacityStatus());if(G==="json"){let q=K?g(J,K):J;P(q);return}console.log(S$.default.bold("System Capacity")),console.log("");let W=J.channels.total;if(console.log(jU("Channels:",W.active,W.limit,"",W.percentage??0)),console.log(t_(J.license)),J.ai_usage){console.log("");for(let q of e_(J.ai_usage))console.log(q)}})}function s_(){return Object.entries(G1).map(([$,U])=>`${$} (${U}_)`).sort(($,U)=>$.localeCompare(U))}function $w($){return Object.hasOwn(G1,$)}function QH($){A($),z(" Valid entities:");for(let U of s_())z(` ${U}`);process.exit(O.USAGE_ERROR)}function GH($,U,Q){return{input:$,entity:U,prefix:G1[U],typeid:q0(U,Q),uuid:Q,sql:`'${Q}'::uuid`}}function Uw($,U){if(U!=null&&!$w(U))QH(`Unknown entity "${U}".`);let Q=K6($);if(Q.kind==="typeid"){if(U!=null&&U!==Q.entity)A(`"${$}" is a ${Q.entity} id, but --as says ${U}.`),z(" Drop --as: a TypeID already carries its entity."),process.exit(O.USAGE_ERROR);return GH($,Q.entity,Q.uuid)}if(Q.kind==="uuid"){if(U==null)QH(`"${$}" is a UUID, which does not carry an entity - pass --as <entity>.`);return GH($,U,Q.uuid)}A(`Cannot read "${$}" as an id: ${Kw[Q.reason]}.`),z(" A TypeID looks like vp_01k3vbk6hxe008000000000001; a UUID like 0198f6b9-9a3d-7000-8000-000000000001."),process.exit(O.USAGE_ERROR)}var Kw={"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 JH($){$.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:G,fields:K}=w($.opts()),J=Uw(U,Q.as);if(Q.sql===!0){console.log(J.sql);return}if(G==="json"){P(g(J,K));return}s([{title:"Id",rows:[{label:"TypeID",value:J.typeid},{label:"UUID",value:J.uuid},{label:"Entity",value:J.entity},{label:"Prefix",value:J.prefix}]}])})}import{existsSync as Qw,lstatSync as Gw,mkdirSync as Jw,readFileSync as Ww,realpathSync as qH,statSync as qw,writeFileSync as pG}from"node:fs";import{homedir as Yw}from"node:os";import{isAbsolute as jw,join as W4,relative as Xw}from"node:path";function WH(){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:`---
95
95
  name: niva-cli
96
96
  description: >
97
97
  NIVA CLI tool for IVR platform management, call debugging, and monitoring.
@@ -433,11 +433,34 @@ niva dashboard hourly
433
433
  niva dashboard top-plans
434
434
  \`\`\`
435
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
+
436
459
  ## Command Groups
437
460
 
438
461
  | Group | Purpose | Key commands |
439
462
  |-------|---------|-------------|
440
- | \`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 |
441
464
  | \`logs\` | Appliance service logs (super-admin) | server, engine, freeswitch, traefik, redis, postgres, client, docs, errors, all |
442
465
  | \`plans\` | Visual IVR plans | list, show, create, edit, configure, validate, test, publish, versions, export |
443
466
  | \`campaigns\` | Dialer campaigns | list, show, stats, summary, create, edit, delete, start, pause, resume, stop, watch, attempts |
@@ -450,6 +473,7 @@ niva dashboard top-plans
450
473
  | \`originate\` | Outbound calls | start |
451
474
  | \`tts\` | TTS resources | voices, models, languages |
452
475
  | \`ai\` | AI module | agents |
476
+ | \`signals\` | Signal library & testing | presets, list, show, test, apply, archive, unarchive |
453
477
  | \`nodes\` | IVR node reference | list, show, schema |
454
478
  | \`config\` | CLI configuration | set, get, show |
455
479
 
@@ -481,19 +505,309 @@ For complete command reference with all options: [references/cli-reference.md](r
481
505
  - \`niva dnc check <phone>\` scripting exit codes: \`0\` = on the DNC list, \`3\` = not listed
482
506
  - \`--from\`/\`--to\`: always use ISO 8601 (\`YYYY-MM-DDT00:00:00Z\`) — works across all commands
483
507
  - Exit codes: \`0\` ok, \`2\` usage error, \`3\` not-found, \`4\` permission denied
484
- `,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 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## 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"}}var YH=["claude","agents","both"],Hw={claude:[".claude"],agents:[".agents"],both:[".agents",".claude"]},Bw=new Set(YH);function Mw($){return Bw.has($)}function Zw(){let $=process.env.HOME;return $!=null&&$!==""?$:Yw()}var Vw="Install the skill for which agent?",vw=[{label:"All (recommended)",value:"both"},{label:"Claude Code",value:"claude"},{label:"Codex / Cursor / Copilot / Gemini CLI / opencode",value:"agents"}];async function Dw($){if($.target!=null){if(!Mw($.target))A(`Error: invalid --target "${$.target}" — expected one of: ${YH.join(", ")}`),process.exit(O.USAGE_ERROR);return $.target}if($.yes)return"both";if($.interactive!==!0)return z("Non-interactive shell — installing for all agents. Pass --target to choose."),"both";return cJ(Vw,vw,$.ask==null?{}:{ask:$.ask})}var jH=/^---\r?\n([\s\S]*?)\r?\n---/,Pw=/^[\w.+-]+$/;function tG($){return Pw.test($)}function Iw($){let U=jH.exec($)?.[1];if(U==null)return;let G=/^[ \t]+cli_version:(.*)$/m.exec(U)?.[1]?.trim().replaceAll(/^"|"$/g,"").trim();return G==null||!tG(G)?void 0:G}function Nw($,U){let Q=$.split(`
485
- `),G=Q.findIndex((K)=>K.startsWith("metadata:"));if(G===-1)return`${$}
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`${$}
486
799
  metadata:
487
- cli_version: "${U}"`;if(Q[G]!=="metadata:")return $;for(let K=G+1;K<Q.length;K++){let J=Q[K];if(!/^\s+\S/.test(J))break;if(/^\s+cli_version:/.test(J))return Q[K]=` cli_version: "${U}"`,Q.join(`
488
- `)}return Q.splice(G+1,0,` cli_version: "${U}"`),Q.join(`
489
- `)}function _w($,U){if(!tG(U))throw Error(`Refusing to stamp a malformed CLI version: ${JSON.stringify(U)}`);let Q=jH.exec($),G=Q?.[1];if(Q==null||G==null)return $;return`---
490
- ${Nw(G,U)}
491
- ---${$.slice(Q.index+Q[0].length)}`}var ww=["skills","niva-cli","references"];function kw($,U){let Q=Xw(U,$);return Q===""||!Q.startsWith("..")&&!jw(Q)}function xw($,U){let Q;try{Q=qH($)}catch{return`${$} does not exist or cannot be resolved.`}let G=$;for(let K of[U,...ww]){G=W4(G,K);let J=Gw(G,{throwIfNoEntry:!1});if(J==null)return;if(J.isSymbolicLink()){let W;try{W=qH(G)}catch{return`${G} is a broken symlink — remove it and retry.`}if(!kw(W,Q))return`${G} is a symlink pointing outside ${Q} (${W}) — refusing to write through it.`}if(!qw(G).isDirectory())return`${G} already exists and is not a directory — remove it and retry.`}return}function Fw($){try{return Iw(Ww($,"utf-8"))}catch{return}}function Lw($,U,Q){if(!Qw($))return;let G=Fw($);if(G==null)z(`Existing skill found in ${U} (version unknown) — overwriting.`);else if(G===Q)z(`Existing skill found in ${U} — overwriting.`);else z(`Updating skill in ${U} from ${G} to ${Q}.`)}function zw($,U,Q,G){let K=W4($,"references");try{Jw(K,{recursive:!0}),pG(W4($,"SKILL.md"),Q),pG(W4(K,"cli-reference.md"),G.cliReference),pG(W4(K,"node-handles.md"),G.nodeHandles)}catch(J){A(`Error: could not write ${U} — ${J instanceof Error?J.message:String(J)}`),process.exit(O.GENERAL_ERROR)}}function XH($){$.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 Dw({target:U.target,yes:$.opts().yes===!0,interactive:hJ()}),G=s4();if(!tG(G))A(`Error: CLI_VERSION is not a plain version string (${JSON.stringify(G)}) — refusing to write the skill.`),process.exit(O.USAGE_ERROR);let K=U.global===!0,J=K?Zw():process.cwd(),W=K?"~/":"",q=Hw[Q],j=q.map((V)=>xw(J,V)).filter((V)=>V!=null);if(j.length>0){for(let V of j)A(`Error: ${V}`);z("Nothing was installed."),process.exit(O.GENERAL_ERROR)}let X=WH(),B=_w(X.skill,G),Z=[];for(let V of q){let N=W4(J,V,"skills","niva-cli"),T=`${W}${V}/skills/niva-cli/`;Lw(W4(N,"SKILL.md"),T,G),zw(N,T,B,X),Z.push(T)}E(`NIVA CLI skill v${G} installed to:`);for(let V of Z)E(` ${V}`);z("Your coding agent will now use the NIVA CLI for IVR management tasks.")})}var R1=H1(M1(),1);var bw=["server","engine","freeswitch","traefik","redis","postgres","client","docs"],Aw={error:R1.default.red,warn:R1.default.yellow,info:R1.default.green,debug:R1.default.dim};function Ow($){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 HH($){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=(Aw[$.level]??((j)=>j))($.level.toUpperCase().padEnd(5)),J=R1.default.cyan(`[${$.service}]`),W=`${R1.default.dim(Q)} ${J} ${K} ${$.message}`,q=Ow($.meta);if(q!=null)W+=R1.default.red(` — ${q}`);return W}function aG($,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 Rw($,U){return new Promise((Q,G)=>{I1($,{onEvent:(K)=>{if(U==="json")console.log(JSON.stringify(K));else console.log(HH(K))},onError:(K)=>{if(K instanceof DOMException&&K.name==="AbortError"){Q();return}G(K)},onSuccess:()=>Q()})})}async function Tw($,U,Q){let G=new AbortController;process.on("SIGINT",()=>{G.abort()});try{await Rw($.system.watchLogs(U,{signal:G.signal}),Q)}catch(K){g1(K)}}async function eG($,U,Q,G,K){let{format:J,fields:W}=w(Q.opts()),q=i$(K??U.level);if(U.follow===!0){await Tw(G(),{service:$,level:q,grep:U.grep},J);return}let j={service:$,since:U.since,until:U.until,level:q,grep:U.grep,limit:U.limit!=null?Number(U.limit):void 0,cursor:U.cursor},X=await _(G().system.logs(j));if(J==="json"){for(let B of X.entries){let Z=W?g(B,W):B;console.log(JSON.stringify(Z))}if(X.nextCursor!=null)console.log(JSON.stringify({nextCursor:X.nextCursor}));return}if(X.entries.length===0){z("No log entries.");return}for(let B of X.entries)console.log(HH(B));if(X.nextCursor!=null)z(`
492
- Next page: --cursor ${X.nextCursor}`)}function BH($,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(J)=>{if(J.follow===!0)n$("Live call-event streaming is not available here. Use `niva calls follow <uuid>` to stream a call's live transcription.");let W=J.callRecord??J.uuid;if(W==null)n$("Please provide --call-record or --follow.");let{format:q,fields:j}=w($.opts()),X=await _(U().callRecords.getEvents({call_record_id:b("call_records",W)}));if(q==="json"){let B=j?X.map((Z)=>g(Z,j)):X;P(B);return}if(X.length===0){z("No events found.");return}u(["Timestamp","Event","Details"],X.map((B)=>({Timestamp:new Date(B.entered_at).toLocaleString(),Event:B.node_type,Details:B.data!=null?JSON.stringify(B.data):"—"})))});for(let J of bw){let W=Q.command(J).description(`View ${J} service logs from the appliance journal`);aG(W),W.action(async(q)=>eG(J,q,$,U))}let G=Q.command("errors").description("View error-level logs across all services (merged timeline)");aG(G,{fixedLevel:!0}),G.action(async(J)=>eG("all",J,$,U,"error"));let K=Q.command("all").description("View a merged timeline of logs from all services");aG(K),K.action(async(J)=>eG("all",J,$,U))}import{readFile as Cw,writeFile as DH}from"node:fs/promises";import{basename as gw}from"node:path";function MH($){if($==null)return'""';return`"${String($).replaceAll('"','""')}"`}function ZH($,U,Q=","){let G=[$.map((K)=>MH(K)).join(Q)];for(let K of U)G.push(K.map((J)=>MH(J)).join(Q));return G.join(`\r
493
- `)}function VH($){let U=0,Q=0,G=!1;for(let K=0;K<$.length;K+=1){let J=$[K];if(J==='"'){if(G&&$[K+1]==='"'){K+=1;continue}G=!G}else if(!G){if(J===",")U+=1;else if(J===";")Q+=1}}return Q>U?";":","}function Sw($,U){let Q="",G=U;for(;G<$.length;G+=1){let K=$[G];if(K!=='"')Q+=K;else if($[G+1]==='"')Q+='"',G+=1;else return{value:Q,end:G}}return{value:Q,end:G}}function vH($,U){let Q=[],G="",K=!1,J=0;while(J<$.length){let W=$[J];if(W==='"'){let q=Sw($,J+1);G+=q.value,J=q.end,K=!0}else if(W===U)Q.push(K?G:G.trim()),G="",K=!1;else G+=W;J+=1}return Q.push(K?G:G.trim()),Q}var $J=["phone_number","name","status","attempt_count","machine_attempts","machine_type","last_attempt_at"],Ew=new Set($J);function sG($,U){return[...U,$]}function PH($){let U={};for(let Q of $){let G=Q.indexOf("=");if(G<=0)A(`Invalid --field "${Q}" (expected key=value)`),process.exit(O.USAGE_ERROR);U[Q.slice(0,G)]=Q.slice(G+1)}return U}function yw($){return $==="phone"||$==="name"||$==="ignore"||/^custom:.+$/.test($)}function uw($,U){if(U==null)return VH($);if(U!==","&&U!==";")A(`Invalid --separator "${U}" (must be , or ;)`),process.exit(O.USAGE_ERROR);return U}function fw($,U){let Q=YQ($),G={};for(let K of $){let J=Q.roles[K]??"ignore";if(J!=="custom"){G[K]=J;continue}let W=Q.customNames[K];G[K]=W!=null&&W.length>0?`custom:${W}`:"ignore"}for(let K of U){let J=K.indexOf("=");if(J<=0)A(`Invalid --map "${K}" (expected <Column>=<role>)`),process.exit(O.USAGE_ERROR);let W=K.slice(0,J),q=K.slice(J+1);if(!$.includes(W))A(`Unknown column "${W}". Available: ${$.join(", ")}`),process.exit(O.USAGE_ERROR);if(!yw(q))A(`Invalid role "${q}" for column "${W}" (phone|name|ignore|custom:<field>)`),process.exit(O.USAGE_ERROR);G[W]=q}return G}function mw($){if($==null)return"—";if(typeof $==="string")return $;if(typeof $==="number"||typeof $==="boolean")return String($);return JSON.stringify($)}async function hw($,U,Q){let G=new AbortController;process.on("SIGINT",()=>G.abort());let K="",J=0;if(await new Promise((W,q)=>{I1($.dialerImports.progress({import_job_id:b("dialer_import_jobs",U)},{signal:G.signal}),{onEvent:(j)=>{if(K=j.status,J=j.invalid,Q==="json")console.log(JSON.stringify(j));else{let X=j.total_rows!=null?String(j.total_rows):"-";z(`[${j.status}] processed ${j.processed_rows}/${X} · imported ${j.imported} · skipped ${j.skipped} · invalid ${j.invalid}`)}if(j.status==="done"||j.status==="failed")W()},onError:(j)=>{if(j instanceof DOMException&&j.name==="AbortError"){W();return}q(j)},onSuccess:()=>W()})}).catch(X4),K==="failed")return O.GENERAL_ERROR;if(K==="done"&&J>0&&Q!=="json")z(`${J} invalid row(s). Inspect with: niva mailing invalid-rows ${U}`);return O.SUCCESS}function IH($,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(G,K)=>{let{format:J,fields:W}=w($.opts()),q=await _(U().dialerContacts.list({campaign_id:b("dialer_campaigns",G),page:Number(K.page),limit:Number(K.limit),status:i$(K.status),search:K.search}));if(J==="json"){P(W?q.items.map((j)=>g(j,W)):q);return}u(["ID","Phone","Name","Status","Attempts","Machine","Last attempt"],q.items.map((j)=>({ID:j.id,Phone:j.phone_number,Name:j.name??"—",Status:j.status,Attempts:j.attempt_count,Machine:U0(j.machine_type),"Last attempt":j.last_attempt_at!=null?p$(j.last_attempt_at):"—"}))),X$(q)}),Q.command("show <campaign_id> <contact_id>").description("Show a mailing contact with its custom fields").action(async(G,K)=>{let{format:J,fields:W}=w($.opts()),q=await _(U().dialerContacts.get({campaign_id:b("dialer_campaigns",G),contact_id:b("dialer_contacts",K)}));if(J==="json"){P(W?g(q,W):q);return}let j=[{title:"Contact",rows:[{label:"ID",value:q.id},{label:"Phone",value:q.phone_number},{label:"Name",value:q.name??"—"},{label:"Status",value:q.status},{label:"Attempts",value:q.attempt_count},{label:"Last attempt",value:q.last_attempt_at!=null?new Date(q.last_attempt_at).toLocaleString():"—"},{label:"Next attempt",value:q.next_attempt_at!=null?new Date(q.next_attempt_at).toLocaleString():"—"},{label:"Created",value:new Date(q.created_at).toLocaleString()}]}],X=q.custom_fields;if(X!=null&&typeof X==="object"&&!Array.isArray(X)&&Object.keys(X).length>0)j.push({title:"Custom fields",rows:Object.entries(X).map(([B,Z])=>({label:B,value:mw(Z)}))});s(j)}),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)",sG,[]).action(async(G,K,J)=>{let{format:W}=w($.opts()),q=PH(J.field),j=await _(U().dialerContacts.add({campaign_id:b("dialer_campaigns",G),phone_number:K,name:J.name,custom_fields:Object.keys(q).length>0?q:void 0}));if(W==="json"){P(j);return}E(`Contact added: ${j.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)",sG,[]).action(async(G,K,J)=>{let{format:W}=w($.opts()),q=await _(U().dialerContacts.update({campaign_id:b("dialer_campaigns",G),contact_id:b("dialer_contacts",K),...J.phone!=null&&{phone_number:J.phone},...J.name!=null&&{name:J.name},...J.field.length>0&&{custom_fields:PH(J.field)}}));if(W==="json"){P(q);return}E("Contact updated")}),Q.command("remove <campaign_id> <contactIds...>").description("Remove (soft-delete) mailing contacts").action(async(G,K)=>{let{format:J}=w($.opts()),W=await _(U().dialerContacts.remove({campaign_id:b("dialer_campaigns",G),ids:b("dialer_contacts",K)}));if(J==="json"){P(W);return}E(`Removed ${W.removed}, skipped ${W.skipped}`)}),Q.command("cancel <campaign_id> <contactIds...>").description("Cancel pending mailing contacts").action(async(G,K)=>{let{format:J}=w($.opts()),W=await _(U().dialerContacts.bulkCancel({campaign_id:b("dialer_campaigns",G),ids:b("dialer_contacts",K)}));if(J==="json"){P(W);return}E(`Cancelled ${W.cancelled}, skipped ${W.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(G,K,J)=>{let{format:W}=w($.opts()),q=K.length>0;if(q&&J.all===!0)A("Use either <contactIds...> or --all, not both"),process.exit(O.USAGE_ERROR);if(!q&&J.all!==!0)A("Provide contact IDs or --all to requeue"),process.exit(O.USAGE_ERROR);if(q){let X=await _(U().dialerContacts.bulkRequeue({campaign_id:b("dialer_campaigns",G),ids:b("dialer_contacts",K)}));if(W==="json"){P(X);return}E(`Requeued ${X.requeued}, skipped ${X.skipped}`);return}let j=await _(U().dialerContacts.requeueAll({campaign_id:b("dialer_campaigns",G),status:i$(J.status)}));if(W==="json"){P(j);return}E(`Requeued ${j.requeued}`)}),Q.command("import <campaign_id> <file>").description("Import a CSV mailing into a campaign").option("--map <pair>","Column mapping override <Column>=<role> (repeatable)",sG,[]).option("--separator <sep>","CSV separator (, or ;) — sniffed when omitted").option("--watch","Follow import progress until it finishes").action(async(G,K,J)=>{let{format:W}=w($.opts()),q=$.opts().yes===!0,j=await Cw(K),X=j.toString("utf-8"),B=X.search(/\r\n|\n|\r/),Z=B===-1?X:X.slice(0,B);if(Z.trim()==="")A("File is empty or has no header row"),process.exit(O.USAGE_ERROR);let V=uw(Z,J.separator),N=vH(Z,V),T=fw(N,J.map);if(W!=="json")u(["Column","Role"],N.map((k$)=>({Column:k$,Role:T[k$]??"ignore"})));await v1("Import with this mapping?",{yes:q});let f=U(),e=await _(f.dialerImports.create({campaign_id:b("dialer_campaigns",G),column_mapping:T,file:new File([j],gw(K))}));if(W!=="json")E(`Import started: ${e.id} (${e.status})`);else if(J.watch!==!0)P(e);if(J.watch===!0){let k$=await hw(f,e.id,W);if(k$!==O.SUCCESS)process.exit(k$)}}),Q.command("import-status <import_job_id>").description("Show the status of a mailing import job").action(async(G)=>{let{format:K,fields:J}=w($.opts()),W=await _(U().dialerImports.get({import_job_id:b("dialer_import_jobs",G)}));if(K==="json"){P(J?g(W,J):W);return}s([{title:"Import job",rows:[{label:"ID",value:W.id},{label:"Status",value:W.status},{label:"Total rows",value:W.total_rows??"—"},{label:"Processed",value:W.processed_rows},{label:"Imported",value:W.imported},{label:"Skipped",value:W.skipped},{label:"Invalid",value:W.invalid},{label:"Has invalid rows",value:W.has_invalid_rows?"yes":"no"},{label:"Created",value:new Date(W.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(G,K)=>{let J=await _(U().dialerImports.invalidRows({import_job_id:b("dialer_import_jobs",G)}));if(J==null){z("No invalid rows.");return}if(K.out!=null){await DH(K.out,J.csv,"utf-8"),E(`Wrote invalid rows to ${K.out}`);return}process.stdout.write(J.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(G,K)=>{let J=await _(U().dialerContacts.exportCsv({campaign_id:b("dialer_campaigns",G),status:i$(K.status),search:K.search})),W=[],q=new Set;for await(let V of J){W.push(V);for(let N of Object.keys(V))if(!Ew.has(N))q.add(N)}if(W.length===0){z("No contacts to export.");return}let j=[...q].sort((V,N)=>V.localeCompare(N)),X=[...$J,...j],B=W.map((V)=>[...$J.map((N)=>V[N]??""),...j.map((N)=>V[N]??"")]),Z=ZH(X,B);if(K.out!=null){await DH(K.out,Z,"utf-8"),E(`Wrote ${W.length} contacts to ${K.out}`);return}process.stdout.write(Z)})}function NH($){if(!($ in d$))console.error(`Unknown node type: ${$}`),console.error(`Available: ${Object.keys(d$).join(", ")}`),process.exit(2)}function cw($){return $ in Q4}function _H($){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:G,fields:K}=w($.opts()),J=cG();if(Q.module!=null)J=J.filter((W)=>W.module===Q.module);if(Q.category!=null)J=J.filter((W)=>W.category===Q.category);if(Q.channel!=null)J=J.filter((W)=>W.channel===Q.channel);if(G==="json"){P(K?J.map((W)=>g(W,K)):J);return}u(["Type","Name","Description","Module","Channel"],J.map((W)=>({Type:W.type,Name:W.name,Description:W.description,Module:W.module,Channel:W.channel})))}),U.command("show <type>").description("Show detailed info for a node type").action((Q)=>{let{format:G}=w($.opts());NH(Q);let K=d6(Q);if(G==="json"){P(K);return}let J=cw(Q)?Q4[Q]:void 0,W=J!=null?Object.entries(J).map(([q,j])=>({label:q,value:String(j)})):[{label:"(no fields)",value:""}];s([{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:W},{title:"Outputs",rows:K.outputs.map((q)=>({label:q.key,value:q.labelKey}))},{title:"Produced Variables",rows:K.producedVariables.length>0?K.producedVariables.map((q)=>({label:`${q.name} (${q.type})`,value:q.descriptionKey})):[{label:"(none)",value:""}]}])}),U.command("schema <type>").description("Output JSON Schema for a node's config (agent-friendly)").action((Q)=>{NH(Q);let G=d6(Q);P(G.configJsonSchema)})}function wH($,U,Q){let G=$.indexOf("=");if(G===-1)throw Error(`${Q} expects key=value (got: ${$})`);let K=$.slice(0,G),J=$.slice(G+1);if(K==="")throw Error(`${Q} expects key=value (got: ${$})`);return U[K]=J,U}function lw($,U){return wH($,U,"--var")}function rw($,U){return wH($,U,"--metadata")}function nw($){return $==="pre"||$==="post"}function iw($){let U=$.amd===!0||$.machineType===!0;if($.amdMode!==void 0&&!U)A("--amd-mode requires --amd or --machine-type"),process.exit(O.USAGE_ERROR);if($.amdMaxWait!==void 0&&$.amdMode!=="pre")A("--amd-max-wait requires --amd-mode pre"),process.exit(O.USAGE_ERROR);let Q;if($.amdMode!==void 0){if(!nw($.amdMode))A(`Invalid --amd-mode "${$.amdMode}": expected pre or post`),process.exit(O.USAGE_ERROR);Q=$.amdMode}let G=$.amdMaxWait===void 0?void 0:Number($.amdMaxWait);if(G!==void 0&&(!Number.isInteger(G)||G<3||G>10))A(`Invalid --amd-max-wait "${$.amdMaxWait}": expected an integer from 3 to 10`),process.exit(O.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:G??6};if(Q==="post")return{...K,mode:Q};return K}function kH($,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",lw,{}).option("--metadata <key=value>","Opaque call metadata persisted with the CDR; repeatable",rw,{}).action(async(G)=>{let{format:K}=w($.opts()),J=Object.entries(G.var),W=Object.entries(G.metadata),q=iw(G),j={plan_id:b("visual_plans",G.plan),destination:G.destination,timeout:Number(G.timeout),...G.maxDuration!==void 0?{max_call_duration_s:Number(G.maxDuration)}:{},...G.callerId!==void 0?{caller_id:G.callerId}:{},...G.callerIdName!==void 0?{caller_id_name:G.callerIdName}:{},...q!==void 0?{answer_recognition:q}:{},...J.length>0?{variables:G.var}:{},...W.length>0?{metadata:G.metadata}:{}},X=await _(U().calls.originate(j));if(K==="json")P(X);else if(X.status==="failed")C1(`Originate outcome: status=failed call_id=${X.call_id} channel_uuid=${X.channel_uuid} answered_at=${X.answered_at??"none"} hangup_cause=${X.hangup_cause??"unknown"} sip_code=${X.sip_code??"unknown"}`);else E(`Originate outcome: status=answered call_id=${X.call_id} channel_uuid=${X.channel_uuid} answered_at=${X.answered_at??"none"} hangup_cause=${X.hangup_cause??"none"} sip_code=${X.sip_code??"none"}`);if(X.status==="failed")process.exit(O.GENERAL_ERROR)})}import{readFile as LH}from"node:fs/promises";async function UJ($){let U=$==="-"?await E1():await LH($,"utf-8"),Q=AG.safeParse(JSON.parse(U));if(!Q.success){A(`Invalid execution plan in "${$}":`);for(let G of Q.error.issues)A(` ✗ ${G.path.join(".")||"(root)"}: ${G.message}`);process.exit(O.GENERAL_ERROR)}return Q.data}function q4($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function ow($){if(!q4($)||!Array.isArray($.nodes)||!Array.isArray($.edges))return!1;let U=$.viewport;return q4(U)&&typeof U.x==="number"&&typeof U.y==="number"&&typeof U.zoom==="number"}async function dw($){let U=$==="-"?await E1():await LH($,"utf-8"),Q;try{Q=JSON.parse(U)}catch{A(`Invalid JSON in plan export "${$}"`),process.exit(O.GENERAL_ERROR)}let G;if(q4(Q)&&Q.format==="niva-plan-v1")G=Q.state;else if(q4(Q)&&q4(Q.draft)&&Q.draft.editor_state!=null)G=Q.draft.editor_state;else if(q4(Q)&&Q.published_editor_state!=null)G=Q.published_editor_state;else if(q4(Q)&&Array.isArray(Q.nodes)&&Array.isArray(Q.edges))G=Q;else A(`Invalid plan export in "${$}"`),process.exit(O.GENERAL_ERROR);if(!ow(G))A(`Invalid editor state in plan export "${$}"`),process.exit(O.GENERAL_ERROR);return G}function KJ($){let U=$.severity==="error"?"✗":"⚠",Q=$.node_id!=null?` [${$.node_id}]`:"";return` ${U}${Q} ${$.message_key}`}var pw="! 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 xH($){try{let U=GQ($),Q=iG(U.nodes,U.edges,O1);if(!dG(Q)){for(let G of Q)A(KJ({node_id:G.nodeId,severity:G.severity,message_key:G.messageKey}));return!1}return C1(pw),!0}catch(U){return A(U instanceof Error?U.message:String(U)),!1}}async function tw($,U,Q,G){if(await _($.channels.update({channel_id:b("channels",U),visual_plan_id:b("visual_plans",Q),reassign:!0})),G!=="json")E(`Channel ${U} assigned to plan`)}async function aw($,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 ew($,U,Q){let G=b("visual_plans",U),K=await _($.channels.list({page:1,limit:100})),J=K.items.filter((q)=>q.visual_plan_id===G),W=K.items.filter((q)=>q.visual_plan_id==null);if(Q==="json"){P({assigned:J,available:W});return}if(J.length>0)console.log(`
494
- Assigned to this plan:`),u(["ID","Type","Name","Identifier","Active"],J.map((q)=>({ID:q.id,Type:q.channel_type,Name:q.name,Identifier:q.identifier??"—",Active:q.is_active?"yes":"no"})));if(W.length>0)console.log(`
495
- Available (unassigned):`),u(["ID","Type","Name","Identifier"],W.map((q)=>({ID:q.id,Type:q.channel_type,Name:q.name,Identifier:q.identifier??"—"})))}function sw($,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())}}}function zH($,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(G)=>{let{format:K,fields:J}=w($.opts()),W=await _(U().visualPlans.list({page:Number(G.page),limit:Number(G.limit),search:G.search}));if(K==="json"){let q=J?W.items.map((j)=>g(j,J)):W;P(q);return}u(["ID","Name","Status","Created"],W.items.map((q)=>({ID:q.id,Name:q.name,Status:q.published_version_id!=null?"published":"draft",Created:new Date(q.created_at).toLocaleDateString()}))),X$(W)}),Q.command("show <plan_id>").description("Show plan details with settings").action(async(G)=>{let{format:K,fields:J}=w($.opts()),W=await _(U().visualPlans.getById({plan_id:b("visual_plans",G)}));if(K==="json"){let q=J?g(W,J):W;P(q);return}s([{title:"Plan",rows:[{label:"ID",value:W.id},{label:"Name",value:W.name},{label:"Status",value:W.published_version_id!=null?"published":"draft"},{label:"Created",value:new Date(W.created_at).toLocaleString()},{label:"Updated",value:new Date(W.updated_at).toLocaleString()}]},{title:"Settings",rows:[{label:"Recording",value:W.recording_enabled?"enabled":"disabled"},{label:"Transcription",value:W.transcription_enabled?"enabled":"disabled"},{label:"Language",value:W.transcription_language??"—"},{label:"Anonymize",value:W.anonymize_enabled?"enabled":"disabled"},{label:"Speech Analytics",value:W.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(G,K)=>{let{format:J}=w($.opts()),W;if(K.executionPlan!=null){if(W=await UJ(K.executionPlan),!xH(W))process.exit(1)}let q=await _(U().visualPlans.create({name:G,language:K.language,description:K.description,recording_enabled:K.recording??!1,transcription_enabled:K.transcription??!1,execution_plan:W}));if(J==="json"){P(q);return}E(`Plan created: ${q.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(G,K)=>{let{format:J}=w($.opts()),W=await UJ(K.executionPlan);if(!xH(W))process.exit(1);let q=await _(U().visualPlans.saveDraft({plan_id:b("visual_plans",G),execution_plan:W,expected_revision:K.expectedRevision!=null?Number(K.expectedRevision):void 0}));if(J==="json"){P(q);return}E(`Draft updated (revision ${q.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(G,K)=>{let{format:J}=w($.opts()),W=await dw(K),q=await _(U().visualPlans.importDraft({plan_id:b("visual_plans",G),editor_state:W}));if(J==="json"){P(q);return}E(`Draft imported (revision ${q.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("--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(G,K)=>{let{format:J}=w($.opts()),W=U();if(K.assignDid!=null)await tw(W,K.assignDid,G,J);if(K.unassignDid!=null)await aw(W,K.unassignDid,J);if(K.listDids===!0){await ew(W,G,J);return}let q=sw(G,K);if(Object.keys(q).length>1){let j=await _(W.visualPlans.update(q));if(J==="json"){P(j);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((G)=>{let K=["voice","chat","both"];if(!K.includes(G.channel))A(`Invalid channel type: ${G.channel}. Must be one of: ${K.join(", ")}`),process.exit(2);let J=G.channel;P({version:1,startNodeId:"start",nodes:{start:{type:"start",label:"Start",varName:"start",config:{channelType:J}},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:J==="both"?{voice:"greeting",chat:"greeting"}:{next:"greeting"},greeting:{next:"end"}}})}),Q.command("delete <plan_id>").description("Delete a visual plan").action(async(G)=>{let{format:K}=w($.opts());if(await _(U().visualPlans.delete({plan_id:b("visual_plans",G)})),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(G,K)=>{let{format:J}=w($.opts());if(K.file!=null){let q=await UJ(K.file),j=await _(U().visualPlans.validate({execution_plan:q}));if(J==="json"){P(j);return}FH(j),process.exit(j.valid?0:1)}if(G==null)A("Provide a plan ID or --file <path>"),process.exit(2);let W=await _(U().visualPlans.validate({plan_id:b("visual_plans",G)}));if(J==="json"){P(W);return}FH(W),process.exit(W.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(G,K)=>{let{format:J}=w($.opts()),W=await _(U().testCall.start({planId:b("visual_plans",G),extension:K.extension}));if(J==="json"){P(W);return}E(`Test call started: uuid=${W.uuid}`),z(`Test ID: ${W.testId}`),z("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(G,K)=>{let{format:J}=w($.opts()),W=await _(U().visualPlans.publish({plan_id:b("visual_plans",G),notes:K.notes}));if(J==="json"){P(W);return}E(`Plan published (version ${W.version})`)}),Q.command("versions <plan_id>").description("List version history").action(async(G)=>{let{format:K}=w($.opts()),J=await _(U().visualPlans.listVersions({plan_id:b("visual_plans",G)}));if(K==="json"){P(J);return}u(["Version","Status","Published By","Published At","Notes"],J.items.map((W)=>({Version:W.version,Status:W.status,"Published By":W.last_edited_by_name??"—","Published At":W.published_at!=null?new Date(W.published_at).toLocaleString():"—",Notes:W.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(G,K)=>{if(K.executionPlan===!0){let q=(await _(U().visualPlans.listVersions({plan_id:b("visual_plans",G)}))).items.find((j)=>j.status==="published"&&j.execution_plan!=null);if(q!=null)P(q.execution_plan);else A("No published version with execution plan found"),process.exit(1);return}let J=await _(U().visualPlans.getById({plan_id:b("visual_plans",G)}));P(J)})}function FH($){if($.valid){E("✓ Plan is valid");return}let U=$.issues.filter((G)=>G.severity==="error"),Q=$.issues.filter((G)=>G.severity==="warning");if(U.length>0){A(`✗ ${U.length} error(s):`);for(let G of U)A(KJ(G))}if(Q.length>0){z(` ${Q.length} warning(s):`);for(let G of Q)z(KJ(G))}}function bH($,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(G)=>{let{format:K,fields:J}=w($.opts()),W=await _(U().schedules.list({page:Number(G.page),limit:Number(G.limit),search:G.search}));if(K==="json"){let q=J?W.items.map((j)=>g(j,J)):W;P(q);return}u(["ID","Name","Description"],W.items.map((q)=>({ID:q.id,Name:q.name,Description:q.description??"—"}))),X$(W)})}var $k="···";function Uk($){return $===""?"—":`${$k}${$}`}function AH($,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(G)=>{let{format:K,fields:J}=w($.opts()),W=await _(U().secrets.list({page:Number(G.page),limit:Number(G.limit),search:G.search}));if(K==="json"){let q=J?W.items.map((j)=>g(j,J)):W;P(q);return}u(["ID","Name","Description","Value","Published","Draft","Updated"],W.items.map((q)=>({ID:q.id,Name:q.name,Description:q.description??"—",Value:Uk(q.value_suffix),Published:q.usage_count.published,Draft:q.usage_count.draft,Updated:new Date(q.updated_at).toLocaleString()}))),X$(W)})}var c$=H1(M1(),1);function Y4($){if($<1024)return`${$} B`;if($<1048576)return`${($/1024).toFixed(1)} KB`;if($<1073741824)return`${($/1048576).toFixed(1)} MB`;return`${($/1073741824).toFixed(1)} GB`}function Kk($){if($==="critical")return c$.default.red($.toUpperCase());if($==="warning")return c$.default.yellow($.toUpperCase());return c$.default.green($.toUpperCase())}function OH($,U){$.command("storage").description("Storage observability and cache stats").command("usage").description("Show storage usage breakdown").action(async()=>{let{format:G}=w($.opts()),K=await _(U().dashboard.storageUsage({}));if(G==="json"){P(K);return}let J=Math.round(K.disk.usagePercent);console.log(`
496
- ${c$.default.bold("Disk")} ${Kk(K.status)}`),console.log(` Total: ${Y4(K.disk.totalBytes)}`),console.log(` Used: ${Y4(K.disk.usedBytes)} (${J}%)`),console.log(` Available: ${Y4(K.disk.availableBytes)}`),console.log(` ${Z1(J,30)}`),console.log(`
497
- ${c$.default.bold("NIVA Storage")}`),console.log(` Total: ${c$.default.cyan(Y4(K.nivaTotal.sizeBytes))} (${K.nivaTotal.diskPercent.toFixed(1)}% of disk)`),console.log(`
498
- ${c$.default.bold("Categories")}`),console.log(` Recordings: ${c$.default.cyan(Y4(K.categories.recordings.sizeBytes))} (${K.categories.recordings.fileCount} files)`),console.log(` TTS Cache: ${c$.default.cyan(Y4(K.categories.ttsCache.sizeBytes))} (${K.categories.ttsCache.fileCount} files, hit rate: ${(K.categories.ttsCache.hitRate*100).toFixed(0)}%)`),console.log(` Audio: ${c$.default.cyan(Y4(K.categories.audio.sizeBytes))} (${K.categories.audio.fileCount} files)`),console.log(`
499
- ${c$.default.bold("Thresholds")}`),console.log(` Warning: ${K.thresholds.warning}%`),console.log(` Critical: ${K.thresholds.critical}%`),console.log()})}function RH($,U){let Q=$.command("tenants").description("Manage tenants");Q.command("list").description("List tenants").action(()=>n$()),Q.command("create").description("Create a tenant").action(()=>n$())}function TH($,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(G)=>{let{format:K,fields:J}=w($.opts()),W=await _(U().tts.listVoices({language:G.language,model:G.model}));if(K==="json"){let q=J?W.map((j)=>g(j,J)):W;P(q);return}u(["ID","Name","Gender","Languages","Model"],W.map((q)=>({ID:q.id,Name:q.name,Gender:q.gender??"-",Languages:q.languages.join(", "),Model:q.model})))}),Q.command("models").description("List available TTS models").action(async()=>{let{format:G,fields:K}=w($.opts()),J=await _(U().tts.listModels());if(G==="json"){let W=K?J.map((q)=>g(q,K)):J;P(W);return}u(["ID","Name","Provider"],J.map((W)=>({ID:W.id,Name:W.name,Provider:W.provider})))}),Q.command("languages").description("List available TTS languages").action(async()=>{let{format:G}=w($.opts()),K=await _(U().tts.listLanguages());if(G==="json"){P(K);return}u(["Language"],K.map((J)=>({Language:J})))})}function Qk($){return $.fields.map((U)=>`${U.name}${U.required?"":"?"}${U.nullable?"|null":""}`).join(", ")}function SH($,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:G,fields:K}=w($.opts()),J=await _(U().webhooks.events.list());if(G==="json"){P(K?J.map((W)=>g(W,K)):J);return}u(["Event","Module","Fields"],J.map((W)=>({Event:W.event,Module:W.required_module??"core",Fields:Qk(W)})))})}function CH($,U,Q){let G=$.command("ws").description("WebSocket chat — connect to a published plan");G.command("chat <plan_id>").description("Start an interactive WebSocket chat session with a published plan").action(async(K)=>{let J=S1($.opts()),W=Q();z("Creating WebSocket session...");let q=await _(U().ws.createSession({planId:b("visual_plans",K)}));if(J==="json"){P(q);return}E(`Session created: ${q.sessionId}`),await N0(v4(W.url,q.wsUrl))}),G.command("session <plan_id>").description("Create a WebSocket session (returns sessionId + wsUrl)").action(async(K)=>{let J=S1($.opts()),W=await _(U().ws.createSession({planId:b("visual_plans",K)})),q=Q(),j=v4(q.url,W.wsUrl);if(J==="json"){P({...W,ws_url:j});return}E(`Session: ${W.sessionId}`),console.log(` WebSocket URL: ${j}`),console.log(` Connect with: websocat ${j}`)})}function gH($,U,Q,G){aW($),hW($,Q,G),_H($),JH($),CJ($,U),QW($,U),rW($,U),kH($,U),zH($,U),sW($,U),IH($,U),Uq($,U),KH($,U),BH($,U),eW($,U),pW($,U),bH($,U),AH($,U),OH($,U),RH($,U),TH($,U),CH($,U,Q),tW($,U,Q),SH($,U),XH($)}function Gk($){try{let{hostname:U}=new URL($);return U.endsWith(".orb.local")||process.env.NIVA_INSECURE==="true"}catch{return!1}}class EH extends Error{constructor(){super("Your session has expired. Run 'niva login' to authenticate again.")}}function Jk($){let U=$.fetchImpl??fetch,Q=async()=>{try{return await $.refresh()}catch(G){if(G instanceof Z$)throw new EH;throw G}};return async(G)=>{let K=$.getSession();if(v0(K))K=await Q();let J=new Request(G);J.headers.set("authorization",`Bearer ${K.access_token}`);let W=await U(J);if(W.status===401){K=await Q();let q=new Request(G);q.headers.set("authorization",`Bearer ${K.access_token}`),W=await U(q)}return W}}function yH($,U,Q){if(Gk($))process.env.NODE_TLS_REJECT_UNAUTHORIZED="0";if(U.kind!=="oauth"){let J=new r1({url:new URL("/api/rpc",$).href,headers:()=>U.kind==="api-key"?{"X-API-Key":U.apiKey}:{}});return l1(J)}let G=U.session,K=new r1({url:new URL("/api/rpc",$).href,fetch:Jk({getSession:()=>G,refresh:async()=>{return G=await D0(Q,G),Z4(Q,G),G}})});return l1(K)}import{readFileSync as Wk}from"node:fs";var qk=1500,Yk="/cli/compatibilidade",XU=null;function jk(){if(XU!=null)return XU;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 G=JSON.parse(U),K=JSON.parse($);Q=uH(G,K)}else{let G=JSON.parse(Xk()),K=Y$(G)?G.supported_niva:void 0,J=Y$(G)?G.compat_table:void 0;Q=uH(K,J)}if(Q==null)throw Error("Invalid apps/cli/compat.json, fix the compat table");return XU=Q,XU}function uH($,U){if(!Y$($)||!Array.isArray(U))return null;let Q=r($.min);if(Q==null)return null;let G=r($.max)??null,K=[];for(let J of g$(U)){let W=r(J.niva_min),q=r(J.dist_tag);if(W==null||q==null)return null;K.push({niva_min:W,niva_max:r(J.niva_max)??null,dist_tag:q})}return{supported_niva:{min:Q,max:G},compat_table:K}}function Xk(){return Wk(new URL("../../compat.json",import.meta.url),"utf-8")}function QJ($){let Q=($.split("-")[0]?.split("+")[0]??"").split(".");if(Q.length!==3)return null;let G=Q.map((K)=>Number.parseInt(K,10));if(G.some((K)=>!Number.isFinite(K)||K<0))return null;return[G[0],G[1],G[2]]}function HU($,U){let Q=QJ($),G=QJ(U);if(Q===null||G===null)return 0;for(let K=0;K<3;K++)if(Q[K]!==G[K])return Q[K]-G[K];return 0}function Hk($,U){let{min:Q,max:G}=U.supported_niva;if(HU($,Q)<0)return!1;if(G!=null&&HU($,G)>0)return!1;return!0}function Bk($,U){for(let Q of U.compat_table){if(HU($,Q.niva_min)<0)continue;if(Q.niva_max!=null&&HU($,Q.niva_max)>0)continue;return Q.dist_tag}return null}function Mk($,U,Q){let{min:G,max:K}=Q.supported_niva,J=K==null?`>= ${G}`:`>= ${G} <= ${K}`,W=Bk($,Q),q=W==null?`See ${Yk}`:`For the compatible release: npx @sippulse/niva@${W} <command>`;return`warning: this CLI (${s4()}) supports NIVA ${J}; ${U} reports ${$}. Some commands may not exist. ${q}`}async function Zk($,U=fetch){let Q=new AbortController,G=setTimeout(()=>Q.abort(),qk);try{let K=await U(new URL("/api/version",$).href,{signal:Q.signal,headers:{accept:"application/json"}});if(!K.ok)return null;let J=await K.json();if(J===null||typeof J!=="object"||!("niva_version"in J))return null;let W=J.niva_version;if(typeof W!=="string"||QJ(W)===null)return null;return W}catch{return null}finally{clearTimeout(G)}}var Vk=null;async function fH($,U={}){if(!$)return;let Q=U.config??jk(),G=await Zk($,U.fetchImpl);if(G===null)return;if(Vk=G,Hk(G,Q))return;console.error(Mk(G,$,Q))}import{chmodSync as Hr,mkdirSync as Br,readFileSync as vk,writeFileSync as Mr}from"node:fs";import{homedir as Dk}from"node:os";import{join as cH}from"node:path";var Pk=cH(Dk(),".niva"),Ik=cH(Pk,"config.json"),mH={url:"http://localhost:3000",apiKey:""};function hH($,U){let Q=$[U];return typeof Q==="string"?Q:void 0}function GJ(){try{let $=JSON.parse(vk(Ik,"utf-8"));return Y$($)?$:{}}catch{return{}}}function lH(){return GJ()}function rH($){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 Nk($){let U=Y$($)?{...$}: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((G)=>typeof G==="string")}function _k(){let $=GJ().auth;return Y$($)?$:{}}function nH(){let $={};for(let[U,Q]of Object.entries(_k()))if(Nk(Q))$[U]=Q;return $}function iH($){let U=GJ();return{url:$.url??process.env.NIVA_URL??hH(U,"url")??mH.url,apiKey:$.apiKey??process.env.NIVA_API_KEY??hH(U,"apiKey")??mH.apiKey}}var wk="table",kk="";function oH($){wk=$}function dH($){kk=$}var xk=new Set(["json","table","plain"]);function Fk($){return xk.has($)}function Lk(){return process.stdout.isTTY===!0&&process.env.NO_COLOR==null}function pH($){if($.output!=null)return Fk($.output)?$.output:"table";if($.json===!0)return"json";return Lk()?"table":"json"}function tH(){return"0.3.0"}var p6=new wJ("niva").description("NIVA CLI \u2014 manage your IVR platform").version(tH()).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 $=p6.opts(),U=pH({json:$.json===!0,output:typeof $.output==="string"?$.output:void 0});oH(U)}).hook("preAction",async()=>{await fH(VU().url)}),BU;function VU(){if(BU!=null)return BU;let $=p6.opts();return BU=iH({url:typeof $.url==="string"?$.url:void 0,apiKey:typeof $.apiKey==="string"?$.apiKey:void 0}),BU}var MU;function aH(){if(MU!=null)return MU;let $=VU(),U=lH(),Q=p6.opts().apiKey;return MU=rH({flagApiKey:typeof Q==="string"?Q:void 0,envApiKey:process.env.NIVA_API_KEY,fileApiKey:typeof U.apiKey==="string"?U.apiKey:void 0,session:nH()[$.url.replace(/\/+$/,"")]}),MU}var ZU;function zk(){if(ZU!=null)return ZU;let $=VU();dH($.url);let U=aH();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 ZU=yH($.url,U,$.url.replace(/\/+$/,"")),ZU}gH(p6,zk,VU,aH);p6.parseAsync().catch(($)=>{console.error($ instanceof Error?$.message:String($)),process.exit(1)});
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)});