@sippulse/niva 0.5.1 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -8
- package/index.js +80 -80
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -1,64 +1,64 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// @bun
|
|
3
|
-
import{createRequire as RC}from"node:module";var bC=Object.create;var{getPrototypeOf:vC,defineProperty:Wo,getOwnPropertyNames:SC}=Object;var
|
|
4
|
-
`)}displayWidth(e){return
|
|
3
|
+
import{createRequire as RC}from"node:module";var bC=Object.create;var{getPrototypeOf:vC,defineProperty:Wo,getOwnPropertyNames:SC}=Object;var zp=Object.prototype.hasOwnProperty;function xC(e){return this[e]}var EC,wC,on=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var o=t?EC??=new WeakMap:wC??=new WeakMap,i=o.get(e);if(i)return i}n=e!=null?bC(vC(e)):{};let a=t||!e||!e.__esModule||!zp.call(e,"default")?Wo(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let s of SC(e))if(!zp.call(a,s))Wo(a,s,{get:xC.bind(e,s),enumerable:!0})}if(r)o.set(e,a);return a};var En=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var CC=(e)=>e;function AC(e,t){this[e]=CC.bind(null,t)}var Fp=(e,t)=>{for(var n in t)Wo(e,n,{get:t[n],enumerable:!0,configurable:!0,set:AC.bind(t,n)})};var TC=(e,t,n)=>{for(var r in t)Wo(e,r,{get:t[r],set:n[r],enumerable:!0,configurable:!0})},Mr=RC(import.meta.url);var Lr=En(function(IC){class Va extends Error{constructor(e,t,n){super(n);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}}class Up extends Va{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}IC.CommanderError=Va;IC.InvalidArgumentError=Up});var Go=En(function(PC){var{InvalidArgumentError:kC}=Lr();class jp{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;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(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new kC(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(t,n);return t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function DC(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}PC.Argument=jp;PC.humanReadableArgName=DC});var Ka=En(function(zC){var{humanReadableArgName:LC}=Go();class Vp{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter((r)=>!r._hidden),n=e._getHelpCommand();if(n&&!n._hidden)t.push(n);if(this.sortSubcommands)t.sort((r,o)=>r.name().localeCompare(o.name()));return t}compareOptions(e,t){let n=(r)=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter((r)=>!r.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),o=n.long&&e._findOption(n.long);if(!r&&!o)t.push(n);else if(n.long&&!o)t.push(e.createOption(n.long,n.description));else if(n.short&&!r)t.push(e.createOption(n.short,n.description))}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let r=n.options.filter((o)=>!o.hidden);t.push(...r)}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleArguments(e){if(e._argsDescription)e.registeredArguments.forEach((t)=>{t.description=t.description||e._argsDescription[t.name()]||""});if(e.registeredArguments.find((t)=>t.description))return e.registeredArguments;return[]}subcommandTerm(e){let t=e.registeredArguments.map((n)=>LC(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,r)=>Math.max(n,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(r)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,r)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(r)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,r)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(r)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,r)=>Math.max(n,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(r)))),0)}commandUsage(e){let t=e._name;if(e._aliases[0])t=t+"|"+e._aliases[0];let n="";for(let r=e.parent;r;r=r.parent)n=r.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((n)=>JSON.stringify(n)).join(", ")}`);if(e.defaultValue!==void 0){if(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==="boolean")t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}if(e.presetArg!==void 0&&e.optional)t.push(`preset: ${JSON.stringify(e.presetArg)}`);if(e.envVar!==void 0)t.push(`env: ${e.envVar}`);if(t.length>0)return`${e.description} (${t.join(", ")})`;return e.description}argumentDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((n)=>JSON.stringify(n)).join(", ")}`);if(e.defaultValue!==void 0)t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`);if(t.length>0){let n=`(${t.join(", ")})`;if(e.description)return`${e.description} ${n}`;return n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function o(u,m){return t.formatItem(u,n,m,t)}let i=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],a=t.commandDescription(e);if(a.length>0)i=i.concat([t.boxWrap(t.styleCommandDescription(a),r),""]);let s=t.visibleArguments(e).map((u)=>o(t.styleArgumentTerm(t.argumentTerm(u)),t.styleArgumentDescription(t.argumentDescription(u))));if(s.length>0)i=i.concat([t.styleTitle("Arguments:"),...s,""]);let c=t.visibleOptions(e).map((u)=>o(t.styleOptionTerm(t.optionTerm(u)),t.styleOptionDescription(t.optionDescription(u))));if(c.length>0)i=i.concat([t.styleTitle("Options:"),...c,""]);if(t.showGlobalOptions){let u=t.visibleGlobalOptions(e).map((m)=>o(t.styleOptionTerm(t.optionTerm(m)),t.styleOptionDescription(t.optionDescription(m))));if(u.length>0)i=i.concat([t.styleTitle("Global Options:"),...u,""])}let d=t.visibleCommands(e).map((u)=>o(t.styleSubcommandTerm(t.subcommandTerm(u)),t.styleSubcommandDescription(t.subcommandDescription(u))));if(d.length>0)i=i.concat([t.styleTitle("Commands:"),...d,""]);return i.join(`
|
|
4
|
+
`)}displayWidth(e){return Kp(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map((t)=>{if(t==="[options]")return this.styleOptionText(t);if(t==="[command]")return this.styleSubcommandText(t);if(t[0]==="["||t[0]==="<")return this.styleArgumentText(t);return this.styleCommandText(t)}).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map((t)=>{if(t==="[options]")return this.styleOptionText(t);if(t[0]==="["||t[0]==="<")return this.styleArgumentText(t);return this.styleSubcommandText(t)}).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let i=" ".repeat(2);if(!n)return i+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),s=2,d=(this.helpWidth??80)-t-s-2,u;if(d<this.minWidthToWrap||r.preformatted(n))u=n;else u=r.boxWrap(n,d).replace(/\n/g,`
|
|
5
5
|
`+" ".repeat(t+s));return i+a+" ".repeat(s)+u.replace(/\n/g,`
|
|
6
6
|
${i}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,o=[];return n.forEach((i)=>{let a=i.match(r);if(a===null){o.push("");return}let s=[a.shift()],c=this.displayWidth(s[0]);a.forEach((d)=>{let u=this.displayWidth(d);if(c+u<=t){s.push(d),c+=u;return}o.push(s.join(""));let m=d.trimStart();s=[m],c=this.displayWidth(m)}),o.push(s.join(""))}),o.join(`
|
|
7
|
-
`)}}function
|
|
7
|
+
`)}}function Kp(e){let t=/\x1b\[\d*(;\d*)*m/g;return e.replace(t,"")}zC.Help=Vp;zC.stripColor=Kp});var qa=En(function(KC){var{InvalidArgumentError:jC}=Lr();class Bp{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=VC(e);if(this.short=n.shortFlag,this.long=n.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(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;if(typeof e==="string")t={[e]:!0};return this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new jC(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(t,n);return t},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return qp(this.name().replace(/^no-/,""));return qp(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class Hp{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach((t)=>{if(t.negate)this.negativeOptions.set(t.attributeName(),t);else this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{if(this.positiveOptions.has(n))this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,o=r!==void 0?r:!1;return t.negate===(o===e)}}function qp(e){return e.split("-").reduce((t,n)=>t+n[0].toUpperCase()+n.slice(1))}function VC(e){let t,n,r=/^-[^-]$/,o=/^--[^-]/,i=e.split(/[ |,]+/).concat("guard");if(r.test(i[0]))t=i.shift();if(o.test(i[0]))n=i.shift();if(!t&&r.test(i[0]))t=i.shift();if(!t&&o.test(i[0]))t=n,n=i.shift();if(i[0].startsWith("-")){let a=i[0],s=`option creation failed due to '${a}' in option flags '${e}'`;if(/^-[^-][^-]/.test(a))throw Error(`${s}
|
|
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
10
|
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(r.test(a))throw Error(`${s}
|
|
11
11
|
- too many short flags`);if(o.test(a))throw Error(`${s}
|
|
12
12
|
- too many long flags`);throw Error(`${s}
|
|
13
|
-
- unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}KC.Option=
|
|
13
|
+
- unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}KC.Option=Bp;KC.DualOptions=Hp});var Wp=En(function(GC){function HC(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let r=0;r<=e.length;r++)n[r]=[r];for(let r=0;r<=t.length;r++)n[0][r]=r;for(let r=1;r<=t.length;r++)for(let o=1;o<=e.length;o++){let i=1;if(e[o-1]===t[r-1])i=0;else i=1;if(n[o][r]=Math.min(n[o-1][r]+1,n[o][r-1]+1,n[o-1][r-1]+i),o>1&&r>1&&e[o-1]===t[r-2]&&e[o-2]===t[r-1])n[o][r]=Math.min(n[o][r],n[o-2][r-2]+1)}return n[e.length][t.length]}function WC(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let n=e.startsWith("--");if(n)e=e.slice(2),t=t.map((a)=>a.slice(2));let r=[],o=3,i=0.4;if(t.forEach((a)=>{if(a.length<=1)return;let s=HC(e,a),c=Math.max(e.length,a.length);if((c-s)/c>i){if(s<o)o=s,r=[a];else if(s===o)r.push(a)}}),r.sort((a,s)=>a.localeCompare(s)),n)r=r.map((a)=>`--${a}`);if(r.length>1)return`
|
|
14
14
|
(Did you mean one of ${r.join(", ")}?)`;if(r.length===1)return`
|
|
15
|
-
(Did you mean ${r[0]}?)`;return""}GC.suggestSimilar=WC});var
|
|
15
|
+
(Did you mean ${r[0]}?)`;return""}GC.suggestSimilar=WC});var Jp=En(function(nA){var YC=Mr("node:events").EventEmitter,nr=Mr("node:child_process"),Pe=Mr("node:path"),an=Mr("node:fs"),H=Mr("node:process"),{Argument:JC,humanReadableArgName:XC}=Go(),{CommanderError:Ba}=Lr(),{Help:QC,stripColor:eA}=Ka(),{Option:Gp,DualOptions:tA}=qa(),{suggestSimilar:Zp}=Wp();class Wa extends YC{constructor(e){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=e||"",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:(t)=>H.stdout.write(t),writeErr:(t)=>H.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>H.stdout.isTTY?H.stdout.columns:void 0,getErrHelpWidth:()=>H.stderr.isTTY?H.stderr.columns:void 0,getOutHasColors:()=>Ha()??(H.stdout.isTTY&&H.stdout.hasColors?.()),getErrHasColors:()=>Ha()??(H.stderr.isTTY&&H.stderr.hasColors?.()),stripColor:(t)=>eA(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,o=n;if(typeof r==="object"&&r!==null)o=r,r=null;o=o||{};let[,i,a]=e.match(/([^ ]+) *(.*)/),s=this.createCommand(i);if(r)s.description(r),s._executableHandler=!0;if(o.isDefault)this._defaultCommandName=s._name;if(s._hidden=!!(o.noHelp||o.hidden),s._executableFile=o.executableFile||null,a)s.arguments(a);if(this._registerCommand(s),s.parent=this,s.copyInheritedSettings(this),r)return this;return s}createCommand(e){return new Wa(e)}createHelp(){return Object.assign(new QC,this.configureHelp())}configureHelp(e){if(e===void 0)return this._helpConfiguration;return this._helpConfiguration=e,this}configureOutput(e){if(e===void 0)return this._outputConfiguration;return Object.assign(this._outputConfiguration,e),this}showHelpAfterError(e=!0){if(typeof e!=="string")e=!!e;return this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
|
|
16
16
|
- specify the name in Command constructor or using .name()`);if(t=t||{},t.isDefault)this._defaultCommandName=e._name;if(t.noHelp||t.hidden)e._hidden=!0;return this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new JC(e,t)}argument(e,t,n,r){let o=this.createArgument(e,t);if(typeof n==="function")o.default(r).argParser(n);else o.default(n);return this.addArgument(o),this}arguments(e){return e.trim().split(/ +/).forEach((t)=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,r]=e.match(/([^ ]+) *(.*)/),o=t??"display help for command",i=this.createCommand(n);if(i.helpOption(!1),r)i.arguments(r);if(o)i.description(o);return this._addImplicitHelpCommand=!0,this._helpCommand=i,this}addHelpCommand(e,t){if(typeof e!=="object")return this.helpCommand(e,t),this;return this._addImplicitHelpCommand=!0,this._helpCommand=e,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(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
|
|
17
|
-
Expecting one of '${n.join("', '")}'`);if(this._lifeCycleHooks[e])this._lifeCycleHooks[e].push(t);else this._lifeCycleHooks[e]=[t];return this}exitOverride(e){if(e)this._exitCallback=e;else this._exitCallback=(t)=>{if(t.code!=="commander.executeSubCommandAsync")throw t};return this}_exit(e,t,n){if(this._exitCallback)this._exitCallback(new
|
|
18
|
-
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=(r)=>[r.name()].concat(r.aliases()),n=t(e).find((r)=>this._findCommand(r));if(n){let r=t(this._findCommand(n)).join("|"),o=t(e).join("|");throw Error(`cannot add command '${o}' as already have command '${r}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let o=e.long.replace(/^--no-/,"--");if(!this._findOption(o))this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else if(e.defaultValue!==void 0)this.setOptionValueWithSource(n,e.defaultValue,"default");let r=(o,i,a)=>{if(o==null&&e.presetArg!==void 0)o=e.presetArg;let s=this.getOptionValue(n);if(o!==null&&e.parseArg)o=this._callParseArg(e,o,s,i);else if(o!==null&&e.variadic)o=e._concatValue(o,s);if(o==null)if(e.negate)o=!1;else if(e.isBoolean()||e.optional)o=!0;else o="";this.setOptionValueWithSource(n,o,a)};if(this.on("option:"+t,(o)=>{let i=`error: option '${e.flags}' argument '${o}' is invalid.`;r(o,i,"cli")}),e.envVar)this.on("optionEnv:"+t,(o)=>{let i=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;r(o,i,"env")});return this}_optionEx(e,t,n,r,o){if(typeof t==="object"&&t instanceof
|
|
17
|
+
Expecting one of '${n.join("', '")}'`);if(this._lifeCycleHooks[e])this._lifeCycleHooks[e].push(t);else this._lifeCycleHooks[e]=[t];return this}exitOverride(e){if(e)this._exitCallback=e;else this._exitCallback=(t)=>{if(t.code!=="commander.executeSubCommandAsync")throw t};return this}_exit(e,t,n){if(this._exitCallback)this._exitCallback(new Ba(e,t,n));H.exit(e)}action(e){let t=(n)=>{let r=this.registeredArguments.length,o=n.slice(0,r);if(this._storeOptionsAsProperties)o[r]=this;else o[r]=this.opts();return o.push(this),e.apply(this,o)};return this._actionHandler=t,this}createOption(e,t){return new Gp(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(o){if(o.code==="commander.invalidArgument"){let i=`${r} ${o.message}`;this.error(i,{exitCode:o.exitCode,code:o.code})}throw o}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
|
|
18
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=(r)=>[r.name()].concat(r.aliases()),n=t(e).find((r)=>this._findCommand(r));if(n){let r=t(this._findCommand(n)).join("|"),o=t(e).join("|");throw Error(`cannot add command '${o}' as already have command '${r}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let o=e.long.replace(/^--no-/,"--");if(!this._findOption(o))this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else if(e.defaultValue!==void 0)this.setOptionValueWithSource(n,e.defaultValue,"default");let r=(o,i,a)=>{if(o==null&&e.presetArg!==void 0)o=e.presetArg;let s=this.getOptionValue(n);if(o!==null&&e.parseArg)o=this._callParseArg(e,o,s,i);else if(o!==null&&e.variadic)o=e._concatValue(o,s);if(o==null)if(e.negate)o=!1;else if(e.isBoolean()||e.optional)o=!0;else o="";this.setOptionValueWithSource(n,o,a)};if(this.on("option:"+t,(o)=>{let i=`error: option '${e.flags}' argument '${o}' is invalid.`;r(o,i,"cli")}),e.envVar)this.on("optionEnv:"+t,(o)=>{let i=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;r(o,i,"env")});return this}_optionEx(e,t,n,r,o){if(typeof t==="object"&&t instanceof Gp)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let i=this.createOption(t,n);if(i.makeOptionMandatory(!!e.mandatory),typeof r==="function")i.default(o).argParser(r);else if(r instanceof RegExp){let a=r;r=(s,c)=>{let d=a.exec(s);return d?d[0]:c},i.default(o).argParser(r)}else i.default(r);return this.addOption(i)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,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(e=!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=!!e,this}getOptionValue(e){if(this._storeOptionsAsProperties)return this[e];return this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){if(this._storeOptionsAsProperties)this[e]=t;else this._optionValues[e]=t;return this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach((n)=>{if(n.getOptionValueSource(e)!==void 0)t=n.getOptionValueSource(e)}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){if(H.versions?.electron)t.from="electron";let r=H.execArgv??[];if(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))t.from="eval"}if(e===void 0)e=H.argv;this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":if(H.defaultApp)this._scriptPath=e[1],n=e.slice(2);else n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),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
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(e,t,n){if(an.existsSync(e))return;let r=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",o=`'${e}' does not exist
|
|
20
20
|
- if '${n}' 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
|
-
- ${r}`;throw Error(o)}_executeSubCommand(e,t){t=t.slice();let n=!1,r=[".js",".ts",".tsx",".mjs",".cjs"];function o(d,u){let m=Pe.resolve(d,u);if(an.existsSync(m))return m;if(r.includes(Pe.extname(u)))return;let y=r.find((_)=>an.existsSync(`${m}${_}`));if(y)return`${m}${y}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let d;try{d=an.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=Pe.resolve(Pe.dirname(d),a)}if(a){let d=o(a,i);if(!d&&!e._executableFile&&this._scriptPath){let u=Pe.basename(this._scriptPath,Pe.extname(this._scriptPath));if(u!==this._name)d=o(a,`${u}-${e._name}`)}i=d||i}n=r.includes(Pe.extname(i));let s;if(H.platform!=="win32")if(n)t.unshift(i),t=
|
|
22
|
+
- ${r}`;throw Error(o)}_executeSubCommand(e,t){t=t.slice();let n=!1,r=[".js",".ts",".tsx",".mjs",".cjs"];function o(d,u){let m=Pe.resolve(d,u);if(an.existsSync(m))return m;if(r.includes(Pe.extname(u)))return;let y=r.find((_)=>an.existsSync(`${m}${_}`));if(y)return`${m}${y}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let d;try{d=an.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=Pe.resolve(Pe.dirname(d),a)}if(a){let d=o(a,i);if(!d&&!e._executableFile&&this._scriptPath){let u=Pe.basename(this._scriptPath,Pe.extname(this._scriptPath));if(u!==this._name)d=o(a,`${u}-${e._name}`)}i=d||i}n=r.includes(Pe.extname(i));let s;if(H.platform!=="win32")if(n)t.unshift(i),t=Yp(H.execArgv).concat(t),s=nr.spawn(H.argv[0],t,{stdio:"inherit"});else s=nr.spawn(i,t,{stdio:"inherit"});else this._checkForMissingExecutable(i,a,e._name),t.unshift(i),t=Yp(H.execArgv).concat(t),s=nr.spawn(H.execPath,t,{stdio:"inherit"});if(!s.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((u)=>{H.on(u,()=>{if(s.killed===!1&&s.exitCode===null)s.kill(u)})});let c=this._exitCallback;s.on("close",(d)=>{if(d=d??1,!c)H.exit(d);else c(new Ba(d,"commander.executeSubCommandAsync","(close)"))}),s.on("error",(d)=>{if(d.code==="ENOENT")this._checkForMissingExecutable(i,a,e._name);else if(d.code==="EACCES")throw Error(`'${i}' not executable`);if(!c)H.exit(1);else{let u=new Ba(1,"commander.executeSubCommandAsync","(error)");u.nestedError=d,c(u)}}),this.runningCommand=s}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);if(!r)this.help({error:!0});r._prepareForParse();let o;return o=this._chainOrCallSubCommandHook(o,r,"preSubcommand"),o=this._chainOrCall(o,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),o}_dispatchHelpCommand(e){if(!e)this.help();let t=this._findCommand(e);if(t&&!t._executableHandler)t.help();return this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((e,t)=>{if(e.required&&this.args[t]==null)this.missingArgument(e.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 e=(n,r,o)=>{let i=r;if(r!==null&&n.parseArg){let a=`error: command-argument value '${r}' is invalid for argument '${n.name()}'.`;i=this._callParseArg(n,r,o,a)}return i};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let o=n.defaultValue;if(n.variadic){if(r<this.args.length){if(o=this.args.slice(r),n.parseArg)o=o.reduce((i,a)=>e(n,a,i),n.defaultValue)}else if(o===void 0)o=[]}else if(r<this.args.length){if(o=this.args[r],n.parseArg)o=e(n,o,n.defaultValue)}t[r]=o}),this.processedArgs=t}_chainOrCall(e,t){if(e&&e.then&&typeof e.then==="function")return e.then(()=>t());return t()}_chainOrCallHooks(e,t){let n=e,r=[];if(this._getCommandAndAncestors().reverse().filter((o)=>o._lifeCycleHooks[t]!==void 0).forEach((o)=>{o._lifeCycleHooks[t].forEach((i)=>{r.push({hookedCommand:o,callback:i})})}),t==="postAction")r.reverse();return r.forEach((o)=>{n=this._chainOrCall(n,()=>o.callback(o.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;if(this._lifeCycleHooks[n]!==void 0)this._lifeCycleHooks[n].forEach((o)=>{r=this._chainOrCall(r,()=>o(this,t))});return r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{if(n.unknown.length>0)this.unknownOption(n.unknown[0])},o=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let i;if(i=this._chainOrCallHooks(i,"preAction"),i=this._chainOrCall(i,()=>this._actionHandler(this.processedArgs)),this.parent)i=this._chainOrCall(i,()=>{this.parent.emit(o,e,t)});return i=this._chainOrCallHooks(i,"postAction"),i}if(this.parent&&this.parent.listenerCount(o))r(),this._processArguments(),this.parent.emit(o,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);if(this.listenerCount("command:*"))this.emit("command:*",e,t);else if(this.commands.length)this.unknownCommand();else r(),this._processArguments()}else if(this.commands.length)r(),this.help({error:!0});else r(),this._processArguments()}_findCommand(e){if(!e)return;return this.commands.find((t)=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find((t)=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((e)=>{e.options.forEach((t)=>{if(t.mandatory&&e.getOptionValue(t.attributeName())===void 0)e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter((n)=>{let r=n.attributeName();if(this.getOptionValue(r)===void 0)return!1;return this.getOptionValueSource(r)!=="default"});e.filter((n)=>n.conflictsWith.length>0).forEach((n)=>{let r=e.find((o)=>n.conflictsWith.includes(o.attributeName()));if(r)this._conflictingOption(n,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((e)=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t,o=e.slice();function i(s){return s.length>1&&s[0]==="-"}let a=null;while(o.length){let s=o.shift();if(s==="--"){if(r===n)r.push(s);r.push(...o);break}if(a&&!i(s)){this.emit(`option:${a.name()}`,s);continue}if(a=null,i(s)){let c=this._findOption(s);if(c){if(c.required){let d=o.shift();if(d===void 0)this.optionMissingArgument(c);this.emit(`option:${c.name()}`,d)}else if(c.optional){let d=null;if(o.length>0&&!i(o[0]))d=o.shift();this.emit(`option:${c.name()}`,d)}else this.emit(`option:${c.name()}`);a=c.variadic?c:null;continue}}if(s.length>2&&s[0]==="-"&&s[1]!=="-"){let c=this._findOption(`-${s[1]}`);if(c){if(c.required||c.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${c.name()}`,s.slice(2));else this.emit(`option:${c.name()}`),o.unshift(`-${s.slice(2)}`);continue}}if(/^--[^=]+=/.test(s)){let c=s.indexOf("="),d=this._findOption(s.slice(0,c));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,s.slice(c+1));continue}}if(i(s))r=n;if((this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(s)){if(t.push(s),o.length>0)n.push(...o);break}else if(this._getHelpCommand()&&s===this._getHelpCommand().name()){if(t.push(s),o.length>0)t.push(...o);break}else if(this._defaultCommandName){if(n.push(s),o.length>0)n.push(...o);break}}if(this._passThroughOptions){if(r.push(s),o.length>0)r.push(...o);break}r.push(s)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let r=this.options[n].attributeName();e[r]=r===this._versionOptionName?this._version:this[r]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){if(this._outputConfiguration.outputError(`${e}
|
|
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 n=t||{},r=n.exitCode||1,o=n.code||"commander.error";this._exit(r,o,e)}_parseOptionsEnv(){this.options.forEach((e)=>{if(e.envVar&&e.envVar in H.env){let t=e.attributeName();if(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))if(e.required||e.optional)this.emit(`optionEnv:${e.name()}`,H.env[e.envVar]);else this.emit(`optionEnv:${e.name()}`)}})}_parseOptionsImplied(){let e=new tA(this.options),t=(n)=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter((n)=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach((n)=>{Object.keys(n.implied).filter((r)=>!t(r)).forEach((r)=>{this.setOptionValueWithSource(r,n.implied[r],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=(i)=>{let a=i.attributeName(),s=this.getOptionValue(a),c=this.options.find((u)=>u.negate&&a===u.attributeName()),d=this.options.find((u)=>!u.negate&&a===u.attributeName());if(c&&(c.presetArg===void 0&&s===!1||c.presetArg!==void 0&&s===c.presetArg))return c;return d||i},r=(i)=>{let a=n(i),s=a.attributeName();if(this.getOptionValueSource(s)==="env")return`environment variable '${a.envVar}'`;return`option '${a.flags}'`},o=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],o=this;do{let i=o.createHelp().visibleOptions(o).filter((a)=>a.long).map((a)=>a.long);r=r.concat(i),o=o.parent}while(o&&!o._enablePositionalOptions);t=
|
|
25
|
+
`),this.outputHelp({error:!0});let n=t||{},r=n.exitCode||1,o=n.code||"commander.error";this._exit(r,o,e)}_parseOptionsEnv(){this.options.forEach((e)=>{if(e.envVar&&e.envVar in H.env){let t=e.attributeName();if(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))if(e.required||e.optional)this.emit(`optionEnv:${e.name()}`,H.env[e.envVar]);else this.emit(`optionEnv:${e.name()}`)}})}_parseOptionsImplied(){let e=new tA(this.options),t=(n)=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter((n)=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach((n)=>{Object.keys(n.implied).filter((r)=>!t(r)).forEach((r)=>{this.setOptionValueWithSource(r,n.implied[r],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=(i)=>{let a=i.attributeName(),s=this.getOptionValue(a),c=this.options.find((u)=>u.negate&&a===u.attributeName()),d=this.options.find((u)=>!u.negate&&a===u.attributeName());if(c&&(c.presetArg===void 0&&s===!1||c.presetArg!==void 0&&s===c.presetArg))return c;return d||i},r=(i)=>{let a=n(i),s=a.attributeName();if(this.getOptionValueSource(s)==="env")return`environment variable '${a.envVar}'`;return`option '${a.flags}'`},o=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],o=this;do{let i=o.createHelp().visibleOptions(o).filter((a)=>a.long).map((a)=>a.long);r=r.concat(i),o=o.parent}while(o&&!o._enablePositionalOptions);t=Zp(e,r)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach((o)=>{if(r.push(o.name()),o.alias())r.push(o.alias())}),t=Zp(e,r)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
26
26
|
`),this._exit(0,"commander.version",e)}),this}description(e,t){if(e===void 0&&t===void 0)return this._description;if(this._description=e,t)this._argsDescription=t;return this}summary(e){if(e===void 0)return this._summary;return this._summary=e,this}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)t=this.commands[this.commands.length-1];if(e===t._name)throw Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let r=[n.name()].concat(n.aliases()).join("|");throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${r}'`)}return t._aliases.push(e),this}aliases(e){if(e===void 0)return this._aliases;return e.forEach((t)=>this.alias(t)),this}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map((n)=>XC(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){if(e===void 0)return this._name;return this._name=e,this}nameFromFilename(e){return this._name=Pe.basename(e,Pe.extname(e)),this}executableDir(e){if(e===void 0)return this._executableDir;return this._executableDir=e,this}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);if(n.hasColors)return r;return this._outputConfiguration.stripColor(r)}_getOutputContext(e){e=e||{};let t=!!e.error,n,r,o;if(t)n=(a)=>this._outputConfiguration.writeErr(a),r=this._outputConfiguration.getErrHasColors(),o=this._outputConfiguration.getErrHelpWidth();else n=(a)=>this._outputConfiguration.writeOut(a),r=this._outputConfiguration.getOutHasColors(),o=this._outputConfiguration.getOutHelpWidth();return{error:t,write:(a)=>{if(!r)a=this._outputConfiguration.stripColor(a);return n(a)},hasColors:r,helpWidth:o}}outputHelp(e){let t;if(typeof e==="function")t=e,e=void 0;let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach((i)=>i.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let o=this.helpInformation({error:n.error});if(t){if(o=t(o),typeof o!=="string"&&!Buffer.isBuffer(o))throw Error("outputHelp callback must return a string or a Buffer")}if(n.write(o),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",r),this._getCommandAndAncestors().forEach((i)=>i.emit("afterAllHelp",r))}helpOption(e,t){if(typeof e==="boolean"){if(e)this._helpOption=this._helpOption??void 0;else this._helpOption=null;return this}return e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=Number(H.exitCode??0);if(t===0&&e&&typeof e!=="function"&&e.error)t=1;this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
|
|
27
27
|
Expecting one of '${n.join("', '")}'`);let r=`${e}Help`;return this.on(r,(o)=>{let i;if(typeof t==="function")i=t({error:o.error,command:o.command});else i=t;if(i)o.write(`${i}
|
|
28
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((r)=>t.is(r)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function Jp(e){return e.map((t)=>{if(!t.startsWith("--inspect"))return t;let n,r="127.0.0.1",o="9229",i;if((i=t.match(/^(--inspect(-brk)?)$/))!==null)n=i[1];else if((i=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(n=i[1],/^\d+$/.test(i[3]))o=i[3];else r=i[3];else if((i=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)n=i[1],r=i[3],o=i[4];if(n&&o!=="0")return`${n}=${r}:${parseInt(o)+1}`;return t})}function Ga(){if(H.env.NO_COLOR||H.env.FORCE_COLOR==="0"||H.env.FORCE_COLOR==="false")return!1;if(H.env.FORCE_COLOR||H.env.CLICOLOR_FORCE!==void 0)return!0;return}nA.Command=Za;nA.useColor=Ga});var jt=En(function(H2,es){var Jo=process||{},_m=Jo.argv||[],Yo=Jo.env||{},pA=!(!!Yo.NO_COLOR||_m.includes("--no-color"))&&(!!Yo.FORCE_COLOR||_m.includes("--color")||Jo.platform==="win32"||(Jo.stdout||{}).isTTY&&Yo.TERM!=="dumb"||!!Yo.CI),mA=(e,t,n=e)=>(r)=>{let o=""+r,i=o.indexOf(t,e.length);return~i?e+fA(o,t,n,i)+t:e+o+t},fA=(e,t,n,r)=>{let o="",i=0;do o+=e.substring(i,r)+n,i=r+t.length,r=e.indexOf(t,i);while(~r);return o+e.substring(i)},bm=(e=pA)=>{let t=e?mA:()=>String;return{isColorSupported:e,reset:t("\x1B[0m","\x1B[0m"),bold:t("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:t("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:t("\x1B[3m","\x1B[23m"),underline:t("\x1B[4m","\x1B[24m"),inverse:t("\x1B[7m","\x1B[27m"),hidden:t("\x1B[8m","\x1B[28m"),strikethrough:t("\x1B[9m","\x1B[29m"),black:t("\x1B[30m","\x1B[39m"),red:t("\x1B[31m","\x1B[39m"),green:t("\x1B[32m","\x1B[39m"),yellow:t("\x1B[33m","\x1B[39m"),blue:t("\x1B[34m","\x1B[39m"),magenta:t("\x1B[35m","\x1B[39m"),cyan:t("\x1B[36m","\x1B[39m"),white:t("\x1B[37m","\x1B[39m"),gray:t("\x1B[90m","\x1B[39m"),bgBlack:t("\x1B[40m","\x1B[49m"),bgRed:t("\x1B[41m","\x1B[49m"),bgGreen:t("\x1B[42m","\x1B[49m"),bgYellow:t("\x1B[43m","\x1B[49m"),bgBlue:t("\x1B[44m","\x1B[49m"),bgMagenta:t("\x1B[45m","\x1B[49m"),bgCyan:t("\x1B[46m","\x1B[49m"),bgWhite:t("\x1B[47m","\x1B[49m"),blackBright:t("\x1B[90m","\x1B[39m"),redBright:t("\x1B[91m","\x1B[39m"),greenBright:t("\x1B[92m","\x1B[39m"),yellowBright:t("\x1B[93m","\x1B[39m"),blueBright:t("\x1B[94m","\x1B[39m"),magentaBright:t("\x1B[95m","\x1B[39m"),cyanBright:t("\x1B[96m","\x1B[39m"),whiteBright:t("\x1B[97m","\x1B[39m"),bgBlackBright:t("\x1B[100m","\x1B[49m"),bgRedBright:t("\x1B[101m","\x1B[49m"),bgGreenBright:t("\x1B[102m","\x1B[49m"),bgYellowBright:t("\x1B[103m","\x1B[49m"),bgBlueBright:t("\x1B[104m","\x1B[49m"),bgMagentaBright:t("\x1B[105m","\x1B[49m"),bgCyanBright:t("\x1B[106m","\x1B[49m"),bgWhiteBright:t("\x1B[107m","\x1B[49m")}};es.exports=bm();es.exports.createColors=bm});var Ja={};TC(Ja,{program:()=>nm,createCommand:()=>rm,createOption:()=>om,createArgument:()=>im,Command:()=>am,Option:()=>sm,Argument:()=>cm,Help:()=>lm,CommanderError:()=>dm,InvalidArgumentError:()=>um,InvalidOptionArgumentError:()=>pm},{program:(T2)=>nm=T2,createCommand:(T2)=>rm=T2,createOption:(T2)=>om=T2,createArgument:(T2)=>im=T2,Command:(T2)=>am=T2,Option:(T2)=>sm=T2,Argument:(T2)=>cm=T2,Help:(T2)=>lm=T2,CommanderError:(T2)=>dm=T2,InvalidArgumentError:(T2)=>um=T2,InvalidOptionArgumentError:(T2)=>pm=T2});var Zt={};Up(Zt,{ZodISODate:()=>no,ZodISODateTime:()=>to,ZodISODuration:()=>oo,ZodISOTime:()=>ro,date:()=>HR,datetime:()=>BR,duration:()=>GR,time:()=>WR});var pr={};Up(pr,{bigint:()=>XR,boolean:()=>JR,date:()=>QR,number:()=>YR,string:()=>ZR});function Ka(e){let t=e.length;while(t>0&&e[t-1]==="/")t-=1;return e.slice(0,t)}var{Argument:Qp}=Go(),{Command:Ya}=Xp(),{CommanderError:iA,InvalidArgumentError:em}=Lr(),{Help:aA}=Ba(),{Option:tm}=Ha();var nm=new Ya,rm=(e)=>new Ya(e),om=(e,t)=>new tm(e,t),im=(e,t)=>new Qp(e,t),am=Ya,sm=tm,cm=Qp,lm=aA,dm=iA,um=em,pm=em;var{program:I2,createCommand:N2,createArgument:O2,createOption:k2,CommanderError:D2,InvalidArgumentError:P2,InvalidOptionArgumentError:$2,Command:mm,Argument:M2,Option:L2,Help:z2}=Ja;import{readFileSync as sA}from"node:fs";function se(e){return typeof e==="object"&&e!=null&&!Array.isArray(e)}function Ee(e){return typeof e==="object"&&e!=null?{...e}:void 0}function X(e){return typeof e==="string"?e:void 0}function wn(e){return typeof e==="number"?e:void 0}function Ye(e){if(!Array.isArray(e))return[];return e.map((t)=>Ee(t)).filter((t)=>t!=null)}function zr(){return"0.5.1"}var Xa="/cli/compatibilidade",Zo=null;function cA(){if(Zo!=null)return Zo;let e='[{"niva_min":"2.0.0","niva_max":null,"dist_tag":"niva-2.0"}]',t='{"min":"2.0.0","max":null}',n=null;if(typeof t==="string"&&typeof e==="string"){let r=JSON.parse(t),o=JSON.parse(e);n=fm(r,o)}else{let r=JSON.parse(lA()),o=se(r)?r.supported_niva:void 0,i=se(r)?r.compat_table:void 0;n=fm(o,i)}if(n==null)throw Error("Invalid apps/cli/compat.json, fix the compat table");return Zo=n,Zo}function fm(e,t){if(!se(e)||!Array.isArray(t))return null;let n=X(e.min);if(n==null)return null;let r=X(e.max)??null,o=[];for(let i of Ye(t)){let a=X(i.niva_min),s=X(i.dist_tag);if(a==null||s==null)return null;o.push({niva_min:a,niva_max:X(i.niva_max)??null,dist_tag:s})}return{supported_niva:{min:n,max:r},compat_table:o}}function lA(){return sA(new URL("../../compat.json",import.meta.url),"utf-8")}function gm(e){let n=(e.split("-")[0]?.split("+")[0]??"").split(".");if(n.length!==3)return null;let r=n.map((o)=>Number.parseInt(o,10));if(r.some((o)=>!Number.isFinite(o)||o<0))return null;return[r[0],r[1],r[2]]}function hm(e,t){let n=gm(e),r=gm(t);if(n===null||r===null)return 0;for(let o=0;o<3;o++)if(n[o]!==r[o])return n[o]-r[o];return 0}function ym(e,t){for(let n of t.compat_table){if(hm(e,n.niva_min)<0)continue;if(n.niva_max!=null&&hm(e,n.niva_max)>0)continue;return n.dist_tag}return null}var dA=null;function uA(){return dA}function Qa(){let e=cA(),t=uA();if(t!=null)return ym(t,e);return ym(e.supported_niva.min,e)}var he=on(jt(),1),gA=new Set(["json","table","plain"]);function hA(e){return gA.has(e)}function yA(){return process.stdout.isTTY===!0&&process.env.NO_COLOR==null}function Cn(e){if(e.output!=null)return hA(e.output)?e.output:"table";if(e.json===!0)return"json";return yA()?"table":"json"}function _A(e,t){return t in e}function N(e,t){if(t==null)return e;let n={};for(let r of t)if(_A(e,r))n[r]=e[r];return n}function v(e){console.log(JSON.stringify(e,null,2))}var bA=/\x1B\[[0-9;]*m/g;function vA(e){return e.replaceAll(bA,"")}var SA=[[128512,128591],[127744,128511],[128640,128767],[129280,129535],[129536,129791],[9728,10175],[127456,127487]],xA=[[65024,65039],[8205,8205]];function vm(e,t){for(let[n,r]of t)if(e>=n&&e<=r)return!0;return!1}function EA(e){if(vm(e,SA))return 2;if(vm(e,xA))return 0;return 1}function Em(e){let t=vA(e),n=0;for(let r of t)n+=EA(r.codePointAt(0));return n}function ts(e,t){let n=Em(e);if(n>=t)return e;return e+" ".repeat(t-n)}function Sm(e){if(e==null)return"";return typeof e==="string"?e:JSON.stringify(e)}function L(e,t){if(t.length===0){console.log(he.default.dim("No results."));return}let n=e.map((o)=>{let i=o.length,a=Math.max(...t.map((s)=>Em(Sm(s[o]))));return Math.max(i,a)}),r=e.map((o,i)=>o.padEnd(n[i])).join(" ");console.log(he.default.bold(r)),console.log(he.default.dim(n.map((o)=>"─".repeat(o)).join("──")));for(let o of t){let i=e.map((a,s)=>ts(Sm(o[a]),n[s])).join(" ");console.log(i)}}function O(e){console.log(he.default.green(e))}function C(e){console.error(he.default.red(e))}function D(e){console.log(he.default.dim(e))}function yt(e){console.error(he.default.dim(e))}function Et(e){console.error(he.default.yellow(e))}function S(e){let{output:t,fields:n}=e,r=Cn({json:e.json===!0,output:typeof t==="string"?t:void 0}),o=typeof n==="string"?n.split(",").map((i)=>i.trim()):void 0;return{format:r,fields:o}}function te(e){if(e.page==null)return;if(e.total_pages==null||e.total==null){D(`Page ${e.page}`);return}D(`Page ${e.page}/${e.total_pages} (${e.total} total)`)}function ke(e){if(e==null)return"—";let t=Math.ceil(e/1000);if(t===0)return"0s";let n=Math.floor(t/3600),r=Math.floor(t%3600/60),o=t%60;if(n>0)return r>0?`${n}h ${r}m`:`${n}h`;if(r>0)return o>0?`${r}m ${o}s`:`${r}m`;return`${o}s`}function ns(e){if(e==null)return"—";switch(e){case"answered":return he.default.green(`✓ ${e}`);case"missed":return he.default.red(`✗ ${e}`);case"busy":return he.default.yellow(`● ${e}`);case"failed":return he.default.dim(`✗ ${e}`);default:return e}}function rs(e,t){if(e==null)return"—";let n=t!=null&&t>0?"+":"",r=t!=null?` (${n}${t})`:"";switch(e){case"positive":return he.default.green(`\uD83D\uDE0A ${e}${r}`);case"negative":return he.default.red(`\uD83D\uDE1E ${e}${r}`);case"neutral":return he.default.yellow(`\uD83D\uDE10 ${e}${r}`);case"mixed":return he.default.blue(`\uD83D\uDD00 ${e}${r}`);default:return`${e}${r}`}}var wA={voicemail:"Voicemail",announcement:"Carrier announcement",ivr:"IVR / switchboard",screening:"Call screening",human:"Human",unknown:"Unclassified"};function Xo(e){return e==null?"—":wA[e]}function An(e,t,n=20){let r=t>0?e/t:0,o=Math.round(r*n),i=n-o;return"█".repeat(o)+"░".repeat(i)}function wt(e,t,n,r=20){let o=An(t,n,r),i=n>0?Math.round(t/n*100):0;console.log(` ${ts(e,14)} ${o} ${t} (${i}%)`)}function J(e){for(let t=0;t<e.length;t++){let n=e[t],r=Math.max(...n.rows.map((i)=>i.label.length)),o=Math.max(r+4+30,n.title.length+4);console.log(he.default.dim(`┌─ ${n.title} ${"─".repeat(Math.max(0,o-n.title.length-4))}`));for(let i of n.rows){let a=i.value==null?"—":String(i.value);console.log(`${he.default.dim("│")} ${ts(i.label,r)} ${a}`)}if(console.log(he.default.dim(`└${"─".repeat(o)}`)),t<e.length-1)console.log("")}}function os(e){for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1,o=r?"└──":"├──",i=n.detail!=null?he.default.dim(` (${n.detail})`):"";if(console.log(` ${o} ${n.label}${i}`),n.children!=null){let a=r?" ":"│ ";for(let s of n.children)console.log(he.default.dim(` ${a}${s}`))}}}function CA(e){let t=e.toLowerCase();return t==="caller"||t==="speaker_l"||t==="speaker_01"}function wm(e){if(e.length===0){D(" No transcript available.");return}for(let t of e){let n=Math.floor(t.initial_time/60),r=Math.floor(t.initial_time%60),o=`${String(n).padStart(2,"0")}:${String(r).padStart(2,"0")}`,i=CA(t.speaker)?he.default.blue("Caller"):he.default.green("Agent "),a=he.default.dim(`[${o}]`);console.log(` ${a} ${i} ${he.default.dim(">")} ${t.text}`)}}function xm(e,t){if(/^\d{4}-\d{2}-\d{2}$/.test(e))return t?`${e}T23:59:59.999Z`:`${e}T00:00:00.000Z`;return e}function _t(e,t=0){let n=new Date,r=e.from!=null?xm(e.from,!1):new Date(n.getFullYear(),n.getMonth(),n.getDate()-t).toISOString(),o=e.to!=null?xm(e.to,!0):n.toISOString();return{date_from:r,date_to:o}}function Me(e){let t=typeof e==="string"?new Date(e):e,n=String(t.getDate()).padStart(2,"0"),r=String(t.getMonth()+1).padStart(2,"0"),o=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}/${r} ${o}:${i}`}var A={SUCCESS:0,GENERAL_ERROR:1,USAGE_ERROR:2,NOT_FOUND:3,PERMISSION_DENIED:4,CONFLICT:5},is="table",AA="";function TA(e){if(e.endsWith("_NOT_FOUND")||e==="NOT_FOUND"||e==="AUDIO_FILE_CONTENT_MISSING")return A.NOT_FOUND;if(e==="UNAUTHORIZED"||e==="FORBIDDEN"||e==="ADMIN_REQUIRED"||e==="API_KEY_INVALID"||e==="INSUFFICIENT_PERMISSIONS"||e==="INSUFFICIENT_SCOPE")return A.PERMISSION_DENIED;if(e==="UNPROCESSABLE_CONTENT"||e==="BAD_REQUEST")return A.USAGE_ERROR;if(e==="AUDIO_FILE_TOO_LARGE"||e==="AUDIO_FILE_INVALID_FORMAT"||e==="AUDIO_FILE_NOT_TTS"||e==="TTS_VOICE_UNAVAILABLE")return A.USAGE_ERROR;if(e==="CONFLICT"||e==="ATTENDANT_BUSY"||e.startsWith("DUPLICATE_")||e.endsWith("_IN_USE"))return A.CONFLICT;if(e==="MODULE_DISABLED")return A.PERMISSION_DENIED;return A.GENERAL_ERROR}function RA(e){return e==="INTERNAL_SERVER_ERROR"||e==="SERVICE_UNAVAILABLE"}var IA={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 NA(e,t){let n=e.message.toLowerCase();if(n.includes("econnrefused")||n.includes("fetch failed")||n.includes("unable to connect"))return`Could not connect to ${t||"server"}
|
|
28
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((r)=>t.is(r)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function Yp(e){return e.map((t)=>{if(!t.startsWith("--inspect"))return t;let n,r="127.0.0.1",o="9229",i;if((i=t.match(/^(--inspect(-brk)?)$/))!==null)n=i[1];else if((i=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(n=i[1],/^\d+$/.test(i[3]))o=i[3];else r=i[3];else if((i=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)n=i[1],r=i[3],o=i[4];if(n&&o!=="0")return`${n}=${r}:${parseInt(o)+1}`;return t})}function Ha(){if(H.env.NO_COLOR||H.env.FORCE_COLOR==="0"||H.env.FORCE_COLOR==="false")return!1;if(H.env.FORCE_COLOR||H.env.CLICOLOR_FORCE!==void 0)return!0;return}nA.Command=Wa;nA.useColor=Ha});var jt=En(function(q2,Ja){var Yo=process||{},mm=Yo.argv||[],Zo=Yo.env||{},sA=!(!!Zo.NO_COLOR||mm.includes("--no-color"))&&(!!Zo.FORCE_COLOR||mm.includes("--color")||Yo.platform==="win32"||(Yo.stdout||{}).isTTY&&Zo.TERM!=="dumb"||!!Zo.CI),cA=(e,t,n=e)=>(r)=>{let o=""+r,i=o.indexOf(t,e.length);return~i?e+lA(o,t,n,i)+t:e+o+t},lA=(e,t,n,r)=>{let o="",i=0;do o+=e.substring(i,r)+n,i=r+t.length,r=e.indexOf(t,i);while(~r);return o+e.substring(i)},fm=(e=sA)=>{let t=e?cA:()=>String;return{isColorSupported:e,reset:t("\x1B[0m","\x1B[0m"),bold:t("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:t("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:t("\x1B[3m","\x1B[23m"),underline:t("\x1B[4m","\x1B[24m"),inverse:t("\x1B[7m","\x1B[27m"),hidden:t("\x1B[8m","\x1B[28m"),strikethrough:t("\x1B[9m","\x1B[29m"),black:t("\x1B[30m","\x1B[39m"),red:t("\x1B[31m","\x1B[39m"),green:t("\x1B[32m","\x1B[39m"),yellow:t("\x1B[33m","\x1B[39m"),blue:t("\x1B[34m","\x1B[39m"),magenta:t("\x1B[35m","\x1B[39m"),cyan:t("\x1B[36m","\x1B[39m"),white:t("\x1B[37m","\x1B[39m"),gray:t("\x1B[90m","\x1B[39m"),bgBlack:t("\x1B[40m","\x1B[49m"),bgRed:t("\x1B[41m","\x1B[49m"),bgGreen:t("\x1B[42m","\x1B[49m"),bgYellow:t("\x1B[43m","\x1B[49m"),bgBlue:t("\x1B[44m","\x1B[49m"),bgMagenta:t("\x1B[45m","\x1B[49m"),bgCyan:t("\x1B[46m","\x1B[49m"),bgWhite:t("\x1B[47m","\x1B[49m"),blackBright:t("\x1B[90m","\x1B[39m"),redBright:t("\x1B[91m","\x1B[39m"),greenBright:t("\x1B[92m","\x1B[39m"),yellowBright:t("\x1B[93m","\x1B[39m"),blueBright:t("\x1B[94m","\x1B[39m"),magentaBright:t("\x1B[95m","\x1B[39m"),cyanBright:t("\x1B[96m","\x1B[39m"),whiteBright:t("\x1B[97m","\x1B[39m"),bgBlackBright:t("\x1B[100m","\x1B[49m"),bgRedBright:t("\x1B[101m","\x1B[49m"),bgGreenBright:t("\x1B[102m","\x1B[49m"),bgYellowBright:t("\x1B[103m","\x1B[49m"),bgBlueBright:t("\x1B[104m","\x1B[49m"),bgMagentaBright:t("\x1B[105m","\x1B[49m"),bgCyanBright:t("\x1B[106m","\x1B[49m"),bgWhiteBright:t("\x1B[107m","\x1B[49m")}};Ja.exports=fm();Ja.exports.createColors=fm});var Za={};TC(Za,{program:()=>tm,createCommand:()=>nm,createOption:()=>rm,createArgument:()=>om,Command:()=>im,Option:()=>am,Argument:()=>sm,Help:()=>cm,CommanderError:()=>lm,InvalidArgumentError:()=>dm,InvalidOptionArgumentError:()=>um},{program:(A2)=>tm=A2,createCommand:(A2)=>nm=A2,createOption:(A2)=>rm=A2,createArgument:(A2)=>om=A2,Command:(A2)=>im=A2,Option:(A2)=>am=A2,Argument:(A2)=>sm=A2,Help:(A2)=>cm=A2,CommanderError:(A2)=>lm=A2,InvalidArgumentError:(A2)=>dm=A2,InvalidOptionArgumentError:(A2)=>um=A2});var Zt={};Fp(Zt,{ZodISODate:()=>no,ZodISODateTime:()=>to,ZodISODuration:()=>oo,ZodISOTime:()=>ro,date:()=>jR,datetime:()=>UR,duration:()=>KR,time:()=>VR});var pr={};Fp(pr,{bigint:()=>WR,boolean:()=>HR,date:()=>GR,number:()=>BR,string:()=>qR});function ja(e){let t=e.length;while(t>0&&e[t-1]==="/")t-=1;return e.slice(0,t)}var{Argument:Xp}=Go(),{Command:Ga}=Jp(),{CommanderError:iA,InvalidArgumentError:Qp}=Lr(),{Help:aA}=Ka(),{Option:em}=qa();var tm=new Ga,nm=(e)=>new Ga(e),rm=(e,t)=>new em(e,t),om=(e,t)=>new Xp(e,t),im=Ga,am=em,sm=Xp,cm=aA,lm=iA,dm=Qp,um=Qp;var{program:R2,createCommand:I2,createArgument:O2,createOption:N2,CommanderError:k2,InvalidArgumentError:D2,InvalidOptionArgumentError:P2,Command:pm,Argument:$2,Option:M2,Help:L2}=Za;function ge(e){return typeof e==="object"&&e!=null&&!Array.isArray(e)}function Ee(e){return typeof e==="object"&&e!=null?{...e}:void 0}function oe(e){return typeof e==="string"?e:void 0}function wn(e){return typeof e==="number"?e:void 0}function xt(e){if(!Array.isArray(e))return[];return e.map((t)=>Ee(t)).filter((t)=>t!=null)}function zr(){return"0.5.2"}var Ya="/cli/compatibilidade";var he=on(jt(),1),dA=new Set(["json","table","plain"]);function uA(e){return dA.has(e)}function pA(){return process.stdout.isTTY===!0&&process.env.NO_COLOR==null}function Cn(e){if(e.output!=null)return uA(e.output)?e.output:"table";if(e.json===!0)return"json";return pA()?"table":"json"}function mA(e,t){return t in e}function O(e,t){if(t==null)return e;let n={};for(let r of t)if(mA(e,r))n[r]=e[r];return n}function v(e){console.log(JSON.stringify(e,null,2))}var fA=/\x1B\[[0-9;]*m/g;function gA(e){return e.replaceAll(fA,"")}var hA=[[128512,128591],[127744,128511],[128640,128767],[129280,129535],[129536,129791],[9728,10175],[127456,127487]],yA=[[65024,65039],[8205,8205]];function gm(e,t){for(let[n,r]of t)if(e>=n&&e<=r)return!0;return!1}function _A(e){if(gm(e,hA))return 2;if(gm(e,yA))return 0;return 1}function _m(e){let t=gA(e),n=0;for(let r of t)n+=_A(r.codePointAt(0));return n}function Xa(e,t){let n=_m(e);if(n>=t)return e;return e+" ".repeat(t-n)}function hm(e){if(e==null)return"";return typeof e==="string"?e:JSON.stringify(e)}function L(e,t){if(t.length===0){console.log(he.default.dim("No results."));return}let n=e.map((o)=>{let i=o.length,a=Math.max(...t.map((s)=>_m(hm(s[o]))));return Math.max(i,a)}),r=e.map((o,i)=>o.padEnd(n[i])).join(" ");console.log(he.default.bold(r)),console.log(he.default.dim(n.map((o)=>"─".repeat(o)).join("──")));for(let o of t){let i=e.map((a,s)=>Xa(hm(o[a]),n[s])).join(" ");console.log(i)}}function N(e){console.log(he.default.green(e))}function C(e){console.error(he.default.red(e))}function P(e){console.log(he.default.dim(e))}function ht(e){console.error(he.default.dim(e))}function Et(e){console.error(he.default.yellow(e))}function S(e){let{output:t,fields:n}=e,r=Cn({json:e.json===!0,output:typeof t==="string"?t:void 0}),o=typeof n==="string"?n.split(",").map((i)=>i.trim()):void 0;return{format:r,fields:o}}function ee(e){if(e.page==null)return;if(e.total_pages==null||e.total==null){P(`Page ${e.page}`);return}P(`Page ${e.page}/${e.total_pages} (${e.total} total)`)}function Ce(e){if(e==null)return"—";let t=Math.ceil(e/1000);if(t===0)return"0s";let n=Math.floor(t/3600),r=Math.floor(t%3600/60),o=t%60;if(n>0)return r>0?`${n}h ${r}m`:`${n}h`;if(r>0)return o>0?`${r}m ${o}s`:`${r}m`;return`${o}s`}function Qa(e){if(e==null)return"—";switch(e){case"answered":return he.default.green(`✓ ${e}`);case"missed":return he.default.red(`✗ ${e}`);case"busy":return he.default.yellow(`● ${e}`);case"failed":return he.default.dim(`✗ ${e}`);default:return e}}function es(e,t){if(e==null)return"—";let n=t!=null&&t>0?"+":"",r=t!=null?` (${n}${t})`:"";switch(e){case"positive":return he.default.green(`\uD83D\uDE0A ${e}${r}`);case"negative":return he.default.red(`\uD83D\uDE1E ${e}${r}`);case"neutral":return he.default.yellow(`\uD83D\uDE10 ${e}${r}`);case"mixed":return he.default.blue(`\uD83D\uDD00 ${e}${r}`);default:return`${e}${r}`}}var bA={voicemail:"Voicemail",announcement:"Carrier announcement",ivr:"IVR / switchboard",screening:"Call screening",human:"Human",unknown:"Unclassified"};function Jo(e){return e==null?"—":bA[e]}function An(e,t,n=20){let r=t>0?e/t:0,o=Math.round(r*n),i=n-o;return"█".repeat(o)+"░".repeat(i)}function wt(e,t,n,r=20){let o=An(t,n,r),i=n>0?Math.round(t/n*100):0;console.log(` ${Xa(e,14)} ${o} ${t} (${i}%)`)}function J(e){for(let t=0;t<e.length;t++){let n=e[t],r=Math.max(...n.rows.map((i)=>i.label.length)),o=Math.max(r+4+30,n.title.length+4);console.log(he.default.dim(`┌─ ${n.title} ${"─".repeat(Math.max(0,o-n.title.length-4))}`));for(let i of n.rows){let a=i.value==null?"—":String(i.value);console.log(`${he.default.dim("│")} ${Xa(i.label,r)} ${a}`)}if(console.log(he.default.dim(`└${"─".repeat(o)}`)),t<e.length-1)console.log("")}}function ts(e){for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1,o=r?"└──":"├──",i=n.detail!=null?he.default.dim(` (${n.detail})`):"";if(console.log(` ${o} ${n.label}${i}`),n.children!=null){let a=r?" ":"│ ";for(let s of n.children)console.log(he.default.dim(` ${a}${s}`))}}}function vA(e){let t=e.toLowerCase();return t==="caller"||t==="speaker_l"||t==="speaker_01"}function bm(e){if(e.length===0){P(" No transcript available.");return}for(let t of e){let n=Math.floor(t.initial_time/60),r=Math.floor(t.initial_time%60),o=`${String(n).padStart(2,"0")}:${String(r).padStart(2,"0")}`,i=vA(t.speaker)?he.default.blue("Caller"):he.default.green("Agent "),a=he.default.dim(`[${o}]`);console.log(` ${a} ${i} ${he.default.dim(">")} ${t.text}`)}}function ym(e,t){if(/^\d{4}-\d{2}-\d{2}$/.test(e))return t?`${e}T23:59:59.999Z`:`${e}T00:00:00.000Z`;return e}function yt(e,t=0){let n=new Date,r=e.from!=null?ym(e.from,!1):new Date(n.getFullYear(),n.getMonth(),n.getDate()-t).toISOString(),o=e.to!=null?ym(e.to,!0):n.toISOString();return{date_from:r,date_to:o}}function Me(e){let t=typeof e==="string"?new Date(e):e,n=String(t.getDate()).padStart(2,"0"),r=String(t.getMonth()+1).padStart(2,"0"),o=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}/${r} ${o}:${i}`}var A={SUCCESS:0,GENERAL_ERROR:1,USAGE_ERROR:2,NOT_FOUND:3,PERMISSION_DENIED:4,CONFLICT:5},ns="table",SA="";function xA(e){if(e.endsWith("_NOT_FOUND")||e==="NOT_FOUND"||e==="AUDIO_FILE_CONTENT_MISSING")return A.NOT_FOUND;if(e==="UNAUTHORIZED"||e==="FORBIDDEN"||e==="ADMIN_REQUIRED"||e==="API_KEY_INVALID"||e==="INSUFFICIENT_PERMISSIONS"||e==="INSUFFICIENT_SCOPE")return A.PERMISSION_DENIED;if(e==="UNPROCESSABLE_CONTENT"||e==="BAD_REQUEST")return A.USAGE_ERROR;if(e==="AUDIO_FILE_TOO_LARGE"||e==="AUDIO_FILE_INVALID_FORMAT"||e==="AUDIO_FILE_NOT_TTS"||e==="TTS_VOICE_UNAVAILABLE")return A.USAGE_ERROR;if(e==="CONFLICT"||e==="ATTENDANT_BUSY"||e.startsWith("DUPLICATE_")||e.endsWith("_IN_USE"))return A.CONFLICT;if(e==="MODULE_DISABLED")return A.PERMISSION_DENIED;return A.GENERAL_ERROR}function EA(e){return e==="INTERNAL_SERVER_ERROR"||e==="SERVICE_UNAVAILABLE"}var wA={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 CA(e,t){let n=e.message.toLowerCase();if(n.includes("econnrefused")||n.includes("fetch failed")||n.includes("unable to connect"))return`Could not connect to ${t||"server"}
|
|
29
29
|
Is the server running? Check with: niva fs status
|
|
30
30
|
Current URL: ${t||"(not set)"} (change with: niva config set url <url>)`;if(n.includes("enotfound")||n.includes("getaddrinfo"))return`Could not resolve hostname in ${t||"(not set)"}
|
|
31
|
-
Check the URL: niva config set url <url>`;return`Connection error: ${e.message}`}function OA(e){let t=Ee(e);if(t==null)return` • ${String(e)}`;let n=t.path,r=Array.isArray(n)?n.join("."):"",o=t.messageKey??t.code??"invalid",i;if(typeof t.message==="string")i=t.message;else if(typeof o==="string")i=o;else i=JSON.stringify(o);return` ✗ ${r?`${r}: `:""}${i}`}function sn(e){return e instanceof Error&&"defined"in e&&"code"in e}function Tn(e){let t=String(Ee(e)?.code);if(t==="NOT_FOUND"&&Ee(e)?.defined===!1)return kA();return{code:t,message:e.message,data:Ee(Ee(e)?.data),hint:IA[t],exitCode:TA(t),retryable:RA(t)}}function kA(){let e=Qa();return{code:"PROCEDURE_NOT_IMPLEMENTED",message:"This NIVA server does not have this command: it is newer than the deployment.",data:void 0,hint:`${e==null?`Check available compatibility at ${Xa}`:`Run: npx @sippulse/niva@${e} <command>`} (the server's NIVA version does not offer this procedure).`,exitCode:A.USAGE_ERROR,retryable:!1}}function Rn(e){C(`Error: ${e.code} — ${e.message}`);let t=e.data?.issues;if(Array.isArray(t))for(let n of t)C(OA(n));if(e.hint!=null)D(` ${e.hint}`)}function DA(e){if(is==="json")v({error:e.code,message:e.message,data:e.data,hint:e.hint,retryable:e.retryable});else Rn(e);process.exit(e.exitCode)}function as(e){return e instanceof Error?NA(e,AA):String(e)}function Ct(e){if(sn(e))DA(Tn(e));let t=as(e);if(is==="json")v({error:"CONNECTION_ERROR",message:e instanceof Error?e.message:String(e),retryable:!0});else C(t);process.exit(A.GENERAL_ERROR)}function In(e){if(sn(e))Ct(e);let t=e instanceof Error?e.message:String(e);if(is==="json")v({error:"STREAM_ERROR",message:t,retryable:!0});else C(`Stream error: ${t}`);process.exit(A.GENERAL_ERROR)}async function b(e){try{return await e}catch(t){Ct(t)}}function Vt(e="Not yet implemented."){D(e),process.exit(A.USAGE_ERROR)}function Cm(e,t){e.command("ai").description("AI module resources").command("agents").description("List AI agents available for voice interactions").action(async()=>{let{format:r,fields:o}=S(e.opts()),i=await b(t().ai.listAgents());if(r==="json"){let a=o?i.map((s)=>N(s,o)):i;v(a);return}L(["ID","Name","Language","SIP Inbound","Description"],i.map((a)=>({ID:a.id,Name:a.name,Language:a.language,"SIP Inbound":a.sip_inbound_enabled?"enabled":"disabled",Description:a.description??"—"})))})}var f_=on(jt(),1);var Am=/^(?:[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 PA(e){return typeof e==="string"&&Am.test(e)}var Tm=PA;var Le=[];for(let e=0;e<256;++e)Le.push((e+256).toString(16).slice(1));function ss(e,t=0){return(Le[e[t+0]]+Le[e[t+1]]+Le[e[t+2]]+Le[e[t+3]]+"-"+Le[e[t+4]]+Le[e[t+5]]+"-"+Le[e[t+6]]+Le[e[t+7]]+"-"+Le[e[t+8]]+Le[e[t+9]]+"-"+Le[e[t+10]]+Le[e[t+11]]+Le[e[t+12]]+Le[e[t+13]]+Le[e[t+14]]+Le[e[t+15]]).toLowerCase()}function $A(e,t=0){let n=ss(e,t);if(!Tm(n))throw TypeError("Stringified UUID is invalid");return n}var Qo=$A;var MA=new Uint8Array(16);function ei(){return crypto.getRandomValues(MA)}var cs={};function LA(e,t,n){let r;if(e)r=Rm(e.random??e.rng?.()??ei(),e.msecs,e.seq,t,n);else{let o=Date.now(),i=ei();zA(cs,o,i),r=Rm(i,cs.msecs,cs.seq,t,n)}return t??ss(r)}function zA(e,t,n){if(e.msecs??=-1/0,e.seq??=0,t>e.msecs)e.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],e.msecs=t;else if(e.seq=e.seq+1|0,e.seq===0)e.msecs++;return e}function Rm(e,t,n,r,o=0){if(e.length<16)throw Error("Random bytes length must be >= 16");if(!r)r=new Uint8Array(16),o=0;else if(o<0||o+16>r.length)throw RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`);return t??=Date.now(),n??=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9],r[o++]=t/1099511627776&255,r[o++]=t/4294967296&255,r[o++]=t/16777216&255,r[o++]=t/65536&255,r[o++]=t/256&255,r[o++]=t&255,r[o++]=112|n>>>28&15,r[o++]=n>>>20&255,r[o++]=128|n>>>14&63,r[o++]=n>>>6&255,r[o++]=n<<2&255|e[10]&3,r[o++]=e[11],r[o++]=e[12],r[o++]=e[13],r[o++]=e[14],r[o++]=e[15],r}var ls=LA;function FA(e){let t,n=new Uint8Array(16);return n[0]=(t=parseInt(e.slice(0,8),16))>>>24,n[1]=t>>>16&255,n[2]=t>>>8&255,n[3]=t&255,n[4]=(t=parseInt(e.slice(9,13),16))>>>8,n[5]=t&255,n[6]=(t=parseInt(e.slice(14,18),16))>>>8,n[7]=t&255,n[8]=(t=parseInt(e.slice(19,23),16))>>>8,n[9]=t&255,n[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,n[11]=t/4294967296&255,n[12]=t>>>24&255,n[13]=t>>>16&255,n[14]=t>>>8&255,n[15]=t&255,n}var ye="0123456789abcdefghjkmnpqrstvwxyz",B=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 ds(e){let t=Array(26).fill("");if(e.length!==16)throw Error(`Invalid length. Expected 16 bytes, got ${e.length}. Input: ${e}`);return t[0]=ye[(e[0]&224)>>5],t[1]=ye[e[0]&31],t[2]=ye[(e[1]&248)>>3],t[3]=ye[(e[1]&7)<<2|(e[2]&192)>>6],t[4]=ye[(e[2]&62)>>1],t[5]=ye[(e[2]&1)<<4|(e[3]&240)>>4],t[6]=ye[(e[3]&15)<<1|(e[4]&128)>>7],t[7]=ye[(e[4]&124)>>2],t[8]=ye[(e[4]&3)<<3|(e[5]&224)>>5],t[9]=ye[e[5]&31],t[10]=ye[(e[6]&248)>>3],t[11]=ye[(e[6]&7)<<2|(e[7]&192)>>6],t[12]=ye[(e[7]&62)>>1],t[13]=ye[(e[7]&1)<<4|(e[8]&240)>>4],t[14]=ye[(e[8]&15)<<1|(e[9]&128)>>7],t[15]=ye[(e[9]&124)>>2],t[16]=ye[(e[9]&3)<<3|(e[10]&224)>>5],t[17]=ye[e[10]&31],t[18]=ye[(e[11]&248)>>3],t[19]=ye[(e[11]&7)<<2|(e[12]&192)>>6],t[20]=ye[(e[12]&62)>>1],t[21]=ye[(e[12]&1)<<4|(e[13]&240)>>4],t[22]=ye[(e[13]&15)<<1|(e[14]&128)>>7],t[23]=ye[(e[14]&124)>>2],t[24]=ye[(e[14]&3)<<3|(e[15]&224)>>5],t[25]=ye[e[15]&31],t.join("")}function Om(e){if(e.length!==26)throw Error(`Invalid length. Expected 26 bytes, got ${e.length}. Input: ${e}`);let n=new TextEncoder().encode(e);if(B[n[0]]===255||B[n[1]]===255||B[n[2]]===255||B[n[3]]===255||B[n[4]]===255||B[n[5]]===255||B[n[6]]===255||B[n[7]]===255||B[n[8]]===255||B[n[9]]===255||B[n[10]]===255||B[n[11]]===255||B[n[12]]===255||B[n[13]]===255||B[n[14]]===255||B[n[15]]===255||B[n[16]]===255||B[n[17]]===255||B[n[18]]===255||B[n[19]]===255||B[n[20]]===255||B[n[21]]===255||B[n[22]]===255||B[n[23]]===255||B[n[24]]===255||B[n[25]]===255)throw Error("Invalid base32 character");let r=new Uint8Array(16);return r[0]=B[n[0]]<<5|B[n[1]],r[1]=B[n[2]]<<3|B[n[3]]>>2,r[2]=(B[n[3]]&3)<<6|B[n[4]]<<1|B[n[5]]>>4,r[3]=(B[n[5]]&15)<<4|B[n[6]]>>1,r[4]=(B[n[6]]&1)<<7|B[n[7]]<<2|B[n[8]]>>3,r[5]=(B[n[8]]&7)<<5|B[n[9]],r[6]=B[n[10]]<<3|B[n[11]]>>2,r[7]=(B[n[11]]&3)<<6|B[n[12]]<<1|B[n[13]]>>4,r[8]=(B[n[13]]&15)<<4|B[n[14]]>>1,r[9]=(B[n[14]]&1)<<7|B[n[15]]<<2|B[n[16]]>>3,r[10]=(B[n[16]]&7)<<5|B[n[17]],r[11]=B[n[18]]<<3|B[n[19]]>>2,r[12]=(B[n[19]]&3)<<6|B[n[20]]<<1|B[n[21]]>>4,r[13]=(B[n[21]]&15)<<4|B[n[22]]>>1,r[14]=(B[n[22]]&1)<<7|B[n[23]]<<2|B[n[24]]>>3,r[15]=(B[n[24]]&7)<<5|B[n[25]],r}function UA(e){if(e.length>63)return!1;let t,n,r;for(n=0,r=e.length;n<r;n+=1){t=e.charCodeAt(n);let o=t>96&&t<123,i=t===95;if((n===0||n===r-1)&&!o)return!1;if(!(o||i))return!1}return!0}var jA=class extends Error{constructor(e){super(`Invalid prefix "${e}". Must be at most 63 ASCII letters [a-z_]`);this.name="InvalidPrefixError"}},VA=class extends Error{constructor(e,t){super(`Invalid TypeId. Prefix mismatch. Expected ${e}, got ${t}`);this.name="PrefixMismatchError"}},KA=class extends Error{constructor(e){super(`Invalid TypeId. Prefix cannot be empty when there's a separator: ${e}`);this.name="EmptyPrefixError"}},km=class extends Error{constructor(e){super(`Invalid length. Suffix should have 26 characters, got ${e}`);this.name="InvalidSuffixLengthError"}},qA=class extends Error{constructor(e){super(`Invalid suffix. First character "${e}" must be in the range [0-7]`);this.name="InvalidSuffixCharacterError"}},BA=class extends Error{constructor(e,t){super(`Cannot convert TypeID of type ${e} to type ${t}`);this.name="TypeIDConversionError"}};function Dm(e="",t=""){if(!UA(e))throw new jA(e);let n;if(t)n=t;else{let r=new Uint8Array(16);ls(void 0,r),n=ds(r)}if(n.length!==26)throw new km(n.length);if(n[0]>"7")throw new qA(n[0]);if(Om(n),e==="")return n;else return`${e}_${n}`}function HA(e,t){let n,r,o=e.lastIndexOf("_");if(o===-1)n="",r=e;else if(n=e.substring(0,o),r=e.substring(o+1),!n)throw new KA(e);if(!r)throw new km(0);if(t&&n!==t)throw new VA(t,n);return Dm(n,r)}function Im(e){let t=e.lastIndexOf("_");if(t===-1)return"";return e.substring(0,t)}function Nm(e){let t=e.lastIndexOf("_");if(t===-1)return e;return e.substring(t+1)}var Nt=class{constructor(e,t=""){this.prefix=e,this.suffix=t;let n=Dm(e,t);this.prefix=Im(n),this.suffix=Nm(n)}getType(){return this.prefix}getSuffix(){return this.suffix}asType(e){let t=this;if(t.prefix!==e)throw new BA(t.prefix,e);return t}toUUIDBytes(){return Om(this.suffix)}toUUID(){return Qo(this.toUUIDBytes())}toString(){if(this.prefix==="")return this.suffix;return`${this.prefix}_${this.suffix}`}static fromString(e,t){let n=HA(e,t);return new Nt(Im(n),Nm(n))}static fromUUIDBytes(e,t){let n=ds(t);return new Nt(e,n)}static fromUUID(e,t){let n=ds(FA(t));return new Nt(e,n)}};function Ur(e){let t=Object.values(e).filter((r)=>typeof r==="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function ps(e,t="|"){return e.map((n)=>gs(n)).join(t)}function jr(e,t){if(typeof t==="bigint")return t.toString();return t}class Pm{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;if(e!==void 0)this._value=e(),this._getter=void 0;return this._value}}function Vr(e){return new Pm(e)}function $m(e){return e===null||e===void 0}function ln(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Mm(e,t){let n=e/t,r=Math.round(n),o=4*Number.EPSILON*Math.max(Math.abs(n),1);if(Math.abs(n-r)<o)return 0;return n-r}function lt(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Kr(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function Kt(e){return Kr(e._zod.def)??e._zod.def.shape}function Lm(e,t,n){Object.defineProperty(e,t,{get(){let r=n();return lt(this,t,r),r},enumerable:!0,configurable:!0})}function zm(e,t,n){if(t in e)lt(e,t,n);else e[t]=n}function Nn(e,t,n,r){let o=Kt(t);for(let i of n){let a=Object.getOwnPropertyDescriptor(o,i);if(!a.enumerable)continue;if(a.get)Lm(e,i,()=>{let s=t._zod.def.shape[i];return r?r(s,i):s});else zm(e,i,r?r(a.value,i):a.value)}}function WA(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);if(!r.enumerable)continue;if(r.get)Lm(e,n,()=>t[n]);else zm(e,n,r.value)}}function dt(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function Fm(e){return JSON.stringify(e)}function Um(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var ms="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function rr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var jm=Vr(()=>{if(ot.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function On(e){if(rr(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let n=t.prototype;if(rr(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function fs(e){if(On(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var Vm=new Set(["string","number","symbol"]),Km=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Bt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function At(e,t,n){let r=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)r._zod.parent=e;return r}function q(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function gs(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function qm(e){return Object.keys(e).filter((t)=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var ti=(()=>({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]}))(),hs={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function GA(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i={};return Nn(i,e,ni(e,t)),At(e,dt(n,{shape:i,checks:[]}))}function ni(e,t){let n=Kt(e),r=[];for(let o of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,o)?.enumerable)throw Error(`Unrecognized key: "${String(o)}"`);if(t[o])r.push(o)}return r}function ZA(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=new Set(ni(e,t)),a={};return Nn(a,e,Reflect.ownKeys(Kt(e)).filter((s)=>!i.has(s))),At(e,dt(n,{shape:a,checks:[]}))}function YA(e,t){if(!On(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let o=Kt(e);for(let i of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(o,i)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return At(e,dt(e._zod.def,{shape:Bm(e,t)}))}function Bm(e,t){let n={};return Nn(n,e,Reflect.ownKeys(Kt(e))),WA(n,t),n}function JA(e,t){if(!On(t))throw Error("Invalid input to safeExtend: expected a plain object");return At(e,dt(e._zod.def,{shape:Bm(e,t)}))}function XA(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n={};Nn(n,e,Reflect.ownKeys(Kt(e))),Nn(n,t,Reflect.ownKeys(Kt(t)));let r=dt(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return At(e,r)}function Hm(e,t,n,r="partial"){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let s=n?new Set(ni(t,n)):void 0,c={};return Nn(c,t,Reflect.ownKeys(Kt(t)),e&&((d,u)=>s&&!s.has(u)?d:new e({type:"optional",innerType:d}))),At(t,dt(t._zod.def,{shape:c,checks:[]}))}function QA(e,t,n){let r=n?new Set(ni(t,n)):void 0,o={};return Nn(o,t,Reflect.ownKeys(Kt(t)),(i,a)=>r&&!r.has(a)?i:new e({type:"nonoptional",innerType:i})),At(t,dt(t._zod.def,{shape:o}))}function Ot(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Wm(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function dn(e,t){return t.map((n)=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Fr(e){return typeof e==="string"?e:e?.message}function ys(e){let t=[];for(let n of e??[]){let r=n._zod.def;if(!/_(length|size)$|_equals$/.test(r.check))break;let o=r.maximum??r.length??r.size;if(o>=0)t.push([o,n])}return t}function ri(e,t,n){var r;for(let o=t;o<e.length;o++)(r=e[o]).schema??(r.schema=n)}function kt(e,t,n){var r;let o=e.inst?._zod?.traits;if(o?.has("$ZodType"))if(o.has("$ZodCheck"))(r=e).schema??(r.schema=e.inst);else e.schema=e.inst;let i=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,a=e.message?e.message:Fr(e.inst?._zod.def?.error?.(e))??Fr(i?.(e))??Fr(t?.error?.(e))??Fr(n.customError?.(e))??Fr(n.localeError?.(e))??"Invalid input",s={};for(let c of Object.keys(e)){if(c==="inst"||c==="schema"||c==="continue"||c==="input"||c==="__proto__")continue;s[c]=e[c]}if(s.path??(s.path=[]),s.message=a,t?.reportInput)s.input=e.input;return s}var eT=/[\uD800-\uDBFF]/;function oi(e){let t=e.length;if(!eT.test(e))return t;let n=t;for(let r=0;r<t-1;r++)if((e.charCodeAt(r)&64512)===55296&&(e.charCodeAt(r+1)&64512)===56320)n--,r++;return n}function ii(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function Gm(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function kn(...e){let[t,n,r]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:r};return{...t}}function Zm(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);if(r.get)Object.defineProperty(e,n,{...r,enumerable:!1});else tT(e,n,r.value)}}function qt(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function ai(e,t,n){return qt(e,t,n,!1)}function si(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return qt(this,n,r(this))},set(o){qt(this,n,o)}})}return t}function tT(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:qt(this,t,n.bind(this))},set(r){qt(this,t,r)}})}function nT(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}var us,cn=!1,rT={configurable:!0,get(){cn=!0;return}};function ne(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&us!==e._zod){us=void 0;return}us=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,rT);let o=cn;cn=!1;try{let i=n(this);if(cn)delete this[t];else Object.defineProperty(this,t,{configurable:!0,writable:!0,value:i});return cn=cn||o,i}catch(i){throw delete this[t],cn=cn||o,i}},set(o){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:o})}})}function oT(e,t,n,r){let o=nT(e,t);if(!o)return;Object.defineProperty(o,t,{configurable:!0,get(){let i={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,i),i.value=n(this),Object.defineProperty(this,t,i),i.value},set(i){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:i})}})}var iT="~constantCatch";function Ym(e){let t=()=>e;return t[iT]=!0,t}var Jm,Qm=Object.freeze({status:"aborted"}),_s={value:void 0,enumerable:!1},Xm="captureStackTrace"in Error?Error:null;function aT(e){let t=Xm;if(t){let n=t.stackTraceLimit;if(typeof n==="number"){try{t.stackTraceLimit=0}catch{return Xm=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function w(e,t,n,r){let o={};function i(y){this.def=y,this.constr=m,this.traits=new Set}i.prototype=o;let a=n,s=a&&new WeakSet;function c(y,_){if(!y._zod){_s.value=new i(_);try{Object.defineProperty(y,"_zod",_s)}finally{_s.value=void 0}}else if(y._zod.traits.has(e))return;if(y._zod.traits.add(e),t(y,_),s){let k=Object.getPrototypeOf(y),V=y._zod.constr.prototype,G=k;while(G&&G!==V)G=Object.getPrototypeOf(G);let oe=G??k;if(!s.has(oe))s.add(oe),Zm(oe,a)}let E=m.prototype;for(let k in E){if(!Object.prototype.hasOwnProperty.call(E,k))continue;if(!(k in y))y[k]=E[k].bind(y)}}let d=r?.Parent??Object;class u extends d{}Object.defineProperty(u,"name",{value:e});function m(y){let _=r?.Parent?aT(u):this;c(_,y);let E=_._zod.deferred;if(E){for(let V of E)V();_._zod.deferred=void 0}let k=globalThis.__zod_globalConfig?.postProcessor;if(k)k(_);return _}return Object.defineProperty(m,"init",{value:c}),Object.defineProperty(m,Symbol.hasInstance,{value:(y)=>{if(r?.Parent&&y instanceof r.Parent)return!0;return y?._zod?.traits?.has(e)}}),Object.defineProperty(m,"name",{value:e}),m}class Dt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class qr extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(Jm=globalThis).__zod_globalConfig??(Jm.__zod_globalConfig={});var ot=globalThis.__zod_globalConfig;function it(e){if(e)Object.assign(ot,e);return ot}function sT(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,jr,2)),e.message}function cT(e){this._zod.message=e}var lT={get:sT,set:cT,enumerable:!0,configurable:!0},vs={value:void 0,enumerable:!1},ef=new WeakSet([Object.prototype,Error.prototype]),tf=(e,t)=>{e.name="$ZodError",vs.value=t,Object.defineProperty(e,"issues",vs),vs.value=void 0,Object.defineProperty(e,"message",lT);let n=Object.getPrototypeOf(e);if(!ef.has(n))ef.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let r=()=>this.message;return Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0})}})},nf=w("$ZodError",tf),YF=w("$ZodError",tf,void 0,{Parent:Error});function dT(e,t,n){if(!Object.prototype.hasOwnProperty.call(e,t))if(t==="__proto__")Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0});else e[t]=n();return e[t]}function Ss(e,t=(n)=>n.message){let n={},r=[];for(let o of e.issues)if(o.path.length>0)dT(n,o.path[0],()=>[]).push(t(o));else r.push(t(o));return{formErrors:r,fieldErrors:n}}function xs(e,t=(n)=>n.message){let n={_errors:[]},r=(o,i=[])=>{for(let a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map((s)=>r({issues:s},[...i,...a.path]));else if(a.code==="invalid_key")r({issues:a.issues},[...i,...a.path]);else if(a.code==="invalid_element")r({issues:a.issues},[...i,...a.path]);else{let s=[...i,...a.path];if(s.length===0)n._errors.push(t(a));else{let c=n,d=0;while(d<s.length){let u=s[d],m=d===s.length-1;if(u==="_errors"){if(m)c._errors.push(t(a));d++;continue}if(!Object.prototype.hasOwnProperty.call(c,u))Object.defineProperty(c,u,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let y=c[u];if(m)y._errors.push(t(a));c=y,d++}}}};return r(e),n}function ci(e,t){return{callee:t?.callee??e,Err:t?.Err}}var li=(e)=>{let t=(n,r,o,i)=>{let a=o?{...o,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},a);if(s instanceof Promise)throw new Dt;if(s.issues.length){let c=new(i?.Err??e)(s.issues.map((d)=>kt(d,a,it())));throw ms(c,i?.callee??t),c}return s.value};return t};var di=(e)=>{let t=async(n,r,o,i)=>{let a=o?{...o,async:!0}:{async:!0},s=n._zod.run({value:r,issues:[]},a);if(s instanceof Promise)s=await s;if(s.issues.length){let c=new(i?.Err??e)(s.issues.map((d)=>kt(d,a,it())));throw ms(c,i?.callee??t),c}return s.value};return t};var ui=(e)=>(t,n,r)=>{let o=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new Dt;return i.issues.length?rf(e,i.issues,o):{success:!0,data:i.value}};function rf(e,t,n){let r;return{success:!1,get error(){if(!r)r=new e(t.map((o)=>kt(o,n,it()))),t=void 0,n=void 0;return r},set error(o){r=o,t=void 0,n=void 0}}}var pi=(e)=>async(t,n,r)=>{let o=r?{...r,async:!0}:{async:!0},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)i=await i;return i.issues.length?rf(e,i.issues,o):{success:!0,data:i.value}};var uT=Symbol.for("zod.compile.invalid"),pT=Symbol.for("zod.compile.fallback"),Es=(e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==uT)return!0;if(r.definite===!0&&n===void 0)return!1}return mT(e,t,n)};function mT(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},o=e._zod.bag.fallbackRun,i;if(o)r[pT]=!0,i=o({value:t,issues:[]},r);else i=e._zod.run({value:t,issues:[]},r);if(i instanceof Promise)throw new Dt;return i.issues.length===0}var ws=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},o=e._zod.run({value:t,issues:[]},r);if(o instanceof Promise)o=await o;return o.issues.length===0},of=(e)=>{let t=li(e),n=(r,o,i,a)=>{let s=i?{...i,direction:"backward"}:{direction:"backward"};return t(r,o,s,ci(n,a))};return n};var af=(e)=>{let t=li(e),n=(r,o,i,a)=>t(r,o,i,ci(n,a));return n};var sf=(e)=>{let t=di(e),n=async(r,o,i,a)=>{let s=i?{...i,direction:"backward"}:{direction:"backward"};return await t(r,o,s,ci(n,a))};return n};var cf=(e)=>{let t=di(e),n=async(r,o,i,a)=>await t(r,o,i,ci(n,a));return n};var lf=(e)=>(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return ui(e)(t,n,o)};var df=(e)=>(t,n,r)=>ui(e)(t,n,r);var uf=(e)=>async(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return pi(e)(t,n,o)};var pf=(e)=>async(t,n,r)=>pi(e)(t,n,r);var mf=/^[cC][0-9a-z]{6,}$/,ff=/^[0-9a-z]+$/,gf=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,hf=/^[0-9a-vA-V]{20}$/,yf=/^[A-Za-z0-9]{27}$/,_f=/^[a-zA-Z0-9_-]{21}$/;function bf(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var vf=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Sf=/^([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})$/,As=(e)=>{if(!e)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}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var xf=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var fT="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function Ef(){return new RegExp(fT,"u")}var wf=/^(?:(?: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])$/,Cf=/^(([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}|:))$/;var Af=/^((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])$/,Tf=/^(([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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Rf=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,If=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;var Nf=/^https?$/,Of=/^\+[1-9]\d{6,14}$/;var kf="(?:(?:\\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])))";function gT(e){return new RegExp(`^${e}$`)}var Df=gT(kf);function Cs(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.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{${e.precision}}`:e.seconds?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?":"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Pf(e){return new RegExp(`^${Cs(e)}$`)}function $f(e){let t=["Z"];if(e.offset)t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${Cs({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,r=e.local?`${n}|${Cs({precision:e.precision})}`:n;return new RegExp(`^${kf}T(?:${r})$`)}var Mf=/^[\s\S]{0,}$/,Lf=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},zf=/^-?\d+n?$/,mi=/^-?\d+$/,or=/^-?\d+(?:\.\d+)?$/,Ff=/^(?:true|false)$/i,Uf=/^null$/i;var jf=/^[^A-Z]*$/,Vf=/^[^a-z]*$/;var ze=w("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])});var Ts=(e)=>{let t=e.value;return!$m(t)&&t.length!==void 0},fi={number:"number",bigint:"bigint",object:"date"},Rs=w("$ZodCheckLessThan",(e,t)=>{ze.init(e,t);let n=fi[typeof t.value];e._zod.check=(r)=>{if(t.inclusive?r.value<=t.value:r.value<t.value)return;r.issues.push({origin:fi[typeof r.value]??n,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Is=w("$ZodCheckGreaterThan",(e,t)=>{ze.init(e,t);let n=fi[typeof t.value];e._zod.check=(r)=>{if(t.inclusive?r.value>=t.value:r.value>t.value)return;r.issues.push({origin:fi[typeof r.value]??n,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Kf=w("$ZodCheckMultipleOf",(e,t)=>{ze.init(e,t),e._zod.check=(n)=>{if(typeof n.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof n.value==="bigint"?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):Mm(n.value,t.value)===0)return;n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),qf=w("$ZodCheckNumberFormat",(e,t)=>{ze.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[o,i]=ti[t.format];e._zod.check=(a)=>{let s=a.value;if(n){if(!Number.isInteger(s)){a.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){if(s>0)a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});else a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}if(s<o)a.issues.push({origin:"number",input:s,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort});if(s>i)a.issues.push({origin:"number",input:s,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}});var Bf=w("$ZodCheckMaxLength",(e,t)=>{var n;ze.init(e,t),(n=e._zod.def).when??(n.when=Ts),e._zod.check=(r)=>{let o=r.value,i=o.length;if((typeof o==="string"&&i>t.maximum?oi(o):i)<=t.maximum)return;let s=ii(o);r.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Hf=w("$ZodCheckMinLength",(e,t)=>{var n;ze.init(e,t),(n=e._zod.def).when??(n.when=Ts),e._zod.check=(r)=>{let o=r.value,i=o.length;if((typeof o==="string"&&i>=t.minimum&&i<t.minimum*2?oi(o):i)>=t.minimum)return;let s=ii(o);r.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Wf=w("$ZodCheckLengthEquals",(e,t)=>{var n;ze.init(e,t),(n=e._zod.def).when??(n.when=Ts),e._zod.check=(r)=>{let o=r.value,i=o.length,a=typeof o==="string"&&i>=t.length&&i<=t.length*2?oi(o):i;if(a===t.length)return;let s=ii(o),c=a>t.length;r.issues.push({origin:s,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Br=w("$ZodCheckStringFormat",(e,t)=>{var n,r;if(ze.init(e,t),t.pattern)(n=e._zod).check??(n.check=(o)=>{if(t.pattern.lastIndex=0,t.pattern.test(o.value))return;o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(r=e._zod).check??(r.check=()=>{})}),Gf=w("$ZodCheckRegex",(e,t)=>{Br.init(e,t),e._zod.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Zf=w("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=jf),Br.init(e,t)}),Yf=w("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Vf),Br.init(e,t)}),Jf=w("$ZodCheckIncludes",(e,t)=>{ze.init(e,t);let n=Bt(t.includes),r=new RegExp(typeof t.position==="number"?`^.{${t.position},}${n}`:n);t.pattern=r,e._zod.check=(o)=>{if(o.value.includes(t.includes,t.position))return;o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Xf=w("$ZodCheckStartsWith",(e,t)=>{ze.init(e,t);let n=new RegExp(`^${Bt(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.check=(r)=>{if(r.value.startsWith(t.prefix))return;r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),Qf=w("$ZodCheckEndsWith",(e,t)=>{ze.init(e,t);let n=new RegExp(`.*${Bt(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.check=(r)=>{if(r.value.endsWith(t.suffix))return;r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}});var eg=w("$ZodCheckOverwrite",(e,t)=>{ze.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class Ns{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
31
|
+
Check the URL: niva config set url <url>`;return`Connection error: ${e.message}`}function AA(e){let t=Ee(e);if(t==null)return` • ${String(e)}`;let n=t.path,r=Array.isArray(n)?n.join("."):"",o=t.messageKey??t.code??"invalid",i;if(typeof t.message==="string")i=t.message;else if(typeof o==="string")i=o;else i=JSON.stringify(o);return` ✗ ${r?`${r}: `:""}${i}`}function sn(e){return e instanceof Error&&"defined"in e&&"code"in e}function Tn(e){let t=String(Ee(e)?.code);if(t==="NOT_FOUND"&&Ee(e)?.defined===!1)return TA();return{code:t,message:e.message,data:Ee(Ee(e)?.data),hint:wA[t],exitCode:xA(t),retryable:EA(t)}}function TA(){return{code:"PROCEDURE_NOT_IMPLEMENTED",message:"This NIVA server does not have this command: it is newer than the deployment.",data:void 0,hint:`${`Check available compatibility at ${Ya}`} (the server's NIVA version does not offer this procedure).`,exitCode:A.USAGE_ERROR,retryable:!1}}function Rn(e){C(`Error: ${e.code} — ${e.message}`);let t=e.data?.issues;if(Array.isArray(t))for(let n of t)C(AA(n));if(e.hint!=null)P(` ${e.hint}`)}function RA(e){if(ns==="json")v({error:e.code,message:e.message,data:e.data,hint:e.hint,retryable:e.retryable});else Rn(e);process.exit(e.exitCode)}function rs(e){return e instanceof Error?CA(e,SA):String(e)}function Ct(e){if(sn(e))RA(Tn(e));let t=rs(e);if(ns==="json")v({error:"CONNECTION_ERROR",message:e instanceof Error?e.message:String(e),retryable:!0});else C(t);process.exit(A.GENERAL_ERROR)}function In(e){if(sn(e))Ct(e);let t=e instanceof Error?e.message:String(e);if(ns==="json")v({error:"STREAM_ERROR",message:t,retryable:!0});else C(`Stream error: ${t}`);process.exit(A.GENERAL_ERROR)}async function b(e){try{return await e}catch(t){Ct(t)}}function Vt(e="Not yet implemented."){P(e),process.exit(A.USAGE_ERROR)}function vm(e,t){e.command("ai").description("AI module resources").command("agents").description("List AI agents available for voice interactions").action(async()=>{let{format:r,fields:o}=S(e.opts()),i=await b(t().ai.listAgents());if(r==="json"){let a=o?i.map((s)=>O(s,o)):i;v(a);return}L(["ID","Name","Language","SIP Inbound","Description"],i.map((a)=>({ID:a.id,Name:a.name,Language:a.language,"SIP Inbound":a.sip_inbound_enabled?"enabled":"disabled",Description:a.description??"—"})))})}var l_=on(jt(),1);var Sm=/^(?:[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 IA(e){return typeof e==="string"&&Sm.test(e)}var xm=IA;var Le=[];for(let e=0;e<256;++e)Le.push((e+256).toString(16).slice(1));function os(e,t=0){return(Le[e[t+0]]+Le[e[t+1]]+Le[e[t+2]]+Le[e[t+3]]+"-"+Le[e[t+4]]+Le[e[t+5]]+"-"+Le[e[t+6]]+Le[e[t+7]]+"-"+Le[e[t+8]]+Le[e[t+9]]+"-"+Le[e[t+10]]+Le[e[t+11]]+Le[e[t+12]]+Le[e[t+13]]+Le[e[t+14]]+Le[e[t+15]]).toLowerCase()}function OA(e,t=0){let n=os(e,t);if(!xm(n))throw TypeError("Stringified UUID is invalid");return n}var Xo=OA;var NA=new Uint8Array(16);function Qo(){return crypto.getRandomValues(NA)}var is={};function kA(e,t,n){let r;if(e)r=Em(e.random??e.rng?.()??Qo(),e.msecs,e.seq,t,n);else{let o=Date.now(),i=Qo();DA(is,o,i),r=Em(i,is.msecs,is.seq,t,n)}return t??os(r)}function DA(e,t,n){if(e.msecs??=-1/0,e.seq??=0,t>e.msecs)e.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],e.msecs=t;else if(e.seq=e.seq+1|0,e.seq===0)e.msecs++;return e}function Em(e,t,n,r,o=0){if(e.length<16)throw Error("Random bytes length must be >= 16");if(!r)r=new Uint8Array(16),o=0;else if(o<0||o+16>r.length)throw RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`);return t??=Date.now(),n??=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9],r[o++]=t/1099511627776&255,r[o++]=t/4294967296&255,r[o++]=t/16777216&255,r[o++]=t/65536&255,r[o++]=t/256&255,r[o++]=t&255,r[o++]=112|n>>>28&15,r[o++]=n>>>20&255,r[o++]=128|n>>>14&63,r[o++]=n>>>6&255,r[o++]=n<<2&255|e[10]&3,r[o++]=e[11],r[o++]=e[12],r[o++]=e[13],r[o++]=e[14],r[o++]=e[15],r}var as=kA;function PA(e){let t,n=new Uint8Array(16);return n[0]=(t=parseInt(e.slice(0,8),16))>>>24,n[1]=t>>>16&255,n[2]=t>>>8&255,n[3]=t&255,n[4]=(t=parseInt(e.slice(9,13),16))>>>8,n[5]=t&255,n[6]=(t=parseInt(e.slice(14,18),16))>>>8,n[7]=t&255,n[8]=(t=parseInt(e.slice(19,23),16))>>>8,n[9]=t&255,n[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,n[11]=t/4294967296&255,n[12]=t>>>24&255,n[13]=t>>>16&255,n[14]=t>>>8&255,n[15]=t&255,n}var ye="0123456789abcdefghjkmnpqrstvwxyz",B=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 ss(e){let t=Array(26).fill("");if(e.length!==16)throw Error(`Invalid length. Expected 16 bytes, got ${e.length}. Input: ${e}`);return t[0]=ye[(e[0]&224)>>5],t[1]=ye[e[0]&31],t[2]=ye[(e[1]&248)>>3],t[3]=ye[(e[1]&7)<<2|(e[2]&192)>>6],t[4]=ye[(e[2]&62)>>1],t[5]=ye[(e[2]&1)<<4|(e[3]&240)>>4],t[6]=ye[(e[3]&15)<<1|(e[4]&128)>>7],t[7]=ye[(e[4]&124)>>2],t[8]=ye[(e[4]&3)<<3|(e[5]&224)>>5],t[9]=ye[e[5]&31],t[10]=ye[(e[6]&248)>>3],t[11]=ye[(e[6]&7)<<2|(e[7]&192)>>6],t[12]=ye[(e[7]&62)>>1],t[13]=ye[(e[7]&1)<<4|(e[8]&240)>>4],t[14]=ye[(e[8]&15)<<1|(e[9]&128)>>7],t[15]=ye[(e[9]&124)>>2],t[16]=ye[(e[9]&3)<<3|(e[10]&224)>>5],t[17]=ye[e[10]&31],t[18]=ye[(e[11]&248)>>3],t[19]=ye[(e[11]&7)<<2|(e[12]&192)>>6],t[20]=ye[(e[12]&62)>>1],t[21]=ye[(e[12]&1)<<4|(e[13]&240)>>4],t[22]=ye[(e[13]&15)<<1|(e[14]&128)>>7],t[23]=ye[(e[14]&124)>>2],t[24]=ye[(e[14]&3)<<3|(e[15]&224)>>5],t[25]=ye[e[15]&31],t.join("")}function Am(e){if(e.length!==26)throw Error(`Invalid length. Expected 26 bytes, got ${e.length}. Input: ${e}`);let n=new TextEncoder().encode(e);if(B[n[0]]===255||B[n[1]]===255||B[n[2]]===255||B[n[3]]===255||B[n[4]]===255||B[n[5]]===255||B[n[6]]===255||B[n[7]]===255||B[n[8]]===255||B[n[9]]===255||B[n[10]]===255||B[n[11]]===255||B[n[12]]===255||B[n[13]]===255||B[n[14]]===255||B[n[15]]===255||B[n[16]]===255||B[n[17]]===255||B[n[18]]===255||B[n[19]]===255||B[n[20]]===255||B[n[21]]===255||B[n[22]]===255||B[n[23]]===255||B[n[24]]===255||B[n[25]]===255)throw Error("Invalid base32 character");let r=new Uint8Array(16);return r[0]=B[n[0]]<<5|B[n[1]],r[1]=B[n[2]]<<3|B[n[3]]>>2,r[2]=(B[n[3]]&3)<<6|B[n[4]]<<1|B[n[5]]>>4,r[3]=(B[n[5]]&15)<<4|B[n[6]]>>1,r[4]=(B[n[6]]&1)<<7|B[n[7]]<<2|B[n[8]]>>3,r[5]=(B[n[8]]&7)<<5|B[n[9]],r[6]=B[n[10]]<<3|B[n[11]]>>2,r[7]=(B[n[11]]&3)<<6|B[n[12]]<<1|B[n[13]]>>4,r[8]=(B[n[13]]&15)<<4|B[n[14]]>>1,r[9]=(B[n[14]]&1)<<7|B[n[15]]<<2|B[n[16]]>>3,r[10]=(B[n[16]]&7)<<5|B[n[17]],r[11]=B[n[18]]<<3|B[n[19]]>>2,r[12]=(B[n[19]]&3)<<6|B[n[20]]<<1|B[n[21]]>>4,r[13]=(B[n[21]]&15)<<4|B[n[22]]>>1,r[14]=(B[n[22]]&1)<<7|B[n[23]]<<2|B[n[24]]>>3,r[15]=(B[n[24]]&7)<<5|B[n[25]],r}function $A(e){if(e.length>63)return!1;let t,n,r;for(n=0,r=e.length;n<r;n+=1){t=e.charCodeAt(n);let o=t>96&&t<123,i=t===95;if((n===0||n===r-1)&&!o)return!1;if(!(o||i))return!1}return!0}var MA=class extends Error{constructor(e){super(`Invalid prefix "${e}". Must be at most 63 ASCII letters [a-z_]`);this.name="InvalidPrefixError"}},LA=class extends Error{constructor(e,t){super(`Invalid TypeId. Prefix mismatch. Expected ${e}, got ${t}`);this.name="PrefixMismatchError"}},zA=class extends Error{constructor(e){super(`Invalid TypeId. Prefix cannot be empty when there's a separator: ${e}`);this.name="EmptyPrefixError"}},Tm=class extends Error{constructor(e){super(`Invalid length. Suffix should have 26 characters, got ${e}`);this.name="InvalidSuffixLengthError"}},FA=class extends Error{constructor(e){super(`Invalid suffix. First character "${e}" must be in the range [0-7]`);this.name="InvalidSuffixCharacterError"}},UA=class extends Error{constructor(e,t){super(`Cannot convert TypeID of type ${e} to type ${t}`);this.name="TypeIDConversionError"}};function Rm(e="",t=""){if(!$A(e))throw new MA(e);let n;if(t)n=t;else{let r=new Uint8Array(16);as(void 0,r),n=ss(r)}if(n.length!==26)throw new Tm(n.length);if(n[0]>"7")throw new FA(n[0]);if(Am(n),e==="")return n;else return`${e}_${n}`}function jA(e,t){let n,r,o=e.lastIndexOf("_");if(o===-1)n="",r=e;else if(n=e.substring(0,o),r=e.substring(o+1),!n)throw new zA(e);if(!r)throw new Tm(0);if(t&&n!==t)throw new LA(t,n);return Rm(n,r)}function wm(e){let t=e.lastIndexOf("_");if(t===-1)return"";return e.substring(0,t)}function Cm(e){let t=e.lastIndexOf("_");if(t===-1)return e;return e.substring(t+1)}var Ot=class{constructor(e,t=""){this.prefix=e,this.suffix=t;let n=Rm(e,t);this.prefix=wm(n),this.suffix=Cm(n)}getType(){return this.prefix}getSuffix(){return this.suffix}asType(e){let t=this;if(t.prefix!==e)throw new UA(t.prefix,e);return t}toUUIDBytes(){return Am(this.suffix)}toUUID(){return Xo(this.toUUIDBytes())}toString(){if(this.prefix==="")return this.suffix;return`${this.prefix}_${this.suffix}`}static fromString(e,t){let n=jA(e,t);return new Ot(wm(n),Cm(n))}static fromUUIDBytes(e,t){let n=ss(t);return new Ot(e,n)}static fromUUID(e,t){let n=ss(PA(t));return new Ot(e,n)}};function Ur(e){let t=Object.values(e).filter((r)=>typeof r==="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function ls(e,t="|"){return e.map((n)=>ps(n)).join(t)}function jr(e,t){if(typeof t==="bigint")return t.toString();return t}class Im{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;if(e!==void 0)this._value=e(),this._getter=void 0;return this._value}}function Vr(e){return new Im(e)}function Om(e){return e===null||e===void 0}function ln(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Nm(e,t){let n=e/t,r=Math.round(n),o=4*Number.EPSILON*Math.max(Math.abs(n),1);if(Math.abs(n-r)<o)return 0;return n-r}function lt(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Kr(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function Kt(e){return Kr(e._zod.def)??e._zod.def.shape}function km(e,t,n){Object.defineProperty(e,t,{get(){let r=n();return lt(this,t,r),r},enumerable:!0,configurable:!0})}function Dm(e,t,n){if(t in e)lt(e,t,n);else e[t]=n}function On(e,t,n,r){let o=Kt(t);for(let i of n){let a=Object.getOwnPropertyDescriptor(o,i);if(!a.enumerable)continue;if(a.get)km(e,i,()=>{let s=t._zod.def.shape[i];return r?r(s,i):s});else Dm(e,i,r?r(a.value,i):a.value)}}function VA(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);if(!r.enumerable)continue;if(r.get)km(e,n,()=>t[n]);else Dm(e,n,r.value)}}function dt(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function Pm(e){return JSON.stringify(e)}function $m(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var ds="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function rr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Mm=Vr(()=>{if(rt.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Nn(e){if(rr(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let n=t.prototype;if(rr(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function us(e){if(Nn(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var Lm=new Set(["string","number","symbol"]),zm=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Bt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function At(e,t,n){let r=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)r._zod.parent=e;return r}function q(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function ps(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function Fm(e){return Object.keys(e).filter((t)=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var ei=(()=>({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]}))(),ms={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function KA(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i={};return On(i,e,ti(e,t)),At(e,dt(n,{shape:i,checks:[]}))}function ti(e,t){let n=Kt(e),r=[];for(let o of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,o)?.enumerable)throw Error(`Unrecognized key: "${String(o)}"`);if(t[o])r.push(o)}return r}function qA(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=new Set(ti(e,t)),a={};return On(a,e,Reflect.ownKeys(Kt(e)).filter((s)=>!i.has(s))),At(e,dt(n,{shape:a,checks:[]}))}function BA(e,t){if(!Nn(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let o=Kt(e);for(let i of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(o,i)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return At(e,dt(e._zod.def,{shape:Um(e,t)}))}function Um(e,t){let n={};return On(n,e,Reflect.ownKeys(Kt(e))),VA(n,t),n}function HA(e,t){if(!Nn(t))throw Error("Invalid input to safeExtend: expected a plain object");return At(e,dt(e._zod.def,{shape:Um(e,t)}))}function WA(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n={};On(n,e,Reflect.ownKeys(Kt(e))),On(n,t,Reflect.ownKeys(Kt(t)));let r=dt(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return At(e,r)}function jm(e,t,n,r="partial"){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let s=n?new Set(ti(t,n)):void 0,c={};return On(c,t,Reflect.ownKeys(Kt(t)),e&&((d,u)=>s&&!s.has(u)?d:new e({type:"optional",innerType:d}))),At(t,dt(t._zod.def,{shape:c,checks:[]}))}function GA(e,t,n){let r=n?new Set(ti(t,n)):void 0,o={};return On(o,t,Reflect.ownKeys(Kt(t)),(i,a)=>r&&!r.has(a)?i:new e({type:"nonoptional",innerType:i})),At(t,dt(t._zod.def,{shape:o}))}function Nt(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Vm(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function dn(e,t){return t.map((n)=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Fr(e){return typeof e==="string"?e:e?.message}function fs(e){let t=[];for(let n of e??[]){let r=n._zod.def;if(!/_(length|size)$|_equals$/.test(r.check))break;let o=r.maximum??r.length??r.size;if(o>=0)t.push([o,n])}return t}function ni(e,t,n){var r;for(let o=t;o<e.length;o++)(r=e[o]).schema??(r.schema=n)}function kt(e,t,n){var r;let o=e.inst?._zod?.traits;if(o?.has("$ZodType"))if(o.has("$ZodCheck"))(r=e).schema??(r.schema=e.inst);else e.schema=e.inst;let i=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,a=e.message?e.message:Fr(e.inst?._zod.def?.error?.(e))??Fr(i?.(e))??Fr(t?.error?.(e))??Fr(n.customError?.(e))??Fr(n.localeError?.(e))??"Invalid input",s={};for(let c of Object.keys(e)){if(c==="inst"||c==="schema"||c==="continue"||c==="input"||c==="__proto__")continue;s[c]=e[c]}if(s.path??(s.path=[]),s.message=a,t?.reportInput)s.input=e.input;return s}var ZA=/[\uD800-\uDBFF]/;function ri(e){let t=e.length;if(!ZA.test(e))return t;let n=t;for(let r=0;r<t-1;r++)if((e.charCodeAt(r)&64512)===55296&&(e.charCodeAt(r+1)&64512)===56320)n--,r++;return n}function oi(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function Km(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function kn(...e){let[t,n,r]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:r};return{...t}}function qm(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);if(r.get)Object.defineProperty(e,n,{...r,enumerable:!1});else YA(e,n,r.value)}}function qt(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function ii(e,t,n){return qt(e,t,n,!1)}function ai(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return qt(this,n,r(this))},set(o){qt(this,n,o)}})}return t}function YA(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:qt(this,t,n.bind(this))},set(r){qt(this,t,r)}})}function JA(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}var cs,cn=!1,XA={configurable:!0,get(){cn=!0;return}};function te(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&cs!==e._zod){cs=void 0;return}cs=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,XA);let o=cn;cn=!1;try{let i=n(this);if(cn)delete this[t];else Object.defineProperty(this,t,{configurable:!0,writable:!0,value:i});return cn=cn||o,i}catch(i){throw delete this[t],cn=cn||o,i}},set(o){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:o})}})}function QA(e,t,n,r){let o=JA(e,t);if(!o)return;Object.defineProperty(o,t,{configurable:!0,get(){let i={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,i),i.value=n(this),Object.defineProperty(this,t,i),i.value},set(i){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:i})}})}var eT="~constantCatch";function Bm(e){let t=()=>e;return t[eT]=!0,t}var Hm,Gm=Object.freeze({status:"aborted"}),gs={value:void 0,enumerable:!1},Wm="captureStackTrace"in Error?Error:null;function tT(e){let t=Wm;if(t){let n=t.stackTraceLimit;if(typeof n==="number"){try{t.stackTraceLimit=0}catch{return Wm=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function w(e,t,n,r){let o={};function i(y){this.def=y,this.constr=m,this.traits=new Set}i.prototype=o;let a=n,s=a&&new WeakSet;function c(y,_){if(!y._zod){gs.value=new i(_);try{Object.defineProperty(y,"_zod",gs)}finally{gs.value=void 0}}else if(y._zod.traits.has(e))return;if(y._zod.traits.add(e),t(y,_),s){let k=Object.getPrototypeOf(y),V=y._zod.constr.prototype,G=k;while(G&&G!==V)G=Object.getPrototypeOf(G);let re=G??k;if(!s.has(re))s.add(re),qm(re,a)}let E=m.prototype;for(let k in E){if(!Object.prototype.hasOwnProperty.call(E,k))continue;if(!(k in y))y[k]=E[k].bind(y)}}let d=r?.Parent??Object;class u extends d{}Object.defineProperty(u,"name",{value:e});function m(y){let _=r?.Parent?tT(u):this;c(_,y);let E=_._zod.deferred;if(E){for(let V of E)V();_._zod.deferred=void 0}let k=globalThis.__zod_globalConfig?.postProcessor;if(k)k(_);return _}return Object.defineProperty(m,"init",{value:c}),Object.defineProperty(m,Symbol.hasInstance,{value:(y)=>{if(r?.Parent&&y instanceof r.Parent)return!0;return y?._zod?.traits?.has(e)}}),Object.defineProperty(m,"name",{value:e}),m}class Dt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class qr extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(Hm=globalThis).__zod_globalConfig??(Hm.__zod_globalConfig={});var rt=globalThis.__zod_globalConfig;function ot(e){if(e)Object.assign(rt,e);return rt}function nT(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,jr,2)),e.message}function rT(e){this._zod.message=e}var oT={get:nT,set:rT,enumerable:!0,configurable:!0},ys={value:void 0,enumerable:!1},Zm=new WeakSet([Object.prototype,Error.prototype]),Ym=(e,t)=>{e.name="$ZodError",ys.value=t,Object.defineProperty(e,"issues",ys),ys.value=void 0,Object.defineProperty(e,"message",oT);let n=Object.getPrototypeOf(e);if(!Zm.has(n))Zm.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let r=()=>this.message;return Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0})}})},Jm=w("$ZodError",Ym),GF=w("$ZodError",Ym,void 0,{Parent:Error});function iT(e,t,n){if(!Object.prototype.hasOwnProperty.call(e,t))if(t==="__proto__")Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0});else e[t]=n();return e[t]}function _s(e,t=(n)=>n.message){let n={},r=[];for(let o of e.issues)if(o.path.length>0)iT(n,o.path[0],()=>[]).push(t(o));else r.push(t(o));return{formErrors:r,fieldErrors:n}}function bs(e,t=(n)=>n.message){let n={_errors:[]},r=(o,i=[])=>{for(let a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map((s)=>r({issues:s},[...i,...a.path]));else if(a.code==="invalid_key")r({issues:a.issues},[...i,...a.path]);else if(a.code==="invalid_element")r({issues:a.issues},[...i,...a.path]);else{let s=[...i,...a.path];if(s.length===0)n._errors.push(t(a));else{let c=n,d=0;while(d<s.length){let u=s[d],m=d===s.length-1;if(u==="_errors"){if(m)c._errors.push(t(a));d++;continue}if(!Object.prototype.hasOwnProperty.call(c,u))Object.defineProperty(c,u,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let y=c[u];if(m)y._errors.push(t(a));c=y,d++}}}};return r(e),n}function si(e,t){return{callee:t?.callee??e,Err:t?.Err}}var ci=(e)=>{let t=(n,r,o,i)=>{let a=o?{...o,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},a);if(s instanceof Promise)throw new Dt;if(s.issues.length){let c=new(i?.Err??e)(s.issues.map((d)=>kt(d,a,ot())));throw ds(c,i?.callee??t),c}return s.value};return t};var li=(e)=>{let t=async(n,r,o,i)=>{let a=o?{...o,async:!0}:{async:!0},s=n._zod.run({value:r,issues:[]},a);if(s instanceof Promise)s=await s;if(s.issues.length){let c=new(i?.Err??e)(s.issues.map((d)=>kt(d,a,ot())));throw ds(c,i?.callee??t),c}return s.value};return t};var di=(e)=>(t,n,r)=>{let o=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new Dt;return i.issues.length?Xm(e,i.issues,o):{success:!0,data:i.value}};function Xm(e,t,n){let r;return{success:!1,get error(){if(!r)r=new e(t.map((o)=>kt(o,n,ot()))),t=void 0,n=void 0;return r},set error(o){r=o,t=void 0,n=void 0}}}var ui=(e)=>async(t,n,r)=>{let o=r?{...r,async:!0}:{async:!0},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)i=await i;return i.issues.length?Xm(e,i.issues,o):{success:!0,data:i.value}};var aT=Symbol.for("zod.compile.invalid"),sT=Symbol.for("zod.compile.fallback"),vs=(e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==aT)return!0;if(r.definite===!0&&n===void 0)return!1}return cT(e,t,n)};function cT(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},o=e._zod.bag.fallbackRun,i;if(o)r[sT]=!0,i=o({value:t,issues:[]},r);else i=e._zod.run({value:t,issues:[]},r);if(i instanceof Promise)throw new Dt;return i.issues.length===0}var Ss=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},o=e._zod.run({value:t,issues:[]},r);if(o instanceof Promise)o=await o;return o.issues.length===0},Qm=(e)=>{let t=ci(e),n=(r,o,i,a)=>{let s=i?{...i,direction:"backward"}:{direction:"backward"};return t(r,o,s,si(n,a))};return n};var ef=(e)=>{let t=ci(e),n=(r,o,i,a)=>t(r,o,i,si(n,a));return n};var tf=(e)=>{let t=li(e),n=async(r,o,i,a)=>{let s=i?{...i,direction:"backward"}:{direction:"backward"};return await t(r,o,s,si(n,a))};return n};var nf=(e)=>{let t=li(e),n=async(r,o,i,a)=>await t(r,o,i,si(n,a));return n};var rf=(e)=>(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return di(e)(t,n,o)};var of=(e)=>(t,n,r)=>di(e)(t,n,r);var af=(e)=>async(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return ui(e)(t,n,o)};var sf=(e)=>async(t,n,r)=>ui(e)(t,n,r);var cf=/^[cC][0-9a-z]{6,}$/,lf=/^[0-9a-z]+$/,df=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,uf=/^[0-9a-vA-V]{20}$/,pf=/^[A-Za-z0-9]{27}$/,mf=/^[a-zA-Z0-9_-]{21}$/;function ff(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var gf=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var hf=/^([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})$/,Es=(e)=>{if(!e)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}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var yf=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var lT="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function _f(){return new RegExp(lT,"u")}var bf=/^(?:(?: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])$/,vf=/^(([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}|:))$/;var Sf=/^((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])$/,xf=/^(([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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ef=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,wf=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;var Cf=/^https?$/,Af=/^\+[1-9]\d{6,14}$/;var Tf="(?:(?:\\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])))";function dT(e){return new RegExp(`^${e}$`)}var Rf=dT(Tf);function xs(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.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{${e.precision}}`:e.seconds?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?":"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function If(e){return new RegExp(`^${xs(e)}$`)}function Of(e){let t=["Z"];if(e.offset)t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${xs({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,r=e.local?`${n}|${xs({precision:e.precision})}`:n;return new RegExp(`^${Tf}T(?:${r})$`)}var Nf=/^[\s\S]{0,}$/,kf=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Df=/^-?\d+n?$/,pi=/^-?\d+$/,or=/^-?\d+(?:\.\d+)?$/,Pf=/^(?:true|false)$/i,$f=/^null$/i;var Mf=/^[^A-Z]*$/,Lf=/^[^a-z]*$/;var ze=w("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])});var ws=(e)=>{let t=e.value;return!Om(t)&&t.length!==void 0},mi={number:"number",bigint:"bigint",object:"date"},Cs=w("$ZodCheckLessThan",(e,t)=>{ze.init(e,t);let n=mi[typeof t.value];e._zod.check=(r)=>{if(t.inclusive?r.value<=t.value:r.value<t.value)return;r.issues.push({origin:mi[typeof r.value]??n,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),As=w("$ZodCheckGreaterThan",(e,t)=>{ze.init(e,t);let n=mi[typeof t.value];e._zod.check=(r)=>{if(t.inclusive?r.value>=t.value:r.value>t.value)return;r.issues.push({origin:mi[typeof r.value]??n,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),zf=w("$ZodCheckMultipleOf",(e,t)=>{ze.init(e,t),e._zod.check=(n)=>{if(typeof n.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof n.value==="bigint"?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):Nm(n.value,t.value)===0)return;n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Ff=w("$ZodCheckNumberFormat",(e,t)=>{ze.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[o,i]=ei[t.format];e._zod.check=(a)=>{let s=a.value;if(n){if(!Number.isInteger(s)){a.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){if(s>0)a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});else a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}if(s<o)a.issues.push({origin:"number",input:s,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort});if(s>i)a.issues.push({origin:"number",input:s,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}});var Uf=w("$ZodCheckMaxLength",(e,t)=>{var n;ze.init(e,t),(n=e._zod.def).when??(n.when=ws),e._zod.check=(r)=>{let o=r.value,i=o.length;if((typeof o==="string"&&i>t.maximum?ri(o):i)<=t.maximum)return;let s=oi(o);r.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),jf=w("$ZodCheckMinLength",(e,t)=>{var n;ze.init(e,t),(n=e._zod.def).when??(n.when=ws),e._zod.check=(r)=>{let o=r.value,i=o.length;if((typeof o==="string"&&i>=t.minimum&&i<t.minimum*2?ri(o):i)>=t.minimum)return;let s=oi(o);r.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Vf=w("$ZodCheckLengthEquals",(e,t)=>{var n;ze.init(e,t),(n=e._zod.def).when??(n.when=ws),e._zod.check=(r)=>{let o=r.value,i=o.length,a=typeof o==="string"&&i>=t.length&&i<=t.length*2?ri(o):i;if(a===t.length)return;let s=oi(o),c=a>t.length;r.issues.push({origin:s,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Br=w("$ZodCheckStringFormat",(e,t)=>{var n,r;if(ze.init(e,t),t.pattern)(n=e._zod).check??(n.check=(o)=>{if(t.pattern.lastIndex=0,t.pattern.test(o.value))return;o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(r=e._zod).check??(r.check=()=>{})}),Kf=w("$ZodCheckRegex",(e,t)=>{Br.init(e,t),e._zod.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),qf=w("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Mf),Br.init(e,t)}),Bf=w("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Lf),Br.init(e,t)}),Hf=w("$ZodCheckIncludes",(e,t)=>{ze.init(e,t);let n=Bt(t.includes),r=new RegExp(typeof t.position==="number"?`^.{${t.position},}${n}`:n);t.pattern=r,e._zod.check=(o)=>{if(o.value.includes(t.includes,t.position))return;o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Wf=w("$ZodCheckStartsWith",(e,t)=>{ze.init(e,t);let n=new RegExp(`^${Bt(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.check=(r)=>{if(r.value.startsWith(t.prefix))return;r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),Gf=w("$ZodCheckEndsWith",(e,t)=>{ze.init(e,t);let n=new RegExp(`.*${Bt(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.check=(r)=>{if(r.value.endsWith(t.suffix))return;r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}});var Zf=w("$ZodCheckOverwrite",(e,t)=>{ze.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class Ts{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
32
32
|
`).filter((i)=>i),r=Math.min(...n.map((i)=>i.length-i.trimStart().length)),o=n.map((i)=>i.slice(r)).map((i)=>" ".repeat(this.indent*2)+i);for(let i of o)this.content.push(i)}compile(){let e=Function,t=this?.content??[""];return new e(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
|
|
33
33
|
${t.join(`
|
|
34
34
|
`)}
|
|
35
|
-
};`)(...Object.values(this.closed))}}var ng={major:4,minor:6,patch:7};var ue=w("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ng;let r=e._zod.def.checks,o=e._zod.traits.has("$ZodCheck")?[e,...r??[]]:r?.length?[...r]:[];for(let i of o)for(let a of i._zod.onattach)a(e);if(o.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let i=(s,c,d)=>{if(s.memo)return s;let u=Ot(s),m;for(let y of c){if(y._zod.def.when){if(Wm(s))continue;if(!y._zod.def.when(s))continue}else if(u)continue;let _=s.issues.length,E=y._zod.check(s);if(E instanceof Promise&&d?.async===!1)throw new Dt;if(m||E instanceof Promise)m=(m??Promise.resolve()).then(async()=>{if(await E,s.issues.length===_)return;if(ri(s.issues,_,e),!u)u=Ot(s,_)});else{if(s.issues.length===_)continue;if(ri(s.issues,_,e),!u)u=Ot(s,_)}}if(m)return m.then(()=>s);return s},a=(s,c,d)=>{if(Ot(s))return s.aborted=!0,s;let u=i(c,o,d);if(u instanceof Promise){if(d.async===!1)throw new Dt;return u.then((m)=>e._zod.parse(m,d))}return e._zod.parse(u,d)};e._zod.run=(s,c)=>{if(c.skipChecks)return e._zod.parse(s,c);if(c.direction==="backward"){let u=e._zod.parse({value:s.value,issues:[]},{...c,skipChecks:!0});if(u instanceof Promise)return u.then((m)=>a(m,s,c));return a(u,s,c)}let d=e._zod.parse(s,c);if(d instanceof Promise){if(c.async===!1)throw new Dt;return d.then((u)=>i(u,o,c))}return i(d,o,c)}}},{get "~standard"(){return ai(this,"~standard",Ds(this))},set "~standard"(e){qt(this,"~standard",e)}}),mg=(e,t)=>e.issues.length?{issues:e.issues.map((n)=>kt(n,t,it()))}:{value:e.value};async function hT(e,t){let n={async:!0};return mg(await e._zod.run({value:t,issues:[]},n),n)}function Ds(e){return{validate:(t)=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return mg(r,n)}catch(r){}return hT(e,t)},vendor:"zod",version:1}}var _i=w("$ZodString",(e,t)=>{ue.init(e,t),e._zod.pattern=t.pattern??Mf,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(o){}if(typeof n.value==="string")return n;return n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),be=w("$ZodStringFormat",(e,t)=>{Br.init(e,t),_i.init(e,t)}),fg=w("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Sf),be.init(e,t)}),gg=w("$ZodUUID",(e,t)=>{if(t.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=As(r))}else t.pattern??(t.pattern=As());be.init(e,t)}),hg=w("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=xf),be.init(e,t)}),yg=1,hi=2;function _g(e){try{if(typeof URL<"u"&&typeof URL.canParse==="function")return URL.canParse(e);return new URL(e),!0}catch{return!1}}function yT(e,t){if(!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t))return _g(e)||hi;return _T(e,t)}function _T(e,t){if(!t.normalize&&t.protocol?.source===Nf.source&&!/^https?:\/\//i.test(e))return yg;try{if(typeof URL<"u"){let n=URL;if(typeof n.parse==="function")return n.parse(e)??hi}return new URL(e)}catch{return hi}}var bT=/[\t\n\r]/g;function rg(e){return e.replace(bT,"")}function vT(e,t){return t.lastIndex=0,t.test(e.hostname)}function ST(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}var bg=w("$ZodURL",(e,t)=>{be.init(e,t),e._zod.check=(n)=>{try{let r=n.value.trim(),o=yT(r,t);if(o===yg){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}if(o===hi){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort});return}if(o===!0){n.value=rg(r);return}if(t.hostname&&!vT(o,t.hostname))n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort});if(t.protocol&&!ST(o,t.protocol))n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort});n.value=t.normalize?o.href:rg(r);return}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),vg=w("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Ef()),be.init(e,t)}),Sg=w("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?_f:bf(t.length)),be.init(e,t)}),xg=w("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=mf),be.init(e,t)}),Eg=w("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=ff),be.init(e,t)}),wg=w("$ZodULID",(e,t)=>{t.pattern??(t.pattern=gf),be.init(e,t)}),Cg=w("$ZodXID",(e,t)=>{t.pattern??(t.pattern=hf),be.init(e,t)}),Ag=w("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=yf),be.init(e,t)}),Tg=w("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=$f(t)),be.init(e,t)}),Rg=w("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Df),be.init(e,t)}),Ig=w("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Pf(t)),be.init(e,t)}),Ng=w("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=vf),be.init(e,t)}),Og=w("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=wf),be.init(e,t)}),xT=/^[0-9a-fA-F:.]+$/;function kg(e){if(!xT.test(e))return!1;return _g(`http://[${e}]`)}var Dg=w("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Cf),be.init(e,t),e._zod.check=(n)=>{if(!kg(n.value))n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}});var Pg=w("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Af),be.init(e,t)});function ET(e){let t=e.split("/");if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let o=Number(r);if(`${o}`!==r)return!1;if(o<0||o>128)return!1;return kg(n)}var $g=w("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Tf),be.init(e,t),e._zod.check=(n)=>{if(!ET(n.value))n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function Mg(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Ps=/^[0-9a-zA-Z+/]*={0,2}$/,Lg=w("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Ps),be.init(e,t),e._zod.check=(n)=>{if(Mg(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),bi=/^[A-Za-z0-9_-]*$/;function wT(e){if(!bi.test(e))return!1;let t=e.replace(/[-_]/g,(r)=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Mg(n)}var zg=w("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=bi),be.init(e,t),e._zod.check=(n)=>{if(wT(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Fg=w("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Of),be.init(e,t)});function CT(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));if("typ"in o&&o?.typ!=="JWT")return!1;if(!o.alg)return!1;if(t&&(!("alg"in o)||o.alg!==t))return!1;return!0}catch{return!1}}var Ug=w("$ZodJWT",(e,t)=>{be.init(e,t),e._zod.check=(n)=>{if(CT(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}});var $s=w("$ZodNumber",(e,t)=>{ue.init(e,t),e._zod.pattern=or,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(a){}let o=n.value;if(typeof o==="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let i=typeof o==="number"?Number.isNaN(o)?"NaN":!Number.isFinite(o)?String(o):void 0:void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),n}}),jg=w("$ZodNumberFormat",(e,t)=>{qf.init(e,t),$s.init(e,t)}),Vg=w("$ZodBoolean",(e,t)=>{ue.init(e,t),e._zod.pattern=Ff,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(i){}let o=n.value;if(typeof o==="boolean")return n;return n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),Kg=w("$ZodBigInt",(e,t)=>{ue.init(e,t),e._zod.pattern=zf,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=BigInt(n.value)}catch(o){}if(typeof n.value==="bigint")return n;return n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:e}),n}});var qg=w("$ZodNull",(e,t)=>{ue.init(e,t),e._zod.pattern=Uf,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{let o=n.value;if(o===null)return n;return n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}});var Bg=w("$ZodUnknown",(e,t)=>{ue.init(e,t),e._zod.parse=(n)=>n}),Hg=w("$ZodNever",(e,t)=>{ue.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});var Wg=w("$ZodDate",(e,t)=>{ue.init(e,t),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=new Date(n.value)}catch(s){}let o=n.value,i=o instanceof Date;if(i&&!Number.isNaN(o.getTime()))return n;return n.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:e}),n}});function AT(e,t){let n=ys(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map((i)=>i[0])),o=e._zod.parse;e._zod.parse=(i,a)=>{let s=t(i.value);if(s>r&&!a?.skipChecks&&a?.direction!=="backward"){for(let[c,d]of ys(e._zod.def.checks))if(s>c&&d._zod.def.when(i)){let u=i.issues.length;return d._zod.check(i),i.issues[u].continue=!1,ri(i.issues,u,e),i}}return o(i,a)}}var TT=(e)=>Array.isArray(e)?e.length:-1;function og(e,t,n){if(e.issues.length)t.issues.push(...dn(n,e.issues));t.value[n]=e.value}var Gg=w("$ZodArray",(e,t)=>{ue.init(e,t);let n=ot.memoizer;n?.attach(e),e._zod.parse=(r,o)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=n?n.alloc(e,r,Array(i.length),o):Array(i.length);let a=[],s=o?.abortEarly;for(let c=0;c<i.length;c++){let d=i[c],u=t.element._zod.run({value:d,issues:[]},o);if(u instanceof Promise)a.push(u.then((m)=>og(m,r,c)));else if(og(u,r,c),s&&u.issues.length!==0&&Ot(u))break}if(a.length)return Promise.all(a).then(()=>r);return r},AT(e,TT)});function yi(e,t,n,r,o,i){let a=n in r,s=i==="optional";if(!a&&s&&o==="optional")return;if(e.issues.length){if(o!==void 0&&s&&!a)return;t.issues.push(...dn(n,e.issues))}if(!a&&o===void 0){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}if(e.value===void 0){if(a||o==="defaulted"&&!s)t.value[n]=void 0}else t.value[n]=e.value}var RT=[];function Zg(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:RT,o=r.length?[...t,...r]:t;for(let a of o)if(!e.shape?.[a]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(a)}": expected a Zod schema`);let i=qm(e.shape);return{...e,allKeys:o,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(i)}}function Yg(e,t,n,r,o,i,a){let s=[],c=o.keySet,d=o.catchall._zod,u=d.def.type,{optin:m,optout:y}=d,_=0;for(let E in t){if(a&&n.issues.length!==_){if(Ot(n,_))break;_=n.issues.length}if(c.has(E))continue;if(E==="__proto__"){if(u==="never")s.push(E);continue}if(u==="never"){s.push(E);continue}let k=d.run({value:t[E],issues:[]},r);if(k instanceof Promise)e.push(k.then((V)=>yi(V,n,E,t,m,y)));else yi(k,n,E,t,m,y)}if(s.length)n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i,continue:!0});if(!e.length)return n;return Promise.all(e).then(()=>n)}var IT=w("$ZodObject",(e,t)=>{ue.init(e,t);let n=Object.getOwnPropertyDescriptor(t,"shape"),r=n?.get?n.get.raw:t.shape??{};if(r){let d=()=>{let u={...r};return Object.defineProperty(t,"shape",{value:u}),d.raw=u,u};d.raw=r,Object.defineProperty(t,"shape",{get:d})}let o=Vr(()=>Zg(t));ne(e,"propValues",(d)=>{let u=d.def.shape,m={};for(let y in u){let _=u[y]._zod;if(_.values){if(!Object.prototype.hasOwnProperty.call(m,y))lt(m,y,new Set);for(let E of _.values)m[y].add(E);if(_.optin!==void 0)m[y].add(void 0)}}return m});let i=rr,a=t.catchall,s,c=ot.memoizer;c?.attach(e),e._zod.parse=(d,u)=>{s??(s=o.value);let m=d.value;if(!i(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),d;d.value=c?c.alloc(e,d,{},u):{};let y=[],_=s.shape,E=u?.abortEarly,k=d.issues.length;for(let V of s.allKeys){if(E&&d.issues.length!==k){if(Ot(d,k))break;k=d.issues.length}if(V==="__proto__")continue;let G=_[V],oe=G._zod.optin,ct=G._zod.optout,nt=G._zod.run({value:m[V],issues:[]},u);if(nt instanceof Promise)y.push(nt.then((ge)=>yi(ge,d,V,m,oe,ct)));else yi(nt,d,V,m,oe,ct)}if(!a)return y.length?Promise.all(y).then(()=>d):d;return Yg(y,m,d,u,o.value,e,E===!0)}}),Jg=w("$ZodObjectJIT",(e,t)=>{IT.init(e,t);let n=e._zod.parse,r=Vr(()=>Zg(t)),o=ot.memoizer,i=(_)=>{let E=r.value,k=E.symbolKeys,V=new Ns(["payload","ctx"],{shape:_,inst:e,memo:o,syms:k}),G=(ge)=>`shape[${ge}]._zod.run({ value: input[${ge}], issues: [] }, ctx)`,oe=(ge,Q)=>`
|
|
36
|
-
let ${
|
|
37
|
-
for (let i = 0; i < ${
|
|
38
|
-
const iss = ${
|
|
39
|
-
iss.path = iss.path ? [${
|
|
35
|
+
};`)(...Object.values(this.closed))}}var Jf={major:4,minor:6,patch:7};var de=w("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Jf;let r=e._zod.def.checks,o=e._zod.traits.has("$ZodCheck")?[e,...r??[]]:r?.length?[...r]:[];for(let i of o)for(let a of i._zod.onattach)a(e);if(o.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let i=(s,c,d)=>{if(s.memo)return s;let u=Nt(s),m;for(let y of c){if(y._zod.def.when){if(Vm(s))continue;if(!y._zod.def.when(s))continue}else if(u)continue;let _=s.issues.length,E=y._zod.check(s);if(E instanceof Promise&&d?.async===!1)throw new Dt;if(m||E instanceof Promise)m=(m??Promise.resolve()).then(async()=>{if(await E,s.issues.length===_)return;if(ni(s.issues,_,e),!u)u=Nt(s,_)});else{if(s.issues.length===_)continue;if(ni(s.issues,_,e),!u)u=Nt(s,_)}}if(m)return m.then(()=>s);return s},a=(s,c,d)=>{if(Nt(s))return s.aborted=!0,s;let u=i(c,o,d);if(u instanceof Promise){if(d.async===!1)throw new Dt;return u.then((m)=>e._zod.parse(m,d))}return e._zod.parse(u,d)};e._zod.run=(s,c)=>{if(c.skipChecks)return e._zod.parse(s,c);if(c.direction==="backward"){let u=e._zod.parse({value:s.value,issues:[]},{...c,skipChecks:!0});if(u instanceof Promise)return u.then((m)=>a(m,s,c));return a(u,s,c)}let d=e._zod.parse(s,c);if(d instanceof Promise){if(c.async===!1)throw new Dt;return d.then((u)=>i(u,o,c))}return i(d,o,c)}}},{get "~standard"(){return ii(this,"~standard",Os(this))},set "~standard"(e){qt(this,"~standard",e)}}),cg=(e,t)=>e.issues.length?{issues:e.issues.map((n)=>kt(n,t,ot()))}:{value:e.value};async function uT(e,t){let n={async:!0};return cg(await e._zod.run({value:t,issues:[]},n),n)}function Os(e){return{validate:(t)=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return cg(r,n)}catch(r){}return uT(e,t)},vendor:"zod",version:1}}var yi=w("$ZodString",(e,t)=>{de.init(e,t),e._zod.pattern=t.pattern??Nf,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(o){}if(typeof n.value==="string")return n;return n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),be=w("$ZodStringFormat",(e,t)=>{Br.init(e,t),yi.init(e,t)}),lg=w("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=hf),be.init(e,t)}),dg=w("$ZodUUID",(e,t)=>{if(t.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Es(r))}else t.pattern??(t.pattern=Es());be.init(e,t)}),ug=w("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=yf),be.init(e,t)}),pg=1,gi=2;function mg(e){try{if(typeof URL<"u"&&typeof URL.canParse==="function")return URL.canParse(e);return new URL(e),!0}catch{return!1}}function pT(e,t){if(!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t))return mg(e)||gi;return mT(e,t)}function mT(e,t){if(!t.normalize&&t.protocol?.source===Cf.source&&!/^https?:\/\//i.test(e))return pg;try{if(typeof URL<"u"){let n=URL;if(typeof n.parse==="function")return n.parse(e)??gi}return new URL(e)}catch{return gi}}var fT=/[\t\n\r]/g;function Xf(e){return e.replace(fT,"")}function gT(e,t){return t.lastIndex=0,t.test(e.hostname)}function hT(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}var fg=w("$ZodURL",(e,t)=>{be.init(e,t),e._zod.check=(n)=>{try{let r=n.value.trim(),o=pT(r,t);if(o===pg){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}if(o===gi){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort});return}if(o===!0){n.value=Xf(r);return}if(t.hostname&&!gT(o,t.hostname))n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort});if(t.protocol&&!hT(o,t.protocol))n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort});n.value=t.normalize?o.href:Xf(r);return}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),gg=w("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=_f()),be.init(e,t)}),hg=w("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?mf:ff(t.length)),be.init(e,t)}),yg=w("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=cf),be.init(e,t)}),_g=w("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=lf),be.init(e,t)}),bg=w("$ZodULID",(e,t)=>{t.pattern??(t.pattern=df),be.init(e,t)}),vg=w("$ZodXID",(e,t)=>{t.pattern??(t.pattern=uf),be.init(e,t)}),Sg=w("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=pf),be.init(e,t)}),xg=w("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Of(t)),be.init(e,t)}),Eg=w("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Rf),be.init(e,t)}),wg=w("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=If(t)),be.init(e,t)}),Cg=w("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=gf),be.init(e,t)}),Ag=w("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=bf),be.init(e,t)}),yT=/^[0-9a-fA-F:.]+$/;function Tg(e){if(!yT.test(e))return!1;return mg(`http://[${e}]`)}var Rg=w("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=vf),be.init(e,t),e._zod.check=(n)=>{if(!Tg(n.value))n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}});var Ig=w("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Sf),be.init(e,t)});function _T(e){let t=e.split("/");if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let o=Number(r);if(`${o}`!==r)return!1;if(o<0||o>128)return!1;return Tg(n)}var Og=w("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=xf),be.init(e,t),e._zod.check=(n)=>{if(!_T(n.value))n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function Ng(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Ns=/^[0-9a-zA-Z+/]*={0,2}$/,kg=w("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Ns),be.init(e,t),e._zod.check=(n)=>{if(Ng(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),_i=/^[A-Za-z0-9_-]*$/;function bT(e){if(!_i.test(e))return!1;let t=e.replace(/[-_]/g,(r)=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Ng(n)}var Dg=w("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=_i),be.init(e,t),e._zod.check=(n)=>{if(bT(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Pg=w("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Af),be.init(e,t)});function vT(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));if("typ"in o&&o?.typ!=="JWT")return!1;if(!o.alg)return!1;if(t&&(!("alg"in o)||o.alg!==t))return!1;return!0}catch{return!1}}var $g=w("$ZodJWT",(e,t)=>{be.init(e,t),e._zod.check=(n)=>{if(vT(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}});var ks=w("$ZodNumber",(e,t)=>{de.init(e,t),e._zod.pattern=or,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(a){}let o=n.value;if(typeof o==="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let i=typeof o==="number"?Number.isNaN(o)?"NaN":!Number.isFinite(o)?String(o):void 0:void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),n}}),Mg=w("$ZodNumberFormat",(e,t)=>{Ff.init(e,t),ks.init(e,t)}),Lg=w("$ZodBoolean",(e,t)=>{de.init(e,t),e._zod.pattern=Pf,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(i){}let o=n.value;if(typeof o==="boolean")return n;return n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),zg=w("$ZodBigInt",(e,t)=>{de.init(e,t),e._zod.pattern=Df,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=BigInt(n.value)}catch(o){}if(typeof n.value==="bigint")return n;return n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:e}),n}});var Fg=w("$ZodNull",(e,t)=>{de.init(e,t),e._zod.pattern=$f,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{let o=n.value;if(o===null)return n;return n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}});var Ug=w("$ZodUnknown",(e,t)=>{de.init(e,t),e._zod.parse=(n)=>n}),jg=w("$ZodNever",(e,t)=>{de.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});var Vg=w("$ZodDate",(e,t)=>{de.init(e,t),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=new Date(n.value)}catch(s){}let o=n.value,i=o instanceof Date;if(i&&!Number.isNaN(o.getTime()))return n;return n.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:e}),n}});function ST(e,t){let n=fs(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map((i)=>i[0])),o=e._zod.parse;e._zod.parse=(i,a)=>{let s=t(i.value);if(s>r&&!a?.skipChecks&&a?.direction!=="backward"){for(let[c,d]of fs(e._zod.def.checks))if(s>c&&d._zod.def.when(i)){let u=i.issues.length;return d._zod.check(i),i.issues[u].continue=!1,ni(i.issues,u,e),i}}return o(i,a)}}var xT=(e)=>Array.isArray(e)?e.length:-1;function Qf(e,t,n){if(e.issues.length)t.issues.push(...dn(n,e.issues));t.value[n]=e.value}var Kg=w("$ZodArray",(e,t)=>{de.init(e,t);let n=rt.memoizer;n?.attach(e),e._zod.parse=(r,o)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=n?n.alloc(e,r,Array(i.length),o):Array(i.length);let a=[],s=o?.abortEarly;for(let c=0;c<i.length;c++){let d=i[c],u=t.element._zod.run({value:d,issues:[]},o);if(u instanceof Promise)a.push(u.then((m)=>Qf(m,r,c)));else if(Qf(u,r,c),s&&u.issues.length!==0&&Nt(u))break}if(a.length)return Promise.all(a).then(()=>r);return r},ST(e,xT)});function hi(e,t,n,r,o,i){let a=n in r,s=i==="optional";if(!a&&s&&o==="optional")return;if(e.issues.length){if(o!==void 0&&s&&!a)return;t.issues.push(...dn(n,e.issues))}if(!a&&o===void 0){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}if(e.value===void 0){if(a||o==="defaulted"&&!s)t.value[n]=void 0}else t.value[n]=e.value}var ET=[];function qg(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:ET,o=r.length?[...t,...r]:t;for(let a of o)if(!e.shape?.[a]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(a)}": expected a Zod schema`);let i=Fm(e.shape);return{...e,allKeys:o,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(i)}}function Bg(e,t,n,r,o,i,a){let s=[],c=o.keySet,d=o.catchall._zod,u=d.def.type,{optin:m,optout:y}=d,_=0;for(let E in t){if(a&&n.issues.length!==_){if(Nt(n,_))break;_=n.issues.length}if(c.has(E))continue;if(E==="__proto__"){if(u==="never")s.push(E);continue}if(u==="never"){s.push(E);continue}let k=d.run({value:t[E],issues:[]},r);if(k instanceof Promise)e.push(k.then((V)=>hi(V,n,E,t,m,y)));else hi(k,n,E,t,m,y)}if(s.length)n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i,continue:!0});if(!e.length)return n;return Promise.all(e).then(()=>n)}var wT=w("$ZodObject",(e,t)=>{de.init(e,t);let n=Object.getOwnPropertyDescriptor(t,"shape"),r=n?.get?n.get.raw:t.shape??{};if(r){let d=()=>{let u={...r};return Object.defineProperty(t,"shape",{value:u}),d.raw=u,u};d.raw=r,Object.defineProperty(t,"shape",{get:d})}let o=Vr(()=>qg(t));te(e,"propValues",(d)=>{let u=d.def.shape,m={};for(let y in u){let _=u[y]._zod;if(_.values){if(!Object.prototype.hasOwnProperty.call(m,y))lt(m,y,new Set);for(let E of _.values)m[y].add(E);if(_.optin!==void 0)m[y].add(void 0)}}return m});let i=rr,a=t.catchall,s,c=rt.memoizer;c?.attach(e),e._zod.parse=(d,u)=>{s??(s=o.value);let m=d.value;if(!i(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),d;d.value=c?c.alloc(e,d,{},u):{};let y=[],_=s.shape,E=u?.abortEarly,k=d.issues.length;for(let V of s.allKeys){if(E&&d.issues.length!==k){if(Nt(d,k))break;k=d.issues.length}if(V==="__proto__")continue;let G=_[V],re=G._zod.optin,ct=G._zod.optout,tt=G._zod.run({value:m[V],issues:[]},u);if(tt instanceof Promise)y.push(tt.then((fe)=>hi(fe,d,V,m,re,ct)));else hi(tt,d,V,m,re,ct)}if(!a)return y.length?Promise.all(y).then(()=>d):d;return Bg(y,m,d,u,o.value,e,E===!0)}}),Hg=w("$ZodObjectJIT",(e,t)=>{wT.init(e,t);let n=e._zod.parse,r=Vr(()=>qg(t)),o=rt.memoizer,i=(_)=>{let E=r.value,k=E.symbolKeys,V=new Ts(["payload","ctx"],{shape:_,inst:e,memo:o,syms:k}),G=(fe)=>`shape[${fe}]._zod.run({ value: input[${fe}], issues: [] }, ctx)`,re=(fe,X)=>`
|
|
36
|
+
let ${fe}_ab = false;
|
|
37
|
+
for (let i = 0; i < ${fe}.issues.length; i++) {
|
|
38
|
+
const iss = ${fe}.issues[i];
|
|
39
|
+
iss.path = iss.path ? [${X}, ...iss.path] : [${X}];
|
|
40
40
|
payload.issues.push(iss);
|
|
41
|
-
if (iss.continue !== true) ${
|
|
41
|
+
if (iss.continue !== true) ${fe}_ab = true;
|
|
42
42
|
}
|
|
43
|
-
if (${
|
|
43
|
+
if (${fe}_ab && ctx && ctx.abortEarly) {
|
|
44
44
|
payload.value = newResult;
|
|
45
45
|
return payload;
|
|
46
|
-
}`;V.write("const input = payload.value;");let ct=Object.create(null),
|
|
47
|
-
const ${
|
|
48
|
-
if (!${
|
|
49
|
-
if (${
|
|
46
|
+
}`;V.write("const input = payload.value;");let ct=Object.create(null),tt=0;for(let fe of E.allKeys)ct[fe]=`key_${tt++}`;V.write(o?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let fe of E.allKeys){if(fe==="__proto__")continue;let X=ct[fe],Ge=typeof fe==="symbol"?`syms[${k.indexOf(fe)}]`:Pm(fe),rn=`${Ge} in input`,tr=_[fe],vn=tr?._zod?.optin,It=vn!==void 0,Uo=tr?._zod?.optout==="optional";if(V.write(`const ${X} = ${G(Ge)};`),It&&Uo){let Ze=vn==="optional"?`${X}_present`:`${X}.value !== undefined || ${X}_present`;V.write(`
|
|
47
|
+
const ${X}_present = ${rn};
|
|
48
|
+
if (!${X}.issues.length || ${X}_present) {
|
|
49
|
+
if (${X}.issues.length) {${re(X,Ge)}
|
|
50
50
|
}
|
|
51
51
|
|
|
52
52
|
if (${Ze}) {
|
|
53
|
-
newResult[${Ge}] = ${
|
|
53
|
+
newResult[${Ge}] = ${X}.value;
|
|
54
54
|
}
|
|
55
55
|
}
|
|
56
56
|
|
|
57
57
|
`)}else if(!It)V.write(`
|
|
58
|
-
const ${
|
|
59
|
-
if (${
|
|
58
|
+
const ${X}_present = ${rn};
|
|
59
|
+
if (${X}.issues.length) {${re(X,Ge)}
|
|
60
60
|
}
|
|
61
|
-
if (!${
|
|
61
|
+
if (!${X}_present && !${X}.issues.length) {
|
|
62
62
|
payload.issues.push({
|
|
63
63
|
code: "invalid_type",
|
|
64
64
|
expected: "nonoptional",
|
|
@@ -71,54 +71,54 @@ ${t.join(`
|
|
|
71
71
|
}
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
-
if (${
|
|
75
|
-
newResult[${Ge}] = ${
|
|
74
|
+
if (${X}_present) {
|
|
75
|
+
newResult[${Ge}] = ${X}.value;
|
|
76
76
|
}
|
|
77
77
|
|
|
78
78
|
`);else if(V.write(`
|
|
79
|
-
if (${
|
|
79
|
+
if (${X}.issues.length) {${re(X,Ge)}
|
|
80
80
|
}
|
|
81
|
-
`),vn==="defaulted")V.write(`newResult[${Ge}] = ${
|
|
82
|
-
if (${
|
|
83
|
-
newResult[${Ge}] = ${
|
|
81
|
+
`),vn==="defaulted")V.write(`newResult[${Ge}] = ${X}.value;`);else V.write(`
|
|
82
|
+
if (${X}.value !== undefined || ${rn}) {
|
|
83
|
+
newResult[${Ge}] = ${X}.value;
|
|
84
84
|
}
|
|
85
|
-
`)}return V.write("payload.value = newResult;"),V.write("return payload;"),V.compile()},a,s=rr,c=!ot.jitless,u=c&&jm.value,m=t.catchall,y;e._zod.parse=(_,E)=>{y??(y=r.value);let k=_.value;if(!s(k))return _.issues.push({expected:"object",code:"invalid_type",input:k,inst:e}),_;if(c&&u&&E?.async===!1&&E.jitless!==!0){if(!a)a=i(t.shape);if(_=a(_,E),!m)return _;return Yg([],k,_,E,y,e,E?.abortEarly===!0)}return n(_,E)}});function ig(e,t,n,r){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let o=e.filter((i)=>!Ot(i));if(o.length===1)return t.value=o[0].value,o[0];return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((i)=>i.issues.map((a)=>kt(a,r,it())))}),t}var Ms=w("$ZodUnion",(e,t)=>{ue.init(e,t),ne(e,"optin",(r)=>r.def.options.some((o)=>o._zod.optin==="defaulted")?"defaulted":r.def.options.some((o)=>o._zod.optin!==void 0)?"optional":void 0),ne(e,"optout",(r)=>r.def.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),ne(e,"values",(r)=>{if(r.def.options.every((o)=>o._zod.values))return new Set(r.def.options.flatMap((o)=>Array.from(o._zod.values)));return}),ne(e,"pattern",(r)=>{if(r.def.options.every((o)=>o._zod.pattern)){let o=r.def.options.map((i)=>i._zod.pattern);return new RegExp(`^(${o.map((i)=>ln(i.source)).join("|")})$`)}return});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,o)=>{if(n)return n(r,o);let i=!1,a=[];for(let s of t.options){let c=s._zod.run({value:r.value,issues:[]},o);if(c instanceof Promise)a.push(c),i=!0;else{if(c.issues.length===0)return c;a.push(c)}}if(!i)return ig(a,r,e,o);return Promise.all(a).then((s)=>ig(s,r,e,o))}});function NT(e){let t=new Map;for(let n of e.options){let r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let o of r)if(t.has(o)){if(o!==void 0)throw Error(`Duplicate discriminator value "${String(o)}"`);t.set(o,null)}else t.set(o,n)}return t}var Xg=w("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Ms.init(e,t);let n=e._zod.parse;ne(e,"propValues",(o)=>{let i={},a=0;for(let s of o.def.options){let c=s._zod.propValues;if(!c||Object.keys(c).length===0)throw Error(`Invalid discriminated union option at index "${o.def.options.indexOf(s)}"`);if(c[o.def.discriminator]?.has(void 0))a++;for(let[d,u]of Object.entries(c)){if(!Object.prototype.hasOwnProperty.call(i,d))lt(i,d,new Set);for(let m of u)i[d].add(m)}}if(!o.def.unionFallback&&a>1)i[o.def.discriminator]?.delete(void 0);return i}),t.options.forEach((o,i)=>{let a=Kr(o._zod.def);if(a&&!Object.prototype.hasOwnProperty.call(a,t.discriminator))throw Error(`Invalid discriminated union option at index "${i}"`)});let r=Vr(()=>NT(t));e._zod.parse=(o,i)=>{let a=o.value;if(!rr(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;let s=a?.[t.discriminator],c=r.value.get(s);if(c&&(s!==void 0||i.direction!=="backward"))return c._zod.run(o,i);if(t.unionFallback||i.direction==="backward")return n(o,i);return o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(r.value.keys()).filter((d)=>r.value.get(d)!==null),input:a,path:[t.discriminator],inst:e}),o}}),Qg=w("$ZodIntersection",(e,t)=>{ue.init(e,t),e._zod.parse=(n,r)=>{let o=n.value,i=t.left._zod.run({value:o,issues:[]},r),a=t.right._zod.run({value:o,issues:[]},r);if(i instanceof Promise||a instanceof Promise)return Promise.all([i,a]).then(([c,d])=>ag(n,c,d));return ag(n,i,a)}});function Os(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(On(e)&&On(t)){let n=Object.keys(t),r=Object.keys(e).filter((i)=>n.indexOf(i)!==-1),o={...e,...t};if(Object.prototype.hasOwnProperty.call(o,"__proto__"))delete o.__proto__;for(let i of r){if(i==="__proto__")continue;let a=Os(e[i],t[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};o[i]=a.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let o=e[r],i=t[r],a=Os(o,i);if(!a.valid)return{valid:!1,mergeErrorPath:[r,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function ag(e,t,n){let r=new Map,o,i=new Map,a=(d,u)=>{let m;if(d.code==="unrecognized_keys"&&!d.path?.length)o??(o=d),m=d.keys;else if(d.code==="invalid_key"&&d.origin==="record"&&d.path?.length===1){let y=String(d.path[0]);if(!i.has(y))i.set(y,d);m=[y]}else return!1;for(let y of m){if(!r.has(y))r.set(y,{});r.get(y)[u]=!0}return!0};for(let d of t.issues)if(!a(d,"l"))e.issues.push(d);for(let d of n.issues)if(!a(d,"r"))e.issues.push(d);let s=[...r].filter(([,d])=>d.l&&d.r).map(([d])=>d);if(s.length){let d=o?s.filter((u)=>o.keys.includes(u)):[];if(d.length)e.issues.push({...o,keys:d});for(let u of s)if(!d.includes(u)&&i.has(u))e.issues.push(i.get(u))}let c=Os(t.value,n.value);if(!c.valid){if(Ot(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var eh=w("$ZodRecord",(e,t)=>{ue.init(e,t);let n=ot.memoizer;n?.attach(e),e._zod.parse=(r,o)=>{let i=r.value;if(!On(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),r;let a=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},o):{};let c=new Set;for(let u of s)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){if(c.add(typeof u==="number"?u.toString():u),u==="__proto__")continue;let m=t.keyType._zod.run({value:u,issues:[]},o);if(m instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(m.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:m.issues.map((E)=>kt(E,o,it())),input:u,path:[u],inst:e});continue}let y=m.value;if(y==="__proto__")continue;let _=t.valueType._zod.run({value:i[u],issues:[]},o);if(_ instanceof Promise)a.push(_.then((E)=>{if(E.issues.length)r.issues.push(...dn(u,E.issues));r.value[y]=E.value}));else{if(_.issues.length)r.issues.push(...dn(u,_.issues));r.value[y]=_.value}}let d;for(let u in i)if(!c.has(u))if(t.mode==="loose"){if(u==="__proto__")continue;r.value[u]=i[u]}else d=d??[],d.push(u);if(d&&d.length>0)r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:d,continue:!0})}else{r.value=n?n.alloc(e,r,{},o):{};let c;for(let d of Reflect.ownKeys(i)){if(d==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(i,d))continue;let u=t.keyType._zod.run({value:d,issues:[]},o);if(u instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof d==="string"&&or.test(d)&&u.issues.length){let E=t.keyType._zod.run({value:Number(d),issues:[]},o);if(E instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(E.issues.length===0)u=E}if(u.issues.length){if(t.mode==="loose")r.value[d]=i[d];else if(s)c=c??[],c.push(d);else r.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map((E)=>kt(E,o,it())),input:d,path:[d],inst:e});continue}let y=u.value;if(y==="__proto__")continue;let _=t.valueType._zod.run({value:i[d],issues:[]},o);if(_ instanceof Promise)a.push(_.then((E)=>{if(E.issues.length)r.issues.push(...dn(d,E.issues));r.value[y]=E.value}));else{if(_.issues.length)r.issues.push(...dn(d,_.issues));r.value[y]=_.value}}if(c&&c.length>0)r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:c,continue:!0})}if(a.length)return Promise.all(a).then(()=>r);return r}});var th=w("$ZodEnum",(e,t)=>{ue.init(e,t);let n=Ur(t.entries),r=new Set(n);e._zod.values=r,ne(e,"pattern",(o)=>{let i=Ur(o.def.entries).filter((a)=>Vm.has(typeof a));return new RegExp(i.length?`^(${i.map((a)=>Bt(a.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(o,i)=>{let a=o.value;if(r.has(a))return o;return o.issues.push({code:"invalid_value",values:n,input:a,inst:e}),o}}),nh=w("$ZodLiteral",(e,t)=>{ue.init(e,t);let n=new Set(t.values);e._zod.values=n,ne(e,"pattern",(r)=>{let o=r.def.values;return new RegExp(o.length?`^(${o.map((i)=>typeof i==="string"?Bt(i):i?Bt(i.toString()):String(i)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(r,o)=>{let i=r.value;if(n.has(i))return r;return r.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),r}});var rh=w("$ZodTransform",(e,t)=>{ue.init(e,t),e._zod.optin="optional",ot.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new qr(e.constructor.name);let o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then((a)=>(n.value=a,n));if(o instanceof Promise)throw new Dt;return n.value=o,n}});function sg(e,t){return e.value=t.issues.length?void 0:t.value,e}var Ls=w("$ZodOptional",(e,t)=>{ue.init(e,t),ne(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",ne(e,"values",(n)=>{let r=n.def.innerType._zod.values;return r?new Set([...r,void 0]):void 0}),ne(e,"pattern",(n)=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${ln(r.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(n.value===void 0){if(t.innerType._zod.optin!=="defaulted")return n;let o=t.innerType._zod.run({value:n.value,issues:[]},r);if(o instanceof Promise)return o.then((i)=>sg(n,i));return sg(n,o)}return t.innerType._zod.run(n,r)}}),oh=w("$ZodExactOptional",(e,t)=>{Ls.init(e,t),ne(e,"values",(n)=>n.def.innerType._zod.values),ne(e,"pattern",(n)=>n.def.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),ih=w("$ZodNullable",(e,t)=>{ue.init(e,t),ne(e,"optin",(n)=>n.def.innerType._zod.optin),ne(e,"optout",(n)=>n.def.innerType._zod.optout),ne(e,"pattern",(n)=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${ln(r.source)}|null)$`):void 0}),ne(e,"values",(n)=>n.def.innerType._zod.values?new Set([...n.def.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>{if(n.value===null)return n;return t.innerType._zod.run(n,r)}}),ah=w("$ZodDefault",(e,t)=>{ue.init(e,t),e._zod.optin="defaulted",ne(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;let o=t.innerType._zod.run(n,r);if(o instanceof Promise)return o.then((i)=>cg(i,t));return cg(o,t)}});function cg(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var sh=w("$ZodPrefault",(e,t)=>{ue.init(e,t),e._zod.optin="defaulted",ne(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)n.value=t.defaultValue;return t.innerType._zod.run(n,r)}}),ch=w("$ZodNonOptional",(e,t)=>{ue.init(e,t),ne(e,"values",(n)=>{let r=n.def.innerType._zod.values;return r?new Set([...r].filter((o)=>o!==void 0)):void 0}),e._zod.parse=(n,r)=>{let o=t.innerType._zod.run(n,r);if(o instanceof Promise)return o.then((i)=>lg(i,e));return lg(o,e)}});function lg(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}function dg(e,t,n,r){if(!t.issues.length){if(e.value=t.value,t.memo)e.memo=!0;return e}return e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map((o)=>kt(o,r,it()))},input:e.value}),e}var lh=w("$ZodCatch",(e,t)=>{ue.init(e,t),ne(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),ne(e,"optout",(n)=>n.def.innerType._zod.optout),ne(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let o=t.innerType._zod.run({value:n.value,issues:[]},r);if(o instanceof Promise)return o.then((i)=>dg(n,i,t,r));return dg(n,o,t,r)}});var dh=w("$ZodPipe",(e,t)=>{ue.init(e,t),ne(e,"values",(n)=>n.def.in._zod.values),ne(e,"optin",(n)=>n.def.in._zod.optin),ne(e,"optout",(n)=>n.def.out._zod.optout),ne(e,"propValues",(n)=>n.def.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){let i=t.out._zod.run(n,r);if(i instanceof Promise)return i.then((a)=>gi(a,t.in,r));return gi(i,t.in,r)}let o=t.in._zod.run(n,r);if(o instanceof Promise)return o.then((i)=>gi(i,t.out,r));return gi(o,t.out,r)}});function gi(e,t,n){if(e.issues.some((r)=>r.code!=="unrecognized_keys"))return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},n)}var uh=w("$ZodReadonly",(e,t)=>{ue.init(e,t),ne(e,"propValues",(n)=>n.def.innerType._zod.propValues),ne(e,"values",(n)=>n.def.innerType._zod.values),ne(e,"optin",(n)=>n.def.innerType?._zod?.optin),ne(e,"optout",(n)=>n.def.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let o=t.innerType._zod.run(n,r);if(o instanceof Promise)return o.then(ug);return ug(o)}});function ug(e){if(!e.memo)e.value=Object.freeze(e.value);return e}function OT(e){let t=e._zod.def,n=t.pattern,r=!!t.format?.includes("int"),o,i;for(let s of t.checks??[]){let c=s._zod.def;if(c.pattern)n=c.pattern;r||(r=!!c.format?.includes("int"));let d=c.minimum??c.length,u=c.maximum??c.length;if(d!==void 0&&(o===void 0||d>o))o=d;if(u!==void 0&&(i===void 0||u<i))i=u}if(n)return n.source;if(o!==void 0&&i!==void 0&&o>i)return"(?!)";if(o!==void 0||i!==void 0)return Lf({minimum:o,maximum:i}).source;let a=e._zod.pattern;return(r&&a===or?mi:a)?.source}function ks(e){let t=e._zod.def,n=e._zod.pattern?.source,r=t.innerType??e._zod.innerType;if(r){let o=r._zod.pattern?.source,i=ks(r);if(n&&o&&i&&i!==o)return n.replace(ln(o),()=>ln(i));return n}if(t.options){let o=t.options.map(ks);if(o.every(Boolean))return`^(${o.map((i)=>ln(i)).join("|")})$`}return OT(e)}var ph=w("$ZodTemplateLiteral",(e,t)=>{ue.init(e,t);let n=[];for(let r of t.parts)if(typeof r==="object"&&r!==null){let o=ks(r);if(!o)throw Error(`Invalid template literal part, no pattern found: ${[...r._zod.traits].shift()}`);n.push(ln(o))}else if(r===null||Km.has(typeof r))n.push(Bt(`${r}`));else throw Error(`Invalid template literal part: ${r}`);e._zod.pattern=new RegExp(`^${n.join("")}$`),e._zod.parse=(r,o)=>{if(typeof r.value!=="string")return r.issues.push({input:r.value,inst:e,expected:"string",code:"invalid_type"}),r;if(e._zod.pattern.lastIndex=0,!e._zod.pattern.test(r.value))return r.issues.push({input:r.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),r;return r}});var mh=w("$ZodCustom",(e,t)=>{ze.init(e,t),ue.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=(n)=>{let r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then((i)=>pg(i,n,r,e));pg(o,n,r,e);return}});function pg(e,t,n,r){if(!e){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};if(r._zod.def.params)o.params=r._zod.def.params;t.issues.push(kn(o))}}class gh extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}}var Fs="~memo",fh=[];function hh(e){return e!==null&&typeof e==="object"}function zs(e){return e.map((t)=>t.path?{...t,path:t.path.slice()}:{...t})}var yh=new WeakMap,Hr=0,xi=1,Wr=2;function Ei(e,t,n){let r=yh.get(e);if(r!==void 0)return r?Wr:Hr;if(t.has(e))return Wr;t.add(e);let o=Hr,i=(u)=>{if(o!==Wr&&u?._zod){let m=Ei(u,t,n);if(m>o)o=m}},a=(u,m)=>{let y=Hr;for(let _ of Reflect.ownKeys(u)){let E=Object.getOwnPropertyDescriptor(u,_);if(m&&!E.enumerable)continue;let k=E.get?xi:E.value?._zod?Ei(E.value,t,n):Hr;if(k>y)y=k}return y},s=(u)=>{if(u>o)o=u},c=e._zod.def,d=c.type;switch(d){case"object":{let u=Kr(c);s(u?a(u,!0):xi),i(c.catchall);break}case"array":i(c.element);break;case"tuple":for(let u of c.items)i(u);i(c.rest);break;case"record":case"map":i(c.keyType),i(c.valueType);break;case"set":i(c.valueType);break;case"union":for(let u of c.options)i(u);break;case"intersection":i(c.left),i(c.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":i(c.innerType);break;case"pipe":i(c.in),i(c.out);break;case"function":i(c.input),i(c.output);break;case"lazy":{let u=c._cachedInner??(n?e._zod.innerType:void 0);s(u?Ei(u,t,!1):xi);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let u in c){let m=Object.getOwnPropertyDescriptor(c,u);if(!m||m.get)continue;let y=m.value;if(!y||typeof y!=="object")continue;if(y._zod)i(y);else if(Array.isArray(y))for(let _ of y)i(_)}}return t.delete(e),kT(e,o)}function kT(e,t){if(t!==xi)yh.set(e,t===Wr);return t}function DT(e,t){let n=e.buckets.get(t);if(!n)n=new WeakMap,e.buckets.set(t,n);return n}var vi,Si=[],PT={alloc(e,t,n){let r=vi;if(!r)return n;vi=void 0;let o={value:n,issues:null};return r.set(t.value,o),Si.push(o),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let n=e._zod.parse,r=(o,i)=>{if(i.direction!=="backward"&&$T(i,o.value))throw new gh;return n(o,i)};if(e._zod.parse=r,e._zod.run===n)e._zod.run=r})},attach(e){var t;let n,r=!1,o,i;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let a=e._zod.parse,s=(c,d)=>{if(n===void 0){let G=Ei(e,new Set,!1);if(G===Hr){if(e._zod.parse=a,e._zod.run===s)e._zod.run=a;return a(c,d)}if(G===Wr||r)n=!0;else r=!0}let u=c.value;if(!hh(u))return a(c,d);let m=d[Fs];if(!m)m={buckets:new WeakMap,backEdges:void 0},d[Fs]=m;let y;if(o===d)y=i;else y=DT(m,e),o=d,i=y;let _=y.get(u);if(_){if(c.value=_.value,_.issues){if(_.issues.length)c.issues.push(...zs(_.issues))}else c.memo=!0,m.backEdges??(m.backEdges=new WeakSet),m.backEdges.add(_.value);return c}vi=y;let E=Si.length,k=a(c,d);vi=void 0;let V=Si.length>E?Si.pop():void 0;if(k instanceof Promise)return k.then((G)=>{if(V)V.issues=G.issues.length?zs(G.issues):fh;return G});if(V)V.issues=k.issues.length?zs(k.issues):fh;return k};if(e._zod.parse=s,e._zod.run===a)e._zod.run=s})}};function Us(){return PT}function $T(e,t){let n=e[Fs]?.backEdges;return n!==void 0&&hh(t)&&n.has(t)}var MT=()=>{let e={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 t(i){return e[i]??null}let n={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",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};function o(i,a){if(i==="number"&&typeof a==="number"&&!Number.isFinite(a))return String(a);return r[i]??i}return(i)=>{switch(i.code){case"invalid_type":{let a=o(i.expected),s=Gm(i.input),c=o(s,i.input);return`Invalid input: expected ${a}, received ${c}`}case"invalid_value":if(i.values.length===1)return`Invalid input: expected ${gs(i.values[0])}`;return`Invalid option: expected one of ${ps(i.values,"|")}`;case"too_big":{let a=i.exact?"exactly ":i.inclusive?"<=":"<",s=t(i.origin);if(s)return`Too big: expected ${i.origin??"value"} to have ${a}${i.maximum.toString()} ${s.unit??"elements"}`;return`Too big: expected ${i.origin??"value"} to be ${a}${i.maximum.toString()}`}case"too_small":{let a=i.exact?"exactly ":i.inclusive?">=":">",s=t(i.origin);if(s)return`Too small: expected ${i.origin} to have ${a}${i.minimum.toString()} ${s.unit}`;return`Too small: expected ${i.origin} to be ${a}${i.minimum.toString()}`}case"invalid_format":{let a=i;if(a.format==="starts_with")return`Invalid string: must start with "${a.prefix}"`;if(a.format==="ends_with")return`Invalid string: must end with "${a.suffix}"`;if(a.format==="includes")return`Invalid string: must include "${a.includes}"`;if(a.format==="regex")return`Invalid string: must match pattern ${a.pattern}`;return`Invalid ${n[a.format]??i.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${i.divisor}`;case"unrecognized_keys":return`Unrecognized key${i.keys.length>1?"s":""}: ${ps(i.keys,", ")}`;case"invalid_key":return`Invalid key in ${i.origin}`;case"invalid_union":if(i.options&&Array.isArray(i.options)&&i.options.length>0)return`Invalid discriminator value. Expected ${i.options.map((s)=>`'${s}'`).join(" | ")}`;if(i.inclusive===!1)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${i.origin}`;default:return"Invalid input"}}};function js(){return{localeError:MT()}}var _h;class bh{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==="object"&&"id"in n)this._idmap.set(n.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function vh(){return new bh}(_h=globalThis).__zod_globalRegistry??(_h.__zod_globalRegistry=vh());var un=globalThis.__zod_globalRegistry;function wi(e){if(e.checks)e.checks=[...e.checks];return e}function Sh(e,t){return new e(wi({type:"string",...q(t)}))}function xh(e,t){return new e(wi({type:"string",coerce:!0,...q(t)}))}function Vs(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...q(t)})}function Eh(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...q(t)})}function wh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...q(t)})}function Ch(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...q(t)})}function Ah(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...q(t)})}function Th(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...q(t)})}function Ks(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...q(t)})}function Rh(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...q(t)})}function Ih(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...q(t)})}function Nh(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...q(t)})}function Oh(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...q(t)})}function kh(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...q(t)})}function Dh(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...q(t)})}function Ph(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...q(t)})}function $h(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...q(t)})}function Mh(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...q(t)})}function Lh(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...q(t)})}function zh(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...q(t)})}function Fh(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...q(t)})}function Uh(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...q(t)})}function jh(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...q(t)})}function Vh(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...q(t)})}function Ci(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...q(t)})}function Ai(e,t){return new e({type:"string",format:"date",check:"string_format",...q(t)})}function Ti(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...q(t)})}function Ri(e,t){return new e({type:"string",format:"duration",check:"string_format",...q(t)})}function Kh(e,t){return new e(wi({type:"number",checks:[],...q(t)}))}function qh(e,t){return new e(wi({type:"number",coerce:!0,checks:[],...q(t)}))}function Bh(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...q(t)})}function Hh(e,t){return new e({type:"boolean",...q(t)})}function Wh(e,t){return new e({type:"boolean",coerce:!0,...q(t)})}function Gh(e,t){return new e({type:"bigint",coerce:!0,...q(t)})}function Zh(e,t){return new e({type:"null",...q(t)})}function Yh(e){return new e({type:"unknown"})}function Jh(e,t){return new e({type:"never",...q(t)})}function Xh(e,t){return new e({type:"date",coerce:!0,...q(t)})}function ar(e,t){return new Rs({check:"less_than",...q(t),value:e,inclusive:!1})}function Ht(e,t){return new Rs({check:"less_than",...q(t),value:e,inclusive:!0})}function sr(e,t){return new Is({check:"greater_than",...q(t),value:e,inclusive:!1})}function Wt(e,t){return new Is({check:"greater_than",...q(t),value:e,inclusive:!0})}function Gr(e,t){return new Kf({check:"multiple_of",...q(t),value:e})}function Ii(e,t){return new Bf({check:"max_length",...q(t),maximum:e})}function cr(e,t){return new Hf({check:"min_length",...q(t),minimum:e})}function Ni(e,t){return new Wf({check:"length_equals",...q(t),length:e})}function qs(e,t){return new Gf({check:"string_format",format:"regex",...q(t),pattern:e})}function Bs(e){return new Zf({check:"string_format",format:"lowercase",...q(e)})}function Hs(e){return new Yf({check:"string_format",format:"uppercase",...q(e)})}function Ws(e,t){return new Jf({check:"string_format",format:"includes",...q(t),includes:e})}function Gs(e,t){return new Xf({check:"string_format",format:"starts_with",...q(t),prefix:e})}function Zs(e,t){return new Qf({check:"string_format",format:"ends_with",...q(t),suffix:e})}function Gt(e){return new eg({check:"overwrite",tx:e})}function Ys(e){return Gt((t)=>t.normalize(e))}function Js(){return Gt((e)=>e.trim())}function Xs(){return Gt((e)=>e.toLowerCase())}function Qs(){return Gt((e)=>e.toUpperCase())}function ec(){return Gt((e)=>Um(e))}function Qh(e,t,n){return new e({type:"array",element:t,...q(n)})}function ey(e,t,n){return new e({type:"custom",check:"custom",fn:t,...q(n)})}function ty(e,t){let n=LT((r)=>(r.addIssue=(o)=>{if(typeof o==="string")r.issues.push(kn(o,r.value,n._zod.def));else{let i=o;if(i.fatal)i.continue=!1;if(i.code??(i.code="custom"),!("input"in i))i.input=r.value;i.inst??(i.inst=n),i.continue??(i.continue=!n._zod.def.abort),r.issues.push(kn(i))}},e(r.value,r)),t);return n}function LT(e,t){let n=new ze({check:"custom",...q(t)});return n._zod.check=e,n}function Zr(e,...t){for(let n of t)for(let r of Reflect.ownKeys(n))if(Object.prototype.propertyIsEnumerable.call(n,r))lt(e,r,n[r]);return e}function Jr(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??un,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function $e(e,t,n,r,o){let i=typeof t.unrepresentable==="function"?t.unrepresentable({zodSchema:e,path:r.path,message:o}):t.unrepresentable;if(i==="any")return!1;if(i===void 0||i==="throw")throw Error(o);return Object.assign(n,i),!0}function me(e,t,n={path:[],schemaPath:[]}){var r;let o=e._zod.def,i=t.seen.get(e);if(i){if(i.count++,n.schemaPath.includes(e))i.cycle=n.path;return i.schema}let a={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,a),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)a.schema=s;else{let u={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,u);else{let y=a.schema,_=t.processors[o.type];if(!_)throw Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);_(e,t,y,u)}let m=e._zod.parent;if(m){if(!a.ref)a.ref=m;me(m,t,u),t.seen.get(m).isParent=!0}}let c=t.metadataRegistry.get(e);if(c)Zr(a.schema,c);if(t.io==="input"&&Je(e))delete a.schema.examples,delete a.schema.default;if(t.io==="input"&&"_prefault"in a.schema)(r=a.schema).default??(r.default=a.schema._prefault);return delete a.schema._prefault,t.seen.get(e).schema}function ny(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function Xr(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let a of e.seen.entries()){let s=e.metadataRegistry.get(a[0])?.id;if(s){let c=r.get(s);if(c&&c!==a[0])throw Error(`Duplicate schema id "${s}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(s,a[0])}}let o=(a)=>{let s=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let m=e.external.registry.get(a[0])?.id,y=e.external.uri??((E)=>E);if(m)return{ref:y(m)};let _=a[1].defId??a[1].schema.id??`schema${e.counter++}`;return a[1].defId=_,{defId:_,ref:`${y("__shared")}#/${s}/${ny(_)}`}}let c="#",d=`${c}/${s}/`;if(a[1]===n&&!a[1].schema.id)return{ref:c};let u=a[1].schema.id??`__schema${e.counter++}`;return{defId:u,ref:d+ny(u)}},i=(a)=>{if(a[1].schema.$ref)return;let s=a[1],{ref:c,defId:d}=o(a);if(s.def={...s.schema},d)s.defId=d;let u=s.schema;for(let m in u)delete u[m];u.$ref=c};if(e.cycles==="throw")for(let a of e.seen.entries()){let s=a[1];if(s.cycle)throw Error(`Cycle detected: #/${s.cycle?.join("/")}/<root>
|
|
86
|
-
|
|
87
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of e.seen.entries()){let s=a[1];if(t===a[0]){i(a);continue}if(e.external){let d=e.external.registry.get(a[0])?.id;if(t!==a[0]&&d){i(a);continue}}if(e.metadataRegistry.get(a[0])?.id){i(a);continue}if(s.cycle){i(a);continue}if(s.count>1){if(e.reused==="ref")i(a)}}if(e.external)e.sharedDefsExtractedFor=e.external}function iy(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let r of t){if(!r||typeof r!=="object")return;iy(r);let o=Object.keys(r);if(o.length!==1||o[0]!=="type")return;let i=r.type;for(let a of Array.isArray(i)?i:[i]){if(typeof a!=="string")return;if(!n.includes(a))n.push(a)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var ay=new Set(["type","properties","required","additionalProperties"]),ry=["oneOf","anyOf"];function oy(e){let t=e.additionalProperties;if(t===void 0||t===!1||typeof t!=="object"||t===null)return null;return Object.keys(t).length?t:null}function tc(e){let t=[];for(let i of e){if(typeof i!=="object"||i.type!=="object")return null;for(let a in i)if(!ay.has(a))return null;t.push(i)}let n={},r=new Set;for(let i of t){for(let a in i.properties){if(Object.prototype.hasOwnProperty.call(n,a))continue;let s=[];for(let d of t){let u=d.properties?.[a]??oy(d);if(u===null||u===void 0)continue;if(!s.some((m)=>JSON.stringify(m)===JSON.stringify(u)))s.push(u)}let c=s.length===1?s[0]:tc(s)??{allOf:s};lt(n,a,c)}for(let a of i.required??[])r.add(a)}let o={type:"object",properties:n};if(r.size)o.required=[...r];if(t.every((i)=>i.additionalProperties===!1))o.additionalProperties=!1;else{let i=[];for(let a of t){let s=oy(a);if(s&&!i.some((c)=>JSON.stringify(c)===JSON.stringify(s)))i.push(s)}if(i.length===1)o.additionalProperties=i[0];else if(i.length>1)o.additionalProperties={allOf:i}}return o}function zT(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let o of ay)if(o in e)return;let n=t.filter((o)=>ry.some((i)=>Array.isArray(o[i]))),r=null;if(!n.length)r=tc(t);else{let o=n[0],i=ry.find((c)=>Array.isArray(o[c]));if(Object.keys(o).length!==1)return;let a=t.filter((c)=>c!==o),s=o[i].map((c)=>tc([...a,c]));if(s.some((c)=>!c))return;r={[i]:s}}if(!r)return;delete e.allOf,Zr(e,r)}function Qr(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let r=(s)=>{let c=e.seen.get(s);if(c.ref===null)return;let d=c.def??c.schema,u={...d},m=c.ref;if(c.ref=null,m){r(m);let _=e.seen.get(m),E=_.schema;if(E.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))d.allOf=d.allOf??[],d.allOf.push(E);else Zr(d,E);if(Zr(d,u),s._zod.parent===m)for(let V in d){if(V==="$ref"||V==="allOf")continue;if(!(V in u))delete d[V]}if(E.$ref&&_.def)for(let V in d){if(V==="$ref"||V==="allOf")continue;if(V in _.def&&JSON.stringify(d[V])===JSON.stringify(_.def[V]))delete d[V]}}let y=s._zod.parent;if(y&&y!==m){r(y);let _=e.seen.get(y);if(_?.schema.$ref){if(d.$ref=_.schema.$ref,_.def)for(let E in d){if(E==="$ref"||E==="allOf")continue;if(E in _.def&&JSON.stringify(d[E])===JSON.stringify(_.def[E]))delete d[E]}}}e.override({zodSchema:s,jsonSchema:d,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let s of[...e.seen.entries()].reverse())r(s[0]);if(e.target!=="openapi-3.0")for(let s of e.seen.entries())iy(s[1].def??s[1].schema);for(let s of e.deferred)s();if(e.intersections.length){let s=new Map;for(let c of e.seen.values())for(let d of[c.schema,c.def]){let u=d?.allOf;if(!Array.isArray(u))continue;let m=s.get(u);if(m)m.push(d);else s.set(u,[d])}for(let c of e.intersections)for(let d of s.get(c)??[])zT(d)}}let o={};if(e.target==="draft-2020-12")o.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")o.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")o.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let s=e.external.registry.get(t)?.id;if(!s)throw Error("Schema is missing an `id` property");o.$id=e.external.uri(s)}Zr(o,n.defId?n.schema:n.def??n.schema);let i=e.metadataRegistry.get(t)?.id;if(i!==void 0&&o.id===i)delete o.id;let a=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let s of e.seen.entries()){let c=s[1];if(c.def&&c.defId){if(c.def.id===c.defId)delete c.def.id;lt(a,c.defId,c.def)}}if(e.external)e.sharedEmitDoneFor=e.external;if(e.external);else if(Object.keys(a).length>0)if(e.target==="draft-2020-12")o.$defs=a;else o.definitions=a;try{let s=JSON.parse(JSON.stringify(o));return Object.defineProperty(s,"~standard",{value:{...t["~standard"],jsonSchema:{input:Yr(t,"input",e.processors),output:Yr(t,"output",e.processors)}},enumerable:!1,writable:!1}),s}catch(s){throw Error("Error converting schema to JSON.")}}function Je(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Je(r.element,n);if(r.type==="set")return Je(r.valueType,n);if(r.type==="lazy")return Je(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault"||r.type==="catch")return Je(r.innerType,n);if(r.type==="intersection")return Je(r.left,n)||Je(r.right,n);if(r.type==="record"||r.type==="map")return Je(r.keyType,n)||Je(r.valueType,n);if(r.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return Je(r.in,n)||Je(r.out,n)}if(r.type==="object"){for(let o in r.shape)if(Je(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(Je(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(Je(o,n))return!0;if(r.rest&&Je(r.rest,n))return!0;return!1}return!1}var sy=(e,t={})=>(n)=>{let r=Jr({...n,processors:t});return me(e,r),Xr(r,e),Qr(r,e)},Yr=(e,t,n={})=>(r)=>{let{libraryOptions:o,target:i}=r??{},a=Jr({...o??{},target:i,io:t,processors:n});return me(e,a),Xr(a,e),Qr(a,e)};var lr=(e,t,n)=>{if(e[t]===void 0||n>e[t])e[t]=n},dr=(e,t,n)=>{if(e[t]===void 0||n<e[t])e[t]=n},cy=(e,t)=>{lr(e,"minimum",t),dr(e,"maximum",t)},my=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},fy=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},gy=(e,t)=>{e.mime=e.mime?e.mime.filter((n)=>t.includes(n)):[...t]},hy=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},ly=(e,t)=>lr(e,"minimum",t.minimum),dy=(e,t)=>dr(e,"maximum",t.maximum),uy=(e)=>(t,n)=>{hy(t,n.format);let[r,o]=e[n.format];lr(t,"minimum",r),dr(t,"maximum",o)},FT={greater_than:(e,t)=>lr(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>dr(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>my(e,t.value),number_format:uy(ti),bigint_format:uy(hs),min_length:ly,max_length:dy,length_equals:(e,t)=>cy(e,t.length),min_size:ly,max_size:dy,size_equals:(e,t)=>cy(e,t.size),string_format:(e,t)=>{if(hy(e,t.format),t.pattern)fy(e,t.pattern);if(t.format==="base64"||t.format==="base64url")e.contentEncoding=t.format;if(t.local||t.precision===-1)e.laxFormat=!0},mime_type:(e,t)=>gy(e,t.mime)};function De(e){let t={},n=e._zod.def,r=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(let i of r)FT[i._zod.def.check]?.(t,i._zod.def);let o=e._zod.bag;if(o.minimum!==void 0)lr(t,"minimum",o.minimum);if(o.exclusiveMinimum!==void 0)lr(t,"exclusiveMinimum",o.exclusiveMinimum);if(o.maximum!==void 0)dr(t,"maximum",o.maximum);if(o.exclusiveMaximum!==void 0)dr(t,"exclusiveMaximum",o.exclusiveMaximum);if(o.multipleOf!==void 0)my(t,o.multipleOf);if(o.format!==void 0){if(t.format??(t.format=o.format),o.format.includes("int"))t.isInt=!0}if(o.mime)gy(t,o.mime);for(let i of o.patterns??[])fy(t,i);return t}var UT={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},jT=new Map([[Ps,Rf],[bi,If]]),yy=(e)=>jT.get(e)??e,oc=(e,t,n,r)=>{let o=n;o.type="string";let{minimum:i,maximum:a,format:s,patterns:c,contentEncoding:d,laxFormat:u}=De(e);if(typeof i==="number")o.minLength=i;if(typeof a==="number")o.maxLength=a;if(s){if(o.format=UT[s]??s,o.format==="")delete o.format;if(s==="time"||u)delete o.format}if(d)o.contentEncoding=d;if(c&&c.size>0){let m=[...c].map(yy);if(m.length===1)o.pattern=m[0].source;else if(m.length>1)o.allOf=[...m.map((y)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:y.source}))]}},ic=(e,t,n,r)=>{let o=n,{minimum:i,maximum:a,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:d,isInt:u}=De(e);o.type=u?"integer":"number";let m=typeof d==="number"&&d>=(i??Number.NEGATIVE_INFINITY),y=typeof c==="number"&&c<=(a??Number.POSITIVE_INFINITY),_=t.target==="draft-04"||t.target==="openapi-3.0";if(m)if(_)o.minimum=d,o.exclusiveMinimum=!0;else o.exclusiveMinimum=d;else if(typeof i==="number")o.minimum=i;if(y)if(_)o.maximum=c,o.exclusiveMaximum=!0;else o.exclusiveMaximum=c;else if(typeof a==="number")o.maximum=a;if(s){let E=new Set;for(let G of s)if(Number.isFinite(G)&&G!==0)E.add(Math.abs(G));else $e(e,t,o,r,`A multipleOf divisor of ${G} cannot be represented in JSON Schema`);let[k,...V]=E;if(k!==void 0)o.multipleOf=k;if(V.length)o.allOf=[...o.allOf??[],...V.map((G)=>({multipleOf:G}))]}},ac=(e,t,n,r)=>{n.type="boolean"},sc=(e,t,n,r)=>{$e(e,t,n,r,"BigInt cannot be represented in JSON Schema")},_y=(e,t,n,r)=>{$e(e,t,n,r,"Symbols cannot be represented in JSON Schema")},cc=(e,t,n,r)=>{if(t.target==="openapi-3.0")n.type="string",n.nullable=!0,n.enum=[null];else n.type="null"},by=(e,t,n,r)=>{$e(e,t,n,r,"Undefined cannot be represented in JSON Schema")},vy=(e,t,n,r)=>{$e(e,t,n,r,"Void cannot be represented in JSON Schema")},lc=(e,t,n,r)=>{n.not={}},Sy=(e,t,n,r)=>{},dc=(e,t,n,r)=>{},uc=(e,t,n,r)=>{$e(e,t,n,r,"Date cannot be represented in JSON Schema")},pc=(e,t,n,r)=>{let o=e._zod.def,i=Ur(o.entries);if(i.length===0){n.not={};return}if(i.every((a)=>typeof a==="number"))n.type="number";if(i.every((a)=>typeof a==="string"))n.type="string";n.enum=i},mc=(e,t,n,r)=>{let o=e._zod.def;if(o.values.length===0){n.not={};return}let i=[];for(let a of o.values)if(a===void 0){if($e(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof a==="bigint"){if($e(e,t,n,r,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(a))}else i.push(a);if(i.length===0);else if(i.length===1){let a=i[0];if(n.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0")n.enum=[a];else n.const=a}else{if(i.every((a)=>typeof a==="number"))n.type="number";if(i.every((a)=>typeof a==="string"))n.type="string";if(i.every((a)=>typeof a==="boolean"))n.type="boolean";if(i.every((a)=>a===null))n.type="null";n.enum=i}},xy=(e,t,n,r)=>{$e(e,t,n,r,"NaN cannot be represented in JSON Schema")},fc=(e,t,n,r)=>{let o=n,i=e._zod.pattern;if(!i)throw Error("Pattern not found in template literal");o.type="string",o.pattern=i.source},Ey=(e,t,n,r)=>{let o=n;o.type="string",o.format="binary",o.contentEncoding="binary";let{minimum:i,maximum:a,mime:s}=De(e);if(i!==void 0)o.minLength=i;if(a!==void 0)o.maxLength=a;if(!s)return;if(s.length===0)o.not={};else if(s.length===1)o.contentMediaType=s[0];else o.anyOf=s.map((c)=>({contentMediaType:c}))},wy=(e,t,n,r)=>{n.type="boolean"},gc=(e,t,n,r)=>{$e(e,t,n,r,"Custom types cannot be represented in JSON Schema")},Cy=(e,t,n,r)=>{$e(e,t,n,r,"Function types cannot be represented in JSON Schema")},hc=(e,t,n,r)=>{$e(e,t,n,r,"Transforms cannot be represented in JSON Schema")},Ay=(e,t,n,r)=>{$e(e,t,n,r,"Map cannot be represented in JSON Schema")},Ty=(e,t,n,r)=>{$e(e,t,n,r,"Set cannot be represented in JSON Schema")},yc=(e,t,n,r)=>{let o=n,i=e._zod.def,{minimum:a,maximum:s}=De(e);if(typeof a==="number")o.minItems=a;if(typeof s==="number")o.maxItems=s;o.type="array",o.items=me(i.element,t,{...r,path:[...r.path,"items"]})};function eo(e){let t=e._zod.def;if(t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform"))return eo(t.out);if(t.type==="catch")return eo(t.innerType);return e._zod.optin}var _c=(e,t,n,r)=>{let o=n,i=e._zod.def,a=i.shape;if(Object.getOwnPropertySymbols(a).length&&$e(e,t,o,r,"Symbol keys cannot be represented in JSON Schema"))return;o.type="object",o.properties={};for(let d in a)lt(o.properties,d,me(a[d],t,{...r,path:[...r.path,"properties",d]}));let c=[];for(let d of Object.keys(a)){let u=i.shape[d];if(t.io==="input"?eo(u)===void 0:u._zod.optout===void 0)c.push(d)}if(c.length>0)o.required=c;if(i.catchall?._zod.def.type==="never")o.additionalProperties=!1;else if(!i.catchall){if(t.io==="output")o.additionalProperties=!1}else if(i.catchall)o.additionalProperties=me(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})},bc=(e,t,n,r)=>{let o=e._zod.def,i=o.inclusive===!1,a=o.options.map((s,c)=>me(s,t,{...r,path:[...r.path,i?"oneOf":"anyOf",c]}));if(i)n.oneOf=a;else n.anyOf=a},vc=(e,t,n,r)=>{let o=e._zod.def,i=me(o.left,t,{...r,path:[...r.path,"allOf",0]}),a=me(o.right,t,{...r,path:[...r.path,"allOf",1]}),s=(d)=>("allOf"in d)&&Object.keys(d).length===1,c=[...s(i)?i.allOf:[i],...s(a)?a.allOf:[a]];n.allOf=c,t.intersections.push(c)},Ry=(e,t,n,r)=>{let o=n,i=e._zod.def;o.type="array";let a=t.target==="draft-2020-12"?"prefixItems":"items",s=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((k,V)=>me(k,t,{...r,path:[...r.path,a,V]})),d=i.rest?me(i.rest,t,{...r,path:[...r.path,s,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null,u=i.items.length;while(u>0){let k=i.items[u-1];if(!(t.io==="input"?eo(k)!==void 0:k._zod.optout==="optional"))break;u--}let m=i.items.length,y=!i.rest;if(t.target==="draft-2020-12"){if(o.prefixItems=c,y)o.items=!1;else if(d)o.items=d;if(u>0)o.minItems=u;if(y)o.maxItems=m}else if(t.target==="openapi-3.0"){if(o.items={anyOf:c},d)o.items.anyOf.push(d);if(u>0)o.minItems=u;if(y)o.maxItems=m}else{if(o.items=c,y)o.additionalItems=!1;else if(d)o.additionalItems=d;if(u>0)o.minItems=u;if(y)o.maxItems=m}let{minimum:_,maximum:E}=De(e);if(typeof _==="number")o.minItems=_;if(typeof E==="number")o.maxItems=E};function nc(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let E=e.get(t)?.def;if(!E)return t;let k=nc(e,E,n);return k===E?t:k}for(let E of["anyOf","oneOf"]){let k=t[E];if(!Array.isArray(k))continue;let V=k.map((G)=>nc(e,G,n));if(V.some((G,oe)=>G!==k[oe]))t={...t,[E]:V}}let r=Array.isArray(t.type)?t.type:[t.type],o=!r.includes("string")&&r.some((E)=>E==="number"||E==="integer"),i=t.enum??(t.const!==void 0?[t.const]:void 0);if(!o&&!i?.some((E)=>typeof E==="number"))return t;let{minimum:a,maximum:s,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:u,format:m,id:y,..._}=t;if(_.enum)_.enum=_.enum.map((E)=>typeof E==="number"?String(E):E);else if(typeof _.const==="number")_.const=String(_.const);if(!o)return _;if(_.type="string",!i)_.pattern=(r.includes("number")?or:mi).source;return _}var rc=new WeakMap;function VT(e){let t=new Map;for(let r of e.seen.values())if(r.def&&!t.has(r.schema))t.set(r.schema,r);let n=new Map;for(let r of rc.get(e)??[]){let o=e.seen.get(r),i=(o?.def??o?.schema)?.propertyNames;if(!i||i===!0||n.has(i))continue;let a=nc(t,i,new Set);if(a!==i)n.set(i,a)}if(!n.size)return;for(let r of e.seen.values())for(let o of[r.schema,r.def]){let i=o&&n.get(o.propertyNames);if(i)o.propertyNames=i}}var Sc=(e,t,n,r)=>{let o=n,i=e._zod.def;o.type="object";let a=i.keyType,s=De(a).patterns;if(i.mode==="loose"&&s&&s.size>0){let u=me(i.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(let m of s)lt(o.patternProperties,yy(m).source,u)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){o.propertyNames=me(i.keyType,t,{...r,path:[...r.path,"propertyNames"]});let u=rc.get(t);if(!u)u=[],rc.set(t,u),t.deferred.push(()=>VT(t));u.push(e)}o.additionalProperties=me(i.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}let c=a._zod.values,d=t.io==="input"&&eo(i.valueType)!==void 0;if(c&&!i.partial&&!d){let u=[...c].filter((m)=>typeof m==="string"||typeof m==="number");if(u.length>0)o.required=u.map(String)}},xc=(e,t,n,r)=>{let o=e._zod.def,i=me(o.innerType,t,r),a=t.seen.get(e);if(t.target==="openapi-3.0")a.ref=o.innerType,n.nullable=!0;else n.anyOf=[i,{type:"null"}]},Ec=(e,t,n,r)=>{let o=e._zod.def;me(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType},wc=Symbol();function Iy(e,t,n,r,o){let i=!1,a=JSON.stringify(e,(s,c)=>{if(typeof c!=="bigint")return c;return i=!0,null});if(!i)return JSON.parse(a);return $e(t,n,r,o,"BigInt defaults cannot be represented in JSON Schema"),wc}var Cc=(e,t,n,r)=>{let o=e._zod.def;me(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType;let a=Iy(o.defaultValue,e,t,n,r);if(a!==wc)n.default=a},Ac=(e,t,n,r)=>{let o=e._zod.def;me(o.innerType,t,r);let i=t.seen.get(e);if(i.ref=o.innerType,t.io!=="input")return;let a=Iy(o.defaultValue,e,t,n,r);if(a!==wc)n._prefault=a},Tc=(e,t,n,r)=>{let o=e._zod.def;me(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType;let a;try{a=o.catchValue(void 0)}catch{$e(e,t,n,r,"Dynamic catch values are not supported in JSON Schema");return}n.default=a},Rc=(e,t,n,r)=>{let o=e._zod.def,i=o.in._zod.traits.has("$ZodTransform"),a=t.io==="input"?i?o.out:o.in:o.out;me(a,t,r);let s=t.seen.get(e);s.ref=a},Ic=(e,t,n,r)=>{let o=e._zod.def;me(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType,n.readOnly=!0},Ny=(e,t,n,r)=>{let o=e._zod.def;me(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType},Oi=(e,t,n,r)=>{let o=e._zod.def;me(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType},Oy=(e,t,n,r)=>{let o=e._zod.innerType;me(o,t,r);let i=t.seen.get(e);i.ref=o},py={string:oc,number:ic,boolean:ac,bigint:sc,symbol:_y,null:cc,undefined:by,void:vy,never:lc,any:Sy,unknown:dc,date:uc,enum:pc,literal:mc,nan:xy,template_literal:fc,file:Ey,success:wy,custom:gc,function:Cy,transform:hc,map:Ay,set:Ty,array:yc,object:_c,union:bc,intersection:vc,tuple:Ry,record:Sc,nullable:xc,nonoptional:Ec,default:Cc,prefault:Ac,catch:Tc,pipe:Rc,readonly:Ic,promise:Ny,optional:Oi,lazy:Oy};function ky(e,t){if("_idmap"in e){let r=e,o=Jr({...t,processors:py}),i={};for(let c of r._idmap.entries()){let[d,u]=c;me(u,o)}let a={},s={registry:r,uri:t?.uri,defs:i};o.external=s;for(let c of r._idmap.entries()){let[d,u]=c;Xr(o,u),lt(a,d,Qr(o,u))}if(Object.keys(i).length>0){let c=o.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[c]:i}}return{schemas:a}}let n=Jr({...t,processors:py});return me(e,n),Xr(n,e),Qr(n,e)}var Dy=new WeakSet([Object.prototype,Error.prototype]);function ki(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let r=n(this);return Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0})}})}var JT=(e,t)=>{nf.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);if(Dy.has(n))return;Dy.add(n),ki(n,"format",(r)=>(o)=>xs(r,o)),ki(n,"flatten",(r)=>(o)=>Ss(r,o)),ki(n,"addIssue",(r)=>(o)=>{r.issues.push(o),r.message=JSON.stringify(r.issues,jr,2)}),ki(n,"addIssues",(r)=>(o)=>{r.issues.push(...o),r.message=JSON.stringify(r.issues,jr,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})};var ut=w("ZodError",JT,void 0,{Parent:Error});var Py=li(ut),$y=di(ut),My=ui(ut),Ly=pi(ut),zy=of(ut),Fy=af(ut),Uy=sf(ut),jy=cf(ut),Vy=lf(ut),Ky=df(ut),qy=uf(ut),By=pf(ut);function QT(){if(!ot.localeError)it(js())}function $i(){if(!ot.memoizer)it({memoizer:Us()})}var fe=w("ZodType",(e,t)=>(QT(),ue.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(dt(t,{checks:[...t.checks??[],...e.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return At(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(VR(e,t))},superRefine(e,t){return this.check(KR(e,t))},overwrite(e){return this.check(Gt(e))},optional(){return Wy(this)},exactOptional(){return RR(this)},nullable(){return Gy(this)},nullish(){return Wy(Gy(this))},nonoptional(e){return PR(this,e)},array(){return z(this)},or(e){return Be([this,e])},and(e){return wR(this,e)},transform(e){return Zy(this,TR(e))},default(e){return OR(this,e)},prefault(e){return DR(this,e)},catch(e){return MR(this,e)},pipe(e){return Zy(this,e)},readonly(){return FR(this)},describe(e){let t=this.clone();return un.add(t,{description:e}),t},meta(...e){if(e.length===0)return un.get(this);let t=this.clone();return un.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get "~standard"(){return ai(this,"~standard",{...Ds(this),jsonSchema:{input:Yr(this,"input"),output:Yr(this,"output")}})},set "~standard"(e){qt(this,"~standard",e)},parse:function e(t,n){return Py(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await $y(this,t,n,{callee:e})},safeParse(e,t){return My(this,e,t)},async safeParseAsync(e,t){return Ly(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){qt(this,"spa",e)},validate(e,t){return Es(this,e,t)},validateAsync(e,t){return ws(this,e,t)},encode:function e(t,n){return zy(this,t,n,{callee:e})},decode:function e(t,n){return Fy(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Uy(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await jy(this,t,n,{callee:e})},safeEncode(e,t){return Vy(this,e,t)},safeDecode(e,t){return Ky(this,e,t)},async safeEncodeAsync(e,t){return qy(this,e,t)},async safeDecodeAsync(e,t){return By(this,e,t)},toJSONSchema(e){return sy(this,{})(e)},get description(){return un.get(this)?.description},get _def(){return this._zod.def}}),Yy=w("_ZodString",(e,t)=>{_i.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>oc(e,n,r,o)},si({format:(e)=>De(e).format??null,minLength:(e)=>De(e).minimum??null,maxLength:(e)=>De(e).maximum??null},{regex(...e){return this.check(qs(...e))},includes(...e){return this.check(Ws(...e))},startsWith(...e){return this.check(Gs(...e))},endsWith(...e){return this.check(Zs(...e))},min(...e){return this.check(cr(...e))},max(...e){return this.check(Ii(...e))},length(...e){return this.check(Ni(...e))},nonempty(...e){return this.check(cr(1,...e))},lowercase(e){return this.check(Bs(e))},uppercase(e){return this.check(Hs(e))},trim(){return this.check(Js())},normalize(...e){return this.check(Ys(...e))},toLowerCase(){return this.check(Xs())},toUpperCase(){return this.check(Qs())},slugify(){return this.check(ec())}})),Oc=w("ZodString",(e,t)=>{_i.init(e,t),Yy.init(e,t)},{email(e){return this.check(Vs(Jy,e))},url(e){return this.check(Ks(Xy,e))},jwt(e){return this.check(Vh(hR,e))},emoji(e){return this.check(Rh(nR,e))},guid(e){return this.check(Eh(tR,e))},uuid(e){return this.check(wh(Di,e))},uuidv4(e){return this.check(Ch(Di,e))},uuidv6(e){return this.check(Ah(Di,e))},uuidv7(e){return this.check(Th(Di,e))},nanoid(e){return this.check(Ih(rR,e))},cuid(e){return this.check(Nh(oR,e))},cuid2(e){return this.check(Oh(iR,e))},ulid(e){return this.check(kh(aR,e))},base64(e){return this.check(Fh(mR,e))},base64url(e){return this.check(Uh(fR,e))},xid(e){return this.check(Dh(sR,e))},ksuid(e){return this.check(Ph(cR,e))},ipv4(e){return this.check($h(lR,e))},ipv6(e){return this.check(Mh(dR,e))},cidrv4(e){return this.check(Lh(uR,e))},cidrv6(e){return this.check(zh(pR,e))},e164(e){return this.check(jh(gR,e))},datetime(e){return this.check(Ci(to,e))},date(e){return this.check(Ai(no,e))},time(e){return this.check(Ti(ro,e))},duration(e){return this.check(Ri(oo,e))}});function l(e){return Sh(Oc,e)}var we=w("ZodStringFormat",(e,t)=>{be.init(e,t),Yy.init(e,t)}),to=w("ZodISODateTime",(e,t)=>{Tg.init(e,t),we.init(e,t)}),no=w("ZodISODate",(e,t)=>{Rg.init(e,t),we.init(e,t)}),ro=w("ZodISOTime",(e,t)=>{Ig.init(e,t),we.init(e,t)}),oo=w("ZodISODuration",(e,t)=>{Ng.init(e,t),we.init(e,t)}),Jy=w("ZodEmail",(e,t)=>{hg.init(e,t),we.init(e,t)});function eR(e){return Vs(Jy,e)}var tR=w("ZodGUID",(e,t)=>{fg.init(e,t),we.init(e,t)});var Di=w("ZodUUID",(e,t)=>{gg.init(e,t),we.init(e,t)});var Xy=w("ZodURL",(e,t)=>{bg.init(e,t),we.init(e,t)});function Qy(e){return Ks(Xy,e)}var nR=w("ZodEmoji",(e,t)=>{vg.init(e,t),we.init(e,t)});var rR=w("ZodNanoID",(e,t)=>{Sg.init(e,t),we.init(e,t)});var oR=w("ZodCUID",(e,t)=>{xg.init(e,t),we.init(e,t)});var iR=w("ZodCUID2",(e,t)=>{Eg.init(e,t),we.init(e,t)});var aR=w("ZodULID",(e,t)=>{wg.init(e,t),we.init(e,t)});var sR=w("ZodXID",(e,t)=>{Cg.init(e,t),we.init(e,t)});var cR=w("ZodKSUID",(e,t)=>{Ag.init(e,t),we.init(e,t)});var lR=w("ZodIPv4",(e,t)=>{Og.init(e,t),we.init(e,t)});var dR=w("ZodIPv6",(e,t)=>{Dg.init(e,t),we.init(e,t)});var uR=w("ZodCIDRv4",(e,t)=>{Pg.init(e,t),we.init(e,t)});var pR=w("ZodCIDRv6",(e,t)=>{$g.init(e,t),we.init(e,t)});var mR=w("ZodBase64",(e,t)=>{Lg.init(e,t),we.init(e,t)});var fR=w("ZodBase64URL",(e,t)=>{zg.init(e,t),we.init(e,t)});var gR=w("ZodE164",(e,t)=>{Fg.init(e,t),we.init(e,t)});var hR=w("ZodJWT",(e,t)=>{Ug.init(e,t),we.init(e,t)});var Mi=w("ZodNumber",(e,t)=>{$s.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ic(e,n,r,o),e.isFinite=!0},si({minValue:(e)=>{let{minimum:t,exclusiveMinimum:n}=De(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:n}=De(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:n}=De(e);return!!t||!!n?.some(Number.isSafeInteger)},format:(e)=>De(e).format??null},{gt(e,t){return this.check(sr(e,t))},gte(e,t){return this.check(Wt(e,t))},min(e,t){return this.check(Wt(e,t))},lt(e,t){return this.check(ar(e,t))},lte(e,t){return this.check(Ht(e,t))},max(e,t){return this.check(Ht(e,t))},int(e){return this.check(Pi(e))},safe(e){return this.check(Pi(e))},positive(e){return this.check(sr(0,e))},nonnegative(e){return this.check(Wt(0,e))},negative(e){return this.check(ar(0,e))},nonpositive(e){return this.check(Ht(0,e))},multipleOf(e,t){return this.check(Gr(e,t))},step(e,t){return this.check(Gr(e,t))},finite(){return this}}));function f(e){return Kh(Mi,e)}var yR=w("ZodNumberFormat",(e,t)=>{jg.init(e,t),Mi.init(e,t)});function Pi(e){return Bh(yR,e)}var kc=w("ZodBoolean",(e,t)=>{Vg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ac(e,n,r,o)});function F(e){return Hh(kc,e)}var e_=w("ZodBigInt",(e,t)=>{Kg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>sc(e,n,r,o)},si({minValue:(e)=>De(e).minimum??null,maxValue:(e)=>De(e).maximum??null,format:(e)=>De(e).format??null},{gte(e,t){return this.check(Wt(e,t))},min(e,t){return this.check(Wt(e,t))},gt(e,t){return this.check(sr(e,t))},lt(e,t){return this.check(ar(e,t))},lte(e,t){return this.check(Ht(e,t))},max(e,t){return this.check(Ht(e,t))},positive(e){return this.check(sr(BigInt(0),e))},negative(e){return this.check(ar(BigInt(0),e))},nonpositive(e){return this.check(Ht(BigInt(0),e))},nonnegative(e){return this.check(Wt(BigInt(0),e))},multipleOf(e,t){return this.check(Gr(e,t))}}));var _R=w("ZodNull",(e,t)=>{qg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>cc(e,n,r,o)});function Pt(e){return Zh(_R,e)}var bR=w("ZodUnknown",(e,t)=>{Bg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>dc(e,n,r,o)});function pt(){return Yh(bR)}var vR=w("ZodNever",(e,t)=>{Hg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>lc(e,n,r,o)});function t_(e){return Jh(vR,e)}var n_=w("ZodDate",(e,t)=>{Wg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>uc(e,n,r,o),e.min=(n,r)=>e.check(Wt(n,r)),e.max=(n,r)=>e.check(Ht(n,r))},si({minDate:(e)=>{let{minimum:t}=De(e);return t?new Date(t):null},maxDate:(e)=>{let{maximum:t}=De(e);return t?new Date(t):null}},{}));var SR=w("ZodArray",(e,t)=>{$i(),Gg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>yc(e,n,r,o),e.element=t.element},{min(e,t){return this.check(cr(e,t))},nonempty(e){return this.check(cr(1,e))},max(e,t){return this.check(Ii(e,t))},length(e,t){return this.check(Ni(e,t))},unwrap(){return this.element}});function z(e,t){return Qh(SR,e,t)}var r_=w("ZodObject",(e,t)=>{$i(),Jg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>_c(e,n,r,o),oT(e,"shape",(n)=>n._zod.def.shape,!1)},{keyof(){return P(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(dt(this._zod.def,{catchall:e}))},passthrough(){return this.clone(dt(this._zod.def,{catchall:pt()}))},loose(){return this.clone(dt(this._zod.def,{catchall:pt()}))},strict(){return this.clone(dt(this._zod.def,{catchall:t_()}))},strip(){return this.clone(dt(this._zod.def,{catchall:void 0}))},extend(e){return YA(this,e)},safeExtend(e){return JA(this,e)},merge(e){return XA(this,e)},pick(e){return GA(this,e)},omit(e){return ZA(this,e)},partial(...e){return Hm(i_,this,e[0])},exactPartial(...e){return Hm(a_,this,e[0],"exactPartial")},required(...e){return QA(s_,this,e[0])}});function g(e,t){let n={type:"object",shape:e??{},...q(t)};return new r_(n)}function K(e,t){return new r_({type:"object",shape:e,catchall:t_(),...q(t)})}var o_=w("ZodUnion",(e,t)=>{Ms.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>bc(e,n,r,o),e.options=t.options});function Be(e,t){return new o_({type:"union",options:e,...q(t)})}var xR=w("ZodDiscriminatedUnion",(e,t)=>{o_.init(e,t),Xg.init(e,t)});function Re(e,t,n){return new xR({type:"union",options:t,discriminator:e,...q(n)})}var ER=w("ZodIntersection",(e,t)=>{Qg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>vc(e,n,r,o)});function wR(e,t){return new ER({type:"intersection",left:e,right:t})}var Hy=w("ZodRecord",(e,t)=>{$i(),eh.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Sc(e,n,r,o),e.keyType=t.keyType,e.valueType=t.valueType});function ie(e,t,n){if(!t||!t._zod)return new Hy({type:"record",keyType:l(),valueType:e,...q(t)});return new Hy({type:"record",keyType:e,valueType:t,...q(n)})}var Nc=w("ZodEnum",(e,t)=>{th.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(r,o,i)=>pc(e,r,o,i),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{let i={};for(let a of r)if(n.has(a))i[a]=t.entries[a];else throw Error(`Key ${a} not found in enum`);return new Nc({...t,checks:[],...q(o),entries:i})},e.exclude=(r,o)=>{let i={...t.entries};for(let a of r)if(n.has(a))delete i[a];else throw Error(`Key ${a} not found in enum`);return new Nc({...t,checks:[],...q(o),entries:i})}});function P(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((r)=>[r,r])):e;return new Nc({type:"enum",entries:n,...q(t)})}var CR=w("ZodLiteral",(e,t)=>{nh.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>mc(e,n,r,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function I(e,t){return new CR({type:"literal",values:Array.isArray(e)?e:[e],...q(t)})}var AR=w("ZodTransform",(e,t)=>{$i(),rh.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>hc(e,n,r,o),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new qr(e.constructor.name);n.addIssue=(i)=>{if(typeof i==="string")n.issues.push(kn(i,n.value,t));else{let a=i;if(a.fatal)a.continue=!1;if(a.code??(a.code="custom"),!("input"in a))a.input=n.value;a.inst??(a.inst=e),n.issues.push(kn(a))}};let o=t.transform(n.value,n);if(o instanceof Promise)return o.then((i)=>(n.value=i,n));return n.value=o,n}});function TR(e){return new AR({type:"transform",transform:e})}var i_=w("ZodOptional",(e,t)=>{Ls.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Oi(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Wy(e){return new i_({type:"optional",innerType:e})}var a_=w("ZodExactOptional",(e,t)=>{oh.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Oi(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function RR(e){return new a_({type:"optional",innerType:e})}var IR=w("ZodNullable",(e,t)=>{ih.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>xc(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Gy(e){return new IR({type:"nullable",innerType:e})}var NR=w("ZodDefault",(e,t)=>{ah.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Cc(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function OR(e,t){return new NR({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():fs(t)}})}var kR=w("ZodPrefault",(e,t)=>{sh.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ac(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function DR(e,t){return new kR({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():fs(t)}})}var s_=w("ZodNonOptional",(e,t)=>{ch.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ec(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function PR(e,t){return new s_({type:"nonoptional",innerType:e,...q(t)})}var $R=w("ZodCatch",(e,t)=>{lh.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Tc(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function MR(e,t){return new $R({type:"catch",innerType:e,catchValue:typeof t==="function"?t:Ym(t)})}var LR=w("ZodPipe",(e,t)=>{dh.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Rc(e,n,r,o),e.in=t.in,e.out=t.out});function Zy(e,t){return new LR({type:"pipe",in:e,out:t})}var zR=w("ZodReadonly",(e,t)=>{uh.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ic(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function FR(e){return new zR({type:"readonly",innerType:e})}var UR=w("ZodTemplateLiteral",(e,t)=>{ph.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>fc(e,n,r,o)});function c_(e,t){return new UR({type:"template_literal",parts:e,...q(t)})}var jR=w("ZodCustom",(e,t)=>{mh.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>gc(e,n,r,o)});function VR(e,t={}){return ey(jR,e,t)}function KR(e,t){return ty(e,t)}function BR(e){return Ci(to,e)}function HR(e){return Ai(no,e)}function WR(e){return Ti(ro,e)}function GR(e){return Ri(oo,e)}function ZR(e){return xh(Oc,e)}function YR(e){return qh(Mi,e)}function JR(e){return Wh(kc,e)}function XR(e){return Gh(e_,e)}function QR(e){return Xh(n_,e)}var W={acl_rules:"acl",organizations:"org",users:"usr",auth_sessions:"ses",user_passkeys:"pky",sso_providers:"sso",org_memberships:"mem",visual_plans:"vp",visual_plan_versions:"vpv",block_presets:"bpr",saved_recipes:"rcp",channels:"ch",schedules:"sched",holiday_groups:"hgrp",holidays:"hol",holiday_calendars:"hcal",holiday_calendar_entries:"hcent",schedule_exceptions:"sexc",audio_files:"aud",destinations:"dest",call_records:"call",call_events:"cev",api_keys:"key",audit_logs:"audit",invitations:"inv",roles:"role",licenses:"lic",webhook_endpoints:"whep",webhook_delivery_logs:"whdl",call_transcriptions:"ctr",call_transcription_embeddings:"cte",analysis_templates:"at",call_analyses:"ca",ai_settings:"ais",usage_records:"ur",contacts:"ct",contact_channels:"ctch",chat_sessions:"csess",notifications:"notif",dialer_campaigns:"dcamp",dialer_contacts:"dct",dialer_attempts:"datt",dialer_dnc:"dnc",dialer_import_jobs:"dimp",export_jobs:"exp",org_secrets:"sec",connectors:"conn",oauth_clients:"oac",oauth_grants:"oag",signals:"sig",signal_versions:"sigv",call_signals:"csig",call_signal_timelines:"cstl",insight_views:"iv",attendants:"att",attendant_status_log:"asl",pause_reasons:"pause",dispositions:"disp",conversations:"conv",queues:"que",saved_replies:"srp",conversation_copilot_suggestions:"csug",assistant_conversations:"aconv",assistant_messages:"amsg",assistant_approvals:"aappr",chat_ws_sessions:"chs",chat_media:"media",chat_messages:"msg"};function Li(e,t){return Nt.fromUUID(W[e],t).toString()}var eI=new Map(Object.keys(W).map((e)=>[W[e],e]));function io(e){return eI.get(e)}var tI=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Dn(e){if(tI.test(e))return{kind:"uuid",uuid:e};let t=e.lastIndexOf("_");if(t<=0||t===e.length-1)return{kind:"invalid",reason:"not-an-id"};let n=e.slice(0,t),r=io(n);if(r===void 0)return{kind:"invalid",reason:"unknown-prefix"};try{return{kind:"typeid",entity:r,prefix:n,uuid:Nt.fromString(e,n).toUUID()}}catch{return{kind:"invalid",reason:"malformed-suffix"}}}function ce(e){return e}function nI(e){return`a ${W[e]}_... TypeID for ${e}, or the raw UUID of that row`}function l_(e,t,n){C(`Invalid id "${t}": ${n}`),D(` Expected ${nI(e)}.`),D(" Convert between the two forms with: niva id <value> [--as <entity>]"),process.exit(A.USAGE_ERROR)}function rI(e){let t=e.lastIndexOf("_");return t>0?e.slice(0,t):""}function d_(e,t){let n=Dn(t);if(n.kind==="uuid")return Li(e,n.uuid);let r=io(rI(t));if(r===e)return t;if(r!==void 0)l_(e,t,`it is a ${r} id`);l_(e,t,"it is neither a UUID nor an id of a known entity")}function x(e,t){let n;if(Array.isArray(t))n=t.map((r)=>d_(e,r));else if(t!==void 0)n=d_(e,t);return n}var u_=["volume","answered","busy","no_answer","failed","duration","ai_cost","flow_errors"],p_=["day","week","month","hour_of_day","weekday","plan","plan_version","channel","outcome"],m_=["answered","busy","no_answer","failed"];function ao(e){if(e==null)return[];return e.split(",").map((t)=>t.trim()).filter((t)=>t.length>0)}function oI(e,t){return[...t,e]}function Tt(e){C(`Error: ${e}`),process.exit(A.USAGE_ERROR)}function g_(e,t){if(!e.startsWith("signal:")||e.length===7)Tt(`invalid ${t} "${e}" — expected signal:<sig_id>`);return{signal_id:x("signals",e.slice(7))}}function iI(e){let t=ao(e);if(t.length===0)Tt("--measure is required (e.g. --measure volume,answered)");if(t.length>6)Tt("--measure accepts at most 6 measures");for(let n of t)if(!u_.includes(n))Tt(`invalid --measure "${n}" — expected one of: ${u_.join(", ")}`);return t.map((n)=>ce(n))}function aI(e){let t=[];for(let n of ao(e)){if(n.startsWith("signal:")){t.push(g_(n,"--by"));continue}if(!p_.includes(n))Tt(`invalid --by "${n}" — expected one of: ${p_.join(", ")} or signal:<sig_id>`);t.push(ce(n))}if(t.length>2)Tt("--by accepts at most 2 dimensions");return t}function sI(e){if(e===void 0)return;let t=ao(e);if(t.length===0)Tt("--plan needs at least one id");return t.map((n)=>x("visual_plans",n))}function cI(e){let t=ao(e);for(let n of t)if(!m_.includes(n))Tt(`invalid --outcome "${n}" — expected one of: ${m_.join(", ")}`);return t.map((n)=>ce(n))}function lI(e){let t=[];for(let n of e){let r=n.indexOf("=");if(r<0)Tt(`invalid --where "${n}" — expected signal:<sig_id>=<v1,v2>`);let o=g_(n.slice(0,r),"--where"),i=ao(n.slice(r+1));if(i.length===0)Tt(`invalid --where "${n}" — expected signal:<sig_id>=<v1,v2>`);t.push({...o,values:i})}return t}function dI(e){let t=Number(e);if(!Number.isInteger(t)||t<1||t>1000)Tt(`invalid --limit "${e}" — expected an integer from 1 to 1000`);return t}function h_(e,t){e.command("analytics").description("Flexible aggregates over calls and signals").command("query").description("Aggregate call measures grouped by time, plan, channel, outcome or signal values").option("--measure <list>","Comma-separated measures: volume,answered,busy,no_answer,failed,duration,ai_cost,flow_errors").option("--by <list>","Comma-separated dimensions: day,week,month,hour_of_day,weekday,plan,plan_version,channel,outcome or signal:<sig_id> (max 2)").option("--from <date>","Start date (YYYY-MM-DD or ISO 8601)").option("--to <date>","End date (YYYY-MM-DD or ISO 8601)").option("--plan <ids>","Comma-separated visual plan IDs").option("--channel <channel>","Filter by channel: voice or chat").option("--outcome <list>","Comma-separated outcomes: answered,busy,no_answer,failed").option("--where <signal:values>","Signal filter signal:<sig_id>=<v1,v2>; repeatable",oI,[]).option("--limit <n>","Max rows (1-1000)","500").action(async(r)=>{let{format:o}=S(e.opts()),{date_from:i,date_to:a}=_t(r),s=iI(r.measure),c=aI(r.by),d=sI(r.plan),u=cI(r.outcome),m=lI(r.where),y=dI(r.limit),_=await b(t().insights.aggregate({measures:s,...c.length>0?{group_by:c}:{},...d!==void 0||r.channel!==void 0||u.length>0||m.length>0?{filters:{...d!==void 0?{plan_ids:d}:{},...r.channel!==void 0?{channel:ce(r.channel)}:{},...u.length>0?{outcomes:u.map((k)=>ce(k))}:{},...m.length>0?{signals:m}:{}}}:{},period:{date_from:i,date_to:a},limit:y}));if(o==="json"){v(_);return}if(_.truncated)Et(`Showing the first ${_.rows.length} rows (--limit ${y}). Narrow the period or filters.`);console.log(f_.default.bold("Analytics")),console.log("");let E=_.columns.map((k)=>k.key);L(E,_.rows.map((k)=>({...k})))})}function y_(e,t){let n=e.command("attendants").description("Manage Desk attendants (requires the desk module)");n.command("list").description("List attendants with their current state").option("--status <s>","Filter by state (available, paused, not_responding, ringing, busy, wrap_up, offline)").option("--endpoint <e>","Filter by endpoint (sip_extension, webrtc)").option("--search <term>","Search by name or email").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().attendants.list({page:Number(r.page),limit:Number(r.limit),search:r.search,status:ce(r.status),endpoint:ce(r.endpoint)}));if(o==="json"){v(i?a.items.map((s)=>N(s,i)):a);return}L(["ID","Name","Email","Endpoint","Status","Reason","Online"],a.items.map((s)=>({ID:s.id,Name:s.user.name,Email:s.user.email,Endpoint:s.endpoint,Status:s.status,Reason:s.status_reason?.name??"—",Online:s.online?"yes":"no"}))),te(a)}),n.command("show <attendant_id>").description("Show one attendant").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().attendants.getById({attendant_id:x("attendants",r)}));if(o==="json"){v(i?N(a,i):a);return}J([{title:"Attendant",rows:[{label:"ID",value:a.id},{label:"Name",value:a.user.name},{label:"Email",value:a.user.email},{label:"Endpoint",value:a.endpoint},{label:"Extension",value:a.extension},{label:"Online",value:a.online}]},{title:"State",rows:[{label:"Status",value:a.status},{label:"Reason",value:a.status_reason?.name},{label:"Since",value:Me(a.status_since)}]},{title:"Capacity",rows:[{label:"Voice",value:a.capacity_voice},{label:"Chat",value:a.capacity_chat},{label:"Auto answer",value:a.auto_answer},{label:"Max wrap-up (s)",value:a.max_wrap_s}]}])}),n.command("set-status <attendant_id> <status>").description("Set an attendant's state as a supervisor (available, paused, offline). A pause or offline asked for during a call never interrupts it: it waits for the work to end and lands as paused. It also takes an attendant out of not_responding").option("--reason <pause_reason_id>","Pause reason (with paused)").action(async(r,o,i)=>{let{format:a,fields:s}=S(e.opts());if(i.reason!=null&&o!=="paused")C("--reason only applies to the paused state"),process.exit(A.USAGE_ERROR);let c=await b(t().attendants.setStatus({attendant_id:x("attendants",r),status:ce(o),reason_id:x("pause_reasons",i.reason)}));if(a==="json"){v(s?N(c,s):c);return}if(c.pending){O(`Pause requested for ${c.attendant.user.name}; it applies when the current work ends`);return}O(`${c.attendant.user.name} is now ${c.attendant.status}`)})}import{readFile as C_,writeFile as A_}from"node:fs/promises";import{basename as T_}from"node:path";function uI(e,t){let n=t.toLowerCase();if(n.endsWith(".wav"))return pI(e);if(n.endsWith(".mp3"))return EI(e);return}function zi(e){if(!Number.isFinite(e)||e<=0)return;let t=Math.round(e);if(t<=0||t>86400000)return;return t}function __(e,t,n){let r="";for(let o=0;o<n;o+=1)r+=String.fromCharCode(e[t+o]??0);return r}function so(e,t,n){if(t+n.length>e.byteLength)return!1;return __(e,t,n.length)===n}function b_(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function pI(e){let t=e.byteLength;if(t<12||!so(e,0,"RIFF")||!so(e,8,"WAVE"))return;let n=b_(e),r,o,i=12;while(i+8<=t){let a=__(e,i,4),s=n.getUint32(i+4,!0),c=i+8;if(a==="fmt "&&s>=16&&c+16<=t){let u=n.getUint16(c+2,!0),m=n.getUint32(c+4,!0),y=n.getUint32(c+8,!0),_=n.getUint16(c+14,!0);r=y>0?y:m*u*_/8}else if(a==="data"){o=Math.min(s,t-c);break}let d=c+s+s%2;if(d<=i)return;i=d}if(r===void 0||r<=0||o===void 0)return;return zi(o/r*1000)}var mI=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320,0],fI=[0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,0],gI=[44100,48000,32000,0],hI=[22050,24000,16000,0],yI=[11025,12000,8000,0];function _I(e){if(e===3)return gI;if(e===2)return hI;return yI}function bI(e,t){if(e)return t?17:32;return t?9:17}function vI(e,t){let n=e[t+1],r=e[t+2],o=e[t+3];if(n===void 0||r===void 0||o===void 0)return;let i=n>>3&3,a=n>>1&3;if(i===1||a!==1)return;let s=i===3,c=(s?mI:fI)[r>>4&15]??0,d=_I(i)[r>>2&3]??0;if(c===0||d===0)return;let u=(o>>6&3)===3;return{bitrate:c*1000,sampleRate:d,samplesPerFrame:s?1152:576,sideInfoSize:bI(s,u)}}function SI(e,t,n){let r=t+4+n;if(!so(e,r,"Xing")&&!so(e,r,"Info"))return;if(r+12>e.byteLength)return;let o=b_(e);if((o.getUint32(r+4,!1)&1)===0)return;let a=o.getUint32(r+8,!1);return a>0?a:void 0}function xI(e){if(!so(e,0,"ID3")||e.byteLength<10)return 0;let t=e[5]??0,n=0;for(let o=6;o<=9;o+=1)n=n<<7|(e[o]??0)&127;let r=(t&16)!==0?10:0;return 10+n+r}function EI(e){let t=e.byteLength,n=xI(e);for(let r=n;r+4<=t;r+=1){if(e[r]!==255||((e[r+1]??0)&224)!==224)continue;let o=vI(e,r);if(o===void 0)continue;let i=SI(e,r,o.sideInfoSize);if(i!==void 0)return zi(i*o.samplesPerFrame*1000/o.sampleRate);return zi((t-r)*8*1000/o.bitrate)}return}async function wI(e,t,n=3000){let r=[t,"-v","error","-show_entries","format=duration","-of","csv=p=0",e],o;try{o=Bun.spawn(r,{stdout:"pipe",stderr:"ignore"})}catch{return}let i=CI(o).catch(()=>{return}),a,s=new Promise((c)=>{a=setTimeout(()=>{o.kill(),setTimeout(()=>o.kill("SIGKILL"),250).unref(),c(void 0)},n)});try{let c=await Promise.race([i,s]);if(c?.exitCode!==0)return;return zi(Number(c.stdout.trim())*1000)}finally{if(a!==void 0)clearTimeout(a)}}async function CI(e){let[t,n]=await Promise.all([new Response(e.stdout).text(),e.exited]);return{stdout:t,exitCode:n}}async function v_(e){let t=uI(e.bytes,e.filePath);if(t!==void 0)return{durationMs:t,source:"header"};if(e.noProbe===!0)return{source:"none"};let n=await wI(e.filePath,e.ffprobePath??"ffprobe",e.probeTimeoutMs);if(n!==void 0)return{durationMs:n,source:"ffprobe"};return{source:"none"}}import{createInterface as Fi}from"node:readline/promises";import{Writable as AI}from"node:stream";function co(){return process.stdin.isTTY===!0}var S_=5;async function x_(e,t,n){let r=e[t].value;for(let o=0;o<S_;o++){let i=(await n(`Choice [${t+1}]: `)).trim();if(i==="")return r;let a=/^\d+$/.test(i)?e[Number(i)-1]:void 0;if(a!=null)return a.value;C(`Invalid choice — enter a number between 1 and ${e.length}.`)}return C(`No valid choice after ${S_} attempts — using the default.`),r}async function E_(e,t){if(t!=null)return t(e);let n=Fi({input:process.stdin,output:process.stderr});try{return await n.question(e)}finally{n.close()}}async function Dc(e,t){if(t!=null)return t(e);let n=new AI({write(o,i,a){a()}}),r=Fi({input:process.stdin,output:n,terminal:!0});process.stderr.write(e);try{return await r.question("")}finally{r.close(),process.stderr.write(`
|
|
88
|
-
`)}}async function
|
|
89
|
-
`)};o(e);for(let[a,s]of t.entries())o(` ${a+1}) ${s.label}`);if(o(""),n.ask!=null)return x_(t,r,n.ask);let i=Fi({input:process.stdin,output:n.output??process.stdout});try{return await x_(t,r,async(a)=>i.question(a))}finally{i.close()}}async function Ce(e,t){if(t.yes)return;if(process.stdin.isTTY!==!0)C("Refusing to prompt in non-interactive mode. Re-run with --yes to confirm."),process.exit(A.USAGE_ERROR);let n=Fi({input:process.stdin,output:process.stderr});try{let r=await n.question(`${e} [y/N] `);if(!/^y(?:es)?$/i.test(r.trim()))C("Aborted."),process.exit(A.USAGE_ERROR)}finally{n.close()}}import{Buffer as TI}from"node:buffer";async function Fe(){return new Promise((e,t)=>{let n=[];process.stdin.on("data",(r)=>n.push(r)),process.stdin.on("end",()=>e(TI.concat(n).toString("utf-8"))),process.stdin.on("error",t)})}var RI=10,II=new Set(["UNAUTHORIZED","FORBIDDEN","API_KEY_INVALID","ADMIN_REQUIRED","INSUFFICIENT_SCOPE"]);function R_(e,t){let n=e.command("audio-files").description("Audio file library");n.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(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().audioFiles.list({page:Number(r.page),limit:Number(r.limit),search:r.search}));if(o==="json"){let s=i?a.items.map((c)=>N(c,i)):a;v(s);return}L(["ID","Name","Type","Duration"],a.items.map((s)=>({ID:s.id,Name:s.name,Type:s.type,Duration:I_(s.duration_ms)}))),te(a)}),n.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(r,o)=>{let{format:i}=S(e.opts()),a=e.opts().yes===!0;if(o.name!=null&&r.length>1)C("--name names a single audio file; drop it when uploading several at once."),process.exit(A.USAGE_ERROR);if(o.durationMs!=null&&r.length>1)C("--duration-ms describes a single audio file; drop it when uploading several at once."),process.exit(A.USAGE_ERROR);let s=OI(o.durationMs);if(r.length>RI)await Ce(`Upload ${r.length} audio files to the library?`,{yes:a});let c=[],d=A.SUCCESS;for(let u of r){let m=await kI(t(),u,{format:i,overrideMs:s,noProbe:o.probe===!1,...o.name!=null&&{name:o.name}});if(c.push(m),m.exitCode>d)d=m.exitCode;if(m.abort)break}if(LI(c,i),d!==A.SUCCESS)process.exit(d)}),n.command("show <audio_file_id>").description("Show an audio file's metadata").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().audioFiles.getById({audio_file_id:x("audio_files",r)}));if(a==null)C("Audio file not found"),process.exit(A.NOT_FOUND);if(o==="json"){v(i?N(a,i):a);return}J(ji(a))}),n.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(r,o)=>{let{format:i}=S(e.opts()),a=e.opts(),s=a.json===!0||a.output==="json";if(o.out==="-"&&s)C("--out - streams binary audio to stdout and cannot be combined with --json."),process.exit(A.USAGE_ERROR);let c=t(),d=await b(c.audioFiles.content({audio_file_id:x("audio_files",r)})),u=new Uint8Array(await d.arrayBuffer());if(o.out==="-"){process.stdout.write(u);return}let m;if(o.out!=null)m=o.out,await A_(m,u);else m=await $I(c,r,d.name),await MI(m,u,o.force===!0);if(i==="json"){v({path:m,bytes:u.length});return}O(`Saved ${m} (${u.length} bytes)`)}),n.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(r,o)=>{let{format:i}=S(e.opts());if(o.name==null&&o.description==null)C("Nothing to update — pass --name and/or --description."),process.exit(A.USAGE_ERROR);let a=await b(t().audioFiles.update({audio_file_id:x("audio_files",r),...o.name!=null&&{name:o.name},...o.description!=null&&{description:o.description}}));if(i==="json"){v(a);return}O(`Audio file updated: ${a.name}`),J(ji(a))}),n.command("delete <audio_file_id>").description("Delete an audio file from the library").action(async(r)=>{let{format:o}=S(e.opts()),i=e.opts().yes===!0;await Ce(`Delete audio file ${r}?`,{yes:i});try{await t().audioFiles.delete({audio_file_id:x("audio_files",r)})}catch(a){zI(a,o)}if(o==="json"){v({id:r,deleted:!0});return}O(`Audio file deleted: ${r}`)}),n.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(r)=>{let{format:o}=S(e.opts()),i=await w_(r),a=await b(t().audioFiles.generateTts({name:r.name,text:i,...r.description!=null&&{description:r.description},...r.voice!=null&&{voice:r.voice},...r.model!=null&&{model:r.model}}));if(o==="json"){v(a);return}O(`TTS audio generated: ${a.id}`),J(ji(a))}),n.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(r,o)=>{let{format:i}=S(e.opts()),a=e.opts().yes===!0,s=await w_(o);await Ce(`Overwrite the audio content of ${r}?`,{yes:a});let c=await b(t().audioFiles.regenerateTts({audio_file_id:x("audio_files",r),text:s,...o.voice!=null&&{voice:o.voice},...o.model!=null&&{model:o.model}}));if(i==="json"){v(c);return}O(`TTS audio regenerated: ${c.id}`),J(ji(c))})}var NI="FILE_UNREADABLE";function I_(e){if(e==null)return"—";if(e<60000)return`${(e/1000).toFixed(1)}s`;return ke(e)}function OI(e){if(e==null)return;let t=Number(e);if(!Number.isInteger(t)||t<=0)C(`Invalid --duration-ms "${e}": expected a positive whole number of milliseconds.`),process.exit(A.USAGE_ERROR);return t}async function kI(e,t,n){let r;try{r=await C_(t)}catch(i){let a=i instanceof Error?i.message:String(i);if(n.format!=="json")C(`Cannot read ${t}: ${a}`);return{file:t,ok:!1,id:void 0,durationSource:"none",error:NI,message:a,exitCode:A.USAGE_ERROR,abort:!1}}let o=await DI(t,r,n);try{let i=await e.audioFiles.upload({file:new File([r],T_(t)),...n.name!=null&&{name:n.name},...o.durationMs!=null&&{duration_ms:o.durationMs}});return{file:t,ok:!0,id:i.id,durationSource:o.source,error:void 0,message:void 0,exitCode:A.SUCCESS,abort:!1}}catch(i){return PI(i,t,o.source,n.format)}}async function DI(e,t,n){if(n.overrideMs!=null)return{durationMs:n.overrideMs,source:"flag"};let r=process.env.NIVA_FFPROBE,o=await v_({filePath:e,bytes:t,noProbe:n.noProbe,...r!=null&&r!==""&&{ffprobePath:r}});if(o.source==="none"&&n.format!=="json")D(`duration unknown for ${e} — install ffmpeg or pass --duration-ms`);return o}function PI(e,t,n,r){let o={file:t,ok:!1,id:void 0,durationSource:n};if(!sn(e)){let a=as(e);if(r!=="json")C(a);return{...o,error:"CONNECTION_ERROR",message:a,exitCode:A.GENERAL_ERROR,abort:!0}}let i=Tn(e);if(r!=="json")Rn(i);return{...o,error:i.code,message:i.message,exitCode:i.exitCode,abort:II.has(i.code)}}async function $I(e,t,n){let o=[(await b(e.audioFiles.getById({audio_file_id:x("audio_files",t)})))?.filename,n,t];return T_(o.find((i)=>i!=null&&i!=="")??t)}async function MI(e,t,n){try{await A_(e,t,n?{}:{flag:"wx"})}catch(r){if(Ee(r)?.code!=="EEXIST")throw r;C(`${e} already exists — pass --out <path> to write elsewhere, or --force to overwrite it.`),process.exit(A.CONFLICT)}}function LI(e,t){if(t==="json"){v(e.map((r)=>({file:r.file,ok:r.ok,...r.id!=null&&{id:r.id},durationSource:r.durationSource,...r.error!=null&&{error:r.error},...r.message!=null&&{message:r.message}})));return}L(["File","ID","Status"],e.map((r)=>({File:r.file,ID:r.id??"—",Status:r.ok?"uploaded":r.error??"failed"})));let n=e.filter((r)=>!r.ok).length;O(`${e.length-n} uploaded, ${n} failed`)}function zI(e,t){if(!sn(e))Ct(e);let n=Tn(e),r=FI(n);if(r==null)Ct(e);if(t==="json")v({error:n.code,message:n.message,plans:r,hint:n.hint,retryable:n.retryable});else Rn(n),D(` Referenced by: ${r.join(", ")}`);process.exit(n.exitCode)}function FI(e){if(e.code!=="AUDIO_FILE_IN_USE")return;let t=e.data?.plans;if(!Array.isArray(t))return;return t.map(String)}async function w_(e){if(e.text!=null&&e.textFile!=null)C("--text and --text-file are mutually exclusive."),process.exit(A.USAGE_ERROR);if(e.text!=null)return e.text;if(e.textFile==null)C("No text to synthesize — pass --text <text> or --text-file <path|->."),process.exit(A.USAGE_ERROR);let n=(e.textFile==="-"?await Fe():await C_(e.textFile,"utf-8")).trim();if(n==="")C(`No text to synthesize: ${e.textFile==="-"?"stdin":e.textFile} is empty.`),process.exit(A.USAGE_ERROR);return n}function ji(e){let t=[{title:"Audio file",rows:[{label:"ID",value:e.id},{label:"Name",value:e.name},{label:"Description",value:e.description},{label:"Type",value:e.type},{label:"Filename",value:e.filename},{label:"Duration",value:I_(e.duration_ms)},{label:"Size",value:e.size_bytes!=null?`${e.size_bytes} bytes`:null},{label:"Default",value:String(e.is_default)}]}];if(e.tts_text!=null||e.voice_id!=null)t.push({title:"TTS",rows:[{label:"Provider",value:e.voice_provider},{label:"Voice",value:e.voice_id},{label:"Text",value:e.tts_text}]});return t}var N_={azul:{hex:"#006eb7",status:"em-uso",note:"O azul histórico da SipPulse"},violeta:{hex:"#7b4bd4",status:"em-uso"},petroleo:{hex:"#00868c",status:"em-uso"},coral:{hex:"#ee5a5a",status:"em-uso",note:"No símbolo vira gradiente",gradient:["#ff8a5c","#e0365a"]},ambar:{hex:"#cc7200",status:"em-uso"},verde:{hex:"#1b9247",status:"em-uso",note:"Fora do software: educação"},magenta:{hex:"#be409d",status:"vaga"},anil:{hex:"#4057c2",status:"vaga"},lima:{hex:"#729513",status:"vaga"},ciano:{hex:"#0089a7",status:"vaga"}};var UI=(e)=>(e in N_),Pc=Object.keys(N_).filter((e)=>UI(e));var jI=/^(?:([^<>]*)<([^<>\s]+)>|([^<>\s]+))$/;function VI(e){let t=jI.exec(e.trim());if(t==null)return null;let n=t[2]??t[3]??"";if(!eR().safeParse(n).success)return null;let r=t[1]?.trim().replaceAll(/^"|"$/g,"")??"";return{name:r===""?null:r,address:n}}var XV=l().trim().max(255).refine((e)=>VI(e)!=null,{message:"Invalid sender"});var O_={"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":{},"audit_log.export_requested":{},"audit_log.export_downloaded":{},"destination.created":{},"destination.updated":{},"destination.deleted":{},"destination.restored":{},"destination.purged":{},"attendant.created":{},"attendant.updated":{},"attendant.sip_credential_rotated":{},"attendant.status_set":{},"attendant.deleted":{},"attendant.restored":{},"attendant.purged":{},"pause_reason.created":{},"pause_reason.updated":{},"pause_reason.deleted":{},"pause_reason.reordered":{},"disposition.created":{},"disposition.updated":{},"disposition.deleted":{},"disposition.reordered":{},"saved_reply.created":{},"saved_reply.updated":{},"saved_reply.deleted":{},"desk_settings.updated":{},"desk_settings.defaults_created":{},"queue.created":{},"queue.updated":{},"queue.deleted":{},"queue.restored":{},"queue.purged":{},"queue.members_replaced":{},"queue.member_removed":{},"queue.members_added":{},"queue.member_updated":{},"holiday.created":{},"holiday.updated":{},"holiday.deleted":{},"holiday_group.created":{},"holiday_group.updated":{},"holiday_group.deleted":{},"holiday_group.imported":{},"holiday_calendar.created":{},"holiday_calendar.updated":{},"holiday_calendar.deleted":{},"holiday_calendar.restored":{},"holiday_calendar.purged":{},"holiday_calendar.ics_imported":{},"holiday_calendar_entry.created":{},"holiday_calendar_entry.updated":{},"holiday_calendar_entry.deleted":{},"invitation.created":{},"invitation.accepted":{},"invitation.revoked":{},"invitation.resent":{},"organization.created":{},"organization.updated":{},"organization.deleted":{},"oauth.authorized":{},"oauth.denied":{},"oauth_grant.revoked":{},"secret.created":{},"secret.updated":{},"secret.deleted":{},"connector.created":{},"connector.updated":{},"connector.deleted":{},"connector.restored":{},"connector.purged":{},"connector.tested":{},"connector.enabled":{},"connector.disabled":{},"connector.sms_sent":{},"connector.phone_number.code_requested":{},"connector.phone_number.verified":{},"connector.phone_number.registered":{},"connector.phone_number.assigned":{},"connector.phone_number.removed":{},"connector.evolution.instance_created":{},"connector.evolution.instance_adopted":{},"connector.evolution.instance_released":{},"signal.created":{},"signal.updated":{},"signal.deleted":{},"signal.restored":{},"signal.purged":{},"insight_view.created":{},"insight_view.updated":{},"insight_view.deleted":{},"insight_view.reordered":{},"dashboard.updated":{},"role.created":{},"role.updated":{},"role.deleted":{},"role.restored":{},"role.purged":{},"channel.created":{},"channel.updated":{},"channel.deleted":{},"channel.activated":{},"channel.deactivated":{},"channel.restored":{},"channel.purged":{},"channel.webchat_key_rotated":{},"channel.webchat_secret_rotated":{},"schedule.created":{},"schedule.updated":{},"schedule.deleted":{},"schedule.restored":{},"schedule.purged":{},"schedule.emergency_set":{},"schedule.emergency_cleared":{},"schedule_exception.created":{},"schedule_exception.updated":{},"schedule_exception.deleted":{},"schedule_exception.restored":{},"schedule_exception.purged":{},"user.created":{},"user.signup":{},"user.login":{},"user.logout":{},"user.password_changed":{},"user.password_reset_requested":{},"user.password_reset_completed":{},"user.account_unlocked":{},"user.second_factor_enrollment_started":{},"user.second_factor_enrolled":{},"user.passkey_registered":{},"user.passkey_renamed":{},"user.passkey_removed":{},"user.second_factor_reset":{},"user.recovery_codes_regenerated":{},"user.session_revoked":{},"user.sessions_revoked":{},"user.role_changed":{},"user.suspended":{},"user.activated":{},"user.removed":{},"block_preset.created":{},"block_preset.updated":{},"block_preset.deleted":{},"saved_recipe.created":{},"saved_recipe.updated":{},"saved_recipe.deleted":{},"visual_plan.created":{},"visual_plan.cloned":{},"visual_plan.updated":{},"visual_plan.deleted":{},"visual_plan.imported":{},"visual_plan.published":{},"visual_plan.restored":{},"visual_plan.purged":{},"webhook_endpoint.created":{},"webhook_endpoint.updated":{},"webhook_endpoint.deleted":{},"webhook_endpoint.restored":{},"webhook_endpoint.purged":{},"webhook_endpoint.secret_rotated":{},"webhook_endpoint.test_sent":{},"webhook_delivery.retried":{},"system.initialized":{},"system.fs_started":{},"system.fs_restarted":{},"system.engine_restarted":{},"system.update_requested":{},"system.update_cancelled":{},"platform_settings.updated":{},"storage_config.updated":{},"recording_storage.updated":{},"storage_cache.purged":{},"platform_admin.assigned":{},"platform_admin.revoked":{},"platform_admin.owner_transferred":{},"platform_admin.mfa_policy_updated":{},"license.activated":{},"org_settings.updated":{},"org_settings.limits_updated":{},"org_plan.modules_updated":{},"org_plan.ai_credential_updated":{},"tenant_module.enabled":{},"tenant_module.disabled":{},"tenant_module.limits_updated":{},"contact.updated":{},"dialer_campaign.created":{},"dialer_campaign.updated":{},"dialer_campaign.deleted":{},"dialer_campaign.restored":{},"dialer_campaign.purged":{},"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":{},"analysis_template.restored":{},"analysis_template.purged":{},"ai_settings.updated":{},"assistant_policy.updated":{},"assistant_models.updated":{},"assistant_conversation.updated":{},"assistant_grant.revoked":{},"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":{},"call_record.export_requested":{},"call_record.export_downloaded":{},"notification.deleted":{},"notification_channel.created":{},"notification_channel.updated":{},"notification_channel.deleted":{},"notification_channel.tested":{},"notification_preference.updated":{},"notification_preference.reset":{},"screen_pop.fetched":{retention:"operational"}},KI=Object.keys(O_);var Vi={telegram:{maxTextLength:4096,supportsButtons:!0,maxButtons:0,supportsList:!1,supportsCarousel:!1,supportsMedia:!0,mediaTypes:["image","audio","video","document"],supportsLocation:!0,supportsTemplate:!1,supportsMarkdown:!0,supportsTypingIndicator:!0,sessionWindow:null,maxMediaSize:{image:10485760,audio:52428800,video:52428800,document:52428800}},whatsapp:{maxTextLength:4096,supportsButtons:!0,maxButtons:3,supportsList:!0,supportsCarousel:!1,supportsMedia:!0,mediaTypes:["image","audio","video","document"],supportsLocation:!0,supportsTemplate:!0,supportsMarkdown:!0,supportsTypingIndicator:!1,sessionWindow:86400000,maxMediaSize:{image:5242880,audio:16777216,video:16777216,document:104857600}},webchat:{maxTextLength:1e4,supportsButtons:!0,maxButtons:0,supportsList:!0,supportsCarousel:!0,supportsMedia:!0,mediaTypes:["image","audio","video","document"],supportsLocation:!0,supportsTemplate:!1,supportsMarkdown:!0,supportsTypingIndicator:!0,sessionWindow:null,maxMediaSize:{image:26214400,audio:26214400,video:26214400,document:26214400}},sms:{maxTextLength:1600,supportsButtons:!1,maxButtons:0,supportsList:!1,supportsCarousel:!1,supportsMedia:!1,mediaTypes:[],supportsLocation:!1,supportsTemplate:!1,supportsMarkdown:!1,supportsTypingIndicator:!1,sessionWindow:null,maxMediaSize:{}}};var pn={label:{max:24},teaser:{max:160}};var Ki=20;var qI=/^[a-z][a-z0-9+.-]*:\/\//,D_=/^\d{1,3}(\.\d{1,3}){3}$/,BI=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,HI=/^\d{1,5}$/;function k_(e){if(e==="null")return!1;if(D_.test(e))return e==="127.0.0.1";return e.split(".").every((t)=>BI.test(t))}function qi(e){let t=e.trim().toLowerCase().replace(qI,""),n=t.search(/[/?#]/);if(n!==-1)t=t.slice(0,n);if(t===""||t.includes("@")||t.includes("["))return null;let r=t.lastIndexOf(":"),o=t,i="";if(r!==-1){o=t.slice(0,r);let a=t.slice(r+1);if(!HI.test(a)||Number(a)<1||Number(a)>65535)return null;i=`:${Number(a)}`}if(o.endsWith("."))o=o.slice(0,-1);if(o.startsWith("*.")){let a=o.slice(2);if(!a.includes(".")||!k_(a)||D_.test(a))return null;return`*.${a}${i}`}if(!k_(o))return null;return`${o}${i}`}var $c=g({}).default({}),Mc=g({phone_number_id:l().min(1),voice_enabled:F().default(!0),chat_enabled:F().default(!0),sip_username:l().optional(),sip_password_encrypted:l().optional(),sip_password_iv:l().optional(),session_timeout_minutes:f().int().min(5).max(10080).default(1440),business_name:l().optional(),display_phone_number:l().optional(),last_webhook_received_at:Zt.datetime().optional(),last_webhook_message_id:l().optional(),last_webhook_status_id:l().optional(),last_webhook_phone_number_id:l().optional(),last_webhook_error:l().optional()}),Lc=g({bot_token:l().min(1),webhook_secret:l().min(1),allow_groups:F().default(!1),session_timeout_minutes:f().int().min(5).max(10080).default(1440),bot_username:l().optional()}),WI=l().transform((e,t)=>{let n=qi(e);if(n==null)return t.addIssue({code:"custom",message:"Use a host with an optional port, or *.domain"}),Qm;return n}),GI=/^#[0-9a-fA-F]{6}$/,ZI=Pc,YI=l().refine((e)=>ZI.includes(e)||GI.test(e),{message:"Use a palette color name or #rrggbb"}),Ue={allowedOrigins:{max:20},title:{max:80},subtitle:{max:120},teaser:pn.teaser,rememberVisitorDays:{min:1,max:90,default:30},messagesPerMinute:{min:5,max:120,default:Ki},maxConcurrentSessions:{min:1,max:5000,default:200}},zc=g({allowed_origins:z(WI).min(1).max(Ue.allowedOrigins.max),appearance:g({title:l().max(Ue.title.max).default(""),subtitle:l().max(Ue.subtitle.max).default(""),teaser:l().max(Ue.teaser.max).default(""),color:YI.default("violeta"),theme:P(["auto","light","dark"]).default("auto")}).default({title:"",subtitle:"",teaser:"",color:"violeta",theme:"auto"}),prechat:g({enabled:F().default(!1),fields:g({name:F().default(!0),email:F().default(!1),phone:F().default(!1)}).default({name:!0,email:!1,phone:!1})}).default({enabled:!1,fields:{name:!0,email:!1,phone:!1}}),consent:g({enabled:F().default(!1),privacy_url:Qy({protocol:/^https$/}).optional()}).default({enabled:!1}),identity:g({enabled:F().default(!1),secret_encrypted:l().optional(),secret_iv:l().optional(),secret_hint:l().optional(),secret_created_at:Zt.datetime().optional(),previous_secret_encrypted:l().optional(),previous_secret_iv:l().optional(),previous_expires_at:Zt.datetime().optional()}).default({enabled:!1}),remember_visitor_days:f().int().min(Ue.rememberVisitorDays.min).max(Ue.rememberVisitorDays.max).default(Ue.rememberVisitorDays.default),limits:g({messages_per_minute:f().int().min(Ue.messagesPerMinute.min).max(Ue.messagesPerMinute.max).default(Ue.messagesPerMinute.default),max_concurrent_sessions:f().int().min(Ue.maxConcurrentSessions.min).max(Ue.maxConcurrentSessions.max).default(Ue.maxConcurrentSessions.default)}).default({messages_per_minute:Ue.messagesPerMinute.default,max_concurrent_sessions:Ue.maxConcurrentSessions.default}),bot_challenge:P(["auto","always","never"]).default("auto")}),P_={sip:$c,telegram:Lc,whatsapp:Mc,webchat:zc,sms:g({}).default({}),rcs:g({}).default({})};var mr=["sip"],lo=["telegram","webchat","sms","rcs"],fr=["whatsapp"],Fc=[...mr,...lo,...fr],$_=[...mr,...fr],M_=[...lo,...fr];var fK=new Set(mr),gK=new Set(fr);var iN=g({chatSessionId:l(),callRecordId:l(),orgId:l(),agentUser:l(),agentHost:l().nullable()}),aN=Re("kind",[g({kind:I("agent_message"),text:l()}),g({kind:I("attendant_message"),text:l().min(1).optional(),media_id:l().min(1).optional(),author_user_id:l()}).refine((e)=>e.text!==void 0||e.media_id!==void 0),g({kind:I("attendant_note"),text:l().min(1),author_user_id:l(),mentions:z(l()).optional()}),g({kind:I("attendant_template"),template:l().min(1),language:l().min(1),components:z(pt()),author_user_id:l()}),g({kind:I("desk_offer"),conversation_id:l()}),g({kind:I("desk_resolved"),conversation_id:l()}),g({kind:I("desk_transferred"),conversation_id:l()}),g({kind:I("timeout"),token:l(),deadlineMs:f()})]);var L_=String.raw`(?:25[0-5]|2[0-4]\d|[01]?\d\d?)`,z_=String.raw`(?:${L_}\.){3}${L_}`,sN=String.raw`${z_}(?:\/(?:3[0-2]|[12]?\d))?`,AK=new RegExp(`^${z_}$`);var He="[0-9a-fA-F]{1,4}",cN=[`(?:${He}:){7}${He}`,`(?:${He}:){1,7}:`,`(?:${He}:){1,6}:${He}`,`(?:${He}:){1,5}(?::${He}){1,2}`,`(?:${He}:){1,4}(?::${He}){1,3}`,`(?:${He}:){1,3}(?::${He}){1,4}`,`(?:${He}:){1,2}(?::${He}){1,5}`,`${He}:(?::${He}){1,6}`,`:(?::${He}){1,7}`,"::(?:ffff(?::0{1,4})?:)?"],lN=`(?:${cN.join("|")})`,dN=String.raw`${lN}(?:\/(?:12[0-8]|1[01]\d|[1-9]?\d))?`,TK=new RegExp(`^(?:${sN}|${dN})$`);function $t(e){let t=e.length;while(t>0&&e[t-1]==="/")t-=1;return e.slice(0,t)}function uN(e){let t=e;if(t==null||typeof t!=="object")throw Error("Execution plan must be a JSON object with { version, startNodeId, nodes, adjacency }");if(!("nodes"in t)||t.nodes==null||typeof t.nodes!=="object"){let n;if(!("nodes"in t))n="missing";else if(Array.isArray(t.nodes))n="an array";else n=typeof t.nodes;throw Error(`Execution plan "nodes" must be an object keyed by node ID, not ${n}`)}if(!("adjacency"in t)||t.adjacency==null||typeof t.adjacency!=="object")throw Error('Execution plan "adjacency" must be an object mapping source → { handle → target }')}function Uc(e){uN(e);let t=Object.entries(e.nodes).map(([r,o])=>({id:r,type:o.type,label:o.label,varName:o.varName,position:{x:0,y:0},config:o.config})),n=[];for(let[r,o]of Object.entries(e.adjacency))for(let[i,a]of Object.entries(o))n.push({id:`${r}-${i}-${a}`,source:r,sourceHandle:i,target:a,targetHandle:"in"});return F_({nodes:t,edges:n,viewport:{x:0,y:0,zoom:1}})}function pN(e){if(!Object.hasOwn(e,"channelType"))return e;let t={...e};return delete t.channelType,t}function mN(e){let t=e.channelType;return t==="chat"||t==="both"?t:"voice"}function F_(e){let t=e.nodes.find((o)=>o.type==="start");if(t==null)return e;let n=mN(t.config),r=e.edges.some((o)=>o.source===t.id&&o.sourceHandle==="next");return{...e,nodes:e.nodes.map((o)=>o.type==="start"?{...o,config:pN(o.config)}:o),edges:n==="both"?e.edges:e.edges.flatMap((o)=>{if(o.source!==t.id)return[o];if(r&&o.sourceHandle===n)return[];return[o.sourceHandle==="next"?{...o,sourceHandle:n}:o]})}}var U_=["rtp","sip_info","inband","other"],j_=64;var V_=g({digit:l().min(1).max(1),source:P(U_),at:Zt.datetime(),node_id:l().nullable()}),fN=g({audio_in_packets:f().int().nonnegative().nullable(),audio_out_packets:f().int().nonnegative().nullable(),dtmf_in_packets:f().int().nonnegative().nullable(),codec:l().nullable(),dtmf_type:l().nullable(),jitter_max_ms:f().nullable(),loss_rate:f().nullable(),mos:f().nullable(),quality_pct:f().nullable(),digits:z(V_).max(j_)});var Pn=3600;var Yt=["none","both","caller"],jc=g({callerSpeechMs:f().int().min(0),ivrSpeechMs:f().int().min(0),version:f().int().min(1)});var mn=["post_call","live"],Vc=g({startByte:f().int().min(0),endByte:f().int().min(0),openedAtMs:f().int().min(0)}).refine((e)=>e.endByte>=e.startByte,{message:"endByte must be greater than or equal to startByte",path:["endByte"]}),K_=g({nodeId:l().min(1),kind:P(["recording","transcription","analysis"]),atByte:f().int().min(0),atMs:f().int().min(0),patch:ie(l(),pt())}),q_=g({samplingPercentage:f().int().min(0).max(100).describe("Recording sampling percentage"),transcriptionSamplingPercentage:f().int().min(0).max(100).default(100).describe("Transcription sampling percentage among selected recordings"),transcriptionEnabled:F().describe("Enable transcription"),transcriptionLanguage:l().nullable().describe("Transcription language"),transcriptionMinDurationSeconds:f().int().min(0).max(Pn).describe("Minimum transcription duration"),transcriptionSpeechRequirement:P(Yt).default("none").describe("Which sides must have spoken for automatic transcription"),transcriptionType:P(mn).default("post_call").describe("Transcription type: after the call ends, or live during the whole transcription window"),anonymizeEnabled:F().describe("Anonymize the transcript"),speechAnalyticsEnabled:F().describe("Enable speech analytics"),sentimentEnabled:F().optional().describe("Enable sentiment analysis"),topicDetectionTopics:z(l()).describe("Topic detection topics"),intentDetectionIntents:z(l()).describe("Intent detection intents"),autoAnalysisEnabled:F().describe("Enable structured analyses"),autoAnalysisInheritOrg:F().describe("Inherit structured analyses from the organization"),autoAnalysisIds:z(l()).describe("Structured analysis IDs")}).transform((e)=>({...e,sentimentEnabled:e.sentimentEnabled??e.speechAnalyticsEnabled})),gN=g({speechAnalyticsEnabled:F(),sentimentEnabled:F().optional(),topicDetectionTopics:z(l()),intentDetectionIntents:z(l()),autoAnalysisEnabled:F(),autoAnalysisIds:z(l())}).transform((e)=>({...e,sentimentEnabled:e.sentimentEnabled??e.speechAnalyticsEnabled}));var hN=g({usePlan:F().default(!0).describe("Use plan recording profile"),samplingPercentage:f().int().min(0).max(100).default(100).describe("Recording sampling percentage"),transcriptionSamplingPercentage:f().int().min(0).max(100).default(100).describe("Transcription sampling percentage"),transcriptionEnabled:F().default(!1).describe("Enable transcription"),transcriptionLanguage:l().default("").describe("Transcription language"),transcriptionMinDurationSeconds:f().int().min(0).max(Pn).default(0).describe("Minimum transcription duration"),transcriptionSpeechRequirement:P(Yt).default("none").describe("Which sides must have spoken for automatic transcription"),transcriptionType:P(mn).default("post_call").describe("Transcription type: after the call ends, or live during the whole transcription window"),anonymizeEnabled:F().default(!1).describe("Anonymize the transcript"),speechAnalyticsEnabled:F().default(!1).describe("Enable speech analytics"),sentimentEnabled:F().optional().describe("Enable sentiment analysis"),topicDetectionTopics:z(l()).default([]).describe("Topic detection topics"),intentDetectionIntents:z(l()).default([]).describe("Intent detection intents"),autoAnalysisEnabled:F().default(!1).describe("Enable structured analyses"),autoAnalysisIds:z(l()).default([]).describe("Structured analysis IDs")}).transform((e)=>({...e,sentimentEnabled:e.sentimentEnabled??e.speechAnalyticsEnabled})),B_=g({sampleRate:f().int().positive(),channels:f().int().positive(),bitsPerSample:f().int().positive()});var yN=g({sampled:F(),transcriptionSampled:F().optional(),profile:q_,recordingFormat:B_.optional(),recordingIntervals:Vc.array().default([]),transcriptionWindows:Vc.array().default([]),directives:K_.array().default([]),voiceActivity:jc.optional()});var _N=["recordingEnabled","samplingPercentage","transcriptionSamplingPercentage","transcriptionEnabled","transcriptionLanguage","transcriptionMinDurationSeconds","transcriptionSpeechRequirement","transcriptionType","anonymizeEnabled","speechAnalyticsEnabled","sentimentEnabled","topicDetectionTopics","intentDetectionIntents","structuredAnalysisEnabled","structuredAnalysisIds"];function qc(e,t,n,r,o=!1){let i=bN(r),a=new Map(n.map((d)=>[d.id,d])),s=wN(t,o),c={};return vN({startNodeId:e,planState:s,nodesById:a,adjacency:r,incoming:i,result:c}),c}function bN(e){let t=new Map;for(let[n,r]of e)for(let o of r.values()){let i=t.get(o)??[];t.set(o,[...i,n])}return t}function vN(e){let{startNodeId:t,planState:n,nodesById:r,adjacency:o,incoming:i,result:a}=e,s=[t],c=new Set(s),d=0,u=Math.max(20,r.size*r.size*4);while(s.length>0&&d++<u){let m=s.shift();if(m===void 0)continue;c.delete(m);let y=r.get(m);if(y===void 0)continue;let _=SN(m,n,y,i,a);if(MN(a[m],_))continue;a[m]=_,EN(s,c,o.get(m)?.values()??[])}}function SN(e,t,n,r,o){let i=(r.get(e)??[]).map((s)=>o[s]).filter((s)=>s!==void 0),a=xN(i,t);return CN(a,n)}function xN(e,t){let n=e[0];return n===void 0?t:e.slice(1).reduce((r,o)=>PN(r,o),n)}function EN(e,t,n){for(let r of n){if(t.has(r))continue;e.push(r),t.add(r)}}function wN(e,t){let n={kind:"plan"};return{recordingEnabled:je(t,n),samplingPercentage:je(e.samplingPercentage,n),transcriptionSamplingPercentage:je(e.transcriptionSamplingPercentage,n),transcriptionEnabled:je(e.transcriptionEnabled,n),transcriptionLanguage:je(e.transcriptionLanguage,n),transcriptionMinDurationSeconds:je(e.transcriptionMinDurationSeconds,n),transcriptionSpeechRequirement:je(e.transcriptionSpeechRequirement,n),transcriptionType:je(e.transcriptionType,n),anonymizeEnabled:je(e.anonymizeEnabled,n),speechAnalyticsEnabled:je(e.speechAnalyticsEnabled,n),sentimentEnabled:je(e.sentimentEnabled,n),topicDetectionTopics:je([...e.topicDetectionTopics],n),intentDetectionIntents:je([...e.intentDetectionIntents],n),structuredAnalysisEnabled:je(e.autoAnalysisEnabled,n),structuredAnalysisIds:je([...e.autoAnalysisIds],n)}}function CN(e,t){let n=AN(t),r={kind:"node",nodeId:t.id,nodeLabel:t.label};return{recordingEnabled:Xe(e.recordingEnabled,n.recordingEnabled,r),samplingPercentage:Xe(e.samplingPercentage,n.samplingPercentage,r),transcriptionSamplingPercentage:Xe(e.transcriptionSamplingPercentage,n.transcriptionSamplingPercentage,r),transcriptionEnabled:Xe(e.transcriptionEnabled,n.transcriptionEnabled,r),transcriptionLanguage:Xe(e.transcriptionLanguage,n.transcriptionLanguage,r),transcriptionMinDurationSeconds:Xe(e.transcriptionMinDurationSeconds,n.transcriptionMinDurationSeconds,r),transcriptionSpeechRequirement:Xe(e.transcriptionSpeechRequirement,n.transcriptionSpeechRequirement,r),transcriptionType:Xe(e.transcriptionType,n.transcriptionType,r),anonymizeEnabled:Xe(e.anonymizeEnabled,n.anonymizeEnabled,r),speechAnalyticsEnabled:Xe(e.speechAnalyticsEnabled,n.speechAnalyticsEnabled,r),sentimentEnabled:Xe(e.sentimentEnabled,n.sentimentEnabled,r),topicDetectionTopics:Xe(e.topicDetectionTopics,n.topicDetectionTopics,r),intentDetectionIntents:Xe(e.intentDetectionIntents,n.intentDetectionIntents,r),structuredAnalysisEnabled:Xe(e.structuredAnalysisEnabled,n.structuredAnalysisEnabled,r),structuredAnalysisIds:Xe(e.structuredAnalysisIds,n.structuredAnalysisIds,r)}}function AN(e){if(e.type==="recording")return TN(e.config);if(e.type==="transcription")return RN(e.config);if(e.type==="analysis")return IN(e.config);return{}}function TN(e){let t={},n=e.enabled;if(typeof n==="boolean")t.recordingEnabled=n;let r=e.samplingPercentage;if(typeof r==="number")t.samplingPercentage=r;return t}function RN(e){let t={},n=e.enabled;if(typeof n==="boolean")t.transcriptionEnabled=n;let r=e.samplingPercentage;if(typeof r==="number")t.transcriptionSamplingPercentage=r;let o=e.language;if(typeof o==="string")t.transcriptionLanguage=o.trim()||null;let i=e.minDurationSeconds;if(typeof i==="number")t.transcriptionMinDurationSeconds=i;let a=e.speechRequirement;if(ON(a))t.transcriptionSpeechRequirement=a;let s=e.transcriptionType;if(DN(s))t.transcriptionType=s;let c=e.anonymizeEnabled;if(typeof c==="boolean")t.anonymizeEnabled=c;let{speechAnalyticsEnabled:d,sentimentEnabled:u}=e;if(typeof d==="boolean")t.speechAnalyticsEnabled=d;if(typeof u==="boolean")t.sentimentEnabled=u;else if(typeof d==="boolean")t.sentimentEnabled=d;return t}function IN(e){let t={},{speechAnalyticsEnabled:n,sentimentEnabled:r}=e;if(typeof n==="boolean")t.speechAnalyticsEnabled=n;if(typeof r==="boolean")t.sentimentEnabled=r;else if(r===void 0&&typeof n==="boolean")t.sentimentEnabled=n;let o=e.topicDetectionTopics;if(Kc(o))t.topicDetectionTopics=o;let i=e.intentDetectionIntents;if(Kc(i))t.intentDetectionIntents=i;let a=e.structuredAnalysisEnabled;if(typeof a==="boolean")t.structuredAnalysisEnabled=a;let s=e.structuredAnalysisIds;if(Kc(s))t.structuredAnalysisIds=s;return t}var NN=Yt;function ON(e){return typeof e==="string"&&NN.includes(e)}var kN=mn;function DN(e){return typeof e==="string"&&kN.includes(e)}function Kc(e){return Array.isArray(e)&&e.every((t)=>typeof t==="string")}function Xe(e,t,n){return t===void 0?e:je(t,n)}function je(e,t){return{kind:"known",value:e,origin:t}}function PN(e,t){return{recordingEnabled:Qe(e.recordingEnabled,t.recordingEnabled),samplingPercentage:Qe(e.samplingPercentage,t.samplingPercentage),transcriptionSamplingPercentage:Qe(e.transcriptionSamplingPercentage,t.transcriptionSamplingPercentage),transcriptionEnabled:Qe(e.transcriptionEnabled,t.transcriptionEnabled),transcriptionLanguage:Qe(e.transcriptionLanguage,t.transcriptionLanguage),transcriptionMinDurationSeconds:Qe(e.transcriptionMinDurationSeconds,t.transcriptionMinDurationSeconds),transcriptionSpeechRequirement:Qe(e.transcriptionSpeechRequirement,t.transcriptionSpeechRequirement),transcriptionType:Qe(e.transcriptionType,t.transcriptionType),anonymizeEnabled:Qe(e.anonymizeEnabled,t.anonymizeEnabled),speechAnalyticsEnabled:Qe(e.speechAnalyticsEnabled,t.speechAnalyticsEnabled),sentimentEnabled:Qe(e.sentimentEnabled,t.sentimentEnabled),topicDetectionTopics:Qe(e.topicDetectionTopics,t.topicDetectionTopics),intentDetectionIntents:Qe(e.intentDetectionIntents,t.intentDetectionIntents),structuredAnalysisEnabled:Qe(e.structuredAnalysisEnabled,t.structuredAnalysisEnabled),structuredAnalysisIds:Qe(e.structuredAnalysisIds,t.structuredAnalysisIds)}}function Qe(e,t){let n=[...H_(e),...H_(t)],r=[];for(let o of n)if(!r.some((i)=>W_(i.value,o.value)))r.push(o);if(r.length===1){let o=$N(e,t,r[0].viaNodeLabel);return je(r[0].value,o)}return{kind:"indeterminate",branches:r}}function $N(e,t,n){if(e.kind==="known")return e.origin;if(t.kind==="known")return t.origin;return{kind:"node",nodeId:"",nodeLabel:n}}function H_(e){if(e.kind==="indeterminate")return e.branches;let t=e.origin.kind==="plan"?"__plan__":e.origin.nodeLabel;return[{value:e.value,viaNodeLabel:t}]}function W_(e,t){return JSON.stringify(e)===JSON.stringify(t)}function MN(e,t){if(e===void 0)return!1;return _N.every((n)=>W_(e[n],t[n]))}function U(e){let t=e.producedVariables;return{meta:{...e.meta,inputs:e.meta.type==="start"?[]:[{key:"in",labelKey:"editor:handles.in"}],producedVariables:typeof t==="function"?(r)=>t(r):t,defaultConfig:e.configSchema.parse({})},configSchema:e.configSchema,producedVariables:e.producedVariables}}var Bi="secrets",LN="secrets".replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);function G_(){return new RegExp(String.raw`\{\{\s*${LN}\.([A-Z][A-Z0-9_]*)\s*\}\}`,"g")}function Z_(e){if(!e.includes("{{"))return[];let t=new Set;for(let n of e.matchAll(G_()))t.add(n[1]);return[...t]}var Y_={httpRequest:new Set(["url","headers","body"]),apiSwitch:new Set(["url","headers","body"]),webhook:new Set(["url","headers","body"])};function J_(e,t){return Y_[e]?.has(t)===!0}function Bc(e,t,n){if(typeof e==="string"){n(t,e);return}if(Array.isArray(e)){e.forEach((r,o)=>Bc(r,`${t}.${o}`,n));return}if(e!=null&&typeof e==="object")for(let[r,o]of Object.entries(e))Bc(o,t===""?r:`${t}.${r}`,n)}function Hi(e){let t=new Set,n=[];return Bc(e.config,"",(r,o)=>{let i=Z_(o);if(i.length===0)return;let a=r.split(".")[0]??"";if(J_(e.type,a)){for(let s of i)t.add(s);return}for(let s of i)n.push({nodeId:e.id,label:e.label,field:r,name:s})}),{allowed:[...t],misplaced:n}}function Wi(e){let t=new Set,n=[];for(let r of e){let o=Hi(r);for(let i of o.allowed)t.add(i);for(let i of o.misplaced)t.add(i.name),n.push(i)}return{names:t,misplaced:n}}function zN(e){return e===`
|
|
90
|
-
`||e==="\r"||e==="\u2028"||e==="\u2029"}function FN(e,t){for(let n=t;n<e.length;n++)if(zN(e[n]))return n;return e.length}function X_(e){let t=[],n=0,r=-1,o=-1;for(;;){let i=e.indexOf("{{",n);if(i===-1)return t;if(r<i+3){if(r=e.indexOf("}}",i+3),r===-1)return t}if(o<i+2)o=FN(e,i+2);if(o<r){n=o+1;continue}t.push({start:i,end:r+2,key:e.slice(i+2,r)}),n=r+2}}function UN(e,t,n){let r="",o=0;return t.forEach((i,a)=>{r+=e.slice(o,i.start)+n(a),o=i.end}),r+e.slice(o)}function Hc(e,t){let n=[],r=0;for(let o of X_(e)){let i=o.start-1>=r&&e[o.start-1]==='"'?o.start-1:o.start,a=e[o.end]==='"'?o.end+1:o.end;n.push({start:i,end:a}),r=a}return UN(e,n,(o)=>t(e.slice(n[o].start,n[o].end)))}var Gi=200;function Q_(e,t){let n=e[t];if(n==="*"||n==="+")return 1;if(n==="{"){let r=e.indexOf("}",t);if(r!==-1&&/^\d+,$/.test(e.slice(t+1,r)))return r-t+1}return 0}function jN(e,t){let n=t+1;while(n<e.length&&e[n]!=="]")n+=e[n]==="\\"?2:1;return n+1}function VN(e,t,n){let r=n.pop()??{repeat:!1},o=Q_(e,t+1);if(o>0&&r.repeat)return{catastrophic:!0,next:t};if((r.repeat||o>0)&&n.length>0)n.at(-1).repeat=!0;return{catastrophic:!1,next:t+(o>0?1+o:1)}}function KN(e,t,n){let r=e[t];if(r==="\\")return{catastrophic:!1,next:t+2};if(r==="[")return{catastrophic:!1,next:jN(e,t)};if(r==="(")return n.push({repeat:!1}),{catastrophic:!1,next:t+1};if(r===")")return VN(e,t,n);let o=Q_(e,t);if(o>0&&n.length>0)n.at(-1).repeat=!0;return{catastrophic:!1,next:t+(o>0?o:1)}}function Wc(e){let t=[],n=0;while(n<e.length){let{catastrophic:r,next:o}=KN(e,n,t);if(r)return!0;n=o}return!1}function qN(e){let t=e.split("/");if(t.length<3)return null;return{key:t[0].trim(),pattern:t.slice(1,-1).join("/"),replacement:t.at(-1)}}function Gc(e){if(!e.includes("{{"))return{valid:!0};for(let t of X_(e)){let n=e.slice(t.start,t.end),r=qN(t.key.trim());if(r===null)continue;if(r.pattern.length>Gi)return{valid:!1,error:`Regex pattern too long in "${n}" (max ${Gi})`};if(Wc(r.pattern))return{valid:!1,error:`Unsafe regex (possible catastrophic backtracking) in "${n}"`};try{new RegExp(r.pattern)}catch(o){let i=o instanceof Error?o.message:String(o);return{valid:!1,error:`Invalid regex in "${n}": ${i}`}}}return{valid:!0}}var nb=["volume","weekday_hour","composition","plans","topics","intents"],rb=l().regex(/^signal:sig_[A-Za-z0-9]+$/),BN=Be([P(nb),rb]),HN=f().int().min(1).max(4);var WN=g({id:l(),type:l(),x:f(),y:f()}),GN=g({source:l(),target:l()}),ZN=g({nodes:z(WN),edges:z(GN)});var ob=["pre","post"];var ib=["accepted","declined","voicemail","timeout"];var ab=["voicemail","announcement","ivr","screening","unknown"];var Zc=["busy","no_answer","failed","machine"];var Yc=["offline","available","paused","not_responding","ringing","busy","wrap_up"],sb=["attendant","system","supervisor"];var cb=["voice","chat"],lb=["queued","offered","active","waiting_customer","wrap_up","closed"],db=["completed","abandoned","timeout","full","no_attendant","transferred","attendant_offline","refused","no_answer","busy","failed"];var YN=["useful","not_useful"],i5=[...YN,"discarded"];var uo=["channels","calls","registrations","codecs","modules","aliases"];var JN=new Set(["phone","telephone","telefone","fone","celular","cel","mobile","movel","numero","number","num","tel","msisdn","whatsapp","telefone celular","numero de telefone"]),XN=new Set(["name","nome","cliente","contato","contact","nome completo","razao social","full name"]);function QN(e){return e.normalize("NFD").replaceAll(/[\u0300-\u036F]/g,"").toLowerCase().replaceAll(/[\s\-_]+/g," ").trim()}function eO(e){return e.normalize("NFD").replaceAll(/[\u0300-\u036F]/g,"").toLowerCase().replaceAll(/[^a-z0-9]+/g,"_").replace(/^_/,"").replace(/_$/,"")}function ub(e){return JN.has(e)||e.includes("telefone")||e.includes("phone")||e.includes("celular")}function tO(e){return XN.has(e)}function Jc(e){let t={},n={},r=new Set,o=!1,i=!1;function a(s){let c=s,d=2;while(r.has(c))c=`${s}_${String(d)}`,d+=1;return r.add(c),c}for(let s of e){let c=QN(s);if(c===""){t[s]="ignore";continue}if(ub(c)&&!o){t[s]="phone",o=!0;continue}if(tO(c)&&!i&&!ub(c)){t[s]="name",i=!0;continue}let d=eO(s);if(d===""){t[s]="ignore";continue}t[s]="custom",n[s]=a(d)}return{roles:t,customNames:n}}var $n={_nodes:{start:{name:"Start",description:"Where every call begins — receives caller ID, DID, and timestamp"},playback:{name:"Playback",description:"Plays a message using text-to-speech or an audio file"},ivr:{name:"IVR Menu",description:"Presents a menu and routes the call based on the digit pressed"},collectDigits:{name:"Collect Digits",description:"Collects a sequence of digits like CPF, account number, or PIN"},transfer:{name:"Transfer",description:"Bridges or redirects the call to an agent, queue, or external number"},hangup:{name:"Hang Up",description:"Terminates the call — place at the end of each plan path"},timeRouting:{name:"Schedule",description:"Checks the current time against a schedule to route on/off hours"},switchCase:{name:"Condition",description:"Evaluates a variable against regex patterns to pick a path"},trafficSplit:{name:"Traffic Split",description:"Distributes calls across several paths by percentage — A/B testing, load balancing between destinations and canary rollout"},setVariable:{name:"Set Variable",description:"Saves a value to reuse later during plan execution"},sequence:{name:"Sequence",description:"Generates sequential numbers for protocols, tickets, or any identifier — DB-backed, never regresses"},counter:{name:"Counter",description:"Counts attempts, events, or anything else — per call or across calls, with an optional limit output"},httpRequest:{name:"HTTP Request",description:"Calls a REST API and stores the response for downstream nodes"},webhook:{name:"Webhook",description:"Fires an HTTP call to an external system and moves on without waiting"},dataTransform:{name:"Transform Data",description:"Applies text, number, date, list, phone, and speech operations to a value without writing code"},sendDtmf:{name:"Send DTMF",description:"Sends DTMF tones to a bridged channel or PBX"},subPlan:{name:"Sub-Plan",description:"Delegates execution to another published plan and returns"},aiAgent:{name:"AI Agent",description:"Hands the call to an AI agent for free-form conversation"},retellAgent:{name:"Retell Agent",description:"Hands the call to a Retell voice agent"},vapiAgent:{name:"Vapi Agent",description:"Hands the call to a Vapi voice assistant"},elevenlabsAgent:{name:"ElevenLabs Agent",description:"Hands the call to an ElevenLabs voice agent"},openaiLiveAgent:{name:"GPT-Live Agent",description:"Hands the call to OpenAI GPT-Live on your organization's own project"},voiceRecognition:{name:"Voice Recognition",description:"Listens to the caller, transcribes speech, and routes by intent"},tell:{name:"Message",description:"Says something to the user — plays audio in voice, sends a message in chat"},menu:{name:"Menu",description:"Presents options and routes by the user's choice — DTMF in voice, buttons in chat"},capture:{name:"Capture",description:"Collects user input — DTMF digits or speech in voice, text in chat"},routeAi:{name:"AI Classifier",description:"Classifies text via AI and routes by intent — a smart condition"},channelRouter:{name:"Channel",description:"Routes the plan based on the active channel mode (voice or chat)"},apiSwitch:{name:"API Switch",description:"Plays a prompt, collects digits, calls an API, and routes by response attribute (legacy)"},enableRecord:{name:"Enable Recording",description:"Activates call recording during plan execution with sampling and analysis options (legacy)"},recording:{name:"Recording",description:"Starts or stops recording from this point in the plan"},transcription:{name:"Transcription",description:"Chooses the transcription scope from this point in the plan"},analysis:{name:"Analysis",description:"Chooses analyses for all available transcription; each block overrides only defined fields"},whatsappTemplate:{name:"Send WhatsApp template",description:"Sends an approved Meta template through WhatsApp Business, in a voice call or in chat"},whatsappMessage:{name:"Send WhatsApp message",description:"Sends a free-text WhatsApp message through an Evolution number, with no template, in a voice call or in chat"},sendSms:{name:"Send SMS",description:"Sends a text message through Twilio, in a voice call or in chat"},phoneLookup:{name:"Phone lookup",description:"Checks a number's format and, optionally, its line type and carrier through Twilio Lookup"},verifyCode:{name:"Verify code",description:"Sends a verification code through Twilio Verify and checks it, in a voice call or in chat"},enterQueue:{name:"Enter queue",description:"Puts the call in a queue of the Mesa: the caller waits with music until an attendant takes it"},queryQueue:{name:"Query queue",description:"Reads who is waiting, who is free and the estimated wait of a queue, ready for a prompt"},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"}},_handles:{in:"In",next:"Next",timeout:"Timeout",error:"Error",answered:"Answered",busy:"Busy",noAnswer:"No Answer",failed:"Failed",sent:"Sent",completed:"Completed",valid:"Valid",invalid:"Invalid",approved:"Approved",rejected:"Rejected",recognized:"Recognized",noInput:"No Input",notApplicable:"Not Applicable",maxRetries:"Max Retries",captured:"Captured",onHours:"On Hours",offHours:"Off Hours",holiday:"Holiday",emergency:"Emergency",queueAnswered:"Answered",queueTimeout:"Timed Out",full:"Queue Full",noAttendant:"No Attendant",default:"Default",fallback:"Fallback",noMatch:"No Match",collected:"Collected",skipped:"Skipped",limitReached:"Limit Reached",voice:"Voice",chat:"Chat",telegram:"Telegram",whatsapp:"WhatsApp",webchat:"Webchat",sms:"SMS"},_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."},playback:{audio:"Audio to play. Use TTS (text-to-speech) or a pre-recorded audio file."},hangup:{cause:"SIP hangup cause code (e.g., 'NORMAL_CLEARING'). Omit for default."},ivr:{audio:"Audio prompt played before collecting DTMF input.",timeout:"Seconds to wait for DTMF input after audio finishes (1-60).",maxAttempts:"Maximum retry attempts before following the error output (1-10)."},collectDigits:{audio:"Audio prompt played before collecting digits.",minDigits:"Minimum number of digits required (1-20).",maxDigits:"Maximum number of digits to collect (1-20).",terminator:"Key that terminates digit collection (e.g., '#'). Single character.",timeout:"Seconds to wait for the first digit after audio finishes (1-60).",interDigitTimeout:"Seconds to wait between consecutive digits (1-30).",maxAttempts:"Maximum retry attempts on invalid input (1-10).",invalidAudio:"Audio played when input fails regex validation. Optional.",regex:"Regex pattern to validate collected digits. Empty means accept any.",resetDigit:"Key that clears collected digits and restarts. Single character. Empty to disable."},transfer:{method:"Transfer method. 'bridge' keeps call control; 'transfer' hands off completely.",destinations:"SIP URIs or phone numbers to dial. At least one required. Tried in order.",timeout:"Ring timeout in seconds per destination (5-120). Omit for carrier default.",attachedData:"Key/value pairs delivered to the agent at transfer (screen-pop). Values support templates."},timeRouting:{scheduleId:"Schedule ID for time-based routing. Routes to onHours/offHours/holiday outputs."},switchCase:{expression:"Template expression to evaluate, e.g., '{{ivr.digits}}'. Matched against case patterns.",cases:"List of patterns to match. Each creates a dynamic output handle 'match:<pattern>'."},trafficSplit:{paths:"Weighted paths. Each creates a dynamic output handle 'path:<name>'.",mode:"'contact' keeps the same contact on the same path (stateless hash); 'call' draws per call (stateless, approximate); 'exact' rotates through a Redis counter so the proportion closes even at low volume."},setVariable:{assignments:"List of variable assignments. At least one required."},counter:{name:"Counter name. Supports templates, e.g. 'attempts_{{start.callerid}}'.",action:"Operation applied to the counter. 'reset' sets it to zero and ignores step.",step:"Amount added or subtracted on each execution (1-1000000). Ignored when the action is 'reset'.",limit:"Value that routes to the 'limitReached' output once the counter reaches it. Empty means count only.",scope:"'call' starts from zero on every call; 'plan' persists across the calls of one plan; 'organization' persists across every plan of the organization.",ttlSeconds:"Lifetime in seconds of a 'plan' or 'organization' counter (60-31536000). Applied when the key is created, so counting does not renew the window."},httpRequest:{method:"HTTP method for the request.",url:"Request URL. Supports template expressions, e.g., 'https://api.example.com/{{start.callerid}}'.",headers:"HTTP headers as key-value pairs. Values support template expressions.",body:"Request body (JSON string). Template expressions allowed. Only for POST/PUT/PATCH.",timeout:"Request timeout in milliseconds. Omit for default."},webhook:{method:"HTTP method for the request.",url:"Destination URL. Supports template expressions, e.g., 'https://hooks.example.com/{{start.callerid}}'.",headers:"HTTP headers as key-value pairs. Values support template expressions.",body:"Request body (JSON string). Template expressions allowed. Only for POST/PUT/PATCH/DELETE."},dataTransform:{steps:"Ordered list of transformation steps. Each step transforms a value and saves the result under a name.",onError:"What to do when a step fails: 'error' follows the error output, 'empty' continues with an empty value."},subPlan:{planId:"ID of a published visual plan to execute as a subplan. Must be published."},sendDtmf:{digits:"DTMF digits to send (0-9, *, #). Supports template expressions."},aiAgent:{agent_id:"SipPulse AI agent ID to invoke. Required for execution.",agent_name:"Display name for the AI agent (used in logs and UI).",additional_instructions:"Extra instructions appended to the agent's system prompt.",variables:"Key-value pairs passed to the agent as context variables.",initial_message:"First message the agent speaks when the conversation starts.",max_duration_minutes:"Maximum conversation duration in minutes (1-60). Call ends on timeout."},retellAgent:{connector_id:"Connector that provides the voice.agent capability, such as a Retell account.",agent_id:"ID of the Retell agent that answers the call. Required for execution.",agent_name:"Display name of the chosen agent, used in logs and the editor.",variables:"Key-value pairs sent to the agent. Every value supports {{variables}}.",max_duration_minutes:"Maximum call duration in minutes (1-60). The bridge ends on timeout.",result_wait_seconds:"How long to wait for Retell's post-call extraction before continuing (0-60)."},vapiAgent:{connector_id:"Connector that provides the voice.agent capability, such as a Vapi account.",assistant_id:"ID of the Vapi assistant that answers the call. Required for execution.",assistant_name:"Display name of the chosen assistant, used in logs and the editor.",variables:"Key-value pairs sent to the agent. Every value supports {{variables}}.",max_duration_minutes:"Maximum call duration in minutes (1-60). The bridge ends on timeout.",result_wait_seconds:"How long to wait for Vapi's end of call report before continuing (0-60)."},elevenlabsAgent:{connector_id:"Connector that provides the voice.agent capability, such as an ElevenLabs account.",agent_id:"ID of the ElevenLabs agent that answers the call. Required for execution.",agent_name:"Display name of the chosen agent, used in logs and the editor.",variables:"Key-value pairs sent to the agent as X-<name> SIP headers. Every value supports {{variables}}.",max_duration_minutes:"Maximum call duration in minutes (1-60). The bridge ends on timeout.",result_wait_seconds:"How long to wait for ElevenLabs' post-call analysis before continuing (0-60)."},openaiLiveAgent:{connector_id:"Connector that provides the voice.agent capability, such as an OpenAI project.",agent_id:"Saved OpenAI agent (Agents API) the call runs. NIVA reads it at every call.",voice:"GPT-Live voice. bossa and tempo are the Brazilian Portuguese voices.",voice_instructions:"Optional persona for the voice: tone, pace, language. Empty uses the agent's instructions.",initial_message:"What the agent says to open the call, in its own words. Empty waits for the caller.",variables:"Call context handed to the agent at the start. Every value supports {{variables}}.",output_fields:"Values the agent returns when it ends, published as output.<name>.",max_duration_minutes:"Maximum call duration in minutes (1-60). The bridge ends on timeout.",result_wait_seconds:"How long to wait, after the agent leg ends, for the session to close (0-60)."},voiceRecognition:{mode:"'intent' classifies speech into configured intents; 'capture' transcribes without classification.",prompt:"Audio prompt played before listening for speech.",intents:"List of intents the LLM should classify speech into. Each creates a dynamic output. Only used in intent mode.",classification_instructions:"Additional instructions for the LLM intent classifier. Only used in intent mode.",listen:"Listening configuration: silence timeout, max duration, language, beep.",processing_audio:"Audio played while the AI processes the speech. Optional.",retry:"Retry behavior: max attempts and alternative prompt when speech is not recognized."},tell:{audio:"Audio to play via TTS, a pre-recorded file, or a remote URL. Used in voice plans.",content:"Message content to send in chat. Used in chat plans."},menu:{options:"Menu options. Each creates a dynamic output handle.",audio:"Voice audio prompt played before collecting DTMF input.",text:"Chat message text displayed above buttons. Supports template expressions.",voiceTimeout:"Seconds to wait for DTMF input in voice mode (1-60).",maxAttempts:"Maximum retry attempts for invalid input before following noMatch (1-10).",invalidMessage:"Chat message sent when input doesn't match any option. Supports template expressions."},capture:{audio:"Audio prompt played before collecting input in voice mode.",voiceMethod:"Voice input method: 'dtmf' for digits, 'speech' for ASR transcription (requires AI).",minDigits:"Minimum number of DTMF digits required (1-20).",maxDigits:"Maximum number of DTMF digits to collect (1-20).",terminators:"Key that terminates digit collection (e.g., '#').",voiceTimeout:"Seconds to wait for input in voice mode (1-60).",listen:"Listening configuration for speech capture: silence detection, max duration, language.",processing_audio:"Audio played while ASR processes the speech. Optional.",retryAudio:"Audio played on retry instead of main prompt. Falls back to main if not set.",text:"Chat prompt message sent before waiting for user input.",validation:"Regex pattern to validate chat text input. Invalid input triggers retry.",invalidMessage:"Chat message sent when input fails validation.",maxAttempts:"Maximum retry attempts for invalid or empty input (1-10)."},routeAi:{input:"Template expression to evaluate. The resolved text is classified by AI.",intents:"List of intents the AI should classify the input into. Each creates a dynamic output handle.",instructions:"Additional instructions for the AI intent classifier."},channelRouter:{},apiSwitch:{audio:"Audio prompt played before collecting digits.",chatText:"Text prompt for chat mode. Supports {{variables}}.",timeout:"Seconds to wait for digit input (1-60).",maxAttempts:"Maximum retry attempts for digit collection (1-10).",digitRegex:"Regex to validate DTMF input. Empty means accept any.",method:"HTTP method for the API request.",url:"API endpoint URL. Supports {{variables}} including collected digits as {{digits}}.",headers:"HTTP headers as key-value pairs.",body:"Request body (JSON). Supports {{variables}}. Only for POST/PUT.",requestTimeout:"HTTP request timeout in milliseconds.",attribute:"JSON attribute name from the API response to match against cases.",cases:"Possible attribute values. Each creates a dynamic output handle 'match:<value>'."},enableRecord:{percentage:"Percentage of calls to record (0-100). 100 records all calls.",minDuration:"Minimum call duration in seconds before recording starts. 0 for immediate.",analyzeCalls:"Enable post-call AI analysis (requires AI module)."},recording:{enabled:"Start or stop recording from this point",samplingPercentage:"Recording sampling percentage when recording starts"},transcription:{enabled:"Start or stop transcription at this point",samplingPercentage:"Percentage of selected recordings that will be transcribed",scope:"Transcription scope: 'from_here' uses audio recorded from this point (default/legacy); 'whole_recording' includes all audio already recorded and continues until transcription is disabled",language:"Language applied to the whole transcription",minDurationSeconds:"Minimum duration applied to the whole transcription",speechRequirement:"Skip calls without conversation, applied to the whole transcription: none, both (caller and IVR) or caller (caller only)",anonymizeEnabled:"Anonymize the whole transcript",sentimentEnabled:"Enable sentiment analysis for all available transcription; omitted fields remain inherited",transcriptionType:"Transcription type: 'post_call' transcribes when the call ends; 'live' also transcribes during the call, billed per recorded minute"},analysis:{speechAnalyticsEnabled:"Enable call summary for all available transcription; omitted fields remain inherited",sentimentEnabled:"Enable sentiment analysis for all available transcription; omitted fields remain inherited",topicDetectionTopics:"Topics for all available transcription; omitted fields remain inherited",intentDetectionIntents:"Intents for all available transcription; omitted fields remain inherited",structuredAnalysisEnabled:"Enable structured analyses for all available transcription; omitted fields remain inherited",structuredAnalysisIds:"Structured analysis IDs for all available transcription; omitted fields remain inherited"},whatsappTemplate:{connectorId:"Connector that provides the WhatsApp templates capability (whatsapp.templates).",phoneNumberId:"Number the message is sent from, one of the connector's numbers.",template:"Approved template to send, by name and language (e.g. boleto / pt_BR).",to:"Recipient. Supports {{variables}}. A number without a country code gets the block's default country code.",defaultCountry:"Country that completes numbers written without a country code. Empty uses the organization's default country.",parameters:"Template variable values. Keys: variable number or name; a media header takes the URL; a URL button takes the suffix. Supports {{variables}}."},whatsappMessage:{connectorId:"Connector that provides the free-text WhatsApp capability (whatsapp.messages), such as an Evolution API gateway.",phoneNumberId:"Number the message is sent from: one connected instance of the connector.",to:"Recipient. Supports {{variables}}. A number without a country code gets the block's default country code.",defaultCountry:"Country that completes numbers written without a country code. Empty uses the organization's default country.",text:"Message text. Supports {{variables}}. Required; at most 4096 characters once the variables are resolved."},sendSms:{connector_id:"Connector that provides the sms.send capability, such as a Twilio account.",from:"Sender. Empty uses the connector's default sender; otherwise a Messaging Service SID (MG...) or an E.164 number.",to:"Recipient. Supports {{variables}}. A number without a country code gets the block's default country code.",default_country:"Country that completes numbers written without a country code. Empty uses the organization's default country.",body:"Message text. Supports {{variables}}; secrets are not allowed in the body.",transliterate:"Replace accented letters by their base letter before sending, so the message fits 160 characters per SMS instead of 70."},phoneLookup:{connector_id:"Connector that provides the phone.lookup capability, such as a Twilio account.",number:"Number to look up. Supports {{variables}}. A number without a country code gets the block's default country code.",default_country:"Country that completes numbers written without a country code. Empty uses the organization's default country.",line_type:"Also fetch line type and carrier. Twilio charges US$ 0,008 per query; format validation alone is free.",line_type_error:"Twilio's own code and message when it could not identify the line type; empty when it did."},verifyCode:{connector_id:"Connector that provides the verify.otp capability, such as a Twilio account.",service_sid:"Verify Service SID (VA...) whose code length and sender configuration the block uses.",to:"Recipient. Supports {{variables}}. A number without a country code gets the block's default country code.",default_country:"Country that completes numbers written without a country code. Empty uses the organization's default country.",channel:"How the code reaches the contact: sms, whatsapp or call.",prompt:"Audio prompt asking for the code, played with the plan's voice. In chat, its text is sent.",max_attempts:"Maximum wrong-code attempts before the block leaves by rejected (1-5).",timeout_seconds:"Seconds to wait for the code after the prompt (1-60)."},enterQueue:{queue_id:"Public id of the queue (que_...) or a {{variable}} that holds it. Required for execution.",priority:"Priority in the queue, 0-100: a higher number is offered first. Supports {{variables}}.",max_wait_s:"Overrides the queue's maximum wait, in seconds (0 = no limit). Empty uses the queue's own.",attached_data:"Key/value pairs delivered to the attendant with the offer. Values support templates."},queryQueue:{queue_id:"Public id of the queue (que_...) or a {{variable}} that holds it. Required for execution."},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 Zi={_nodes:{start:{name:"Início",description:"Onde toda chamada começa — recebe caller ID, DID e timestamp"},playback:{name:"Reprodução",description:"Reproduz uma mensagem usando TTS ou arquivo de áudio"},ivr:{name:"Menu IVR",description:"Apresenta um menu e roteia a chamada pelo dígito pressionado"},collectDigits:{name:"Coletar Dígitos",description:"Coleta uma sequência de dígitos como CPF, número de conta ou PIN"},transfer:{name:"Transferência",description:"Conecta ou redireciona a chamada para agente, fila ou número externo"},hangup:{name:"Desligar",description:"Encerra a chamada — coloque no final de cada caminho do plano"},timeRouting:{name:"Agenda",description:"Verifica o horário atual contra uma agenda para rotear dentro/fora do expediente"},switchCase:{name:"Condição",description:"Avalia uma variável contra padrões regex para escolher um caminho"},trafficSplit:{name:"Dividir tráfego",description:"Distribuidor de chamadas por percentual entre vários caminhos — teste A/B, balanceamento entre destinos e rampa de canário"},setVariable:{name:"Definir Variável",description:"Salva um valor para reusar depois durante a execução do plano"},sequence:{name:"Sequência",description:"Gera números sequenciais para protocolos, tickets ou qualquer identificador — durável em banco, nunca regride"},counter:{name:"Contador",description:"Conta tentativas, eventos ou qualquer coisa — por chamada ou entre chamadas, com saída opcional de limite"},httpRequest:{name:"Requisição HTTP",description:"Chama uma API REST e armazena a resposta para os blocos seguintes"},webhook:{name:"Webhook",description:"Dispara uma chamada HTTP para um sistema externo e segue sem esperar"},dataTransform:{name:"Transformar Dados",description:"Aplica operações de texto, número, data, lista, telefone e fala sobre um valor sem escrever código"},sendDtmf:{name:"Enviar DTMF",description:"Envia tons DTMF para o canal conectado ou PBX"},subPlan:{name:"Sub-Plano",description:"Delega execução para outro plano publicado e retorna"},aiAgent:{name:"Agente de IA",description:"Entrega a chamada para um agente IA para conversa livre"},retellAgent:{name:"Agente Retell",description:"Entrega a chamada para um agente de voz da Retell"},vapiAgent:{name:"Agente Vapi",description:"Entrega a chamada para um assistente de voz da Vapi"},elevenlabsAgent:{name:"Agente ElevenLabs",description:"Entrega a chamada para um agente de voz da ElevenLabs"},openaiLiveAgent:{name:"Agente GPT-Live",description:"Entrega a chamada para o GPT-Live, da OpenAI, no projeto da sua organização"},voiceRecognition:{name:"Reconhecimento de Voz",description:"Ouve o chamador, transcreve a fala e roteia por intenção"},tell:{name:"Mensagem",description:"Diz algo ao usuário — reproduz áudio na voz, envia mensagem no chat"},menu:{name:"Menu",description:"Apresenta opções e roteia pela escolha do usuário — DTMF na voz, botões no chat"},capture:{name:"Captura",description:"Coleta entrada do usuário — dígitos DTMF ou fala na voz, texto no chat"},routeAi:{name:"Classificador IA",description:"Classifica texto via IA e roteia por intenção — uma condição inteligente"},channelRouter:{name:"Canal",description:"Roteia o plano com base no modo ativo do canal (voz ou chat)"},apiSwitch:{name:"API Switch",description:"Reproduz prompt, coleta dígitos, chama API e roteia pelo atributo da resposta (legado)"},enableRecord:{name:"Ativar Gravação",description:"Ativa gravação da chamada durante o plano com amostragem e análise (legado)"},recording:{name:"Gravação",description:"Inicia ou encerra a gravação a partir deste ponto do plano"},transcription:{name:"Transcrição",description:"Escolhe o escopo da transcrição a partir deste ponto do plano"},analysis:{name:"Análise",description:"Escolhe análises para toda a transcrição disponível; cada bloco sobrescreve apenas os campos definidos"},whatsappTemplate:{name:"Enviar template WhatsApp",description:"Envia um template aprovado da Meta pelo WhatsApp Business, em chamada de voz ou em chat"},whatsappMessage:{name:"Enviar mensagem WhatsApp",description:"Envia uma mensagem de texto livre pelo WhatsApp de um número Evolution, sem template, em chamada de voz ou em chat"},sendSms:{name:"Enviar SMS",description:"Envia uma mensagem de texto pela Twilio, em chamada de voz ou em chat"},phoneLookup:{name:"Consultar número",description:"Confere o formato do número e, se pedido, o tipo de linha e a operadora pela Twilio Lookup"},verifyCode:{name:"Verificar código",description:"Envia um código de verificação pela Twilio Verify e confere, em chamada de voz ou em chat"},enterQueue:{name:"Entrar na fila",description:"Coloca a chamada numa fila da Mesa: o cliente espera com música até um atendente assumir"},queryQueue:{name:"Consultar fila",description:"Lê quem espera, quem está livre e a espera estimada de uma fila, pronto para um aviso"},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"}},_handles:{in:"Entrada",next:"Próximo",timeout:"Timeout",error:"Erro",answered:"Atendeu",busy:"Ocupado",noAnswer:"Sem Resposta",failed:"Falhou",sent:"Enviado",completed:"Concluído",valid:"Válido",invalid:"Inválido",approved:"Aprovado",rejected:"Recusado",recognized:"Reconhecido",noInput:"Sem Entrada",notApplicable:"Não Aplicável",maxRetries:"Máx. Tentativas",captured:"Capturado",onHours:"Em Horário",offHours:"Fora de Horário",holiday:"Feriado",emergency:"Emergência",queueAnswered:"Atendido",queueTimeout:"Tempo Esgotado",full:"Fila Cheia",noAttendant:"Sem Atendente",default:"Padrão",fallback:"Fallback",noMatch:"Sem Correspondência",collected:"Coletado",skipped:"Ignorado",limitReached:"Limite Atingido",voice:"Voz",chat:"Chat",telegram:"Telegram",whatsapp:"WhatsApp",webchat:"Webchat",sms:"SMS"},_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."},playback:{audio:"Áudio para reproduzir. Use TTS (texto para fala) ou arquivo de áudio pré-gravado."},hangup:{cause:"Código de causa SIP para desligamento (ex: 'NORMAL_CLEARING'). Omita para padrão."},ivr:{audio:"Prompt de áudio reproduzido antes de coletar entrada DTMF.",timeout:"Segundos de espera por entrada DTMF após o áudio (1-60).",maxAttempts:"Máximo de tentativas antes de seguir pela saída de erro (1-10)."},collectDigits:{audio:"Prompt de áudio reproduzido antes de coletar dígitos.",minDigits:"Número mínimo de dígitos necessários (1-20).",maxDigits:"Número máximo de dígitos a coletar (1-20).",terminator:"Tecla que encerra a coleta de dígitos (ex: '#'). Um caractere.",timeout:"Segundos de espera pelo primeiro dígito após o áudio (1-60).",interDigitTimeout:"Segundos de espera entre dígitos consecutivos (1-30).",maxAttempts:"Máximo de tentativas em entrada inválida (1-10).",invalidAudio:"Áudio reproduzido quando a entrada falha na validação regex. Opcional.",regex:"Padrão regex para validar dígitos coletados. Vazio aceita qualquer entrada.",resetDigit:"Tecla que limpa dígitos coletados e reinicia. Um caractere. Vazio para desabilitar."},transfer:{method:"Método de transferência. 'bridge' mantém controle da chamada; 'transfer' transfere completamente.",destinations:"URIs SIP ou números de telefone para discar. Pelo menos um obrigatório. Tentados em ordem.",timeout:"Timeout de toque em segundos por destino (5-120). Omita para padrão da operadora.",attachedData:"Pares chave/valor entregues ao atendente na transferência (screen-pop). Valores aceitam templates."},timeRouting:{scheduleId:"ID da agenda para roteamento por horário. Direciona para saídas onHours/offHours/holiday."},switchCase:{expression:"Expressão template a avaliar, ex: '{{ivr.digits}}'. Comparada com os padrões dos cases.",cases:"Lista de padrões para comparar. Cada um cria uma saída dinâmica 'match:<padrão>'."},trafficSplit:{paths:"Caminhos com peso. Cada um cria uma saída dinâmica 'path:<nome>'.",mode:"'contact' mantém o mesmo contato sempre no mesmo caminho (hash sem estado); 'call' sorteia a cada chamada (sem estado, aproximado); 'exact' usa um rodízio contado no Redis e fecha a proporção mesmo em volume baixo."},setVariable:{assignments:"Lista de atribuições de variáveis. Pelo menos uma obrigatória."},counter:{name:"Nome do contador. Suporta templates, ex: 'tentativas_{{start.callerid}}'.",action:"Operação aplicada ao contador. 'reset' zera o contador e ignora o passo.",step:"Quantidade somada ou subtraída a cada execução (1-1000000). Ignorada quando a ação é 'reset'.",limit:"Valor que direciona para a saída 'limitReached' quando o contador o alcança. Vazio apenas conta.",scope:"'call' começa do zero a cada chamada; 'plan' persiste entre as chamadas de um plano; 'organization' persiste entre todos os planos da organização.",ttlSeconds:"Tempo de vida em segundos de um contador de escopo 'plan' ou 'organization' (60-31536000). Aplicado na criação da chave, então contar não renova a janela."},httpRequest:{method:"Método HTTP da requisição.",url:"URL da requisição. Suporta expressões template, ex: 'https://api.example.com/{{start.callerid}}'.",headers:"Cabeçalhos HTTP como pares chave-valor. Valores suportam expressões template.",body:"Corpo da requisição (string JSON). Expressões template permitidas. Apenas para POST/PUT/PATCH.",timeout:"Timeout da requisição em milissegundos. Omita para padrão."},webhook:{method:"Método HTTP da requisição.",url:"URL de destino. Suporta expressões template, ex: 'https://hooks.example.com/{{start.callerid}}'.",headers:"Cabeçalhos HTTP como pares chave-valor. Valores suportam expressões template.",body:"Corpo da requisição (string JSON). Expressões template permitidas. Apenas para POST/PUT/PATCH/DELETE."},dataTransform:{steps:"Lista ordenada de passos de transformação. Cada passo transforma um valor e salva o resultado num nome.",onError:"O que fazer quando um passo falha: 'error' segue pela saída de erro, 'empty' continua com um valor vazio."},subPlan:{planId:"ID de um plano visual publicado para executar como subplano. Deve estar publicado."},sendDtmf:{digits:"Dígitos DTMF para enviar (0-9, *, #). Suporta expressões template."},aiAgent:{agent_id:"ID do agente SipPulse AI a invocar. Obrigatório para execução.",agent_name:"Nome de exibição do agente AI (usado em logs e na interface).",additional_instructions:"Instruções extras adicionadas ao prompt do sistema do agente.",variables:"Pares chave-valor passados ao agente como variáveis de contexto.",initial_message:"Primeira mensagem que o agente fala ao iniciar a conversa.",max_duration_minutes:"Duração máxima da conversa em minutos (1-60). Chamada encerra no timeout."},retellAgent:{connector_id:"Conector com a capacidade de agente de voz (voice.agent), como uma conta Retell.",agent_id:"ID do agente da Retell que atende a ligação. Obrigatório para execução.",agent_name:"Nome de exibição do agente escolhido, usado nos logs e no editor.",variables:"Pares chave-valor enviados ao agente. Cada valor aceita {{variáveis}}.",max_duration_minutes:"Duração máxima da chamada em minutos (1-60). A ponte encerra no timeout.",result_wait_seconds:"Tempo de espera pela extração pós-chamada da Retell antes de seguir (0-60)."},vapiAgent:{connector_id:"Conector com a capacidade de agente de voz (voice.agent), como uma conta Vapi.",assistant_id:"ID do assistente da Vapi que atende a ligação. Obrigatório para execução.",assistant_name:"Nome de exibição do assistente escolhido, usado nos logs e no editor.",variables:"Pares chave-valor enviados ao agente. Cada valor aceita {{variáveis}}.",max_duration_minutes:"Duração máxima da chamada em minutos (1-60). A ponte encerra no timeout.",result_wait_seconds:"Tempo de espera pelo relatório da Vapi antes de seguir (0-60)."},elevenlabsAgent:{connector_id:"Conector com a capacidade de agente de voz (voice.agent), como uma conta ElevenLabs.",agent_id:"ID do agente da ElevenLabs que atende a ligação. Obrigatório para execução.",agent_name:"Nome de exibição do agente escolhido, usado nos logs e no editor.",variables:"Pares chave-valor enviados ao agente como cabeçalhos SIP X-<nome>. Cada valor aceita {{variáveis}}.",max_duration_minutes:"Duração máxima da chamada em minutos (1-60). A ponte encerra no timeout.",result_wait_seconds:"Tempo de espera pela análise pós-chamada da ElevenLabs antes de seguir (0-60)."},openaiLiveAgent:{connector_id:"Conector com a capacidade de agente de voz (voice.agent), como um projeto da OpenAI.",agent_id:"Agente salvo na OpenAI (Agents API) que atende a chamada. O NIVA lê o agente a cada ligação.",voice:"Voz do GPT-Live. bossa e tempo são as vozes de português do Brasil.",voice_instructions:"Persona opcional da voz: tom, ritmo, idioma. Vazio usa as instruções do agente.",initial_message:"O que o agente diz para abrir a ligação, com as palavras dele. Vazio espera o cliente falar.",variables:"Contexto da chamada entregue ao agente no início. Cada valor aceita {{variáveis}}.",output_fields:"Valores que o agente devolve ao encerrar, publicados como output.<nome>.",max_duration_minutes:"Duração máxima da chamada em minutos (1-60). A ponte encerra no timeout.",result_wait_seconds:"Tempo de espera, depois que a ligação com o agente cai, pelo fechamento da sessão (0-60)."},voiceRecognition:{mode:"'intent' classifica a fala em intenções configuradas; 'capture' transcreve sem classificação.",prompt:"Prompt de áudio reproduzido antes de escutar a fala.",intents:"Lista de intenções para o LLM classificar a fala. Cada uma cria uma saída dinâmica. Só usado no modo intent.",classification_instructions:"Instruções adicionais para o classificador de intenções do LLM. Só usado no modo intent.",listen:"Configuração de escuta: timeout de silêncio, duração máxima, idioma, beep.",processing_audio:"Áudio reproduzido enquanto a IA processa a fala. Opcional.",retry:"Comportamento de retentativa: máximo de tentativas e prompt alternativo quando a fala não é reconhecida."},tell:{audio:"Áudio para reproduzir via TTS, arquivo pré-gravado ou URL remota. Usado em planos de voz.",content:"Conteúdo da mensagem a enviar no chat. Usado em planos de chat."},menu:{options:"Opções do menu. Cada uma cria uma saída dinâmica.",audio:"Prompt de áudio reproduzido antes de coletar entrada DTMF na voz.",text:"Texto da mensagem no chat, exibido acima dos botões. Suporta expressões template.",voiceTimeout:"Segundos de espera por entrada DTMF no modo voz (1-60).",maxAttempts:"Máximo de tentativas para entrada inválida antes de seguir pela saída noMatch (1-10).",invalidMessage:"Mensagem enviada no chat quando a entrada não corresponde a nenhuma opção. Suporta expressões template."},capture:{audio:"Prompt de áudio reproduzido antes de coletar entrada no modo voz.",voiceMethod:"Método de entrada por voz: 'dtmf' para dígitos, 'speech' para transcrição ASR (requer IA).",minDigits:"Número mínimo de dígitos DTMF necessários (1-20).",maxDigits:"Número máximo de dígitos DTMF a coletar (1-20).",terminators:"Tecla que encerra a coleta de dígitos (ex: '#').",voiceTimeout:"Segundos de espera por entrada no modo voz (1-60).",listen:"Configuração de escuta para captura de fala: detecção de silêncio, duração máxima, idioma.",processing_audio:"Áudio reproduzido enquanto o ASR processa a fala. Opcional.",retryAudio:"Áudio reproduzido na retentativa ao invés do prompt principal. Usa o principal se não definido.",text:"Mensagem de prompt no chat enviada antes de aguardar a entrada do usuário.",validation:"Padrão regex para validar a entrada de texto no chat. Entrada inválida aciona retentativa.",invalidMessage:"Mensagem enviada no chat quando a entrada falha na validação.",maxAttempts:"Máximo de tentativas para entrada inválida ou vazia (1-10)."},routeAi:{input:"Expressão template para avaliar. O texto resolvido é classificado pela IA.",intents:"Lista de intenções para a IA classificar a entrada. Cada uma cria uma saída dinâmica.",instructions:"Instruções adicionais para o classificador de intenções da IA."},channelRouter:{},apiSwitch:{audio:"Prompt de áudio reproduzido antes de coletar dígitos.",chatText:"Prompt de texto para modo chat. Suporta {{variáveis}}.",timeout:"Segundos de espera por entrada de dígito (1-60).",maxAttempts:"Máximo de tentativas para coleta de dígitos (1-10).",digitRegex:"Regex para validar entrada DTMF. Vazio aceita qualquer entrada.",method:"Método HTTP da requisição à API.",url:"URL do endpoint da API. Suporta {{variáveis}} incluindo dígitos coletados como {{digits}}.",headers:"Cabeçalhos HTTP como pares chave-valor.",body:"Corpo da requisição (JSON). Suporta {{variáveis}}. Apenas para POST/PUT.",requestTimeout:"Timeout da requisição HTTP em milissegundos.",attribute:"Nome do atributo JSON da resposta da API para comparar com os cases.",cases:"Valores possíveis do atributo. Cada um cria uma saída dinâmica 'match:<valor>'."},enableRecord:{percentage:"Porcentagem de chamadas a gravar (0-100). 100 grava todas.",minDuration:"Duração mínima da chamada em segundos antes de iniciar a gravação. 0 para imediato.",analyzeCalls:"Ativar análise pós-chamada por IA (requer módulo AI)."},recording:{enabled:"Iniciar ou encerrar a gravação a partir deste ponto",samplingPercentage:"Porcentagem de amostragem quando a gravação começa"},transcription:{enabled:"Iniciar ou encerrar a transcrição a partir deste ponto",samplingPercentage:"Percentual das gravações selecionadas que serão transcritas",scope:"Escopo da transcrição: 'from_here' usa o áudio gravado a partir deste ponto (padrão/legado); 'whole_recording' inclui todo o áudio já gravado e continua até a transcrição ser desligada",language:"Idioma aplicado à transcrição inteira",minDurationSeconds:"Duração mínima aplicada à transcrição inteira",speechRequirement:"Pular chamadas sem conversa, aplicado à transcrição inteira: none, both (cliente e URA) ou caller (só o cliente)",anonymizeEnabled:"Anonimizar a transcrição inteira",sentimentEnabled:"Ativar análise de sentimento para toda a transcrição disponível; campos omitidos são herdados",transcriptionType:"Tipo de transcrição: 'post_call' transcreve quando a chamada termina; 'live' também transcreve durante a chamada, custo por minuto gravado"},analysis:{speechAnalyticsEnabled:"Ativar resumo da chamada para toda a transcrição disponível; campos omitidos são herdados",sentimentEnabled:"Ativar análise de sentimento para toda a transcrição disponível; campos omitidos são herdados",topicDetectionTopics:"Tópicos para toda a transcrição disponível; campos omitidos são herdados",intentDetectionIntents:"Intenções para toda a transcrição disponível; campos omitidos são herdados",structuredAnalysisEnabled:"Ativar análises estruturadas para toda a transcrição disponível; campos omitidos são herdados",structuredAnalysisIds:"IDs das análises estruturadas para toda a transcrição disponível; campos omitidos são herdados"},whatsappTemplate:{connectorId:"Conector com a capacidade de templates do WhatsApp (whatsapp.templates).",phoneNumberId:"Número de origem da mensagem, entre os números do conector.",template:"Template aprovado a enviar, por nome e idioma (ex.: boleto / pt_BR).",to:"Destinatário. Suporta {{variáveis}}. Número sem DDI recebe o DDI padrão do bloco.",defaultCountry:"País que completa os números escritos sem DDI. Vazio usa o país padrão da organização.",parameters:"Valores das variáveis do template. Chaves: número ou nome da variável; cabeçalho de mídia recebe a URL; botão de URL recebe o sufixo. Suporta {{variáveis}}."},whatsappMessage:{connectorId:"Conector com a capacidade de mensagens livres do WhatsApp (whatsapp.messages), como um gateway Evolution API.",phoneNumberId:"Número de origem da mensagem: uma instância conectada do conector.",to:"Destinatário. Suporta {{variáveis}}. Número sem DDI recebe o DDI padrão do bloco.",defaultCountry:"País que completa os números escritos sem DDI. Vazio usa o país padrão da organização.",text:"Texto da mensagem. Suporta {{variáveis}}. Obrigatório; no máximo 4096 caracteres depois de resolver as variáveis."},sendSms:{connector_id:"Conector com a capacidade sms.send, como uma conta da Twilio.",from:"Remetente. Vazio usa o remetente padrão do conector; senão, um Messaging Service SID (MG...) ou um número E.164.",to:"Destinatário. Suporta {{variáveis}}. Número sem DDI recebe o DDI padrão do bloco.",default_country:"País que completa os números escritos sem DDI. Vazio usa o país padrão da organização.",body:"Texto da mensagem. Suporta {{variáveis}}; segredos não são permitidos no corpo.",transliterate:"Troca letras acentuadas pela letra sem acento antes de enviar, para caber 160 caracteres por SMS em vez de 70."},phoneLookup:{connector_id:"Conector com a capacidade phone.lookup, como uma conta da Twilio.",number:"Número a consultar. Suporta {{variáveis}}. Número sem DDI recebe o DDI padrão do bloco.",default_country:"País que completa os números escritos sem DDI. Vazio usa o país padrão da organização.",line_type:"Busca também o tipo de linha e a operadora. A Twilio cobra US$ 0,008 por consulta; só validar o formato é grátis.",line_type_error:"Código e mensagem da própria Twilio quando ela não conseguiu identificar o tipo de linha; vazio quando conseguiu."},verifyCode:{connector_id:"Conector com a capacidade verify.otp, como uma conta da Twilio.",service_sid:"SID do Serviço do Verify (VA...) cujo tamanho de código e remetente o bloco usa.",to:"Destinatário. Suporta {{variáveis}}. Número sem DDI recebe o DDI padrão do bloco.",default_country:"País que completa os números escritos sem DDI. Vazio usa o país padrão da organização.",channel:"Como o código chega ao contato: sms, whatsapp ou ligação.",prompt:"Áudio que pede o código, falado com a voz do plano. No chat, o texto dele é enviado.",max_attempts:"Máximo de códigos errados antes de o bloco sair por Recusado (1-5).",timeout_seconds:"Segundos de espera pelo código depois do aviso (1-60)."},enterQueue:{queue_id:"Id público da fila (que_...) ou uma {{variável}} que o contém. Obrigatório para execução.",priority:"Prioridade na fila, de 0 a 100: o número maior é oferecido primeiro. Aceita {{variáveis}}.",max_wait_s:"Substitui a espera máxima da fila, em segundos (0 = sem limite). Vazio usa a da própria fila.",attached_data:"Pares chave/valor entregues ao atendente junto com a oferta. Valores aceitam templates."},queryQueue:{queue_id:"Id público da fila (que_...) ou uma {{variável}} que o contém. Obrigatório para execução."},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 nO={en:$n,"pt-BR":Zi};function Xc(e,t="en"){return nO[t]._nodes?.[e]}var Yi=["core","ai","desk","queues","dialer","omnichannel","enterprise","assistant","copilot","classifier"],Qc=Yi.filter((e)=>e!=="core");function Mn(e,t){return typeof e.outputs==="function"?e.outputs(t):e.outputs}var pb={interaction:{order:0},handling:{order:1},routing:{order:2},media:{order:3},data:{order:4},legacy:{order:5}},rO=Object.entries(pb).sort(([,e],[,t])=>e.order-t.order).map(([e])=>e);var el=g({reason:l().max(128,{error:"editor:validation.dncReasonTooLong"}).default("").describe("Optional short reason recorded on the DNC entry (max 128 chars). Plain text, no templates."),phoneOverride:l().default("").describe("Optional number/template to add instead of the auto-resolved one. Supports {{variables}}. Empty = auto-resolve (dialer contact, then caller ID).")}),tl=U({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:el,producedVariables:[{name:"dnc_added",type:"string",descriptionKey:"editor:vars.dncAdded"},{name:"dnc_phone",type:"string",descriptionKey:"editor:vars.dncPhone"}]});var nl=g({agent_id:l().default("").describe("SipPulse AI agent ID to invoke. Required for execution."),agent_name:l().default("").describe("Display name for the AI agent (used in logs and UI)."),additional_instructions:l().default("").describe("Extra instructions appended to the agent's system prompt."),variables:ie(l(),pt()).default({}).describe("Key-value pairs passed to the agent as context variables."),initial_message:l().default("").describe("First message the agent speaks when the conversation starts."),max_duration_minutes:f().min(1).max(60).default(10).describe("Maximum conversation duration in minutes (1-60). Call ends on timeout.")}),rl=U({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:nl,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 ol=l().min(1).max(255).regex(/^[A-Za-z0-9_-]+$/,{error:"Invalid structured analysis id"});var il=g({speechAnalyticsEnabled:F().optional(),sentimentEnabled:F().nullable().optional(),topicDetectionTopics:z(l()).optional(),intentDetectionIntents:z(l()).optional(),structuredAnalysisEnabled:F().optional(),structuredAnalysisIds:z(ol).max(100).optional()}),al=U({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:il,producedVariables:[{name:"selected",type:"number",descriptionKey:"editor:vars.analysisSelected"}]});var aO=/\{\{[^{}]*\}\}/g,sO=/^\{\{[^{}]*\}\}$/,cO=new Set(["http:","https:"]);function mb(e){if(!URL.canParse(e))return!1;return cO.has(new URL(e).protocol)}function fb(e){let t=e.trim();if(t==="")return"empty";if(sO.test(t))return"from-variable";let n=0,r=t.replaceAll(aO,()=>(n+=1,`v${n}`));return mb(r)?"valid":"malformed"}function sl(e){return fb(e)!=="malformed"}var gb=["postgres","redis","freeswitch","engine","server"],B5=new Set(gb);var cl=g({text:l().min(1,{error:"editor:validation.emptyTtsText"}).describe("Text to synthesize into speech."),voice:l().optional().describe("TTS voice ID (e.g., 'pt-BR-FranciscaNeural'). Resolved dynamically when absent."),model:l().optional().describe("TTS model ID (e.g., 'pulse-tts'). Resolved dynamically when absent.")}),ve=Be([g({tts:cl.describe("Text-to-speech audio source.")}),g({file:g({id:l().min(1,{error:"editor:validation.noAudioFile"}).describe("Audio file ID from the audio library."),name:l().describe("Display name of the audio file."),path:l().describe("Storage path of the audio file.")}).describe("Pre-recorded audio file source.")}),g({url:g({value:l().min(1,{error:"editor:validation.emptyAudioUrl"}).refine(sl,{error:"editor:validation.malformedAudioUrl"}).describe("Audio URL fetched at call time. Supports {{variables}}; secrets are not allowed."),fallbackTts:cl.optional().describe("Spoken when the URL fails. Absent means take the error output.")}).describe("Remote audio source fetched at call time.")})]),lO=ve.optional().catch(void 0);var gr=l().refine((e)=>e.trim()!=="",{error:"editor:validation.urlRequired"}).refine((e)=>!/\s/.test(e.trim()),{error:"editor:validation.urlHasSpace"}).default("");var dO=g({value:l().min(1,{error:"editor:validation.caseValueRequired"}).default("").describe("Attribute value to match. Creates a 'match:<value>' output.")}),ll=g({audio:ve.optional().describe("Audio prompt played before collecting digits."),chatText:l().default("").describe("Text prompt for chat mode. Supports {{variables}}."),timeout:f().int().min(1).max(60).default(5).describe("Seconds to wait for digit input (1-60)."),maxAttempts:f().int().min(1).max(10).default(3).describe("Maximum retry attempts for digit collection (1-10)."),digitRegex:l().default("").describe("Regex to validate DTMF input. Empty means accept any."),method:P(["GET","POST","PUT"]).default("GET").describe("HTTP method for the API request."),url:gr.describe("API endpoint URL. Supports {{variables}} including collected digits as {{digits}}."),headers:ie(l(),l()).optional().describe("HTTP headers as key-value pairs."),body:l().optional().describe("Request body (JSON). Supports {{variables}}. Only for POST/PUT."),requestTimeout:f().int().min(1000).max(60000).default(1e4).describe("HTTP request timeout in milliseconds."),attribute:l().default("").describe("JSON attribute name from the API response to match against cases."),cases:z(dO).default([]).describe("Possible attribute values. Each creates a dynamic output handle 'match:<value>'.")}),dl=U({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:(e)=>[...(e.cases??[]).map((r)=>typeof r==="string"?r:r.value).filter((r)=>typeof r==="string"&&r!=="").map((r)=>({key:`match:${r}`,labelKey:r})),{key:"noInput",labelKey:"editor:handles.noInput"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:ll,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 uO=g({language:l().optional().describe("BCP 47 language code for speech recognition (e.g., 'pt-BR'). Omit for plan default."),initial_timeout_s:f().min(3).max(60).default(10).describe("Maximum seconds to wait for speech to begin (3-60)."),timeout_s:f().min(1).max(30).default(3).describe("Seconds of post-speech silence before stopping recording (1-30)."),max_duration_s:f().min(1).max(60).default(15).describe("Maximum recording duration in seconds (1-60)."),beep:F().default(!1).describe("Play a beep sound before starting to listen.")}),ul=g({maxAttempts:f().min(1).max(10).default(3).describe("Maximum retry attempts for invalid or empty input (1-10)."),audio:ve.optional().describe("Audio prompt played before collecting input in voice mode."),voiceMethod:P(["dtmf","speech"]).default("dtmf").describe("Voice input method: 'dtmf' for digits, 'speech' for ASR transcription (requires AI)."),minDigits:f().min(1).max(20).default(1).describe("Minimum number of DTMF digits required (1-20)."),maxDigits:f().min(1).max(20).default(1).describe("Maximum number of DTMF digits to collect (1-20)."),terminators:l().default("#").describe("Key that terminates digit collection (e.g., '#')."),voiceTimeout:f().min(1).max(60).default(5).describe("Seconds to wait for input in voice mode (1-60)."),listen:uO.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:ve.optional().describe("Audio played while ASR processes the speech. Optional."),retryAudio:ve.optional().describe("Audio played on retry instead of main prompt. Falls back to main if not set."),text:l().default("").describe("Chat prompt message sent before waiting for user input. Supports {{variables}}."),validation:l().optional().describe("Regex pattern to validate chat text input. Invalid input triggers retry."),invalidMessage:l().optional().describe("Chat message sent when input fails validation. Supports {{variables}}.")}),pl=U({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:ul,producedVariables:[{name:"text",type:"string",descriptionKey:"editor:vars.capturedText"},{name:"attempts",type:"number",descriptionKey:"editor:vars.captureAttempts"},{name:"media_url",type:"string",descriptionKey:"editor:vars.captureMediaUrl"},{name:"media_kind",type:"string",descriptionKey:"editor:vars.captureMediaKind"},{name:"media_content_type",type:"string",descriptionKey:"editor:vars.captureMediaContentType"},{name:"media_name",type:"string",descriptionKey:"editor:vars.captureMediaName"},{name:"media_size",type:"number",descriptionKey:"editor:vars.captureMediaSize"}]});var ml=g({}),fl=U({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:ml,producedVariables:[{name:"channelType",type:"string",descriptionKey:"editor:vars.channelType"}]});var gl=g({audio:ve.default({tts:{text:""}}).describe("Audio prompt played before collecting digits."),minDigits:f().min(1,{error:"editor:validation.minDigitsMin"}).max(20,{error:"editor:validation.minDigitsMax"}).default(1).describe("Minimum number of digits required (1-20)."),maxDigits:f().min(1,{error:"editor:validation.maxDigitsMin"}).max(20,{error:"editor:validation.maxDigitsMax"}).default(1).describe("Maximum number of digits to collect (1-20)."),terminator:l().max(1).default("#").describe("Key that terminates digit collection (e.g., '#'). Single character."),timeout:f().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:f().min(1,{error:"editor:validation.interDigitTimeoutMin"}).max(30,{error:"editor:validation.interDigitTimeoutMax"}).default(3).describe("Seconds to wait between consecutive digits (1-30)."),maxAttempts:f().min(1,{error:"editor:validation.attemptsMin"}).max(10,{error:"editor:validation.attemptsMax"}).default(3).describe("Maximum retry attempts on invalid input (1-10)."),invalidAudio:ve.optional().describe("Audio played when input fails regex validation. Optional."),regex:l().default("").describe("Regex pattern to validate collected digits. Empty means accept any."),resetDigit:l().max(1).default("").describe("Key that clears collected digits and restarts. Single character. Empty to disable.")}),hl=U({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:gl,producedVariables:[{name:"digits",type:"string",descriptionKey:"editor:vars.collectedDigits"},{name:"attempts",type:"number",descriptionKey:"editor:vars.collectAttempts"}]});var yl=g({name:l().min(1,{error:"editor:validation.counterNameRequired"}).default("").describe("Counter name. Supports templates, e.g. 'attempts_{{start.callerid}}'."),action:P(["increment","decrement","reset"]).default("increment").describe("Operation applied to the counter. 'reset' sets it to zero and ignores step."),step:f().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:f().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:P(["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:f().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.")}),_l=U({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:yl,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 P4=new Intl.NumberFormat("en-US",{useGrouping:!1,maximumFractionDigits:10});var fO={BR:"55",US:"1",CA:"1",MX:"52",AR:"54",CL:"56",CO:"57",PE:"51",UY:"598",PY:"595",BO:"591",EC:"593",VE:"58",PT:"351",ES:"34",GB:"44",FR:"33",DE:"49",IT:"39"},gO=Object.entries(fO).map(([e,t])=>({country:e,callingCode:t}));var hb={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 AO=new Set(["error_code","error_message","error_step","error_var"]),TO=l().refine((e)=>e.trim()!=="",{error:"editor:validation.emptySaveAs"}).refine((e)=>!AO.has(e.trim()),{error:"editor:validation.reservedSaveAs"}).describe("Name the result is saved under. Readable by later steps and by other nodes."),Se=(e)=>I(e).describe("Operation this step applies to the source."),yb=P(["minutes","hours","days","months","years"]).describe("Time unit used by the step: minutes, hours, days, months, or years."),xe=g({source:l().describe("Value the step transforms. Literal text or a template like '{{start.callerid}}'."),saveAs:TO}),RO=Re("op",[xe.extend({op:Se("uppercase")}),xe.extend({op:Se("lowercase")}),xe.extend({op:Se("capitalize")}),xe.extend({op:Se("trim")}),xe.extend({op:Se("replace"),search:l().describe("Literal text to look for. Not a regular expression. Empty leaves the source untouched."),replacement:l().describe("Text that replaces every occurrence of the searched text.")}),xe.extend({op:Se("regexReplace"),pattern:l().describe("Regular expression used to match text. Nested repetition and patterns over 200 characters are rejected."),replacement:l().describe("Text that replaces every match. Supports JavaScript backreferences such as '$1'.")}),xe.extend({op:Se("part"),separator:l().describe("Text that splits the source into parts. Empty splits into single characters."),index:f().int().describe("Zero-based index of the part to keep. Negative counts from the end.")}),xe.extend({op:Se("add"),operand:l().describe("Number added to the source. Literal value or template.")}),xe.extend({op:Se("subtract"),operand:l().describe("Number subtracted from the source. Literal value or template.")}),xe.extend({op:Se("multiply"),operand:l().describe("Number the source is multiplied by. Literal value or template.")}),xe.extend({op:Se("divide"),operand:l().describe("Number the source is divided by. Literal value or template. Zero fails with 'divide_by_zero'.")}),xe.extend({op:Se("round"),decimals:f().int().min(0).max(10).default(0).describe("Decimal places to keep (0-10). Rounds half away from zero.")}),xe.extend({op:Se("currency"),currency:l().default("BRL").describe("ISO 4217 currency code used to format the amount, e.g. 'BRL'."),locale:l().default("pt-BR").describe("Locale used to format the amount, e.g. 'pt-BR'.")}),xe.extend({op:Se("dateOffset"),amount:f().int().describe("How many units to add to the date. Negative subtracts."),unit:yb}),xe.extend({op:Se("dateDiff"),operand:l().describe("Date compared against the source. The result is operand minus source. Literal or template."),unit:yb}),xe.extend({op:Se("dateFormat"),format:l().default("dd/MM/yyyy").describe("Output pattern, e.g. 'dd/MM/yyyy'. Text between single quotes is kept as written."),locale:l().default("pt-BR").describe("Locale used for month and weekday names, e.g. 'pt-BR'.")}),xe.extend({op:Se("normalizePhone"),country:l().default("BR").describe("ISO 3166-1 alpha-2 country code used for national numbers. Defaults to 'BR'.")}),xe.extend({op:Se("count")}),xe.extend({op:Se("join"),separator:l().default(", ").describe("Text placed between items, except before the last one."),lastSeparator:l().default(" e ").describe("Text placed before the last item. Ignored when the list has a single item.")}),xe.extend({op:Se("item"),index:f().int().describe("Zero-based index of the item to keep. Negative counts from the end.")}),xe.extend({op:Se("filter"),field:l().default("").describe("Object field compared on each item. Empty compares the item itself."),operand:l().describe("Value each item is compared against, as text. Literal or template.")}),xe.extend({op:Se("spellOut")}),xe.extend({op:Se("inWords")}),xe.extend({op:Se("default"),operand:l().describe("Value used when the source is empty. Literal value or template.")})]),bl=g({steps:z(RO).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:P(["error","empty"]).default("error").describe("What to do when a step fails: 'error' follows the error output, 'empty' continues with an empty value.")}),vl=U({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:bl,producedVariables:(e)=>{let t=new Map;for(let n of e.steps){if(n.saveAs==="")continue;t.set(n.saveAs,{name:n.saveAs,type:hb[n.op],descriptionKey:"editor:vars.transformed"})}return[...t.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 Sl=g({connector_id:l().default("").describe("Public id of the connector that provides voice.agent (an ElevenLabs account). Required for execution."),agent_id:l().default("").describe("Id of the ElevenLabs agent that answers the call. Required for execution."),agent_name:l().default("").describe("Display name of the chosen ElevenLabs agent, for logs and the editor."),variables:ie(l(),l()).default({}).describe("Key-value pairs sent to the agent as X-<name> SIP headers. Every value supports {{variables}}."),max_duration_minutes:f().min(1).max(60).default(10).describe("Maximum call duration in minutes (1-60). The bridge ends on timeout."),result_wait_seconds:f().int().min(0).max(60).default(15).describe("How long to wait for ElevenLabs' post-call analysis before continuing.")}),xl=U({meta:{type:"elevenlabsAgent",module:"ai",nameKey:"editor:nodes.elevenlabsAgent.name",descriptionKey:"editor:nodes.elevenlabsAgent.description",color:"iris",icon:"Sparkles",category:"handling",order:5,nature:"composite",display:"full",channel:"voice",requires:"voice.agent",connector:{kind:"elevenlabs",configKey:"connector_id"},outputs:[{key:"completed",labelKey:"editor:handles.completed"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:Sl,producedVariables:[{name:"duration_ms",type:"number",descriptionKey:"editor:vars.elevenlabsAgent.durationMs"},{name:"provider_call_id",type:"string",descriptionKey:"editor:vars.elevenlabsAgent.providerCallId"},{name:"ended_reason",type:"string",descriptionKey:"editor:vars.elevenlabsAgent.endedReason"},{name:"summary",type:"string",descriptionKey:"editor:vars.elevenlabsAgent.summary"},{name:"analysis_pending",type:"string",descriptionKey:"editor:vars.elevenlabsAgent.analysisPending"},{name:"output.*",type:"string",descriptionKey:"editor:vars.elevenlabsAgent.output"}]});var El=g({percentage:f().int().min(0).max(100).default(100).describe("Percentage of calls to record (0-100). 100 records all calls."),minDuration:f().int().min(0).default(0).describe("Minimum call duration in seconds before recording starts. 0 for immediate."),analyzeCalls:F().default(!1).describe("Enable post-call AI analysis (requires AI module).")}),wl=U({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:El,producedVariables:[{name:"recording",type:"string",descriptionKey:"editor:vars.recordingStatus"}]});function Ji(e){let t=g({key:l().describe(e.key),value:l().default("").describe("Field value. Supports template expressions like '{{cliente.nome}}'.")});return z(t).default([]).describe(e.list).superRefine((n,r)=>{let o=new Set;n.forEach((i,a)=>{let s=i.key.trim();if(s===""){r.addIssue({code:"custom",message:"editor:validation.attachedKeyRequired",path:[a,"key"]});return}if(o.has(s))r.addIssue({code:"custom",message:"editor:validation.duplicateAttachedKey",path:[a,"key"]});o.add(s)})})}var Cl=g({queue_id:l().default("").describe("Public id of the queue (que_...) or a {{variable}} that holds it. Required for execution."),priority:Be([Pi().min(0).max(100),l()]).default(0).describe("Priority in the queue, 0-100: a higher number is offered first. Supports {{variables}}."),max_wait_s:Be([Pi().min(0).max(86400),l()]).optional().describe("Overrides the queue's maximum wait, in seconds (0 = no limit). Empty uses the queue's own."),attached_data:Ji({key:"Attached-data field name shown to the attendant (e.g. 'Nome').",list:"Key/value pairs delivered to the attendant with the offer. Values support templates."})}),Al=U({meta:{type:"enterQueue",module:"queues",nameKey:"editor:nodes.enterQueue.name",descriptionKey:"editor:nodes.enterQueue.description",color:"amber",icon:"ListOrdered",category:"handling",order:7,nature:"action",display:"full",channel:"both",outputs:[{key:"answered",labelKey:"editor:handles.queueAnswered"},{key:"timeout",labelKey:"editor:handles.queueTimeout"},{key:"full",labelKey:"editor:handles.full"},{key:"noAttendant",labelKey:"editor:handles.noAttendant"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:Cl,producedVariables:[{name:"conversation_id",type:"string",descriptionKey:"editor:vars.enterQueue.conversationId"},{name:"outcome",type:"string",descriptionKey:"editor:vars.enterQueue.outcome"},{name:"wait_s",type:"number",descriptionKey:"editor:vars.enterQueue.waitS"},{name:"attendant_id",type:"string",descriptionKey:"editor:vars.enterQueue.attendantId"},{name:"note",type:"string",descriptionKey:"editor:vars.enterQueue.note"},{name:"disposition",type:"string",descriptionKey:"editor:vars.enterQueue.disposition"},{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"}]});var Tl=g({cause:l().optional().describe("SIP hangup cause code (e.g., 'NORMAL_CLEARING'). Omit for default.")}),Rl=U({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:Tl,producedVariables:[]});var Il=g({method:P(["GET","POST","PUT","PATCH","DELETE"]).default("GET").describe("HTTP method for the request."),url:gr.describe("Request URL. Supports template expressions, e.g., 'https://api.example.com/{{start.callerid}}'."),headers:ie(l(),l()).optional().describe("HTTP headers as key-value pairs. Values support template expressions."),body:l().optional().describe("Request body (JSON string). Template expressions allowed. Only for POST/PUT/PATCH."),timeout:f().optional().describe("Request timeout in milliseconds. Omit for default.")}),Nl=U({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:Il,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 Ol=g({audio:ve.default({tts:{text:""}}).describe("Audio prompt played before collecting DTMF input."),timeout:f().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:f().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).")}),kl=U({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:Ol,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 Dl=g({id:l().min(1).default("").describe("Unique option identifier. Used as button ID in chat and output handle suffix."),label:l().min(1).default("").describe("Display label shown to the user. Button text in chat, spoken in voice prompt."),digit:l().default("").describe("DTMF digit for voice mode (0-9, *, #). Leave empty to skip voice for this option.")}),Pl=g({options:z(Dl).default([]).describe("Menu options. Each creates a dynamic output handle."),maxAttempts:f().min(1).max(10).default(3).describe("Maximum retry attempts for invalid input before following noMatch (1-10)."),audio:ve.optional().describe("Voice audio prompt played before collecting DTMF input. If omitted, caller hears nothing before digit collection."),voiceTimeout:f().min(1).max(60).default(5).describe("Seconds to wait for DTMF input in voice mode (1-60)."),text:l().default("").describe("Chat message text displayed above buttons. Supports template expressions."),invalidMessage:l().optional().describe("Chat message sent when input doesn't match any option. Supports template expressions.")}),$l=U({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:(e)=>[...(e.options??[]).map((r)=>typeof r==="object"&&r!=null?r:null).filter((r)=>r!=null&&typeof r.id==="string"&&r.id!=="").map((r)=>({key:`option:${r.id}`,labelKey:r.label})),{key:"noMatch",labelKey:"editor:handles.noMatch"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:Pl,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 Ml=g({name:l().default("").describe("Variable name: lowercase letters, digits and underscores (output.<name>)."),description:l().default("").describe("What the agent must put in this field. The backend model reads it as the parameter description."),required:F().default(!0).describe("Whether the agent must fill the field before ending.")}),po=/^[a-z][a-z0-9_]{0,63}$/u,mo=g({connector_id:l().default("").describe("Public id of the connector that provides voice.agent (an OpenAI project). Required for execution."),agent_id:l().default("").describe("Id of the saved OpenAI agent (Agents API) the call runs. Required for execution."),voice:l().default("bossa").describe("GPT-Live voice (audio.output.voice). bossa and tempo are the Brazilian Portuguese voices."),voice_instructions:l().default("").describe("Optional persona for the voice layer (tone, pace, language). Empty uses the saved agent's instructions. Supports {{variables}}."),initial_message:l().default("").describe("What the agent says to open the call, in its own words. Empty waits for the caller. Supports {{variables}}."),variables:ie(l(),l()).default({}).describe("Call context handed to the agent at the start. Every value supports {{variables}}."),output_fields:z(Ml).default([]).describe("Values the agent returns when it ends the call, published as output.<name>."),max_duration_minutes:f().min(1).max(60).default(10).describe("Maximum call duration in minutes (1-60). The bridge ends on timeout."),result_wait_seconds:f().int().min(0).max(60).default(10).describe("How long to wait, after the call leg ends, for GPT-Live to close the session and report.")}),Ll=U({meta:{type:"openaiLiveAgent",module:"ai",nameKey:"editor:nodes.openaiLiveAgent.name",descriptionKey:"editor:nodes.openaiLiveAgent.description",color:"iris",icon:"AudioWaveform",category:"handling",order:6,nature:"composite",display:"full",channel:"voice",requires:"voice.agent",connector:{kind:"openai_live",configKey:"connector_id"},outputs:[{key:"completed",labelKey:"editor:handles.completed"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:mo,producedVariables:(e)=>[{name:"duration_ms",type:"number",descriptionKey:"editor:vars.openaiLiveAgent.durationMs"},{name:"provider_call_id",type:"string",descriptionKey:"editor:vars.openaiLiveAgent.providerCallId"},{name:"ended_reason",type:"string",descriptionKey:"editor:vars.openaiLiveAgent.endedReason"},{name:"transcript",type:"string",descriptionKey:"editor:vars.openaiLiveAgent.transcript"},{name:"analysis_pending",type:"string",descriptionKey:"editor:vars.openaiLiveAgent.analysisPending"},...e.output_fields.filter((t)=>po.test(t.name)).map((t)=>({name:`output.${t.name}`,type:"string",descriptionKey:"editor:vars.openaiLiveAgent.outputField"}))]});var zl=g({connector_id:l().default("").describe("Public id of the connector that provides phone.lookup (a Twilio account). Required for execution."),number:l().default("{{Start.callerid}}").describe("Number expression. Supports {{variables}}. Normalized with the platform E.164 rule: a number without a country code is completed with the country below, or the organization's default country."),default_country:l().regex(/^([A-Za-z]{2})?$/u,{error:"editor:validation.whatsappCountry"}).default("").describe("ISO 3166-1 alpha-2 country (e.g. BR) that completes numbers written without a country code. Empty uses the organization's default country."),line_type:F().default(!1).describe("Also fetch line type and carrier. Twilio charges US$ 0,008 per query; format validation alone is free.")}),Fl=U({meta:{type:"phoneLookup",module:"core",nameKey:"editor:nodes.phoneLookup.name",descriptionKey:"editor:nodes.phoneLookup.description",color:"blue",icon:"PhoneForwarded",category:"data",nature:"action",display:"compact",channel:"both",order:10,requires:"phone.lookup",connector:{kind:"twilio",configKey:"connector_id"},outputs:[{key:"valid",labelKey:"editor:handles.valid"},{key:"invalid",labelKey:"editor:handles.invalid"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:zl,producedVariables:[{name:"phone_number",type:"string",descriptionKey:"editor:vars.phoneLookup.phoneNumber"},{name:"national_format",type:"string",descriptionKey:"editor:vars.phoneLookup.nationalFormat"},{name:"country_code",type:"string",descriptionKey:"editor:vars.phoneLookup.countryCode"},{name:"line_type",type:"string",descriptionKey:"editor:vars.phoneLookup.lineType"},{name:"carrier_name",type:"string",descriptionKey:"editor:vars.phoneLookup.carrierName"},{name:"line_type_error",type:"string",descriptionKey:"editor:vars.phoneLookup.lineTypeError"}]});var Ul=g({audio:ve.default({tts:{text:""}}).describe("Audio to play. Use TTS (text-to-speech) or a pre-recorded audio file.")}),jl=U({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:Ul,producedVariables:[]});var Vl=g({queue_id:l().default("").describe("Public id of the queue (que_...) or a {{variable}} that holds it. Required for execution.")}),Kl=U({meta:{type:"queryQueue",module:"queues",nameKey:"editor:nodes.queryQueue.name",descriptionKey:"editor:nodes.queryQueue.description",color:"amber",icon:"ChartNoAxesColumn",category:"handling",order:8,nature:"action",display:"compact",channel:"voice",outputs:[{key:"default",labelKey:"editor:handles.default"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:Vl,producedVariables:[{name:"waiting",type:"number",descriptionKey:"editor:vars.queryQueue.waiting"},{name:"available",type:"number",descriptionKey:"editor:vars.queryQueue.available"},{name:"estimated_wait_s",type:"number",descriptionKey:"editor:vars.queryQueue.estimatedWaitS"},{name:"estimated_wait_text",type:"string",descriptionKey:"editor:vars.queryQueue.estimatedWaitText"},{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"}]});var ql=g({enabled:F().optional(),samplingPercentage:f().int().min(0).max(100).optional()}),Bl=U({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:ql,producedVariables:[{name:"status",type:"string",descriptionKey:"editor:vars.recordingStatus"}]});var Hl=g({connector_id:l().default("").describe("Public id of the connector that provides voice.agent (a Retell account). Required for execution."),agent_id:l().default("").describe("Id of the Retell agent that answers the call. Required for execution."),agent_name:l().default("").describe("Display name of the chosen Retell agent, for logs and the editor."),variables:ie(l(),l()).default({}).describe("Key-value pairs sent to the agent. Every value supports {{variables}}."),max_duration_minutes:f().min(1).max(60).default(10).describe("Maximum call duration in minutes (1-60). The bridge ends on timeout."),result_wait_seconds:f().int().min(0).max(60).default(15).describe("How long to wait for Retell's post-call extraction before continuing.")}),Wl=U({meta:{type:"retellAgent",module:"ai",nameKey:"editor:nodes.retellAgent.name",descriptionKey:"editor:nodes.retellAgent.description",color:"iris",icon:"AudioLines",category:"handling",order:3,nature:"composite",display:"full",channel:"voice",requires:"voice.agent",connector:{kind:"retell",configKey:"connector_id"},outputs:[{key:"completed",labelKey:"editor:handles.completed"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:Hl,producedVariables:[{name:"duration_ms",type:"number",descriptionKey:"editor:vars.retellAgent.durationMs"},{name:"provider_call_id",type:"string",descriptionKey:"editor:vars.retellAgent.providerCallId"},{name:"ended_reason",type:"string",descriptionKey:"editor:vars.retellAgent.endedReason"},{name:"summary",type:"string",descriptionKey:"editor:vars.retellAgent.summary"},{name:"analysis_pending",type:"string",descriptionKey:"editor:vars.retellAgent.analysisPending"},{name:"output.*",type:"string",descriptionKey:"editor:vars.retellAgent.output"}]});var IO=g({label:l().min(1).describe("Intent name. Creates a dynamic output handle 'intent:<label>'."),description:l().default("").describe("Description of what this intent means, used for LLM classification.")}),Gl=g({input:l().default("").describe("Template expression to evaluate, e.g. '{{resposta}}'. The resolved text is classified by AI."),intents:z(IO).default([]).describe("List of intents the LLM should classify the input into. Each creates a dynamic output handle."),instructions:l().default("").describe("Additional instructions for the LLM intent classifier.")}),Zl=U({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:(e)=>[...(e.intents??[]).map((r)=>r.label).filter((r)=>typeof r==="string"&&r!=="").map((r)=>({key:`intent:${r}`,labelKey:r})),{key:"notApplicable",labelKey:"editor:handles.notApplicable"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:Gl,producedVariables:[{name:"intent",type:"string",descriptionKey:"editor:vars.routeAi.intent"},{name:"confidence",type:"number",descriptionKey:"editor:vars.routeAi.confidence"}]});var Yl=g({digits:l().min(1,{error:"editor:validation.digitsRequired"}).default("").describe("DTMF digits to send (0-9, *, #). Supports template expressions.")}),Jl=U({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:Yl,producedVariables:[{name:"dtmf",type:"string",descriptionKey:"editor:vars.dtmf"}]});var Xl=g({connector_id:l().default("").describe("Public id of the connector that provides sms.send (a Twilio account). Required for execution."),from:l().default("").describe("Sender expression: empty uses the connector's default sender, otherwise a Messaging Service SID (MG...) or an E.164 number."),to:l().default("{{Start.callerid}}").describe("Recipient expression. Supports {{variables}}. Normalized with the platform E.164 rule: a number without a country code is completed with the country below, or the organization's default country."),default_country:l().regex(/^([A-Za-z]{2})?$/u,{error:"editor:validation.whatsappCountry"}).default("").describe("ISO 3166-1 alpha-2 country (e.g. BR) that completes recipients written without a country code. Empty uses the organization's default country."),body:l().default("").describe("Message text. Supports {{variables}}; secrets are not allowed in the body."),transliterate:F().default(!1).describe("Replace accented letters by their base letter before sending, so the message fits 160 characters per SMS instead of 70.")}),Ql=U({meta:{type:"sendSms",module:"core",nameKey:"editor:nodes.sendSms.name",descriptionKey:"editor:nodes.sendSms.description",color:"green",icon:"MessageSquare",category:"data",nature:"sideEffect",display:"compact",channel:"both",order:9,requires:"sms.send",connector:{kind:"twilio",configKey:"connector_id"},outputs:[{key:"sent",labelKey:"editor:handles.sent"},{key:"failed",labelKey:"editor:handles.failed"}]},configSchema:Xl,producedVariables:[{name:"message_sid",type:"string",descriptionKey:"editor:vars.sendSms.messageSid"},{name:"segments",type:"number",descriptionKey:"editor:vars.sendSms.segments"},{name:"encoding",type:"string",descriptionKey:"editor:vars.sendSms.encoding"},{name:"error_code",type:"string",descriptionKey:"editor:vars.sendSms.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.sendSms.errorMessage"}]});var ed=g({prefix:l().max(16,{error:"editor:validation.prefixMaxLength"}).default("").describe("Short prefix prepended to the sequence (e.g. 'SAC', '200')."),dateFormat:P(["none","yyyyMMdd","yyMMdd","yyyyMM","ddMMyyyy","yyyyMMddHHmmss"]).default("yyyyMMdd").describe("Date format inserted between prefix and counter."),padding:f().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:P(["daily","monthly","never"]).default("daily").describe("When the counter resets to 1. Uses org timezone for boundary.")}),td=U({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:ed,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 NO=g({key:l().describe("Variable name. Readable as '{{vars.key}}' and through the block's generated namespace."),value:l().describe("Value to assign. Supports template expressions like '{{start.callerid}}'.")}),nd=g({assignments:z(NO).min(1,{error:"editor:validation.noAssignments"}).default([]).describe("List of variable assignments. At least one required.")}),rd=U({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:nd,producedVariables:(e)=>e.assignments.map((t)=>({name:t.key,type:"string",descriptionKey:"editor:vars.custom"}))});var od=g({autoAnswer:F().optional().describe("Auto-answer incoming call before processing. Disable for pre-answer routing.")}),id=U({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:[{key:"voice",labelKey:"editor:handles.voice"},{key:"chat",labelKey:"editor:handles.chat"}]},configSchema:od,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 ad=g({planId:l().min(1,{error:"editor:validation.planIdRequired"}).default("").describe("ID of a published visual plan to execute as a sub-flow. Must be published."),args:ie(l().regex(/^[A-Z_]\w*$/i).max(64),l().max(512)).default({}),endCallOnChildHangup:F().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.")}),sd=U({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:ad,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 OO=g({pattern:l().min(1,{error:"editor:validation.casePatternRequired"}).default("").describe("Value to match against the expression. Creates a 'match:<pattern>' output.")}),cd=g({expression:l().min(1,{error:"editor:validation.expressionRequired"}).default("").describe("Template expression to evaluate, e.g., '{{ivr.digits}}'. Matched against case patterns."),cases:z(OO).default([]).describe("List of patterns to match. Each creates a dynamic output handle 'match:<pattern>'.")}),ld=U({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:(e)=>[...(e.cases??[]).map((r)=>typeof r==="string"?r:r.pattern).filter((r)=>typeof r==="string"&&r!=="").map((r)=>({key:`match:${r}`,labelKey:r})),{key:"fallback",labelKey:"editor:handles.fallback"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:cd,producedVariables:[{name:"destination",type:"string",descriptionKey:"editor:vars.switchDestination"}]});var _b=["image","audio","video","document"],Xi=1048576,kO={image:10*Xi,audio:16*Xi,video:16*Xi,document:20*Xi};var Qi=P(_b),hr=g({id:l().describe("Public TypeID of the attachment (media_...)."),kind:Qi,content_type:l().describe("Type sniffed from the file content."),size_bytes:f().int().nonnegative(),filename:l().nullable(),transcript:l().nullable().describe("Transcript of an audio attachment, when it could be produced.")}),DO=hr.extend({url:l().describe("Signed download link."),url_expires_at:Zt.datetime()});var PO=g({type:I("text"),text:l().min(1)}),bb=Re("provider",[g({provider:I("telegram"),file_id:l().min(1),file_name:l().optional(),mime_type:l().optional()}),g({provider:I("whatsapp"),media_id:l().min(1),file_name:l().optional(),mime_type:l().optional()}),g({provider:I("evolution"),base64:l().optional(),mime_type:l().optional(),file_name:l().optional(),message_key:g({id:l().min(1),remote_jid:l().min(1),from_me:F()})}),g({provider:I("webchat"),media_id:l().min(1)})]),$O=g({type:I("media"),mediaType:Qi,caption:l().optional(),source:bb,attachment:hr.optional()}),MO=g({type:I("location"),lat:f(),lng:f()}),LO=g({type:I("button_reply"),buttonId:l().min(1),buttonText:l()}),zO=g({type:I("list_reply"),listId:l().min(1),listTitle:l()}),FO=g({type:I("command"),command:l().min(1),args:l().optional()}),UO=Re("type",[PO,$O,MO,LO,zO,FO]),yr=g({id:l().min(1),label:l().min(1)}),jO=g({id:l().min(1),title:l().min(1),description:l().optional()}),ea=g({title:l().min(1),items:z(jO).min(1)}),vb=g({title:l().min(1),description:l().optional(),imageUrl:l().optional(),buttons:z(yr).default([])}),VO=g({type:I("text"),text:l().min(1),markdown:F().optional()}),KO=g({type:I("media"),mediaType:P(["image","audio","video","document"]),url:l().min(1),caption:l().optional()}),qO=g({type:I("location"),lat:f(),lng:f(),label:l().optional()}),BO=g({type:I("buttons"),text:l().min(1),buttons:z(yr).min(1)}),HO=g({type:I("list"),text:l().min(1),buttonText:l().min(1),sections:z(ea).min(1)}),WO=g({type:I("carousel"),cards:z(vb).min(1)}),GO=g({type:I("template"),templateId:l().min(1),params:ie(l(),l()).default({})}),ta=Re("type",[VO,KO,qO,BO,HO,WO,GO]),ZO=ta.optional().catch(void 0);var dd=g({audio:ve.optional().describe("Audio to play via TTS, a pre-recorded file, or a remote URL. Used in voice plans."),content:ta.optional().describe("Message content to send in chat. Used in chat plans.")});function Sb(e){return typeof e==="object"&&e!==null&&"url"in e}var ud=U({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:(e)=>Sb(e.audio)?[{key:"next",labelKey:"editor:handles.next"},{key:"error",labelKey:"editor:handles.error"}]:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:dd,producedVariables:(e)=>Sb(e.audio)?[{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"}]:[]});var pd=g({scheduleId:l().optional().describe("Schedule ID for time-based routing. Routes to onHours/offHours/holiday outputs."),emergencyOutput:F().default(!1).describe("Adds an 'emergency' output taken while the schedule is in emergency; otherwise emergency routes to offHours.")}),md=U({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:(e)=>[{key:"onHours",labelKey:"editor:handles.onHours"},{key:"offHours",labelKey:"editor:handles.offHours"},{key:"holiday",labelKey:"editor:handles.holiday"},...e.emergencyOutput===!0?[{key:"emergency",labelKey:"editor:handles.emergency"}]:[]]},configSchema:pd,producedVariables:[{name:"result",type:"string",descriptionKey:"editor:vars.timeResult"},{name:"holiday",type:"string",descriptionKey:"editor:vars.holiday"},{name:"status",type:"string",descriptionKey:"editor:vars.timeStatus"},{name:"reason",type:"string",descriptionKey:"editor:vars.timeReason"},{name:"description",type:"string",descriptionKey:"editor:vars.timeDescription"},{name:"closes_at",type:"string",descriptionKey:"editor:vars.timeClosesAt"},{name:"minutes_to_close",type:"number",descriptionKey:"editor:vars.timeMinutesToClose"},{name:"reopens_at",type:"string",descriptionKey:"editor:vars.timeReopensAt"},{name:"reopens_speech",type:"string",descriptionKey:"editor:vars.timeReopensSpeech"},{name:"hours_speech",type:"string",descriptionKey:"editor:vars.timeHoursSpeech"},{name:"period",type:"string",descriptionKey:"editor:vars.timePeriod"}]});var fd=g({name:l().min(1,{error:"editor:validation.trafficSplitPathNameRequired"}).default("").describe("Path name. Creates a 'path:<name>' output handle."),weight:f().int().min(0).max(100).default(1).describe("Relative share of this path (0-100). Zero disables it without deleting it.")}),gd=g({paths:z(fd).default([{name:"A",weight:50},{name:"B",weight:50}]).describe("Weighted paths. Each creates a dynamic output handle 'path:<name>'."),mode:P(["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.")}),hd=U({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:(e)=>{let t=e.paths??[],n=[],r=new Set;for(let o of t){let i=typeof o==="object"&&o!=null?o.name:void 0;if(typeof i!=="string"||i===""||r.has(i))continue;r.add(i),n.push(i)}return[...n.map((o)=>({key:`path:${o}`,labelKey:o})),{key:"error",labelKey:"editor:handles.error"}]}},configSchema:gd,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 yd=g({enabled:F().optional(),scope:P(["from_here","whole_recording"]).optional(),samplingPercentage:f().int().min(0).max(100).optional(),language:l().optional(),minDurationSeconds:f().int().min(0).max(Pn).optional(),speechRequirement:P(Yt).optional(),anonymizeEnabled:F().optional(),speechAnalyticsEnabled:F().optional(),sentimentEnabled:F().optional(),transcriptionType:P(mn).optional()}),_d=U({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:yd,producedVariables:[{name:"status",type:"string",descriptionKey:"editor:vars.transcriptionStatus"}]});var bd=g({method:P(["bridge","transfer"]).default("bridge").describe("Transfer method. 'bridge' keeps call control; 'transfer' hands off completely."),destinations:z(l()).default([]).describe("SIP URIs or phone numbers to dial. At least one required. Tried in order."),timeout:f().min(5).max(120).optional().describe("Ring timeout in seconds per destination (5-120). Omit for carrier default."),attachedData:Ji({key:"Attached-data field name shown to the agent / CRM (e.g. 'Nome').",list:"Key/value pairs delivered to the agent at transfer time (screen-pop). Values support templates."})}),vd=U({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:bd,producedVariables:[{name:"status",type:"string",descriptionKey:"editor:vars.transferStatus"},{name:"note",type:"string",descriptionKey:"editor:vars.transferNote"},{name:"disposition",type:"string",descriptionKey:"editor:vars.transferDisposition"},{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"}]});var Sd=g({connector_id:l().default("").describe("Public id of the connector that provides voice.agent (a Vapi account). Required for execution."),assistant_id:l().default("").describe("Id of the Vapi assistant that answers the call. Required for execution."),assistant_name:l().default("").describe("Display name of the chosen Vapi assistant, for logs and the editor."),variables:ie(l(),l()).default({}).describe("Key-value pairs sent to the agent. Every value supports {{variables}}."),max_duration_minutes:f().min(1).max(60).default(10).describe("Maximum call duration in minutes (1-60). The bridge ends on timeout."),result_wait_seconds:f().int().min(0).max(60).default(15).describe("How long to wait for Vapi's end of call report before continuing.")}),xd=U({meta:{type:"vapiAgent",module:"ai",nameKey:"editor:nodes.vapiAgent.name",descriptionKey:"editor:nodes.vapiAgent.description",color:"iris",icon:"AudioWaveform",category:"handling",order:4,nature:"composite",display:"full",channel:"voice",requires:"voice.agent",connector:{kind:"vapi",configKey:"connector_id"},outputs:[{key:"completed",labelKey:"editor:handles.completed"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:Sd,producedVariables:[{name:"duration_ms",type:"number",descriptionKey:"editor:vars.vapiAgent.durationMs"},{name:"provider_call_id",type:"string",descriptionKey:"editor:vars.vapiAgent.providerCallId"},{name:"ended_reason",type:"string",descriptionKey:"editor:vars.vapiAgent.endedReason"},{name:"summary",type:"string",descriptionKey:"editor:vars.vapiAgent.summary"},{name:"analysis_pending",type:"string",descriptionKey:"editor:vars.vapiAgent.analysisPending"},{name:"output.*",type:"string",descriptionKey:"editor:vars.vapiAgent.output"}]});var Ed="Enviamos um código por SMS. Digite o código no teclado do telefone.",wd=g({connector_id:l().default("").describe("Public id of the connector that provides verify.otp (a Twilio account). Required for execution."),service_sid:l().default("").describe("Verify Service SID (VA...) whose code length and sender configuration the block uses."),to:l().default("{{Start.callerid}}").describe("Recipient expression. Supports {{variables}}. Normalized with the platform E.164 rule: a number without a country code is completed with the country below, or the organization's default country."),default_country:l().regex(/^([A-Za-z]{2})?$/u,{error:"editor:validation.whatsappCountry"}).default("").describe("ISO 3166-1 alpha-2 country (e.g. BR) that completes recipients written without a country code. Empty uses the organization's default country."),channel:P(["sms","whatsapp","call"]).default("sms").describe("How the code reaches the contact: sms, whatsapp or call. Twilio sends it; NIVA needs no extra setup."),prompt:ve.default({tts:{text:Ed}}).describe("Audio prompt asking for the code, played with the plan's voice. In chat, its text is sent."),max_attempts:f().int().min(1,{error:"editor:validation.attemptsMin"}).max(5,{error:"editor:validation.attemptsMax"}).default(3).describe("Maximum wrong-code attempts before the block leaves by rejected (1-5)."),timeout_seconds:f().int().min(1,{error:"editor:validation.timeoutMin"}).max(60,{error:"editor:validation.timeoutMax"}).default(10).describe("Seconds to wait for the code after the prompt (1-60).")}),Cd=U({meta:{type:"verifyCode",module:"core",nameKey:"editor:nodes.verifyCode.name",descriptionKey:"editor:nodes.verifyCode.description",color:"purple",icon:"ShieldCheck",category:"data",nature:"composite",display:"full",channel:"both",order:11,requires:"verify.otp",connector:{kind:"twilio",configKey:"connector_id"},sensitiveInput:!0,outputs:[{key:"approved",labelKey:"editor:handles.approved"},{key:"rejected",labelKey:"editor:handles.rejected"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:wd,producedVariables:[{name:"status",type:"string",descriptionKey:"editor:vars.verifyCode.status"},{name:"attempts",type:"number",descriptionKey:"editor:vars.verifyCode.attempts"},{name:"channel",type:"string",descriptionKey:"editor:vars.verifyCode.channel"}]});var YO=g({label:l().min(1).describe("Intent name. Creates a dynamic output handle 'intent:<label>'."),description:l().default("").describe("Description of what this intent means, used for LLM classification.")}),JO=g({language:l().optional().describe("BCP 47 language code for speech recognition (e.g., 'pt-BR'). Omit for plan default."),initial_timeout_s:f().min(3).max(60).default(10).describe("Maximum seconds to wait for speech to begin (3-60)."),timeout_s:f().min(1).max(30).default(3).describe("Seconds of post-speech silence before stopping recording (1-30)."),max_duration_s:f().min(1).max(60).default(15).describe("Maximum recording duration in seconds (1-60)."),beep:F().default(!1).describe("Play a beep sound before starting to listen.")}),XO=g({max_retries:f().min(0).max(5).default(2).describe("Maximum retries when speech is not recognized (0-5)."),prompt:ve.optional().describe("Audio played when retrying after unrecognized speech. Falls back to main prompt if not set.")});var Ad=g({mode:P(["intent","capture"]).default("intent").describe("'intent' classifies speech into configured intents; 'capture' transcribes speech without classification."),prompt:ve.default({tts:{text:""}}).describe("Audio prompt played before listening for speech."),intents:z(YO).default([]).describe("List of intents the LLM should classify speech into. Only used when mode is 'intent'."),classification_instructions:l().default("").describe("Additional instructions for the LLM intent classifier. Only used when mode is 'intent'."),listen:JO.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:ve.optional().describe("Audio played while the AI processes the speech. Optional."),retry:XO.default({max_retries:2}).describe("Retry behavior when speech is not recognized.")}),Td=U({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:(e)=>{if((e.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[...(e.intents??[]).map((o)=>typeof o==="string"?o:o.label).filter((o)=>typeof o==="string"&&o!=="").map((o)=>({key:`intent:${o}`,labelKey:o})),{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:Ad,producedVariables:(e)=>{if(e.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 Rd=g({method:P(["POST","PUT","PATCH","GET","DELETE"]).default("POST").describe("HTTP method for the request."),url:gr.describe("Destination URL. Supports template expressions, e.g., 'https://hooks.example.com/{{start.callerid}}'."),headers:ie(l(),l()).optional().describe("HTTP headers as key-value pairs. Values support template expressions."),body:l().optional().describe("Request body (JSON string). Template expressions allowed. Only for POST/PUT/PATCH/DELETE.")}),Id=U({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:Rd,producedVariables:[]});var Nd=4096,Od=g({connectorId:l().default("").describe("Public id of the connector that provides whatsapp.messages (an Evolution API gateway)."),phoneNumberId:l().default("").describe("Name of the Evolution instance the message is sent from: one connected number of the connector."),to:l().default("{{Start.callerid}}").describe("Recipient expression. Supports {{variables}}. Normalized with the platform E.164 rule: numbers without a country code are completed with the country below, or the organization's default country."),defaultCountry:l().regex(/^([A-Za-z]{2})?$/u,{error:"editor:validation.whatsappCountry"}).default("").describe("ISO 3166-1 alpha-2 country (e.g. BR) that completes recipients written without a country code. Empty uses the organization's default country."),text:l().default("").describe(`Message text. Supports {{variables}}. Required; at most ${Nd} characters once the variables are resolved.`)}),kd=U({meta:{type:"whatsappMessage",module:"core",nameKey:"editor:nodes.whatsappMessage.name",descriptionKey:"editor:nodes.whatsappMessage.description",color:"green",icon:"MessageCircle",category:"data",nature:"sideEffect",display:"compact",channel:"both",order:8,requires:"whatsapp.messages",connector:{kind:"evolution_api",configKey:"connectorId"},outputs:[{key:"sent",labelKey:"editor:handles.sent"},{key:"failed",labelKey:"editor:handles.failed"}]},configSchema:Od,producedVariables:[{name:"message_id",type:"string",descriptionKey:"editor:vars.whatsappMessage.messageId"},{name:"error_code",type:"string",descriptionKey:"editor:vars.whatsappMessage.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.whatsappMessage.errorMessage"}]});var xb=ie(l(),l()).default({}),Dd=g({connectorId:l().default("").describe("Public id of the connector that provides whatsapp.templates (e.g. a WhatsApp Business connector)."),phoneNumberId:l().default("").describe("Id of the WhatsApp number the message is sent from, one of the connector's numbers."),template:g({name:l().default(""),language:l().default("")}).default({name:"",language:""}).describe("The approved message template to send, by name and language code (e.g. boleto / pt_BR)."),to:l().default("{{Start.callerid}}").describe("Recipient expression. Supports {{variables}}. Normalized with the platform E.164 rule: numbers without a country code are completed with the country below, or the organization's default country."),defaultCountry:l().regex(/^([A-Za-z]{2})?$/u,{error:"editor:validation.whatsappCountry"}).default("").describe("ISO 3166-1 alpha-2 country (e.g. BR) that completes recipients written without a country code. Empty uses the organization's default country."),parameters:g({header:l().optional().describe("Header value: the text variable of a text header, or the media URL of an image/video/document header."),body:xb.describe("Body variable values, keyed by variable name ('1', '2' or 'first_name')."),buttons:xb.describe("URL button suffix values, keyed by the button's index ('0', '1', ...).")}).default({body:{},buttons:{}}).describe("Template variable values. Every value supports {{variables}}.")}),Pd=U({meta:{type:"whatsappTemplate",module:"core",nameKey:"editor:nodes.whatsappTemplate.name",descriptionKey:"editor:nodes.whatsappTemplate.description",color:"green",icon:"MessageCircle",category:"data",nature:"sideEffect",display:"compact",channel:"both",order:7,requires:"whatsapp.templates",connector:{kind:"whatsapp_business",configKey:"connectorId"},outputs:[{key:"sent",labelKey:"editor:handles.sent"},{key:"failed",labelKey:"editor:handles.failed"}]},configSchema:Dd,producedVariables:[{name:"message_id",type:"string",descriptionKey:"editor:vars.whatsappMessageId"},{name:"error_code",type:"string",descriptionKey:"editor:vars.whatsappErrorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.whatsappErrorMessage"}]});var vt={start:id,playback:jl,ivr:kl,collectDigits:hl,transfer:vd,enterQueue:Al,queryQueue:Kl,hangup:Rl,timeRouting:md,switchCase:ld,trafficSplit:hd,setVariable:rd,sequence:td,counter:_l,httpRequest:Nl,webhook:Id,whatsappTemplate:Pd,whatsappMessage:kd,sendSms:Ql,phoneLookup:Fl,verifyCode:Cd,dataTransform:vl,subPlan:sd,sendDtmf:Jl,aiAgent:rl,retellAgent:Wl,vapiAgent:xd,elevenlabsAgent:xl,openaiLiveAgent:Ll,voiceRecognition:Td,tell:ud,menu:$l,capture:pl,routeAi:Zl,channelRouter:fl,addToDnc:tl,apiSwitch:dl,enableRecord:wl,recording:Bl,transcription:_d,analysis:al},St=Object.fromEntries(Object.entries(vt).map(([e,t])=>[e,t.meta]));var hH=Number.MAX_SAFE_INTEGER;var $d=["active","expired","suspended","poc"],Eb=g({enabled:F(),limits:ie(l(),Be([f(),l(),F(),z(l())])).default({})}),ak=g({id:l().min(1),name:l().min(1)}),sk=g({customerId:l(),customerName:l().optional(),serial:l(),status:P($d),issuedAt:pr.date(),expiresAt:pr.date().nullable(),gracePeriodDays:f().int().min(0),modules:ie(l(),Eb),isExpired:F(),isInGracePeriod:F(),daysUntilExpiry:f().nullable(),keepsAccess:F().optional(),plan:pt().optional().transform((e)=>{let t=ak.safeParse(e);return t.success?t.data:void 0})}),ck=g({voice:f().int().default(0),chat:f().int().default(0)}).optional(),lk=g({customer_id:l().min(1),customer_name:l().min(1).optional(),serial:l().min(1),status:P($d),issued_at:pr.date(),expires_at:pr.date().nullable().default(null),grace_period_days:f().int().min(0).default(0),max_concurrent_channels:ck,modules:ie(l(),Eb)});var _r=["yes_no","choice","scale"],wb=["caller","agent","both"],br=["info","warning","critical"],fo=["worse","better","neutral"],dk=/^[a-z][a-z0-9_]{0,63}$/,uk=/^[a-z0-9][a-z0-9_]{0,47}$/,Cb=g({key:l().regex(uk),label:l().min(1).max(80),description:l().max(240).optional(),archived:F().default(!1)}),Ab=Be([g({answer:P(["yes","no"])}),g({options:z(l()).min(1)}),g({level_at_least:f()}),g({level_at_most:f()})]),pk=g({when:Ab,severity:P(br),bell:F().default(!1),attendant_hint:l().trim().min(1).max(200).nullable().optional()}),mk=g({slug:l().regex(dk),name:l().trim().min(1).max(80),question:l().trim().min(1).max(500),kind:P(_r),options:z(Cb).min(2).max(12).optional(),levels:z(l().min(1).max(40)).min(3).max(5).optional(),higher_is:P(fo).optional(),speaker:P(wb),scope:g({node_types:z(l().min(1)).min(1).max(20)}).nullable(),live:F(),alert:pk.nullable()});function Tb(e){return e.higher_is??"worse"}function fk(e,t){if(e.kind==="choice"){if(e.options===void 0){t.addIssue({code:"custom",message:"signals:validation.optionsRequired",path:["options"]});return}let n=e.options.map((r)=>r.key);if(new Set(n).size!==n.length)t.addIssue({code:"custom",message:"signals:validation.optionKeyUnique",path:["options"]});if(e.options.filter((r)=>!r.archived).length<2)t.addIssue({code:"custom",message:"signals:validation.twoActiveOptions",path:["options"]})}else if(e.options!==void 0)t.addIssue({code:"custom",message:"signals:validation.optionsChoiceOnly",path:["options"]})}function gk(e,t){if(e.kind==="scale"){if(e.levels===void 0)t.addIssue({code:"custom",message:"signals:validation.levelsRequired",path:["levels"]})}else{if(e.levels!==void 0)t.addIssue({code:"custom",message:"signals:validation.levelsScaleOnly",path:["levels"]});if(e.higher_is!==void 0)t.addIssue({code:"custom",message:"signals:validation.higherIsScaleOnly",path:["higher_is"]})}}function hk(e,t){if(e.levels===void 0)return!1;let n=Tb(e),r=e.levels.length-1;if("level_at_least"in t){let o=t.level_at_least;return n!=="better"&&Number.isInteger(o)&&o>=1&&o<=r}if("level_at_most"in t){let o=t.level_at_most;return n!=="worse"&&Number.isInteger(o)&&o>=0&&o<=r-1}return!1}function yk(e){if(e.alert===null)return!0;let t=e.alert.when;switch(e.kind){case"yes_no":return"answer"in t;case"choice":return"options"in t&&e.options!==void 0&&t.options.every((n)=>e.options?.some((r)=>r.key===n&&!r.archived)===!0);case"scale":return hk(e,t)}}function Rb(e,t){if(fk(e,t),gk(e,t),!yk(e))t.addIssue({code:"custom",message:"signals:validation.whenMustMatchKind",path:["alert","when"]})}var vr=mk.superRefine(Rb);var na=g({channel:Be([I(0),I(1)]),text:l(),isFinal:F(),confidence:f(),start:f(),end:f(),words:z(g({word:l(),start:f(),end:f()})).optional(),timestamp:l(),nodeId:l().optional(),nodeLabel:l().optional(),nodeType:l().optional(),redacted:F().optional(),attachment:hr.omit({transcript:!0}).optional()}),Ob={signal:g({id:l().min(1),slug:l().min(1),name:l(),kind:P(_r),severity:P(br).nullable(),bell:F()}),value:Be([F(),l(),f(),Pt()]),value_label:l(),confidence:f(),at_seconds:f(),node:g({id:l(),label:l(),type:l()}).nullable(),late:F()},ra=g({type:I("signal_value"),...Ob}),oa=g({type:I("signal_triggered"),...Ob}),kb=Re("type",[ra,oa]),bk=Re("type",[g({type:I("segment"),segment:na}),ra,oa,g({type:I("started"),backlog_seconds:f(),live_from:f()}),g({type:I("caught_up")}),g({type:I("ended")}),g({type:I("error"),message:l()})]),vk=Re("type",[g({type:I("segment"),segment:na}),g({type:I("history"),segments:z(na),signals:z(kb).optional()}),ra,oa,g({type:I("starting")}),g({type:I("started"),backlog_seconds:f(),live_from:f()}),g({type:I("caught_up")}),g({type:I("ended")}),g({type:I("error"),message:l()}),g({type:I("unavailable"),reason:P(["not_recorded","no_credential","test_call"])})]),Sk=g({uuid:l(),action:P(["start","stop"])}),Db=["not_live","provider_error","drain_timeout","redact_mid_call"],Pb=g({startByte:f().int().min(0),endByte:f().int().min(0)}),xk=g({complete:F(),reason:P(Db).optional(),model:l(),redact:F(),coveredRanges:z(Pb)});var Ek=Qc.filter((e)=>e!=="classifier");function ae(e){return{...e,defaults:{...e.defaults,email:e.defaults.email??!1}}}var Mt={enabled:!0,toast:!0},xt={enabled:!0,toast:!1},wk={enabled:!1,toast:!1},Ck={freeswitch:"FreeSWITCH",database:"Database",redis:"Redis"},ia=(e)=>Ck[e]??"Redis",Lt=(e,t,n)=>e===1?t:n,$b={"email.delivery_failed":ae({kind:"email.delivery_failed",area:"services",audience:"platform",permission:"system:diagnostics",severity:"warning",params:K({}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/system/email",defaults:xt,en:{title:()=>"Email delivery failed",body:()=>"An email could not be delivered. Check the SMTP settings and server logs."},pt:{title:()=>"Falha no envio de e-mail",body:()=>"Um e-mail não pôde ser entregue. Confira o SMTP em Sistema > E-mail e os logs do servidor."}}),"service.down":ae({kind:"service.down",area:"services",audience:"platform",permission:"system:diagnostics",severity:"critical",params:K({component:l()}),grouping:{mode:"incident"},groupKey:(e)=>e.component,link:()=>"/dashboard",defaults:Mt,en:{title:(e)=>`${ia(e.component)} offline`,body:(e)=>`${ia(e.component)} is unreachable.`},pt:{title:(e)=>`${e.component} indisponível`,body:(e)=>`Não foi possível acessar ${e.component}.`},webhook:{alertType:(e)=>`service_offline:${e.component}`,resolvedTitle:(e)=>`${ia(e.component)} recovered`,resolvedBody:(e)=>`${ia(e.component)} is back online.`}}),"license.expiring":ae({kind:"license.expiring",area:"usage",audience:"platform",permission:"system:diagnostics",severity:"warning",params:K({days:f(),expires_on:l()}),grouping:{mode:"incident"},groupKey:(e)=>e.expires_on,link:()=>"/system/license",defaults:xt,en:{title:(e)=>`License expires in ${e.days} ${Lt(e.days,"day","days")}`,body:(e)=>`License expires in ${e.days} ${Lt(e.days,"day","days")}.`},pt:{title:()=>"Licença próxima do vencimento",body:(e)=>`A licença vence em ${e.days} ${e.days===1?"dia":"dias"}.`},webhook:{alertType:()=>"license_expiring",metricValue:(e)=>e.days,threshold:()=>30,resolvedTitle:()=>"License expiry warning closed",resolvedBody:()=>"The license was renewed or has expired."}}),"license.expired":ae({kind:"license.expired",area:"usage",audience:"platform",permission:"system:diagnostics",severity:"critical",params:K({}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/system/license",defaults:Mt,locked:!0,en:{title:()=>"License expired",body:()=>"NIVA license has expired."},pt:{title:()=>"Licença vencida",body:()=>"A licença da NIVA venceu."},webhook:{alertType:()=>"license_expired"}}),"storage.disk":ae({kind:"storage.disk",area:"services",audience:"platform",permission:"system:diagnostics",severity:"warning",params:K({pct:f(),threshold:f()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/system/storage",defaults:xt,en:{title:(e)=>`Disk usage ${e.pct}%`,body:(e)=>`Disk usage at ${e.pct}%.`},pt:{title:()=>"Uso de disco elevado",body:(e)=>`O uso do disco chegou a ${e.pct}%.`},webhook:{alertType:()=>"storage_high",metricValue:(e)=>e.pct,threshold:(e)=>e.threshold}}),"storage.recordings_blocked":ae({kind:"storage.recordings_blocked",area:"services",audience:"platform",permission:"system:diagnostics",severity:"warning",params:K({used:f(),cap:f()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/system/storage",defaults:xt,en:{title:(e)=>`Recording storage cap reached (${e.used} GB of ${e.cap} GB)`,body:(e)=>`Recordings use ${e.used} GB against a ${e.cap} GB cap and none may be removed yet.`},pt:{title:()=>"Limite de armazenamento das gravações atingido",body:(e)=>`As gravações ocupam ${e.used} GB de ${e.cap} GB e ainda não podem ser removidas.`},webhook:{alertType:()=>"recording_retention_blocked",metricValue:(e)=>e.used,threshold:(e)=>e.cap}}),"calls.error_rate":ae({kind:"calls.error_rate",area:"calls",audience:"organization",permission:"call_record:read",severity:"warning",params:K({rate:f(),failures:f(),total:f(),threshold:f(),plan_name:l().optional()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/reports",defaults:Mt,en:{title:(e)=>`Call error rate ${e.rate}%`,body:(e)=>`${e.failures}/${e.total} failed.`},pt:{title:()=>"Taxa de erros nas chamadas",body:(e)=>`${e.failures} de ${e.total} chamadas falharam (${e.rate}%).`},webhook:{alertType:()=>"call_error_rate",metricValue:(e)=>e.rate,threshold:(e)=>e.threshold}}),"calls.plan_error_rate":ae({kind:"calls.plan_error_rate",area:"calls",audience:"organization",permission:"call_record:read",severity:"warning",params:K({plan_id:l(),plan_name:l(),rate:f(),failures:f(),total:f(),threshold:f()}),grouping:{mode:"incident"},groupKey:(e)=>e.plan_id,link:()=>"/reports",defaults:xt,en:{title:(e)=>`${e.plan_name}: error rate ${e.rate}%`,body:(e)=>`${e.failures}/${e.total} failed.`},pt:{title:(e)=>`Erros no plano ${e.plan_name}`,body:(e)=>`${e.failures} de ${e.total} chamadas falharam (${e.rate}%).`},webhook:{alertType:()=>"plan_error_rate",metricValue:(e)=>e.rate,threshold:(e)=>e.threshold}}),"calls.transfer_failure":ae({kind:"calls.transfer_failure",area:"calls",audience:"organization",permission:"call_record:read",severity:"warning",params:K({rate:f(),failures:f(),total:f(),threshold:f()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/reports",defaults:xt,en:{title:(e)=>`Transfer failure rate ${e.rate}%`,body:(e)=>`${e.failures}/${e.total} failed.`},pt:{title:()=>"Falhas nas transferências",body:(e)=>`${e.failures} de ${e.total} transferências falharam (${e.rate}%).`},webhook:{alertType:()=>"transfer_failure_rate",metricValue:(e)=>e.rate,threshold:(e)=>e.threshold}}),"calls.stale":ae({kind:"calls.stale",area:"calls",audience:"organization",permission:"call_record:read",severity:"warning",params:K({count:f(),threshold:f()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/reports",defaults:xt,en:{title:()=>"Stale calls detected",body:(e)=>`${e.count} ${Lt(e.count,"stale call","stale calls")}.`},pt:{title:()=>"Chamadas sem atividade",body:(e)=>`Foram detectadas ${e.count} chamadas sem atividade.`},webhook:{alertType:()=>"stale_calls",metricValue:(e)=>e.count,threshold:(e)=>e.threshold}}),"calls.transcription_failed":ae({kind:"calls.transcription_failed",area:"calls",audience:"organization",permission:"call_record:read",severity:"warning",params:K({count:f(),threshold:f()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/reports",defaults:xt,en:{title:()=>"Transcription failures",body:(e)=>`${e.count} ${Lt(e.count,"failure","failures")}.`},pt:{title:()=>"Falhas na transcrição",body:(e)=>`Foram detectadas ${e.count} falhas na transcrição.`},webhook:{alertType:()=>"transcription_failures",metricValue:(e)=>e.count,threshold:(e)=>e.threshold}}),"desk.mention":ae({kind:"desk.mention",area:"desk",audience:"organization",permission:"desk:use",severity:"info",params:K({mention_id:l(),conversation_id:l(),author_name:l(),contact_name:l().nullable()}),grouping:{mode:"once"},groupKey:(e)=>e.mention_id,link:(e)=>`/desk?conversation=${e.conversation_id}`,defaults:{enabled:!0,toast:!0,email:!1},en:{title:()=>"You were mentioned",body:(e)=>e.contact_name===null?`${e.author_name} mentioned you in a note.`:`${e.author_name} mentioned you in a note on the conversation with ${e.contact_name}.`},pt:{title:()=>"Você foi mencionado",body:(e)=>e.contact_name===null?`${e.author_name} mencionou você em uma nota.`:`${e.author_name} mencionou você em uma nota da conversa com ${e.contact_name}.`}}),"calls.export_ready":ae({kind:"calls.export_ready",area:"calls",audience:"organization",permission:"call_record:export",severity:"info",params:K({export_job_id:l(),filename:l(),total_records:f().nullable()}),grouping:{mode:"once"},groupKey:(e)=>e.export_job_id,link:()=>"/reports?tab=exports",defaults:{enabled:!0,toast:!0,email:!1},en:{title:()=>"Export ready",body:(e)=>`${e.filename} is ready to download.`},pt:{title:()=>"Exportação pronta",body:(e)=>`${e.filename} está pronto para download.`}}),"calls.export_failed":ae({kind:"calls.export_failed",area:"calls",audience:"organization",permission:"call_record:export",severity:"warning",params:K({export_job_id:l(),filename:l(),total_records:f().nullable()}),grouping:{mode:"once"},groupKey:(e)=>e.export_job_id,link:()=>"/reports?tab=exports",defaults:{enabled:!0,toast:!0,email:!1},en:{title:()=>"Export failed",body:(e)=>`${e.filename} could not be generated.`},pt:{title:()=>"Falha na exportação",body:(e)=>`Não foi possível gerar ${e.filename}.`}}),"audit.export_ready":ae({kind:"audit.export_ready",area:"audit",audience:"organization",permission:"audit:read",severity:"info",params:K({export_job_id:l(),filename:l(),total_records:f().nullable()}),grouping:{mode:"once"},groupKey:(e)=>e.export_job_id,link:()=>"/settings/audit?tab=exports",defaults:{enabled:!0,toast:!0,email:!1},en:{title:()=>"Export ready",body:(e)=>`${e.filename} is ready to download.`},pt:{title:()=>"Exportação pronta",body:(e)=>`${e.filename} está pronto para download.`}}),"audit.export_failed":ae({kind:"audit.export_failed",area:"audit",audience:"organization",permission:"audit:read",severity:"warning",params:K({export_job_id:l(),filename:l(),total_records:f().nullable()}),grouping:{mode:"once"},groupKey:(e)=>e.export_job_id,link:()=>"/settings/audit?tab=exports",defaults:{enabled:!0,toast:!0,email:!1},en:{title:()=>"Export failed",body:(e)=>`${e.filename} could not be generated.`},pt:{title:()=>"Falha na exportação",body:(e)=>`Não foi possível gerar ${e.filename}.`}}),"calls.rejected":ae({kind:"calls.rejected",area:"calls",audience:"organization",permission:"call_record:read",severity:"warning",params:K({reason:l(),destination:l(),count:f()}),grouping:{mode:"window",windowSeconds:900},groupKey:(e)=>e.reason,link:()=>"/reports",defaults:xt,en:{title:()=>"Calls rejected",body:(e,t)=>`${t.count} ${Lt(t.count,"call","calls")} rejected (${e.reason}).`},pt:{title:()=>"Chamadas rejeitadas",body:(e,t)=>`${t.count} ${t.count===1?"chamada rejeitada":"chamadas rejeitadas"}: ${e.reason}.`}}),"calls.node_error":ae({kind:"calls.node_error",area:"calls",audience:"organization",permission:"call_record:read",severity:"warning",params:K({node_id:l(),node_type:l(),node_label:l(),error_code:l(),visual_plan_id:l(),visual_plan_name:l(),count:f()}),grouping:{mode:"window",windowSeconds:900},groupKey:(e)=>`${e.visual_plan_id}:${e.node_id}:${e.error_code}`,link:()=>"/reports",defaults:xt,en:{title:()=>"Call node errors",body:(e,t)=>`${t.count} ${Lt(t.count,"error","errors")} in ${e.node_label} (${e.error_code}).`},pt:{title:()=>"Erros nos nós de chamada",body:(e,t)=>`${t.count} ${t.count===1?"erro":"erros"} em ${e.node_label} (${e.error_code}).`}}),"webhook.endpoint_down":ae({kind:"webhook.endpoint_down",area:"integrations",audience:"organization",permission:"webhook:read",severity:"critical",params:K({endpoint_id:l(),endpoint_url:l(),endpoint_description:l().nullable(),failed_attempts:f(),last_error:l().nullable()}),grouping:{mode:"incident"},groupKey:(e)=>e.endpoint_id,link:()=>"/settings/webhooks",defaults:Mt,en:{title:()=>"Webhook endpoint failing",body:(e)=>`${e.failed_attempts} consecutive ${Lt(e.failed_attempts,"failure","failures")}.`},pt:{title:()=>"Webhook com falhas",body:(e)=>`${e.failed_attempts} ${e.failed_attempts===1?"falha consecutiva":"falhas consecutivas"} na entrega do webhook.`},webhook:{alertType:()=>"webhook_failures",metricValue:(e)=>e.failed_attempts,threshold:()=>3}}),"webhook.queue_delayed":ae({kind:"webhook.queue_delayed",area:"integrations",audience:"organization",permission:"webhook:read",severity:"warning",params:K({depth:f(),minutes:f(),threshold:f()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/settings/webhooks",defaults:xt,en:{title:(e)=>`Webhook queue delayed ${e.minutes} min`,body:(e)=>`${e.depth} pending ${Lt(e.depth,"delivery","deliveries")}; the oldest has waited ${e.minutes} min.`},pt:{title:()=>"Fila de webhooks atrasada",body:(e)=>`${e.depth} entregas pendentes; a mais antiga aguarda há ${e.minutes} min.`},webhook:{alertType:()=>"webhook_queue_backlog",metricValue:(e)=>e.minutes,threshold:(e)=>e.threshold}}),"connector.needs_attention":ae({kind:"connector.needs_attention",area:"integrations",audience:"organization",permission:"connector:read",severity:"critical",params:K({connector_id:l(),connector_name:l(),kind:l(),error_code:l(),error_message:l()}),grouping:{mode:"incident"},groupKey:(e)=>e.connector_id,link:(e)=>`/settings/connectors/${e.connector_id}`,defaults:Mt,en:{title:(e)=>`Connector ${e.connector_name} needs attention`,body:(e)=>`${e.error_code}: ${e.error_message}`},pt:{title:(e)=>`O conector ${e.connector_name} precisa de atenção`,body:(e)=>`${e.error_code}: ${e.error_message}`},webhook:{alertType:()=>"connector_needs_attention"}}),"secret.missing":ae({kind:"secret.missing",area:"integrations",audience:"organization",permission:"secret:read",severity:"critical",params:K({secret:l(),node_label:l()}),grouping:{mode:"window",windowSeconds:3600},groupKey:(e)=>e.secret,link:()=>"/settings/secrets",defaults:Mt,en:{title:()=>"Secret missing",body:(e)=>`The secret ${e.secret} is missing for ${e.node_label}.`},pt:{title:()=>"Secret ausente",body:(e)=>`O secret ${e.secret} está ausente em ${e.node_label}.`}}),"signal.triggered":ae({kind:"signal.triggered",area:"signals",audience:"organization",permission:"ai:read",severity:"warning",params:K({signal:l(),signal_id:l(),call_id:l(),caller:l().nullable()}),grouping:{mode:"window",windowSeconds:900},groupKey:(e)=>e.signal_id,link:(e,t)=>t.count===1?`/reports?trace=${e.call_id}`:`/reports?signal=${e.signal_id}`,defaults:Mt,en:{title:(e)=>`Signal triggered: ${e.signal}`,body:(e,t)=>`${t.count} ${Lt(t.count,"call","calls")} triggered ${e.signal}.`},pt:{title:(e)=>`Sinal detectado: ${e.signal}`,body:(e,t)=>`${t.count} ${t.count===1?"chamada acionou":"chamadas acionaram"} o sinal ${e.signal}.`}}),"usage.channel_capacity":ae({kind:"usage.channel_capacity",area:"usage",audience:"organization",permission:"channel:read",severity:"warning",params:K({pct:f(),active:f(),limit:f(),pool:l()}),grouping:{mode:"incident"},groupKey:(e)=>e.pool,link:()=>"/dashboard",defaults:Mt,en:{title:(e)=>`${e.pool} channel capacity ${e.pct}%`,body:(e)=>`${e.active}/${e.limit} ${e.pool} ${Lt(e.limit,"channel","channels")} in use.`},pt:{title:()=>"Capacidade de canais",body:(e)=>`${e.active} de ${e.limit} canais ${e.pool} em uso (${e.pct}%).`},webhook:{alertType:()=>"channel_capacity",metricValue:(e)=>e.pct,threshold:()=>90}}),"usage.audit_retention":ae({kind:"usage.audit_retention",area:"usage",audience:"organization",permission:"audit:read",severity:"warning",params:K({count:f(),limit:f()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/settings/audit",defaults:wk,en:{title:()=>"Audit retention capacity exceeded",body:(e)=>`Audit log count (${e.count}) exceeds the retention limit (${e.limit}).`},pt:{title:()=>"Limite de retenção da auditoria excedido",body:(e)=>`${e.count} registros de auditoria ultrapassam o limite de ${e.limit}.`},webhook:{alertType:()=>"audit_retention_capacity",metricValue:(e)=>e.count,threshold:(e)=>e.limit}}),"system.update_available":ae({kind:"system.update_available",area:"services",audience:"platform",permission:"system:diagnostics",severity:"info",params:K({version:l()}),grouping:{mode:"once"},groupKey:(e)=>e.version,link:()=>"/system/updates",defaults:xt,en:{title:(e)=>`NIVA ${e.version} is available`,body:(e)=>`A new NIVA release is available: ${e.version}.`},pt:{title:(e)=>`NIVA ${e.version} disponível`,body:(e)=>`Uma nova versão da NIVA está disponível: ${e.version}.`}}),"system.update_completed":ae({kind:"system.update_completed",area:"services",audience:"platform",permission:"system:diagnostics",severity:"info",params:K({run_id:l(),from_version:l(),to_version:l()}),grouping:{mode:"once"},groupKey:(e)=>e.run_id,link:()=>"/system/updates",defaults:Mt,en:{title:(e)=>`NIVA updated to ${e.to_version}`,body:(e)=>`NIVA was updated from ${e.from_version} to ${e.to_version}.`},pt:{title:(e)=>`NIVA atualizada para ${e.to_version}`,body:(e)=>`A NIVA foi atualizada de ${e.from_version} para ${e.to_version}.`}}),"system.update_failed":ae({kind:"system.update_failed",area:"services",audience:"platform",permission:"system:diagnostics",severity:"critical",params:K({run_id:l(),status:P(["failed","rolled_back","action_required"]),error_code:l()}),grouping:{mode:"once"},groupKey:(e)=>e.run_id,link:()=>"/system/updates",defaults:Mt,en:{title:()=>"NIVA update failed",body:(e)=>`The update ended with status ${e.status} (${e.error_code}).`},pt:{title:()=>"Falha na atualização da NIVA",body:(e)=>`A atualização terminou com o estado ${e.status} (${e.error_code}).`}})};var Mb="urn:ietf:params:oauth:grant-type:device_code",Lb=["authorization_code","refresh_token",Mb],Md="ABCDEFGHJKLMNPQRSTUVWXYZ",Rk=g({resource:l(),authorization_servers:z(l()).min(1),scopes_supported:z(l()),bearer_methods_supported:z(l()),resource_name:l().optional()}),Ik=g({issuer:l(),authorization_endpoint:l(),token_endpoint:l(),registration_endpoint:l(),revocation_endpoint:l(),device_authorization_endpoint:l(),response_types_supported:z(l()),grant_types_supported:z(l()),code_challenge_methods_supported:z(l()),token_endpoint_auth_methods_supported:z(l()),client_id_metadata_document_supported:I(!0),authorization_response_iss_parameter_supported:I(!0),scopes_supported:z(l())}),Nk=l().refine((e)=>{try{return new URL(e).protocol==="https:"}catch{return!1}},"must be an https URL"),Ok=g({client_id:Nk,redirect_uris:z(l().min(1)).min(1),client_name:l().optional(),client_uri:l().optional(),logo_uri:l().optional(),scope:l().optional(),grant_types:z(l()).optional(),response_types:z(l()).optional(),token_endpoint_auth_method:l().optional(),token_endpoint_auth_methods_supported:z(l()).optional(),application_type:P(["native","web"]).optional()}).refine(kk,{error:'client must support the "none" token endpoint auth method',path:["token_endpoint_auth_method"]});function kk(e){let t=e.token_endpoint_auth_methods_supported;if(t!=null)return t.includes("none");let n=e.token_endpoint_auth_method;return n==null||n==="none"}var Dk=g({redirect_uris:z(l().min(1)).min(1),client_name:l().max(200).optional(),client_uri:l().optional(),logo_uri:l().optional(),scope:l().optional(),grant_types:z(P(Lb)).optional(),response_types:z(I("code")).optional(),token_endpoint_auth_method:I("none").optional(),application_type:P(["native","web"]).optional()}),Pk=g({client_id:l(),client_id_issued_at:f().int(),redirect_uris:z(l()),client_name:l().optional(),token_endpoint_auth_method:I("none"),grant_types:z(l()),response_types:z(l()),application_type:P(["native","web"]).optional(),scope:l().optional()}),$k=g({client_id:l().min(1).max(2048),scope:l().max(2000).default(""),resource:l().min(1).max(2048)}),Mk=g({device_code:l().min(1),user_code:l().regex(new RegExp(`^[${Md}]{4}-[${Md}]{4}$`)),verification_uri:l(),verification_uri_complete:l().optional(),expires_in:f().int().positive(),interval:f().int().positive()});var Ld=["tomato","red","ruby","crimson","pink","plum","purple","violet","iris","indigo","blue","cyan","teal","jade","green","grass","bronze","gold","sky","mint","lime","amber","orange"];var aa={visual_plan:["read","create","update","delete","publish"],channel:["read","create","update","delete"],destination:["read","create","update","delete"],schedule:["read","create","update","delete"],holiday:["read","create","update","delete"],audio_file:["read","create","update","delete"],call_record:["read","export","purge"],call_content:["read"],call:["originate","hangup"],chat:["create"],dashboard:["read","update"],notification:["manage"],test_call:["execute"],tts:["read"],org_settings:["read","update"],user:["read","invite","update_role","suspend","remove","reset_password"],api_key:["read","create","revoke"],oauth_grant:["read","revoke"],acl:["read","create","update","delete"],audit:["read"],webhook:["read","create","update","delete"],ai:["read","execute","configure","manage_key"],assistant:["use"],org_integration:["read","update"],analysis_template:["read","create","update","delete"],contact:["read","update"],dialer_campaign:["read","create","update","delete","control"],dialer_dnc:["read","manage"],archive:["read","purge"],secret:["read","create","update","delete"],connector:["read","create","update","delete"],role:["read","create","update","delete"],desk:["use"],attendant:["read","create","update","delete"],desk_settings:["read","update"],conversation:["read"],saved_reply:["read","manage"],desk_monitor:["read","control"],queue:["read","create","update","delete"],queue_monitor:["read","control"],license:["read","manage"],organization:["list","create","update","delete"],integration:["read","update"],org_plan:["read","update"],platform_admin:["read","manage"],platform_storage:["manage"],system:["logs","diagnostics","operate","update"]},zd={visual_plan:"organization",channel:"organization",destination:"organization",schedule:"organization",holiday:"organization",audio_file:"organization",call_record:"organization",call_content:"organization",call:"organization",chat:"organization",dashboard:"organization",notification:"organization",test_call:"organization",tts:"organization",org_settings:"organization",user:"organization",api_key:"organization",oauth_grant:"organization",acl:"organization",audit:"organization",webhook:"organization",ai:"organization",assistant:"organization",org_integration:"organization",analysis_template:"organization",contact:"organization",dialer_campaign:"organization",dialer_dnc:"organization",archive:"organization",secret:"organization",connector:"organization",role:"organization",desk:"organization",attendant:"organization",desk_settings:"organization",conversation:"organization",saved_reply:"organization",desk_monitor:"organization",queue:"organization",queue_monitor:"organization",license:"platform",organization:"platform",integration:"platform",org_plan:"platform",platform_admin:"platform",platform_storage:"platform",system:"platform"},zb=Object.entries(aa),Fb=zb.flatMap(([e,t])=>t.map((n)=>`${e}:${n}`));var Ub={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","chat:create","call:hangup","dashboard:read","dashboard:update","call_record:read","call_record:export","call_content:read","tts:read","ai:read","ai:execute","assistant:use","ai:configure","analysis_template:read","analysis_template:create","analysis_template:update","analysis_template:delete","contact:read","contact:update","dialer_campaign:read","dialer_campaign:create","dialer_campaign:update","dialer_campaign:delete","dialer_campaign:control","dialer_dnc:read","dialer_dnc:manage","archive:read","user:read","role:read","webhook:read","api_key:read","oauth_grant:read","desk:use","attendant:read","attendant:create","attendant:update","attendant:delete","desk_settings:read","desk_settings:update","conversation:read","saved_reply:read","saved_reply:manage","queue:read","queue:create","queue:update","queue:delete","desk_monitor:read","desk_monitor:control","queue_monitor:read","queue_monitor:control"],supervisor:["visual_plan:read","channel:read","destination:read","schedule:read","holiday:read","audio_file:read","dashboard:read","dashboard:update","call_record:read","call_record:export","call_content:read","test_call:execute","call:hangup","tts:read","ai:read","ai:execute","assistant:use","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","desk:use","attendant:read","desk_settings:read","conversation:read","saved_reply:read","saved_reply:manage","queue:read","desk_monitor:read","desk_monitor:control","queue_monitor:read","queue_monitor:control"],operator:["visual_plan:read","channel:read","destination:read","schedule:read","holiday:read","audio_file:read","dashboard:read","call_record:read","test_call:execute","call:hangup","tts:read","contact:read","contact:update","dialer_campaign:read","dialer_dnc:read","user:read","archive:read"],viewer:["visual_plan:read","channel:read","destination:read","schedule:read","holiday:read","audio_file:read","dashboard:read","call_record:read","tts:read","user:read","role:read","webhook:read","api_key:read","oauth_grant:read","acl:read","audit:read","ai:read","analysis_template:read","contact:read","dialer_campaign:read","dialer_dnc:read","archive:read","attendant:read","conversation:read","queue:read"],attendant:["desk:use","contact:read","contact:update","audio_file:read","saved_reply:read"]},Lk=Object.keys(Ub);var qH=zb.filter(([e])=>zd[e]==="organization").flatMap(([e,t])=>t.map((n)=>`${e}:${n}`));var BH=new Map(Fb.map((e)=>[e,e])),HH=new Map(Object.entries(zd));var ZH=new Set(`@£$¥èéùìòÇ
|
|
91
|
-
Øø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !"#¤%&'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà`);var Fd={plans:{entities:["visual_plan","audio_file","tts","analysis_template","test_call"]},telephony:{entities:["channel","destination","schedule","holiday","acl"]},calls:{entities:["call","call_record","call_content","contact","dashboard","notification","archive","ai","assistant"]},chat:{entities:["chat"],module:"omnichannel"},dialer:{entities:["dialer_campaign","dialer_dnc"],module:"dialer"},desk:{entities:["desk","attendant","desk_settings","conversation","saved_reply","desk_monitor"],module:"desk"},queues:{entities:["queue","queue_monitor"],module:"queues"},admin:{entities:["user","role","api_key","oauth_grant","org_settings","webhook","org_integration","audit","secret","connector","license"]},platform:{entities:["organization","integration","org_plan","platform_admin","platform_storage","system"],platformOnly:!0}},Fk=Object.keys(Fd),Uk=new Map;for(let e of Fk)for(let t of Fd[e].entities)Uk.set(t,e);var jb=new Set(["*:read","*:write","offline_access"]);for(let e of Object.keys(aa))jb.add(`${e}:read`),jb.add(`${e}:write`);var Ud=g({version:I(1),startNodeId:l().min(1),nodes:ie(l(),g({type:l().min(1),label:l(),varName:l(),config:ie(l(),pt())})),adjacency:ie(l(),ie(l(),l()))});function jd(e,t,n,r){return Vk(e,t,n,r)}function jk(e,t){if(e&&t)return"converged";if(e)return"voice-only";if(t)return"chat-only";return"unreachable"}function Vk(e,t,n,r){let o=t.get(e)?.get("voice"),i=t.get(e)?.get("chat"),a=o!=null?Vb(o,t,r,"voice"):new Set,s=i!=null?Vb(i,t,r,"chat"):new Set;if(o!=null)a.add(o);if(i!=null)s.add(i);let c={};for(let d of n)c[d]=d===e?"converged":jk(a.has(d),s.has(d));return c}function Vb(e,t,n,r){let o=new Set,i=[e];o.add(e);let a=0;while(a<i.length){let s=i[a++],c=t.get(s);if(c==null)continue;if(r!=null&&n?.has(s)){let d=c.get(r);if(d!=null&&!o.has(d))o.add(d),i.push(d);continue}for(let d of c.values())if(!o.has(d))o.add(d),i.push(d)}return o}function M(){return(e,t)=>({key:t,prefix:`${e}:`})}var Kb={deskPresence:M()("desk-presence",(e)=>`desk-presence:${e}`),deskUnread:M()("desk-unread",(e)=>`desk-unread:${e}`),deskRegistered:M()("desk-registered",(e)=>`desk-registered:${e}`),deskSipCredential:M()("desk-sip-credential",(e)=>`desk-sip-credential:${e}`),deskLeg:M()("desk-leg",(e)=>`desk-leg:${e}`),deskLost:M()("desk-lost",(e)=>`desk-lost:${e}`),deskTransfer:M()("desk-transfer",(e)=>`desk-transfer:${e}`),queueRouterLock:M()("queue-router-lock",()=>"queue-router-lock"),queueOfferTaken:M()("queue-offer-taken",(e)=>`queue-offer-taken:${e}`),queueRecoverLock:M()("queue-recover-lock",(e)=>`queue-recover-lock:${e}`),queueRecoverAttempts:M()("queue-recover-attempts",(e)=>`queue-recover-attempts:${e}`),deskSweeperLock:M()("desk-sweeper-lock",()=>"desk-sweeper-lock"),call:M()("call",(e)=>`call:${e}`),testPlan:M()("test-plan",(e)=>`test-plan:${e}`),testChatPlan:M()("test-chat-plan",(e)=>`test-chat-plan:${e}`),testEditorState:M()("test-editor-state",(e)=>`test-editor-state:${e}`),testExecutionTrace:M()("test-execution-trace",(e)=>`test-execution-trace:${e}`),refreshToken:M()("rt",(e)=>`rt:${e}`),hostActionConfirmation:M()("host-action-confirmation",(e)=>`host-action-confirmation:${e}`),exportDownloadTicket:M()("export-dl",(e)=>`export-dl:${e}`),revokedToken:M()("revoked",(e)=>`revoked:${e}`),revokedSession:M()("revoked-session",(e)=>`revoked-session:${e}`),legacyAuthCutoff:M()("legacy-auth-cutoff",(e)=>`legacy-auth-cutoff:${e}`),oauthCode:M()("oauth:code",(e)=>`oauth:code:${e}`),oauthCimd:M()("oauth:cimd",(e)=>`oauth:cimd:${e}`),oauthDevice:M()("oauth:device",(e)=>`oauth:device:${e}`),oauthUsercode:M()("oauth:usercode",(e)=>`oauth:usercode:${e}`),oauthUsercodeAttempts:M()("oauth:usercode-attempts",(e)=>`oauth:usercode-attempts:${e}`),channels:M()("niva:channels",(e)=>`niva:channels:${e}`),concurrentChannels:M()("niva:concurrent_channels",(e,t)=>`niva:concurrent_channels:${e}:${t}`),peakConcurrentChannels:M()("niva:peak_concurrent",(e,t)=>`niva:peak_concurrent:${e}:${t}`),dialerCampaignActive:M()("niva:dialer_campaign_active",(e)=>`niva:dialer_campaign_active:${e}`),capacityReservation:M()("niva:capacity_reservation",(e)=>`niva:capacity_reservation:${e}`),capacityReservationData:M()("niva:capacity_reservation_data",()=>"niva:capacity_reservation_data"),capacityReservationExpiry:M()("niva:capacity_reservation_expiry",()=>"niva:capacity_reservation_expiry"),capacityReservationHandoff:M()("niva:capacity_reservation_handoff",(e)=>`niva:capacity_reservation_handoff:${e}`),counterByPlan:M()("niva:counter:plan",(e,t,n)=>`niva:counter:plan:${e}:${t}:${n}`),counterByOrg:M()("niva:counter:org",(e,t)=>`niva:counter:org:${e}:${t}`),trafficSplitRotation:M()("niva:traffic_split",(e,t,n,r)=>`niva:traffic_split:${e}:${t}:${n}:${r}`),rateLimit:M()("rl",(e,t)=>`rl:${e}:${t}`),liveTranscriptionSegments:M()("live-ts",(e)=>`live-ts:${e}`),liveSignalEvents:M()("live-sig",(e)=>`live-sig:${e}`),chatSignalState:M()("chat-sig",(e)=>`chat-sig:${e}`),chatSignalLock:M()("chat-sig-lock",(e)=>`chat-sig-lock:${e}`),deskCopilotReplyDebounce:M()("desk-copilot-reply",(e)=>`desk-copilot-reply:${e}`),deskCopilotReplyWaiting:M()("desk-copilot-reply-waiting",(e)=>`desk-copilot-reply-waiting:${e}`),deskCopilotCueOwner:M()("desk-copilot-cue-owner",(e)=>`desk-copilot-cue-owner:${e}`),deskCopilotCueWindow:M()("desk-copilot-cue-window",(e)=>`desk-copilot-cue-window:${e}`),chatSignalPending:M()("chat-sig-pending",(e)=>`chat-sig-pending:${e}`),liveTranscriptionSummary:M()("live-ts-summary",(e)=>`live-ts-summary:${e}`),transcriptionWatchers:M()("ts-watchers",(e)=>`ts-watchers:${e}`),transcriptionDeferredJobs:M()("transcription:deferred:jobs",()=>"transcription:deferred:jobs"),transcriptionDeferredReady:M()("transcription:deferred:ready",()=>"transcription:deferred:ready"),transcriptionDeferredLeases:M()("transcription:deferred:leases",()=>"transcription:deferred:leases"),chatSession:M()("chat-session",(e)=>`chat-session:${e}`),chatSessionEnded:M()("chat-session-ended",(e)=>`chat-session-ended:${e}`),chatLookup:M()("chat-lookup",(e,t,n)=>`chat-lookup:${e}:${t}:${n}`),chatRelay:M()("chat-relay-token",(e)=>`chat-relay-token:${e}`),chatRelayInbox:M()("chat-relay-inbox",(e)=>`chat-relay-inbox:${e}`),chatRelayDeadlines:M()("chat-relay-deadlines",()=>"chat-relay-deadlines"),chatRelayArmed:M()("chat-relay-armed",(e)=>`chat-relay-armed:${e}`),chatWsLink:M()("chat-ws-link",(e)=>`chat-ws-link:${e}`),activeVoiceCalls:M()("niva:active:voice",(e)=>`niva:active:voice:${e}`),activeChatSessions:M()("niva:active:chat",(e)=>`niva:active:chat:${e}`),chatLock:M()("chat-lock",(e,t)=>`chat-lock:${e}:${t}`),chatInboundMessage:M()("chat-inbound-message",(e,t,n,r)=>`chat-inbound-message:${e}:${t}:${n}:${r}`),wsSession:M()("ws:session",(e)=>`ws:session:${e}`),wsMessageLog:M()("ws:log",(e)=>`ws:log:${e}`),wsSeq:M()("ws:seq",(e)=>`ws:seq:${e}`),webchatChannelEpoch:M()("webchat:channel-epoch",(e)=>`webchat:channel-epoch:${e}`),webchatConcurrentSessions:M()("webchat:sessions",(e)=>`webchat:sessions:${e}`),webchatSessionCreations:M()("webchat:created",(e)=>`webchat:created:${e}`),webchatChallengeUsed:M()("webchat:challenge-used",(e)=>`webchat:challenge-used:${e}`),webchatMessageRate:M()("webchat:msg-rate",(e,t)=>`webchat:msg-rate:${e}:${t}`),webchatUpgradeRate:M()("webchat:upgrade-rate",(e)=>`webchat:upgrade-rate:${e}`),healthStatus:M()("health-status",(e)=>`health-status:${e}`),alertCooldown:M()("alert-cd",(e,t)=>`alert-cd:${e}:${t}`),auditRetentionOverCap:M()("audit-retention",()=>"audit-retention:over-cap"),storageCleanup:M()("storage:cleanup",(e)=>`storage:cleanup:${e}`),recordingDownloadAudit:M()("rec-dl-audit",(e,t)=>`rec-dl-audit:${e}:${t}`),connectorPhoneNumbers:M()("connector:phone-numbers",(e,t)=>`connector:phone-numbers:v${t}:${e}`),connectorPhoneNumbersVersion:M()("connector:phone-numbers:version",(e)=>`connector:${e}:phone-numbers:version`),connectorTemplates:M()("connector:templates",(e,t)=>`connector:templates:v${t}:${e}`),connectorTemplatesVersion:M()("connector:templates:version",(e)=>`connector:${e}:templates:version`),whatsappTemplateMessage:M()("wa-template-msg",(e)=>`wa-template-msg:${e}`),whatsappMessageRate:M()("wa-message-rate",(e,t)=>`wa-message-rate:${e}:${t}`),screenPop:M()("screenpop",(e,t)=>`screenpop:${e}:${t}`),screenPopLegacy:M()("call_info",(e)=>`call_info_${e}`),engineHeartbeat:M()("engine:heartbeat",()=>"engine:heartbeat")};function qk(e){return St[e]?.connector}function Vd(e,t){return typeof e==="string"&&e!==""&&!t.has(e)}function go(e,t){return{nodeId:e.id,severity:"error",messageKey:t,params:{label:e.label}}}function Bk(e,t){if(e.type!=="timeRouting"||t==null)return null;if(!Vd(e.config.scheduleId,t))return null;return go(e,"editor:validation.danglingSchedule")}function Hk(e,t){if(e.type!=="subPlan"||t==null)return null;if(!Vd(e.config.planId,t))return null;return go(e,"editor:validation.danglingPlan")}function Wk(e,t){if(t==null)return null;let n=e.config.audio;if(n==null||typeof n!=="object"||!("file"in n))return null;let r=n.file;if(r==null||typeof r!=="object"||!("id"in r))return null;if(!Vd(r.id,t))return null;return go(e,"editor:validation.danglingAudioFile")}function Gk(e,t){if(t==null)return null;let n=qk(e.type);if(n==null)return null;let r=e.config[n.configKey];if(typeof r!=="string"||r==="")return null;let o=t.get(r);if(o===void 0)return go(e,"editor:validation.danglingConnector");if(o!==n.kind)return go(e,"editor:validation.connectorKindMismatch");return null}function Zk(e,t){if(t==null)return[];return Hi(e).allowed.filter((n)=>!t.has(n)).map((n)=>({nodeId:e.id,severity:"error",messageKey:"editor:validation.danglingSecret",params:{label:e.label,secret:n}}))}function Kd(e,t){let n=[];for(let r of e){let o=Bk(r,t.schedules);if(o!=null)n.push(o);let i=Hk(r,t.publishedPlans);if(i!=null)n.push(i);let a=Wk(r,t.audioFiles);if(a!=null)n.push(a);let s=Gk(r,t.connectors);if(s!=null)n.push(s);n.push(...Zk(r,t.secrets))}return n}function qd(e,t){let n=[];for(let r of e){if(r.type!=="aiAgent"||t.aiAgents==null)continue;let o=r.config.agent_id;if(typeof o==="string"&&o!==""&&!t.aiAgents.has(o))n.push({nodeId:r.id,severity:"warning",messageKey:"editor:validation.danglingAiAgent",params:{label:r.label}})}return n}var mt={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"]},Bd=[...mt.basic,...mt.details,...mt.media,...mt.errors,...mt.origin,...mt.metadata,...mt.variables],qb=/^analysis:[a-z0-9][a-z0-9-]*\.[A-Za-z0-9_-]+(?:\[\])?(?:\.[A-Za-z0-9_-]+(?:\[\])?)*$/,Yk=l().regex(qb,{error:"Invalid structured-analysis export column"}).refine((e)=>Bb(e),{error:"Invalid structured-analysis export column"});function Bb(e){return qb.test(e)}var Hb=/^signal:[a-z][a-z0-9_]*(?:\.triggered_at)?$/;function Wb(e){return Hb.test(e)}var Jk=l().regex(Hb,{error:"Invalid signal export column"}).refine((e)=>Wb(e),{error:"Invalid signal export column"}),Gb=["sip_call_id","remote_addr","user_agent"],Xk=new Set(Gb),Qk=Bd.filter((e)=>!Xk.has(e)),e0=[...mt.basic];var t0={basic:[...mt.basic],full:[...Bd],ai_audit:[...mt.basic,"transcription_status","transcription","analysis","sentiment_label","ai_agent_price","ai_agent_currency",...mt.errors,...mt.metadata,"variables"]};var Sr=Zt.datetime(),ho={conversation_id:l().min(1).meta({"x-niva-typeid":W.conversations}),call_record_id:l().min(1).nullable().meta({"x-niva-typeid":W.call_records}),attendant_id:l().min(1).nullable().meta({"x-niva-typeid":W.attendants}),user_id:l().min(1).nullable().meta({"x-niva-typeid":W.users}),channel:P(cb),status:P(lb),outcome:P(db).nullable(),joined_at:Sr,offered_at:Sr.nullable(),answered_at:Sr.nullable(),ended_at:Sr.nullable(),wrapped_at:Sr.nullable(),wait_ms:f().int().nonnegative().nullable(),talk_ms:f().int().nonnegative().nullable(),wrap_ms:f().int().nonnegative().nullable()},Hd=K({...ho,queue_id:l().min(1).meta({"x-niva-typeid":W.queues})}),Wd=K({...ho,queue_id:l().min(1).meta({"x-niva-typeid":W.queues}),wait_s:f().int().nonnegative(),short:F()}),Gd=K(ho),Zd=K(ho),Yd=K({...ho,disposition:K({id:l().min(1).meta({"x-niva-typeid":W.dispositions}),code:l(),name:l(),color:P(Ld).nullable().describe("The colour the organization gave the disposition; null is neutral.")}).nullable(),note:l().nullable()}),Jd=K({attendant_id:l().min(1).meta({"x-niva-typeid":W.attendants}),user_id:l().min(1).meta({"x-niva-typeid":W.users}),from:P(Yc),to:P(Yc),reason:K({id:l().min(1).meta({"x-niva-typeid":W.pause_reasons}),name:l()}).nullable(),source:P(sb),changed_at:Sr});var sa=["call.started","call.answered","call.amd_completed","call.hangup","call.rejected","call.node_entered","call.node_error","call.node_warning","call.transcribed","call.transcription_failed","call.analysis_completed","call.transferred","call.recording_available","call.intent_matched","call.signal_triggered","conversation.queued","conversation.abandoned","conversation.offered","conversation.answered","conversation.wrapped","attendant.status_changed","plan.published","message.sent","dialer.attempt.finished","alert.fired","alert.resolved","service.down","service.up","webhook.test"],n0=sa.filter((e)=>e!=="webhook.test");var Zb=[1,5,30,120,300,600],r0=Zb.length,Yb=P(["inbound","outbound"]),Ae=Zt.datetime(),ft=ie(l(),l()),o0=K({amd:I(!0),machine_type:I(!0).optional(),mode:P(ob).optional(),max_wait_seconds:f().int().min(3).max(10).optional()}).superRefine((e,t)=>{if(e.max_wait_seconds!==void 0&&e.mode!=="pre")t.addIssue({code:"custom",path:["max_wait_seconds"],message:"max_wait_seconds is only valid with mode=pre"})}),Jb=K({call_id:l().min(1).meta({"x-niva-typeid":W.call_records}),caller_id:l(),callee_id:l(),direction:Yb,visual_plan_id:l().min(1).meta({"x-niva-typeid":W.visual_plans}),visual_plan_name:l(),started_at:Ae,answer_recognition:o0.optional(),metadata:ft}),Xb=K({call_id:l().min(1).meta({"x-niva-typeid":W.call_records}),caller_id:l(),callee_id:l(),answered_at:Ae,metadata:ft}),eu=P(["machine","human","silence","unknown"]),Qb=P(ab),ev=K({call_id:l().min(1).meta({"x-niva-typeid":W.call_records}),channel_uuid:l().min(1),result:eu,machine_type:Qb.optional(),completed_at:Ae,metadata:ft}).superRefine((e,t)=>{if(e.machine_type!==void 0&&e.result!=="machine")t.addIssue({code:"custom",path:["machine_type"],message:"machine_type is only valid when result is machine"})}),tv=K({call_id:l().min(1).meta({"x-niva-typeid":W.call_records}),caller_id:l(),callee_id:l(),direction:Yb,visual_plan_id:l().min(1).meta({"x-niva-typeid":W.visual_plans}),visual_plan_name:l(),started_at:Ae,answered_at:Ae.nullable(),ended_at:Ae,duration_ms:f().nonnegative(),hangup_cause:l(),hangup_disposition:l(),was_recorded:F(),variables:ie(l(),l()),sip_code:l().nullable(),billsec:f().nonnegative().nullable(),answer_recognition_results:K({amd:eu}).optional(),metadata:ft}),nv=["not_found","channel_inactive","channel_deleted","plan_deleted","no_published_version","org_deleted","acl_denied","capacity_global","capacity_org","capacity_campaign","capacity_reservation"],rv=P(nv),ov=K({caller:l(),destination:l(),reason:rv,hangup_cause:l()}),iv=K({call_id:l().min(1).meta({"x-niva-typeid":W.call_records}),caller_id:l(),callee_id:l(),node_id:l().min(1),node_type:l(),node_label:l(),handle_used:l(),digit:l().nullable(),entered_at:Ae,exited_at:Ae,duration_ms:f().nonnegative(),visual_plan_id:l().min(1).meta({"x-niva-typeid":W.visual_plans}),metadata:ft}),tu=K({call_id:l().min(1).meta({"x-niva-typeid":W.call_records}),caller_id:l(),callee_id:l(),node_id:l().min(1),node_type:l(),node_label:l(),error_code:l(),error_message:l(),visual_plan_id:l().min(1).meta({"x-niva-typeid":W.visual_plans}),visual_plan_name:l(),occurred_at:Ae,metadata:ft}),av=tu,nu=K({call_record_id:l().min(1).meta({"x-niva-typeid":W.call_records}),transcription_id:l().min(1).meta({"x-niva-typeid":W.call_transcriptions}),full_text:l(),is_anonymized:F(),metadata:ft}),sv=nu.pick({call_record_id:!0,transcription_id:!0,metadata:!0}).extend({error_code:P(["ASR_REJECTED","RETRIES_EXHAUSTED","RANGE_TRANSCRIPTION_FAILED","PROCESSING_TIMEOUT"]),error_message:l()}),cv=["native","local","sippulse_ai"],i0=P(cv),lv=K({source:I("native"),id:Pt(),template_id:Pt(),name:l(),category:Pt()}),dv=K({source:I("local"),id:l().min(1).meta({"x-niva-typeid":W.call_analyses}),template_id:l().min(1).meta({"x-niva-typeid":W.analysis_templates}),name:l(),category:l().nullable()}),uv=K({source:I("sippulse_ai"),id:l().min(1).meta({"x-niva-typeid":W.call_analyses}),template_id:Pt(),external_id:l().min(1),slug:l().min(1),name:l(),category:Pt(),model:l().nullable()}),xW=Re("source",[lv,dv,uv]),ru={status:P(["completed","failed"]),result:ie(l(),pt()).nullable(),error_message:l().nullable(),error_code:l().nullable()},a0=K({...lv.shape,...ru}),s0=K({...dv.shape,...ru}),c0=K({...uv.shape,...ru}),l0=Re("source",[a0,s0,c0]).superRefine((e,t)=>{if(e.status==="failed"&&e.result!==null)t.addIssue({code:"custom",path:["result"],message:"Failed analyses must have a null result"})}),pv=P(["caller","agent"]),mv=K({id:l().min(1).meta({"x-niva-typeid":W.signals}),slug:l().min(1),name:l(),kind:P(_r),version:f().int().positive()}),d0=K({signal:mv,value:Be([F(),l(),f(),Pt()]),value_label:l().nullable(),confidence:f().nullable(),triggered:K({at_seconds:f(),value:Be([F(),l(),f(),Pt()]),value_label:l().nullable(),confidence:f().nullable(),late:F(),node_id:l().nullable()}).nullable()}),fv=K({call_id:l().min(1).meta({"x-niva-typeid":W.call_records}),call_record_id:l().min(1).meta({"x-niva-typeid":W.call_records}),transcription_id:l().min(1).meta({"x-niva-typeid":W.call_transcriptions}),visual_plan_id:l().nullable().meta({"x-niva-typeid":W.visual_plans}),analyses:l0.array(),signals:d0.array(),analyzed_at:Ae,metadata:ft}),gv=["answered","busy","noAnswer","failed"],hv=P(gv),yv=K({call_id:l().min(1).meta({"x-niva-typeid":W.call_records}),caller_id:l(),callee_id:l(),to_destination:l(),method:P(["bridge","sip_message","blind"]),disposition:hv,status:l(),duration_ms:f().nonnegative().nullable(),note:l().nullable(),transferred_at:Ae,metadata:ft}),_v=K({call_id:l().min(1).meta({"x-niva-typeid":W.call_records}),call_record_id:l().min(1).meta({"x-niva-typeid":W.call_records}),recording_url:l(),storage_path:l(),duration_seconds:f().nonnegative().nullable(),format:l(),size_bytes:f().nonnegative().nullable(),available_at:Ae,metadata:ft}),u0=K({intent:l(),confidence:f()}),bv=K({call_id:l().min(1).meta({"x-niva-typeid":W.call_records}),caller_id:l(),callee_id:l(),node_id:l().min(1),visual_plan_id:l().min(1).meta({"x-niva-typeid":W.visual_plans}),transcript:l(),intent:l(),confidence:f(),alternatives:z(u0),language:l().nullable(),matched_at:Ae,metadata:ft}),p0=K({speaker:pv,text:l(),start_seconds:f()}),m0=K({call_id:l().min(1).meta({"x-niva-typeid":W.call_records}),visual_plan_id:l().nullable().meta({"x-niva-typeid":W.visual_plans}),signal:mv,value:Be([F(),l(),f(),Pt()]),value_label:l(),confidence:f(),severity:P(br),speaker:pv,at_seconds:f(),late:F(),source:P(["live","end_of_call"]),node:K({id:l(),label:l(),type:l()}).nullable(),window:z(p0),is_anonymized:F(),trace_url:l().nullable(),metadata:ft}),vv=K({plan_id:l().min(1).meta({"x-niva-typeid":W.visual_plans}),plan_name:l(),version_id:l().min(1).meta({"x-niva-typeid":W.visual_plan_versions}),version_number:f().int().nonnegative(),published_by_user_id:l().min(1).meta({"x-niva-typeid":W.users}),notes:l().nullable(),published_at:Ae}),Sv=["text","media","audio","image","video","document","location","interactive"],xv=K({session_id:l().min(1).meta({"x-niva-typeid":W.call_records}),channel_type:l(),to:l(),message_type:P(Sv),text:l().nullable(),media_url:l().nullable(),node_id:l().nullable(),sent_at:Ae}),Ev=["answered","machine","silence","busy","no_answer","failed","originate_error","cancelled"],wv=P(Ev),Cv=K({campaign_id:l().min(1).meta({"x-niva-typeid":W.dialer_campaigns}),campaign_name:l(),contact_id:l().min(1).meta({"x-niva-typeid":W.dialer_contacts}),phone_number:l(),attempt_number:f().int().nonnegative(),status:wv,hangup_cause:l().nullable(),sip_code:l().nullable(),call_uuid:l().nullable(),started_at:Ae.nullable(),answered_at:Ae.nullable(),ended_at:Ae.nullable(),duration_s:f().nonnegative().nullable(),screening_outcome:P(ib).nullable(),custom_fields:ie(l(),l())}),Av=K({alert_type:l(),severity:P(["critical","warning","info"]),title:l(),body:l(),metric_value:f().optional(),threshold:f().optional()}),Tv=K({alert_type:l(),title:l(),body:l()}),Rv=K({component:l(),checked_at:Ae}),Iv=K({component:l(),downtime_seconds:f().nonnegative().nullable(),recovered_at:Ae}),Nv=K({webhook_endpoint_id:l().min(1),message:l().min(1)}),ca={"call.started":Jb,"call.answered":Xb,"call.amd_completed":ev,"call.hangup":tv,"call.rejected":ov,"call.node_entered":iv,"call.node_error":tu,"call.node_warning":av,"call.transcribed":nu,"call.transcription_failed":sv,"call.analysis_completed":fv,"call.transferred":yv,"call.recording_available":_v,"call.intent_matched":bv,"call.signal_triggered":m0,"conversation.queued":Hd,"conversation.abandoned":Wd,"conversation.offered":Gd,"conversation.answered":Zd,"conversation.wrapped":Yd,"attendant.status_changed":Jd,"plan.published":vv,"message.sent":xv,"dialer.attempt.finished":Cv,"alert.fired":Av,"alert.resolved":Tv,"service.down":Rv,"service.up":Iv,"webhook.test":Nv};function le(e){return K({event:I(e),event_id:l().min(1),org_id:l().min(1),timestamp:Ae,data:ca[e]})}var f0=Re("event",[le("call.started"),le("call.answered"),le("call.amd_completed"),le("call.hangup"),le("call.rejected"),le("call.node_entered"),le("call.node_error"),le("call.node_warning"),le("call.transcribed"),le("call.transcription_failed"),le("call.analysis_completed"),le("call.transferred"),le("call.recording_available"),le("call.intent_matched"),le("call.signal_triggered"),le("conversation.queued"),le("conversation.abandoned"),le("conversation.offered"),le("conversation.answered"),le("conversation.wrapped"),le("attendant.status_changed"),le("plan.published"),le("message.sent"),le("dialer.attempt.finished"),le("alert.fired"),le("alert.resolved"),le("service.down"),le("service.up"),le("webhook.test")]);function de(e){return K({event:I(e),event_id:l().min(1),timestamp:Ae,data:ca[e]})}var g0=Re("event",[de("call.started"),de("call.answered"),de("call.amd_completed"),de("call.hangup"),de("call.rejected"),de("call.node_entered"),de("call.node_error"),de("call.node_warning"),de("call.transcribed"),de("call.transcription_failed"),de("call.analysis_completed"),de("call.transferred"),de("call.recording_available"),de("call.intent_matched"),de("call.signal_triggered"),de("conversation.queued"),de("conversation.abandoned"),de("conversation.offered"),de("conversation.answered"),de("conversation.wrapped"),de("attendant.status_changed"),de("plan.published"),de("message.sent"),de("dialer.attempt.finished"),de("alert.fired"),de("alert.resolved"),de("service.down"),de("service.up"),de("webhook.test")]),Y="01kknxab29enebk2vhm0tz0yyd",Qd={conversation_id:`conv_${Y}`,call_record_id:`call_${Y}`,attendant_id:null,user_id:null,channel:"voice",status:"queued",outcome:null,joined_at:"2026-01-15T12:00:20.000Z",offered_at:null,answered_at:null,ended_at:null,wrapped_at:null,wait_ms:null,talk_ms:null,wrap_ms:null},Xd={...Qd,attendant_id:`att_${Y}`,user_id:`usr_${Y}`,status:"offered",offered_at:"2026-01-15T12:00:20.000Z"},Ov={"call.started":{call_id:`call_${Y}`,caller_id:"+15551230001",callee_id:"+15551230002",direction:"inbound",visual_plan_id:`vp_${Y}`,visual_plan_name:"Support IVR",started_at:"2026-01-15T12:00:00.000Z",metadata:{}},"call.answered":{call_id:`call_${Y}`,caller_id:"+15551230001",callee_id:"+15551230002",answered_at:"2026-01-15T12:00:03.000Z",metadata:{}},"call.amd_completed":{call_id:`call_${Y}`,channel_uuid:"freeswitch-channel-example",result:"machine",machine_type:"voicemail",completed_at:"2026-01-15T12:00:05.000Z",metadata:{}},"call.hangup":{call_id:`call_${Y}`,caller_id:"+15551230001",callee_id:"+15551230002",direction:"inbound",visual_plan_id:`vp_${Y}`,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_${Y}`,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_${Y}`,metadata:{}},"call.node_error":{call_id:`call_${Y}`,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_${Y}`,visual_plan_name:"Support IVR",occurred_at:"2026-01-15T12:00:10.000Z",metadata:{}},"call.node_warning":{call_id:`call_${Y}`,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_${Y}`,visual_plan_name:"Support IVR",occurred_at:"2026-01-15T12:00:10.000Z",metadata:{}},"call.transcribed":{call_record_id:`call_${Y}`,transcription_id:`ctr_${Y}`,full_text:"Hello, I need help with my account.",is_anonymized:!0,metadata:{}},"call.transcription_failed":{call_record_id:`call_${Y}`,transcription_id:`ctr_${Y}`,error_code:"ASR_REJECTED",error_message:"The speech recognition provider rejected the transcription.",metadata:{}},"call.analysis_completed":{call_id:`call_${Y}`,call_record_id:`call_${Y}`,transcription_id:`ctr_${Y}`,visual_plan_id:`vp_${Y}`,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_${Y}`,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_${Y}`,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_${Y}`,caller_id:"+15551230001",callee_id:"+15551230002",to_destination:"support@example.invalid",method:"bridge",disposition:"answered",status:"SUCCESS",duration_ms:null,note:null,transferred_at:"2026-01-15T12:00:20.000Z",metadata:{}},"call.recording_available":{call_id:`call_${Y}`,call_record_id:`call_${Y}`,recording_url:`https://example.invalid/recordings/call_${Y}.wav`,storage_path:`recordings/example/call_${Y}.wav`,duration_seconds:57,format:"wav",size_bytes:912000,available_at:"2026-01-15T12:01:01.000Z",metadata:{}},"call.intent_matched":{call_id:`call_${Y}`,caller_id:"+15551230001",callee_id:"+15551230002",node_id:"node_intent",visual_plan_id:`vp_${Y}`,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_${Y}`,visual_plan_id:`vp_${Y}`,signal:{id:`sig_${Y}`,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_${Y}`,metadata:{}},"conversation.queued":{...Qd,queue_id:`que_${Y}`},"conversation.abandoned":{...Qd,status:"closed",outcome:"abandoned",ended_at:"2026-01-15T12:00:44.000Z",queue_id:`que_${Y}`,wait_s:24,short:!1},"conversation.offered":Xd,"conversation.answered":{...Xd,status:"active",answered_at:"2026-01-15T12:00:26.000Z",wait_ms:6000},"conversation.wrapped":{...Xd,status:"closed",outcome:"completed",answered_at:"2026-01-15T12:00:26.000Z",ended_at:"2026-01-15T12:04:26.000Z",wrapped_at:"2026-01-15T12:05:06.000Z",wait_ms:6000,talk_ms:240000,wrap_ms:40000,disposition:{id:`disp_${Y}`,code:"resolved",name:"Resolved",color:"green"},note:"Customer confirmed the new address."},"attendant.status_changed":{attendant_id:`att_${Y}`,user_id:`usr_${Y}`,from:"available",to:"paused",reason:{id:`pause_${Y}`,name:"Lunch"},source:"attendant",changed_at:"2026-01-15T12:30:00.000Z"},"plan.published":{plan_id:`vp_${Y}`,plan_name:"Support IVR",version_id:`vpv_${Y}`,version_number:3,published_by_user_id:`usr_${Y}`,notes:"Updated support routing",published_at:"2026-01-15T11:00:00.000Z"},"message.sent":{session_id:`call_${Y}`,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_${Y}`,campaign_name:"January outreach",contact_id:`dct_${Y}`,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,screening_outcome:null,custom_fields:{segment:"example"}},"alert.fired":{alert_type:"service_offline",severity:"critical",title:"Example service offline",body:"The example service is unavailable.",metric_value:1,threshold:1},"alert.resolved":{alert_type:"service_offline",title:"Example service recovered",body:"The example service is available again."},"service.down":{component:"example-service",checked_at:"2026-01-15T12:00:00.000Z"},"service.up":{component:"example-service",downtime_seconds:null,recovered_at:"2026-01-15T12:05:00.000Z"},"webhook.test":{webhook_endpoint_id:`whep_${Y}`,message:"This is a test webhook delivery."}};function yo(e){let t=vt[e],n=St[e],r=n.defaultConfig,o=Mn(n,r),i=typeof n.producedVariables==="function"?n.producedVariables(r):n.producedVariables,a=Xc(e,"en");return{type:e,name:a?.name??e,description:a?.description??"",nameKey:n.nameKey,descriptionKey:n.descriptionKey,module:n.module,category:n.category,channel:n.channel,nature:n.nature,configJsonSchema:ky(t.configSchema,{unrepresentable:"any"}),outputs:o,producedVariables:i,defaultConfig:r}}var y0=Object.keys(vt);function ou(){return y0.map((e)=>yo(e))}var _0=["string","number","boolean","object","array"],kv=K({name:l(),type:P(_0),required:F(),nullable:F()}),Dv=K({event:P(sa),required_module:P(Yi).nullable(),fields:z(kv),example:ie(l(),pt())}),b0=z(Dv);var Pv="edge";var v0=g({text:l().min(1).max(5000),voice:l().min(1),model:l().default(Pv)});var S0=g({signal_id:l(),t:f().min(0),v:Be([F(),l(),Pt(),f()]),c:f().min(0).max(1),node_id:l().nullable()});function iu(e){let t=e.normalize("NFD").replaceAll(/[\u0300-\u036F]/g,"").toLowerCase().replaceAll(/[^a-z0-9]+/g,"_").replaceAll(/_+/g,"_").replaceAll(/^_|_$/g,"");if(!/^[a-z]/.test(t))return`signal_${t}`.slice(0,64)||"signal";return t.slice(0,64)}var la=[{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 au(e,t){let n=e.texts[t];return vr.parse({slug:iu(n.name),name:n.name,question:n.question,kind:e.kind,...e.kind==="choice"?{options:(n.options??[]).map((r,o)=>({key:e.option_keys?.[o]??`option_${o}`,label:r.label,...r.description!==void 0?{description:r.description}:{}}))}:{},...e.kind==="scale"?{levels:n.levels??[]}:{},speaker:e.speaker,scope:e.scope,live:e.live,alert:e.alert})}var $v=["not_applicable","disabled","waiting","pending","processing","completed","failed","skipped","purged","expired"];var kG=new Set($v);var su=ie(l(),l());var da=g({id:l(),sequence:f().int().nonnegative(),nodeId:l(),nodeType:l(),nodeLabel:l(),status:P(["running","completed","warning","error"]),enteredAt:l(),exitedAt:l().nullable(),durationMs:f().int().nonnegative().nullable(),handleUsed:l().nullable(),digit:l().nullable(),variablesBefore:su,variablesAfter:su.nullable(),resolvedConfig:ie(l(),pt()),resultData:ie(l(),pt()).nullable()}).superRefine((e,t)=>{let n=[e.exitedAt,e.durationMs,e.handleUsed,e.variablesAfter];if(e.status==="running"?n.some((o)=>o!==null):n.includes(null))t.addIssue({code:"custom",path:["status"],message:"Running steps must have empty exit fields; terminal steps must have complete exit fields"})}),T0=g({orgId:l(),status:P(["active","waiting_input","ended"]),currentNodeId:l(),variables:su,steps:z(da),truncated:F()});function Ln(e){return{audio:{tts:{text:e}}}}function I0(e){return{type:"text",text:e}}function T(e){return{...Ln(e),content:I0(e)}}function re(e,t,n={},r){return{options:t,maxAttempts:3,audio:Ln(e).audio,text:r??e,...n}}function Ne(e,t={}){return{audio:Ln(e).audio,text:e,...t}}function ee(e,t,n,r){return[p(`${e}a`,t,"answered",n),p(`${e}b`,t,"busy",r),p(`${e}n`,t,"noAnswer",r),p(`${e}e`,t,"error",r)]}var N0={x:0,y:0};function h(e,t,n,r,o){return{id:e,type:t,label:n,varName:r,position:N0,config:o}}function p(e,t,n,r){return{id:e,source:t,sourceHandle:n,target:r,targetHandle:"in"}}var Mv={id:"atendente-virtual-ia",category:"ai",requiredModules:["ai"],tags:["ia","agente","ai","virtual","conversacional"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Olá! Sou o assistente virtual. Posso ajudar com diversas questões.")),h("ai1","aiAgent","Agente IA","agente_ia",{agent_id:"",agent_name:"",additional_instructions:"",variables:{},initial_message:"Olá, como posso ajudar?",max_duration_minutes:10}),h("m1","menu","Satisfação","satisfacao",re("Resolvemos sua dúvida? Se sim, tecle 1. Para falar com um atendente, tecle 2.",[{id:"satisfeito",label:"Satisfeito",digit:"1"},{id:"atendente",label:"Falar com atendente",digit:"2"}],{},"Escolha uma opção:")),h("t2","tell","Agradecimento","agradecimento",T("Obrigado pelo contato. Tenha um bom dia!")),h("t3","tell","Transferindo","transferindo",T("Vou transferir para um atendente humano.")),h("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["1000"],timeout:45}),h("t4","tell","Erro IA","erro_ia",T("Houve um problema com o assistente. Vou transferir para um atendente.")),h("t5","tell","Transferência Falhou","transferencia_falhou",T("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","ai1"),p("e3","ai1","completed","m1"),p("e4","ai1","error","t4"),p("e5","m1","option:satisfeito","t2"),p("e6","m1","option:atendente","t3"),p("e7","m1","noMatch","t3"),p("e8","m1","error","t3"),p("e9","t2","next","h1"),p("e10","t3","next","x1"),p("e11","t4","next","x1"),...ee("ex1","x1","h1","t5"),p("e12","t5","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var Lv={id:"atendimento-agente-ia",category:"ai",requiredModules:["ai"],tags:["ia","ai","agente","atendimento","intencao","classificacao","transferencia"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Olá! Você ligou para a nossa central. Em poucas palavras, me diga como posso ajudar.")),h("c1","capture","Captura","captura",Ne("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:Ln("Um momento enquanto analiso o seu pedido.").audio})),h("ra1","routeAi","Classificador","classificador",{input:"{{captura.text}}",intents:[{label:"suporte",description:"Problemas técnicos, falhas, dúvidas de uso do produto ou serviço"},{label:"financeiro",description:"Faturas, cobranças, pagamentos, reembolsos e negociações"}],instructions:"Classifique o motivo do contato do cliente. Duplique um ramo para cada novo assunto atendido."}),h("ai1","aiAgent","Agente","agente",{agent_id:"",agent_name:"",additional_instructions:"O usuário está entrando com o seguinte pedido: {{captura.text}}",variables:{},initial_message:"",max_duration_minutes:10}),h("sw1","switchCase","Decidir","decidir",{expression:"{{agente.output.resultado}}",cases:[{pattern:"^resolvido$"}]}),h("t2","tell","Despedida","despedida",T("Obrigado pelo contato. Tenha um ótimo dia!")),h("t3","tell","Não Entendi","nao_entendeu",T("Não consegui entender o motivo do contato. Vou transferir para um atendente.")),h("t4","tell","Erro Técnico","erro_tecnico",T("Tivemos um problema no atendimento automático. Vou transferir para um atendente.")),h("x1","transfer","Transferência Humana","transfer_humano",{method:"bridge",destinations:["1000"]}),h("t5","tell","Transferência Falhou","transfer_falhou",T("Não conseguimos completar a transferência. Por favor, ligue novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","c1"),p("e3","c1","collected","ra1"),p("e4","c1","noInput","t3"),p("e5","c1","error","t4"),p("e6","ra1","intent:suporte","ai1"),p("e7","ra1","intent:financeiro","x1"),p("e8","ra1","notApplicable","t3"),p("e9","ra1","error","t4"),p("e10","ai1","completed","sw1"),p("e11","ai1","error","t4"),p("e12","sw1","match:^resolvido$","t2"),p("e13","sw1","fallback","x1"),p("e14","sw1","error","t4"),p("e15","t3","next","x1"),p("e16","t4","next","x1"),p("e17","t2","next","h1"),p("e18","x1","answered","t2"),p("e19","x1","busy","t5"),p("e20","x1","noAnswer","t5"),p("e21","x1","error","t5"),p("e22","t5","next","h1")],viewport:{x:0,y:0,zoom:0.75}}};var zv={id:"atendimento-setores",category:"core",requiredModules:[],tags:["menu","transfer","setores","departamentos","ura"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Bem-vindo. Escolha entre financeiro, suporte, vendas ou ouvidoria.")),h("m1","menu","Menu Principal","menu_principal",re("Para financeiro, tecle 1. Para suporte, tecle 2. Para vendas, tecle 3. Para ouvidoria, tecle 4.",[{id:"financeiro",label:"Financeiro",digit:"1"},{id:"suporte",label:"Suporte Técnico",digit:"2"},{id:"vendas",label:"Vendas",digit:"3"},{id:"ouvidoria",label:"Ouvidoria",digit:"4"}],{},"Escolha o setor desejado:")),h("t2","tell","Transferindo Financeiro","transferindo_financeiro",T("Aguarde, transferindo para o financeiro.")),h("t3","tell","Transferindo Suporte","transferindo_suporte",T("Aguarde, transferindo para o suporte técnico.")),h("t4","tell","Transferindo Vendas","transferindo_vendas",T("Aguarde, transferindo para vendas.")),h("t5","tell","Transferindo Ouvidoria","transferindo_ouvidoria",T("Aguarde, transferindo para a ouvidoria.")),h("x1","transfer","Financeiro","financeiro",{method:"bridge",destinations:["1001"],timeout:30}),h("x2","transfer","Suporte","suporte",{method:"bridge",destinations:["1002"],timeout:30}),h("x3","transfer","Vendas","vendas",{method:"bridge",destinations:["1003"],timeout:30}),h("x4","transfer","Ouvidoria","ouvidoria",{method:"bridge",destinations:["1004"],timeout:30}),h("t6","tell","Opção Inválida","opcao_invalida",T("Não entendi sua escolha. Por favor, ligue novamente.")),h("t7","tell","Transferência Falhou","transferencia_falhou",T("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","m1"),p("e3","m1","option:financeiro","t2"),p("e4","m1","option:suporte","t3"),p("e5","m1","option:vendas","t4"),p("e6","m1","option:ouvidoria","t5"),p("e7","t2","next","x1"),p("e8","t3","next","x2"),p("e9","t4","next","x3"),p("e10","t5","next","x4"),p("e11","m1","noMatch","t6"),p("e12","m1","error","t6"),p("e13","t6","next","h1"),...ee("ex1","x1","h1","t7"),...ee("ex2","x2","h1","t7"),...ee("ex3","x3","h1","t7"),...ee("ex4","x4","h1","t7"),p("e14","t7","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var Fv={id:"banco-sac",category:"industry",requiredModules:[],tags:["banco","financeiro","sac","saldo","extrato","cartao"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("c1","capture","CPF do Cliente","cpf_cliente",Ne("Bem-vindo ao banco. Digite os onze números do seu CPF.",{voiceMethod:"dtmf",minDigits:11,maxDigits:11,terminators:"#",text:"Bem-vindo ao banco. Informe seu CPF (somente números):",validation:String.raw`^\d{11}$`,invalidMessage:"CPF inválido. Informe os 11 dígitos, somente números:"})),h("m1","menu","Menu Serviços","menu_servicos",re("Para consultar saldo, tecle 1. Para extrato, tecle 2. Para cartões, tecle 3. Para falar com um atendente, tecle 4.",[{id:"saldo",label:"Consultar saldo",digit:"1"},{id:"extrato",label:"Extrato",digit:"2"},{id:"cartao",label:"Cartões",digit:"3"},{id:"atendente",label:"Falar com atendente",digit:"4"}],{},"Escolha o serviço desejado:")),h("http1","httpRequest","Consultar Saldo","consultar_saldo",{method:"GET",url:"https://api.example.com/accounts/{{cpf_cliente.text}}/balance",headers:{},body:"",timeout:10}),h("t1","tell","Saldo Informado","saldo_informado",T("O seu saldo é: {{consultar_saldo.response}}. Obrigado pelo contato.")),h("t2","tell","Extrato","extrato",T("Seu extrato será enviado por SMS em instantes.")),h("t3","tell","Cartões","cartoes",T("Para informações sobre cartões, vou transferir para um especialista.")),h("t4","tell","Transferindo Atendente","transferindo_atendente",T("Aguarde, vou transferir para um atendente.")),h("t5","tell","Erro Consulta","erro_consulta",T("Não foi possível realizar a consulta agora. Vou transferir para um atendente.")),h("t6","tell","Sem Identificação","sem_identificacao",T("Não consegui identificar o seu CPF. Vou transferir para um atendente.")),h("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["5001"],timeout:45}),h("t7","tell","Transferência Falhou","transferencia_falhou",T("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","c1"),p("e1c","s1","chat","c1"),p("e2","c1","collected","m1"),p("e3","c1","noInput","t6"),p("e4","c1","error","t6"),p("e5","m1","option:saldo","http1"),p("e6","m1","option:extrato","t2"),p("e7","m1","option:cartao","t3"),p("e8","m1","option:atendente","t4"),p("e9","m1","noMatch","t6"),p("e10","m1","error","t6"),p("e11","http1","next","t1"),p("e12","http1","error","t5"),p("e13","t1","next","h1"),p("e14","t2","next","h1"),p("e15","t3","next","x1"),p("e16","t4","next","x1"),p("e17","t5","next","x1"),p("e18","t6","next","x1"),...ee("ex1","x1","h1","t7"),p("e19","t7","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var Uv={id:"clinica-agendamento",category:"industry",requiredModules:[],tags:["clinica","saude","agendamento","consulta","medico"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Bem-vindo à central de agendamentos.")),h("m1","menu","Especialidade","especialidade",re("Para Clínico Geral, tecle 1. Para Cardiologia, tecle 2. Para Ortopedia, tecle 3.",[{id:"clinico",label:"Clínico Geral",digit:"1"},{id:"cardio",label:"Cardiologia",digit:"2"},{id:"orto",label:"Ortopedia",digit:"3"}],{},"Escolha a especialidade desejada:")),h("c1","capture","CPF do Paciente","cpf_paciente",Ne("Digite os onze números do CPF do paciente.",{voiceMethod:"dtmf",minDigits:11,maxDigits:11,terminators:"#",text:"Informe o CPF do paciente (somente números):",validation:String.raw`^\d{11}$`,invalidMessage:"CPF inválido. Informe os 11 dígitos, somente números:"})),h("http1","httpRequest","Consultar Agenda","consultar_agenda",{method:"POST",url:"https://api.example.com/appointments/check",headers:{"Content-Type":"application/json"},body:'{"cpf": "{{cpf_paciente.text}}", "specialty": "{{especialidade.selectedId}}"}',timeout:10}),h("t2","tell","Resultado da Consulta","resultado_consulta",T("{{consultar_agenda.response}}")),h("t3","tell","Erro na Consulta","erro_consulta",T("Não conseguimos consultar a agenda no momento. Por favor, tente novamente mais tarde.")),h("t4","tell","Sem Dados","sem_dados",T("Não consegui capturar as informações necessárias. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","m1"),p("e3","m1","option:clinico","c1"),p("e4","m1","option:cardio","c1"),p("e5","m1","option:orto","c1"),p("e6","m1","noMatch","t4"),p("e7","m1","error","t4"),p("e8","c1","collected","http1"),p("e9","c1","noInput","t4"),p("e10","c1","error","t4"),p("e11","http1","next","t2"),p("e12","http1","error","t3"),p("e13","t2","next","h1"),p("e14","t3","next","h1"),p("e15","t4","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var jv={id:"cobranca-automatizada",category:"capture",requiredModules:[],tags:["cobranca","debito","pagamento","boleto","pix","negociacao"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Intro Cobrança","intro_cobranca",T("Olá, identificamos um débito em aberto na sua conta.")),h("m1","menu","Opções de Pagamento","opcoes_pagamento",re("Para negociar a dívida, tecle 1. Para receber o boleto atualizado, tecle 2. Para pagar via Pix, tecle 3.",[{id:"negociar",label:"Negociar dívida",digit:"1"},{id:"boleto",label:"Receber boleto",digit:"2"},{id:"pix",label:"Pagar via Pix",digit:"3"}],{},"Escolha uma opção de pagamento:")),h("c1","capture","Identificação","identificacao",Ne("Informe seu CPF ou número de contrato e finalize com a tecla jogo da velha.",{voiceMethod:"dtmf",minDigits:4,maxDigits:14,terminators:"#",text:"Informe seu CPF ou número de contrato (somente números):",validation:String.raw`^\d{4,14}$`,invalidMessage:"Identificação inválida. Informe apenas números, entre 4 e 14 dígitos:"})),h("t2","tell","Transferindo Negociação","transferindo_negociacao",T("Recebi sua identificação. Vou transferir para um especialista em negociação.")),h("x1","transfer","Negociação","negociacao",{method:"bridge",destinations:["2001"],timeout:45}),h("t3","tell","Boleto Enviado","boleto_enviado",T("O boleto atualizado será enviado para seu contato cadastrado em até 5 minutos.")),h("t4","tell","Chave Pix","chave_pix",T("Nossa chave Pix é o CNPJ da empresa. Após o pagamento, a baixa será automática em até 2 horas.")),h("t5","tell","Opção Inválida","opcao_invalida",T("Não entendi sua escolha. Por favor, ligue novamente.")),h("t6","tell","Sem Identificação","sem_identificacao",T("Não recebi sua identificação. Por favor, ligue novamente com os dados em mãos.")),h("t7","tell","Transferência Falhou","transferencia_falhou",T("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","m1"),p("e3","m1","option:negociar","c1"),p("e4","m1","option:boleto","t3"),p("e5","m1","option:pix","t4"),p("e6","m1","noMatch","t5"),p("e7","m1","error","t5"),p("e8","c1","collected","t2"),p("e9","c1","noInput","t6"),p("e10","c1","error","t6"),p("e11","t2","next","x1"),p("e12","t3","next","h1"),p("e13","t4","next","h1"),p("e14","t5","next","h1"),p("e15","t6","next","h1"),...ee("ex1","x1","h1","t7"),p("e16","t7","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var Vv={id:"coleta-dados-api",category:"capture",requiredModules:[],tags:["capture","api","http","dados","integracao"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Olá. Vou consultar uma informação para você.")),h("c1","capture","Identificação","identificacao",Ne("Informe seu número de identificação e finalize com a tecla jogo da velha.",{voiceMethod:"dtmf",minDigits:4,maxDigits:14,terminators:"#",text:"Informe seu número de identificação (somente números):",validation:String.raw`^\d{4,14}$`,invalidMessage:"Identificação inválida. Informe apenas números, entre 4 e 14 dígitos:"})),h("http1","httpRequest","Consultar API","consultar_api",{method:"GET",url:"https://api.example.com/lookup/{{identificacao.text}}",headers:{},body:"",timeout:10}),h("sw1","switchCase","Tipo de Falha","tipo_falha",{expression:"{{consultar_api.status_code}}",cases:[{pattern:"^404$"}]}),h("t2","tell","Resultado Encontrado","resultado_encontrado",T("Encontrei as informações solicitadas: {{consultar_api.response}}. Obrigado pelo contato.")),h("t3","tell","Não Encontrado","nao_encontrado",T("Não encontrei registros para essa identificação. Verifique o número e tente novamente.")),h("t4","tell","Erro de Consulta","erro_consulta",T("Houve um erro na consulta. Tente novamente mais tarde.")),h("t5","tell","Sem Identificação","sem_identificacao",T("Não consegui capturar sua identificação. Por favor, ligue novamente com o número em mãos.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","c1"),p("e3","c1","collected","http1"),p("e4","c1","noInput","t5"),p("e5","c1","error","t5"),p("e6","http1","next","t2"),p("e7","http1","error","sw1"),p("e8","sw1","match:^404$","t3"),p("e9","sw1","fallback","t4"),p("e10","sw1","error","t4"),p("e11","t2","next","h1"),p("e12","t3","next","h1"),p("e13","t4","next","h1"),p("e14","t5","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var Kv={id:"faq-ia-escalacao",category:"ai",requiredModules:["ai"],tags:["faq","ia","escalacao","ai","agente"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Olá! Sou o assistente virtual. Posso tirar dúvidas sobre nossos serviços.")),h("ai1","aiAgent","Agente FAQ","agente_faq",{agent_id:"",agent_name:"",additional_instructions:"Responda perguntas frequentes sobre os serviços da empresa. Se não souber a resposta, informe que vai transferir para um atendente.",variables:{},initial_message:"Olá! Qual sua dúvida?",max_duration_minutes:5}),h("m1","menu","Resolveu?","resolveu",re("Sua dúvida foi resolvida? Se sim, tecle 1. Para falar com um atendente, tecle 2.",[{id:"resolvido",label:"Sim, resolvido",digit:"1"},{id:"atendente",label:"Falar com atendente",digit:"2"}],{},"Escolha uma opção:")),h("t2","tell","Agradecimento","agradecimento",T("Ótimo! Se precisar de algo mais, é só entrar em contato.")),h("t3","tell","Transferindo","transferindo",T("Aguarde, vou transferir para um atendente.")),h("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["1000"],timeout:45}),h("t4","tell","Transferência Falhou","transferencia_falhou",T("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","ai1"),p("e3","ai1","completed","m1"),p("e4","ai1","error","t3"),p("e5","m1","option:resolvido","t2"),p("e6","m1","option:atendente","t3"),p("e7","m1","noMatch","t3"),p("e8","m1","error","t3"),p("e9","t2","next","h1"),p("e10","t3","next","x1"),...ee("ex1","x1","h1","t4"),p("e11","t4","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var qv={id:"faq-informacoes",category:"core",requiredModules:[],tags:["faq","informacoes","autoatendimento","info"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Olá, sou o assistente virtual. Posso ajudar com suporte, financeiro, vendas ou horários de atendimento.")),h("m1","menu","Menu FAQ","menu_faq",re("Para suporte técnico, tecle 1. Para financeiro, tecle 2. Para vendas, tecle 3. Para horários de atendimento, tecle 4.",[{id:"suporte",label:"Suporte Técnico",digit:"1"},{id:"financeiro",label:"Financeiro",digit:"2"},{id:"vendas",label:"Vendas",digit:"3"},{id:"horarios",label:"Horários",digit:"4"}],{},"Escolha um assunto:")),h("t2","tell","Info Suporte","info_suporte",T("Nossa equipe de suporte está disponível 24 horas por dia. Você também pode abrir um chamado pelo nosso portal.")),h("t3","tell","Info Financeiro","info_financeiro",T("Para boletos, notas fiscais e negociações, acesse nosso portal financeiro ou fale com atendimento em horário comercial.")),h("t4","tell","Info Vendas","info_vendas",T("Conheça nossos planos e promoções no nosso site. Para falar com um consultor, ligue em horário comercial.")),h("t5","tell","Info Horários","info_horarios",T("Nosso atendimento funciona de segunda a sexta, das 8h às 20h. Aos sábados, das 8h às 14h.")),h("t6","tell","Opção Inválida","opcao_invalida",T("Não entendi sua escolha. Encerrando o atendimento. Até logo.")),h("h1","hangup","Fim","fim",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","m1"),p("e3","m1","option:suporte","t2"),p("e4","m1","option:financeiro","t3"),p("e5","m1","option:vendas","t4"),p("e6","m1","option:horarios","t5"),p("e7","t2","next","m1"),p("e8","t3","next","m1"),p("e9","t4","next","m1"),p("e10","t5","next","m1"),p("e11","m1","noMatch","t6"),p("e12","m1","error","t6"),p("e13","t6","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var Bv={id:"horario-comercial",category:"core",requiredModules:[],tags:["horario","schedule","tempo","comercial","expediente"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("tr1","timeRouting","Horário Atendimento","horario_atendimento",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Bem-vindo. Como posso ajudar?")),h("m1","menu","Menu Principal","menu_principal",re("Para suporte, tecle 1. Para vendas, tecle 2.",[{id:"suporte",label:"Suporte",digit:"1"},{id:"vendas",label:"Vendas",digit:"2"}],{},"Escolha uma opção:")),h("t2","tell","Transferindo Suporte","transferindo_suporte",T("Transferindo para o suporte.")),h("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),h("t3","tell","Transferindo Vendas","transferindo_vendas",T("Transferindo para vendas.")),h("x2","transfer","Vendas","vendas",{method:"bridge",destinations:["1002"],timeout:30}),h("t4","tell","Fora do Horário","fora_horario",T("Nosso horário de atendimento é de segunda a sexta, das 8h às 18h. Ligue novamente no próximo dia útil.")),h("t5","tell","Opção Não Reconhecida","opcao_nao_reconhecida",T("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),h("t6","tell","Transferência Falhou","transferencia_falhou",T("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","tr1"),p("e1c","s1","chat","tr1"),p("e2","tr1","onHours","t1"),p("e3","tr1","offHours","t4"),p("e4","tr1","holiday","t4"),p("e5","t1","next","m1"),p("e6","m1","option:suporte","t2"),p("e7","m1","option:vendas","t3"),p("e8","t2","next","x1"),p("e9","t3","next","x2"),p("e10","m1","noMatch","t5"),p("e11","m1","error","t5"),p("e12","t5","next","x1"),...ee("ex1","x1","h1","t6"),...ee("ex2","x2","h1","t6"),p("e13","t4","next","h1"),p("e14","t6","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var Hv={id:"isp-suporte-tecnico",category:"industry",requiredModules:[],tags:["isp","provedor","internet","suporte","tecnico","telecom"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Bem-vindo ao suporte técnico.")),h("m1","menu","Tipo de Serviço","tipo_servico",re("Para problemas de internet, tecle 1. Para problemas de telefonia, tecle 2.",[{id:"internet",label:"Internet",digit:"1"},{id:"telefonia",label:"Telefonia",digit:"2"}],{},"Escolha o tipo de serviço:")),h("c1","capture","Contrato Internet","contrato_internet",Ne("Informe o número do seu contrato.",{voiceMethod:"dtmf",minDigits:3,maxDigits:10,terminators:"#",text:"Informe o número do seu contrato:",validation:String.raw`^\d{3,10}$`,invalidMessage:"O número do contrato deve ter de 3 a 10 dígitos. Tente novamente:"})),h("c2","capture","Contrato Telefonia","contrato_telefonia",Ne("Informe o número do seu contrato.",{voiceMethod:"dtmf",minDigits:3,maxDigits:10,terminators:"#",text:"Informe o número do seu contrato:",validation:String.raw`^\d{3,10}$`,invalidMessage:"O número do contrato deve ter de 3 a 10 dígitos. Tente novamente:"})),h("http1","httpRequest","Status Internet","status_internet",{method:"GET",url:"https://api.example.com/contracts/{{contrato_internet.text}}/status?service=internet",headers:{},body:"",timeout:10}),h("http2","httpRequest","Status Telefonia","status_telefonia",{method:"GET",url:"https://api.example.com/contracts/{{contrato_telefonia.text}}/status?service=telefonia",headers:{},body:"",timeout:10}),h("t2","tell","Status Internet","status_internet_info",T("Sobre sua conexão de internet: {{status_internet.response}}")),h("t3","tell","Status Telefonia","status_telefonia_info",T("Sobre seu serviço de telefonia: {{status_telefonia.response}}")),h("sw1","switchCase","Falha Internet","falha_internet",{expression:"{{status_internet.status_code}}",cases:[{pattern:"^404$"}]}),h("sw2","switchCase","Falha Telefonia","falha_telefonia",{expression:"{{status_telefonia.status_code}}",cases:[{pattern:"^404$"}]}),h("t4","tell","Contrato Não Encontrado","contrato_nao_encontrado",T("Não encontrei esse contrato. Vou transferir para um atendente.")),h("t5","tell","Erro de Consulta","erro_consulta",T("Não foi possível consultar o status agora. Vou transferir para um atendente.")),h("t6","tell","Sem Contrato","sem_contrato",T("Não consegui capturar o número do contrato. Vou transferir para um atendente.")),h("t7","tell","Opção Não Reconhecida","opcao_nao_reconhecida",T("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),h("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["3001"],timeout:60}),h("t8","tell","Transferência Falhou","transferencia_falhou",T("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","m1"),p("e3","m1","option:internet","c1"),p("e4","m1","option:telefonia","c2"),p("e5","m1","noMatch","t7"),p("e5e","m1","error","t7"),p("e6","c1","collected","http1"),p("e7","c1","noInput","t6"),p("e7e","c1","error","t6"),p("e8","http1","next","t2"),p("e9","http1","error","sw1"),p("e10","sw1","match:^404$","t4"),p("e11","sw1","fallback","t5"),p("e11e","sw1","error","t5"),p("e12","t2","next","h1"),p("e13","c2","collected","http2"),p("e14","c2","noInput","t6"),p("e14e","c2","error","t6"),p("e15","http2","next","t3"),p("e16","http2","error","sw2"),p("e17","sw2","match:^404$","t4"),p("e18","sw2","fallback","t5"),p("e18e","sw2","error","t5"),p("e19","t3","next","h1"),p("e20","t4","next","x1"),p("e21","t5","next","x1"),p("e22","t6","next","x1"),p("e23","t7","next","x1"),...ee("ex1","x1","h1","t8"),p("e24","t8","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var Wv={id:"mensagem-simples",category:"core",requiredModules:[],tags:["mensagem","simples","aviso","anuncio","basico"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Mensagem","mensagem",T("Obrigado por ligar. No momento não estamos disponíveis. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","h1")],viewport:{x:0,y:0,zoom:1}}};var Gv={id:"menu-multinivel",category:"advanced",requiredModules:[],tags:["menu","multinivel","departamento","hierarquia","complexo"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Bem-vindo. Escolha o setor desejado.")),h("m1","menu","Menu Principal","menu_principal",re("Para atendimento, tecle 1. Para comercial, tecle 2. Para administrativo, tecle 3.",[{id:"atendimento",label:"Atendimento",digit:"1"},{id:"comercial",label:"Comercial",digit:"2"},{id:"administrativo",label:"Administrativo",digit:"3"}],{},"Escolha o setor desejado:")),h("m2","menu","Atendimento","atendimento",re("Para suporte técnico, tecle 1. Para financeiro, tecle 2.",[{id:"suporte",label:"Suporte Técnico",digit:"1"},{id:"financeiro",label:"Financeiro",digit:"2"}],{},"Escolha uma opção:")),h("m3","menu","Comercial","comercial",re("Para vendas, tecle 1. Para parcerias, tecle 2.",[{id:"vendas",label:"Vendas",digit:"1"},{id:"parcerias",label:"Parcerias",digit:"2"}],{},"Escolha uma opção:")),h("m4","menu","Administrativo","administrativo",re("Para RH, tecle 1. Para jurídico, tecle 2.",[{id:"rh",label:"RH",digit:"1"},{id:"juridico",label:"Jurídico",digit:"2"}],{},"Escolha uma opção:")),h("t2","tell","Transferindo Suporte","transferindo_suporte",T("Transferindo para suporte técnico.")),h("t3","tell","Transferindo Financeiro","transferindo_financeiro",T("Transferindo para financeiro.")),h("t4","tell","Transferindo Vendas","transferindo_vendas",T("Transferindo para vendas.")),h("t5","tell","Transferindo Parcerias","transferindo_parcerias",T("Transferindo para parcerias.")),h("t6","tell","Transferindo RH","transferindo_rh",T("Transferindo para RH.")),h("t7","tell","Transferindo Jurídico","transferindo_juridico",T("Transferindo para jurídico.")),h("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),h("x2","transfer","Financeiro","financeiro",{method:"bridge",destinations:["1002"],timeout:45}),h("x3","transfer","Vendas","vendas",{method:"bridge",destinations:["2001"],timeout:30}),h("x4","transfer","Parcerias","parcerias",{method:"bridge",destinations:["2002"],timeout:30}),h("x5","transfer","RH","rh",{method:"bridge",destinations:["3001"],timeout:30}),h("x6","transfer","Jurídico","juridico",{method:"bridge",destinations:["3002"],timeout:30}),h("t8","tell","Opção Não Reconhecida","opcao_nao_reconhecida",T("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),h("t9","tell","Transferência Falhou","transferencia_falhou",T("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","m1"),p("e3","m1","option:atendimento","m2"),p("e4","m1","option:comercial","m3"),p("e5","m1","option:administrativo","m4"),p("e6","m1","noMatch","t8"),p("e6e","m1","error","t8"),p("e7","m2","option:suporte","t2"),p("e8","m2","option:financeiro","t3"),p("e9","m2","noMatch","t8"),p("e9e","m2","error","t8"),p("e10","m3","option:vendas","t4"),p("e11","m3","option:parcerias","t5"),p("e12","m3","noMatch","t8"),p("e12e","m3","error","t8"),p("e13","m4","option:rh","t6"),p("e14","m4","option:juridico","t7"),p("e15","m4","noMatch","t8"),p("e15e","m4","error","t8"),p("e16","t2","next","x1"),p("e17","t3","next","x2"),p("e18","t4","next","x3"),p("e19","t5","next","x4"),p("e20","t6","next","x5"),p("e21","t7","next","x6"),p("e28","t8","next","x1"),...ee("ex1","x1","h1","t9"),...ee("ex2","x2","h1","t9"),...ee("ex3","x3","h1","t9"),...ee("ex4","x4","h1","t9"),...ee("ex5","x5","h1","t9"),...ee("ex6","x6","h1","t9"),p("e29","t9","next","h1")],viewport:{x:0,y:0,zoom:0.7}}};var Zv={id:"notificacao-atendimento",category:"core",requiredModules:[],tags:["notificacao","aviso","atendimento","callback"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Notificação","notificacao",T("Olá, temos uma informação importante sobre sua conta.")),h("m1","menu","Precisa de Ajuda?","precisa_ajuda",re("Tecle 1 para falar com um atendente, ou 2 para encerrar.",[{id:"sim",label:"Sim, falar com atendente",digit:"1"},{id:"nao",label:"Não, obrigado",digit:"2"}],{},"Deseja falar com um atendente?")),h("t2","tell","Transferindo","transferindo",T("Aguarde, vou transferir para um atendente.")),h("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["1000"],timeout:45}),h("t3","tell","Agradecimento","agradecimento",T("Obrigado pelo seu tempo. Tenha um bom dia!")),h("t4","tell","Transferência Falhou","transferencia_falhou",T("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","m1"),p("e3","m1","option:sim","t2"),p("e4","m1","option:nao","t3"),p("e5","m1","noMatch","t3"),p("e6","m1","error","t3"),p("e7","t2","next","x1"),...ee("ex1","x1","h1","t4"),p("e8","t3","next","h1"),p("e9","t4","next","h1")],viewport:{x:0,y:0,zoom:0.9}}};var Yv={id:"pesquisa-nps",category:"advanced",requiredModules:["ai"],tags:["nps","pesquisa","promotor","detrator","feedback","avaliacao"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Intro NPS","intro_nps",T("Gostaríamos de saber sua opinião sobre nosso atendimento.")),h("c1","capture","Nota NPS","nota_nps",Ne("De 0 a 10, qual a probabilidade de recomendar nossos serviços? Tecle a nota.",{voiceMethod:"dtmf",minDigits:1,maxDigits:2,terminators:"#",text:"De 0 a 10, qual a probabilidade de recomendar nossos serviços?",validation:"^(10|[0-9])$",invalidMessage:"Informe uma nota de 0 a 10:"})),h("sw1","switchCase","Classificar NPS","classificar_nps",{expression:"{{nota_nps.text}}",cases:[{pattern:"^9$"},{pattern:"^10$"},{pattern:"^7$"},{pattern:"^8$"}]}),h("t2","tell","Promotor","promotor",T("Que ótimo! Ficamos muito felizes com sua avaliação.")),h("t3","tell","Neutro","neutro",T("Obrigado pela avaliação. Vamos trabalhar para melhorar.")),h("t4","tell","Detrator","detrator",T("Lamentamos que sua experiência não tenha sido satisfatória.")),h("c2","capture","Feedback","feedback",Ne("Pode nos dizer o que podemos melhorar? Fale após o sinal.",{voiceMethod:"speech",text:"Pode nos dizer o que podemos melhorar?"})),h("http1","httpRequest","Salvar Pesquisa","salvar_pesquisa",{method:"POST",url:"https://api.example.com/nps",headers:{"Content-Type":"application/json"},body:'{"score": "{{nota_nps.text}}", "feedback": "{{feedback.text}}"}',timeout:10}),h("t5","tell","Agradecimento","agradecimento",T("Obrigado pelo seu feedback. Ele é muito importante para nós.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","c1"),p("e3","c1","collected","sw1"),p("e4","c1","noInput","t5"),p("e4e","c1","error","t5"),p("e5","sw1","match:^9$","t2"),p("e6","sw1","match:^10$","t2"),p("e7","sw1","match:^7$","t3"),p("e8","sw1","match:^8$","t3"),p("e9","sw1","fallback","t4"),p("e9e","sw1","error","t4"),p("e10","t2","next","c2"),p("e11","t3","next","c2"),p("e12","t4","next","c2"),p("e13","c2","collected","http1"),p("e14","c2","noInput","http1"),p("e14e","c2","error","http1"),p("e15","http1","next","t5"),p("e16","http1","error","t5"),p("e17","t5","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var Jv={id:"pesquisa-satisfacao",category:"core",requiredModules:[],tags:["pesquisa","satisfacao","csat","avaliacao","nota"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Intro Pesquisa","intro_pesquisa",T("Gostaríamos de avaliar o atendimento que você recebeu.")),h("m1","menu","Nota de Satisfação","nota_satisfacao",re("Como você avalia o atendimento? Tecle 1 para péssimo, 2 para ruim, 3 para regular, 4 para bom, ou 5 para excelente.",[{id:"nota_1",label:"1 - Péssimo",digit:"1"},{id:"nota_2",label:"2 - Ruim",digit:"2"},{id:"nota_3",label:"3 - Regular",digit:"3"},{id:"nota_4",label:"4 - Bom",digit:"4"},{id:"nota_5",label:"5 - Excelente",digit:"5"}],{maxAttempts:2},"Como você avalia o atendimento que recebeu?")),h("t2","tell","Agradecimento","agradecimento",T("Você avaliou nosso atendimento como: {{nota_satisfacao.selectedLabel}}. Obrigado, sua opinião nos ajuda a melhorar.")),h("t3","tell","Sem Resposta","sem_resposta",T("Não conseguimos registrar sua avaliação. Agradecemos o contato.")),h("h1","hangup","Desligamento","desligamento",{}),h("h2","hangup","Desligamento Timeout","desligamento_timeout",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","m1"),p("e3","m1","option:nota_1","t2"),p("e4","m1","option:nota_2","t2"),p("e5","m1","option:nota_3","t2"),p("e6","m1","option:nota_4","t2"),p("e7","m1","option:nota_5","t2"),p("e8","t2","next","h1"),p("e9","m1","noMatch","t3"),p("e10","m1","error","t3"),p("e11","t3","next","h2")],viewport:{x:0,y:0,zoom:0.9}}};var Xv={id:"roteamento-canal",category:"omnichannel",requiredModules:[],tags:["canal","omnichannel","voz","chat","roteamento"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("cr1","channelRouter","Roteador de Canal","roteador_canal",{}),h("t1","tell","Boas-vindas Voz","boas_vindas_voz",T("Bem-vindo ao nosso atendimento por telefone.")),h("m1","menu","Menu Voz","menu_voz",re("Para suporte, tecle 1. Para vendas, tecle 2.",[{id:"suporte",label:"Suporte",digit:"1"},{id:"vendas",label:"Vendas",digit:"2"}])),h("t2","tell","Boas-vindas Chat","boas_vindas_chat",T("Olá! Bem-vindo ao nosso atendimento por chat.")),h("m2","menu","Menu Chat","menu_chat",re("Para suporte, tecle 1. Para vendas, tecle 2.",[{id:"suporte",label:"Suporte",digit:"1"},{id:"vendas",label:"Vendas",digit:"2"}],{},"Escolha uma opção:")),h("t3","tell","Transferindo Suporte","transferindo_suporte",T("Transferindo para o suporte.")),h("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),h("t4","tell","Transferindo Vendas","transferindo_vendas",T("Transferindo para vendas.")),h("x2","transfer","Vendas","vendas",{method:"bridge",destinations:["1002"],timeout:30}),h("t5","tell","Opção Não Reconhecida","opcao_nao_reconhecida",T("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),h("t6","tell","Transferência Falhou","transferencia_falhou",T("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","cr1"),p("e1c","s1","chat","cr1"),p("e2","cr1","voice","t1"),p("e3","cr1","chat","t2"),p("e4","t1","next","m1"),p("e5","t2","next","m2"),p("e6","m1","option:suporte","t3"),p("e7","m1","option:vendas","t4"),p("e8","m2","option:suporte","t3"),p("e9","m2","option:vendas","t4"),p("e10","t3","next","x1"),p("e11","t4","next","x2"),...ee("ex1","x1","h1","t6"),...ee("ex2","x2","h1","t6"),p("e12","m1","noMatch","t5"),p("e13","m1","error","t5"),p("e14","m2","noMatch","t5"),p("e15","m2","error","t5"),p("e16","t5","next","x1"),p("e17","t6","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var Qv={id:"status-pedido",category:"capture",requiredModules:[],tags:["pedido","status","rastreio","ecommerce","api"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Olá. Vou consultar o status do seu pedido.")),h("c1","capture","Número do Pedido","numero_pedido",Ne("Informe o número do seu pedido e finalize com a tecla jogo da velha.",{voiceMethod:"dtmf",minDigits:1,maxDigits:10,terminators:"#",text:"Informe o número do seu pedido:",validation:String.raw`^\d{1,10}$`,invalidMessage:"O número do pedido deve conter apenas dígitos. Tente novamente:"})),h("http1","httpRequest","Consultar Pedido","consultar_pedido",{method:"GET",url:"https://api.example.com/orders/{{numero_pedido.text}}",headers:{},body:"",timeout:10}),h("sw1","switchCase","Tipo de Falha","tipo_falha",{expression:"{{consultar_pedido.status_code}}",cases:[{pattern:"^404$"}]}),h("t2","tell","Status do Pedido","status_do_pedido",T("O status do seu pedido é: {{consultar_pedido.response}}")),h("t3","tell","Pedido Não Encontrado","pedido_nao_encontrado",T("Não encontrei esse número de pedido. Verifique e tente novamente.")),h("t4","tell","Erro de Consulta","erro_consulta",T("Houve um erro ao consultar o pedido. Tente novamente mais tarde.")),h("t5","tell","Sem Número","sem_numero",T("Não consegui capturar o número do pedido. Por favor, ligue novamente com o número em mãos.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","c1"),p("e3","c1","collected","http1"),p("e4","c1","noInput","t5"),p("e5","c1","error","t5"),p("e6","http1","next","t2"),p("e7","http1","error","sw1"),p("e8","sw1","match:^404$","t3"),p("e9","sw1","fallback","t4"),p("e10","sw1","error","t4"),p("e11","t2","next","h1"),p("e12","t3","next","h1"),p("e13","t4","next","h1"),p("e14","t5","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var eS={id:"triagem-inteligente",category:"ai",requiredModules:["ai"],tags:["triagem","intencao","intent","ia","roteamento","ai"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Olá! Vou te direcionar para o setor correto.")),h("c1","capture","Motivo do Contato","motivo_contato",Ne("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:Ln("Um momento enquanto identifico o setor correto.").audio,text:"Descreva em poucas palavras com o que você precisa de ajuda:"})),h("ra1","routeAi","Classificar Intenção","classificar_intencao",{input:"{{motivo_contato.text}}",intents:[{label:"suporte",description:"Problemas técnicos, dúvidas de uso, erros no sistema"},{label:"financeiro",description:"Faturas, cobranças, pagamentos, reembolsos"},{label:"vendas",description:"Novos produtos, planos, promoções, contratação"}],instructions:"Classifique a intenção do cliente com base no que ele disse."}),h("t2","tell","Direcionando Suporte","direcionando_suporte",T("Entendi, vou transferir para o suporte técnico.")),h("t3","tell","Direcionando Financeiro","direcionando_financeiro",T("Entendi, vou transferir para o financeiro.")),h("t4","tell","Direcionando Vendas","direcionando_vendas",T("Entendi, vou transferir para vendas.")),h("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),h("x2","transfer","Financeiro","financeiro",{method:"bridge",destinations:["1002"],timeout:45}),h("x3","transfer","Vendas","vendas",{method:"bridge",destinations:["1003"],timeout:30}),h("t5","tell","Não Identificado","nao_identificado",T("Não consegui identificar sua necessidade. Vou transferir para um atendente.")),h("x4","transfer","Atendente Geral","atendente_geral",{method:"bridge",destinations:["1000"],timeout:45}),h("t6","tell","Transferência Falhou","transferencia_falhou",T("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","c1"),p("e3","c1","collected","ra1"),p("e4","c1","noInput","t5"),p("e5","c1","error","t5"),p("e6","ra1","intent:suporte","t2"),p("e7","ra1","intent:financeiro","t3"),p("e8","ra1","intent:vendas","t4"),p("e9","ra1","notApplicable","t5"),p("e10","ra1","error","t5"),p("e11","t2","next","x1"),p("e12","t3","next","x2"),p("e13","t4","next","x3"),p("e14","t5","next","x4"),...ee("ex1","x1","h1","t6"),...ee("ex2","x2","h1","t6"),...ee("ex3","x3","h1","t6"),...ee("ex4","x4","h1","t6"),p("e15","t6","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var tS={id:"ura-reversa-spot",category:"core",requiredModules:[],tags:["spot","ura reversa","campanha","outbound","discagem","tecla"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("m1","menu","Spot","spot",re("Substitua este texto pelo áudio do seu spot. Para falar com um atendente, tecle 1.",[{id:"interesse",label:"Falar com atendente",digit:"1"}],{maxAttempts:1},"Substitua este texto pelo conteúdo do seu spot.")),h("t1","tell","Agradecimento","agradecimento",T("Obrigado! Em instantes um atendente entrará em contato.")),h("t2","tell","Encerramento","encerramento",T("Obrigado pela atenção. Até logo!")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","m1"),p("e1c","s1","chat","m1"),p("e2","m1","option:interesse","t1"),p("e3","m1","noMatch","t2"),p("e4","m1","error","t2"),p("e5","t1","next","h1"),p("e6","t2","next","h1")],viewport:{x:0,y:0,zoom:0.9}}};var nS={"atendente-virtual-ia":{ai1:{x:672,y:170},h1:{x:2352,y:254},m1:{x:1008,y:0},s1:{x:0,y:26},t1:{x:336,y:109},t2:{x:1680,y:61},t3:{x:1344,y:113},t4:{x:1344,y:253},t5:{x:2016,y:306},x1:{x:1680,y:201}},"atendimento-agente-ia":{ai1:{x:1344,y:38},c1:{x:672,y:208},h1:{x:3024,y:139},ra1:{x:1008,y:116},s1:{x:0,y:64},sw1:{x:1680,y:0},t1:{x:336,y:147},t2:{x:2688,y:78},t3:{x:1344,y:221},t4:{x:2016,y:153},t5:{x:2688,y:218},x1:{x:2352,y:113}},"atendimento-setores":{h1:{x:2016,y:740},m1:{x:672,y:307},s1:{x:0,y:163},t1:{x:336,y:246},t2:{x:1008,y:0},t3:{x:1008,y:206},t4:{x:1008,y:412},t5:{x:1008,y:552},t6:{x:1008,y:692},t7:{x:1680,y:556},x1:{x:1344,y:61},x2:{x:1344,y:267},x3:{x:1344,y:473},x4:{x:1344,y:679}},"banco-sac":{c1:{x:336,y:356},h1:{x:2352,y:314},http1:{x:1008,y:0},m1:{x:672,y:170},s1:{x:0,y:273},t1:{x:1680,y:205},t2:{x:1344,y:253},t3:{x:1344,y:393},t4:{x:1008,y:321},t5:{x:1344,y:113},t6:{x:1008,y:461},t7:{x:2016,y:537},x1:{x:1680,y:454}},"clinica-agendamento":{c1:{x:1008,y:140},h1:{x:2016,y:306},http1:{x:1344,y:131},m1:{x:672,y:144},s1:{x:0,y:0},t1:{x:336,y:83},t2:{x:1680,y:105},t3:{x:1680,y:245},t4:{x:1344,y:293}},"cobranca-automatizada":{c1:{x:1008,y:139},h1:{x:2352,y:283},m1:{x:672,y:339},s1:{x:0,y:195},t1:{x:336,y:278},t2:{x:1344,y:0},t3:{x:1680,y:335},t4:{x:2016,y:444},t5:{x:1008,y:496},t6:{x:1344,y:222},t7:{x:2016,y:174},x1:{x:1680,y:61}},"coleta-dados-api":{c1:{x:672,y:196},h1:{x:2016,y:174},http1:{x:1008,y:65},s1:{x:0,y:52},sw1:{x:1344,y:148},t1:{x:336,y:135},t2:{x:1344,y:0},t3:{x:1680,y:113},t4:{x:1680,y:253},t5:{x:1008,y:301}},"faq-ia-escalacao":{ai1:{x:672,y:144},h1:{x:2352,y:306},m1:{x:1008,y:52},s1:{x:0,y:0},t1:{x:336,y:83},t2:{x:1680,y:113},t3:{x:1344,y:179},t4:{x:2016,y:358},x1:{x:1680,y:253}},"faq-informacoes":{h1:{x:1354,y:708},m1:{x:672,y:144},s1:{x:0,y:0},t1:{x:336,y:83},t2:{x:1018,y:67},t3:{x:1018,y:227},t4:{x:1018,y:367},t5:{x:1018,y:507},t6:{x:1018,y:647}},"horario-comercial":{h1:{x:2352,y:442},m1:{x:1008,y:206},s1:{x:0,y:193},t1:{x:672,y:145},t2:{x:1344,y:0},t3:{x:1344,y:193},t4:{x:672,y:381},t5:{x:1344,y:333},t6:{x:2016,y:333},tr1:{x:336,y:276},x1:{x:1680,y:61},x2:{x:1680,y:267}},"isp-suporte-tecnico":{c1:{x:1008,y:43},c2:{x:1008,y:227},h1:{x:3034,y:296},http1:{x:1344,y:22},http2:{x:1344,y:341},m1:{x:672,y:144},s1:{x:0,y:0},sw1:{x:1690,y:135},sw2:{x:1690,y:319},t1:{x:336,y:83},t2:{x:2362,y:83},t3:{x:2698,y:488},t4:{x:2026,y:204},t5:{x:2026,y:344},t6:{x:1344,y:201},t7:{x:1008,y:411},t8:{x:2698,y:348},x1:{x:2362,y:265}},"mensagem-simples":{h1:{x:672,y:144},s1:{x:0,y:0},t1:{x:336,y:83}},"menu-multinivel":{h1:{x:2372,y:487},m1:{x:672,y:482},m2:{x:1008,y:250},m3:{x:1008,y:456},m4:{x:1008,y:683},s1:{x:0,y:338},t1:{x:336,y:421},t2:{x:1354,y:71},t3:{x:1354,y:211},t4:{x:1354,y:351},t5:{x:1354,y:491},t6:{x:1354,y:771},t7:{x:1354,y:969},t8:{x:1354,y:631},t9:{x:2036,y:539},x1:{x:1690,y:206},x2:{x:1690,y:0},x3:{x:1690,y:412},x4:{x:1690,y:618},x5:{x:1690,y:824},x6:{x:1690,y:1030}},"notificacao-atendimento":{h1:{x:2016,y:284},m1:{x:672,y:144},s1:{x:0,y:0},t1:{x:336,y:83},t2:{x:1008,y:49},t3:{x:1008,y:271},t4:{x:1680,y:223},x1:{x:1344,y:110}},"pesquisa-nps":{c1:{x:672,y:310},c2:{x:1680,y:201},h1:{x:2688,y:476},http1:{x:2016,y:284},s1:{x:0,y:166},sw1:{x:1008,y:35},t1:{x:336,y:249},t2:{x:1344,y:0},t3:{x:1344,y:140},t4:{x:1344,y:280},t5:{x:2352,y:415}},"pesquisa-satisfacao":{h1:{x:1344,y:288},h2:{x:1344,y:428},m1:{x:672,y:144},s1:{x:0,y:0},t1:{x:336,y:83},t2:{x:1008,y:227},t3:{x:1008,y:367}},"roteamento-canal":{cr1:{x:336,y:83},h1:{x:2362,y:507},m1:{x:1008,y:205},m2:{x:1008,y:411},s1:{x:0,y:0},t1:{x:672,y:144},t2:{x:672,y:350},t3:{x:1354,y:258},t4:{x:1354,y:398},t5:{x:1354,y:538},t6:{x:2026,y:446},x1:{x:1690,y:319},x2:{x:1690,y:525}},"status-pedido":{c1:{x:672,y:196},h1:{x:2016,y:174},http1:{x:1008,y:65},s1:{x:0,y:52},sw1:{x:1344,y:148},t1:{x:336,y:135},t2:{x:1344,y:0},t3:{x:1680,y:113},t4:{x:1680,y:253},t5:{x:1008,y:301}},"triagem-inteligente":{c1:{x:672,y:381},h1:{x:2352,y:455},ra1:{x:1008,y:241},s1:{x:0,y:237},t1:{x:336,y:320},t2:{x:1344,y:0},t3:{x:1344,y:206},t4:{x:1344,y:346},t5:{x:1344,y:486},t6:{x:2016,y:394},x1:{x:1680,y:61},x2:{x:1680,y:267},x3:{x:1680,y:473},x4:{x:1680,y:679}},"ura-reversa-spot":{h1:{x:1008,y:109},m1:{x:336,y:83},s1:{x:0,y:0},t1:{x:672,y:48},t2:{x:672,y:188}}};function O0(e){let t=nS[e.id];if(t==null)return e;return{...e,editorState:{...e.editorState,nodes:e.editorState.nodes.map((n)=>{let r=t[n.id];return r==null?n:{...n,position:{...r}}})}}}var rS=[zv,Bv,Jv,qv,Wv,tS,Vv,jv,Qv,Mv,eS,Kv,Lv,Xv,Zv,Uv,Hv,Fv,Gv,Yv].map((e)=>O0(e));var cu="desk:";function ua(e){let t=e.trim();if(!t.startsWith(cu))return{kind:"plain"};let n=t.slice(cu.length);if(n.includes("{{"))return{kind:"template"};let r;try{r=Nt.fromString(n,W.attendants)}catch{return{kind:"invalid"}}try{return{kind:"desk",attendantId:r.toUUID(),publicId:n}}catch{return{kind:"desk",attendantId:null,publicId:n}}}var oS=[{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"}]}],iS="vars",aS="counters",lu=new Set([...oS.map((e)=>e.nodeVarName),Bi,iS,aS].map((e)=>e.split(".")[0]));function du(e){return lu.has(e)}var cS={tell:new Set(["audio"]),menu:new Set(["audio","voiceTimeout"]),capture:new Set(["audio","voiceMethod","minDigits","maxDigits","terminators","voiceTimeout","listen","processing_audio","retryAudio"])},lS={tell:new Set(["content"]),menu:new Set(["text","invalidMessage"]),capture:new Set(["text","validation","invalidMessage"])};function uu(e,t,n,r){let o=e.filter((d)=>d.type==="start"),i=K0(t),a=o[0]?.id,s=c1(e,t),c=[...j0(o),...V0(e,t),...q0(e,i,a),...B0(e),...H0(e),...W0(e),...G0(e),...Z0(e),...Y0(e),...Q0(e),...e1(e),...t1(e,t,n),...o1(e,i,a),...i1(e),...a1(e),...s1(e,n,r?.disabledModules),...r?.entities!=null?Kd(e,r.entities):[],...r?.externalEntities!=null?qd(e,r.externalEntities):[],...l1(e,n,s),...u1(e),...m1(e),...p1(e),...r?.mediaProfile!=null?L0(e,t,r.mediaProfile):[]];if(s!=null)return f1(c,e,s);return c}function L0(e,t,n){let r=e.find((s)=>s.type==="start");if(r==null)return[];let o=new Map;for(let s of t){let c=o.get(s.source)??new Map;c.set(s.sourceHandle,s.target),o.set(s.source,c)}let i=qc(r.id,n.profile,e,o,n.recordingEnabled),a=[];for(let s of e){let c=i[s.id];if(c==null||!z0(s.type))continue;let u=F0(s.type,c).filter((m)=>m.value.kind==="indeterminate");if(u.length>0)a.push({nodeId:s.id,severity:"warning",messageKey:"editor:validation.mediaStateIndeterminate",params:{label:s.label,fields:u.map((m)=>m.name).join(", "),paths:u.map((m)=>U0(m.value)).join("; ")}});if(s.type==="transcription"&&c.transcriptionEnabled.kind==="known"&&c.transcriptionEnabled.value&&c.recordingEnabled.kind==="known"&&!c.recordingEnabled.value)a.push({nodeId:s.id,severity:"warning",messageKey:"editor:validation.transcriptionWithoutRecording",params:{label:s.label}})}return a}function z0(e){return e==="recording"||e==="transcription"||e==="analysis"}function F0(e,t){if(e==="recording")return[{name:"recording",value:t.recordingEnabled},{name:"sampling",value:t.samplingPercentage}];if(e==="transcription")return[{name:"recording",value:t.recordingEnabled},{name:"transcription",value:t.transcriptionEnabled},{name:"language",value:t.transcriptionLanguage},{name:"minimum_duration",value:t.transcriptionMinDurationSeconds},{name:"anonymization",value:t.anonymizeEnabled}];return[{name:"transcription",value:t.transcriptionEnabled},{name:"speech_analytics",value:t.speechAnalyticsEnabled},{name:"sentiment",value:t.sentimentEnabled},{name:"topics",value:t.topicDetectionTopics},{name:"intents",value:t.intentDetectionIntents},{name:"structured_analysis",value:t.structuredAnalysisEnabled},{name:"analysis_ids",value:t.structuredAnalysisIds}]}function U0(e){if(e.kind==="known")return"";return e.branches.map((t)=>t.viaNodeLabel).join(", ")}function j0(e){if(e.length===0)return[{nodeId:"",severity:"error",messageKey:"editor:validation.noStart"}];return e.slice(1).map((t)=>({nodeId:t.id,severity:"error",messageKey:"editor:validation.multipleStart"}))}function V0(e,t){let n=new Set(e.filter((r)=>r.type==="start").map((r)=>r.id));return t.filter((r)=>n.has(r.source)&&r.sourceHandle!=="voice"&&r.sourceHandle!=="chat").map((r)=>({nodeId:r.source,severity:"error",messageKey:"editor:validation.startEdgeHandle",params:{handle:r.sourceHandle}}))}function K0(e){let t=new Map;for(let n of e){let r=t.get(n.source)??[];r.push(n.target),t.set(n.source,r)}return t}function q0(e,t,n){if(n===void 0)return[];let r=new Set([n]),o=[n];while(o.length>0){let a=o.pop();for(let s of t.get(a)??[])if(!r.has(s))r.add(s),o.push(s)}let i=[];for(let a of e)if(a.type!=="start"&&!r.has(a.id))i.push({nodeId:a.id,severity:"warning",messageKey:"editor:validation.unreachable",params:{label:a.label}});return i}function B0(e){let t=[];for(let n of e){if(!Object.hasOwn(vt,n.type)){t.push({nodeId:n.id,severity:"error",messageKey:"editor:validation.unknownNodeType",params:{label:n.label,type:n.type}});continue}let r=vt[n.type],o=r.configSchema.safeParse(n.config),i=o.success?o.data:n.config,a=o.success?r.configSchema.safeParse(i):o;if(a.success)continue;for(let s of a.error.issues){let c=s.message.startsWith("editor:")?s.message:"editor:validation.invalidField";t.push({nodeId:n.id,severity:"error",messageKey:c,params:{label:n.label,field:s.path.join(".")}})}}return t}function _o(e){let t=[];for(let n of e){if(n.type!=="transfer")continue;let r=vt.transfer.configSchema.safeParse(n.config);if(!r.success)continue;t.push({node:n,destinations:r.data.destinations,attachedData:r.data.attachedData})}return t}function H0(e){let t=[];for(let{node:n,destinations:r}of _o(e)){if(r.some((o)=>o.trim()!==""))continue;t.push({nodeId:n.id,severity:"error",messageKey:"editor:validation.noDestinations",params:{label:n.label}})}return t}function W0(e){let t=[];for(let{node:n,destinations:r,attachedData:o}of _o(e)){let i=[...r.map((a,s)=>({field:`destinations.${s}`,template:a})),...o.map((a)=>({field:a.key,template:a.value}))];for(let{field:a,template:s}of i){if(Gc(s).valid)continue;t.push({nodeId:n.id,severity:"error",messageKey:"editor:validation.invalidTemplateSyntax",params:{label:n.label,field:a}})}}return t}function G0(e){let t=[];for(let{node:n,destinations:r}of _o(e))r.forEach((o,i)=>{if(!/\s/.test(o.trim()))return;t.push({nodeId:n.id,severity:"error",messageKey:"editor:validation.destinationHasSpace",params:{label:n.label,field:`destinations.${i}`}})});return t}function Z0(e){let t=[];for(let{node:n,destinations:r}of _o(e))r.forEach((o,i)=>{if(ua(o).kind!=="invalid")return;t.push({nodeId:n.id,severity:"error",messageKey:"editor:validation.invalidDeskDestination",params:{label:n.label,field:`destinations.${i}`}})});return t}function Y0(e){let t=[];for(let n of e){if(n.type!=="enterQueue"&&n.type!=="queryQueue")continue;let r=n.config.queue_id,o=typeof r==="string"?r.trim():"";if(o.includes("{{")||J0(o))continue;t.push({nodeId:n.id,severity:"error",messageKey:"editor:validation.invalidQueueId",params:{label:n.label,field:"queue_id"}})}return t}function J0(e){try{return Nt.fromString(e,W.queues).toUUID(),!0}catch{return!1}}var X0=new Set(["httpRequest","webhook"]);function Q0(e){let t=[];for(let n of e){if(!X0.has(n.type))continue;let r=typeof n.config.body==="string"?n.config.body:"";if(r.trim()==="")continue;let o=Hc(r,()=>'"__tpl__"');try{JSON.parse(o)}catch{t.push({nodeId:n.id,severity:"warning",messageKey:"editor:validation.invalidJson",params:{label:n.label}})}}return t}function e1(e){return Wi(e).misplaced.map((t)=>({nodeId:t.nodeId,severity:"error",messageKey:"editor:validation.secretFieldNotAllowed",params:{label:t.label,field:t.field,secret:t.name}}))}function t1(e,t,n){let r=new Set(t.map((i)=>i.source)),o=[];for(let i of e){if(!Object.hasOwn(n,i.type))continue;let a=n[i.type];if(Mn(a,i.config).length===0)continue;if(r.has(i.id))continue;o.push({nodeId:i.id,severity:"warning",messageKey:"editor:validation.noOutputConnection",params:{label:i.label}})}return o}function n1(e){if(e.type!=="counter")return!1;let t=e.config.action??"increment",n=e.config.limit;return t==="increment"&&typeof n==="number"&&n>0}function r1(e,t){let n=new Set([e]),r=[e];for(let o=r.pop();o!==void 0;o=r.pop())for(let i of t.get(o)??[])if(!n.has(i))n.add(i),r.push(i);return n}function o1(e,t,n){if(n===void 0)return[];let r=new Map(e.map((_)=>[_.id,_])),o=(_)=>{let E=r.get(_);return E!==void 0&&n1(E)},i=r1(n,t),a=0,s=1,c=2,d=new Map;for(let _ of e)d.set(_.id,a);let u=new Set;function m(_){d.set(_,s);for(let E of o(_)?[]:t.get(_)??[])if(d.get(E)===s)u.add(E);else if(d.get(E)===a)m(E);d.set(_,c)}for(let _ of i)if(d.get(_)===a)m(_);let y=[];for(let _ of u){let E=r.get(_);if(E===void 0)continue;if(!(typeof E.config.maxAttempts==="number"&&E.config.maxAttempts>0))y.push({nodeId:_,severity:"error",messageKey:"editor:validation.infiniteCycle",params:{label:E.label}})}return y}function i1(e){let t=new Map,n=[];for(let r of e)if(t.get(r.varName)!==void 0)n.push({nodeId:r.id,severity:"error",messageKey:"editor:validation.duplicateVarName",params:{label:r.label,varName:r.varName}});else t.set(r.varName,r.id);return n}function a1(e){return e.filter((t)=>du(t.varName)).map((t)=>({nodeId:t.id,severity:"error",messageKey:"editor:validation.reservedVarName",params:{label:t.label,varName:t.varName}}))}function s1(e,t,n){if(n==null||n.size===0)return[];let r=[];for(let o of e){if(!Object.hasOwn(t,o.type))continue;let i=t[o.type];if(i.module!=="core"&&n.has(i.module))r.push(sS(o,i.module))}if(n.has("desk")){for(let{node:o,destinations:i}of _o(e))if(i.some((a)=>ua(a).kind!=="plain"))r.push(sS(o,"desk"))}return r}function sS(e,t){return{nodeId:e.id,severity:"warning",messageKey:"editor:validation.moduleDisabled",params:{label:e.label,module:t}}}function c1(e,t){let n=e.find((i)=>i.type==="start");if(n==null)return null;let r=new Map;for(let i of t){let a=r.get(i.source);if(a==null)a=new Map,r.set(i.source,a);a.set(i.sourceHandle,i.target)}let o=new Set;for(let i of e)if(i.type==="channelRouter")o.add(i.id);return jd(n.id,r,e.map((i)=>i.id),o.size>0?o:void 0)}function l1(e,t,n){if(n==null)return[];let r=[];for(let o of e){if(o.type==="start")continue;if(!Object.hasOwn(t,o.type))continue;let i=t[o.type],a=n[o.id];if(a==null||a==="unreachable"||a==="converged")continue;if(i.channel==="voice"&&a==="chat-only")r.push({nodeId:o.id,severity:"error",messageKey:"editor:validation.voiceNodeInChatBranch",params:{label:o.label}});if(i.channel==="chat"&&a==="voice-only")r.push({nodeId:o.id,severity:"error",messageKey:"editor:validation.chatNodeInVoiceBranch",params:{label:o.label}})}return r}var d1={retellAgent:{agentField:"agent_id",agentMessageKey:"editor:validation.voiceAgentAgentRequired"},vapiAgent:{agentField:"assistant_id",agentMessageKey:"editor:validation.voiceAgentAssistantRequired"},elevenlabsAgent:{agentField:"agent_id",agentMessageKey:"editor:validation.voiceAgentAgentRequired"},openaiLiveAgent:{agentField:"agent_id",agentMessageKey:"editor:validation.openaiLiveAgentRequired"}};function u1(e){let t=[];for(let n of e){let r=d1[n.type];if(r===void 0)continue;let o=n.config.connector_id;if(typeof o!=="string"||o==="")t.push({nodeId:n.id,severity:"error",messageKey:"editor:validation.voiceAgentConnectorRequired",params:{label:n.label}});let i=n.config[r.agentField];if(typeof i!=="string"||i==="")t.push({nodeId:n.id,severity:"error",messageKey:r.agentMessageKey,params:{label:n.label}})}return t}function p1(e){return e.filter((t)=>t.type==="timeRouting").filter((t)=>t.config.scheduleId===void 0||t.config.scheduleId==="").map((t)=>({nodeId:t.id,severity:"warning",messageKey:"editor:validation.timeRoutingWithoutSchedule",params:{label:t.label}}))}function m1(e){let t=[];for(let n of e){if(n.type!=="openaiLiveAgent")continue;let r=mo.shape.output_fields.safeParse(n.config.output_fields);if(!r.success)continue;let o=new Set;for(let i of r.data){let a=po.test(i.name)&&!o.has(i.name);if(o.add(i.name),a)continue;t.push({nodeId:n.id,severity:"error",messageKey:"editor:validation.openaiLiveOutputFieldInvalid",params:{label:n.label,name:i.name}})}}return t}function f1(e,t,n){let r=new Map(t.map((o)=>[o.id,o.type]));return e.filter((o)=>{let i=o.params?.field;if(i==null||o.nodeId==="")return!0;let a=r.get(o.nodeId);if(a==null)return!0;let s=n[o.nodeId];if(s==null||s==="converged"||s==="unreachable")return!0;let c=i.split(".")[0];if(s==="chat-only"&&cS[a]?.has(c))return!1;if(s==="voice-only"&&lS[a]?.has(c))return!1;return!0})}function pu(e){return e.every((t)=>t.severity!=="error")}var pa="niva-webchat",ma=1;var at={source:I(pa),v:I(ma)},dS=["chat","form","consent","ended","closed"],mu=P(dS),y1=ie(l(),pt()),_1=g({prechat:g({enabled:F(),fields:g({name:F(),email:F(),phone:F()})}),consent:g({enabled:F(),privacy_url:l().optional()})}),b1=g({layout:P(["bubble","side","inline"]),side:P(["left","right"]),label:l().max(pn.label.max),teaser:l().max(pn.teaser.max)}),v1=Re("type",[g({...at,type:I("open")}),g({...at,type:I("close")}),g({...at,type:I("send"),text:l()}),g({...at,type:I("set_context"),context:ie(l(),pt())}),g({...at,type:I("identify"),token:l()}),g({...at,type:I("shutdown")}),g({...at,type:I("preview"),appearance:y1,scene:mu,visitor:_1,launcher:b1})]),S1=Re("type",[g({...at,type:I("ready")}),g({...at,type:I("opened")}),g({...at,type:I("closed")}),g({...at,type:I("unread"),count:f().int().min(0)}),g({...at,type:I("ended")}),g({...at,type:I("request_close")})]),x1=g({...at,type:I("preview_scene"),scene:mu});var E1=P(["image","audio","video","document"]),w1=g({type:I("text"),text:l().min(1)}),C1=g({type:I("location"),lat:f(),lng:f()}),A1=g({type:I("button_reply"),button_id:l().min(1),button_text:l()}),T1=g({type:I("list_reply"),list_id:l().min(1),list_title:l()}),R1=g({type:I("command"),command:l().min(1),args:l().optional()}),I1=g({type:I("media"),media_id:l().regex(/^media_[0-7][0-9a-hjkmnp-tv-z]{25}$/),caption:l().max(4000).optional()}),uS=Re("type",[w1,C1,A1,T1,R1,I1]),N1=g({title:l().min(1),description:l().optional(),image_url:l().optional(),buttons:z(yr).default([])}),O1=g({type:I("text"),text:l().min(1),markdown:F().optional()}),k1=g({type:I("media"),media_type:E1,url:l().min(1),caption:l().optional()}),D1=g({type:I("location"),lat:f(),lng:f(),label:l().optional()}),P1=g({type:I("buttons"),text:l().min(1),buttons:z(yr).min(1)}),$1=g({type:I("list"),text:l().min(1),button_text:l().min(1),sections:z(ea).min(1)}),M1=g({type:I("carousel"),cards:z(N1).min(1)}),L1=g({type:I("template"),template_id:l().min(1),params:ie(l(),l()).default({})}),pS=Re("type",[O1,k1,D1,P1,$1,M1,L1]);var z1=g({type:I("message"),message:uS}),F1=g({type:I("typing")}),U1=g({type:I("ping")}),j1=g({type:I("resume"),last_seq:f().int().min(0)}),V1=g({type:I("start")}),K1=Re("type",[z1,F1,U1,j1,V1]),mS=g({type:I("connected"),seq:f().int(),ts:f(),session_id:l()}),fS=g({type:I("message"),seq:f().int(),ts:f(),id:l(),message:pS,nodeId:l().optional()}),gS=g({type:I("typing"),seq:f().int(),ts:f(),active:F()}),hS=g({type:I("state"),seq:f().int(),ts:f(),status:P(["active","waiting_input","ended"])}),yS=g({type:I("trace"),seq:f().int(),ts:f(),currentNodeId:l(),variables:ie(l(),l()),status:P(["active","waiting_input","ended"]),truncated:F(),step:da.optional()}),_S=g({type:I("error"),seq:f().int(),ts:f(),code:l(),message:l()}),bS=g({type:I("pong"),seq:f().int(),ts:f()}),q1=Re("type",[mS,fS,gS,hS,yS,_S,bS]),B1=g({type:I("replay"),seq:f().int(),ts:f(),messages:z(q1)}),H1=Re("type",[mS,fS,gS,hS,yS,_S,bS,B1]);var fa=c_([I(W.signals),I("_"),l()]),W1=c_([I(W.visual_plans),I("_"),l()]),G1=["volume","answered","busy","no_answer","failed","outcome","duration","ai_cost","flow_errors"],Z1=["answered","busy","no_answer","failed"],Y1=["number","trend","compare","distribution","weekday_hour"],J1=["plan_version","plan","hour_of_day","weekday","channel"];var q9=Be([I(1),I(2),I(3),I(4)]).describe("Pinned-card column span (1-4). Null means the default for the query shape.");var X1=["today","yesterday","last_7_days","last_30_days","this_month","last_month"],Q1=["voice","chat"],eD=Be([g({preset:P(X1)}),g({date_from:l(),date_to:l()}),g({last_days:f().int().min(1).max(366)})]),tD=Re("kind",[g({kind:I("calls"),measure:P(G1),value:P(Z1).optional()}),g({kind:I("signal"),signal_id:fa,value:l().optional()})]),nD=Be([P(J1),g({signal_id:fa})]),rD=g({subject:tD,shape:P(Y1),compare_by:nD.optional(),period:eD,channel:P(Q1).optional(),plan_id:W1.optional()}),oD=g({id:fa,name:l(),question:l(),kind:P(["yes_no","choice","scale"]),options:z(g({key:l(),label:l()})).optional(),levels:z(l()).optional(),higher_is:P(fo).optional()}),B9=g({org_id:l(),signals:z(oD)}),bo=g({answered:f().int(),no_answer:f().int().nullable(),not_evaluated:f().int().nullable()}),iD=g({shape:I("number"),value:f(),n:f().int(),dist:z(g({key:l(),label:l(),value:f()})).optional(),rate:f().nullable(),low:f().nullable(),high:f().nullable(),previous:g({value:f(),rate:f().nullable(),low:f().nullable(),high:f().nullable()}).nullable(),change:P(["up","down","stable"]).nullable(),denominator:bo}),SS=g({bucket:l(),value:f(),n:f().int(),low:f().nullable(),high:f().nullable(),small:F()}),aD=g({date:l(),label:l()}),sD=g({key:l(),label:l(),points:z(SS)}),cD=g({shape:I("trend"),granularity:P(["day","hour"]),points:z(SS),series:z(sD).optional(),plan_versions:z(aD),denominator:bo}),lD=g({key:l(),label:l().nullable(),version:f().int().nullable().optional(),value:f(),n:f().int(),low:f().nullable(),high:f().nullable(),small:F(),dist:z(g({key:l(),label:l(),value:f()})).optional()}),dD=g({shape:I("compare"),rows:z(lD),denominator:bo}),uD=g({key:l(),label:l(),value:f(),n:f().int()}),pD=g({shape:I("distribution"),rows:z(uD),denominator:bo}),mD=g({weekday:f().int(),hour:f().int(),value:f(),n:f().int(),low:f().nullable(),high:f().nullable()}),fD=g({shape:I("weekday_hour"),cells:z(mD),denominator:bo}),H9=Re("shape",[iD,cD,dD,pD,fD]),vS=g({rate:f(),low:f(),high:f()}),gD=g({signal_id:fa,kind:P(["yes_no","choice","scale"]),name:l(),question:l(),alert_label:l().nullable(),alert_below:F(),higher_is:P(fo).nullable(),n:f().int(),value:f().nullable(),rate:f().nullable(),low:f().nullable(),high:f().nullable(),distribution:z(g({key:l(),label:l(),value:f()})),series:z(g({bucket:l(),value:f(),n:f().int()})),alert_share:vS.nullable(),previous_share:vS.nullable(),in_alert:F()}),W9=g({cards:z(gD)}),hD=g({strategy:l(),model:l(),ms:f(),input_tokens:f(),output_tokens:f()}),G9=g({query:rD.nullable(),confidence:f(),period_explicit:F(),meta:hD});var vo="x-niva-cli-command";function xS(e){return e[0]??{}}function Fn(e){return Array.isArray(e)?e:e===void 0||e===null?[]:[e]}var fu=4300,yD=/^-?(?:0|[1-9]\d*)$/;function ES(e,t){if((e.startsWith("-")?e.length-1:e.length)>t||!yD.test(e))return;return BigInt(e)}var gu="orpc",_D="@orpc/shared",bD="1.16.1";class hu extends Error{constructor(...e){super(...e);this.name="AbortError"}}function yu(e){let t;return()=>{if(t)return t.result;let n=e();return t={result:n},n}}function vD(e){let t=Promise.resolve();return(...n)=>t=t.catch(()=>{}).then(()=>e(...n))}var SD=2,xD=`__${_D}@${bD}/otel/config__`;function So(){return globalThis[xD]}function ga(e,t={},n){return So()?.tracer?.startSpan(e,t,n)}function gn(e,t,n={}){if(!e)return;let r=ED(t);if(e.recordException(r),!n.signal?.aborted||n.signal.reason!==t)e.setStatus({code:SD,message:r.message})}function ED(e){if(e instanceof Error){let t={message:e.message,name:e.name,stack:e.stack};if("code"in e&&(typeof e.code==="string"||typeof e.code==="number"))t.code=e.code;return t}return{message:String(e)}}async function Un({name:e,context:t,...n},r){let o=So()?.tracer;if(!o)return r();let i=async(a)=>{try{return await r(a)}catch(s){throw gn(a,s,n),s}finally{a.end()}};if(t)return o.startActiveSpan(e,n,t,i);else return o.startActiveSpan(e,n,i)}async function zn(e,t){let n=So();if(!e||!n)return t();let r=n.trace.setSpan(n.context.active(),e);return n.context.with(r,t)}function Jt(e){if(!e||typeof e!=="object")return!1;return"next"in e&&typeof e.next==="function"&&Symbol.asyncIterator in e&&typeof e[Symbol.asyncIterator]==="function"}var wD=Symbol.for("asyncDispose"),CD=Symbol.asyncDispose??wD;class jn{#e=!1;#t=!1;#n;#r;constructor(e,t){this.#n=t,this.#r=vD(async()=>{if(this.#e)return{done:!0,value:void 0};try{let n=await e();if(n.done)this.#e=!0;return n}catch(n){throw this.#e=!0,n}finally{if(this.#e&&!this.#t)this.#t=!0,await this.#n("next")}})}next(){return this.#r()}async return(e){if(this.#e=!0,!this.#t)this.#t=!0,await this.#n("return");return{done:!0,value:e}}async throw(e){if(this.#e=!0,!this.#t)this.#t=!0,await this.#n("throw");throw e}async[CD](){if(this.#e=!0,!this.#t)this.#t=!0,await this.#n("dispose")}[Symbol.asyncIterator](){return this}}function _u({name:e,...t},n){let r;return new jn(async()=>{r??=ga(e);try{let o=await zn(r,()=>n.next());return r?.addEvent(o.done?"completed":"yielded"),o}catch(o){throw gn(r,o,t),o}},async(o)=>{try{if(o!=="next")await zn(r,()=>n.return?.())}catch(i){throw gn(r,i,t),i}finally{r?.end()}})}function xo(e,t,n){let r=(o,i)=>{let a=e[i];if(!a)return n(o);return a({...o,next:(s=o)=>r(s,i+1)})};return r(t,0)}function Eo(e){if(!e)return;return JSON.parse(e)}function Vn(e){return JSON.stringify(e)}function wS(e){if(!zt(e))return null;return Object.getPrototypeOf(e)?.constructor}function wo(e){if(!e||typeof e!=="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||!t||!t.constructor}function zt(e){return!!e&&(typeof e==="object"||typeof e==="function")}function AD(e,t,n){if(t==="__proto__")Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0});else e[t]=n}function bu(e,t,n){let r=e[t];if(r!==n)return r;let o;if(Array.isArray(r))o=r.slice();else if(wo(r))o={...r};else return r;return AD(e,t,o),o}function Co(e,...t){if(typeof e==="function")return e(...t);return e}function vu(e){return new Proxy(e,{get(t,n,r){let o=Reflect.get(t,n,r);if(n!=="then"||typeof o!=="function")return o;return new Proxy(o,{apply(i,a,s){if(s.length!==2||s.some((d)=>!RD(d)))return Reflect.apply(i,a,s);let c=!0;s[0].call(a,vu(new Proxy(t,{get:(d,u,m)=>{if(c&&u==="then"){c=!1;return}return Reflect.get(d,u,m)}})))}})}})}var TD=/^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;function RD(e){return typeof e==="function"&&TD.test(e.toString())}var ID=/^[dgimsuvy]*$/;function CS(e){return ID.test(e)&&new Set(e).size===e.length&&!(e.includes("u")&&e.includes("v"))}function AS(e,t){let n,r=0,o=()=>{if(n===void 0)n=new RegExp(e,t),n.lastIndex=r;return n};return new Proxy(Object.create(RegExp.prototype),{get(i,a){if(a===Symbol.toStringTag)return"RegExp";if(n===void 0){if(a==="lastIndex")return r;if(!(a in RegExp.prototype))return}let s=o(),c=Reflect.get(s,a,s);return typeof c==="function"&&a!=="constructor"?c.bind(s):c},set(i,a,s){if(n===void 0&&a==="lastIndex")return r=s,!0;let c=o();return Reflect.set(c,a,s,c)},has(i,a){if(n===void 0)return a==="lastIndex"||a in RegExp.prototype;return Reflect.has(n,a)}})}function TS(e){try{return decodeURIComponent(e)}catch{return e}}var ND="@orpc/client",OD="1.16.1",RS=new Set(["bind","valueOf","toString","toJSON"]),ya={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 kD(e,t){return t??ya[e]?.status??500}function DD(e,t){return t||ya[e]?.message||e}var ha;class Kn extends Error{defined;code;status;data;static{let e=Symbol.for(`__${ND}@${OD}/error/ORPC_ERROR_CONSTRUCTORS__`);globalThis[e]??=new WeakSet,ha=globalThis[e],ha.add(Kn)}constructor(e,...t){let n=xS(t);if(n.status!==void 0&&!_a(n.status))throw Error("[ORPCError] Invalid error status code.");let r=DD(e,n.message);super(r,n);this.code=e,this.status=kD(e,n.status),this.defined=n.defined??!1,this.data=n.data}toJSON(){return{defined:this.defined,code:this.code,status:this.status,message:this.message,data:this.data}}static[Symbol.hasInstance](e){if(ha.has(this)){let t=wS(e);if(t&&ha.has(t))return!0}return super[Symbol.hasInstance](e)}}function IS(e){return e instanceof Kn?e:new Kn("INTERNAL_SERVER_ERROR",{message:"Internal server error",cause:e})}function _a(e){return e<200||e>=400}function Su(e){if(!wo(e))return!1;let t=["defined","code","status","message","data"];if(Object.keys(e).some((n)=>!t.includes(n)))return!1;return"defined"in e&&typeof e.defined==="boolean"&&"code"in e&&typeof e.code==="string"&&"status"in e&&typeof e.status==="number"&&_a(e.status)&&"message"in e&&typeof e.message==="string"}function xu(e,t={}){return new Kn(e.code,{...t,...e})}class Ao extends TypeError{}class NS extends TypeError{}class Xt extends Error{data;constructor(e){super(e?.message??"An error event was received",e);this.data=e?.data}}var PD=/\r\n|\r(?!\n)|\n/,$D=/(?:\r\n|\r(?!\n)|\n){2}/,MD=/(?:\r\n|\r(?!\n)|\n){2}/g,LD=13,zD=10,FD=32;function UD(e){let t={data:void 0,event:void 0,id:void 0,retry:void 0,comments:[]};for(let n of e.split(PD)){if(n==="")continue;let r=n.indexOf(":"),o=r===-1?"":n.slice(n.charCodeAt(r+1)===FD?r+2:r+1);if(r===0){t.comments.push(o);continue}switch(r===-1?n:n.slice(0,r)){case"data":t.data=t.data===void 0?o:`${t.data}
|
|
92
|
-
${o}`;break;case"event":t.event=o;break;case"id":t.id=o;break;case"retry":{let i=Number.parseInt(o,10);if(i>=0&&i.toString()===o)t.retry=i;break}}}return t}class
|
|
85
|
+
`)}return V.write("payload.value = newResult;"),V.write("return payload;"),V.compile()},a,s=rr,c=!rt.jitless,u=c&&Mm.value,m=t.catchall,y;e._zod.parse=(_,E)=>{y??(y=r.value);let k=_.value;if(!s(k))return _.issues.push({expected:"object",code:"invalid_type",input:k,inst:e}),_;if(c&&u&&E?.async===!1&&E.jitless!==!0){if(!a)a=i(t.shape);if(_=a(_,E),!m)return _;return Bg([],k,_,E,y,e,E?.abortEarly===!0)}return n(_,E)}});function eg(e,t,n,r){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let o=e.filter((i)=>!Nt(i));if(o.length===1)return t.value=o[0].value,o[0];return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((i)=>i.issues.map((a)=>kt(a,r,ot())))}),t}var Ds=w("$ZodUnion",(e,t)=>{de.init(e,t),te(e,"optin",(r)=>r.def.options.some((o)=>o._zod.optin==="defaulted")?"defaulted":r.def.options.some((o)=>o._zod.optin!==void 0)?"optional":void 0),te(e,"optout",(r)=>r.def.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),te(e,"values",(r)=>{if(r.def.options.every((o)=>o._zod.values))return new Set(r.def.options.flatMap((o)=>Array.from(o._zod.values)));return}),te(e,"pattern",(r)=>{if(r.def.options.every((o)=>o._zod.pattern)){let o=r.def.options.map((i)=>i._zod.pattern);return new RegExp(`^(${o.map((i)=>ln(i.source)).join("|")})$`)}return});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,o)=>{if(n)return n(r,o);let i=!1,a=[];for(let s of t.options){let c=s._zod.run({value:r.value,issues:[]},o);if(c instanceof Promise)a.push(c),i=!0;else{if(c.issues.length===0)return c;a.push(c)}}if(!i)return eg(a,r,e,o);return Promise.all(a).then((s)=>eg(s,r,e,o))}});function CT(e){let t=new Map;for(let n of e.options){let r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let o of r)if(t.has(o)){if(o!==void 0)throw Error(`Duplicate discriminator value "${String(o)}"`);t.set(o,null)}else t.set(o,n)}return t}var Wg=w("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Ds.init(e,t);let n=e._zod.parse;te(e,"propValues",(o)=>{let i={},a=0;for(let s of o.def.options){let c=s._zod.propValues;if(!c||Object.keys(c).length===0)throw Error(`Invalid discriminated union option at index "${o.def.options.indexOf(s)}"`);if(c[o.def.discriminator]?.has(void 0))a++;for(let[d,u]of Object.entries(c)){if(!Object.prototype.hasOwnProperty.call(i,d))lt(i,d,new Set);for(let m of u)i[d].add(m)}}if(!o.def.unionFallback&&a>1)i[o.def.discriminator]?.delete(void 0);return i}),t.options.forEach((o,i)=>{let a=Kr(o._zod.def);if(a&&!Object.prototype.hasOwnProperty.call(a,t.discriminator))throw Error(`Invalid discriminated union option at index "${i}"`)});let r=Vr(()=>CT(t));e._zod.parse=(o,i)=>{let a=o.value;if(!rr(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;let s=a?.[t.discriminator],c=r.value.get(s);if(c&&(s!==void 0||i.direction!=="backward"))return c._zod.run(o,i);if(t.unionFallback||i.direction==="backward")return n(o,i);return o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(r.value.keys()).filter((d)=>r.value.get(d)!==null),input:a,path:[t.discriminator],inst:e}),o}}),Gg=w("$ZodIntersection",(e,t)=>{de.init(e,t),e._zod.parse=(n,r)=>{let o=n.value,i=t.left._zod.run({value:o,issues:[]},r),a=t.right._zod.run({value:o,issues:[]},r);if(i instanceof Promise||a instanceof Promise)return Promise.all([i,a]).then(([c,d])=>tg(n,c,d));return tg(n,i,a)}});function Rs(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(Nn(e)&&Nn(t)){let n=Object.keys(t),r=Object.keys(e).filter((i)=>n.indexOf(i)!==-1),o={...e,...t};if(Object.prototype.hasOwnProperty.call(o,"__proto__"))delete o.__proto__;for(let i of r){if(i==="__proto__")continue;let a=Rs(e[i],t[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};o[i]=a.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let o=e[r],i=t[r],a=Rs(o,i);if(!a.valid)return{valid:!1,mergeErrorPath:[r,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function tg(e,t,n){let r=new Map,o,i=new Map,a=(d,u)=>{let m;if(d.code==="unrecognized_keys"&&!d.path?.length)o??(o=d),m=d.keys;else if(d.code==="invalid_key"&&d.origin==="record"&&d.path?.length===1){let y=String(d.path[0]);if(!i.has(y))i.set(y,d);m=[y]}else return!1;for(let y of m){if(!r.has(y))r.set(y,{});r.get(y)[u]=!0}return!0};for(let d of t.issues)if(!a(d,"l"))e.issues.push(d);for(let d of n.issues)if(!a(d,"r"))e.issues.push(d);let s=[...r].filter(([,d])=>d.l&&d.r).map(([d])=>d);if(s.length){let d=o?s.filter((u)=>o.keys.includes(u)):[];if(d.length)e.issues.push({...o,keys:d});for(let u of s)if(!d.includes(u)&&i.has(u))e.issues.push(i.get(u))}let c=Rs(t.value,n.value);if(!c.valid){if(Nt(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var Zg=w("$ZodRecord",(e,t)=>{de.init(e,t);let n=rt.memoizer;n?.attach(e),e._zod.parse=(r,o)=>{let i=r.value;if(!Nn(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),r;let a=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},o):{};let c=new Set;for(let u of s)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){if(c.add(typeof u==="number"?u.toString():u),u==="__proto__")continue;let m=t.keyType._zod.run({value:u,issues:[]},o);if(m instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(m.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:m.issues.map((E)=>kt(E,o,ot())),input:u,path:[u],inst:e});continue}let y=m.value;if(y==="__proto__")continue;let _=t.valueType._zod.run({value:i[u],issues:[]},o);if(_ instanceof Promise)a.push(_.then((E)=>{if(E.issues.length)r.issues.push(...dn(u,E.issues));r.value[y]=E.value}));else{if(_.issues.length)r.issues.push(...dn(u,_.issues));r.value[y]=_.value}}let d;for(let u in i)if(!c.has(u))if(t.mode==="loose"){if(u==="__proto__")continue;r.value[u]=i[u]}else d=d??[],d.push(u);if(d&&d.length>0)r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:d,continue:!0})}else{r.value=n?n.alloc(e,r,{},o):{};let c;for(let d of Reflect.ownKeys(i)){if(d==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(i,d))continue;let u=t.keyType._zod.run({value:d,issues:[]},o);if(u instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof d==="string"&&or.test(d)&&u.issues.length){let E=t.keyType._zod.run({value:Number(d),issues:[]},o);if(E instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(E.issues.length===0)u=E}if(u.issues.length){if(t.mode==="loose")r.value[d]=i[d];else if(s)c=c??[],c.push(d);else r.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map((E)=>kt(E,o,ot())),input:d,path:[d],inst:e});continue}let y=u.value;if(y==="__proto__")continue;let _=t.valueType._zod.run({value:i[d],issues:[]},o);if(_ instanceof Promise)a.push(_.then((E)=>{if(E.issues.length)r.issues.push(...dn(d,E.issues));r.value[y]=E.value}));else{if(_.issues.length)r.issues.push(...dn(d,_.issues));r.value[y]=_.value}}if(c&&c.length>0)r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:c,continue:!0})}if(a.length)return Promise.all(a).then(()=>r);return r}});var Yg=w("$ZodEnum",(e,t)=>{de.init(e,t);let n=Ur(t.entries),r=new Set(n);e._zod.values=r,te(e,"pattern",(o)=>{let i=Ur(o.def.entries).filter((a)=>Lm.has(typeof a));return new RegExp(i.length?`^(${i.map((a)=>Bt(a.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(o,i)=>{let a=o.value;if(r.has(a))return o;return o.issues.push({code:"invalid_value",values:n,input:a,inst:e}),o}}),Jg=w("$ZodLiteral",(e,t)=>{de.init(e,t);let n=new Set(t.values);e._zod.values=n,te(e,"pattern",(r)=>{let o=r.def.values;return new RegExp(o.length?`^(${o.map((i)=>typeof i==="string"?Bt(i):i?Bt(i.toString()):String(i)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(r,o)=>{let i=r.value;if(n.has(i))return r;return r.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),r}});var Xg=w("$ZodTransform",(e,t)=>{de.init(e,t),e._zod.optin="optional",rt.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new qr(e.constructor.name);let o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then((a)=>(n.value=a,n));if(o instanceof Promise)throw new Dt;return n.value=o,n}});function ng(e,t){return e.value=t.issues.length?void 0:t.value,e}var Ps=w("$ZodOptional",(e,t)=>{de.init(e,t),te(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",te(e,"values",(n)=>{let r=n.def.innerType._zod.values;return r?new Set([...r,void 0]):void 0}),te(e,"pattern",(n)=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${ln(r.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(n.value===void 0){if(t.innerType._zod.optin!=="defaulted")return n;let o=t.innerType._zod.run({value:n.value,issues:[]},r);if(o instanceof Promise)return o.then((i)=>ng(n,i));return ng(n,o)}return t.innerType._zod.run(n,r)}}),Qg=w("$ZodExactOptional",(e,t)=>{Ps.init(e,t),te(e,"values",(n)=>n.def.innerType._zod.values),te(e,"pattern",(n)=>n.def.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),eh=w("$ZodNullable",(e,t)=>{de.init(e,t),te(e,"optin",(n)=>n.def.innerType._zod.optin),te(e,"optout",(n)=>n.def.innerType._zod.optout),te(e,"pattern",(n)=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${ln(r.source)}|null)$`):void 0}),te(e,"values",(n)=>n.def.innerType._zod.values?new Set([...n.def.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>{if(n.value===null)return n;return t.innerType._zod.run(n,r)}}),th=w("$ZodDefault",(e,t)=>{de.init(e,t),e._zod.optin="defaulted",te(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;let o=t.innerType._zod.run(n,r);if(o instanceof Promise)return o.then((i)=>rg(i,t));return rg(o,t)}});function rg(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var nh=w("$ZodPrefault",(e,t)=>{de.init(e,t),e._zod.optin="defaulted",te(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)n.value=t.defaultValue;return t.innerType._zod.run(n,r)}}),rh=w("$ZodNonOptional",(e,t)=>{de.init(e,t),te(e,"values",(n)=>{let r=n.def.innerType._zod.values;return r?new Set([...r].filter((o)=>o!==void 0)):void 0}),e._zod.parse=(n,r)=>{let o=t.innerType._zod.run(n,r);if(o instanceof Promise)return o.then((i)=>og(i,e));return og(o,e)}});function og(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}function ig(e,t,n,r){if(!t.issues.length){if(e.value=t.value,t.memo)e.memo=!0;return e}return e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map((o)=>kt(o,r,ot()))},input:e.value}),e}var oh=w("$ZodCatch",(e,t)=>{de.init(e,t),te(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),te(e,"optout",(n)=>n.def.innerType._zod.optout),te(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let o=t.innerType._zod.run({value:n.value,issues:[]},r);if(o instanceof Promise)return o.then((i)=>ig(n,i,t,r));return ig(n,o,t,r)}});var ih=w("$ZodPipe",(e,t)=>{de.init(e,t),te(e,"values",(n)=>n.def.in._zod.values),te(e,"optin",(n)=>n.def.in._zod.optin),te(e,"optout",(n)=>n.def.out._zod.optout),te(e,"propValues",(n)=>n.def.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){let i=t.out._zod.run(n,r);if(i instanceof Promise)return i.then((a)=>fi(a,t.in,r));return fi(i,t.in,r)}let o=t.in._zod.run(n,r);if(o instanceof Promise)return o.then((i)=>fi(i,t.out,r));return fi(o,t.out,r)}});function fi(e,t,n){if(e.issues.some((r)=>r.code!=="unrecognized_keys"))return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},n)}var ah=w("$ZodReadonly",(e,t)=>{de.init(e,t),te(e,"propValues",(n)=>n.def.innerType._zod.propValues),te(e,"values",(n)=>n.def.innerType._zod.values),te(e,"optin",(n)=>n.def.innerType?._zod?.optin),te(e,"optout",(n)=>n.def.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let o=t.innerType._zod.run(n,r);if(o instanceof Promise)return o.then(ag);return ag(o)}});function ag(e){if(!e.memo)e.value=Object.freeze(e.value);return e}function AT(e){let t=e._zod.def,n=t.pattern,r=!!t.format?.includes("int"),o,i;for(let s of t.checks??[]){let c=s._zod.def;if(c.pattern)n=c.pattern;r||(r=!!c.format?.includes("int"));let d=c.minimum??c.length,u=c.maximum??c.length;if(d!==void 0&&(o===void 0||d>o))o=d;if(u!==void 0&&(i===void 0||u<i))i=u}if(n)return n.source;if(o!==void 0&&i!==void 0&&o>i)return"(?!)";if(o!==void 0||i!==void 0)return kf({minimum:o,maximum:i}).source;let a=e._zod.pattern;return(r&&a===or?pi:a)?.source}function Is(e){let t=e._zod.def,n=e._zod.pattern?.source,r=t.innerType??e._zod.innerType;if(r){let o=r._zod.pattern?.source,i=Is(r);if(n&&o&&i&&i!==o)return n.replace(ln(o),()=>ln(i));return n}if(t.options){let o=t.options.map(Is);if(o.every(Boolean))return`^(${o.map((i)=>ln(i)).join("|")})$`}return AT(e)}var sh=w("$ZodTemplateLiteral",(e,t)=>{de.init(e,t);let n=[];for(let r of t.parts)if(typeof r==="object"&&r!==null){let o=Is(r);if(!o)throw Error(`Invalid template literal part, no pattern found: ${[...r._zod.traits].shift()}`);n.push(ln(o))}else if(r===null||zm.has(typeof r))n.push(Bt(`${r}`));else throw Error(`Invalid template literal part: ${r}`);e._zod.pattern=new RegExp(`^${n.join("")}$`),e._zod.parse=(r,o)=>{if(typeof r.value!=="string")return r.issues.push({input:r.value,inst:e,expected:"string",code:"invalid_type"}),r;if(e._zod.pattern.lastIndex=0,!e._zod.pattern.test(r.value))return r.issues.push({input:r.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),r;return r}});var ch=w("$ZodCustom",(e,t)=>{ze.init(e,t),de.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=(n)=>{let r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then((i)=>sg(i,n,r,e));sg(o,n,r,e);return}});function sg(e,t,n,r){if(!e){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};if(r._zod.def.params)o.params=r._zod.def.params;t.issues.push(kn(o))}}class dh extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}}var Ms="~memo",lh=[];function uh(e){return e!==null&&typeof e==="object"}function $s(e){return e.map((t)=>t.path?{...t,path:t.path.slice()}:{...t})}var ph=new WeakMap,Hr=0,Si=1,Wr=2;function xi(e,t,n){let r=ph.get(e);if(r!==void 0)return r?Wr:Hr;if(t.has(e))return Wr;t.add(e);let o=Hr,i=(u)=>{if(o!==Wr&&u?._zod){let m=xi(u,t,n);if(m>o)o=m}},a=(u,m)=>{let y=Hr;for(let _ of Reflect.ownKeys(u)){let E=Object.getOwnPropertyDescriptor(u,_);if(m&&!E.enumerable)continue;let k=E.get?Si:E.value?._zod?xi(E.value,t,n):Hr;if(k>y)y=k}return y},s=(u)=>{if(u>o)o=u},c=e._zod.def,d=c.type;switch(d){case"object":{let u=Kr(c);s(u?a(u,!0):Si),i(c.catchall);break}case"array":i(c.element);break;case"tuple":for(let u of c.items)i(u);i(c.rest);break;case"record":case"map":i(c.keyType),i(c.valueType);break;case"set":i(c.valueType);break;case"union":for(let u of c.options)i(u);break;case"intersection":i(c.left),i(c.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":i(c.innerType);break;case"pipe":i(c.in),i(c.out);break;case"function":i(c.input),i(c.output);break;case"lazy":{let u=c._cachedInner??(n?e._zod.innerType:void 0);s(u?xi(u,t,!1):Si);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let u in c){let m=Object.getOwnPropertyDescriptor(c,u);if(!m||m.get)continue;let y=m.value;if(!y||typeof y!=="object")continue;if(y._zod)i(y);else if(Array.isArray(y))for(let _ of y)i(_)}}return t.delete(e),TT(e,o)}function TT(e,t){if(t!==Si)ph.set(e,t===Wr);return t}function RT(e,t){let n=e.buckets.get(t);if(!n)n=new WeakMap,e.buckets.set(t,n);return n}var bi,vi=[],IT={alloc(e,t,n){let r=bi;if(!r)return n;bi=void 0;let o={value:n,issues:null};return r.set(t.value,o),vi.push(o),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let n=e._zod.parse,r=(o,i)=>{if(i.direction!=="backward"&&OT(i,o.value))throw new dh;return n(o,i)};if(e._zod.parse=r,e._zod.run===n)e._zod.run=r})},attach(e){var t;let n,r=!1,o,i;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let a=e._zod.parse,s=(c,d)=>{if(n===void 0){let G=xi(e,new Set,!1);if(G===Hr){if(e._zod.parse=a,e._zod.run===s)e._zod.run=a;return a(c,d)}if(G===Wr||r)n=!0;else r=!0}let u=c.value;if(!uh(u))return a(c,d);let m=d[Ms];if(!m)m={buckets:new WeakMap,backEdges:void 0},d[Ms]=m;let y;if(o===d)y=i;else y=RT(m,e),o=d,i=y;let _=y.get(u);if(_){if(c.value=_.value,_.issues){if(_.issues.length)c.issues.push(...$s(_.issues))}else c.memo=!0,m.backEdges??(m.backEdges=new WeakSet),m.backEdges.add(_.value);return c}bi=y;let E=vi.length,k=a(c,d);bi=void 0;let V=vi.length>E?vi.pop():void 0;if(k instanceof Promise)return k.then((G)=>{if(V)V.issues=G.issues.length?$s(G.issues):lh;return G});if(V)V.issues=k.issues.length?$s(k.issues):lh;return k};if(e._zod.parse=s,e._zod.run===a)e._zod.run=s})}};function Ls(){return IT}function OT(e,t){let n=e[Ms]?.backEdges;return n!==void 0&&uh(t)&&n.has(t)}var NT=()=>{let e={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 t(i){return e[i]??null}let n={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",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};function o(i,a){if(i==="number"&&typeof a==="number"&&!Number.isFinite(a))return String(a);return r[i]??i}return(i)=>{switch(i.code){case"invalid_type":{let a=o(i.expected),s=Km(i.input),c=o(s,i.input);return`Invalid input: expected ${a}, received ${c}`}case"invalid_value":if(i.values.length===1)return`Invalid input: expected ${ps(i.values[0])}`;return`Invalid option: expected one of ${ls(i.values,"|")}`;case"too_big":{let a=i.exact?"exactly ":i.inclusive?"<=":"<",s=t(i.origin);if(s)return`Too big: expected ${i.origin??"value"} to have ${a}${i.maximum.toString()} ${s.unit??"elements"}`;return`Too big: expected ${i.origin??"value"} to be ${a}${i.maximum.toString()}`}case"too_small":{let a=i.exact?"exactly ":i.inclusive?">=":">",s=t(i.origin);if(s)return`Too small: expected ${i.origin} to have ${a}${i.minimum.toString()} ${s.unit}`;return`Too small: expected ${i.origin} to be ${a}${i.minimum.toString()}`}case"invalid_format":{let a=i;if(a.format==="starts_with")return`Invalid string: must start with "${a.prefix}"`;if(a.format==="ends_with")return`Invalid string: must end with "${a.suffix}"`;if(a.format==="includes")return`Invalid string: must include "${a.includes}"`;if(a.format==="regex")return`Invalid string: must match pattern ${a.pattern}`;return`Invalid ${n[a.format]??i.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${i.divisor}`;case"unrecognized_keys":return`Unrecognized key${i.keys.length>1?"s":""}: ${ls(i.keys,", ")}`;case"invalid_key":return`Invalid key in ${i.origin}`;case"invalid_union":if(i.options&&Array.isArray(i.options)&&i.options.length>0)return`Invalid discriminator value. Expected ${i.options.map((s)=>`'${s}'`).join(" | ")}`;if(i.inclusive===!1)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${i.origin}`;default:return"Invalid input"}}};function zs(){return{localeError:NT()}}var mh;class fh{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==="object"&&"id"in n)this._idmap.set(n.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function gh(){return new fh}(mh=globalThis).__zod_globalRegistry??(mh.__zod_globalRegistry=gh());var un=globalThis.__zod_globalRegistry;function Ei(e){if(e.checks)e.checks=[...e.checks];return e}function hh(e,t){return new e(Ei({type:"string",...q(t)}))}function yh(e,t){return new e(Ei({type:"string",coerce:!0,...q(t)}))}function Fs(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...q(t)})}function _h(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...q(t)})}function bh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...q(t)})}function vh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...q(t)})}function Sh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...q(t)})}function xh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...q(t)})}function Us(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...q(t)})}function Eh(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...q(t)})}function wh(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...q(t)})}function Ch(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...q(t)})}function Ah(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...q(t)})}function Th(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...q(t)})}function Rh(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...q(t)})}function Ih(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...q(t)})}function Oh(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...q(t)})}function Nh(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...q(t)})}function kh(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...q(t)})}function Dh(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...q(t)})}function Ph(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...q(t)})}function $h(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...q(t)})}function Mh(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...q(t)})}function Lh(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...q(t)})}function wi(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...q(t)})}function Ci(e,t){return new e({type:"string",format:"date",check:"string_format",...q(t)})}function Ai(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...q(t)})}function Ti(e,t){return new e({type:"string",format:"duration",check:"string_format",...q(t)})}function zh(e,t){return new e(Ei({type:"number",checks:[],...q(t)}))}function Fh(e,t){return new e(Ei({type:"number",coerce:!0,checks:[],...q(t)}))}function Uh(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...q(t)})}function jh(e,t){return new e({type:"boolean",...q(t)})}function Vh(e,t){return new e({type:"boolean",coerce:!0,...q(t)})}function Kh(e,t){return new e({type:"bigint",coerce:!0,...q(t)})}function qh(e,t){return new e({type:"null",...q(t)})}function Bh(e){return new e({type:"unknown"})}function Hh(e,t){return new e({type:"never",...q(t)})}function Wh(e,t){return new e({type:"date",coerce:!0,...q(t)})}function ar(e,t){return new Cs({check:"less_than",...q(t),value:e,inclusive:!1})}function Ht(e,t){return new Cs({check:"less_than",...q(t),value:e,inclusive:!0})}function sr(e,t){return new As({check:"greater_than",...q(t),value:e,inclusive:!1})}function Wt(e,t){return new As({check:"greater_than",...q(t),value:e,inclusive:!0})}function Gr(e,t){return new zf({check:"multiple_of",...q(t),value:e})}function Ri(e,t){return new Uf({check:"max_length",...q(t),maximum:e})}function cr(e,t){return new jf({check:"min_length",...q(t),minimum:e})}function Ii(e,t){return new Vf({check:"length_equals",...q(t),length:e})}function js(e,t){return new Kf({check:"string_format",format:"regex",...q(t),pattern:e})}function Vs(e){return new qf({check:"string_format",format:"lowercase",...q(e)})}function Ks(e){return new Bf({check:"string_format",format:"uppercase",...q(e)})}function qs(e,t){return new Hf({check:"string_format",format:"includes",...q(t),includes:e})}function Bs(e,t){return new Wf({check:"string_format",format:"starts_with",...q(t),prefix:e})}function Hs(e,t){return new Gf({check:"string_format",format:"ends_with",...q(t),suffix:e})}function Gt(e){return new Zf({check:"overwrite",tx:e})}function Ws(e){return Gt((t)=>t.normalize(e))}function Gs(){return Gt((e)=>e.trim())}function Zs(){return Gt((e)=>e.toLowerCase())}function Ys(){return Gt((e)=>e.toUpperCase())}function Js(){return Gt((e)=>$m(e))}function Gh(e,t,n){return new e({type:"array",element:t,...q(n)})}function Zh(e,t,n){return new e({type:"custom",check:"custom",fn:t,...q(n)})}function Yh(e,t){let n=kT((r)=>(r.addIssue=(o)=>{if(typeof o==="string")r.issues.push(kn(o,r.value,n._zod.def));else{let i=o;if(i.fatal)i.continue=!1;if(i.code??(i.code="custom"),!("input"in i))i.input=r.value;i.inst??(i.inst=n),i.continue??(i.continue=!n._zod.def.abort),r.issues.push(kn(i))}},e(r.value,r)),t);return n}function kT(e,t){let n=new ze({check:"custom",...q(t)});return n._zod.check=e,n}function Zr(e,...t){for(let n of t)for(let r of Reflect.ownKeys(n))if(Object.prototype.propertyIsEnumerable.call(n,r))lt(e,r,n[r]);return e}function Jr(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??un,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function $e(e,t,n,r,o){let i=typeof t.unrepresentable==="function"?t.unrepresentable({zodSchema:e,path:r.path,message:o}):t.unrepresentable;if(i==="any")return!1;if(i===void 0||i==="throw")throw Error(o);return Object.assign(n,i),!0}function pe(e,t,n={path:[],schemaPath:[]}){var r;let o=e._zod.def,i=t.seen.get(e);if(i){if(i.count++,n.schemaPath.includes(e))i.cycle=n.path;return i.schema}let a={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,a),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)a.schema=s;else{let u={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,u);else{let y=a.schema,_=t.processors[o.type];if(!_)throw Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);_(e,t,y,u)}let m=e._zod.parent;if(m){if(!a.ref)a.ref=m;pe(m,t,u),t.seen.get(m).isParent=!0}}let c=t.metadataRegistry.get(e);if(c)Zr(a.schema,c);if(t.io==="input"&&Ye(e))delete a.schema.examples,delete a.schema.default;if(t.io==="input"&&"_prefault"in a.schema)(r=a.schema).default??(r.default=a.schema._prefault);return delete a.schema._prefault,t.seen.get(e).schema}function Jh(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function Xr(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let a of e.seen.entries()){let s=e.metadataRegistry.get(a[0])?.id;if(s){let c=r.get(s);if(c&&c!==a[0])throw Error(`Duplicate schema id "${s}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(s,a[0])}}let o=(a)=>{let s=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let m=e.external.registry.get(a[0])?.id,y=e.external.uri??((E)=>E);if(m)return{ref:y(m)};let _=a[1].defId??a[1].schema.id??`schema${e.counter++}`;return a[1].defId=_,{defId:_,ref:`${y("__shared")}#/${s}/${Jh(_)}`}}let c="#",d=`${c}/${s}/`;if(a[1]===n&&!a[1].schema.id)return{ref:c};let u=a[1].schema.id??`__schema${e.counter++}`;return{defId:u,ref:d+Jh(u)}},i=(a)=>{if(a[1].schema.$ref)return;let s=a[1],{ref:c,defId:d}=o(a);if(s.def={...s.schema},d)s.defId=d;let u=s.schema;for(let m in u)delete u[m];u.$ref=c};if(e.cycles==="throw")for(let a of e.seen.entries()){let s=a[1];if(s.cycle)throw Error(`Cycle detected: #/${s.cycle?.join("/")}/<root>
|
|
86
|
+
|
|
87
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of e.seen.entries()){let s=a[1];if(t===a[0]){i(a);continue}if(e.external){let d=e.external.registry.get(a[0])?.id;if(t!==a[0]&&d){i(a);continue}}if(e.metadataRegistry.get(a[0])?.id){i(a);continue}if(s.cycle){i(a);continue}if(s.count>1){if(e.reused==="ref")i(a)}}if(e.external)e.sharedDefsExtractedFor=e.external}function ey(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let r of t){if(!r||typeof r!=="object")return;ey(r);let o=Object.keys(r);if(o.length!==1||o[0]!=="type")return;let i=r.type;for(let a of Array.isArray(i)?i:[i]){if(typeof a!=="string")return;if(!n.includes(a))n.push(a)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var ty=new Set(["type","properties","required","additionalProperties"]),Xh=["oneOf","anyOf"];function Qh(e){let t=e.additionalProperties;if(t===void 0||t===!1||typeof t!=="object"||t===null)return null;return Object.keys(t).length?t:null}function Xs(e){let t=[];for(let i of e){if(typeof i!=="object"||i.type!=="object")return null;for(let a in i)if(!ty.has(a))return null;t.push(i)}let n={},r=new Set;for(let i of t){for(let a in i.properties){if(Object.prototype.hasOwnProperty.call(n,a))continue;let s=[];for(let d of t){let u=d.properties?.[a]??Qh(d);if(u===null||u===void 0)continue;if(!s.some((m)=>JSON.stringify(m)===JSON.stringify(u)))s.push(u)}let c=s.length===1?s[0]:Xs(s)??{allOf:s};lt(n,a,c)}for(let a of i.required??[])r.add(a)}let o={type:"object",properties:n};if(r.size)o.required=[...r];if(t.every((i)=>i.additionalProperties===!1))o.additionalProperties=!1;else{let i=[];for(let a of t){let s=Qh(a);if(s&&!i.some((c)=>JSON.stringify(c)===JSON.stringify(s)))i.push(s)}if(i.length===1)o.additionalProperties=i[0];else if(i.length>1)o.additionalProperties={allOf:i}}return o}function DT(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let o of ty)if(o in e)return;let n=t.filter((o)=>Xh.some((i)=>Array.isArray(o[i]))),r=null;if(!n.length)r=Xs(t);else{let o=n[0],i=Xh.find((c)=>Array.isArray(o[c]));if(Object.keys(o).length!==1)return;let a=t.filter((c)=>c!==o),s=o[i].map((c)=>Xs([...a,c]));if(s.some((c)=>!c))return;r={[i]:s}}if(!r)return;delete e.allOf,Zr(e,r)}function Qr(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let r=(s)=>{let c=e.seen.get(s);if(c.ref===null)return;let d=c.def??c.schema,u={...d},m=c.ref;if(c.ref=null,m){r(m);let _=e.seen.get(m),E=_.schema;if(E.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))d.allOf=d.allOf??[],d.allOf.push(E);else Zr(d,E);if(Zr(d,u),s._zod.parent===m)for(let V in d){if(V==="$ref"||V==="allOf")continue;if(!(V in u))delete d[V]}if(E.$ref&&_.def)for(let V in d){if(V==="$ref"||V==="allOf")continue;if(V in _.def&&JSON.stringify(d[V])===JSON.stringify(_.def[V]))delete d[V]}}let y=s._zod.parent;if(y&&y!==m){r(y);let _=e.seen.get(y);if(_?.schema.$ref){if(d.$ref=_.schema.$ref,_.def)for(let E in d){if(E==="$ref"||E==="allOf")continue;if(E in _.def&&JSON.stringify(d[E])===JSON.stringify(_.def[E]))delete d[E]}}}e.override({zodSchema:s,jsonSchema:d,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let s of[...e.seen.entries()].reverse())r(s[0]);if(e.target!=="openapi-3.0")for(let s of e.seen.entries())ey(s[1].def??s[1].schema);for(let s of e.deferred)s();if(e.intersections.length){let s=new Map;for(let c of e.seen.values())for(let d of[c.schema,c.def]){let u=d?.allOf;if(!Array.isArray(u))continue;let m=s.get(u);if(m)m.push(d);else s.set(u,[d])}for(let c of e.intersections)for(let d of s.get(c)??[])DT(d)}}let o={};if(e.target==="draft-2020-12")o.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")o.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")o.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let s=e.external.registry.get(t)?.id;if(!s)throw Error("Schema is missing an `id` property");o.$id=e.external.uri(s)}Zr(o,n.defId?n.schema:n.def??n.schema);let i=e.metadataRegistry.get(t)?.id;if(i!==void 0&&o.id===i)delete o.id;let a=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let s of e.seen.entries()){let c=s[1];if(c.def&&c.defId){if(c.def.id===c.defId)delete c.def.id;lt(a,c.defId,c.def)}}if(e.external)e.sharedEmitDoneFor=e.external;if(e.external);else if(Object.keys(a).length>0)if(e.target==="draft-2020-12")o.$defs=a;else o.definitions=a;try{let s=JSON.parse(JSON.stringify(o));return Object.defineProperty(s,"~standard",{value:{...t["~standard"],jsonSchema:{input:Yr(t,"input",e.processors),output:Yr(t,"output",e.processors)}},enumerable:!1,writable:!1}),s}catch(s){throw Error("Error converting schema to JSON.")}}function Ye(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Ye(r.element,n);if(r.type==="set")return Ye(r.valueType,n);if(r.type==="lazy")return Ye(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault"||r.type==="catch")return Ye(r.innerType,n);if(r.type==="intersection")return Ye(r.left,n)||Ye(r.right,n);if(r.type==="record"||r.type==="map")return Ye(r.keyType,n)||Ye(r.valueType,n);if(r.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return Ye(r.in,n)||Ye(r.out,n)}if(r.type==="object"){for(let o in r.shape)if(Ye(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(Ye(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(Ye(o,n))return!0;if(r.rest&&Ye(r.rest,n))return!0;return!1}return!1}var ny=(e,t={})=>(n)=>{let r=Jr({...n,processors:t});return pe(e,r),Xr(r,e),Qr(r,e)},Yr=(e,t,n={})=>(r)=>{let{libraryOptions:o,target:i}=r??{},a=Jr({...o??{},target:i,io:t,processors:n});return pe(e,a),Xr(a,e),Qr(a,e)};var lr=(e,t,n)=>{if(e[t]===void 0||n>e[t])e[t]=n},dr=(e,t,n)=>{if(e[t]===void 0||n<e[t])e[t]=n},ry=(e,t)=>{lr(e,"minimum",t),dr(e,"maximum",t)},cy=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},ly=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},dy=(e,t)=>{e.mime=e.mime?e.mime.filter((n)=>t.includes(n)):[...t]},uy=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},oy=(e,t)=>lr(e,"minimum",t.minimum),iy=(e,t)=>dr(e,"maximum",t.maximum),ay=(e)=>(t,n)=>{uy(t,n.format);let[r,o]=e[n.format];lr(t,"minimum",r),dr(t,"maximum",o)},PT={greater_than:(e,t)=>lr(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>dr(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>cy(e,t.value),number_format:ay(ei),bigint_format:ay(ms),min_length:oy,max_length:iy,length_equals:(e,t)=>ry(e,t.length),min_size:oy,max_size:iy,size_equals:(e,t)=>ry(e,t.size),string_format:(e,t)=>{if(uy(e,t.format),t.pattern)ly(e,t.pattern);if(t.format==="base64"||t.format==="base64url")e.contentEncoding=t.format;if(t.local||t.precision===-1)e.laxFormat=!0},mime_type:(e,t)=>dy(e,t.mime)};function De(e){let t={},n=e._zod.def,r=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(let i of r)PT[i._zod.def.check]?.(t,i._zod.def);let o=e._zod.bag;if(o.minimum!==void 0)lr(t,"minimum",o.minimum);if(o.exclusiveMinimum!==void 0)lr(t,"exclusiveMinimum",o.exclusiveMinimum);if(o.maximum!==void 0)dr(t,"maximum",o.maximum);if(o.exclusiveMaximum!==void 0)dr(t,"exclusiveMaximum",o.exclusiveMaximum);if(o.multipleOf!==void 0)cy(t,o.multipleOf);if(o.format!==void 0){if(t.format??(t.format=o.format),o.format.includes("int"))t.isInt=!0}if(o.mime)dy(t,o.mime);for(let i of o.patterns??[])ly(t,i);return t}var $T={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},MT=new Map([[Ns,Ef],[_i,wf]]),py=(e)=>MT.get(e)??e,tc=(e,t,n,r)=>{let o=n;o.type="string";let{minimum:i,maximum:a,format:s,patterns:c,contentEncoding:d,laxFormat:u}=De(e);if(typeof i==="number")o.minLength=i;if(typeof a==="number")o.maxLength=a;if(s){if(o.format=$T[s]??s,o.format==="")delete o.format;if(s==="time"||u)delete o.format}if(d)o.contentEncoding=d;if(c&&c.size>0){let m=[...c].map(py);if(m.length===1)o.pattern=m[0].source;else if(m.length>1)o.allOf=[...m.map((y)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:y.source}))]}},nc=(e,t,n,r)=>{let o=n,{minimum:i,maximum:a,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:d,isInt:u}=De(e);o.type=u?"integer":"number";let m=typeof d==="number"&&d>=(i??Number.NEGATIVE_INFINITY),y=typeof c==="number"&&c<=(a??Number.POSITIVE_INFINITY),_=t.target==="draft-04"||t.target==="openapi-3.0";if(m)if(_)o.minimum=d,o.exclusiveMinimum=!0;else o.exclusiveMinimum=d;else if(typeof i==="number")o.minimum=i;if(y)if(_)o.maximum=c,o.exclusiveMaximum=!0;else o.exclusiveMaximum=c;else if(typeof a==="number")o.maximum=a;if(s){let E=new Set;for(let G of s)if(Number.isFinite(G)&&G!==0)E.add(Math.abs(G));else $e(e,t,o,r,`A multipleOf divisor of ${G} cannot be represented in JSON Schema`);let[k,...V]=E;if(k!==void 0)o.multipleOf=k;if(V.length)o.allOf=[...o.allOf??[],...V.map((G)=>({multipleOf:G}))]}},rc=(e,t,n,r)=>{n.type="boolean"},oc=(e,t,n,r)=>{$e(e,t,n,r,"BigInt cannot be represented in JSON Schema")},my=(e,t,n,r)=>{$e(e,t,n,r,"Symbols cannot be represented in JSON Schema")},ic=(e,t,n,r)=>{if(t.target==="openapi-3.0")n.type="string",n.nullable=!0,n.enum=[null];else n.type="null"},fy=(e,t,n,r)=>{$e(e,t,n,r,"Undefined cannot be represented in JSON Schema")},gy=(e,t,n,r)=>{$e(e,t,n,r,"Void cannot be represented in JSON Schema")},ac=(e,t,n,r)=>{n.not={}},hy=(e,t,n,r)=>{},sc=(e,t,n,r)=>{},cc=(e,t,n,r)=>{$e(e,t,n,r,"Date cannot be represented in JSON Schema")},lc=(e,t,n,r)=>{let o=e._zod.def,i=Ur(o.entries);if(i.length===0){n.not={};return}if(i.every((a)=>typeof a==="number"))n.type="number";if(i.every((a)=>typeof a==="string"))n.type="string";n.enum=i},dc=(e,t,n,r)=>{let o=e._zod.def;if(o.values.length===0){n.not={};return}let i=[];for(let a of o.values)if(a===void 0){if($e(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof a==="bigint"){if($e(e,t,n,r,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(a))}else i.push(a);if(i.length===0);else if(i.length===1){let a=i[0];if(n.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0")n.enum=[a];else n.const=a}else{if(i.every((a)=>typeof a==="number"))n.type="number";if(i.every((a)=>typeof a==="string"))n.type="string";if(i.every((a)=>typeof a==="boolean"))n.type="boolean";if(i.every((a)=>a===null))n.type="null";n.enum=i}},yy=(e,t,n,r)=>{$e(e,t,n,r,"NaN cannot be represented in JSON Schema")},uc=(e,t,n,r)=>{let o=n,i=e._zod.pattern;if(!i)throw Error("Pattern not found in template literal");o.type="string",o.pattern=i.source},_y=(e,t,n,r)=>{let o=n;o.type="string",o.format="binary",o.contentEncoding="binary";let{minimum:i,maximum:a,mime:s}=De(e);if(i!==void 0)o.minLength=i;if(a!==void 0)o.maxLength=a;if(!s)return;if(s.length===0)o.not={};else if(s.length===1)o.contentMediaType=s[0];else o.anyOf=s.map((c)=>({contentMediaType:c}))},by=(e,t,n,r)=>{n.type="boolean"},pc=(e,t,n,r)=>{$e(e,t,n,r,"Custom types cannot be represented in JSON Schema")},vy=(e,t,n,r)=>{$e(e,t,n,r,"Function types cannot be represented in JSON Schema")},mc=(e,t,n,r)=>{$e(e,t,n,r,"Transforms cannot be represented in JSON Schema")},Sy=(e,t,n,r)=>{$e(e,t,n,r,"Map cannot be represented in JSON Schema")},xy=(e,t,n,r)=>{$e(e,t,n,r,"Set cannot be represented in JSON Schema")},fc=(e,t,n,r)=>{let o=n,i=e._zod.def,{minimum:a,maximum:s}=De(e);if(typeof a==="number")o.minItems=a;if(typeof s==="number")o.maxItems=s;o.type="array",o.items=pe(i.element,t,{...r,path:[...r.path,"items"]})};function eo(e){let t=e._zod.def;if(t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform"))return eo(t.out);if(t.type==="catch")return eo(t.innerType);return e._zod.optin}var gc=(e,t,n,r)=>{let o=n,i=e._zod.def,a=i.shape;if(Object.getOwnPropertySymbols(a).length&&$e(e,t,o,r,"Symbol keys cannot be represented in JSON Schema"))return;o.type="object",o.properties={};for(let d in a)lt(o.properties,d,pe(a[d],t,{...r,path:[...r.path,"properties",d]}));let c=[];for(let d of Object.keys(a)){let u=i.shape[d];if(t.io==="input"?eo(u)===void 0:u._zod.optout===void 0)c.push(d)}if(c.length>0)o.required=c;if(i.catchall?._zod.def.type==="never")o.additionalProperties=!1;else if(!i.catchall){if(t.io==="output")o.additionalProperties=!1}else if(i.catchall)o.additionalProperties=pe(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})},hc=(e,t,n,r)=>{let o=e._zod.def,i=o.inclusive===!1,a=o.options.map((s,c)=>pe(s,t,{...r,path:[...r.path,i?"oneOf":"anyOf",c]}));if(i)n.oneOf=a;else n.anyOf=a},yc=(e,t,n,r)=>{let o=e._zod.def,i=pe(o.left,t,{...r,path:[...r.path,"allOf",0]}),a=pe(o.right,t,{...r,path:[...r.path,"allOf",1]}),s=(d)=>("allOf"in d)&&Object.keys(d).length===1,c=[...s(i)?i.allOf:[i],...s(a)?a.allOf:[a]];n.allOf=c,t.intersections.push(c)},Ey=(e,t,n,r)=>{let o=n,i=e._zod.def;o.type="array";let a=t.target==="draft-2020-12"?"prefixItems":"items",s=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((k,V)=>pe(k,t,{...r,path:[...r.path,a,V]})),d=i.rest?pe(i.rest,t,{...r,path:[...r.path,s,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null,u=i.items.length;while(u>0){let k=i.items[u-1];if(!(t.io==="input"?eo(k)!==void 0:k._zod.optout==="optional"))break;u--}let m=i.items.length,y=!i.rest;if(t.target==="draft-2020-12"){if(o.prefixItems=c,y)o.items=!1;else if(d)o.items=d;if(u>0)o.minItems=u;if(y)o.maxItems=m}else if(t.target==="openapi-3.0"){if(o.items={anyOf:c},d)o.items.anyOf.push(d);if(u>0)o.minItems=u;if(y)o.maxItems=m}else{if(o.items=c,y)o.additionalItems=!1;else if(d)o.additionalItems=d;if(u>0)o.minItems=u;if(y)o.maxItems=m}let{minimum:_,maximum:E}=De(e);if(typeof _==="number")o.minItems=_;if(typeof E==="number")o.maxItems=E};function Qs(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let E=e.get(t)?.def;if(!E)return t;let k=Qs(e,E,n);return k===E?t:k}for(let E of["anyOf","oneOf"]){let k=t[E];if(!Array.isArray(k))continue;let V=k.map((G)=>Qs(e,G,n));if(V.some((G,re)=>G!==k[re]))t={...t,[E]:V}}let r=Array.isArray(t.type)?t.type:[t.type],o=!r.includes("string")&&r.some((E)=>E==="number"||E==="integer"),i=t.enum??(t.const!==void 0?[t.const]:void 0);if(!o&&!i?.some((E)=>typeof E==="number"))return t;let{minimum:a,maximum:s,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:u,format:m,id:y,..._}=t;if(_.enum)_.enum=_.enum.map((E)=>typeof E==="number"?String(E):E);else if(typeof _.const==="number")_.const=String(_.const);if(!o)return _;if(_.type="string",!i)_.pattern=(r.includes("number")?or:pi).source;return _}var ec=new WeakMap;function LT(e){let t=new Map;for(let r of e.seen.values())if(r.def&&!t.has(r.schema))t.set(r.schema,r);let n=new Map;for(let r of ec.get(e)??[]){let o=e.seen.get(r),i=(o?.def??o?.schema)?.propertyNames;if(!i||i===!0||n.has(i))continue;let a=Qs(t,i,new Set);if(a!==i)n.set(i,a)}if(!n.size)return;for(let r of e.seen.values())for(let o of[r.schema,r.def]){let i=o&&n.get(o.propertyNames);if(i)o.propertyNames=i}}var _c=(e,t,n,r)=>{let o=n,i=e._zod.def;o.type="object";let a=i.keyType,s=De(a).patterns;if(i.mode==="loose"&&s&&s.size>0){let u=pe(i.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(let m of s)lt(o.patternProperties,py(m).source,u)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){o.propertyNames=pe(i.keyType,t,{...r,path:[...r.path,"propertyNames"]});let u=ec.get(t);if(!u)u=[],ec.set(t,u),t.deferred.push(()=>LT(t));u.push(e)}o.additionalProperties=pe(i.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}let c=a._zod.values,d=t.io==="input"&&eo(i.valueType)!==void 0;if(c&&!i.partial&&!d){let u=[...c].filter((m)=>typeof m==="string"||typeof m==="number");if(u.length>0)o.required=u.map(String)}},bc=(e,t,n,r)=>{let o=e._zod.def,i=pe(o.innerType,t,r),a=t.seen.get(e);if(t.target==="openapi-3.0")a.ref=o.innerType,n.nullable=!0;else n.anyOf=[i,{type:"null"}]},vc=(e,t,n,r)=>{let o=e._zod.def;pe(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType},Sc=Symbol();function wy(e,t,n,r,o){let i=!1,a=JSON.stringify(e,(s,c)=>{if(typeof c!=="bigint")return c;return i=!0,null});if(!i)return JSON.parse(a);return $e(t,n,r,o,"BigInt defaults cannot be represented in JSON Schema"),Sc}var xc=(e,t,n,r)=>{let o=e._zod.def;pe(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType;let a=wy(o.defaultValue,e,t,n,r);if(a!==Sc)n.default=a},Ec=(e,t,n,r)=>{let o=e._zod.def;pe(o.innerType,t,r);let i=t.seen.get(e);if(i.ref=o.innerType,t.io!=="input")return;let a=wy(o.defaultValue,e,t,n,r);if(a!==Sc)n._prefault=a},wc=(e,t,n,r)=>{let o=e._zod.def;pe(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType;let a;try{a=o.catchValue(void 0)}catch{$e(e,t,n,r,"Dynamic catch values are not supported in JSON Schema");return}n.default=a},Cc=(e,t,n,r)=>{let o=e._zod.def,i=o.in._zod.traits.has("$ZodTransform"),a=t.io==="input"?i?o.out:o.in:o.out;pe(a,t,r);let s=t.seen.get(e);s.ref=a},Ac=(e,t,n,r)=>{let o=e._zod.def;pe(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType,n.readOnly=!0},Cy=(e,t,n,r)=>{let o=e._zod.def;pe(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType},Oi=(e,t,n,r)=>{let o=e._zod.def;pe(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType},Ay=(e,t,n,r)=>{let o=e._zod.innerType;pe(o,t,r);let i=t.seen.get(e);i.ref=o},sy={string:tc,number:nc,boolean:rc,bigint:oc,symbol:my,null:ic,undefined:fy,void:gy,never:ac,any:hy,unknown:sc,date:cc,enum:lc,literal:dc,nan:yy,template_literal:uc,file:_y,success:by,custom:pc,function:vy,transform:mc,map:Sy,set:xy,array:fc,object:gc,union:hc,intersection:yc,tuple:Ey,record:_c,nullable:bc,nonoptional:vc,default:xc,prefault:Ec,catch:wc,pipe:Cc,readonly:Ac,promise:Cy,optional:Oi,lazy:Ay};function Ty(e,t){if("_idmap"in e){let r=e,o=Jr({...t,processors:sy}),i={};for(let c of r._idmap.entries()){let[d,u]=c;pe(u,o)}let a={},s={registry:r,uri:t?.uri,defs:i};o.external=s;for(let c of r._idmap.entries()){let[d,u]=c;Xr(o,u),lt(a,d,Qr(o,u))}if(Object.keys(i).length>0){let c=o.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[c]:i}}return{schemas:a}}let n=Jr({...t,processors:sy});return pe(e,n),Xr(n,e),Qr(n,e)}var Ry=new WeakSet([Object.prototype,Error.prototype]);function Ni(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let r=n(this);return Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0})}})}var HT=(e,t)=>{Jm.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);if(Ry.has(n))return;Ry.add(n),Ni(n,"format",(r)=>(o)=>bs(r,o)),Ni(n,"flatten",(r)=>(o)=>_s(r,o)),Ni(n,"addIssue",(r)=>(o)=>{r.issues.push(o),r.message=JSON.stringify(r.issues,jr,2)}),Ni(n,"addIssues",(r)=>(o)=>{r.issues.push(...o),r.message=JSON.stringify(r.issues,jr,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})};var ut=w("ZodError",HT,void 0,{Parent:Error});var Iy=ci(ut),Oy=li(ut),Ny=di(ut),ky=ui(ut),Dy=Qm(ut),Py=ef(ut),$y=tf(ut),My=nf(ut),Ly=rf(ut),zy=of(ut),Fy=af(ut),Uy=sf(ut);function GT(){if(!rt.localeError)ot(zs())}function Pi(){if(!rt.memoizer)ot({memoizer:Ls()})}var me=w("ZodType",(e,t)=>(GT(),de.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(dt(t,{checks:[...t.checks??[],...e.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return At(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(LR(e,t))},superRefine(e,t){return this.check(zR(e,t))},overwrite(e){return this.check(Gt(e))},optional(){return Vy(this)},exactOptional(){return ER(this)},nullable(){return Ky(this)},nullish(){return Vy(Ky(this))},nonoptional(e){return IR(this,e)},array(){return z(this)},or(e){return Be([this,e])},and(e){return bR(this,e)},transform(e){return qy(this,xR(e))},default(e){return AR(this,e)},prefault(e){return RR(this,e)},catch(e){return NR(this,e)},pipe(e){return qy(this,e)},readonly(){return PR(this)},describe(e){let t=this.clone();return un.add(t,{description:e}),t},meta(...e){if(e.length===0)return un.get(this);let t=this.clone();return un.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get "~standard"(){return ii(this,"~standard",{...Os(this),jsonSchema:{input:Yr(this,"input"),output:Yr(this,"output")}})},set "~standard"(e){qt(this,"~standard",e)},parse:function e(t,n){return Iy(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Oy(this,t,n,{callee:e})},safeParse(e,t){return Ny(this,e,t)},async safeParseAsync(e,t){return ky(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){qt(this,"spa",e)},validate(e,t){return vs(this,e,t)},validateAsync(e,t){return Ss(this,e,t)},encode:function e(t,n){return Dy(this,t,n,{callee:e})},decode:function e(t,n){return Py(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await $y(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await My(this,t,n,{callee:e})},safeEncode(e,t){return Ly(this,e,t)},safeDecode(e,t){return zy(this,e,t)},async safeEncodeAsync(e,t){return Fy(this,e,t)},async safeDecodeAsync(e,t){return Uy(this,e,t)},toJSONSchema(e){return ny(this,{})(e)},get description(){return un.get(this)?.description},get _def(){return this._zod.def}}),By=w("_ZodString",(e,t)=>{yi.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>tc(e,n,r,o)},ai({format:(e)=>De(e).format??null,minLength:(e)=>De(e).minimum??null,maxLength:(e)=>De(e).maximum??null},{regex(...e){return this.check(js(...e))},includes(...e){return this.check(qs(...e))},startsWith(...e){return this.check(Bs(...e))},endsWith(...e){return this.check(Hs(...e))},min(...e){return this.check(cr(...e))},max(...e){return this.check(Ri(...e))},length(...e){return this.check(Ii(...e))},nonempty(...e){return this.check(cr(1,...e))},lowercase(e){return this.check(Vs(e))},uppercase(e){return this.check(Ks(e))},trim(){return this.check(Gs())},normalize(...e){return this.check(Ws(...e))},toLowerCase(){return this.check(Zs())},toUpperCase(){return this.check(Ys())},slugify(){return this.check(Js())}})),Rc=w("ZodString",(e,t)=>{yi.init(e,t),By.init(e,t)},{email(e){return this.check(Fs(Hy,e))},url(e){return this.check(Us(Wy,e))},jwt(e){return this.check(Lh(uR,e))},emoji(e){return this.check(Eh(JT,e))},guid(e){return this.check(_h(YT,e))},uuid(e){return this.check(bh(ki,e))},uuidv4(e){return this.check(vh(ki,e))},uuidv6(e){return this.check(Sh(ki,e))},uuidv7(e){return this.check(xh(ki,e))},nanoid(e){return this.check(wh(XT,e))},cuid(e){return this.check(Ch(QT,e))},cuid2(e){return this.check(Ah(eR,e))},ulid(e){return this.check(Th(tR,e))},base64(e){return this.check(Ph(cR,e))},base64url(e){return this.check($h(lR,e))},xid(e){return this.check(Rh(nR,e))},ksuid(e){return this.check(Ih(rR,e))},ipv4(e){return this.check(Oh(oR,e))},ipv6(e){return this.check(Nh(iR,e))},cidrv4(e){return this.check(kh(aR,e))},cidrv6(e){return this.check(Dh(sR,e))},e164(e){return this.check(Mh(dR,e))},datetime(e){return this.check(wi(to,e))},date(e){return this.check(Ci(no,e))},time(e){return this.check(Ai(ro,e))},duration(e){return this.check(Ti(oo,e))}});function l(e){return hh(Rc,e)}var we=w("ZodStringFormat",(e,t)=>{be.init(e,t),By.init(e,t)}),to=w("ZodISODateTime",(e,t)=>{xg.init(e,t),we.init(e,t)}),no=w("ZodISODate",(e,t)=>{Eg.init(e,t),we.init(e,t)}),ro=w("ZodISOTime",(e,t)=>{wg.init(e,t),we.init(e,t)}),oo=w("ZodISODuration",(e,t)=>{Cg.init(e,t),we.init(e,t)}),Hy=w("ZodEmail",(e,t)=>{ug.init(e,t),we.init(e,t)});function ZT(e){return Fs(Hy,e)}var YT=w("ZodGUID",(e,t)=>{lg.init(e,t),we.init(e,t)});var ki=w("ZodUUID",(e,t)=>{dg.init(e,t),we.init(e,t)});var Wy=w("ZodURL",(e,t)=>{fg.init(e,t),we.init(e,t)});function Gy(e){return Us(Wy,e)}var JT=w("ZodEmoji",(e,t)=>{gg.init(e,t),we.init(e,t)});var XT=w("ZodNanoID",(e,t)=>{hg.init(e,t),we.init(e,t)});var QT=w("ZodCUID",(e,t)=>{yg.init(e,t),we.init(e,t)});var eR=w("ZodCUID2",(e,t)=>{_g.init(e,t),we.init(e,t)});var tR=w("ZodULID",(e,t)=>{bg.init(e,t),we.init(e,t)});var nR=w("ZodXID",(e,t)=>{vg.init(e,t),we.init(e,t)});var rR=w("ZodKSUID",(e,t)=>{Sg.init(e,t),we.init(e,t)});var oR=w("ZodIPv4",(e,t)=>{Ag.init(e,t),we.init(e,t)});var iR=w("ZodIPv6",(e,t)=>{Rg.init(e,t),we.init(e,t)});var aR=w("ZodCIDRv4",(e,t)=>{Ig.init(e,t),we.init(e,t)});var sR=w("ZodCIDRv6",(e,t)=>{Og.init(e,t),we.init(e,t)});var cR=w("ZodBase64",(e,t)=>{kg.init(e,t),we.init(e,t)});var lR=w("ZodBase64URL",(e,t)=>{Dg.init(e,t),we.init(e,t)});var dR=w("ZodE164",(e,t)=>{Pg.init(e,t),we.init(e,t)});var uR=w("ZodJWT",(e,t)=>{$g.init(e,t),we.init(e,t)});var $i=w("ZodNumber",(e,t)=>{ks.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>nc(e,n,r,o),e.isFinite=!0},ai({minValue:(e)=>{let{minimum:t,exclusiveMinimum:n}=De(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:n}=De(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:n}=De(e);return!!t||!!n?.some(Number.isSafeInteger)},format:(e)=>De(e).format??null},{gt(e,t){return this.check(sr(e,t))},gte(e,t){return this.check(Wt(e,t))},min(e,t){return this.check(Wt(e,t))},lt(e,t){return this.check(ar(e,t))},lte(e,t){return this.check(Ht(e,t))},max(e,t){return this.check(Ht(e,t))},int(e){return this.check(Di(e))},safe(e){return this.check(Di(e))},positive(e){return this.check(sr(0,e))},nonnegative(e){return this.check(Wt(0,e))},negative(e){return this.check(ar(0,e))},nonpositive(e){return this.check(Ht(0,e))},multipleOf(e,t){return this.check(Gr(e,t))},step(e,t){return this.check(Gr(e,t))},finite(){return this}}));function f(e){return zh($i,e)}var pR=w("ZodNumberFormat",(e,t)=>{Mg.init(e,t),$i.init(e,t)});function Di(e){return Uh(pR,e)}var Ic=w("ZodBoolean",(e,t)=>{Lg.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>rc(e,n,r,o)});function F(e){return jh(Ic,e)}var Zy=w("ZodBigInt",(e,t)=>{zg.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>oc(e,n,r,o)},ai({minValue:(e)=>De(e).minimum??null,maxValue:(e)=>De(e).maximum??null,format:(e)=>De(e).format??null},{gte(e,t){return this.check(Wt(e,t))},min(e,t){return this.check(Wt(e,t))},gt(e,t){return this.check(sr(e,t))},lt(e,t){return this.check(ar(e,t))},lte(e,t){return this.check(Ht(e,t))},max(e,t){return this.check(Ht(e,t))},positive(e){return this.check(sr(BigInt(0),e))},negative(e){return this.check(ar(BigInt(0),e))},nonpositive(e){return this.check(Ht(BigInt(0),e))},nonnegative(e){return this.check(Wt(BigInt(0),e))},multipleOf(e,t){return this.check(Gr(e,t))}}));var mR=w("ZodNull",(e,t)=>{Fg.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ic(e,n,r,o)});function Pt(e){return qh(mR,e)}var fR=w("ZodUnknown",(e,t)=>{Ug.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>sc(e,n,r,o)});function it(){return Bh(fR)}var gR=w("ZodNever",(e,t)=>{jg.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ac(e,n,r,o)});function Yy(e){return Hh(gR,e)}var Jy=w("ZodDate",(e,t)=>{Vg.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>cc(e,n,r,o),e.min=(n,r)=>e.check(Wt(n,r)),e.max=(n,r)=>e.check(Ht(n,r))},ai({minDate:(e)=>{let{minimum:t}=De(e);return t?new Date(t):null},maxDate:(e)=>{let{maximum:t}=De(e);return t?new Date(t):null}},{}));var hR=w("ZodArray",(e,t)=>{Pi(),Kg.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>fc(e,n,r,o),e.element=t.element},{min(e,t){return this.check(cr(e,t))},nonempty(e){return this.check(cr(1,e))},max(e,t){return this.check(Ri(e,t))},length(e,t){return this.check(Ii(e,t))},unwrap(){return this.element}});function z(e,t){return Gh(hR,e,t)}var Xy=w("ZodObject",(e,t)=>{Pi(),Hg.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>gc(e,n,r,o),QA(e,"shape",(n)=>n._zod.def.shape,!1)},{keyof(){return D(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(dt(this._zod.def,{catchall:e}))},passthrough(){return this.clone(dt(this._zod.def,{catchall:it()}))},loose(){return this.clone(dt(this._zod.def,{catchall:it()}))},strict(){return this.clone(dt(this._zod.def,{catchall:Yy()}))},strip(){return this.clone(dt(this._zod.def,{catchall:void 0}))},extend(e){return BA(this,e)},safeExtend(e){return HA(this,e)},merge(e){return WA(this,e)},pick(e){return KA(this,e)},omit(e){return qA(this,e)},partial(...e){return jm(e_,this,e[0])},exactPartial(...e){return jm(t_,this,e[0],"exactPartial")},required(...e){return GA(n_,this,e[0])}});function g(e,t){let n={type:"object",shape:e??{},...q(t)};return new Xy(n)}function K(e,t){return new Xy({type:"object",shape:e,catchall:Yy(),...q(t)})}var Qy=w("ZodUnion",(e,t)=>{Ds.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>hc(e,n,r,o),e.options=t.options});function Be(e,t){return new Qy({type:"union",options:e,...q(t)})}var yR=w("ZodDiscriminatedUnion",(e,t)=>{Qy.init(e,t),Wg.init(e,t)});function Ae(e,t,n){return new yR({type:"union",options:t,discriminator:e,...q(n)})}var _R=w("ZodIntersection",(e,t)=>{Gg.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>yc(e,n,r,o)});function bR(e,t){return new _R({type:"intersection",left:e,right:t})}var jy=w("ZodRecord",(e,t)=>{Pi(),Zg.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>_c(e,n,r,o),e.keyType=t.keyType,e.valueType=t.valueType});function ie(e,t,n){if(!t||!t._zod)return new jy({type:"record",keyType:l(),valueType:e,...q(t)});return new jy({type:"record",keyType:e,valueType:t,...q(n)})}var Tc=w("ZodEnum",(e,t)=>{Yg.init(e,t),me.init(e,t),e._zod.processJSONSchema=(r,o,i)=>lc(e,r,o,i),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{let i={};for(let a of r)if(n.has(a))i[a]=t.entries[a];else throw Error(`Key ${a} not found in enum`);return new Tc({...t,checks:[],...q(o),entries:i})},e.exclude=(r,o)=>{let i={...t.entries};for(let a of r)if(n.has(a))delete i[a];else throw Error(`Key ${a} not found in enum`);return new Tc({...t,checks:[],...q(o),entries:i})}});function D(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((r)=>[r,r])):e;return new Tc({type:"enum",entries:n,...q(t)})}var vR=w("ZodLiteral",(e,t)=>{Jg.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>dc(e,n,r,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function I(e,t){return new vR({type:"literal",values:Array.isArray(e)?e:[e],...q(t)})}var SR=w("ZodTransform",(e,t)=>{Pi(),Xg.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>mc(e,n,r,o),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new qr(e.constructor.name);n.addIssue=(i)=>{if(typeof i==="string")n.issues.push(kn(i,n.value,t));else{let a=i;if(a.fatal)a.continue=!1;if(a.code??(a.code="custom"),!("input"in a))a.input=n.value;a.inst??(a.inst=e),n.issues.push(kn(a))}};let o=t.transform(n.value,n);if(o instanceof Promise)return o.then((i)=>(n.value=i,n));return n.value=o,n}});function xR(e){return new SR({type:"transform",transform:e})}var e_=w("ZodOptional",(e,t)=>{Ps.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Oi(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Vy(e){return new e_({type:"optional",innerType:e})}var t_=w("ZodExactOptional",(e,t)=>{Qg.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Oi(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function ER(e){return new t_({type:"optional",innerType:e})}var wR=w("ZodNullable",(e,t)=>{eh.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>bc(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Ky(e){return new wR({type:"nullable",innerType:e})}var CR=w("ZodDefault",(e,t)=>{th.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>xc(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function AR(e,t){return new CR({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():us(t)}})}var TR=w("ZodPrefault",(e,t)=>{nh.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ec(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function RR(e,t){return new TR({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():us(t)}})}var n_=w("ZodNonOptional",(e,t)=>{rh.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>vc(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function IR(e,t){return new n_({type:"nonoptional",innerType:e,...q(t)})}var OR=w("ZodCatch",(e,t)=>{oh.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>wc(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function NR(e,t){return new OR({type:"catch",innerType:e,catchValue:typeof t==="function"?t:Bm(t)})}var kR=w("ZodPipe",(e,t)=>{ih.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Cc(e,n,r,o),e.in=t.in,e.out=t.out});function qy(e,t){return new kR({type:"pipe",in:e,out:t})}var DR=w("ZodReadonly",(e,t)=>{ah.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ac(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function PR(e){return new DR({type:"readonly",innerType:e})}var $R=w("ZodTemplateLiteral",(e,t)=>{sh.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>uc(e,n,r,o)});function r_(e,t){return new $R({type:"template_literal",parts:e,...q(t)})}var MR=w("ZodCustom",(e,t)=>{ch.init(e,t),me.init(e,t),e._zod.processJSONSchema=(n,r,o)=>pc(e,n,r,o)});function LR(e,t={}){return Zh(MR,e,t)}function zR(e,t){return Yh(e,t)}function UR(e){return wi(to,e)}function jR(e){return Ci(no,e)}function VR(e){return Ai(ro,e)}function KR(e){return Ti(oo,e)}function qR(e){return yh(Rc,e)}function BR(e){return Fh($i,e)}function HR(e){return Vh(Ic,e)}function WR(e){return Kh(Zy,e)}function GR(e){return Wh(Jy,e)}var W={acl_rules:"acl",organizations:"org",users:"usr",auth_sessions:"ses",user_passkeys:"pky",sso_providers:"sso",org_memberships:"mem",visual_plans:"vp",visual_plan_versions:"vpv",block_presets:"bpr",saved_recipes:"rcp",channels:"ch",schedules:"sched",holiday_groups:"hgrp",holidays:"hol",holiday_calendars:"hcal",holiday_calendar_entries:"hcent",schedule_exceptions:"sexc",audio_files:"aud",destinations:"dest",call_records:"call",call_events:"cev",api_keys:"key",audit_logs:"audit",invitations:"inv",roles:"role",licenses:"lic",webhook_endpoints:"whep",webhook_delivery_logs:"whdl",call_transcriptions:"ctr",call_transcription_embeddings:"cte",analysis_templates:"at",call_analyses:"ca",ai_settings:"ais",usage_records:"ur",contacts:"ct",contact_channels:"ctch",chat_sessions:"csess",notifications:"notif",dialer_campaigns:"dcamp",dialer_contacts:"dct",dialer_attempts:"datt",dialer_dnc:"dnc",dialer_import_jobs:"dimp",export_jobs:"exp",org_secrets:"sec",connectors:"conn",oauth_clients:"oac",oauth_grants:"oag",signals:"sig",signal_versions:"sigv",call_signals:"csig",call_signal_timelines:"cstl",insight_views:"iv",attendants:"att",attendant_status_log:"asl",pause_reasons:"pause",dispositions:"disp",conversations:"conv",queues:"que",saved_replies:"srp",conversation_copilot_suggestions:"csug",assistant_conversations:"aconv",assistant_messages:"amsg",assistant_approvals:"aappr",chat_ws_sessions:"chs",chat_media:"media",chat_messages:"msg"};function Mi(e,t){return Ot.fromUUID(W[e],t).toString()}var ZR=new Map(Object.keys(W).map((e)=>[W[e],e]));function io(e){return ZR.get(e)}var YR=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Dn(e){if(YR.test(e))return{kind:"uuid",uuid:e};let t=e.lastIndexOf("_");if(t<=0||t===e.length-1)return{kind:"invalid",reason:"not-an-id"};let n=e.slice(0,t),r=io(n);if(r===void 0)return{kind:"invalid",reason:"unknown-prefix"};try{return{kind:"typeid",entity:r,prefix:n,uuid:Ot.fromString(e,n).toUUID()}}catch{return{kind:"invalid",reason:"malformed-suffix"}}}function se(e){return e}function JR(e){return`a ${W[e]}_... TypeID for ${e}, or the raw UUID of that row`}function o_(e,t,n){C(`Invalid id "${t}": ${n}`),P(` Expected ${JR(e)}.`),P(" Convert between the two forms with: niva id <value> [--as <entity>]"),process.exit(A.USAGE_ERROR)}function XR(e){let t=e.lastIndexOf("_");return t>0?e.slice(0,t):""}function i_(e,t){let n=Dn(t);if(n.kind==="uuid")return Mi(e,n.uuid);let r=io(XR(t));if(r===e)return t;if(r!==void 0)o_(e,t,`it is a ${r} id`);o_(e,t,"it is neither a UUID nor an id of a known entity")}function x(e,t){let n;if(Array.isArray(t))n=t.map((r)=>i_(e,r));else if(t!==void 0)n=i_(e,t);return n}var a_=["volume","answered","busy","no_answer","failed","duration","ai_cost","flow_errors"],s_=["day","week","month","hour_of_day","weekday","plan","plan_version","channel","outcome"],c_=["answered","busy","no_answer","failed"];function ao(e){if(e==null)return[];return e.split(",").map((t)=>t.trim()).filter((t)=>t.length>0)}function QR(e,t){return[...t,e]}function Tt(e){C(`Error: ${e}`),process.exit(A.USAGE_ERROR)}function d_(e,t){if(!e.startsWith("signal:")||e.length===7)Tt(`invalid ${t} "${e}" — expected signal:<sig_id>`);return{signal_id:x("signals",e.slice(7))}}function eI(e){let t=ao(e);if(t.length===0)Tt("--measure is required (e.g. --measure volume,answered)");if(t.length>6)Tt("--measure accepts at most 6 measures");for(let n of t)if(!a_.includes(n))Tt(`invalid --measure "${n}" — expected one of: ${a_.join(", ")}`);return t.map((n)=>se(n))}function tI(e){let t=[];for(let n of ao(e)){if(n.startsWith("signal:")){t.push(d_(n,"--by"));continue}if(!s_.includes(n))Tt(`invalid --by "${n}" — expected one of: ${s_.join(", ")} or signal:<sig_id>`);t.push(se(n))}if(t.length>2)Tt("--by accepts at most 2 dimensions");return t}function nI(e){if(e===void 0)return;let t=ao(e);if(t.length===0)Tt("--plan needs at least one id");return t.map((n)=>x("visual_plans",n))}function rI(e){let t=ao(e);for(let n of t)if(!c_.includes(n))Tt(`invalid --outcome "${n}" — expected one of: ${c_.join(", ")}`);return t.map((n)=>se(n))}function oI(e){let t=[];for(let n of e){let r=n.indexOf("=");if(r<0)Tt(`invalid --where "${n}" — expected signal:<sig_id>=<v1,v2>`);let o=d_(n.slice(0,r),"--where"),i=ao(n.slice(r+1));if(i.length===0)Tt(`invalid --where "${n}" — expected signal:<sig_id>=<v1,v2>`);t.push({...o,values:i})}return t}function iI(e){let t=Number(e);if(!Number.isInteger(t)||t<1||t>1000)Tt(`invalid --limit "${e}" — expected an integer from 1 to 1000`);return t}function u_(e,t){e.command("analytics").description("Flexible aggregates over calls and signals").command("query").description("Aggregate call measures grouped by time, plan, channel, outcome or signal values").option("--measure <list>","Comma-separated measures: volume,answered,busy,no_answer,failed,duration,ai_cost,flow_errors").option("--by <list>","Comma-separated dimensions: day,week,month,hour_of_day,weekday,plan,plan_version,channel,outcome or signal:<sig_id> (max 2)").option("--from <date>","Start date (YYYY-MM-DD or ISO 8601)").option("--to <date>","End date (YYYY-MM-DD or ISO 8601)").option("--plan <ids>","Comma-separated visual plan IDs").option("--channel <channel>","Filter by channel: voice or chat").option("--outcome <list>","Comma-separated outcomes: answered,busy,no_answer,failed").option("--where <signal:values>","Signal filter signal:<sig_id>=<v1,v2>; repeatable",QR,[]).option("--limit <n>","Max rows (1-1000)","500").action(async(r)=>{let{format:o}=S(e.opts()),{date_from:i,date_to:a}=yt(r),s=eI(r.measure),c=tI(r.by),d=nI(r.plan),u=rI(r.outcome),m=oI(r.where),y=iI(r.limit),_=await b(t().insights.aggregate({measures:s,...c.length>0?{group_by:c}:{},...d!==void 0||r.channel!==void 0||u.length>0||m.length>0?{filters:{...d!==void 0?{plan_ids:d}:{},...r.channel!==void 0?{channel:se(r.channel)}:{},...u.length>0?{outcomes:u.map((k)=>se(k))}:{},...m.length>0?{signals:m}:{}}}:{},period:{date_from:i,date_to:a},limit:y}));if(o==="json"){v(_);return}if(_.truncated)Et(`Showing the first ${_.rows.length} rows (--limit ${y}). Narrow the period or filters.`);console.log(l_.default.bold("Analytics")),console.log("");let E=_.columns.map((k)=>k.key);L(E,_.rows.map((k)=>({...k})))})}function p_(e,t){let n=e.command("attendants").description("Manage Desk attendants (requires the desk module)");n.command("list").description("List attendants with their current state").option("--status <s>","Filter by state (available, paused, not_responding, ringing, busy, wrap_up, offline)").option("--endpoint <e>","Filter by endpoint (sip_extension, webrtc)").option("--search <term>","Search by name or email").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().attendants.list({page:Number(r.page),limit:Number(r.limit),search:r.search,status:se(r.status),endpoint:se(r.endpoint)}));if(o==="json"){v(i?a.items.map((s)=>O(s,i)):a);return}L(["ID","Name","Email","Endpoint","Status","Reason","Online"],a.items.map((s)=>({ID:s.id,Name:s.user.name,Email:s.user.email,Endpoint:s.endpoint,Status:s.status,Reason:s.status_reason?.name??"—",Online:s.online?"yes":"no"}))),ee(a)}),n.command("show <attendant_id>").description("Show one attendant").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().attendants.getById({attendant_id:x("attendants",r)}));if(o==="json"){v(i?O(a,i):a);return}J([{title:"Attendant",rows:[{label:"ID",value:a.id},{label:"Name",value:a.user.name},{label:"Email",value:a.user.email},{label:"Endpoint",value:a.endpoint},{label:"Extension",value:a.extension},{label:"Online",value:a.online}]},{title:"State",rows:[{label:"Status",value:a.status},{label:"Reason",value:a.status_reason?.name},{label:"Since",value:Me(a.status_since)}]},{title:"Capacity",rows:[{label:"Voice",value:a.capacity_voice},{label:"Chat",value:a.capacity_chat},{label:"Auto answer",value:a.auto_answer},{label:"Max wrap-up (s)",value:a.max_wrap_s}]}])}),n.command("set-status <attendant_id> <status>").description("Set an attendant's state as a supervisor (available, paused, offline). A pause or offline asked for during a call never interrupts it: it waits for the work to end and lands as paused. It also takes an attendant out of not_responding").option("--reason <pause_reason_id>","Pause reason (with paused)").action(async(r,o,i)=>{let{format:a,fields:s}=S(e.opts());if(i.reason!=null&&o!=="paused")C("--reason only applies to the paused state"),process.exit(A.USAGE_ERROR);let c=await b(t().attendants.setStatus({attendant_id:x("attendants",r),status:se(o),reason_id:x("pause_reasons",i.reason)}));if(a==="json"){v(s?O(c,s):c);return}if(c.pending){N(`Pause requested for ${c.attendant.user.name}; it applies when the current work ends`);return}N(`${c.attendant.user.name} is now ${c.attendant.status}`)})}import{readFile as v_,writeFile as S_}from"node:fs/promises";import{basename as x_}from"node:path";function aI(e,t){let n=t.toLowerCase();if(n.endsWith(".wav"))return sI(e);if(n.endsWith(".mp3"))return _I(e);return}function Li(e){if(!Number.isFinite(e)||e<=0)return;let t=Math.round(e);if(t<=0||t>86400000)return;return t}function m_(e,t,n){let r="";for(let o=0;o<n;o+=1)r+=String.fromCharCode(e[t+o]??0);return r}function so(e,t,n){if(t+n.length>e.byteLength)return!1;return m_(e,t,n.length)===n}function f_(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function sI(e){let t=e.byteLength;if(t<12||!so(e,0,"RIFF")||!so(e,8,"WAVE"))return;let n=f_(e),r,o,i=12;while(i+8<=t){let a=m_(e,i,4),s=n.getUint32(i+4,!0),c=i+8;if(a==="fmt "&&s>=16&&c+16<=t){let u=n.getUint16(c+2,!0),m=n.getUint32(c+4,!0),y=n.getUint32(c+8,!0),_=n.getUint16(c+14,!0);r=y>0?y:m*u*_/8}else if(a==="data"){o=Math.min(s,t-c);break}let d=c+s+s%2;if(d<=i)return;i=d}if(r===void 0||r<=0||o===void 0)return;return Li(o/r*1000)}var cI=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320,0],lI=[0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,0],dI=[44100,48000,32000,0],uI=[22050,24000,16000,0],pI=[11025,12000,8000,0];function mI(e){if(e===3)return dI;if(e===2)return uI;return pI}function fI(e,t){if(e)return t?17:32;return t?9:17}function gI(e,t){let n=e[t+1],r=e[t+2],o=e[t+3];if(n===void 0||r===void 0||o===void 0)return;let i=n>>3&3,a=n>>1&3;if(i===1||a!==1)return;let s=i===3,c=(s?cI:lI)[r>>4&15]??0,d=mI(i)[r>>2&3]??0;if(c===0||d===0)return;let u=(o>>6&3)===3;return{bitrate:c*1000,sampleRate:d,samplesPerFrame:s?1152:576,sideInfoSize:fI(s,u)}}function hI(e,t,n){let r=t+4+n;if(!so(e,r,"Xing")&&!so(e,r,"Info"))return;if(r+12>e.byteLength)return;let o=f_(e);if((o.getUint32(r+4,!1)&1)===0)return;let a=o.getUint32(r+8,!1);return a>0?a:void 0}function yI(e){if(!so(e,0,"ID3")||e.byteLength<10)return 0;let t=e[5]??0,n=0;for(let o=6;o<=9;o+=1)n=n<<7|(e[o]??0)&127;let r=(t&16)!==0?10:0;return 10+n+r}function _I(e){let t=e.byteLength,n=yI(e);for(let r=n;r+4<=t;r+=1){if(e[r]!==255||((e[r+1]??0)&224)!==224)continue;let o=gI(e,r);if(o===void 0)continue;let i=hI(e,r,o.sideInfoSize);if(i!==void 0)return Li(i*o.samplesPerFrame*1000/o.sampleRate);return Li((t-r)*8*1000/o.bitrate)}return}async function bI(e,t,n=3000){let r=[t,"-v","error","-show_entries","format=duration","-of","csv=p=0",e],o;try{o=Bun.spawn(r,{stdout:"pipe",stderr:"ignore"})}catch{return}let i=vI(o).catch(()=>{return}),a,s=new Promise((c)=>{a=setTimeout(()=>{o.kill(),setTimeout(()=>o.kill("SIGKILL"),250).unref(),c(void 0)},n)});try{let c=await Promise.race([i,s]);if(c?.exitCode!==0)return;return Li(Number(c.stdout.trim())*1000)}finally{if(a!==void 0)clearTimeout(a)}}async function vI(e){let[t,n]=await Promise.all([new Response(e.stdout).text(),e.exited]);return{stdout:t,exitCode:n}}async function g_(e){let t=aI(e.bytes,e.filePath);if(t!==void 0)return{durationMs:t,source:"header"};if(e.noProbe===!0)return{source:"none"};let n=await bI(e.filePath,e.ffprobePath??"ffprobe",e.probeTimeoutMs);if(n!==void 0)return{durationMs:n,source:"ffprobe"};return{source:"none"}}import{createInterface as zi}from"node:readline/promises";import{Writable as SI}from"node:stream";function co(){return process.stdin.isTTY===!0}var h_=5;async function y_(e,t,n){let r=e[t].value;for(let o=0;o<h_;o++){let i=(await n(`Choice [${t+1}]: `)).trim();if(i==="")return r;let a=/^\d+$/.test(i)?e[Number(i)-1]:void 0;if(a!=null)return a.value;C(`Invalid choice — enter a number between 1 and ${e.length}.`)}return C(`No valid choice after ${h_} attempts — using the default.`),r}async function __(e,t){if(t!=null)return t(e);let n=zi({input:process.stdin,output:process.stderr});try{return await n.question(e)}finally{n.close()}}async function Oc(e,t){if(t!=null)return t(e);let n=new SI({write(o,i,a){a()}}),r=zi({input:process.stdin,output:n,terminal:!0});process.stderr.write(e);try{return await r.question("")}finally{r.close(),process.stderr.write(`
|
|
88
|
+
`)}}async function Fi(e,t,n={}){let r=n.defaultIndex??0,o=(a)=>{if(n.output==null)console.log(a);else n.output.write(`${a}
|
|
89
|
+
`)};o(e);for(let[a,s]of t.entries())o(` ${a+1}) ${s.label}`);if(o(""),n.ask!=null)return y_(t,r,n.ask);let i=zi({input:process.stdin,output:n.output??process.stdout});try{return await y_(t,r,async(a)=>i.question(a))}finally{i.close()}}async function Te(e,t){if(t.yes)return;if(process.stdin.isTTY!==!0)C("Refusing to prompt in non-interactive mode. Re-run with --yes to confirm."),process.exit(A.USAGE_ERROR);let n=zi({input:process.stdin,output:process.stderr});try{let r=await n.question(`${e} [y/N] `);if(!/^y(?:es)?$/i.test(r.trim()))C("Aborted."),process.exit(A.USAGE_ERROR)}finally{n.close()}}import{Buffer as xI}from"node:buffer";async function Fe(){return new Promise((e,t)=>{let n=[];process.stdin.on("data",(r)=>n.push(r)),process.stdin.on("end",()=>e(xI.concat(n).toString("utf-8"))),process.stdin.on("error",t)})}var EI=10,wI=new Set(["UNAUTHORIZED","FORBIDDEN","API_KEY_INVALID","ADMIN_REQUIRED","INSUFFICIENT_SCOPE"]);function E_(e,t){let n=e.command("audio-files").description("Audio file library");n.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(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().audioFiles.list({page:Number(r.page),limit:Number(r.limit),search:r.search}));if(o==="json"){let s=i?a.items.map((c)=>O(c,i)):a;v(s);return}L(["ID","Name","Type","Duration"],a.items.map((s)=>({ID:s.id,Name:s.name,Type:s.type,Duration:w_(s.duration_ms)}))),ee(a)}),n.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(r,o)=>{let{format:i}=S(e.opts()),a=e.opts().yes===!0;if(o.name!=null&&r.length>1)C("--name names a single audio file; drop it when uploading several at once."),process.exit(A.USAGE_ERROR);if(o.durationMs!=null&&r.length>1)C("--duration-ms describes a single audio file; drop it when uploading several at once."),process.exit(A.USAGE_ERROR);let s=AI(o.durationMs);if(r.length>EI)await Te(`Upload ${r.length} audio files to the library?`,{yes:a});let c=[],d=A.SUCCESS;for(let u of r){let m=await TI(t(),u,{format:i,overrideMs:s,noProbe:o.probe===!1,...o.name!=null&&{name:o.name}});if(c.push(m),m.exitCode>d)d=m.exitCode;if(m.abort)break}if(kI(c,i),d!==A.SUCCESS)process.exit(d)}),n.command("show <audio_file_id>").description("Show an audio file's metadata").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().audioFiles.getById({audio_file_id:x("audio_files",r)}));if(a==null)C("Audio file not found"),process.exit(A.NOT_FOUND);if(o==="json"){v(i?O(a,i):a);return}J(Ui(a))}),n.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(r,o)=>{let{format:i}=S(e.opts()),a=e.opts(),s=a.json===!0||a.output==="json";if(o.out==="-"&&s)C("--out - streams binary audio to stdout and cannot be combined with --json."),process.exit(A.USAGE_ERROR);let c=t(),d=await b(c.audioFiles.content({audio_file_id:x("audio_files",r)})),u=new Uint8Array(await d.arrayBuffer());if(o.out==="-"){process.stdout.write(u);return}let m;if(o.out!=null)m=o.out,await S_(m,u);else m=await OI(c,r,d.name),await NI(m,u,o.force===!0);if(i==="json"){v({path:m,bytes:u.length});return}N(`Saved ${m} (${u.length} bytes)`)}),n.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(r,o)=>{let{format:i}=S(e.opts());if(o.name==null&&o.description==null)C("Nothing to update — pass --name and/or --description."),process.exit(A.USAGE_ERROR);let a=await b(t().audioFiles.update({audio_file_id:x("audio_files",r),...o.name!=null&&{name:o.name},...o.description!=null&&{description:o.description}}));if(i==="json"){v(a);return}N(`Audio file updated: ${a.name}`),J(Ui(a))}),n.command("delete <audio_file_id>").description("Delete an audio file from the library").action(async(r)=>{let{format:o}=S(e.opts()),i=e.opts().yes===!0;await Te(`Delete audio file ${r}?`,{yes:i});try{await t().audioFiles.delete({audio_file_id:x("audio_files",r)})}catch(a){DI(a,o)}if(o==="json"){v({id:r,deleted:!0});return}N(`Audio file deleted: ${r}`)}),n.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(r)=>{let{format:o}=S(e.opts()),i=await b_(r),a=await b(t().audioFiles.generateTts({name:r.name,text:i,...r.description!=null&&{description:r.description},...r.voice!=null&&{voice:r.voice},...r.model!=null&&{model:r.model}}));if(o==="json"){v(a);return}N(`TTS audio generated: ${a.id}`),J(Ui(a))}),n.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(r,o)=>{let{format:i}=S(e.opts()),a=e.opts().yes===!0,s=await b_(o);await Te(`Overwrite the audio content of ${r}?`,{yes:a});let c=await b(t().audioFiles.regenerateTts({audio_file_id:x("audio_files",r),text:s,...o.voice!=null&&{voice:o.voice},...o.model!=null&&{model:o.model}}));if(i==="json"){v(c);return}N(`TTS audio regenerated: ${c.id}`),J(Ui(c))})}var CI="FILE_UNREADABLE";function w_(e){if(e==null)return"—";if(e<60000)return`${(e/1000).toFixed(1)}s`;return Ce(e)}function AI(e){if(e==null)return;let t=Number(e);if(!Number.isInteger(t)||t<=0)C(`Invalid --duration-ms "${e}": expected a positive whole number of milliseconds.`),process.exit(A.USAGE_ERROR);return t}async function TI(e,t,n){let r;try{r=await v_(t)}catch(i){let a=i instanceof Error?i.message:String(i);if(n.format!=="json")C(`Cannot read ${t}: ${a}`);return{file:t,ok:!1,id:void 0,durationSource:"none",error:CI,message:a,exitCode:A.USAGE_ERROR,abort:!1}}let o=await RI(t,r,n);try{let i=await e.audioFiles.upload({file:new File([r],x_(t)),...n.name!=null&&{name:n.name},...o.durationMs!=null&&{duration_ms:o.durationMs}});return{file:t,ok:!0,id:i.id,durationSource:o.source,error:void 0,message:void 0,exitCode:A.SUCCESS,abort:!1}}catch(i){return II(i,t,o.source,n.format)}}async function RI(e,t,n){if(n.overrideMs!=null)return{durationMs:n.overrideMs,source:"flag"};let r=process.env.NIVA_FFPROBE,o=await g_({filePath:e,bytes:t,noProbe:n.noProbe,...r!=null&&r!==""&&{ffprobePath:r}});if(o.source==="none"&&n.format!=="json")P(`duration unknown for ${e} — install ffmpeg or pass --duration-ms`);return o}function II(e,t,n,r){let o={file:t,ok:!1,id:void 0,durationSource:n};if(!sn(e)){let a=rs(e);if(r!=="json")C(a);return{...o,error:"CONNECTION_ERROR",message:a,exitCode:A.GENERAL_ERROR,abort:!0}}let i=Tn(e);if(r!=="json")Rn(i);return{...o,error:i.code,message:i.message,exitCode:i.exitCode,abort:wI.has(i.code)}}async function OI(e,t,n){let o=[(await b(e.audioFiles.getById({audio_file_id:x("audio_files",t)})))?.filename,n,t];return x_(o.find((i)=>i!=null&&i!=="")??t)}async function NI(e,t,n){try{await S_(e,t,n?{}:{flag:"wx"})}catch(r){if(Ee(r)?.code!=="EEXIST")throw r;C(`${e} already exists — pass --out <path> to write elsewhere, or --force to overwrite it.`),process.exit(A.CONFLICT)}}function kI(e,t){if(t==="json"){v(e.map((r)=>({file:r.file,ok:r.ok,...r.id!=null&&{id:r.id},durationSource:r.durationSource,...r.error!=null&&{error:r.error},...r.message!=null&&{message:r.message}})));return}L(["File","ID","Status"],e.map((r)=>({File:r.file,ID:r.id??"—",Status:r.ok?"uploaded":r.error??"failed"})));let n=e.filter((r)=>!r.ok).length;N(`${e.length-n} uploaded, ${n} failed`)}function DI(e,t){if(!sn(e))Ct(e);let n=Tn(e),r=PI(n);if(r==null)Ct(e);if(t==="json")v({error:n.code,message:n.message,plans:r,hint:n.hint,retryable:n.retryable});else Rn(n),P(` Referenced by: ${r.join(", ")}`);process.exit(n.exitCode)}function PI(e){if(e.code!=="AUDIO_FILE_IN_USE")return;let t=e.data?.plans;if(!Array.isArray(t))return;return t.map(String)}async function b_(e){if(e.text!=null&&e.textFile!=null)C("--text and --text-file are mutually exclusive."),process.exit(A.USAGE_ERROR);if(e.text!=null)return e.text;if(e.textFile==null)C("No text to synthesize — pass --text <text> or --text-file <path|->."),process.exit(A.USAGE_ERROR);let n=(e.textFile==="-"?await Fe():await v_(e.textFile,"utf-8")).trim();if(n==="")C(`No text to synthesize: ${e.textFile==="-"?"stdin":e.textFile} is empty.`),process.exit(A.USAGE_ERROR);return n}function Ui(e){let t=[{title:"Audio file",rows:[{label:"ID",value:e.id},{label:"Name",value:e.name},{label:"Description",value:e.description},{label:"Type",value:e.type},{label:"Filename",value:e.filename},{label:"Duration",value:w_(e.duration_ms)},{label:"Size",value:e.size_bytes!=null?`${e.size_bytes} bytes`:null},{label:"Default",value:String(e.is_default)}]}];if(e.tts_text!=null||e.voice_id!=null)t.push({title:"TTS",rows:[{label:"Provider",value:e.voice_provider},{label:"Voice",value:e.voice_id},{label:"Text",value:e.tts_text}]});return t}var C_={azul:{hex:"#006eb7",status:"em-uso",note:"O azul histórico da SipPulse"},violeta:{hex:"#7b4bd4",status:"em-uso"},petroleo:{hex:"#00868c",status:"em-uso"},coral:{hex:"#ee5a5a",status:"em-uso",note:"No símbolo vira gradiente",gradient:["#ff8a5c","#e0365a"]},ambar:{hex:"#cc7200",status:"em-uso"},verde:{hex:"#1b9247",status:"em-uso",note:"Fora do software: educação"},magenta:{hex:"#be409d",status:"vaga"},anil:{hex:"#4057c2",status:"vaga"},lima:{hex:"#729513",status:"vaga"},ciano:{hex:"#0089a7",status:"vaga"}};var $I=(e)=>(e in C_),Nc=Object.keys(C_).filter((e)=>$I(e));var MI=/^(?:([^<>]*)<([^<>\s]+)>|([^<>\s]+))$/;function LI(e){let t=MI.exec(e.trim());if(t==null)return null;let n=t[2]??t[3]??"";if(!ZT().safeParse(n).success)return null;let r=t[1]?.trim().replaceAll(/^"|"$/g,"")??"";return{name:r===""?null:r,address:n}}var YV=l().trim().max(255).refine((e)=>LI(e)!=null,{message:"Invalid sender"});var A_={"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":{},"audit_log.export_requested":{},"audit_log.export_downloaded":{},"destination.created":{},"destination.updated":{},"destination.deleted":{},"destination.restored":{},"destination.purged":{},"attendant.created":{},"attendant.updated":{},"attendant.sip_credential_rotated":{},"attendant.status_set":{},"attendant.deleted":{},"attendant.restored":{},"attendant.purged":{},"pause_reason.created":{},"pause_reason.updated":{},"pause_reason.deleted":{},"pause_reason.reordered":{},"disposition.created":{},"disposition.updated":{},"disposition.deleted":{},"disposition.reordered":{},"saved_reply.created":{},"saved_reply.updated":{},"saved_reply.deleted":{},"desk_settings.updated":{},"desk_settings.defaults_created":{},"queue.created":{},"queue.updated":{},"queue.deleted":{},"queue.restored":{},"queue.purged":{},"queue.members_replaced":{},"queue.member_removed":{},"queue.members_added":{},"queue.member_updated":{},"queue.call_listened":{},"holiday.created":{},"holiday.updated":{},"holiday.deleted":{},"holiday_group.created":{},"holiday_group.updated":{},"holiday_group.deleted":{},"holiday_group.imported":{},"holiday_calendar.created":{},"holiday_calendar.updated":{},"holiday_calendar.deleted":{},"holiday_calendar.restored":{},"holiday_calendar.purged":{},"holiday_calendar.ics_imported":{},"holiday_calendar_entry.created":{},"holiday_calendar_entry.updated":{},"holiday_calendar_entry.deleted":{},"invitation.created":{},"invitation.accepted":{},"invitation.revoked":{},"invitation.resent":{},"organization.created":{},"organization.updated":{},"organization.deleted":{},"oauth.authorized":{},"oauth.denied":{},"oauth_grant.revoked":{},"secret.created":{},"secret.updated":{},"secret.deleted":{},"connector.created":{},"connector.updated":{},"connector.deleted":{},"connector.restored":{},"connector.purged":{},"connector.tested":{},"connector.enabled":{},"connector.disabled":{},"connector.sms_sent":{},"connector.phone_number.code_requested":{},"connector.phone_number.verified":{},"connector.phone_number.registered":{},"connector.phone_number.assigned":{},"connector.phone_number.removed":{},"connector.evolution.instance_created":{},"connector.evolution.instance_adopted":{},"connector.evolution.instance_released":{},"signal.created":{},"signal.updated":{},"signal.deleted":{},"signal.restored":{},"signal.purged":{},"insight_view.created":{},"insight_view.updated":{},"insight_view.deleted":{},"insight_view.reordered":{},"dashboard.updated":{},"role.created":{},"role.updated":{},"role.deleted":{},"role.restored":{},"role.purged":{},"channel.created":{},"channel.updated":{},"channel.deleted":{},"channel.activated":{},"channel.deactivated":{},"channel.restored":{},"channel.purged":{},"channel.webchat_key_rotated":{},"channel.webchat_secret_rotated":{},"schedule.created":{},"schedule.updated":{},"schedule.deleted":{},"schedule.restored":{},"schedule.purged":{},"schedule.emergency_set":{},"schedule.emergency_cleared":{},"schedule_exception.created":{},"schedule_exception.updated":{},"schedule_exception.deleted":{},"schedule_exception.restored":{},"schedule_exception.purged":{},"user.created":{},"user.signup":{},"user.login":{},"user.logout":{},"user.password_changed":{},"user.password_reset_requested":{},"user.password_reset_completed":{},"user.account_unlocked":{},"user.second_factor_enrollment_started":{},"user.second_factor_enrolled":{},"user.passkey_registered":{},"user.passkey_renamed":{},"user.passkey_removed":{},"user.second_factor_reset":{},"user.recovery_codes_regenerated":{},"user.session_revoked":{},"user.sessions_revoked":{},"user.role_changed":{},"user.suspended":{},"user.activated":{},"user.removed":{},"block_preset.created":{},"block_preset.updated":{},"block_preset.deleted":{},"saved_recipe.created":{},"saved_recipe.updated":{},"saved_recipe.deleted":{},"visual_plan.created":{},"visual_plan.cloned":{},"visual_plan.updated":{},"visual_plan.deleted":{},"visual_plan.imported":{},"visual_plan.published":{},"visual_plan.restored":{},"visual_plan.purged":{},"webhook_endpoint.created":{},"webhook_endpoint.updated":{},"webhook_endpoint.deleted":{},"webhook_endpoint.restored":{},"webhook_endpoint.purged":{},"webhook_endpoint.secret_rotated":{},"webhook_endpoint.test_sent":{},"webhook_delivery.retried":{},"system.initialized":{},"system.fs_started":{},"system.fs_restarted":{},"system.engine_restarted":{},"system.update_requested":{},"system.update_cancelled":{},"platform_settings.updated":{},"storage_config.updated":{},"recording_storage.updated":{},"storage_cache.purged":{},"platform_admin.assigned":{},"platform_admin.revoked":{},"platform_admin.owner_transferred":{},"platform_admin.mfa_policy_updated":{},"license.activated":{},"license.renewed_offline":{},"org_settings.updated":{},"org_settings.limits_updated":{},"org_plan.modules_updated":{},"org_plan.ai_credential_updated":{},"tenant_module.enabled":{},"tenant_module.disabled":{},"tenant_module.limits_updated":{},"contact.updated":{},"dialer_campaign.created":{},"dialer_campaign.updated":{},"dialer_campaign.deleted":{},"dialer_campaign.restored":{},"dialer_campaign.purged":{},"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":{},"analysis_template.restored":{},"analysis_template.purged":{},"ai_settings.updated":{},"assistant_policy.updated":{},"assistant_models.updated":{},"assistant_conversation.updated":{},"assistant_grant.revoked":{},"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":{},"call_record.export_requested":{},"call_record.export_downloaded":{},"notification.deleted":{},"notification_channel.created":{},"notification_channel.updated":{},"notification_channel.deleted":{},"notification_channel.tested":{},"notification_preference.updated":{},"notification_preference.reset":{},"screen_pop.fetched":{retention:"operational"}},zI=Object.keys(A_);var ji={telegram:{maxTextLength:4096,supportsButtons:!0,maxButtons:0,supportsList:!1,supportsCarousel:!1,supportsMedia:!0,mediaTypes:["image","audio","video","document"],supportsLocation:!0,supportsTemplate:!1,supportsMarkdown:!0,supportsTypingIndicator:!0,sessionWindow:null,maxMediaSize:{image:10485760,audio:52428800,video:52428800,document:52428800}},whatsapp:{maxTextLength:4096,supportsButtons:!0,maxButtons:3,supportsList:!0,supportsCarousel:!1,supportsMedia:!0,mediaTypes:["image","audio","video","document"],supportsLocation:!0,supportsTemplate:!0,supportsMarkdown:!0,supportsTypingIndicator:!1,sessionWindow:86400000,maxMediaSize:{image:5242880,audio:16777216,video:16777216,document:104857600}},webchat:{maxTextLength:1e4,supportsButtons:!0,maxButtons:0,supportsList:!0,supportsCarousel:!0,supportsMedia:!0,mediaTypes:["image","audio","video","document"],supportsLocation:!0,supportsTemplate:!1,supportsMarkdown:!0,supportsTypingIndicator:!0,sessionWindow:null,maxMediaSize:{image:26214400,audio:26214400,video:26214400,document:26214400}},sms:{maxTextLength:1600,supportsButtons:!1,maxButtons:0,supportsList:!1,supportsCarousel:!1,supportsMedia:!1,mediaTypes:[],supportsLocation:!1,supportsTemplate:!1,supportsMarkdown:!1,supportsTypingIndicator:!1,sessionWindow:null,maxMediaSize:{}}};var pn={label:{max:24},teaser:{max:160}};var Vi=20;var FI=/^[a-z][a-z0-9+.-]*:\/\//,R_=/^\d{1,3}(\.\d{1,3}){3}$/,UI=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,jI=/^\d{1,5}$/;function T_(e){if(e==="null")return!1;if(R_.test(e))return e==="127.0.0.1";return e.split(".").every((t)=>UI.test(t))}function Ki(e){let t=e.trim().toLowerCase().replace(FI,""),n=t.search(/[/?#]/);if(n!==-1)t=t.slice(0,n);if(t===""||t.includes("@")||t.includes("["))return null;let r=t.lastIndexOf(":"),o=t,i="";if(r!==-1){o=t.slice(0,r);let a=t.slice(r+1);if(!jI.test(a)||Number(a)<1||Number(a)>65535)return null;i=`:${Number(a)}`}if(o.endsWith("."))o=o.slice(0,-1);if(o.startsWith("*.")){let a=o.slice(2);if(!a.includes(".")||!T_(a)||R_.test(a))return null;return`*.${a}${i}`}if(!T_(o))return null;return`${o}${i}`}var kc=g({}).default({}),Dc=g({phone_number_id:l().min(1),voice_enabled:F().default(!0),chat_enabled:F().default(!0),sip_username:l().optional(),sip_password_encrypted:l().optional(),sip_password_iv:l().optional(),session_timeout_minutes:f().int().min(5).max(10080).default(1440),business_name:l().optional(),display_phone_number:l().optional(),last_webhook_received_at:Zt.datetime().optional(),last_webhook_message_id:l().optional(),last_webhook_status_id:l().optional(),last_webhook_phone_number_id:l().optional(),last_webhook_error:l().optional()}),Pc=g({bot_token:l().min(1),webhook_secret:l().min(1),allow_groups:F().default(!1),session_timeout_minutes:f().int().min(5).max(10080).default(1440),bot_username:l().optional()}),VI=l().transform((e,t)=>{let n=Ki(e);if(n==null)return t.addIssue({code:"custom",message:"Use a host with an optional port, or *.domain"}),Gm;return n}),KI=/^#[0-9a-fA-F]{6}$/,qI=Nc,BI=l().refine((e)=>qI.includes(e)||KI.test(e),{message:"Use a palette color name or #rrggbb"}),Ue={allowedOrigins:{max:20},title:{max:80},subtitle:{max:120},teaser:pn.teaser,rememberVisitorDays:{min:1,max:90,default:30},messagesPerMinute:{min:5,max:120,default:Vi},maxConcurrentSessions:{min:1,max:5000,default:200}},$c=g({allowed_origins:z(VI).min(1).max(Ue.allowedOrigins.max),appearance:g({title:l().max(Ue.title.max).default(""),subtitle:l().max(Ue.subtitle.max).default(""),teaser:l().max(Ue.teaser.max).default(""),color:BI.default("violeta"),theme:D(["auto","light","dark"]).default("auto")}).default({title:"",subtitle:"",teaser:"",color:"violeta",theme:"auto"}),prechat:g({enabled:F().default(!1),fields:g({name:F().default(!0),email:F().default(!1),phone:F().default(!1)}).default({name:!0,email:!1,phone:!1})}).default({enabled:!1,fields:{name:!0,email:!1,phone:!1}}),consent:g({enabled:F().default(!1),privacy_url:Gy({protocol:/^https$/}).optional()}).default({enabled:!1}),identity:g({enabled:F().default(!1),secret_encrypted:l().optional(),secret_iv:l().optional(),secret_hint:l().optional(),secret_created_at:Zt.datetime().optional(),previous_secret_encrypted:l().optional(),previous_secret_iv:l().optional(),previous_expires_at:Zt.datetime().optional()}).default({enabled:!1}),remember_visitor_days:f().int().min(Ue.rememberVisitorDays.min).max(Ue.rememberVisitorDays.max).default(Ue.rememberVisitorDays.default),limits:g({messages_per_minute:f().int().min(Ue.messagesPerMinute.min).max(Ue.messagesPerMinute.max).default(Ue.messagesPerMinute.default),max_concurrent_sessions:f().int().min(Ue.maxConcurrentSessions.min).max(Ue.maxConcurrentSessions.max).default(Ue.maxConcurrentSessions.default)}).default({messages_per_minute:Ue.messagesPerMinute.default,max_concurrent_sessions:Ue.maxConcurrentSessions.default}),bot_challenge:D(["auto","always","never"]).default("auto")}),I_={sip:kc,telegram:Pc,whatsapp:Dc,webchat:$c,sms:g({}).default({}),rcs:g({}).default({})};var mr=["sip"],lo=["telegram","webchat","sms","rcs"],fr=["whatsapp"],Mc=[...mr,...lo,...fr],O_=[...mr,...fr],N_=[...lo,...fr];var pK=new Set(mr),mK=new Set(fr);var eO=g({chatSessionId:l(),callRecordId:l(),orgId:l(),agentUser:l(),agentHost:l().nullable()}),tO=Ae("kind",[g({kind:I("agent_message"),text:l()}),g({kind:I("attendant_message"),text:l().min(1).optional(),media_id:l().min(1).optional(),author_user_id:l()}).refine((e)=>e.text!==void 0||e.media_id!==void 0),g({kind:I("attendant_note"),text:l().min(1),author_user_id:l(),mentions:z(l()).optional()}),g({kind:I("attendant_template"),template:l().min(1),language:l().min(1),components:z(it()),author_user_id:l()}),g({kind:I("desk_offer"),conversation_id:l()}),g({kind:I("desk_resolved"),conversation_id:l()}),g({kind:I("desk_transferred"),conversation_id:l()}),g({kind:I("timeout"),token:l(),deadlineMs:f()})]);var k_=String.raw`(?:25[0-5]|2[0-4]\d|[01]?\d\d?)`,D_=String.raw`(?:${k_}\.){3}${k_}`,nO=String.raw`${D_}(?:\/(?:3[0-2]|[12]?\d))?`,wK=new RegExp(`^${D_}$`);var He="[0-9a-fA-F]{1,4}",rO=[`(?:${He}:){7}${He}`,`(?:${He}:){1,7}:`,`(?:${He}:){1,6}:${He}`,`(?:${He}:){1,5}(?::${He}){1,2}`,`(?:${He}:){1,4}(?::${He}){1,3}`,`(?:${He}:){1,3}(?::${He}){1,4}`,`(?:${He}:){1,2}(?::${He}){1,5}`,`${He}:(?::${He}){1,6}`,`:(?::${He}){1,7}`,"::(?:ffff(?::0{1,4})?:)?"],oO=`(?:${rO.join("|")})`,iO=String.raw`${oO}(?:\/(?:12[0-8]|1[01]\d|[1-9]?\d))?`,CK=new RegExp(`^(?:${nO}|${iO})$`);function $t(e){let t=e.length;while(t>0&&e[t-1]==="/")t-=1;return e.slice(0,t)}function aO(e){let t=e;if(t==null||typeof t!=="object")throw Error("Execution plan must be a JSON object with { version, startNodeId, nodes, adjacency }");if(!("nodes"in t)||t.nodes==null||typeof t.nodes!=="object"){let n;if(!("nodes"in t))n="missing";else if(Array.isArray(t.nodes))n="an array";else n=typeof t.nodes;throw Error(`Execution plan "nodes" must be an object keyed by node ID, not ${n}`)}if(!("adjacency"in t)||t.adjacency==null||typeof t.adjacency!=="object")throw Error('Execution plan "adjacency" must be an object mapping source → { handle → target }')}function Lc(e){aO(e);let t=Object.entries(e.nodes).map(([r,o])=>({id:r,type:o.type,label:o.label,varName:o.varName,position:{x:0,y:0},config:o.config})),n=[];for(let[r,o]of Object.entries(e.adjacency))for(let[i,a]of Object.entries(o))n.push({id:`${r}-${i}-${a}`,source:r,sourceHandle:i,target:a,targetHandle:"in"});return P_({nodes:t,edges:n,viewport:{x:0,y:0,zoom:1}})}function sO(e){if(!Object.hasOwn(e,"channelType"))return e;let t={...e};return delete t.channelType,t}function cO(e){let t=e.channelType;return t==="chat"||t==="both"?t:"voice"}function P_(e){let t=e.nodes.find((o)=>o.type==="start");if(t==null)return e;let n=cO(t.config),r=e.edges.some((o)=>o.source===t.id&&o.sourceHandle==="next");return{...e,nodes:e.nodes.map((o)=>o.type==="start"?{...o,config:sO(o.config)}:o),edges:n==="both"?e.edges:e.edges.flatMap((o)=>{if(o.source!==t.id)return[o];if(r&&o.sourceHandle===n)return[];return[o.sourceHandle==="next"?{...o,sourceHandle:n}:o]})}}var $_=["rtp","sip_info","inband","other"],M_=64;var L_=g({digit:l().min(1).max(1),source:D($_),at:Zt.datetime(),node_id:l().nullable()}),lO=g({audio_in_packets:f().int().nonnegative().nullable(),audio_out_packets:f().int().nonnegative().nullable(),dtmf_in_packets:f().int().nonnegative().nullable(),codec:l().nullable(),dtmf_type:l().nullable(),jitter_max_ms:f().nullable(),loss_rate:f().nullable(),mos:f().nullable(),quality_pct:f().nullable(),digits:z(L_).max(M_)});var Pn=3600;var Yt=["none","both","caller"],zc=g({callerSpeechMs:f().int().min(0),ivrSpeechMs:f().int().min(0),version:f().int().min(1)});var mn=["post_call","live"],Fc=g({startByte:f().int().min(0),endByte:f().int().min(0),openedAtMs:f().int().min(0)}).refine((e)=>e.endByte>=e.startByte,{message:"endByte must be greater than or equal to startByte",path:["endByte"]}),z_=g({nodeId:l().min(1),kind:D(["recording","transcription","analysis"]),atByte:f().int().min(0),atMs:f().int().min(0),patch:ie(l(),it())}),F_=g({samplingPercentage:f().int().min(0).max(100).describe("Recording sampling percentage"),transcriptionSamplingPercentage:f().int().min(0).max(100).default(100).describe("Transcription sampling percentage among selected recordings"),transcriptionEnabled:F().describe("Enable transcription"),transcriptionLanguage:l().nullable().describe("Transcription language"),transcriptionMinDurationSeconds:f().int().min(0).max(Pn).describe("Minimum transcription duration"),transcriptionSpeechRequirement:D(Yt).default("none").describe("Which sides must have spoken for automatic transcription"),transcriptionType:D(mn).default("post_call").describe("Transcription type: after the call ends, or live during the whole transcription window"),anonymizeEnabled:F().describe("Anonymize the transcript"),speechAnalyticsEnabled:F().describe("Enable speech analytics"),sentimentEnabled:F().optional().describe("Enable sentiment analysis"),topicDetectionTopics:z(l()).describe("Topic detection topics"),intentDetectionIntents:z(l()).describe("Intent detection intents"),autoAnalysisEnabled:F().describe("Enable structured analyses"),autoAnalysisInheritOrg:F().describe("Inherit structured analyses from the organization"),autoAnalysisIds:z(l()).describe("Structured analysis IDs")}).transform((e)=>({...e,sentimentEnabled:e.sentimentEnabled??e.speechAnalyticsEnabled})),dO=g({speechAnalyticsEnabled:F(),sentimentEnabled:F().optional(),topicDetectionTopics:z(l()),intentDetectionIntents:z(l()),autoAnalysisEnabled:F(),autoAnalysisIds:z(l())}).transform((e)=>({...e,sentimentEnabled:e.sentimentEnabled??e.speechAnalyticsEnabled}));var uO=g({usePlan:F().default(!0).describe("Use plan recording profile"),samplingPercentage:f().int().min(0).max(100).default(100).describe("Recording sampling percentage"),transcriptionSamplingPercentage:f().int().min(0).max(100).default(100).describe("Transcription sampling percentage"),transcriptionEnabled:F().default(!1).describe("Enable transcription"),transcriptionLanguage:l().default("").describe("Transcription language"),transcriptionMinDurationSeconds:f().int().min(0).max(Pn).default(0).describe("Minimum transcription duration"),transcriptionSpeechRequirement:D(Yt).default("none").describe("Which sides must have spoken for automatic transcription"),transcriptionType:D(mn).default("post_call").describe("Transcription type: after the call ends, or live during the whole transcription window"),anonymizeEnabled:F().default(!1).describe("Anonymize the transcript"),speechAnalyticsEnabled:F().default(!1).describe("Enable speech analytics"),sentimentEnabled:F().optional().describe("Enable sentiment analysis"),topicDetectionTopics:z(l()).default([]).describe("Topic detection topics"),intentDetectionIntents:z(l()).default([]).describe("Intent detection intents"),autoAnalysisEnabled:F().default(!1).describe("Enable structured analyses"),autoAnalysisIds:z(l()).default([]).describe("Structured analysis IDs")}).transform((e)=>({...e,sentimentEnabled:e.sentimentEnabled??e.speechAnalyticsEnabled})),U_=g({sampleRate:f().int().positive(),channels:f().int().positive(),bitsPerSample:f().int().positive()});var pO=g({sampled:F(),transcriptionSampled:F().optional(),profile:F_,recordingFormat:U_.optional(),recordingIntervals:Fc.array().default([]),transcriptionWindows:Fc.array().default([]),directives:z_.array().default([]),voiceActivity:zc.optional()});var mO=["recordingEnabled","samplingPercentage","transcriptionSamplingPercentage","transcriptionEnabled","transcriptionLanguage","transcriptionMinDurationSeconds","transcriptionSpeechRequirement","transcriptionType","anonymizeEnabled","speechAnalyticsEnabled","sentimentEnabled","topicDetectionTopics","intentDetectionIntents","structuredAnalysisEnabled","structuredAnalysisIds"];function jc(e,t,n,r,o=!1){let i=fO(r),a=new Map(n.map((d)=>[d.id,d])),s=bO(t,o),c={};return gO({startNodeId:e,planState:s,nodesById:a,adjacency:r,incoming:i,result:c}),c}function fO(e){let t=new Map;for(let[n,r]of e)for(let o of r.values()){let i=t.get(o)??[];t.set(o,[...i,n])}return t}function gO(e){let{startNodeId:t,planState:n,nodesById:r,adjacency:o,incoming:i,result:a}=e,s=[t],c=new Set(s),d=0,u=Math.max(20,r.size*r.size*4);while(s.length>0&&d++<u){let m=s.shift();if(m===void 0)continue;c.delete(m);let y=r.get(m);if(y===void 0)continue;let _=hO(m,n,y,i,a);if(NO(a[m],_))continue;a[m]=_,_O(s,c,o.get(m)?.values()??[])}}function hO(e,t,n,r,o){let i=(r.get(e)??[]).map((s)=>o[s]).filter((s)=>s!==void 0),a=yO(i,t);return vO(a,n)}function yO(e,t){let n=e[0];return n===void 0?t:e.slice(1).reduce((r,o)=>IO(r,o),n)}function _O(e,t,n){for(let r of n){if(t.has(r))continue;e.push(r),t.add(r)}}function bO(e,t){let n={kind:"plan"};return{recordingEnabled:je(t,n),samplingPercentage:je(e.samplingPercentage,n),transcriptionSamplingPercentage:je(e.transcriptionSamplingPercentage,n),transcriptionEnabled:je(e.transcriptionEnabled,n),transcriptionLanguage:je(e.transcriptionLanguage,n),transcriptionMinDurationSeconds:je(e.transcriptionMinDurationSeconds,n),transcriptionSpeechRequirement:je(e.transcriptionSpeechRequirement,n),transcriptionType:je(e.transcriptionType,n),anonymizeEnabled:je(e.anonymizeEnabled,n),speechAnalyticsEnabled:je(e.speechAnalyticsEnabled,n),sentimentEnabled:je(e.sentimentEnabled,n),topicDetectionTopics:je([...e.topicDetectionTopics],n),intentDetectionIntents:je([...e.intentDetectionIntents],n),structuredAnalysisEnabled:je(e.autoAnalysisEnabled,n),structuredAnalysisIds:je([...e.autoAnalysisIds],n)}}function vO(e,t){let n=SO(t),r={kind:"node",nodeId:t.id,nodeLabel:t.label};return{recordingEnabled:Je(e.recordingEnabled,n.recordingEnabled,r),samplingPercentage:Je(e.samplingPercentage,n.samplingPercentage,r),transcriptionSamplingPercentage:Je(e.transcriptionSamplingPercentage,n.transcriptionSamplingPercentage,r),transcriptionEnabled:Je(e.transcriptionEnabled,n.transcriptionEnabled,r),transcriptionLanguage:Je(e.transcriptionLanguage,n.transcriptionLanguage,r),transcriptionMinDurationSeconds:Je(e.transcriptionMinDurationSeconds,n.transcriptionMinDurationSeconds,r),transcriptionSpeechRequirement:Je(e.transcriptionSpeechRequirement,n.transcriptionSpeechRequirement,r),transcriptionType:Je(e.transcriptionType,n.transcriptionType,r),anonymizeEnabled:Je(e.anonymizeEnabled,n.anonymizeEnabled,r),speechAnalyticsEnabled:Je(e.speechAnalyticsEnabled,n.speechAnalyticsEnabled,r),sentimentEnabled:Je(e.sentimentEnabled,n.sentimentEnabled,r),topicDetectionTopics:Je(e.topicDetectionTopics,n.topicDetectionTopics,r),intentDetectionIntents:Je(e.intentDetectionIntents,n.intentDetectionIntents,r),structuredAnalysisEnabled:Je(e.structuredAnalysisEnabled,n.structuredAnalysisEnabled,r),structuredAnalysisIds:Je(e.structuredAnalysisIds,n.structuredAnalysisIds,r)}}function SO(e){if(e.type==="recording")return xO(e.config);if(e.type==="transcription")return EO(e.config);if(e.type==="analysis")return wO(e.config);return{}}function xO(e){let t={},n=e.enabled;if(typeof n==="boolean")t.recordingEnabled=n;let r=e.samplingPercentage;if(typeof r==="number")t.samplingPercentage=r;return t}function EO(e){let t={},n=e.enabled;if(typeof n==="boolean")t.transcriptionEnabled=n;let r=e.samplingPercentage;if(typeof r==="number")t.transcriptionSamplingPercentage=r;let o=e.language;if(typeof o==="string")t.transcriptionLanguage=o.trim()||null;let i=e.minDurationSeconds;if(typeof i==="number")t.transcriptionMinDurationSeconds=i;let a=e.speechRequirement;if(AO(a))t.transcriptionSpeechRequirement=a;let s=e.transcriptionType;if(RO(s))t.transcriptionType=s;let c=e.anonymizeEnabled;if(typeof c==="boolean")t.anonymizeEnabled=c;let{speechAnalyticsEnabled:d,sentimentEnabled:u}=e;if(typeof d==="boolean")t.speechAnalyticsEnabled=d;if(typeof u==="boolean")t.sentimentEnabled=u;else if(typeof d==="boolean")t.sentimentEnabled=d;return t}function wO(e){let t={},{speechAnalyticsEnabled:n,sentimentEnabled:r}=e;if(typeof n==="boolean")t.speechAnalyticsEnabled=n;if(typeof r==="boolean")t.sentimentEnabled=r;else if(r===void 0&&typeof n==="boolean")t.sentimentEnabled=n;let o=e.topicDetectionTopics;if(Uc(o))t.topicDetectionTopics=o;let i=e.intentDetectionIntents;if(Uc(i))t.intentDetectionIntents=i;let a=e.structuredAnalysisEnabled;if(typeof a==="boolean")t.structuredAnalysisEnabled=a;let s=e.structuredAnalysisIds;if(Uc(s))t.structuredAnalysisIds=s;return t}var CO=Yt;function AO(e){return typeof e==="string"&&CO.includes(e)}var TO=mn;function RO(e){return typeof e==="string"&&TO.includes(e)}function Uc(e){return Array.isArray(e)&&e.every((t)=>typeof t==="string")}function Je(e,t,n){return t===void 0?e:je(t,n)}function je(e,t){return{kind:"known",value:e,origin:t}}function IO(e,t){return{recordingEnabled:Xe(e.recordingEnabled,t.recordingEnabled),samplingPercentage:Xe(e.samplingPercentage,t.samplingPercentage),transcriptionSamplingPercentage:Xe(e.transcriptionSamplingPercentage,t.transcriptionSamplingPercentage),transcriptionEnabled:Xe(e.transcriptionEnabled,t.transcriptionEnabled),transcriptionLanguage:Xe(e.transcriptionLanguage,t.transcriptionLanguage),transcriptionMinDurationSeconds:Xe(e.transcriptionMinDurationSeconds,t.transcriptionMinDurationSeconds),transcriptionSpeechRequirement:Xe(e.transcriptionSpeechRequirement,t.transcriptionSpeechRequirement),transcriptionType:Xe(e.transcriptionType,t.transcriptionType),anonymizeEnabled:Xe(e.anonymizeEnabled,t.anonymizeEnabled),speechAnalyticsEnabled:Xe(e.speechAnalyticsEnabled,t.speechAnalyticsEnabled),sentimentEnabled:Xe(e.sentimentEnabled,t.sentimentEnabled),topicDetectionTopics:Xe(e.topicDetectionTopics,t.topicDetectionTopics),intentDetectionIntents:Xe(e.intentDetectionIntents,t.intentDetectionIntents),structuredAnalysisEnabled:Xe(e.structuredAnalysisEnabled,t.structuredAnalysisEnabled),structuredAnalysisIds:Xe(e.structuredAnalysisIds,t.structuredAnalysisIds)}}function Xe(e,t){let n=[...j_(e),...j_(t)],r=[];for(let o of n)if(!r.some((i)=>V_(i.value,o.value)))r.push(o);if(r.length===1){let o=OO(e,t,r[0].viaNodeLabel);return je(r[0].value,o)}return{kind:"indeterminate",branches:r}}function OO(e,t,n){if(e.kind==="known")return e.origin;if(t.kind==="known")return t.origin;return{kind:"node",nodeId:"",nodeLabel:n}}function j_(e){if(e.kind==="indeterminate")return e.branches;let t=e.origin.kind==="plan"?"__plan__":e.origin.nodeLabel;return[{value:e.value,viaNodeLabel:t}]}function V_(e,t){return JSON.stringify(e)===JSON.stringify(t)}function NO(e,t){if(e===void 0)return!1;return mO.every((n)=>V_(e[n],t[n]))}function U(e){let t=e.producedVariables;return{meta:{...e.meta,inputs:e.meta.type==="start"?[]:[{key:"in",labelKey:"editor:handles.in"}],producedVariables:typeof t==="function"?(r)=>t(r):t,defaultConfig:e.configSchema.parse({})},configSchema:e.configSchema,producedVariables:e.producedVariables}}var qi="secrets",kO="secrets".replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);function K_(){return new RegExp(String.raw`\{\{\s*${kO}\.([A-Z][A-Z0-9_]*)\s*\}\}`,"g")}function q_(e){if(!e.includes("{{"))return[];let t=new Set;for(let n of e.matchAll(K_()))t.add(n[1]);return[...t]}var B_={httpRequest:new Set(["url","headers","body"]),apiSwitch:new Set(["url","headers","body"]),webhook:new Set(["url","headers","body"])};function H_(e,t){return B_[e]?.has(t)===!0}function Vc(e,t,n){if(typeof e==="string"){n(t,e);return}if(Array.isArray(e)){e.forEach((r,o)=>Vc(r,`${t}.${o}`,n));return}if(e!=null&&typeof e==="object")for(let[r,o]of Object.entries(e))Vc(o,t===""?r:`${t}.${r}`,n)}function Bi(e){let t=new Set,n=[];return Vc(e.config,"",(r,o)=>{let i=q_(o);if(i.length===0)return;let a=r.split(".")[0]??"";if(H_(e.type,a)){for(let s of i)t.add(s);return}for(let s of i)n.push({nodeId:e.id,label:e.label,field:r,name:s})}),{allowed:[...t],misplaced:n}}function Hi(e){let t=new Set,n=[];for(let r of e){let o=Bi(r);for(let i of o.allowed)t.add(i);for(let i of o.misplaced)t.add(i.name),n.push(i)}return{names:t,misplaced:n}}function DO(e){return e===`
|
|
90
|
+
`||e==="\r"||e==="\u2028"||e==="\u2029"}function PO(e,t){for(let n=t;n<e.length;n++)if(DO(e[n]))return n;return e.length}function W_(e){let t=[],n=0,r=-1,o=-1;for(;;){let i=e.indexOf("{{",n);if(i===-1)return t;if(r<i+3){if(r=e.indexOf("}}",i+3),r===-1)return t}if(o<i+2)o=PO(e,i+2);if(o<r){n=o+1;continue}t.push({start:i,end:r+2,key:e.slice(i+2,r)}),n=r+2}}function $O(e,t,n){let r="",o=0;return t.forEach((i,a)=>{r+=e.slice(o,i.start)+n(a),o=i.end}),r+e.slice(o)}function Kc(e,t){let n=[],r=0;for(let o of W_(e)){let i=o.start-1>=r&&e[o.start-1]==='"'?o.start-1:o.start,a=e[o.end]==='"'?o.end+1:o.end;n.push({start:i,end:a}),r=a}return $O(e,n,(o)=>t(e.slice(n[o].start,n[o].end)))}var Wi=200;function G_(e,t){let n=e[t];if(n==="*"||n==="+")return 1;if(n==="{"){let r=e.indexOf("}",t);if(r!==-1&&/^\d+,$/.test(e.slice(t+1,r)))return r-t+1}return 0}function MO(e,t){let n=t+1;while(n<e.length&&e[n]!=="]")n+=e[n]==="\\"?2:1;return n+1}function LO(e,t,n){let r=n.pop()??{repeat:!1},o=G_(e,t+1);if(o>0&&r.repeat)return{catastrophic:!0,next:t};if((r.repeat||o>0)&&n.length>0)n.at(-1).repeat=!0;return{catastrophic:!1,next:t+(o>0?1+o:1)}}function zO(e,t,n){let r=e[t];if(r==="\\")return{catastrophic:!1,next:t+2};if(r==="[")return{catastrophic:!1,next:MO(e,t)};if(r==="(")return n.push({repeat:!1}),{catastrophic:!1,next:t+1};if(r===")")return LO(e,t,n);let o=G_(e,t);if(o>0&&n.length>0)n.at(-1).repeat=!0;return{catastrophic:!1,next:t+(o>0?o:1)}}function qc(e){let t=[],n=0;while(n<e.length){let{catastrophic:r,next:o}=zO(e,n,t);if(r)return!0;n=o}return!1}function FO(e){let t=e.split("/");if(t.length<3)return null;return{key:t[0].trim(),pattern:t.slice(1,-1).join("/"),replacement:t.at(-1)}}function Bc(e){if(!e.includes("{{"))return{valid:!0};for(let t of W_(e)){let n=e.slice(t.start,t.end),r=FO(t.key.trim());if(r===null)continue;if(r.pattern.length>Wi)return{valid:!1,error:`Regex pattern too long in "${n}" (max ${Wi})`};if(qc(r.pattern))return{valid:!1,error:`Unsafe regex (possible catastrophic backtracking) in "${n}"`};try{new RegExp(r.pattern)}catch(o){let i=o instanceof Error?o.message:String(o);return{valid:!1,error:`Invalid regex in "${n}": ${i}`}}}return{valid:!0}}var J_=["volume","weekday_hour","composition","plans","topics","intents"],X_=l().regex(/^signal:sig_[A-Za-z0-9]+$/),UO=Be([D(J_),X_]),jO=f().int().min(1).max(4);var VO=g({id:l(),type:l(),x:f(),y:f()}),KO=g({source:l(),target:l()}),qO=g({nodes:z(VO),edges:z(KO)});var Q_=["pre","post"],Hc=["hangup","continue"];var eb=["accepted","declined","voicemail","timeout"];var tb=["voicemail","announcement","ivr","screening","unknown"],nb=["machine","human","silence","unknown"];var Wc=["busy","no_answer","failed","machine"];var Gc=["offline","available","paused","not_responding","ringing","busy","wrap_up"],rb=["attendant","system","supervisor"];var ob=["voice","chat"],ib=["queued","offered","active","waiting_customer","wrap_up","closed"],ab=["completed","abandoned","timeout","full","no_attendant","transferred","attendant_offline","refused","no_answer","busy","failed"];var BO=["useful","not_useful"],o5=[...BO,"discarded"];var uo=["channels","calls","registrations","codecs","modules","aliases"];var HO=new Set(["phone","telephone","telefone","fone","celular","cel","mobile","movel","numero","number","num","tel","msisdn","whatsapp","telefone celular","numero de telefone"]),WO=new Set(["name","nome","cliente","contato","contact","nome completo","razao social","full name"]);function GO(e){return e.normalize("NFD").replaceAll(/[\u0300-\u036F]/g,"").toLowerCase().replaceAll(/[\s\-_]+/g," ").trim()}function ZO(e){return e.normalize("NFD").replaceAll(/[\u0300-\u036F]/g,"").toLowerCase().replaceAll(/[^a-z0-9]+/g,"_").replace(/^_/,"").replace(/_$/,"")}function sb(e){return HO.has(e)||e.includes("telefone")||e.includes("phone")||e.includes("celular")}function YO(e){return WO.has(e)}function Zc(e){let t={},n={},r=new Set,o=!1,i=!1;function a(s){let c=s,d=2;while(r.has(c))c=`${s}_${String(d)}`,d+=1;return r.add(c),c}for(let s of e){let c=GO(s);if(c===""){t[s]="ignore";continue}if(sb(c)&&!o){t[s]="phone",o=!0;continue}if(YO(c)&&!i&&!sb(c)){t[s]="name",i=!0;continue}let d=ZO(s);if(d===""){t[s]="ignore";continue}t[s]="custom",n[s]=a(d)}return{roles:t,customNames:n}}var $n={_nodes:{start:{name:"Start",description:"Where every call begins — receives caller ID, DID, and timestamp"},playback:{name:"Playback",description:"Plays a message using text-to-speech or an audio file"},ivr:{name:"IVR Menu",description:"Presents a menu and routes the call based on the digit pressed"},collectDigits:{name:"Collect Digits",description:"Collects a sequence of digits like CPF, account number, or PIN"},transfer:{name:"Transfer",description:"Bridges or redirects the call to an agent, queue, or external number"},hangup:{name:"Hang Up",description:"Terminates the call — place at the end of each plan path"},timeRouting:{name:"Schedule",description:"Checks the current time against a schedule to route on/off hours"},switchCase:{name:"Condition",description:"Evaluates a variable against regex patterns to pick a path"},trafficSplit:{name:"Traffic Split",description:"Distributes calls across several paths by percentage — A/B testing, load balancing between destinations and canary rollout"},setVariable:{name:"Set Variable",description:"Saves a value to reuse later during plan execution"},sequence:{name:"Sequence",description:"Generates sequential numbers for protocols, tickets, or any identifier — DB-backed, never regresses"},counter:{name:"Counter",description:"Counts attempts, events, or anything else — per call or across calls, with an optional limit output"},httpRequest:{name:"HTTP Request",description:"Calls a REST API and stores the response for downstream nodes"},webhook:{name:"Webhook",description:"Fires an HTTP call to an external system and moves on without waiting"},dataTransform:{name:"Transform Data",description:"Applies text, number, date, list, phone, and speech operations to a value without writing code"},sendDtmf:{name:"Send DTMF",description:"Sends DTMF tones to a bridged channel or PBX"},subPlan:{name:"Sub-Plan",description:"Delegates execution to another published plan and returns"},aiAgent:{name:"AI Agent",description:"Hands the call to an AI agent for free-form conversation"},retellAgent:{name:"Retell Agent",description:"Hands the call to a Retell voice agent"},vapiAgent:{name:"Vapi Agent",description:"Hands the call to a Vapi voice assistant"},elevenlabsAgent:{name:"ElevenLabs Agent",description:"Hands the call to an ElevenLabs voice agent"},openaiLiveAgent:{name:"GPT-Live Agent",description:"Hands the call to OpenAI GPT-Live on your organization's own project"},voiceRecognition:{name:"Voice Recognition",description:"Listens to the caller, transcribes speech, and routes by intent"},tell:{name:"Message",description:"Says something to the user — plays audio in voice, sends a message in chat"},menu:{name:"Menu",description:"Presents options and routes by the user's choice — DTMF in voice, buttons in chat"},capture:{name:"Capture",description:"Collects user input — DTMF digits or speech in voice, text in chat"},routeAi:{name:"AI Classifier",description:"Classifies text via AI and routes by intent — a smart condition"},channelRouter:{name:"Channel",description:"Routes the plan based on the active channel mode (voice or chat)"},apiSwitch:{name:"API Switch",description:"Plays a prompt, collects digits, calls an API, and routes by response attribute (legacy)"},enableRecord:{name:"Enable Recording",description:"Activates call recording during plan execution with sampling and analysis options (legacy)"},recording:{name:"Recording",description:"Starts or stops recording from this point in the plan"},transcription:{name:"Transcription",description:"Chooses the transcription scope from this point in the plan"},analysis:{name:"Analysis",description:"Chooses analyses for all available transcription; each block overrides only defined fields"},whatsappTemplate:{name:"Send WhatsApp template",description:"Sends an approved Meta template through WhatsApp Business, in a voice call or in chat"},whatsappMessage:{name:"Send WhatsApp message",description:"Sends a free-text WhatsApp message through an Evolution number, with no template, in a voice call or in chat"},sendSms:{name:"Send SMS",description:"Sends a text message through Twilio, in a voice call or in chat"},phoneLookup:{name:"Phone lookup",description:"Checks a number's format and, optionally, its line type and carrier through Twilio Lookup"},verifyCode:{name:"Verify code",description:"Sends a verification code through Twilio Verify and checks it, in a voice call or in chat"},enterQueue:{name:"Enter queue",description:"Puts the call in a queue of the Mesa: the caller waits with music until an attendant takes it"},queryQueue:{name:"Query queue",description:"Reads who is waiting, who is free and the estimated wait of a queue, ready for a prompt"},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"}},_handles:{in:"In",next:"Next",timeout:"Timeout",error:"Error",answered:"Answered",busy:"Busy",noAnswer:"No Answer",failed:"Failed",sent:"Sent",completed:"Completed",valid:"Valid",invalid:"Invalid",approved:"Approved",rejected:"Rejected",recognized:"Recognized",noInput:"No Input",notApplicable:"Not Applicable",maxRetries:"Max Retries",captured:"Captured",onHours:"On Hours",offHours:"Off Hours",holiday:"Holiday",emergency:"Emergency",queueAnswered:"Answered",queueTimeout:"Timed Out",full:"Queue Full",noAttendant:"No Attendant",default:"Default",fallback:"Fallback",noMatch:"No Match",collected:"Collected",skipped:"Skipped",limitReached:"Limit Reached",voice:"Voice",chat:"Chat",telegram:"Telegram",whatsapp:"WhatsApp",webchat:"Webchat",sms:"SMS"},_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."},playback:{audio:"Audio to play. Use TTS (text-to-speech) or a pre-recorded audio file."},hangup:{cause:"SIP hangup cause code (e.g., 'NORMAL_CLEARING'). Omit for default."},ivr:{audio:"Audio prompt played before collecting DTMF input.",timeout:"Seconds to wait for DTMF input after audio finishes (1-60).",maxAttempts:"Maximum retry attempts before following the error output (1-10)."},collectDigits:{audio:"Audio prompt played before collecting digits.",minDigits:"Minimum number of digits required (1-20).",maxDigits:"Maximum number of digits to collect (1-20).",terminator:"Key that terminates digit collection (e.g., '#'). Single character.",timeout:"Seconds to wait for the first digit after audio finishes (1-60).",interDigitTimeout:"Seconds to wait between consecutive digits (1-30).",maxAttempts:"Maximum retry attempts on invalid input (1-10).",invalidAudio:"Audio played when input fails regex validation. Optional.",regex:"Regex pattern to validate collected digits. Empty means accept any.",resetDigit:"Key that clears collected digits and restarts. Single character. Empty to disable."},transfer:{method:"Transfer method. 'bridge' keeps call control; 'transfer' hands off completely.",destinations:"SIP URIs or phone numbers to dial. At least one required. Tried in order.",timeout:"Ring timeout in seconds per destination (5-120). Omit for carrier default.",attachedData:"Key/value pairs delivered to the agent at transfer (screen-pop). Values support templates."},timeRouting:{scheduleId:"Schedule ID for time-based routing. Routes to onHours/offHours/holiday outputs."},switchCase:{expression:"Template expression to evaluate, e.g., '{{ivr.digits}}'. Matched against case patterns.",cases:"List of patterns to match. Each creates a dynamic output handle 'match:<pattern>'."},trafficSplit:{paths:"Weighted paths. Each creates a dynamic output handle 'path:<name>'.",mode:"'contact' keeps the same contact on the same path (stateless hash); 'call' draws per call (stateless, approximate); 'exact' rotates through a Redis counter so the proportion closes even at low volume."},setVariable:{assignments:"List of variable assignments. At least one required."},counter:{name:"Counter name. Supports templates, e.g. 'attempts_{{start.callerid}}'.",action:"Operation applied to the counter. 'reset' sets it to zero and ignores step.",step:"Amount added or subtracted on each execution (1-1000000). Ignored when the action is 'reset'.",limit:"Value that routes to the 'limitReached' output once the counter reaches it. Empty means count only.",scope:"'call' starts from zero on every call; 'plan' persists across the calls of one plan; 'organization' persists across every plan of the organization.",ttlSeconds:"Lifetime in seconds of a 'plan' or 'organization' counter (60-31536000). Applied when the key is created, so counting does not renew the window."},httpRequest:{method:"HTTP method for the request.",url:"Request URL. Supports template expressions, e.g., 'https://api.example.com/{{start.callerid}}'.",headers:"HTTP headers as key-value pairs. Values support template expressions.",body:"Request body (JSON string). Template expressions allowed. Only for POST/PUT/PATCH.",timeout:"Request timeout in milliseconds. Omit for default."},webhook:{method:"HTTP method for the request.",url:"Destination URL. Supports template expressions, e.g., 'https://hooks.example.com/{{start.callerid}}'.",headers:"HTTP headers as key-value pairs. Values support template expressions.",body:"Request body (JSON string). Template expressions allowed. Only for POST/PUT/PATCH/DELETE."},dataTransform:{steps:"Ordered list of transformation steps. Each step transforms a value and saves the result under a name.",onError:"What to do when a step fails: 'error' follows the error output, 'empty' continues with an empty value."},subPlan:{planId:"ID of a published visual plan to execute as a subplan. Must be published."},sendDtmf:{digits:"DTMF digits to send (0-9, *, #). Supports template expressions."},aiAgent:{agent_id:"SipPulse AI agent ID to invoke. Required for execution.",agent_name:"Display name for the AI agent (used in logs and UI).",additional_instructions:"Extra instructions appended to the agent's system prompt.",variables:"Key-value pairs passed to the agent as context variables.",initial_message:"First message the agent speaks when the conversation starts.",max_duration_minutes:"Maximum conversation duration in minutes (1-60). Call ends on timeout."},retellAgent:{connector_id:"Connector that provides the voice.agent capability, such as a Retell account.",agent_id:"ID of the Retell agent that answers the call. Required for execution.",agent_name:"Display name of the chosen agent, used in logs and the editor.",variables:"Key-value pairs sent to the agent. Every value supports {{variables}}.",max_duration_minutes:"Maximum call duration in minutes (1-60). The bridge ends on timeout.",result_wait_seconds:"How long to wait for Retell's post-call extraction before continuing (0-60)."},vapiAgent:{connector_id:"Connector that provides the voice.agent capability, such as a Vapi account.",assistant_id:"ID of the Vapi assistant that answers the call. Required for execution.",assistant_name:"Display name of the chosen assistant, used in logs and the editor.",variables:"Key-value pairs sent to the agent. Every value supports {{variables}}.",max_duration_minutes:"Maximum call duration in minutes (1-60). The bridge ends on timeout.",result_wait_seconds:"How long to wait for Vapi's end of call report before continuing (0-60)."},elevenlabsAgent:{connector_id:"Connector that provides the voice.agent capability, such as an ElevenLabs account.",agent_id:"ID of the ElevenLabs agent that answers the call. Required for execution.",agent_name:"Display name of the chosen agent, used in logs and the editor.",variables:"Key-value pairs sent to the agent as X-<name> SIP headers. Every value supports {{variables}}.",max_duration_minutes:"Maximum call duration in minutes (1-60). The bridge ends on timeout.",result_wait_seconds:"How long to wait for ElevenLabs' post-call analysis before continuing (0-60)."},openaiLiveAgent:{connector_id:"Connector that provides the voice.agent capability, such as an OpenAI project.",agent_id:"Saved OpenAI agent (Agents API) the call runs. NIVA reads it at every call.",voice:"GPT-Live voice. bossa and tempo are the Brazilian Portuguese voices.",voice_instructions:"Optional persona for the voice: tone, pace, language. Empty uses the agent's instructions.",initial_message:"What the agent says to open the call, in its own words. Empty waits for the caller.",variables:"Call context handed to the agent at the start. Every value supports {{variables}}.",output_fields:"Values the agent returns when it ends, published as output.<name>.",max_duration_minutes:"Maximum call duration in minutes (1-60). The bridge ends on timeout.",result_wait_seconds:"How long to wait, after the agent leg ends, for the session to close (0-60)."},voiceRecognition:{mode:"'intent' classifies speech into configured intents; 'capture' transcribes without classification.",prompt:"Audio prompt played before listening for speech.",intents:"List of intents the LLM should classify speech into. Each creates a dynamic output. Only used in intent mode.",classification_instructions:"Additional instructions for the LLM intent classifier. Only used in intent mode.",listen:"Listening configuration: silence timeout, max duration, language, beep.",processing_audio:"Audio played while the AI processes the speech. Optional.",retry:"Retry behavior: max attempts and alternative prompt when speech is not recognized."},tell:{audio:"Audio to play via TTS, a pre-recorded file, or a remote URL. Used in voice plans.",content:"Message content to send in chat. Used in chat plans."},menu:{options:"Menu options. Each creates a dynamic output handle.",audio:"Voice audio prompt played before collecting DTMF input.",text:"Chat message text displayed above buttons. Supports template expressions.",voiceTimeout:"Seconds to wait for DTMF input in voice mode (1-60).",maxAttempts:"Maximum retry attempts for invalid input before following noMatch (1-10).",invalidMessage:"Chat message sent when input doesn't match any option. Supports template expressions."},capture:{audio:"Audio prompt played before collecting input in voice mode.",voiceMethod:"Voice input method: 'dtmf' for digits, 'speech' for ASR transcription (requires AI).",minDigits:"Minimum number of DTMF digits required (1-20).",maxDigits:"Maximum number of DTMF digits to collect (1-20).",terminators:"Key that terminates digit collection (e.g., '#').",voiceTimeout:"Seconds to wait for input in voice mode (1-60).",listen:"Listening configuration for speech capture: silence detection, max duration, language.",processing_audio:"Audio played while ASR processes the speech. Optional.",retryAudio:"Audio played on retry instead of main prompt. Falls back to main if not set.",text:"Chat prompt message sent before waiting for user input.",validation:"Regex pattern to validate chat text input. Invalid input triggers retry.",invalidMessage:"Chat message sent when input fails validation.",maxAttempts:"Maximum retry attempts for invalid or empty input (1-10)."},routeAi:{input:"Template expression to evaluate. The resolved text is classified by AI.",intents:"List of intents the AI should classify the input into. Each creates a dynamic output handle.",instructions:"Additional instructions for the AI intent classifier."},channelRouter:{},apiSwitch:{audio:"Audio prompt played before collecting digits.",chatText:"Text prompt for chat mode. Supports {{variables}}.",timeout:"Seconds to wait for digit input (1-60).",maxAttempts:"Maximum retry attempts for digit collection (1-10).",digitRegex:"Regex to validate DTMF input. Empty means accept any.",method:"HTTP method for the API request.",url:"API endpoint URL. Supports {{variables}} including collected digits as {{digits}}.",headers:"HTTP headers as key-value pairs.",body:"Request body (JSON). Supports {{variables}}. Only for POST/PUT.",requestTimeout:"HTTP request timeout in milliseconds.",attribute:"JSON attribute name from the API response to match against cases.",cases:"Possible attribute values. Each creates a dynamic output handle 'match:<value>'."},enableRecord:{percentage:"Percentage of calls to record (0-100). 100 records all calls.",minDuration:"Minimum call duration in seconds before recording starts. 0 for immediate.",analyzeCalls:"Enable post-call AI analysis (requires AI module)."},recording:{enabled:"Start or stop recording from this point",samplingPercentage:"Recording sampling percentage when recording starts"},transcription:{enabled:"Start or stop transcription at this point",samplingPercentage:"Percentage of selected recordings that will be transcribed",scope:"Transcription scope: 'from_here' uses audio recorded from this point (default/legacy); 'whole_recording' includes all audio already recorded and continues until transcription is disabled",language:"Language applied to the whole transcription",minDurationSeconds:"Minimum duration applied to the whole transcription",speechRequirement:"Skip calls without conversation, applied to the whole transcription: none, both (caller and IVR) or caller (caller only)",anonymizeEnabled:"Anonymize the whole transcript",sentimentEnabled:"Enable sentiment analysis for all available transcription; omitted fields remain inherited",transcriptionType:"Transcription type: 'post_call' transcribes when the call ends; 'live' also transcribes during the call, billed per recorded minute"},analysis:{speechAnalyticsEnabled:"Enable call summary for all available transcription; omitted fields remain inherited",sentimentEnabled:"Enable sentiment analysis for all available transcription; omitted fields remain inherited",topicDetectionTopics:"Topics for all available transcription; omitted fields remain inherited",intentDetectionIntents:"Intents for all available transcription; omitted fields remain inherited",structuredAnalysisEnabled:"Enable structured analyses for all available transcription; omitted fields remain inherited",structuredAnalysisIds:"Structured analysis IDs for all available transcription; omitted fields remain inherited"},whatsappTemplate:{connectorId:"Connector that provides the WhatsApp templates capability (whatsapp.templates).",phoneNumberId:"Number the message is sent from, one of the connector's numbers.",template:"Approved template to send, by name and language (e.g. boleto / pt_BR).",to:"Recipient. Supports {{variables}}. A number without a country code gets the block's default country code.",defaultCountry:"Country that completes numbers written without a country code. Empty uses the organization's default country.",parameters:"Template variable values. Keys: variable number or name; a media header takes the URL; a URL button takes the suffix. Supports {{variables}}."},whatsappMessage:{connectorId:"Connector that provides the free-text WhatsApp capability (whatsapp.messages), such as an Evolution API gateway.",phoneNumberId:"Number the message is sent from: one connected instance of the connector.",to:"Recipient. Supports {{variables}}. A number without a country code gets the block's default country code.",defaultCountry:"Country that completes numbers written without a country code. Empty uses the organization's default country.",text:"Message text. Supports {{variables}}. Required; at most 4096 characters once the variables are resolved."},sendSms:{connector_id:"Connector that provides the sms.send capability, such as a Twilio account.",from:"Sender. Empty uses the connector's default sender; otherwise a Messaging Service SID (MG...) or an E.164 number.",to:"Recipient. Supports {{variables}}. A number without a country code gets the block's default country code.",default_country:"Country that completes numbers written without a country code. Empty uses the organization's default country.",body:"Message text. Supports {{variables}}; secrets are not allowed in the body.",transliterate:"Replace accented letters by their base letter before sending, so the message fits 160 characters per SMS instead of 70."},phoneLookup:{connector_id:"Connector that provides the phone.lookup capability, such as a Twilio account.",number:"Number to look up. Supports {{variables}}. A number without a country code gets the block's default country code.",default_country:"Country that completes numbers written without a country code. Empty uses the organization's default country.",line_type:"Also fetch line type and carrier. Twilio charges US$ 0,008 per query; format validation alone is free.",line_type_error:"Twilio's own code and message when it could not identify the line type; empty when it did."},verifyCode:{connector_id:"Connector that provides the verify.otp capability, such as a Twilio account.",service_sid:"Verify Service SID (VA...) whose code length and sender configuration the block uses.",to:"Recipient. Supports {{variables}}. A number without a country code gets the block's default country code.",default_country:"Country that completes numbers written without a country code. Empty uses the organization's default country.",channel:"How the code reaches the contact: sms, whatsapp or call.",prompt:"Audio prompt asking for the code, played with the plan's voice. In chat, its text is sent.",max_attempts:"Maximum wrong-code attempts before the block leaves by rejected (1-5).",timeout_seconds:"Seconds to wait for the code after the prompt (1-60)."},enterQueue:{queue_id:"Public id of the queue (que_...) or a {{variable}} that holds it. Required for execution.",priority:"Priority in the queue, 0-100: a higher number is offered first. Supports {{variables}}.",max_wait_s:"Overrides the queue's maximum wait, in seconds (0 = no limit). Empty uses the queue's own.",attached_data:"Key/value pairs delivered to the attendant with the offer. Values support templates."},queryQueue:{queue_id:"Public id of the queue (que_...) or a {{variable}} that holds it. Required for execution."},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 Gi={_nodes:{start:{name:"Início",description:"Onde toda chamada começa — recebe caller ID, DID e timestamp"},playback:{name:"Reprodução",description:"Reproduz uma mensagem usando TTS ou arquivo de áudio"},ivr:{name:"Menu IVR",description:"Apresenta um menu e roteia a chamada pelo dígito pressionado"},collectDigits:{name:"Coletar Dígitos",description:"Coleta uma sequência de dígitos como CPF, número de conta ou PIN"},transfer:{name:"Transferência",description:"Conecta ou redireciona a chamada para agente, fila ou número externo"},hangup:{name:"Desligar",description:"Encerra a chamada — coloque no final de cada caminho do plano"},timeRouting:{name:"Agenda",description:"Verifica o horário atual contra uma agenda para rotear dentro/fora do expediente"},switchCase:{name:"Condição",description:"Avalia uma variável contra padrões regex para escolher um caminho"},trafficSplit:{name:"Dividir tráfego",description:"Distribuidor de chamadas por percentual entre vários caminhos — teste A/B, balanceamento entre destinos e rampa de canário"},setVariable:{name:"Definir Variável",description:"Salva um valor para reusar depois durante a execução do plano"},sequence:{name:"Sequência",description:"Gera números sequenciais para protocolos, tickets ou qualquer identificador — durável em banco, nunca regride"},counter:{name:"Contador",description:"Conta tentativas, eventos ou qualquer coisa — por chamada ou entre chamadas, com saída opcional de limite"},httpRequest:{name:"Requisição HTTP",description:"Chama uma API REST e armazena a resposta para os blocos seguintes"},webhook:{name:"Webhook",description:"Dispara uma chamada HTTP para um sistema externo e segue sem esperar"},dataTransform:{name:"Transformar Dados",description:"Aplica operações de texto, número, data, lista, telefone e fala sobre um valor sem escrever código"},sendDtmf:{name:"Enviar DTMF",description:"Envia tons DTMF para o canal conectado ou PBX"},subPlan:{name:"Sub-Plano",description:"Delega execução para outro plano publicado e retorna"},aiAgent:{name:"Agente de IA",description:"Entrega a chamada para um agente IA para conversa livre"},retellAgent:{name:"Agente Retell",description:"Entrega a chamada para um agente de voz da Retell"},vapiAgent:{name:"Agente Vapi",description:"Entrega a chamada para um assistente de voz da Vapi"},elevenlabsAgent:{name:"Agente ElevenLabs",description:"Entrega a chamada para um agente de voz da ElevenLabs"},openaiLiveAgent:{name:"Agente GPT-Live",description:"Entrega a chamada para o GPT-Live, da OpenAI, no projeto da sua organização"},voiceRecognition:{name:"Reconhecimento de Voz",description:"Ouve o chamador, transcreve a fala e roteia por intenção"},tell:{name:"Mensagem",description:"Diz algo ao usuário — reproduz áudio na voz, envia mensagem no chat"},menu:{name:"Menu",description:"Apresenta opções e roteia pela escolha do usuário — DTMF na voz, botões no chat"},capture:{name:"Captura",description:"Coleta entrada do usuário — dígitos DTMF ou fala na voz, texto no chat"},routeAi:{name:"Classificador IA",description:"Classifica texto via IA e roteia por intenção — uma condição inteligente"},channelRouter:{name:"Canal",description:"Roteia o plano com base no modo ativo do canal (voz ou chat)"},apiSwitch:{name:"API Switch",description:"Reproduz prompt, coleta dígitos, chama API e roteia pelo atributo da resposta (legado)"},enableRecord:{name:"Ativar Gravação",description:"Ativa gravação da chamada durante o plano com amostragem e análise (legado)"},recording:{name:"Gravação",description:"Inicia ou encerra a gravação a partir deste ponto do plano"},transcription:{name:"Transcrição",description:"Escolhe o escopo da transcrição a partir deste ponto do plano"},analysis:{name:"Análise",description:"Escolhe análises para toda a transcrição disponível; cada bloco sobrescreve apenas os campos definidos"},whatsappTemplate:{name:"Enviar template WhatsApp",description:"Envia um template aprovado da Meta pelo WhatsApp Business, em chamada de voz ou em chat"},whatsappMessage:{name:"Enviar mensagem WhatsApp",description:"Envia uma mensagem de texto livre pelo WhatsApp de um número Evolution, sem template, em chamada de voz ou em chat"},sendSms:{name:"Enviar SMS",description:"Envia uma mensagem de texto pela Twilio, em chamada de voz ou em chat"},phoneLookup:{name:"Consultar número",description:"Confere o formato do número e, se pedido, o tipo de linha e a operadora pela Twilio Lookup"},verifyCode:{name:"Verificar código",description:"Envia um código de verificação pela Twilio Verify e confere, em chamada de voz ou em chat"},enterQueue:{name:"Entrar na fila",description:"Coloca a chamada numa fila da Mesa: o cliente espera com música até um atendente assumir"},queryQueue:{name:"Consultar fila",description:"Lê quem espera, quem está livre e a espera estimada de uma fila, pronto para um aviso"},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"}},_handles:{in:"Entrada",next:"Próximo",timeout:"Tempo Esgotado",error:"Erro",answered:"Atendeu",busy:"Ocupado",noAnswer:"Sem Resposta",failed:"Falhou",sent:"Enviado",completed:"Concluído",valid:"Válido",invalid:"Inválido",approved:"Aprovado",rejected:"Recusado",recognized:"Reconhecido",noInput:"Sem Entrada",notApplicable:"Não Aplicável",maxRetries:"Máx. Tentativas",captured:"Capturado",onHours:"Em Horário",offHours:"Fora de Horário",holiday:"Feriado",emergency:"Emergência",queueAnswered:"Atendido",queueTimeout:"Tempo Esgotado",full:"Fila Cheia",noAttendant:"Sem Atendente",default:"Padrão",fallback:"Nenhum Caso",noMatch:"Sem Correspondência",collected:"Coletado",skipped:"Ignorado",limitReached:"Limite Atingido",voice:"Voz",chat:"Chat",telegram:"Telegram",whatsapp:"WhatsApp",webchat:"Webchat",sms:"SMS"},_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."},playback:{audio:"Áudio para reproduzir. Use TTS (texto para fala) ou arquivo de áudio pré-gravado."},hangup:{cause:"Código de causa SIP para desligamento (ex: 'NORMAL_CLEARING'). Omita para padrão."},ivr:{audio:"Prompt de áudio reproduzido antes de coletar entrada DTMF.",timeout:"Segundos de espera por entrada DTMF após o áudio (1-60).",maxAttempts:"Máximo de tentativas antes de seguir pela saída de erro (1-10)."},collectDigits:{audio:"Prompt de áudio reproduzido antes de coletar dígitos.",minDigits:"Número mínimo de dígitos necessários (1-20).",maxDigits:"Número máximo de dígitos a coletar (1-20).",terminator:"Tecla que encerra a coleta de dígitos (ex: '#'). Um caractere.",timeout:"Segundos de espera pelo primeiro dígito após o áudio (1-60).",interDigitTimeout:"Segundos de espera entre dígitos consecutivos (1-30).",maxAttempts:"Máximo de tentativas em entrada inválida (1-10).",invalidAudio:"Áudio reproduzido quando a entrada falha na validação regex. Opcional.",regex:"Padrão regex para validar dígitos coletados. Vazio aceita qualquer entrada.",resetDigit:"Tecla que limpa dígitos coletados e reinicia. Um caractere. Vazio para desabilitar."},transfer:{method:"Método de transferência. 'bridge' mantém controle da chamada; 'transfer' transfere completamente.",destinations:"URIs SIP ou números de telefone para discar. Pelo menos um obrigatório. Tentados em ordem.",timeout:"Timeout de toque em segundos por destino (5-120). Omita para padrão da operadora.",attachedData:"Pares chave/valor entregues ao atendente na transferência (screen-pop). Valores aceitam templates."},timeRouting:{scheduleId:"ID da agenda para roteamento por horário. Direciona para saídas onHours/offHours/holiday."},switchCase:{expression:"Expressão template a avaliar, ex: '{{ivr.digits}}'. Comparada com os padrões dos cases.",cases:"Lista de padrões para comparar. Cada um cria uma saída dinâmica 'match:<padrão>'."},trafficSplit:{paths:"Caminhos com peso. Cada um cria uma saída dinâmica 'path:<nome>'.",mode:"'contact' mantém o mesmo contato sempre no mesmo caminho (hash sem estado); 'call' sorteia a cada chamada (sem estado, aproximado); 'exact' usa um rodízio contado no Redis e fecha a proporção mesmo em volume baixo."},setVariable:{assignments:"Lista de atribuições de variáveis. Pelo menos uma obrigatória."},counter:{name:"Nome do contador. Suporta templates, ex: 'tentativas_{{start.callerid}}'.",action:"Operação aplicada ao contador. 'reset' zera o contador e ignora o passo.",step:"Quantidade somada ou subtraída a cada execução (1-1000000). Ignorada quando a ação é 'reset'.",limit:"Valor que direciona para a saída 'limitReached' quando o contador o alcança. Vazio apenas conta.",scope:"'call' começa do zero a cada chamada; 'plan' persiste entre as chamadas de um plano; 'organization' persiste entre todos os planos da organização.",ttlSeconds:"Tempo de vida em segundos de um contador de escopo 'plan' ou 'organization' (60-31536000). Aplicado na criação da chave, então contar não renova a janela."},httpRequest:{method:"Método HTTP da requisição.",url:"URL da requisição. Suporta expressões template, ex: 'https://api.example.com/{{start.callerid}}'.",headers:"Cabeçalhos HTTP como pares chave-valor. Valores suportam expressões template.",body:"Corpo da requisição (string JSON). Expressões template permitidas. Apenas para POST/PUT/PATCH.",timeout:"Timeout da requisição em milissegundos. Omita para padrão."},webhook:{method:"Método HTTP da requisição.",url:"URL de destino. Suporta expressões template, ex: 'https://hooks.example.com/{{start.callerid}}'.",headers:"Cabeçalhos HTTP como pares chave-valor. Valores suportam expressões template.",body:"Corpo da requisição (string JSON). Expressões template permitidas. Apenas para POST/PUT/PATCH/DELETE."},dataTransform:{steps:"Lista ordenada de passos de transformação. Cada passo transforma um valor e salva o resultado num nome.",onError:"O que fazer quando um passo falha: 'error' segue pela saída de erro, 'empty' continua com um valor vazio."},subPlan:{planId:"ID de um plano visual publicado para executar como subplano. Deve estar publicado."},sendDtmf:{digits:"Dígitos DTMF para enviar (0-9, *, #). Suporta expressões template."},aiAgent:{agent_id:"ID do agente SipPulse AI a invocar. Obrigatório para execução.",agent_name:"Nome de exibição do agente AI (usado em logs e na interface).",additional_instructions:"Instruções extras adicionadas ao prompt do sistema do agente.",variables:"Pares chave-valor passados ao agente como variáveis de contexto.",initial_message:"Primeira mensagem que o agente fala ao iniciar a conversa.",max_duration_minutes:"Duração máxima da conversa em minutos (1-60). Chamada encerra no timeout."},retellAgent:{connector_id:"Conector com a capacidade de agente de voz (voice.agent), como uma conta Retell.",agent_id:"ID do agente da Retell que atende a ligação. Obrigatório para execução.",agent_name:"Nome de exibição do agente escolhido, usado nos logs e no editor.",variables:"Pares chave-valor enviados ao agente. Cada valor aceita {{variáveis}}.",max_duration_minutes:"Duração máxima da chamada em minutos (1-60). A ponte encerra no timeout.",result_wait_seconds:"Tempo de espera pela extração pós-chamada da Retell antes de seguir (0-60)."},vapiAgent:{connector_id:"Conector com a capacidade de agente de voz (voice.agent), como uma conta Vapi.",assistant_id:"ID do assistente da Vapi que atende a ligação. Obrigatório para execução.",assistant_name:"Nome de exibição do assistente escolhido, usado nos logs e no editor.",variables:"Pares chave-valor enviados ao agente. Cada valor aceita {{variáveis}}.",max_duration_minutes:"Duração máxima da chamada em minutos (1-60). A ponte encerra no timeout.",result_wait_seconds:"Tempo de espera pelo relatório da Vapi antes de seguir (0-60)."},elevenlabsAgent:{connector_id:"Conector com a capacidade de agente de voz (voice.agent), como uma conta ElevenLabs.",agent_id:"ID do agente da ElevenLabs que atende a ligação. Obrigatório para execução.",agent_name:"Nome de exibição do agente escolhido, usado nos logs e no editor.",variables:"Pares chave-valor enviados ao agente como cabeçalhos SIP X-<nome>. Cada valor aceita {{variáveis}}.",max_duration_minutes:"Duração máxima da chamada em minutos (1-60). A ponte encerra no timeout.",result_wait_seconds:"Tempo de espera pela análise pós-chamada da ElevenLabs antes de seguir (0-60)."},openaiLiveAgent:{connector_id:"Conector com a capacidade de agente de voz (voice.agent), como um projeto da OpenAI.",agent_id:"Agente salvo na OpenAI (Agents API) que atende a chamada. O NIVA lê o agente a cada ligação.",voice:"Voz do GPT-Live. bossa e tempo são as vozes de português do Brasil.",voice_instructions:"Persona opcional da voz: tom, ritmo, idioma. Vazio usa as instruções do agente.",initial_message:"O que o agente diz para abrir a ligação, com as palavras dele. Vazio espera o cliente falar.",variables:"Contexto da chamada entregue ao agente no início. Cada valor aceita {{variáveis}}.",output_fields:"Valores que o agente devolve ao encerrar, publicados como output.<nome>.",max_duration_minutes:"Duração máxima da chamada em minutos (1-60). A ponte encerra no timeout.",result_wait_seconds:"Tempo de espera, depois que a ligação com o agente cai, pelo fechamento da sessão (0-60)."},voiceRecognition:{mode:"'intent' classifica a fala em intenções configuradas; 'capture' transcreve sem classificação.",prompt:"Prompt de áudio reproduzido antes de escutar a fala.",intents:"Lista de intenções para o LLM classificar a fala. Cada uma cria uma saída dinâmica. Só usado no modo intent.",classification_instructions:"Instruções adicionais para o classificador de intenções do LLM. Só usado no modo intent.",listen:"Configuração de escuta: timeout de silêncio, duração máxima, idioma, beep.",processing_audio:"Áudio reproduzido enquanto a IA processa a fala. Opcional.",retry:"Comportamento de retentativa: máximo de tentativas e prompt alternativo quando a fala não é reconhecida."},tell:{audio:"Áudio para reproduzir via TTS, arquivo pré-gravado ou URL remota. Usado em planos de voz.",content:"Conteúdo da mensagem a enviar no chat. Usado em planos de chat."},menu:{options:"Opções do menu. Cada uma cria uma saída dinâmica.",audio:"Prompt de áudio reproduzido antes de coletar entrada DTMF na voz.",text:"Texto da mensagem no chat, exibido acima dos botões. Suporta expressões template.",voiceTimeout:"Segundos de espera por entrada DTMF no modo voz (1-60).",maxAttempts:"Máximo de tentativas para entrada inválida antes de seguir pela saída noMatch (1-10).",invalidMessage:"Mensagem enviada no chat quando a entrada não corresponde a nenhuma opção. Suporta expressões template."},capture:{audio:"Prompt de áudio reproduzido antes de coletar entrada no modo voz.",voiceMethod:"Método de entrada por voz: 'dtmf' para dígitos, 'speech' para transcrição ASR (requer IA).",minDigits:"Número mínimo de dígitos DTMF necessários (1-20).",maxDigits:"Número máximo de dígitos DTMF a coletar (1-20).",terminators:"Tecla que encerra a coleta de dígitos (ex: '#').",voiceTimeout:"Segundos de espera por entrada no modo voz (1-60).",listen:"Configuração de escuta para captura de fala: detecção de silêncio, duração máxima, idioma.",processing_audio:"Áudio reproduzido enquanto o ASR processa a fala. Opcional.",retryAudio:"Áudio reproduzido na retentativa ao invés do prompt principal. Usa o principal se não definido.",text:"Mensagem de prompt no chat enviada antes de aguardar a entrada do usuário.",validation:"Padrão regex para validar a entrada de texto no chat. Entrada inválida aciona retentativa.",invalidMessage:"Mensagem enviada no chat quando a entrada falha na validação.",maxAttempts:"Máximo de tentativas para entrada inválida ou vazia (1-10)."},routeAi:{input:"Expressão template para avaliar. O texto resolvido é classificado pela IA.",intents:"Lista de intenções para a IA classificar a entrada. Cada uma cria uma saída dinâmica.",instructions:"Instruções adicionais para o classificador de intenções da IA."},channelRouter:{},apiSwitch:{audio:"Prompt de áudio reproduzido antes de coletar dígitos.",chatText:"Prompt de texto para modo chat. Suporta {{variáveis}}.",timeout:"Segundos de espera por entrada de dígito (1-60).",maxAttempts:"Máximo de tentativas para coleta de dígitos (1-10).",digitRegex:"Regex para validar entrada DTMF. Vazio aceita qualquer entrada.",method:"Método HTTP da requisição à API.",url:"URL do endpoint da API. Suporta {{variáveis}} incluindo dígitos coletados como {{digits}}.",headers:"Cabeçalhos HTTP como pares chave-valor.",body:"Corpo da requisição (JSON). Suporta {{variáveis}}. Apenas para POST/PUT.",requestTimeout:"Timeout da requisição HTTP em milissegundos.",attribute:"Nome do atributo JSON da resposta da API para comparar com os cases.",cases:"Valores possíveis do atributo. Cada um cria uma saída dinâmica 'match:<valor>'."},enableRecord:{percentage:"Porcentagem de chamadas a gravar (0-100). 100 grava todas.",minDuration:"Duração mínima da chamada em segundos antes de iniciar a gravação. 0 para imediato.",analyzeCalls:"Ativar análise pós-chamada por IA (requer módulo AI)."},recording:{enabled:"Iniciar ou encerrar a gravação a partir deste ponto",samplingPercentage:"Porcentagem de amostragem quando a gravação começa"},transcription:{enabled:"Iniciar ou encerrar a transcrição a partir deste ponto",samplingPercentage:"Percentual das gravações selecionadas que serão transcritas",scope:"Escopo da transcrição: 'from_here' usa o áudio gravado a partir deste ponto (padrão/legado); 'whole_recording' inclui todo o áudio já gravado e continua até a transcrição ser desligada",language:"Idioma aplicado à transcrição inteira",minDurationSeconds:"Duração mínima aplicada à transcrição inteira",speechRequirement:"Pular chamadas sem conversa, aplicado à transcrição inteira: none, both (cliente e URA) ou caller (só o cliente)",anonymizeEnabled:"Anonimizar a transcrição inteira",sentimentEnabled:"Ativar análise de sentimento para toda a transcrição disponível; campos omitidos são herdados",transcriptionType:"Tipo de transcrição: 'post_call' transcreve quando a chamada termina; 'live' também transcreve durante a chamada, custo por minuto gravado"},analysis:{speechAnalyticsEnabled:"Ativar resumo da chamada para toda a transcrição disponível; campos omitidos são herdados",sentimentEnabled:"Ativar análise de sentimento para toda a transcrição disponível; campos omitidos são herdados",topicDetectionTopics:"Tópicos para toda a transcrição disponível; campos omitidos são herdados",intentDetectionIntents:"Intenções para toda a transcrição disponível; campos omitidos são herdados",structuredAnalysisEnabled:"Ativar análises estruturadas para toda a transcrição disponível; campos omitidos são herdados",structuredAnalysisIds:"IDs das análises estruturadas para toda a transcrição disponível; campos omitidos são herdados"},whatsappTemplate:{connectorId:"Conector com a capacidade de templates do WhatsApp (whatsapp.templates).",phoneNumberId:"Número de origem da mensagem, entre os números do conector.",template:"Template aprovado a enviar, por nome e idioma (ex.: boleto / pt_BR).",to:"Destinatário. Suporta {{variáveis}}. Número sem DDI recebe o DDI padrão do bloco.",defaultCountry:"País que completa os números escritos sem DDI. Vazio usa o país padrão da organização.",parameters:"Valores das variáveis do template. Chaves: número ou nome da variável; cabeçalho de mídia recebe a URL; botão de URL recebe o sufixo. Suporta {{variáveis}}."},whatsappMessage:{connectorId:"Conector com a capacidade de mensagens livres do WhatsApp (whatsapp.messages), como um gateway Evolution API.",phoneNumberId:"Número de origem da mensagem: uma instância conectada do conector.",to:"Destinatário. Suporta {{variáveis}}. Número sem DDI recebe o DDI padrão do bloco.",defaultCountry:"País que completa os números escritos sem DDI. Vazio usa o país padrão da organização.",text:"Texto da mensagem. Suporta {{variáveis}}. Obrigatório; no máximo 4096 caracteres depois de resolver as variáveis."},sendSms:{connector_id:"Conector com a capacidade sms.send, como uma conta da Twilio.",from:"Remetente. Vazio usa o remetente padrão do conector; senão, um Messaging Service SID (MG...) ou um número E.164.",to:"Destinatário. Suporta {{variáveis}}. Número sem DDI recebe o DDI padrão do bloco.",default_country:"País que completa os números escritos sem DDI. Vazio usa o país padrão da organização.",body:"Texto da mensagem. Suporta {{variáveis}}; segredos não são permitidos no corpo.",transliterate:"Troca letras acentuadas pela letra sem acento antes de enviar, para caber 160 caracteres por SMS em vez de 70."},phoneLookup:{connector_id:"Conector com a capacidade phone.lookup, como uma conta da Twilio.",number:"Número a consultar. Suporta {{variáveis}}. Número sem DDI recebe o DDI padrão do bloco.",default_country:"País que completa os números escritos sem DDI. Vazio usa o país padrão da organização.",line_type:"Busca também o tipo de linha e a operadora. A Twilio cobra US$ 0,008 por consulta; só validar o formato é grátis.",line_type_error:"Código e mensagem da própria Twilio quando ela não conseguiu identificar o tipo de linha; vazio quando conseguiu."},verifyCode:{connector_id:"Conector com a capacidade verify.otp, como uma conta da Twilio.",service_sid:"SID do Serviço do Verify (VA...) cujo tamanho de código e remetente o bloco usa.",to:"Destinatário. Suporta {{variáveis}}. Número sem DDI recebe o DDI padrão do bloco.",default_country:"País que completa os números escritos sem DDI. Vazio usa o país padrão da organização.",channel:"Como o código chega ao contato: sms, whatsapp ou ligação.",prompt:"Áudio que pede o código, falado com a voz do plano. No chat, o texto dele é enviado.",max_attempts:"Máximo de códigos errados antes de o bloco sair por Recusado (1-5).",timeout_seconds:"Segundos de espera pelo código depois do aviso (1-60)."},enterQueue:{queue_id:"Id público da fila (que_...) ou uma {{variável}} que o contém. Obrigatório para execução.",priority:"Prioridade na fila, de 0 a 100: o número maior é oferecido primeiro. Aceita {{variáveis}}.",max_wait_s:"Substitui a espera máxima da fila, em segundos (0 = sem limite). Vazio usa a da própria fila.",attached_data:"Pares chave/valor entregues ao atendente junto com a oferta. Valores aceitam templates."},queryQueue:{queue_id:"Id público da fila (que_...) ou uma {{variável}} que o contém. Obrigatório para execução."},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 JO={en:$n,"pt-BR":Gi};function Yc(e,t="en"){return JO[t]._nodes?.[e]}var Zi=["core","ai","desk","queues","dialer","omnichannel","enterprise","assistant","copilot","classifier"],Jc=Zi.filter((e)=>e!=="core");function Mn(e,t){return typeof e.outputs==="function"?e.outputs(t):e.outputs}var cb={interaction:{order:0},handling:{order:1},routing:{order:2},media:{order:3},data:{order:4},legacy:{order:5}},XO=Object.entries(cb).sort(([,e],[,t])=>e.order-t.order).map(([e])=>e);var Xc=g({reason:l().max(128,{error:"editor:validation.dncReasonTooLong"}).default("").describe("Optional short reason recorded on the DNC entry (max 128 chars). Plain text, no templates."),phoneOverride:l().default("").describe("Optional number/template to add instead of the auto-resolved one. Supports {{variables}}. Empty = auto-resolve (dialer contact, then caller ID).")}),Qc=U({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:Xc,producedVariables:[{name:"dnc_added",type:"string",descriptionKey:"editor:vars.dncAdded"},{name:"dnc_phone",type:"string",descriptionKey:"editor:vars.dncPhone"}]});var el=g({agent_id:l().default("").describe("SipPulse AI agent ID to invoke. Required for execution."),agent_name:l().default("").describe("Display name for the AI agent (used in logs and UI)."),additional_instructions:l().default("").describe("Extra instructions appended to the agent's system prompt."),variables:ie(l(),it()).default({}).describe("Key-value pairs passed to the agent as context variables."),initial_message:l().default("").describe("First message the agent speaks when the conversation starts."),max_duration_minutes:f().min(1).max(60).default(10).describe("Maximum conversation duration in minutes (1-60). Call ends on timeout.")}),tl=U({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:el,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 nl=l().min(1).max(255).regex(/^[A-Za-z0-9_-]+$/,{error:"Invalid structured analysis id"});var rl=g({speechAnalyticsEnabled:F().optional(),sentimentEnabled:F().nullable().optional(),topicDetectionTopics:z(l()).optional(),intentDetectionIntents:z(l()).optional(),structuredAnalysisEnabled:F().optional(),structuredAnalysisIds:z(nl).max(100).optional()}),ol=U({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:rl,producedVariables:[{name:"selected",type:"number",descriptionKey:"editor:vars.analysisSelected"}]});var tN=/\{\{[^{}]*\}\}/g,nN=/^\{\{[^{}]*\}\}$/,rN=new Set(["http:","https:"]);function lb(e){if(!URL.canParse(e))return!1;return rN.has(new URL(e).protocol)}function db(e){let t=e.trim();if(t==="")return"empty";if(nN.test(t))return"from-variable";let n=0,r=t.replaceAll(tN,()=>(n+=1,`v${n}`));return lb(r)?"valid":"malformed"}function il(e){return db(e)!=="malformed"}var ub=["postgres","redis","freeswitch","engine","server"],q5=new Set(ub);var al=g({text:l().min(1,{error:"editor:validation.emptyTtsText"}).describe("Text to synthesize into speech."),voice:l().optional().describe("TTS voice ID (e.g., 'pt-BR-FranciscaNeural'). Resolved dynamically when absent."),model:l().optional().describe("TTS model ID (e.g., 'pulse-tts'). Resolved dynamically when absent.")}),ve=Be([g({tts:al.describe("Text-to-speech audio source.")}),g({file:g({id:l().min(1,{error:"editor:validation.noAudioFile"}).describe("Audio file ID from the audio library."),name:l().describe("Display name of the audio file."),path:l().describe("Storage path of the audio file.")}).describe("Pre-recorded audio file source.")}),g({url:g({value:l().min(1,{error:"editor:validation.emptyAudioUrl"}).refine(il,{error:"editor:validation.malformedAudioUrl"}).describe("Audio URL fetched at call time. Supports {{variables}}; secrets are not allowed."),fallbackTts:al.optional().describe("Spoken when the URL fails. Absent means take the error output.")}).describe("Remote audio source fetched at call time.")})]),oN=ve.optional().catch(void 0);var gr=l().refine((e)=>e.trim()!=="",{error:"editor:validation.urlRequired"}).refine((e)=>!/\s/.test(e.trim()),{error:"editor:validation.urlHasSpace"}).default("");var iN=g({value:l().min(1,{error:"editor:validation.caseValueRequired"}).default("").describe("Attribute value to match. Creates a 'match:<value>' output.")}),sl=g({audio:ve.optional().describe("Audio prompt played before collecting digits."),chatText:l().default("").describe("Text prompt for chat mode. Supports {{variables}}."),timeout:f().int().min(1).max(60).default(5).describe("Seconds to wait for digit input (1-60)."),maxAttempts:f().int().min(1).max(10).default(3).describe("Maximum retry attempts for digit collection (1-10)."),digitRegex:l().default("").describe("Regex to validate DTMF input. Empty means accept any."),method:D(["GET","POST","PUT"]).default("GET").describe("HTTP method for the API request."),url:gr.describe("API endpoint URL. Supports {{variables}} including collected digits as {{digits}}."),headers:ie(l(),l()).optional().describe("HTTP headers as key-value pairs."),body:l().optional().describe("Request body (JSON). Supports {{variables}}. Only for POST/PUT."),requestTimeout:f().int().min(1000).max(60000).default(1e4).describe("HTTP request timeout in milliseconds."),attribute:l().default("").describe("JSON attribute name from the API response to match against cases."),cases:z(iN).default([]).describe("Possible attribute values. Each creates a dynamic output handle 'match:<value>'.")}),cl=U({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:(e)=>[...(e.cases??[]).map((r)=>typeof r==="string"?r:r.value).filter((r)=>typeof r==="string"&&r!=="").map((r)=>({key:`match:${r}`,labelKey:r})),{key:"noInput",labelKey:"editor:handles.noInput"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:sl,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 aN=g({language:l().optional().describe("BCP 47 language code for speech recognition (e.g., 'pt-BR'). Omit for plan default."),initial_timeout_s:f().min(3).max(60).default(10).describe("Maximum seconds to wait for speech to begin (3-60)."),timeout_s:f().min(1).max(30).default(3).describe("Seconds of post-speech silence before stopping recording (1-30)."),max_duration_s:f().min(1).max(60).default(15).describe("Maximum recording duration in seconds (1-60)."),beep:F().default(!1).describe("Play a beep sound before starting to listen.")}),ll=g({maxAttempts:f().min(1).max(10).default(3).describe("Maximum retry attempts for invalid or empty input (1-10)."),audio:ve.optional().describe("Audio prompt played before collecting input in voice mode."),voiceMethod:D(["dtmf","speech"]).default("dtmf").describe("Voice input method: 'dtmf' for digits, 'speech' for ASR transcription (requires AI)."),minDigits:f().min(1).max(20).default(1).describe("Minimum number of DTMF digits required (1-20)."),maxDigits:f().min(1).max(20).default(1).describe("Maximum number of DTMF digits to collect (1-20)."),terminators:l().default("#").describe("Key that terminates digit collection (e.g., '#')."),voiceTimeout:f().min(1).max(60).default(5).describe("Seconds to wait for input in voice mode (1-60)."),listen:aN.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:ve.optional().describe("Audio played while ASR processes the speech. Optional."),retryAudio:ve.optional().describe("Audio played on retry instead of main prompt. Falls back to main if not set."),text:l().default("").describe("Chat prompt message sent before waiting for user input. Supports {{variables}}."),validation:l().optional().describe("Regex pattern to validate chat text input. Invalid input triggers retry."),invalidMessage:l().optional().describe("Chat message sent when input fails validation. Supports {{variables}}.")}),dl=U({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:ll,producedVariables:[{name:"text",type:"string",descriptionKey:"editor:vars.capturedText"},{name:"attempts",type:"number",descriptionKey:"editor:vars.captureAttempts"},{name:"media_url",type:"string",descriptionKey:"editor:vars.captureMediaUrl"},{name:"media_kind",type:"string",descriptionKey:"editor:vars.captureMediaKind"},{name:"media_content_type",type:"string",descriptionKey:"editor:vars.captureMediaContentType"},{name:"media_name",type:"string",descriptionKey:"editor:vars.captureMediaName"},{name:"media_size",type:"number",descriptionKey:"editor:vars.captureMediaSize"}]});var ul=g({}),pl=U({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:ul,producedVariables:[{name:"channelType",type:"string",descriptionKey:"editor:vars.channelType"}]});var ml=g({audio:ve.default({tts:{text:""}}).describe("Audio prompt played before collecting digits."),minDigits:f().min(1,{error:"editor:validation.minDigitsMin"}).max(20,{error:"editor:validation.minDigitsMax"}).default(1).describe("Minimum number of digits required (1-20)."),maxDigits:f().min(1,{error:"editor:validation.maxDigitsMin"}).max(20,{error:"editor:validation.maxDigitsMax"}).default(1).describe("Maximum number of digits to collect (1-20)."),terminator:l().max(1).default("#").describe("Key that terminates digit collection (e.g., '#'). Single character."),timeout:f().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:f().min(1,{error:"editor:validation.interDigitTimeoutMin"}).max(30,{error:"editor:validation.interDigitTimeoutMax"}).default(3).describe("Seconds to wait between consecutive digits (1-30)."),maxAttempts:f().min(1,{error:"editor:validation.attemptsMin"}).max(10,{error:"editor:validation.attemptsMax"}).default(3).describe("Maximum retry attempts on invalid input (1-10)."),invalidAudio:ve.optional().describe("Audio played when input fails regex validation. Optional."),regex:l().default("").describe("Regex pattern to validate collected digits. Empty means accept any."),resetDigit:l().max(1).default("").describe("Key that clears collected digits and restarts. Single character. Empty to disable.")}),fl=U({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:ml,producedVariables:[{name:"digits",type:"string",descriptionKey:"editor:vars.collectedDigits"},{name:"attempts",type:"number",descriptionKey:"editor:vars.collectAttempts"}]});var gl=g({name:l().min(1,{error:"editor:validation.counterNameRequired"}).default("").describe("Counter name. Supports templates, e.g. 'attempts_{{start.callerid}}'."),action:D(["increment","decrement","reset"]).default("increment").describe("Operation applied to the counter. 'reset' sets it to zero and ignores step."),step:f().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:f().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:D(["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:f().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.")}),hl=U({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:gl,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 D4=new Intl.NumberFormat("en-US",{useGrouping:!1,maximumFractionDigits:10});var lN={BR:"55",US:"1",CA:"1",MX:"52",AR:"54",CL:"56",CO:"57",PE:"51",UY:"598",PY:"595",BO:"591",EC:"593",VE:"58",PT:"351",ES:"34",GB:"44",FR:"33",DE:"49",IT:"39"},dN=Object.entries(lN).map(([e,t])=>({country:e,callingCode:t}));var pb={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 SN=new Set(["error_code","error_message","error_step","error_var"]),xN=l().refine((e)=>e.trim()!=="",{error:"editor:validation.emptySaveAs"}).refine((e)=>!SN.has(e.trim()),{error:"editor:validation.reservedSaveAs"}).describe("Name the result is saved under. Readable by later steps and by other nodes."),Se=(e)=>I(e).describe("Operation this step applies to the source."),mb=D(["minutes","hours","days","months","years"]).describe("Time unit used by the step: minutes, hours, days, months, or years."),xe=g({source:l().describe("Value the step transforms. Literal text or a template like '{{start.callerid}}'."),saveAs:xN}),EN=Ae("op",[xe.extend({op:Se("uppercase")}),xe.extend({op:Se("lowercase")}),xe.extend({op:Se("capitalize")}),xe.extend({op:Se("trim")}),xe.extend({op:Se("replace"),search:l().describe("Literal text to look for. Not a regular expression. Empty leaves the source untouched."),replacement:l().describe("Text that replaces every occurrence of the searched text.")}),xe.extend({op:Se("regexReplace"),pattern:l().describe("Regular expression used to match text. Nested repetition and patterns over 200 characters are rejected."),replacement:l().describe("Text that replaces every match. Supports JavaScript backreferences such as '$1'.")}),xe.extend({op:Se("part"),separator:l().describe("Text that splits the source into parts. Empty splits into single characters."),index:f().int().describe("Zero-based index of the part to keep. Negative counts from the end.")}),xe.extend({op:Se("add"),operand:l().describe("Number added to the source. Literal value or template.")}),xe.extend({op:Se("subtract"),operand:l().describe("Number subtracted from the source. Literal value or template.")}),xe.extend({op:Se("multiply"),operand:l().describe("Number the source is multiplied by. Literal value or template.")}),xe.extend({op:Se("divide"),operand:l().describe("Number the source is divided by. Literal value or template. Zero fails with 'divide_by_zero'.")}),xe.extend({op:Se("round"),decimals:f().int().min(0).max(10).default(0).describe("Decimal places to keep (0-10). Rounds half away from zero.")}),xe.extend({op:Se("currency"),currency:l().default("BRL").describe("ISO 4217 currency code used to format the amount, e.g. 'BRL'."),locale:l().default("pt-BR").describe("Locale used to format the amount, e.g. 'pt-BR'.")}),xe.extend({op:Se("dateOffset"),amount:f().int().describe("How many units to add to the date. Negative subtracts."),unit:mb}),xe.extend({op:Se("dateDiff"),operand:l().describe("Date compared against the source. The result is operand minus source. Literal or template."),unit:mb}),xe.extend({op:Se("dateFormat"),format:l().default("dd/MM/yyyy").describe("Output pattern, e.g. 'dd/MM/yyyy'. Text between single quotes is kept as written."),locale:l().default("pt-BR").describe("Locale used for month and weekday names, e.g. 'pt-BR'.")}),xe.extend({op:Se("normalizePhone"),country:l().default("BR").describe("ISO 3166-1 alpha-2 country code used for national numbers. Defaults to 'BR'.")}),xe.extend({op:Se("count")}),xe.extend({op:Se("join"),separator:l().default(", ").describe("Text placed between items, except before the last one."),lastSeparator:l().default(" e ").describe("Text placed before the last item. Ignored when the list has a single item.")}),xe.extend({op:Se("item"),index:f().int().describe("Zero-based index of the item to keep. Negative counts from the end.")}),xe.extend({op:Se("filter"),field:l().default("").describe("Object field compared on each item. Empty compares the item itself."),operand:l().describe("Value each item is compared against, as text. Literal or template.")}),xe.extend({op:Se("spellOut")}),xe.extend({op:Se("inWords")}),xe.extend({op:Se("default"),operand:l().describe("Value used when the source is empty. Literal value or template.")})]),yl=g({steps:z(EN).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:D(["error","empty"]).default("error").describe("What to do when a step fails: 'error' follows the error output, 'empty' continues with an empty value.")}),_l=U({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:yl,producedVariables:(e)=>{let t=new Map;for(let n of e.steps){if(n.saveAs==="")continue;t.set(n.saveAs,{name:n.saveAs,type:pb[n.op],descriptionKey:"editor:vars.transformed"})}return[...t.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 bl=g({connector_id:l().default("").describe("Public id of the connector that provides voice.agent (an ElevenLabs account). Required for execution."),agent_id:l().default("").describe("Id of the ElevenLabs agent that answers the call. Required for execution."),agent_name:l().default("").describe("Display name of the chosen ElevenLabs agent, for logs and the editor."),variables:ie(l(),l()).default({}).describe("Key-value pairs sent to the agent as X-<name> SIP headers. Every value supports {{variables}}."),max_duration_minutes:f().min(1).max(60).default(10).describe("Maximum call duration in minutes (1-60). The bridge ends on timeout."),result_wait_seconds:f().int().min(0).max(60).default(15).describe("How long to wait for ElevenLabs' post-call analysis before continuing.")}),vl=U({meta:{type:"elevenlabsAgent",module:"ai",nameKey:"editor:nodes.elevenlabsAgent.name",descriptionKey:"editor:nodes.elevenlabsAgent.description",color:"iris",icon:"Sparkles",category:"handling",order:5,nature:"composite",display:"full",channel:"voice",requires:"voice.agent",connector:{kind:"elevenlabs",configKey:"connector_id"},outputs:[{key:"completed",labelKey:"editor:handles.completed"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:bl,producedVariables:[{name:"duration_ms",type:"number",descriptionKey:"editor:vars.elevenlabsAgent.durationMs"},{name:"provider_call_id",type:"string",descriptionKey:"editor:vars.elevenlabsAgent.providerCallId"},{name:"ended_reason",type:"string",descriptionKey:"editor:vars.elevenlabsAgent.endedReason"},{name:"summary",type:"string",descriptionKey:"editor:vars.elevenlabsAgent.summary"},{name:"analysis_pending",type:"string",descriptionKey:"editor:vars.elevenlabsAgent.analysisPending"},{name:"output.*",type:"string",descriptionKey:"editor:vars.elevenlabsAgent.output"}]});var Sl=g({percentage:f().int().min(0).max(100).default(100).describe("Percentage of calls to record (0-100). 100 records all calls."),minDuration:f().int().min(0).default(0).describe("Minimum call duration in seconds before recording starts. 0 for immediate."),analyzeCalls:F().default(!1).describe("Enable post-call AI analysis (requires AI module).")}),xl=U({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:Sl,producedVariables:[{name:"recording",type:"string",descriptionKey:"editor:vars.recordingStatus"}]});function Yi(e){let t=g({key:l().describe(e.key),value:l().default("").describe("Field value. Supports template expressions like '{{cliente.nome}}'.")});return z(t).default([]).describe(e.list).superRefine((n,r)=>{let o=new Set;n.forEach((i,a)=>{let s=i.key.trim();if(s===""){r.addIssue({code:"custom",message:"editor:validation.attachedKeyRequired",path:[a,"key"]});return}if(o.has(s))r.addIssue({code:"custom",message:"editor:validation.duplicateAttachedKey",path:[a,"key"]});o.add(s)})})}var El=g({queue_id:l().default("").describe("Public id of the queue (que_...) or a {{variable}} that holds it. Required for execution."),priority:Be([Di().min(0).max(100),l()]).default(0).describe("Priority in the queue, 0-100: a higher number is offered first. Supports {{variables}}."),max_wait_s:Be([Di().min(0).max(86400),l()]).optional().describe("Overrides the queue's maximum wait, in seconds (0 = no limit). Empty uses the queue's own."),attached_data:Yi({key:"Attached-data field name shown to the attendant (e.g. 'Nome').",list:"Key/value pairs delivered to the attendant with the offer. Values support templates."})}),wl=U({meta:{type:"enterQueue",module:"queues",nameKey:"editor:nodes.enterQueue.name",descriptionKey:"editor:nodes.enterQueue.description",color:"amber",icon:"ListOrdered",category:"handling",order:7,nature:"action",display:"full",channel:"both",outputs:[{key:"answered",labelKey:"editor:handles.queueAnswered"},{key:"timeout",labelKey:"editor:handles.queueTimeout"},{key:"full",labelKey:"editor:handles.full"},{key:"noAttendant",labelKey:"editor:handles.noAttendant"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:El,producedVariables:[{name:"conversation_id",type:"string",descriptionKey:"editor:vars.enterQueue.conversationId"},{name:"outcome",type:"string",descriptionKey:"editor:vars.enterQueue.outcome"},{name:"wait_s",type:"number",descriptionKey:"editor:vars.enterQueue.waitS"},{name:"attendant_id",type:"string",descriptionKey:"editor:vars.enterQueue.attendantId"},{name:"note",type:"string",descriptionKey:"editor:vars.enterQueue.note"},{name:"disposition",type:"string",descriptionKey:"editor:vars.enterQueue.disposition"},{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"}]});var Cl=g({cause:l().optional().describe("SIP hangup cause code (e.g., 'NORMAL_CLEARING'). Omit for default.")}),Al=U({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:Cl,producedVariables:[]});var Tl=g({method:D(["GET","POST","PUT","PATCH","DELETE"]).default("GET").describe("HTTP method for the request."),url:gr.describe("Request URL. Supports template expressions, e.g., 'https://api.example.com/{{start.callerid}}'."),headers:ie(l(),l()).optional().describe("HTTP headers as key-value pairs. Values support template expressions."),body:l().optional().describe("Request body (JSON string). Template expressions allowed. Only for POST/PUT/PATCH."),timeout:f().optional().describe("Request timeout in milliseconds. Omit for default.")}),Rl=U({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:Tl,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 Il=g({audio:ve.default({tts:{text:""}}).describe("Audio prompt played before collecting DTMF input."),timeout:f().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:f().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).")}),Ol=U({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:Il,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 Nl=g({id:l().min(1).default("").describe("Unique option identifier. Used as button ID in chat and output handle suffix."),label:l().min(1).default("").describe("Display label shown to the user. Button text in chat, spoken in voice prompt."),digit:l().default("").describe("DTMF digit for voice mode (0-9, *, #). Leave empty to skip voice for this option.")}),kl=g({options:z(Nl).default([]).describe("Menu options. Each creates a dynamic output handle."),maxAttempts:f().min(1).max(10).default(3).describe("Maximum retry attempts for invalid input before following noMatch (1-10)."),audio:ve.optional().describe("Voice audio prompt played before collecting DTMF input. If omitted, caller hears nothing before digit collection."),voiceTimeout:f().min(1).max(60).default(5).describe("Seconds to wait for DTMF input in voice mode (1-60)."),text:l().default("").describe("Chat message text displayed above buttons. Supports template expressions."),invalidMessage:l().optional().describe("Chat message sent when input doesn't match any option. Supports template expressions.")}),Dl=U({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:(e)=>[...(e.options??[]).map((r)=>typeof r==="object"&&r!=null?r:null).filter((r)=>r!=null&&typeof r.id==="string"&&r.id!=="").map((r)=>({key:`option:${r.id}`,labelKey:r.label})),{key:"noMatch",labelKey:"editor:handles.noMatch"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:kl,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 Pl=g({name:l().default("").describe("Variable name: lowercase letters, digits and underscores (output.<name>)."),description:l().default("").describe("What the agent must put in this field. The backend model reads it as the parameter description."),required:F().default(!0).describe("Whether the agent must fill the field before ending.")}),po=/^[a-z][a-z0-9_]{0,63}$/u,mo=g({connector_id:l().default("").describe("Public id of the connector that provides voice.agent (an OpenAI project). Required for execution."),agent_id:l().default("").describe("Id of the saved OpenAI agent (Agents API) the call runs. Required for execution."),voice:l().default("bossa").describe("GPT-Live voice (audio.output.voice). bossa and tempo are the Brazilian Portuguese voices."),voice_instructions:l().default("").describe("Optional persona for the voice layer (tone, pace, language). Empty uses the saved agent's instructions. Supports {{variables}}."),initial_message:l().default("").describe("What the agent says to open the call, in its own words. Empty waits for the caller. Supports {{variables}}."),variables:ie(l(),l()).default({}).describe("Call context handed to the agent at the start. Every value supports {{variables}}."),output_fields:z(Pl).default([]).describe("Values the agent returns when it ends the call, published as output.<name>."),max_duration_minutes:f().min(1).max(60).default(10).describe("Maximum call duration in minutes (1-60). The bridge ends on timeout."),result_wait_seconds:f().int().min(0).max(60).default(10).describe("How long to wait, after the call leg ends, for GPT-Live to close the session and report.")}),$l=U({meta:{type:"openaiLiveAgent",module:"ai",nameKey:"editor:nodes.openaiLiveAgent.name",descriptionKey:"editor:nodes.openaiLiveAgent.description",color:"iris",icon:"AudioWaveform",category:"handling",order:6,nature:"composite",display:"full",channel:"voice",requires:"voice.agent",connector:{kind:"openai_live",configKey:"connector_id"},outputs:[{key:"completed",labelKey:"editor:handles.completed"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:mo,producedVariables:(e)=>[{name:"duration_ms",type:"number",descriptionKey:"editor:vars.openaiLiveAgent.durationMs"},{name:"provider_call_id",type:"string",descriptionKey:"editor:vars.openaiLiveAgent.providerCallId"},{name:"ended_reason",type:"string",descriptionKey:"editor:vars.openaiLiveAgent.endedReason"},{name:"transcript",type:"string",descriptionKey:"editor:vars.openaiLiveAgent.transcript"},{name:"analysis_pending",type:"string",descriptionKey:"editor:vars.openaiLiveAgent.analysisPending"},...e.output_fields.filter((t)=>po.test(t.name)).map((t)=>({name:`output.${t.name}`,type:"string",descriptionKey:"editor:vars.openaiLiveAgent.outputField"}))]});var Ml=g({connector_id:l().default("").describe("Public id of the connector that provides phone.lookup (a Twilio account). Required for execution."),number:l().default("{{Start.callerid}}").describe("Number expression. Supports {{variables}}. Normalized with the platform E.164 rule: a number without a country code is completed with the country below, or the organization's default country."),default_country:l().regex(/^([A-Za-z]{2})?$/u,{error:"editor:validation.whatsappCountry"}).default("").describe("ISO 3166-1 alpha-2 country (e.g. BR) that completes numbers written without a country code. Empty uses the organization's default country."),line_type:F().default(!1).describe("Also fetch line type and carrier. Twilio charges US$ 0,008 per query; format validation alone is free.")}),Ll=U({meta:{type:"phoneLookup",module:"core",nameKey:"editor:nodes.phoneLookup.name",descriptionKey:"editor:nodes.phoneLookup.description",color:"blue",icon:"PhoneForwarded",category:"data",nature:"action",display:"compact",channel:"both",order:10,requires:"phone.lookup",connector:{kind:"twilio",configKey:"connector_id"},outputs:[{key:"valid",labelKey:"editor:handles.valid"},{key:"invalid",labelKey:"editor:handles.invalid"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:Ml,producedVariables:[{name:"phone_number",type:"string",descriptionKey:"editor:vars.phoneLookup.phoneNumber"},{name:"national_format",type:"string",descriptionKey:"editor:vars.phoneLookup.nationalFormat"},{name:"country_code",type:"string",descriptionKey:"editor:vars.phoneLookup.countryCode"},{name:"line_type",type:"string",descriptionKey:"editor:vars.phoneLookup.lineType"},{name:"carrier_name",type:"string",descriptionKey:"editor:vars.phoneLookup.carrierName"},{name:"line_type_error",type:"string",descriptionKey:"editor:vars.phoneLookup.lineTypeError"}]});var zl=g({audio:ve.default({tts:{text:""}}).describe("Audio to play. Use TTS (text-to-speech) or a pre-recorded audio file.")}),Fl=U({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:zl,producedVariables:[]});var Ul=g({queue_id:l().default("").describe("Public id of the queue (que_...) or a {{variable}} that holds it. Required for execution.")}),jl=U({meta:{type:"queryQueue",module:"queues",nameKey:"editor:nodes.queryQueue.name",descriptionKey:"editor:nodes.queryQueue.description",color:"amber",icon:"ChartNoAxesColumn",category:"handling",order:8,nature:"action",display:"compact",channel:"voice",outputs:[{key:"default",labelKey:"editor:handles.default"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:Ul,producedVariables:[{name:"waiting",type:"number",descriptionKey:"editor:vars.queryQueue.waiting"},{name:"available",type:"number",descriptionKey:"editor:vars.queryQueue.available"},{name:"estimated_wait_s",type:"number",descriptionKey:"editor:vars.queryQueue.estimatedWaitS"},{name:"estimated_wait_text",type:"string",descriptionKey:"editor:vars.queryQueue.estimatedWaitText"},{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"}]});var Vl=g({enabled:F().optional(),samplingPercentage:f().int().min(0).max(100).optional()}),Kl=U({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:Vl,producedVariables:[{name:"status",type:"string",descriptionKey:"editor:vars.recordingStatus"}]});var ql=g({connector_id:l().default("").describe("Public id of the connector that provides voice.agent (a Retell account). Required for execution."),agent_id:l().default("").describe("Id of the Retell agent that answers the call. Required for execution."),agent_name:l().default("").describe("Display name of the chosen Retell agent, for logs and the editor."),variables:ie(l(),l()).default({}).describe("Key-value pairs sent to the agent. Every value supports {{variables}}."),max_duration_minutes:f().min(1).max(60).default(10).describe("Maximum call duration in minutes (1-60). The bridge ends on timeout."),result_wait_seconds:f().int().min(0).max(60).default(15).describe("How long to wait for Retell's post-call extraction before continuing.")}),Bl=U({meta:{type:"retellAgent",module:"ai",nameKey:"editor:nodes.retellAgent.name",descriptionKey:"editor:nodes.retellAgent.description",color:"iris",icon:"AudioLines",category:"handling",order:3,nature:"composite",display:"full",channel:"voice",requires:"voice.agent",connector:{kind:"retell",configKey:"connector_id"},outputs:[{key:"completed",labelKey:"editor:handles.completed"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:ql,producedVariables:[{name:"duration_ms",type:"number",descriptionKey:"editor:vars.retellAgent.durationMs"},{name:"provider_call_id",type:"string",descriptionKey:"editor:vars.retellAgent.providerCallId"},{name:"ended_reason",type:"string",descriptionKey:"editor:vars.retellAgent.endedReason"},{name:"summary",type:"string",descriptionKey:"editor:vars.retellAgent.summary"},{name:"analysis_pending",type:"string",descriptionKey:"editor:vars.retellAgent.analysisPending"},{name:"output.*",type:"string",descriptionKey:"editor:vars.retellAgent.output"}]});var wN=g({label:l().min(1).describe("Intent name. Creates a dynamic output handle 'intent:<label>'."),description:l().default("").describe("Description of what this intent means, used for LLM classification.")}),Hl=g({input:l().default("").describe("Template expression to evaluate, e.g. '{{resposta}}'. The resolved text is classified by AI."),intents:z(wN).default([]).describe("List of intents the LLM should classify the input into. Each creates a dynamic output handle."),instructions:l().default("").describe("Additional instructions for the LLM intent classifier.")}),Wl=U({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:(e)=>[...(e.intents??[]).map((r)=>r.label).filter((r)=>typeof r==="string"&&r!=="").map((r)=>({key:`intent:${r}`,labelKey:r})),{key:"notApplicable",labelKey:"editor:handles.notApplicable"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:Hl,producedVariables:[{name:"intent",type:"string",descriptionKey:"editor:vars.routeAi.intent"},{name:"confidence",type:"number",descriptionKey:"editor:vars.routeAi.confidence"}]});var Gl=g({digits:l().min(1,{error:"editor:validation.digitsRequired"}).default("").describe("DTMF digits to send (0-9, *, #). Supports template expressions.")}),Zl=U({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:Gl,producedVariables:[{name:"dtmf",type:"string",descriptionKey:"editor:vars.dtmf"}]});var Yl=g({connector_id:l().default("").describe("Public id of the connector that provides sms.send (a Twilio account). Required for execution."),from:l().default("").describe("Sender expression: empty uses the connector's default sender, otherwise a Messaging Service SID (MG...) or an E.164 number."),to:l().default("{{Start.callerid}}").describe("Recipient expression. Supports {{variables}}. Normalized with the platform E.164 rule: a number without a country code is completed with the country below, or the organization's default country."),default_country:l().regex(/^([A-Za-z]{2})?$/u,{error:"editor:validation.whatsappCountry"}).default("").describe("ISO 3166-1 alpha-2 country (e.g. BR) that completes recipients written without a country code. Empty uses the organization's default country."),body:l().default("").describe("Message text. Supports {{variables}}; secrets are not allowed in the body."),transliterate:F().default(!1).describe("Replace accented letters by their base letter before sending, so the message fits 160 characters per SMS instead of 70.")}),Jl=U({meta:{type:"sendSms",module:"core",nameKey:"editor:nodes.sendSms.name",descriptionKey:"editor:nodes.sendSms.description",color:"green",icon:"MessageSquare",category:"data",nature:"sideEffect",display:"compact",channel:"both",order:9,requires:"sms.send",connector:{kind:"twilio",configKey:"connector_id"},outputs:[{key:"sent",labelKey:"editor:handles.sent"},{key:"failed",labelKey:"editor:handles.failed"}]},configSchema:Yl,producedVariables:[{name:"message_sid",type:"string",descriptionKey:"editor:vars.sendSms.messageSid"},{name:"segments",type:"number",descriptionKey:"editor:vars.sendSms.segments"},{name:"encoding",type:"string",descriptionKey:"editor:vars.sendSms.encoding"},{name:"error_code",type:"string",descriptionKey:"editor:vars.sendSms.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.sendSms.errorMessage"}]});var Xl=g({prefix:l().max(16,{error:"editor:validation.prefixMaxLength"}).default("").describe("Short prefix prepended to the sequence (e.g. 'SAC', '200')."),dateFormat:D(["none","yyyyMMdd","yyMMdd","yyyyMM","ddMMyyyy","yyyyMMddHHmmss"]).default("yyyyMMdd").describe("Date format inserted between prefix and counter."),padding:f().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:D(["daily","monthly","never"]).default("daily").describe("When the counter resets to 1. Uses org timezone for boundary.")}),Ql=U({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:Xl,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 CN=g({key:l().describe("Variable name. Readable as '{{vars.key}}' and through the block's generated namespace."),value:l().describe("Value to assign. Supports template expressions like '{{start.callerid}}'.")}),ed=g({assignments:z(CN).min(1,{error:"editor:validation.noAssignments"}).default([]).describe("List of variable assignments. At least one required.")}),td=U({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:ed,producedVariables:(e)=>e.assignments.map((t)=>({name:t.key,type:"string",descriptionKey:"editor:vars.custom"}))});var nd=g({autoAnswer:F().optional().describe("Auto-answer incoming call before processing. Disable for pre-answer routing.")}),rd=U({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:[{key:"voice",labelKey:"editor:handles.voice"},{key:"chat",labelKey:"editor:handles.chat"}]},configSchema:nd,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 od=g({planId:l().min(1,{error:"editor:validation.planIdRequired"}).default("").describe("ID of a published visual plan to execute as a sub-flow. Must be published."),args:ie(l().regex(/^[A-Z_]\w*$/i).max(64),l().max(512)).default({}),endCallOnChildHangup:F().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.")}),id=U({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:od,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 AN=g({pattern:l().min(1,{error:"editor:validation.casePatternRequired"}).default("").describe("Value to match against the expression. Creates a 'match:<pattern>' output.")}),ad=g({expression:l().min(1,{error:"editor:validation.expressionRequired"}).default("").describe("Template expression to evaluate, e.g., '{{ivr.digits}}'. Matched against case patterns."),cases:z(AN).default([]).describe("List of patterns to match. Each creates a dynamic output handle 'match:<pattern>'.")}),sd=U({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:(e)=>[...(e.cases??[]).map((r)=>typeof r==="string"?r:r.pattern).filter((r)=>typeof r==="string"&&r!=="").map((r)=>({key:`match:${r}`,labelKey:r})),{key:"fallback",labelKey:"editor:handles.fallback"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:ad,producedVariables:[{name:"destination",type:"string",descriptionKey:"editor:vars.switchDestination"}]});var fb=["image","audio","video","document"],Ji=1048576,TN={image:10*Ji,audio:16*Ji,video:16*Ji,document:20*Ji};var Xi=D(fb),hr=g({id:l().describe("Public TypeID of the attachment (media_...)."),kind:Xi,content_type:l().describe("Type sniffed from the file content."),size_bytes:f().int().nonnegative(),filename:l().nullable(),transcript:l().nullable().describe("Transcript of an audio attachment, when it could be produced.")}),RN=hr.extend({url:l().describe("Signed download link."),url_expires_at:Zt.datetime()});var IN=g({type:I("text"),text:l().min(1)}),gb=Ae("provider",[g({provider:I("telegram"),file_id:l().min(1),file_name:l().optional(),mime_type:l().optional()}),g({provider:I("whatsapp"),media_id:l().min(1),file_name:l().optional(),mime_type:l().optional()}),g({provider:I("evolution"),base64:l().optional(),mime_type:l().optional(),file_name:l().optional(),message_key:g({id:l().min(1),remote_jid:l().min(1),from_me:F()})}),g({provider:I("webchat"),media_id:l().min(1)})]),ON=g({type:I("media"),mediaType:Xi,caption:l().optional(),source:gb,attachment:hr.optional()}),NN=g({type:I("location"),lat:f(),lng:f()}),kN=g({type:I("button_reply"),buttonId:l().min(1),buttonText:l()}),DN=g({type:I("list_reply"),listId:l().min(1),listTitle:l()}),PN=g({type:I("command"),command:l().min(1),args:l().optional()}),$N=Ae("type",[IN,ON,NN,kN,DN,PN]),yr=g({id:l().min(1),label:l().min(1)}),MN=g({id:l().min(1),title:l().min(1),description:l().optional()}),Qi=g({title:l().min(1),items:z(MN).min(1)}),hb=g({title:l().min(1),description:l().optional(),imageUrl:l().optional(),buttons:z(yr).default([])}),LN=g({type:I("text"),text:l().min(1),markdown:F().optional()}),zN=g({type:I("media"),mediaType:D(["image","audio","video","document"]),url:l().min(1),caption:l().optional()}),FN=g({type:I("location"),lat:f(),lng:f(),label:l().optional()}),UN=g({type:I("buttons"),text:l().min(1),buttons:z(yr).min(1)}),jN=g({type:I("list"),text:l().min(1),buttonText:l().min(1),sections:z(Qi).min(1)}),VN=g({type:I("carousel"),cards:z(hb).min(1)}),KN=g({type:I("template"),templateId:l().min(1),params:ie(l(),l()).default({})}),ea=Ae("type",[LN,zN,FN,UN,jN,VN,KN]),qN=ea.optional().catch(void 0);var cd=g({audio:ve.optional().describe("Audio to play via TTS, a pre-recorded file, or a remote URL. Used in voice plans."),content:ea.optional().describe("Message content to send in chat. Used in chat plans.")});function yb(e){return typeof e==="object"&&e!==null&&"url"in e}var ld=U({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:(e)=>yb(e.audio)?[{key:"next",labelKey:"editor:handles.next"},{key:"error",labelKey:"editor:handles.error"}]:[{key:"next",labelKey:"editor:handles.next"}]},configSchema:cd,producedVariables:(e)=>yb(e.audio)?[{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"}]:[]});var dd=g({scheduleId:l().optional().describe("Schedule ID for time-based routing. Routes to onHours/offHours/holiday outputs."),emergencyOutput:F().default(!1).describe("Adds an 'emergency' output taken while the schedule is in emergency; otherwise emergency routes to offHours.")}),ud=U({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:(e)=>[{key:"onHours",labelKey:"editor:handles.onHours"},{key:"offHours",labelKey:"editor:handles.offHours"},{key:"holiday",labelKey:"editor:handles.holiday"},...e.emergencyOutput===!0?[{key:"emergency",labelKey:"editor:handles.emergency"}]:[]]},configSchema:dd,producedVariables:[{name:"result",type:"string",descriptionKey:"editor:vars.timeResult"},{name:"holiday",type:"string",descriptionKey:"editor:vars.holiday"},{name:"status",type:"string",descriptionKey:"editor:vars.timeStatus"},{name:"reason",type:"string",descriptionKey:"editor:vars.timeReason"},{name:"description",type:"string",descriptionKey:"editor:vars.timeDescription"},{name:"closes_at",type:"string",descriptionKey:"editor:vars.timeClosesAt"},{name:"minutes_to_close",type:"number",descriptionKey:"editor:vars.timeMinutesToClose"},{name:"reopens_at",type:"string",descriptionKey:"editor:vars.timeReopensAt"},{name:"reopens_speech",type:"string",descriptionKey:"editor:vars.timeReopensSpeech"},{name:"hours_speech",type:"string",descriptionKey:"editor:vars.timeHoursSpeech"},{name:"period",type:"string",descriptionKey:"editor:vars.timePeriod"}]});var pd=g({name:l().min(1,{error:"editor:validation.trafficSplitPathNameRequired"}).default("").describe("Path name. Creates a 'path:<name>' output handle."),weight:f().int().min(0).max(100).default(1).describe("Relative share of this path (0-100). Zero disables it without deleting it.")}),md=g({paths:z(pd).default([{name:"A",weight:50},{name:"B",weight:50}]).describe("Weighted paths. Each creates a dynamic output handle 'path:<name>'."),mode:D(["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.")}),fd=U({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:(e)=>{let t=e.paths??[],n=[],r=new Set;for(let o of t){let i=typeof o==="object"&&o!=null?o.name:void 0;if(typeof i!=="string"||i===""||r.has(i))continue;r.add(i),n.push(i)}return[...n.map((o)=>({key:`path:${o}`,labelKey:o})),{key:"error",labelKey:"editor:handles.error"}]}},configSchema:md,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 gd=g({enabled:F().optional(),scope:D(["from_here","whole_recording"]).optional(),samplingPercentage:f().int().min(0).max(100).optional(),language:l().optional(),minDurationSeconds:f().int().min(0).max(Pn).optional(),speechRequirement:D(Yt).optional(),anonymizeEnabled:F().optional(),speechAnalyticsEnabled:F().optional(),sentimentEnabled:F().optional(),transcriptionType:D(mn).optional()}),hd=U({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:gd,producedVariables:[{name:"status",type:"string",descriptionKey:"editor:vars.transcriptionStatus"}]});var yd=g({method:D(["bridge","transfer"]).default("bridge").describe("Transfer method. 'bridge' keeps call control; 'transfer' hands off completely."),destinations:z(l()).default([]).describe("SIP URIs or phone numbers to dial. At least one required. Tried in order."),timeout:f().min(5).max(120).optional().describe("Ring timeout in seconds per destination (5-120). Omit for carrier default."),attachedData:Yi({key:"Attached-data field name shown to the agent / CRM (e.g. 'Nome').",list:"Key/value pairs delivered to the agent at transfer time (screen-pop). Values support templates."})}),_d=U({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:yd,producedVariables:[{name:"status",type:"string",descriptionKey:"editor:vars.transferStatus"},{name:"note",type:"string",descriptionKey:"editor:vars.transferNote"},{name:"disposition",type:"string",descriptionKey:"editor:vars.transferDisposition"},{name:"error_code",type:"string",descriptionKey:"editor:vars.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.errorMessage"}]});var bd=g({connector_id:l().default("").describe("Public id of the connector that provides voice.agent (a Vapi account). Required for execution."),assistant_id:l().default("").describe("Id of the Vapi assistant that answers the call. Required for execution."),assistant_name:l().default("").describe("Display name of the chosen Vapi assistant, for logs and the editor."),variables:ie(l(),l()).default({}).describe("Key-value pairs sent to the agent. Every value supports {{variables}}."),max_duration_minutes:f().min(1).max(60).default(10).describe("Maximum call duration in minutes (1-60). The bridge ends on timeout."),result_wait_seconds:f().int().min(0).max(60).default(15).describe("How long to wait for Vapi's end of call report before continuing.")}),vd=U({meta:{type:"vapiAgent",module:"ai",nameKey:"editor:nodes.vapiAgent.name",descriptionKey:"editor:nodes.vapiAgent.description",color:"iris",icon:"AudioWaveform",category:"handling",order:4,nature:"composite",display:"full",channel:"voice",requires:"voice.agent",connector:{kind:"vapi",configKey:"connector_id"},outputs:[{key:"completed",labelKey:"editor:handles.completed"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:bd,producedVariables:[{name:"duration_ms",type:"number",descriptionKey:"editor:vars.vapiAgent.durationMs"},{name:"provider_call_id",type:"string",descriptionKey:"editor:vars.vapiAgent.providerCallId"},{name:"ended_reason",type:"string",descriptionKey:"editor:vars.vapiAgent.endedReason"},{name:"summary",type:"string",descriptionKey:"editor:vars.vapiAgent.summary"},{name:"analysis_pending",type:"string",descriptionKey:"editor:vars.vapiAgent.analysisPending"},{name:"output.*",type:"string",descriptionKey:"editor:vars.vapiAgent.output"}]});var Sd="Enviamos um código por SMS. Digite o código no teclado do telefone.",xd=g({connector_id:l().default("").describe("Public id of the connector that provides verify.otp (a Twilio account). Required for execution."),service_sid:l().default("").describe("Verify Service SID (VA...) whose code length and sender configuration the block uses."),to:l().default("{{Start.callerid}}").describe("Recipient expression. Supports {{variables}}. Normalized with the platform E.164 rule: a number without a country code is completed with the country below, or the organization's default country."),default_country:l().regex(/^([A-Za-z]{2})?$/u,{error:"editor:validation.whatsappCountry"}).default("").describe("ISO 3166-1 alpha-2 country (e.g. BR) that completes recipients written without a country code. Empty uses the organization's default country."),channel:D(["sms","whatsapp","call"]).default("sms").describe("How the code reaches the contact: sms, whatsapp or call. Twilio sends it; NIVA needs no extra setup."),prompt:ve.default({tts:{text:Sd}}).describe("Audio prompt asking for the code, played with the plan's voice. In chat, its text is sent."),max_attempts:f().int().min(1,{error:"editor:validation.attemptsMin"}).max(5,{error:"editor:validation.attemptsMax"}).default(3).describe("Maximum wrong-code attempts before the block leaves by rejected (1-5)."),timeout_seconds:f().int().min(1,{error:"editor:validation.timeoutMin"}).max(60,{error:"editor:validation.timeoutMax"}).default(10).describe("Seconds to wait for the code after the prompt (1-60).")}),Ed=U({meta:{type:"verifyCode",module:"core",nameKey:"editor:nodes.verifyCode.name",descriptionKey:"editor:nodes.verifyCode.description",color:"purple",icon:"ShieldCheck",category:"data",nature:"composite",display:"full",channel:"both",order:11,requires:"verify.otp",connector:{kind:"twilio",configKey:"connector_id"},sensitiveInput:!0,outputs:[{key:"approved",labelKey:"editor:handles.approved"},{key:"rejected",labelKey:"editor:handles.rejected"},{key:"error",labelKey:"editor:handles.error"}]},configSchema:xd,producedVariables:[{name:"status",type:"string",descriptionKey:"editor:vars.verifyCode.status"},{name:"attempts",type:"number",descriptionKey:"editor:vars.verifyCode.attempts"},{name:"channel",type:"string",descriptionKey:"editor:vars.verifyCode.channel"}]});var BN=g({label:l().min(1).describe("Intent name. Creates a dynamic output handle 'intent:<label>'."),description:l().default("").describe("Description of what this intent means, used for LLM classification.")}),HN=g({language:l().optional().describe("BCP 47 language code for speech recognition (e.g., 'pt-BR'). Omit for plan default."),initial_timeout_s:f().min(3).max(60).default(10).describe("Maximum seconds to wait for speech to begin (3-60)."),timeout_s:f().min(1).max(30).default(3).describe("Seconds of post-speech silence before stopping recording (1-30)."),max_duration_s:f().min(1).max(60).default(15).describe("Maximum recording duration in seconds (1-60)."),beep:F().default(!1).describe("Play a beep sound before starting to listen.")}),WN=g({max_retries:f().min(0).max(5).default(2).describe("Maximum retries when speech is not recognized (0-5)."),prompt:ve.optional().describe("Audio played when retrying after unrecognized speech. Falls back to main prompt if not set.")});var wd=g({mode:D(["intent","capture"]).default("intent").describe("'intent' classifies speech into configured intents; 'capture' transcribes speech without classification."),prompt:ve.default({tts:{text:""}}).describe("Audio prompt played before listening for speech."),intents:z(BN).default([]).describe("List of intents the LLM should classify speech into. Only used when mode is 'intent'."),classification_instructions:l().default("").describe("Additional instructions for the LLM intent classifier. Only used when mode is 'intent'."),listen:HN.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:ve.optional().describe("Audio played while the AI processes the speech. Optional."),retry:WN.default({max_retries:2}).describe("Retry behavior when speech is not recognized.")}),Cd=U({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:(e)=>{if((e.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[...(e.intents??[]).map((o)=>typeof o==="string"?o:o.label).filter((o)=>typeof o==="string"&&o!=="").map((o)=>({key:`intent:${o}`,labelKey:o})),{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:wd,producedVariables:(e)=>{if(e.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 Ad=g({method:D(["POST","PUT","PATCH","GET","DELETE"]).default("POST").describe("HTTP method for the request."),url:gr.describe("Destination URL. Supports template expressions, e.g., 'https://hooks.example.com/{{start.callerid}}'."),headers:ie(l(),l()).optional().describe("HTTP headers as key-value pairs. Values support template expressions."),body:l().optional().describe("Request body (JSON string). Template expressions allowed. Only for POST/PUT/PATCH/DELETE.")}),Td=U({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:Ad,producedVariables:[]});var Rd=4096,Id=g({connectorId:l().default("").describe("Public id of the connector that provides whatsapp.messages (an Evolution API gateway)."),phoneNumberId:l().default("").describe("Name of the Evolution instance the message is sent from: one connected number of the connector."),to:l().default("{{Start.callerid}}").describe("Recipient expression. Supports {{variables}}. Normalized with the platform E.164 rule: numbers without a country code are completed with the country below, or the organization's default country."),defaultCountry:l().regex(/^([A-Za-z]{2})?$/u,{error:"editor:validation.whatsappCountry"}).default("").describe("ISO 3166-1 alpha-2 country (e.g. BR) that completes recipients written without a country code. Empty uses the organization's default country."),text:l().default("").describe(`Message text. Supports {{variables}}. Required; at most ${Rd} characters once the variables are resolved.`)}),Od=U({meta:{type:"whatsappMessage",module:"core",nameKey:"editor:nodes.whatsappMessage.name",descriptionKey:"editor:nodes.whatsappMessage.description",color:"green",icon:"MessageCircle",category:"data",nature:"sideEffect",display:"compact",channel:"both",order:8,requires:"whatsapp.messages",connector:{kind:"evolution_api",configKey:"connectorId"},outputs:[{key:"sent",labelKey:"editor:handles.sent"},{key:"failed",labelKey:"editor:handles.failed"}]},configSchema:Id,producedVariables:[{name:"message_id",type:"string",descriptionKey:"editor:vars.whatsappMessage.messageId"},{name:"error_code",type:"string",descriptionKey:"editor:vars.whatsappMessage.errorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.whatsappMessage.errorMessage"}]});var _b=ie(l(),l()).default({}),Nd=g({connectorId:l().default("").describe("Public id of the connector that provides whatsapp.templates (e.g. a WhatsApp Business connector)."),phoneNumberId:l().default("").describe("Id of the WhatsApp number the message is sent from, one of the connector's numbers."),template:g({name:l().default(""),language:l().default("")}).default({name:"",language:""}).describe("The approved message template to send, by name and language code (e.g. boleto / pt_BR)."),to:l().default("{{Start.callerid}}").describe("Recipient expression. Supports {{variables}}. Normalized with the platform E.164 rule: numbers without a country code are completed with the country below, or the organization's default country."),defaultCountry:l().regex(/^([A-Za-z]{2})?$/u,{error:"editor:validation.whatsappCountry"}).default("").describe("ISO 3166-1 alpha-2 country (e.g. BR) that completes recipients written without a country code. Empty uses the organization's default country."),parameters:g({header:l().optional().describe("Header value: the text variable of a text header, or the media URL of an image/video/document header."),body:_b.describe("Body variable values, keyed by variable name ('1', '2' or 'first_name')."),buttons:_b.describe("URL button suffix values, keyed by the button's index ('0', '1', ...).")}).default({body:{},buttons:{}}).describe("Template variable values. Every value supports {{variables}}.")}),kd=U({meta:{type:"whatsappTemplate",module:"core",nameKey:"editor:nodes.whatsappTemplate.name",descriptionKey:"editor:nodes.whatsappTemplate.description",color:"green",icon:"MessageCircle",category:"data",nature:"sideEffect",display:"compact",channel:"both",order:7,requires:"whatsapp.templates",connector:{kind:"whatsapp_business",configKey:"connectorId"},outputs:[{key:"sent",labelKey:"editor:handles.sent"},{key:"failed",labelKey:"editor:handles.failed"}]},configSchema:Nd,producedVariables:[{name:"message_id",type:"string",descriptionKey:"editor:vars.whatsappMessageId"},{name:"error_code",type:"string",descriptionKey:"editor:vars.whatsappErrorCode"},{name:"error_message",type:"string",descriptionKey:"editor:vars.whatsappErrorMessage"}]});var bt={start:rd,playback:Fl,ivr:Ol,collectDigits:fl,transfer:_d,enterQueue:wl,queryQueue:jl,hangup:Al,timeRouting:ud,switchCase:sd,trafficSplit:fd,setVariable:td,sequence:Ql,counter:hl,httpRequest:Rl,webhook:Td,whatsappTemplate:kd,whatsappMessage:Od,sendSms:Jl,phoneLookup:Ll,verifyCode:Ed,dataTransform:_l,subPlan:id,sendDtmf:Zl,aiAgent:tl,retellAgent:Bl,vapiAgent:vd,elevenlabsAgent:vl,openaiLiveAgent:$l,voiceRecognition:Cd,tell:ld,menu:Dl,capture:dl,routeAi:Wl,channelRouter:pl,addToDnc:Qc,apiSwitch:cl,enableRecord:xl,recording:Kl,transcription:hd,analysis:ol},vt=Object.fromEntries(Object.entries(bt).map(([e,t])=>[e,t.meta]));var gH=Number.MAX_SAFE_INTEGER;var Dd=["active","expired","suspended","poc"],vb=g({enabled:F(),limits:ie(l(),Be([f(),l(),F(),z(l())])).default({})}),tk=g({id:l().min(1),name:l().min(1)}),Sb=["voice","chat","attendants","organizations"],bb=f().int().min(0),nk=Ae("strategy",[g({strategy:I("none")}),g({strategy:I("tolerate"),tolerancePercent:bb}),g({strategy:I("tolerate_charge"),cap:bb.nullable().default(null)})]),rk=it().optional().transform((e)=>{if(typeof e!=="object"||e===null||Array.isArray(e))return;let t={};for(let n of Sb){let r=nk.safeParse(Reflect.get(e,n));if(r.success)t[n]=r.data}return Object.keys(t).length===0?void 0:t}),ok=g({customerId:l(),customerName:l().optional(),serial:l(),status:D(Dd),issuedAt:pr.date(),expiresAt:pr.date().nullable(),gracePeriodDays:f().int().min(0),modules:ie(l(),vb),isExpired:F(),isInGracePeriod:F(),daysUntilExpiry:f().nullable(),keepsAccess:F().optional(),plan:it().optional().transform((e)=>{let t=tk.safeParse(e);return t.success?t.data:void 0}),overage:rk}),ik=g({voice:f().int().default(0),chat:f().int().default(0)}).optional(),ak=g({customer_id:l().min(1),customer_name:l().min(1).optional(),serial:l().min(1),status:D(Dd),issued_at:pr.date(),expires_at:pr.date().nullable().default(null),grace_period_days:f().int().min(0).default(0),max_concurrent_channels:ik,modules:ie(l(),vb)});var _r=["yes_no","choice","scale"],xb=["caller","agent","both"],br=["info","warning","critical"],fo=["worse","better","neutral"],sk=/^[a-z][a-z0-9_]{0,63}$/,ck=/^[a-z0-9][a-z0-9_]{0,47}$/,Eb=g({key:l().regex(ck),label:l().min(1).max(80),description:l().max(240).optional(),archived:F().default(!1)}),wb=Be([g({answer:D(["yes","no"])}),g({options:z(l()).min(1)}),g({level_at_least:f()}),g({level_at_most:f()})]),lk=g({when:wb,severity:D(br),bell:F().default(!1),attendant_hint:l().trim().min(1).max(200).nullable().optional()}),dk=g({slug:l().regex(sk),name:l().trim().min(1).max(80),question:l().trim().min(1).max(500),kind:D(_r),options:z(Eb).min(2).max(12).optional(),levels:z(l().min(1).max(40)).min(3).max(5).optional(),higher_is:D(fo).optional(),speaker:D(xb),scope:g({node_types:z(l().min(1)).min(1).max(20)}).nullable(),live:F(),alert:lk.nullable()});function Cb(e){return e.higher_is??"worse"}function uk(e,t){if(e.kind==="choice"){if(e.options===void 0){t.addIssue({code:"custom",message:"signals:validation.optionsRequired",path:["options"]});return}let n=e.options.map((r)=>r.key);if(new Set(n).size!==n.length)t.addIssue({code:"custom",message:"signals:validation.optionKeyUnique",path:["options"]});if(e.options.filter((r)=>!r.archived).length<2)t.addIssue({code:"custom",message:"signals:validation.twoActiveOptions",path:["options"]})}else if(e.options!==void 0)t.addIssue({code:"custom",message:"signals:validation.optionsChoiceOnly",path:["options"]})}function pk(e,t){if(e.kind==="scale"){if(e.levels===void 0)t.addIssue({code:"custom",message:"signals:validation.levelsRequired",path:["levels"]})}else{if(e.levels!==void 0)t.addIssue({code:"custom",message:"signals:validation.levelsScaleOnly",path:["levels"]});if(e.higher_is!==void 0)t.addIssue({code:"custom",message:"signals:validation.higherIsScaleOnly",path:["higher_is"]})}}function mk(e,t){if(e.levels===void 0)return!1;let n=Cb(e),r=e.levels.length-1;if("level_at_least"in t){let o=t.level_at_least;return n!=="better"&&Number.isInteger(o)&&o>=1&&o<=r}if("level_at_most"in t){let o=t.level_at_most;return n!=="worse"&&Number.isInteger(o)&&o>=0&&o<=r-1}return!1}function fk(e){if(e.alert===null)return!0;let t=e.alert.when;switch(e.kind){case"yes_no":return"answer"in t;case"choice":return"options"in t&&e.options!==void 0&&t.options.every((n)=>e.options?.some((r)=>r.key===n&&!r.archived)===!0);case"scale":return mk(e,t)}}function Ab(e,t){if(uk(e,t),pk(e,t),!fk(e))t.addIssue({code:"custom",message:"signals:validation.whenMustMatchKind",path:["alert","when"]})}var vr=dk.superRefine(Ab);var ta=g({channel:Be([I(0),I(1)]),text:l(),isFinal:F(),confidence:f(),start:f(),end:f(),words:z(g({word:l(),start:f(),end:f()})).optional(),timestamp:l(),nodeId:l().optional(),nodeLabel:l().optional(),nodeType:l().optional(),redacted:F().optional(),attachment:hr.omit({transcript:!0}).optional()}),Ib={signal:g({id:l().min(1),slug:l().min(1),name:l(),kind:D(_r),severity:D(br).nullable(),bell:F()}),value:Be([F(),l(),f(),Pt()]),value_label:l(),confidence:f(),at_seconds:f(),node:g({id:l(),label:l(),type:l()}).nullable(),late:F()},na=g({type:I("signal_value"),...Ib}),ra=g({type:I("signal_triggered"),...Ib}),Ob=Ae("type",[na,ra]),hk=Ae("type",[g({type:I("segment"),segment:ta}),na,ra,g({type:I("started"),backlog_seconds:f(),live_from:f()}),g({type:I("caught_up")}),g({type:I("ended")}),g({type:I("error"),message:l()})]),yk=Ae("type",[g({type:I("segment"),segment:ta}),g({type:I("history"),segments:z(ta),signals:z(Ob).optional()}),na,ra,g({type:I("starting")}),g({type:I("started"),backlog_seconds:f(),live_from:f()}),g({type:I("caught_up")}),g({type:I("ended")}),g({type:I("error"),message:l()}),g({type:I("unavailable"),reason:D(["not_recorded","no_credential","test_call"])})]),_k=g({uuid:l(),action:D(["start","stop"])}),Nb=["not_live","provider_error","drain_timeout","redact_mid_call"],kb=g({startByte:f().int().min(0),endByte:f().int().min(0)}),bk=g({complete:F(),reason:D(Nb).optional(),model:l(),redact:F(),coveredRanges:z(kb)});var vk=Jc.filter((e)=>e!=="classifier");function ae(e){return{...e,defaults:{...e.defaults,email:e.defaults.email??!1}}}var Mt={enabled:!0,toast:!0},St={enabled:!0,toast:!1},Sk={enabled:!1,toast:!1},xk={freeswitch:"FreeSWITCH",database:"Database",redis:"Redis"},oa=(e)=>xk[e]??"Redis",Lt=(e,t,n)=>e===1?t:n,Db={"email.delivery_failed":ae({kind:"email.delivery_failed",area:"services",audience:"platform",permission:"system:diagnostics",severity:"warning",params:K({}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/system/email",defaults:St,en:{title:()=>"Email delivery failed",body:()=>"An email could not be delivered. Check the SMTP settings and server logs."},pt:{title:()=>"Falha no envio de e-mail",body:()=>"Um e-mail não pôde ser entregue. Confira o SMTP em Sistema > E-mail e os logs do servidor."}}),"service.down":ae({kind:"service.down",area:"services",audience:"platform",permission:"system:diagnostics",severity:"critical",params:K({component:l()}),grouping:{mode:"incident"},groupKey:(e)=>e.component,link:()=>"/dashboard",defaults:Mt,en:{title:(e)=>`${oa(e.component)} offline`,body:(e)=>`${oa(e.component)} is unreachable.`},pt:{title:(e)=>`${e.component} indisponível`,body:(e)=>`Não foi possível acessar ${e.component}.`},webhook:{alertType:(e)=>`service_offline:${e.component}`,resolvedTitle:(e)=>`${oa(e.component)} recovered`,resolvedBody:(e)=>`${oa(e.component)} is back online.`}}),"license.expiring":ae({kind:"license.expiring",area:"usage",audience:"platform",permission:"system:diagnostics",severity:"warning",params:K({days:f(),expires_on:l()}),grouping:{mode:"incident"},groupKey:(e)=>e.expires_on,link:()=>"/system/license",defaults:St,en:{title:(e)=>`License expires in ${e.days} ${Lt(e.days,"day","days")}`,body:(e)=>`License expires in ${e.days} ${Lt(e.days,"day","days")}.`},pt:{title:()=>"Licença próxima do vencimento",body:(e)=>`A licença vence em ${e.days} ${e.days===1?"dia":"dias"}.`},webhook:{alertType:()=>"license_expiring",metricValue:(e)=>e.days,threshold:()=>30,resolvedTitle:()=>"License expiry warning closed",resolvedBody:()=>"The license was renewed or has expired."}}),"license.expired":ae({kind:"license.expired",area:"usage",audience:"platform",permission:"system:diagnostics",severity:"critical",params:K({}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/system/license",defaults:Mt,locked:!0,en:{title:()=>"License expired",body:()=>"NIVA license has expired."},pt:{title:()=>"Licença vencida",body:()=>"A licença da NIVA venceu."},webhook:{alertType:()=>"license_expired"}}),"storage.disk":ae({kind:"storage.disk",area:"services",audience:"platform",permission:"system:diagnostics",severity:"warning",params:K({pct:f(),threshold:f()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/system/storage",defaults:St,en:{title:(e)=>`Disk usage ${e.pct}%`,body:(e)=>`Disk usage at ${e.pct}%.`},pt:{title:()=>"Uso de disco elevado",body:(e)=>`O uso do disco chegou a ${e.pct}%.`},webhook:{alertType:()=>"storage_high",metricValue:(e)=>e.pct,threshold:(e)=>e.threshold}}),"storage.recordings_blocked":ae({kind:"storage.recordings_blocked",area:"services",audience:"platform",permission:"system:diagnostics",severity:"warning",params:K({used:f(),cap:f()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/system/storage",defaults:St,en:{title:(e)=>`Recording storage cap reached (${e.used} GB of ${e.cap} GB)`,body:(e)=>`Recordings use ${e.used} GB against a ${e.cap} GB cap and none may be removed yet.`},pt:{title:()=>"Limite de armazenamento das gravações atingido",body:(e)=>`As gravações ocupam ${e.used} GB de ${e.cap} GB e ainda não podem ser removidas.`},webhook:{alertType:()=>"recording_retention_blocked",metricValue:(e)=>e.used,threshold:(e)=>e.cap}}),"calls.error_rate":ae({kind:"calls.error_rate",area:"calls",audience:"organization",permission:"call_record:read",severity:"warning",params:K({rate:f(),failures:f(),total:f(),threshold:f(),plan_name:l().optional()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/reports",defaults:Mt,en:{title:(e)=>`Call error rate ${e.rate}%`,body:(e)=>`${e.failures}/${e.total} failed.`},pt:{title:()=>"Taxa de erros nas chamadas",body:(e)=>`${e.failures} de ${e.total} chamadas falharam (${e.rate}%).`},webhook:{alertType:()=>"call_error_rate",metricValue:(e)=>e.rate,threshold:(e)=>e.threshold}}),"calls.plan_error_rate":ae({kind:"calls.plan_error_rate",area:"calls",audience:"organization",permission:"call_record:read",severity:"warning",params:K({plan_id:l(),plan_name:l(),rate:f(),failures:f(),total:f(),threshold:f()}),grouping:{mode:"incident"},groupKey:(e)=>e.plan_id,link:()=>"/reports",defaults:St,en:{title:(e)=>`${e.plan_name}: error rate ${e.rate}%`,body:(e)=>`${e.failures}/${e.total} failed.`},pt:{title:(e)=>`Erros no plano ${e.plan_name}`,body:(e)=>`${e.failures} de ${e.total} chamadas falharam (${e.rate}%).`},webhook:{alertType:()=>"plan_error_rate",metricValue:(e)=>e.rate,threshold:(e)=>e.threshold}}),"calls.transfer_failure":ae({kind:"calls.transfer_failure",area:"calls",audience:"organization",permission:"call_record:read",severity:"warning",params:K({rate:f(),failures:f(),total:f(),threshold:f()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/reports",defaults:St,en:{title:(e)=>`Transfer failure rate ${e.rate}%`,body:(e)=>`${e.failures}/${e.total} failed.`},pt:{title:()=>"Falhas nas transferências",body:(e)=>`${e.failures} de ${e.total} transferências falharam (${e.rate}%).`},webhook:{alertType:()=>"transfer_failure_rate",metricValue:(e)=>e.rate,threshold:(e)=>e.threshold}}),"calls.stale":ae({kind:"calls.stale",area:"calls",audience:"organization",permission:"call_record:read",severity:"warning",params:K({count:f(),threshold:f()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/reports",defaults:St,en:{title:()=>"Stale calls detected",body:(e)=>`${e.count} ${Lt(e.count,"stale call","stale calls")}.`},pt:{title:()=>"Chamadas sem atividade",body:(e)=>`Foram detectadas ${e.count} chamadas sem atividade.`},webhook:{alertType:()=>"stale_calls",metricValue:(e)=>e.count,threshold:(e)=>e.threshold}}),"calls.transcription_failed":ae({kind:"calls.transcription_failed",area:"calls",audience:"organization",permission:"call_record:read",severity:"warning",params:K({count:f(),threshold:f()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/reports",defaults:St,en:{title:()=>"Transcription failures",body:(e)=>`${e.count} ${Lt(e.count,"failure","failures")}.`},pt:{title:()=>"Falhas na transcrição",body:(e)=>`Foram detectadas ${e.count} falhas na transcrição.`},webhook:{alertType:()=>"transcription_failures",metricValue:(e)=>e.count,threshold:(e)=>e.threshold}}),"desk.mention":ae({kind:"desk.mention",area:"desk",audience:"organization",permission:"desk:use",severity:"info",params:K({mention_id:l(),conversation_id:l(),author_name:l(),contact_name:l().nullable()}),grouping:{mode:"once"},groupKey:(e)=>e.mention_id,link:(e)=>`/desk?conversation=${e.conversation_id}`,defaults:{enabled:!0,toast:!0,email:!1},en:{title:()=>"You were mentioned",body:(e)=>e.contact_name===null?`${e.author_name} mentioned you in a note.`:`${e.author_name} mentioned you in a note on the conversation with ${e.contact_name}.`},pt:{title:()=>"Você foi mencionado",body:(e)=>e.contact_name===null?`${e.author_name} mencionou você em uma nota.`:`${e.author_name} mencionou você em uma nota da conversa com ${e.contact_name}.`}}),"calls.export_ready":ae({kind:"calls.export_ready",area:"calls",audience:"organization",permission:"call_record:export",severity:"info",params:K({export_job_id:l(),filename:l(),total_records:f().nullable()}),grouping:{mode:"once"},groupKey:(e)=>e.export_job_id,link:()=>"/reports?tab=exports",defaults:{enabled:!0,toast:!0,email:!1},en:{title:()=>"Export ready",body:(e)=>`${e.filename} is ready to download.`},pt:{title:()=>"Exportação pronta",body:(e)=>`${e.filename} está pronto para download.`}}),"calls.export_failed":ae({kind:"calls.export_failed",area:"calls",audience:"organization",permission:"call_record:export",severity:"warning",params:K({export_job_id:l(),filename:l(),total_records:f().nullable()}),grouping:{mode:"once"},groupKey:(e)=>e.export_job_id,link:()=>"/reports?tab=exports",defaults:{enabled:!0,toast:!0,email:!1},en:{title:()=>"Export failed",body:(e)=>`${e.filename} could not be generated.`},pt:{title:()=>"Falha na exportação",body:(e)=>`Não foi possível gerar ${e.filename}.`}}),"audit.export_ready":ae({kind:"audit.export_ready",area:"audit",audience:"organization",permission:"audit:read",severity:"info",params:K({export_job_id:l(),filename:l(),total_records:f().nullable()}),grouping:{mode:"once"},groupKey:(e)=>e.export_job_id,link:()=>"/settings/audit?tab=exports",defaults:{enabled:!0,toast:!0,email:!1},en:{title:()=>"Export ready",body:(e)=>`${e.filename} is ready to download.`},pt:{title:()=>"Exportação pronta",body:(e)=>`${e.filename} está pronto para download.`}}),"audit.export_failed":ae({kind:"audit.export_failed",area:"audit",audience:"organization",permission:"audit:read",severity:"warning",params:K({export_job_id:l(),filename:l(),total_records:f().nullable()}),grouping:{mode:"once"},groupKey:(e)=>e.export_job_id,link:()=>"/settings/audit?tab=exports",defaults:{enabled:!0,toast:!0,email:!1},en:{title:()=>"Export failed",body:(e)=>`${e.filename} could not be generated.`},pt:{title:()=>"Falha na exportação",body:(e)=>`Não foi possível gerar ${e.filename}.`}}),"calls.rejected":ae({kind:"calls.rejected",area:"calls",audience:"organization",permission:"call_record:read",severity:"warning",params:K({reason:l(),destination:l(),count:f()}),grouping:{mode:"window",windowSeconds:900},groupKey:(e)=>e.reason,link:()=>"/reports",defaults:St,en:{title:()=>"Calls rejected",body:(e,t)=>`${t.count} ${Lt(t.count,"call","calls")} rejected (${e.reason}).`},pt:{title:()=>"Chamadas rejeitadas",body:(e,t)=>`${t.count} ${t.count===1?"chamada rejeitada":"chamadas rejeitadas"}: ${e.reason}.`}}),"calls.node_error":ae({kind:"calls.node_error",area:"calls",audience:"organization",permission:"call_record:read",severity:"warning",params:K({node_id:l(),node_type:l(),node_label:l(),error_code:l(),visual_plan_id:l(),visual_plan_name:l(),count:f()}),grouping:{mode:"window",windowSeconds:900},groupKey:(e)=>`${e.visual_plan_id}:${e.node_id}:${e.error_code}`,link:()=>"/reports",defaults:St,en:{title:()=>"Call node errors",body:(e,t)=>`${t.count} ${Lt(t.count,"error","errors")} in ${e.node_label} (${e.error_code}).`},pt:{title:()=>"Erros nos nós de chamada",body:(e,t)=>`${t.count} ${t.count===1?"erro":"erros"} em ${e.node_label} (${e.error_code}).`}}),"webhook.endpoint_down":ae({kind:"webhook.endpoint_down",area:"integrations",audience:"organization",permission:"webhook:read",severity:"critical",params:K({endpoint_id:l(),endpoint_url:l(),endpoint_description:l().nullable(),failed_attempts:f(),last_error:l().nullable()}),grouping:{mode:"incident"},groupKey:(e)=>e.endpoint_id,link:()=>"/settings/webhooks",defaults:Mt,en:{title:()=>"Webhook endpoint failing",body:(e)=>`${e.failed_attempts} consecutive ${Lt(e.failed_attempts,"failure","failures")}.`},pt:{title:()=>"Webhook com falhas",body:(e)=>`${e.failed_attempts} ${e.failed_attempts===1?"falha consecutiva":"falhas consecutivas"} na entrega do webhook.`},webhook:{alertType:()=>"webhook_failures",metricValue:(e)=>e.failed_attempts,threshold:()=>3}}),"webhook.queue_delayed":ae({kind:"webhook.queue_delayed",area:"integrations",audience:"organization",permission:"webhook:read",severity:"warning",params:K({depth:f(),minutes:f(),threshold:f()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/settings/webhooks",defaults:St,en:{title:(e)=>`Webhook queue delayed ${e.minutes} min`,body:(e)=>`${e.depth} pending ${Lt(e.depth,"delivery","deliveries")}; the oldest has waited ${e.minutes} min.`},pt:{title:()=>"Fila de webhooks atrasada",body:(e)=>`${e.depth} entregas pendentes; a mais antiga aguarda há ${e.minutes} min.`},webhook:{alertType:()=>"webhook_queue_backlog",metricValue:(e)=>e.minutes,threshold:(e)=>e.threshold}}),"connector.needs_attention":ae({kind:"connector.needs_attention",area:"integrations",audience:"organization",permission:"connector:read",severity:"critical",params:K({connector_id:l(),connector_name:l(),kind:l(),error_code:l(),error_message:l()}),grouping:{mode:"incident"},groupKey:(e)=>e.connector_id,link:(e)=>`/settings/connectors/${e.connector_id}`,defaults:Mt,en:{title:(e)=>`Connector ${e.connector_name} needs attention`,body:(e)=>`${e.error_code}: ${e.error_message}`},pt:{title:(e)=>`O conector ${e.connector_name} precisa de atenção`,body:(e)=>`${e.error_code}: ${e.error_message}`},webhook:{alertType:()=>"connector_needs_attention"}}),"secret.missing":ae({kind:"secret.missing",area:"integrations",audience:"organization",permission:"secret:read",severity:"critical",params:K({secret:l(),node_label:l()}),grouping:{mode:"window",windowSeconds:3600},groupKey:(e)=>e.secret,link:()=>"/settings/secrets",defaults:Mt,en:{title:()=>"Secret missing",body:(e)=>`The secret ${e.secret} is missing for ${e.node_label}.`},pt:{title:()=>"Secret ausente",body:(e)=>`O secret ${e.secret} está ausente em ${e.node_label}.`}}),"signal.triggered":ae({kind:"signal.triggered",area:"signals",audience:"organization",permission:"ai:read",severity:"warning",params:K({signal:l(),signal_id:l(),call_id:l(),caller:l().nullable()}),grouping:{mode:"window",windowSeconds:900},groupKey:(e)=>e.signal_id,link:(e,t)=>t.count===1?`/reports?trace=${e.call_id}`:`/reports?signal=${e.signal_id}`,defaults:Mt,en:{title:(e)=>`Signal triggered: ${e.signal}`,body:(e,t)=>`${t.count} ${Lt(t.count,"call","calls")} triggered ${e.signal}.`},pt:{title:(e)=>`Sinal detectado: ${e.signal}`,body:(e,t)=>`${t.count} ${t.count===1?"chamada acionou":"chamadas acionaram"} o sinal ${e.signal}.`}}),"usage.channel_capacity":ae({kind:"usage.channel_capacity",area:"usage",audience:"organization",permission:"channel:read",severity:"warning",params:K({pct:f(),active:f(),limit:f(),pool:l()}),grouping:{mode:"incident"},groupKey:(e)=>e.pool,link:()=>"/dashboard",defaults:Mt,en:{title:(e)=>`${e.pool} channel capacity ${e.pct}%`,body:(e)=>`${e.active}/${e.limit} ${e.pool} ${Lt(e.limit,"channel","channels")} in use.`},pt:{title:()=>"Capacidade de canais",body:(e)=>`${e.active} de ${e.limit} canais ${e.pool} em uso (${e.pct}%).`},webhook:{alertType:()=>"channel_capacity",metricValue:(e)=>e.pct,threshold:()=>90}}),"usage.audit_retention":ae({kind:"usage.audit_retention",area:"usage",audience:"organization",permission:"audit:read",severity:"warning",params:K({count:f(),limit:f()}),grouping:{mode:"incident"},groupKey:()=>"",link:()=>"/settings/audit",defaults:Sk,en:{title:()=>"Audit retention capacity exceeded",body:(e)=>`Audit log count (${e.count}) exceeds the retention limit (${e.limit}).`},pt:{title:()=>"Limite de retenção da auditoria excedido",body:(e)=>`${e.count} registros de auditoria ultrapassam o limite de ${e.limit}.`},webhook:{alertType:()=>"audit_retention_capacity",metricValue:(e)=>e.count,threshold:(e)=>e.limit}}),"system.update_available":ae({kind:"system.update_available",area:"services",audience:"platform",permission:"system:diagnostics",severity:"info",params:K({version:l()}),grouping:{mode:"once"},groupKey:(e)=>e.version,link:()=>"/system/updates",defaults:St,en:{title:(e)=>`NIVA ${e.version} is available`,body:(e)=>`A new NIVA release is available: ${e.version}.`},pt:{title:(e)=>`NIVA ${e.version} disponível`,body:(e)=>`Uma nova versão da NIVA está disponível: ${e.version}.`}}),"system.update_completed":ae({kind:"system.update_completed",area:"services",audience:"platform",permission:"system:diagnostics",severity:"info",params:K({run_id:l(),from_version:l(),to_version:l()}),grouping:{mode:"once"},groupKey:(e)=>e.run_id,link:()=>"/system/updates",defaults:Mt,en:{title:(e)=>`NIVA updated to ${e.to_version}`,body:(e)=>`NIVA was updated from ${e.from_version} to ${e.to_version}.`},pt:{title:(e)=>`NIVA atualizada para ${e.to_version}`,body:(e)=>`A NIVA foi atualizada de ${e.from_version} para ${e.to_version}.`}}),"system.update_failed":ae({kind:"system.update_failed",area:"services",audience:"platform",permission:"system:diagnostics",severity:"critical",params:K({run_id:l(),status:D(["failed","rolled_back","action_required"]),error_code:l()}),grouping:{mode:"once"},groupKey:(e)=>e.run_id,link:()=>"/system/updates",defaults:Mt,en:{title:()=>"NIVA update failed",body:(e)=>`The update ended with status ${e.status} (${e.error_code}).`},pt:{title:()=>"Falha na atualização da NIVA",body:(e)=>`A atualização terminou com o estado ${e.status} (${e.error_code}).`}})};var Pb="urn:ietf:params:oauth:grant-type:device_code",$b=["authorization_code","refresh_token",Pb],Pd="ABCDEFGHJKLMNPQRSTUVWXYZ",Ck=g({resource:l(),authorization_servers:z(l()).min(1),scopes_supported:z(l()),bearer_methods_supported:z(l()),resource_name:l().optional()}),Ak=g({issuer:l(),authorization_endpoint:l(),token_endpoint:l(),registration_endpoint:l(),revocation_endpoint:l(),device_authorization_endpoint:l(),response_types_supported:z(l()),grant_types_supported:z(l()),code_challenge_methods_supported:z(l()),token_endpoint_auth_methods_supported:z(l()),client_id_metadata_document_supported:I(!0),authorization_response_iss_parameter_supported:I(!0),scopes_supported:z(l())}),Tk=l().refine((e)=>{try{return new URL(e).protocol==="https:"}catch{return!1}},"must be an https URL"),Rk=g({client_id:Tk,redirect_uris:z(l().min(1)).min(1),client_name:l().optional(),client_uri:l().optional(),logo_uri:l().optional(),scope:l().optional(),grant_types:z(l()).optional(),response_types:z(l()).optional(),token_endpoint_auth_method:l().optional(),token_endpoint_auth_methods_supported:z(l()).optional(),application_type:D(["native","web"]).optional()}).refine(Ik,{error:'client must support the "none" token endpoint auth method',path:["token_endpoint_auth_method"]});function Ik(e){let t=e.token_endpoint_auth_methods_supported;if(t!=null)return t.includes("none");let n=e.token_endpoint_auth_method;return n==null||n==="none"}var Ok=g({redirect_uris:z(l().min(1)).min(1),client_name:l().max(200).optional(),client_uri:l().optional(),logo_uri:l().optional(),scope:l().optional(),grant_types:z(D($b)).optional(),response_types:z(I("code")).optional(),token_endpoint_auth_method:I("none").optional(),application_type:D(["native","web"]).optional()}),Nk=g({client_id:l(),client_id_issued_at:f().int(),redirect_uris:z(l()),client_name:l().optional(),token_endpoint_auth_method:I("none"),grant_types:z(l()),response_types:z(l()),application_type:D(["native","web"]).optional(),scope:l().optional()}),kk=g({client_id:l().min(1).max(2048),scope:l().max(2000).default(""),resource:l().min(1).max(2048)}),Dk=g({device_code:l().min(1),user_code:l().regex(new RegExp(`^[${Pd}]{4}-[${Pd}]{4}$`)),verification_uri:l(),verification_uri_complete:l().optional(),expires_in:f().int().positive(),interval:f().int().positive()});var $d=["tomato","red","ruby","crimson","pink","plum","purple","violet","iris","indigo","blue","cyan","teal","jade","green","grass","bronze","gold","sky","mint","lime","amber","orange"];var ia={visual_plan:["read","create","update","delete","publish"],channel:["read","create","update","delete"],destination:["read","create","update","delete"],schedule:["read","create","update","delete"],holiday:["read","create","update","delete"],audio_file:["read","create","update","delete"],call_record:["read","export","purge"],call_content:["read"],call:["originate","hangup"],chat:["create"],dashboard:["read","update"],notification:["manage"],test_call:["execute"],tts:["read"],org_settings:["read","update"],user:["read","invite","update_role","suspend","remove","reset_password"],api_key:["read","create","revoke"],oauth_grant:["read","revoke"],acl:["read","create","update","delete"],audit:["read"],webhook:["read","create","update","delete"],ai:["read","execute","configure","manage_key"],assistant:["use"],org_integration:["read","update"],analysis_template:["read","create","update","delete"],contact:["read","update"],dialer_campaign:["read","create","update","delete","control"],dialer_dnc:["read","manage"],archive:["read","purge"],secret:["read","create","update","delete"],connector:["read","create","update","delete"],role:["read","create","update","delete"],desk:["use"],attendant:["read","create","update","delete"],desk_settings:["read","update"],conversation:["read"],saved_reply:["read","manage"],desk_monitor:["read","control"],queue:["read","create","update","delete"],queue_monitor:["read","control"],license:["read","manage"],organization:["list","create","update","delete"],integration:["read","update"],org_plan:["read","update"],platform_admin:["read","manage"],platform_storage:["manage"],system:["logs","diagnostics","operate","update"]},Md={visual_plan:"organization",channel:"organization",destination:"organization",schedule:"organization",holiday:"organization",audio_file:"organization",call_record:"organization",call_content:"organization",call:"organization",chat:"organization",dashboard:"organization",notification:"organization",test_call:"organization",tts:"organization",org_settings:"organization",user:"organization",api_key:"organization",oauth_grant:"organization",acl:"organization",audit:"organization",webhook:"organization",ai:"organization",assistant:"organization",org_integration:"organization",analysis_template:"organization",contact:"organization",dialer_campaign:"organization",dialer_dnc:"organization",archive:"organization",secret:"organization",connector:"organization",role:"organization",desk:"organization",attendant:"organization",desk_settings:"organization",conversation:"organization",saved_reply:"organization",desk_monitor:"organization",queue:"organization",queue_monitor:"organization",license:"platform",organization:"platform",integration:"platform",org_plan:"platform",platform_admin:"platform",platform_storage:"platform",system:"platform"},Mb=Object.entries(ia),Lb=Mb.flatMap(([e,t])=>t.map((n)=>`${e}:${n}`));var zb={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","chat:create","call:hangup","dashboard:read","dashboard:update","call_record:read","call_record:export","call_content:read","tts:read","ai:read","ai:execute","assistant:use","ai:configure","analysis_template:read","analysis_template:create","analysis_template:update","analysis_template:delete","contact:read","contact:update","dialer_campaign:read","dialer_campaign:create","dialer_campaign:update","dialer_campaign:delete","dialer_campaign:control","dialer_dnc:read","dialer_dnc:manage","archive:read","user:read","role:read","webhook:read","api_key:read","oauth_grant:read","desk:use","attendant:read","attendant:create","attendant:update","attendant:delete","desk_settings:read","desk_settings:update","conversation:read","saved_reply:read","saved_reply:manage","queue:read","queue:create","queue:update","queue:delete","desk_monitor:read","desk_monitor:control","queue_monitor:read","queue_monitor:control"],supervisor:["visual_plan:read","channel:read","destination:read","schedule:read","holiday:read","audio_file:read","dashboard:read","dashboard:update","call_record:read","call_record:export","call_content:read","test_call:execute","call:hangup","tts:read","ai:read","ai:execute","assistant:use","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","desk:use","attendant:read","desk_settings:read","conversation:read","saved_reply:read","saved_reply:manage","queue:read","desk_monitor:read","desk_monitor:control","queue_monitor:read","queue_monitor:control"],operator:["visual_plan:read","channel:read","destination:read","schedule:read","holiday:read","audio_file:read","dashboard:read","call_record:read","test_call:execute","call:hangup","tts:read","contact:read","contact:update","dialer_campaign:read","dialer_dnc:read","user:read","archive:read"],viewer:["visual_plan:read","channel:read","destination:read","schedule:read","holiday:read","audio_file:read","dashboard:read","call_record:read","tts:read","user:read","role:read","webhook:read","api_key:read","oauth_grant:read","acl:read","audit:read","ai:read","analysis_template:read","contact:read","dialer_campaign:read","dialer_dnc:read","archive:read","attendant:read","conversation:read","queue:read"],attendant:["desk:use","contact:read","contact:update","audio_file:read","saved_reply:read"]},Pk=Object.keys(zb);var KH=Mb.filter(([e])=>Md[e]==="organization").flatMap(([e,t])=>t.map((n)=>`${e}:${n}`));var qH=new Map(Lb.map((e)=>[e,e])),BH=new Map(Object.entries(Md));var GH=new Set(`@£$¥èéùìòÇ
|
|
91
|
+
Øø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !"#¤%&'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà`);var Ld={plans:{entities:["visual_plan","audio_file","tts","analysis_template","test_call"]},telephony:{entities:["channel","destination","schedule","holiday","acl"]},calls:{entities:["call","call_record","call_content","contact","dashboard","notification","archive","ai","assistant"]},chat:{entities:["chat"],module:"omnichannel"},dialer:{entities:["dialer_campaign","dialer_dnc"],module:"dialer"},desk:{entities:["desk","attendant","desk_settings","conversation","saved_reply","desk_monitor"],module:"desk"},queues:{entities:["queue","queue_monitor"],module:"queues"},admin:{entities:["user","role","api_key","oauth_grant","org_settings","webhook","org_integration","audit","secret","connector","license"]},platform:{entities:["organization","integration","org_plan","platform_admin","platform_storage","system"],platformOnly:!0}},Mk=Object.keys(Ld),Lk=new Map;for(let e of Mk)for(let t of Ld[e].entities)Lk.set(t,e);var Fb=new Set(["*:read","*:write","offline_access"]);for(let e of Object.keys(ia))Fb.add(`${e}:read`),Fb.add(`${e}:write`);var zd=g({version:I(1),startNodeId:l().min(1),nodes:ie(l(),g({type:l().min(1),label:l(),varName:l(),config:ie(l(),it())})),adjacency:ie(l(),ie(l(),l()))});function Fd(e,t,n,r){return Fk(e,t,n,r)}function zk(e,t){if(e&&t)return"converged";if(e)return"voice-only";if(t)return"chat-only";return"unreachable"}function Fk(e,t,n,r){let o=t.get(e)?.get("voice"),i=t.get(e)?.get("chat"),a=o!=null?Ub(o,t,r,"voice"):new Set,s=i!=null?Ub(i,t,r,"chat"):new Set;if(o!=null)a.add(o);if(i!=null)s.add(i);let c={};for(let d of n)c[d]=d===e?"converged":zk(a.has(d),s.has(d));return c}function Ub(e,t,n,r){let o=new Set,i=[e];o.add(e);let a=0;while(a<i.length){let s=i[a++],c=t.get(s);if(c==null)continue;if(r!=null&&n?.has(s)){let d=c.get(r);if(d!=null&&!o.has(d))o.add(d),i.push(d);continue}for(let d of c.values())if(!o.has(d))o.add(d),i.push(d)}return o}function M(){return(e,t)=>({key:t,prefix:`${e}:`})}var jb={deskPresence:M()("desk-presence",(e)=>`desk-presence:${e}`),deskUnread:M()("desk-unread",(e)=>`desk-unread:${e}`),deskRegistered:M()("desk-registered",(e)=>`desk-registered:${e}`),deskSipCredential:M()("desk-sip-credential",(e)=>`desk-sip-credential:${e}`),queueListen:M()("queue-listen",(e)=>`queue-listen:${e}`),deskLeg:M()("desk-leg",(e)=>`desk-leg:${e}`),deskLost:M()("desk-lost",(e)=>`desk-lost:${e}`),deskTransfer:M()("desk-transfer",(e)=>`desk-transfer:${e}`),queueRouterLock:M()("queue-router-lock",()=>"queue-router-lock"),queueOfferTaken:M()("queue-offer-taken",(e)=>`queue-offer-taken:${e}`),queueRecoverLock:M()("queue-recover-lock",(e)=>`queue-recover-lock:${e}`),queueRecoverAttempts:M()("queue-recover-attempts",(e)=>`queue-recover-attempts:${e}`),deskSweeperLock:M()("desk-sweeper-lock",()=>"desk-sweeper-lock"),call:M()("call",(e)=>`call:${e}`),testPlan:M()("test-plan",(e)=>`test-plan:${e}`),testChatPlan:M()("test-chat-plan",(e)=>`test-chat-plan:${e}`),testEditorState:M()("test-editor-state",(e)=>`test-editor-state:${e}`),testExecutionTrace:M()("test-execution-trace",(e)=>`test-execution-trace:${e}`),refreshToken:M()("rt",(e)=>`rt:${e}`),hostActionConfirmation:M()("host-action-confirmation",(e)=>`host-action-confirmation:${e}`),exportDownloadTicket:M()("export-dl",(e)=>`export-dl:${e}`),revokedToken:M()("revoked",(e)=>`revoked:${e}`),revokedSession:M()("revoked-session",(e)=>`revoked-session:${e}`),legacyAuthCutoff:M()("legacy-auth-cutoff",(e)=>`legacy-auth-cutoff:${e}`),oauthCode:M()("oauth:code",(e)=>`oauth:code:${e}`),oauthCimd:M()("oauth:cimd",(e)=>`oauth:cimd:${e}`),oauthDevice:M()("oauth:device",(e)=>`oauth:device:${e}`),oauthUsercode:M()("oauth:usercode",(e)=>`oauth:usercode:${e}`),oauthUsercodeAttempts:M()("oauth:usercode-attempts",(e)=>`oauth:usercode-attempts:${e}`),channels:M()("niva:channels",(e)=>`niva:channels:${e}`),concurrentChannels:M()("niva:concurrent_channels",(e,t)=>`niva:concurrent_channels:${e}:${t}`),peakConcurrentChannels:M()("niva:peak_concurrent",(e,t,n)=>n===void 0?`niva:peak_concurrent:${e}:${t}`:`niva:peak_concurrent:${e}:${t}:${n}`),dialerCampaignActive:M()("niva:dialer_campaign_active",(e)=>`niva:dialer_campaign_active:${e}`),capacityReservation:M()("niva:capacity_reservation",(e)=>`niva:capacity_reservation:${e}`),capacityReservationData:M()("niva:capacity_reservation_data",()=>"niva:capacity_reservation_data"),capacityReservationExpiry:M()("niva:capacity_reservation_expiry",()=>"niva:capacity_reservation_expiry"),capacityReservationHandoff:M()("niva:capacity_reservation_handoff",(e)=>`niva:capacity_reservation_handoff:${e}`),counterByPlan:M()("niva:counter:plan",(e,t,n)=>`niva:counter:plan:${e}:${t}:${n}`),counterByOrg:M()("niva:counter:org",(e,t)=>`niva:counter:org:${e}:${t}`),trafficSplitRotation:M()("niva:traffic_split",(e,t,n,r)=>`niva:traffic_split:${e}:${t}:${n}:${r}`),rateLimit:M()("rl",(e,t)=>`rl:${e}:${t}`),liveTranscriptionSegments:M()("live-ts",(e)=>`live-ts:${e}`),liveSignalEvents:M()("live-sig",(e)=>`live-sig:${e}`),chatSignalState:M()("chat-sig",(e)=>`chat-sig:${e}`),chatSignalLock:M()("chat-sig-lock",(e)=>`chat-sig-lock:${e}`),deskCopilotReplyDebounce:M()("desk-copilot-reply",(e)=>`desk-copilot-reply:${e}`),deskCopilotReplyWaiting:M()("desk-copilot-reply-waiting",(e)=>`desk-copilot-reply-waiting:${e}`),deskCopilotCueOwner:M()("desk-copilot-cue-owner",(e)=>`desk-copilot-cue-owner:${e}`),deskCopilotCueWindow:M()("desk-copilot-cue-window",(e)=>`desk-copilot-cue-window:${e}`),chatSignalPending:M()("chat-sig-pending",(e)=>`chat-sig-pending:${e}`),liveTranscriptionSummary:M()("live-ts-summary",(e)=>`live-ts-summary:${e}`),transcriptionWatchers:M()("ts-watchers",(e)=>`ts-watchers:${e}`),transcriptionDeferredJobs:M()("transcription:deferred:jobs",()=>"transcription:deferred:jobs"),transcriptionDeferredReady:M()("transcription:deferred:ready",()=>"transcription:deferred:ready"),transcriptionDeferredLeases:M()("transcription:deferred:leases",()=>"transcription:deferred:leases"),chatSession:M()("chat-session",(e)=>`chat-session:${e}`),chatSessionEnded:M()("chat-session-ended",(e)=>`chat-session-ended:${e}`),chatLookup:M()("chat-lookup",(e,t,n)=>`chat-lookup:${e}:${t}:${n}`),chatRelay:M()("chat-relay-token",(e)=>`chat-relay-token:${e}`),chatRelayInbox:M()("chat-relay-inbox",(e)=>`chat-relay-inbox:${e}`),chatRelayDeadlines:M()("chat-relay-deadlines",()=>"chat-relay-deadlines"),chatRelayArmed:M()("chat-relay-armed",(e)=>`chat-relay-armed:${e}`),chatWsLink:M()("chat-ws-link",(e)=>`chat-ws-link:${e}`),activeVoiceCalls:M()("niva:active:voice",(e)=>`niva:active:voice:${e}`),activeChatSessions:M()("niva:active:chat",(e)=>`niva:active:chat:${e}`),chatLock:M()("chat-lock",(e,t)=>`chat-lock:${e}:${t}`),chatInboundMessage:M()("chat-inbound-message",(e,t,n,r)=>`chat-inbound-message:${e}:${t}:${n}:${r}`),wsSession:M()("ws:session",(e)=>`ws:session:${e}`),wsMessageLog:M()("ws:log",(e)=>`ws:log:${e}`),wsSeq:M()("ws:seq",(e)=>`ws:seq:${e}`),webchatChannelEpoch:M()("webchat:channel-epoch",(e)=>`webchat:channel-epoch:${e}`),webchatConcurrentSessions:M()("webchat:sessions",(e)=>`webchat:sessions:${e}`),webchatSessionCreations:M()("webchat:created",(e)=>`webchat:created:${e}`),webchatChallengeUsed:M()("webchat:challenge-used",(e)=>`webchat:challenge-used:${e}`),webchatMessageRate:M()("webchat:msg-rate",(e,t)=>`webchat:msg-rate:${e}:${t}`),webchatUpgradeRate:M()("webchat:upgrade-rate",(e)=>`webchat:upgrade-rate:${e}`),healthStatus:M()("health-status",(e)=>`health-status:${e}`),alertCooldown:M()("alert-cd",(e,t)=>`alert-cd:${e}:${t}`),auditRetentionOverCap:M()("audit-retention",()=>"audit-retention:over-cap"),storageCleanup:M()("storage:cleanup",(e)=>`storage:cleanup:${e}`),recordingDownloadAudit:M()("rec-dl-audit",(e,t)=>`rec-dl-audit:${e}:${t}`),connectorPhoneNumbers:M()("connector:phone-numbers",(e,t)=>`connector:phone-numbers:v${t}:${e}`),connectorPhoneNumbersVersion:M()("connector:phone-numbers:version",(e)=>`connector:${e}:phone-numbers:version`),connectorTemplates:M()("connector:templates",(e,t)=>`connector:templates:v${t}:${e}`),connectorTemplatesVersion:M()("connector:templates:version",(e)=>`connector:${e}:templates:version`),whatsappTemplateMessage:M()("wa-template-msg",(e)=>`wa-template-msg:${e}`),whatsappMessageRate:M()("wa-message-rate",(e,t)=>`wa-message-rate:${e}:${t}`),screenPop:M()("screenpop",(e,t)=>`screenpop:${e}:${t}`),screenPopLegacy:M()("call_info",(e)=>`call_info_${e}`),engineHeartbeat:M()("engine:heartbeat",()=>"engine:heartbeat")};function jk(e){return vt[e]?.connector}function Ud(e,t){return typeof e==="string"&&e!==""&&!t.has(e)}function go(e,t){return{nodeId:e.id,severity:"error",messageKey:t,params:{label:e.label}}}function Vk(e,t){if(e.type!=="timeRouting"||t==null)return null;if(!Ud(e.config.scheduleId,t))return null;return go(e,"editor:validation.danglingSchedule")}function Kk(e,t){if(e.type!=="subPlan"||t==null)return null;if(!Ud(e.config.planId,t))return null;return go(e,"editor:validation.danglingPlan")}function qk(e,t){if(t==null)return null;let n=e.config.audio;if(n==null||typeof n!=="object"||!("file"in n))return null;let r=n.file;if(r==null||typeof r!=="object"||!("id"in r))return null;if(!Ud(r.id,t))return null;return go(e,"editor:validation.danglingAudioFile")}function Bk(e,t){if(t==null)return null;let n=jk(e.type);if(n==null)return null;let r=e.config[n.configKey];if(typeof r!=="string"||r==="")return null;let o=t.get(r);if(o===void 0)return go(e,"editor:validation.danglingConnector");if(o!==n.kind)return go(e,"editor:validation.connectorKindMismatch");return null}function Hk(e,t){if(t==null)return[];return Bi(e).allowed.filter((n)=>!t.has(n)).map((n)=>({nodeId:e.id,severity:"error",messageKey:"editor:validation.danglingSecret",params:{label:e.label,secret:n}}))}function jd(e,t){let n=[];for(let r of e){let o=Vk(r,t.schedules);if(o!=null)n.push(o);let i=Kk(r,t.publishedPlans);if(i!=null)n.push(i);let a=qk(r,t.audioFiles);if(a!=null)n.push(a);let s=Bk(r,t.connectors);if(s!=null)n.push(s);n.push(...Hk(r,t.secrets))}return n}function Vd(e,t){let n=[];for(let r of e){if(r.type!=="aiAgent"||t.aiAgents==null)continue;let o=r.config.agent_id;if(typeof o==="string"&&o!==""&&!t.aiAgents.has(o))n.push({nodeId:r.id,severity:"warning",messageKey:"editor:validation.danglingAiAgent",params:{label:r.label}})}return n}var pt={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","ring_duration_s","talk_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"]},Kd=[...pt.basic,...pt.details,...pt.media,...pt.errors,...pt.origin,...pt.metadata,...pt.variables],Vb=/^analysis:[a-z0-9][a-z0-9-]*\.[A-Za-z0-9_-]+(?:\[\])?(?:\.[A-Za-z0-9_-]+(?:\[\])?)*$/,Wk=l().regex(Vb,{error:"Invalid structured-analysis export column"}).refine((e)=>Kb(e),{error:"Invalid structured-analysis export column"});function Kb(e){return Vb.test(e)}var qb=/^signal:[a-z][a-z0-9_]*(?:\.triggered_at)?$/;function Bb(e){return qb.test(e)}var Gk=l().regex(qb,{error:"Invalid signal export column"}).refine((e)=>Bb(e),{error:"Invalid signal export column"}),Hb=["sip_call_id","remote_addr","user_agent"],Zk=new Set(Hb),Yk=Kd.filter((e)=>!Zk.has(e)),Jk=[...pt.basic];var Xk={basic:[...pt.basic],full:[...Kd],ai_audit:[...pt.basic,"transcription_status","transcription","analysis","sentiment_label","ai_agent_price","ai_agent_currency",...pt.errors,...pt.metadata,"variables"]};var Sr=Zt.datetime(),ho={conversation_id:l().min(1).meta({"x-niva-typeid":W.conversations}),call_record_id:l().min(1).nullable().meta({"x-niva-typeid":W.call_records}),attendant_id:l().min(1).nullable().meta({"x-niva-typeid":W.attendants}),user_id:l().min(1).nullable().meta({"x-niva-typeid":W.users}),channel:D(ob),status:D(ib),outcome:D(ab).nullable(),joined_at:Sr,offered_at:Sr.nullable(),answered_at:Sr.nullable(),ended_at:Sr.nullable(),wrapped_at:Sr.nullable(),wait_ms:f().int().nonnegative().nullable(),talk_ms:f().int().nonnegative().nullable(),wrap_ms:f().int().nonnegative().nullable()},qd=K({...ho,queue_id:l().min(1).meta({"x-niva-typeid":W.queues})}),Bd=K({...ho,queue_id:l().min(1).meta({"x-niva-typeid":W.queues}),wait_s:f().int().nonnegative(),short:F()}),Hd=K(ho),Wd=K(ho),Gd=K({...ho,disposition:K({id:l().min(1).meta({"x-niva-typeid":W.dispositions}),code:l(),name:l(),color:D($d).nullable().describe("The colour the organization gave the disposition; null is neutral.")}).nullable(),note:l().nullable()}),Zd=K({attendant_id:l().min(1).meta({"x-niva-typeid":W.attendants}),user_id:l().min(1).meta({"x-niva-typeid":W.users}),from:D(Gc),to:D(Gc),reason:K({id:l().min(1).meta({"x-niva-typeid":W.pause_reasons}),name:l()}).nullable(),source:D(rb),changed_at:Sr});var aa=["call.started","call.answered","call.amd_completed","call.hangup","call.rejected","call.node_entered","call.node_error","call.node_warning","call.transcribed","call.transcription_failed","call.analysis_completed","call.transferred","call.recording_available","call.intent_matched","call.signal_triggered","conversation.queued","conversation.abandoned","conversation.offered","conversation.answered","conversation.wrapped","attendant.status_changed","plan.published","message.sent","dialer.attempt.finished","alert.fired","alert.resolved","service.down","service.up","webhook.test"],Qk=aa.filter((e)=>e!=="webhook.test");var Wb=[1,5,30,120,300,600],e0=Wb.length,Gb=D(["inbound","outbound"]),Re=Zt.datetime(),mt=ie(l(),l()),t0=K({amd:I(!0),machine_type:I(!0).optional(),mode:D(Q_).optional(),max_wait_seconds:f().int().min(3).max(10).optional(),actions:K({silence:D(Hc).optional(),unknown:D(Hc).optional()}).optional()}).superRefine((e,t)=>{if(e.max_wait_seconds!==void 0&&e.mode!=="pre")t.addIssue({code:"custom",path:["max_wait_seconds"],message:"max_wait_seconds is only valid with mode=pre"});if(e.actions!==void 0&&e.mode!=="pre")t.addIssue({code:"custom",path:["actions"],message:"actions is only valid with mode=pre"})}),Zb=K({call_id:l().min(1).meta({"x-niva-typeid":W.call_records}),caller_id:l(),callee_id:l(),direction:Gb,visual_plan_id:l().min(1).meta({"x-niva-typeid":W.visual_plans}),visual_plan_name:l(),started_at:Re,answer_recognition:t0.optional(),metadata:mt}),Yb=K({call_id:l().min(1).meta({"x-niva-typeid":W.call_records}),caller_id:l(),callee_id:l(),answered_at:Re,metadata:mt}),Xd=D(nb),Jb=D(tb),Xb=K({call_id:l().min(1).meta({"x-niva-typeid":W.call_records}),channel_uuid:l().min(1),result:Xd,machine_type:Jb.optional(),completed_at:Re,metadata:mt}).superRefine((e,t)=>{if(e.machine_type!==void 0&&e.result!=="machine")t.addIssue({code:"custom",path:["machine_type"],message:"machine_type is only valid when result is machine"})}),Qb=K({call_id:l().min(1).meta({"x-niva-typeid":W.call_records}),caller_id:l(),callee_id:l(),direction:Gb,visual_plan_id:l().min(1).meta({"x-niva-typeid":W.visual_plans}),visual_plan_name:l(),started_at:Re,answered_at:Re.nullable(),ended_at:Re,duration_ms:f().nonnegative(),ring_duration_ms:f().nonnegative().optional(),talk_duration_ms:f().nonnegative().nullable().optional(),hangup_cause:l(),hangup_disposition:l(),was_recorded:F(),variables:ie(l(),l()),sip_code:l().nullable(),billsec:f().nonnegative().nullable(),answer_recognition_results:K({amd:Xd}).optional(),metadata:mt}),ev=["not_found","channel_inactive","channel_deleted","plan_deleted","no_published_version","org_deleted","acl_denied","capacity_global","capacity_org","capacity_campaign","capacity_reservation"],tv=D(ev),nv=K({caller:l(),destination:l(),reason:tv,hangup_cause:l()}),rv=K({call_id:l().min(1).meta({"x-niva-typeid":W.call_records}),caller_id:l(),callee_id:l(),node_id:l().min(1),node_type:l(),node_label:l(),handle_used:l(),digit:l().nullable(),entered_at:Re,exited_at:Re,duration_ms:f().nonnegative(),visual_plan_id:l().min(1).meta({"x-niva-typeid":W.visual_plans}),metadata:mt}),Qd=K({call_id:l().min(1).meta({"x-niva-typeid":W.call_records}),caller_id:l(),callee_id:l(),node_id:l().min(1),node_type:l(),node_label:l(),error_code:l(),error_message:l(),visual_plan_id:l().min(1).meta({"x-niva-typeid":W.visual_plans}),visual_plan_name:l(),occurred_at:Re,metadata:mt}),ov=Qd,eu=K({call_record_id:l().min(1).meta({"x-niva-typeid":W.call_records}),transcription_id:l().min(1).meta({"x-niva-typeid":W.call_transcriptions}),full_text:l(),is_anonymized:F(),metadata:mt}),iv=eu.pick({call_record_id:!0,transcription_id:!0,metadata:!0}).extend({error_code:D(["ASR_REJECTED","RETRIES_EXHAUSTED","RANGE_TRANSCRIPTION_FAILED","PROCESSING_TIMEOUT"]),error_message:l()}),av=["native","local","sippulse_ai"],n0=D(av),sv=K({source:I("native"),id:Pt(),template_id:Pt(),name:l(),category:Pt()}),cv=K({source:I("local"),id:l().min(1).meta({"x-niva-typeid":W.call_analyses}),template_id:l().min(1).meta({"x-niva-typeid":W.analysis_templates}),name:l(),category:l().nullable()}),lv=K({source:I("sippulse_ai"),id:l().min(1).meta({"x-niva-typeid":W.call_analyses}),template_id:Pt(),external_id:l().min(1),slug:l().min(1),name:l(),category:Pt(),model:l().nullable()}),SW=Ae("source",[sv,cv,lv]),tu={status:D(["completed","failed"]),result:ie(l(),it()).nullable(),error_message:l().nullable(),error_code:l().nullable()},r0=K({...sv.shape,...tu}),o0=K({...cv.shape,...tu}),i0=K({...lv.shape,...tu}),a0=Ae("source",[r0,o0,i0]).superRefine((e,t)=>{if(e.status==="failed"&&e.result!==null)t.addIssue({code:"custom",path:["result"],message:"Failed analyses must have a null result"})}),dv=D(["caller","agent"]),uv=K({id:l().min(1).meta({"x-niva-typeid":W.signals}),slug:l().min(1),name:l(),kind:D(_r),version:f().int().positive()}),s0=K({signal:uv,value:Be([F(),l(),f(),Pt()]),value_label:l().nullable(),confidence:f().nullable(),triggered:K({at_seconds:f(),value:Be([F(),l(),f(),Pt()]),value_label:l().nullable(),confidence:f().nullable(),late:F(),node_id:l().nullable()}).nullable()}),pv=K({call_id:l().min(1).meta({"x-niva-typeid":W.call_records}),call_record_id:l().min(1).meta({"x-niva-typeid":W.call_records}),transcription_id:l().min(1).meta({"x-niva-typeid":W.call_transcriptions}),visual_plan_id:l().nullable().meta({"x-niva-typeid":W.visual_plans}),analyses:a0.array(),signals:s0.array(),analyzed_at:Re,metadata:mt}),mv=["answered","busy","noAnswer","failed"],fv=D(mv),gv=K({call_id:l().min(1).meta({"x-niva-typeid":W.call_records}),caller_id:l(),callee_id:l(),to_destination:l(),method:D(["bridge","sip_message","blind"]),disposition:fv,status:l(),duration_ms:f().nonnegative().nullable(),note:l().nullable(),transferred_at:Re,metadata:mt}),hv=K({call_id:l().min(1).meta({"x-niva-typeid":W.call_records}),call_record_id:l().min(1).meta({"x-niva-typeid":W.call_records}),recording_url:l(),storage_path:l(),duration_seconds:f().nonnegative().nullable(),format:l(),size_bytes:f().nonnegative().nullable(),available_at:Re,metadata:mt}),c0=K({intent:l(),confidence:f()}),yv=K({call_id:l().min(1).meta({"x-niva-typeid":W.call_records}),caller_id:l(),callee_id:l(),node_id:l().min(1),visual_plan_id:l().min(1).meta({"x-niva-typeid":W.visual_plans}),transcript:l(),intent:l(),confidence:f(),alternatives:z(c0),language:l().nullable(),matched_at:Re,metadata:mt}),l0=K({speaker:dv,text:l(),start_seconds:f()}),d0=K({call_id:l().min(1).meta({"x-niva-typeid":W.call_records}),visual_plan_id:l().nullable().meta({"x-niva-typeid":W.visual_plans}),signal:uv,value:Be([F(),l(),f(),Pt()]),value_label:l(),confidence:f(),severity:D(br),speaker:dv,at_seconds:f(),late:F(),source:D(["live","end_of_call"]),node:K({id:l(),label:l(),type:l()}).nullable(),window:z(l0),is_anonymized:F(),trace_url:l().nullable(),metadata:mt}),_v=K({plan_id:l().min(1).meta({"x-niva-typeid":W.visual_plans}),plan_name:l(),version_id:l().min(1).meta({"x-niva-typeid":W.visual_plan_versions}),version_number:f().int().nonnegative(),published_by_user_id:l().min(1).meta({"x-niva-typeid":W.users}),notes:l().nullable(),published_at:Re}),bv=["text","media","audio","image","video","document","location","interactive"],vv=K({session_id:l().min(1).meta({"x-niva-typeid":W.call_records}),channel_type:l(),to:l(),message_type:D(bv),text:l().nullable(),media_url:l().nullable(),node_id:l().nullable(),sent_at:Re}),Sv=["answered","machine","silence","busy","no_answer","failed","originate_error","cancelled"],xv=D(Sv),Ev=K({campaign_id:l().min(1).meta({"x-niva-typeid":W.dialer_campaigns}),campaign_name:l(),contact_id:l().min(1).meta({"x-niva-typeid":W.dialer_contacts}),phone_number:l(),attempt_number:f().int().nonnegative(),status:xv,hangup_cause:l().nullable(),sip_code:l().nullable(),call_uuid:l().nullable(),started_at:Re.nullable(),answered_at:Re.nullable(),ended_at:Re.nullable(),duration_s:f().nonnegative().nullable(),screening_outcome:D(eb).nullable(),custom_fields:ie(l(),l())}),wv=K({alert_type:l(),severity:D(["critical","warning","info"]),title:l(),body:l(),metric_value:f().optional(),threshold:f().optional()}),Cv=K({alert_type:l(),title:l(),body:l()}),Av=K({component:l(),checked_at:Re}),Tv=K({component:l(),downtime_seconds:f().nonnegative().nullable(),recovered_at:Re}),Rv=K({webhook_endpoint_id:l().min(1),message:l().min(1)}),sa={"call.started":Zb,"call.answered":Yb,"call.amd_completed":Xb,"call.hangup":Qb,"call.rejected":nv,"call.node_entered":rv,"call.node_error":Qd,"call.node_warning":ov,"call.transcribed":eu,"call.transcription_failed":iv,"call.analysis_completed":pv,"call.transferred":gv,"call.recording_available":hv,"call.intent_matched":yv,"call.signal_triggered":d0,"conversation.queued":qd,"conversation.abandoned":Bd,"conversation.offered":Hd,"conversation.answered":Wd,"conversation.wrapped":Gd,"attendant.status_changed":Zd,"plan.published":_v,"message.sent":vv,"dialer.attempt.finished":Ev,"alert.fired":wv,"alert.resolved":Cv,"service.down":Av,"service.up":Tv,"webhook.test":Rv};function ce(e){return K({event:I(e),event_id:l().min(1),org_id:l().min(1),timestamp:Re,data:sa[e]})}var u0=Ae("event",[ce("call.started"),ce("call.answered"),ce("call.amd_completed"),ce("call.hangup"),ce("call.rejected"),ce("call.node_entered"),ce("call.node_error"),ce("call.node_warning"),ce("call.transcribed"),ce("call.transcription_failed"),ce("call.analysis_completed"),ce("call.transferred"),ce("call.recording_available"),ce("call.intent_matched"),ce("call.signal_triggered"),ce("conversation.queued"),ce("conversation.abandoned"),ce("conversation.offered"),ce("conversation.answered"),ce("conversation.wrapped"),ce("attendant.status_changed"),ce("plan.published"),ce("message.sent"),ce("dialer.attempt.finished"),ce("alert.fired"),ce("alert.resolved"),ce("service.down"),ce("service.up"),ce("webhook.test")]);function le(e){return K({event:I(e),event_id:l().min(1),timestamp:Re,data:sa[e]})}var p0=Ae("event",[le("call.started"),le("call.answered"),le("call.amd_completed"),le("call.hangup"),le("call.rejected"),le("call.node_entered"),le("call.node_error"),le("call.node_warning"),le("call.transcribed"),le("call.transcription_failed"),le("call.analysis_completed"),le("call.transferred"),le("call.recording_available"),le("call.intent_matched"),le("call.signal_triggered"),le("conversation.queued"),le("conversation.abandoned"),le("conversation.offered"),le("conversation.answered"),le("conversation.wrapped"),le("attendant.status_changed"),le("plan.published"),le("message.sent"),le("dialer.attempt.finished"),le("alert.fired"),le("alert.resolved"),le("service.down"),le("service.up"),le("webhook.test")]),Y="01kknxab29enebk2vhm0tz0yyd",Jd={conversation_id:`conv_${Y}`,call_record_id:`call_${Y}`,attendant_id:null,user_id:null,channel:"voice",status:"queued",outcome:null,joined_at:"2026-01-15T12:00:20.000Z",offered_at:null,answered_at:null,ended_at:null,wrapped_at:null,wait_ms:null,talk_ms:null,wrap_ms:null},Yd={...Jd,attendant_id:`att_${Y}`,user_id:`usr_${Y}`,status:"offered",offered_at:"2026-01-15T12:00:20.000Z"},Iv={"call.started":{call_id:`call_${Y}`,caller_id:"+15551230001",callee_id:"+15551230002",direction:"inbound",visual_plan_id:`vp_${Y}`,visual_plan_name:"Support IVR",started_at:"2026-01-15T12:00:00.000Z",metadata:{}},"call.answered":{call_id:`call_${Y}`,caller_id:"+15551230001",callee_id:"+15551230002",answered_at:"2026-01-15T12:00:03.000Z",metadata:{}},"call.amd_completed":{call_id:`call_${Y}`,channel_uuid:"freeswitch-channel-example",result:"machine",machine_type:"voicemail",completed_at:"2026-01-15T12:00:05.000Z",metadata:{}},"call.hangup":{call_id:`call_${Y}`,caller_id:"+15551230001",callee_id:"+15551230002",direction:"inbound",visual_plan_id:`vp_${Y}`,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,ring_duration_ms:3000,talk_duration_ms:57000,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_${Y}`,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_${Y}`,metadata:{}},"call.node_error":{call_id:`call_${Y}`,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_${Y}`,visual_plan_name:"Support IVR",occurred_at:"2026-01-15T12:00:10.000Z",metadata:{}},"call.node_warning":{call_id:`call_${Y}`,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_${Y}`,visual_plan_name:"Support IVR",occurred_at:"2026-01-15T12:00:10.000Z",metadata:{}},"call.transcribed":{call_record_id:`call_${Y}`,transcription_id:`ctr_${Y}`,full_text:"Hello, I need help with my account.",is_anonymized:!0,metadata:{}},"call.transcription_failed":{call_record_id:`call_${Y}`,transcription_id:`ctr_${Y}`,error_code:"ASR_REJECTED",error_message:"The speech recognition provider rejected the transcription.",metadata:{}},"call.analysis_completed":{call_id:`call_${Y}`,call_record_id:`call_${Y}`,transcription_id:`ctr_${Y}`,visual_plan_id:`vp_${Y}`,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_${Y}`,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_${Y}`,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_${Y}`,caller_id:"+15551230001",callee_id:"+15551230002",to_destination:"support@example.invalid",method:"bridge",disposition:"answered",status:"SUCCESS",duration_ms:null,note:null,transferred_at:"2026-01-15T12:00:20.000Z",metadata:{}},"call.recording_available":{call_id:`call_${Y}`,call_record_id:`call_${Y}`,recording_url:`https://example.invalid/recordings/call_${Y}.wav`,storage_path:`recordings/example/call_${Y}.wav`,duration_seconds:57,format:"wav",size_bytes:912000,available_at:"2026-01-15T12:01:01.000Z",metadata:{}},"call.intent_matched":{call_id:`call_${Y}`,caller_id:"+15551230001",callee_id:"+15551230002",node_id:"node_intent",visual_plan_id:`vp_${Y}`,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_${Y}`,visual_plan_id:`vp_${Y}`,signal:{id:`sig_${Y}`,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_${Y}`,metadata:{}},"conversation.queued":{...Jd,queue_id:`que_${Y}`},"conversation.abandoned":{...Jd,status:"closed",outcome:"abandoned",ended_at:"2026-01-15T12:00:44.000Z",queue_id:`que_${Y}`,wait_s:24,short:!1},"conversation.offered":Yd,"conversation.answered":{...Yd,status:"active",answered_at:"2026-01-15T12:00:26.000Z",wait_ms:6000},"conversation.wrapped":{...Yd,status:"closed",outcome:"completed",answered_at:"2026-01-15T12:00:26.000Z",ended_at:"2026-01-15T12:04:26.000Z",wrapped_at:"2026-01-15T12:05:06.000Z",wait_ms:6000,talk_ms:240000,wrap_ms:40000,disposition:{id:`disp_${Y}`,code:"resolved",name:"Resolved",color:"green"},note:"Customer confirmed the new address."},"attendant.status_changed":{attendant_id:`att_${Y}`,user_id:`usr_${Y}`,from:"available",to:"paused",reason:{id:`pause_${Y}`,name:"Lunch"},source:"attendant",changed_at:"2026-01-15T12:30:00.000Z"},"plan.published":{plan_id:`vp_${Y}`,plan_name:"Support IVR",version_id:`vpv_${Y}`,version_number:3,published_by_user_id:`usr_${Y}`,notes:"Updated support routing",published_at:"2026-01-15T11:00:00.000Z"},"message.sent":{session_id:`call_${Y}`,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_${Y}`,campaign_name:"January outreach",contact_id:`dct_${Y}`,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,screening_outcome:null,custom_fields:{segment:"example"}},"alert.fired":{alert_type:"service_offline",severity:"critical",title:"Example service offline",body:"The example service is unavailable.",metric_value:1,threshold:1},"alert.resolved":{alert_type:"service_offline",title:"Example service recovered",body:"The example service is available again."},"service.down":{component:"example-service",checked_at:"2026-01-15T12:00:00.000Z"},"service.up":{component:"example-service",downtime_seconds:null,recovered_at:"2026-01-15T12:05:00.000Z"},"webhook.test":{webhook_endpoint_id:`whep_${Y}`,message:"This is a test webhook delivery."}};function yo(e){let t=bt[e],n=vt[e],r=n.defaultConfig,o=Mn(n,r),i=typeof n.producedVariables==="function"?n.producedVariables(r):n.producedVariables,a=Yc(e,"en");return{type:e,name:a?.name??e,description:a?.description??"",nameKey:n.nameKey,descriptionKey:n.descriptionKey,module:n.module,category:n.category,channel:n.channel,nature:n.nature,configJsonSchema:Ty(t.configSchema,{unrepresentable:"any"}),outputs:o,producedVariables:i,defaultConfig:r}}var f0=Object.keys(bt);function nu(){return f0.map((e)=>yo(e))}var g0=["string","number","boolean","object","array"],Ov=K({name:l(),type:D(g0),required:F(),nullable:F()}),Nv=K({event:D(aa),required_module:D(Zi).nullable(),fields:z(Ov),example:ie(l(),it())}),h0=z(Nv);var kv="edge";var y0=g({text:l().min(1).max(5000),voice:l().min(1),model:l().default(kv)});var _0=g({signal_id:l(),t:f().min(0),v:Be([F(),l(),Pt(),f()]),c:f().min(0).max(1),node_id:l().nullable()});function ru(e){let t=e.normalize("NFD").replaceAll(/[\u0300-\u036F]/g,"").toLowerCase().replaceAll(/[^a-z0-9]+/g,"_").replaceAll(/_+/g,"_").replaceAll(/^_|_$/g,"");if(!/^[a-z]/.test(t))return`signal_${t}`.slice(0,64)||"signal";return t.slice(0,64)}var ca=[{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 ou(e,t){let n=e.texts[t];return vr.parse({slug:ru(n.name),name:n.name,question:n.question,kind:e.kind,...e.kind==="choice"?{options:(n.options??[]).map((r,o)=>({key:e.option_keys?.[o]??`option_${o}`,label:r.label,...r.description!==void 0?{description:r.description}:{}}))}:{},...e.kind==="scale"?{levels:n.levels??[]}:{},speaker:e.speaker,scope:e.scope,live:e.live,alert:e.alert})}var Dv=["not_applicable","disabled","waiting","pending","processing","completed","failed","skipped","purged","expired"];var NG=new Set(Dv);var iu=ie(l(),l());var la=g({id:l(),sequence:f().int().nonnegative(),nodeId:l(),nodeType:l(),nodeLabel:l(),status:D(["running","completed","warning","error"]),enteredAt:l(),exitedAt:l().nullable(),durationMs:f().int().nonnegative().nullable(),handleUsed:l().nullable(),digit:l().nullable(),variablesBefore:iu,variablesAfter:iu.nullable(),resolvedConfig:ie(l(),it()),resultData:ie(l(),it()).nullable()}).superRefine((e,t)=>{let n=[e.exitedAt,e.durationMs,e.handleUsed,e.variablesAfter];if(e.status==="running"?n.some((o)=>o!==null):n.includes(null))t.addIssue({code:"custom",path:["status"],message:"Running steps must have empty exit fields; terminal steps must have complete exit fields"})}),w0=g({orgId:l(),status:D(["active","waiting_input","ended"]),currentNodeId:l(),variables:iu,steps:z(la),truncated:F()});function Ln(e){return{audio:{tts:{text:e}}}}function A0(e){return{type:"text",text:e}}function T(e){return{...Ln(e),content:A0(e)}}function ne(e,t,n={},r){return{options:t,maxAttempts:3,audio:Ln(e).audio,text:r??e,...n}}function Ne(e,t={}){return{audio:Ln(e).audio,text:e,...t}}function Q(e,t,n,r){return[p(`${e}a`,t,"answered",n),p(`${e}b`,t,"busy",r),p(`${e}n`,t,"noAnswer",r),p(`${e}e`,t,"error",r)]}var T0={x:0,y:0};function h(e,t,n,r,o){return{id:e,type:t,label:n,varName:r,position:T0,config:o}}function p(e,t,n,r){return{id:e,source:t,sourceHandle:n,target:r,targetHandle:"in"}}var Pv={id:"atendente-virtual-ia",category:"ai",requiredModules:["ai"],tags:["ia","agente","ai","virtual","conversacional"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Olá! Sou o assistente virtual. Posso ajudar com diversas questões.")),h("ai1","aiAgent","Agente IA","agente_ia",{agent_id:"",agent_name:"",additional_instructions:"",variables:{},initial_message:"Olá, como posso ajudar?",max_duration_minutes:10}),h("m1","menu","Satisfação","satisfacao",ne("Resolvemos sua dúvida? Se sim, tecle 1. Para falar com um atendente, tecle 2.",[{id:"satisfeito",label:"Satisfeito",digit:"1"},{id:"atendente",label:"Falar com atendente",digit:"2"}],{},"Escolha uma opção:")),h("t2","tell","Agradecimento","agradecimento",T("Obrigado pelo contato. Tenha um bom dia!")),h("t3","tell","Transferindo","transferindo",T("Vou transferir para um atendente humano.")),h("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["1000"],timeout:45}),h("t4","tell","Erro IA","erro_ia",T("Houve um problema com o assistente. Vou transferir para um atendente.")),h("t5","tell","Transferência Falhou","transferencia_falhou",T("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","ai1"),p("e3","ai1","completed","m1"),p("e4","ai1","error","t4"),p("e5","m1","option:satisfeito","t2"),p("e6","m1","option:atendente","t3"),p("e7","m1","noMatch","t3"),p("e8","m1","error","t3"),p("e9","t2","next","h1"),p("e10","t3","next","x1"),p("e11","t4","next","x1"),...Q("ex1","x1","h1","t5"),p("e12","t5","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var $v={id:"atendimento-agente-ia",category:"ai",requiredModules:["ai"],tags:["ia","ai","agente","atendimento","intencao","classificacao","transferencia"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Olá! Você ligou para a nossa central. Em poucas palavras, me diga como posso ajudar.")),h("c1","capture","Captura","captura",Ne("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:Ln("Um momento enquanto analiso o seu pedido.").audio})),h("ra1","routeAi","Classificador","classificador",{input:"{{captura.text}}",intents:[{label:"suporte",description:"Problemas técnicos, falhas, dúvidas de uso do produto ou serviço"},{label:"financeiro",description:"Faturas, cobranças, pagamentos, reembolsos e negociações"}],instructions:"Classifique o motivo do contato do cliente. Duplique um ramo para cada novo assunto atendido."}),h("ai1","aiAgent","Agente","agente",{agent_id:"",agent_name:"",additional_instructions:"O usuário está entrando com o seguinte pedido: {{captura.text}}",variables:{},initial_message:"",max_duration_minutes:10}),h("sw1","switchCase","Decidir","decidir",{expression:"{{agente.output.resultado}}",cases:[{pattern:"^resolvido$"}]}),h("t2","tell","Despedida","despedida",T("Obrigado pelo contato. Tenha um ótimo dia!")),h("t3","tell","Não Entendi","nao_entendeu",T("Não consegui entender o motivo do contato. Vou transferir para um atendente.")),h("t4","tell","Erro Técnico","erro_tecnico",T("Tivemos um problema no atendimento automático. Vou transferir para um atendente.")),h("x1","transfer","Transferência Humana","transfer_humano",{method:"bridge",destinations:["1000"]}),h("t5","tell","Transferência Falhou","transfer_falhou",T("Não conseguimos completar a transferência. Por favor, ligue novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","c1"),p("e3","c1","collected","ra1"),p("e4","c1","noInput","t3"),p("e5","c1","error","t4"),p("e6","ra1","intent:suporte","ai1"),p("e7","ra1","intent:financeiro","x1"),p("e8","ra1","notApplicable","t3"),p("e9","ra1","error","t4"),p("e10","ai1","completed","sw1"),p("e11","ai1","error","t4"),p("e12","sw1","match:^resolvido$","t2"),p("e13","sw1","fallback","x1"),p("e14","sw1","error","t4"),p("e15","t3","next","x1"),p("e16","t4","next","x1"),p("e17","t2","next","h1"),p("e18","x1","answered","t2"),p("e19","x1","busy","t5"),p("e20","x1","noAnswer","t5"),p("e21","x1","error","t5"),p("e22","t5","next","h1")],viewport:{x:0,y:0,zoom:0.75}}};var Mv={id:"atendimento-setores",category:"core",requiredModules:[],tags:["menu","transfer","setores","departamentos","ura"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Bem-vindo. Escolha entre financeiro, suporte, vendas ou ouvidoria.")),h("m1","menu","Menu Principal","menu_principal",ne("Para financeiro, tecle 1. Para suporte, tecle 2. Para vendas, tecle 3. Para ouvidoria, tecle 4.",[{id:"financeiro",label:"Financeiro",digit:"1"},{id:"suporte",label:"Suporte Técnico",digit:"2"},{id:"vendas",label:"Vendas",digit:"3"},{id:"ouvidoria",label:"Ouvidoria",digit:"4"}],{},"Escolha o setor desejado:")),h("t2","tell","Transferindo Financeiro","transferindo_financeiro",T("Aguarde, transferindo para o financeiro.")),h("t3","tell","Transferindo Suporte","transferindo_suporte",T("Aguarde, transferindo para o suporte técnico.")),h("t4","tell","Transferindo Vendas","transferindo_vendas",T("Aguarde, transferindo para vendas.")),h("t5","tell","Transferindo Ouvidoria","transferindo_ouvidoria",T("Aguarde, transferindo para a ouvidoria.")),h("x1","transfer","Financeiro","financeiro",{method:"bridge",destinations:["1001"],timeout:30}),h("x2","transfer","Suporte","suporte",{method:"bridge",destinations:["1002"],timeout:30}),h("x3","transfer","Vendas","vendas",{method:"bridge",destinations:["1003"],timeout:30}),h("x4","transfer","Ouvidoria","ouvidoria",{method:"bridge",destinations:["1004"],timeout:30}),h("t6","tell","Opção Inválida","opcao_invalida",T("Não entendi sua escolha. Por favor, ligue novamente.")),h("t7","tell","Transferência Falhou","transferencia_falhou",T("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","m1"),p("e3","m1","option:financeiro","t2"),p("e4","m1","option:suporte","t3"),p("e5","m1","option:vendas","t4"),p("e6","m1","option:ouvidoria","t5"),p("e7","t2","next","x1"),p("e8","t3","next","x2"),p("e9","t4","next","x3"),p("e10","t5","next","x4"),p("e11","m1","noMatch","t6"),p("e12","m1","error","t6"),p("e13","t6","next","h1"),...Q("ex1","x1","h1","t7"),...Q("ex2","x2","h1","t7"),...Q("ex3","x3","h1","t7"),...Q("ex4","x4","h1","t7"),p("e14","t7","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var Lv={id:"banco-sac",category:"industry",requiredModules:[],tags:["banco","financeiro","sac","saldo","extrato","cartao"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("c1","capture","CPF do Cliente","cpf_cliente",Ne("Bem-vindo ao banco. Digite os onze números do seu CPF.",{voiceMethod:"dtmf",minDigits:11,maxDigits:11,terminators:"#",text:"Bem-vindo ao banco. Informe seu CPF (somente números):",validation:String.raw`^\d{11}$`,invalidMessage:"CPF inválido. Informe os 11 dígitos, somente números:"})),h("m1","menu","Menu Serviços","menu_servicos",ne("Para consultar saldo, tecle 1. Para extrato, tecle 2. Para cartões, tecle 3. Para falar com um atendente, tecle 4.",[{id:"saldo",label:"Consultar saldo",digit:"1"},{id:"extrato",label:"Extrato",digit:"2"},{id:"cartao",label:"Cartões",digit:"3"},{id:"atendente",label:"Falar com atendente",digit:"4"}],{},"Escolha o serviço desejado:")),h("http1","httpRequest","Consultar Saldo","consultar_saldo",{method:"GET",url:"https://api.example.com/accounts/{{cpf_cliente.text}}/balance",headers:{},body:"",timeout:10}),h("t1","tell","Saldo Informado","saldo_informado",T("O seu saldo é: {{consultar_saldo.response}}. Obrigado pelo contato.")),h("t2","tell","Extrato","extrato",T("Seu extrato será enviado por SMS em instantes.")),h("t3","tell","Cartões","cartoes",T("Para informações sobre cartões, vou transferir para um especialista.")),h("t4","tell","Transferindo Atendente","transferindo_atendente",T("Aguarde, vou transferir para um atendente.")),h("t5","tell","Erro Consulta","erro_consulta",T("Não foi possível realizar a consulta agora. Vou transferir para um atendente.")),h("t6","tell","Sem Identificação","sem_identificacao",T("Não consegui identificar o seu CPF. Vou transferir para um atendente.")),h("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["5001"],timeout:45}),h("t7","tell","Transferência Falhou","transferencia_falhou",T("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","c1"),p("e1c","s1","chat","c1"),p("e2","c1","collected","m1"),p("e3","c1","noInput","t6"),p("e4","c1","error","t6"),p("e5","m1","option:saldo","http1"),p("e6","m1","option:extrato","t2"),p("e7","m1","option:cartao","t3"),p("e8","m1","option:atendente","t4"),p("e9","m1","noMatch","t6"),p("e10","m1","error","t6"),p("e11","http1","next","t1"),p("e12","http1","error","t5"),p("e13","t1","next","h1"),p("e14","t2","next","h1"),p("e15","t3","next","x1"),p("e16","t4","next","x1"),p("e17","t5","next","x1"),p("e18","t6","next","x1"),...Q("ex1","x1","h1","t7"),p("e19","t7","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var zv={id:"clinica-agendamento",category:"industry",requiredModules:[],tags:["clinica","saude","agendamento","consulta","medico"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Bem-vindo à central de agendamentos.")),h("m1","menu","Especialidade","especialidade",ne("Para Clínico Geral, tecle 1. Para Cardiologia, tecle 2. Para Ortopedia, tecle 3.",[{id:"clinico",label:"Clínico Geral",digit:"1"},{id:"cardio",label:"Cardiologia",digit:"2"},{id:"orto",label:"Ortopedia",digit:"3"}],{},"Escolha a especialidade desejada:")),h("c1","capture","CPF do Paciente","cpf_paciente",Ne("Digite os onze números do CPF do paciente.",{voiceMethod:"dtmf",minDigits:11,maxDigits:11,terminators:"#",text:"Informe o CPF do paciente (somente números):",validation:String.raw`^\d{11}$`,invalidMessage:"CPF inválido. Informe os 11 dígitos, somente números:"})),h("http1","httpRequest","Consultar Agenda","consultar_agenda",{method:"POST",url:"https://api.example.com/appointments/check",headers:{"Content-Type":"application/json"},body:'{"cpf": "{{cpf_paciente.text}}", "specialty": "{{especialidade.selectedId}}"}',timeout:10}),h("t2","tell","Resultado da Consulta","resultado_consulta",T("{{consultar_agenda.response}}")),h("t3","tell","Erro na Consulta","erro_consulta",T("Não conseguimos consultar a agenda no momento. Por favor, tente novamente mais tarde.")),h("t4","tell","Sem Dados","sem_dados",T("Não consegui capturar as informações necessárias. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","m1"),p("e3","m1","option:clinico","c1"),p("e4","m1","option:cardio","c1"),p("e5","m1","option:orto","c1"),p("e6","m1","noMatch","t4"),p("e7","m1","error","t4"),p("e8","c1","collected","http1"),p("e9","c1","noInput","t4"),p("e10","c1","error","t4"),p("e11","http1","next","t2"),p("e12","http1","error","t3"),p("e13","t2","next","h1"),p("e14","t3","next","h1"),p("e15","t4","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var Fv={id:"cobranca-automatizada",category:"capture",requiredModules:[],tags:["cobranca","debito","pagamento","boleto","pix","negociacao"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Intro Cobrança","intro_cobranca",T("Olá, identificamos um débito em aberto na sua conta.")),h("m1","menu","Opções de Pagamento","opcoes_pagamento",ne("Para negociar a dívida, tecle 1. Para receber o boleto atualizado, tecle 2. Para pagar via Pix, tecle 3.",[{id:"negociar",label:"Negociar dívida",digit:"1"},{id:"boleto",label:"Receber boleto",digit:"2"},{id:"pix",label:"Pagar via Pix",digit:"3"}],{},"Escolha uma opção de pagamento:")),h("c1","capture","Identificação","identificacao",Ne("Informe seu CPF ou número de contrato e finalize com a tecla jogo da velha.",{voiceMethod:"dtmf",minDigits:4,maxDigits:14,terminators:"#",text:"Informe seu CPF ou número de contrato (somente números):",validation:String.raw`^\d{4,14}$`,invalidMessage:"Identificação inválida. Informe apenas números, entre 4 e 14 dígitos:"})),h("t2","tell","Transferindo Negociação","transferindo_negociacao",T("Recebi sua identificação. Vou transferir para um especialista em negociação.")),h("x1","transfer","Negociação","negociacao",{method:"bridge",destinations:["2001"],timeout:45}),h("t3","tell","Boleto Enviado","boleto_enviado",T("O boleto atualizado será enviado para seu contato cadastrado em até 5 minutos.")),h("t4","tell","Chave Pix","chave_pix",T("Nossa chave Pix é o CNPJ da empresa. Após o pagamento, a baixa será automática em até 2 horas.")),h("t5","tell","Opção Inválida","opcao_invalida",T("Não entendi sua escolha. Por favor, ligue novamente.")),h("t6","tell","Sem Identificação","sem_identificacao",T("Não recebi sua identificação. Por favor, ligue novamente com os dados em mãos.")),h("t7","tell","Transferência Falhou","transferencia_falhou",T("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","m1"),p("e3","m1","option:negociar","c1"),p("e4","m1","option:boleto","t3"),p("e5","m1","option:pix","t4"),p("e6","m1","noMatch","t5"),p("e7","m1","error","t5"),p("e8","c1","collected","t2"),p("e9","c1","noInput","t6"),p("e10","c1","error","t6"),p("e11","t2","next","x1"),p("e12","t3","next","h1"),p("e13","t4","next","h1"),p("e14","t5","next","h1"),p("e15","t6","next","h1"),...Q("ex1","x1","h1","t7"),p("e16","t7","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var Uv={id:"coleta-dados-api",category:"capture",requiredModules:[],tags:["capture","api","http","dados","integracao"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Olá. Vou consultar uma informação para você.")),h("c1","capture","Identificação","identificacao",Ne("Informe seu número de identificação e finalize com a tecla jogo da velha.",{voiceMethod:"dtmf",minDigits:4,maxDigits:14,terminators:"#",text:"Informe seu número de identificação (somente números):",validation:String.raw`^\d{4,14}$`,invalidMessage:"Identificação inválida. Informe apenas números, entre 4 e 14 dígitos:"})),h("http1","httpRequest","Consultar API","consultar_api",{method:"GET",url:"https://api.example.com/lookup/{{identificacao.text}}",headers:{},body:"",timeout:10}),h("sw1","switchCase","Tipo de Falha","tipo_falha",{expression:"{{consultar_api.status_code}}",cases:[{pattern:"^404$"}]}),h("t2","tell","Resultado Encontrado","resultado_encontrado",T("Encontrei as informações solicitadas: {{consultar_api.response}}. Obrigado pelo contato.")),h("t3","tell","Não Encontrado","nao_encontrado",T("Não encontrei registros para essa identificação. Verifique o número e tente novamente.")),h("t4","tell","Erro de Consulta","erro_consulta",T("Houve um erro na consulta. Tente novamente mais tarde.")),h("t5","tell","Sem Identificação","sem_identificacao",T("Não consegui capturar sua identificação. Por favor, ligue novamente com o número em mãos.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","c1"),p("e3","c1","collected","http1"),p("e4","c1","noInput","t5"),p("e5","c1","error","t5"),p("e6","http1","next","t2"),p("e7","http1","error","sw1"),p("e8","sw1","match:^404$","t3"),p("e9","sw1","fallback","t4"),p("e10","sw1","error","t4"),p("e11","t2","next","h1"),p("e12","t3","next","h1"),p("e13","t4","next","h1"),p("e14","t5","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var jv={id:"faq-ia-escalacao",category:"ai",requiredModules:["ai"],tags:["faq","ia","escalacao","ai","agente"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Olá! Sou o assistente virtual. Posso tirar dúvidas sobre nossos serviços.")),h("ai1","aiAgent","Agente FAQ","agente_faq",{agent_id:"",agent_name:"",additional_instructions:"Responda perguntas frequentes sobre os serviços da empresa. Se não souber a resposta, informe que vai transferir para um atendente.",variables:{},initial_message:"Olá! Qual sua dúvida?",max_duration_minutes:5}),h("m1","menu","Resolveu?","resolveu",ne("Sua dúvida foi resolvida? Se sim, tecle 1. Para falar com um atendente, tecle 2.",[{id:"resolvido",label:"Sim, resolvido",digit:"1"},{id:"atendente",label:"Falar com atendente",digit:"2"}],{},"Escolha uma opção:")),h("t2","tell","Agradecimento","agradecimento",T("Ótimo! Se precisar de algo mais, é só entrar em contato.")),h("t3","tell","Transferindo","transferindo",T("Aguarde, vou transferir para um atendente.")),h("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["1000"],timeout:45}),h("t4","tell","Transferência Falhou","transferencia_falhou",T("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","ai1"),p("e3","ai1","completed","m1"),p("e4","ai1","error","t3"),p("e5","m1","option:resolvido","t2"),p("e6","m1","option:atendente","t3"),p("e7","m1","noMatch","t3"),p("e8","m1","error","t3"),p("e9","t2","next","h1"),p("e10","t3","next","x1"),...Q("ex1","x1","h1","t4"),p("e11","t4","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var Vv={id:"faq-informacoes",category:"core",requiredModules:[],tags:["faq","informacoes","autoatendimento","info"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Olá, sou o assistente virtual. Posso ajudar com suporte, financeiro, vendas ou horários de atendimento.")),h("m1","menu","Menu FAQ","menu_faq",ne("Para suporte técnico, tecle 1. Para financeiro, tecle 2. Para vendas, tecle 3. Para horários de atendimento, tecle 4.",[{id:"suporte",label:"Suporte Técnico",digit:"1"},{id:"financeiro",label:"Financeiro",digit:"2"},{id:"vendas",label:"Vendas",digit:"3"},{id:"horarios",label:"Horários",digit:"4"}],{},"Escolha um assunto:")),h("t2","tell","Info Suporte","info_suporte",T("Nossa equipe de suporte está disponível 24 horas por dia. Você também pode abrir um chamado pelo nosso portal.")),h("t3","tell","Info Financeiro","info_financeiro",T("Para boletos, notas fiscais e negociações, acesse nosso portal financeiro ou fale com atendimento em horário comercial.")),h("t4","tell","Info Vendas","info_vendas",T("Conheça nossos planos e promoções no nosso site. Para falar com um consultor, ligue em horário comercial.")),h("t5","tell","Info Horários","info_horarios",T("Nosso atendimento funciona de segunda a sexta, das 8h às 20h. Aos sábados, das 8h às 14h.")),h("t6","tell","Opção Inválida","opcao_invalida",T("Não entendi sua escolha. Encerrando o atendimento. Até logo.")),h("h1","hangup","Fim","fim",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","m1"),p("e3","m1","option:suporte","t2"),p("e4","m1","option:financeiro","t3"),p("e5","m1","option:vendas","t4"),p("e6","m1","option:horarios","t5"),p("e7","t2","next","m1"),p("e8","t3","next","m1"),p("e9","t4","next","m1"),p("e10","t5","next","m1"),p("e11","m1","noMatch","t6"),p("e12","m1","error","t6"),p("e13","t6","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var Kv={id:"horario-comercial",category:"core",requiredModules:[],tags:["horario","schedule","tempo","comercial","expediente"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("tr1","timeRouting","Horário Atendimento","horario_atendimento",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Bem-vindo. Como posso ajudar?")),h("m1","menu","Menu Principal","menu_principal",ne("Para suporte, tecle 1. Para vendas, tecle 2.",[{id:"suporte",label:"Suporte",digit:"1"},{id:"vendas",label:"Vendas",digit:"2"}],{},"Escolha uma opção:")),h("t2","tell","Transferindo Suporte","transferindo_suporte",T("Transferindo para o suporte.")),h("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),h("t3","tell","Transferindo Vendas","transferindo_vendas",T("Transferindo para vendas.")),h("x2","transfer","Vendas","vendas",{method:"bridge",destinations:["1002"],timeout:30}),h("t4","tell","Fora do Horário","fora_horario",T("Nosso horário de atendimento é de segunda a sexta, das 8h às 18h. Ligue novamente no próximo dia útil.")),h("t5","tell","Opção Não Reconhecida","opcao_nao_reconhecida",T("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),h("t6","tell","Transferência Falhou","transferencia_falhou",T("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","tr1"),p("e1c","s1","chat","tr1"),p("e2","tr1","onHours","t1"),p("e3","tr1","offHours","t4"),p("e4","tr1","holiday","t4"),p("e5","t1","next","m1"),p("e6","m1","option:suporte","t2"),p("e7","m1","option:vendas","t3"),p("e8","t2","next","x1"),p("e9","t3","next","x2"),p("e10","m1","noMatch","t5"),p("e11","m1","error","t5"),p("e12","t5","next","x1"),...Q("ex1","x1","h1","t6"),...Q("ex2","x2","h1","t6"),p("e13","t4","next","h1"),p("e14","t6","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var qv={id:"isp-suporte-tecnico",category:"industry",requiredModules:[],tags:["isp","provedor","internet","suporte","tecnico","telecom"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Bem-vindo ao suporte técnico.")),h("m1","menu","Tipo de Serviço","tipo_servico",ne("Para problemas de internet, tecle 1. Para problemas de telefonia, tecle 2.",[{id:"internet",label:"Internet",digit:"1"},{id:"telefonia",label:"Telefonia",digit:"2"}],{},"Escolha o tipo de serviço:")),h("c1","capture","Contrato Internet","contrato_internet",Ne("Informe o número do seu contrato.",{voiceMethod:"dtmf",minDigits:3,maxDigits:10,terminators:"#",text:"Informe o número do seu contrato:",validation:String.raw`^\d{3,10}$`,invalidMessage:"O número do contrato deve ter de 3 a 10 dígitos. Tente novamente:"})),h("c2","capture","Contrato Telefonia","contrato_telefonia",Ne("Informe o número do seu contrato.",{voiceMethod:"dtmf",minDigits:3,maxDigits:10,terminators:"#",text:"Informe o número do seu contrato:",validation:String.raw`^\d{3,10}$`,invalidMessage:"O número do contrato deve ter de 3 a 10 dígitos. Tente novamente:"})),h("http1","httpRequest","Status Internet","status_internet",{method:"GET",url:"https://api.example.com/contracts/{{contrato_internet.text}}/status?service=internet",headers:{},body:"",timeout:10}),h("http2","httpRequest","Status Telefonia","status_telefonia",{method:"GET",url:"https://api.example.com/contracts/{{contrato_telefonia.text}}/status?service=telefonia",headers:{},body:"",timeout:10}),h("t2","tell","Status Internet","status_internet_info",T("Sobre sua conexão de internet: {{status_internet.response}}")),h("t3","tell","Status Telefonia","status_telefonia_info",T("Sobre seu serviço de telefonia: {{status_telefonia.response}}")),h("sw1","switchCase","Falha Internet","falha_internet",{expression:"{{status_internet.status_code}}",cases:[{pattern:"^404$"}]}),h("sw2","switchCase","Falha Telefonia","falha_telefonia",{expression:"{{status_telefonia.status_code}}",cases:[{pattern:"^404$"}]}),h("t4","tell","Contrato Não Encontrado","contrato_nao_encontrado",T("Não encontrei esse contrato. Vou transferir para um atendente.")),h("t5","tell","Erro de Consulta","erro_consulta",T("Não foi possível consultar o status agora. Vou transferir para um atendente.")),h("t6","tell","Sem Contrato","sem_contrato",T("Não consegui capturar o número do contrato. Vou transferir para um atendente.")),h("t7","tell","Opção Não Reconhecida","opcao_nao_reconhecida",T("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),h("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["3001"],timeout:60}),h("t8","tell","Transferência Falhou","transferencia_falhou",T("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","m1"),p("e3","m1","option:internet","c1"),p("e4","m1","option:telefonia","c2"),p("e5","m1","noMatch","t7"),p("e5e","m1","error","t7"),p("e6","c1","collected","http1"),p("e7","c1","noInput","t6"),p("e7e","c1","error","t6"),p("e8","http1","next","t2"),p("e9","http1","error","sw1"),p("e10","sw1","match:^404$","t4"),p("e11","sw1","fallback","t5"),p("e11e","sw1","error","t5"),p("e12","t2","next","h1"),p("e13","c2","collected","http2"),p("e14","c2","noInput","t6"),p("e14e","c2","error","t6"),p("e15","http2","next","t3"),p("e16","http2","error","sw2"),p("e17","sw2","match:^404$","t4"),p("e18","sw2","fallback","t5"),p("e18e","sw2","error","t5"),p("e19","t3","next","h1"),p("e20","t4","next","x1"),p("e21","t5","next","x1"),p("e22","t6","next","x1"),p("e23","t7","next","x1"),...Q("ex1","x1","h1","t8"),p("e24","t8","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var Bv={id:"mensagem-simples",category:"core",requiredModules:[],tags:["mensagem","simples","aviso","anuncio","basico"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Mensagem","mensagem",T("Obrigado por ligar. No momento não estamos disponíveis. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","h1")],viewport:{x:0,y:0,zoom:1}}};var Hv={id:"menu-multinivel",category:"advanced",requiredModules:[],tags:["menu","multinivel","departamento","hierarquia","complexo"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Bem-vindo. Escolha o setor desejado.")),h("m1","menu","Menu Principal","menu_principal",ne("Para atendimento, tecle 1. Para comercial, tecle 2. Para administrativo, tecle 3.",[{id:"atendimento",label:"Atendimento",digit:"1"},{id:"comercial",label:"Comercial",digit:"2"},{id:"administrativo",label:"Administrativo",digit:"3"}],{},"Escolha o setor desejado:")),h("m2","menu","Atendimento","atendimento",ne("Para suporte técnico, tecle 1. Para financeiro, tecle 2.",[{id:"suporte",label:"Suporte Técnico",digit:"1"},{id:"financeiro",label:"Financeiro",digit:"2"}],{},"Escolha uma opção:")),h("m3","menu","Comercial","comercial",ne("Para vendas, tecle 1. Para parcerias, tecle 2.",[{id:"vendas",label:"Vendas",digit:"1"},{id:"parcerias",label:"Parcerias",digit:"2"}],{},"Escolha uma opção:")),h("m4","menu","Administrativo","administrativo",ne("Para RH, tecle 1. Para jurídico, tecle 2.",[{id:"rh",label:"RH",digit:"1"},{id:"juridico",label:"Jurídico",digit:"2"}],{},"Escolha uma opção:")),h("t2","tell","Transferindo Suporte","transferindo_suporte",T("Transferindo para suporte técnico.")),h("t3","tell","Transferindo Financeiro","transferindo_financeiro",T("Transferindo para financeiro.")),h("t4","tell","Transferindo Vendas","transferindo_vendas",T("Transferindo para vendas.")),h("t5","tell","Transferindo Parcerias","transferindo_parcerias",T("Transferindo para parcerias.")),h("t6","tell","Transferindo RH","transferindo_rh",T("Transferindo para RH.")),h("t7","tell","Transferindo Jurídico","transferindo_juridico",T("Transferindo para jurídico.")),h("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),h("x2","transfer","Financeiro","financeiro",{method:"bridge",destinations:["1002"],timeout:45}),h("x3","transfer","Vendas","vendas",{method:"bridge",destinations:["2001"],timeout:30}),h("x4","transfer","Parcerias","parcerias",{method:"bridge",destinations:["2002"],timeout:30}),h("x5","transfer","RH","rh",{method:"bridge",destinations:["3001"],timeout:30}),h("x6","transfer","Jurídico","juridico",{method:"bridge",destinations:["3002"],timeout:30}),h("t8","tell","Opção Não Reconhecida","opcao_nao_reconhecida",T("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),h("t9","tell","Transferência Falhou","transferencia_falhou",T("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","m1"),p("e3","m1","option:atendimento","m2"),p("e4","m1","option:comercial","m3"),p("e5","m1","option:administrativo","m4"),p("e6","m1","noMatch","t8"),p("e6e","m1","error","t8"),p("e7","m2","option:suporte","t2"),p("e8","m2","option:financeiro","t3"),p("e9","m2","noMatch","t8"),p("e9e","m2","error","t8"),p("e10","m3","option:vendas","t4"),p("e11","m3","option:parcerias","t5"),p("e12","m3","noMatch","t8"),p("e12e","m3","error","t8"),p("e13","m4","option:rh","t6"),p("e14","m4","option:juridico","t7"),p("e15","m4","noMatch","t8"),p("e15e","m4","error","t8"),p("e16","t2","next","x1"),p("e17","t3","next","x2"),p("e18","t4","next","x3"),p("e19","t5","next","x4"),p("e20","t6","next","x5"),p("e21","t7","next","x6"),p("e28","t8","next","x1"),...Q("ex1","x1","h1","t9"),...Q("ex2","x2","h1","t9"),...Q("ex3","x3","h1","t9"),...Q("ex4","x4","h1","t9"),...Q("ex5","x5","h1","t9"),...Q("ex6","x6","h1","t9"),p("e29","t9","next","h1")],viewport:{x:0,y:0,zoom:0.7}}};var Wv={id:"notificacao-atendimento",category:"core",requiredModules:[],tags:["notificacao","aviso","atendimento","callback"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Notificação","notificacao",T("Olá, temos uma informação importante sobre sua conta.")),h("m1","menu","Precisa de Ajuda?","precisa_ajuda",ne("Tecle 1 para falar com um atendente, ou 2 para encerrar.",[{id:"sim",label:"Sim, falar com atendente",digit:"1"},{id:"nao",label:"Não, obrigado",digit:"2"}],{},"Deseja falar com um atendente?")),h("t2","tell","Transferindo","transferindo",T("Aguarde, vou transferir para um atendente.")),h("x1","transfer","Atendente","atendente",{method:"bridge",destinations:["1000"],timeout:45}),h("t3","tell","Agradecimento","agradecimento",T("Obrigado pelo seu tempo. Tenha um bom dia!")),h("t4","tell","Transferência Falhou","transferencia_falhou",T("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","m1"),p("e3","m1","option:sim","t2"),p("e4","m1","option:nao","t3"),p("e5","m1","noMatch","t3"),p("e6","m1","error","t3"),p("e7","t2","next","x1"),...Q("ex1","x1","h1","t4"),p("e8","t3","next","h1"),p("e9","t4","next","h1")],viewport:{x:0,y:0,zoom:0.9}}};var Gv={id:"pesquisa-nps",category:"advanced",requiredModules:["ai"],tags:["nps","pesquisa","promotor","detrator","feedback","avaliacao"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Intro NPS","intro_nps",T("Gostaríamos de saber sua opinião sobre nosso atendimento.")),h("c1","capture","Nota NPS","nota_nps",Ne("De 0 a 10, qual a probabilidade de recomendar nossos serviços? Tecle a nota.",{voiceMethod:"dtmf",minDigits:1,maxDigits:2,terminators:"#",text:"De 0 a 10, qual a probabilidade de recomendar nossos serviços?",validation:"^(10|[0-9])$",invalidMessage:"Informe uma nota de 0 a 10:"})),h("sw1","switchCase","Classificar NPS","classificar_nps",{expression:"{{nota_nps.text}}",cases:[{pattern:"^9$"},{pattern:"^10$"},{pattern:"^7$"},{pattern:"^8$"}]}),h("t2","tell","Promotor","promotor",T("Que ótimo! Ficamos muito felizes com sua avaliação.")),h("t3","tell","Neutro","neutro",T("Obrigado pela avaliação. Vamos trabalhar para melhorar.")),h("t4","tell","Detrator","detrator",T("Lamentamos que sua experiência não tenha sido satisfatória.")),h("c2","capture","Feedback","feedback",Ne("Pode nos dizer o que podemos melhorar? Fale após o sinal.",{voiceMethod:"speech",text:"Pode nos dizer o que podemos melhorar?"})),h("http1","httpRequest","Salvar Pesquisa","salvar_pesquisa",{method:"POST",url:"https://api.example.com/nps",headers:{"Content-Type":"application/json"},body:'{"score": "{{nota_nps.text}}", "feedback": "{{feedback.text}}"}',timeout:10}),h("t5","tell","Agradecimento","agradecimento",T("Obrigado pelo seu feedback. Ele é muito importante para nós.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","c1"),p("e3","c1","collected","sw1"),p("e4","c1","noInput","t5"),p("e4e","c1","error","t5"),p("e5","sw1","match:^9$","t2"),p("e6","sw1","match:^10$","t2"),p("e7","sw1","match:^7$","t3"),p("e8","sw1","match:^8$","t3"),p("e9","sw1","fallback","t4"),p("e9e","sw1","error","t4"),p("e10","t2","next","c2"),p("e11","t3","next","c2"),p("e12","t4","next","c2"),p("e13","c2","collected","http1"),p("e14","c2","noInput","http1"),p("e14e","c2","error","http1"),p("e15","http1","next","t5"),p("e16","http1","error","t5"),p("e17","t5","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var Zv={id:"pesquisa-satisfacao",category:"core",requiredModules:[],tags:["pesquisa","satisfacao","csat","avaliacao","nota"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Intro Pesquisa","intro_pesquisa",T("Gostaríamos de avaliar o atendimento que você recebeu.")),h("m1","menu","Nota de Satisfação","nota_satisfacao",ne("Como você avalia o atendimento? Tecle 1 para péssimo, 2 para ruim, 3 para regular, 4 para bom, ou 5 para excelente.",[{id:"nota_1",label:"1 - Péssimo",digit:"1"},{id:"nota_2",label:"2 - Ruim",digit:"2"},{id:"nota_3",label:"3 - Regular",digit:"3"},{id:"nota_4",label:"4 - Bom",digit:"4"},{id:"nota_5",label:"5 - Excelente",digit:"5"}],{maxAttempts:2},"Como você avalia o atendimento que recebeu?")),h("t2","tell","Agradecimento","agradecimento",T("Você avaliou nosso atendimento como: {{nota_satisfacao.selectedLabel}}. Obrigado, sua opinião nos ajuda a melhorar.")),h("t3","tell","Sem Resposta","sem_resposta",T("Não conseguimos registrar sua avaliação. Agradecemos o contato.")),h("h1","hangup","Desligamento","desligamento",{}),h("h2","hangup","Desligamento Timeout","desligamento_timeout",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","m1"),p("e3","m1","option:nota_1","t2"),p("e4","m1","option:nota_2","t2"),p("e5","m1","option:nota_3","t2"),p("e6","m1","option:nota_4","t2"),p("e7","m1","option:nota_5","t2"),p("e8","t2","next","h1"),p("e9","m1","noMatch","t3"),p("e10","m1","error","t3"),p("e11","t3","next","h2")],viewport:{x:0,y:0,zoom:0.9}}};var Yv={id:"roteamento-canal",category:"omnichannel",requiredModules:[],tags:["canal","omnichannel","voz","chat","roteamento"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("cr1","channelRouter","Roteador de Canal","roteador_canal",{}),h("t1","tell","Boas-vindas Voz","boas_vindas_voz",T("Bem-vindo ao nosso atendimento por telefone.")),h("m1","menu","Menu Voz","menu_voz",ne("Para suporte, tecle 1. Para vendas, tecle 2.",[{id:"suporte",label:"Suporte",digit:"1"},{id:"vendas",label:"Vendas",digit:"2"}])),h("t2","tell","Boas-vindas Chat","boas_vindas_chat",T("Olá! Bem-vindo ao nosso atendimento por chat.")),h("m2","menu","Menu Chat","menu_chat",ne("Para suporte, tecle 1. Para vendas, tecle 2.",[{id:"suporte",label:"Suporte",digit:"1"},{id:"vendas",label:"Vendas",digit:"2"}],{},"Escolha uma opção:")),h("t3","tell","Transferindo Suporte","transferindo_suporte",T("Transferindo para o suporte.")),h("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),h("t4","tell","Transferindo Vendas","transferindo_vendas",T("Transferindo para vendas.")),h("x2","transfer","Vendas","vendas",{method:"bridge",destinations:["1002"],timeout:30}),h("t5","tell","Opção Não Reconhecida","opcao_nao_reconhecida",T("Não identifiquei a opção escolhida. Vou transferir para um atendente.")),h("t6","tell","Transferência Falhou","transferencia_falhou",T("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","cr1"),p("e1c","s1","chat","cr1"),p("e2","cr1","voice","t1"),p("e3","cr1","chat","t2"),p("e4","t1","next","m1"),p("e5","t2","next","m2"),p("e6","m1","option:suporte","t3"),p("e7","m1","option:vendas","t4"),p("e8","m2","option:suporte","t3"),p("e9","m2","option:vendas","t4"),p("e10","t3","next","x1"),p("e11","t4","next","x2"),...Q("ex1","x1","h1","t6"),...Q("ex2","x2","h1","t6"),p("e12","m1","noMatch","t5"),p("e13","m1","error","t5"),p("e14","m2","noMatch","t5"),p("e15","m2","error","t5"),p("e16","t5","next","x1"),p("e17","t6","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var Jv={id:"status-pedido",category:"capture",requiredModules:[],tags:["pedido","status","rastreio","ecommerce","api"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Olá. Vou consultar o status do seu pedido.")),h("c1","capture","Número do Pedido","numero_pedido",Ne("Informe o número do seu pedido e finalize com a tecla jogo da velha.",{voiceMethod:"dtmf",minDigits:1,maxDigits:10,terminators:"#",text:"Informe o número do seu pedido:",validation:String.raw`^\d{1,10}$`,invalidMessage:"O número do pedido deve conter apenas dígitos. Tente novamente:"})),h("http1","httpRequest","Consultar Pedido","consultar_pedido",{method:"GET",url:"https://api.example.com/orders/{{numero_pedido.text}}",headers:{},body:"",timeout:10}),h("sw1","switchCase","Tipo de Falha","tipo_falha",{expression:"{{consultar_pedido.status_code}}",cases:[{pattern:"^404$"}]}),h("t2","tell","Status do Pedido","status_do_pedido",T("O status do seu pedido é: {{consultar_pedido.response}}")),h("t3","tell","Pedido Não Encontrado","pedido_nao_encontrado",T("Não encontrei esse número de pedido. Verifique e tente novamente.")),h("t4","tell","Erro de Consulta","erro_consulta",T("Houve um erro ao consultar o pedido. Tente novamente mais tarde.")),h("t5","tell","Sem Número","sem_numero",T("Não consegui capturar o número do pedido. Por favor, ligue novamente com o número em mãos.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","c1"),p("e3","c1","collected","http1"),p("e4","c1","noInput","t5"),p("e5","c1","error","t5"),p("e6","http1","next","t2"),p("e7","http1","error","sw1"),p("e8","sw1","match:^404$","t3"),p("e9","sw1","fallback","t4"),p("e10","sw1","error","t4"),p("e11","t2","next","h1"),p("e12","t3","next","h1"),p("e13","t4","next","h1"),p("e14","t5","next","h1")],viewport:{x:0,y:0,zoom:0.85}}};var Xv={id:"triagem-inteligente",category:"ai",requiredModules:["ai"],tags:["triagem","intencao","intent","ia","roteamento","ai"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("t1","tell","Boas-vindas","boas_vindas",T("Olá! Vou te direcionar para o setor correto.")),h("c1","capture","Motivo do Contato","motivo_contato",Ne("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:Ln("Um momento enquanto identifico o setor correto.").audio,text:"Descreva em poucas palavras com o que você precisa de ajuda:"})),h("ra1","routeAi","Classificar Intenção","classificar_intencao",{input:"{{motivo_contato.text}}",intents:[{label:"suporte",description:"Problemas técnicos, dúvidas de uso, erros no sistema"},{label:"financeiro",description:"Faturas, cobranças, pagamentos, reembolsos"},{label:"vendas",description:"Novos produtos, planos, promoções, contratação"}],instructions:"Classifique a intenção do cliente com base no que ele disse."}),h("t2","tell","Direcionando Suporte","direcionando_suporte",T("Entendi, vou transferir para o suporte técnico.")),h("t3","tell","Direcionando Financeiro","direcionando_financeiro",T("Entendi, vou transferir para o financeiro.")),h("t4","tell","Direcionando Vendas","direcionando_vendas",T("Entendi, vou transferir para vendas.")),h("x1","transfer","Suporte","suporte",{method:"bridge",destinations:["1001"],timeout:45}),h("x2","transfer","Financeiro","financeiro",{method:"bridge",destinations:["1002"],timeout:45}),h("x3","transfer","Vendas","vendas",{method:"bridge",destinations:["1003"],timeout:30}),h("t5","tell","Não Identificado","nao_identificado",T("Não consegui identificar sua necessidade. Vou transferir para um atendente.")),h("x4","transfer","Atendente Geral","atendente_geral",{method:"bridge",destinations:["1000"],timeout:45}),h("t6","tell","Transferência Falhou","transferencia_falhou",T("Não conseguimos completar a transferência no momento. Por favor, tente novamente mais tarde.")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","t1"),p("e1c","s1","chat","t1"),p("e2","t1","next","c1"),p("e3","c1","collected","ra1"),p("e4","c1","noInput","t5"),p("e5","c1","error","t5"),p("e6","ra1","intent:suporte","t2"),p("e7","ra1","intent:financeiro","t3"),p("e8","ra1","intent:vendas","t4"),p("e9","ra1","notApplicable","t5"),p("e10","ra1","error","t5"),p("e11","t2","next","x1"),p("e12","t3","next","x2"),p("e13","t4","next","x3"),p("e14","t5","next","x4"),...Q("ex1","x1","h1","t6"),...Q("ex2","x2","h1","t6"),...Q("ex3","x3","h1","t6"),...Q("ex4","x4","h1","t6"),p("e15","t6","next","h1")],viewport:{x:0,y:0,zoom:0.8}}};var Qv={id:"ura-reversa-spot",category:"core",requiredModules:[],tags:["spot","ura reversa","campanha","outbound","discagem","tecla"],editorState:{nodes:[h("s1","start","Início","inicio",{}),h("m1","menu","Spot","spot",ne("Substitua este texto pelo áudio do seu spot. Para falar com um atendente, tecle 1.",[{id:"interesse",label:"Falar com atendente",digit:"1"}],{maxAttempts:1},"Substitua este texto pelo conteúdo do seu spot.")),h("t1","tell","Agradecimento","agradecimento",T("Obrigado! Em instantes um atendente entrará em contato.")),h("t2","tell","Encerramento","encerramento",T("Obrigado pela atenção. Até logo!")),h("h1","hangup","Desligamento","desligamento",{})],edges:[p("e1v","s1","voice","m1"),p("e1c","s1","chat","m1"),p("e2","m1","option:interesse","t1"),p("e3","m1","noMatch","t2"),p("e4","m1","error","t2"),p("e5","t1","next","h1"),p("e6","t2","next","h1")],viewport:{x:0,y:0,zoom:0.9}}};var eS={"atendente-virtual-ia":{ai1:{x:672,y:170},h1:{x:2352,y:254},m1:{x:1008,y:0},s1:{x:0,y:26},t1:{x:336,y:109},t2:{x:1680,y:61},t3:{x:1344,y:113},t4:{x:1344,y:253},t5:{x:2016,y:306},x1:{x:1680,y:201}},"atendimento-agente-ia":{ai1:{x:1344,y:38},c1:{x:672,y:208},h1:{x:3024,y:139},ra1:{x:1008,y:116},s1:{x:0,y:64},sw1:{x:1680,y:0},t1:{x:336,y:147},t2:{x:2688,y:78},t3:{x:1344,y:221},t4:{x:2016,y:153},t5:{x:2688,y:218},x1:{x:2352,y:113}},"atendimento-setores":{h1:{x:2016,y:740},m1:{x:672,y:307},s1:{x:0,y:163},t1:{x:336,y:246},t2:{x:1008,y:0},t3:{x:1008,y:206},t4:{x:1008,y:412},t5:{x:1008,y:552},t6:{x:1008,y:692},t7:{x:1680,y:556},x1:{x:1344,y:61},x2:{x:1344,y:267},x3:{x:1344,y:473},x4:{x:1344,y:679}},"banco-sac":{c1:{x:336,y:356},h1:{x:2352,y:314},http1:{x:1008,y:0},m1:{x:672,y:170},s1:{x:0,y:273},t1:{x:1680,y:205},t2:{x:1344,y:253},t3:{x:1344,y:393},t4:{x:1008,y:321},t5:{x:1344,y:113},t6:{x:1008,y:461},t7:{x:2016,y:537},x1:{x:1680,y:454}},"clinica-agendamento":{c1:{x:1008,y:140},h1:{x:2016,y:306},http1:{x:1344,y:131},m1:{x:672,y:144},s1:{x:0,y:0},t1:{x:336,y:83},t2:{x:1680,y:105},t3:{x:1680,y:245},t4:{x:1344,y:293}},"cobranca-automatizada":{c1:{x:1008,y:139},h1:{x:2352,y:283},m1:{x:672,y:339},s1:{x:0,y:195},t1:{x:336,y:278},t2:{x:1344,y:0},t3:{x:1680,y:335},t4:{x:2016,y:444},t5:{x:1008,y:496},t6:{x:1344,y:222},t7:{x:2016,y:174},x1:{x:1680,y:61}},"coleta-dados-api":{c1:{x:672,y:196},h1:{x:2016,y:174},http1:{x:1008,y:65},s1:{x:0,y:52},sw1:{x:1344,y:148},t1:{x:336,y:135},t2:{x:1344,y:0},t3:{x:1680,y:113},t4:{x:1680,y:253},t5:{x:1008,y:301}},"faq-ia-escalacao":{ai1:{x:672,y:144},h1:{x:2352,y:306},m1:{x:1008,y:52},s1:{x:0,y:0},t1:{x:336,y:83},t2:{x:1680,y:113},t3:{x:1344,y:179},t4:{x:2016,y:358},x1:{x:1680,y:253}},"faq-informacoes":{h1:{x:1354,y:708},m1:{x:672,y:144},s1:{x:0,y:0},t1:{x:336,y:83},t2:{x:1018,y:67},t3:{x:1018,y:227},t4:{x:1018,y:367},t5:{x:1018,y:507},t6:{x:1018,y:647}},"horario-comercial":{h1:{x:2352,y:442},m1:{x:1008,y:206},s1:{x:0,y:193},t1:{x:672,y:145},t2:{x:1344,y:0},t3:{x:1344,y:193},t4:{x:672,y:381},t5:{x:1344,y:333},t6:{x:2016,y:333},tr1:{x:336,y:276},x1:{x:1680,y:61},x2:{x:1680,y:267}},"isp-suporte-tecnico":{c1:{x:1008,y:43},c2:{x:1008,y:227},h1:{x:3034,y:296},http1:{x:1344,y:22},http2:{x:1344,y:341},m1:{x:672,y:144},s1:{x:0,y:0},sw1:{x:1690,y:135},sw2:{x:1690,y:319},t1:{x:336,y:83},t2:{x:2362,y:83},t3:{x:2698,y:488},t4:{x:2026,y:204},t5:{x:2026,y:344},t6:{x:1344,y:201},t7:{x:1008,y:411},t8:{x:2698,y:348},x1:{x:2362,y:265}},"mensagem-simples":{h1:{x:672,y:144},s1:{x:0,y:0},t1:{x:336,y:83}},"menu-multinivel":{h1:{x:2372,y:487},m1:{x:672,y:482},m2:{x:1008,y:250},m3:{x:1008,y:456},m4:{x:1008,y:683},s1:{x:0,y:338},t1:{x:336,y:421},t2:{x:1354,y:71},t3:{x:1354,y:211},t4:{x:1354,y:351},t5:{x:1354,y:491},t6:{x:1354,y:771},t7:{x:1354,y:969},t8:{x:1354,y:631},t9:{x:2036,y:539},x1:{x:1690,y:206},x2:{x:1690,y:0},x3:{x:1690,y:412},x4:{x:1690,y:618},x5:{x:1690,y:824},x6:{x:1690,y:1030}},"notificacao-atendimento":{h1:{x:2016,y:284},m1:{x:672,y:144},s1:{x:0,y:0},t1:{x:336,y:83},t2:{x:1008,y:49},t3:{x:1008,y:271},t4:{x:1680,y:223},x1:{x:1344,y:110}},"pesquisa-nps":{c1:{x:672,y:310},c2:{x:1680,y:201},h1:{x:2688,y:476},http1:{x:2016,y:284},s1:{x:0,y:166},sw1:{x:1008,y:35},t1:{x:336,y:249},t2:{x:1344,y:0},t3:{x:1344,y:140},t4:{x:1344,y:280},t5:{x:2352,y:415}},"pesquisa-satisfacao":{h1:{x:1344,y:288},h2:{x:1344,y:428},m1:{x:672,y:144},s1:{x:0,y:0},t1:{x:336,y:83},t2:{x:1008,y:227},t3:{x:1008,y:367}},"roteamento-canal":{cr1:{x:336,y:83},h1:{x:2362,y:507},m1:{x:1008,y:205},m2:{x:1008,y:411},s1:{x:0,y:0},t1:{x:672,y:144},t2:{x:672,y:350},t3:{x:1354,y:258},t4:{x:1354,y:398},t5:{x:1354,y:538},t6:{x:2026,y:446},x1:{x:1690,y:319},x2:{x:1690,y:525}},"status-pedido":{c1:{x:672,y:196},h1:{x:2016,y:174},http1:{x:1008,y:65},s1:{x:0,y:52},sw1:{x:1344,y:148},t1:{x:336,y:135},t2:{x:1344,y:0},t3:{x:1680,y:113},t4:{x:1680,y:253},t5:{x:1008,y:301}},"triagem-inteligente":{c1:{x:672,y:381},h1:{x:2352,y:455},ra1:{x:1008,y:241},s1:{x:0,y:237},t1:{x:336,y:320},t2:{x:1344,y:0},t3:{x:1344,y:206},t4:{x:1344,y:346},t5:{x:1344,y:486},t6:{x:2016,y:394},x1:{x:1680,y:61},x2:{x:1680,y:267},x3:{x:1680,y:473},x4:{x:1680,y:679}},"ura-reversa-spot":{h1:{x:1008,y:109},m1:{x:336,y:83},s1:{x:0,y:0},t1:{x:672,y:48},t2:{x:672,y:188}}};function R0(e){let t=eS[e.id];if(t==null)return e;return{...e,editorState:{...e.editorState,nodes:e.editorState.nodes.map((n)=>{let r=t[n.id];return r==null?n:{...n,position:{...r}}})}}}var tS=[Mv,Kv,Zv,Vv,Bv,Qv,Uv,Fv,Jv,Pv,Xv,jv,$v,Yv,Wv,zv,qv,Lv,Hv,Gv].map((e)=>R0(e));var au="desk:";function da(e){let t=e.trim();if(!t.startsWith(au))return{kind:"plain"};let n=t.slice(au.length);if(n.includes("{{"))return{kind:"template"};let r;try{r=Ot.fromString(n,W.attendants)}catch{return{kind:"invalid"}}try{return{kind:"desk",attendantId:r.toUUID(),publicId:n}}catch{return{kind:"desk",attendantId:null,publicId:n}}}var nS=[{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"}]}],rS="vars",oS="counters",su=new Set([...nS.map((e)=>e.nodeVarName),qi,rS,oS].map((e)=>e.split(".")[0]));function cu(e){return su.has(e)}var aS={tell:new Set(["audio"]),menu:new Set(["audio","voiceTimeout"]),capture:new Set(["audio","voiceMethod","minDigits","maxDigits","terminators","voiceTimeout","listen","processing_audio","retryAudio"])},sS={tell:new Set(["content"]),menu:new Set(["text","invalidMessage"]),capture:new Set(["text","validation","invalidMessage"])};function lu(e,t,n,r){let o=e.filter((d)=>d.type==="start"),i=U0(t),a=o[0]?.id,s=i1(e,t),c=[...z0(o),...F0(e,t),...j0(e,i,a),...V0(e),...K0(e),...q0(e),...B0(e),...H0(e),...W0(e),...Y0(e),...J0(e),...X0(e,t,n),...t1(e,i,a),...n1(e),...r1(e),...o1(e,n,r?.disabledModules),...r?.entities!=null?jd(e,r.entities):[],...r?.externalEntities!=null?Vd(e,r.externalEntities):[],...a1(e,n,s),...c1(e),...d1(e),...l1(e),...r?.mediaProfile!=null?P0(e,t,r.mediaProfile):[]];if(s!=null)return u1(c,e,s);return c}function P0(e,t,n){let r=e.find((s)=>s.type==="start");if(r==null)return[];let o=new Map;for(let s of t){let c=o.get(s.source)??new Map;c.set(s.sourceHandle,s.target),o.set(s.source,c)}let i=jc(r.id,n.profile,e,o,n.recordingEnabled),a=[];for(let s of e){let c=i[s.id];if(c==null||!$0(s.type))continue;let u=M0(s.type,c).filter((m)=>m.value.kind==="indeterminate");if(u.length>0)a.push({nodeId:s.id,severity:"warning",messageKey:"editor:validation.mediaStateIndeterminate",params:{label:s.label,fields:u.map((m)=>m.name).join(", "),paths:u.map((m)=>L0(m.value)).join("; ")}});if(s.type==="transcription"&&c.transcriptionEnabled.kind==="known"&&c.transcriptionEnabled.value&&c.recordingEnabled.kind==="known"&&!c.recordingEnabled.value)a.push({nodeId:s.id,severity:"warning",messageKey:"editor:validation.transcriptionWithoutRecording",params:{label:s.label}})}return a}function $0(e){return e==="recording"||e==="transcription"||e==="analysis"}function M0(e,t){if(e==="recording")return[{name:"recording",value:t.recordingEnabled},{name:"sampling",value:t.samplingPercentage}];if(e==="transcription")return[{name:"recording",value:t.recordingEnabled},{name:"transcription",value:t.transcriptionEnabled},{name:"language",value:t.transcriptionLanguage},{name:"minimum_duration",value:t.transcriptionMinDurationSeconds},{name:"anonymization",value:t.anonymizeEnabled}];return[{name:"transcription",value:t.transcriptionEnabled},{name:"speech_analytics",value:t.speechAnalyticsEnabled},{name:"sentiment",value:t.sentimentEnabled},{name:"topics",value:t.topicDetectionTopics},{name:"intents",value:t.intentDetectionIntents},{name:"structured_analysis",value:t.structuredAnalysisEnabled},{name:"analysis_ids",value:t.structuredAnalysisIds}]}function L0(e){if(e.kind==="known")return"";return e.branches.map((t)=>t.viaNodeLabel).join(", ")}function z0(e){if(e.length===0)return[{nodeId:"",severity:"error",messageKey:"editor:validation.noStart"}];return e.slice(1).map((t)=>({nodeId:t.id,severity:"error",messageKey:"editor:validation.multipleStart"}))}function F0(e,t){let n=new Set(e.filter((r)=>r.type==="start").map((r)=>r.id));return t.filter((r)=>n.has(r.source)&&r.sourceHandle!=="voice"&&r.sourceHandle!=="chat").map((r)=>({nodeId:r.source,severity:"error",messageKey:"editor:validation.startEdgeHandle",params:{handle:r.sourceHandle}}))}function U0(e){let t=new Map;for(let n of e){let r=t.get(n.source)??[];r.push(n.target),t.set(n.source,r)}return t}function j0(e,t,n){if(n===void 0)return[];let r=new Set([n]),o=[n];while(o.length>0){let a=o.pop();for(let s of t.get(a)??[])if(!r.has(s))r.add(s),o.push(s)}let i=[];for(let a of e)if(a.type!=="start"&&!r.has(a.id))i.push({nodeId:a.id,severity:"warning",messageKey:"editor:validation.unreachable",params:{label:a.label}});return i}function V0(e){let t=[];for(let n of e){if(!Object.hasOwn(bt,n.type)){t.push({nodeId:n.id,severity:"error",messageKey:"editor:validation.unknownNodeType",params:{label:n.label,type:n.type}});continue}let r=bt[n.type],o=r.configSchema.safeParse(n.config),i=o.success?o.data:n.config,a=o.success?r.configSchema.safeParse(i):o;if(a.success)continue;for(let s of a.error.issues){let c=s.message.startsWith("editor:")?s.message:"editor:validation.invalidField";t.push({nodeId:n.id,severity:"error",messageKey:c,params:{label:n.label,field:s.path.join(".")}})}}return t}function _o(e){let t=[];for(let n of e){if(n.type!=="transfer")continue;let r=bt.transfer.configSchema.safeParse(n.config);if(!r.success)continue;t.push({node:n,destinations:r.data.destinations,attachedData:r.data.attachedData})}return t}function K0(e){let t=[];for(let{node:n,destinations:r}of _o(e)){if(r.some((o)=>o.trim()!==""))continue;t.push({nodeId:n.id,severity:"error",messageKey:"editor:validation.noDestinations",params:{label:n.label}})}return t}function q0(e){let t=[];for(let{node:n,destinations:r,attachedData:o}of _o(e)){let i=[...r.map((a,s)=>({field:`destinations.${s}`,template:a})),...o.map((a)=>({field:a.key,template:a.value}))];for(let{field:a,template:s}of i){if(Bc(s).valid)continue;t.push({nodeId:n.id,severity:"error",messageKey:"editor:validation.invalidTemplateSyntax",params:{label:n.label,field:a}})}}return t}function B0(e){let t=[];for(let{node:n,destinations:r}of _o(e))r.forEach((o,i)=>{if(!/\s/.test(o.trim()))return;t.push({nodeId:n.id,severity:"error",messageKey:"editor:validation.destinationHasSpace",params:{label:n.label,field:`destinations.${i}`}})});return t}function H0(e){let t=[];for(let{node:n,destinations:r}of _o(e))r.forEach((o,i)=>{if(da(o).kind!=="invalid")return;t.push({nodeId:n.id,severity:"error",messageKey:"editor:validation.invalidDeskDestination",params:{label:n.label,field:`destinations.${i}`}})});return t}function W0(e){let t=[];for(let n of e){if(n.type!=="enterQueue"&&n.type!=="queryQueue")continue;let r=n.config.queue_id,o=typeof r==="string"?r.trim():"";if(o.includes("{{")||G0(o))continue;t.push({nodeId:n.id,severity:"error",messageKey:"editor:validation.invalidQueueId",params:{label:n.label,field:"queue_id"}})}return t}function G0(e){try{return Ot.fromString(e,W.queues).toUUID(),!0}catch{return!1}}var Z0=new Set(["httpRequest","webhook"]);function Y0(e){let t=[];for(let n of e){if(!Z0.has(n.type))continue;let r=typeof n.config.body==="string"?n.config.body:"";if(r.trim()==="")continue;let o=Kc(r,()=>'"__tpl__"');try{JSON.parse(o)}catch{t.push({nodeId:n.id,severity:"warning",messageKey:"editor:validation.invalidJson",params:{label:n.label}})}}return t}function J0(e){return Hi(e).misplaced.map((t)=>({nodeId:t.nodeId,severity:"error",messageKey:"editor:validation.secretFieldNotAllowed",params:{label:t.label,field:t.field,secret:t.name}}))}function X0(e,t,n){let r=new Set(t.map((i)=>i.source)),o=[];for(let i of e){if(!Object.hasOwn(n,i.type))continue;let a=n[i.type];if(Mn(a,i.config).length===0)continue;if(r.has(i.id))continue;o.push({nodeId:i.id,severity:"warning",messageKey:"editor:validation.noOutputConnection",params:{label:i.label}})}return o}function Q0(e){if(e.type!=="counter")return!1;let t=e.config.action??"increment",n=e.config.limit;return t==="increment"&&typeof n==="number"&&n>0}function e1(e,t){let n=new Set([e]),r=[e];for(let o=r.pop();o!==void 0;o=r.pop())for(let i of t.get(o)??[])if(!n.has(i))n.add(i),r.push(i);return n}function t1(e,t,n){if(n===void 0)return[];let r=new Map(e.map((_)=>[_.id,_])),o=(_)=>{let E=r.get(_);return E!==void 0&&Q0(E)},i=e1(n,t),a=0,s=1,c=2,d=new Map;for(let _ of e)d.set(_.id,a);let u=new Set;function m(_){d.set(_,s);for(let E of o(_)?[]:t.get(_)??[])if(d.get(E)===s)u.add(E);else if(d.get(E)===a)m(E);d.set(_,c)}for(let _ of i)if(d.get(_)===a)m(_);let y=[];for(let _ of u){let E=r.get(_);if(E===void 0)continue;if(!(typeof E.config.maxAttempts==="number"&&E.config.maxAttempts>0))y.push({nodeId:_,severity:"error",messageKey:"editor:validation.infiniteCycle",params:{label:E.label}})}return y}function n1(e){let t=new Map,n=[];for(let r of e)if(t.get(r.varName)!==void 0)n.push({nodeId:r.id,severity:"error",messageKey:"editor:validation.duplicateVarName",params:{label:r.label,varName:r.varName}});else t.set(r.varName,r.id);return n}function r1(e){return e.filter((t)=>cu(t.varName)).map((t)=>({nodeId:t.id,severity:"error",messageKey:"editor:validation.reservedVarName",params:{label:t.label,varName:t.varName}}))}function o1(e,t,n){if(n==null||n.size===0)return[];let r=[];for(let o of e){if(!Object.hasOwn(t,o.type))continue;let i=t[o.type];if(i.module!=="core"&&n.has(i.module))r.push(iS(o,i.module))}if(n.has("desk")){for(let{node:o,destinations:i}of _o(e))if(i.some((a)=>da(a).kind!=="plain"))r.push(iS(o,"desk"))}return r}function iS(e,t){return{nodeId:e.id,severity:"warning",messageKey:"editor:validation.moduleDisabled",params:{label:e.label,module:t}}}function i1(e,t){let n=e.find((i)=>i.type==="start");if(n==null)return null;let r=new Map;for(let i of t){let a=r.get(i.source);if(a==null)a=new Map,r.set(i.source,a);a.set(i.sourceHandle,i.target)}let o=new Set;for(let i of e)if(i.type==="channelRouter")o.add(i.id);return Fd(n.id,r,e.map((i)=>i.id),o.size>0?o:void 0)}function a1(e,t,n){if(n==null)return[];let r=[];for(let o of e){if(o.type==="start")continue;if(!Object.hasOwn(t,o.type))continue;let i=t[o.type],a=n[o.id];if(a==null||a==="unreachable"||a==="converged")continue;if(i.channel==="voice"&&a==="chat-only")r.push({nodeId:o.id,severity:"error",messageKey:"editor:validation.voiceNodeInChatBranch",params:{label:o.label}});if(i.channel==="chat"&&a==="voice-only")r.push({nodeId:o.id,severity:"error",messageKey:"editor:validation.chatNodeInVoiceBranch",params:{label:o.label}})}return r}var s1={retellAgent:{agentField:"agent_id",agentMessageKey:"editor:validation.voiceAgentAgentRequired"},vapiAgent:{agentField:"assistant_id",agentMessageKey:"editor:validation.voiceAgentAssistantRequired"},elevenlabsAgent:{agentField:"agent_id",agentMessageKey:"editor:validation.voiceAgentAgentRequired"},openaiLiveAgent:{agentField:"agent_id",agentMessageKey:"editor:validation.openaiLiveAgentRequired"}};function c1(e){let t=[];for(let n of e){let r=s1[n.type];if(r===void 0)continue;let o=n.config.connector_id;if(typeof o!=="string"||o==="")t.push({nodeId:n.id,severity:"error",messageKey:"editor:validation.voiceAgentConnectorRequired",params:{label:n.label}});let i=n.config[r.agentField];if(typeof i!=="string"||i==="")t.push({nodeId:n.id,severity:"error",messageKey:r.agentMessageKey,params:{label:n.label}})}return t}function l1(e){return e.filter((t)=>t.type==="timeRouting").filter((t)=>t.config.scheduleId===void 0||t.config.scheduleId==="").map((t)=>({nodeId:t.id,severity:"warning",messageKey:"editor:validation.timeRoutingWithoutSchedule",params:{label:t.label}}))}function d1(e){let t=[];for(let n of e){if(n.type!=="openaiLiveAgent")continue;let r=mo.shape.output_fields.safeParse(n.config.output_fields);if(!r.success)continue;let o=new Set;for(let i of r.data){let a=po.test(i.name)&&!o.has(i.name);if(o.add(i.name),a)continue;t.push({nodeId:n.id,severity:"error",messageKey:"editor:validation.openaiLiveOutputFieldInvalid",params:{label:n.label,name:i.name}})}}return t}function u1(e,t,n){let r=new Map(t.map((o)=>[o.id,o.type]));return e.filter((o)=>{let i=o.params?.field;if(i==null||o.nodeId==="")return!0;let a=r.get(o.nodeId);if(a==null)return!0;let s=n[o.nodeId];if(s==null||s==="converged"||s==="unreachable")return!0;let c=i.split(".")[0];if(s==="chat-only"&&aS[a]?.has(c))return!1;if(s==="voice-only"&&sS[a]?.has(c))return!1;return!0})}function du(e){return e.every((t)=>t.severity!=="error")}var ua="niva-webchat",pa=1;var at={source:I(ua),v:I(pa)},cS=["chat","form","consent","ended","closed"],uu=D(cS),f1=ie(l(),it()),g1=g({prechat:g({enabled:F(),fields:g({name:F(),email:F(),phone:F()})}),consent:g({enabled:F(),privacy_url:l().optional()})}),h1=g({layout:D(["bubble","side","inline"]),side:D(["left","right"]),label:l().max(pn.label.max),teaser:l().max(pn.teaser.max)}),y1=Ae("type",[g({...at,type:I("open")}),g({...at,type:I("close")}),g({...at,type:I("send"),text:l()}),g({...at,type:I("set_context"),context:ie(l(),it())}),g({...at,type:I("identify"),token:l()}),g({...at,type:I("shutdown")}),g({...at,type:I("preview"),appearance:f1,scene:uu,visitor:g1,launcher:h1})]),_1=Ae("type",[g({...at,type:I("ready")}),g({...at,type:I("opened")}),g({...at,type:I("closed")}),g({...at,type:I("unread"),count:f().int().min(0)}),g({...at,type:I("ended")}),g({...at,type:I("request_close")})]),b1=g({...at,type:I("preview_scene"),scene:uu});var v1=D(["image","audio","video","document"]),S1=g({type:I("text"),text:l().min(1)}),x1=g({type:I("location"),lat:f(),lng:f()}),E1=g({type:I("button_reply"),button_id:l().min(1),button_text:l()}),w1=g({type:I("list_reply"),list_id:l().min(1),list_title:l()}),C1=g({type:I("command"),command:l().min(1),args:l().optional()}),A1=g({type:I("media"),media_id:l().regex(/^media_[0-7][0-9a-hjkmnp-tv-z]{25}$/),caption:l().max(4000).optional()}),lS=Ae("type",[S1,x1,E1,w1,C1,A1]),T1=g({title:l().min(1),description:l().optional(),image_url:l().optional(),buttons:z(yr).default([])}),R1=g({type:I("text"),text:l().min(1),markdown:F().optional()}),I1=g({type:I("media"),media_type:v1,url:l().min(1),caption:l().optional()}),O1=g({type:I("location"),lat:f(),lng:f(),label:l().optional()}),N1=g({type:I("buttons"),text:l().min(1),buttons:z(yr).min(1)}),k1=g({type:I("list"),text:l().min(1),button_text:l().min(1),sections:z(Qi).min(1)}),D1=g({type:I("carousel"),cards:z(T1).min(1)}),P1=g({type:I("template"),template_id:l().min(1),params:ie(l(),l()).default({})}),dS=Ae("type",[R1,I1,O1,N1,k1,D1,P1]);var $1=g({type:I("message"),message:lS}),M1=g({type:I("typing")}),L1=g({type:I("ping")}),z1=g({type:I("resume"),last_seq:f().int().min(0)}),F1=g({type:I("start")}),U1=Ae("type",[$1,M1,L1,z1,F1]),uS=g({type:I("connected"),seq:f().int(),ts:f(),session_id:l()}),pS=g({type:I("message"),seq:f().int(),ts:f(),id:l(),message:dS,nodeId:l().optional()}),mS=g({type:I("typing"),seq:f().int(),ts:f(),active:F()}),fS=g({type:I("state"),seq:f().int(),ts:f(),status:D(["active","waiting_input","ended"])}),gS=g({type:I("trace"),seq:f().int(),ts:f(),currentNodeId:l(),variables:ie(l(),l()),status:D(["active","waiting_input","ended"]),truncated:F(),step:la.optional()}),hS=g({type:I("error"),seq:f().int(),ts:f(),code:l(),message:l()}),yS=g({type:I("pong"),seq:f().int(),ts:f()}),j1=Ae("type",[uS,pS,mS,fS,gS,hS,yS]),V1=g({type:I("replay"),seq:f().int(),ts:f(),messages:z(j1)}),K1=Ae("type",[uS,pS,mS,fS,gS,hS,yS,V1]);var ma=r_([I(W.signals),I("_"),l()]),q1=r_([I(W.visual_plans),I("_"),l()]),B1=["volume","answered","busy","no_answer","failed","outcome","duration","ai_cost","flow_errors"],H1=["answered","busy","no_answer","failed"],W1=["number","trend","compare","distribution","weekday_hour"],G1=["plan_version","plan","hour_of_day","weekday","channel"];var K9=Be([I(1),I(2),I(3),I(4)]).describe("Pinned-card column span (1-4). Null means the default for the query shape.");var Z1=["today","yesterday","last_7_days","last_30_days","this_month","last_month"],Y1=["voice","chat"],J1=Be([g({preset:D(Z1)}),g({date_from:l(),date_to:l()}),g({last_days:f().int().min(1).max(366)})]),X1=Ae("kind",[g({kind:I("calls"),measure:D(B1),value:D(H1).optional()}),g({kind:I("signal"),signal_id:ma,value:l().optional()})]),Q1=Be([D(G1),g({signal_id:ma})]),eD=g({subject:X1,shape:D(W1),compare_by:Q1.optional(),period:J1,channel:D(Y1).optional(),plan_id:q1.optional()}),tD=g({id:ma,name:l(),question:l(),kind:D(["yes_no","choice","scale"]),options:z(g({key:l(),label:l()})).optional(),levels:z(l()).optional(),higher_is:D(fo).optional()}),q9=g({org_id:l(),signals:z(tD)}),bo=g({answered:f().int(),no_answer:f().int().nullable(),not_evaluated:f().int().nullable()}),nD=g({shape:I("number"),value:f(),n:f().int(),dist:z(g({key:l(),label:l(),value:f()})).optional(),rate:f().nullable(),low:f().nullable(),high:f().nullable(),previous:g({value:f(),rate:f().nullable(),low:f().nullable(),high:f().nullable()}).nullable(),change:D(["up","down","stable"]).nullable(),denominator:bo}),bS=g({bucket:l(),value:f(),n:f().int(),low:f().nullable(),high:f().nullable(),small:F()}),rD=g({date:l(),label:l()}),oD=g({key:l(),label:l(),points:z(bS)}),iD=g({shape:I("trend"),granularity:D(["day","hour"]),points:z(bS),series:z(oD).optional(),plan_versions:z(rD),denominator:bo}),aD=g({key:l(),label:l().nullable(),version:f().int().nullable().optional(),value:f(),n:f().int(),low:f().nullable(),high:f().nullable(),small:F(),dist:z(g({key:l(),label:l(),value:f()})).optional()}),sD=g({shape:I("compare"),rows:z(aD),denominator:bo}),cD=g({key:l(),label:l(),value:f(),n:f().int()}),lD=g({shape:I("distribution"),rows:z(cD),denominator:bo}),dD=g({weekday:f().int(),hour:f().int(),value:f(),n:f().int(),low:f().nullable(),high:f().nullable()}),uD=g({shape:I("weekday_hour"),cells:z(dD),denominator:bo}),B9=Ae("shape",[nD,iD,sD,lD,uD]),_S=g({rate:f(),low:f(),high:f()}),pD=g({signal_id:ma,kind:D(["yes_no","choice","scale"]),name:l(),question:l(),alert_label:l().nullable(),alert_below:F(),higher_is:D(fo).nullable(),n:f().int(),value:f().nullable(),rate:f().nullable(),low:f().nullable(),high:f().nullable(),distribution:z(g({key:l(),label:l(),value:f()})),series:z(g({bucket:l(),value:f(),n:f().int()})),alert_share:_S.nullable(),previous_share:_S.nullable(),in_alert:F()}),H9=g({cards:z(pD)}),mD=g({strategy:l(),model:l(),ms:f(),input_tokens:f(),output_tokens:f()}),W9=g({query:eD.nullable(),confidence:f(),period_explicit:F(),meta:mD});var vo="x-niva-cli-command";function vS(e){return e[0]??{}}function Fn(e){return Array.isArray(e)?e:e===void 0||e===null?[]:[e]}var pu=4300,fD=/^-?(?:0|[1-9]\d*)$/;function SS(e,t){if((e.startsWith("-")?e.length-1:e.length)>t||!fD.test(e))return;return BigInt(e)}var mu="orpc",gD="@orpc/shared",hD="1.16.1";class fu extends Error{constructor(...e){super(...e);this.name="AbortError"}}function gu(e){let t;return()=>{if(t)return t.result;let n=e();return t={result:n},n}}function yD(e){let t=Promise.resolve();return(...n)=>t=t.catch(()=>{}).then(()=>e(...n))}var _D=2,bD=`__${gD}@${hD}/otel/config__`;function So(){return globalThis[bD]}function fa(e,t={},n){return So()?.tracer?.startSpan(e,t,n)}function gn(e,t,n={}){if(!e)return;let r=vD(t);if(e.recordException(r),!n.signal?.aborted||n.signal.reason!==t)e.setStatus({code:_D,message:r.message})}function vD(e){if(e instanceof Error){let t={message:e.message,name:e.name,stack:e.stack};if("code"in e&&(typeof e.code==="string"||typeof e.code==="number"))t.code=e.code;return t}return{message:String(e)}}async function Un({name:e,context:t,...n},r){let o=So()?.tracer;if(!o)return r();let i=async(a)=>{try{return await r(a)}catch(s){throw gn(a,s,n),s}finally{a.end()}};if(t)return o.startActiveSpan(e,n,t,i);else return o.startActiveSpan(e,n,i)}async function zn(e,t){let n=So();if(!e||!n)return t();let r=n.trace.setSpan(n.context.active(),e);return n.context.with(r,t)}function Jt(e){if(!e||typeof e!=="object")return!1;return"next"in e&&typeof e.next==="function"&&Symbol.asyncIterator in e&&typeof e[Symbol.asyncIterator]==="function"}var SD=Symbol.for("asyncDispose"),xD=Symbol.asyncDispose??SD;class jn{#e=!1;#t=!1;#n;#r;constructor(e,t){this.#n=t,this.#r=yD(async()=>{if(this.#e)return{done:!0,value:void 0};try{let n=await e();if(n.done)this.#e=!0;return n}catch(n){throw this.#e=!0,n}finally{if(this.#e&&!this.#t)this.#t=!0,await this.#n("next")}})}next(){return this.#r()}async return(e){if(this.#e=!0,!this.#t)this.#t=!0,await this.#n("return");return{done:!0,value:e}}async throw(e){if(this.#e=!0,!this.#t)this.#t=!0,await this.#n("throw");throw e}async[xD](){if(this.#e=!0,!this.#t)this.#t=!0,await this.#n("dispose")}[Symbol.asyncIterator](){return this}}function hu({name:e,...t},n){let r;return new jn(async()=>{r??=fa(e);try{let o=await zn(r,()=>n.next());return r?.addEvent(o.done?"completed":"yielded"),o}catch(o){throw gn(r,o,t),o}},async(o)=>{try{if(o!=="next")await zn(r,()=>n.return?.())}catch(i){throw gn(r,i,t),i}finally{r?.end()}})}function xo(e,t,n){let r=(o,i)=>{let a=e[i];if(!a)return n(o);return a({...o,next:(s=o)=>r(s,i+1)})};return r(t,0)}function Eo(e){if(!e)return;return JSON.parse(e)}function Vn(e){return JSON.stringify(e)}function xS(e){if(!zt(e))return null;return Object.getPrototypeOf(e)?.constructor}function wo(e){if(!e||typeof e!=="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||!t||!t.constructor}function zt(e){return!!e&&(typeof e==="object"||typeof e==="function")}function ED(e,t,n){if(t==="__proto__")Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0});else e[t]=n}function yu(e,t,n){let r=e[t];if(r!==n)return r;let o;if(Array.isArray(r))o=r.slice();else if(wo(r))o={...r};else return r;return ED(e,t,o),o}function Co(e,...t){if(typeof e==="function")return e(...t);return e}function _u(e){return new Proxy(e,{get(t,n,r){let o=Reflect.get(t,n,r);if(n!=="then"||typeof o!=="function")return o;return new Proxy(o,{apply(i,a,s){if(s.length!==2||s.some((d)=>!CD(d)))return Reflect.apply(i,a,s);let c=!0;s[0].call(a,_u(new Proxy(t,{get:(d,u,m)=>{if(c&&u==="then"){c=!1;return}return Reflect.get(d,u,m)}})))}})}})}var wD=/^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;function CD(e){return typeof e==="function"&&wD.test(e.toString())}var AD=/^[dgimsuvy]*$/;function ES(e){return AD.test(e)&&new Set(e).size===e.length&&!(e.includes("u")&&e.includes("v"))}function wS(e,t){let n,r=0,o=()=>{if(n===void 0)n=new RegExp(e,t),n.lastIndex=r;return n};return new Proxy(Object.create(RegExp.prototype),{get(i,a){if(a===Symbol.toStringTag)return"RegExp";if(n===void 0){if(a==="lastIndex")return r;if(!(a in RegExp.prototype))return}let s=o(),c=Reflect.get(s,a,s);return typeof c==="function"&&a!=="constructor"?c.bind(s):c},set(i,a,s){if(n===void 0&&a==="lastIndex")return r=s,!0;let c=o();return Reflect.set(c,a,s,c)},has(i,a){if(n===void 0)return a==="lastIndex"||a in RegExp.prototype;return Reflect.has(n,a)}})}function CS(e){try{return decodeURIComponent(e)}catch{return e}}var TD="@orpc/client",RD="1.16.1",AS=new Set(["bind","valueOf","toString","toJSON"]),ha={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 ID(e,t){return t??ha[e]?.status??500}function OD(e,t){return t||ha[e]?.message||e}var ga;class Kn extends Error{defined;code;status;data;static{let e=Symbol.for(`__${TD}@${RD}/error/ORPC_ERROR_CONSTRUCTORS__`);globalThis[e]??=new WeakSet,ga=globalThis[e],ga.add(Kn)}constructor(e,...t){let n=vS(t);if(n.status!==void 0&&!ya(n.status))throw Error("[ORPCError] Invalid error status code.");let r=OD(e,n.message);super(r,n);this.code=e,this.status=ID(e,n.status),this.defined=n.defined??!1,this.data=n.data}toJSON(){return{defined:this.defined,code:this.code,status:this.status,message:this.message,data:this.data}}static[Symbol.hasInstance](e){if(ga.has(this)){let t=xS(e);if(t&&ga.has(t))return!0}return super[Symbol.hasInstance](e)}}function TS(e){return e instanceof Kn?e:new Kn("INTERNAL_SERVER_ERROR",{message:"Internal server error",cause:e})}function ya(e){return e<200||e>=400}function bu(e){if(!wo(e))return!1;let t=["defined","code","status","message","data"];if(Object.keys(e).some((n)=>!t.includes(n)))return!1;return"defined"in e&&typeof e.defined==="boolean"&&"code"in e&&typeof e.code==="string"&&"status"in e&&typeof e.status==="number"&&ya(e.status)&&"message"in e&&typeof e.message==="string"}function vu(e,t={}){return new Kn(e.code,{...t,...e})}class Ao extends TypeError{}class RS extends TypeError{}class Xt extends Error{data;constructor(e){super(e?.message??"An error event was received",e);this.data=e?.data}}var ND=/\r\n|\r(?!\n)|\n/,kD=/(?:\r\n|\r(?!\n)|\n){2}/,DD=/(?:\r\n|\r(?!\n)|\n){2}/g,PD=13,$D=10,MD=32;function LD(e){let t={data:void 0,event:void 0,id:void 0,retry:void 0,comments:[]};for(let n of e.split(ND)){if(n==="")continue;let r=n.indexOf(":"),o=r===-1?"":n.slice(n.charCodeAt(r+1)===MD?r+2:r+1);if(r===0){t.comments.push(o);continue}switch(r===-1?n:n.slice(0,r)){case"data":t.data=t.data===void 0?o:`${t.data}
|
|
92
|
+
${o}`;break;case"event":t.event=o;break;case"id":t.id=o;break;case"retry":{let i=Number.parseInt(o,10);if(i>=0&&i.toString()===o)t.retry=i;break}}}return t}class IS{constructor(e={}){this.options=e}pending=[];tail="";discardLeadingLF=!1;feed(e){if(e==="")return;if(this.discardLeadingLF){if(this.discardLeadingLF=!1,e.charCodeAt(0)===$D){if(e=e.slice(1),e==="")return}}let t=this.tail+e;if(!kD.test(t)){this.pending.push(e),this.tail=t.slice(-3);return}this.pending.push(e);let n=this.pending.length===1?e:this.pending.join(""),r=n.length-t.length,o=[],i=0;for(let s of t.matchAll(DD))o.push(n.slice(i,r+s.index)),i=r+s.index+s[0].length;let a=n.slice(i);if(this.pending.length=0,this.tail=a.slice(-3),a==="")this.discardLeadingLF=e.charCodeAt(e.length-1)===PD;else this.pending.push(a);for(let s of o){let c=LD(s);if(this.options.onEvent)this.options.onEvent(c)}}end(){if(this.pending.length!==0)throw new RS("Event Iterator ended before complete")}}class Su extends TransformStream{constructor(){let e;super({start(t){e=new IS({onEvent:(n)=>{t.enqueue(n)}})},transform(t){e.feed(t)},flush(){e.end()}})}}var zD=/\r\n|[\n\r]/,FD=/\r\n|[\n\r]/g;function xu(e){return zD.test(e)}function OS(e){if(xu(e))throw new Ao("Event's id must not contain a carriage return or newline character")}function UD(e){if(xu(e))throw new Ao("Event's event must not contain a carriage return or newline character")}function NS(e){if(!Number.isInteger(e)||e<0)throw new Ao("Event's retry must be a integer and >= 0")}function kS(e){if(xu(e))throw new Ao("Event's comment must not contain a carriage return or newline character")}function jD(e){if(e===void 0)return"";return`data: ${e.replace(FD,`
|
|
93
93
|
data: `)}
|
|
94
|
-
`}function
|
|
95
|
-
`;return t}function To(e){let t="";if(t+=
|
|
96
|
-
`;if(e.retry!==void 0)
|
|
97
|
-
`;if(e.id!==void 0)
|
|
98
|
-
`;return t+=
|
|
99
|
-
`,t}var $S=Symbol("ORPC_EVENT_SOURCE_META");function qn(e,t){if(t.id===void 0&&t.retry===void 0&&!t.comments?.length)return e;if(t.id!==void 0)kS(t.id);if(t.retry!==void 0)DS(t.retry);if(t.comments!==void 0)for(let n of t.comments)PS(n);return new Proxy(e,{get(n,r,o){if(r===$S)return t;return Reflect.get(n,r,o)}})}function xr(e){return zt(e)?Reflect.get(e,$S):void 0}function MS(e,t="inline"){let n=e.replace(/[^\x20-\x7E]/g,"_").replace(/"/g,"\\\""),r=encodeURIComponent(e).replace(/['()*]/g,(o)=>`%${o.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(7C|60|5E)/g,(o,i)=>String.fromCharCode(Number.parseInt(i,16)));return`${t}; filename="${n}"; filename*=utf-8''${r}`}function LS(e){let t=e.match(/filename\*=(UTF-8'')?([^;]*)/i);if(t&&typeof t[2]==="string")return TS(t[2]);let n=e.match(/filename="((?:\\"|[^"])*)"/i);if(n&&typeof n[1]==="string")return n[1].replace(/\\"/g,'"')}function zS(e,t){let n={...e};for(let r in t)if(Array.isArray(t[r]))n[r]=[...Fn(n[r]),...t[r]];else if(t[r]!==void 0)if(Array.isArray(n[r]))n[r]=[...n[r],t[r]];else if(n[r]!==void 0)n[r]=[n[r],t[r]];else n[r]=t[r];return n}function Cu(e,t){let n=async(r)=>{let o=await t.error(r);if(o!==r){let i=xr(r);if(i&&zt(o))o=qn(o,i)}return o};return new jn(async()=>{let{done:r,value:o}=await(async()=>{try{return await e.next()}catch(a){throw await n(a)}})(),i=await t.value(o,r);if(i!==o){let a=xr(o);if(a&&zt(i))i=qn(i,a)}return{done:r,value:i}},async()=>{try{await e.return?.()}catch(r){throw await n(r)}})}function HD(e){return{...e,context:e.context??{}}}function Qt(e,t){return(async()=>{let n;try{let r=await e;while(!0){let{done:o,value:i}=await r.next();if(o){let a=i;n=[null,a,!0],t.onSuccess?.(a);break}t.onEvent(i)}}catch(r){if(n=[r,void 0,!1],!t.onError&&!t.onFinish)throw r;t.onError?.(r)}finally{t.onFinish?.(n)}})(),async()=>{await(await e)?.return?.()}}function Bn(e,t={}){let n=t.path??[],o=new Proxy(async(...[i,a={}])=>await e.call(n,i,HD(a)),{get(i,a){if(typeof a!=="string"||RS.has(a))return Reflect.get(i,a);return Bn(e,{...t,path:[...n,a]})}});return vu(o)}function WD(e,t={}){let r=e?.pipeThrough(new TextDecoderStream).pipeThrough(new Eu)?.getReader(),o,i=!1;return new jn(async()=>{o??=ga("consume_event_iterator_stream");try{while(!0){if(r===void 0)return{done:!0,value:void 0};let{done:a,value:s}=await zn(o,()=>r.read());if(a){if(i)throw new hu("Stream was cancelled");return{done:!0,value:void 0}}switch(s.event??(s.data!==void 0?"message":void 0)){case"message":{let d=Eo(s.data);if(zt(d))d=qn(d,s);return o?.addEvent("message"),{done:!1,value:d}}case"error":{let d=new Xt({data:Eo(s.data)});throw d=qn(d,s),o?.addEvent("error"),d}case"done":case"close":{let d=Eo(s.data);if(zt(d))d=qn(d,s);return o?.addEvent("done"),{done:!0,value:d}}default:o?.addEvent("maybe_keepalive")}}}catch(a){if(!(a instanceof Xt))gn(o,a,t);throw a}},async(a)=>{try{if(a!=="next")i=!0,o?.addEvent("cancelled");await zn(o,()=>r?.cancel())}catch(s){throw gn(o,s,t),s}finally{o?.end()}})}function GD(e,t={}){let n=t.eventIteratorKeepAliveEnabled??!0,r=t.eventIteratorKeepAliveInterval??5000,o=t.eventIteratorKeepAliveComment??"",i=t.eventIteratorInitialCommentEnabled??!0,a=t.eventIteratorInitialComment??"",s=!1,c,d;return new ReadableStream({start(m){if(d=ga("stream_event_iterator"),i)m.enqueue(To({comments:[a]}))},async pull(m){try{if(n)c=setInterval(()=>{m.enqueue(To({comments:[o]})),d?.addEvent("keepalive")},r);let y=await zn(d,()=>e.next());if(clearInterval(c),s)return;let _=xr(y.value);if(!y.done||y.value!==void 0||_!==void 0){let E=y.done?"done":"message";m.enqueue(To({..._,event:E,data:Vn(y.value)})),d?.addEvent(E)}if(y.done)m.close(),d?.end()}catch(y){if(clearInterval(c),s)return;if(y instanceof Xt)m.enqueue(To({...xr(y),event:"error",data:Vn(y.data)})),d?.addEvent("error"),m.close();else gn(d,y),m.error(y);d?.end()}},async cancel(){try{s=!0,clearInterval(c),d?.addEvent("cancelled"),await zn(d,()=>e.return?.())}catch(m){throw gn(d,m),m}finally{d?.end()}}}).pipeThrough(new TextEncoderStream)}function ZD(e,t={}){return Un({name:"parse_standard_body",signal:t.signal},async()=>{let n=e.headers.get("content-disposition");if(typeof n==="string"){let i=LS(n)??"blob",a=await e.blob();return new File([a],i,{type:a.type})}let r=e.headers.get("content-type");if(!r||r.startsWith("application/json")){let i=await e.text();return Eo(i)}if(r.startsWith("multipart/form-data"))return await e.formData();if(r.startsWith("application/x-www-form-urlencoded")){let i=await e.text();return new URLSearchParams(i)}if(r.startsWith("text/event-stream"))return WD(e.body,t);if(r.startsWith("text/plain"))return await e.text();let o=await e.blob();return new File([o],"blob",{type:o.type})})}function YD(e,t,n={}){if(e instanceof ReadableStream)return e;let r=t.get("content-disposition");if(t.delete("content-type"),t.delete("content-disposition"),e===void 0)return;if(e instanceof Blob)return t.set("content-type",e.type),t.set("content-length",e.size.toString()),t.set("content-disposition",r??MS(e instanceof File?e.name:"blob")),e;if(e instanceof FormData)return e;if(e instanceof URLSearchParams)return e;if(Jt(e))return t.set("content-type","text/event-stream"),GD(e,n);return t.set("content-type","application/json"),Vn(e)}function Au(e,t={}){return e.forEach((n,r)=>{if(Array.isArray(t[r]))t[r].push(n);else if(t[r]!==void 0)t[r]=[t[r],n];else t[r]=n}),t}function JD(e,t=new Headers){for(let[n,r]of Object.entries(e))if(Array.isArray(r))for(let o of r)t.append(n,o);else if(r!==void 0)t.append(n,r);return t}function FS(e,t={}){let n=JD(e.headers),r=YD(e.body,n,t);return new Request(e.url,{signal:e.signal,method:e.method,headers:n,body:r})}function US(e,t={}){return{body:yu(()=>ZD(e,t)),status:e.status,get headers(){let n=Au(e.headers);return Object.defineProperty(this,"headers",{value:n,writable:!0}),n},set headers(n){Object.defineProperty(this,"headers",{value:n,writable:!0})}}}class ba{plugins;constructor(e=[]){this.plugins=[...e].sort((t,n)=>(t.order??0)-(n.order??0))}init(e){for(let t of this.plugins)t.init?.(e)}}class jS{constructor(e,t,n={}){this.codec=e,this.sender=t,new ba(n.plugins).init(n),this.interceptors=Fn(n.interceptors),this.clientInterceptors=Fn(n.clientInterceptors)}interceptors;clientInterceptors;call(e,t,n){return Un({name:`${gu}.${e.join("/")}`,signal:n.signal},(r)=>{if(r?.setAttribute("rpc.system",gu),r?.setAttribute("rpc.method",e.join(".")),Jt(t))t=_u({name:"consume_event_iterator_input",signal:n.signal},t);return xo(this.interceptors,{...n,path:e,input:t},async({path:o,input:i,...a})=>{let s=So(),c,d=s?.trace.getActiveSpan()??r;if(d&&s)c=s?.trace.setSpan(s.context.active(),d);let u=await Un({name:"encode_request",context:c},()=>this.codec.encode(o,i,a)),m=await xo(this.clientInterceptors,{...a,input:i,path:o,request:u},({input:_,path:E,request:k,...V})=>Un({name:"send_request",signal:V.signal,context:c},()=>this.sender.call(k,V,E,_))),y=await Un({name:"decode_response",context:c},()=>this.codec.decode(m,a,o,i));if(Jt(y))return _u({name:"consume_event_iterator_output",signal:a.signal},y);return y})})}}var Ve={BIGINT:0,DATE:1,NAN:2,UNDEFINED:3,URL:4,REGEXP:5,SET:6,MAP:7},XD=new Set(Object.values(Ve)),QD=/^\/(.*)\/([a-z]*)$/;function Ro(e){return TypeError(`Invalid RPC serialized data: ${e}`)}function en(e,t,n){return Ro(`type ${e} (${t}) expects ${n}.`)}class VS{customSerializers;constructor(e={}){if(this.customSerializers=e.customJsonSerializers??[],this.customSerializers.length!==new Set(this.customSerializers.map((t)=>t.type)).size)throw Error("Custom serializer type must be unique.")}serialize(e,t=[],n=[],r=[],o=[]){for(let i of this.customSerializers)if(i.condition(e)){let a=this.serialize(i.serialize(e),t,n,r,o);return n.push([i.type,...t]),a}if(e instanceof Blob)return r.push(t),o.push(e),[e,n,r,o];if(typeof e==="bigint")return n.push([Ve.BIGINT,...t]),[e.toString(),n,r,o];if(e instanceof Date){if(n.push([Ve.DATE,...t]),Number.isNaN(e.getTime()))return[null,n,r,o];return[e.toISOString(),n,r,o]}if(Number.isNaN(e))return n.push([Ve.NAN,...t]),[null,n,r,o];if(e instanceof URL)return n.push([Ve.URL,...t]),[e.toString(),n,r,o];if(e instanceof RegExp)return n.push([Ve.REGEXP,...t]),[e.toString(),n,r,o];if(e instanceof Set){let i=this.serialize(Array.from(e),t,n,r,o);return n.push([Ve.SET,...t]),i}if(e instanceof Map){let i=this.serialize(Array.from(e.entries()),t,n,r,o);return n.push([Ve.MAP,...t]),i}if(Array.isArray(e))return[e.map((a,s)=>{if(a===void 0)return n.push([Ve.UNDEFINED,...t,s]),null;return this.serialize(a,[...t,s],n,r,o)[0]}),n,r,o];if(wo(e)){let i={};for(let a in e){if(a==="toJSON"&&typeof e[a]==="function")continue;i[a]=this.serialize(e[a],[...t,a],n,r,o)[0]}return[i,n,r,o]}return[e,n,r,o]}deserialize(e,t,n,r){let o={data:e},i={data:e};if(n&&r)n.forEach((a,s)=>{let c=r(s);if(!(c instanceof Blob))throw Ro(`blob ${s} is not a Blob.`);let d=i,u=o,m="data";a.forEach((y)=>{if(d=d[m],u=bu(u,m,d),m=y,!Object.hasOwn(u,m))throw Ro(`segment "${m}" does not exist.`)}),u[m]=c});for(let a of t){let s=a[0],c=this.customSerializers.find((_)=>_.type===s);if(c===void 0&&!XD.has(s))continue;let d=i,u=o,m="data";for(let _=1;_<a.length;_++)if(d=d[m],u=bu(u,m,d),m=a[_],!Object.hasOwn(u,m))throw Ro(`segment "${m}" does not exist.`);if(c!==void 0){u[m]=c.deserialize(u[m]);continue}let y=u[m];switch(s){case Ve.BIGINT:{if(typeof y!=="string")throw en(s,"bigint","a string");let _=ES(y,fu);if(_===void 0)throw en(s,"bigint",`a decimal integer string of at most ${fu} digits`);u[m]=_;break}case Ve.DATE:if(typeof y!=="string"&&y!==null)throw en(s,"date","a string or null");u[m]=new Date(y??Number.NaN);break;case Ve.NAN:if(y!==null)throw en(s,"nan","null");u[m]=Number.NaN;break;case Ve.UNDEFINED:if(y!==null)throw en(s,"undefined","null");u[m]=void 0;break;case Ve.URL:if(typeof y!=="string")throw en(s,"url","a string");u[m]=new URL(y);break;case Ve.REGEXP:{if(typeof y!=="string")throw en(s,"regexp","a string");let _=y.match(QD);if(_===null||!CS(_[2]))throw Ro(`type ${s} (regexp) expects a "/pattern/flags" string.`);u[m]=AS(_[1],_[2]);break}case Ve.SET:if(!Array.isArray(y))throw en(s,"set","an array");u[m]=new Set(y);break;case Ve.MAP:if(!Array.isArray(y))throw en(s,"map","an array");u[m]=new Map(y);break}}return o.data}}function eP(e){return`/${e.map(encodeURIComponent).join("/")}`}function tP(e){if(typeof e.forEach==="function")return Au(e);return e}function nP(e){return Object.entries(ya).find(([,t])=>t.status===e)?.[0]??"MALFORMED_ORPC_ERROR_RESPONSE"}class KS{constructor(e,t){this.serializer=e,this.baseUrl=t.url,this.maxUrlLength=t.maxUrlLength??2083,this.fallbackMethod=t.fallbackMethod??"POST",this.expectedMethod=t.method??this.fallbackMethod,this.headers=t.headers??{}}baseUrl;maxUrlLength;fallbackMethod;expectedMethod;headers;async encode(e,t,n){let r=tP(await Co(this.headers,n,e,t));if(n.lastEventId!==void 0)r=zS(r,{"last-event-id":n.lastEventId});let o=await Co(this.expectedMethod,n,e,t),i=await Co(this.baseUrl,n,e,t),a=new URL(i);a.pathname=`${a.pathname.replace(/\/$/,"")}${eP(e)}`;let s=this.serializer.serialize(t);if(o==="GET"&&!(s instanceof FormData)&&!Jt(s)){let c=await Co(this.maxUrlLength,n,e,t),d=new URL(a);if(d.searchParams.append("data",Vn(s)),d.toString().length<=c)return{body:void 0,method:o,headers:r,url:d,signal:n.signal}}return{url:a,method:o==="GET"?this.fallbackMethod:o,headers:r,body:s,signal:n.signal}}async decode(e){let t=!_a(e.status),n=await(async()=>{let r=!1;try{let o=await e.body();return r=!0,this.serializer.deserialize(o)}catch(o){if(!r)throw Error("Cannot parse response body, please check the response body and content-type.",{cause:o});throw Error("Invalid RPC response format.",{cause:o})}})();if(!t){if(Su(n))throw xu(n);throw new Kn(nP(e.status),{status:e.status,data:{...e,body:n}})}return n}}class qS{constructor(e){this.jsonSerializer=e}serialize(e){if(Jt(e))return Cu(e,{value:async(t)=>this.#e(t,!1),error:async(t)=>new Xt({data:this.#e(IS(t).toJSON(),!1),cause:t})});return this.#e(e,!0)}#e(e,t){let[n,r,o,i]=this.jsonSerializer.serialize(e),a=r.length===0?void 0:r;if(!t||i.length===0)return{json:n,meta:a};let s=new FormData;return s.set("data",Vn({json:n,meta:a,maps:o})),i.forEach((c,d)=>{s.set(d.toString(),c)}),s}deserialize(e){if(Jt(e))return Cu(e,{value:async(t)=>this.#t(t),error:async(t)=>{if(!(t instanceof Xt))return t;let n=this.#t(t.data);if(Su(n))return xu(n,{cause:t});return new Xt({data:n,cause:t})}});return this.#t(e)}#t(e){if(e===void 0)return;if(!(e instanceof FormData))return this.jsonSerializer.deserialize(e.json,e.meta??[]);let t=JSON.parse(e.get("data"));return this.jsonSerializer.deserialize(t.json,t.meta??[],t.maps,(n)=>e.get(n.toString()))}}class Tu extends jS{constructor(e,t){let n=new VS(t),r=new qS(n),o=new KS(r,t);super(o,e,t)}}class BS extends ba{initRuntimeAdapter(e){for(let t of this.plugins)t.initRuntimeAdapter?.(e)}}class HS{fetch;toFetchRequestOptions;adapterInterceptors;constructor(e){new BS(e.plugins).initRuntimeAdapter(e),this.fetch=e.fetch??globalThis.fetch.bind(globalThis),this.toFetchRequestOptions=e,this.adapterInterceptors=Fn(e.adapterInterceptors)}async call(e,t,n,r){let o=FS(e,this.toFetchRequestOptions),i=await xo(this.adapterInterceptors,{...t,request:o,path:n,input:r,init:{redirect:"manual"}},({request:s,path:c,input:d,init:u,...m})=>this.fetch(s,u,m,c,d));return US(i,{signal:o.signal})}}class Hn extends Tu{constructor(e){let t=new HS(e);super(t,e)}}import{chmodSync as Ru,mkdirSync as WS,readFileSync as rP,writeFileSync as Iu}from"node:fs";import{homedir as oP}from"node:os";import{join as GS}from"node:path";var Nu=GS(oP(),".niva"),Wn=GS(Nu,"config.json");function Io(){try{let e=JSON.parse(rP(Wn,"utf-8"));return se(e)?e:{}}catch{return{}}}function ZS(e,t){WS(Nu,{recursive:!0});let r={...Io(),[e]:t};Iu(Wn,`${JSON.stringify(r,null,2)}
|
|
100
|
-
`,{mode:384}),
|
|
101
|
-
`,{mode:384}),
|
|
102
|
-
`,{mode:384}),Ru(Wn,384)}import{createHash as aP,randomBytes as QS}from"node:crypto";import{createServer as sP}from"node:http";var cP=600000,lP=120,dP=5;class Ke extends Error{code;constructor(e,t){super(t);this.code=e}}function uP(e){let t=Ee(e),n=X(t?.access_token),r=wn(t?.expires_in);if(t==null||n==null||r==null)return null;let o=X(t.refresh_token),i=X(t.scope);return{access_token:n,expires_in:r,...o!=null?{refresh_token:o}:{},...i!=null?{scope:i}:{}}}function ex(e,t){let n=Ee(e),r=X(n?.error)??`http_${String(t)}`,o=X(n?.error_description)??r;return new Ke(r,o)}function pP(){return QS(32).toString("base64url")}function mP(e){return aP("sha256").update(e).digest("base64url")}function tx(e,t){if(e.NIVA_NO_BROWSER==="1")return!1;let n=e.CI;if(n==="true"||n==="1")return!1;if(t==="linux")return e.DISPLAY!=null||e.WAYLAND_DISPLAY!=null;return!0}function Du(e){let t;if(process.platform==="darwin")t=[["open",e]];else if(process.platform==="win32")t=[["cmd","/c","start","",e]];else t=[["xdg-open",e]];for(let n of t){let[r,...o]=n;if(r==null)continue;try{return Bun.spawn([r,...o],{stdout:"ignore",stderr:"ignore"}).exited.then((a)=>{if(a!==0)XS(e)}),!0}catch{continue}}return XS(e),!1}function XS(e){console.error(`Open this URL to continue: ${e}`)}async function Pu(e){let t=new URL("/.well-known/oauth-authorization-server",$t(e)),n=await fetch(t),r=await n.json().catch(()=>({})),o=Ee(r),i=X(o?.issuer),a=X(o?.authorization_endpoint),s=X(o?.token_endpoint);if(!n.ok||o==null||i==null||a==null||s==null)throw new Ke("discovery_failed",`Could not read OAuth metadata from ${e}`);let c=X(o.device_authorization_endpoint);return{issuer:i,authorization_endpoint:a,token_endpoint:s,...c!=null?{device_authorization_endpoint:c}:{}}}async function $u(e,t){let n=await fetch(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=await n.json().catch(()=>({}));if(!n.ok)throw ex(r,n.status);let o=uP(r);if(o==null)throw new Ke("invalid_response","The token endpoint answered an unexpected body");return o}function fP(e){return(t,n)=>{let r=new URL(t.url??"/","http://127.0.0.1");if(r.pathname!=="/callback"){n.writeHead(404).end();return}n.writeHead(200,{"content-type":"text/html; charset=utf-8"}),n.end("<html><body><p>Login complete. You can close this tab and go back to the terminal.</p></body></html>");let o=r.searchParams.get("code"),i=r.searchParams.get("state"),a=r.searchParams.get("iss")??void 0,s=r.searchParams.get("error");if(s!=null)e({error:s});else if(o!=null&&i!=null)e({code:o,state:i,iss:a});else e({error:"invalid_request"})}}function gP(e,t){return new Promise((n,r)=>{let o=setTimeout(()=>{e.current=null,t(),r(new Ke("timeout","Timed out waiting for the browser callback"))},cP);e.current=(i)=>{if(clearTimeout(o),t(),"error"in i)r(new Ke(i.error,`Authorization failed: ${i.error}`));else n(i)}})}function hP(){return new Promise((e,t)=>{let n={current:null},r=sP(fP((i)=>n.current?.(i))),o=async()=>gP(n,()=>r.close());r.on("error",t),r.listen(0,"127.0.0.1",()=>{let i=r.address();if(i==null||typeof i==="string"){t(Error("Could not bind the loopback listener"));return}e({redirectUri:`http://127.0.0.1:${i.port}/callback`,waitForCode:o,close:()=>r.close()})})})}async function nx(e,t){let n=await hP(),r=pP(),o=QS(16).toString("base64url"),i=new URL(e.authorization_endpoint);i.searchParams.set("response_type","code"),i.searchParams.set("client_id",t.clientId),i.searchParams.set("redirect_uri",n.redirectUri),i.searchParams.set("scope",t.scopes.join(" ")),i.searchParams.set("state",o),i.searchParams.set("code_challenge",mP(r)),i.searchParams.set("code_challenge_method","S256"),i.searchParams.set("resource",t.resource);try{Du(i.href);let a=await n.waitForCode();if(a.state!==o)throw new Ke("state_mismatch","The state returned by the server does not match");if(a.iss!=null&&a.iss!==e.issuer)throw new Ke("issuer_mismatch","The issuer returned by the server does not match");return await $u(e.token_endpoint,{grant_type:"authorization_code",code:a.code,redirect_uri:n.redirectUri,client_id:t.clientId,code_verifier:r})}finally{n.close()}}function yP(e){let t=Ee(e);if(t==null)return null;let n=["device_code","user_code","verification_uri","verification_uri_complete"].map((o)=>X(t[o])),r=["expires_in","interval"].map((o)=>wn(t[o]));if(n.some((o)=>o==null)||r.some((o)=>o==null))return null;return{device_code:n[0],user_code:n[1],verification_uri:n[2],verification_uri_complete:n[3],expires_in:r[0],interval:r[1]}}async function rx(e,t){let n=e.device_authorization_endpoint;if(n==null)throw new Ke("unsupported_grant_type","This server does not support the device flow");let r=await fetch(n,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:t.clientId,scope:t.scopes.join(" "),resource:t.resource}).toString()}),o=await r.json().catch(()=>({})),i=r.ok?yP(o):null;if(i==null)throw r.ok?new Ke("invalid_response","The device authorization endpoint answered an unexpected body"):ex(o,r.status);return i}async function ox(e,t,n){let r=t.interval*1000,o=Date.now()+t.expires_in*1000;while(Date.now()<o){await Bun.sleep(r);try{return await $u(e,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:t.device_code,client_id:n})}catch(i){if(i instanceof Ke){if(i.code==="authorization_pending")continue;if(i.code==="slow_down"){r+=dP*1000;continue}}throw i}}throw new Ke("expired_token","The device code expired before authorization completed")}function va(e,t=Math.floor(Date.now()/1000)){return e.expires_at-t<lP}async function Sa(e,t){let n=await Pu(e),r=await $u(n.token_endpoint,{grant_type:"refresh_token",refresh_token:t.refresh_token,client_id:"niva-cli"});if(r.refresh_token==null)throw new Ke("invalid_grant","The server did not return a refresh token");return{access_token:r.access_token,refresh_token:r.refresh_token,expires_at:Math.floor(Date.now()/1000)+r.expires_in,org_id:t.org_id,scopes:r.scope!=null?r.scope.split(" ").filter((o)=>o!==""):t.scopes}}function Mu(e){try{let{hostname:t}=new URL(e);return t.endsWith(".orb.local")||process.env.NIVA_INSECURE==="true"}catch{return!1}}var ix;function ax(){return ix==null?{}:{[vo]:ix}}class sx extends Error{constructor(){super("Your session has expired. Run 'niva login' to authenticate again.")}}function _P(e){let t=e.fetchImpl??fetch,n=async()=>{try{return await e.refresh()}catch(r){if(r instanceof Ke)throw new sx;throw r}};return async(r)=>{let o=e.getSession();if(va(o))o=await n();let i=new Request(r);i.headers.set("authorization",`Bearer ${o.access_token}`);let a=await t(i);if(a.status===401){o=await n();let s=new Request(r);s.headers.set("authorization",`Bearer ${o.access_token}`),a=await t(s)}return a}}function Lu(e,t,n){if(Mu(e))process.env.NODE_TLS_REJECT_UNAUTHORIZED="0";if(t.kind!=="oauth"){let i=new Hn({url:new URL("/api/rpc",e).href,headers:()=>({...ax(),...t.kind==="api-key"?{"X-API-Key":t.apiKey}:{}})});return Bn(i)}let r=t.session,o=new Hn({url:new URL("/api/rpc",e).href,headers:ax,fetch:_P({getSession:()=>r,refresh:async()=>(r=await Sa(n,r),wr(n,r),r)})});return Bn(o)}var zu="niva-cli",bP=["*:read","*:write","offline_access"],vP=["*:read","offline_access"];function cx(e,t){return{access_token:e.access_token,refresh_token:e.refresh_token??"",expires_at:Math.floor(Date.now()/1000)+e.expires_in,org_id:t,scopes:e.scope!=null?e.scope.split(" ").filter((n)=>n!==""):[]}}async function SP(e,t){return(await Lu(e,{kind:"oauth",session:cx(t,"")},e).oauth.whoami()).organization?.id??""}function lx(e,t,n){e.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(r)=>{let o=Er(t().url);if(!o.startsWith("https://"))Et("Server URL is not https: tokens travel unencrypted on this network.");let i=r.readOnly===!0?vP:bP,a=`${o}/api`,s=await Pu(o),c={scopes:i,resource:a,clientId:zu},d,u=tx(process.env,process.platform);if(r.device===!0||!u){let y=await rx(s,c);if(D(`Open ${y.verification_uri} and enter the code: ${y.user_code}`),u)Du(y.verification_uri_complete);d=await ox(s.token_endpoint,y,zu)}else d=await nx(s,c);let m=await SP(o,d);wr(o,cx(d,m)),O(`Logged in to ${o}`)}),e.command("logout").description("Revoke the saved session and remove it from the config file").action(async()=>{let r=Er(t().url),o=YS()[r];if(o==null){D(`No saved session for ${r}`);return}try{await fetch(new URL("/oauth/revoke",r),{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:o.refresh_token,client_id:zu}).toString()})}catch{Et("Could not reach the server to revoke the token; clearing the local session anyway.")}JS(r),O(`Logged out of ${r}`)}),e.command("whoami").description("Show the authenticated user, organization, scopes and token expiry").action(async()=>{let r=Er(t().url),o=n();if(o.kind==="none"){C(`No credential configured for ${r}. Run 'niva login' first.`),process.exitCode=1;return}let a=await Lu(r,o,r).oauth.whoami();v({url:r,user:a.user.email,organization:a.organization?.name,scopes:a.scopes,credential:a.credential,...o.kind==="oauth"?{expires_at:new Date(o.session.expires_at*1000).toISOString()}:{}})})}var Fu=["blocker","degraded","minor"],Uu=["always","sometimes","once"],xP=Fu,EP=Uu;function dx(e,t){return[...t,e]}function wP(e){return xP.includes(e)}function CP(e){return EP.includes(e)}function ux(e,t){e.command("bug-report").description("Report a problem to the NIVA support team").option("--title <title>","Short summary (3-120 characters)").option("--description <description>","What happened (10-4000 characters)").option("--severity <level>",`How bad it is: ${Fu.join(", ")}`).option("--expected <expected>","What you expected to happen").option("--step <step>","A reproduction step (repeatable)",dx,[]).option("--frequency <frequency>",`How often it happens: ${Uu.join(", ")}`).option("--resource <typeid>","Related resource TypeID (repeatable)",dx,[]).action(async(n)=>{let{title:r,description:o,severity:i,expected:a,frequency:s,step:c,resource:d}=n,u=[];if(r===void 0||r==="")u.push("--title");if(o===void 0||o==="")u.push("--description");if(i===void 0||i==="")u.push("--severity");if(u.length>0)C(`Missing required option${u.length>1?"s":""}: ${u.join(", ")}`),process.exit(A.USAGE_ERROR);if(r===void 0||o===void 0||i===void 0)process.exit(A.USAGE_ERROR);if(!wP(i))C(`Invalid --severity '${i}'. Expected one of: ${Fu.join(", ")}`),process.exit(A.USAGE_ERROR);if(s!==void 0&&!CP(s))C(`Invalid --frequency '${s}'. Expected one of: ${Uu.join(", ")}`),process.exit(A.USAGE_ERROR);let{format:m}=S(e.opts()),y=c.length>0?c.map((E,k)=>`${k+1}. ${E}`).join(`
|
|
103
|
-
`):void 0,_=await b(t().bugReports.create({title:r,description:o,severity:i,expected:a,steps:y,frequency:s,resources:d.length>0?d:void 0,source:"cli"}));if(m==="json"){v(_);return}O(`Report sent (${_.reference})`)})}import{basename as TP}from"node:path";var pe=on(jt(),1);var AP=/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i,px=4;async function xa(e,t){if(AP.test(t))return t;if(t.length<px)C(`UUID prefix too short — provide at least ${px} characters.`),process.exit(A.USAGE_ERROR);let n=await b(e.dashboard.activeCalls()),r=t.toLowerCase(),o=n.filter((i)=>i.uuid.toLowerCase().startsWith(r));if(o.length===0)C(`No active call matching "${t}".`),process.exit(A.NOT_FOUND);if(o.length>1){C(`Ambiguous UUID prefix "${t}" — matches ${o.length} calls. Be more specific.`);for(let i of o)D(` ${i.uuid} ${i.callerId}`);process.exit(A.USAGE_ERROR)}return o[0].uuid}var RP={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 IP(e){let t=Math.max(0,Math.floor(e)),n=Math.floor(t/60),r=t%60;return`${String(n).padStart(2,"0")}:${String(r).padStart(2,"0")}`}function NP(e){if(e==null)return"—";return`${IP(e.at_seconds)}${e.late?" (late)":""}`}function gx(e,t,n){let r=e.command("calls").description("Manage calls");r.command("list").description("List active calls").action(async()=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().dashboard.activeCalls());if(o==="json"){let s=i?a.map((c)=>N(c,i)):a;v(s);return}if(a.length===0){D("No active calls.");return}L(["UUID","Caller","Plan","Duration"],a.map((s)=>({UUID:s.uuid,Caller:s.callerId,Plan:s.planName??"—",Duration:s.startedAt?`${Math.round((Date.now()-new Date(s.startedAt).getTime())/1000)}s`:"—"})))}),r.command("show <call_record_id>").description("Show call details from CDR (rich detail view)").action(async(o)=>{let{format:i,fields:a}=S(e.opts()),s=await b(t().callRecords.getById({call_record_id:x("call_records",o)}));if(i==="json"){let c=a&&s!=null?N(s,a):s;v(c);return}if(s==null){D("Call record not found.");return}J([{title:"Call Record",rows:kP(s)}])}),r.command("hangup <call>").description("Hang up an active call by TypeID (call_...), full channel UUID, or UUID prefix").action(async(o)=>{let{format:i}=S(e.opts()),a=t(),s=o,c;if(o.startsWith("call_"))c=await b(a.calls.hangupCall({call_id:x("call_records",o)}));else s=await xa(a,o),c=await b(a.calls.hangupActiveCall({uuid:s}));if(i==="json"){v(c);return}O(`Call ${s} terminated.`)}),r.command("signals <call_record_id>").description("Show the signal results of a recorded call").action(async(o)=>{let{format:i,fields:a}=S(e.opts()),s=await b(t().signals.callSignals({call_id:x("call_records",o)}));if(i==="json"){let c=a?s.map((d)=>N(d,a)):s;v(c);return}if(s.length===0){D("No signal results for this call.");return}L(["Signal","Value","Confidence","Triggered at","Severity"],s.map((c)=>({Signal:c.signal.name,Value:c.value_label??"—",Confidence:c.confidence==null?"—":`${Math.round(c.confidence*100)}%`,"Triggered at":NP(c.trigger),Severity:c.definition.alert?.severity??"—"})))}),r.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(o)=>{let{format:i,fields:a}=S(e.opts()),s=await b(t().callRecords.list({page:Number(o.page),limit:Number(o.limit),search:o.caller}));if(i==="json"){let c=a?s.items.map((d)=>N(d,a)):s;v(c);return}L(["ID","Caller","Callee","Duration","Disposition","Date"],s.items.map((c)=>({ID:c.id,Caller:c.caller_id??"—",Callee:c.callee_id??"—",Duration:ke(c.duration_ms),Disposition:c.hangup_disposition??"—",Date:new Date(c.started_at).toLocaleString()}))),te(s)}),r.command("follow <uuid>").description("Follow live transcription of an active call").action(async(o)=>{let{format:i}=S(e.opts()),a=t(),s=await xa(a,o),c=new AbortController;process.on("SIGINT",()=>{c.abort()});let d=!1,u=!1;function m(_){y();let E=hx(_);process.stdout.write(pe.default.dim(E)),u=!0}function y(){if(!u)return;process.stdout.clearLine(0),process.stdout.cursorTo(0),u=!1}await new Promise((_,E)=>{Qt(a.dashboard.watchLiveTranscription({uuid:s},{signal:c.signal}),{onEvent:(k)=>{if(d=!0,i==="json"){v(k);return}switch(k.type){case"starting":D("Connecting...");break;case"started":D("Transcription started.");break;case"caught_up":break;case"unavailable":D(RP[k.reason]),_();break;case"ended":y(),D("Transcription ended."),_();break;case"error":console.error(pe.default.red(`Error: ${k.message}`));break;case"history":for(let V of k.segments)mx(V);for(let V of k.signals??[])fx(V);break;case"signal_value":case"signal_triggered":fx(k);break;case"segment":if(k.segment.isFinal)y(),mx(k.segment);else m(k.segment);break}},onError:(k)=>{if(k instanceof DOMException&&k.name==="AbortError"){y(),_();return}E(k)},onSuccess:()=>{if(!d)D("Live transcription not available for this call.");_()}})}).catch((_)=>{y(),In(_)})}),r.command("transfer <uuid> <destination>").description("Transfer an active call").action(()=>Vt()),r.command("spy <uuid>").description("Spy on an active call").action(()=>Vt()),r.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(o)=>{let{format:i,fields:a}=S(e.opts()),s=await b(t().callRecords.list({page:Number(o.page),limit:Number(o.limit),date_from:o.from,date_to:o.to,visual_plan_id:x("visual_plans",o.plan),channel_id:x("channels",o.phone),status:o.status,caller_search:o.caller,min_duration:o.minDuration!=null?Number(o.minDuration):void 0,max_duration:o.maxDuration!=null?Number(o.maxDuration):void 0,has_recording:o.hasRecording,has_transcription:o.hasTranscription}));if(i==="json"){if(a)v(s.items.map((c)=>N(c,a)));else v(s);return}if(s.items.length===0){D("No call records found.");return}L(["ID","Caller","Direction","Duration","Status","Sentiment","Plan","Date"],s.items.map((c)=>{let d=c.sentiment_score!=null?Number(c.sentiment_score):null;return{ID:c.id,Caller:c.caller_id??"—",Direction:c.direction??"—",Duration:ke(c.duration_ms),Status:ns(c.hangup_disposition),Sentiment:c.sentiment_label!=null?rs(c.sentiment_label,d):"—",Plan:c.visual_plan_name??"—",Date:Me(c.started_at)}})),te(s)}),r.command("trace <call_record_id>").description("Show node-by-node execution trace for a call").action(async(o)=>{let{format:i,fields:a}=S(e.opts()),s=await b(t().callRecords.getTrace({call_record_id:x("call_records",o)}));if(i==="json"){let _=a&&s!=null?N(s,a):s;v(_);return}if(s==null){D("Call trace not found.");return}let c=s.callRecord;if(console.log(`${pe.default.bold("Call Trace")} — ${o} (${ke(c.duration_ms)}, ${c.hangup_disposition??"unknown"})`),c.visual_plan_name!=null)console.log(`Plan: ${c.visual_plan_name}`);console.log("");let d=s.events;if(d.length===0){D(" No events recorded (0 nodes visited).");return}let u=d.map((_,E)=>{let k=_.duration_ms!=null?`${(_.duration_ms/1000).toFixed(1)}s`:"—",V=`${pe.default.cyan(_.node_type)}`;if(_.node_label!=null){let oe=pe.default.bold(`"${_.node_label}"`);V+=` ${oe}`}if(V+=pe.default.dim(` (${k})`),_.digit!=null)V+=` → digit: ${pe.default.yellow(_.digit)}`;let G=[];if(_.handle_used!=null)G.push(pe.default.dim(`└─→ ${_.handle_used}`));if(se(_.data)){let oe=Object.entries(_.data).filter(([,ct])=>ct!=null&&typeof ct!=="object").map(([ct,nt])=>`${ct}: ${String(nt)}`);if(oe.length>0)G.push(pe.default.dim(`└─ ${oe.join(", ")}`))}return{label:V,children:G.length>0?G:void 0}});os(u),console.log("");let m=d.at(-1),y=m.node_label??m.node_type;D(` ${d.length} nodes visited · Last: ${m.node_type} "${y}" · Hangup: ${c.hangup_cause??"—"}`)}),r.command("transcript <call_record_id>").description("Show call transcription with speech analytics").action(async(o)=>{let{format:i,fields:a}=S(e.opts()),s=await b(t().ai.getTranscription({call_record_id:x("call_records",o)}));if(i==="json"){let u=a&&s!=null?N(s,a):s;v(u);return}console.log(`${pe.default.bold("Transcript")} — ${o}`),console.log("");let c=PP(s?.segments);if(c.length===0||s?.status==="disabled")D(" No transcript available.");else wm(c);let d=s!=null?$P(s):[];if(d.length>0)console.log(""),J([{title:"Speech Analytics",rows:d}])}),r.command("purge-voice <call_record_id>").description("Permanently erase a call's voice content (recording, transcription, embeddings)").action(async(o)=>{let{format:i}=S(e.opts()),a=e.opts().yes===!0;if(i!=="json")console.log(`${pe.default.bold("Erase voice content")} — ${o}`),D(" Deletes: recording file, transcription and its semantic-search embeddings."),D(" Keeps: the call record (CDR), its event timeline and existing analyses."),D(" This is irreversible."),console.log("");await Ce("Erase the voice content of this call?",{yes:a});let s=await b(t().callRecords.purgeVoiceContent({call_record_id:x("call_records",o)}));if(i==="json"){v(s);return}O("Voice content erased"),J([{title:"Deleted",rows:[{label:"Recording",value:String(s.deleted.recording)},{label:"Transcriptions",value:String(s.deleted.transcriptions)},{label:"Embeddings",value:String(s.deleted.embeddings)},{label:"Analyses detached",value:String(s.analyses_detached)}]}])}),r.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(o,i)=>{let{format:a,fields:s}=S(e.opts()),c=await b(t().ai.searchTranscriptions({query:o,limit:Number(i.limit),threshold:Number(i.threshold),date_from:i.from,date_to:i.to,visual_plan_id:x("visual_plans",i.plan)}));if(a==="json"){let u=s?c.map((m)=>N(m,s)):c;v(u);return}let d=c;if(console.log(`${pe.default.bold("Semantic Search")}: "${o}"`),console.log(`${d.length} result${d.length!==1?"s":""} (threshold: ${i.threshold})`),d.length===0){D(`
|
|
104
|
-
No results found.`);return}console.log("");for(let u of d){let m=`${Math.round(u.similarity*100)}%`,y=u.call_record_id,_=Me(u.started_at),E=
|
|
105
|
-
│ `)});let o=Ye(e.topics);if(o.length>0)t.push({label:"Topics",value:o.map((i)=>DP(i)).join(" · ")});return t}function hx(e){let t=Math.floor(e.start/60),n=Math.floor(e.start%60),r=`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`,o=e.channel===0?pe.default.blue("Caller"):pe.default.green("System");return`${pe.default.dim(`[${r}]`)} ${o} ${pe.default.dim(">")} ${e.text}`}function mx(e){console.log(hx(e))}function fx(e){let t=`${Math.round(e.confidence*100)}%`;if(e.type==="signal_value"){D(` ↳ ${e.signal.name}: ${e.value_label} (${t})`);return}let n=e.node!=null?` · ${e.node.label}`:"",r=e.late?" (late)":"";console.log(pe.default.bold(pe.default.yellow(` \uD83D\uDD14 ${e.signal.name}: ${e.value_label} (${t})${n}${r}`)))}function MP(e){if(e.status==="queued")return"queued";let{processed_records:t,total_records:n}=e,r=n!=null&&n>0?`${t}/${n} (${Math.floor(t*100/n)}%)`:`${t} records`;return e.status==="paused"?`${r} - paused, resumes on its own`:r}async function LP(e,t){return await new Promise((n,r)=>{Qt(e.callRecords.exportJobProgress({export_job_id:t}),{onEvent:(o)=>yt(MP(o)),onError:r,onSuccess:()=>n()})}).catch((n)=>{In(n)}),b(e.callRecords.exportJobGet({export_job_id:t}))}async function zP(e,t){if(t.separator!==","&&t.separator!==";")C("--separator must be ',' or ';'."),process.exit(A.USAGE_ERROR);if(t.job!=null)return b(e.callRecords.exportJobGet({export_job_id:x("export_jobs",t.job)}));let{from:n,to:r}=t;if(n==null||r==null)C("--from and --to are required unless --job is given."),process.exit(A.USAGE_ERROR);return b(e.callRecords.exportJobCreate({date_from:n,date_to:r,separator:t.separator,include_events:t.includeEvents===!0,...t.columns!=null?{columns:t.columns.split(",").map((o)=>o.trim())}:{}}))}async function FP(e,t,n){if(n.out!=null||n.force===!0)return;if(!await Bun.file(e).exists())return;if(C(`${e} already exists - pass --out <path> to write elsewhere, or --force to overwrite it.`),n.job==null)yt(`The export keeps running on the server: download it later with --job ${t.id}.`);process.exit(A.CONFLICT)}function UP(e){if(e.status==="failed")return`Export ${e.id} failed: ${e.error_code??"unknown error"}.`;if(e.status==="cancelled")return`Export ${e.id} was cancelled.`;if(e.status==="expired")return`Export ${e.id} expired and its file was removed.`;return`Export ${e.id} stopped while ${e.status}. Wait for it again with --job ${e.id}.`}async function jP(e,t,n){let r="";for(let o=0;o<2;o+=1){let{url:i}=await b(e.callRecords.exportDownloadTicket({export_job_id:t}));try{let a=await fetch(new URL(i,n));if(a.ok)return a;r=`HTTP ${a.status}`}catch(a){r=a instanceof Error?a.message:String(a)}}return C(`Download failed (${r}). Run the command again with --job ${t} to retry.`),process.exit(A.GENERAL_ERROR)}import{readFile as VP}from"node:fs/promises";async function yx(e){let t=e==="-"?await Fe():await VP(e,"utf-8"),n=JSON.parse(t);if(!se(n))C(`Invalid campaign file "${e}": expected a JSON object`),process.exit(A.USAGE_ERROR);return n}function KP(e){return{...e.name!=null&&{name:e.name},...e.description!=null&&{description:e.description},...e.callerId!=null&&{caller_id:e.callerId},...e.trunkOverride!=null&&{trunk_override:e.trunkOverride},...e.maxConcurrent!=null&&{max_concurrent_calls:Number(e.maxConcurrent)},...e.ringTimeout!=null&&{ring_timeout_s:Number(e.ringTimeout)},...e.maxDuration!=null&&{max_call_duration_s:Number(e.maxDuration)},...e.priority!=null&&{priority:Number(e.priority)}}}var _x=["interval_min","max_attempts"];function Ar(e){C(`Invalid --retry-rules: ${e}`),process.exit(A.USAGE_ERROR)}function qP(e,t){if(!se(t))return Ar(`"${e}" must be an object`);let n={};for(let[r,o]of Object.entries(t)){let i=_x.find((a)=>a===r);if(i===void 0)return Ar(`unknown field "${r}" in "${e}" (allowed: ${_x.join(", ")})`);if(typeof o!=="number")return Ar(`"${e}.${r}" must be a number`);n[i]=o}return n}function BP(e){let t;try{t=JSON.parse(e)}catch{return Ar("not valid JSON")}if(t===null)return null;if(!se(t))return Ar("expected a JSON object or null");let n={};for(let[r,o]of Object.entries(t)){let i=Zc.find((a)=>a===r);if(i===void 0)return Ar(`unknown class "${r}" (allowed: ${Zc.join(", ")})`);n[i]=qP(i,o)}return n}function HP(e){let t=e.retryOn!=null?new Set(e.retryOn.split(",").map((n)=>n.trim())):void 0;return{...e.retryAttempts!=null&&{retry_max_attempts:Number(e.retryAttempts)},...e.retryInterval!=null&&{retry_interval_min:Number(e.retryInterval)},...e.retryRules!=null&&{retry_rules:BP(e.retryRules)},...e.windowStart!=null&&{call_window_start:e.windowStart},...e.windowEnd!=null&&{call_window_end:e.windowEnd},...e.windowDays!=null&&{call_window_days:e.windowDays},...e.autoStartAt!=null&&{auto_start_at:e.autoStartAt},...e.autoStopAt!=null&&{auto_stop_at:e.autoStopAt},...t!=null&&{retry_on_busy:t.has("busy"),retry_on_no_answer:t.has("no_answer"),retry_on_failed:t.has("failed")},...e.recurring===!0&&{recurring:!0}}}function bx(e){return{...KP(e),...HP(e)}}function Cr(e){if(e==null)return"inherit (org default)";if(typeof e==="boolean")return e?"yes":"no";return String(e)}function vx(e){return e.option("--description <text>","Campaign description").option("--caller-id <id>","Caller ID for outbound calls").option("--trunk-override <trunk>","Trunk override (default: org trunk)").option("--max-concurrent <n>","Max concurrent calls").option("--ring-timeout <s>","Ring timeout in seconds before no-answer").option("--max-duration <s>","Max call duration in seconds").option("--retry-attempts <n>","Max retry attempts").option("--retry-interval <min>","Retry interval in minutes").option("--retry-on <list>","Retry on outcomes (comma list: busy,no_answer,failed)").option("--retry-rules <json>",`Per-outcome retry overrides, e.g. '{"busy":{"interval_min":5,"max_attempts":3}}' (null clears)`).option("--window-start <HH:MM>","Call window start time").option("--window-end <HH:MM>","Call window end time").option("--window-days <list>","Call window days (comma ints, 0=Sun..6=Sat)").option("--priority <n>","Campaign priority (0-100)").option("--recurring","Enable recurring dialing").option("--auto-start-at <iso>","Auto-start timestamp (ISO 8601)").option("--auto-stop-at <iso>","Auto-stop timestamp (ISO 8601)").option("--file <path>","JSON file with campaign fields (- for stdin)")}function Sx(e,t){let n=e.command("campaigns").description("Manage dialer campaigns");n.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(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().dialerCampaigns.list({page:Number(r.page),limit:Number(r.limit),search:r.search,status:ce(r.status)}));if(o==="json"){let s=i?a.items.map((c)=>N(c,i)):a;v(s);return}L(["ID","Name","Status","Contacts","Answered","Created"],a.items.map((s)=>({ID:s.id,Name:s.name,Status:s.status,Contacts:s.total_contacts,Answered:s.answered_count,Created:Me(s.created_at)}))),te(a)}),n.command("show <campaign_id>").description("Show campaign details").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().dialerCampaigns.get({campaign_id:x("dialer_campaigns",r)}));if(a==null){if(o==="json")v(null),process.exit(A.NOT_FOUND);C("Campaign not found"),process.exit(A.NOT_FOUND)}if(o==="json"){let s=i?N(a,i):a;v(s);return}J([{title:"Campaign",rows:[{label:"ID",value:a.id},{label:"Name",value:a.name},{label:"Description",value:a.description},{label:"Status",value:a.status},{label:"Plan",value:a.plan_id},{label:"Channel",value:a.channel_type},{label:"Priority",value:a.priority},{label:"Created",value:new Date(a.created_at).toLocaleString()},{label:"Updated",value:new Date(a.updated_at).toLocaleString()}]},{title:"Dialing",rows:[{label:"Caller ID",value:a.caller_id},{label:"Trunk",value:a.trunk_override},{label:"Max Concurrent",value:a.max_concurrent_calls},{label:"Ring Timeout",value:`${a.ring_timeout_s}s`},{label:"Max Duration",value:`${a.max_call_duration_s}s`}]},{title:"Retry",rows:[{label:"Max Attempts",value:a.retry_max_attempts},{label:"Interval",value:`${a.retry_interval_min}min`},{label:"On Busy",value:a.retry_on_busy?"yes":"no"},{label:"On No Answer",value:a.retry_on_no_answer?"yes":"no"},{label:"On Failed",value:a.retry_on_failed?"yes":"no"},...a.retry_rules!=null?[{label:"Retry Rules",value:JSON.stringify(a.retry_rules)}]:[]]},{title:"Answering machine",rows:[{label:"Detection",value:a.amd_enabled?"on":"off"},{label:"Retry On Machine",value:a.retry_on_machine?"yes":"no"},{label:"Block After All",value:Cr(a.amd_block_after_all_machine)},{label:"Block Min Attempts",value:Cr(a.amd_block_min_attempts)},{label:"On Voicemail",value:Cr(a.amd_action_voicemail)},{label:"On Announcement",value:Cr(a.amd_action_announcement)},{label:"On IVR",value:Cr(a.amd_action_ivr)},{label:"On Screening",value:Cr(a.amd_action_screening)}]},{title:"Window & schedule",rows:[{label:"Window Start",value:a.call_window_start},{label:"Window End",value:a.call_window_end},{label:"Window Days",value:a.call_window_days},{label:"Recurring",value:a.recurring?"yes":"no"},{label:"Recurrence",value:a.recurrence_mode},{label:"Auto Start",value:a.auto_start_at?new Date(a.auto_start_at).toLocaleString():null},{label:"Auto Stop",value:a.auto_stop_at?new Date(a.auto_stop_at).toLocaleString():null}]}])}),n.command("stats <campaign_id>").description("Show campaign statistics").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().dialerCampaigns.stats({campaign_id:x("dialer_campaigns",r)}));if(o==="json"){let d=i?N(a,i):a;v(d);return}let s=a.capacity_context;J([{title:"Stats",rows:[{label:"Status",value:a.status},{label:"Total",value:a.total_contacts},{label:"Pending",value:a.pending_count},{label:"Calling",value:a.calling_count},{label:"Answered",value:a.answered_count},{label:"Machine",value:a.machine_count},{label:"Busy",value:a.busy_count},{label:"No Answer",value:a.no_answer_count},{label:"Failed",value:a.failed_count},{label:"DNC Skipped",value:a.dnc_skipped_count},{label:"Cancelled",value:a.cancelled_count}]},{title:"Capacity",rows:[{label:"Waiting",value:a.waiting_capacity?"yes":"no"},{label:"Used",value:s!=null?s.used:null},{label:"Capacity",value:s!=null?s.capacity:null},{label:"Reserve",value:s!=null?s.reserve:null},{label:"Module Disabled",value:a.module_disabled?"yes":"no"}]}]);let c=Number(a.total_contacts);if(c>0)console.log(""),wt("Answered",Number(a.answered_count),c),wt("Busy",Number(a.busy_count),c),wt("No Answer",Number(a.no_answer_count),c),wt("Failed",Number(a.failed_count),c)}),n.command("summary").description("Show running-campaign summary").action(async()=>{let{format:r,fields:o}=S(e.opts()),i=await b(t().dialerCampaigns.summary());if(r==="json"){let a=o?N(i,o):i;v(a);return}J([{title:"Summary",rows:[{label:"Running",value:i.running},{label:"Calling",value:i.calling},{label:"Campaign",value:i.campaign!=null?`${i.campaign.name} (${i.campaign.id})`:null}]}])}),vx(n.command("create <name>").description("Create a dialer campaign").requiredOption("--plan <plan_id>","Visual plan ID to dial")).action(async(r,o)=>{let{format:i}=S(e.opts()),a=o.file!=null?await yx(o.file):{},s=bx(o),c=await b(t().dialerCampaigns.create({...a,...s,name:r,plan_id:x("visual_plans",o.plan)}));if(i==="json"){v(c);return}O(`Campaign created: ${c.id} — ${c.name}`)}),vx(n.command("edit <campaign_id>").description("Update a dialer campaign").option("--name <name>","Campaign name")).action(async(r,o)=>{let{format:i}=S(e.opts()),a=o.file!=null?await yx(o.file):{},s=bx(o),c=await b(t().dialerCampaigns.update({campaign_id:x("dialer_campaigns",r),...a,...s}));if(i==="json"){v(c);return}O(`Campaign updated: ${c.name}`)}),n.command("delete <campaign_id>").description("Delete a dialer campaign").action(async(r)=>{let{format:o}=S(e.opts());if(await b(t().dialerCampaigns.delete({campaign_id:x("dialer_campaigns",r)})),o==="json"){v({success:!0});return}O("Campaign deleted")});for(let r of["start","pause","resume","stop"])n.command(`${r} <campaign_id>`).description(`${r[0].toUpperCase()}${r.slice(1)} a campaign`).action(async(o)=>{let{format:i}=S(e.opts()),a=await b(t().dialerCampaigns.control({campaign_id:x("dialer_campaigns",o),action:r}));if(i==="json"){v(a);return}O(`Campaign "${a.name}" → ${a.status}`)});n.command("watch <campaign_id>").description("Watch live campaign stats (streams until Ctrl-C)").action(async(r)=>{let{format:o}=S(e.opts()),i=t(),a=new AbortController;process.on("SIGINT",()=>{a.abort()}),await new Promise((s,c)=>{Qt(i.dialerCampaigns.liveStats({campaign_id:x("dialer_campaigns",r)},{signal:a.signal}),{onEvent:(d)=>{if(o==="json"){console.log(JSON.stringify(d));return}let u=new Date().toLocaleTimeString(),m=d.counters,y=d.waiting_capacity?"yes":"no";console.log(`${u} status=${d.status} calling=${d.calling} pending_retry=${d.pending_retry} answered=${m.answered_count} busy=${m.busy_count} failed=${m.failed_count} waiting_capacity=${y}`)},onError:(d)=>{if(d instanceof DOMException&&d.name==="AbortError"){s();return}c(d)},onSuccess:()=>{s()}})}).catch(In)}),n.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(r,o)=>{let{format:i,fields:a}=S(e.opts()),s=await b(t().dialerAttempts.list({campaign_id:x("dialer_campaigns",r),status:ce(o.status),contact_id:x("dialer_contacts",o.contact),page:Number(o.page),limit:Number(o.limit)}));if(i==="json"){let c=a?s.items.map((d)=>N(d,a)):s;v(c);return}L(["ID","#","Phone","Name","Status","Machine","Cause","Started","Duration","Record"],s.items.map((c)=>({ID:c.id,"#":c.attempt_number,Phone:c.phone_number??"—",Name:c.contact_name??"—",Status:c.status??"—",Machine:Xo(c.machine_type),Cause:c.hangup_cause??"—",Started:c.started_at?Me(c.started_at):"—",Duration:c.duration_s!=null?ke(c.duration_s*1000):"—",Record:c.call_record_id??"—"}))),te(s)})}import{readFile as XP}from"node:fs/promises";var WP={format:"bubble",side:"right",label:"",teaser:""},xx=(e,t)=>e.trim().slice(0,t),GP=(e)=>xx(e.label,pn.label.max),ZP=(e)=>xx(e.teaser,pn.teaser.max);function No(e,t){return` ${e}="${t.replaceAll("&","&").replaceAll('"',""")}"`}function Ex(e){return`${$t(e)}/webchat/v1/loader.js`}function YP(e){return`<niva-chat key="${e}" mode="inline"></niva-chat>`}function JP(e,t,n=WP){let r=GP(n),o=ZP(n),i=[No("data-key",t),n.format==="side"?No("data-layout","side"):"",n.side==="left"?No("data-side","left"):"",n.format==="side"&&r!==""?No("data-label",r):"",n.format==="bubble"&&o!==""?No("data-teaser",o):""].join("");return`<script async src="${Ex(e)}"${i}></script>`}function wx(e,t,n){if(n.format==="inline")return{script:`<script async src="${Ex(e)}"></script>`,element:YP(t)};return{script:JP(e,t,n),element:null}}var QP=new Set(["bot_token","webhook_secret","sip_password_encrypted","sip_password_iv"]),e$="<hidden>";function We(e){C(`Error: ${e}`),process.exit(A.USAGE_ERROR)}function tn(e){return x("channels",e)}function ju(e){return x("connectors",e)}function Vu(e){return x("visual_plans",e)}function Cx(e){return x("schedules",e)}function Ax(e){let t=Ee(e);if(t==null)return e;return Object.fromEntries(Object.entries(t).map(([n,r])=>[n,QP.has(n)?e$:r]))}function Ku(e){return{...e,config:Ax(e.config)}}async function t$(e){let t=e==="-"?await Fe():await XP(e,"utf-8"),n;try{n=JSON.parse(t)}catch{We(`invalid config file "${e}": not valid JSON.`)}if(!se(n))We(`invalid config file "${e}": expected a JSON object.`);return n}function Tx(e){return e.option("--bot-token-env <VAR>","Telegram bot token, read from this environment variable").option("--bot-token-stdin","Telegram bot token, read from stdin")}function Rx(e){return Tx(e).option("--phone-number-id <id>","WhatsApp phone_number_id (see: niva channels whatsapp-numbers <connector_id>)").option("--allow-groups","Telegram: let the bot answer in groups").option("--session-timeout <minutes>","Chat session timeout in minutes (5-10080)").option("--file <path>","JSON file with the channel config object (- for stdin); flags override its keys")}async function Ix(e){if(e.botTokenEnv!=null&&e.botTokenStdin===!0)We("--bot-token-env and --bot-token-stdin are mutually exclusive.");if(e.botTokenEnv!=null){let t=process.env[e.botTokenEnv];if(t==null||t==="")We(`environment variable ${e.botTokenEnv} is not set or empty (--bot-token-env).`);return t}if(e.botTokenStdin===!0)return(await Fe()).replace(/\r?\n$/,"");return}async function Nx(e){if(e.file==="-"&&e.botTokenStdin===!0)We("--file - and --bot-token-stdin both read stdin; pass the token with --bot-token-env instead.");let t=e.file==null?{}:await t$(e.file),n=await Ix(e);if(n!=null)t.bot_token=n;if(e.phoneNumberId!=null)t.phone_number_id=e.phoneNumberId;if(e.allowGroups===!0)t.allow_groups=!0;if(e.sessionTimeout!=null)t.session_timeout_minutes=Number(e.sessionTimeout);if(e.origin!=null)t.allowed_origins=e.origin;return Object.keys(t).length===0?void 0:t}function n$(e,t){return[...t??[],e]}function r$(e){if(e.visual_plan_id==null)return"-";return`${e.visual_plan_name??"?"} (${e.visual_plan_id})`}function o$(e){if(e.visual_plan_id==null)return;let t=e.visual_plan_published_version==null?"never published":"v"+e.visual_plan_published_version;return e.visual_plan_has_unpublished_changes?t+" (unpublished changes)":t}function i$(e){let t=Ee(Ax(e.config))??{},n=Object.entries(t).map(([r,o])=>({label:r,value:typeof o==="object"&&o!==null?JSON.stringify(o):String(o)}));J([{title:`${e.name} (${e.id})`,rows:[{label:"Type",value:e.channel_type},{label:"Description",value:e.description},{label:"Identifier",value:e.identifier},{label:"Active",value:e.is_active?"yes":"no"},{label:"Plan",value:r$(e)},{label:"Plan version",value:o$(e)},{label:"Schedule",value:e.schedule_id==null?void 0:`${e.schedule_name??"?"} (${e.schedule_id})`},{label:"Connector",value:e.connector_id},{label:"Webhook URL",value:e.webhook_url},{label:"Calls (7d)",value:e.calls_7d?.total},{label:"Last call",value:e.last_call_at?.toISOString()},{label:"Created",value:e.created_at.toISOString()},{label:"Updated",value:e.updated_at.toISOString()}]},{title:"Config (credentials hidden)",rows:n.length>0?n:[{label:"(empty)",value:""}]}])}function qu(e,t,n,r){if(n==="json"){let o=Ku(e);v(r?N(o,r):o);return}O(`Channel ${t}: ${e.name} (${e.id})`)}function a$(e){return e.readiness.ready?"ready":"not ready"}function s$(e,t,n){e.command("list").description("List channels with type, plan, active state and 7-day call count; --alert shows the ones needing attention").option("--type <type>","Filter by channel type (sip, whatsapp, telegram, webchat)").option("--active","Only active channels").option("--inactive","Only inactive channels").option("--alert","Only channels with an alert: active with no plan, never-published plan, or failed WhatsApp webhook sync").option("--search <term>","Search by name").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(r)=>{if(r.active===!0&&r.inactive===!0)We("--active and --inactive are mutually exclusive.");let{format:o,fields:i}=S(t.opts()),a=await b(n().channels.list({page:Number(r.page),limit:Number(r.limit),...r.search!=null&&{search:r.search},...r.type!=null&&{channel_type:r.type},...r.active===!0&&{is_active:!0},...r.inactive===!0&&{is_active:!1},...r.alert===!0&&{alert:!0}})),s=a.items.map((c)=>Ku(c));if(o==="json"){v(i?s.map((c)=>N(c,i)):{...a,items:s});return}L(["ID","Type","Name","Identifier","Plan","Active","Calls 7d"],s.map((c)=>({ID:c.id,Type:c.channel_type,Name:c.name,Identifier:c.identifier??"-",Plan:c.visual_plan_name??"-",Active:c.is_active?"yes":"no","Calls 7d":c.calls_7d?.total??"-"}))),te(a)})}function c$(e,t,n){e.command("show <id>").description("Show a channel: plan, schedule, connector, webhook URL and config (credentials hidden)").action(async(r)=>{let{format:o,fields:i}=S(t.opts()),a=await b(n().channels.getById({channel_id:tn(r)}));if(a==null)C(`Channel not found: ${r}`),process.exit(A.NOT_FOUND);if(o==="json"){let s=Ku(a);v(i?N(s,i):s);return}i$(a)})}function l$(e,t,n){let r=e.command("create <type>").description("Create a channel of type sip, whatsapp, telegram or webchat. WhatsApp needs --connector and --phone-number-id; Telegram needs a bot token (--bot-token-env or --bot-token-stdin); webchat needs at least one --origin (the site domain the chat may open on).").requiredOption("--name <name>","Channel name").option("--description <text>","Channel description").option("--identifier <id>","Provider-facing identifier (e.g. the SIP number); unique within the organization").option("--connector <id>","WhatsApp: connector (conn_...) that owns the account").option("--plan <id>","Visual plan (vp_...) that answers on this channel").option("--schedule <id>","Schedule (sched_...) that gates when the channel is available").option("--origin <domain>","Webchat: a site domain the chat may open on (repeat for more)",n$).option("--inactive","Create the channel switched off");Rx(r).action(async(o,i)=>{let{format:a,fields:s}=S(t.opts());if(o==="webchat"&&(i.origin??[]).length===0)We("a webchat channel needs at least one --origin <domain>: the site the chat may open on.");if(o!=="webchat"&&i.origin!=null)We("--origin only applies to a webchat channel.");let c=await Nx(i),d={channel_type:ce(o),name:i.name,...i.description!=null&&{description:i.description},...i.identifier!=null&&{identifier:i.identifier},...i.connector!=null&&{connector_id:ju(i.connector)},...i.plan!=null&&{visual_plan_id:Vu(i.plan)},...i.schedule!=null&&{schedule_id:Cx(i.schedule)},...i.inactive===!0&&{is_active:!1},...c!=null&&{config:c}},u=await b(n().channels.create(d));qu(u,"created",a,s)})}function d$(e,t,n){let r=e.command("update <id>").description("Change a channel: name, plan, schedule, connector or config (merged into the stored config). Moving a channel off a plan it already has needs --reassign.").option("--name <name>","New name").option("--description <text>","New description").option("--identifier <id>","New provider-facing identifier").option("--connector <id>","WhatsApp: connector (conn_...) that owns the account").option("--plan <id>","Attach this visual plan (vp_...)").option("--detach-plan","Detach the current plan").option("--schedule <id>","Attach this schedule (sched_...)").option("--detach-schedule","Detach the current schedule").option("--reassign","Allow moving the channel to another plan even when it already has one");Rx(r).action(async(o,i)=>{if(i.plan!=null&&i.detachPlan===!0)We("--plan and --detach-plan are mutually exclusive.");if(i.schedule!=null&&i.detachSchedule===!0)We("--schedule and --detach-schedule are mutually exclusive.");let{format:a,fields:s}=S(t.opts()),c=await Nx(i),d={channel_id:tn(o),...i.name!=null&&{name:i.name},...i.description!=null&&{description:i.description},...i.identifier!=null&&{identifier:i.identifier},...i.connector!=null&&{connector_id:ju(i.connector)},...i.plan!=null&&{visual_plan_id:Vu(i.plan)},...i.detachPlan===!0&&{visual_plan_id:null},...i.schedule!=null&&{schedule_id:Cx(i.schedule)},...i.detachSchedule===!0&&{schedule_id:null},...i.reassign===!0&&{reassign:!0},...c!=null&&{config:c}};if(Object.keys(d).length===1)We("nothing to update: pass at least one of --name, --plan, --schedule, --connector, --file, ...");let u=await b(n().channels.update(d));qu(u,"updated",a,s)})}function u$(e,t,n){e.command("assign <id>").description("Point a channel at a visual plan so it answers with it; the plan must be published. Moving a channel off a plan it already has needs --reassign.").requiredOption("--plan <plan_id>","Visual plan (vp_...) to answer with").option("--reassign","Allow moving the channel to another plan even when it already has one").action(async(r,o)=>{let{format:i,fields:a}=S(t.opts()),s=await b(n().channels.update({channel_id:tn(r),visual_plan_id:Vu(o.plan),...o.reassign===!0&&{reassign:!0}}));qu(s,"assigned to plan "+o.plan,i,a)})}function p$(e,t,n){for(let[r,o]of[["enable",!0],["disable",!1]])e.command(`${r} <id>`).description(o?"Switch a channel on so it answers calls and chats with its plan":"Switch a channel off; it stops answering until enabled again").action(async(i)=>{let{format:a}=S(t.opts());if(await b(n().channels.toggle({channel_id:tn(i),is_active:o})),a==="json"){v({id:i,is_active:o});return}O(`Channel ${o?"enabled":"disabled"}: ${i}`)})}function m$(e,t,n){e.command("delete <id>").description("Delete a channel (needs --yes in a non-interactive shell)").action(async(r)=>{let{format:o}=S(t.opts()),i=t.opts().yes===!0;if(await Ce(`Delete channel ${r}?`,{yes:i}),await b(n().channels.delete({channel_id:tn(r)})),o==="json"){v({id:r,deleted:!0});return}O(`Channel deleted: ${r}`)})}function f$(e,t,n){let r=e.command("test-connection").description("Check a Telegram bot token against Telegram without creating a channel; prints the bot username. Telegram is the only type the API accepts.");Tx(r).action(async(o)=>{let{format:i}=S(t.opts()),a=await Ix(o);if(a==null)We("pass the bot token with --bot-token-env <VAR> or --bot-token-stdin.");let s=await b(n().channels.testConnection({channel_type:"telegram",config:{bot_token:a}}));if(i==="json")v(s);else if(s.ok)O("Telegram bot reachable"+(s.username==null?"":": @"+s.username));else C(`Telegram connection failed: ${s.error??"unknown error"}`);if(!s.ok)process.exit(A.GENERAL_ERROR)})}function g$(e,t,n){e.command("setup-whatsapp-sip <id>").description("Configure WhatsApp calling (SIP) with Meta for a WhatsApp channel, so voice calls reach NIVA. Run it after the channel exists.").action(async(r)=>{let{format:o}=S(t.opts());if(await b(n().channels.setupWhatsappSip({channel_id:tn(r)})),o==="json"){v({id:r,ok:!0});return}O(`WhatsApp SIP configured for channel ${r}`)})}function h$(e,t,n){e.command("whatsapp-connectors").description("List the WhatsApp connectors a WhatsApp channel can use (id, name, status, account)").action(async()=>{let{format:r,fields:o}=S(t.opts()),i=await b(n().channels.whatsappConnectors());if(r==="json"){v(o?i.map((a)=>N(a,o)):i);return}L(["ID","Name","Status","Account"],i.map((a)=>({ID:a.id,Name:a.name,Status:a.status,Account:a.account_label??"-"})))})}function y$(e,t,n){e.command("whatsapp-numbers <connector_id>").description("List the WhatsApp phone numbers of a connector with readiness and the bound channel; the ID column is the --phone-number-id for channels create").option("--refresh","Bypass the 5-minute cache and read the numbers again").action(async(r,o)=>{let{format:i,fields:a}=S(t.opts()),s=await b(n().channels.whatsappNumbers({connector_id:ju(r),refresh:o.refresh===!0}));if(i==="json"){v(a?s.map((c)=>N(c,a)):s);return}L(["ID","Number","Name","Readiness","Channel"],s.map((c)=>({ID:c.id,Number:c.display_phone_number,Name:c.verified_name,Readiness:a$(c),Channel:c.channel==null?"-":`${c.channel.name} (${c.channel.id})`})))})}function _$(e){if(e.inline===!0)return"inline";return e.layout==="side"?"side":"bubble"}function b$(e,t,n,r){let o=e.command("webchat").description("Webchat channels: install snippet and key rotation");o.command("snippet <channel_id>").description("Print the install snippet of a webchat channel, exactly what the Installation box in the app builds: the script tag (format and side go on it), plus the <niva-chat> element with --inline").option("--layout <layout>","Launcher format: bubble (default) or side").option("--side <side>","Launcher side: right (default) or left").option("--label <text>","Side tab text (layout side only, 24 characters)").option("--teaser <text>","Invite beside the bubble for this page (layout bubble only, 160 characters)").option("--inline","Embed the chat in the page: the script without the key plus the <niva-chat> element").action(async(i,a)=>{let{format:s}=S(t.opts());if(a.layout!=null&&a.layout!=="bubble"&&a.layout!=="side")We(`--layout must be bubble or side, got "${a.layout}".`);if(a.side!=null&&a.side!=="right"&&a.side!=="left")We(`--side must be right or left, got "${a.side}".`);if(a.inline===!0&&(a.layout!=null||a.side!=null||a.label!=null||a.teaser!=null))We("--inline embeds the chat in the page: it takes no --layout, --side, --label or --teaser.");let c=await b(n().channels.getById({channel_id:tn(i)}));if(c==null)C(`Channel not found: ${i}`),process.exit(A.NOT_FOUND);if(c.channel_type!=="webchat"||c.identifier==null)We(`channel ${i} is not a webchat channel.`);let d={format:_$(a),side:a.side==="left"?"left":"right",label:a.label??"",teaser:a.teaser??""},u=wx(r().url,c.identifier,d);if(s==="json"){v(u);return}if(console.log(u.script),u.element!=null)console.log(u.element)}),o.command("rotate-key <channel_id>").description("Replace the public key of a webchat channel and print the new one. The old key stops working at once: every site with the old snippet loses the chat and open conversations are closed (needs --yes in a non-interactive shell)").action(async(i)=>{let{format:a}=S(t.opts()),s=t.opts().yes===!0;await Ce(`Rotate the public key of ${i}? Sites with the old snippet stop showing the chat.`,{yes:s});let c=await b(n().channels.rotateWebchatKey({channel_id:tn(i)}));if(a==="json"){v(c);return}console.log(c.public_key),yt("Update the snippet on every site: niva channels webchat snippet "+i)}),o.command("rotate-secret <channel_id>").description("Generate a new identity secret for a webchat channel and print it once to stdout; it cannot be read again. The previous secret keeps verifying identity tokens for 24 hours (needs --yes in a non-interactive shell)").action(async(i)=>{let{format:a}=S(t.opts()),s=t.opts().yes===!0;await Ce(`Generate a new identity secret for ${i}?`,{yes:s});let c=await b(n().channels.rotateWebchatSecret({channel_id:tn(i)}));if(a==="json"){v(c);return}console.log(c.secret),yt("Shown once: store it now. The previous secret keeps working for 24 hours.")})}var v$=/unknown option '([^']*)'/;function S$(e){let t=v$.exec(e)?.[1];if(t==null)return e;let n=t.indexOf("=");if(n<0)return e;let r=t.slice(0,n),o=e.replace(`'${t}'`,`'${r}=<redacted>'`);if(r!=="--bot-token")return o;return`${o}
|
|
106
|
-
Use --bot-token-env <VAR> or --bot-token-stdin for a credential instead of a literal value.`}function Ox(e,t,n){let r=e.createCommand("channels").description("Channels (SIP, WhatsApp, Telegram, webchat): the entry points a plan answers on");r.configureOutput({outputError:(o,i)=>i(S$(o))}),e.addCommand(r),s$(r,e,t),c$(r,e,t),l$(r,e,t),d$(r,e,t),u$(r,e,t),p$(r,e,t),m$(r,e,t),f$(r,e,t),g$(r,e,t),h$(r,e,t),y$(r,e,t),b$(r,e,t,n)}import{readFile as V$}from"node:fs/promises";class Bu{sets=new Map;on(e,t){let n=this.sets.get(e)??new Set;this.sets.set(e,n);let r=(o)=>{t(o)};return n.add(r),()=>void n.delete(r)}async once(e){return new Promise((t)=>{let n=this.on(e,(r)=>{n(),t(r)})})}emit(e,t){for(let n of Array.from(this.sets.get(e)??[]))try{n(t)}catch(r){queueMicrotask(()=>{throw r})}}}class Hu extends Error{name="NivaError"}class Te extends Hu{name="NivaChatError";code;fatal;constructor(e,t,n){super(t,n.cause===void 0?void 0:{cause:n.cause});this.code=e,this.fatal=n.fatal}}function Tr(e){try{let t=new URL(e),n=t.searchParams.get("session");if(n===null||n==="")return null;if(t.protocol!=="wss:"&&t.protocol!=="ws:")return null;let o=`${t.protocol==="wss:"?"https:":"http:"}//${t.host}/api/v1/chat`;return{base:o,url:`${o}/media`,session:n}}catch{return null}}function x$(e){switch(e){case"CHAT_MEDIA_TOO_LARGE":case"CHAT_MEDIA_UNSUPPORTED":case"WEBCHAT_SESSION_INVALID":case"WEBCHAT_ORIGIN_DENIED":case"CHAT_MEDIA_NOT_FOUND":case"CHAT_SESSION_NOT_FOUND":return e;default:return"UPLOAD_FAILED"}}var E$={code:"UPLOAD_FAILED",message:"The file could not be uploaded"};function Gn(e,t,n=E$){let r=typeof e==="object"&&e!==null?e:{},o=Reflect.get(r,"message"),i=x$(Reflect.get(r,"code")),a=i==="UPLOAD_FAILED"?n.code:i;return new Te(t===429?"RATE_LIMITED":a,typeof o==="string"?o:n.message,{fatal:!1})}var Wu={code:"END_FAILED",message:"The conversation could not be ended"};async function Gu(e){let t=e.wsUrl===null?null:Tr(e.wsUrl);if(t===null)throw new Te("OFFLINE","There is no chat session to end",{fatal:!1});let n=`${t.base}/sessions/${encodeURIComponent(t.session)}`,r={method:"DELETE",headers:{authorization:`Bearer ${t.session}`},keepalive:!0},o;try{o=await(e.fetch===void 0?globalThis.fetch(n,r):e.fetch(n,r))}catch(i){throw new Te(Wu.code,Wu.message,{fatal:!1,cause:i})}if(!o.ok)throw Gn(await o.json().catch(()=>null),o.status,Wu)}function kx(e){return typeof e==="object"&&"file"in e}function w$(e){let t=Reflect.get(e,"name");return typeof t==="string"&&t!==""?t:"file"}function Dx(e){return{type:"file",name:w$(e.file),content_type:e.file.type,size_bytes:e.file.size,...e.caption===void 0||e.caption===""?{}:{caption:e.caption},file:e.file}}function Px(e){if(typeof e!=="string")return e;let t=e.trim();return t===""?null:{type:"text",text:t}}function $x(e){if("label"in e)return{type:"button_reply",button_id:e.id,button_text:e.label};return{type:"list_reply",list_id:e.id,list_title:e.title}}function Mx(e,t){return Object.freeze({author:"visitor",id:`local-${Date.now().toString(36)}-${t}`,ts:Date.now(),message:e,delivery:e.type==="file"?"uploading":"queued"})}var Lx=25000,zx=8,Fx=1,Zu=(e)=>Math.min(30000,1000*2**e);function Ux(e){if(e==="CAPACITY_EXCEEDED"||e==="RATE_LIMITED"||e==="INVALID_MESSAGE"||e==="MEDIA_NOT_FOUND")return e;if(e==="INVALID_JSON")return"INVALID_MESSAGE";return"EXECUTION_ERROR"}var jx=(e)=>e==="RATE_LIMITED"||e==="INVALID_MESSAGE"||e==="INVALID_JSON"||e==="MEDIA_NOT_FOUND";function Vx(e){let t=globalThis;if(typeof t!=="object"||t===null||typeof Reflect.get(t,"addEventListener")!=="function"||typeof Reflect.get(t,"removeEventListener")!=="function")return null;return globalThis.addEventListener("online",e),()=>globalThis.removeEventListener("online",e)}var Kx={4009:["SUPERSEDED","Another connection took over this chat session"],1008:["UNAVAILABLE","The chat is no longer available for this session"]};var wa=(e)=>e.author==="visitor"&&e.message.type==="file",qx=(e)=>e.filter((t)=>wa(t)&&t.delivery==="uploading").map((t)=>t.id),Bx=(e)=>e.find((t)=>t.author==="visitor"&&(t.delivery==="queued"||t.delivery==="uploading"));function Hx(e,t){if(e.message.type!=="file")return e.message;if(t===null)return null;return{type:"media",media_id:t,...e.message.caption===void 0?{}:{caption:e.message.caption}}}function Yu(e,t){if(e.message.type!=="file")return e;let{media_id:n,...r}=e.message;return{...e,message:t===null?r:{...r,media_id:t}}}var Wx=(e)=>wa(e)&&(e.delivery==="uploading"||e.delivery==="queued")?Object.freeze({...e,delivery:"failed"}):e,Gx=(e)=>e.filter((t)=>t.author==="visitor"&&(t.delivery==="queued"||wa(t)&&t.delivery==="uploading")).map((t)=>Wx(t)).map((t)=>wa(t)?Yu(t,null):t),Zx=(e)=>e.map((t)=>Object.freeze(Wx(t)));function Yx(e){return Object.freeze({author:"plan",id:e.id,seq:e.seq,ts:e.ts,message:e.message})}function Jx(e,t,n,r){let o;try{o=t===void 0?new WebSocket(e):t(e)}catch{return null}return o.onopen=()=>{if(n())r.open()},o.onmessage=(i)=>{let a=i.data;if(n())r.message(a)},o.onclose=(i)=>{if(n())r.close(i.code)},o.onerror=()=>{},o}function C$(e){return typeof e==="object"&&e!==null&&typeof Reflect.get(e,"getItem")==="function"&&typeof Reflect.get(e,"setItem")==="function"&&typeof Reflect.get(e,"removeItem")==="function"}function Xx(e){if(e==="none")return null;try{let t=Reflect.get(globalThis,e==="tab"?"sessionStorage":"localStorage");return C$(t)?t:null}catch{return null}}function A$(e){if(typeof e!=="object"||e===null)return!1;let t=Reflect.get(e,"author"),n=Reflect.get(e,"message");return(t==="plan"||t==="visitor")&&typeof Reflect.get(e,"id")==="string"&&typeof Reflect.get(e,"ts")==="number"&&typeof n==="object"&&n!==null}function Qx(e,t){try{let n=e.getItem(t);if(n===null)return null;let r=JSON.parse(n);if(typeof r!=="object"||r===null||Reflect.get(r,"v")!==1)return null;let o=Reflect.get(r,"wsUrl"),i=Reflect.get(r,"started"),a=Reflect.get(r,"lastSeq"),s=Reflect.get(r,"status"),c=Reflect.get(r,"messages");if(typeof o!=="string"||typeof i!=="boolean"||typeof a!=="number")return null;if(!Array.isArray(c))return null;return{wsUrl:o,started:i,lastSeq:a,status:s==="active"||s==="waiting_input"||s==="ended"?s:null,messages:c.filter((m)=>A$(m))}}catch{return null}}function T$(e){if(e.author!=="visitor"||e.message.type!=="file")return e;let{file:t,...n}=e.message;return{...e,message:n}}function eE(e,t,n){try{e.setItem(t,JSON.stringify({v:1,...n,messages:n.messages.map((r)=>T$(r))}))}catch{}}function Ju(e,t){try{e.removeItem(t)}catch{}}class Xu{stops=new Map;has(e){return this.stops.has(e)}after(e,t,n){this.clear(e);let r=setTimeout(()=>{this.stops.delete(e),n()},t);this.stops.set(e,()=>clearTimeout(r))}every(e,t,n){this.clear(e);let r=setInterval(n,t);this.stops.set(e,()=>clearInterval(r))}clear(e){this.stops.get(e)?.(),this.stops.delete(e)}clearAll(){for(let e of this.stops.values())e();this.stops.clear()}}var Qu={code:"DOWNLOAD_FAILED",message:"The file could not be downloaded"},ep=()=>new DOMException("The download was aborted","AbortError");function tE(e){let t=new Set,n=!1;async function r(o,i){if(n||i?.signal?.aborted===!0)throw ep();let a=e.wsUrl(),s=a===null?null:Tr(a);if(s===null)throw new Te("OFFLINE","There is no chat session to download the file with",{fatal:!1});let c=new AbortController,d=()=>c.abort();i?.signal?.addEventListener("abort",d,{once:!0}),t.add(c);try{let u=`${s.url}/${encodeURIComponent(o)}`,m={method:"GET",headers:{authorization:`Bearer ${s.session}`},signal:c.signal},y=await(e.fetch===void 0?globalThis.fetch(u,m):e.fetch(u,m));if(!y.ok)throw Gn(await y.json().catch(()=>null),y.status,Qu);let _=await y.blob();if(c.signal.aborted)throw ep();return _}catch(u){if(c.signal.aborted)throw ep();if(u instanceof Te)throw u;throw new Te(Qu.code,Qu.message,{fatal:!1,cause:u})}finally{t.delete(c),i?.signal?.removeEventListener("abort",d)}}return{get:r,abortAll(){for(let o of t)o.abort();t.clear()},close(){n=!0}}}async function R$(e){let t=new FormData;t.set("file",e.file,e.name);let n={method:"POST",headers:{authorization:`Bearer ${e.target.session}`},body:t,signal:e.signal},r;try{r=await(e.fetch===void 0?globalThis.fetch(e.target.url,n):e.fetch(e.target.url,n))}catch(a){if(e.signal.aborted)throw a;throw new Te("UPLOAD_FAILED","The file could not be uploaded",{fatal:!1,cause:a})}let o=await r.json().catch(()=>null);if(!r.ok)throw Gn(o,r.status);let i=typeof o==="object"&&o!==null?Reflect.get(o,"id"):void 0;if(typeof i!=="string")throw Gn(null);return i}function nE(e){let t=new Map,n=tE(e),r=0;function o(i){let a=t.get(i),s=e.wsUrl();if(a?.controller!==null||s===null)return;let c=Tr(s);if(c===null){e.settle(i,new Te("UPLOAD_FAILED","The file could not be uploaded",{fatal:!1}));return}let d=new AbortController;a.controller=d;let u=r,m=()=>e.stopped()||u!==r||d.signal.aborted;R$({target:c,file:a.file,name:a.name,signal:d.signal,fetch:e.fetch}).then((y)=>{if(m())return;a.controller=null,a.mediaId=y,e.settle(i,"queued")},(y)=>{if(m())return;a.controller=null,e.settle(i,y instanceof Te?y:new Te("UPLOAD_FAILED","The file could not be uploaded",{fatal:!1,cause:y}))})}return{add(i,a,s){t.set(i,{file:a,name:s,mediaId:null,controller:null})},start:o,has:(i)=>t.has(i),mediaId:(i)=>t.get(i)?.mediaId??null,retryAs:(i)=>t.get(i)?.mediaId===null?"uploading":"queued",dropMediaId(i){let a=t.get(i);if(a!==void 0)a.mediaId=null},dropAllMediaIds(){for(let i of t.values())i.mediaId=null},getFile:n.get,closeDownloads:()=>n.close(),abortAll(){r+=1,n.abortAll();for(let i of t.values())i.controller?.abort(),i.controller=null}}}var I$=new Set(["text","media","location","buttons","list","carousel","template"]),N$=new Set(["active","waiting_input","ended"]);function tp(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function O$(e){return tp(e)&&typeof e.type==="string"&&I$.has(e.type)}function k$(e){return typeof e==="string"&&N$.has(e)}function D$(e,t){let{id:n,ts:r,message:o}=e;if(typeof n!=="string"||typeof r!=="number"||!O$(o))return null;return{type:"message",seq:t,id:n,ts:r,message:o}}function P$(e,t){let{code:n,message:r}=e;if(typeof n!=="string")return null;return{type:"error",seq:t,code:n,message:typeof r==="string"?r:n}}function rE(e){if(!tp(e))return null;let t=e.type;if(t==="trace")return{type:t};let n=e.seq;if(typeof n!=="number")return null;switch(t){case"connected":case"pong":return{type:t,seq:n};case"typing":return typeof e.active==="boolean"?{type:t,seq:n,active:e.active}:null;case"state":return k$(e.status)?{type:t,seq:n,status:e.status}:null;case"error":return P$(e,n);case"message":return D$(e,n);default:return null}}function $$(e){if(tp(e)&&e.type==="replay"){let{seq:t,messages:n}=e;if(typeof t!=="number"||!Array.isArray(n))return null;let r=[],o=n;for(let i of o){let a=rE(i);if(a!==null)r.push(a)}return{type:"replay",seq:t,messages:r}}return rE(e)}function oE(e){if(typeof e!=="string")return null;try{return $$(JSON.parse(e))}catch{return null}}function iE(e,t){return e.filter((n)=>n.type!=="trace"&&n.seq>t).sort((n,r)=>n.seq-r.seq)}function np(e){let t=e.storageKey??"niva-chat",n=Xx(e.persist??"tab"),r=new Bu,o=[],i=null,a=!1,s="connecting",c=0,d=!1,u=null,m=null,y=0,_=0,E=0,k=0,V=new Xu,G=!1,oe=!1,ct=!1,nt=!1,ge=!1,Q=null,Ge=!1,rn=!1,tr=0,vn=!1,It=0,Uo=0,Ze=nE({wsUrl:()=>u,stopped:()=>oe,fetch:e.fetch,settle:(R,Z)=>rt(()=>{if(Ko(R,(_e)=>({..._e,delivery:Z==="queued"?"queued":"failed"})),Z!=="queued")r.emit("error",Z)})}),Ut=!1,Ma=null,jo=La();function La(){return Object.freeze({messages:Object.freeze([...o]),connection:s,status:i,typing:a})}function Vo(){if(nC(),!Ut)return;Ut=!1,jo=La(),r.emit("change",jo)}function rt(R){R(),fC(),Vo()}function nC(){if(n===null||ct||u===null)return;eE(n,t,{wsUrl:u,started:d,lastSeq:c,status:i,messages:o})}function Sn(R){if(s===R)return;s=R,Ut=!0,r.emit("connection",R)}function Or(R){if(a===R)return;a=R,Ut=!0,r.emit("typing",R)}function rC(R){if(i===R)return;i=R,Ut=!0,r.emit("status",R)}function Ko(R,Z){let _e=(qe)=>Object.freeze(Ze.has(R)?Yu(Z(qe),Ze.mediaId(R)):Z(qe));o=o.map((qe)=>qe.author==="visitor"&&qe.id===R?_e(qe):qe),Ut=!0}function kr(R,Z,_e){r.emit("error",new Te(R,Z,{fatal:_e}))}function Dr(R){if(m?.readyState!==Fx)return!1;try{return m.send(JSON.stringify(R)),!0}catch{return!1}}function qo(){V.clearAll(),G=!1}function za(){rn=!1,tr=0,V.clear("start")}let xn=()=>!oe;function Fa(){y+=1;let R=m;if(m=null,ge=!1,za(),R===null)return;try{R.close(1000)}catch{}}function Bo(){if(Or(!1),!xn())return;if(k>=zx){Sn("offline"),kr("OFFLINE","Could not reach the chat; will try again when the browser is back online",!1);return}let R=Zu(k);if(k+=1,Sn("reconnecting"),!xn())return;V.after("retry",R,()=>{if(oe)return;rt(kp)})}function kp(){if(!xn())return;if(u===null)Ho(!1);else if(It>0&&It%2===0)Ho(!0);else Ua()}function Ua(){let R=u;if(R===null||oe)return;y+=1;let Z=y;G=!1,ge=!1,vn=!1;let _e=Jx(R,e.webSocket,()=>Z===y,{open:()=>{k=0},message:(qe)=>rt(()=>iC(qe)),close:(qe)=>rt(()=>pC(qe))});if(_e===null){It+=1,Bo();return}m=_e}function oC(){G=!1,V.every("ping",Lx,()=>{if(oe)return;if(G){rt(()=>{qo(),Fa(),Bo()});return}if(Dr({type:"ping"}))G=!0})}async function Ho(R){if(!xn())return;_+=1;let Z=_,_e;try{_e=await e.session()}catch(qe){if(Z!==_||!xn())return;rt(()=>{if(R)It+=1;if(qe instanceof Te)r.emit("error",qe);if(qe instanceof Te&&qe.fatal)Pr();else Bo()});return}if(Z!==_||!xn())return;rt(()=>{if(R){if(Pp(),Sn("connecting"),Vo(),kr("SESSION_EXPIRED","The chat session expired; a new conversation was started",!1),!xn())return}u=_e,d=!1,Ua()})}function iC(R){let Z=oE(R);if(Z===null)return;G=!1,aC(Z)}function aC(R){if(R.type==="connected")sC();else if(R.type==="replay")cC(R.messages);else if(R.type==="error")dC(R.code,R.message,R.seq);else if(R.type!=="pong"&&R.type!=="trace")Va(R)}function sC(){let R=y;if(vn=!0,It=0,d)ge=!0,Dr({type:"resume",last_seq:c});else Dr({type:"start"}),d=!0,rn=!0;if(Sn("connected"),oe||R!==y)return;oC()}function cC(R){if(ge=!1,lC(R),Q!==null&&!Ge)ja("queued")}function ja(R){if(Q!==null&&R!==null)Ko(Q,(Z)=>({...Z,delivery:R}));Q=null,nt=!1}function lC(R){for(let Z of iE(R,c))if(Z.type==="message"||Z.type==="typing"||Z.type==="state")Va(Z);else if(Z.type==="error")c=Z.seq}function Va(R){if(c=Math.max(c,R.seq),R.type==="typing"?R.active:R.type==="state"&&R.status==="active")Ge=!0;if(R.type!=="typing")Q=null,za();switch(R.type){case"message":{if(o.some((_e)=>_e.author==="plan"&&_e.id===R.id))return;let Z=Yx(R);o=[...o,Z],Ut=!0,Or(!1),r.emit("message",Z);return}case"typing":Or(R.active);return;case"state":if(R.status!=="active")nt=!1;if(R.status==="ended")Or(!1);rC(R.status);return}}function dC(R,Z,_e){if(c=Math.max(c,_e),R==="TURN_IN_FLIGHT"){ja("queued"),nt=!0;return}if(R==="SESSION_EXPIRED"){$p();return}if(R==="MODULE_DISABLED"){Dp("MODULE_DISABLED",Z);return}if(R==="MEDIA_NOT_FOUND"&&Q!==null)Ze.dropMediaId(Q);if(ja(jx(R)?"failed":null),kr(Ux(R),Z,!1),rn&&!oe)uC()}function uC(){if(V.has("start"))return;let R=Zu(tr);tr+=1,V.after("start",R,()=>{if(!rn||s!=="connected")return;Dr({type:"start"})})}function pC(R){qo(),m=null,ge=!1,za();let Z=Kx[R];if(Z!==void 0){Dp(...Z);return}if(R===1011){$p();return}if(!vn)It+=1;Bo()}function Pr(R=!1){if(oe=!0,_+=1,Ze.abortAll(),!R)Ze.closeDownloads();if(qo(),Fa(),Ma?.(),Ma=null,!R)e.signal?.removeEventListener("abort",zp);Or(!1),Sn("closed")}function Dp(R,Z){Pr(),Vo(),kr(R,Z,!0)}function Pp(){if(E+=1,qo(),Fa(),n!==null)Ju(n,t);Ze.abortAll(),Ze.dropAllMediaIds(),o=Gx(o),i=null,a=!1,c=0,d=!1,u=null,nt=!1,Q=null,Ge=!1,It=0,Ut=!0}function $p(){Pp(),k=0,Sn("connecting"),Vo(),kr("SESSION_EXPIRED","The chat session expired; a new conversation was started",!1),Ho(!1)}function mC(){if(oe||s!=="offline")return;k=0,rt(()=>{Sn("reconnecting"),kp()})}function fC(){if(oe)return;for(let _e of qx(o))Ze.start(_e);if(s!=="connected"||ge||nt||i!=="waiting_input")return;let R=Bx(o);if(R===void 0||R.delivery==="uploading")return;let Z=Hx(R,Ze.mediaId(R.id));if(Z===null||!Dr({type:"message",message:Z}))return;Ko(R.id,(_e)=>({..._e,delivery:"sent"})),nt=!0,Q=R.id,Ge=!1}function Mp(R){if(i==="ended")return;Uo+=1;let Z=Mx(R,Uo);if(R.type==="file"&&R.file!==void 0)Ze.add(Z.id,R.file,R.name);rt(()=>{o=[...o,Z],Ut=!0})}function gC(R){let Z=kx(R)?Dx(R):Px(R);if(Z!==null)Mp(Z)}function hC(R){let Z=o.find((_e)=>_e.author==="visitor"&&_e.id===R);if(Z?.author!=="visitor"||Z.delivery!=="failed")return;if(Z.message.type==="file"&&!Ze.has(R))return;rt(()=>Ko(R,(_e)=>({..._e,delivery:Ze.retryAs(R)})))}function yC(R,Z){return r.on(R,Z)}async function _C(){if(i==="ended")return;let R=E;if(await Gu({wsUrl:u,fetch:e.fetch}),R===E&&!oe)rt(()=>Va({type:"state",seq:c,status:"ended"}))}function Lp(R){if(R?.forget===!0){if(i!=="ended")Gu({wsUrl:u,fetch:e.fetch}).catch(()=>{return});if(ct=!0,n!==null)Ju(n,t)}rt(Pr)}let zp=()=>Lp(),$r=n===null?null:Qx(n,t);if($r!==null)({wsUrl:u,started:d,lastSeq:c,status:i}=$r),o=Zx($r.messages),jo=La();if(Ma=Vx(mC),e.signal?.aborted===!0)rt(Pr);else if(e.signal?.addEventListener("abort",zp,{once:!0}),$r===null)Ho(!1);else if($r.status==="ended")rt(()=>Pr(!0));else Ua();return{get state(){return jo},send:gC,select:(R)=>Mp($x(R)),retry:hC,getFile:Ze.getFile,end:_C,close:Lp,on:yC,once:async(R)=>r.once(R)}}var st=on(jt(),1);function M$(e,t){let n=!0;return async()=>{if(n)return n=!1,e;if(t===void 0)throw new Te("SESSION_EXPIRED","The chat session expired",{fatal:!0});return t()}}async function Ca(e,t){D(`Connecting to ${e}`);let n=Mu(e)?{tls:{rejectUnauthorized:!1}}:void 0,r=!1,o=!1,i=np({session:M$(e,t),persist:"none",webSocket:(a)=>new WebSocket(a,n)});throw i.on("connection",(a)=>{switch(a){case"connected":if(!r)r=!0,console.log(st.default.green(` Connected. Type a message and press Enter. Ctrl+C or /quit to exit.
|
|
107
|
-
`)),
|
|
108
|
-
Disconnected`);else C("Failed to connect");process.exit(r||o?0:1);return;case"connecting":return}}),i.on("message",(a)=>{for(let s of
|
|
109
|
-
Session ended.`)),process.exit(0)}),i.on("error",(a)=>{console.log(st.default.red(` error: [${a.code}] ${a.message}`))}),await new Promise(()=>{}),Error("unreachable")}function hn(e,t){return e.replace(/^http/,"ws")+t}var Zn=st.default.cyan(" bot");function
|
|
110
|
-
`);o=a.pop();for(let s of a){let c=s.trim();if(c==="")continue;if(c==="/quit"||c==="/exit"){r();return}console.log(`${st.default.blue(" you")} ${c}`),e.send(c)}}),process.once("SIGINT",()=>{
|
|
111
|
-
Closing...`),r()})}function aE(e,t,n){let r=e.command("chat").description("Test chat — interactive session against a visual plan (draft or published)");r.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(o,i)=>{let a=Cn(e.opts()),s=n(),c;if(i.editorState!=null){let m=await V$(i.editorState,"utf-8");c=JSON.parse(m)}if(a!=="json")D("Creating test chat session...");let d=async()=>b(t().testChat.createSession({planId:x("visual_plans",o),editor_state:c})),u=await d();if(a==="json"){v({...u,ws_url:hn(s.url,u.wsUrl)});return}O(`Session created: ${u.sessionId}`),await Ca(hn(s.url,u.wsUrl),async()=>hn(s.url,(await d()).wsUrl))}),r.command("stop <sessionId>").description("Stop an active test chat session").action(async(o)=>{let i=Cn(e.opts());if(await b(t().testChat.stop({sessionId:x("chat_ws_sessions",o)})),i==="json"){v({session_id:o,stopped:!0});return}O(`Session ${o} stopped.`)})}function sE(e){let t=e.command("config").description("Manage CLI configuration");t.command("set <key> <value>").description("Set a config value (url, api-key)").action((n,r)=>{ZS(n==="api-key"?"apiKey":n,r),O(`Set ${n} = ${r}`)}),t.command("get <key>").description("Get a config value (url, api-key)").action((n)=>{let r=n==="api-key"?"apiKey":n,i=Ou()[r];if(i==null){D(`(${n} not set)`);return}console.log(typeof i==="string"?i:JSON.stringify(i))}),t.command("show").description("Show current configuration").action(()=>{let n=Ou();v(n)})}var rp={"channel.whatsapp":{consumers:["channel"]},"whatsapp.templates":{consumers:["node"]},"whatsapp.messages":{consumers:["node"]},"sms.send":{consumers:["node","notification"]},"email.send":{consumers:["node","notification"]},"tools.catalog":{consumers:["node","mcp"]},"calendar.events":{consumers:["node"]},"voice.agent":{consumers:["node"]},"phone.lookup":{consumers:["node","mcp"]},"verify.otp":{consumers:["node","mcp"]}};function cE(e){return Object.hasOwn(rp,e)}var K$=Object.keys(rp).filter((e)=>cE(e));class op{#e;constructor(e){this.#e=e}static of(e){return new op(e)}reveal(){return this.#e}toString(){return"[redacted]"}toJSON(){return"[redacted]"}[Symbol.for("nodejs.util.inspect.custom")](){return"[redacted]"}}function B$(e){return e.secret===!0}function et(e){let t={},n={},r={};for(let[o,i]of Object.entries(e.fields)){let a=i.secret===!0?l().min(1):i.schema,s=i.optional===!0?a.optional():a;if(t[o]=s,B$(i))r[o]=s;else n[o]=s}return{...e,fieldsSchema:g(t),configSchema:g(n),credentialsSchema:g(r)}}var ip=et({kind:"elevenlabs",version:1,nameKey:"connectors.kinds.elevenlabs.name",descriptionKey:"connectors.kinds.elevenlabs.description",icon:"elevenlabs",category:"telephony",module:"ai",docsPath:"/configuracoes/conectores-elevenlabs",auth:{strategy:"fields"},fields:{api_key:{secret:!0,step:"api_key"},agent_numbers:{schema:l().default("{}"),step:"numbers"}},setup:[{id:"api_key",titleKey:"connectors.kinds.elevenlabs.setup.api_key"},{id:"numbers",titleKey:"connectors.kinds.elevenlabs.setup.numbers"}],provides:["voice.agent"]});var H$=Qy({protocol:/^https?$/u}).check(Gt((e)=>$t(e))).describe("Base URL of the Evolution API gateway, such as https://evolution.example.com."),ap=et({kind:"evolution_api",version:1,nameKey:"connectors.kinds.evolution_api.name",descriptionKey:"connectors.kinds.evolution_api.description",icon:"evolution",category:"messaging",module:"omnichannel",docsPath:"/configuracoes/conectores-evolution-api",auth:{strategy:"fields"},fields:{base_url:{schema:H$,step:"gateway"},api_key:{secret:!0,step:"api_key"}},identity:"base_url",setup:[{id:"gateway",titleKey:"connectors.kinds.evolution_api.setup.gateway",url:"https://doc.evolution-api.com"},{id:"api_key",titleKey:"connectors.kinds.evolution_api.setup.api_key"}],provides:["channel.whatsapp","whatsapp.messages"],webhook:{verification:"none",signature:"shared_secret_header",scope:"number"}});var sp=et({kind:"retell",version:1,nameKey:"connectors.kinds.retell.name",descriptionKey:"connectors.kinds.retell.description",icon:"retell",category:"telephony",module:"ai",docsPath:"/configuracoes/conectores-retell",auth:{strategy:"fields"},fields:{api_key:{secret:!0,step:"api_key"}},setup:[{id:"api_key",titleKey:"connectors.kinds.retell.setup.api_key"}],provides:["voice.agent"]});var cp=et({kind:"twilio",version:1,nameKey:"connectors.kinds.twilio.name",descriptionKey:"connectors.kinds.twilio.description",icon:"twilio",category:"telephony",module:"omnichannel",docsPath:"/configuracoes/conectores-twilio",auth:{strategy:"fields"},fields:{account_sid:{schema:l().regex(/^AC[0-9a-fA-F]{32}$/u),step:"credentials"},api_key_sid:{schema:l().regex(/^SK[0-9a-fA-F]{32}$/u),step:"credentials"},api_key_secret:{secret:!0,step:"credentials"},default_sender:{schema:l().regex(/^(MG[0-9a-fA-F]{32}|\+[1-9]\d{6,14})$/u),step:"senders",discover:"senders",optional:!0}},identity:"account_sid",discoverKeys:["verify_services"],setup:[{id:"credentials",titleKey:"connectors.kinds.twilio.setup.credentials",url:"https://console.twilio.com/"},{id:"senders",titleKey:"connectors.kinds.twilio.setup.senders"}],provides:["sms.send","phone.lookup","verify.otp"]});var lE=["us","eu"],lp=et({kind:"vapi",version:1,nameKey:"connectors.kinds.vapi.name",descriptionKey:"connectors.kinds.vapi.description",icon:"vapi",category:"telephony",module:"ai",docsPath:"/configuracoes/conectores-vapi",auth:{strategy:"fields"},fields:{api_key:{secret:!0,step:"api_key"},region:{schema:P(lE).default("us"),step:"region"}},setup:[{id:"api_key",titleKey:"connectors.kinds.vapi.setup.api_key"},{id:"region",titleKey:"connectors.kinds.vapi.setup.region"}],provides:["voice.agent"],webhook:{verification:"none",signature:"shared_secret_header",scope:"connector"}});var dE=["global","eu"],dp=et({kind:"openai_live",version:1,nameKey:"connectors.kinds.openai_live.name",descriptionKey:"connectors.kinds.openai_live.description",icon:"openai",category:"telephony",module:"ai",docsPath:"/configuracoes/conectores-openai-live",auth:{strategy:"fields"},fields:{api_key:{secret:!0,step:"api_key"},project_id:{schema:l().regex(/^proj_[A-Za-z0-9]+$/u).describe("Id of the OpenAI project with GPT-Live SIP enabled (proj_...)."),step:"project",discover:"project"},region:{schema:P(dE).default("global").describe("`eu` for a project with European data residency; it changes both the SIP and the API host."),step:"project"},webhook_secret:{secret:!0,step:"webhook",optional:!0}},identity:"project_id",setup:[{id:"api_key",titleKey:"connectors.kinds.openai_live.setup.api_key"},{id:"project",titleKey:"connectors.kinds.openai_live.setup.project",url:"https://platform.openai.com/settings"},{id:"webhook",titleKey:"connectors.kinds.openai_live.setup.webhook",url:"https://platform.openai.com/settings/project/webhooks"}],provides:["voice.agent"],webhook:{verification:"none",signature:"standard_webhooks",scope:"connector"}});var up=et({kind:"whatsapp_business",version:1,nameKey:"connectors.kinds.whatsapp_business.name",descriptionKey:"connectors.kinds.whatsapp_business.description",icon:"whatsapp",category:"messaging",module:"omnichannel",docsPath:"/configuracoes/conectores-whatsapp",auth:{strategy:"fields"},fields:{app_id:{schema:l().regex(/^\d+$/),step:"meta_app"},app_secret:{secret:!0,step:"meta_app"},access_token:{secret:!0,step:"system_user"},waba_id:{schema:l().regex(/^\d+$/),step:"waba",discover:"wabas"},business_id:{schema:l().regex(/^\d+$/),step:"waba",optional:!0}},identity:"waba_id",setup:[{id:"meta_app",titleKey:"connectors.kinds.whatsapp_business.setup.meta_app",url:"https://developers.facebook.com/apps"},{id:"system_user",titleKey:"connectors.kinds.whatsapp_business.setup.system_user",url:"https://business.facebook.com/settings/system-users"},{id:"waba",titleKey:"connectors.kinds.whatsapp_business.setup.waba"}],provides:["channel.whatsapp","whatsapp.templates"],webhook:{verification:"meta_hub_challenge",signature:"meta_hmac_sha256",scope:"connector"}});var nn={whatsapp_business:up,evolution_api:ap,twilio:cp,elevenlabs:ip,retell:sp,vapi:lp,openai_live:dp};function Oo(e){return Object.hasOwn(nn,e)}var ko=Object.keys(nn).filter((e)=>Oo(e));var G$={...Vi.whatsapp,supportsButtons:!1,maxButtons:0,supportsList:!1,supportsMedia:!1,mediaTypes:[],supportsLocation:!1,supportsTemplate:!1,sessionWindow:null,maxMediaSize:{}},xre={whatsapp_business:{calling:!0,number_registration:!0,templates:!0,official:!0,chat_capabilities:Vi.whatsapp},evolution_api:{calling:!1,number_registration:!1,templates:!1,official:!1,chat_capabilities:G$}};function Z$(e){return e.replaceAll("_","-")}function pp(e){return e.replaceAll(/_([a-z0-9])/g,(t,n)=>n.toUpperCase())}function Yn(e){let[t]=e.cli.split(" ");return t??e.cli}function Y$(e,t){let n=Z$(e);if(t.secret===!0)return[{source:"stdin",key:`${pp(e)}Stdin`,cli:`--${n}-stdin`},{source:"env",key:`${pp(e)}Env`,cli:`--${n}-env <VAR>`}];return[{source:"value",key:pp(e),cli:`--${n} <value>`}]}function Rr(e){let t=nn[e].fields;return Object.entries(t).map(([n,r])=>({field:n,secret:r.secret===!0,optional:r.optional===!0,step:r.step,discover:"discover"in r?r.discover:void 0,options:Y$(n,r)}))}function Do(){return ko.flatMap((e)=>Rr(e))}function mp(e,t){let n=e[t.key];if(n===void 0||n===!1)return!1;return t.source==="value"||n!==""}function uE(e){return Do().some((t)=>t.options.some((n)=>mp(e,n)))}function pE(e,t){let n=new Set(Rr(t).flatMap((i)=>i.options.map((a)=>a.key))),r=new Set,o=[];for(let i of Do())for(let a of i.options){if(n.has(a.key)||r.has(a.key))continue;if(r.add(a.key),mp(e,a))o.push(Yn(a))}return o}function mE(e){return Rr(e).flatMap((t)=>t.options.map((n)=>Yn(n)))}function fE(e,t){let n=[];for(let r of Rr(t))for(let o of r.options){if(!mp(e,o))continue;n.push({flag:r,option:o,source:o.source,raw:o.source==="stdin"?"":String(e[o.key])})}return n}function gE(){let e=new Set,t=[];for(let n of Do())for(let r of n.options){if(e.has(r.key))continue;e.add(r.key);let o=n.secret?"credential":"field";t.push({cli:r.cli,description:`${o} "${n.field}" (step "${n.step}")`})}return t}var Po;function gt(e){C(`Error: ${e}`),process.exit(A.USAGE_ERROR)}function Aa(e){if(!Oo(e))gt(`unknown connector kind "${e}". Known kinds: ${ko.join(", ")}.`);return e}function Oe(e){return x("connectors",e)}function J$(e){return e.split("_").map((t)=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function X$(){let e=new Set(["--pin"]);for(let t of Do())if(t.secret)e.add(`--${t.field.replaceAll("_","-")}`);return e}var Q$=/unknown option '([^']*)'/;function eM(e){let t=Q$.exec(e)?.[1];if(t==null)return e;let n=t.indexOf("=");if(n<0)return e;let r=t.slice(0,n),o=e.replace(`'${t}'`,`'${r}=<redacted>'`);if(!X$().has(r))return o;return`${o}
|
|
112
|
-
Use ${r}-env <VAR> or ${r}-stdin for a credential instead of a literal value.`}function tM(e){return e===""?"-":`···${e}`}function nM(e,t){let n=nn[e].setup.find((r)=>r.id===t);return n!=null&&"url"in n?n.url:void 0}function fp(e){for(let t of gE())e.option(t.cli,t.description)}function gp(e,t){let n=pE(e,t);if(n.length>0)gt(`${n.join(", ")} is not a field of ${t}. Valid flags: ${mE(t).join(", ")}.`)}async function rM(e){if(e.source==="value")return e.raw;if(e.source==="env"){let t=process.env[e.raw];if(t==null||t==="")gt(`environment variable ${e.raw} is not set or empty (${Yn(e.option)}).`);return t}return(await Fe()).replace(/\r?\n$/,"")}async function hp(e,t){let n=fE(e,t),r=new Map;for(let a of n){let s=r.get(a.flag.field);if(s==null)r.set(a.flag.field,[a]);else s.push(a)}for(let[a,s]of r)if(s.length>1)gt(`multiple flags provide "${a}": ${s.map((c)=>Yn(c.option)).join(", ")}. Pass only one.`);let o=n.filter((a)=>a.source==="stdin");if(o.length>1)gt(`at most one field may read from stdin per invocation: ${o.map((a)=>Yn(a.option)).join(", ")}.`);let i={};for(let a of n)i[a.flag.field]=await rM(a);return i}function oM(e){return e.options.map(Yn).join(" or ")}async function iM(e,t,n,r){let o=nM(e,t.step),i=o==null?`${t.field} (${t.step})`:`${t.field} (${t.step}: ${o})`;if(t.discover!=null){let a=await b(r().connectors.discover({kind:e,key:t.discover,fields:{...n}})),s=a.length===1?a[0]:void 0;if(s!=null)return yt(`Using the only ${t.field}: ${s.label} (${s.value})`),s.value;if(a.length>1){let c=a.map((d)=>({label:d.description==null?d.label:`${d.label} - ${d.description}`,value:d.value}));return Ui(i,c,Po==null?{output:process.stderr}:{ask:Po,output:process.stderr})}}if(t.secret)return Dc(`${i}: `,Po);return E_(`${i}: `,Po)}async function aM(e,t,n){let r=[];for(let o of Rr(e)){if(t[o.field]!=null||o.optional)continue;if(!co()){r.push(o);continue}t[o.field]=await iM(e,o,t,n)}if(r.length>0)gt(`missing required field(s): ${r.map((o)=>oM(o)).join(", ")}.`);return t}function sM(e,t){if(!sn(e))Ct(e);let n=Tn(e);if(t==="json")v({error:n.code,message:n.message,data:n.data,hint:n.hint,retryable:n.retryable});else if(Rn(n),n.code==="CONNECTOR_TEST_FAILED")lM(Ye(n.data?.checks));process.exit(n.exitCode)}async function Jn(e,t){try{return await e}catch(n){sM(n,t)}}function _E(e,t){if(!sn(e))Ct(e);let n=Tn(e);if(n.code!=="CONNECTOR_IN_USE")Ct(e);let r=Ye(n.data?.channels).map((o)=>({id:X(o.id)??"",name:X(o.name)??""}));if(t==="json")v({error:n.code,message:n.message,channels:r,hint:n.hint,retryable:n.retryable});else Rn(n),L(["Channel ID","Name"],r.map((o)=>({"Channel ID":o.id,Name:o.name})));process.exit(n.exitCode)}function cM(e){return e.map((t)=>({Check:t.id,OK:t.ok?"yes":"no",Message:t.message??""}))}function lM(e){L(["Check","OK","Message"],e.map((t)=>({Check:X(t.id)??"",OK:t.ok===!0?"yes":"no",Message:X(t.message)??""})))}function dM(e){if(e.ready)return"ready";let t=[];if(!e.verified)t.push("not verified");if(!e.registered)t.push("not registered");if(!e.name_approved)t.push("name pending");return t.join(", ")}function uM(e){let t=[{title:"Connector",rows:[{label:"ID",value:e.id},{label:"Name",value:e.name},{label:"Kind",value:e.kind},{label:"Status",value:e.status},{label:"Account",value:e.account_label},{label:"External ID",value:e.external_id},{label:"Created",value:new Date(e.created_at).toLocaleString()},{label:"Updated",value:new Date(e.updated_at).toLocaleString()},{label:"Last checked",value:e.last_checked_at==null?null:new Date(e.last_checked_at).toLocaleString()},{label:"Last error",value:e.last_error==null?null:`${e.last_error.code}: ${e.last_error.message}`},{label:"Last warning",value:e.last_warning==null?null:e.last_warning.message}]},{title:"Config",rows:Object.entries(e.config).map(([n,r])=>({label:n,value:r}))},{title:"Credentials",rows:Object.entries(e.secret_suffixes).map(([n,r])=>({label:n,value:tM(r)}))},{title:"Webhook",rows:[{label:"URL",value:e.webhook.url},{label:"Verify token",value:e.webhook.verify_token==null?null:"configured"},{label:"Verified at",value:e.webhook.verified_at==null?null:new Date(e.webhook.verified_at).toLocaleString()}]}];if(e.channels.length>0)t.push({title:"Channels",rows:e.channels.map((n)=>({label:n.name,value:`${n.channel_type} (${n.id})`}))});return t}function pM(e,t){let n={...e,webhook:{url:e.webhook.url,verify_token_configured:e.webhook.verify_token!=null,verified_at:e.webhook.verified_at}};return t?N(n,t):n}function mM(e,t){let n={...e,webhook:e.webhook===null?null:{status:e.webhook.status,reason:e.webhook.reason,url:e.webhook.url}};return t?N(n,t):n}function fM(e){if(e===null)return;if(e.status==="subscribed"){yt("Webhook subscribed automatically.");return}let t=e.reason==null?"":` (${e.reason})`;if(yt(`Webhook needs manual setup${t}.`),e.url!=null)yt(` URL: ${e.url}`);yt(" Verify token: see the connector's page in the web app (never printed here).")}function gM(e){let t=Ee(e.properties)??{},n=new Set(Array.isArray(e.required)?e.required.filter((r)=>typeof r==="string"):[]);return Object.entries(t).map(([r,o])=>{let i=Ee(o)??{},a=i["x-niva-secret"]===!0||i.writeOnly===!0;return{name:r,access:a?"secret":"public",required:n.has(r),step:X(i["x-niva-step"])??""}})}function hM(e,t,n){e.command("types").description("List connector types, or describe one kind's fields and setup steps").action(async()=>{let{format:o,fields:i}=S(t.opts()),a=await b(n().connectors.types.list());if(o==="json"){v(i?a.map((s)=>N(s,i)):a);return}L(["Kind","Name","Capabilities"],a.map((s)=>({Kind:s.kind,Name:J$(s.kind),Capabilities:s.provides.join(", ")})))}).command("describe <kind>").description("Show a kind's fields (public/secret, required) and setup steps with their URLs").action(async(o)=>{let{format:i,fields:a}=S(t.opts()),s=Aa(o),c=await b(n().connectors.types.describe({kind:s}));if(i==="json"){v(a?N(c,a):c);return}J([{title:"Type",rows:[{label:"Kind",value:c.kind},{label:"Version",value:c.version},{label:"Auth",value:c.auth_strategy},{label:"Category",value:c.category},{label:"Module",value:c.module},{label:"Docs",value:c.docs_path},{label:"Provides",value:c.provides.join(", ")},{label:"Discover",value:c.discover.join(", ")||"-"}]}]),L(["Field","Access","Required","Step"],gM(c.fields_json_schema).map((d)=>({Field:d.name,Access:d.access,Required:d.required?"yes":"no",Step:d.step}))),L(["Setup step","Title","URL"],c.setup.map((d)=>({"Setup step":d.id,Title:d.title_key,URL:d.url??"-"})))})}function yM(e,t,n){e.command("list").description("List connectors with their kind, status, account and channel count").action(async()=>{let{format:r,fields:o}=S(t.opts()),i=await b(n().connectors.list());if(r==="json"){v(o?i.map((a)=>N(a,o)):i);return}L(["ID","Name","Kind","Status","Account","Channels"],i.map((a)=>({ID:a.id,Name:a.name,Kind:a.kind,Status:a.status,Account:a.account_label??"-",Channels:a.channel_count})))})}function _M(e,t,n){e.command("show <id>").description("Show a connector's details, credentials suffixes and webhook status").action(async(r)=>{let{format:o,fields:i}=S(t.opts()),a=await b(n().connectors.get({connector_id:Oe(r)}));if(o==="json"){v(pM(a,i));return}J(uM(a))})}function bM(e){if(e===void 0)return"-";return e?"yes":"no"}function vM(e,t,n){let r=e.command("agents").description("Voice agents of a connector: list them, activate or deactivate an ElevenLabs agent's number");r.command("list <id>",{isDefault:!0}).description("List the voice agents of a connector that provides voice.agent; Ready says whether an activated agent can take calls").action(async(o)=>{let{format:i,fields:a}=S(t.opts()),s=await b(n().connectors.voiceAgents({connector_id:Oe(o)}));if(i==="json"){v(a?{agents:s.agents.map((c)=>N(c,a))}:s);return}L(["ID","Name","Channel","Ready","Updated"],s.agents.map((c)=>({ID:c.id,Name:c.name,Channel:c.channel,Ready:bM(c.ready),Updated:c.updated_at?.toISOString()??"-"})))});for(let[o,i]of[["activate",!1],["deactivate",!0]])r.command(`${o} <id> <agent_id>`).description(i?"Deactivate an ElevenLabs agent: NIVA removes the SIP number it registered for the agent. Plans can no longer call it.":"Activate an ElevenLabs agent: NIVA registers a SIP number on the account and binds it to the agent. Needed before a plan can call it.").action(async(a,s)=>{let{format:c,fields:d}=S(t.opts()),u=await Jn(n().connectors.agentNumbers.set({connector_id:Oe(a),agent_id:s,remove:i}),c);if(c==="json"){v(d?N(u,d):u);return}O(`Agent ${s} ${i?"deactivated":"activated"} on connector ${u.name} (${u.id})`)})}function SM(e,t,n){e.command("senders <id>").description("List the SMS senders (Messaging Services and numbers) of a connector that provides sms.send").action(async(r)=>{let{format:o,fields:i}=S(t.opts()),a=await b(n().connectors.senders.list({connector_id:Oe(r)}));if(o==="json"){v(i?a.map((s)=>N(s,i)):a);return}L(["ID","Label","Kind","Number","SMS","Brazil"],a.map((s)=>({ID:s.id,Label:s.label,Kind:s.kind==="messaging_service"?"Messaging Service":"Number",Number:s.number??"-",SMS:s.capabilities.sms?"yes":"no",Brazil:s.brazil_p2p_only?"p2p only":"-"})))})}function xM(e,t,n){e.command("verify-services <id>").description("List the Twilio Verify Services of a connector that provides verify.otp").action(async(r)=>{let{format:o,fields:i}=S(t.opts()),a=await b(n().connectors.verifyServices.list({connector_id:Oe(r)}));if(o==="json"){v(i?a.map((s)=>N(s,i)):a);return}L(["SID","Name","Code length","Channels"],a.map((s)=>({SID:s.sid,Name:s.friendly_name,"Code length":s.code_length??"-",Channels:s.channels.join(", ")})))})}function EM(e,t,n){e.command("test <id>").description("Run a connector's health test; exits 1 when any check fails").action(async(r)=>{let{format:o,fields:i}=S(t.opts()),a=await b(n().connectors.test({connector_id:Oe(r)}));if(o==="json")v(i?N(a,i):a);else if(L(["Check","OK","Message"],cM(a.health.checks)),a.health.ok)O(`Connector test passed: ${a.status}`);else C(`Connector test failed: ${a.health.code} - ${a.health.message}`);if(!a.health.ok)process.exit(A.GENERAL_ERROR)})}function wM(e,t,n){let r=e.command("discover <kind> <key>").description("Run a kind's discover function with credentials not yet stored (e.g. wabas)");fp(r),r.action(async(o,i,a)=>{let s=Aa(o);gp(a,s);let{format:c,fields:d}=S(t.opts()),u=await hp(a,s),m=await b(n().connectors.discover({kind:s,key:i,fields:u}));if(c==="json"){v(d?m.map((y)=>N(y,d)):m);return}L(["Value","Label","Description"],m.map((y)=>({Value:y.value,Label:y.label,Description:y.description??"-"})))})}function CM(e,t,n){let r=e.command("create <kind>").description("Create a connector; credentials come from --<field>-env/--<field>-stdin or a hidden prompt").requiredOption("--name <name>","Human label shown in the UI");fp(r),r.action(async(o,i)=>{let a=Aa(o);gp(i,a);let{format:s,fields:c}=S(t.opts()),d=await hp(i,a),u=await aM(a,d,n),m=await Jn(n().connectors.create({kind:a,name:i.name,fields:u}),s);if(s==="json"){v(mM(m,c));return}O(`Connector created: ${m.name} (${m.id})`),fM(m.webhook)})}function AM(e,t,n){let r=e.command("update <id>").description("Rename a connector or rotate fields; only the flags given are sent").option("--name <name>","New human label");fp(r),r.action(async(o,i)=>{let{format:a,fields:s}=S(t.opts()),c={connector_id:Oe(o)};if(i.name!=null)c.name=i.name;if(uE(i)){let u=await b(n().connectors.get({connector_id:Oe(o)})),m=Aa(u.kind);gp(i,m),c.fields=await hp(i,m)}let d=await Jn(n().connectors.update(c),a);if(a==="json"){v(s?N(d,s):d);return}O(`Connector updated: ${d.name} (${d.id})`)})}function TM(e,t,n){for(let[r,o]of[["enable",!0],["disable",!1]])e.command(`${r} <id>`).description(`${o?"Enable":"Disable"} a connector`).action(async(i)=>{let{format:a,fields:s}=S(t.opts()),c=await b(n().connectors.setEnabled({connector_id:Oe(i),enabled:o}));if(a==="json"){v(s?N(c,s):c);return}O(`Connector ${o?"enabled":"disabled"}: ${c.name} (${c.status})`)})}function RM(e,t,n){e.command("delete <id>").description("Delete a connector; blocked and explained when a channel still references it").action(async(r)=>{let{format:o}=S(t.opts()),i=t.opts().yes===!0;await Ce(`Delete connector ${r}?`,{yes:i});try{await n().connectors.delete({connector_id:Oe(r)})}catch(a){_E(a,o)}if(o==="json"){v({id:r,deleted:!0});return}O(`Connector deleted: ${r}`)})}function IM(e,t,n){let r=e.command("numbers <id>").description("WhatsApp phone numbers of a connector, with readiness and the bound channel").option("--refresh","Bypass the 5-minute cache and read the numbers again");r.action(async(o,i)=>{let{format:a,fields:s}=S(t.opts()),c=await b(n().connectors.phoneNumbers.list({connector_id:Oe(o),refresh:i.refresh===!0}));if(a==="json"){v(s?c.map((d)=>N(d,s)):c);return}L(["ID","Number","Name","Readiness","Channel"],c.map((d)=>({ID:d.id,Number:d.display_phone_number,Name:d.verified_name,Readiness:dM(d.readiness),Channel:d.channel==null?"-":d.channel.name})))}),r.command("request-code <id> <phone_number_id>").description("Ask Meta to send the phone number's ownership code by SMS or voice").requiredOption("--method <method>","sms or voice").option("--language <language>","Language for the message","pt_BR").action(async(o,i,a)=>{let s=kM(a.method),{format:c}=S(t.opts());if(await b(n().connectors.phoneNumbers.requestCode({connector_id:Oe(o),phone_number_id:i,method:s,language:a.language})),c==="json"){v({success:!0,phone_number_id:i});return}O(`Verification code requested for ${i} by ${a.method}.`)}),r.command("verify <id> <phone_number_id>").description("Submit the 6-digit ownership code Meta sent").requiredOption("--code <code>","The 6-digit code").action(async(o,i,a)=>{if(!/^\d{6}$/u.test(a.code))gt("--code must be the 6-digit code Meta sent.");let{format:s}=S(t.opts());if(await b(n().connectors.phoneNumbers.verifyCode({connector_id:Oe(o),phone_number_id:i,code:a.code})),s==="json"){v({success:!0,phone_number_id:i});return}O(`Phone number verified: ${i}`)}),r.command("register <id> <phone_number_id>").description("Register a phone number on the Cloud API with its 6-digit PIN").option("--pin-stdin","Read the PIN from stdin").option("--pin-env <VAR>","Read the PIN from an environment variable").action(async(o,i,a)=>{let s=await PM(a),{format:c}=S(t.opts());if(await b(n().connectors.phoneNumbers.register({connector_id:Oe(o),phone_number_id:i,pin:s})),c==="json"){v({success:!0,phone_number_id:i});return}O(`Phone number registered: ${i}`)})}function NM(e){if(e.webhook==="this_connector")return"this connector";if(e.webhook==="other")return`other (${e.other_webhook_host??"unknown host"})`;return"none"}function hE(e){if(e===void 0)return;let t=e.replaceAll(/[\s+()-]/gu,"");if(!/^\d{8,15}$/u.test(t))gt("--number must be the phone number with country code, digits only.");return t}function yE(e,t){if(t.state==="open"){O(`Instance ${e} is already paired.`);return}if(t.pairingCode!==null)O(`Pairing code for ${e}: ${t.pairingCode}`),D("On the phone: WhatsApp > Linked devices > Link a device > Link with phone number instead.");if(t.qrCode!==null)D(`QR code (raw): ${t.qrCode}`);D(`To scan the QR code, open the connector in the web screen (Settings > Connectors). Run \`niva connectors instances list <id>\` until ${e} shows open.`)}function OM(e,t,n){let r=e.command("instances").description("WhatsApp instances (one per number) of an Evolution API connector: list, create, pair, adopt, release");r.command("list <id>",{isDefault:!0}).description("List the instances of the gateway, with the paired number, state and who their webhook delivers to").action(async(o)=>{let{format:i,fields:a}=S(t.opts()),s=await b(n().connectors.evolution.instances.list({connector_id:Oe(o)}));if(i==="json"){v(a?s.map((c)=>N(c,a)):s);return}L(["Name","Number","Profile","State","Webhook"],s.map((c)=>({Name:c.name,Number:c.display_phone_number===""?"-":c.display_phone_number,Profile:c.profile_name??"-",State:c.state,Webhook:NM(c)})))}),r.command("create <id> <name>").description("Create an instance on the gateway with the NIVA webhook already set. A person must then pair it on the phone (pairing code with --number, or the QR in the web screen)").option("--number <phone>","Phone number with country code, digits only; also issues a pairing code").action(async(o,i,a)=>{let s=hE(a.number),{format:c,fields:d}=S(t.opts()),u=await Jn(n().connectors.evolution.instances.create({connector_id:Oe(o),name:i}),c),m=s===void 0?null:await Jn(n().connectors.evolution.instances.connect({connector_id:Oe(o),name:i,phone_number:s}),c);if(c==="json"){let y={...u,pairing_code:m?.pairing_code??null};v(d?N(y,d):y);return}O(`Instance created: ${u.name}`),yE(u.name,{state:m?.state??u.state,pairingCode:m?.pairing_code??null,qrCode:u.qr?.code??null})}),r.command("connect <id> <name>").description("Get a new QR code or pairing code for an instance that is not paired yet; a person pairs it on the phone").option("--number <phone>","Phone number with country code, digits only; issues a pairing code").action(async(o,i,a)=>{let s=hE(a.number),{format:c,fields:d}=S(t.opts()),u=await Jn(n().connectors.evolution.instances.connect({connector_id:Oe(o),name:i,...s===void 0?{}:{phone_number:s}}),c);if(c==="json"){v(d?N(u,d):u);return}yE(i,{state:u.state,pairingCode:u.pairing_code,qrCode:null})}),r.command("adopt <id> <names...>").description("Bring existing instances under this connector. Each instance has ONE webhook: adopting REPLACES the current one (an n8n flow stops receiving messages)").action(async(o,i)=>{let{format:a,fields:s}=S(t.opts()),c=t.opts().yes===!0;await Ce(`Point the webhook of ${i.join(", ")} at connector ${o}? This replaces whatever each one delivers to now.`,{yes:c});let d=await Jn(n().connectors.evolution.instances.adopt({connector_id:Oe(o),names:i}),a),u=d.results.some((m)=>!m.ok);if(a==="json")v(s?{results:d.results.map((m)=>N(m,s))}:d);else L(["Name","Result","Error"],d.results.map((m)=>({Name:m.name,Result:m.ok?"adopted":"failed",Error:m.error??"-"})));if(u)process.exit(A.GENERAL_ERROR)}),r.command("release <id> <name>").description("Turn off the NIVA webhook of an instance. The instance stays on the gateway and stays paired").action(async(o,i)=>{let{format:a}=S(t.opts()),s=t.opts().yes===!0;await Ce(`Release instance ${i} from connector ${o}?`,{yes:s});try{await n().connectors.evolution.instances.release({connector_id:Oe(o),name:i})}catch(c){_E(c,a)}if(a==="json"){v({name:i,released:!0});return}O(`Instance released: ${i}`)})}function kM(e){let t=e.toUpperCase();if(t==="SMS"||t==="VOICE")return t;gt(`--method must be sms or voice (got "${e}").`)}async function DM(e){if(e.pinEnv!=null){let t=process.env[e.pinEnv];if(t==null||t==="")gt(`environment variable ${e.pinEnv} is not set or empty.`);return t}if(e.pinStdin===!0)return(await Fe()).replace(/\r?\n$/,"");if(co())return Dc("WhatsApp registration PIN (6 digits): ",Po);gt("no PIN given - pass --pin-env <VAR>, --pin-stdin, or run from a TTY.")}async function PM(e){if(e.pinStdin===!0&&e.pinEnv!=null)gt("--pin-stdin and --pin-env are mutually exclusive.");let t=await DM(e);if(!/^\d{6}$/u.test(t))gt("the PIN must be the 6-digit number Meta gave you.");return t}function bE(e,t){let n=e.createCommand("connectors").description("Connectors (WhatsApp, and the kinds that follow)");n.configureOutput({outputError:(r,o)=>o(eM(r))}),e.addCommand(n),hM(n,e,t),yM(n,e,t),_M(n,e,t),vM(n,e,t),SM(n,e,t),xM(n,e,t),EM(n,e,t),wM(n,e,t),CM(n,e,t),AM(n,e,t),TM(n,e,t),RM(n,e,t),IM(n,e,t),OM(n,e,t)}function vE(e,t){let n=e.command("conversations").description("Inspect Desk conversations: requests for human work over a call or chat (requires the desk module)");n.command("list").description("List conversations").option("--attendant <attendant_id>","Only conversations handled by this attendant").option("--channel <c>","Filter by channel (voice, chat)").option("--status <s>","Filter by status").option("--outcome <o>","Filter by outcome").option("--call <call_id>","Only conversations over this call").option("--from <date>","Created from (YYYY-MM-DD or ISO timestamp)").option("--to <date>","Created until (YYYY-MM-DD or ISO timestamp)").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().conversations.list({page:Number(r.page),limit:Number(r.limit),attendant_id:x("attendants",r.attendant),channel:ce(r.channel),status:ce(r.status),outcome:ce(r.outcome),call_record_id:x("call_records",r.call),date_from:r.from,date_to:r.to}));if(o==="json"){v(i?a.items.map((s)=>N(s,i)):a);return}L(["ID","Channel","Status","Outcome","Attendant","Wait","Talk","Joined"],a.items.map((s)=>({ID:s.id,Channel:s.channel,Status:s.status,Outcome:s.outcome??"—",Attendant:s.attendant_id??"—",Wait:ke(s.wait_ms),Talk:ke(s.talk_ms),Joined:Me(s.joined_at)}))),te(a)}),n.command("show <conversation_id>").description("Show one conversation").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().conversations.getById({conversation_id:x("conversations",r)}));if(o==="json"){v(i?N(a,i):a);return}J([{title:"Conversation",rows:[{label:"ID",value:a.id},{label:"Channel",value:a.channel},{label:"Status",value:a.status},{label:"Outcome",value:a.outcome},{label:"Call",value:a.call_record_id},{label:"Chat session",value:a.session_key},{label:"Contact",value:a.contact_id},{label:"Attendant",value:a.attendant_id},{label:"Refusals",value:a.refusals}]},{title:"Times",rows:[{label:"Joined",value:Me(a.joined_at)},{label:"Wait",value:ke(a.wait_ms)},{label:"Talk",value:ke(a.talk_ms)},{label:"Wrap-up",value:ke(a.wrap_ms)}]},{title:"Wrap-up",rows:[{label:"Disposition",value:a.disposition_id},{label:"Note",value:a.note},{label:"AI summary",value:a.ai_summary}]}])})}var Rt=on(jt(),1);function $o(e){return e.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 $M(e){if(e==null)return"";if(e.missed>0)return`${e.total} (${e.missed} missed)`;return`${e.total}`}function MM(e,t){if(e>t)return"↑";if(e<t)return"↓";return"→"}function LM(e){let t=e.avg_score!=null?Number(e.avg_score):null,n=e.previous_avg_score!=null?Number(e.previous_avg_score):null,r=t!=null&&t>0?"+":"",o=t!=null?`${r}${t.toFixed(2)}`:"—",i="";if(n!=null&&t!=null){let a=MM(t,n);i=` (prev: ${n>0?"+":""}${n.toFixed(2)} ${a})`}return` Avg Score: ${o}${i}`}function SE(e,t){let n=e.command("dashboard").description("Dashboard and monitoring");n.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(r)=>{let{format:o,fields:i}=S(e.opts()),{date_from:a,date_to:s}=_t(r),c=await b(t().dashboard.metrics({date_from:a,date_to:s}));if(o==="json"){let d=i?N(c,i):c;v(d);return}if(console.log(`Period: ${a} → ${s}`),console.log(`Total calls: ${c.current.total_calls}`),console.log(`Answered: ${c.current.answered}`),console.log(`Missed: ${c.current.missed}`),c.current.avg_duration_ms!=null)console.log(`Avg duration: ${ke(c.current.avg_duration_ms)}`)}),$o(n.command("sentiment").description("Show sentiment distribution for calls")).action(async(r)=>{let{format:o,fields:i}=S(e.opts()),{date_from:a,date_to:s}=_t(r),c=await b(t().dashboard.speechSentiment({date_from:a,date_to:s,visual_plan_id:x("visual_plans",r.plan),channel_id:x("channels",r.phone)}));if(o==="json"){let m=i?N(c,i):c;v(m);return}if(console.log(Rt.default.bold("Sentiment Overview")),console.log(`Analyzed: ${c.analyzed_count} calls`),!c.has_enough_data){D(`
|
|
113
|
-
Not enough data (need ${c.minimum_required}, have ${c.analyzed_count})`);return}console.log("");let d=c.distribution,u=Math.max(d.positive,d.neutral,d.negative,d.mixed);wt(Rt.default.green("positive"),d.positive,u),wt(Rt.default.yellow("neutral"),d.neutral,u),wt(Rt.default.red("negative"),d.negative,u),wt(Rt.default.blue("mixed"),d.mixed,u),console.log(""),console.log(
|
|
114
|
-
Not enough data.`);return}console.log("");let d=Math.max(...c.topics.map((u)=>u.call_count));for(let u of c.topics){let m=c.analyzed_count>0?Math.round(u.call_count/c.analyzed_count*100):0,y=An(u.call_count,d);console.log(` ${u.label.padEnd(16)} ${y} ${u.call_count} calls (${m}%) confidence: ${u.avg_confidence.toFixed(2)}`)}}),$o(n.command("intents").description("Show detected intents from call transcriptions")).option("--limit <n>","Max intents to show","10").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),{date_from:a,date_to:s}=
|
|
115
|
-
Not enough data.`);return}console.log("");let d=Math.max(...c.intents.map((u)=>u.call_count));for(let u of c.intents)wt(u.label,u.call_count,d)}),$o(n.command("trend").description("Show sentiment trend over time")).option("--granularity <g>","Granularity: hour or day","day").action(async(r)=>{let{format:o}=S(e.opts()),{date_from:i,date_to:a}=
|
|
116
|
-
No data available.`);return}console.log(""),L(["Date","Analyzed","Positive","Neutral","Negative","Avg Score"],s.map((c)=>{let d=new Date(c.bucket),u=`${String(d.getDate()).padStart(2,"0")}/${String(d.getMonth()+1).padStart(2,"0")}`,m=c.avg_score!=null&&c.avg_score>0?"+":"",y=c.avg_score!=null?`${m}${c.avg_score.toFixed(2)}`:"—";return{Date:u,Analyzed:c.analyzed,Positive:c.positive,Neutral:c.neutral,Negative:c.negative,"Avg Score":y}}))}),$o(n.command("weekday-hour").description("Show call volume heatmap by weekday and hour")).action(async(r)=>{let{format:o}=S(e.opts()),{date_from:i,date_to:a}=
|
|
117
|
-
No data available.`);return}let c=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],d=new Map(s.cells.map((m)=>[`${m.weekday}:${m.hour}`,m])),u=Array.from({length:24},(m,y)=>String(y).padStart(2,"0"));console.log(""),L(["Weekday",...u],c.map((m,y)=>{let _={Weekday:m};for(let E of u)_[E]
|
|
118
|
-
No data available.`);return}console.log(""),L(["Plan","Total","Answered","Avg Duration"],c.map((d)=>({Plan:d.visual_plan_name??"—",Total:d.total,Answered:`${d.answered} (${d.total>0?Math.round(d.answered/d.total*100):0}%)`,"Avg Duration":ke(d.avg_duration_ms)})))})}function xE(e,t){e.command("desk").description("The Desk's copilot (requires the desk, ai and copilot modules)").command("copilot").description("How the Mesa copilot is doing").command("stats").description("What the copilot's suggestions amounted to in a window: replies, answers, wrap-ups, latency, tokens").requiredOption("--from <date>","Start of the window, inclusive (ISO timestamp or YYYY-MM-DD)").requiredOption("--to <date>","End of the window, exclusive (ISO timestamp; YYYY-MM-DD is that day's end). Up to 93 days").option("--queue <queue_id>","Only the conversations of this queue").action(async(o)=>{let{format:i,fields:a}=S(e.opts()),{date_from:s,date_to:c}=_t({from:o.from,to:o.to}),d=await b(t().desk.copilot.stats({from:s,to:c,queue_id:x("queues",o.queue)}));if(i==="json"){v(a?N(d,a):d);return}let u=d.latency_ms===null?"—":`${d.latency_ms.p50} / ${d.latency_ms.p95}`;J([{title:"Replies",rows:[{label:"Shown",value:d.replies.shown},{label:"Used",value:d.replies.used},{label:"Edited",value:d.replies.edited},{label:"Discarded",value:d.replies.discarded},{label:"Ignored",value:d.replies.ignored}]},{title:"Answers",rows:[{label:"Asked",value:d.answers.asked},{label:"Useful",value:d.answers.useful},{label:"Not useful",value:d.answers.not_useful}]},{title:"Wrap-ups",rows:[{label:"Shown",value:d.wrap_ups.shown},{label:"Disposition kept",value:d.wrap_ups.disposition_kept},{label:"Note edited",value:d.wrap_ups.note_edited}]},{title:"Cues",rows:[{label:"Shown",value:d.cues.shown},{label:"Useful",value:d.cues.useful},{label:"Discarded",value:d.cues.discarded}]},{title:"Cost",rows:[{label:"Summaries",value:d.summaries.shown},{label:"Latency p50 / p95 (ms)",value:u},{label:"Input tokens",value:d.tokens.input},{label:"Output tokens",value:d.tokens.output}]}])})}import{readFile as zM}from"node:fs/promises";var EE=1e4;function wE(e,t){let n=e.command("dnc").description("Manage the do-not-call list");n.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(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().dialerDnc.list({page:Number(r.page),limit:Number(r.limit),search:r.search}));if(o==="json"){v(i?a.items.map((s)=>N(s,i)):a);return}L(["ID","Phone","Reason","Added"],a.items.map((s)=>({ID:s.id,Phone:s.phone_number,Reason:s.reason??"—",Added:Me(s.created_at)}))),te(a)}),n.command("add <phone>").description("Add a number to the do-not-call list").option("--reason <r>","Reason for the block").action(async(r,o)=>{let{format:i}=S(e.opts()),a=await b(t().dialerDnc.add({phone_number:r,reason:o.reason}));if(i==="json"){v(a);return}O(`Added ${a.phone_number} to DNC`)}),n.command("remove <ids...>").description("Remove do-not-call entries").action(async(r)=>{let{format:o}=S(e.opts());if(r.length===1){let a=await b(t().dialerDnc.remove({dnc_id:x("dialer_dnc",r[0])}));if(o==="json"){v(a);return}O("Removed DNC entry");return}let i=await b(t().dialerDnc.bulkRemove({ids:x("dialer_dnc",r)}));if(o==="json"){v(i);return}O(`Removed ${i.removed}`)}),n.command("check <phone>").description("Check if a number is on the DNC list (exit 0 = listed, 3 = not listed)").action(async(r)=>{let{format:o}=S(e.opts()),i=await b(t().dialerDnc.list({page:1,limit:20,search:r})),a=r.replaceAll(/\D/g,""),s=a===""?void 0:i.items.find((c)=>{let d=String(c.phone_number).replaceAll(/\D/g,"");return d===a||d.endsWith(a)});if(s!=null){if(o==="json")v(s);else J([{title:"DNC entry",rows:[{label:"ID",value:s.id},{label:"Phone",value:s.phone_number},{label:"Reason",value:s.reason??"—"},{label:"Added",value:new Date(s.created_at).toLocaleString()}]}]);return}if(o==="json")v({listed:!1});else D("Not in DNC list.");process.exit(A.NOT_FOUND)}),n.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(r,o)=>{let{format:i}=S(e.opts()),s=(await zM(r,"utf-8")).split(/\r\n|\n|\r/).map((u)=>u.trim()).filter((u)=>u.length>0&&!u.startsWith("#"));if(s.length===0)C("No phone numbers found in file"),process.exit(A.USAGE_ERROR);let c=0,d=0;for(let u=0;u<s.length;u+=EE){let m=s.slice(u,u+EE),y=await b(t().dialerDnc.bulkImport({numbers:m,reason:o.reason}));c+=y.added,d+=y.skipped}if(i==="json"){v({added:c,skipped:d});return}O(`Added ${c}, skipped ${d}`)})}var ht=on(jt(),1);var FM=new Set(uo);function UM(e){return FM.has(e)}var Ta=(e)=>e==="online"?ht.default.green(e):ht.default.red(e);function jM(e){let t;if(e.is_expired)t=ht.default.red("expired");else if(e.is_in_grace_period)t=ht.default.yellow("grace period");else t=ht.default.green(e.status);let n=e.days_until_expiry!=null?` (${e.days_until_expiry}d remaining)`:"";return` License: ${t}${n}`}var CE=10,VM="unlimited".padEnd(CE);function Ra(e,t,n,r,o){let i=` ${e.padEnd(11)}`;if(n==null)return`${i}${ht.default.dim(VM)} ${t}${r}`;return`${i}${An(t,n,CE)} ${t}/${n}${r} (${Math.round(o)}%)`}function KM(e){let t=[ht.default.bold(" AI Usage:")],{stt:n,tts:r,llm:o}=e;if(n)t.push(Ra("STT:",Math.round(n.current),n.limit," min",n.percentage));if(r)t.push(Ra("TTS:",r.current,r.limit," chars",r.percentage));if(o)t.push(Ra("LLM:",o.current,o.limit," tokens",o.percentage));return t}async function qM(e){try{return(await e().system.fsServiceStatus()).sip_firewall??null}catch{return null}}function AE(e,t){let n=e.command("fs").description("FreeSWITCH status and debug");n.command("status").description("Check system health (server, DB, Redis, FreeSWITCH)").action(async()=>{let{format:r,fields:o}=S(e.opts()),i=await b(t().dashboard.health()),a=await qM(t);if(r==="json"){let s=a?{...i,sip_firewall:a}:i,c=o?N(s,o):s;v(c);return}if(console.log(`Server: ${Ta(i.server)}`),console.log(`PostgreSQL: ${Ta(i.postgres)}`),console.log(`Redis: ${Ta(i.redis)}`),console.log(`FreeSWITCH: ${Ta(i.freeswitch.status)}`),i.freeswitch.uptime!=null&&i.freeswitch.uptime!=="")console.log(` Uptime: ${i.freeswitch.uptime}`);if(i.freeswitch.sessions)console.log(` Sessions: ${i.freeswitch.sessions.active}/${i.freeswitch.sessions.limit}`);if(i.freeswitch.cps)console.log(` CPS: ${i.freeswitch.cps.current}/${i.freeswitch.cps.limit}`);if(i.freeswitch.idleCpu!=null)console.log(` Idle CPU: ${i.freeswitch.idleCpu}%`);if(a)console.log(`SIP firewall: ${a.mode} · allow ${a.allow_entries} · peers ${a.peer_entries} · `+`would drop ${a.would_drop_packets} pkts / dropped ${a.dropped_packets} pkts from ${a.offender_entries} IPs`)}),n.command("channels").description("List active FreeSWITCH channels").action(async()=>{let{format:r,fields:o}=S(e.opts()),i=await b(t().dashboard.activeCalls());if(r==="json"){let a=o?i.map((s)=>N(s,o)):i;v(a);return}if(i.length===0){D("No active channels.");return}L(["UUID","Caller","Plan","Node","Duration"],i.map((a)=>({UUID:a.uuid,Caller:a.callerId,Plan:a.planName??"—",Node:a.currentNodeLabel??"—",Duration:a.startedAt?`${Math.round((Date.now()-new Date(a.startedAt).getTime())/1000)}s`:"—"}))),D(`${i.length} active channel(s)`)}),n.command("registrations").description("List SIP registrations").action(async()=>{let{format:r,fields:o}=S(e.opts()),i=await b(t().testCall.registrations());if(r==="json"){let a=o?i.map((s)=>N(s,o)):i;v(a);return}if(i.length===0){D("No SIP registrations.");return}L(["Extension","Agent"],i.map((a)=>({Extension:a.extension,Agent:a.agent??"—"})))}),n.command("dump <uuid>").description("Dump all channel variables for an active call").action(async(r)=>{let{format:o}=S(e.opts()),i=await b(t().dashboard.fsDumpChannel({uuid:r}));if(Object.keys(i).length===0){if(o==="json")v({});else C(`Channel ${r} not found.`);process.exit(A.NOT_FOUND)}if(o==="json"){v(i);return}console.log(ht.default.bold(`Channel Variables — ${r}`)),console.log("");for(let[a,s]of Object.entries(i))console.log(` ${ht.default.cyan(a.padEnd(40))} ${s}`)}),n.command("sofia").description("Show SIP profile status").action(async()=>{let{format:r}=S(e.opts()),o=await b(t().dashboard.fsSofiaStatus());if(r==="json"){v(o);return}if(o.length===0){D("No Sofia profiles configured.");return}console.log(ht.default.bold("Sofia SIP Profiles")),console.log(""),L(["Name","Type","Data","State"],o.map((i)=>({Name:i.name,Type:i.type,Data:i.data,State:i.state})))}),n.command("show <entity>").description(`Show FreeSWITCH data (${uo.join(", ")})`).action(async(r)=>{if(!UM(r))C(`Unknown entity "${r}". Allowed: ${uo.join(", ")}`),process.exit(A.USAGE_ERROR);let{format:o}=S(e.opts()),i=await b(t().dashboard.fsShow({entity:r}));if(o==="json"){v(i);return}console.log(ht.default.bold(`FreeSWITCH: show ${r}`)),console.log(""),console.log(JSON.stringify(i,null,2))}),n.command("capacity").description("Show system capacity: channels, license, AI usage").action(async()=>{let{format:r,fields:o}=S(e.opts()),i=await b(t().dashboard.capacityStatus());if(r==="json"){let s=o?N(i,o):i;v(s);return}console.log(ht.default.bold("System Capacity")),console.log("");let a=i.channels.total;if(console.log(Ra("Channels:",a.active,a.limit,"",a.percentage??0)),console.log(jM(i.license)),i.ai_usage){console.log("");for(let s of KM(i.ai_usage))console.log(s)}})}import{readFile as BM}from"node:fs/promises";async function yp(e){try{return e==="-"?await Fe():await BM(e,"utf-8")}catch{C(`Cannot read "${e}".`),process.exit(A.USAGE_ERROR)}}async function Ir(e){let t=await yp(e),n;try{n=JSON.parse(t)}catch{C(`Invalid JSON in "${e}".`),process.exit(A.USAGE_ERROR)}if(!se(n))C(`Invalid body in "${e}": expected a JSON object.`),process.exit(A.USAGE_ERROR);return n}var HM=["fixed:MM-DD every year on that day, e.g. fixed:03-23","single:YYYY-MM-DD one dated occurrence, or single:YYYY-MM-DD..YYYY-MM-DD for a range","easter:N N days after (negative: before) Easter, e.g. easter:-47 is Carnival","nth:MONTH:WEEKDAY:N the Nth weekday of a month (WEEKDAY 0 = Sunday, N 1-5 or -1 for the last), e.g. nth:11:4:4",`json the API rule object, e.g. '{"kind":"easter","offset_days":-2}'`].join(`
|
|
119
|
-
`);function
|
|
94
|
+
`}function VD(e){let t="";for(let n of e??[])kS(n),t+=`: ${n}
|
|
95
|
+
`;return t}function To(e){let t="";if(t+=VD(e.comments),e.event!==void 0)UD(e.event),t+=`event: ${e.event}
|
|
96
|
+
`;if(e.retry!==void 0)NS(e.retry),t+=`retry: ${e.retry}
|
|
97
|
+
`;if(e.id!==void 0)OS(e.id),t+=`id: ${e.id}
|
|
98
|
+
`;return t+=jD(e.data),t+=`
|
|
99
|
+
`,t}var DS=Symbol("ORPC_EVENT_SOURCE_META");function qn(e,t){if(t.id===void 0&&t.retry===void 0&&!t.comments?.length)return e;if(t.id!==void 0)OS(t.id);if(t.retry!==void 0)NS(t.retry);if(t.comments!==void 0)for(let n of t.comments)kS(n);return new Proxy(e,{get(n,r,o){if(r===DS)return t;return Reflect.get(n,r,o)}})}function xr(e){return zt(e)?Reflect.get(e,DS):void 0}function PS(e,t="inline"){let n=e.replace(/[^\x20-\x7E]/g,"_").replace(/"/g,"\\\""),r=encodeURIComponent(e).replace(/['()*]/g,(o)=>`%${o.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(7C|60|5E)/g,(o,i)=>String.fromCharCode(Number.parseInt(i,16)));return`${t}; filename="${n}"; filename*=utf-8''${r}`}function $S(e){let t=e.match(/filename\*=(UTF-8'')?([^;]*)/i);if(t&&typeof t[2]==="string")return CS(t[2]);let n=e.match(/filename="((?:\\"|[^"])*)"/i);if(n&&typeof n[1]==="string")return n[1].replace(/\\"/g,'"')}function MS(e,t){let n={...e};for(let r in t)if(Array.isArray(t[r]))n[r]=[...Fn(n[r]),...t[r]];else if(t[r]!==void 0)if(Array.isArray(n[r]))n[r]=[...n[r],t[r]];else if(n[r]!==void 0)n[r]=[n[r],t[r]];else n[r]=t[r];return n}function Eu(e,t){let n=async(r)=>{let o=await t.error(r);if(o!==r){let i=xr(r);if(i&&zt(o))o=qn(o,i)}return o};return new jn(async()=>{let{done:r,value:o}=await(async()=>{try{return await e.next()}catch(a){throw await n(a)}})(),i=await t.value(o,r);if(i!==o){let a=xr(o);if(a&&zt(i))i=qn(i,a)}return{done:r,value:i}},async()=>{try{await e.return?.()}catch(r){throw await n(r)}})}function KD(e){return{...e,context:e.context??{}}}function Qt(e,t){return(async()=>{let n;try{let r=await e;while(!0){let{done:o,value:i}=await r.next();if(o){let a=i;n=[null,a,!0],t.onSuccess?.(a);break}t.onEvent(i)}}catch(r){if(n=[r,void 0,!1],!t.onError&&!t.onFinish)throw r;t.onError?.(r)}finally{t.onFinish?.(n)}})(),async()=>{await(await e)?.return?.()}}function Bn(e,t={}){let n=t.path??[],o=new Proxy(async(...[i,a={}])=>await e.call(n,i,KD(a)),{get(i,a){if(typeof a!=="string"||AS.has(a))return Reflect.get(i,a);return Bn(e,{...t,path:[...n,a]})}});return _u(o)}function qD(e,t={}){let r=e?.pipeThrough(new TextDecoderStream).pipeThrough(new Su)?.getReader(),o,i=!1;return new jn(async()=>{o??=fa("consume_event_iterator_stream");try{while(!0){if(r===void 0)return{done:!0,value:void 0};let{done:a,value:s}=await zn(o,()=>r.read());if(a){if(i)throw new fu("Stream was cancelled");return{done:!0,value:void 0}}switch(s.event??(s.data!==void 0?"message":void 0)){case"message":{let d=Eo(s.data);if(zt(d))d=qn(d,s);return o?.addEvent("message"),{done:!1,value:d}}case"error":{let d=new Xt({data:Eo(s.data)});throw d=qn(d,s),o?.addEvent("error"),d}case"done":case"close":{let d=Eo(s.data);if(zt(d))d=qn(d,s);return o?.addEvent("done"),{done:!0,value:d}}default:o?.addEvent("maybe_keepalive")}}}catch(a){if(!(a instanceof Xt))gn(o,a,t);throw a}},async(a)=>{try{if(a!=="next")i=!0,o?.addEvent("cancelled");await zn(o,()=>r?.cancel())}catch(s){throw gn(o,s,t),s}finally{o?.end()}})}function BD(e,t={}){let n=t.eventIteratorKeepAliveEnabled??!0,r=t.eventIteratorKeepAliveInterval??5000,o=t.eventIteratorKeepAliveComment??"",i=t.eventIteratorInitialCommentEnabled??!0,a=t.eventIteratorInitialComment??"",s=!1,c,d;return new ReadableStream({start(m){if(d=fa("stream_event_iterator"),i)m.enqueue(To({comments:[a]}))},async pull(m){try{if(n)c=setInterval(()=>{m.enqueue(To({comments:[o]})),d?.addEvent("keepalive")},r);let y=await zn(d,()=>e.next());if(clearInterval(c),s)return;let _=xr(y.value);if(!y.done||y.value!==void 0||_!==void 0){let E=y.done?"done":"message";m.enqueue(To({..._,event:E,data:Vn(y.value)})),d?.addEvent(E)}if(y.done)m.close(),d?.end()}catch(y){if(clearInterval(c),s)return;if(y instanceof Xt)m.enqueue(To({...xr(y),event:"error",data:Vn(y.data)})),d?.addEvent("error"),m.close();else gn(d,y),m.error(y);d?.end()}},async cancel(){try{s=!0,clearInterval(c),d?.addEvent("cancelled"),await zn(d,()=>e.return?.())}catch(m){throw gn(d,m),m}finally{d?.end()}}}).pipeThrough(new TextEncoderStream)}function HD(e,t={}){return Un({name:"parse_standard_body",signal:t.signal},async()=>{let n=e.headers.get("content-disposition");if(typeof n==="string"){let i=$S(n)??"blob",a=await e.blob();return new File([a],i,{type:a.type})}let r=e.headers.get("content-type");if(!r||r.startsWith("application/json")){let i=await e.text();return Eo(i)}if(r.startsWith("multipart/form-data"))return await e.formData();if(r.startsWith("application/x-www-form-urlencoded")){let i=await e.text();return new URLSearchParams(i)}if(r.startsWith("text/event-stream"))return qD(e.body,t);if(r.startsWith("text/plain"))return await e.text();let o=await e.blob();return new File([o],"blob",{type:o.type})})}function WD(e,t,n={}){if(e instanceof ReadableStream)return e;let r=t.get("content-disposition");if(t.delete("content-type"),t.delete("content-disposition"),e===void 0)return;if(e instanceof Blob)return t.set("content-type",e.type),t.set("content-length",e.size.toString()),t.set("content-disposition",r??PS(e instanceof File?e.name:"blob")),e;if(e instanceof FormData)return e;if(e instanceof URLSearchParams)return e;if(Jt(e))return t.set("content-type","text/event-stream"),BD(e,n);return t.set("content-type","application/json"),Vn(e)}function wu(e,t={}){return e.forEach((n,r)=>{if(Array.isArray(t[r]))t[r].push(n);else if(t[r]!==void 0)t[r]=[t[r],n];else t[r]=n}),t}function GD(e,t=new Headers){for(let[n,r]of Object.entries(e))if(Array.isArray(r))for(let o of r)t.append(n,o);else if(r!==void 0)t.append(n,r);return t}function LS(e,t={}){let n=GD(e.headers),r=WD(e.body,n,t);return new Request(e.url,{signal:e.signal,method:e.method,headers:n,body:r})}function zS(e,t={}){return{body:gu(()=>HD(e,t)),status:e.status,get headers(){let n=wu(e.headers);return Object.defineProperty(this,"headers",{value:n,writable:!0}),n},set headers(n){Object.defineProperty(this,"headers",{value:n,writable:!0})}}}class _a{plugins;constructor(e=[]){this.plugins=[...e].sort((t,n)=>(t.order??0)-(n.order??0))}init(e){for(let t of this.plugins)t.init?.(e)}}class FS{constructor(e,t,n={}){this.codec=e,this.sender=t,new _a(n.plugins).init(n),this.interceptors=Fn(n.interceptors),this.clientInterceptors=Fn(n.clientInterceptors)}interceptors;clientInterceptors;call(e,t,n){return Un({name:`${mu}.${e.join("/")}`,signal:n.signal},(r)=>{if(r?.setAttribute("rpc.system",mu),r?.setAttribute("rpc.method",e.join(".")),Jt(t))t=hu({name:"consume_event_iterator_input",signal:n.signal},t);return xo(this.interceptors,{...n,path:e,input:t},async({path:o,input:i,...a})=>{let s=So(),c,d=s?.trace.getActiveSpan()??r;if(d&&s)c=s?.trace.setSpan(s.context.active(),d);let u=await Un({name:"encode_request",context:c},()=>this.codec.encode(o,i,a)),m=await xo(this.clientInterceptors,{...a,input:i,path:o,request:u},({input:_,path:E,request:k,...V})=>Un({name:"send_request",signal:V.signal,context:c},()=>this.sender.call(k,V,E,_))),y=await Un({name:"decode_response",context:c},()=>this.codec.decode(m,a,o,i));if(Jt(y))return hu({name:"consume_event_iterator_output",signal:a.signal},y);return y})})}}var Ve={BIGINT:0,DATE:1,NAN:2,UNDEFINED:3,URL:4,REGEXP:5,SET:6,MAP:7},ZD=new Set(Object.values(Ve)),YD=/^\/(.*)\/([a-z]*)$/;function Ro(e){return TypeError(`Invalid RPC serialized data: ${e}`)}function en(e,t,n){return Ro(`type ${e} (${t}) expects ${n}.`)}class US{customSerializers;constructor(e={}){if(this.customSerializers=e.customJsonSerializers??[],this.customSerializers.length!==new Set(this.customSerializers.map((t)=>t.type)).size)throw Error("Custom serializer type must be unique.")}serialize(e,t=[],n=[],r=[],o=[]){for(let i of this.customSerializers)if(i.condition(e)){let a=this.serialize(i.serialize(e),t,n,r,o);return n.push([i.type,...t]),a}if(e instanceof Blob)return r.push(t),o.push(e),[e,n,r,o];if(typeof e==="bigint")return n.push([Ve.BIGINT,...t]),[e.toString(),n,r,o];if(e instanceof Date){if(n.push([Ve.DATE,...t]),Number.isNaN(e.getTime()))return[null,n,r,o];return[e.toISOString(),n,r,o]}if(Number.isNaN(e))return n.push([Ve.NAN,...t]),[null,n,r,o];if(e instanceof URL)return n.push([Ve.URL,...t]),[e.toString(),n,r,o];if(e instanceof RegExp)return n.push([Ve.REGEXP,...t]),[e.toString(),n,r,o];if(e instanceof Set){let i=this.serialize(Array.from(e),t,n,r,o);return n.push([Ve.SET,...t]),i}if(e instanceof Map){let i=this.serialize(Array.from(e.entries()),t,n,r,o);return n.push([Ve.MAP,...t]),i}if(Array.isArray(e))return[e.map((a,s)=>{if(a===void 0)return n.push([Ve.UNDEFINED,...t,s]),null;return this.serialize(a,[...t,s],n,r,o)[0]}),n,r,o];if(wo(e)){let i={};for(let a in e){if(a==="toJSON"&&typeof e[a]==="function")continue;i[a]=this.serialize(e[a],[...t,a],n,r,o)[0]}return[i,n,r,o]}return[e,n,r,o]}deserialize(e,t,n,r){let o={data:e},i={data:e};if(n&&r)n.forEach((a,s)=>{let c=r(s);if(!(c instanceof Blob))throw Ro(`blob ${s} is not a Blob.`);let d=i,u=o,m="data";a.forEach((y)=>{if(d=d[m],u=yu(u,m,d),m=y,!Object.hasOwn(u,m))throw Ro(`segment "${m}" does not exist.`)}),u[m]=c});for(let a of t){let s=a[0],c=this.customSerializers.find((_)=>_.type===s);if(c===void 0&&!ZD.has(s))continue;let d=i,u=o,m="data";for(let _=1;_<a.length;_++)if(d=d[m],u=yu(u,m,d),m=a[_],!Object.hasOwn(u,m))throw Ro(`segment "${m}" does not exist.`);if(c!==void 0){u[m]=c.deserialize(u[m]);continue}let y=u[m];switch(s){case Ve.BIGINT:{if(typeof y!=="string")throw en(s,"bigint","a string");let _=SS(y,pu);if(_===void 0)throw en(s,"bigint",`a decimal integer string of at most ${pu} digits`);u[m]=_;break}case Ve.DATE:if(typeof y!=="string"&&y!==null)throw en(s,"date","a string or null");u[m]=new Date(y??Number.NaN);break;case Ve.NAN:if(y!==null)throw en(s,"nan","null");u[m]=Number.NaN;break;case Ve.UNDEFINED:if(y!==null)throw en(s,"undefined","null");u[m]=void 0;break;case Ve.URL:if(typeof y!=="string")throw en(s,"url","a string");u[m]=new URL(y);break;case Ve.REGEXP:{if(typeof y!=="string")throw en(s,"regexp","a string");let _=y.match(YD);if(_===null||!ES(_[2]))throw Ro(`type ${s} (regexp) expects a "/pattern/flags" string.`);u[m]=wS(_[1],_[2]);break}case Ve.SET:if(!Array.isArray(y))throw en(s,"set","an array");u[m]=new Set(y);break;case Ve.MAP:if(!Array.isArray(y))throw en(s,"map","an array");u[m]=new Map(y);break}}return o.data}}function JD(e){return`/${e.map(encodeURIComponent).join("/")}`}function XD(e){if(typeof e.forEach==="function")return wu(e);return e}function QD(e){return Object.entries(ha).find(([,t])=>t.status===e)?.[0]??"MALFORMED_ORPC_ERROR_RESPONSE"}class jS{constructor(e,t){this.serializer=e,this.baseUrl=t.url,this.maxUrlLength=t.maxUrlLength??2083,this.fallbackMethod=t.fallbackMethod??"POST",this.expectedMethod=t.method??this.fallbackMethod,this.headers=t.headers??{}}baseUrl;maxUrlLength;fallbackMethod;expectedMethod;headers;async encode(e,t,n){let r=XD(await Co(this.headers,n,e,t));if(n.lastEventId!==void 0)r=MS(r,{"last-event-id":n.lastEventId});let o=await Co(this.expectedMethod,n,e,t),i=await Co(this.baseUrl,n,e,t),a=new URL(i);a.pathname=`${a.pathname.replace(/\/$/,"")}${JD(e)}`;let s=this.serializer.serialize(t);if(o==="GET"&&!(s instanceof FormData)&&!Jt(s)){let c=await Co(this.maxUrlLength,n,e,t),d=new URL(a);if(d.searchParams.append("data",Vn(s)),d.toString().length<=c)return{body:void 0,method:o,headers:r,url:d,signal:n.signal}}return{url:a,method:o==="GET"?this.fallbackMethod:o,headers:r,body:s,signal:n.signal}}async decode(e){let t=!ya(e.status),n=await(async()=>{let r=!1;try{let o=await e.body();return r=!0,this.serializer.deserialize(o)}catch(o){if(!r)throw Error("Cannot parse response body, please check the response body and content-type.",{cause:o});throw Error("Invalid RPC response format.",{cause:o})}})();if(!t){if(bu(n))throw vu(n);throw new Kn(QD(e.status),{status:e.status,data:{...e,body:n}})}return n}}class VS{constructor(e){this.jsonSerializer=e}serialize(e){if(Jt(e))return Eu(e,{value:async(t)=>this.#e(t,!1),error:async(t)=>new Xt({data:this.#e(TS(t).toJSON(),!1),cause:t})});return this.#e(e,!0)}#e(e,t){let[n,r,o,i]=this.jsonSerializer.serialize(e),a=r.length===0?void 0:r;if(!t||i.length===0)return{json:n,meta:a};let s=new FormData;return s.set("data",Vn({json:n,meta:a,maps:o})),i.forEach((c,d)=>{s.set(d.toString(),c)}),s}deserialize(e){if(Jt(e))return Eu(e,{value:async(t)=>this.#t(t),error:async(t)=>{if(!(t instanceof Xt))return t;let n=this.#t(t.data);if(bu(n))return vu(n,{cause:t});return new Xt({data:n,cause:t})}});return this.#t(e)}#t(e){if(e===void 0)return;if(!(e instanceof FormData))return this.jsonSerializer.deserialize(e.json,e.meta??[]);let t=JSON.parse(e.get("data"));return this.jsonSerializer.deserialize(t.json,t.meta??[],t.maps,(n)=>e.get(n.toString()))}}class Cu extends FS{constructor(e,t){let n=new US(t),r=new VS(n),o=new jS(r,t);super(o,e,t)}}class KS extends _a{initRuntimeAdapter(e){for(let t of this.plugins)t.initRuntimeAdapter?.(e)}}class qS{fetch;toFetchRequestOptions;adapterInterceptors;constructor(e){new KS(e.plugins).initRuntimeAdapter(e),this.fetch=e.fetch??globalThis.fetch.bind(globalThis),this.toFetchRequestOptions=e,this.adapterInterceptors=Fn(e.adapterInterceptors)}async call(e,t,n,r){let o=LS(e,this.toFetchRequestOptions),i=await xo(this.adapterInterceptors,{...t,request:o,path:n,input:r,init:{redirect:"manual"}},({request:s,path:c,input:d,init:u,...m})=>this.fetch(s,u,m,c,d));return zS(i,{signal:o.signal})}}class Hn extends Cu{constructor(e){let t=new qS(e);super(t,e)}}import{chmodSync as Au,mkdirSync as BS,readFileSync as eP,writeFileSync as Tu}from"node:fs";import{homedir as tP}from"node:os";import{join as HS}from"node:path";var Ru=HS(tP(),".niva"),Wn=HS(Ru,"config.json");function Io(){try{let e=JSON.parse(eP(Wn,"utf-8"));return ge(e)?e:{}}catch{return{}}}function WS(e,t){BS(Ru,{recursive:!0});let r={...Io(),[e]:t};Tu(Wn,`${JSON.stringify(r,null,2)}
|
|
100
|
+
`,{mode:384}),Au(Wn,384)}function Iu(){return Io()}function Er(e){return $t(e)}function nP(e){let t=ge(e)?{...e}:void 0;if(t==null)return!1;let n=t.scopes;return typeof t.access_token==="string"&&typeof t.refresh_token==="string"&&typeof t.expires_at==="number"&&typeof t.org_id==="string"&&Array.isArray(n)&&n.every((r)=>typeof r==="string")}function Ou(){let e=Io().auth;return ge(e)?e:{}}function GS(){let e={};for(let[t,n]of Object.entries(Ou()))if(nP(n))e[t]=n;return e}function wr(e,t){BS(Ru,{recursive:!0});let n={...Io(),auth:{...Ou(),[Er(e)]:t}};Tu(Wn,`${JSON.stringify(n,null,2)}
|
|
101
|
+
`,{mode:384}),Au(Wn,384)}function ZS(e){let t=Ou(),n=Er(e);if(!(n in t))return;delete t[n];let r={...Io(),auth:t};Tu(Wn,`${JSON.stringify(r,null,2)}
|
|
102
|
+
`,{mode:384}),Au(Wn,384)}import{createHash as rP,randomBytes as JS}from"node:crypto";import{createServer as oP}from"node:http";var iP=600000,aP=120,sP=5;class Ke extends Error{code;constructor(e,t){super(t);this.code=e}}function cP(e){let t=Ee(e),n=oe(t?.access_token),r=wn(t?.expires_in);if(t==null||n==null||r==null)return null;let o=oe(t.refresh_token),i=oe(t.scope);return{access_token:n,expires_in:r,...o!=null?{refresh_token:o}:{},...i!=null?{scope:i}:{}}}function XS(e,t){let n=Ee(e),r=oe(n?.error)??`http_${String(t)}`,o=oe(n?.error_description)??r;return new Ke(r,o)}function lP(){return JS(32).toString("base64url")}function dP(e){return rP("sha256").update(e).digest("base64url")}function QS(e,t){if(e.NIVA_NO_BROWSER==="1")return!1;let n=e.CI;if(n==="true"||n==="1")return!1;if(t==="linux")return e.DISPLAY!=null||e.WAYLAND_DISPLAY!=null;return!0}function Nu(e){let t;if(process.platform==="darwin")t=[["open",e]];else if(process.platform==="win32")t=[["cmd","/c","start","",e]];else t=[["xdg-open",e]];for(let n of t){let[r,...o]=n;if(r==null)continue;try{return Bun.spawn([r,...o],{stdout:"ignore",stderr:"ignore"}).exited.then((a)=>{if(a!==0)YS(e)}),!0}catch{continue}}return YS(e),!1}function YS(e){console.error(`Open this URL to continue: ${e}`)}async function ku(e){let t=new URL("/.well-known/oauth-authorization-server",$t(e)),n=await fetch(t),r=await n.json().catch(()=>({})),o=Ee(r),i=oe(o?.issuer),a=oe(o?.authorization_endpoint),s=oe(o?.token_endpoint);if(!n.ok||o==null||i==null||a==null||s==null)throw new Ke("discovery_failed",`Could not read OAuth metadata from ${e}`);let c=oe(o.device_authorization_endpoint);return{issuer:i,authorization_endpoint:a,token_endpoint:s,...c!=null?{device_authorization_endpoint:c}:{}}}async function Du(e,t){let n=await fetch(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=await n.json().catch(()=>({}));if(!n.ok)throw XS(r,n.status);let o=cP(r);if(o==null)throw new Ke("invalid_response","The token endpoint answered an unexpected body");return o}function uP(e){return(t,n)=>{let r=new URL(t.url??"/","http://127.0.0.1");if(r.pathname!=="/callback"){n.writeHead(404).end();return}n.writeHead(200,{"content-type":"text/html; charset=utf-8"}),n.end("<html><body><p>Login complete. You can close this tab and go back to the terminal.</p></body></html>");let o=r.searchParams.get("code"),i=r.searchParams.get("state"),a=r.searchParams.get("iss")??void 0,s=r.searchParams.get("error");if(s!=null)e({error:s});else if(o!=null&&i!=null)e({code:o,state:i,iss:a});else e({error:"invalid_request"})}}function pP(e,t){return new Promise((n,r)=>{let o=setTimeout(()=>{e.current=null,t(),r(new Ke("timeout","Timed out waiting for the browser callback"))},iP);e.current=(i)=>{if(clearTimeout(o),t(),"error"in i)r(new Ke(i.error,`Authorization failed: ${i.error}`));else n(i)}})}function mP(){return new Promise((e,t)=>{let n={current:null},r=oP(uP((i)=>n.current?.(i))),o=async()=>pP(n,()=>r.close());r.on("error",t),r.listen(0,"127.0.0.1",()=>{let i=r.address();if(i==null||typeof i==="string"){t(Error("Could not bind the loopback listener"));return}e({redirectUri:`http://127.0.0.1:${i.port}/callback`,waitForCode:o,close:()=>r.close()})})})}async function ex(e,t){let n=await mP(),r=lP(),o=JS(16).toString("base64url"),i=new URL(e.authorization_endpoint);i.searchParams.set("response_type","code"),i.searchParams.set("client_id",t.clientId),i.searchParams.set("redirect_uri",n.redirectUri),i.searchParams.set("scope",t.scopes.join(" ")),i.searchParams.set("state",o),i.searchParams.set("code_challenge",dP(r)),i.searchParams.set("code_challenge_method","S256"),i.searchParams.set("resource",t.resource);try{Nu(i.href);let a=await n.waitForCode();if(a.state!==o)throw new Ke("state_mismatch","The state returned by the server does not match");if(a.iss!=null&&a.iss!==e.issuer)throw new Ke("issuer_mismatch","The issuer returned by the server does not match");return await Du(e.token_endpoint,{grant_type:"authorization_code",code:a.code,redirect_uri:n.redirectUri,client_id:t.clientId,code_verifier:r})}finally{n.close()}}function fP(e){let t=Ee(e);if(t==null)return null;let n=["device_code","user_code","verification_uri","verification_uri_complete"].map((o)=>oe(t[o])),r=["expires_in","interval"].map((o)=>wn(t[o]));if(n.some((o)=>o==null)||r.some((o)=>o==null))return null;return{device_code:n[0],user_code:n[1],verification_uri:n[2],verification_uri_complete:n[3],expires_in:r[0],interval:r[1]}}async function tx(e,t){let n=e.device_authorization_endpoint;if(n==null)throw new Ke("unsupported_grant_type","This server does not support the device flow");let r=await fetch(n,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:t.clientId,scope:t.scopes.join(" "),resource:t.resource}).toString()}),o=await r.json().catch(()=>({})),i=r.ok?fP(o):null;if(i==null)throw r.ok?new Ke("invalid_response","The device authorization endpoint answered an unexpected body"):XS(o,r.status);return i}async function nx(e,t,n){let r=t.interval*1000,o=Date.now()+t.expires_in*1000;while(Date.now()<o){await Bun.sleep(r);try{return await Du(e,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:t.device_code,client_id:n})}catch(i){if(i instanceof Ke){if(i.code==="authorization_pending")continue;if(i.code==="slow_down"){r+=sP*1000;continue}}throw i}}throw new Ke("expired_token","The device code expired before authorization completed")}function ba(e,t=Math.floor(Date.now()/1000)){return e.expires_at-t<aP}async function va(e,t){let n=await ku(e),r=await Du(n.token_endpoint,{grant_type:"refresh_token",refresh_token:t.refresh_token,client_id:"niva-cli"});if(r.refresh_token==null)throw new Ke("invalid_grant","The server did not return a refresh token");return{access_token:r.access_token,refresh_token:r.refresh_token,expires_at:Math.floor(Date.now()/1000)+r.expires_in,org_id:t.org_id,scopes:r.scope!=null?r.scope.split(" ").filter((o)=>o!==""):t.scopes}}function Pu(e){try{let{hostname:t}=new URL(e);return t.endsWith(".orb.local")||process.env.NIVA_INSECURE==="true"}catch{return!1}}var rx;function ox(){return rx==null?{}:{[vo]:rx}}class ix extends Error{constructor(){super("Your session has expired. Run 'niva login' to authenticate again.")}}function gP(e){let t=e.fetchImpl??fetch,n=async()=>{try{return await e.refresh()}catch(r){if(r instanceof Ke)throw new ix;throw r}};return async(r)=>{let o=e.getSession();if(ba(o))o=await n();let i=new Request(r);i.headers.set("authorization",`Bearer ${o.access_token}`);let a=await t(i);if(a.status===401){o=await n();let s=new Request(r);s.headers.set("authorization",`Bearer ${o.access_token}`),a=await t(s)}return a}}function $u(e,t,n){if(Pu(e))process.env.NODE_TLS_REJECT_UNAUTHORIZED="0";if(t.kind!=="oauth"){let i=new Hn({url:new URL("/api/rpc",e).href,headers:()=>({...ox(),...t.kind==="api-key"?{"X-API-Key":t.apiKey}:{}})});return Bn(i)}let r=t.session,o=new Hn({url:new URL("/api/rpc",e).href,headers:ox,fetch:gP({getSession:()=>r,refresh:async()=>(r=await va(n,r),wr(n,r),r)})});return Bn(o)}var Mu="niva-cli",hP=["*:read","*:write","offline_access"],yP=["*:read","offline_access"];function ax(e,t){return{access_token:e.access_token,refresh_token:e.refresh_token??"",expires_at:Math.floor(Date.now()/1000)+e.expires_in,org_id:t,scopes:e.scope!=null?e.scope.split(" ").filter((n)=>n!==""):[]}}async function _P(e,t){return(await $u(e,{kind:"oauth",session:ax(t,"")},e).oauth.whoami()).organization?.id??""}function sx(e,t,n){e.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(r)=>{let o=Er(t().url);if(!o.startsWith("https://"))Et("Server URL is not https: tokens travel unencrypted on this network.");let i=r.readOnly===!0?yP:hP,a=`${o}/api`,s=await ku(o),c={scopes:i,resource:a,clientId:Mu},d,u=QS(process.env,process.platform);if(r.device===!0||!u){let y=await tx(s,c);if(P(`Open ${y.verification_uri} and enter the code: ${y.user_code}`),u)Nu(y.verification_uri_complete);d=await nx(s.token_endpoint,y,Mu)}else d=await ex(s,c);let m=await _P(o,d);wr(o,ax(d,m)),N(`Logged in to ${o}`)}),e.command("logout").description("Revoke the saved session and remove it from the config file").action(async()=>{let r=Er(t().url),o=GS()[r];if(o==null){P(`No saved session for ${r}`);return}try{await fetch(new URL("/oauth/revoke",r),{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:o.refresh_token,client_id:Mu}).toString()})}catch{Et("Could not reach the server to revoke the token; clearing the local session anyway.")}ZS(r),N(`Logged out of ${r}`)}),e.command("whoami").description("Show the authenticated user, organization, scopes and token expiry").action(async()=>{let r=Er(t().url),o=n();if(o.kind==="none"){C(`No credential configured for ${r}. Run 'niva login' first.`),process.exitCode=1;return}let a=await $u(r,o,r).oauth.whoami();v({url:r,user:a.user.email,organization:a.organization?.name,scopes:a.scopes,credential:a.credential,...o.kind==="oauth"?{expires_at:new Date(o.session.expires_at*1000).toISOString()}:{}})})}var Lu=["blocker","degraded","minor"],zu=["always","sometimes","once"],bP=Lu,vP=zu;function cx(e,t){return[...t,e]}function SP(e){return bP.includes(e)}function xP(e){return vP.includes(e)}function lx(e,t){e.command("bug-report").description("Report a problem to the NIVA support team").option("--title <title>","Short summary (3-120 characters)").option("--description <description>","What happened (10-4000 characters)").option("--severity <level>",`How bad it is: ${Lu.join(", ")}`).option("--expected <expected>","What you expected to happen").option("--step <step>","A reproduction step (repeatable)",cx,[]).option("--frequency <frequency>",`How often it happens: ${zu.join(", ")}`).option("--resource <typeid>","Related resource TypeID (repeatable)",cx,[]).action(async(n)=>{let{title:r,description:o,severity:i,expected:a,frequency:s,step:c,resource:d}=n,u=[];if(r===void 0||r==="")u.push("--title");if(o===void 0||o==="")u.push("--description");if(i===void 0||i==="")u.push("--severity");if(u.length>0)C(`Missing required option${u.length>1?"s":""}: ${u.join(", ")}`),process.exit(A.USAGE_ERROR);if(r===void 0||o===void 0||i===void 0)process.exit(A.USAGE_ERROR);if(!SP(i))C(`Invalid --severity '${i}'. Expected one of: ${Lu.join(", ")}`),process.exit(A.USAGE_ERROR);if(s!==void 0&&!xP(s))C(`Invalid --frequency '${s}'. Expected one of: ${zu.join(", ")}`),process.exit(A.USAGE_ERROR);let{format:m}=S(e.opts()),y=c.length>0?c.map((E,k)=>`${k+1}. ${E}`).join(`
|
|
103
|
+
`):void 0,_=await b(t().bugReports.create({title:r,description:o,severity:i,expected:a,steps:y,frequency:s,resources:d.length>0?d:void 0,source:"cli"}));if(m==="json"){v(_);return}N(`Report sent (${_.reference})`)})}import{basename as wP}from"node:path";var ue=on(jt(),1);var EP=/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i,dx=4;async function Sa(e,t){if(EP.test(t))return t;if(t.length<dx)C(`UUID prefix too short — provide at least ${dx} characters.`),process.exit(A.USAGE_ERROR);let n=await b(e.dashboard.activeCalls()),r=t.toLowerCase(),o=n.filter((i)=>i.uuid.toLowerCase().startsWith(r));if(o.length===0)C(`No active call matching "${t}".`),process.exit(A.NOT_FOUND);if(o.length>1){C(`Ambiguous UUID prefix "${t}" — matches ${o.length} calls. Be more specific.`);for(let i of o)P(` ${i.uuid} ${i.callerId}`);process.exit(A.USAGE_ERROR)}return o[0].uuid}var CP={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 AP(e){let t=Math.max(0,Math.floor(e)),n=Math.floor(t/60),r=t%60;return`${String(n).padStart(2,"0")}:${String(r).padStart(2,"0")}`}function TP(e){if(e==null)return"—";return`${AP(e.at_seconds)}${e.late?" (late)":""}`}function mx(e,t,n){let r=e.command("calls").description("Manage calls");r.command("list").description("List active calls").action(async()=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().dashboard.activeCalls());if(o==="json"){let s=i?a.map((c)=>O(c,i)):a;v(s);return}if(a.length===0){P("No active calls.");return}L(["UUID","Caller","Plan","Duration"],a.map((s)=>({UUID:s.uuid,Caller:s.callerId,Plan:s.planName??"—",Duration:s.startedAt?`${Math.round((Date.now()-new Date(s.startedAt).getTime())/1000)}s`:"—"})))}),r.command("show <call_record_id>").description("Show call details from CDR (rich detail view)").action(async(o)=>{let{format:i,fields:a}=S(e.opts()),s=await b(t().callRecords.getById({call_record_id:x("call_records",o)}));if(i==="json"){let c=a&&s!=null?O(s,a):s;v(c);return}if(s==null){P("Call record not found.");return}J([{title:"Call Record",rows:IP(s)}])}),r.command("hangup <call>").description("Hang up an active call by TypeID (call_...), full channel UUID, or UUID prefix").action(async(o)=>{let{format:i}=S(e.opts()),a=t(),s=o,c;if(o.startsWith("call_"))c=await b(a.calls.hangupCall({call_id:x("call_records",o)}));else s=await Sa(a,o),c=await b(a.calls.hangupActiveCall({uuid:s}));if(i==="json"){v(c);return}N(`Call ${s} terminated.`)}),r.command("signals <call_record_id>").description("Show the signal results of a recorded call").action(async(o)=>{let{format:i,fields:a}=S(e.opts()),s=await b(t().signals.callSignals({call_id:x("call_records",o)}));if(i==="json"){let c=a?s.map((d)=>O(d,a)):s;v(c);return}if(s.length===0){P("No signal results for this call.");return}L(["Signal","Value","Confidence","Triggered at","Severity"],s.map((c)=>({Signal:c.signal.name,Value:c.value_label??"—",Confidence:c.confidence==null?"—":`${Math.round(c.confidence*100)}%`,"Triggered at":TP(c.trigger),Severity:c.definition.alert?.severity??"—"})))}),r.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(o)=>{let{format:i,fields:a}=S(e.opts()),s=await b(t().callRecords.list({page:Number(o.page),limit:Number(o.limit),search:o.caller}));if(i==="json"){let c=a?s.items.map((d)=>O(d,a)):s;v(c);return}L(["ID","Caller","Callee","Duration","Talk","AMD","Disposition","Date"],s.items.map((c)=>({ID:c.id,Caller:c.caller_id??"—",Callee:c.callee_id??"—",Duration:Ce(c.duration_ms),Talk:Ce(c.talk_duration_ms),AMD:Fu(c.answer_recognition_results),Disposition:c.hangup_disposition??"—",Date:new Date(c.started_at).toLocaleString()}))),ee(s)}),r.command("follow <uuid>").description("Follow live transcription of an active call").action(async(o)=>{let{format:i}=S(e.opts()),a=t(),s=await Sa(a,o),c=new AbortController;process.on("SIGINT",()=>{c.abort()});let d=!1,u=!1;function m(_){y();let E=fx(_);process.stdout.write(ue.default.dim(E)),u=!0}function y(){if(!u)return;process.stdout.clearLine(0),process.stdout.cursorTo(0),u=!1}await new Promise((_,E)=>{Qt(a.dashboard.watchLiveTranscription({uuid:s},{signal:c.signal}),{onEvent:(k)=>{if(d=!0,i==="json"){v(k);return}switch(k.type){case"starting":P("Connecting...");break;case"started":P("Transcription started.");break;case"caught_up":break;case"unavailable":P(CP[k.reason]),_();break;case"ended":y(),P("Transcription ended."),_();break;case"error":console.error(ue.default.red(`Error: ${k.message}`));break;case"history":for(let V of k.segments)ux(V);for(let V of k.signals??[])px(V);break;case"signal_value":case"signal_triggered":px(k);break;case"segment":if(k.segment.isFinal)y(),ux(k.segment);else m(k.segment);break}},onError:(k)=>{if(k instanceof DOMException&&k.name==="AbortError"){y(),_();return}E(k)},onSuccess:()=>{if(!d)P("Live transcription not available for this call.");_()}})}).catch((_)=>{y(),In(_)})}),r.command("transfer <uuid> <destination>").description("Transfer an active call").action(()=>Vt()),r.command("spy <uuid>").description("Spy on an active call").action(()=>Vt()),r.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(o)=>{let{format:i,fields:a}=S(e.opts()),s=await b(t().callRecords.list({page:Number(o.page),limit:Number(o.limit),date_from:o.from,date_to:o.to,visual_plan_id:x("visual_plans",o.plan),channel_id:x("channels",o.phone),status:o.status,caller_search:o.caller,min_duration:o.minDuration!=null?Number(o.minDuration):void 0,max_duration:o.maxDuration!=null?Number(o.maxDuration):void 0,has_recording:o.hasRecording,has_transcription:o.hasTranscription}));if(i==="json"){if(a)v(s.items.map((c)=>O(c,a)));else v(s);return}if(s.items.length===0){P("No call records found.");return}L(["ID","Caller","Direction","Duration","Talk","AMD","Status","Sentiment","Plan","Date"],s.items.map((c)=>{let d=c.sentiment_score!=null?Number(c.sentiment_score):null;return{ID:c.id,Caller:c.caller_id??"—",Direction:c.direction??"—",Duration:Ce(c.duration_ms),Talk:Ce(c.talk_duration_ms),AMD:Fu(c.answer_recognition_results),Status:Qa(c.hangup_disposition),Sentiment:c.sentiment_label!=null?es(c.sentiment_label,d):"—",Plan:c.visual_plan_name??"—",Date:Me(c.started_at)}})),ee(s)}),r.command("trace <call_record_id>").description("Show node-by-node execution trace for a call").action(async(o)=>{let{format:i,fields:a}=S(e.opts()),s=await b(t().callRecords.getTrace({call_record_id:x("call_records",o)}));if(i==="json"){let _=a&&s!=null?O(s,a):s;v(_);return}if(s==null){P("Call trace not found.");return}let c=s.callRecord;if(console.log(`${ue.default.bold("Call Trace")} — ${o} (${Ce(c.duration_ms)}, ${c.hangup_disposition??"unknown"})`),c.visual_plan_name!=null)console.log(`Plan: ${c.visual_plan_name}`);console.log("");let d=s.events;if(d.length===0){P(" No events recorded (0 nodes visited).");return}let u=d.map((_,E)=>{let k=_.duration_ms!=null?`${(_.duration_ms/1000).toFixed(1)}s`:"—",V=`${ue.default.cyan(_.node_type)}`;if(_.node_label!=null){let re=ue.default.bold(`"${_.node_label}"`);V+=` ${re}`}if(V+=ue.default.dim(` (${k})`),_.digit!=null)V+=` → digit: ${ue.default.yellow(_.digit)}`;let G=[];if(_.handle_used!=null)G.push(ue.default.dim(`└─→ ${_.handle_used}`));if(ge(_.data)){let re=Object.entries(_.data).filter(([,ct])=>ct!=null&&typeof ct!=="object").map(([ct,tt])=>`${ct}: ${String(tt)}`);if(re.length>0)G.push(ue.default.dim(`└─ ${re.join(", ")}`))}return{label:V,children:G.length>0?G:void 0}});ts(u),console.log("");let m=d.at(-1),y=m.node_label??m.node_type;P(` ${d.length} nodes visited · Last: ${m.node_type} "${y}" · Hangup: ${c.hangup_cause??"—"}`)}),r.command("transcript <call_record_id>").description("Show call transcription with speech analytics").action(async(o)=>{let{format:i,fields:a}=S(e.opts()),s=await b(t().ai.getTranscription({call_record_id:x("call_records",o)}));if(i==="json"){let u=a&&s!=null?O(s,a):s;v(u);return}console.log(`${ue.default.bold("Transcript")} — ${o}`),console.log("");let c=NP(s?.segments);if(c.length===0||s?.status==="disabled")P(" No transcript available.");else bm(c);let d=s!=null?kP(s):[];if(d.length>0)console.log(""),J([{title:"Speech Analytics",rows:d}])}),r.command("purge-voice <call_record_id>").description("Permanently erase a call's voice content (recording, transcription, embeddings)").action(async(o)=>{let{format:i}=S(e.opts()),a=e.opts().yes===!0;if(i!=="json")console.log(`${ue.default.bold("Erase voice content")} — ${o}`),P(" Deletes: recording file, transcription and its semantic-search embeddings."),P(" Keeps: the call record (CDR), its event timeline and existing analyses."),P(" This is irreversible."),console.log("");await Te("Erase the voice content of this call?",{yes:a});let s=await b(t().callRecords.purgeVoiceContent({call_record_id:x("call_records",o)}));if(i==="json"){v(s);return}N("Voice content erased"),J([{title:"Deleted",rows:[{label:"Recording",value:String(s.deleted.recording)},{label:"Transcriptions",value:String(s.deleted.transcriptions)},{label:"Embeddings",value:String(s.deleted.embeddings)},{label:"Analyses detached",value:String(s.analyses_detached)}]}])}),r.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(o,i)=>{let{format:a,fields:s}=S(e.opts()),c=await b(t().ai.searchTranscriptions({query:o,limit:Number(i.limit),threshold:Number(i.threshold),date_from:i.from,date_to:i.to,visual_plan_id:x("visual_plans",i.plan)}));if(a==="json"){let u=s?c.map((m)=>O(m,s)):c;v(u);return}let d=c;if(console.log(`${ue.default.bold("Semantic Search")}: "${o}"`),console.log(`${d.length} result${d.length!==1?"s":""} (threshold: ${i.threshold})`),d.length===0){P(`
|
|
104
|
+
No results found.`);return}console.log("");for(let u of d){let m=`${Math.round(u.similarity*100)}%`,y=u.call_record_id,_=Me(u.started_at),E=Ce(u.duration_ms);console.log(` ${ue.default.bold(m.padStart(4))} │ ${y} │ ${_} │ ${u.caller_id??"—"} │ ${u.direction} │ ${E} │ ${u.visual_plan_name??"—"}`);let k=String(u.chunk_text).replaceAll(/\s+/g," ").trim(),V=120,G=k.length>V?`${k.slice(0,V)}...`:k;console.log(ue.default.dim(` │ "${G}"`)),console.log("")}}),r.command("export").description("Export calls to CSV in the background (a .zip of CSV parts built on the server)").option("--from <date>","First day of the period (YYYY-MM-DD)").option("--to <date>","Last day of the period (YYYY-MM-DD)").option("--columns <keys>","Comma-separated column keys (default: the server's default set)").option("--separator <char>","Field separator: ',' or ';'",",").option("--include-events","One row per block executed inside each call").option("--out <path>","Write the .zip to this path (default: the job's filename in the current directory)").option("--force","Overwrite an existing file when writing to the default filename").option("--no-wait","Print the job and exit without waiting for it").option("--job <export_job_id>","Wait for and download an existing export instead of creating one").action(async(o)=>{let{format:i}=S(e.opts()),a=t(),s=await $P(a,o);if(o.wait===!1){if(i==="json")v(s);else N(`Export ${s.id} is ${s.status}.`);return}let c=o.out??wP(s.filename);await MP(c,s,o);let d=await PP(a,s.id);if(d.status!=="ready")C(LP(d)),process.exit(A.GENERAL_ERROR);let u=await zP(a,s.id,n().url),m=await Bun.write(c,u);if(i==="json"){v({export_job_id:s.id,status:d.status,path:c,bytes:m});return}N(`Saved ${c} (${m} bytes)`)}),r.command("inspect <uuid>").description("Inspect an active call: current node, variables, execution path").action(async(o)=>{let{format:i,fields:a}=S(e.opts()),s=t(),c=await Sa(s,o),d=await b(s.dashboard.activeCallTrace({uuid:c}));if(i==="json"){let y=a?O(d,a):d;v(y);return}J([{title:"Active Call",rows:[{label:"UUID",value:c},{label:"Current",value:d.currentNodeId??"—"}]}]);let u=d.variables;if(Object.keys(u).length>0){let y=Object.entries(u).map(([_,E])=>({label:_,value:E}));J([{title:`Variables (${Object.keys(u).length})`,rows:y}])}let m=d.events;if(m.length>0){console.log(""),console.log(ue.default.bold("Execution Path:"));let y=m.map((_)=>{let E=_.duration_ms!=null?`${(_.duration_ms/1000).toFixed(1)}s`:"waiting...",k=_.node_id===d.currentNodeId,G=`${k?ue.default.yellow("●"):ue.default.green("✓")} ${ue.default.cyan(_.node_type)}`;if(_.node_label!=null){let re=ue.default.bold(`"${_.node_label}"`);G+=` ${re}`}if(G+=ue.default.dim(` (${E})`),k)G+=ue.default.yellow(" ← current");return{label:G}});ts(y)}})}function RP(e){if(e.has_recording)return"yes";if(e.was_recorded)return"processing";return"no"}function Fu(e){if(e?.amd==null)return"—";return e.amd_action==="hangup"?`${e.amd} (hangup)`:e.amd}function xa(e){return e!=null&&e!==""}function IP(e){let t=e.answered_at!=null?new Date(e.answered_at):null,n=new Date(e.started_at),r=t!=null?`${Math.round((t.getTime()-n.getTime())/1000)}s ring`:null,o=xa(r)?` (${r})`:"",i=e.visual_plan_version_number!=null?` v${e.visual_plan_version_number}`:"",a=xa(e.visual_plan_name)?`${e.visual_plan_name}${i}`:null,s=xa(e.sip_hangup_disposition)?` (${e.sip_hangup_disposition})`:"",c=e.transcription_status==="none"?"disabled":e.transcription_status;return[{label:"ID",value:e.id},{label:"Direction",value:e.direction},{label:"Caller",value:e.caller_id},{label:"Callee",value:e.callee_id},{label:"Plan",value:a},{label:"Started",value:n.toLocaleString()},{label:"Answered",value:t!=null?`${t.toLocaleString()}${o}`:null},{label:"Ended",value:e.ended_at!=null?new Date(e.ended_at).toLocaleString():null},{label:"Duration",value:Ce(e.duration_ms)},{label:"Talk",value:e.talk_duration_ms!=null?Ce(e.talk_duration_ms):null},{label:"Status",value:Qa(e.hangup_disposition)},{label:"Recording",value:RP(e)},{label:"Transcribed",value:c},{label:"AMD",value:e.answer_recognition_results?.amd!=null?Fu(e.answer_recognition_results):null},{label:"Machine type",value:e.answer_recognition_results?.machine_type},{label:"Hangup",value:xa(e.hangup_cause)?`${e.hangup_cause}${s}`:null}]}function OP(e){let t=wn(e.confidence),n=t!=null?` (${t.toFixed(2)})`:"";return`${oe(e.topic)??oe(e.label)??"?"}${n}`}function NP(e){let t=[];for(let n of xt(e)){let r=oe(n.speaker),o=oe(n.text),i=wn(n.initial_time);if(r!=null&&o!=null&&i!=null)t.push({speaker:r,text:o,initial_time:i})}return t}function kP(e){let t=[],n=Ee(e.sentiment_overall);if(n!=null)t.push({label:"Sentiment",value:es(oe(n.label),wn(n.score))});if(e.intent!=null)t.push({label:"Intent",value:e.intent});if(e.summary!=null)t.push({label:"Summary",value:e.summary});let r=Array.isArray(e.key_points)?e.key_points.filter((i)=>typeof i==="string"):[];if(r.length>0)t.push({label:"Key Points",value:r.map((i)=>`• ${i}`).join(`
|
|
105
|
+
│ `)});let o=xt(e.topics);if(o.length>0)t.push({label:"Topics",value:o.map((i)=>OP(i)).join(" · ")});return t}function fx(e){let t=Math.floor(e.start/60),n=Math.floor(e.start%60),r=`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`,o=e.channel===0?ue.default.blue("Caller"):ue.default.green("System");return`${ue.default.dim(`[${r}]`)} ${o} ${ue.default.dim(">")} ${e.text}`}function ux(e){console.log(fx(e))}function px(e){let t=`${Math.round(e.confidence*100)}%`;if(e.type==="signal_value"){P(` ↳ ${e.signal.name}: ${e.value_label} (${t})`);return}let n=e.node!=null?` · ${e.node.label}`:"",r=e.late?" (late)":"";console.log(ue.default.bold(ue.default.yellow(` \uD83D\uDD14 ${e.signal.name}: ${e.value_label} (${t})${n}${r}`)))}function DP(e){if(e.status==="queued")return"queued";let{processed_records:t,total_records:n}=e,r=n!=null&&n>0?`${t}/${n} (${Math.floor(t*100/n)}%)`:`${t} records`;return e.status==="paused"?`${r} - paused, resumes on its own`:r}async function PP(e,t){return await new Promise((n,r)=>{Qt(e.callRecords.exportJobProgress({export_job_id:t}),{onEvent:(o)=>ht(DP(o)),onError:r,onSuccess:()=>n()})}).catch((n)=>{In(n)}),b(e.callRecords.exportJobGet({export_job_id:t}))}async function $P(e,t){if(t.separator!==","&&t.separator!==";")C("--separator must be ',' or ';'."),process.exit(A.USAGE_ERROR);if(t.job!=null)return b(e.callRecords.exportJobGet({export_job_id:x("export_jobs",t.job)}));let{from:n,to:r}=t;if(n==null||r==null)C("--from and --to are required unless --job is given."),process.exit(A.USAGE_ERROR);return b(e.callRecords.exportJobCreate({date_from:n,date_to:r,separator:t.separator,include_events:t.includeEvents===!0,...t.columns!=null?{columns:t.columns.split(",").map((o)=>o.trim())}:{}}))}async function MP(e,t,n){if(n.out!=null||n.force===!0)return;if(!await Bun.file(e).exists())return;if(C(`${e} already exists - pass --out <path> to write elsewhere, or --force to overwrite it.`),n.job==null)ht(`The export keeps running on the server: download it later with --job ${t.id}.`);process.exit(A.CONFLICT)}function LP(e){if(e.status==="failed")return`Export ${e.id} failed: ${e.error_code??"unknown error"}.`;if(e.status==="cancelled")return`Export ${e.id} was cancelled.`;if(e.status==="expired")return`Export ${e.id} expired and its file was removed.`;return`Export ${e.id} stopped while ${e.status}. Wait for it again with --job ${e.id}.`}async function zP(e,t,n){let r="";for(let o=0;o<2;o+=1){let{url:i}=await b(e.callRecords.exportDownloadTicket({export_job_id:t}));try{let a=await fetch(new URL(i,n));if(a.ok)return a;r=`HTTP ${a.status}`}catch(a){r=a instanceof Error?a.message:String(a)}}return C(`Download failed (${r}). Run the command again with --job ${t} to retry.`),process.exit(A.GENERAL_ERROR)}import{readFile as FP}from"node:fs/promises";async function gx(e){let t=e==="-"?await Fe():await FP(e,"utf-8"),n=JSON.parse(t);if(!ge(n))C(`Invalid campaign file "${e}": expected a JSON object`),process.exit(A.USAGE_ERROR);return n}function UP(e){return{...e.name!=null&&{name:e.name},...e.description!=null&&{description:e.description},...e.callerId!=null&&{caller_id:e.callerId},...e.trunkOverride!=null&&{trunk_override:e.trunkOverride},...e.maxConcurrent!=null&&{max_concurrent_calls:Number(e.maxConcurrent)},...e.ringTimeout!=null&&{ring_timeout_s:Number(e.ringTimeout)},...e.maxDuration!=null&&{max_call_duration_s:Number(e.maxDuration)},...e.priority!=null&&{priority:Number(e.priority)}}}var hx=["interval_min","max_attempts"];function Ar(e){C(`Invalid --retry-rules: ${e}`),process.exit(A.USAGE_ERROR)}function jP(e,t){if(!ge(t))return Ar(`"${e}" must be an object`);let n={};for(let[r,o]of Object.entries(t)){let i=hx.find((a)=>a===r);if(i===void 0)return Ar(`unknown field "${r}" in "${e}" (allowed: ${hx.join(", ")})`);if(typeof o!=="number")return Ar(`"${e}.${r}" must be a number`);n[i]=o}return n}function VP(e){let t;try{t=JSON.parse(e)}catch{return Ar("not valid JSON")}if(t===null)return null;if(!ge(t))return Ar("expected a JSON object or null");let n={};for(let[r,o]of Object.entries(t)){let i=Wc.find((a)=>a===r);if(i===void 0)return Ar(`unknown class "${r}" (allowed: ${Wc.join(", ")})`);n[i]=jP(i,o)}return n}function KP(e){let t=e.retryOn!=null?new Set(e.retryOn.split(",").map((n)=>n.trim())):void 0;return{...e.retryAttempts!=null&&{retry_max_attempts:Number(e.retryAttempts)},...e.retryInterval!=null&&{retry_interval_min:Number(e.retryInterval)},...e.retryRules!=null&&{retry_rules:VP(e.retryRules)},...e.windowStart!=null&&{call_window_start:e.windowStart},...e.windowEnd!=null&&{call_window_end:e.windowEnd},...e.windowDays!=null&&{call_window_days:e.windowDays},...e.autoStartAt!=null&&{auto_start_at:e.autoStartAt},...e.autoStopAt!=null&&{auto_stop_at:e.autoStopAt},...t!=null&&{retry_on_busy:t.has("busy"),retry_on_no_answer:t.has("no_answer"),retry_on_failed:t.has("failed")},...e.recurring===!0&&{recurring:!0}}}function yx(e){return{...UP(e),...KP(e)}}function Cr(e){if(e==null)return"inherit (org default)";if(typeof e==="boolean")return e?"yes":"no";return String(e)}function _x(e){return e.option("--description <text>","Campaign description").option("--caller-id <id>","Caller ID for outbound calls").option("--trunk-override <trunk>","Trunk override (default: org trunk)").option("--max-concurrent <n>","Max concurrent calls").option("--ring-timeout <s>","Ring timeout in seconds before no-answer").option("--max-duration <s>","Max call duration in seconds").option("--retry-attempts <n>","Max retry attempts").option("--retry-interval <min>","Retry interval in minutes").option("--retry-on <list>","Retry on outcomes (comma list: busy,no_answer,failed)").option("--retry-rules <json>",`Per-outcome retry overrides, e.g. '{"busy":{"interval_min":5,"max_attempts":3}}' (null clears)`).option("--window-start <HH:MM>","Call window start time").option("--window-end <HH:MM>","Call window end time").option("--window-days <list>","Call window days (comma ints, 0=Sun..6=Sat)").option("--priority <n>","Campaign priority (0-100)").option("--recurring","Enable recurring dialing").option("--auto-start-at <iso>","Auto-start timestamp (ISO 8601)").option("--auto-stop-at <iso>","Auto-stop timestamp (ISO 8601)").option("--file <path>","JSON file with campaign fields (- for stdin)")}function bx(e,t){let n=e.command("campaigns").description("Manage dialer campaigns");n.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(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().dialerCampaigns.list({page:Number(r.page),limit:Number(r.limit),search:r.search,status:se(r.status)}));if(o==="json"){let s=i?a.items.map((c)=>O(c,i)):a;v(s);return}L(["ID","Name","Status","Contacts","Answered","Created"],a.items.map((s)=>({ID:s.id,Name:s.name,Status:s.status,Contacts:s.total_contacts,Answered:s.answered_count,Created:Me(s.created_at)}))),ee(a)}),n.command("show <campaign_id>").description("Show campaign details").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().dialerCampaigns.get({campaign_id:x("dialer_campaigns",r)}));if(a==null){if(o==="json")v(null),process.exit(A.NOT_FOUND);C("Campaign not found"),process.exit(A.NOT_FOUND)}if(o==="json"){let s=i?O(a,i):a;v(s);return}J([{title:"Campaign",rows:[{label:"ID",value:a.id},{label:"Name",value:a.name},{label:"Description",value:a.description},{label:"Status",value:a.status},{label:"Plan",value:a.plan_id},{label:"Channel",value:a.channel_type},{label:"Priority",value:a.priority},{label:"Created",value:new Date(a.created_at).toLocaleString()},{label:"Updated",value:new Date(a.updated_at).toLocaleString()}]},{title:"Dialing",rows:[{label:"Caller ID",value:a.caller_id},{label:"Trunk",value:a.trunk_override},{label:"Max Concurrent",value:a.max_concurrent_calls},{label:"Ring Timeout",value:`${a.ring_timeout_s}s`},{label:"Max Duration",value:`${a.max_call_duration_s}s`}]},{title:"Retry",rows:[{label:"Max Attempts",value:a.retry_max_attempts},{label:"Interval",value:`${a.retry_interval_min}min`},{label:"On Busy",value:a.retry_on_busy?"yes":"no"},{label:"On No Answer",value:a.retry_on_no_answer?"yes":"no"},{label:"On Failed",value:a.retry_on_failed?"yes":"no"},...a.retry_rules!=null?[{label:"Retry Rules",value:JSON.stringify(a.retry_rules)}]:[]]},{title:"Answering machine",rows:[{label:"Detection",value:a.amd_enabled?"on":"off"},{label:"Retry On Machine",value:a.retry_on_machine?"yes":"no"},{label:"Block After All",value:Cr(a.amd_block_after_all_machine)},{label:"Block Min Attempts",value:Cr(a.amd_block_min_attempts)},{label:"On Voicemail",value:Cr(a.amd_action_voicemail)},{label:"On Announcement",value:Cr(a.amd_action_announcement)},{label:"On IVR",value:Cr(a.amd_action_ivr)},{label:"On Screening",value:Cr(a.amd_action_screening)}]},{title:"Window & schedule",rows:[{label:"Window Start",value:a.call_window_start},{label:"Window End",value:a.call_window_end},{label:"Window Days",value:a.call_window_days},{label:"Recurring",value:a.recurring?"yes":"no"},{label:"Recurrence",value:a.recurrence_mode},{label:"Auto Start",value:a.auto_start_at?new Date(a.auto_start_at).toLocaleString():null},{label:"Auto Stop",value:a.auto_stop_at?new Date(a.auto_stop_at).toLocaleString():null}]}])}),n.command("stats <campaign_id>").description("Show campaign statistics").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().dialerCampaigns.stats({campaign_id:x("dialer_campaigns",r)}));if(o==="json"){let d=i?O(a,i):a;v(d);return}let s=a.capacity_context;J([{title:"Stats",rows:[{label:"Status",value:a.status},{label:"Total",value:a.total_contacts},{label:"Pending",value:a.pending_count},{label:"Calling",value:a.calling_count},{label:"Answered",value:a.answered_count},{label:"Machine",value:a.machine_count},{label:"Busy",value:a.busy_count},{label:"No Answer",value:a.no_answer_count},{label:"Failed",value:a.failed_count},{label:"DNC Skipped",value:a.dnc_skipped_count},{label:"Cancelled",value:a.cancelled_count}]},{title:"Capacity",rows:[{label:"Waiting",value:a.waiting_capacity?"yes":"no"},{label:"Used",value:s!=null?s.used:null},{label:"Capacity",value:s!=null?s.capacity:null},{label:"Reserve",value:s!=null?s.reserve:null},{label:"Module Disabled",value:a.module_disabled?"yes":"no"}]}]);let c=Number(a.total_contacts);if(c>0)console.log(""),wt("Answered",Number(a.answered_count),c),wt("Busy",Number(a.busy_count),c),wt("No Answer",Number(a.no_answer_count),c),wt("Failed",Number(a.failed_count),c)}),n.command("summary").description("Show running-campaign summary").action(async()=>{let{format:r,fields:o}=S(e.opts()),i=await b(t().dialerCampaigns.summary());if(r==="json"){let a=o?O(i,o):i;v(a);return}J([{title:"Summary",rows:[{label:"Running",value:i.running},{label:"Calling",value:i.calling},{label:"Campaign",value:i.campaign!=null?`${i.campaign.name} (${i.campaign.id})`:null}]}])}),_x(n.command("create <name>").description("Create a dialer campaign").requiredOption("--plan <plan_id>","Visual plan ID to dial")).action(async(r,o)=>{let{format:i}=S(e.opts()),a=o.file!=null?await gx(o.file):{},s=yx(o),c=await b(t().dialerCampaigns.create({...a,...s,name:r,plan_id:x("visual_plans",o.plan)}));if(i==="json"){v(c);return}N(`Campaign created: ${c.id} — ${c.name}`)}),_x(n.command("edit <campaign_id>").description("Update a dialer campaign").option("--name <name>","Campaign name")).action(async(r,o)=>{let{format:i}=S(e.opts()),a=o.file!=null?await gx(o.file):{},s=yx(o),c=await b(t().dialerCampaigns.update({campaign_id:x("dialer_campaigns",r),...a,...s}));if(i==="json"){v(c);return}N(`Campaign updated: ${c.name}`)}),n.command("delete <campaign_id>").description("Delete a dialer campaign").action(async(r)=>{let{format:o}=S(e.opts());if(await b(t().dialerCampaigns.delete({campaign_id:x("dialer_campaigns",r)})),o==="json"){v({success:!0});return}N("Campaign deleted")});for(let r of["start","pause","resume","stop"])n.command(`${r} <campaign_id>`).description(`${r[0].toUpperCase()}${r.slice(1)} a campaign`).action(async(o)=>{let{format:i}=S(e.opts()),a=await b(t().dialerCampaigns.control({campaign_id:x("dialer_campaigns",o),action:r}));if(i==="json"){v(a);return}N(`Campaign "${a.name}" → ${a.status}`)});n.command("watch <campaign_id>").description("Watch live campaign stats (streams until Ctrl-C)").action(async(r)=>{let{format:o}=S(e.opts()),i=t(),a=new AbortController;process.on("SIGINT",()=>{a.abort()}),await new Promise((s,c)=>{Qt(i.dialerCampaigns.liveStats({campaign_id:x("dialer_campaigns",r)},{signal:a.signal}),{onEvent:(d)=>{if(o==="json"){console.log(JSON.stringify(d));return}let u=new Date().toLocaleTimeString(),m=d.counters,y=d.waiting_capacity?"yes":"no";console.log(`${u} status=${d.status} calling=${d.calling} pending_retry=${d.pending_retry} answered=${m.answered_count} busy=${m.busy_count} failed=${m.failed_count} waiting_capacity=${y}`)},onError:(d)=>{if(d instanceof DOMException&&d.name==="AbortError"){s();return}c(d)},onSuccess:()=>{s()}})}).catch(In)}),n.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(r,o)=>{let{format:i,fields:a}=S(e.opts()),s=await b(t().dialerAttempts.list({campaign_id:x("dialer_campaigns",r),status:se(o.status),contact_id:x("dialer_contacts",o.contact),page:Number(o.page),limit:Number(o.limit)}));if(i==="json"){let c=a?s.items.map((d)=>O(d,a)):s;v(c);return}L(["ID","#","Phone","Name","Status","Machine","Cause","Started","Duration","Record"],s.items.map((c)=>({ID:c.id,"#":c.attempt_number,Phone:c.phone_number??"—",Name:c.contact_name??"—",Status:c.status??"—",Machine:Jo(c.machine_type),Cause:c.hangup_cause??"—",Started:c.started_at?Me(c.started_at):"—",Duration:c.duration_s!=null?Ce(c.duration_s*1000):"—",Record:c.call_record_id??"—"}))),ee(s)})}import{readFile as ZP}from"node:fs/promises";var qP={format:"bubble",side:"right",label:"",teaser:""},vx=(e,t)=>e.trim().slice(0,t),BP=(e)=>vx(e.label,pn.label.max),HP=(e)=>vx(e.teaser,pn.teaser.max);function Oo(e,t){return` ${e}="${t.replaceAll("&","&").replaceAll('"',""")}"`}function Sx(e){return`${$t(e)}/webchat/v1/loader.js`}function WP(e){return`<niva-chat key="${e}" mode="inline"></niva-chat>`}function GP(e,t,n=qP){let r=BP(n),o=HP(n),i=[Oo("data-key",t),n.format==="side"?Oo("data-layout","side"):"",n.side==="left"?Oo("data-side","left"):"",n.format==="side"&&r!==""?Oo("data-label",r):"",n.format==="bubble"&&o!==""?Oo("data-teaser",o):""].join("");return`<script async src="${Sx(e)}"${i}></script>`}function xx(e,t,n){if(n.format==="inline")return{script:`<script async src="${Sx(e)}"></script>`,element:WP(t)};return{script:GP(e,t,n),element:null}}var YP=new Set(["bot_token","webhook_secret","sip_password_encrypted","sip_password_iv"]),JP="<hidden>";function We(e){C(`Error: ${e}`),process.exit(A.USAGE_ERROR)}function tn(e){return x("channels",e)}function Uu(e){return x("connectors",e)}function ju(e){return x("visual_plans",e)}function Ex(e){return x("schedules",e)}function wx(e){let t=Ee(e);if(t==null)return e;return Object.fromEntries(Object.entries(t).map(([n,r])=>[n,YP.has(n)?JP:r]))}function Vu(e){return{...e,config:wx(e.config)}}async function XP(e){let t=e==="-"?await Fe():await ZP(e,"utf-8"),n;try{n=JSON.parse(t)}catch{We(`invalid config file "${e}": not valid JSON.`)}if(!ge(n))We(`invalid config file "${e}": expected a JSON object.`);return n}function Cx(e){return e.option("--bot-token-env <VAR>","Telegram bot token, read from this environment variable").option("--bot-token-stdin","Telegram bot token, read from stdin")}function Ax(e){return Cx(e).option("--phone-number-id <id>","WhatsApp phone_number_id (see: niva channels whatsapp-numbers <connector_id>)").option("--allow-groups","Telegram: let the bot answer in groups").option("--session-timeout <minutes>","Chat session timeout in minutes (5-10080)").option("--file <path>","JSON file with the channel config object (- for stdin); flags override its keys")}async function Tx(e){if(e.botTokenEnv!=null&&e.botTokenStdin===!0)We("--bot-token-env and --bot-token-stdin are mutually exclusive.");if(e.botTokenEnv!=null){let t=process.env[e.botTokenEnv];if(t==null||t==="")We(`environment variable ${e.botTokenEnv} is not set or empty (--bot-token-env).`);return t}if(e.botTokenStdin===!0)return(await Fe()).replace(/\r?\n$/,"");return}async function Rx(e){if(e.file==="-"&&e.botTokenStdin===!0)We("--file - and --bot-token-stdin both read stdin; pass the token with --bot-token-env instead.");let t=e.file==null?{}:await XP(e.file),n=await Tx(e);if(n!=null)t.bot_token=n;if(e.phoneNumberId!=null)t.phone_number_id=e.phoneNumberId;if(e.allowGroups===!0)t.allow_groups=!0;if(e.sessionTimeout!=null)t.session_timeout_minutes=Number(e.sessionTimeout);if(e.origin!=null)t.allowed_origins=e.origin;return Object.keys(t).length===0?void 0:t}function QP(e,t){return[...t??[],e]}function e$(e){if(e.visual_plan_id==null)return"-";return`${e.visual_plan_name??"?"} (${e.visual_plan_id})`}function t$(e){if(e.visual_plan_id==null)return;let t=e.visual_plan_published_version==null?"never published":"v"+e.visual_plan_published_version;return e.visual_plan_has_unpublished_changes?t+" (unpublished changes)":t}function n$(e){let t=Ee(wx(e.config))??{},n=Object.entries(t).map(([r,o])=>({label:r,value:typeof o==="object"&&o!==null?JSON.stringify(o):String(o)}));J([{title:`${e.name} (${e.id})`,rows:[{label:"Type",value:e.channel_type},{label:"Description",value:e.description},{label:"Identifier",value:e.identifier},{label:"Active",value:e.is_active?"yes":"no"},{label:"Plan",value:e$(e)},{label:"Plan version",value:t$(e)},{label:"Schedule",value:e.schedule_id==null?void 0:`${e.schedule_name??"?"} (${e.schedule_id})`},{label:"Connector",value:e.connector_id},{label:"Webhook URL",value:e.webhook_url},{label:"Calls (7d)",value:e.calls_7d?.total},{label:"Last call",value:e.last_call_at?.toISOString()},{label:"Created",value:e.created_at.toISOString()},{label:"Updated",value:e.updated_at.toISOString()}]},{title:"Config (credentials hidden)",rows:n.length>0?n:[{label:"(empty)",value:""}]}])}function Ku(e,t,n,r){if(n==="json"){let o=Vu(e);v(r?O(o,r):o);return}N(`Channel ${t}: ${e.name} (${e.id})`)}function r$(e){return e.readiness.ready?"ready":"not ready"}function o$(e,t,n){e.command("list").description("List channels with type, plan, active state and 7-day call count; --alert shows the ones needing attention").option("--type <type>","Filter by channel type (sip, whatsapp, telegram, webchat)").option("--active","Only active channels").option("--inactive","Only inactive channels").option("--alert","Only channels with an alert: active with no plan, never-published plan, or failed WhatsApp webhook sync").option("--search <term>","Search by name").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(r)=>{if(r.active===!0&&r.inactive===!0)We("--active and --inactive are mutually exclusive.");let{format:o,fields:i}=S(t.opts()),a=await b(n().channels.list({page:Number(r.page),limit:Number(r.limit),...r.search!=null&&{search:r.search},...r.type!=null&&{channel_type:r.type},...r.active===!0&&{is_active:!0},...r.inactive===!0&&{is_active:!1},...r.alert===!0&&{alert:!0}})),s=a.items.map((c)=>Vu(c));if(o==="json"){v(i?s.map((c)=>O(c,i)):{...a,items:s});return}L(["ID","Type","Name","Identifier","Plan","Active","Calls 7d"],s.map((c)=>({ID:c.id,Type:c.channel_type,Name:c.name,Identifier:c.identifier??"-",Plan:c.visual_plan_name??"-",Active:c.is_active?"yes":"no","Calls 7d":c.calls_7d?.total??"-"}))),ee(a)})}function i$(e,t,n){e.command("show <id>").description("Show a channel: plan, schedule, connector, webhook URL and config (credentials hidden)").action(async(r)=>{let{format:o,fields:i}=S(t.opts()),a=await b(n().channels.getById({channel_id:tn(r)}));if(a==null)C(`Channel not found: ${r}`),process.exit(A.NOT_FOUND);if(o==="json"){let s=Vu(a);v(i?O(s,i):s);return}n$(a)})}function a$(e,t,n){let r=e.command("create <type>").description("Create a channel of type sip, whatsapp, telegram or webchat. WhatsApp needs --connector and --phone-number-id; Telegram needs a bot token (--bot-token-env or --bot-token-stdin); webchat needs at least one --origin (the site domain the chat may open on).").requiredOption("--name <name>","Channel name").option("--description <text>","Channel description").option("--identifier <id>","Provider-facing identifier (e.g. the SIP number); unique within the organization").option("--connector <id>","WhatsApp: connector (conn_...) that owns the account").option("--plan <id>","Visual plan (vp_...) that answers on this channel").option("--schedule <id>","Schedule (sched_...) that gates when the channel is available").option("--origin <domain>","Webchat: a site domain the chat may open on (repeat for more)",QP).option("--inactive","Create the channel switched off");Ax(r).action(async(o,i)=>{let{format:a,fields:s}=S(t.opts());if(o==="webchat"&&(i.origin??[]).length===0)We("a webchat channel needs at least one --origin <domain>: the site the chat may open on.");if(o!=="webchat"&&i.origin!=null)We("--origin only applies to a webchat channel.");let c=await Rx(i),d={channel_type:se(o),name:i.name,...i.description!=null&&{description:i.description},...i.identifier!=null&&{identifier:i.identifier},...i.connector!=null&&{connector_id:Uu(i.connector)},...i.plan!=null&&{visual_plan_id:ju(i.plan)},...i.schedule!=null&&{schedule_id:Ex(i.schedule)},...i.inactive===!0&&{is_active:!1},...c!=null&&{config:c}},u=await b(n().channels.create(d));Ku(u,"created",a,s)})}function s$(e,t,n){let r=e.command("update <id>").description("Change a channel: name, plan, schedule, connector or config (merged into the stored config). Moving a channel off a plan it already has needs --reassign.").option("--name <name>","New name").option("--description <text>","New description").option("--identifier <id>","New provider-facing identifier").option("--connector <id>","WhatsApp: connector (conn_...) that owns the account").option("--plan <id>","Attach this visual plan (vp_...)").option("--detach-plan","Detach the current plan").option("--schedule <id>","Attach this schedule (sched_...)").option("--detach-schedule","Detach the current schedule").option("--reassign","Allow moving the channel to another plan even when it already has one");Ax(r).action(async(o,i)=>{if(i.plan!=null&&i.detachPlan===!0)We("--plan and --detach-plan are mutually exclusive.");if(i.schedule!=null&&i.detachSchedule===!0)We("--schedule and --detach-schedule are mutually exclusive.");let{format:a,fields:s}=S(t.opts()),c=await Rx(i),d={channel_id:tn(o),...i.name!=null&&{name:i.name},...i.description!=null&&{description:i.description},...i.identifier!=null&&{identifier:i.identifier},...i.connector!=null&&{connector_id:Uu(i.connector)},...i.plan!=null&&{visual_plan_id:ju(i.plan)},...i.detachPlan===!0&&{visual_plan_id:null},...i.schedule!=null&&{schedule_id:Ex(i.schedule)},...i.detachSchedule===!0&&{schedule_id:null},...i.reassign===!0&&{reassign:!0},...c!=null&&{config:c}};if(Object.keys(d).length===1)We("nothing to update: pass at least one of --name, --plan, --schedule, --connector, --file, ...");let u=await b(n().channels.update(d));Ku(u,"updated",a,s)})}function c$(e,t,n){e.command("assign <id>").description("Point a channel at a visual plan so it answers with it; the plan must be published. Moving a channel off a plan it already has needs --reassign.").requiredOption("--plan <plan_id>","Visual plan (vp_...) to answer with").option("--reassign","Allow moving the channel to another plan even when it already has one").action(async(r,o)=>{let{format:i,fields:a}=S(t.opts()),s=await b(n().channels.update({channel_id:tn(r),visual_plan_id:ju(o.plan),...o.reassign===!0&&{reassign:!0}}));Ku(s,"assigned to plan "+o.plan,i,a)})}function l$(e,t,n){for(let[r,o]of[["enable",!0],["disable",!1]])e.command(`${r} <id>`).description(o?"Switch a channel on so it answers calls and chats with its plan":"Switch a channel off; it stops answering until enabled again").action(async(i)=>{let{format:a}=S(t.opts());if(await b(n().channels.toggle({channel_id:tn(i),is_active:o})),a==="json"){v({id:i,is_active:o});return}N(`Channel ${o?"enabled":"disabled"}: ${i}`)})}function d$(e,t,n){e.command("delete <id>").description("Delete a channel (needs --yes in a non-interactive shell)").action(async(r)=>{let{format:o}=S(t.opts()),i=t.opts().yes===!0;if(await Te(`Delete channel ${r}?`,{yes:i}),await b(n().channels.delete({channel_id:tn(r)})),o==="json"){v({id:r,deleted:!0});return}N(`Channel deleted: ${r}`)})}function u$(e,t,n){let r=e.command("test-connection").description("Check a Telegram bot token against Telegram without creating a channel; prints the bot username. Telegram is the only type the API accepts.");Cx(r).action(async(o)=>{let{format:i}=S(t.opts()),a=await Tx(o);if(a==null)We("pass the bot token with --bot-token-env <VAR> or --bot-token-stdin.");let s=await b(n().channels.testConnection({channel_type:"telegram",config:{bot_token:a}}));if(i==="json")v(s);else if(s.ok)N("Telegram bot reachable"+(s.username==null?"":": @"+s.username));else C(`Telegram connection failed: ${s.error??"unknown error"}`);if(!s.ok)process.exit(A.GENERAL_ERROR)})}function p$(e,t,n){e.command("setup-whatsapp-sip <id>").description("Configure WhatsApp calling (SIP) with Meta for a WhatsApp channel, so voice calls reach NIVA. Run it after the channel exists.").action(async(r)=>{let{format:o}=S(t.opts());if(await b(n().channels.setupWhatsappSip({channel_id:tn(r)})),o==="json"){v({id:r,ok:!0});return}N(`WhatsApp SIP configured for channel ${r}`)})}function m$(e,t,n){e.command("whatsapp-connectors").description("List the WhatsApp connectors a WhatsApp channel can use (id, name, status, account)").action(async()=>{let{format:r,fields:o}=S(t.opts()),i=await b(n().channels.whatsappConnectors());if(r==="json"){v(o?i.map((a)=>O(a,o)):i);return}L(["ID","Name","Status","Account"],i.map((a)=>({ID:a.id,Name:a.name,Status:a.status,Account:a.account_label??"-"})))})}function f$(e,t,n){e.command("whatsapp-numbers <connector_id>").description("List the WhatsApp phone numbers of a connector with readiness and the bound channel; the ID column is the --phone-number-id for channels create").option("--refresh","Bypass the 5-minute cache and read the numbers again").action(async(r,o)=>{let{format:i,fields:a}=S(t.opts()),s=await b(n().channels.whatsappNumbers({connector_id:Uu(r),refresh:o.refresh===!0}));if(i==="json"){v(a?s.map((c)=>O(c,a)):s);return}L(["ID","Number","Name","Readiness","Channel"],s.map((c)=>({ID:c.id,Number:c.display_phone_number,Name:c.verified_name,Readiness:r$(c),Channel:c.channel==null?"-":`${c.channel.name} (${c.channel.id})`})))})}function g$(e){if(e.inline===!0)return"inline";return e.layout==="side"?"side":"bubble"}function h$(e,t,n,r){let o=e.command("webchat").description("Webchat channels: install snippet and key rotation");o.command("snippet <channel_id>").description("Print the install snippet of a webchat channel, exactly what the Installation box in the app builds: the script tag (format and side go on it), plus the <niva-chat> element with --inline").option("--layout <layout>","Launcher format: bubble (default) or side").option("--side <side>","Launcher side: right (default) or left").option("--label <text>","Side tab text (layout side only, 24 characters)").option("--teaser <text>","Invite beside the bubble for this page (layout bubble only, 160 characters)").option("--inline","Embed the chat in the page: the script without the key plus the <niva-chat> element").action(async(i,a)=>{let{format:s}=S(t.opts());if(a.layout!=null&&a.layout!=="bubble"&&a.layout!=="side")We(`--layout must be bubble or side, got "${a.layout}".`);if(a.side!=null&&a.side!=="right"&&a.side!=="left")We(`--side must be right or left, got "${a.side}".`);if(a.inline===!0&&(a.layout!=null||a.side!=null||a.label!=null||a.teaser!=null))We("--inline embeds the chat in the page: it takes no --layout, --side, --label or --teaser.");let c=await b(n().channels.getById({channel_id:tn(i)}));if(c==null)C(`Channel not found: ${i}`),process.exit(A.NOT_FOUND);if(c.channel_type!=="webchat"||c.identifier==null)We(`channel ${i} is not a webchat channel.`);let d={format:g$(a),side:a.side==="left"?"left":"right",label:a.label??"",teaser:a.teaser??""},u=xx(r().url,c.identifier,d);if(s==="json"){v(u);return}if(console.log(u.script),u.element!=null)console.log(u.element)}),o.command("rotate-key <channel_id>").description("Replace the public key of a webchat channel and print the new one. The old key stops working at once: every site with the old snippet loses the chat and open conversations are closed (needs --yes in a non-interactive shell)").action(async(i)=>{let{format:a}=S(t.opts()),s=t.opts().yes===!0;await Te(`Rotate the public key of ${i}? Sites with the old snippet stop showing the chat.`,{yes:s});let c=await b(n().channels.rotateWebchatKey({channel_id:tn(i)}));if(a==="json"){v(c);return}console.log(c.public_key),ht("Update the snippet on every site: niva channels webchat snippet "+i)}),o.command("rotate-secret <channel_id>").description("Generate a new identity secret for a webchat channel and print it once to stdout; it cannot be read again. The previous secret keeps verifying identity tokens for 24 hours (needs --yes in a non-interactive shell)").action(async(i)=>{let{format:a}=S(t.opts()),s=t.opts().yes===!0;await Te(`Generate a new identity secret for ${i}?`,{yes:s});let c=await b(n().channels.rotateWebchatSecret({channel_id:tn(i)}));if(a==="json"){v(c);return}console.log(c.secret),ht("Shown once: store it now. The previous secret keeps working for 24 hours.")})}var y$=/unknown option '([^']*)'/;function _$(e){let t=y$.exec(e)?.[1];if(t==null)return e;let n=t.indexOf("=");if(n<0)return e;let r=t.slice(0,n),o=e.replace(`'${t}'`,`'${r}=<redacted>'`);if(r!=="--bot-token")return o;return`${o}
|
|
106
|
+
Use --bot-token-env <VAR> or --bot-token-stdin for a credential instead of a literal value.`}function Ix(e,t,n){let r=e.createCommand("channels").description("Channels (SIP, WhatsApp, Telegram, webchat): the entry points a plan answers on");r.configureOutput({outputError:(o,i)=>i(_$(o))}),e.addCommand(r),o$(r,e,t),i$(r,e,t),a$(r,e,t),s$(r,e,t),c$(r,e,t),l$(r,e,t),d$(r,e,t),u$(r,e,t),p$(r,e,t),m$(r,e,t),f$(r,e,t),h$(r,e,t,n)}import{readFile as F$}from"node:fs/promises";class qu{sets=new Map;on(e,t){let n=this.sets.get(e)??new Set;this.sets.set(e,n);let r=(o)=>{t(o)};return n.add(r),()=>void n.delete(r)}async once(e){return new Promise((t)=>{let n=this.on(e,(r)=>{n(),t(r)})})}emit(e,t){for(let n of Array.from(this.sets.get(e)??[]))try{n(t)}catch(r){queueMicrotask(()=>{throw r})}}}class Bu extends Error{name="NivaError"}class Ie extends Bu{name="NivaChatError";code;fatal;constructor(e,t,n){super(t,n.cause===void 0?void 0:{cause:n.cause});this.code=e,this.fatal=n.fatal}}function Tr(e){try{let t=new URL(e),n=t.searchParams.get("session");if(n===null||n==="")return null;if(t.protocol!=="wss:"&&t.protocol!=="ws:")return null;let o=`${t.protocol==="wss:"?"https:":"http:"}//${t.host}/api/v1/chat`;return{base:o,url:`${o}/media`,session:n}}catch{return null}}function b$(e){switch(e){case"CHAT_MEDIA_TOO_LARGE":case"CHAT_MEDIA_UNSUPPORTED":case"WEBCHAT_SESSION_INVALID":case"WEBCHAT_ORIGIN_DENIED":case"CHAT_MEDIA_NOT_FOUND":case"CHAT_SESSION_NOT_FOUND":return e;default:return"UPLOAD_FAILED"}}var v$={code:"UPLOAD_FAILED",message:"The file could not be uploaded"};function Gn(e,t,n=v$){let r=typeof e==="object"&&e!==null?e:{},o=Reflect.get(r,"message"),i=b$(Reflect.get(r,"code")),a=i==="UPLOAD_FAILED"?n.code:i;return new Ie(t===429?"RATE_LIMITED":a,typeof o==="string"?o:n.message,{fatal:!1})}var Hu={code:"END_FAILED",message:"The conversation could not be ended"};async function Wu(e){let t=e.wsUrl===null?null:Tr(e.wsUrl);if(t===null)throw new Ie("OFFLINE","There is no chat session to end",{fatal:!1});let n=`${t.base}/sessions/${encodeURIComponent(t.session)}`,r={method:"DELETE",headers:{authorization:`Bearer ${t.session}`},keepalive:!0},o;try{o=await(e.fetch===void 0?globalThis.fetch(n,r):e.fetch(n,r))}catch(i){throw new Ie(Hu.code,Hu.message,{fatal:!1,cause:i})}if(!o.ok)throw Gn(await o.json().catch(()=>null),o.status,Hu)}function Ox(e){return typeof e==="object"&&"file"in e}function S$(e){let t=Reflect.get(e,"name");return typeof t==="string"&&t!==""?t:"file"}function Nx(e){return{type:"file",name:S$(e.file),content_type:e.file.type,size_bytes:e.file.size,...e.caption===void 0||e.caption===""?{}:{caption:e.caption},file:e.file}}function kx(e){if(typeof e!=="string")return e;let t=e.trim();return t===""?null:{type:"text",text:t}}function Dx(e){if("label"in e)return{type:"button_reply",button_id:e.id,button_text:e.label};return{type:"list_reply",list_id:e.id,list_title:e.title}}function Px(e,t){return Object.freeze({author:"visitor",id:`local-${Date.now().toString(36)}-${t}`,ts:Date.now(),message:e,delivery:e.type==="file"?"uploading":"queued"})}var $x=25000,Mx=8,Lx=1,Gu=(e)=>Math.min(30000,1000*2**e);function zx(e){if(e==="CAPACITY_EXCEEDED"||e==="RATE_LIMITED"||e==="INVALID_MESSAGE"||e==="MEDIA_NOT_FOUND")return e;if(e==="INVALID_JSON")return"INVALID_MESSAGE";return"EXECUTION_ERROR"}var Fx=(e)=>e==="RATE_LIMITED"||e==="INVALID_MESSAGE"||e==="INVALID_JSON"||e==="MEDIA_NOT_FOUND";function Ux(e){let t=globalThis;if(typeof t!=="object"||t===null||typeof Reflect.get(t,"addEventListener")!=="function"||typeof Reflect.get(t,"removeEventListener")!=="function")return null;return globalThis.addEventListener("online",e),()=>globalThis.removeEventListener("online",e)}var jx={4009:["SUPERSEDED","Another connection took over this chat session"],1008:["UNAVAILABLE","The chat is no longer available for this session"]};var Ea=(e)=>e.author==="visitor"&&e.message.type==="file",Vx=(e)=>e.filter((t)=>Ea(t)&&t.delivery==="uploading").map((t)=>t.id),Kx=(e)=>e.find((t)=>t.author==="visitor"&&(t.delivery==="queued"||t.delivery==="uploading"));function qx(e,t){if(e.message.type!=="file")return e.message;if(t===null)return null;return{type:"media",media_id:t,...e.message.caption===void 0?{}:{caption:e.message.caption}}}function Zu(e,t){if(e.message.type!=="file")return e;let{media_id:n,...r}=e.message;return{...e,message:t===null?r:{...r,media_id:t}}}var Bx=(e)=>Ea(e)&&(e.delivery==="uploading"||e.delivery==="queued")?Object.freeze({...e,delivery:"failed"}):e,Hx=(e)=>e.filter((t)=>t.author==="visitor"&&(t.delivery==="queued"||Ea(t)&&t.delivery==="uploading")).map((t)=>Bx(t)).map((t)=>Ea(t)?Zu(t,null):t),Wx=(e)=>e.map((t)=>Object.freeze(Bx(t)));function Gx(e){return Object.freeze({author:"plan",id:e.id,seq:e.seq,ts:e.ts,message:e.message})}function Zx(e,t,n,r){let o;try{o=t===void 0?new WebSocket(e):t(e)}catch{return null}return o.onopen=()=>{if(n())r.open()},o.onmessage=(i)=>{let a=i.data;if(n())r.message(a)},o.onclose=(i)=>{if(n())r.close(i.code)},o.onerror=()=>{},o}function x$(e){return typeof e==="object"&&e!==null&&typeof Reflect.get(e,"getItem")==="function"&&typeof Reflect.get(e,"setItem")==="function"&&typeof Reflect.get(e,"removeItem")==="function"}function Yx(e){if(e==="none")return null;try{let t=Reflect.get(globalThis,e==="tab"?"sessionStorage":"localStorage");return x$(t)?t:null}catch{return null}}function E$(e){if(typeof e!=="object"||e===null)return!1;let t=Reflect.get(e,"author"),n=Reflect.get(e,"message");return(t==="plan"||t==="visitor")&&typeof Reflect.get(e,"id")==="string"&&typeof Reflect.get(e,"ts")==="number"&&typeof n==="object"&&n!==null}function Jx(e,t){try{let n=e.getItem(t);if(n===null)return null;let r=JSON.parse(n);if(typeof r!=="object"||r===null||Reflect.get(r,"v")!==1)return null;let o=Reflect.get(r,"wsUrl"),i=Reflect.get(r,"started"),a=Reflect.get(r,"lastSeq"),s=Reflect.get(r,"status"),c=Reflect.get(r,"messages");if(typeof o!=="string"||typeof i!=="boolean"||typeof a!=="number")return null;if(!Array.isArray(c))return null;return{wsUrl:o,started:i,lastSeq:a,status:s==="active"||s==="waiting_input"||s==="ended"?s:null,messages:c.filter((m)=>E$(m))}}catch{return null}}function w$(e){if(e.author!=="visitor"||e.message.type!=="file")return e;let{file:t,...n}=e.message;return{...e,message:n}}function Xx(e,t,n){try{e.setItem(t,JSON.stringify({v:1,...n,messages:n.messages.map((r)=>w$(r))}))}catch{}}function Yu(e,t){try{e.removeItem(t)}catch{}}class Ju{stops=new Map;has(e){return this.stops.has(e)}after(e,t,n){this.clear(e);let r=setTimeout(()=>{this.stops.delete(e),n()},t);this.stops.set(e,()=>clearTimeout(r))}every(e,t,n){this.clear(e);let r=setInterval(n,t);this.stops.set(e,()=>clearInterval(r))}clear(e){this.stops.get(e)?.(),this.stops.delete(e)}clearAll(){for(let e of this.stops.values())e();this.stops.clear()}}var Xu={code:"DOWNLOAD_FAILED",message:"The file could not be downloaded"},Qu=()=>new DOMException("The download was aborted","AbortError");function Qx(e){let t=new Set,n=!1;async function r(o,i){if(n||i?.signal?.aborted===!0)throw Qu();let a=e.wsUrl(),s=a===null?null:Tr(a);if(s===null)throw new Ie("OFFLINE","There is no chat session to download the file with",{fatal:!1});let c=new AbortController,d=()=>c.abort();i?.signal?.addEventListener("abort",d,{once:!0}),t.add(c);try{let u=`${s.url}/${encodeURIComponent(o)}`,m={method:"GET",headers:{authorization:`Bearer ${s.session}`},signal:c.signal},y=await(e.fetch===void 0?globalThis.fetch(u,m):e.fetch(u,m));if(!y.ok)throw Gn(await y.json().catch(()=>null),y.status,Xu);let _=await y.blob();if(c.signal.aborted)throw Qu();return _}catch(u){if(c.signal.aborted)throw Qu();if(u instanceof Ie)throw u;throw new Ie(Xu.code,Xu.message,{fatal:!1,cause:u})}finally{t.delete(c),i?.signal?.removeEventListener("abort",d)}}return{get:r,abortAll(){for(let o of t)o.abort();t.clear()},close(){n=!0}}}async function C$(e){let t=new FormData;t.set("file",e.file,e.name);let n={method:"POST",headers:{authorization:`Bearer ${e.target.session}`},body:t,signal:e.signal},r;try{r=await(e.fetch===void 0?globalThis.fetch(e.target.url,n):e.fetch(e.target.url,n))}catch(a){if(e.signal.aborted)throw a;throw new Ie("UPLOAD_FAILED","The file could not be uploaded",{fatal:!1,cause:a})}let o=await r.json().catch(()=>null);if(!r.ok)throw Gn(o,r.status);let i=typeof o==="object"&&o!==null?Reflect.get(o,"id"):void 0;if(typeof i!=="string")throw Gn(null);return i}function eE(e){let t=new Map,n=Qx(e),r=0;function o(i){let a=t.get(i),s=e.wsUrl();if(a?.controller!==null||s===null)return;let c=Tr(s);if(c===null){e.settle(i,new Ie("UPLOAD_FAILED","The file could not be uploaded",{fatal:!1}));return}let d=new AbortController;a.controller=d;let u=r,m=()=>e.stopped()||u!==r||d.signal.aborted;C$({target:c,file:a.file,name:a.name,signal:d.signal,fetch:e.fetch}).then((y)=>{if(m())return;a.controller=null,a.mediaId=y,e.settle(i,"queued")},(y)=>{if(m())return;a.controller=null,e.settle(i,y instanceof Ie?y:new Ie("UPLOAD_FAILED","The file could not be uploaded",{fatal:!1,cause:y}))})}return{add(i,a,s){t.set(i,{file:a,name:s,mediaId:null,controller:null})},start:o,has:(i)=>t.has(i),mediaId:(i)=>t.get(i)?.mediaId??null,retryAs:(i)=>t.get(i)?.mediaId===null?"uploading":"queued",dropMediaId(i){let a=t.get(i);if(a!==void 0)a.mediaId=null},dropAllMediaIds(){for(let i of t.values())i.mediaId=null},getFile:n.get,closeDownloads:()=>n.close(),abortAll(){r+=1,n.abortAll();for(let i of t.values())i.controller?.abort(),i.controller=null}}}var A$=new Set(["text","media","location","buttons","list","carousel","template"]),T$=new Set(["active","waiting_input","ended"]);function ep(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function R$(e){return ep(e)&&typeof e.type==="string"&&A$.has(e.type)}function I$(e){return typeof e==="string"&&T$.has(e)}function O$(e,t){let{id:n,ts:r,message:o}=e;if(typeof n!=="string"||typeof r!=="number"||!R$(o))return null;return{type:"message",seq:t,id:n,ts:r,message:o}}function N$(e,t){let{code:n,message:r}=e;if(typeof n!=="string")return null;return{type:"error",seq:t,code:n,message:typeof r==="string"?r:n}}function tE(e){if(!ep(e))return null;let t=e.type;if(t==="trace")return{type:t};let n=e.seq;if(typeof n!=="number")return null;switch(t){case"connected":case"pong":return{type:t,seq:n};case"typing":return typeof e.active==="boolean"?{type:t,seq:n,active:e.active}:null;case"state":return I$(e.status)?{type:t,seq:n,status:e.status}:null;case"error":return N$(e,n);case"message":return O$(e,n);default:return null}}function k$(e){if(ep(e)&&e.type==="replay"){let{seq:t,messages:n}=e;if(typeof t!=="number"||!Array.isArray(n))return null;let r=[],o=n;for(let i of o){let a=tE(i);if(a!==null)r.push(a)}return{type:"replay",seq:t,messages:r}}return tE(e)}function nE(e){if(typeof e!=="string")return null;try{return k$(JSON.parse(e))}catch{return null}}function rE(e,t){return e.filter((n)=>n.type!=="trace"&&n.seq>t).sort((n,r)=>n.seq-r.seq)}function tp(e){let t=e.storageKey??"niva-chat",n=Yx(e.persist??"tab"),r=new qu,o=[],i=null,a=!1,s="connecting",c=0,d=!1,u=null,m=null,y=0,_=0,E=0,k=0,V=new Ju,G=!1,re=!1,ct=!1,tt=!1,fe=!1,X=null,Ge=!1,rn=!1,tr=0,vn=!1,It=0,Uo=0,Ze=eE({wsUrl:()=>u,stopped:()=>re,fetch:e.fetch,settle:(R,Z)=>nt(()=>{if(Ko(R,(_e)=>({..._e,delivery:Z==="queued"?"queued":"failed"})),Z!=="queued")r.emit("error",Z)})}),Ut=!1,Pa=null,jo=$a();function $a(){return Object.freeze({messages:Object.freeze([...o]),connection:s,status:i,typing:a})}function Vo(){if(nC(),!Ut)return;Ut=!1,jo=$a(),r.emit("change",jo)}function nt(R){R(),fC(),Vo()}function nC(){if(n===null||ct||u===null)return;Xx(n,t,{wsUrl:u,started:d,lastSeq:c,status:i,messages:o})}function Sn(R){if(s===R)return;s=R,Ut=!0,r.emit("connection",R)}function Nr(R){if(a===R)return;a=R,Ut=!0,r.emit("typing",R)}function rC(R){if(i===R)return;i=R,Ut=!0,r.emit("status",R)}function Ko(R,Z){let _e=(qe)=>Object.freeze(Ze.has(R)?Zu(Z(qe),Ze.mediaId(R)):Z(qe));o=o.map((qe)=>qe.author==="visitor"&&qe.id===R?_e(qe):qe),Ut=!0}function kr(R,Z,_e){r.emit("error",new Ie(R,Z,{fatal:_e}))}function Dr(R){if(m?.readyState!==Lx)return!1;try{return m.send(JSON.stringify(R)),!0}catch{return!1}}function qo(){V.clearAll(),G=!1}function Ma(){rn=!1,tr=0,V.clear("start")}let xn=()=>!re;function La(){y+=1;let R=m;if(m=null,fe=!1,Ma(),R===null)return;try{R.close(1000)}catch{}}function Bo(){if(Nr(!1),!xn())return;if(k>=Mx){Sn("offline"),kr("OFFLINE","Could not reach the chat; will try again when the browser is back online",!1);return}let R=Gu(k);if(k+=1,Sn("reconnecting"),!xn())return;V.after("retry",R,()=>{if(re)return;nt(Np)})}function Np(){if(!xn())return;if(u===null)Ho(!1);else if(It>0&&It%2===0)Ho(!0);else za()}function za(){let R=u;if(R===null||re)return;y+=1;let Z=y;G=!1,fe=!1,vn=!1;let _e=Zx(R,e.webSocket,()=>Z===y,{open:()=>{k=0},message:(qe)=>nt(()=>iC(qe)),close:(qe)=>nt(()=>pC(qe))});if(_e===null){It+=1,Bo();return}m=_e}function oC(){G=!1,V.every("ping",$x,()=>{if(re)return;if(G){nt(()=>{qo(),La(),Bo()});return}if(Dr({type:"ping"}))G=!0})}async function Ho(R){if(!xn())return;_+=1;let Z=_,_e;try{_e=await e.session()}catch(qe){if(Z!==_||!xn())return;nt(()=>{if(R)It+=1;if(qe instanceof Ie)r.emit("error",qe);if(qe instanceof Ie&&qe.fatal)Pr();else Bo()});return}if(Z!==_||!xn())return;nt(()=>{if(R){if(Dp(),Sn("connecting"),Vo(),kr("SESSION_EXPIRED","The chat session expired; a new conversation was started",!1),!xn())return}u=_e,d=!1,za()})}function iC(R){let Z=nE(R);if(Z===null)return;G=!1,aC(Z)}function aC(R){if(R.type==="connected")sC();else if(R.type==="replay")cC(R.messages);else if(R.type==="error")dC(R.code,R.message,R.seq);else if(R.type!=="pong"&&R.type!=="trace")Ua(R)}function sC(){let R=y;if(vn=!0,It=0,d)fe=!0,Dr({type:"resume",last_seq:c});else Dr({type:"start"}),d=!0,rn=!0;if(Sn("connected"),re||R!==y)return;oC()}function cC(R){if(fe=!1,lC(R),X!==null&&!Ge)Fa("queued")}function Fa(R){if(X!==null&&R!==null)Ko(X,(Z)=>({...Z,delivery:R}));X=null,tt=!1}function lC(R){for(let Z of rE(R,c))if(Z.type==="message"||Z.type==="typing"||Z.type==="state")Ua(Z);else if(Z.type==="error")c=Z.seq}function Ua(R){if(c=Math.max(c,R.seq),R.type==="typing"?R.active:R.type==="state"&&R.status==="active")Ge=!0;if(R.type!=="typing")X=null,Ma();switch(R.type){case"message":{if(o.some((_e)=>_e.author==="plan"&&_e.id===R.id))return;let Z=Gx(R);o=[...o,Z],Ut=!0,Nr(!1),r.emit("message",Z);return}case"typing":Nr(R.active);return;case"state":if(R.status!=="active")tt=!1;if(R.status==="ended")Nr(!1);rC(R.status);return}}function dC(R,Z,_e){if(c=Math.max(c,_e),R==="TURN_IN_FLIGHT"){Fa("queued"),tt=!0;return}if(R==="SESSION_EXPIRED"){Pp();return}if(R==="MODULE_DISABLED"){kp("MODULE_DISABLED",Z);return}if(R==="MEDIA_NOT_FOUND"&&X!==null)Ze.dropMediaId(X);if(Fa(Fx(R)?"failed":null),kr(zx(R),Z,!1),rn&&!re)uC()}function uC(){if(V.has("start"))return;let R=Gu(tr);tr+=1,V.after("start",R,()=>{if(!rn||s!=="connected")return;Dr({type:"start"})})}function pC(R){qo(),m=null,fe=!1,Ma();let Z=jx[R];if(Z!==void 0){kp(...Z);return}if(R===1011){Pp();return}if(!vn)It+=1;Bo()}function Pr(R=!1){if(re=!0,_+=1,Ze.abortAll(),!R)Ze.closeDownloads();if(qo(),La(),Pa?.(),Pa=null,!R)e.signal?.removeEventListener("abort",Lp);Nr(!1),Sn("closed")}function kp(R,Z){Pr(),Vo(),kr(R,Z,!0)}function Dp(){if(E+=1,qo(),La(),n!==null)Yu(n,t);Ze.abortAll(),Ze.dropAllMediaIds(),o=Hx(o),i=null,a=!1,c=0,d=!1,u=null,tt=!1,X=null,Ge=!1,It=0,Ut=!0}function Pp(){Dp(),k=0,Sn("connecting"),Vo(),kr("SESSION_EXPIRED","The chat session expired; a new conversation was started",!1),Ho(!1)}function mC(){if(re||s!=="offline")return;k=0,nt(()=>{Sn("reconnecting"),Np()})}function fC(){if(re)return;for(let _e of Vx(o))Ze.start(_e);if(s!=="connected"||fe||tt||i!=="waiting_input")return;let R=Kx(o);if(R===void 0||R.delivery==="uploading")return;let Z=qx(R,Ze.mediaId(R.id));if(Z===null||!Dr({type:"message",message:Z}))return;Ko(R.id,(_e)=>({..._e,delivery:"sent"})),tt=!0,X=R.id,Ge=!1}function $p(R){if(i==="ended")return;Uo+=1;let Z=Px(R,Uo);if(R.type==="file"&&R.file!==void 0)Ze.add(Z.id,R.file,R.name);nt(()=>{o=[...o,Z],Ut=!0})}function gC(R){let Z=Ox(R)?Nx(R):kx(R);if(Z!==null)$p(Z)}function hC(R){let Z=o.find((_e)=>_e.author==="visitor"&&_e.id===R);if(Z?.author!=="visitor"||Z.delivery!=="failed")return;if(Z.message.type==="file"&&!Ze.has(R))return;nt(()=>Ko(R,(_e)=>({..._e,delivery:Ze.retryAs(R)})))}function yC(R,Z){return r.on(R,Z)}async function _C(){if(i==="ended")return;let R=E;if(await Wu({wsUrl:u,fetch:e.fetch}),R===E&&!re)nt(()=>Ua({type:"state",seq:c,status:"ended"}))}function Mp(R){if(R?.forget===!0){if(i!=="ended")Wu({wsUrl:u,fetch:e.fetch}).catch(()=>{return});if(ct=!0,n!==null)Yu(n,t)}nt(Pr)}let Lp=()=>Mp(),$r=n===null?null:Jx(n,t);if($r!==null)({wsUrl:u,started:d,lastSeq:c,status:i}=$r),o=Wx($r.messages),jo=$a();if(Pa=Ux(mC),e.signal?.aborted===!0)nt(Pr);else if(e.signal?.addEventListener("abort",Lp,{once:!0}),$r===null)Ho(!1);else if($r.status==="ended")nt(()=>Pr(!0));else za();return{get state(){return jo},send:gC,select:(R)=>$p(Dx(R)),retry:hC,getFile:Ze.getFile,end:_C,close:Mp,on:yC,once:async(R)=>r.once(R)}}var st=on(jt(),1);function D$(e,t){let n=!0;return async()=>{if(n)return n=!1,e;if(t===void 0)throw new Ie("SESSION_EXPIRED","The chat session expired",{fatal:!0});return t()}}async function wa(e,t){P(`Connecting to ${e}`);let n=Pu(e)?{tls:{rejectUnauthorized:!1}}:void 0,r=!1,o=!1,i=tp({session:D$(e,t),persist:"none",webSocket:(a)=>new WebSocket(a,n)});throw i.on("connection",(a)=>{switch(a){case"connected":if(!r)r=!0,console.log(st.default.green(` Connected. Type a message and press Enter. Ctrl+C or /quit to exit.
|
|
107
|
+
`)),z$(i,()=>{o=!0});return;case"reconnecting":if(!r)C("Failed to connect"),process.exit(1);P(" Connection lost, reconnecting...");return;case"offline":C("Could not reach the server"),process.exit(r?0:1);return;case"closed":if(r)P(`
|
|
108
|
+
Disconnected`);else C("Failed to connect");process.exit(r||o?0:1);return;case"connecting":return}}),i.on("message",(a)=>{for(let s of L$({...a.message}))console.log(s)}),i.on("typing",(a)=>{process.stdout.write(a?st.default.dim(" bot is typing...\r"):" \r")}),i.on("status",(a)=>{if(a==="ended")console.log(st.default.dim(`
|
|
109
|
+
Session ended.`)),process.exit(0)}),i.on("error",(a)=>{console.log(st.default.red(` error: [${a.code}] ${a.message}`))}),await new Promise(()=>{}),Error("unreachable")}function hn(e,t){return e.replace(/^http/,"ws")+t}var Zn=st.default.cyan(" bot");function P$(e,t){let n=[`${Zn} ${e}`];for(let r of xt(t.buttons)){let o=st.default.dim(`[${String(r.id)}]`);n.push(` ${o} ${String(r.label)}`)}return n}function $$(e,t){let n=[`${Zn} ${e}`];for(let r of xt(t.sections)){n.push(` ${st.default.bold(String(r.title))}`);for(let o of xt(r.items)){let i=st.default.dim(`[${String(o.id)}]`);n.push(` ${i} ${String(o.title)}`)}}return n}function M$(e){return xt(e.cards).map((t)=>{let n=oe(t.description),r=n!=null?` — ${n}`:"";return`${Zn} ${st.default.bold(String(t.title))}${r}`})}function L$(e){let t=oe(e.type)??"",n=oe(e.text)??"";switch(t){case"text":return[`${Zn} ${n}`];case"buttons":return P$(n,e);case"list":return $$(n,e);case"media":{let r=st.default.dim(`[${String(e.media_type)}]`),o=typeof e.caption==="string"?` — ${e.caption}`:"";return[`${Zn} ${r} ${String(e.url)}${o}`]}case"location":{let r=typeof e.label==="string"?` (${e.label})`:"";return[`${Zn} ${st.default.dim("[location]")} ${String(e.lat)},${String(e.lng)}${r}`]}case"carousel":return M$(e);default:{let r=st.default.dim(`[${t}]`);return[`${Zn} ${r} ${JSON.stringify(e)}`]}}}function z$(e,t){let n=process.stdin;n.setEncoding("utf-8"),n.resume();let r=()=>{t(),e.close()},o="";n.on("data",(i)=>{o+=i;let a=o.split(`
|
|
110
|
+
`);o=a.pop();for(let s of a){let c=s.trim();if(c==="")continue;if(c==="/quit"||c==="/exit"){r();return}console.log(`${st.default.blue(" you")} ${c}`),e.send(c)}}),process.once("SIGINT",()=>{P(`
|
|
111
|
+
Closing...`),r()})}function oE(e,t,n){let r=e.command("chat").description("Test chat — interactive session against a visual plan (draft or published)");r.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(o,i)=>{let a=Cn(e.opts()),s=n(),c;if(i.editorState!=null){let m=await F$(i.editorState,"utf-8");c=JSON.parse(m)}if(a!=="json")P("Creating test chat session...");let d=async()=>b(t().testChat.createSession({planId:x("visual_plans",o),editor_state:c})),u=await d();if(a==="json"){v({...u,ws_url:hn(s.url,u.wsUrl)});return}N(`Session created: ${u.sessionId}`),await wa(hn(s.url,u.wsUrl),async()=>hn(s.url,(await d()).wsUrl))}),r.command("stop <sessionId>").description("Stop an active test chat session").action(async(o)=>{let i=Cn(e.opts());if(await b(t().testChat.stop({sessionId:x("chat_ws_sessions",o)})),i==="json"){v({session_id:o,stopped:!0});return}N(`Session ${o} stopped.`)})}function iE(e){let t=e.command("config").description("Manage CLI configuration");t.command("set <key> <value>").description("Set a config value (url, api-key)").action((n,r)=>{WS(n==="api-key"?"apiKey":n,r),N(`Set ${n} = ${r}`)}),t.command("get <key>").description("Get a config value (url, api-key)").action((n)=>{let r=n==="api-key"?"apiKey":n,i=Iu()[r];if(i==null){P(`(${n} not set)`);return}console.log(typeof i==="string"?i:JSON.stringify(i))}),t.command("show").description("Show current configuration").action(()=>{let n=Iu();v(n)})}var np={"channel.whatsapp":{consumers:["channel"]},"whatsapp.templates":{consumers:["node"]},"whatsapp.messages":{consumers:["node"]},"sms.send":{consumers:["node","notification"]},"email.send":{consumers:["node","notification"]},"tools.catalog":{consumers:["node","mcp"]},"calendar.events":{consumers:["node"]},"voice.agent":{consumers:["node"]},"phone.lookup":{consumers:["node","mcp"]},"verify.otp":{consumers:["node","mcp"]}};function aE(e){return Object.hasOwn(np,e)}var U$=Object.keys(np).filter((e)=>aE(e));class rp{#e;constructor(e){this.#e=e}static of(e){return new rp(e)}reveal(){return this.#e}toString(){return"[redacted]"}toJSON(){return"[redacted]"}[Symbol.for("nodejs.util.inspect.custom")](){return"[redacted]"}}function V$(e){return e.secret===!0}function Qe(e){let t={},n={},r={};for(let[o,i]of Object.entries(e.fields)){let a=i.secret===!0?l().min(1):i.schema,s=i.optional===!0?a.optional():a;if(t[o]=s,V$(i))r[o]=s;else n[o]=s}return{...e,fieldsSchema:g(t),configSchema:g(n),credentialsSchema:g(r)}}var op=Qe({kind:"elevenlabs",version:1,nameKey:"connectors.kinds.elevenlabs.name",descriptionKey:"connectors.kinds.elevenlabs.description",icon:"elevenlabs",category:"telephony",module:"ai",docsPath:"/configuracoes/conectores-elevenlabs",auth:{strategy:"fields"},fields:{api_key:{secret:!0,step:"api_key"},agent_numbers:{schema:l().default("{}"),step:"numbers"}},setup:[{id:"api_key",titleKey:"connectors.kinds.elevenlabs.setup.api_key"},{id:"numbers",titleKey:"connectors.kinds.elevenlabs.setup.numbers"}],provides:["voice.agent"]});var K$=Gy({protocol:/^https?$/u}).check(Gt((e)=>$t(e))).describe("Base URL of the Evolution API gateway, such as https://evolution.example.com."),ip=Qe({kind:"evolution_api",version:1,nameKey:"connectors.kinds.evolution_api.name",descriptionKey:"connectors.kinds.evolution_api.description",icon:"evolution",category:"messaging",module:"omnichannel",docsPath:"/configuracoes/conectores-evolution-api",auth:{strategy:"fields"},fields:{base_url:{schema:K$,step:"gateway"},api_key:{secret:!0,step:"api_key"}},identity:"base_url",setup:[{id:"gateway",titleKey:"connectors.kinds.evolution_api.setup.gateway",url:"https://doc.evolution-api.com"},{id:"api_key",titleKey:"connectors.kinds.evolution_api.setup.api_key"}],provides:["channel.whatsapp","whatsapp.messages"],webhook:{verification:"none",signature:"shared_secret_header",scope:"number"}});var ap=Qe({kind:"retell",version:1,nameKey:"connectors.kinds.retell.name",descriptionKey:"connectors.kinds.retell.description",icon:"retell",category:"telephony",module:"ai",docsPath:"/configuracoes/conectores-retell",auth:{strategy:"fields"},fields:{api_key:{secret:!0,step:"api_key"}},setup:[{id:"api_key",titleKey:"connectors.kinds.retell.setup.api_key"}],provides:["voice.agent"]});var sp=Qe({kind:"twilio",version:1,nameKey:"connectors.kinds.twilio.name",descriptionKey:"connectors.kinds.twilio.description",icon:"twilio",category:"telephony",module:"omnichannel",docsPath:"/configuracoes/conectores-twilio",auth:{strategy:"fields"},fields:{account_sid:{schema:l().regex(/^AC[0-9a-fA-F]{32}$/u),step:"credentials"},api_key_sid:{schema:l().regex(/^SK[0-9a-fA-F]{32}$/u),step:"credentials"},api_key_secret:{secret:!0,step:"credentials"},default_sender:{schema:l().regex(/^(MG[0-9a-fA-F]{32}|\+[1-9]\d{6,14})$/u),step:"senders",discover:"senders",optional:!0}},identity:"account_sid",discoverKeys:["verify_services"],setup:[{id:"credentials",titleKey:"connectors.kinds.twilio.setup.credentials",url:"https://console.twilio.com/"},{id:"senders",titleKey:"connectors.kinds.twilio.setup.senders"}],provides:["sms.send","phone.lookup","verify.otp"]});var sE=["us","eu"],cp=Qe({kind:"vapi",version:1,nameKey:"connectors.kinds.vapi.name",descriptionKey:"connectors.kinds.vapi.description",icon:"vapi",category:"telephony",module:"ai",docsPath:"/configuracoes/conectores-vapi",auth:{strategy:"fields"},fields:{api_key:{secret:!0,step:"api_key"},region:{schema:D(sE).default("us"),step:"region"}},setup:[{id:"api_key",titleKey:"connectors.kinds.vapi.setup.api_key"},{id:"region",titleKey:"connectors.kinds.vapi.setup.region"}],provides:["voice.agent"],webhook:{verification:"none",signature:"shared_secret_header",scope:"connector"}});var cE=["global","eu"],lp=Qe({kind:"openai_live",version:1,nameKey:"connectors.kinds.openai_live.name",descriptionKey:"connectors.kinds.openai_live.description",icon:"openai",category:"telephony",module:"ai",docsPath:"/configuracoes/conectores-openai-live",auth:{strategy:"fields"},fields:{api_key:{secret:!0,step:"api_key"},project_id:{schema:l().regex(/^proj_[A-Za-z0-9]+$/u).describe("Id of the OpenAI project with GPT-Live SIP enabled (proj_...)."),step:"project",discover:"project"},region:{schema:D(cE).default("global").describe("`eu` for a project with European data residency; it changes both the SIP and the API host."),step:"project"},webhook_secret:{secret:!0,step:"webhook",optional:!0}},identity:"project_id",setup:[{id:"api_key",titleKey:"connectors.kinds.openai_live.setup.api_key"},{id:"project",titleKey:"connectors.kinds.openai_live.setup.project",url:"https://platform.openai.com/settings"},{id:"webhook",titleKey:"connectors.kinds.openai_live.setup.webhook",url:"https://platform.openai.com/settings/project/webhooks"}],provides:["voice.agent"],webhook:{verification:"none",signature:"standard_webhooks",scope:"connector"}});var dp=Qe({kind:"whatsapp_business",version:1,nameKey:"connectors.kinds.whatsapp_business.name",descriptionKey:"connectors.kinds.whatsapp_business.description",icon:"whatsapp",category:"messaging",module:"omnichannel",docsPath:"/configuracoes/conectores-whatsapp",auth:{strategy:"fields"},fields:{app_id:{schema:l().regex(/^\d+$/),step:"meta_app"},app_secret:{secret:!0,step:"meta_app"},access_token:{secret:!0,step:"system_user"},waba_id:{schema:l().regex(/^\d+$/),step:"waba",discover:"wabas"},business_id:{schema:l().regex(/^\d+$/),step:"waba",optional:!0}},identity:"waba_id",setup:[{id:"meta_app",titleKey:"connectors.kinds.whatsapp_business.setup.meta_app",url:"https://developers.facebook.com/apps"},{id:"system_user",titleKey:"connectors.kinds.whatsapp_business.setup.system_user",url:"https://business.facebook.com/settings/system-users"},{id:"waba",titleKey:"connectors.kinds.whatsapp_business.setup.waba"}],provides:["channel.whatsapp","whatsapp.templates"],webhook:{verification:"meta_hub_challenge",signature:"meta_hmac_sha256",scope:"connector"}});var nn={whatsapp_business:dp,evolution_api:ip,twilio:sp,elevenlabs:op,retell:ap,vapi:cp,openai_live:lp};function No(e){return Object.hasOwn(nn,e)}var ko=Object.keys(nn).filter((e)=>No(e));var B$={...ji.whatsapp,supportsButtons:!1,maxButtons:0,supportsList:!1,supportsMedia:!1,mediaTypes:[],supportsLocation:!1,supportsTemplate:!1,sessionWindow:null,maxMediaSize:{}},Ere={whatsapp_business:{calling:!0,number_registration:!0,templates:!0,official:!0,chat_capabilities:ji.whatsapp},evolution_api:{calling:!1,number_registration:!1,templates:!1,official:!1,chat_capabilities:B$}};function H$(e){return e.replaceAll("_","-")}function up(e){return e.replaceAll(/_([a-z0-9])/g,(t,n)=>n.toUpperCase())}function Yn(e){let[t]=e.cli.split(" ");return t??e.cli}function W$(e,t){let n=H$(e);if(t.secret===!0)return[{source:"stdin",key:`${up(e)}Stdin`,cli:`--${n}-stdin`},{source:"env",key:`${up(e)}Env`,cli:`--${n}-env <VAR>`}];return[{source:"value",key:up(e),cli:`--${n} <value>`}]}function Rr(e){let t=nn[e].fields;return Object.entries(t).map(([n,r])=>({field:n,secret:r.secret===!0,optional:r.optional===!0,step:r.step,discover:"discover"in r?r.discover:void 0,options:W$(n,r)}))}function Do(){return ko.flatMap((e)=>Rr(e))}function pp(e,t){let n=e[t.key];if(n===void 0||n===!1)return!1;return t.source==="value"||n!==""}function lE(e){return Do().some((t)=>t.options.some((n)=>pp(e,n)))}function dE(e,t){let n=new Set(Rr(t).flatMap((i)=>i.options.map((a)=>a.key))),r=new Set,o=[];for(let i of Do())for(let a of i.options){if(n.has(a.key)||r.has(a.key))continue;if(r.add(a.key),pp(e,a))o.push(Yn(a))}return o}function uE(e){return Rr(e).flatMap((t)=>t.options.map((n)=>Yn(n)))}function pE(e,t){let n=[];for(let r of Rr(t))for(let o of r.options){if(!pp(e,o))continue;n.push({flag:r,option:o,source:o.source,raw:o.source==="stdin"?"":String(e[o.key])})}return n}function mE(){let e=new Set,t=[];for(let n of Do())for(let r of n.options){if(e.has(r.key))continue;e.add(r.key);let o=n.secret?"credential":"field";t.push({cli:r.cli,description:`${o} "${n.field}" (step "${n.step}")`})}return t}var Po;function ft(e){C(`Error: ${e}`),process.exit(A.USAGE_ERROR)}function Ca(e){if(!No(e))ft(`unknown connector kind "${e}". Known kinds: ${ko.join(", ")}.`);return e}function ke(e){return x("connectors",e)}function G$(e){return e.split("_").map((t)=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Z$(){let e=new Set(["--pin"]);for(let t of Do())if(t.secret)e.add(`--${t.field.replaceAll("_","-")}`);return e}var Y$=/unknown option '([^']*)'/;function J$(e){let t=Y$.exec(e)?.[1];if(t==null)return e;let n=t.indexOf("=");if(n<0)return e;let r=t.slice(0,n),o=e.replace(`'${t}'`,`'${r}=<redacted>'`);if(!Z$().has(r))return o;return`${o}
|
|
112
|
+
Use ${r}-env <VAR> or ${r}-stdin for a credential instead of a literal value.`}function X$(e){return e===""?"-":`···${e}`}function Q$(e,t){let n=nn[e].setup.find((r)=>r.id===t);return n!=null&&"url"in n?n.url:void 0}function mp(e){for(let t of mE())e.option(t.cli,t.description)}function fp(e,t){let n=dE(e,t);if(n.length>0)ft(`${n.join(", ")} is not a field of ${t}. Valid flags: ${uE(t).join(", ")}.`)}async function eM(e){if(e.source==="value")return e.raw;if(e.source==="env"){let t=process.env[e.raw];if(t==null||t==="")ft(`environment variable ${e.raw} is not set or empty (${Yn(e.option)}).`);return t}return(await Fe()).replace(/\r?\n$/,"")}async function gp(e,t){let n=pE(e,t),r=new Map;for(let a of n){let s=r.get(a.flag.field);if(s==null)r.set(a.flag.field,[a]);else s.push(a)}for(let[a,s]of r)if(s.length>1)ft(`multiple flags provide "${a}": ${s.map((c)=>Yn(c.option)).join(", ")}. Pass only one.`);let o=n.filter((a)=>a.source==="stdin");if(o.length>1)ft(`at most one field may read from stdin per invocation: ${o.map((a)=>Yn(a.option)).join(", ")}.`);let i={};for(let a of n)i[a.flag.field]=await eM(a);return i}function tM(e){return e.options.map(Yn).join(" or ")}async function nM(e,t,n,r){let o=Q$(e,t.step),i=o==null?`${t.field} (${t.step})`:`${t.field} (${t.step}: ${o})`;if(t.discover!=null){let a=await b(r().connectors.discover({kind:e,key:t.discover,fields:{...n}})),s=a.length===1?a[0]:void 0;if(s!=null)return ht(`Using the only ${t.field}: ${s.label} (${s.value})`),s.value;if(a.length>1){let c=a.map((d)=>({label:d.description==null?d.label:`${d.label} - ${d.description}`,value:d.value}));return Fi(i,c,Po==null?{output:process.stderr}:{ask:Po,output:process.stderr})}}if(t.secret)return Oc(`${i}: `,Po);return __(`${i}: `,Po)}async function rM(e,t,n){let r=[];for(let o of Rr(e)){if(t[o.field]!=null||o.optional)continue;if(!co()){r.push(o);continue}t[o.field]=await nM(e,o,t,n)}if(r.length>0)ft(`missing required field(s): ${r.map((o)=>tM(o)).join(", ")}.`);return t}function oM(e,t){if(!sn(e))Ct(e);let n=Tn(e);if(t==="json")v({error:n.code,message:n.message,data:n.data,hint:n.hint,retryable:n.retryable});else if(Rn(n),n.code==="CONNECTOR_TEST_FAILED")aM(xt(n.data?.checks));process.exit(n.exitCode)}async function Jn(e,t){try{return await e}catch(n){oM(n,t)}}function hE(e,t){if(!sn(e))Ct(e);let n=Tn(e);if(n.code!=="CONNECTOR_IN_USE")Ct(e);let r=xt(n.data?.channels).map((o)=>({id:oe(o.id)??"",name:oe(o.name)??""}));if(t==="json")v({error:n.code,message:n.message,channels:r,hint:n.hint,retryable:n.retryable});else Rn(n),L(["Channel ID","Name"],r.map((o)=>({"Channel ID":o.id,Name:o.name})));process.exit(n.exitCode)}function iM(e){return e.map((t)=>({Check:t.id,OK:t.ok?"yes":"no",Message:t.message??""}))}function aM(e){L(["Check","OK","Message"],e.map((t)=>({Check:oe(t.id)??"",OK:t.ok===!0?"yes":"no",Message:oe(t.message)??""})))}function sM(e){if(e.ready)return"ready";let t=[];if(!e.verified)t.push("not verified");if(!e.registered)t.push("not registered");if(!e.name_approved)t.push("name pending");return t.join(", ")}function cM(e){let t=[{title:"Connector",rows:[{label:"ID",value:e.id},{label:"Name",value:e.name},{label:"Kind",value:e.kind},{label:"Status",value:e.status},{label:"Account",value:e.account_label},{label:"External ID",value:e.external_id},{label:"Created",value:new Date(e.created_at).toLocaleString()},{label:"Updated",value:new Date(e.updated_at).toLocaleString()},{label:"Last checked",value:e.last_checked_at==null?null:new Date(e.last_checked_at).toLocaleString()},{label:"Last error",value:e.last_error==null?null:`${e.last_error.code}: ${e.last_error.message}`},{label:"Last warning",value:e.last_warning==null?null:e.last_warning.message}]},{title:"Config",rows:Object.entries(e.config).map(([n,r])=>({label:n,value:r}))},{title:"Credentials",rows:Object.entries(e.secret_suffixes).map(([n,r])=>({label:n,value:X$(r)}))},{title:"Webhook",rows:[{label:"URL",value:e.webhook.url},{label:"Verify token",value:e.webhook.verify_token==null?null:"configured"},{label:"Verified at",value:e.webhook.verified_at==null?null:new Date(e.webhook.verified_at).toLocaleString()}]}];if(e.channels.length>0)t.push({title:"Channels",rows:e.channels.map((n)=>({label:n.name,value:`${n.channel_type} (${n.id})`}))});return t}function lM(e,t){let n={...e,webhook:{url:e.webhook.url,verify_token_configured:e.webhook.verify_token!=null,verified_at:e.webhook.verified_at}};return t?O(n,t):n}function dM(e,t){let n={...e,webhook:e.webhook===null?null:{status:e.webhook.status,reason:e.webhook.reason,url:e.webhook.url}};return t?O(n,t):n}function uM(e){if(e===null)return;if(e.status==="subscribed"){ht("Webhook subscribed automatically.");return}let t=e.reason==null?"":` (${e.reason})`;if(ht(`Webhook needs manual setup${t}.`),e.url!=null)ht(` URL: ${e.url}`);ht(" Verify token: see the connector's page in the web app (never printed here).")}function pM(e){let t=Ee(e.properties)??{},n=new Set(Array.isArray(e.required)?e.required.filter((r)=>typeof r==="string"):[]);return Object.entries(t).map(([r,o])=>{let i=Ee(o)??{},a=i["x-niva-secret"]===!0||i.writeOnly===!0;return{name:r,access:a?"secret":"public",required:n.has(r),step:oe(i["x-niva-step"])??""}})}function mM(e,t,n){e.command("types").description("List connector types, or describe one kind's fields and setup steps").action(async()=>{let{format:o,fields:i}=S(t.opts()),a=await b(n().connectors.types.list());if(o==="json"){v(i?a.map((s)=>O(s,i)):a);return}L(["Kind","Name","Capabilities"],a.map((s)=>({Kind:s.kind,Name:G$(s.kind),Capabilities:s.provides.join(", ")})))}).command("describe <kind>").description("Show a kind's fields (public/secret, required) and setup steps with their URLs").action(async(o)=>{let{format:i,fields:a}=S(t.opts()),s=Ca(o),c=await b(n().connectors.types.describe({kind:s}));if(i==="json"){v(a?O(c,a):c);return}J([{title:"Type",rows:[{label:"Kind",value:c.kind},{label:"Version",value:c.version},{label:"Auth",value:c.auth_strategy},{label:"Category",value:c.category},{label:"Module",value:c.module},{label:"Docs",value:c.docs_path},{label:"Provides",value:c.provides.join(", ")},{label:"Discover",value:c.discover.join(", ")||"-"}]}]),L(["Field","Access","Required","Step"],pM(c.fields_json_schema).map((d)=>({Field:d.name,Access:d.access,Required:d.required?"yes":"no",Step:d.step}))),L(["Setup step","Title","URL"],c.setup.map((d)=>({"Setup step":d.id,Title:d.title_key,URL:d.url??"-"})))})}function fM(e,t,n){e.command("list").description("List connectors with their kind, status, account and channel count").action(async()=>{let{format:r,fields:o}=S(t.opts()),i=await b(n().connectors.list());if(r==="json"){v(o?i.map((a)=>O(a,o)):i);return}L(["ID","Name","Kind","Status","Account","Channels"],i.map((a)=>({ID:a.id,Name:a.name,Kind:a.kind,Status:a.status,Account:a.account_label??"-",Channels:a.channel_count})))})}function gM(e,t,n){e.command("show <id>").description("Show a connector's details, credentials suffixes and webhook status").action(async(r)=>{let{format:o,fields:i}=S(t.opts()),a=await b(n().connectors.get({connector_id:ke(r)}));if(o==="json"){v(lM(a,i));return}J(cM(a))})}function hM(e){if(e===void 0)return"-";return e?"yes":"no"}function yM(e,t,n){let r=e.command("agents").description("Voice agents of a connector: list them, activate or deactivate an ElevenLabs agent's number");r.command("list <id>",{isDefault:!0}).description("List the voice agents of a connector that provides voice.agent; Ready says whether an activated agent can take calls").action(async(o)=>{let{format:i,fields:a}=S(t.opts()),s=await b(n().connectors.voiceAgents({connector_id:ke(o)}));if(i==="json"){v(a?{agents:s.agents.map((c)=>O(c,a))}:s);return}L(["ID","Name","Channel","Ready","Updated"],s.agents.map((c)=>({ID:c.id,Name:c.name,Channel:c.channel,Ready:hM(c.ready),Updated:c.updated_at?.toISOString()??"-"})))});for(let[o,i]of[["activate",!1],["deactivate",!0]])r.command(`${o} <id> <agent_id>`).description(i?"Deactivate an ElevenLabs agent: NIVA removes the SIP number it registered for the agent. Plans can no longer call it.":"Activate an ElevenLabs agent: NIVA registers a SIP number on the account and binds it to the agent. Needed before a plan can call it.").action(async(a,s)=>{let{format:c,fields:d}=S(t.opts()),u=await Jn(n().connectors.agentNumbers.set({connector_id:ke(a),agent_id:s,remove:i}),c);if(c==="json"){v(d?O(u,d):u);return}N(`Agent ${s} ${i?"deactivated":"activated"} on connector ${u.name} (${u.id})`)})}function _M(e,t,n){e.command("senders <id>").description("List the SMS senders (Messaging Services and numbers) of a connector that provides sms.send").action(async(r)=>{let{format:o,fields:i}=S(t.opts()),a=await b(n().connectors.senders.list({connector_id:ke(r)}));if(o==="json"){v(i?a.map((s)=>O(s,i)):a);return}L(["ID","Label","Kind","Number","SMS","Brazil"],a.map((s)=>({ID:s.id,Label:s.label,Kind:s.kind==="messaging_service"?"Messaging Service":"Number",Number:s.number??"-",SMS:s.capabilities.sms?"yes":"no",Brazil:s.brazil_p2p_only?"p2p only":"-"})))})}function bM(e,t,n){e.command("verify-services <id>").description("List the Twilio Verify Services of a connector that provides verify.otp").action(async(r)=>{let{format:o,fields:i}=S(t.opts()),a=await b(n().connectors.verifyServices.list({connector_id:ke(r)}));if(o==="json"){v(i?a.map((s)=>O(s,i)):a);return}L(["SID","Name","Code length","Channels"],a.map((s)=>({SID:s.sid,Name:s.friendly_name,"Code length":s.code_length??"-",Channels:s.channels.join(", ")})))})}function vM(e,t,n){e.command("test <id>").description("Run a connector's health test; exits 1 when any check fails").action(async(r)=>{let{format:o,fields:i}=S(t.opts()),a=await b(n().connectors.test({connector_id:ke(r)}));if(o==="json")v(i?O(a,i):a);else if(L(["Check","OK","Message"],iM(a.health.checks)),a.health.ok)N(`Connector test passed: ${a.status}`);else C(`Connector test failed: ${a.health.code} - ${a.health.message}`);if(!a.health.ok)process.exit(A.GENERAL_ERROR)})}function SM(e,t,n){let r=e.command("discover <kind> <key>").description("Run a kind's discover function with credentials not yet stored (e.g. wabas)");mp(r),r.action(async(o,i,a)=>{let s=Ca(o);fp(a,s);let{format:c,fields:d}=S(t.opts()),u=await gp(a,s),m=await b(n().connectors.discover({kind:s,key:i,fields:u}));if(c==="json"){v(d?m.map((y)=>O(y,d)):m);return}L(["Value","Label","Description"],m.map((y)=>({Value:y.value,Label:y.label,Description:y.description??"-"})))})}function xM(e,t,n){let r=e.command("create <kind>").description("Create a connector; credentials come from --<field>-env/--<field>-stdin or a hidden prompt").requiredOption("--name <name>","Human label shown in the UI");mp(r),r.action(async(o,i)=>{let a=Ca(o);fp(i,a);let{format:s,fields:c}=S(t.opts()),d=await gp(i,a),u=await rM(a,d,n),m=await Jn(n().connectors.create({kind:a,name:i.name,fields:u}),s);if(s==="json"){v(dM(m,c));return}N(`Connector created: ${m.name} (${m.id})`),uM(m.webhook)})}function EM(e,t,n){let r=e.command("update <id>").description("Rename a connector or rotate fields; only the flags given are sent").option("--name <name>","New human label");mp(r),r.action(async(o,i)=>{let{format:a,fields:s}=S(t.opts()),c={connector_id:ke(o)};if(i.name!=null)c.name=i.name;if(lE(i)){let u=await b(n().connectors.get({connector_id:ke(o)})),m=Ca(u.kind);fp(i,m),c.fields=await gp(i,m)}let d=await Jn(n().connectors.update(c),a);if(a==="json"){v(s?O(d,s):d);return}N(`Connector updated: ${d.name} (${d.id})`)})}function wM(e,t,n){for(let[r,o]of[["enable",!0],["disable",!1]])e.command(`${r} <id>`).description(`${o?"Enable":"Disable"} a connector`).action(async(i)=>{let{format:a,fields:s}=S(t.opts()),c=await b(n().connectors.setEnabled({connector_id:ke(i),enabled:o}));if(a==="json"){v(s?O(c,s):c);return}N(`Connector ${o?"enabled":"disabled"}: ${c.name} (${c.status})`)})}function CM(e,t,n){e.command("delete <id>").description("Delete a connector; blocked and explained when a channel still references it").action(async(r)=>{let{format:o}=S(t.opts()),i=t.opts().yes===!0;await Te(`Delete connector ${r}?`,{yes:i});try{await n().connectors.delete({connector_id:ke(r)})}catch(a){hE(a,o)}if(o==="json"){v({id:r,deleted:!0});return}N(`Connector deleted: ${r}`)})}function AM(e,t,n){let r=e.command("numbers <id>").description("WhatsApp phone numbers of a connector, with readiness and the bound channel").option("--refresh","Bypass the 5-minute cache and read the numbers again");r.action(async(o,i)=>{let{format:a,fields:s}=S(t.opts()),c=await b(n().connectors.phoneNumbers.list({connector_id:ke(o),refresh:i.refresh===!0}));if(a==="json"){v(s?c.map((d)=>O(d,s)):c);return}L(["ID","Number","Name","Readiness","Channel"],c.map((d)=>({ID:d.id,Number:d.display_phone_number,Name:d.verified_name,Readiness:sM(d.readiness),Channel:d.channel==null?"-":d.channel.name})))}),r.command("request-code <id> <phone_number_id>").description("Ask Meta to send the phone number's ownership code by SMS or voice").requiredOption("--method <method>","sms or voice").option("--language <language>","Language for the message","pt_BR").action(async(o,i,a)=>{let s=IM(a.method),{format:c}=S(t.opts());if(await b(n().connectors.phoneNumbers.requestCode({connector_id:ke(o),phone_number_id:i,method:s,language:a.language})),c==="json"){v({success:!0,phone_number_id:i});return}N(`Verification code requested for ${i} by ${a.method}.`)}),r.command("verify <id> <phone_number_id>").description("Submit the 6-digit ownership code Meta sent").requiredOption("--code <code>","The 6-digit code").action(async(o,i,a)=>{if(!/^\d{6}$/u.test(a.code))ft("--code must be the 6-digit code Meta sent.");let{format:s}=S(t.opts());if(await b(n().connectors.phoneNumbers.verifyCode({connector_id:ke(o),phone_number_id:i,code:a.code})),s==="json"){v({success:!0,phone_number_id:i});return}N(`Phone number verified: ${i}`)}),r.command("register <id> <phone_number_id>").description("Register a phone number on the Cloud API with its 6-digit PIN").option("--pin-stdin","Read the PIN from stdin").option("--pin-env <VAR>","Read the PIN from an environment variable").action(async(o,i,a)=>{let s=await NM(a),{format:c}=S(t.opts());if(await b(n().connectors.phoneNumbers.register({connector_id:ke(o),phone_number_id:i,pin:s})),c==="json"){v({success:!0,phone_number_id:i});return}N(`Phone number registered: ${i}`)})}function TM(e){if(e.webhook==="this_connector")return"this connector";if(e.webhook==="other")return`other (${e.other_webhook_host??"unknown host"})`;return"none"}function fE(e){if(e===void 0)return;let t=e.replaceAll(/[\s+()-]/gu,"");if(!/^\d{8,15}$/u.test(t))ft("--number must be the phone number with country code, digits only.");return t}function gE(e,t){if(t.state==="open"){N(`Instance ${e} is already paired.`);return}if(t.pairingCode!==null)N(`Pairing code for ${e}: ${t.pairingCode}`),P("On the phone: WhatsApp > Linked devices > Link a device > Link with phone number instead.");if(t.qrCode!==null)P(`QR code (raw): ${t.qrCode}`);P(`To scan the QR code, open the connector in the web screen (Settings > Connectors). Run \`niva connectors instances list <id>\` until ${e} shows open.`)}function RM(e,t,n){let r=e.command("instances").description("WhatsApp instances (one per number) of an Evolution API connector: list, create, pair, adopt, release");r.command("list <id>",{isDefault:!0}).description("List the instances of the gateway, with the paired number, state and who their webhook delivers to").action(async(o)=>{let{format:i,fields:a}=S(t.opts()),s=await b(n().connectors.evolution.instances.list({connector_id:ke(o)}));if(i==="json"){v(a?s.map((c)=>O(c,a)):s);return}L(["Name","Number","Profile","State","Webhook"],s.map((c)=>({Name:c.name,Number:c.display_phone_number===""?"-":c.display_phone_number,Profile:c.profile_name??"-",State:c.state,Webhook:TM(c)})))}),r.command("create <id> <name>").description("Create an instance on the gateway with the NIVA webhook already set. A person must then pair it on the phone (pairing code with --number, or the QR in the web screen)").option("--number <phone>","Phone number with country code, digits only; also issues a pairing code").action(async(o,i,a)=>{let s=fE(a.number),{format:c,fields:d}=S(t.opts()),u=await Jn(n().connectors.evolution.instances.create({connector_id:ke(o),name:i}),c),m=s===void 0?null:await Jn(n().connectors.evolution.instances.connect({connector_id:ke(o),name:i,phone_number:s}),c);if(c==="json"){let y={...u,pairing_code:m?.pairing_code??null};v(d?O(y,d):y);return}N(`Instance created: ${u.name}`),gE(u.name,{state:m?.state??u.state,pairingCode:m?.pairing_code??null,qrCode:u.qr?.code??null})}),r.command("connect <id> <name>").description("Get a new QR code or pairing code for an instance that is not paired yet; a person pairs it on the phone").option("--number <phone>","Phone number with country code, digits only; issues a pairing code").action(async(o,i,a)=>{let s=fE(a.number),{format:c,fields:d}=S(t.opts()),u=await Jn(n().connectors.evolution.instances.connect({connector_id:ke(o),name:i,...s===void 0?{}:{phone_number:s}}),c);if(c==="json"){v(d?O(u,d):u);return}gE(i,{state:u.state,pairingCode:u.pairing_code,qrCode:null})}),r.command("adopt <id> <names...>").description("Bring existing instances under this connector. Each instance has ONE webhook: adopting REPLACES the current one (an n8n flow stops receiving messages)").action(async(o,i)=>{let{format:a,fields:s}=S(t.opts()),c=t.opts().yes===!0;await Te(`Point the webhook of ${i.join(", ")} at connector ${o}? This replaces whatever each one delivers to now.`,{yes:c});let d=await Jn(n().connectors.evolution.instances.adopt({connector_id:ke(o),names:i}),a),u=d.results.some((m)=>!m.ok);if(a==="json")v(s?{results:d.results.map((m)=>O(m,s))}:d);else L(["Name","Result","Error"],d.results.map((m)=>({Name:m.name,Result:m.ok?"adopted":"failed",Error:m.error??"-"})));if(u)process.exit(A.GENERAL_ERROR)}),r.command("release <id> <name>").description("Turn off the NIVA webhook of an instance. The instance stays on the gateway and stays paired").action(async(o,i)=>{let{format:a}=S(t.opts()),s=t.opts().yes===!0;await Te(`Release instance ${i} from connector ${o}?`,{yes:s});try{await n().connectors.evolution.instances.release({connector_id:ke(o),name:i})}catch(c){hE(c,a)}if(a==="json"){v({name:i,released:!0});return}N(`Instance released: ${i}`)})}function IM(e){let t=e.toUpperCase();if(t==="SMS"||t==="VOICE")return t;ft(`--method must be sms or voice (got "${e}").`)}async function OM(e){if(e.pinEnv!=null){let t=process.env[e.pinEnv];if(t==null||t==="")ft(`environment variable ${e.pinEnv} is not set or empty.`);return t}if(e.pinStdin===!0)return(await Fe()).replace(/\r?\n$/,"");if(co())return Oc("WhatsApp registration PIN (6 digits): ",Po);ft("no PIN given - pass --pin-env <VAR>, --pin-stdin, or run from a TTY.")}async function NM(e){if(e.pinStdin===!0&&e.pinEnv!=null)ft("--pin-stdin and --pin-env are mutually exclusive.");let t=await OM(e);if(!/^\d{6}$/u.test(t))ft("the PIN must be the 6-digit number Meta gave you.");return t}function yE(e,t){let n=e.createCommand("connectors").description("Connectors (WhatsApp, and the kinds that follow)");n.configureOutput({outputError:(r,o)=>o(J$(r))}),e.addCommand(n),mM(n,e,t),fM(n,e,t),gM(n,e,t),yM(n,e,t),_M(n,e,t),bM(n,e,t),vM(n,e,t),SM(n,e,t),xM(n,e,t),EM(n,e,t),wM(n,e,t),CM(n,e,t),AM(n,e,t),RM(n,e,t)}function _E(e,t){let n=e.command("conversations").description("Inspect Desk conversations: requests for human work over a call or chat (requires the desk module)");n.command("list").description("List conversations").option("--attendant <attendant_id>","Only conversations handled by this attendant").option("--channel <c>","Filter by channel (voice, chat)").option("--status <s>","Filter by status").option("--outcome <o>","Filter by outcome").option("--call <call_id>","Only conversations over this call").option("--from <date>","Created from (YYYY-MM-DD or ISO timestamp)").option("--to <date>","Created until (YYYY-MM-DD or ISO timestamp)").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().conversations.list({page:Number(r.page),limit:Number(r.limit),attendant_id:x("attendants",r.attendant),channel:se(r.channel),status:se(r.status),outcome:se(r.outcome),call_record_id:x("call_records",r.call),date_from:r.from,date_to:r.to}));if(o==="json"){v(i?a.items.map((s)=>O(s,i)):a);return}L(["ID","Channel","Status","Outcome","Attendant","Wait","Talk","Joined"],a.items.map((s)=>({ID:s.id,Channel:s.channel,Status:s.status,Outcome:s.outcome??"—",Attendant:s.attendant_id??"—",Wait:Ce(s.wait_ms),Talk:Ce(s.talk_ms),Joined:Me(s.joined_at)}))),ee(a)}),n.command("show <conversation_id>").description("Show one conversation").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().conversations.getById({conversation_id:x("conversations",r)}));if(o==="json"){v(i?O(a,i):a);return}J([{title:"Conversation",rows:[{label:"ID",value:a.id},{label:"Channel",value:a.channel},{label:"Status",value:a.status},{label:"Outcome",value:a.outcome},{label:"Call",value:a.call_record_id},{label:"Chat session",value:a.session_key},{label:"Contact",value:a.contact_id},{label:"Attendant",value:a.attendant_id},{label:"Refusals",value:a.refusals}]},{title:"Times",rows:[{label:"Joined",value:Me(a.joined_at)},{label:"Wait",value:Ce(a.wait_ms)},{label:"Talk",value:Ce(a.talk_ms)},{label:"Wrap-up",value:Ce(a.wrap_ms)}]},{title:"Wrap-up",rows:[{label:"Disposition",value:a.disposition_id},{label:"Note",value:a.note},{label:"AI summary",value:a.ai_summary}]}])})}var Rt=on(jt(),1);function $o(e){return e.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 kM(e){if(e==null)return"";if(e.missed>0)return`${e.total} (${e.missed} missed)`;return`${e.total}`}function DM(e,t){if(e>t)return"↑";if(e<t)return"↓";return"→"}function PM(e){let t=e.avg_score!=null?Number(e.avg_score):null,n=e.previous_avg_score!=null?Number(e.previous_avg_score):null,r=t!=null&&t>0?"+":"",o=t!=null?`${r}${t.toFixed(2)}`:"—",i="";if(n!=null&&t!=null){let a=DM(t,n);i=` (prev: ${n>0?"+":""}${n.toFixed(2)} ${a})`}return` Avg Score: ${o}${i}`}function bE(e,t){let n=e.command("dashboard").description("Dashboard and monitoring");n.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(r)=>{let{format:o,fields:i}=S(e.opts()),{date_from:a,date_to:s}=yt(r),c=await b(t().dashboard.metrics({date_from:a,date_to:s}));if(o==="json"){let d=i?O(c,i):c;v(d);return}if(console.log(`Period: ${a} → ${s}`),console.log(`Total calls: ${c.current.total_calls}`),console.log(`Answered: ${c.current.answered}`),console.log(`Missed: ${c.current.missed}`),c.current.avg_duration_ms!=null)console.log(`Avg duration: ${Ce(c.current.avg_duration_ms)}`)}),$o(n.command("sentiment").description("Show sentiment distribution for calls")).action(async(r)=>{let{format:o,fields:i}=S(e.opts()),{date_from:a,date_to:s}=yt(r),c=await b(t().dashboard.speechSentiment({date_from:a,date_to:s,visual_plan_id:x("visual_plans",r.plan),channel_id:x("channels",r.phone)}));if(o==="json"){let m=i?O(c,i):c;v(m);return}if(console.log(Rt.default.bold("Sentiment Overview")),console.log(`Analyzed: ${c.analyzed_count} calls`),!c.has_enough_data){P(`
|
|
113
|
+
Not enough data (need ${c.minimum_required}, have ${c.analyzed_count})`);return}console.log("");let d=c.distribution,u=Math.max(d.positive,d.neutral,d.negative,d.mixed);wt(Rt.default.green("positive"),d.positive,u),wt(Rt.default.yellow("neutral"),d.neutral,u),wt(Rt.default.red("negative"),d.negative,u),wt(Rt.default.blue("mixed"),d.mixed,u),console.log(""),console.log(PM(c))}),$o(n.command("topics").description("Show top discussed topics from call transcriptions")).option("--limit <n>","Max topics to show","15").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),{date_from:a,date_to:s}=yt(r),c=await b(t().dashboard.speechTopics({date_from:a,date_to:s,limit:Number(r.limit),visual_plan_id:x("visual_plans",r.plan),channel_id:x("channels",r.phone)}));if(o==="json"){let u=i?O(c,i):c;v(u);return}if(console.log(`${Rt.default.bold("Top Topics")} (${c.analyzed_count} analyzed)`),!c.has_enough_data||c.topics.length===0){P(`
|
|
114
|
+
Not enough data.`);return}console.log("");let d=Math.max(...c.topics.map((u)=>u.call_count));for(let u of c.topics){let m=c.analyzed_count>0?Math.round(u.call_count/c.analyzed_count*100):0,y=An(u.call_count,d);console.log(` ${u.label.padEnd(16)} ${y} ${u.call_count} calls (${m}%) confidence: ${u.avg_confidence.toFixed(2)}`)}}),$o(n.command("intents").description("Show detected intents from call transcriptions")).option("--limit <n>","Max intents to show","10").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),{date_from:a,date_to:s}=yt(r),c=await b(t().dashboard.speechIntents({date_from:a,date_to:s,limit:Number(r.limit),visual_plan_id:x("visual_plans",r.plan),channel_id:x("channels",r.phone)}));if(o==="json"){let u=i?O(c,i):c;v(u);return}if(console.log(`${Rt.default.bold("Detected Intents")} (${c.analyzed_count} analyzed)`),!c.has_enough_data||c.intents.length===0){P(`
|
|
115
|
+
Not enough data.`);return}console.log("");let d=Math.max(...c.intents.map((u)=>u.call_count));for(let u of c.intents)wt(u.label,u.call_count,d)}),$o(n.command("trend").description("Show sentiment trend over time")).option("--granularity <g>","Granularity: hour or day","day").action(async(r)=>{let{format:o}=S(e.opts()),{date_from:i,date_to:a}=yt(r,7),s=await b(t().dashboard.speechSentimentTrend({date_from:i,date_to:a,granularity:se(r.granularity),visual_plan_id:x("visual_plans",r.plan),channel_id:x("channels",r.phone)}));if(o==="json"){v(s);return}if(console.log(Rt.default.bold("Sentiment Trend")),s.length===0){P(`
|
|
116
|
+
No data available.`);return}console.log(""),L(["Date","Analyzed","Positive","Neutral","Negative","Avg Score"],s.map((c)=>{let d=new Date(c.bucket),u=`${String(d.getDate()).padStart(2,"0")}/${String(d.getMonth()+1).padStart(2,"0")}`,m=c.avg_score!=null&&c.avg_score>0?"+":"",y=c.avg_score!=null?`${m}${c.avg_score.toFixed(2)}`:"—";return{Date:u,Analyzed:c.analyzed,Positive:c.positive,Neutral:c.neutral,Negative:c.negative,"Avg Score":y}}))}),$o(n.command("weekday-hour").description("Show call volume heatmap by weekday and hour")).action(async(r)=>{let{format:o}=S(e.opts()),{date_from:i,date_to:a}=yt(r),s=await b(t().dashboard.weekdayHour({date_from:i,date_to:a,visual_plan_id:x("visual_plans",r.plan),channel_id:x("channels",r.phone)}));if(o==="json"){v(s);return}if(console.log(Rt.default.bold("Weekday × Hour")),s.cells.length===0){P(`
|
|
117
|
+
No data available.`);return}let c=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],d=new Map(s.cells.map((m)=>[`${m.weekday}:${m.hour}`,m])),u=Array.from({length:24},(m,y)=>String(y).padStart(2,"0"));console.log(""),L(["Weekday",...u],c.map((m,y)=>{let _={Weekday:m};for(let E of u)_[E]=kM(d.get(`${y}:${Number(E)}`));return _}))}),n.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(r)=>{let{format:o,fields:i}=S(e.opts()),{date_from:a,date_to:s}=yt(r),c=await b(t().dashboard.topPlans({date_from:a,date_to:s,limit:Number(r.limit)}));if(o==="json"){let d=i?c.map((u)=>O(u,i)):c;v(d);return}if(console.log(Rt.default.bold("Top Plans")),c.length===0){P(`
|
|
118
|
+
No data available.`);return}console.log(""),L(["Plan","Total","Answered","Avg Duration"],c.map((d)=>({Plan:d.visual_plan_name??"—",Total:d.total,Answered:`${d.answered} (${d.total>0?Math.round(d.answered/d.total*100):0}%)`,"Avg Duration":Ce(d.avg_duration_ms)})))})}function vE(e,t){e.command("desk").description("The Desk's copilot (requires the desk, ai and copilot modules)").command("copilot").description("How the Mesa copilot is doing").command("stats").description("What the copilot's suggestions amounted to in a window: replies, answers, wrap-ups, latency, tokens").requiredOption("--from <date>","Start of the window, inclusive (ISO timestamp or YYYY-MM-DD)").requiredOption("--to <date>","End of the window, exclusive (ISO timestamp; YYYY-MM-DD is that day's end). Up to 93 days").option("--queue <queue_id>","Only the conversations of this queue").action(async(o)=>{let{format:i,fields:a}=S(e.opts()),{date_from:s,date_to:c}=yt({from:o.from,to:o.to}),d=await b(t().desk.copilot.stats({from:s,to:c,queue_id:x("queues",o.queue)}));if(i==="json"){v(a?O(d,a):d);return}let u=d.latency_ms===null?"—":`${d.latency_ms.p50} / ${d.latency_ms.p95}`;J([{title:"Replies",rows:[{label:"Shown",value:d.replies.shown},{label:"Used",value:d.replies.used},{label:"Edited",value:d.replies.edited},{label:"Discarded",value:d.replies.discarded},{label:"Ignored",value:d.replies.ignored}]},{title:"Answers",rows:[{label:"Asked",value:d.answers.asked},{label:"Useful",value:d.answers.useful},{label:"Not useful",value:d.answers.not_useful}]},{title:"Wrap-ups",rows:[{label:"Shown",value:d.wrap_ups.shown},{label:"Disposition kept",value:d.wrap_ups.disposition_kept},{label:"Note edited",value:d.wrap_ups.note_edited}]},{title:"Cues",rows:[{label:"Shown",value:d.cues.shown},{label:"Useful",value:d.cues.useful},{label:"Discarded",value:d.cues.discarded}]},{title:"Cost",rows:[{label:"Summaries",value:d.summaries.shown},{label:"Latency p50 / p95 (ms)",value:u},{label:"Input tokens",value:d.tokens.input},{label:"Output tokens",value:d.tokens.output}]}])})}import{readFile as $M}from"node:fs/promises";var SE=1e4;function xE(e,t){let n=e.command("dnc").description("Manage the do-not-call list");n.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(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().dialerDnc.list({page:Number(r.page),limit:Number(r.limit),search:r.search}));if(o==="json"){v(i?a.items.map((s)=>O(s,i)):a);return}L(["ID","Phone","Reason","Added"],a.items.map((s)=>({ID:s.id,Phone:s.phone_number,Reason:s.reason??"—",Added:Me(s.created_at)}))),ee(a)}),n.command("add <phone>").description("Add a number to the do-not-call list").option("--reason <r>","Reason for the block").action(async(r,o)=>{let{format:i}=S(e.opts()),a=await b(t().dialerDnc.add({phone_number:r,reason:o.reason}));if(i==="json"){v(a);return}N(`Added ${a.phone_number} to DNC`)}),n.command("remove <ids...>").description("Remove do-not-call entries").action(async(r)=>{let{format:o}=S(e.opts());if(r.length===1){let a=await b(t().dialerDnc.remove({dnc_id:x("dialer_dnc",r[0])}));if(o==="json"){v(a);return}N("Removed DNC entry");return}let i=await b(t().dialerDnc.bulkRemove({ids:x("dialer_dnc",r)}));if(o==="json"){v(i);return}N(`Removed ${i.removed}`)}),n.command("check <phone>").description("Check if a number is on the DNC list (exit 0 = listed, 3 = not listed)").action(async(r)=>{let{format:o}=S(e.opts()),i=await b(t().dialerDnc.list({page:1,limit:20,search:r})),a=r.replaceAll(/\D/g,""),s=a===""?void 0:i.items.find((c)=>{let d=String(c.phone_number).replaceAll(/\D/g,"");return d===a||d.endsWith(a)});if(s!=null){if(o==="json")v(s);else J([{title:"DNC entry",rows:[{label:"ID",value:s.id},{label:"Phone",value:s.phone_number},{label:"Reason",value:s.reason??"—"},{label:"Added",value:new Date(s.created_at).toLocaleString()}]}]);return}if(o==="json")v({listed:!1});else P("Not in DNC list.");process.exit(A.NOT_FOUND)}),n.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(r,o)=>{let{format:i}=S(e.opts()),s=(await $M(r,"utf-8")).split(/\r\n|\n|\r/).map((u)=>u.trim()).filter((u)=>u.length>0&&!u.startsWith("#"));if(s.length===0)C("No phone numbers found in file"),process.exit(A.USAGE_ERROR);let c=0,d=0;for(let u=0;u<s.length;u+=SE){let m=s.slice(u,u+SE),y=await b(t().dialerDnc.bulkImport({numbers:m,reason:o.reason}));c+=y.added,d+=y.skipped}if(i==="json"){v({added:c,skipped:d});return}N(`Added ${c}, skipped ${d}`)})}var gt=on(jt(),1);var MM=new Set(uo);function LM(e){return MM.has(e)}var Aa=(e)=>e==="online"?gt.default.green(e):gt.default.red(e);function zM(e){let t;if(e.is_expired)t=gt.default.red("expired");else if(e.is_in_grace_period)t=gt.default.yellow("grace period");else t=gt.default.green(e.status);let n=e.days_until_expiry!=null?` (${e.days_until_expiry}d remaining)`:"";return` License: ${t}${n}`}var EE=10,FM="unlimited".padEnd(EE);function Ta(e,t,n,r,o){let i=` ${e.padEnd(11)}`;if(n==null)return`${i}${gt.default.dim(FM)} ${t}${r}`;return`${i}${An(t,n,EE)} ${t}/${n}${r} (${Math.round(o)}%)`}function UM(e){let t=[gt.default.bold(" AI Usage:")],{stt:n,tts:r,llm:o}=e;if(n)t.push(Ta("STT:",Math.round(n.current),n.limit," min",n.percentage));if(r)t.push(Ta("TTS:",r.current,r.limit," chars",r.percentage));if(o)t.push(Ta("LLM:",o.current,o.limit," tokens",o.percentage));return t}async function jM(e){try{return(await e().system.fsServiceStatus()).sip_firewall??null}catch{return null}}function wE(e,t){let n=e.command("fs").description("FreeSWITCH status and debug");n.command("status").description("Check system health (server, DB, Redis, FreeSWITCH)").action(async()=>{let{format:r,fields:o}=S(e.opts()),i=await b(t().dashboard.health()),a=await jM(t);if(r==="json"){let s=a?{...i,sip_firewall:a}:i,c=o?O(s,o):s;v(c);return}if(console.log(`Server: ${Aa(i.server)}`),console.log(`PostgreSQL: ${Aa(i.postgres)}`),console.log(`Redis: ${Aa(i.redis)}`),console.log(`FreeSWITCH: ${Aa(i.freeswitch.status)}`),i.freeswitch.uptime!=null&&i.freeswitch.uptime!=="")console.log(` Uptime: ${i.freeswitch.uptime}`);if(i.freeswitch.sessions)console.log(` Sessions: ${i.freeswitch.sessions.active}/${i.freeswitch.sessions.limit}`);if(i.freeswitch.cps)console.log(` CPS: ${i.freeswitch.cps.current}/${i.freeswitch.cps.limit}`);if(i.freeswitch.idleCpu!=null)console.log(` Idle CPU: ${i.freeswitch.idleCpu}%`);if(a)console.log(`SIP firewall: ${a.mode} · allow ${a.allow_entries} · peers ${a.peer_entries} · `+`would drop ${a.would_drop_packets} pkts / dropped ${a.dropped_packets} pkts from ${a.offender_entries} IPs`)}),n.command("channels").description("List active FreeSWITCH channels").action(async()=>{let{format:r,fields:o}=S(e.opts()),i=await b(t().dashboard.activeCalls());if(r==="json"){let a=o?i.map((s)=>O(s,o)):i;v(a);return}if(i.length===0){P("No active channels.");return}L(["UUID","Caller","Plan","Node","Duration"],i.map((a)=>({UUID:a.uuid,Caller:a.callerId,Plan:a.planName??"—",Node:a.currentNodeLabel??"—",Duration:a.startedAt?`${Math.round((Date.now()-new Date(a.startedAt).getTime())/1000)}s`:"—"}))),P(`${i.length} active channel(s)`)}),n.command("registrations").description("List SIP registrations").action(async()=>{let{format:r,fields:o}=S(e.opts()),i=await b(t().testCall.registrations());if(r==="json"){let a=o?i.map((s)=>O(s,o)):i;v(a);return}if(i.length===0){P("No SIP registrations.");return}L(["Extension","Agent"],i.map((a)=>({Extension:a.extension,Agent:a.agent??"—"})))}),n.command("dump <uuid>").description("Dump all channel variables for an active call").action(async(r)=>{let{format:o}=S(e.opts()),i=await b(t().dashboard.fsDumpChannel({uuid:r}));if(Object.keys(i).length===0){if(o==="json")v({});else C(`Channel ${r} not found.`);process.exit(A.NOT_FOUND)}if(o==="json"){v(i);return}console.log(gt.default.bold(`Channel Variables — ${r}`)),console.log("");for(let[a,s]of Object.entries(i))console.log(` ${gt.default.cyan(a.padEnd(40))} ${s}`)}),n.command("sofia").description("Show SIP profile status").action(async()=>{let{format:r}=S(e.opts()),o=await b(t().dashboard.fsSofiaStatus());if(r==="json"){v(o);return}if(o.length===0){P("No Sofia profiles configured.");return}console.log(gt.default.bold("Sofia SIP Profiles")),console.log(""),L(["Name","Type","Data","State"],o.map((i)=>({Name:i.name,Type:i.type,Data:i.data,State:i.state})))}),n.command("show <entity>").description(`Show FreeSWITCH data (${uo.join(", ")})`).action(async(r)=>{if(!LM(r))C(`Unknown entity "${r}". Allowed: ${uo.join(", ")}`),process.exit(A.USAGE_ERROR);let{format:o}=S(e.opts()),i=await b(t().dashboard.fsShow({entity:r}));if(o==="json"){v(i);return}console.log(gt.default.bold(`FreeSWITCH: show ${r}`)),console.log(""),console.log(JSON.stringify(i,null,2))}),n.command("capacity").description("Show system capacity: channels, license, AI usage").action(async()=>{let{format:r,fields:o}=S(e.opts()),i=await b(t().dashboard.capacityStatus());if(r==="json"){let s=o?O(i,o):i;v(s);return}console.log(gt.default.bold("System Capacity")),console.log("");let a=i.channels.total;if(console.log(Ta("Channels:",a.active,a.limit,"",a.percentage??0)),console.log(zM(i.license)),i.ai_usage){console.log("");for(let s of UM(i.ai_usage))console.log(s)}})}import{readFile as VM}from"node:fs/promises";async function hp(e){try{return e==="-"?await Fe():await VM(e,"utf-8")}catch{C(`Cannot read "${e}".`),process.exit(A.USAGE_ERROR)}}async function Ir(e){let t=await hp(e),n;try{n=JSON.parse(t)}catch{C(`Invalid JSON in "${e}".`),process.exit(A.USAGE_ERROR)}if(!ge(n))C(`Invalid body in "${e}": expected a JSON object.`),process.exit(A.USAGE_ERROR);return n}var KM=["fixed:MM-DD every year on that day, e.g. fixed:03-23","single:YYYY-MM-DD one dated occurrence, or single:YYYY-MM-DD..YYYY-MM-DD for a range","easter:N N days after (negative: before) Easter, e.g. easter:-47 is Carnival","nth:MONTH:WEEKDAY:N the Nth weekday of a month (WEEKDAY 0 = Sunday, N 1-5 or -1 for the last), e.g. nth:11:4:4",`json the API rule object, e.g. '{"kind":"easter","offset_days":-2}'`].join(`
|
|
119
|
+
`);function et(e,t){throw Error(`Invalid holiday rule "${e}": ${t}.
|
|
120
120
|
Accepted forms:
|
|
121
|
-
${HM}`)}function WM(e){return[31,29,31,30,31,30,31,31,30,31,30,31][e-1]??0}function TE(e){return/^-?\d+$/.test(e)?Number(e):void 0}function RE(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().startsWith(e)}function NE(e,t,n){if(t===void 0||t<1||t>12)return tt(e,"month must be 1-12");if(n===void 0||n<1||n>WM(t))return tt(e,"day is not a real day of that month");return{kind:"fixed",month:t,day:n}}function OE(e,t,n){if(t===void 0||!RE(t))return tt(e,"start date must be a real YYYY-MM-DD");if(n===void 0)return{kind:"single",start_date:t};if(!RE(n))return tt(e,"end date must be a real YYYY-MM-DD");if(n<t)return tt(e,"end date is before the start date");return{kind:"single",start_date:t,end_date:n}}function kE(e,t){if(t===void 0||t<-366||t>366)return tt(e,"offset must be an integer from -366 to 366");return{kind:"easter",offset_days:t}}function DE(e,t,n,r){if(t===void 0||t<1||t>12)return tt(e,"month must be 1-12");if(n===void 0||n<0||n>6)return tt(e,"weekday must be 0-6, 0 = Sunday");if(r===1||r===2||r===3||r===4||r===5||r===-1)return{kind:"nth_weekday",month:t,weekday:n,nth:r};return tt(e,"N must be 1-5, or -1 for the last")}function Nr(e){return typeof e==="number"&&Number.isInteger(e)?e:void 0}function IE(e){return typeof e==="string"?e:void 0}function GM(e){let t;try{t=JSON.parse(e)}catch{return tt(e,"not valid JSON")}if(!se(t))return tt(e,"JSON must be an object");switch(t.kind){case"fixed":return NE(e,Nr(t.month),Nr(t.day));case"single":return OE(e,IE(t.start_date),IE(t.end_date));case"easter":return kE(e,Nr(t.offset_days));case"nth_weekday":return DE(e,Nr(t.month),Nr(t.weekday),Nr(t.nth));default:return tt(e,"kind must be fixed, single, easter or nth_weekday")}}function PE(e){let t=e.trim();if(t.startsWith("{"))return GM(t);let[n,...r]=t.split(":"),o=r.join(":");switch(n??""){case"fixed":{let i=/^(\d{2})-(\d{2})$/.exec(o);return NE(e,i?Number(i[1]):void 0,i?Number(i[2]):void 0)}case"single":{let[i,a,...s]=o.split("..");if(s.length>0)return tt(e,"a range has exactly two dates");return OE(e,i,a)}case"easter":return kE(e,TE(o));case"nth":{let i=r.map((a)=>TE(a));if(i.length!==3)return tt(e,"expected nth:MONTH:WEEKDAY:N");return DE(e,i[0],i[1],i[2])}default:return tt(e,"unknown form")}}function Ia(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(typeof e==="string"?new Date(e):e)}async function Mo(e){return(await e.oauth.whoami()).organization?.timezone??"UTC"}function $E(e){if(e===void 0)return"—";return e.reason==="emergency"?"emergency":e.status}function Lo(e){if(e==null)return"—";return e instanceof Date?e.toISOString():e}var ZM=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function YM(e){if(e.length===0)return"—";return e.map((t)=>`${t.days.map((n)=>ZM[n]??n).join(",")} ${t.start}-${t.end}`).join("; ")}function _p(e){return e.length===0?"closed all day":e.map((t)=>`${t.start}-${t.end}`).join(", ")}function JM(e){if(e.length===0)return"—";return e.map((t)=>t.source==="catalog"?t.code:t.holiday_calendar_id).join(", ")}function XM(e){return{page:Number(e.page),limit:Number(e.limit)}}function Ft(e,t){let{fields:n}=S(e.opts());v(n&&t!==null&&typeof t==="object"&&!Array.isArray(t)?N(t,n):t)}async function ME(e,t,n,r){if(e==="json"){v(t?n.map((i)=>N(i,t)):n);return}let o=await r();L(["Date","Holiday","Type","Mode","Hours","Calendar"],n.map((i)=>({Date:Ia(i.occurrence.start,o),Holiday:i.occurrence.name,Type:i.occurrence.type,Mode:i.overridden?`${i.mode} (override)`:i.mode,Hours:i.mode==="reduced"?_p(i.intervals):"—",Calendar:i.occurrence.calendar.source==="catalog"?i.occurrence.calendar.code:i.occurrence.calendar.name})))}function QM(e,t,n){let r=e.command("exceptions").description("Exceptions: dates that replace the normal hours (a training day, a one-off closure)");r.command("list").description("List exceptions").option("--schedule <id>","Only the exceptions that apply to this schedule").option("--limit <n>","Items per page","20").option("--page <n>","Page number","1").action(async(o)=>{let{format:i,fields:a}=S(t.opts()),s=await b(n().scheduleExceptions.list({...XM(o),schedule_id:x("schedules",o.schedule)}));if(i==="json"){v(a?s.items.map((c)=>N(c,a)):s);return}L(["ID","Name","From","To","Yearly","Open windows"],s.items.map((c)=>({ID:c.id,Name:c.name,From:c.start_date,To:c.end_date??c.start_date,Yearly:c.yearly?"yes":"no","Open windows":_p(c.intervals)}))),te(s)}),r.command("show <id>").description("Show an exception").action(async(o)=>{let{format:i}=S(t.opts()),a=await b(n().scheduleExceptions.getById({schedule_exception_id:x("schedule_exceptions",o)}));if(i==="json"){Ft(t,a);return}J([{title:a.name,rows:[{label:"ID",value:a.id},{label:"From",value:a.start_date},{label:"To",value:a.end_date??a.start_date},{label:"Yearly",value:a.yearly?"yes":"no"},{label:"Open windows",value:_p(a.intervals)},{label:"Schedules",value:a.schedule_ids.join(", ")||"—"}]}])}),r.command("create").description("Create an exception from JSON: { name, start_date, end_date?, yearly?, intervals?: [{ start, end }], schedule_ids? }").requiredOption("--file <path>","JSON body (- for stdin)").action(async(o)=>{let{format:i}=S(t.opts()),a=await b(n().scheduleExceptions.create(await Ir(o.file)));if(i==="json"){Ft(t,a);return}O(`Exception created: ${a.id} (${a.name})`)}),r.command("update <id>").description("Update an exception from JSON; only the fields sent change (intervals and schedule_ids replace)").requiredOption("--file <path>","JSON body (- for stdin)").action(async(o,i)=>{let{format:a}=S(t.opts()),s=await Ir(i.file),c=await b(n().scheduleExceptions.update({...s,schedule_exception_id:x("schedule_exceptions",o)}));if(a==="json"){Ft(t,c);return}O(`Exception updated: ${c.id} (${c.name})`)}),r.command("delete <id>").description("Delete an exception (needs --yes in a non-interactive shell)").action(async(o)=>{let{format:i}=S(t.opts());await Ce(`Delete exception ${o}?`,{yes:t.opts().yes===!0});let a=x("schedule_exceptions",o);if(await b(n().scheduleExceptions.delete({schedule_exception_id:a})),i==="json"){v({id:a,deleted:!0});return}O(`Exception deleted: ${a}`)})}function LE(e,t){let n=e.command("schedules").description("Business hours: schedules, exceptions and emergency close");n.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(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().schedules.list({page:Number(r.page),limit:Number(r.limit),search:r.search}));if(o==="json"){let s=i?a.items.map((c)=>N(c,i)):a;v(s);return}L(["ID","Name","Status","Description"],a.items.map((s)=>({ID:s.id,Name:s.name,Status:$E(s.current),Description:s.description??"—"}))),te(a)}),n.command("show <id>").description("Show a schedule: hours, timezone, subscribed holiday calendars, emergency and current status").action(async(r)=>{let{format:o}=S(e.opts()),i=await b(t().schedules.getById({schedule_id:x("schedules",r)}));if(i===null)C(`Schedule "${r}" not found.`),process.exit(A.NOT_FOUND);if(o==="json"){Ft(e,i);return}J([{title:i.name,rows:[{label:"ID",value:i.id},{label:"Status now",value:$E(i.current)},{label:"Timezone",value:i.timezone},{label:"Weekly hours",value:YM(i.weekly_hours)},{label:"Holiday calendars",value:JM(i.holiday_calendars)},{label:"Holidays that close",value:i.holiday_close_types.join(", ")},{label:"Emergency",value:i.emergency?i.emergency.reason??"closed":null}]}])}),n.command("create").description('Create a schedule from JSON: { name, weekly_hours: [{ days: [1,2,3,4,5], start: "09:00", end: "18:00" }], timezone?, holiday_calendars?: [{ source: "catalog", code: "BR-SP" } | { source: "custom", holiday_calendar_id }], holiday_close_types? }').requiredOption("--file <path>","JSON body (- for stdin)").action(async(r)=>{let{format:o}=S(e.opts()),i=await b(t().schedules.create(await Ir(r.file)));if(o==="json"){Ft(e,i);return}O(`Schedule created: ${i.id} (${i.name})`)}),n.command("update <id>").description("Update a schedule from JSON; only the fields sent change. holiday_calendars replaces the whole list: read it with `schedules show` and send it complete").requiredOption("--file <path>","JSON body (- for stdin)").action(async(r,o)=>{let{format:i}=S(e.opts()),a=await Ir(o.file),s=await b(t().schedules.update({...a,schedule_id:x("schedules",r)}));if(i==="json"){Ft(e,s);return}O(`Schedule updated: ${s.id} (${s.name})`)}),n.command("delete <id>").description("Delete a schedule (needs --yes in a non-interactive shell); check `schedules usage` first").action(async(r)=>{let{format:o}=S(e.opts());await Ce(`Delete schedule ${r}?`,{yes:e.opts().yes===!0});let i=x("schedules",r);if(await b(t().schedules.delete({schedule_id:i})),o==="json"){v({id:i,deleted:!0});return}O(`Schedule deleted: ${i}`)}),n.command("simulate <id>").description("Evaluate a schedule at an instant and say which layer decided: emergency, exception, holiday or weekly").option("--at <iso>","ISO 8601 instant with offset, e.g. 2026-12-25T10:00:00-03:00 (default: now)").action(async(r,o)=>{let{format:i}=S(e.opts()),a=await b(t().schedules.simulate({schedule_id:x("schedules",r),at:o.at??new Date().toISOString()}));if(i==="json"){Ft(e,a);return}J([{title:"Simulation",rows:[{label:"Status",value:a.status},{label:"Decided by",value:a.reason},{label:"Description",value:a.description},{label:"Agenda output",value:a.output},{label:"Closes at",value:Lo(a.closes_at)},{label:"Reopens at",value:Lo(a.reopens_at)}]}])}),n.command("holidays <id>").description("List the holidays that apply to a schedule in a window, with the mode each takes").option("--from <date>","Window start, YYYY-MM-DD (default: today)").option("--to <date>","Window end, YYYY-MM-DD, included (default: one year after --from)").action(async(r,o)=>{let{format:i,fields:a}=S(e.opts()),s=await b(t().schedules.holidays({schedule_id:x("schedules",r),from:o.from,to:o.to}));await ME(i,a,s,async()=>(await b(t().schedules.getById({schedule_id:x("schedules",r)})))?.timezone??await Mo(t()))}),n.command("preview-holidays").description("Preview the holidays a calendar setup would produce, without saving a schedule. JSON: { holiday_calendars, holiday_close_types?, holiday_overrides? }").requiredOption("--file <path>","JSON body (- for stdin)").option("--from <date>","Window start, YYYY-MM-DD (default: today)").option("--to <date>","Window end, YYYY-MM-DD, included (default: one year after --from)").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await Ir(r.file),s=await b(t().schedules.previewHolidays({...a,...r.from===void 0?{}:{from:r.from},...r.to===void 0?{}:{to:r.to}}));await ME(o,i,s,async()=>a.timezone??await Mo(t()))}),n.command("upcoming").description("Holidays and exceptions that close or change the hours, across every schedule, in date order").option("--days <n>","How many days ahead (default: 60)").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().schedules.upcoming({days:r.days===void 0?void 0:Number(r.days)}));if(o==="json"){v(i?a.map((s)=>N(s,i)):a);return}L(["Date","Until","Schedule","Kind","Name","Effect"],a.map((s)=>({Date:s.date,Until:s.end_date,Schedule:s.schedule_name,Kind:s.kind,Name:s.name,Effect:s.effect})))}),n.command("usage <id>").description("List the plans and channels that use a schedule").action(async(r)=>{let{format:o}=S(e.opts()),i=await b(t().schedules.usage({schedule_id:x("schedules",r)}));if(o==="json"){Ft(e,i);return}L(["Kind","ID","Name"],[...i.plans.map((a)=>({Kind:"plan",ID:a.id,Name:a.name})),...i.channels.map((a)=>({Kind:"channel",ID:a.id,Name:a.name}))])}),n.command("close <id>").description("Emergency close: the schedule is closed now, ahead of every other layer. Takes effect on live calls").requiredOption("--reason <text>","Why it is closed").option("--until <iso>","ISO 8601 instant with offset when it reopens on its own (default: until `reopen`)").action(async(r,o)=>{let{format:i}=S(e.opts()),a=await b(t().schedules.setEmergency({schedule_id:x("schedules",r),reason:o.reason,until:o.until}));if(i==="json"){Ft(e,a);return}O(`Schedule closed: ${a.id} (${o.reason})`)}),n.command("reopen <id>").description("End an emergency close and return to the normal hours").action(async(r)=>{let{format:o}=S(e.opts()),i=await b(t().schedules.clearEmergency({schedule_id:x("schedules",r)}));if(o==="json"){Ft(e,i);return}O(`Schedule reopened: ${i.id}`)}),QM(n,e,t)}var bp="Rule: fixed:MM-DD | single:YYYY-MM-DD[..YYYY-MM-DD] | easter:N | nth:MONTH:WEEKDAY:N | a JSON rule object";function vp(e){try{return PE(e)}catch(t){C(t instanceof Error?t.message:String(t)),process.exit(A.USAGE_ERROR)}}function zE(e){switch(e.kind){case"fixed":return`every year ${String(e.month).padStart(2,"0")}-${String(e.day).padStart(2,"0")}`;case"single":return e.end_date===void 0?e.start_date:`${e.start_date}..${e.end_date}`;case"easter":return`easter ${e.offset_days>=0?"+":""}${e.offset_days}`;case"nth_weekday":return`nth ${e.nth} weekday ${e.weekday} of month ${e.month}`}}function Xn(e,t){let{fields:n}=S(e.opts());v(n&&t!==null&&typeof t==="object"&&!Array.isArray(t)?N(t,n):t)}function jE(e){return{page:Number(e.page),limit:Number(e.limit)}}function FE(e){return e.option("--start-time <hh:mm>","Start of a partial-day window (with --end-time)").option("--end-time <hh:mm>","End of a partial-day window (with --start-time)")}function UE(e,t){return e!==null&&t!==null?`${e}-${t}`:null}function eL(e,t){if(t===void 0)return e.next_occurrence??"—";let n=e.occurrence_in_year;return n===null?"—":`${n.start_date}..${n.end_date}`}function tL(e,t,n){let r=e.command("calendars").description("Own holiday calendars (the built-in catalog is separate)");r.command("list").description("List own holiday calendars").option("--limit <n>","Items per page","20").option("--page <n>","Page number","1").option("--search <term>","Search by name").action(async(o)=>{let{format:i,fields:a}=S(t.opts()),s=await b(n().holidayCalendars.list({...jE(o),search:o.search}));if(i==="json"){v(a?s.items.map((c)=>N(c,a)):s);return}L(["ID","Name","Description"],s.items.map((c)=>({ID:c.id,Name:c.name,Description:c.description??"—"}))),te(s)}),r.command("show <id>").description("Show a holiday calendar").action(async(o)=>{let{format:i}=S(t.opts()),a=await b(n().holidayCalendars.getById({holiday_calendar_id:x("holiday_calendars",o)}));if(i==="json"){Xn(t,a);return}J([{title:a.name,rows:[{label:"ID",value:a.id},{label:"Description",value:a.description}]}])}),r.command("create").description("Create an empty holiday calendar; add holidays with `holidays entries create`").requiredOption("--name <name>","Calendar name, e.g. the city").option("--description <text>","Description").action(async(o)=>{let{format:i}=S(t.opts()),a=await b(n().holidayCalendars.create({name:o.name,description:o.description}));if(i==="json"){Xn(t,a);return}O(`Holiday calendar created: ${a.id} (${a.name})`)}),r.command("update <id>").description("Rename a holiday calendar or change its description").option("--name <name>","New name").option("--description <text>","New description").action(async(o,i)=>{let{format:a}=S(t.opts()),s=await b(n().holidayCalendars.update({holiday_calendar_id:x("holiday_calendars",o),name:i.name,description:i.description}));if(a==="json"){Xn(t,s);return}O(`Holiday calendar updated: ${s.id} (${s.name})`)}),r.command("delete <id>").description("Delete a holiday calendar and its entries (needs --yes in a non-interactive shell)").action(async(o)=>{let{format:i}=S(t.opts());await Ce(`Delete holiday calendar ${o} and all its entries?`,{yes:t.opts().yes===!0});let a=x("holiday_calendars",o);if(await b(n().holidayCalendars.delete({holiday_calendar_id:a})),i==="json"){v({id:a,deleted:!0});return}O(`Holiday calendar deleted: ${a}`)}),r.command("import <id>").description("Import an .ics file as entries. Dated events become single dates of that year, not yearly holidays; recreate the yearly ones as rules").requiredOption("--file <path>",".ics file (- for stdin)").action(async(o,i)=>{let{format:a}=S(t.opts()),s=await b(n().holidayCalendars.importIcs({holiday_calendar_id:x("holiday_calendars",o),content:await yp(i.file)}));if(a==="json"){Xn(t,s);return}O(`Imported ${s.imported} event(s), skipped ${s.skipped}.`)})}function nL(e,t,n){let r=e.command("entries").description("Holidays inside an own calendar");r.command("list <calendar_id>").description("List the entries of a calendar; --year shows the days each rule covers that year").option("--year <yyyy>","Calendar year").option("--limit <n>","Items per page","20").option("--page <n>","Page number","1").action(async(o,i)=>{let{format:a,fields:s}=S(t.opts()),c=await b(n().holidayCalendars.entries.list({holiday_calendar_id:x("holiday_calendars",o),year:i.year===void 0?void 0:Number(i.year),...jE(i)}));if(a==="json"){v(s?c.items.map((d)=>N(d,s)):c);return}L(["ID","Name","Type","Rule","Hours",i.year===void 0?"Next":`In ${i.year}`],c.items.map((d)=>({ID:d.id,Name:d.name,Type:d.type,Rule:zE(d.rule),Hours:UE(d.start_time,d.end_time)??"whole day",[i.year===void 0?"Next":`In ${i.year}`]:eL(d,i.year)}))),te(c)}),r.command("show <calendar_id> <entry_id>").description("Show one entry").action(async(o,i)=>{let{format:a}=S(t.opts()),s=await b(n().holidayCalendars.entries.getById({holiday_calendar_id:x("holiday_calendars",o),holiday_calendar_entry_id:x("holiday_calendar_entries",i)}));if(a==="json"){Xn(t,s);return}J([{title:s.name,rows:[{label:"ID",value:s.id},{label:"Type",value:s.type},{label:"Rule",value:zE(s.rule)},{label:"Hours",value:UE(s.start_time,s.end_time)},{label:"Next occurrence",value:s.next_occurrence},{label:"Source",value:s.source}]}])}),FE(r.command("create <calendar_id>").description("Add a holiday. A holiday that repeats yearly is a recurring rule (fixed, easter, nth), never a single date. Carnival is easter:-47, Good Friday easter:-2, Corpus Christi easter:60").requiredOption("--name <name>","Holiday name").option("--type <type>","public | optional | bank","public").requiredOption("--rule <rule>",bp)).action(async(o,i)=>{let{format:a}=S(t.opts()),s=await b(n().holidayCalendars.entries.create({holiday_calendar_id:x("holiday_calendars",o),name:i.name,type:ce(i.type),rule:vp(i.rule),start_time:i.startTime,end_time:i.endTime}));if(a==="json"){Xn(t,s);return}O(`Entry created: ${s.id} (${s.name})`)}),FE(r.command("update <calendar_id> <entry_id>").description("Update an entry; only the options sent change").option("--name <name>","New name").option("--type <type>","public | optional | bank").option("--rule <rule>",bp)).action(async(o,i,a)=>{let{format:s}=S(t.opts()),c=await b(n().holidayCalendars.entries.update({holiday_calendar_id:x("holiday_calendars",o),holiday_calendar_entry_id:x("holiday_calendar_entries",i),name:a.name,type:ce(a.type),rule:a.rule===void 0?void 0:vp(a.rule),start_time:a.startTime,end_time:a.endTime}));if(s==="json"){Xn(t,c);return}O(`Entry updated: ${c.id} (${c.name})`)}),r.command("delete <calendar_id> <entry_id>").description("Delete an entry (needs --yes in a non-interactive shell)").action(async(o,i)=>{let{format:a}=S(t.opts());await Ce(`Delete entry ${i}?`,{yes:t.opts().yes===!0});let s=x("holiday_calendar_entries",i);if(await b(n().holidayCalendars.entries.delete({holiday_calendar_id:x("holiday_calendars",o),holiday_calendar_entry_id:s})),a==="json"){v({id:s,deleted:!0});return}O(`Entry deleted: ${s}`)})}async function rL(e,t){let[n,r]=t.split("-");if(n!==void 0&&r!==void 0){let i=(await b(e.holidayCatalog.regions({country_code:n}))).find((a)=>a.code===`${n}-${r}`);if(i!==void 0)return i.timezone}return Mo(e)}function oL(e,t,n){let r=e.command("catalog").description("Built-in holiday catalog (offline, same for everyone)");r.command("countries").description("List the catalog countries").action(async()=>{let{format:o,fields:i}=S(t.opts()),a=await b(n().holidayCatalog.countries());if(o==="json"){v(i?a.map((s)=>N(s,i)):a);return}L(["Code","Name"],a.map((s)=>({Code:s.code,Name:s.name})))}),r.command("regions <country_code>").description("List the states and cities of a catalog country, with their codes (BR-SP, BR-SP-SP)").action(async(o)=>{let{format:i,fields:a}=S(t.opts()),s=await b(n().holidayCatalog.regions({country_code:o}));if(i==="json"){v(a?s.map((c)=>N(c,a)):s);return}L(["Code","Name","Timezone","Cities"],s.map((c)=>({Code:c.code,Name:c.name,Timezone:c.timezone,Cities:c.cities.map((d)=>`${d.code} ${d.name}`).join(", ")||"—"})))}),r.command("holidays <code>").description("Holidays of one catalog level (BR, BR-SP or BR-SP-SP) for a year. A state lists only what the country lacks and a city only what neither has").option("--year <yyyy>","Year (default: this year)").action(async(o,i)=>{let{format:a,fields:s}=S(t.opts()),c=await b(n().holidayCatalog.holidays({code:o,year:i.year===void 0?new Date().getFullYear():Number(i.year)}));if(a==="json"){v(s?c.map((u)=>N(u,s)):c);return}let d=await rL(n(),o);L(["Date","Holiday","Type","Rule"],c.map((u)=>({Date:Ia(u.start,d),Holiday:u.name,Type:u.type,Rule:u.rule_description??"—"})))})}function VE(e,t){let n=e.command("holidays").description("Holiday calendars: own calendars, entries and the catalog");tL(n,e,t),nL(n,e,t),oL(n,e,t),n.command("preview-rule").description("Dry-run a rule: its next occurrences, without saving anything. Run it before `entries create`").requiredOption("--rule <rule>",bp).option("--count <n>","How many occurrences (1-10)","5").option("--start-time <hh:mm>","Start of a partial-day window (with --end-time)").option("--end-time <hh:mm>","End of a partial-day window (with --start-time)").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().holidayCalendars.previewRule({rule:vp(r.rule),count:Number(r.count),start_time:r.startTime,end_time:r.endTime}));if(o==="json"){v(i?a.map((s)=>N(s,i)):a);return}L(["Start","End (exclusive)"],a.map((s)=>({Start:Lo(s.start),"End (exclusive)":Lo(s.end)})))})}function iL(){return Object.entries(W).map(([e,t])=>`${e} (${t}_)`).sort((e,t)=>e.localeCompare(t))}function aL(e){return Object.hasOwn(W,e)}function KE(e){C(e),D(" Valid entities:");for(let t of iL())D(` ${t}`);process.exit(A.USAGE_ERROR)}function qE(e,t,n){return{input:e,entity:t,prefix:W[t],typeid:Li(t,n),uuid:n,sql:`'${n}'::uuid`}}function sL(e,t){if(t!=null&&!aL(t))KE(`Unknown entity "${t}".`);let n=Dn(e);if(n.kind==="typeid"){if(t!=null&&t!==n.entity)C(`"${e}" is a ${n.entity} id, but --as says ${t}.`),D(" Drop --as: a TypeID already carries its entity."),process.exit(A.USAGE_ERROR);return qE(e,n.entity,n.uuid)}if(n.kind==="uuid"){if(t==null)KE(`"${e}" is a UUID, which does not carry an entity - pass --as <entity>.`);return qE(e,t,n.uuid)}C(`Cannot read "${e}" as an id: ${cL[n.reason]}.`),D(" A TypeID looks like vp_01k3vbk6hxe008000000000001; a UUID like 0198f6b9-9a3d-7000-8000-000000000001."),process.exit(A.USAGE_ERROR)}var cL={"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 BE(e){e.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((t,n)=>{let{format:r,fields:o}=S(e.opts()),i=sL(t,n.as);if(n.sql===!0){console.log(i.sql);return}if(r==="json"){v(N(i,o));return}J([{title:"Id",rows:[{label:"TypeID",value:i.typeid},{label:"UUID",value:i.uuid},{label:"Entity",value:i.entity},{label:"Prefix",value:i.prefix}]}])})}import{existsSync as ZE,lstatSync as YE,mkdirSync as hL,readFileSync as JE,realpathSync as WE,rmSync as yL,statSync as _L,writeFileSync as GE}from"node:fs";import{homedir as bL}from"node:os";import{dirname as vL,isAbsolute as XE,join as yn,relative as SL}from"node:path";import{readdirSync as lL,readFileSync as dL}from"node:fs";import{join as uL,relative as pL}from"node:path";import{fileURLToPath as mL}from"node:url";var Qn="SKILL.md";function fL(e,t){if(e===t)return 0;return e<t?-1:1}function gL(e){let t={},n=lL(e,{recursive:!0,withFileTypes:!0});for(let r of n){if(!r.isFile()||r.name.startsWith("."))continue;let o=uL(r.parentPath,r.name);t[pL(e,o).replaceAll("\\","/")]=dL(o,"utf-8")}return Object.fromEntries(Object.entries(t).toSorted(([r],[o])=>fL(r,o)))}function HE(){if(typeof{"SKILL.md":`---
|
|
121
|
+
${KM}`)}function qM(e){return[31,29,31,30,31,30,31,31,30,31,30,31][e-1]??0}function CE(e){return/^-?\d+$/.test(e)?Number(e):void 0}function AE(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().startsWith(e)}function RE(e,t,n){if(t===void 0||t<1||t>12)return et(e,"month must be 1-12");if(n===void 0||n<1||n>qM(t))return et(e,"day is not a real day of that month");return{kind:"fixed",month:t,day:n}}function IE(e,t,n){if(t===void 0||!AE(t))return et(e,"start date must be a real YYYY-MM-DD");if(n===void 0)return{kind:"single",start_date:t};if(!AE(n))return et(e,"end date must be a real YYYY-MM-DD");if(n<t)return et(e,"end date is before the start date");return{kind:"single",start_date:t,end_date:n}}function OE(e,t){if(t===void 0||t<-366||t>366)return et(e,"offset must be an integer from -366 to 366");return{kind:"easter",offset_days:t}}function NE(e,t,n,r){if(t===void 0||t<1||t>12)return et(e,"month must be 1-12");if(n===void 0||n<0||n>6)return et(e,"weekday must be 0-6, 0 = Sunday");if(r===1||r===2||r===3||r===4||r===5||r===-1)return{kind:"nth_weekday",month:t,weekday:n,nth:r};return et(e,"N must be 1-5, or -1 for the last")}function Or(e){return typeof e==="number"&&Number.isInteger(e)?e:void 0}function TE(e){return typeof e==="string"?e:void 0}function BM(e){let t;try{t=JSON.parse(e)}catch{return et(e,"not valid JSON")}if(!ge(t))return et(e,"JSON must be an object");switch(t.kind){case"fixed":return RE(e,Or(t.month),Or(t.day));case"single":return IE(e,TE(t.start_date),TE(t.end_date));case"easter":return OE(e,Or(t.offset_days));case"nth_weekday":return NE(e,Or(t.month),Or(t.weekday),Or(t.nth));default:return et(e,"kind must be fixed, single, easter or nth_weekday")}}function kE(e){let t=e.trim();if(t.startsWith("{"))return BM(t);let[n,...r]=t.split(":"),o=r.join(":");switch(n??""){case"fixed":{let i=/^(\d{2})-(\d{2})$/.exec(o);return RE(e,i?Number(i[1]):void 0,i?Number(i[2]):void 0)}case"single":{let[i,a,...s]=o.split("..");if(s.length>0)return et(e,"a range has exactly two dates");return IE(e,i,a)}case"easter":return OE(e,CE(o));case"nth":{let i=r.map((a)=>CE(a));if(i.length!==3)return et(e,"expected nth:MONTH:WEEKDAY:N");return NE(e,i[0],i[1],i[2])}default:return et(e,"unknown form")}}function Ra(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(typeof e==="string"?new Date(e):e)}async function Mo(e){return(await e.oauth.whoami()).organization?.timezone??"UTC"}function DE(e){if(e===void 0)return"—";return e.reason==="emergency"?"emergency":e.status}function Lo(e){if(e==null)return"—";return e instanceof Date?e.toISOString():e}var HM=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function WM(e){if(e.length===0)return"—";return e.map((t)=>`${t.days.map((n)=>HM[n]??n).join(",")} ${t.start}-${t.end}`).join("; ")}function yp(e){return e.length===0?"closed all day":e.map((t)=>`${t.start}-${t.end}`).join(", ")}function GM(e){if(e.length===0)return"—";return e.map((t)=>t.source==="catalog"?t.code:t.holiday_calendar_id).join(", ")}function ZM(e){return{page:Number(e.page),limit:Number(e.limit)}}function Ft(e,t){let{fields:n}=S(e.opts());v(n&&t!==null&&typeof t==="object"&&!Array.isArray(t)?O(t,n):t)}async function PE(e,t,n,r){if(e==="json"){v(t?n.map((i)=>O(i,t)):n);return}let o=await r();L(["Date","Holiday","Type","Mode","Hours","Calendar"],n.map((i)=>({Date:Ra(i.occurrence.start,o),Holiday:i.occurrence.name,Type:i.occurrence.type,Mode:i.overridden?`${i.mode} (override)`:i.mode,Hours:i.mode==="reduced"?yp(i.intervals):"—",Calendar:i.occurrence.calendar.source==="catalog"?i.occurrence.calendar.code:i.occurrence.calendar.name})))}function YM(e,t,n){let r=e.command("exceptions").description("Exceptions: dates that replace the normal hours (a training day, a one-off closure)");r.command("list").description("List exceptions").option("--schedule <id>","Only the exceptions that apply to this schedule").option("--limit <n>","Items per page","20").option("--page <n>","Page number","1").action(async(o)=>{let{format:i,fields:a}=S(t.opts()),s=await b(n().scheduleExceptions.list({...ZM(o),schedule_id:x("schedules",o.schedule)}));if(i==="json"){v(a?s.items.map((c)=>O(c,a)):s);return}L(["ID","Name","From","To","Yearly","Open windows"],s.items.map((c)=>({ID:c.id,Name:c.name,From:c.start_date,To:c.end_date??c.start_date,Yearly:c.yearly?"yes":"no","Open windows":yp(c.intervals)}))),ee(s)}),r.command("show <id>").description("Show an exception").action(async(o)=>{let{format:i}=S(t.opts()),a=await b(n().scheduleExceptions.getById({schedule_exception_id:x("schedule_exceptions",o)}));if(i==="json"){Ft(t,a);return}J([{title:a.name,rows:[{label:"ID",value:a.id},{label:"From",value:a.start_date},{label:"To",value:a.end_date??a.start_date},{label:"Yearly",value:a.yearly?"yes":"no"},{label:"Open windows",value:yp(a.intervals)},{label:"Schedules",value:a.schedule_ids.join(", ")||"—"}]}])}),r.command("create").description("Create an exception from JSON: { name, start_date, end_date?, yearly?, intervals?: [{ start, end }], schedule_ids? }").requiredOption("--file <path>","JSON body (- for stdin)").action(async(o)=>{let{format:i}=S(t.opts()),a=await b(n().scheduleExceptions.create(await Ir(o.file)));if(i==="json"){Ft(t,a);return}N(`Exception created: ${a.id} (${a.name})`)}),r.command("update <id>").description("Update an exception from JSON; only the fields sent change (intervals and schedule_ids replace)").requiredOption("--file <path>","JSON body (- for stdin)").action(async(o,i)=>{let{format:a}=S(t.opts()),s=await Ir(i.file),c=await b(n().scheduleExceptions.update({...s,schedule_exception_id:x("schedule_exceptions",o)}));if(a==="json"){Ft(t,c);return}N(`Exception updated: ${c.id} (${c.name})`)}),r.command("delete <id>").description("Delete an exception (needs --yes in a non-interactive shell)").action(async(o)=>{let{format:i}=S(t.opts());await Te(`Delete exception ${o}?`,{yes:t.opts().yes===!0});let a=x("schedule_exceptions",o);if(await b(n().scheduleExceptions.delete({schedule_exception_id:a})),i==="json"){v({id:a,deleted:!0});return}N(`Exception deleted: ${a}`)})}function $E(e,t){let n=e.command("schedules").description("Business hours: schedules, exceptions and emergency close");n.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(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().schedules.list({page:Number(r.page),limit:Number(r.limit),search:r.search}));if(o==="json"){let s=i?a.items.map((c)=>O(c,i)):a;v(s);return}L(["ID","Name","Status","Description"],a.items.map((s)=>({ID:s.id,Name:s.name,Status:DE(s.current),Description:s.description??"—"}))),ee(a)}),n.command("show <id>").description("Show a schedule: hours, timezone, subscribed holiday calendars, emergency and current status").action(async(r)=>{let{format:o}=S(e.opts()),i=await b(t().schedules.getById({schedule_id:x("schedules",r)}));if(i===null)C(`Schedule "${r}" not found.`),process.exit(A.NOT_FOUND);if(o==="json"){Ft(e,i);return}J([{title:i.name,rows:[{label:"ID",value:i.id},{label:"Status now",value:DE(i.current)},{label:"Timezone",value:i.timezone},{label:"Weekly hours",value:WM(i.weekly_hours)},{label:"Holiday calendars",value:GM(i.holiday_calendars)},{label:"Holidays that close",value:i.holiday_close_types.join(", ")},{label:"Emergency",value:i.emergency?i.emergency.reason??"closed":null}]}])}),n.command("create").description('Create a schedule from JSON: { name, weekly_hours: [{ days: [1,2,3,4,5], start: "09:00", end: "18:00" }], timezone?, holiday_calendars?: [{ source: "catalog", code: "BR-SP" } | { source: "custom", holiday_calendar_id }], holiday_close_types? }').requiredOption("--file <path>","JSON body (- for stdin)").action(async(r)=>{let{format:o}=S(e.opts()),i=await b(t().schedules.create(await Ir(r.file)));if(o==="json"){Ft(e,i);return}N(`Schedule created: ${i.id} (${i.name})`)}),n.command("update <id>").description("Update a schedule from JSON; only the fields sent change. holiday_calendars replaces the whole list: read it with `schedules show` and send it complete").requiredOption("--file <path>","JSON body (- for stdin)").action(async(r,o)=>{let{format:i}=S(e.opts()),a=await Ir(o.file),s=await b(t().schedules.update({...a,schedule_id:x("schedules",r)}));if(i==="json"){Ft(e,s);return}N(`Schedule updated: ${s.id} (${s.name})`)}),n.command("delete <id>").description("Delete a schedule (needs --yes in a non-interactive shell); check `schedules usage` first").action(async(r)=>{let{format:o}=S(e.opts());await Te(`Delete schedule ${r}?`,{yes:e.opts().yes===!0});let i=x("schedules",r);if(await b(t().schedules.delete({schedule_id:i})),o==="json"){v({id:i,deleted:!0});return}N(`Schedule deleted: ${i}`)}),n.command("simulate <id>").description("Evaluate a schedule at an instant and say which layer decided: emergency, exception, holiday or weekly").option("--at <iso>","ISO 8601 instant with offset, e.g. 2026-12-25T10:00:00-03:00 (default: now)").action(async(r,o)=>{let{format:i}=S(e.opts()),a=await b(t().schedules.simulate({schedule_id:x("schedules",r),at:o.at??new Date().toISOString()}));if(i==="json"){Ft(e,a);return}J([{title:"Simulation",rows:[{label:"Status",value:a.status},{label:"Decided by",value:a.reason},{label:"Description",value:a.description},{label:"Agenda output",value:a.output},{label:"Closes at",value:Lo(a.closes_at)},{label:"Reopens at",value:Lo(a.reopens_at)}]}])}),n.command("holidays <id>").description("List the holidays that apply to a schedule in a window, with the mode each takes").option("--from <date>","Window start, YYYY-MM-DD (default: today)").option("--to <date>","Window end, YYYY-MM-DD, included (default: one year after --from)").action(async(r,o)=>{let{format:i,fields:a}=S(e.opts()),s=await b(t().schedules.holidays({schedule_id:x("schedules",r),from:o.from,to:o.to}));await PE(i,a,s,async()=>(await b(t().schedules.getById({schedule_id:x("schedules",r)})))?.timezone??await Mo(t()))}),n.command("preview-holidays").description("Preview the holidays a calendar setup would produce, without saving a schedule. JSON: { holiday_calendars, holiday_close_types?, holiday_overrides? }").requiredOption("--file <path>","JSON body (- for stdin)").option("--from <date>","Window start, YYYY-MM-DD (default: today)").option("--to <date>","Window end, YYYY-MM-DD, included (default: one year after --from)").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await Ir(r.file),s=await b(t().schedules.previewHolidays({...a,...r.from===void 0?{}:{from:r.from},...r.to===void 0?{}:{to:r.to}}));await PE(o,i,s,async()=>a.timezone??await Mo(t()))}),n.command("upcoming").description("Holidays and exceptions that close or change the hours, across every schedule, in date order").option("--days <n>","How many days ahead (default: 60)").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().schedules.upcoming({days:r.days===void 0?void 0:Number(r.days)}));if(o==="json"){v(i?a.map((s)=>O(s,i)):a);return}L(["Date","Until","Schedule","Kind","Name","Effect"],a.map((s)=>({Date:s.date,Until:s.end_date,Schedule:s.schedule_name,Kind:s.kind,Name:s.name,Effect:s.effect})))}),n.command("usage <id>").description("List the plans and channels that use a schedule").action(async(r)=>{let{format:o}=S(e.opts()),i=await b(t().schedules.usage({schedule_id:x("schedules",r)}));if(o==="json"){Ft(e,i);return}L(["Kind","ID","Name"],[...i.plans.map((a)=>({Kind:"plan",ID:a.id,Name:a.name})),...i.channels.map((a)=>({Kind:"channel",ID:a.id,Name:a.name}))])}),n.command("close <id>").description("Emergency close: the schedule is closed now, ahead of every other layer. Takes effect on live calls").requiredOption("--reason <text>","Why it is closed").option("--until <iso>","ISO 8601 instant with offset when it reopens on its own (default: until `reopen`)").action(async(r,o)=>{let{format:i}=S(e.opts()),a=await b(t().schedules.setEmergency({schedule_id:x("schedules",r),reason:o.reason,until:o.until}));if(i==="json"){Ft(e,a);return}N(`Schedule closed: ${a.id} (${o.reason})`)}),n.command("reopen <id>").description("End an emergency close and return to the normal hours").action(async(r)=>{let{format:o}=S(e.opts()),i=await b(t().schedules.clearEmergency({schedule_id:x("schedules",r)}));if(o==="json"){Ft(e,i);return}N(`Schedule reopened: ${i.id}`)}),YM(n,e,t)}var _p="Rule: fixed:MM-DD | single:YYYY-MM-DD[..YYYY-MM-DD] | easter:N | nth:MONTH:WEEKDAY:N | a JSON rule object";function bp(e){try{return kE(e)}catch(t){C(t instanceof Error?t.message:String(t)),process.exit(A.USAGE_ERROR)}}function ME(e){switch(e.kind){case"fixed":return`every year ${String(e.month).padStart(2,"0")}-${String(e.day).padStart(2,"0")}`;case"single":return e.end_date===void 0?e.start_date:`${e.start_date}..${e.end_date}`;case"easter":return`easter ${e.offset_days>=0?"+":""}${e.offset_days}`;case"nth_weekday":return`nth ${e.nth} weekday ${e.weekday} of month ${e.month}`}}function Xn(e,t){let{fields:n}=S(e.opts());v(n&&t!==null&&typeof t==="object"&&!Array.isArray(t)?O(t,n):t)}function FE(e){return{page:Number(e.page),limit:Number(e.limit)}}function LE(e){return e.option("--start-time <hh:mm>","Start of a partial-day window (with --end-time)").option("--end-time <hh:mm>","End of a partial-day window (with --start-time)")}function zE(e,t){return e!==null&&t!==null?`${e}-${t}`:null}function JM(e,t){if(t===void 0)return e.next_occurrence??"—";let n=e.occurrence_in_year;return n===null?"—":`${n.start_date}..${n.end_date}`}function XM(e,t,n){let r=e.command("calendars").description("Own holiday calendars (the built-in catalog is separate)");r.command("list").description("List own holiday calendars").option("--limit <n>","Items per page","20").option("--page <n>","Page number","1").option("--search <term>","Search by name").action(async(o)=>{let{format:i,fields:a}=S(t.opts()),s=await b(n().holidayCalendars.list({...FE(o),search:o.search}));if(i==="json"){v(a?s.items.map((c)=>O(c,a)):s);return}L(["ID","Name","Description"],s.items.map((c)=>({ID:c.id,Name:c.name,Description:c.description??"—"}))),ee(s)}),r.command("show <id>").description("Show a holiday calendar").action(async(o)=>{let{format:i}=S(t.opts()),a=await b(n().holidayCalendars.getById({holiday_calendar_id:x("holiday_calendars",o)}));if(i==="json"){Xn(t,a);return}J([{title:a.name,rows:[{label:"ID",value:a.id},{label:"Description",value:a.description}]}])}),r.command("create").description("Create an empty holiday calendar; add holidays with `holidays entries create`").requiredOption("--name <name>","Calendar name, e.g. the city").option("--description <text>","Description").action(async(o)=>{let{format:i}=S(t.opts()),a=await b(n().holidayCalendars.create({name:o.name,description:o.description}));if(i==="json"){Xn(t,a);return}N(`Holiday calendar created: ${a.id} (${a.name})`)}),r.command("update <id>").description("Rename a holiday calendar or change its description").option("--name <name>","New name").option("--description <text>","New description").action(async(o,i)=>{let{format:a}=S(t.opts()),s=await b(n().holidayCalendars.update({holiday_calendar_id:x("holiday_calendars",o),name:i.name,description:i.description}));if(a==="json"){Xn(t,s);return}N(`Holiday calendar updated: ${s.id} (${s.name})`)}),r.command("delete <id>").description("Delete a holiday calendar and its entries (needs --yes in a non-interactive shell)").action(async(o)=>{let{format:i}=S(t.opts());await Te(`Delete holiday calendar ${o} and all its entries?`,{yes:t.opts().yes===!0});let a=x("holiday_calendars",o);if(await b(n().holidayCalendars.delete({holiday_calendar_id:a})),i==="json"){v({id:a,deleted:!0});return}N(`Holiday calendar deleted: ${a}`)}),r.command("import <id>").description("Import an .ics file as entries. Dated events become single dates of that year, not yearly holidays; recreate the yearly ones as rules").requiredOption("--file <path>",".ics file (- for stdin)").action(async(o,i)=>{let{format:a}=S(t.opts()),s=await b(n().holidayCalendars.importIcs({holiday_calendar_id:x("holiday_calendars",o),content:await hp(i.file)}));if(a==="json"){Xn(t,s);return}N(`Imported ${s.imported} event(s), skipped ${s.skipped}.`)})}function QM(e,t,n){let r=e.command("entries").description("Holidays inside an own calendar");r.command("list <calendar_id>").description("List the entries of a calendar; --year shows the days each rule covers that year").option("--year <yyyy>","Calendar year").option("--limit <n>","Items per page","20").option("--page <n>","Page number","1").action(async(o,i)=>{let{format:a,fields:s}=S(t.opts()),c=await b(n().holidayCalendars.entries.list({holiday_calendar_id:x("holiday_calendars",o),year:i.year===void 0?void 0:Number(i.year),...FE(i)}));if(a==="json"){v(s?c.items.map((d)=>O(d,s)):c);return}L(["ID","Name","Type","Rule","Hours",i.year===void 0?"Next":`In ${i.year}`],c.items.map((d)=>({ID:d.id,Name:d.name,Type:d.type,Rule:ME(d.rule),Hours:zE(d.start_time,d.end_time)??"whole day",[i.year===void 0?"Next":`In ${i.year}`]:JM(d,i.year)}))),ee(c)}),r.command("show <calendar_id> <entry_id>").description("Show one entry").action(async(o,i)=>{let{format:a}=S(t.opts()),s=await b(n().holidayCalendars.entries.getById({holiday_calendar_id:x("holiday_calendars",o),holiday_calendar_entry_id:x("holiday_calendar_entries",i)}));if(a==="json"){Xn(t,s);return}J([{title:s.name,rows:[{label:"ID",value:s.id},{label:"Type",value:s.type},{label:"Rule",value:ME(s.rule)},{label:"Hours",value:zE(s.start_time,s.end_time)},{label:"Next occurrence",value:s.next_occurrence},{label:"Source",value:s.source}]}])}),LE(r.command("create <calendar_id>").description("Add a holiday. A holiday that repeats yearly is a recurring rule (fixed, easter, nth), never a single date. Carnival is easter:-47, Good Friday easter:-2, Corpus Christi easter:60").requiredOption("--name <name>","Holiday name").option("--type <type>","public | optional | bank","public").requiredOption("--rule <rule>",_p)).action(async(o,i)=>{let{format:a}=S(t.opts()),s=await b(n().holidayCalendars.entries.create({holiday_calendar_id:x("holiday_calendars",o),name:i.name,type:se(i.type),rule:bp(i.rule),start_time:i.startTime,end_time:i.endTime}));if(a==="json"){Xn(t,s);return}N(`Entry created: ${s.id} (${s.name})`)}),LE(r.command("update <calendar_id> <entry_id>").description("Update an entry; only the options sent change").option("--name <name>","New name").option("--type <type>","public | optional | bank").option("--rule <rule>",_p)).action(async(o,i,a)=>{let{format:s}=S(t.opts()),c=await b(n().holidayCalendars.entries.update({holiday_calendar_id:x("holiday_calendars",o),holiday_calendar_entry_id:x("holiday_calendar_entries",i),name:a.name,type:se(a.type),rule:a.rule===void 0?void 0:bp(a.rule),start_time:a.startTime,end_time:a.endTime}));if(s==="json"){Xn(t,c);return}N(`Entry updated: ${c.id} (${c.name})`)}),r.command("delete <calendar_id> <entry_id>").description("Delete an entry (needs --yes in a non-interactive shell)").action(async(o,i)=>{let{format:a}=S(t.opts());await Te(`Delete entry ${i}?`,{yes:t.opts().yes===!0});let s=x("holiday_calendar_entries",i);if(await b(n().holidayCalendars.entries.delete({holiday_calendar_id:x("holiday_calendars",o),holiday_calendar_entry_id:s})),a==="json"){v({id:s,deleted:!0});return}N(`Entry deleted: ${s}`)})}async function eL(e,t){let[n,r]=t.split("-");if(n!==void 0&&r!==void 0){let i=(await b(e.holidayCatalog.regions({country_code:n}))).find((a)=>a.code===`${n}-${r}`);if(i!==void 0)return i.timezone}return Mo(e)}function tL(e,t,n){let r=e.command("catalog").description("Built-in holiday catalog (offline, same for everyone)");r.command("countries").description("List the catalog countries").action(async()=>{let{format:o,fields:i}=S(t.opts()),a=await b(n().holidayCatalog.countries());if(o==="json"){v(i?a.map((s)=>O(s,i)):a);return}L(["Code","Name"],a.map((s)=>({Code:s.code,Name:s.name})))}),r.command("regions <country_code>").description("List the states and cities of a catalog country, with their codes (BR-SP, BR-SP-SP)").action(async(o)=>{let{format:i,fields:a}=S(t.opts()),s=await b(n().holidayCatalog.regions({country_code:o}));if(i==="json"){v(a?s.map((c)=>O(c,a)):s);return}L(["Code","Name","Timezone","Cities"],s.map((c)=>({Code:c.code,Name:c.name,Timezone:c.timezone,Cities:c.cities.map((d)=>`${d.code} ${d.name}`).join(", ")||"—"})))}),r.command("holidays <code>").description("Holidays of one catalog level (BR, BR-SP or BR-SP-SP) for a year. A state lists only what the country lacks and a city only what neither has").option("--year <yyyy>","Year (default: this year)").action(async(o,i)=>{let{format:a,fields:s}=S(t.opts()),c=await b(n().holidayCatalog.holidays({code:o,year:i.year===void 0?new Date().getFullYear():Number(i.year)}));if(a==="json"){v(s?c.map((u)=>O(u,s)):c);return}let d=await eL(n(),o);L(["Date","Holiday","Type","Rule"],c.map((u)=>({Date:Ra(u.start,d),Holiday:u.name,Type:u.type,Rule:u.rule_description??"—"})))})}function UE(e,t){let n=e.command("holidays").description("Holiday calendars: own calendars, entries and the catalog");XM(n,e,t),QM(n,e,t),tL(n,e,t),n.command("preview-rule").description("Dry-run a rule: its next occurrences, without saving anything. Run it before `entries create`").requiredOption("--rule <rule>",_p).option("--count <n>","How many occurrences (1-10)","5").option("--start-time <hh:mm>","Start of a partial-day window (with --end-time)").option("--end-time <hh:mm>","End of a partial-day window (with --start-time)").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().holidayCalendars.previewRule({rule:bp(r.rule),count:Number(r.count),start_time:r.startTime,end_time:r.endTime}));if(o==="json"){v(i?a.map((s)=>O(s,i)):a);return}L(["Start","End (exclusive)"],a.map((s)=>({Start:Lo(s.start),"End (exclusive)":Lo(s.end)})))})}function nL(){return Object.entries(W).map(([e,t])=>`${e} (${t}_)`).sort((e,t)=>e.localeCompare(t))}function rL(e){return Object.hasOwn(W,e)}function jE(e){C(e),P(" Valid entities:");for(let t of nL())P(` ${t}`);process.exit(A.USAGE_ERROR)}function VE(e,t,n){return{input:e,entity:t,prefix:W[t],typeid:Mi(t,n),uuid:n,sql:`'${n}'::uuid`}}function oL(e,t){if(t!=null&&!rL(t))jE(`Unknown entity "${t}".`);let n=Dn(e);if(n.kind==="typeid"){if(t!=null&&t!==n.entity)C(`"${e}" is a ${n.entity} id, but --as says ${t}.`),P(" Drop --as: a TypeID already carries its entity."),process.exit(A.USAGE_ERROR);return VE(e,n.entity,n.uuid)}if(n.kind==="uuid"){if(t==null)jE(`"${e}" is a UUID, which does not carry an entity - pass --as <entity>.`);return VE(e,t,n.uuid)}C(`Cannot read "${e}" as an id: ${iL[n.reason]}.`),P(" A TypeID looks like vp_01k3vbk6hxe008000000000001; a UUID like 0198f6b9-9a3d-7000-8000-000000000001."),process.exit(A.USAGE_ERROR)}var iL={"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 KE(e){e.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((t,n)=>{let{format:r,fields:o}=S(e.opts()),i=oL(t,n.as);if(n.sql===!0){console.log(i.sql);return}if(r==="json"){v(O(i,o));return}J([{title:"Id",rows:[{label:"TypeID",value:i.typeid},{label:"UUID",value:i.uuid},{label:"Entity",value:i.entity},{label:"Prefix",value:i.prefix}]}])})}import{existsSync as WE,lstatSync as GE,mkdirSync as mL,readFileSync as ZE,realpathSync as BE,rmSync as fL,statSync as gL,writeFileSync as HE}from"node:fs";import{homedir as hL}from"node:os";import{dirname as yL,isAbsolute as YE,join as yn,relative as _L}from"node:path";import{readdirSync as aL,readFileSync as sL}from"node:fs";import{join as cL,relative as lL}from"node:path";import{fileURLToPath as dL}from"node:url";var Qn="SKILL.md";function uL(e,t){if(e===t)return 0;return e<t?-1:1}function pL(e){let t={},n=aL(e,{recursive:!0,withFileTypes:!0});for(let r of n){if(!r.isFile()||r.name.startsWith("."))continue;let o=cL(r.parentPath,r.name);t[lL(e,o).replaceAll("\\","/")]=sL(o,"utf-8")}return Object.fromEntries(Object.entries(t).toSorted(([r],[o])=>uL(r,o)))}function qE(){if(typeof{"SKILL.md":`---
|
|
122
122
|
name: niva-cli
|
|
123
123
|
description: >
|
|
124
124
|
NIVA CLI for the IVR/omnichannel platform: debug calls, monitor health, read logs,
|
|
@@ -2324,21 +2324,21 @@ niva signals test --preset off_script_offer --plan <plan_id> --last 5
|
|
|
2324
2324
|
Pages on this installation's docs (open them when the task needs the user-facing detail):
|
|
2325
2325
|
|
|
2326
2326
|
- \`<NIVA_URL>/docs/en/configuracoes/signals\`, \`<NIVA_URL>/docs/en/dashboard/signals\`, \`<NIVA_URL>/docs/en/configuracoes/webhooks\`
|
|
2327
|
-
`};return
|
|
2327
|
+
`};return pL(dL(new URL("../../skill-template",import.meta.url)))}var JE=["claude","agents","both"],bL={claude:[".claude"],agents:[".agents"],both:[".agents",".claude"]},vL=new Set(JE);function SL(e){return vL.has(e)}function xL(){let e=process.env.HOME;return e!=null&&e!==""?e:hL()}var EL="Install the skill for which agent?",wL=[{label:"All (recommended)",value:"both"},{label:"Claude Code",value:"claude"},{label:"Codex / Cursor / Copilot / Gemini CLI / opencode",value:"agents"}];async function CL(e){if(e.target!=null){if(!SL(e.target))C(`Error: invalid --target "${e.target}" — expected one of: ${JE.join(", ")}`),process.exit(A.USAGE_ERROR);return e.target}if(e.yes)return"both";if(e.interactive!==!0)return P("Non-interactive shell — installing for all agents. Pass --target to choose."),"both";return Fi(EL,wL,e.ask==null?{}:{ask:e.ask})}var XE=/^---\r?\n([\s\S]*?)\r?\n---/,AL=/^[\w.+-]+$/;function vp(e){return AL.test(e)}function TL(e){let t=XE.exec(e)?.[1];if(t==null)return;let r=/^[ \t]+cli_version:(.*)$/m.exec(t)?.[1]?.trim().replaceAll(/^"|"$/g,"").trim();return r==null||!vp(r)?void 0:r}function RL(e,t){let n=e.split(`
|
|
2328
2328
|
`),r=n.findIndex((o)=>o.startsWith("metadata:"));if(r===-1)return`${e}
|
|
2329
2329
|
metadata:
|
|
2330
2330
|
cli_version: "${t}"`;if(n[r]!=="metadata:")return e;for(let o=r+1;o<n.length;o++){let i=n[o];if(!/^\s+\S/.test(i))break;if(/^\s+cli_version:/.test(i))return n[o]=` cli_version: "${t}"`,n.join(`
|
|
2331
2331
|
`)}return n.splice(r+1,0,` cli_version: "${t}"`),n.join(`
|
|
2332
|
-
`)}function
|
|
2333
|
-
${
|
|
2334
|
-
---${e.slice(n.index+n[0].length)}`}var
|
|
2335
|
-
`)}catch(o){C(`Error: could not write ${t} — ${o instanceof Error?o.message:String(o)}`),process.exit(A.GENERAL_ERROR)}}function
|
|
2336
|
-
Next page: --cursor ${d.nextCursor}`)}function
|
|
2337
|
-
`)}function sw(e){let t=0,n=0,r=!1;for(let o=0;o<e.length;o+=1){let i=e[o];if(i==='"'){if(r&&e[o+1]==='"'){o+=1;continue}r=!r}else if(!r){if(i===",")t+=1;else if(i===";")n+=1}}return n>t?";":","}function GL(e,t){let n="",r=t;for(;r<e.length;r+=1){let o=e[r];if(o!=='"')n+=o;else if(e[r+1]==='"')n+='"',r+=1;else return{value:n,end:r}}return{value:n,end:r}}function cw(e,t){let n=[],r="",o=!1,i=0;while(i<e.length){let a=e[i];if(a==='"'){let s=GL(e,i+1);r+=s.value,i=s.end,o=!0}else if(a===t)n.push(o?r:r.trim()),r="",o=!1;else r+=a;i+=1}return n.push(o?r:r.trim()),n}var Cp=["phone_number","name","status","attempt_count","machine_attempts","machine_type","last_attempt_at"],JL=new Set(Cp);function wp(e,t){return[...t,e]}function dw(e){let t={};for(let n of e){let r=n.indexOf("=");if(r<=0)C(`Invalid --field "${n}" (expected key=value)`),process.exit(A.USAGE_ERROR);t[n.slice(0,r)]=n.slice(r+1)}return t}function XL(e){return e==="phone"||e==="name"||e==="ignore"||/^custom:.+$/.test(e)}function QL(e,t){if(t==null)return sw(e);if(t!==","&&t!==";")C(`Invalid --separator "${t}" (must be , or ;)`),process.exit(A.USAGE_ERROR);return t}function ez(e,t){let n=Jc(e),r={};for(let o of e){let i=n.roles[o]??"ignore";if(i!=="custom"){r[o]=i;continue}let a=n.customNames[o];r[o]=a!=null&&a.length>0?`custom:${a}`:"ignore"}for(let o of t){let i=o.indexOf("=");if(i<=0)C(`Invalid --map "${o}" (expected <Column>=<role>)`),process.exit(A.USAGE_ERROR);let a=o.slice(0,i),s=o.slice(i+1);if(!e.includes(a))C(`Unknown column "${a}". Available: ${e.join(", ")}`),process.exit(A.USAGE_ERROR);if(!XL(s))C(`Invalid role "${s}" for column "${a}" (phone|name|ignore|custom:<field>)`),process.exit(A.USAGE_ERROR);r[a]=s}return r}function tz(e){if(e==null)return"—";if(typeof e==="string")return e;if(typeof e==="number"||typeof e==="boolean")return String(e);return JSON.stringify(e)}async function nz(e,t,n){let r=new AbortController;process.on("SIGINT",()=>r.abort());let o="",i=0;if(await new Promise((a,s)=>{Qt(e.dialerImports.progress({import_job_id:x("dialer_import_jobs",t)},{signal:r.signal}),{onEvent:(c)=>{if(o=c.status,i=c.invalid,n==="json")console.log(JSON.stringify(c));else{let d=c.total_rows!=null?String(c.total_rows):"-";D(`[${c.status}] processed ${c.processed_rows}/${d} · imported ${c.imported} · skipped ${c.skipped} · invalid ${c.invalid}`)}if(c.status==="done"||c.status==="failed")a()},onError:(c)=>{if(c instanceof DOMException&&c.name==="AbortError"){a();return}s(c)},onSuccess:()=>a()})}).catch(In),o==="failed")return A.GENERAL_ERROR;if(o==="done"&&i>0&&n!=="json")D(`${i} invalid row(s). Inspect with: niva mailing invalid-rows ${t}`);return A.SUCCESS}function uw(e,t){let n=e.command("mailing").description("Manage campaign mailing (contacts & imports)");n.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(r,o)=>{let{format:i,fields:a}=S(e.opts()),s=await b(t().dialerContacts.list({campaign_id:x("dialer_campaigns",r),page:Number(o.page),limit:Number(o.limit),status:ce(o.status),search:o.search}));if(i==="json"){v(a?s.items.map((c)=>N(c,a)):s);return}L(["ID","Phone","Name","Status","Attempts","Machine","Last attempt"],s.items.map((c)=>({ID:c.id,Phone:c.phone_number,Name:c.name??"—",Status:c.status,Attempts:c.attempt_count,Machine:Xo(c.machine_type),"Last attempt":c.last_attempt_at!=null?Me(c.last_attempt_at):"—"}))),te(s)}),n.command("show <campaign_id> <contact_id>").description("Show a mailing contact with its custom fields").action(async(r,o)=>{let{format:i,fields:a}=S(e.opts()),s=await b(t().dialerContacts.get({campaign_id:x("dialer_campaigns",r),contact_id:x("dialer_contacts",o)}));if(i==="json"){v(a?N(s,a):s);return}let c=[{title:"Contact",rows:[{label:"ID",value:s.id},{label:"Phone",value:s.phone_number},{label:"Name",value:s.name??"—"},{label:"Status",value:s.status},{label:"Attempts",value:s.attempt_count},{label:"Last attempt",value:s.last_attempt_at!=null?new Date(s.last_attempt_at).toLocaleString():"—"},{label:"Next attempt",value:s.next_attempt_at!=null?new Date(s.next_attempt_at).toLocaleString():"—"},{label:"Created",value:new Date(s.created_at).toLocaleString()}]}],d=s.custom_fields;if(d!=null&&typeof d==="object"&&!Array.isArray(d)&&Object.keys(d).length>0)c.push({title:"Custom fields",rows:Object.entries(d).map(([u,m])=>({label:u,value:tz(m)}))});J(c)}),n.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)",wp,[]).action(async(r,o,i)=>{let{format:a}=S(e.opts()),s=dw(i.field),c=await b(t().dialerContacts.add({campaign_id:x("dialer_campaigns",r),phone_number:o,name:i.name,custom_fields:Object.keys(s).length>0?s:void 0}));if(a==="json"){v(c);return}O(`Contact added: ${c.id}`)}),n.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)",wp,[]).action(async(r,o,i)=>{let{format:a}=S(e.opts()),s=await b(t().dialerContacts.update({campaign_id:x("dialer_campaigns",r),contact_id:x("dialer_contacts",o),...i.phone!=null&&{phone_number:i.phone},...i.name!=null&&{name:i.name},...i.field.length>0&&{custom_fields:dw(i.field)}}));if(a==="json"){v(s);return}O("Contact updated")}),n.command("remove <campaign_id> <contactIds...>").description("Remove (soft-delete) mailing contacts").action(async(r,o)=>{let{format:i}=S(e.opts()),a=await b(t().dialerContacts.remove({campaign_id:x("dialer_campaigns",r),ids:x("dialer_contacts",o)}));if(i==="json"){v(a);return}O(`Removed ${a.removed}, skipped ${a.skipped}`)}),n.command("cancel <campaign_id> <contactIds...>").description("Cancel pending mailing contacts").action(async(r,o)=>{let{format:i}=S(e.opts()),a=await b(t().dialerContacts.bulkCancel({campaign_id:x("dialer_campaigns",r),ids:x("dialer_contacts",o)}));if(i==="json"){v(a);return}O(`Cancelled ${a.cancelled}, skipped ${a.skipped}`)}),n.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(r,o,i)=>{let{format:a}=S(e.opts()),s=o.length>0;if(s&&i.all===!0)C("Use either <contactIds...> or --all, not both"),process.exit(A.USAGE_ERROR);if(!s&&i.all!==!0)C("Provide contact IDs or --all to requeue"),process.exit(A.USAGE_ERROR);if(s){let d=await b(t().dialerContacts.bulkRequeue({campaign_id:x("dialer_campaigns",r),ids:x("dialer_contacts",o)}));if(a==="json"){v(d);return}O(`Requeued ${d.requeued}, skipped ${d.skipped}`);return}let c=await b(t().dialerContacts.requeueAll({campaign_id:x("dialer_campaigns",r),status:ce(i.status)}));if(a==="json"){v(c);return}O(`Requeued ${c.requeued}`)}),n.command("import <campaign_id> <file>").description("Import a CSV mailing into a campaign").option("--map <pair>","Column mapping override <Column>=<role> (repeatable)",wp,[]).option("--separator <sep>","CSV separator (, or ;) — sniffed when omitted").option("--watch","Follow import progress until it finishes").action(async(r,o,i)=>{let{format:a}=S(e.opts()),s=e.opts().yes===!0,c=await ZL(o),d=c.toString("utf-8"),u=d.search(/\r\n|\n|\r/),m=u===-1?d:d.slice(0,u);if(m.trim()==="")C("File is empty or has no header row"),process.exit(A.USAGE_ERROR);let y=QL(m,i.separator),_=cw(m,y),E=ez(_,i.map);if(a!=="json")L(["Column","Role"],_.map((G)=>({Column:G,Role:E[G]??"ignore"})));await Ce("Import with this mapping?",{yes:s});let k=t(),V=await b(k.dialerImports.create({campaign_id:x("dialer_campaigns",r),column_mapping:E,file:new File([c],YL(o))}));if(a!=="json")O(`Import started: ${V.id} (${V.status})`);else if(i.watch!==!0)v(V);if(i.watch===!0){let G=await nz(k,V.id,a);if(G!==A.SUCCESS)process.exit(G)}}),n.command("import-status <import_job_id>").description("Show the status of a mailing import job").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().dialerImports.get({import_job_id:x("dialer_import_jobs",r)}));if(o==="json"){v(i?N(a,i):a);return}J([{title:"Import job",rows:[{label:"ID",value:a.id},{label:"Status",value:a.status},{label:"Total rows",value:a.total_rows??"—"},{label:"Processed",value:a.processed_rows},{label:"Imported",value:a.imported},{label:"Skipped",value:a.skipped},{label:"Invalid",value:a.invalid},{label:"Has invalid rows",value:a.has_invalid_rows?"yes":"no"},{label:"Created",value:new Date(a.created_at).toLocaleString()}]}])}),n.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(r,o)=>{let i=await b(t().dialerImports.invalidRows({import_job_id:x("dialer_import_jobs",r)}));if(i==null){D("No invalid rows.");return}if(o.out!=null){await lw(o.out,i.csv,"utf-8"),O(`Wrote invalid rows to ${o.out}`);return}process.stdout.write(i.csv)}),n.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(r,o)=>{let i=await b(t().dialerContacts.exportCsv({campaign_id:x("dialer_campaigns",r),status:ce(o.status),search:o.search})),a=[],s=new Set;for await(let y of i){a.push(y);for(let _ of Object.keys(y))if(!JL.has(_))s.add(_)}if(a.length===0){D("No contacts to export.");return}let c=[...s].sort((y,_)=>y.localeCompare(_)),d=[...Cp,...c],u=a.map((y)=>[...Cp.map((_)=>y[_]??""),...c.map((_)=>y[_]??"")]),m=aw(d,u);if(o.out!=null){await lw(o.out,m,"utf-8"),O(`Wrote ${a.length} contacts to ${o.out}`);return}process.stdout.write(m)})}function pw(e){if(!(e in vt))console.error(`Unknown node type: ${e}`),console.error(`Available: ${Object.keys(vt).join(", ")}`),process.exit(2)}function Ap(e){return St[e]?.connector}function rz(e){return`${e.kind} (config key ${e.configKey}) - create it with niva connectors create ${e.kind}`}function oz(e){return e in $n}function mw(e){let t=e.command("nodes").description("IVR node types reference");t.command("list").description("List node types with module, channel and the connector kind a block needs (- when none)").option("--module <module>","Filter by module (core, ai)").option("--category <cat>","Filter by category (interaction, handling, routing, data, legacy)").option("--channel <ch>","Filter by channel (voice, chat, both)").action((n)=>{let{format:r,fields:o}=S(e.opts()),i=ou();if(n.module!=null)i=i.filter((a)=>a.module===n.module);if(n.category!=null)i=i.filter((a)=>a.category===n.category);if(n.channel!=null)i=i.filter((a)=>a.channel===n.channel);if(r==="json"){let a=i.map((s)=>({...s,connector:Ap(s.type)??null}));v(o?a.map((s)=>N(s,o)):a);return}L(["Type","Name","Description","Module","Channel","Connector"],i.map((a)=>({Type:a.type,Name:a.name,Description:a.description,Module:a.module,Channel:a.channel,Connector:Ap(a.type)?.kind??"-"})))}),t.command("show <type>").description("Show a node type: config fields, outputs, variables and the connector it needs").action((n)=>{let{format:r}=S(e.opts());pw(n);let o=yo(n),i=Ap(n);if(r==="json"){v({...o,connector:i??null});return}let a=oz(n)?$n[n]:void 0,s=a!=null?Object.entries(a).map(([c,d])=>({label:c,value:String(d)})):[{label:"(no fields)",value:""}];J([{title:`${o.name} (${o.type})`,rows:[{label:"Description",value:o.description},{label:"Module",value:o.module},{label:"Category",value:o.category},{label:"Channel",value:o.channel},{label:"Nature",value:o.nature},...i!=null?[{label:"Connector",value:rz(i)}]:[]]},{title:"Config Fields",rows:s},{title:"Outputs",rows:o.outputs.map((c)=>({label:c.key,value:c.labelKey}))},{title:"Produced Variables",rows:o.producedVariables.length>0?o.producedVariables.map((c)=>({label:`${c.name} (${c.type})`,value:c.descriptionKey})):[{label:"(none)",value:""}]}])}),t.command("schema <type>").description("Output JSON Schema for a node's config (agent-friendly)").action((n)=>{pw(n);let r=yo(n);v(r.configJsonSchema)})}var fw=7;function gw(e,t,n){let r=e.indexOf("=");if(r===-1)throw Error(`${n} expects key=value (got: ${e})`);let o=e.slice(0,r),i=e.slice(r+1);if(o==="")throw Error(`${n} expects key=value (got: ${e})`);return t[o]=i,t}function iz(e,t){return gw(e,t,"--var")}function az(e,t){return gw(e,t,"--metadata")}function sz(e){return e==="pre"||e==="post"}function cz(e){let t=e.amd===!0||e.machineType===!0;if(e.amdMode!==void 0&&!t)C("--amd-mode requires --amd or --machine-type"),process.exit(A.USAGE_ERROR);if(e.amdMaxWait!==void 0&&e.amdMode!=="pre")C("--amd-max-wait requires --amd-mode pre"),process.exit(A.USAGE_ERROR);let n;if(e.amdMode!==void 0){if(!sz(e.amdMode))C(`Invalid --amd-mode "${e.amdMode}": expected pre or post`),process.exit(A.USAGE_ERROR);n=e.amdMode}let r=e.amdMaxWait===void 0?void 0:Number(e.amdMaxWait);if(r!==void 0&&(!Number.isInteger(r)||r<3||r>10))C(`Invalid --amd-max-wait "${e.amdMaxWait}": expected an integer from 3 to 10`),process.exit(A.USAGE_ERROR);if(!t)return;let o=e.machineType===!0?{amd:!0,machine_type:!0}:{amd:!0};if(n==="pre")return{...o,mode:n,max_wait_seconds:r??fw};if(n==="post")return{...o,mode:n};return o}function hw(e,t){e.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 the Classifier module 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 ${fw})`).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",iz,{}).option("--metadata <key=value>","Opaque call metadata persisted with the CDR; repeatable",az,{}).action(async(r)=>{let{format:o}=S(e.opts()),i=Object.entries(r.var),a=Object.entries(r.metadata),s=cz(r),c={plan_id:x("visual_plans",r.plan),destination:r.destination,timeout:Number(r.timeout),...r.maxDuration!==void 0?{max_call_duration_s:Number(r.maxDuration)}:{},...r.callerId!==void 0?{caller_id:r.callerId}:{},...r.callerIdName!==void 0?{caller_id_name:r.callerIdName}:{},...s!==void 0?{answer_recognition:s}:{},...i.length>0?{variables:r.var}:{},...a.length>0?{metadata:r.metadata}:{}},d=await b(t().calls.originate(c));if(o==="json")v(d);else if(d.status==="failed")Et(`Originate outcome: status=failed call_id=${d.call_id} channel_uuid=${d.channel_uuid} answered_at=${d.answered_at??"none"} hangup_cause=${d.hangup_cause??"unknown"} sip_code=${d.sip_code??"unknown"}`);else O(`Originate outcome: status=answered call_id=${d.call_id} channel_uuid=${d.channel_uuid} answered_at=${d.answered_at??"none"} hangup_cause=${d.hangup_cause??"none"} sip_code=${d.sip_code??"none"}`);if(d.status==="failed")process.exit(A.GENERAL_ERROR)})}import{readFile as Cw}from"node:fs/promises";import{readFile as lz}from"node:fs/promises";function dz(e){return"usage_count"in e}function uz(e){let t=Math.max(0,Math.floor(e)),n=Math.floor(t/60),r=t%60;return`${String(n).padStart(2,"0")}:${String(r).padStart(2,"0")}`}function pz(e){return e==="caller"?"Cliente":"Atendimento"}function yw(e){if(e==null||e==="pt-BR")return"pt-BR";if(e==="en")return"en";C(`Error: invalid --locale "${e}" — expected one of: pt-BR, en`),process.exit(A.USAGE_ERROR)}async function vw(e){let t=e==="-"?await Fe():await lz(e,"utf-8"),n;try{n=JSON.parse(t)}catch{C(`Invalid JSON in "${e}"`),process.exit(A.USAGE_ERROR)}if(!se(n))C(`Invalid signal file "${e}": expected a JSON object`),process.exit(A.USAGE_ERROR);return n}function Sw(e,t){let n=e.slug==null&&t!=null?{...e,slug:t}:e,r=vr.safeParse(n);if(!r.success){C("Invalid signal definition:");for(let o of r.error.issues)C(` ✗ ${o.path.join(".")||"(root)"}: ${o.message}`);process.exit(A.USAGE_ERROR)}return r.data}function mz(e){return vr.parse({slug:e.slug,name:e.name,question:e.question,kind:e.kind,...e.options!==void 0?{options:e.options}:{},...e.levels!==void 0?{levels:e.levels}:{},...e.higher_is!==void 0?{higher_is:e.higher_is}:{},speaker:e.speaker,scope:e.scope,live:e.live,alert:e.alert})}async function zo(e,t){return(await b(e.signals.list({search:t,limit:100,page:1,include_archived:!0}))).items.find((r)=>r.slug===t)}function fz(e){if(Dn(e).kind==="uuid")return!0;let t=e.lastIndexOf("_");return t>0&&io(e.slice(0,t))==="signals"}async function _w(e,t){if(!fz(t))return zo(e,t);let n=await b(e.signals.get({signal_id:x("signals",t)}));return await zo(e,n.slug)??n}function gz(e){if("answer"in e)return e.answer==="yes"?"for Sim":"for Não";if("options"in e)return`for ${e.options.join(", ")}`;if("level_at_most"in e)return`dropping to level ${e.level_at_most}`;return`reaching level ${e.level_at_least}`}function hz(e){let t=e.description!=null?` — ${e.description}`:"",n=e.archived?" (archived)":"";return`${e.label}${t}${n}`}function bw(e){for(let t of e.turns){let n=t.index===e.first_trigger_index?" <- would trigger":"";console.log(`${uz(t.start)} ${pz(t.speaker)} ${t.value_label}${n}`)}console.log(`Fim da chamada ${e.final==null?"ninguém falou no trecho que o signal escuta":e.final.value_label}`)}async function yz(e,t,n){if(t.file!=null)return Sw(await vw(t.file),"test_signal");if(t.preset!=null){let o=la.find((i)=>i.id===t.preset);if(o==null)C(`Error: unknown preset "${t.preset}".`),D(` Valid presets: ${la.map((i)=>i.id).join(", ")}`),process.exit(A.USAGE_ERROR);return au(o,n)}let r=await zo(e,t.slug??"");if(r==null)C(`Signal "${t.slug}" not found.`),process.exit(A.NOT_FOUND);return mz(r)}function _z(e,t,n){if(e.text!=null)return{definition:t,text:e.text,locale:n};if(e.call!=null)return{definition:t,call_id:x("call_records",e.call),locale:n};return{definition:t,visual_plan_id:x("visual_plans",e.plan??""),last:e.last!=null?Number(e.last):void 0,locale:n}}function xw(e,t){let n=e.command("signals").description("Signal library and testing");n.command("presets").description("List the ten signal models").option("--locale <locale>","Locale of the texts: pt-BR or en","pt-BR").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=yw(r.locale),s=await b(t().signals.presets({locale:a}));if(o==="json"){v(i?s.map((c)=>N(c,i)):s);return}L(["ID","Name","Kind","Speaker","Live","Severity"],s.map((c)=>({ID:c.id,Name:c.definition.name,Kind:c.definition.kind,Speaker:c.definition.speaker,Live:c.definition.live?"yes":"no",Severity:c.definition.alert?.severity??"—"})))}),n.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(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().signals.list({page:Number(r.page),limit:Number(r.limit),search:r.search,include_archived:r.includeArchived===!0}));if(o==="json"){let s=i?a.items.map((c)=>N(c,i)):a;v(s);return}L(["Slug","Name","Kind","Live","Org default","Usage","Fires 7d","Version","Archived"],a.items.map((s)=>({Slug:s.slug,Name:s.name,Kind:s.kind,Live:s.live?"yes":"no","Org default":s.is_org_default?"yes":"no",Usage:`${s.usage_count.published}/${s.usage_count.draft}`,"Fires 7d":s.fires_last_7_days.reduce((c,d)=>c+d,0),Version:s.version,Archived:s.archived_at!=null?"yes":"no"}))),te(a)}),n.command("show <slug_or_id>").description("Show one signal (slug or sig_... TypeID) with its usage").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await _w(t(),r);if(a==null)C(`Signal "${r}" not found.`),process.exit(A.NOT_FOUND);if(o==="json"){v(i?N(a,i):a);return}let s=[{title:"Signal",rows:[{label:"ID",value:a.id},{label:"Slug",value:a.slug},{label:"Name",value:a.name},{label:"Question",value:a.question},{label:"Kind",value:a.kind},...a.higher_is!==void 0?[{label:"Higher is",value:a.higher_is}]:[],{label:"Speaker",value:a.speaker},{label:"Scope",value:a.scope?.node_types.join(", ")??"whole call"},{label:"Live",value:a.live?"yes":"no"},{label:"Org default",value:a.is_org_default?"yes":"no"},{label:"Version",value:a.version},{label:"Archived",value:a.archived_at!=null?"yes":"no"}]},{title:"Alert",rows:a.alert==null?[{label:"When",value:"—"}]:[{label:"When",value:gz(a.alert.when)},{label:"Severity",value:a.alert.severity},{label:"Bell",value:a.alert.bell?"yes":"no"},{label:"Attendant hint",value:a.alert.attendant_hint??"—"}]}];if(a.options!==void 0)s.push({title:"Options",rows:a.options.map((c)=>({label:c.key,value:hz(c)}))});if(a.levels!==void 0)s.push({title:"Levels",rows:a.levels.map((c,d)=>({label:String(d+1),value:c}))});if(dz(a))s.push({title:"Usage",rows:[{label:"Published plans",value:a.usage_count.published},{label:"Draft plans",value:a.usage_count.draft},{label:"Fires 7d",value:a.fires_last_7_days.reduce((c,d)=>c+d,0)},{label:"Evaluated calls 7d",value:a.evaluated_calls_last_7_days.reduce((c,d)=>c+d,0)}]});J(s)}),n.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(r)=>{let{format:o}=S(e.opts()),i=t(),a=yw(r.locale),s=[r.file,r.preset,r.slug].filter((y)=>y!=null).length,c=[r.text,r.call,r.plan].filter((y)=>y!=null).length;if(s!==1||c!==1)C("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(r.last!=null&&r.plan==null)C("Error: --last only applies with --plan."),process.exit(A.USAGE_ERROR);let d=await yz(i,r,a),u=_z(r,d,a),m=await b(i.signals.test(u));if(o==="json"){v(m);return}if("calls"in m)m.calls.forEach((y,_)=>{if(_>0)console.log("");console.log(`Call ${y.call_id}`),bw(y)});else if("turns"in m)bw(m);else console.log(`${m.value_label}${m.would_trigger?" <- would trigger":""}`)}),n.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(r)=>{let{format:o}=S(e.opts()),i=t(),a=await vw(r.file),s=Sw(a),c=typeof a.is_org_default==="boolean"?a.is_org_default:void 0,d=await b(i.signals.upsertBySlug({...s,...c!==void 0?{is_org_default:c}:{},dry_run:r.dryRun===!0}));if(o==="json"){v(d);return}bz(d.status,d.changed_fields,d.signal.slug,r.dryRun===!0)}),n.command("delete <slug_or_id>").description("Move a signal to the trash (slug or sig_... TypeID)").action(async(r)=>{let{format:o}=S(e.opts()),i=await _w(t(),r);if(i==null)C(`Signal "${r}" not found.`),process.exit(A.NOT_FOUND);let a=await b(t().signals.delete({signal_id:x("signals",i.id)}));if(o==="json"){v(a);return}O(`Signal moved to the trash: ${a.slug}. Restore it from Settings > Archive.`)})}function bz(e,t,n,r){if(e==="created"){O(r?`would create: ${n}`:`created: ${n}`);return}if(e==="unchanged"){D(`unchanged: ${n}`);return}O(r?`would update: ${n} (changed: ${t.join(", ")})`:`updated: ${n} (changed: ${t.join(", ")})`)}async function Tp(e){let t=e==="-"?await Fe():await Cw(e,"utf-8"),n=Ud.safeParse(JSON.parse(t));if(!n.success){C(`Invalid execution plan in "${e}":`);for(let r of n.error.issues)C(` ✗ ${r.path.join(".")||"(root)"}: ${r.message}`);process.exit(A.GENERAL_ERROR)}return n.data}function er(e){return e!=null&&typeof e==="object"&&!Array.isArray(e)}function vz(e){if(!er(e)||!Array.isArray(e.nodes)||!Array.isArray(e.edges))return!1;let t=e.viewport;return er(t)&&typeof t.x==="number"&&typeof t.y==="number"&&typeof t.zoom==="number"}async function Sz(e){let t=e==="-"?await Fe():await Cw(e,"utf-8"),n;try{n=JSON.parse(t)}catch{C(`Invalid JSON in plan export "${e}"`),process.exit(A.GENERAL_ERROR)}let r;if(er(n)&&n.format==="niva-plan-v1")r=n.state;else if(er(n)&&er(n.draft)&&n.draft.editor_state!=null)r=n.draft.editor_state;else if(er(n)&&n.published_editor_state!=null)r=n.published_editor_state;else if(er(n)&&Array.isArray(n.nodes)&&Array.isArray(n.edges))r=n;else C(`Invalid plan export in "${e}"`),process.exit(A.GENERAL_ERROR);if(!vz(r))C(`Invalid editor state in plan export "${e}"`),process.exit(A.GENERAL_ERROR);return r}function Rp(e){let t=e.severity==="error"?"✗":"⚠",n=e.node_id!=null?` [${e.node_id}]`:"";return` ${t}${n} ${e.message_key}`}var xz="! 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 Ew(e){try{let t=Uc(e),n=uu(t.nodes,t.edges,St);if(!pu(n)){for(let r of n)C(Rp({node_id:r.nodeId,severity:r.severity,message_key:r.messageKey}));return!1}return Et(xz),!0}catch(t){return C(t instanceof Error?t.message:String(t)),!1}}async function Ez(e,t,n,r){if(await b(e.channels.update({channel_id:x("channels",t),visual_plan_id:x("visual_plans",n),reassign:!0})),r!=="json")O(`Channel ${t} assigned to plan`)}async function wz(e,t,n){if(await b(e.channels.update({channel_id:x("channels",t),visual_plan_id:null})),n!=="json")O(`Channel ${t} unassigned from plan`)}async function Cz(e,t,n){let r=x("visual_plans",t),o=await b(e.channels.list({page:1,limit:100})),i=o.items.filter((s)=>s.visual_plan_id===r),a=o.items.filter((s)=>s.visual_plan_id==null);if(n==="json"){v({assigned:i,available:a});return}if(i.length>0)console.log(`
|
|
2332
|
+
`)}function IL(e,t){if(!vp(t))throw Error(`Refusing to stamp a malformed CLI version: ${JSON.stringify(t)}`);let n=XE.exec(e),r=n?.[1];if(n==null||r==null)return e;return`---
|
|
2333
|
+
${RL(r,t)}
|
|
2334
|
+
---${e.slice(n.index+n[0].length)}`}var OL=["skills","niva-cli","references"];function NL(e,t){let n=_L(t,e);return n===""||!n.startsWith("..")&&!YE(n)}function kL(e,t){let n;try{n=BE(e)}catch{return`${e} does not exist or cannot be resolved.`}let r=e;for(let o of[t,...OL]){r=yn(r,o);let i=GE(r,{throwIfNoEntry:!1});if(i==null)return;if(i.isSymbolicLink()){let a;try{a=BE(r)}catch{return`${r} is a broken symlink — remove it and retry.`}if(!NL(a,n))return`${r} is a symlink pointing outside ${n} (${a}) — refusing to write through it.`}if(!gL(r).isDirectory())return`${r} already exists and is not a directory — remove it and retry.`}return}function DL(e){try{return TL(ZE(e,"utf-8"))}catch{return}}function PL(e,t,n){if(!WE(e))return;let r=DL(e);if(r==null)P(`Existing skill found in ${t} (version unknown) — overwriting.`);else if(r===n)P(`Existing skill found in ${t} — overwriting.`);else P(`Updating skill in ${t} from ${r} to ${n}.`)}var QE=".niva-install.json",$L=[Qn,"references/cli-reference.md","references/node-handles.md","references/signals.md"];function ML(e){if(typeof e!=="string"||e===""||YE(e)||e.includes("\\"))return!1;return!e.split("/").some((t)=>t===".."||t==="."||t==="")}function LL(e){try{let t=JSON.parse(ZE(yn(e,QE),"utf-8"));if(typeof t!=="object"||t===null||!("files"in t)||!Array.isArray(t.files))return[];return t.files.filter((n)=>ML(n))}catch{return WE(yn(e,Qn))?[...$L]:[]}}function zL(e,t,n){for(let r of t){if(n.has(r))continue;let o=yn(e,r);if(GE(o,{throwIfNoEntry:!1})?.isFile()===!0)fL(o)}}function FL(e,t,n){let r=Object.keys(n);try{zL(e,LL(e),new Set(r));for(let[o,i]of Object.entries(n)){let a=yn(e,o);mL(yL(a),{recursive:!0}),HE(a,i)}HE(yn(e,QE),`${JSON.stringify({version:1,files:r},null,2)}
|
|
2335
|
+
`)}catch(o){C(`Error: could not write ${t} — ${o instanceof Error?o.message:String(o)}`),process.exit(A.GENERAL_ERROR)}}function ew(e){e.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(t)=>{let n=await CL({target:t.target,yes:e.opts().yes===!0,interactive:co()}),r=zr();if(!vp(r))C(`Error: CLI_VERSION is not a plain version string (${JSON.stringify(r)}) — refusing to write the skill.`),process.exit(A.USAGE_ERROR);let o=t.global===!0,i=o?xL():process.cwd(),a=o?"~/":"",s=bL[n],c=s.map((_)=>kL(i,_)).filter((_)=>_!=null);if(c.length>0){for(let _ of c)C(`Error: ${_}`);P("Nothing was installed."),process.exit(A.GENERAL_ERROR)}let d=qE(),u=d[Qn];if(u==null)C(`Error: this build carries no ${Qn} — reinstall the CLI.`),process.exit(A.GENERAL_ERROR);let m={...d,[Qn]:IL(u,r)},y=[];for(let _ of s){let E=yn(i,_,"skills","niva-cli"),k=`${a}${_}/skills/niva-cli/`;PL(yn(E,Qn),k,r),FL(E,k,m),y.push(k)}N(`NIVA CLI skill v${r} installed to:`);for(let _ of y)N(` ${_}`);P("Your coding agent will now use the NIVA CLI for IVR management tasks.")})}var _n=on(jt(),1);var UL=["server","engine","freeswitch","traefik","redis","postgres","client","docs"],jL={error:_n.default.red,warn:_n.default.yellow,info:_n.default.green,debug:_n.default.dim};function VL(e){if(e==null)return;let t=e.error;if(t!=null&&typeof t==="object"&&"message"in t){let n=t.message;if(typeof n==="string")return n}return}function tw(e){let t=new Date(e.ts),n=Number.isNaN(t.getTime())?e.ts:`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}`,o=(jL[e.level]??((c)=>c))(e.level.toUpperCase().padEnd(5)),i=_n.default.cyan(`[${e.service}]`),a=`${_n.default.dim(n)} ${i} ${o} ${e.message}`,s=VL(e.meta);if(s!=null)a+=_n.default.red(` — ${s}`);return a}function Sp(e,t={}){if(e.option("--since <v>","Start time — relative (e.g. 1h, 30m, 45s) or ISO date").option("--until <v>","End time — relative or ISO date"),t.fixedLevel!==!0)e.option("--level <level>","Minimum severity: error, warn, info, debug");return e.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)"),e}async function KL(e,t){return new Promise((n,r)=>{Qt(e,{onEvent:(o)=>{if(t==="json")console.log(JSON.stringify(o));else console.log(tw(o))},onError:(o)=>{if(o instanceof DOMException&&o.name==="AbortError"){n();return}r(o)},onSuccess:()=>n()})})}async function qL(e,t,n){let r=new AbortController;process.on("SIGINT",()=>{r.abort()});try{await KL(e.system.watchLogs(t,{signal:r.signal}),n)}catch(o){Ct(o)}}async function xp(e,t,n,r,o){let{format:i,fields:a}=S(n.opts()),s=se(o??t.level);if(t.follow===!0){await qL(r(),{service:e,level:s,grep:t.grep},i);return}let c={service:e,since:t.since,until:t.until,level:s,grep:t.grep,limit:t.limit!=null?Number(t.limit):void 0,cursor:t.cursor},d=await b(r().system.logs(c));if(i==="json"){for(let u of d.entries){let m=a?O(u,a):u;console.log(JSON.stringify(m))}if(d.nextCursor!=null)console.log(JSON.stringify({nextCursor:d.nextCursor}));return}if(d.entries.length===0){P("No log entries.");return}for(let u of d.entries)console.log(tw(u));if(d.nextCursor!=null)P(`
|
|
2336
|
+
Next page: --cursor ${d.nextCursor}`)}function nw(e,t){let n=e.command("logs").description("View service logs and call events");n.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(i)=>{if(i.follow===!0)Vt("Live call-event streaming is not available here. Use `niva calls follow <uuid>` to stream a call's live transcription.");let a=i.callRecord??i.uuid;if(a==null)Vt("Please provide --call-record or --follow.");let{format:s,fields:c}=S(e.opts()),d=await b(t().callRecords.getEvents({call_record_id:x("call_records",a)}));if(s==="json"){let u=c?d.map((m)=>O(m,c)):d;v(u);return}if(d.length===0){P("No events found.");return}L(["Timestamp","Event","Details"],d.map((u)=>({Timestamp:new Date(u.entered_at).toLocaleString(),Event:u.node_type,Details:u.data!=null?JSON.stringify(u.data):"—"})))});for(let i of UL){let a=n.command(i).description(`View ${i} service logs from the appliance journal`);Sp(a),a.action(async(s)=>xp(i,s,e,t))}let r=n.command("errors").description("View error-level logs across all services (merged timeline)");Sp(r,{fixedLevel:!0}),r.action(async(i)=>xp("all",i,e,t,"error"));let o=n.command("all").description("View a merged timeline of logs from all services");Sp(o),o.action(async(i)=>xp("all",i,e,t))}import{readFile as HL,writeFile as sw}from"node:fs/promises";import{basename as WL}from"node:path";function rw(e){if(e==null)return'""';return`"${String(e).replaceAll('"','""')}"`}function ow(e,t,n=","){let r=[e.map((o)=>rw(o)).join(n)];for(let o of t)r.push(o.map((i)=>rw(i)).join(n));return r.join(`\r
|
|
2337
|
+
`)}function iw(e){let t=0,n=0,r=!1;for(let o=0;o<e.length;o+=1){let i=e[o];if(i==='"'){if(r&&e[o+1]==='"'){o+=1;continue}r=!r}else if(!r){if(i===",")t+=1;else if(i===";")n+=1}}return n>t?";":","}function BL(e,t){let n="",r=t;for(;r<e.length;r+=1){let o=e[r];if(o!=='"')n+=o;else if(e[r+1]==='"')n+='"',r+=1;else return{value:n,end:r}}return{value:n,end:r}}function aw(e,t){let n=[],r="",o=!1,i=0;while(i<e.length){let a=e[i];if(a==='"'){let s=BL(e,i+1);r+=s.value,i=s.end,o=!0}else if(a===t)n.push(o?r:r.trim()),r="",o=!1;else r+=a;i+=1}return n.push(o?r:r.trim()),n}var wp=["phone_number","name","status","attempt_count","machine_attempts","machine_type","last_attempt_at"],GL=new Set(wp);function Ep(e,t){return[...t,e]}function cw(e){let t={};for(let n of e){let r=n.indexOf("=");if(r<=0)C(`Invalid --field "${n}" (expected key=value)`),process.exit(A.USAGE_ERROR);t[n.slice(0,r)]=n.slice(r+1)}return t}function ZL(e){return e==="phone"||e==="name"||e==="ignore"||/^custom:.+$/.test(e)}function YL(e,t){if(t==null)return iw(e);if(t!==","&&t!==";")C(`Invalid --separator "${t}" (must be , or ;)`),process.exit(A.USAGE_ERROR);return t}function JL(e,t){let n=Zc(e),r={};for(let o of e){let i=n.roles[o]??"ignore";if(i!=="custom"){r[o]=i;continue}let a=n.customNames[o];r[o]=a!=null&&a.length>0?`custom:${a}`:"ignore"}for(let o of t){let i=o.indexOf("=");if(i<=0)C(`Invalid --map "${o}" (expected <Column>=<role>)`),process.exit(A.USAGE_ERROR);let a=o.slice(0,i),s=o.slice(i+1);if(!e.includes(a))C(`Unknown column "${a}". Available: ${e.join(", ")}`),process.exit(A.USAGE_ERROR);if(!ZL(s))C(`Invalid role "${s}" for column "${a}" (phone|name|ignore|custom:<field>)`),process.exit(A.USAGE_ERROR);r[a]=s}return r}function XL(e){if(e==null)return"—";if(typeof e==="string")return e;if(typeof e==="number"||typeof e==="boolean")return String(e);return JSON.stringify(e)}async function QL(e,t,n){let r=new AbortController;process.on("SIGINT",()=>r.abort());let o="",i=0;if(await new Promise((a,s)=>{Qt(e.dialerImports.progress({import_job_id:x("dialer_import_jobs",t)},{signal:r.signal}),{onEvent:(c)=>{if(o=c.status,i=c.invalid,n==="json")console.log(JSON.stringify(c));else{let d=c.total_rows!=null?String(c.total_rows):"-";P(`[${c.status}] processed ${c.processed_rows}/${d} · imported ${c.imported} · skipped ${c.skipped} · invalid ${c.invalid}`)}if(c.status==="done"||c.status==="failed")a()},onError:(c)=>{if(c instanceof DOMException&&c.name==="AbortError"){a();return}s(c)},onSuccess:()=>a()})}).catch(In),o==="failed")return A.GENERAL_ERROR;if(o==="done"&&i>0&&n!=="json")P(`${i} invalid row(s). Inspect with: niva mailing invalid-rows ${t}`);return A.SUCCESS}function lw(e,t){let n=e.command("mailing").description("Manage campaign mailing (contacts & imports)");n.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(r,o)=>{let{format:i,fields:a}=S(e.opts()),s=await b(t().dialerContacts.list({campaign_id:x("dialer_campaigns",r),page:Number(o.page),limit:Number(o.limit),status:se(o.status),search:o.search}));if(i==="json"){v(a?s.items.map((c)=>O(c,a)):s);return}L(["ID","Phone","Name","Status","Attempts","Machine","Last attempt"],s.items.map((c)=>({ID:c.id,Phone:c.phone_number,Name:c.name??"—",Status:c.status,Attempts:c.attempt_count,Machine:Jo(c.machine_type),"Last attempt":c.last_attempt_at!=null?Me(c.last_attempt_at):"—"}))),ee(s)}),n.command("show <campaign_id> <contact_id>").description("Show a mailing contact with its custom fields").action(async(r,o)=>{let{format:i,fields:a}=S(e.opts()),s=await b(t().dialerContacts.get({campaign_id:x("dialer_campaigns",r),contact_id:x("dialer_contacts",o)}));if(i==="json"){v(a?O(s,a):s);return}let c=[{title:"Contact",rows:[{label:"ID",value:s.id},{label:"Phone",value:s.phone_number},{label:"Name",value:s.name??"—"},{label:"Status",value:s.status},{label:"Attempts",value:s.attempt_count},{label:"Last attempt",value:s.last_attempt_at!=null?new Date(s.last_attempt_at).toLocaleString():"—"},{label:"Next attempt",value:s.next_attempt_at!=null?new Date(s.next_attempt_at).toLocaleString():"—"},{label:"Created",value:new Date(s.created_at).toLocaleString()}]}],d=s.custom_fields;if(d!=null&&typeof d==="object"&&!Array.isArray(d)&&Object.keys(d).length>0)c.push({title:"Custom fields",rows:Object.entries(d).map(([u,m])=>({label:u,value:XL(m)}))});J(c)}),n.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)",Ep,[]).action(async(r,o,i)=>{let{format:a}=S(e.opts()),s=cw(i.field),c=await b(t().dialerContacts.add({campaign_id:x("dialer_campaigns",r),phone_number:o,name:i.name,custom_fields:Object.keys(s).length>0?s:void 0}));if(a==="json"){v(c);return}N(`Contact added: ${c.id}`)}),n.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)",Ep,[]).action(async(r,o,i)=>{let{format:a}=S(e.opts()),s=await b(t().dialerContacts.update({campaign_id:x("dialer_campaigns",r),contact_id:x("dialer_contacts",o),...i.phone!=null&&{phone_number:i.phone},...i.name!=null&&{name:i.name},...i.field.length>0&&{custom_fields:cw(i.field)}}));if(a==="json"){v(s);return}N("Contact updated")}),n.command("remove <campaign_id> <contactIds...>").description("Remove (soft-delete) mailing contacts").action(async(r,o)=>{let{format:i}=S(e.opts()),a=await b(t().dialerContacts.remove({campaign_id:x("dialer_campaigns",r),ids:x("dialer_contacts",o)}));if(i==="json"){v(a);return}N(`Removed ${a.removed}, skipped ${a.skipped}`)}),n.command("cancel <campaign_id> <contactIds...>").description("Cancel pending mailing contacts").action(async(r,o)=>{let{format:i}=S(e.opts()),a=await b(t().dialerContacts.bulkCancel({campaign_id:x("dialer_campaigns",r),ids:x("dialer_contacts",o)}));if(i==="json"){v(a);return}N(`Cancelled ${a.cancelled}, skipped ${a.skipped}`)}),n.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(r,o,i)=>{let{format:a}=S(e.opts()),s=o.length>0;if(s&&i.all===!0)C("Use either <contactIds...> or --all, not both"),process.exit(A.USAGE_ERROR);if(!s&&i.all!==!0)C("Provide contact IDs or --all to requeue"),process.exit(A.USAGE_ERROR);if(s){let d=await b(t().dialerContacts.bulkRequeue({campaign_id:x("dialer_campaigns",r),ids:x("dialer_contacts",o)}));if(a==="json"){v(d);return}N(`Requeued ${d.requeued}, skipped ${d.skipped}`);return}let c=await b(t().dialerContacts.requeueAll({campaign_id:x("dialer_campaigns",r),status:se(i.status)}));if(a==="json"){v(c);return}N(`Requeued ${c.requeued}`)}),n.command("import <campaign_id> <file>").description("Import a CSV mailing into a campaign").option("--map <pair>","Column mapping override <Column>=<role> (repeatable)",Ep,[]).option("--separator <sep>","CSV separator (, or ;) — sniffed when omitted").option("--watch","Follow import progress until it finishes").action(async(r,o,i)=>{let{format:a}=S(e.opts()),s=e.opts().yes===!0,c=await HL(o),d=c.toString("utf-8"),u=d.search(/\r\n|\n|\r/),m=u===-1?d:d.slice(0,u);if(m.trim()==="")C("File is empty or has no header row"),process.exit(A.USAGE_ERROR);let y=YL(m,i.separator),_=aw(m,y),E=JL(_,i.map);if(a!=="json")L(["Column","Role"],_.map((G)=>({Column:G,Role:E[G]??"ignore"})));await Te("Import with this mapping?",{yes:s});let k=t(),V=await b(k.dialerImports.create({campaign_id:x("dialer_campaigns",r),column_mapping:E,file:new File([c],WL(o))}));if(a!=="json")N(`Import started: ${V.id} (${V.status})`);else if(i.watch!==!0)v(V);if(i.watch===!0){let G=await QL(k,V.id,a);if(G!==A.SUCCESS)process.exit(G)}}),n.command("import-status <import_job_id>").description("Show the status of a mailing import job").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().dialerImports.get({import_job_id:x("dialer_import_jobs",r)}));if(o==="json"){v(i?O(a,i):a);return}J([{title:"Import job",rows:[{label:"ID",value:a.id},{label:"Status",value:a.status},{label:"Total rows",value:a.total_rows??"—"},{label:"Processed",value:a.processed_rows},{label:"Imported",value:a.imported},{label:"Skipped",value:a.skipped},{label:"Invalid",value:a.invalid},{label:"Has invalid rows",value:a.has_invalid_rows?"yes":"no"},{label:"Created",value:new Date(a.created_at).toLocaleString()}]}])}),n.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(r,o)=>{let i=await b(t().dialerImports.invalidRows({import_job_id:x("dialer_import_jobs",r)}));if(i==null){P("No invalid rows.");return}if(o.out!=null){await sw(o.out,i.csv,"utf-8"),N(`Wrote invalid rows to ${o.out}`);return}process.stdout.write(i.csv)}),n.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(r,o)=>{let i=await b(t().dialerContacts.exportCsv({campaign_id:x("dialer_campaigns",r),status:se(o.status),search:o.search})),a=[],s=new Set;for await(let y of i){a.push(y);for(let _ of Object.keys(y))if(!GL.has(_))s.add(_)}if(a.length===0){P("No contacts to export.");return}let c=[...s].sort((y,_)=>y.localeCompare(_)),d=[...wp,...c],u=a.map((y)=>[...wp.map((_)=>y[_]??""),...c.map((_)=>y[_]??"")]),m=ow(d,u);if(o.out!=null){await sw(o.out,m,"utf-8"),N(`Wrote ${a.length} contacts to ${o.out}`);return}process.stdout.write(m)})}function dw(e){if(!(e in bt))console.error(`Unknown node type: ${e}`),console.error(`Available: ${Object.keys(bt).join(", ")}`),process.exit(2)}function Cp(e){return vt[e]?.connector}function ez(e){return`${e.kind} (config key ${e.configKey}) - create it with niva connectors create ${e.kind}`}function tz(e){return e in $n}function uw(e){let t=e.command("nodes").description("IVR node types reference");t.command("list").description("List node types with module, channel and the connector kind a block needs (- when none)").option("--module <module>","Filter by module (core, ai)").option("--category <cat>","Filter by category (interaction, handling, routing, data, legacy)").option("--channel <ch>","Filter by channel (voice, chat, both)").action((n)=>{let{format:r,fields:o}=S(e.opts()),i=nu();if(n.module!=null)i=i.filter((a)=>a.module===n.module);if(n.category!=null)i=i.filter((a)=>a.category===n.category);if(n.channel!=null)i=i.filter((a)=>a.channel===n.channel);if(r==="json"){let a=i.map((s)=>({...s,connector:Cp(s.type)??null}));v(o?a.map((s)=>O(s,o)):a);return}L(["Type","Name","Description","Module","Channel","Connector"],i.map((a)=>({Type:a.type,Name:a.name,Description:a.description,Module:a.module,Channel:a.channel,Connector:Cp(a.type)?.kind??"-"})))}),t.command("show <type>").description("Show a node type: config fields, outputs, variables and the connector it needs").action((n)=>{let{format:r}=S(e.opts());dw(n);let o=yo(n),i=Cp(n);if(r==="json"){v({...o,connector:i??null});return}let a=tz(n)?$n[n]:void 0,s=a!=null?Object.entries(a).map(([c,d])=>({label:c,value:String(d)})):[{label:"(no fields)",value:""}];J([{title:`${o.name} (${o.type})`,rows:[{label:"Description",value:o.description},{label:"Module",value:o.module},{label:"Category",value:o.category},{label:"Channel",value:o.channel},{label:"Nature",value:o.nature},...i!=null?[{label:"Connector",value:ez(i)}]:[]]},{title:"Config Fields",rows:s},{title:"Outputs",rows:o.outputs.map((c)=>({label:c.key,value:c.labelKey}))},{title:"Produced Variables",rows:o.producedVariables.length>0?o.producedVariables.map((c)=>({label:`${c.name} (${c.type})`,value:c.descriptionKey})):[{label:"(none)",value:""}]}])}),t.command("schema <type>").description("Output JSON Schema for a node's config (agent-friendly)").action((n)=>{dw(n);let r=yo(n);v(r.configJsonSchema)})}var mw=7;function fw(e,t,n){let r=e.indexOf("=");if(r===-1)throw Error(`${n} expects key=value (got: ${e})`);let o=e.slice(0,r),i=e.slice(r+1);if(o==="")throw Error(`${n} expects key=value (got: ${e})`);return t[o]=i,t}function nz(e,t){return fw(e,t,"--var")}function rz(e,t){return fw(e,t,"--metadata")}function oz(e){return e==="pre"||e==="post"}function iz(e){return e==="hangup"||e==="continue"}function pw(e,t){if(t===void 0)return;if(!iz(t))C(`Invalid ${e} "${t}": expected hangup or continue`),process.exit(A.USAGE_ERROR);return t}function az(e){if(e===void 0)return;let t=Number(e);if(!Number.isInteger(t)||t<3||t>10)C(`Invalid --amd-max-wait "${e}": expected an integer from 3 to 10`),process.exit(A.USAGE_ERROR);return t}function sz(e){let t=pw("--amd-on-silence",e.amdOnSilence),n=pw("--amd-on-unknown",e.amdOnUnknown);if(t===void 0&&n===void 0)return{};return{actions:{...t!==void 0?{silence:t}:{},...n!==void 0?{unknown:n}:{}}}}function cz(e){let t=[["--amd-max-wait",e.amdMaxWait],["--amd-on-silence",e.amdOnSilence],["--amd-on-unknown",e.amdOnUnknown]];for(let[n,r]of t)if(r!==void 0&&e.amdMode!=="pre")C(`${n} requires --amd-mode pre`),process.exit(A.USAGE_ERROR)}function lz(e){let t=e.amd===!0||e.machineType===!0;if(e.amdMode!==void 0&&!t)C("--amd-mode requires --amd or --machine-type"),process.exit(A.USAGE_ERROR);cz(e);let n;if(e.amdMode!==void 0){if(!oz(e.amdMode))C(`Invalid --amd-mode "${e.amdMode}": expected pre or post`),process.exit(A.USAGE_ERROR);n=e.amdMode}let r=az(e.amdMaxWait),o=sz(e);if(!t)return;let i=e.machineType===!0?{amd:!0,machine_type:!0}:{amd:!0};if(n==="pre")return{...i,mode:n,max_wait_seconds:r??mw,...o};if(n==="post")return{...i,mode:n};return i}function gw(e,t){e.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; requires the Classifier module (403 MODULE_DISABLED without it)").option("--machine-type","Beta: identify voicemail, carrier announcement, IVR, or call screening; requires the Classifier module 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 ${mw})`).option("--amd-on-silence <action>","Pre mode only: what a silent line does (hangup|continue; default hangup). The plan reads the verdict as {{args.amd_result}}").option("--amd-on-unknown <action>","Pre mode only: what a window that expires with no verdict does (hangup|continue; default continue)").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",nz,{}).option("--metadata <key=value>","Opaque call metadata persisted with the CDR; repeatable",rz,{}).action(async(r)=>{let{format:o}=S(e.opts()),i=Object.entries(r.var),a=Object.entries(r.metadata),s=lz(r),c={plan_id:x("visual_plans",r.plan),destination:r.destination,timeout:Number(r.timeout),...r.maxDuration!==void 0?{max_call_duration_s:Number(r.maxDuration)}:{},...r.callerId!==void 0?{caller_id:r.callerId}:{},...r.callerIdName!==void 0?{caller_id_name:r.callerIdName}:{},...s!==void 0?{answer_recognition:s}:{},...i.length>0?{variables:r.var}:{},...a.length>0?{metadata:r.metadata}:{}},d=await b(t().calls.originate(c));if(o==="json")v(d);else if(d.status==="failed")Et(`Originate outcome: status=failed call_id=${d.call_id} channel_uuid=${d.channel_uuid} answered_at=${d.answered_at??"none"} hangup_cause=${d.hangup_cause??"unknown"} sip_code=${d.sip_code??"unknown"}`);else N(`Originate outcome: status=answered call_id=${d.call_id} channel_uuid=${d.channel_uuid} answered_at=${d.answered_at??"none"} hangup_cause=${d.hangup_cause??"none"} sip_code=${d.sip_code??"none"}`);if(d.status==="failed")process.exit(A.GENERAL_ERROR)})}import{readFile as ww}from"node:fs/promises";import{readFile as dz}from"node:fs/promises";function uz(e){return"usage_count"in e}function pz(e){let t=Math.max(0,Math.floor(e)),n=Math.floor(t/60),r=t%60;return`${String(n).padStart(2,"0")}:${String(r).padStart(2,"0")}`}function mz(e){return e==="caller"?"Cliente":"Atendimento"}function hw(e){if(e==null||e==="pt-BR")return"pt-BR";if(e==="en")return"en";C(`Error: invalid --locale "${e}" — expected one of: pt-BR, en`),process.exit(A.USAGE_ERROR)}async function bw(e){let t=e==="-"?await Fe():await dz(e,"utf-8"),n;try{n=JSON.parse(t)}catch{C(`Invalid JSON in "${e}"`),process.exit(A.USAGE_ERROR)}if(!ge(n))C(`Invalid signal file "${e}": expected a JSON object`),process.exit(A.USAGE_ERROR);return n}function vw(e,t){let n=e.slug==null&&t!=null?{...e,slug:t}:e,r=vr.safeParse(n);if(!r.success){C("Invalid signal definition:");for(let o of r.error.issues)C(` ✗ ${o.path.join(".")||"(root)"}: ${o.message}`);process.exit(A.USAGE_ERROR)}return r.data}function fz(e){return vr.parse({slug:e.slug,name:e.name,question:e.question,kind:e.kind,...e.options!==void 0?{options:e.options}:{},...e.levels!==void 0?{levels:e.levels}:{},...e.higher_is!==void 0?{higher_is:e.higher_is}:{},speaker:e.speaker,scope:e.scope,live:e.live,alert:e.alert})}async function zo(e,t){return(await b(e.signals.list({search:t,limit:100,page:1,include_archived:!0}))).items.find((r)=>r.slug===t)}function gz(e){if(Dn(e).kind==="uuid")return!0;let t=e.lastIndexOf("_");return t>0&&io(e.slice(0,t))==="signals"}async function yw(e,t){if(!gz(t))return zo(e,t);let n=await b(e.signals.get({signal_id:x("signals",t)}));return await zo(e,n.slug)??n}function hz(e){if("answer"in e)return e.answer==="yes"?"for Sim":"for Não";if("options"in e)return`for ${e.options.join(", ")}`;if("level_at_most"in e)return`dropping to level ${e.level_at_most}`;return`reaching level ${e.level_at_least}`}function yz(e){let t=e.description!=null?` — ${e.description}`:"",n=e.archived?" (archived)":"";return`${e.label}${t}${n}`}function _w(e){for(let t of e.turns){let n=t.index===e.first_trigger_index?" <- would trigger":"";console.log(`${pz(t.start)} ${mz(t.speaker)} ${t.value_label}${n}`)}console.log(`Fim da chamada ${e.final==null?"ninguém falou no trecho que o signal escuta":e.final.value_label}`)}async function _z(e,t,n){if(t.file!=null)return vw(await bw(t.file),"test_signal");if(t.preset!=null){let o=ca.find((i)=>i.id===t.preset);if(o==null)C(`Error: unknown preset "${t.preset}".`),P(` Valid presets: ${ca.map((i)=>i.id).join(", ")}`),process.exit(A.USAGE_ERROR);return ou(o,n)}let r=await zo(e,t.slug??"");if(r==null)C(`Signal "${t.slug}" not found.`),process.exit(A.NOT_FOUND);return fz(r)}function bz(e,t,n){if(e.text!=null)return{definition:t,text:e.text,locale:n};if(e.call!=null)return{definition:t,call_id:x("call_records",e.call),locale:n};return{definition:t,visual_plan_id:x("visual_plans",e.plan??""),last:e.last!=null?Number(e.last):void 0,locale:n}}function Sw(e,t){let n=e.command("signals").description("Signal library and testing");n.command("presets").description("List the ten signal models").option("--locale <locale>","Locale of the texts: pt-BR or en","pt-BR").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=hw(r.locale),s=await b(t().signals.presets({locale:a}));if(o==="json"){v(i?s.map((c)=>O(c,i)):s);return}L(["ID","Name","Kind","Speaker","Live","Severity"],s.map((c)=>({ID:c.id,Name:c.definition.name,Kind:c.definition.kind,Speaker:c.definition.speaker,Live:c.definition.live?"yes":"no",Severity:c.definition.alert?.severity??"—"})))}),n.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(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().signals.list({page:Number(r.page),limit:Number(r.limit),search:r.search,include_archived:r.includeArchived===!0}));if(o==="json"){let s=i?a.items.map((c)=>O(c,i)):a;v(s);return}L(["Slug","Name","Kind","Live","Org default","Usage","Fires 7d","Version","Archived"],a.items.map((s)=>({Slug:s.slug,Name:s.name,Kind:s.kind,Live:s.live?"yes":"no","Org default":s.is_org_default?"yes":"no",Usage:`${s.usage_count.published}/${s.usage_count.draft}`,"Fires 7d":s.fires_last_7_days.reduce((c,d)=>c+d,0),Version:s.version,Archived:s.archived_at!=null?"yes":"no"}))),ee(a)}),n.command("show <slug_or_id>").description("Show one signal (slug or sig_... TypeID) with its usage").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await yw(t(),r);if(a==null)C(`Signal "${r}" not found.`),process.exit(A.NOT_FOUND);if(o==="json"){v(i?O(a,i):a);return}let s=[{title:"Signal",rows:[{label:"ID",value:a.id},{label:"Slug",value:a.slug},{label:"Name",value:a.name},{label:"Question",value:a.question},{label:"Kind",value:a.kind},...a.higher_is!==void 0?[{label:"Higher is",value:a.higher_is}]:[],{label:"Speaker",value:a.speaker},{label:"Scope",value:a.scope?.node_types.join(", ")??"whole call"},{label:"Live",value:a.live?"yes":"no"},{label:"Org default",value:a.is_org_default?"yes":"no"},{label:"Version",value:a.version},{label:"Archived",value:a.archived_at!=null?"yes":"no"}]},{title:"Alert",rows:a.alert==null?[{label:"When",value:"—"}]:[{label:"When",value:hz(a.alert.when)},{label:"Severity",value:a.alert.severity},{label:"Bell",value:a.alert.bell?"yes":"no"},{label:"Attendant hint",value:a.alert.attendant_hint??"—"}]}];if(a.options!==void 0)s.push({title:"Options",rows:a.options.map((c)=>({label:c.key,value:yz(c)}))});if(a.levels!==void 0)s.push({title:"Levels",rows:a.levels.map((c,d)=>({label:String(d+1),value:c}))});if(uz(a))s.push({title:"Usage",rows:[{label:"Published plans",value:a.usage_count.published},{label:"Draft plans",value:a.usage_count.draft},{label:"Fires 7d",value:a.fires_last_7_days.reduce((c,d)=>c+d,0)},{label:"Evaluated calls 7d",value:a.evaluated_calls_last_7_days.reduce((c,d)=>c+d,0)}]});J(s)}),n.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(r)=>{let{format:o}=S(e.opts()),i=t(),a=hw(r.locale),s=[r.file,r.preset,r.slug].filter((y)=>y!=null).length,c=[r.text,r.call,r.plan].filter((y)=>y!=null).length;if(s!==1||c!==1)C("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(r.last!=null&&r.plan==null)C("Error: --last only applies with --plan."),process.exit(A.USAGE_ERROR);let d=await _z(i,r,a),u=bz(r,d,a),m=await b(i.signals.test(u));if(o==="json"){v(m);return}if("calls"in m)m.calls.forEach((y,_)=>{if(_>0)console.log("");console.log(`Call ${y.call_id}`),_w(y)});else if("turns"in m)_w(m);else console.log(`${m.value_label}${m.would_trigger?" <- would trigger":""}`)}),n.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(r)=>{let{format:o}=S(e.opts()),i=t(),a=await bw(r.file),s=vw(a),c=typeof a.is_org_default==="boolean"?a.is_org_default:void 0,d=await b(i.signals.upsertBySlug({...s,...c!==void 0?{is_org_default:c}:{},dry_run:r.dryRun===!0}));if(o==="json"){v(d);return}vz(d.status,d.changed_fields,d.signal.slug,r.dryRun===!0)}),n.command("delete <slug_or_id>").description("Move a signal to the trash (slug or sig_... TypeID)").action(async(r)=>{let{format:o}=S(e.opts()),i=await yw(t(),r);if(i==null)C(`Signal "${r}" not found.`),process.exit(A.NOT_FOUND);let a=await b(t().signals.delete({signal_id:x("signals",i.id)}));if(o==="json"){v(a);return}N(`Signal moved to the trash: ${a.slug}. Restore it from Settings > Archive.`)})}function vz(e,t,n,r){if(e==="created"){N(r?`would create: ${n}`:`created: ${n}`);return}if(e==="unchanged"){P(`unchanged: ${n}`);return}N(r?`would update: ${n} (changed: ${t.join(", ")})`:`updated: ${n} (changed: ${t.join(", ")})`)}async function Ap(e){let t=e==="-"?await Fe():await ww(e,"utf-8"),n=zd.safeParse(JSON.parse(t));if(!n.success){C(`Invalid execution plan in "${e}":`);for(let r of n.error.issues)C(` ✗ ${r.path.join(".")||"(root)"}: ${r.message}`);process.exit(A.GENERAL_ERROR)}return n.data}function er(e){return e!=null&&typeof e==="object"&&!Array.isArray(e)}function Sz(e){if(!er(e)||!Array.isArray(e.nodes)||!Array.isArray(e.edges))return!1;let t=e.viewport;return er(t)&&typeof t.x==="number"&&typeof t.y==="number"&&typeof t.zoom==="number"}async function xz(e){let t=e==="-"?await Fe():await ww(e,"utf-8"),n;try{n=JSON.parse(t)}catch{C(`Invalid JSON in plan export "${e}"`),process.exit(A.GENERAL_ERROR)}let r;if(er(n)&&n.format==="niva-plan-v1")r=n.state;else if(er(n)&&er(n.draft)&&n.draft.editor_state!=null)r=n.draft.editor_state;else if(er(n)&&n.published_editor_state!=null)r=n.published_editor_state;else if(er(n)&&Array.isArray(n.nodes)&&Array.isArray(n.edges))r=n;else C(`Invalid plan export in "${e}"`),process.exit(A.GENERAL_ERROR);if(!Sz(r))C(`Invalid editor state in plan export "${e}"`),process.exit(A.GENERAL_ERROR);return r}function Tp(e){let t=e.severity==="error"?"✗":"⚠",n=e.node_id!=null?` [${e.node_id}]`:"";return` ${t}${n} ${e.message_key}`}var Ez="! 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 xw(e){try{let t=Lc(e),n=lu(t.nodes,t.edges,vt);if(!du(n)){for(let r of n)C(Tp({node_id:r.nodeId,severity:r.severity,message_key:r.messageKey}));return!1}return Et(Ez),!0}catch(t){return C(t instanceof Error?t.message:String(t)),!1}}async function wz(e,t,n,r){if(await b(e.channels.update({channel_id:x("channels",t),visual_plan_id:x("visual_plans",n),reassign:!0})),r!=="json")N(`Channel ${t} assigned to plan`)}async function Cz(e,t,n){if(await b(e.channels.update({channel_id:x("channels",t),visual_plan_id:null})),n!=="json")N(`Channel ${t} unassigned from plan`)}async function Az(e,t,n){let r=x("visual_plans",t),o=await b(e.channels.list({page:1,limit:100})),i=o.items.filter((s)=>s.visual_plan_id===r),a=o.items.filter((s)=>s.visual_plan_id==null);if(n==="json"){v({assigned:i,available:a});return}if(i.length>0)console.log(`
|
|
2338
2338
|
Assigned to this plan:`),L(["ID","Type","Name","Identifier","Active"],i.map((s)=>({ID:s.id,Type:s.channel_type,Name:s.name,Identifier:s.identifier??"—",Active:s.is_active?"yes":"no"})));if(a.length>0)console.log(`
|
|
2339
|
-
Available (unassigned):`),L(["ID","Type","Name","Identifier"],a.map((s)=>({ID:s.id,Type:s.channel_type,Name:s.name,Identifier:s.identifier??"—"})))}function Az(e,t){return{plan_id:x("visual_plans",e),...t.name!=null&&{name:t.name},...t.description!=null&&{description:t.description},...t.recording!==void 0&&{recording_enabled:t.recording},...t.transcription!==void 0&&{transcription_enabled:t.transcription},...t.transcriptionLanguage!=null&&{transcription_language:t.transcriptionLanguage},...t.anonymize!==void 0&&{anonymize_enabled:t.anonymize},...t.speechAnalytics!==void 0&&{speech_analytics_enabled:t.speechAnalytics},...t.sentiment!==void 0&&{sentiment_enabled:t.sentiment},...t.topics!=null&&{topic_detection_topics:t.topics.split(",").map((n)=>n.trim())},...t.intents!=null&&{intent_detection_intents:t.intents.split(",").map((n)=>n.trim())},...t.signalsInherit!==void 0&&{signals_inherit_org:t.signalsInherit}}}async function Tz(e,t,n,r,o,i){let a=t.startsWith("-")?"-":"+",s=t.startsWith("+")||t.startsWith("-")?t.slice(1):t,c=await zo(e,s);if(c==null){o.push(s);return}if(a==="-"){r.delete(c.id);return}if(r.add(c.id),c.live===!0&&n.transcription_type!=="live")i.push(`Signal "${c.name}" runs live, but this plan uses ${n.transcription_type} transcription: it only runs at the end of the call until the plan switches to live transcription.`)}async function Rz(e,t,n){let r=await b(e.visualPlans.getById({plan_id:x("visual_plans",t)})),o=r.signals_inherit_org===!0,i=new Set(o?await Iz(e):r.signal_ids),a=[],s=[];for(let c of n.split(",")){let d=c.trim();if(d==="")continue;await Tz(e,d,r,i,a,s)}if(a.length>0)C(`Unknown signal slug(s): ${a.join(", ")}`),D("List the library with: niva signals list"),process.exit(A.USAGE_ERROR);return{signal_ids:[...i].sort((c,d)=>c.localeCompare(d)),warnings:s,switchedToCustom:o}}async function Iz(e){let t=[],n=1;for(;;){let r=await b(e.signals.list({page:n,limit:100,include_archived:!1}));for(let o of r.items)if(o.is_org_default)t.push(o.id);if(r.page>=r.total_pages)break;n+=1}return t}function Aw(e,t){let n=e.command("plans").description("Manage visual plans");n.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(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().visualPlans.list({page:Number(r.page),limit:Number(r.limit),search:r.search}));if(o==="json"){let s=i?a.items.map((c)=>N(c,i)):a;v(s);return}L(["ID","Name","Status","Created"],a.items.map((s)=>({ID:s.id,Name:s.name,Status:s.published_version_id!=null?"published":"draft",Created:new Date(s.created_at).toLocaleDateString()}))),te(a)}),n.command("show <plan_id>").description("Show plan details with settings").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().visualPlans.getById({plan_id:x("visual_plans",r)}));if(o==="json"){let s=i?N(a,i):a;v(s);return}J([{title:"Plan",rows:[{label:"ID",value:a.id},{label:"Name",value:a.name},{label:"Status",value:a.published_version_id!=null?"published":"draft"},{label:"Created",value:new Date(a.created_at).toLocaleString()},{label:"Updated",value:new Date(a.updated_at).toLocaleString()}]},{title:"Settings",rows:[{label:"Recording",value:a.recording_enabled?"enabled":"disabled"},{label:"Transcription",value:a.transcription_enabled?"enabled":"disabled"},{label:"Language",value:a.transcription_language??"—"},{label:"Anonymize",value:a.anonymize_enabled?"enabled":"disabled"},{label:"Call Summary",value:a.speech_analytics_enabled?"enabled":"disabled"},{label:"Sentiment",value:a.sentiment_enabled?"enabled":"disabled"}]}])}),n.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(r,o)=>{let{format:i}=S(e.opts()),a;if(o.executionPlan!=null){if(a=await Tp(o.executionPlan),!Ew(a))process.exit(1)}let s=await b(t().visualPlans.create({name:r,language:o.language,description:o.description,recording_enabled:o.recording??!1,transcription_enabled:o.transcription??!1,execution_plan:a}));if(i==="json"){v(s);return}O(`Plan created: ${s.id}`)}),n.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(r,o)=>{let{format:i}=S(e.opts()),a=await Tp(o.executionPlan);if(!Ew(a))process.exit(1);let s=await b(t().visualPlans.saveDraft({plan_id:x("visual_plans",r),execution_plan:a,expected_revision:o.expectedRevision!=null?Number(o.expectedRevision):void 0}));if(i==="json"){v(s);return}O(`Draft updated (revision ${s.revision})`)}),n.command("import <plan_id> <file>").description("Import a browser or CLI-exported plan JSON as the draft of an existing destination plan").action(async(r,o)=>{let{format:i}=S(e.opts()),a=await Sz(o),s=await b(t().visualPlans.importDraft({plan_id:x("visual_plans",r),editor_state:a}));if(i==="json"){v(s);return}O(`Draft imported (revision ${s.revision})`)}),n.command("configure <plan_id>").description("Configure plan settings, metadata, and DIDs").option("--name <name>","Plan name").option("--description <text>","Plan description").option("--recording","Enable recording").option("--no-recording","Disable recording").option("--transcription","Enable transcription").option("--no-transcription","Disable transcription").option("--transcription-language <code>","Transcription language").option("--anonymize","Enable anonymization").option("--no-anonymize","Disable anonymization").option("--speech-analytics","Enable call summary and key points").option("--no-speech-analytics","Disable call summary and key points").option("--sentiment","Enable sentiment analysis").option("--no-sentiment","Disable sentiment analysis").option("--topics <list>","Legacy topic hints (comma-separated)").option("--intents <list>","Legacy intent hints (comma-separated)").option("--signals <list>","Link signals (comma-separated: +slug to add, -slug to remove, bare slug to add)").option("--signals-inherit","Follow the organization's signal library").option("--no-signals-inherit","Own the plan's signal list").option("--assign-did <id>","Assign a phone number to this plan").option("--unassign-did <id>","Unassign a phone number from this plan").option("--list-dids","List DIDs assigned to this plan").action(async(r,o)=>{let{format:i}=S(e.opts()),a=t();if(o.assignDid!=null)await Ez(a,o.assignDid,r,i);if(o.unassignDid!=null)await wz(a,o.unassignDid,i);if(o.listDids===!0){await Cz(a,r,i);return}let s=Az(r,o);if(o.signals!=null){if(o.signalsInherit===!0)C("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:c,warnings:d,switchedToCustom:u}=await Rz(a,r,o.signals);if(s.signal_ids=c,u)s.signals_inherit_org=!1,Et("This plan now chooses its own signals instead of following the organization.");for(let m of d)Et(m)}if(Object.keys(s).length>1){let c=await b(a.visualPlans.update(s));if(i==="json"){v(c);return}O("Plan configuration updated")}}),n.command("scaffold").description("Output a minimal valid execution plan JSON template").action(()=>{v({version:1,startNodeId:"start",nodes:{start:{type:"start",label:"Start",varName:"start",config:{}},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:{voice:"greeting",chat:"greeting"},greeting:{next:"end"}}})}),n.command("delete <plan_id>").description("Delete a visual plan").action(async(r)=>{let{format:o}=S(e.opts());if(await b(t().visualPlans.delete({plan_id:x("visual_plans",r)})),o==="json"){v({success:!0});return}O("Plan deleted")}),n.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(r,o)=>{let{format:i}=S(e.opts());if(o.file!=null){let s=await Tp(o.file),c=await b(t().visualPlans.validate({execution_plan:s}));if(i==="json"){v(c);return}ww(c),process.exit(c.valid?0:1)}if(r==null)C("Provide a plan ID or --file <path>"),process.exit(2);let a=await b(t().visualPlans.validate({plan_id:x("visual_plans",r)}));if(i==="json"){v(a);return}ww(a),process.exit(a.valid?0:1)}),n.command("test <plan_id>").description("Start a test call for a plan").requiredOption("--extension <ext>","SIP extension to call").action(async(r,o)=>{let{format:i}=S(e.opts()),a=await b(t().testCall.start({planId:x("visual_plans",r),extension:o.extension}));if(i==="json"){v(a);return}O(`Test call started: uuid=${a.uuid}`),D(`Test ID: ${a.testId}`),D("Use 'niva calls follow <uuid>' to watch the call")}),n.command("publish <plan_id>").description("Publish the current draft").option("--notes <text>","Publication notes").action(async(r,o)=>{let{format:i}=S(e.opts()),a=await b(t().visualPlans.publish({plan_id:x("visual_plans",r),notes:o.notes}));if(i==="json"){v(a);return}O(`Plan published (version ${a.version})`)}),n.command("versions <plan_id>").description("List version history").action(async(r)=>{let{format:o}=S(e.opts()),i=await b(t().visualPlans.listVersions({plan_id:x("visual_plans",r)}));if(o==="json"){v(i);return}L(["Version","Status","Published By","Published At","Notes"],i.items.map((a)=>({Version:a.version,Status:a.status,"Published By":a.last_edited_by_name??"—","Published At":a.published_at!=null?new Date(a.published_at).toLocaleString():"—",Notes:a.notes??"—"})))}),n.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(r,o)=>{if(o.executionPlan===!0){let s=(await b(t().visualPlans.listVersions({plan_id:x("visual_plans",r)}))).items.find((c)=>c.status==="published"&&c.execution_plan!=null);if(s!=null)v(s.execution_plan);else C("No published version with execution plan found"),process.exit(1);return}let i=await b(t().visualPlans.getById({plan_id:x("visual_plans",r)}));v(i)})}function ww(e){if(e.valid){O("✓ Plan is valid");return}let t=e.issues.filter((r)=>r.severity==="error"),n=e.issues.filter((r)=>r.severity==="warning");if(t.length>0){C(`✗ ${t.length} error(s):`);for(let r of t)C(Rp(r))}if(n.length>0){D(` ${n.length} warning(s):`);for(let r of n)D(Rp(r))}}function Tw({live:e,day:t}){return[{title:"Live",rows:[{label:"Waiting",value:e.waiting},{label:"Longest wait (s)",value:e.longest_wait_s},{label:"Offered",value:e.offered},{label:"In service",value:e.in_service},{label:"Members logged in",value:e.members_logged_in},{label:"Available members",value:e.available_members}]},{title:"Day",rows:[{label:"Offered",value:t.offered},{label:"Answered",value:t.answered},{label:"Answered in SLA",value:t.answered_in_sla},{label:"Abandoned",value:t.abandoned},{label:"Short abandoned",value:t.short_abandoned},{label:"Timeout",value:t.timeout},{label:"SLA (%)",value:t.sla_pct},{label:"Abandon (%)",value:t.abandon_pct},{label:"Average wait (s)",value:t.avg_wait_s},{label:"Average talk (s)",value:t.avg_talk_s}]}]}function Rw(e,t){let n=e.command("queues").description("Inspect voice queues and how they are doing (requires the queues module)");n.command("list").description("List queues with the callers waiting, the longest wait and the members available").option("--search <term>","Search by queue name").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().queues.list({page:Number(r.page),limit:Number(r.limit),search:r.search}));if(o==="json"){v(i?a.items.map((s)=>N(s,i)):a);return}L(["ID","Name","Strategy","Waiting","Longest wait (s)","Available"],a.items.map((s)=>({ID:s.id,Name:s.name,Strategy:s.strategy,Waiting:s.live.waiting,"Longest wait (s)":s.live.longest_wait_s,Available:s.live.available}))),te(a)}),n.command("show <queue_id>").description("Show one queue: settings, members with priority and state, live state and the day").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().queues.getById({queue_id:x("queues",r)}));if(o==="json"){v(i?N(a,i):a);return}J([{title:"Queue",rows:[{label:"ID",value:a.id},{label:"Name",value:a.name},{label:"Channels",value:a.channels.join(", ")},{label:"Strategy",value:a.strategy},{label:"Music",value:a.moh_audio_id??"house music"}]},{title:"Limits",rows:[{label:"Max wait (s)",value:a.max_wait_s},{label:"Max size",value:a.max_size},{label:"Offer timeout (s)",value:a.offer_timeout_s},{label:"Wrap-up (s)",value:a.wrap_s},{label:"Max refusals",value:a.max_refusals},{label:"SLA threshold (s)",value:a.sla_threshold_s},{label:"SLA target (%)",value:a.sla_target_pct},{label:"Short abandon (s)",value:a.short_abandon_s}]},...Tw(a)]),console.log(""),L(["Attendant","Name","Priority","Status","Since"],a.members.map((s)=>({Attendant:s.attendant.id,Name:s.attendant.user.name,Priority:s.priority,Status:s.attendant.status,Since:Me(s.attendant.status_since)})))}),n.command("stats <queue_id>").description("A queue's live state and its day numbers (since the organization's local midnight)").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().queues.stats({queue_id:x("queues",r)}));if(o==="json"){v(i?N(a,i):a);return}J(Tw(a))})}var Nz="···";function Oz(e){return e===""?"—":`${Nz}${e}`}function Iw(e,t){e.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(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().secrets.list({page:Number(r.page),limit:Number(r.limit),search:r.search}));if(o==="json"){let s=i?a.items.map((c)=>N(c,i)):a;v(s);return}L(["ID","Name","Description","Value","Published","Draft","Updated"],a.items.map((s)=>({ID:s.id,Name:s.name,Description:s.description??"—",Value:Oz(s.value_suffix),Published:s.usage_count.published,Draft:s.usage_count.draft,Updated:new Date(s.updated_at).toLocaleString()}))),te(a)})}var Ie=on(jt(),1);var kz=[{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 bn(e){if(e<1024)return`${e} B`;if(e<1048576)return`${(e/1024).toFixed(1)} KB`;if(e<1073741824)return`${(e/1048576).toFixed(1)} MB`;return`${(e/1073741824).toFixed(1)} GB`}function Dz(e){if(e==="critical")return Ie.default.red(e.toUpperCase());if(e==="warning")return Ie.default.yellow(e.toUpperCase());return Ie.default.green(e.toUpperCase())}function Pz(e){if(e>0)return"+";if(e<0)return"-";return""}function $z(e){if(e===void 0)return"not available";return e.bytes==null?"not measured":bn(e.bytes)}function Nw(e){if(e?.bytesPerDay==null)return"-";return`${Pz(e.bytesPerDay)}${bn(Math.abs(e.bytesPerDay))}/day`}function Mz(e){if(e?.fileCount==null)return"-";return`${e.fileCount} files`}function Lz(e){switch(e){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 zz(e){if(e==="webhook")return"webhook";if(e==="audit")return"audit";if(e==="other")return null;return"call"}function Fz(e,t){let n=zz(t);if(n==null)return"-";let r=e.cleanups.find((o)=>o.name===n);if(r==null)return"no data";if(!r.ok)return Ie.default.red("failed");return r.backlog==null?"not reported":`${r.backlog} pending`}function Uz(e){if(e.collecting)return`${Ie.default.yellow("Collecting")} - no sample yet, categories are not measured.`;if(e.daysUntilFull!=null)return`Full in ~${e.daysUntilFull} days at the current net rate.`;if(e.stable)return"Stable - no net growth since the last samples.";return"Collecting - not enough history for a projection yet."}function jz(e){let t=Math.round(e.disk.usagePercent);if(console.log(`
|
|
2340
|
-
${
|
|
2341
|
-
${
|
|
2342
|
-
${
|
|
2343
|
-
${
|
|
2344
|
-
${Ie.default.bold("Thresholds")}`),console.log(` Warning: ${e.thresholds.warning}%`),console.log(` Critical: ${e.thresholds.critical}%`)}function Ow(e,t){e.command("storage").description("Storage observability and cache stats").command("usage").description("Show storage usage breakdown").action(async()=>{let{format:r}=S(e.opts()),o=await b(t().dashboard.storageUsage({}));if(r==="json"){v(o);return}jz(o),Vz(o),qz(o),Bz(o),Hz(o),console.log()})}function kw(e,t){let n=e.command("tenants").description("Manage tenants");n.command("list").description("List tenants").action(()=>Vt()),n.command("create").description("Create a tenant").action(()=>Vt())}function Dw(e,t){let n=e.command("tts").description("Text-to-speech resources (to synthesize audio, see: niva audio-files generate-tts)");n.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(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().tts.listVoices({language:r.language,model:r.model}));if(o==="json"){let s=i?a.map((c)=>N(c,i)):a;v(s);return}L(["ID","Name","Gender","Languages","Model"],a.map((s)=>({ID:s.id,Name:s.name,Gender:s.gender??"-",Languages:s.languages.join(", "),Model:s.model})))}),n.command("models").description("List available TTS models").action(async()=>{let{format:r,fields:o}=S(e.opts()),i=await b(t().tts.listModels());if(r==="json"){let a=o?i.map((s)=>N(s,o)):i;v(a);return}L(["ID","Name","Provider"],i.map((a)=>({ID:a.id,Name:a.name,Provider:a.provider})))}),n.command("languages").description("List available TTS languages").action(async()=>{let{format:r}=S(e.opts()),o=await b(t().tts.listLanguages());if(r==="json"){v(o);return}L(["Language"],o.map((i)=>({Language:i})))})}function Wz(e){return e.fields.map((t)=>`${t.name}${t.required?"":"?"}${t.nullable?"|null":""}`).join(", ")}function Pw(e,t){e.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:r,fields:o}=S(e.opts()),i=await b(t().webhooks.events.list());if(r==="json"){v(o?i.map((a)=>N(a,o)):i);return}L(["Event","Module","Fields"],i.map((a)=>({Event:a.event,Module:a.required_module??"core",Fields:Wz(a)})))})}function $w(e,t,n){let r=e.command("ws").description("WebSocket chat — connect to a published plan");r.command("chat <plan_id>").description("Start an interactive WebSocket chat session with a published plan").action(async(o)=>{let i=Cn(e.opts()),a=n();D("Creating WebSocket session...");let s=async()=>b(t().ws.createSession({planId:x("visual_plans",o)})),c=await s();if(i==="json"){v(c);return}O(`Session created: ${c.sessionId}`),await Ca(hn(a.url,c.wsUrl),async()=>hn(a.url,(await s()).wsUrl))}),r.command("session <plan_id>").description("Create a WebSocket session (returns sessionId + wsUrl)").action(async(o)=>{let i=Cn(e.opts()),a=await b(t().ws.createSession({planId:x("visual_plans",o)})),s=n(),c=hn(s.url,a.wsUrl);if(i==="json"){v({...a,ws_url:c});return}O(`Session: ${a.sessionId}`),console.log(` WebSocket URL: ${c}`),console.log(` Connect with: websocat ${c}`)})}function Mw(e,t,n,r){sE(e),lx(e,n,r),mw(e),BE(e),Cm(e,t),ux(e,t),h_(e,t),R_(e,t),gx(e,t,n),hw(e,t),Aw(e,t),Rw(e,t),uw(e,t),y_(e,t),vE(e,t),xE(e,t),wE(e,t),AE(e,t),ow(e,t),SE(e,t),Sx(e,t),Ox(e,t,n),bE(e,t),LE(e,t),VE(e,t),Iw(e,t),xw(e,t),Ow(e,t),kw(e,t),Dw(e,t),$w(e,t,n),aE(e,t,n),Pw(e,t),nw(e)}function Gz(e){try{let{hostname:t}=new URL(e);return t.endsWith(".orb.local")||process.env.NIVA_INSECURE==="true"}catch{return!1}}function zw(e){let t=[];for(let n=e;n.parent!=null;n=n.parent)t.unshift(n.name());return t.join(" ")}var Ip;function Fw(e){Ip=e===""?void 0:e}function Lw(){return Ip==null?{}:{[vo]:Ip}}class Uw extends Error{constructor(){super("Your session has expired. Run 'niva login' to authenticate again.")}}function Zz(e){let t=e.fetchImpl??fetch,n=async()=>{try{return await e.refresh()}catch(r){if(r instanceof Ke)throw new Uw;throw r}};return async(r)=>{let o=e.getSession();if(va(o))o=await n();let i=new Request(r);i.headers.set("authorization",`Bearer ${o.access_token}`);let a=await t(i);if(a.status===401){o=await n();let s=new Request(r);s.headers.set("authorization",`Bearer ${o.access_token}`),a=await t(s)}return a}}function jw(e,t,n){if(Gz(e))process.env.NODE_TLS_REJECT_UNAUTHORIZED="0";if(t.kind!=="oauth"){let i=new Hn({url:new URL("/api/rpc",e).href,headers:()=>({...Lw(),...t.kind==="api-key"?{"X-API-Key":t.apiKey}:{}})});return Bn(i)}let r=t.session,o=new Hn({url:new URL("/api/rpc",e).href,headers:Lw,fetch:Zz({getSession:()=>r,refresh:async()=>(r=await Sa(n,r),wr(n,r),r)})});return Bn(o)}import{readFileSync as Yz}from"node:fs";var Jz=1500,Xz="/cli/compatibilidade",Na=null;function Qz(){if(Na!=null)return Na;let e='[{"niva_min":"2.0.0","niva_max":null,"dist_tag":"niva-2.0"}]',t='{"min":"2.0.0","max":null}',n=null;if(typeof t==="string"&&typeof e==="string"){let r=JSON.parse(t),o=JSON.parse(e);n=Vw(r,o)}else{let r=JSON.parse(e2()),o=se(r)?r.supported_niva:void 0,i=se(r)?r.compat_table:void 0;n=Vw(o,i)}if(n==null)throw Error("Invalid apps/cli/compat.json, fix the compat table");return Na=n,Na}function Vw(e,t){if(!se(e)||!Array.isArray(t))return null;let n=X(e.min);if(n==null)return null;let r=X(e.max)??null,o=[];for(let i of Ye(t)){let a=X(i.niva_min),s=X(i.dist_tag);if(a==null||s==null)return null;o.push({niva_min:a,niva_max:X(i.niva_max)??null,dist_tag:s})}return{supported_niva:{min:n,max:r},compat_table:o}}function e2(){return Yz(new URL("../../compat.json",import.meta.url),"utf-8")}function Np(e){let n=(e.split("-")[0]?.split("+")[0]??"").split(".");if(n.length!==3)return null;let r=n.map((o)=>Number.parseInt(o,10));if(r.some((o)=>!Number.isFinite(o)||o<0))return null;return[r[0],r[1],r[2]]}function Oa(e,t){let n=Np(e),r=Np(t);if(n===null||r===null)return 0;for(let o=0;o<3;o++)if(n[o]!==r[o])return n[o]-r[o];return 0}function t2(e,t){let{min:n,max:r}=t.supported_niva;if(Oa(e,n)<0)return!1;if(r!=null&&Oa(e,r)>0)return!1;return!0}function n2(e,t){for(let n of t.compat_table){if(Oa(e,n.niva_min)<0)continue;if(n.niva_max!=null&&Oa(e,n.niva_max)>0)continue;return n.dist_tag}return null}function r2(e,t,n){let{min:r,max:o}=n.supported_niva,i=o==null?`>= ${r}`:`>= ${r} <= ${o}`,a=n2(e,n),s=a==null?`See ${Xz}`:`For the compatible release: npx @sippulse/niva@${a} <command>`;return`warning: this CLI (${zr()}) supports NIVA ${i}; ${t} reports ${e}. Some commands may not exist. ${s}`}async function o2(e,t=fetch){let n=new AbortController,r=setTimeout(()=>n.abort(),Jz);try{let o=await t(new URL("/api/version",e).href,{signal:n.signal,headers:{accept:"application/json"}});if(!o.ok)return null;let i=await o.json();if(i===null||typeof i!=="object"||!("niva_version"in i))return null;let a=i.niva_version;if(typeof a!=="string"||Np(a)===null)return null;return a}catch{return null}finally{clearTimeout(r)}}var i2=null;async function Kw(e,t={}){if(!e)return;let n=t.config??Qz(),r=await o2(e,t.fetchImpl);if(r===null)return;if(i2=r,t2(r,n))return;console.error(r2(r,e,n))}import{chmodSync as Fse,mkdirSync as Use,readFileSync as a2,writeFileSync as jse}from"node:fs";import{homedir as s2}from"node:os";import{join as Hw}from"node:path";var c2=Hw(s2(),".niva"),l2=Hw(c2,"config.json"),qw={url:"http://localhost:3000",apiKey:""};function Bw(e,t){let n=e[t];return typeof n==="string"?n:void 0}function Op(){try{let e=JSON.parse(a2(l2,"utf-8"));return se(e)?e:{}}catch{return{}}}function Ww(){return Op()}function Gw(e){if(e.flagApiKey!=null&&e.flagApiKey!=="")return{kind:"api-key",apiKey:e.flagApiKey};if(e.envApiKey!=null&&e.envApiKey!=="")return{kind:"api-key",apiKey:e.envApiKey};if(e.session!=null)return{kind:"oauth",session:e.session};if(e.fileApiKey!=null&&e.fileApiKey!=="")return{kind:"api-key",apiKey:e.fileApiKey};return{kind:"none"}}function d2(e){let t=se(e)?{...e}:void 0;if(t==null)return!1;let n=t.scopes;return typeof t.access_token==="string"&&typeof t.refresh_token==="string"&&typeof t.expires_at==="number"&&typeof t.org_id==="string"&&Array.isArray(n)&&n.every((r)=>typeof r==="string")}function u2(){let e=Op().auth;return se(e)?e:{}}function Zw(){let e={};for(let[t,n]of Object.entries(u2()))if(d2(n))e[t]=n;return e}function Yw(e){let t=Op();return{url:e.url??process.env.NIVA_URL??Bw(t,"url")??qw.url,apiKey:e.apiKey??process.env.NIVA_API_KEY??Bw(t,"apiKey")??qw.apiKey}}var p2="table",m2="";function Jw(e){p2=e}function Xw(e){m2=e}var f2=new Set(["json","table","plain"]);function g2(e){return f2.has(e)}function h2(){return process.stdout.isTTY===!0&&process.env.NO_COLOR==null}function Qw(e){if(e.output!=null)return g2(e.output)?e.output:"table";if(e.json===!0)return"json";return h2()?"table":"json"}function eC(){return"0.5.1"}var Fo=new mm("niva").description("NIVA CLI \u2014 manage your IVR platform").version(eC()).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",(e,t)=>{Fw(zw(t));let n=Fo.opts(),r=Qw({json:n.json===!0,output:typeof n.output==="string"?n.output:void 0});Jw(r)}).hook("preAction",async()=>{await Kw($a().url)}),ka;function $a(){if(ka!=null)return ka;let e=Fo.opts();return ka=Yw({url:typeof e.url==="string"?e.url:void 0,apiKey:typeof e.apiKey==="string"?e.apiKey:void 0}),ka}var Da;function tC(){if(Da!=null)return Da;let e=$a(),t=Ww(),n=Fo.opts().apiKey;return Da=Gw({flagApiKey:typeof n==="string"?n:void 0,envApiKey:process.env.NIVA_API_KEY,fileApiKey:typeof t.apiKey==="string"?t.apiKey:void 0,session:Zw()[Ka(e.url)]}),Da}var Pa;function y2(){if(Pa!=null)return Pa;let e=$a();Xw(e.url);let t=tC();if(t.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 Pa=jw(e.url,t,Ka(e.url)),Pa}Mw(Fo,y2,$a,tC);Fo.parseAsync().catch((e)=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});
|
|
2339
|
+
Available (unassigned):`),L(["ID","Type","Name","Identifier"],a.map((s)=>({ID:s.id,Type:s.channel_type,Name:s.name,Identifier:s.identifier??"—"})))}function Tz(e,t){return{plan_id:x("visual_plans",e),...t.name!=null&&{name:t.name},...t.description!=null&&{description:t.description},...t.recording!==void 0&&{recording_enabled:t.recording},...t.transcription!==void 0&&{transcription_enabled:t.transcription},...t.transcriptionLanguage!=null&&{transcription_language:t.transcriptionLanguage},...t.anonymize!==void 0&&{anonymize_enabled:t.anonymize},...t.speechAnalytics!==void 0&&{speech_analytics_enabled:t.speechAnalytics},...t.sentiment!==void 0&&{sentiment_enabled:t.sentiment},...t.topics!=null&&{topic_detection_topics:t.topics.split(",").map((n)=>n.trim())},...t.intents!=null&&{intent_detection_intents:t.intents.split(",").map((n)=>n.trim())},...t.signalsInherit!==void 0&&{signals_inherit_org:t.signalsInherit}}}async function Rz(e,t,n,r,o,i){let a=t.startsWith("-")?"-":"+",s=t.startsWith("+")||t.startsWith("-")?t.slice(1):t,c=await zo(e,s);if(c==null){o.push(s);return}if(a==="-"){r.delete(c.id);return}if(r.add(c.id),c.live===!0&&n.transcription_type!=="live")i.push(`Signal "${c.name}" runs live, but this plan uses ${n.transcription_type} transcription: it only runs at the end of the call until the plan switches to live transcription.`)}async function Iz(e,t,n){let r=await b(e.visualPlans.getById({plan_id:x("visual_plans",t)})),o=r.signals_inherit_org===!0,i=new Set(o?await Oz(e):r.signal_ids),a=[],s=[];for(let c of n.split(",")){let d=c.trim();if(d==="")continue;await Rz(e,d,r,i,a,s)}if(a.length>0)C(`Unknown signal slug(s): ${a.join(", ")}`),P("List the library with: niva signals list"),process.exit(A.USAGE_ERROR);return{signal_ids:[...i].sort((c,d)=>c.localeCompare(d)),warnings:s,switchedToCustom:o}}async function Oz(e){let t=[],n=1;for(;;){let r=await b(e.signals.list({page:n,limit:100,include_archived:!1}));for(let o of r.items)if(o.is_org_default)t.push(o.id);if(r.page>=r.total_pages)break;n+=1}return t}function Cw(e,t){let n=e.command("plans").description("Manage visual plans");n.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(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().visualPlans.list({page:Number(r.page),limit:Number(r.limit),search:r.search}));if(o==="json"){let s=i?a.items.map((c)=>O(c,i)):a;v(s);return}L(["ID","Name","Status","Created"],a.items.map((s)=>({ID:s.id,Name:s.name,Status:s.published_version_id!=null?"published":"draft",Created:new Date(s.created_at).toLocaleDateString()}))),ee(a)}),n.command("show <plan_id>").description("Show plan details with settings").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().visualPlans.getById({plan_id:x("visual_plans",r)}));if(o==="json"){let s=i?O(a,i):a;v(s);return}J([{title:"Plan",rows:[{label:"ID",value:a.id},{label:"Name",value:a.name},{label:"Status",value:a.published_version_id!=null?"published":"draft"},{label:"Created",value:new Date(a.created_at).toLocaleString()},{label:"Updated",value:new Date(a.updated_at).toLocaleString()}]},{title:"Settings",rows:[{label:"Recording",value:a.recording_enabled?"enabled":"disabled"},{label:"Transcription",value:a.transcription_enabled?"enabled":"disabled"},{label:"Language",value:a.transcription_language??"—"},{label:"Anonymize",value:a.anonymize_enabled?"enabled":"disabled"},{label:"Call Summary",value:a.speech_analytics_enabled?"enabled":"disabled"},{label:"Sentiment",value:a.sentiment_enabled?"enabled":"disabled"}]}])}),n.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(r,o)=>{let{format:i}=S(e.opts()),a;if(o.executionPlan!=null){if(a=await Ap(o.executionPlan),!xw(a))process.exit(1)}let s=await b(t().visualPlans.create({name:r,language:o.language,description:o.description,recording_enabled:o.recording??!1,transcription_enabled:o.transcription??!1,execution_plan:a}));if(i==="json"){v(s);return}N(`Plan created: ${s.id}`)}),n.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(r,o)=>{let{format:i}=S(e.opts()),a=await Ap(o.executionPlan);if(!xw(a))process.exit(1);let s=await b(t().visualPlans.saveDraft({plan_id:x("visual_plans",r),execution_plan:a,expected_revision:o.expectedRevision!=null?Number(o.expectedRevision):void 0}));if(i==="json"){v(s);return}N(`Draft updated (revision ${s.revision})`)}),n.command("import <plan_id> <file>").description("Import a browser or CLI-exported plan JSON as the draft of an existing destination plan").action(async(r,o)=>{let{format:i}=S(e.opts()),a=await xz(o),s=await b(t().visualPlans.importDraft({plan_id:x("visual_plans",r),editor_state:a}));if(i==="json"){v(s);return}N(`Draft imported (revision ${s.revision})`)}),n.command("configure <plan_id>").description("Configure plan settings, metadata, and DIDs").option("--name <name>","Plan name").option("--description <text>","Plan description").option("--recording","Enable recording").option("--no-recording","Disable recording").option("--transcription","Enable transcription").option("--no-transcription","Disable transcription").option("--transcription-language <code>","Transcription language").option("--anonymize","Enable anonymization").option("--no-anonymize","Disable anonymization").option("--speech-analytics","Enable call summary and key points").option("--no-speech-analytics","Disable call summary and key points").option("--sentiment","Enable sentiment analysis").option("--no-sentiment","Disable sentiment analysis").option("--topics <list>","Legacy topic hints (comma-separated)").option("--intents <list>","Legacy intent hints (comma-separated)").option("--signals <list>","Link signals (comma-separated: +slug to add, -slug to remove, bare slug to add)").option("--signals-inherit","Follow the organization's signal library").option("--no-signals-inherit","Own the plan's signal list").option("--assign-did <id>","Assign a phone number to this plan").option("--unassign-did <id>","Unassign a phone number from this plan").option("--list-dids","List DIDs assigned to this plan").action(async(r,o)=>{let{format:i}=S(e.opts()),a=t();if(o.assignDid!=null)await wz(a,o.assignDid,r,i);if(o.unassignDid!=null)await Cz(a,o.unassignDid,i);if(o.listDids===!0){await Az(a,r,i);return}let s=Tz(r,o);if(o.signals!=null){if(o.signalsInherit===!0)C("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:c,warnings:d,switchedToCustom:u}=await Iz(a,r,o.signals);if(s.signal_ids=c,u)s.signals_inherit_org=!1,Et("This plan now chooses its own signals instead of following the organization.");for(let m of d)Et(m)}if(Object.keys(s).length>1){let c=await b(a.visualPlans.update(s));if(i==="json"){v(c);return}N("Plan configuration updated")}}),n.command("scaffold").description("Output a minimal valid execution plan JSON template").action(()=>{v({version:1,startNodeId:"start",nodes:{start:{type:"start",label:"Start",varName:"start",config:{}},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:{voice:"greeting",chat:"greeting"},greeting:{next:"end"}}})}),n.command("delete <plan_id>").description("Delete a visual plan").action(async(r)=>{let{format:o}=S(e.opts());if(await b(t().visualPlans.delete({plan_id:x("visual_plans",r)})),o==="json"){v({success:!0});return}N("Plan deleted")}),n.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(r,o)=>{let{format:i}=S(e.opts());if(o.file!=null){let s=await Ap(o.file),c=await b(t().visualPlans.validate({execution_plan:s}));if(i==="json"){v(c);return}Ew(c),process.exit(c.valid?0:1)}if(r==null)C("Provide a plan ID or --file <path>"),process.exit(2);let a=await b(t().visualPlans.validate({plan_id:x("visual_plans",r)}));if(i==="json"){v(a);return}Ew(a),process.exit(a.valid?0:1)}),n.command("test <plan_id>").description("Start a test call for a plan").requiredOption("--extension <ext>","SIP extension to call").action(async(r,o)=>{let{format:i}=S(e.opts()),a=await b(t().testCall.start({planId:x("visual_plans",r),extension:o.extension}));if(i==="json"){v(a);return}N(`Test call started: uuid=${a.uuid}`),P(`Test ID: ${a.testId}`),P("Use 'niva calls follow <uuid>' to watch the call")}),n.command("publish <plan_id>").description("Publish the current draft").option("--notes <text>","Publication notes").action(async(r,o)=>{let{format:i}=S(e.opts()),a=await b(t().visualPlans.publish({plan_id:x("visual_plans",r),notes:o.notes}));if(i==="json"){v(a);return}N(`Plan published (version ${a.version})`)}),n.command("versions <plan_id>").description("List version history").action(async(r)=>{let{format:o}=S(e.opts()),i=await b(t().visualPlans.listVersions({plan_id:x("visual_plans",r)}));if(o==="json"){v(i);return}L(["Version","Status","Published By","Published At","Notes"],i.items.map((a)=>({Version:a.version,Status:a.status,"Published By":a.last_edited_by_name??"—","Published At":a.published_at!=null?new Date(a.published_at).toLocaleString():"—",Notes:a.notes??"—"})))}),n.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(r,o)=>{if(o.executionPlan===!0){let s=(await b(t().visualPlans.listVersions({plan_id:x("visual_plans",r)}))).items.find((c)=>c.status==="published"&&c.execution_plan!=null);if(s!=null)v(s.execution_plan);else C("No published version with execution plan found"),process.exit(1);return}let i=await b(t().visualPlans.getById({plan_id:x("visual_plans",r)}));v(i)})}function Ew(e){if(e.valid){N("✓ Plan is valid");return}let t=e.issues.filter((r)=>r.severity==="error"),n=e.issues.filter((r)=>r.severity==="warning");if(t.length>0){C(`✗ ${t.length} error(s):`);for(let r of t)C(Tp(r))}if(n.length>0){P(` ${n.length} warning(s):`);for(let r of n)P(Tp(r))}}function Aw({live:e,day:t}){return[{title:"Live",rows:[{label:"Waiting",value:e.waiting},{label:"Longest wait (s)",value:e.longest_wait_s},{label:"Offered",value:e.offered},{label:"In service",value:e.in_service},{label:"Members logged in",value:e.members_logged_in},{label:"Available members",value:e.available_members}]},{title:"Day",rows:[{label:"Offered",value:t.offered},{label:"Answered",value:t.answered},{label:"Answered in SLA",value:t.answered_in_sla},{label:"Abandoned",value:t.abandoned},{label:"Short abandoned",value:t.short_abandoned},{label:"Timeout",value:t.timeout},{label:"SLA (%)",value:t.sla_pct},{label:"Abandon (%)",value:t.abandon_pct},{label:"Average wait (s)",value:t.avg_wait_s},{label:"Average talk (s)",value:t.avg_talk_s}]}]}function Tw(e,t){let n=e.command("queues").description("Inspect voice queues and how they are doing (requires the queues module)");n.command("list").description("List queues with the callers waiting, the longest wait and the members available").option("--search <term>","Search by queue name").option("--page <n>","Page number","1").option("--limit <n>","Items per page","20").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().queues.list({page:Number(r.page),limit:Number(r.limit),search:r.search}));if(o==="json"){v(i?a.items.map((s)=>O(s,i)):a);return}L(["ID","Name","Strategy","Waiting","Longest wait (s)","Available"],a.items.map((s)=>({ID:s.id,Name:s.name,Strategy:s.strategy,Waiting:s.live.waiting,"Longest wait (s)":s.live.longest_wait_s,Available:s.live.available}))),ee(a)}),n.command("show <queue_id>").description("Show one queue: settings, members with priority and state, live state and the day").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().queues.getById({queue_id:x("queues",r)}));if(o==="json"){v(i?O(a,i):a);return}J([{title:"Queue",rows:[{label:"ID",value:a.id},{label:"Name",value:a.name},{label:"Channels",value:a.channels.join(", ")},{label:"Strategy",value:a.strategy},{label:"Music",value:a.moh_audio_id??"house music"}]},{title:"Limits",rows:[{label:"Max wait (s)",value:a.max_wait_s},{label:"Max size",value:a.max_size},{label:"Offer timeout (s)",value:a.offer_timeout_s},{label:"Wrap-up (s)",value:a.wrap_s},{label:"Max refusals",value:a.max_refusals},{label:"SLA threshold (s)",value:a.sla_threshold_s},{label:"SLA target (%)",value:a.sla_target_pct},{label:"Short abandon (s)",value:a.short_abandon_s}]},...Aw(a)]),console.log(""),L(["Attendant","Name","Priority","Status","Since"],a.members.map((s)=>({Attendant:s.attendant.id,Name:s.attendant.user.name,Priority:s.priority,Status:s.attendant.status,Since:Me(s.attendant.status_since)})))}),n.command("stats <queue_id>").description("A queue's live state and its day numbers (since the organization's local midnight)").action(async(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().queues.stats({queue_id:x("queues",r)}));if(o==="json"){v(i?O(a,i):a);return}J(Aw(a))})}var Nz="···";function kz(e){return e===""?"—":`${Nz}${e}`}function Rw(e,t){e.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(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().secrets.list({page:Number(r.page),limit:Number(r.limit),search:r.search}));if(o==="json"){let s=i?a.items.map((c)=>O(c,i)):a;v(s);return}L(["ID","Name","Description","Value","Published","Draft","Updated"],a.items.map((s)=>({ID:s.id,Name:s.name,Description:s.description??"—",Value:kz(s.value_suffix),Published:s.usage_count.published,Draft:s.usage_count.draft,Updated:new Date(s.updated_at).toLocaleString()}))),ee(a)})}var Oe=on(jt(),1);var Dz=[{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 bn(e){if(e<1024)return`${e} B`;if(e<1048576)return`${(e/1024).toFixed(1)} KB`;if(e<1073741824)return`${(e/1048576).toFixed(1)} MB`;return`${(e/1073741824).toFixed(1)} GB`}function Pz(e){if(e==="critical")return Oe.default.red(e.toUpperCase());if(e==="warning")return Oe.default.yellow(e.toUpperCase());return Oe.default.green(e.toUpperCase())}function $z(e){if(e>0)return"+";if(e<0)return"-";return""}function Mz(e){if(e===void 0)return"not available";return e.bytes==null?"not measured":bn(e.bytes)}function Iw(e){if(e?.bytesPerDay==null)return"-";return`${$z(e.bytesPerDay)}${bn(Math.abs(e.bytesPerDay))}/day`}function Lz(e){if(e?.fileCount==null)return"-";return`${e.fileCount} files`}function zz(e){switch(e){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 Fz(e){if(e==="webhook")return"webhook";if(e==="audit")return"audit";if(e==="other")return null;return"call"}function Uz(e,t){let n=Fz(t);if(n==null)return"-";let r=e.cleanups.find((o)=>o.name===n);if(r==null)return"no data";if(!r.ok)return Oe.default.red("failed");return r.backlog==null?"not reported":`${r.backlog} pending`}function jz(e){if(e.collecting)return`${Oe.default.yellow("Collecting")} - no sample yet, categories are not measured.`;if(e.daysUntilFull!=null)return`Full in ~${e.daysUntilFull} days at the current net rate.`;if(e.stable)return"Stable - no net growth since the last samples.";return"Collecting - not enough history for a projection yet."}function Vz(e){let t=Math.round(e.disk.usagePercent);if(console.log(`
|
|
2340
|
+
${Oe.default.bold("Disk")} ${Pz(e.status)}`),console.log(` Total: ${bn(e.disk.totalBytes)}`),console.log(` Used: ${bn(e.disk.usedBytes)} (${t}%)`),console.log(` Available: ${bn(e.disk.availableBytes)}`),console.log(` ${An(t,100,30)}`),console.log(` ${jz(e)}`),e.retentionStartsInDays!=null)console.log(` Retention starts acting in ${e.retentionStartsInDays} days.`);if(e.sampledAt!=null)console.log(` Categories measured at ${e.sampledAt}`)}function Kz(e){console.log(`
|
|
2341
|
+
${Oe.default.bold("Categories")}`);for(let{key:t,label:n}of Dz){let r=e.categories[t];console.log(` ${n.padEnd(16)} ${Oe.default.cyan(Mz(r).padEnd(20))} ${Iw(r).padEnd(14)} ${Lz(r)}`)}}function qz(e,t){let n=t.retentionDays==null?t.retentionSource:`${t.retentionDays}d (${t.retentionSource})`;console.log(` ${zz(t.class).padEnd(22)} ${bn(t.bytes).padEnd(10)} ${String(t.rows).padEnd(11)} ${(t.oldestAt?.slice(0,10)??"-").padEnd(11)} ${Iw(t).padEnd(13)} ${n.padEnd(18)} ${bn(t.reclaimableBytes).padEnd(18)} ${Uz(e,t.class)}`)}function Bz(e){if(console.log(`
|
|
2342
|
+
${Oe.default.bold("Database")}`),e.databaseClasses===void 0){console.log(` ${Oe.default.dim("Not available - requires platform_storage:manage.")}`);return}if(e.databaseClasses.length===0){console.log(` ${Oe.default.yellow("Collecting")} - no sample yet.`);return}let t=e.databaseClasses.reduce((n,r)=>n+r.bytes,0);console.log(` Sum by class: ${Oe.default.cyan(bn(t))}`),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 n of e.databaseClasses)qz(e,n);console.log(` ${Oe.default.dim("Rows and reclaimable are estimates from pg_stat_user_tables (updated after ANALYZE).")}`),console.log(` ${Oe.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(` ${Oe.default.dim("Retention frees space for reuse inside PostgreSQL; returning it to disk needs VACUUM FULL or pg_repack.")}`)}function Hz(e){if(console.log(`
|
|
2343
|
+
${Oe.default.bold("Cleanups")}`),e.cleanups.length===0){console.log(` ${Oe.default.dim("No data - no pass has been recorded yet.")}`);return}for(let t of e.cleanups){let n=t.ok?Oe.default.green("ok".padEnd(16)):Oe.default.red("failed".padEnd(16)),r=t.backlog==null?"not reported":`${t.backlog} pending`;console.log(` ${t.name.padEnd(10)} ${n} deleted ${t.deleted} backlog ${r}`)}}function Wz(e){console.log(`
|
|
2344
|
+
${Oe.default.bold("Thresholds")}`),console.log(` Warning: ${e.thresholds.warning}%`),console.log(` Critical: ${e.thresholds.critical}%`)}function Ow(e,t){e.command("storage").description("Storage observability and cache stats").command("usage").description("Show storage usage breakdown").action(async()=>{let{format:r}=S(e.opts()),o=await b(t().dashboard.storageUsage({}));if(r==="json"){v(o);return}Vz(o),Kz(o),Bz(o),Hz(o),Wz(o),console.log()})}function Nw(e,t){let n=e.command("tenants").description("Manage tenants");n.command("list").description("List tenants").action(()=>Vt()),n.command("create").description("Create a tenant").action(()=>Vt())}function kw(e,t){let n=e.command("tts").description("Text-to-speech resources (to synthesize audio, see: niva audio-files generate-tts)");n.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(r)=>{let{format:o,fields:i}=S(e.opts()),a=await b(t().tts.listVoices({language:r.language,model:r.model}));if(o==="json"){let s=i?a.map((c)=>O(c,i)):a;v(s);return}L(["ID","Name","Gender","Languages","Model"],a.map((s)=>({ID:s.id,Name:s.name,Gender:s.gender??"-",Languages:s.languages.join(", "),Model:s.model})))}),n.command("models").description("List available TTS models").action(async()=>{let{format:r,fields:o}=S(e.opts()),i=await b(t().tts.listModels());if(r==="json"){let a=o?i.map((s)=>O(s,o)):i;v(a);return}L(["ID","Name","Provider"],i.map((a)=>({ID:a.id,Name:a.name,Provider:a.provider})))}),n.command("languages").description("List available TTS languages").action(async()=>{let{format:r}=S(e.opts()),o=await b(t().tts.listLanguages());if(r==="json"){v(o);return}L(["Language"],o.map((i)=>({Language:i})))})}function Gz(e){return e.fields.map((t)=>`${t.name}${t.required?"":"?"}${t.nullable?"|null":""}`).join(", ")}function Dw(e,t){e.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:r,fields:o}=S(e.opts()),i=await b(t().webhooks.events.list());if(r==="json"){v(o?i.map((a)=>O(a,o)):i);return}L(["Event","Module","Fields"],i.map((a)=>({Event:a.event,Module:a.required_module??"core",Fields:Gz(a)})))})}function Pw(e,t,n){let r=e.command("ws").description("WebSocket chat — connect to a published plan");r.command("chat <plan_id>").description("Start an interactive WebSocket chat session with a published plan").action(async(o)=>{let i=Cn(e.opts()),a=n();P("Creating WebSocket session...");let s=async()=>b(t().ws.createSession({planId:x("visual_plans",o)})),c=await s();if(i==="json"){v(c);return}N(`Session created: ${c.sessionId}`),await wa(hn(a.url,c.wsUrl),async()=>hn(a.url,(await s()).wsUrl))}),r.command("session <plan_id>").description("Create a WebSocket session (returns sessionId + wsUrl)").action(async(o)=>{let i=Cn(e.opts()),a=await b(t().ws.createSession({planId:x("visual_plans",o)})),s=n(),c=hn(s.url,a.wsUrl);if(i==="json"){v({...a,ws_url:c});return}N(`Session: ${a.sessionId}`),console.log(` WebSocket URL: ${c}`),console.log(` Connect with: websocat ${c}`)})}function $w(e,t,n,r){iE(e),sx(e,n,r),uw(e),KE(e),vm(e,t),lx(e,t),u_(e,t),E_(e,t),mx(e,t,n),gw(e,t),Cw(e,t),Tw(e,t),lw(e,t),p_(e,t),_E(e,t),vE(e,t),xE(e,t),wE(e,t),nw(e,t),bE(e,t),bx(e,t),Ix(e,t,n),yE(e,t),$E(e,t),UE(e,t),Rw(e,t),Sw(e,t),Ow(e,t),Nw(e,t),kw(e,t),Pw(e,t,n),oE(e,t,n),Dw(e,t),ew(e)}function Zz(e){try{let{hostname:t}=new URL(e);return t.endsWith(".orb.local")||process.env.NIVA_INSECURE==="true"}catch{return!1}}function Lw(e){let t=[];for(let n=e;n.parent!=null;n=n.parent)t.unshift(n.name());return t.join(" ")}var Rp;function zw(e){Rp=e===""?void 0:e}function Mw(){return Rp==null?{}:{[vo]:Rp}}class Fw extends Error{constructor(){super("Your session has expired. Run 'niva login' to authenticate again.")}}function Yz(e){let t=e.fetchImpl??fetch,n=async()=>{try{return await e.refresh()}catch(r){if(r instanceof Ke)throw new Fw;throw r}};return async(r)=>{let o=e.getSession();if(ba(o))o=await n();let i=new Request(r);i.headers.set("authorization",`Bearer ${o.access_token}`);let a=await t(i);if(a.status===401){o=await n();let s=new Request(r);s.headers.set("authorization",`Bearer ${o.access_token}`),a=await t(s)}return a}}function Uw(e,t,n){if(Zz(e))process.env.NODE_TLS_REJECT_UNAUTHORIZED="0";if(t.kind!=="oauth"){let i=new Hn({url:new URL("/api/rpc",e).href,headers:()=>({...Mw(),...t.kind==="api-key"?{"X-API-Key":t.apiKey}:{}})});return Bn(i)}let r=t.session,o=new Hn({url:new URL("/api/rpc",e).href,headers:Mw,fetch:Yz({getSession:()=>r,refresh:async()=>(r=await va(n,r),wr(n,r),r)})});return Bn(o)}import{readFileSync as Jz}from"node:fs";var Xz=1500,Qz="/cli/compatibilidade",Ia=null;function e2(){if(Ia!=null)return Ia;let e='{"min":"2.0.0","max":null}',t=null;if(typeof e==="string"){let n=JSON.parse(e);t=jw(n)}else{let n=JSON.parse(t2()),r=ge(n)?n.supported_niva:void 0;t=jw(r)}if(t==null)throw Error("Invalid apps/cli/compat.json, fix supported_niva");return Ia=t,Ia}function jw(e){if(!ge(e))return null;let t=oe(e.min);if(t==null)return null;let n=oe(e.max)??null;return{supported_niva:{min:t,max:n}}}function t2(){return Jz(new URL("../../compat.json",import.meta.url),"utf-8")}function Ip(e){let n=(e.split("-")[0]?.split("+")[0]??"").split(".");if(n.length!==3)return null;let r=n.map((o)=>Number.parseInt(o,10));if(r.some((o)=>!Number.isFinite(o)||o<0))return null;return[r[0],r[1],r[2]]}function Vw(e,t){let n=Ip(e),r=Ip(t);if(n===null||r===null)return 0;for(let o=0;o<3;o++)if(n[o]!==r[o])return n[o]-r[o];return 0}function n2(e,t){let{min:n,max:r}=t.supported_niva;if(Vw(e,n)<0)return!1;if(r!=null&&Vw(e,r)>0)return!1;return!0}function r2(e,t,n){let{min:r,max:o}=n.supported_niva,i=o==null?`>= ${r}`:`>= ${r} <= ${o}`;return`warning: this CLI (${zr()}) supports NIVA ${i}; ${t} reports ${e}. Some commands may not exist. See ${Qz}`}async function o2(e,t=fetch){let n=new AbortController,r=setTimeout(()=>n.abort(),Xz);try{let o=await t(new URL("/api/version",e).href,{signal:n.signal,headers:{accept:"application/json"}});if(!o.ok)return null;let i=await o.json();if(i===null||typeof i!=="object"||!("niva_version"in i))return null;let a=i.niva_version;if(typeof a!=="string"||Ip(a)===null)return null;return a}catch{return null}finally{clearTimeout(r)}}async function Kw(e,t={}){if(!e)return;let n=t.config??e2(),r=await o2(e,t.fetchImpl);if(r===null)return;if(n2(r,n))return;console.error(r2(r,e,n))}import{chmodSync as Use,mkdirSync as jse,readFileSync as i2,writeFileSync as Vse}from"node:fs";import{homedir as a2}from"node:os";import{join as Hw}from"node:path";var s2=Hw(a2(),".niva"),c2=Hw(s2,"config.json"),qw={url:"http://localhost:3000",apiKey:""};function Bw(e,t){let n=e[t];return typeof n==="string"?n:void 0}function Op(){try{let e=JSON.parse(i2(c2,"utf-8"));return ge(e)?e:{}}catch{return{}}}function Ww(){return Op()}function Gw(e){if(e.flagApiKey!=null&&e.flagApiKey!=="")return{kind:"api-key",apiKey:e.flagApiKey};if(e.envApiKey!=null&&e.envApiKey!=="")return{kind:"api-key",apiKey:e.envApiKey};if(e.session!=null)return{kind:"oauth",session:e.session};if(e.fileApiKey!=null&&e.fileApiKey!=="")return{kind:"api-key",apiKey:e.fileApiKey};return{kind:"none"}}function l2(e){let t=ge(e)?{...e}:void 0;if(t==null)return!1;let n=t.scopes;return typeof t.access_token==="string"&&typeof t.refresh_token==="string"&&typeof t.expires_at==="number"&&typeof t.org_id==="string"&&Array.isArray(n)&&n.every((r)=>typeof r==="string")}function d2(){let e=Op().auth;return ge(e)?e:{}}function Zw(){let e={};for(let[t,n]of Object.entries(d2()))if(l2(n))e[t]=n;return e}function Yw(e){let t=Op();return{url:e.url??process.env.NIVA_URL??Bw(t,"url")??qw.url,apiKey:e.apiKey??process.env.NIVA_API_KEY??Bw(t,"apiKey")??qw.apiKey}}var u2="table",p2="";function Jw(e){u2=e}function Xw(e){p2=e}var m2=new Set(["json","table","plain"]);function f2(e){return m2.has(e)}function g2(){return process.stdout.isTTY===!0&&process.env.NO_COLOR==null}function Qw(e){if(e.output!=null)return f2(e.output)?e.output:"table";if(e.json===!0)return"json";return g2()?"table":"json"}function eC(){return"0.5.2"}var Fo=new pm("niva").description("NIVA CLI \u2014 manage your IVR platform").version(eC()).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",(e,t)=>{zw(Lw(t));let n=Fo.opts(),r=Qw({json:n.json===!0,output:typeof n.output==="string"?n.output:void 0});Jw(r)}).hook("preAction",async()=>{await Kw(Da().url)}),Oa;function Da(){if(Oa!=null)return Oa;let e=Fo.opts();return Oa=Yw({url:typeof e.url==="string"?e.url:void 0,apiKey:typeof e.apiKey==="string"?e.apiKey:void 0}),Oa}var Na;function tC(){if(Na!=null)return Na;let e=Da(),t=Ww(),n=Fo.opts().apiKey;return Na=Gw({flagApiKey:typeof n==="string"?n:void 0,envApiKey:process.env.NIVA_API_KEY,fileApiKey:typeof t.apiKey==="string"?t.apiKey:void 0,session:Zw()[ja(e.url)]}),Na}var ka;function h2(){if(ka!=null)return ka;let e=Da();Xw(e.url);let t=tC();if(t.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 ka=Uw(e.url,t,ja(e.url)),ka}$w(Fo,h2,Da,tC);Fo.parseAsync().catch((e)=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});
|