franchising 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/messaging/index.cjs +1 -1
- package/dist/messaging/index.d.cts +154 -11
- package/dist/messaging/index.d.ts +154 -11
- package/dist/messaging/index.js +1 -1
- package/dist/{version-CMkha8JJ.cjs → version-79f-RqdP.cjs} +1 -1
- package/dist/version-DiXfOKVT.js +1 -0
- package/package.json +1 -1
- package/dist/version-B0ADow60.js +0 -1
package/dist/cli.js
CHANGED
|
@@ -17,7 +17,7 @@ Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._life
|
|
|
17
17
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
18
18
|
- ${t?`searched for local subcommand relative to directory '${t}'`:`no directory for search for local subcommand, use .executableDir() to supply a custom directory`}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let n=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function r(e,t){let r=s.resolve(e,t);if(c.existsSync(r))return r;if(n.includes(s.extname(t)))return;let i=n.find(e=>c.existsSync(`${r}${e}`));if(i)return`${r}${i}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,o=this._executableDir||``;if(this._scriptPath){let e;try{e=c.realpathSync(this._scriptPath)}catch{e=this._scriptPath}o=s.resolve(s.dirname(e),o)}if(o){let t=r(o,i);if(!t&&!e._executableFile&&this._scriptPath){let n=s.basename(this._scriptPath,s.extname(this._scriptPath));n!==this._name&&(t=r(o,`${n}-${e._name}`))}i=t||i}let l=n.includes(s.extname(i)),u;d.platform===`win32`?(this._checkForMissingExecutable(i,o,e._name),t.unshift(i),t=De(d.execArgv).concat(t),u=a.spawn(d.execPath,t,{stdio:`inherit`})):l?(t.unshift(i),t=De(d.execArgv).concat(t),u=a.spawn(d.argv[0],t,{stdio:`inherit`})):u=a.spawn(i,t,{stdio:`inherit`}),u.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{d.on(e,()=>{u.killed===!1&&u.exitCode===null&&u.kill(e)})});let f=this._exitCallback;u.on(`close`,e=>{e??=1,f?f(new he(e,`commander.executeSubCommandAsync`,`(close)`)):d.exit(e)}),u.on(`error`,t=>{if(t.code===`ENOENT`)this._checkForMissingExecutable(i,o,e._name);else if(t.code===`EACCES`)throw Error(`'${i}' not executable`);if(!f)d.exit(1);else{let e=new he(1,`commander.executeSubCommandAsync`,`(error)`);e.nestedError=t,f(e)}}),this.runningCommand=u}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,`preSubcommand`),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??`--help`])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic||this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(e,t,n)=>{let r=t;if(t!==null&&e.parseArg){let i=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;r=this._callParseArg(e,t,n,i)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((t,r)=>e(n,r,t),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then==`function`?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(e=>e._lifeCycleHooks[t]!==void 0).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{r.push({hookedCommand:e,callback:t})})}),t===`postAction`&&r.reverse(),r.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(e=>{r=this._chainOrCall(r,()=>e(this,t))}),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);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=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let n;return n=this._chainOrCallHooks(n,`preAction`),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(i,e,t)})),n=this._chainOrCallHooks(n,`postAction`),n}if(this.parent?.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand(`*`))return this._dispatchSubcommand(`*`,e,t);this.listenerCount(`command:*`)?this.emit(`command:*`,e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)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=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(e=>{let t=e.attributeName();return this.getOptionValue(t)!==void 0&&this.getOptionValueSource(t)!=="default"});e.filter(e=>e.conflictsWith.length>0).forEach(t=>{let n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function i(e){return e.length>1&&e[0]===`-`}let a=e=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(e)?!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e))):!1,o=null,s=null,c=0;for(;c<e.length||s;){let l=s??e[c++];if(s=null,l===`--`){r===n&&r.push(l),r.push(...e.slice(c));break}if(o&&(!i(l)||a(l)))this.emit(`option:${o.name()}`,l);else{if(o=null,i(l)){let t=this._findOption(l);if(t){if(t.required){let n=e[c++];n===void 0&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,n)}else if(t.optional){let n=null;c<e.length&&(!i(e[c])||a(e[c]))&&(n=e[c++]),this.emit(`option:${t.name()}`,n)}else this.emit(`option:${t.name()}`);o=t.variadic?t:null;continue}}if(l.length>2&&l[0]===`-`&&l[1]!==`-`){let e=this._findOption(`-${l[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,l.slice(2)):(this.emit(`option:${e.name()}`),s=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let e=l.indexOf(`=`),t=this._findOption(l.slice(0,e));if(t&&(t.required||t.optional)){this.emit(`option:${t.name()}`,l.slice(e+1));continue}}if(r===t&&i(l)&&!(this.commands.length===0&&a(l))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),n.push(...e.slice(c));break}if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}if(this._defaultCommandName){n.push(l,...e.slice(c));break}}if(this._passThroughOptions){r.push(l,...e.slice(c));break}r.push(l)}}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
19
19
|
`),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in d.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||[`default`,`config`,`env`].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,d.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new xe(this.options),t=e=>this.getOptionValue(e)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(e));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],`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=e=>{let t=e.attributeName(),n=this.getOptionValue(t),r=this.options.find(e=>e.negate&&t===e.attributeName()),i=this.options.find(e=>!e.negate&&t===e.attributeName());return r&&(r.presetArg===void 0&&n===!1||r.presetArg!==void 0&&n===r.presetArg)?r:i||e},r=e=>{let t=n(e),r=t.attributeName();return this.getOptionValueSource(r)===`env`?`environment variable '${t.envVar}'`:`option '${t.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:`commander.conflictingOption`})}unknownOption(e){if(this._allowUnknownOption)return;let t=``;if(e.startsWith(`--`)&&this._showSuggestionAfterError){let n=[],r=this;do{let e=r.createHelp().visibleOptions(r).filter(e=>e.long).map(e=>e.long);n=n.concat(e),r=r.parent}while(r&&!r._enablePositionalOptions);t=Te(e,n)}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`,r=e.length,i=`error: too many arguments${this.parent?` for '${this.name()}'`:``}. Expected ${t} argument${n} but got ${r}: ${e.join(`, `)}.`;this.error(i,{code:`commander.excessArguments`})}unknownCommand(){let e=this.args[0],t=``;if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=Te(e,n)}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||=`-V, --version`,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}\n`),this._exit(0,`commander.version`,e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(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]),e===t._name)throw Error(`Command alias can't be the same as its name`);let n=this.parent?._findCommand(e);if(n){let t=[n.name()].concat(n.aliases()).join(`|`);throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(e=>ve(e));return[].concat(this.options.length||this._helpOption!==null?`[options]`:[],this.commands.length?`[command]`:[],this.registeredArguments.length?e:[]).join(` `)}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??``:(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??``:(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??``:(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=s.basename(e,s.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(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);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e||={};let t=!!e.error,n,r,i;return t?(n=e=>this._outputConfiguration.writeErr(e),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:e=>(r||(e=this._outputConfiguration.stripColor(e)),n(e)),hasColors:r,helpWidth:i}}outputHelp(e){let t;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(e=>e.emit(`beforeAllHelp`,r)),this.emit(`beforeHelp`,r);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),typeof i!=`string`&&!Buffer.isBuffer(i)))throw Error(`outputHelp callback must return a string or a Buffer`);n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit(`afterHelp`,r),this._getCommandAndAncestors().forEach(e=>e.emit(`afterAllHelp`,r))}helpOption(e,t){return typeof e==`boolean`?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??`-h, --help`,t??`display help for command`),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(d.exitCode??0);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.
|
|
20
|
-
Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function De(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function Oe(){if(d.env.NO_COLOR||d.env.FORCE_COLOR===`0`||d.env.FORCE_COLOR===`false`)return!1;if(d.env.FORCE_COLOR||d.env.CLICOLOR_FORCE!==void 0)return!0}new Ee;const ke=`0.
|
|
20
|
+
Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function De(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function Oe(){if(d.env.NO_COLOR||d.env.FORCE_COLOR===`0`||d.env.FORCE_COLOR===`false`)return!1;if(d.env.FORCE_COLOR||d.env.CLICOLOR_FORCE!==void 0)return!0}new Ee;const ke=`0.4.0`,Ae=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),je=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Me=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,Ne=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Pe=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Fe=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,Ie=/\t{1,1000}/y,Le=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,Re=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,ze=/\p{M}+/gu,Be={limit:1/0,ellipsis:``},Ve=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Ve(i,Be,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[Re,l],[Ne,0],[Pe,o],[Ie,s],[Le,c],[Fe,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(ze,``)){let t=e.codePointAt(0)||0;if(S=je(t)?2:Me(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===Fe?Ae(e.slice(p,n.lastIndex)):n===Le?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},He={limit:1/0,ellipsis:``,ellipsisWidth:0},T=(e,t={})=>Ve(e,He,t).width,Ue=`]8;;`,We=RegExp(`(?:\\[(?<code>\\d+)m|\\${Ue}(?<uri>.*))`,`y`),Ge=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},Ke=e=>`[${e}m`,qe=e=>`${Ue}${e}`,Je=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:T(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=T(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===``)&&(i=!0,a=t.startsWith(Ue,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},Ye=e=>{let t=e.split(` `),n=t.length;for(;n&&!T(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Xe=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=T(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=T(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),Je(s,r,t),c=T(s.at(-1)??``)}else{if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Je(s,r,t),c=T(s.at(-1)??``);continue}s.push(``),c=0}c+i>t&&n.wordWrap===!1?(Je(s,r,t),c=T(s.at(-1)??``)):(s[s.length-1]+=r,c+=i)}}n.trim!==!1&&(s=s.map(e=>Ye(e)));let l=s.join(`
|
|
21
21
|
`),u=!1;for(let e=0;e<l.length;e++){let t=l[e];if(r+=t,u)u=!1;else if(u=t>=`\ud800`&&t<=`\udbff`,u)continue;if(t===`\x1B`||t===``){We.lastIndex=e+1;let t=We.exec(l)?.groups;if(t?.code!==void 0){let e=Number.parseFloat(t.code);i=e===39?void 0:e}else t?.uri!==void 0&&(a=t.uri.length===0?void 0:t.uri)}if(l[e+1]===`
|
|
22
22
|
`){a&&(r+=qe(``));let e=i?Ge(i):void 0;i&&e&&(r+=Ke(e))}else t===`
|
|
23
23
|
`&&(i&&Ge(i)&&(r+=Ke(i)),a&&(r+=qe(a)))}return r},Ze=/\r?\n/;function E(e,t,n){return String(e).normalize().split(Ze).map(e=>Xe(e,t,n)).join(`
|
|
@@ -369,7 +369,7 @@ export class AuthSessionController {
|
|
|
369
369
|
};
|
|
370
370
|
}
|
|
371
371
|
}
|
|
372
|
-
`}const Kr=`franchising`,qr=`^0.
|
|
372
|
+
`}const Kr=`franchising`,qr=`^0.4.0`,Jr={[Kr]:qr},Yr={"@opentelemetry/api":`^1.9.0`,"@opentelemetry/api-logs":`^0.208.0`,"@opentelemetry/auto-instrumentations-node":`^0.67.0`,"@opentelemetry/exporter-logs-otlp-http":`^0.208.0`,"@opentelemetry/exporter-metrics-otlp-http":`^0.208.0`,"@opentelemetry/exporter-trace-otlp-http":`^0.208.0`,"@opentelemetry/resources":`^2.0.0`,"@opentelemetry/sdk-logs":`^0.208.0`,"@opentelemetry/sdk-metrics":`^2.0.0`,"@opentelemetry/sdk-node":`^0.208.0`,"nestjs-pino":`^4.4.0`,pino:`^9.7.0 || ^10.0.0`},Xr={betterstack:{"@sentry/node":`^9.0.0`},posthog:{"posthog-node":`^5.52.4`}},Zr={jose:`^6.2.12`,zod:`^4.6.7`},Qr={"class-variance-authority":`^0.7.1`,cmdk:`^1.1.1`,cnfast:`0.1.0`,"input-otp":`^1.5.0`,"lucide-react":`^0.469.0`,"radix-ui":`^1.6.7`,"react-day-picker":`^10.0.1`,sonner:`^2.0.7`,"sugar-high":`^2.4.1`,vaul:`^1.1.2`},$r=[{id:`organization`,label:`Organization`,hint:`Organizacoes, membros, convites e papeis.`,serverImport:{name:`organization`,from:`better-auth/plugins`},clientImport:{name:`organizationClient`,from:`better-auth/client/plugins`},config:` organization({
|
|
373
373
|
allowUserToCreateOrganization: true,
|
|
374
374
|
creatorRole: 'owner',
|
|
375
375
|
}),`,needsMigration:!0},{id:`admin`,label:`Admin`,hint:`Papel de administrador, banimento e impersonacao.`,serverImport:{name:`admin`,from:`better-auth/plugins`},clientImport:{name:`adminClient`,from:`better-auth/client/plugins`},config:` admin({
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./version-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./version-79f-RqdP.cjs");exports.version=e.t;
|
package/dist/index.d.cts
CHANGED
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{t as version}from"./version-
|
|
1
|
+
export{t as version}from"./version-DiXfOKVT.js";
|
package/dist/messaging/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});const e=require("../version-CMkha8JJ.cjs"),t=1048576,n=20*t,r=5*t,i=10*t,a=1024,o=2048,s=[`upload`,`url`],c=[`attachment`,`inline`],l=[`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/vnd.ms-powerpoint`,`application/vnd.openxmlformats-officedocument.presentationml.presentation`],u=[`application/pdf`,`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`text/csv`,`text/plain`,...l,`application/vnd.oasis.opendocument.text`,`application/vnd.oasis.opendocument.spreadsheet`,`application/zip`,`text/calendar`],d=/* @__PURE__ */ `apk.app.bat.cmd.com.cpl.dll.dmg.exe.hta.jar.js.jse.lnk.msi.msp.pif.ps1.reg.scr.sh.vb.vbe.vbs.wsf.wsh`.split(`.`),f=[`image`,`video`,`audio`,`document`],p={image:[`image/jpeg`,`image/png`],video:[`video/mp4`,`video/3gpp`],audio:[`audio/aac`,`audio/mp4`,`audio/mpeg`,`audio/amr`,`audio/ogg`],document:[`application/pdf`,...l,`text/plain`,`text/csv`,`application/zip`]},m={image:r,video:i,audio:i,document:i},ee=/* @__PURE__ */ `UNAUTHENTICATED.INVALID_API_KEY.ACTIVE_PROJECT_REQUIRED.PROJECT_ROLE_REQUIRED.VALIDATION_ERROR.FROM_DOMAIN_NOT_VERIFIED.SENDER_NOT_FOUND.WHATSAPP_TEMPLATE_NOT_FOUND.WHATSAPP_TEMPLATE_CONFLICT.WHATSAPP_TEMPLATE_PROVIDER_UNSUPPORTED.WHATSAPP_TEMPLATE_SUBMISSION_FAILED.WHATSAPP_TEMPLATE_SYNC_FAILED.WHATSAPP_TEMPLATE_INVALID_STATE.WHATSAPP_TEMPLATE_BODY_CONFLICT.ATTACHMENTS_NOT_SUPPORTED_FOR_CHANNEL.ATTACHMENTS_PROVIDER_TEMPLATE_CONFLICT.ATTACHMENT_INVALID.ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED.ATTACHMENT_TOO_LARGE.ATTACHMENTS_LIMIT_EXCEEDED.ATTACHMENT_URL_NOT_ALLOWED.WHATSAPP_CAPTION_INVALID.PAYLOAD_TOO_LARGE.ATTACHMENT_STORAGE_UNAVAILABLE.ATTACHMENT_STORAGE_NOT_CONFIGURED.ATTACHMENT_EXPIRED.MESSAGE_NOT_FOUND.MESSAGE_NOT_RETRYABLE.MESSAGE_CONTENT_EXPIRED.IDEMPOTENCY_KEY_REUSED.ROUTE_NOT_FOUND.INTERNAL_SERVER_ERROR.RATE_LIMIT_EXCEEDED.CONNECTION_ERROR.TIMEOUT.UNEXPECTED_RESPONSE`.split(`.`);var h=class extends Error{name=`MessagingError`;code;status;errors;constructor(e){super(e.message,{cause:e.cause}),this.code=e.code,this.status=e.status,this.errors=e.errors}get retryable(){return this.status===0||this.status===408||this.status===429||this.status>=500}toJSON(){return{name:this.name,code:this.code,message:this.message,status:this.status,...this.errors?{errors:this.errors}:{}}}},g=class extends h{name=`ValidationError`},_=class extends h{name=`AuthenticationError`},v=class extends h{name=`PermissionError`},y=class extends h{name=`NotFoundError`},b=class extends h{name=`RateLimitError`;retryAfter;constructor(e){super(e),this.retryAfter=e.retryAfter}},x=class extends h{name=`ServerError`},S=class extends h{name=`ConnectionError`},C=class extends h{name=`TimeoutError`};function w(e){return e instanceof h}function T(e){let t={code:e.code,message:e.message,status:e.status,...e.errors?{errors:e.errors}:{}};return e.status===429?new b({...t,...e.retryAfter===void 0?{}:{retryAfter:e.retryAfter}}):e.status>=500?new x(t):e.status===401?new _(t):e.status===403?new v(t):e.status===404?new y(t):e.status===400||e.status===422?new g(t):new h(t)}function te(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e))if(r!==void 0){if(Array.isArray(r))for(let e of r)t.append(n,String(e));else t.append(n,r instanceof Date?r.toISOString():String(r))}let n=t.toString();return n?`?${n}`:``}const E=8e3,ne=e=>new Promise(t=>setTimeout(t,e));function re(e,t){if(t!==void 0)return Math.min(t*1e3,E);let n=Math.min(500*2**e,E);return Math.round(n*(.5+Math.random()*.5))}function ie(e){if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t;let n=Date.parse(e);if(!Number.isNaN(n))return Math.max(0,Math.round((n-Date.now())/1e3))}function D(e){if(e.length===1)return e[0];let t=AbortSignal.any;if(t)return t(e);let n=new AbortController;for(let t of e){if(t.aborted){n.abort(t.reason);break}t.addEventListener(`abort`,()=>n.abort(t.reason),{once:!0})}return n.signal}function O(e){return{data:e,error:null}}function k(e){return{data:null,error:e}}const A=e.t,ae=`rockdev-messaging-node/${A}`;var oe=class{config;constructor(e){this.config=e}async request(e){let t=`${this.config.baseUrl}/v1${e.path}${e.query?te(e.query):``}`,n=e.method===`GET`||e.idempotencyKey!==void 0?this.config.maxRetries:0,r;for(let i=0;i<=n;i+=1){let a=await this.attempt(t,e);if(a.error===null)return a;if(r=a.error,!a.error.retryable||e.options?.signal?.aborted||i===n)break;await ne(re(i,a.error.retryAfter))}return k(r)}async attempt(e,t){let n=t.options?.timeout??this.config.timeout,r=new AbortController,i=setTimeout(()=>r.abort(),n),a=[r.signal];t.options?.signal&&a.push(t.options.signal);let o;try{o=await this.config.fetch(e,{method:t.method,headers:this.headers(t),signal:D(a),...t.body===void 0?{}:{body:JSON.stringify(t.body)}})}catch(e){return t.options?.signal?.aborted?k(new h({code:`CONNECTION_ERROR`,message:`The request was aborted by the caller.`,status:0,cause:e})):r.signal.aborted?k(new C({code:`TIMEOUT`,message:`The request did not complete within ${n}ms.`,status:0,cause:e})):k(new S({code:`CONNECTION_ERROR`,message:e instanceof Error?e.message:`The request could not reach the Messaging API.`,status:0,cause:e}))}finally{clearTimeout(i)}return this.parse(o)}headers(e){let t=e=>Object.fromEntries(Object.entries(e).filter(([e])=>e.toLowerCase()!==`idempotency-key`));return{accept:`application/json`,authorization:`Bearer ${this.config.secret}`,"user-agent":ae,...e.body===void 0?{}:{"content-type":`application/json`},...t(this.config.headers),...t(e.options?.headers??{}),...e.idempotencyKey===void 0?{}:{"idempotency-key":e.idempotencyKey}}}async parse(e){let t=await e.text().catch(()=>``),n;try{n=t?JSON.parse(t):void 0}catch{n=void 0}if(!e.ok){let t=ie(e.headers.get(`retry-after`));return k(T({code:n?.code??`INTERNAL_SERVER_ERROR`,message:n?.message??`The Messaging API responded with ${e.status}.`,status:e.status,...n?.errors?{errors:n.errors}:{},...t===void 0?{}:{retryAfter:t}}))}return!n||n.data===void 0?k(new h({code:`UNEXPECTED_RESPONSE`,message:`The Messaging API responded without the expected body.`,status:e.status})):O(n.data)}},j=class{messages;constructor(e){this.messages=e}async send(e,t){let{to:n,...r}=e;return this.messages.send({...r,to:typeof n==`string`?{email:n}:n},t)}async batch(e,t){return this.messages.batch(e.map(({to:e,...t})=>({...t,to:typeof e==`string`?{email:e}:e})),t)}},M=class e{fetchPage;messages;nextCursor;constructor(e,t){this.fetchPage=t,this.messages=e.messages,this.nextCursor=e.nextCursor}get hasMore(){return this.nextCursor!==null}async next(){return this.nextCursor===null?{data:new e({messages:[],nextCursor:null},this.fetchPage),error:null}:this.fetchPage(this.nextCursor)}async*[Symbol.asyncIterator](){let e=this;for(;;){for(let t of e.messages)yield t;if(!e.hasMore)return;let{data:t,error:n}=await e.next();if(n)throw n;e=t}}};function N(e){if(e!==void 0)return e instanceof Date?e.toISOString():e}function se(e){return{status:e.status,channel:e.channel,to:e.to,search:e.search,scheduled:e.scheduled,createdAfter:N(e.createdAfter),createdBefore:N(e.createdBefore),limit:e.limit,cursor:e.cursor}}const P=24576;function ce(e){if(typeof e.toBase64==`function`)return e.toBase64();let t=globalThis.Buffer;if(t)return t.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`);let n=``;for(let t=0;t<e.length;t+=P){let r=e.subarray(t,t+P),i=``;for(let e=0;e<r.length;e+=1)i+=String.fromCharCode(r[e]);n+=btoa(i)}return n}function le(e){let t=e.endsWith(`==`)?2:+!!e.endsWith(`=`);return e.length/4*3-t}function ue(e){return typeof Blob<`u`&&e instanceof Blob}function de(e){return`email`in e&&e.email!==void 0?`email`:`whatsapp`in e&&e.whatsapp!==void 0?`whatsapp`:`sms`in e&&e.sms!==void 0?`sms`:`webpush`}function F(e){return typeof e==`string`?e.includes(`@`)?{email:e}:{whatsapp:e}:e}function I(e){let t=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(e);if(!t)return null;let[n,r]=[Number(t[1]),Number(t[2])];return n===0||n===10||n===127||n===100&&r>=64&&r<=127||n===169&&r===254||n===172&&r>=16&&r<=31||n===192&&r===168||n===198&&(r===18||r===19)||n>=224}function L(e){if(!e.startsWith(`[`))return null;let t=e.slice(1,-1).toLowerCase(),n=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(t);return n?.[1]?I(n[1])??!0:t===`::`||t===`::1`||t.startsWith(`::ffff:`)||/^f[cd]/.test(t)||/^fe[89ab]/.test(t)||t.startsWith(`ff`)}function R(e){try{return new URL(e)}catch{return null}}const z={pdf:`application/pdf`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,csv:`text/csv`,txt:`text/plain`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,xls:`application/vnd.ms-excel`,xlsx:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,ppt:`application/vnd.ms-powerpoint`,pptx:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,odt:`application/vnd.oasis.opendocument.text`,ods:`application/vnd.oasis.opendocument.spreadsheet`,zip:`application/zip`,ics:`text/calendar`,mp4:`video/mp4`,"3gp":`video/3gpp`,aac:`audio/aac`,m4a:`audio/mp4`,mp3:`audio/mpeg`,amr:`audio/amr`,ogg:`audio/ogg`,opus:`audio/ogg`};function B(e){return(e.split(`;`)[0]??``).trim().toLowerCase()}function V(e){let t=e.lastIndexOf(`.`);return t<=0||t===e.length-1?``:e.slice(t+1).toLowerCase()}function H(e){let t=B(e);for(let e of f)if(p[e].includes(t))return e;return null}function fe(e){return z[V(e.trim())]}const pe=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*(\s*;.*)?$/i,me=/^[A-Za-z0-9+/]*={0,2}$/,he=/[/\\\u0000-\u001f\u007f]/;var U=class{code;message;detail;constructor(e,t,n){this.code=e,this.message=t,this.detail=n}};function W(e,t,n=t){throw new U(e,t,n)}function ge(e,t){let n=e=>W(`ATTACHMENT_URL_NOT_ALLOWED`,`The attachment URL is not allowed: ${e}.`,`${t}.url ${e}`);e.length>2048&&n(`must be at most ${o} characters long`);let r=R(e)??n(`must be a valid URL`);r.protocol!==`https:`&&n(`must use https`),(r.username||r.password)&&n(`must not contain credentials`),r.port&&r.port!==`443`&&n(`must use the default port`);let i=r.hostname.toLowerCase().replace(/\.$/,``);(i===`localhost`||i.endsWith(`.localhost`)||i.endsWith(`.local`)||i.endsWith(`.internal`))&&n(`must not point to a local host`),!i.startsWith(`[`)&&!i.includes(`.`)&&n(`must use a fully qualified host name`),(I(i)||L(i))&&n(`must not point to a private address`)}async function _e(e,t){let n=e=>W(`ATTACHMENT_INVALID`,`The attachment is invalid.`,e);typeof e==`object`&&e||n(`${t} must be an object`);let{filename:r,disposition:i,contentId:a}=e;(typeof r!=`string`||r.trim()===``)&&n(`${t}.filename is required`),r.length>255&&n(`${t}.filename must be at most 255 characters long`),he.test(r)&&n(`${t}.filename must not contain path separators or control characters`);let o=`url`in e&&e.url!==void 0;o===(`content`in e&&e.content!==void 0)&&n(`${t} must have exactly one of url or content`),i!==void 0&&!c.includes(i)&&n(`${t}.disposition must be one of attachment, inline`),a!==void 0&&(typeof a!=`string`||a===``||a.length>255)&&n(`${t}.contentId must be a non-empty string of at most 255 characters`),i===`inline`&&(a??``).trim()===``&&n(`${t}.contentId is required for inline attachments`);let s={...i===void 0?{}:{disposition:i},...a===void 0?{}:{contentId:a}},l=e=>e===void 0||e.trim()===``?n(`${t}.contentType is required`):(pe.test(e)||n(`${t}.contentType must be a type/subtype MIME type`),e);if(o){let{url:i}=e;return typeof i==`string`?(ge(i,t),{body:{filename:r,contentType:l(e.contentType),url:i,...s},size:null}):n(`${t}.url must be a string`)}let{content:u}=e,d,f,p;if(typeof u==`string`)u.length%4==0&&me.test(u)||n(`${t}.content must be valid base64`),d=u,f=le(u);else{let e;if(u instanceof Uint8Array)e=u;else if(u instanceof ArrayBuffer)e=new Uint8Array(u);else if(ArrayBuffer.isView(u))e=new Uint8Array(u.buffer,u.byteOffset,u.byteLength);else if(ue(u))p=u.type||void 0,e=new Uint8Array(await u.arrayBuffer());else return n(`${t}.content must be a Uint8Array, ArrayBuffer, Blob or base64 string`);d=ce(e),f=e.byteLength}return{body:{filename:r,contentType:l(e.contentType??p??fe(r)),content:d,...s},size:f}}function ve(e,t,r){if(e===`email`){t.length>10&&W(`ATTACHMENTS_LIMIT_EXCEEDED`,`An email accepts at most 10 attachments.`);let e=0;t.forEach(({body:t,size:n},r)=>{let i=`attachments.${r}`;u.includes(B(t.contentType))||W(`ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED`,`The attachment content type is not allowed for email.`,`${i}.contentType ${B(t.contentType)} is not allowed`),d.includes(V(t.filename.trim()))&&W(`ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED`,`The attachment file extension is not allowed.`,`${i}.filename has a blocked extension`),e+=n??0}),e>20971520&&W(`ATTACHMENT_TOO_LARGE`,`Email attachments must add up to at most ${n} bytes.`);return}t.length>1&&W(`ATTACHMENTS_LIMIT_EXCEEDED`,`A WhatsApp message accepts at most 1 attachment.`);let[i]=t;if(!i)return;let o=`attachments.0`;(i.body.disposition!==void 0||i.body.contentId!==void 0)&&W(`ATTACHMENT_INVALID`,`The attachment is invalid.`,`${o}.disposition and contentId are email-only`);let s=H(i.body.contentType);s||W(`ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED`,`The attachment content type is not allowed for WhatsApp.`,`${o}.contentType ${B(i.body.contentType)} is not allowed`);let c=m[s];i.size!==null&&i.size>c&&W(`ATTACHMENT_TOO_LARGE`,`WhatsApp ${s} attachments must be at most ${c} bytes.`),r!==void 0&&s===`audio`&&W(`WHATSAPP_CAPTION_INVALID`,`WhatsApp audio does not accept a caption.`,`content must be empty for audio attachments`),r!==void 0&&r.length>1024&&W(`WHATSAPP_CAPTION_INVALID`,`A WhatsApp caption must be at most ${a} characters long.`,`content must be at most ${a} characters long`)}async function ye(e,t,n=``){try{let n=de(e.to);n!==`email`&&n!==`whatsapp`&&W(`ATTACHMENTS_NOT_SUPPORTED_FOR_CHANNEL`,`Attachments are not supported for the ${n} channel.`),e.providerTemplate!==void 0&&W(`ATTACHMENTS_PROVIDER_TEMPLATE_CONFLICT`,`Attachments cannot be combined with providerTemplate.`),Array.isArray(t)||W(`ATTACHMENT_INVALID`,`The attachment is invalid.`,`attachments must be an array`);let r=[];for(let[e,n]of t.entries())r.push(await _e(n,`attachments.${e}`));return ve(n,r,e.content),O(r.map(({body:e})=>e))}catch(e){if(!(e instanceof U))throw e;return k(new g({code:e.code,message:e.message,status:400,errors:[`${n}${e.detail}`]}))}}function be(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}async function G(e,t=``){let{to:n,sendAt:r,attachments:i,...a}=e,{idempotencyKey:o,...s}=a,c=F(n),l;if(i!==void 0&&i.length>0){let e=await ye({to:c,content:s.content,providerTemplate:s.providerTemplate},i,t);if(e.error)return k(e.error);l=e.data}return O(be({...s,to:c,sendAt:N(r),attachments:l}))}var K=class{http;constructor(e){this.http=e}async send(e,t){let n=await G(e);return n.error?k(n.error):this.http.request({method:`POST`,path:`/messages`,body:n.data,...e.idempotencyKey===void 0?{}:{idempotencyKey:e.idempotencyKey},...t?{options:t}:{}})}async batch(e,t){let{idempotencyKey:n,...r}=t??{},i=[];for(let[t,n]of e.entries()){let e=await G(n,`${t}.`);if(e.error)return k(e.error);i.push(e.data)}return this.http.request({method:`POST`,path:`/messages/batch`,body:i,...n===void 0?{}:{idempotencyKey:n},...t?{options:r}:{}})}async create(e,t){return this.send(e,t)}async retry(e,t,n){return this.http.request({method:`POST`,path:`/messages/${encodeURIComponent(e)}/retry`,idempotencyKey:t.idempotencyKey,...n?{options:n}:{}})}async get(e,t){return this.http.request({method:`GET`,path:`/messages/${encodeURIComponent(e)}`,...t?{options:t}:{}})}async retrieve(e,t){return this.get(e,t)}async list(e={},t){let{data:n,error:r}=await this.http.request({method:`GET`,path:`/messages`,query:se(e),...t?{options:t}:{}});return r?{data:null,error:r}:{data:new M(n,n=>this.list({...e,cursor:n},t)),error:null}}},q=class{messages;constructor(e){this.messages=e}async send(e,t){let{to:n,...r}=e;return this.messages.send({...r,to:typeof n==`string`?{sms:n}:n},t)}async batch(e,t){return this.messages.batch(e.map(({to:e,...t})=>({...t,to:typeof e==`string`?{sms:e}:e})),t)}},J=class{messages;http;constructor(e,t){this.messages=e,this.http=t}async createSubscriptionToken(e,t){return this.http.request({method:`POST`,path:`/webpush/subscription-tokens`,body:e,...t?{options:t}:{}})}async send(e,t){let{to:n,...r}=e;return this.messages.send({...r,to:{webpush:typeof n==`string`?{recipientId:n}:n}},t)}async batch(e,t){return this.messages.batch(e.map(({to:e,...t})=>({...t,to:{webpush:typeof e==`string`?{recipientId:e}:e}})),t)}},Y=class{messages;constructor(e){this.messages=e}async send(e,t){let{to:n,...r}=e;return this.messages.send({...r,to:typeof n==`string`?{whatsapp:n}:n},t)}async batch(e,t){return this.messages.batch(e.map(({to:e,...t})=>({...t,to:typeof e==`string`?{whatsapp:e}:e})),t)}},X=class{http;constructor(e){this.http=e}list(e={},t){return this.http.request({method:`GET`,path:`/whatsapp-templates`,query:{senderId:e.senderId},...t?{options:t}:{}})}get(e,t){return this.http.request({method:`GET`,path:`/whatsapp-templates/${encodeURIComponent(e)}`,...t?{options:t}:{}})}create(e,t){return this.http.request({method:`POST`,path:`/whatsapp-templates`,body:e,...t?{options:t}:{}})}update(e,t,n){return this.http.request({method:`PATCH`,path:`/whatsapp-templates/${encodeURIComponent(e)}`,body:t,...n?{options:n}:{}})}submit(e,t,n){return this.http.request({method:`POST`,path:`/whatsapp-templates/${encodeURIComponent(e)}/submit`,body:t,...n?{options:n}:{}})}sync(e,t){return this.http.request({method:`POST`,path:`/whatsapp-templates/sync`,body:e,...t?{options:t}:{}})}};function xe(e){return(globalThis.process?.env?.[e])?.trim()||void 0}var Z=class{messages;emails;whatsapp;whatsappTemplates;sms;webPush;constructor(e){let t=typeof e==`string`?{secret:e}:e,n=t.secret?.trim();if(!n)throw Error("Messaging: `secret` é obrigatório. Use a API key do projeto, por exemplo new Messaging({ secret: process.env.MESSAGING_API_KEY }).");let r=new oe({secret:n,baseUrl:(t.baseUrl??xe(`MESSAGING_BASE_URL`)??`https://api.messaging.rockfeller.com.br`).replace(/\/+$/,``),timeout:t.timeout??3e4,maxRetries:t.maxRetries??2,headers:t.headers??{},fetch:t.fetch??((e,t)=>globalThis.fetch(e,t))});this.messages=new K(r),this.emails=new j(this.messages),this.whatsapp=new Y(this.messages),this.whatsappTemplates=new X(r),this.sms=new q(this.messages),this.webPush=new J(this.messages,r)}};const Se=[`email`,`whatsapp`,`sms`,`webpush`],Ce=[`resend`,`unosend`,`twilio`,`meta`,`evolution`],we=[`normal`,`low`],Q=[`accepted`,`canceled`,`processing`,`sent`,`delivered`,`complained`,`bounced`,`suppressed`,`failed`],Te=[`pending`,`canceled`,`processing`,`sent`,`delivered`,`complained`,`bounced`,`suppressed`,`failed`],Ee=[`delivered`,`complained`],De=[`bounced`,`suppressed`,`failed`],$=[`canceled`,`delivered`,`complained`,`bounced`,`suppressed`,`failed`];function Oe(e){return $.includes(e)}const ke=[`sent`,`failed`,`unknown`],Ae=[`email.sent`,`email.delivered`,`email.delivery_delayed`,`email.opened`,`email.clicked`,`email.bounced`,`email.complained`,`email.failed`,`email.suppressed`,`whatsapp.sent`,`whatsapp.delivered`,`whatsapp.read`,`whatsapp.failed`,`sms.sent`,`sms.delivered`,`sms.failed`,`sms.bounced`,`webpush.sent`,`webpush.failed`,`webpush.expired`],je=[`MARKETING`,`UTILITY`],Me=[`DRAFT`,`SUBMITTING`,`SUBMISSION_UNKNOWN`,`PENDING`,`APPROVED`,`REJECTED`,`PAUSED`,`DISABLED`,`DELETED`];exports.ATTACHMENT_FILENAME_MAX_LENGTH=255,exports.ATTACHMENT_URL_MAX_LENGTH=o,exports.AuthenticationError=_,exports.BLOCKED_ATTACHMENT_EXTENSIONS=d,exports.ConnectionError=S,exports.DEFAULT_BASE_URL=`https://api.messaging.rockfeller.com.br`,exports.DEFAULT_MAX_RETRIES=2,exports.DEFAULT_TIMEOUT_MS=3e4,exports.EMAIL_ATTACHMENTS_MAX_COUNT=10,exports.EMAIL_ATTACHMENTS_MAX_TOTAL_BYTES=n,exports.EMAIL_ATTACHMENT_CONTENT_TYPES=u,exports.EMAIL_ATTACHMENT_DISPOSITIONS=c,exports.Emails=j,exports.MESSAGE_ATTACHMENT_SOURCES=s,exports.MESSAGE_ATTEMPT_OUTCOMES=ke,exports.MESSAGE_BATCH_MAX_SIZE=100,exports.MESSAGE_BODY_MAX_BYTES=262144,exports.MESSAGE_DELIVERED_STATUSES=Ee,exports.MESSAGE_DELIVERY_STATUSES=Te,exports.MESSAGE_DELIVERY_TERMINAL_STATUSES=$,exports.MESSAGE_EVENT_TYPES=Ae,exports.MESSAGE_JSON_MAX_BYTES=65536,exports.MESSAGE_LIST_DEFAULT_LIMIT=25,exports.MESSAGE_LIST_MAX_LIMIT=100,exports.MESSAGE_PRIORITIES=we,exports.MESSAGE_STATUSES=Q,exports.MESSAGE_SUBJECT_MAX_LENGTH=998,exports.MESSAGE_UNDELIVERED_STATUSES=De,exports.MESSAGING_ERROR_CODES=ee,exports.Messages=K,exports.MessagesPage=M,exports.Messaging=Z,exports.default=Z,exports.MessagingError=h,exports.NotFoundError=y,exports.PROVIDER_CHANNELS=Se,exports.PROVIDER_IDS=Ce,exports.PermissionError=v,exports.RateLimitError=b,exports.SMS_CONTENT_MAX_LENGTH=1600,exports.ServerError=x,exports.Sms=q,exports.TimeoutError=C,exports.VERSION=A,exports.ValidationError=g,exports.WHATSAPP_ATTACHMENTS_MAX_COUNT=1,exports.WHATSAPP_CAPTION_MAX_LENGTH=a,exports.WHATSAPP_IMAGE_MAX_BYTES=r,exports.WHATSAPP_MEDIA_KINDS=f,exports.WHATSAPP_MEDIA_MAX_BYTES=i,exports.WHATSAPP_MEDIA_MAX_BYTES_BY_KIND=m,exports.WHATSAPP_MEDIA_TYPES=p,exports.WHATSAPP_TEMPLATE_CATEGORIES=je,exports.WHATSAPP_TEMPLATE_STATUSES=Me,exports.WebPush=J,exports.WhatsApp=Y,exports.WhatsAppTemplates=X,exports.failure=k,exports.isMessagingError=w,exports.isTerminalDeliveryStatus=Oe,exports.success=O;
|
|
1
|
+
Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});const e=require("../version-79f-RqdP.cjs"),t=1048576,n=20*t,r=5*t,i=10*t,a=1024,o=2048,s=[`upload`,`url`],c=[`attachment`,`inline`],l=[`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/vnd.ms-powerpoint`,`application/vnd.openxmlformats-officedocument.presentationml.presentation`],u=[`application/pdf`,`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`text/csv`,`text/plain`,...l,`application/vnd.oasis.opendocument.text`,`application/vnd.oasis.opendocument.spreadsheet`,`application/zip`,`text/calendar`],d=/* @__PURE__ */ `apk.app.bat.cmd.com.cpl.dll.dmg.exe.hta.jar.js.jse.lnk.msi.msp.pif.ps1.reg.scr.sh.vb.vbe.vbs.wsf.wsh`.split(`.`),f=[`image`,`video`,`audio`,`document`],p={image:[`image/jpeg`,`image/png`],video:[`video/mp4`,`video/3gpp`],audio:[`audio/aac`,`audio/mp4`,`audio/mpeg`,`audio/amr`,`audio/ogg`],document:[`application/pdf`,...l,`text/plain`,`text/csv`,`application/zip`]},m={image:r,video:i,audio:i,document:i},ee=/* @__PURE__ */ `UNAUTHENTICATED.INVALID_API_KEY.ACTIVE_PROJECT_REQUIRED.PROJECT_ROLE_REQUIRED.VALIDATION_ERROR.FROM_DOMAIN_NOT_VERIFIED.SENDER_NOT_FOUND.WHATSAPP_TEMPLATE_NOT_FOUND.WHATSAPP_TEMPLATE_CONFLICT.WHATSAPP_TEMPLATE_PROVIDER_UNSUPPORTED.WHATSAPP_TEMPLATE_SUBMISSION_FAILED.WHATSAPP_TEMPLATE_SYNC_FAILED.WHATSAPP_TEMPLATE_INVALID_STATE.WHATSAPP_TEMPLATE_BODY_CONFLICT.ATTACHMENTS_NOT_SUPPORTED_FOR_CHANNEL.ATTACHMENTS_PROVIDER_TEMPLATE_CONFLICT.ATTACHMENT_INVALID.ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED.ATTACHMENT_TOO_LARGE.ATTACHMENTS_LIMIT_EXCEEDED.ATTACHMENT_URL_NOT_ALLOWED.WHATSAPP_CAPTION_INVALID.PAYLOAD_TOO_LARGE.ATTACHMENT_STORAGE_UNAVAILABLE.ATTACHMENT_STORAGE_NOT_CONFIGURED.ATTACHMENT_EXPIRED.MESSAGE_NOT_FOUND.SUPPRESSION_NOT_FOUND.MESSAGE_NOT_RETRYABLE.MESSAGE_CONTENT_EXPIRED.IDEMPOTENCY_KEY_REUSED.ROUTE_NOT_FOUND.INTERNAL_SERVER_ERROR.RATE_LIMIT_EXCEEDED.CONNECTION_ERROR.TIMEOUT.UNEXPECTED_RESPONSE`.split(`.`);var h=class extends Error{name=`MessagingError`;code;status;errors;constructor(e){super(e.message,{cause:e.cause}),this.code=e.code,this.status=e.status,this.errors=e.errors}get retryable(){return this.status===0||this.status===408||this.status===429||this.status>=500}toJSON(){return{name:this.name,code:this.code,message:this.message,status:this.status,...this.errors?{errors:this.errors}:{}}}},g=class extends h{name=`ValidationError`},_=class extends h{name=`AuthenticationError`},v=class extends h{name=`PermissionError`},y=class extends h{name=`NotFoundError`},b=class extends h{name=`RateLimitError`;retryAfter;constructor(e){super(e),this.retryAfter=e.retryAfter}},x=class extends h{name=`ServerError`},S=class extends h{name=`ConnectionError`},C=class extends h{name=`TimeoutError`};function w(e){return e instanceof h}function T(e){let t={code:e.code,message:e.message,status:e.status,...e.errors?{errors:e.errors}:{}};return e.status===429?new b({...t,...e.retryAfter===void 0?{}:{retryAfter:e.retryAfter}}):e.status>=500?new x(t):e.status===401?new _(t):e.status===403?new v(t):e.status===404?new y(t):e.status===400||e.status===422?new g(t):new h(t)}function te(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e))if(r!==void 0){if(Array.isArray(r))for(let e of r)t.append(n,String(e));else t.append(n,r instanceof Date?r.toISOString():String(r))}let n=t.toString();return n?`?${n}`:``}const E=8e3,ne=e=>new Promise(t=>setTimeout(t,e));function re(e,t){if(t!==void 0)return Math.min(t*1e3,E);let n=Math.min(500*2**e,E);return Math.round(n*(.5+Math.random()*.5))}function ie(e){if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t;let n=Date.parse(e);if(!Number.isNaN(n))return Math.max(0,Math.round((n-Date.now())/1e3))}function D(e){if(e.length===1)return e[0];let t=AbortSignal.any;if(t)return t(e);let n=new AbortController;for(let t of e){if(t.aborted){n.abort(t.reason);break}t.addEventListener(`abort`,()=>n.abort(t.reason),{once:!0})}return n.signal}function O(e){return{data:e,error:null}}function k(e){return{data:null,error:e}}const A=e.t,ae=`rockdev-messaging-node/${A}`;var oe=class{config;constructor(e){this.config=e}async request(e){let t=`${this.config.baseUrl}/v1${e.path}${e.query?te(e.query):``}`,n=e.method===`GET`||e.idempotencyKey!==void 0?this.config.maxRetries:0,r;for(let i=0;i<=n;i+=1){let a=await this.attempt(t,e);if(a.error===null)return a;if(r=a.error,!a.error.retryable||e.options?.signal?.aborted||i===n)break;await ne(re(i,a.error.retryAfter))}return k(r)}async attempt(e,t){let n=t.options?.timeout??this.config.timeout,r=new AbortController,i=setTimeout(()=>r.abort(),n),a=[r.signal];t.options?.signal&&a.push(t.options.signal);let o;try{o=await this.config.fetch(e,{method:t.method,headers:this.headers(t),signal:D(a),...t.body===void 0?{}:{body:JSON.stringify(t.body)}})}catch(e){return t.options?.signal?.aborted?k(new h({code:`CONNECTION_ERROR`,message:`The request was aborted by the caller.`,status:0,cause:e})):r.signal.aborted?k(new C({code:`TIMEOUT`,message:`The request did not complete within ${n}ms.`,status:0,cause:e})):k(new S({code:`CONNECTION_ERROR`,message:e instanceof Error?e.message:`The request could not reach the Messaging API.`,status:0,cause:e}))}finally{clearTimeout(i)}return this.parse(o)}headers(e){let t=e=>Object.fromEntries(Object.entries(e).filter(([e])=>e.toLowerCase()!==`idempotency-key`));return{accept:`application/json`,authorization:`Bearer ${this.config.secret}`,"user-agent":ae,...e.body===void 0?{}:{"content-type":`application/json`},...t(this.config.headers),...t(e.options?.headers??{}),...e.idempotencyKey===void 0?{}:{"idempotency-key":e.idempotencyKey}}}async parse(e){let t=await e.text().catch(()=>``),n;try{n=t?JSON.parse(t):void 0}catch{n=void 0}if(!e.ok){let t=ie(e.headers.get(`retry-after`));return k(T({code:n?.code??`INTERNAL_SERVER_ERROR`,message:n?.message??`The Messaging API responded with ${e.status}.`,status:e.status,...n?.errors?{errors:n.errors}:{},...t===void 0?{}:{retryAfter:t}}))}return!n||n.data===void 0?k(new h({code:`UNEXPECTED_RESPONSE`,message:`The Messaging API responded without the expected body.`,status:e.status})):O(n.data)}},j=class{messages;constructor(e){this.messages=e}async send(e,t){let{to:n,...r}=e;return this.messages.send({...r,to:typeof n==`string`?{email:n}:n},t)}async batch(e,t){return this.messages.batch(e.map(({to:e,...t})=>({...t,to:typeof e==`string`?{email:e}:e})),t)}},M=class e{fetchPage;messages;nextCursor;constructor(e,t){this.fetchPage=t,this.messages=e.messages,this.nextCursor=e.nextCursor}get hasMore(){return this.nextCursor!==null}async next(){return this.nextCursor===null?{data:new e({messages:[],nextCursor:null},this.fetchPage),error:null}:this.fetchPage(this.nextCursor)}async*[Symbol.asyncIterator](){let e=this;for(;;){for(let t of e.messages)yield t;if(!e.hasMore)return;let{data:t,error:n}=await e.next();if(n)throw n;e=t}}};function N(e){if(e!==void 0)return e instanceof Date?e.toISOString():e}function se(e){return{status:e.status,channel:e.channel,to:e.to,search:e.search,scheduled:e.scheduled,createdAfter:N(e.createdAfter),createdBefore:N(e.createdBefore),limit:e.limit,cursor:e.cursor}}const P=24576;function ce(e){if(typeof e.toBase64==`function`)return e.toBase64();let t=globalThis.Buffer;if(t)return t.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`);let n=``;for(let t=0;t<e.length;t+=P){let r=e.subarray(t,t+P),i=``;for(let e=0;e<r.length;e+=1)i+=String.fromCharCode(r[e]);n+=btoa(i)}return n}function le(e){let t=e.endsWith(`==`)?2:+!!e.endsWith(`=`);return e.length/4*3-t}function ue(e){return typeof Blob<`u`&&e instanceof Blob}function de(e){return`email`in e&&e.email!==void 0?`email`:`whatsapp`in e&&e.whatsapp!==void 0?`whatsapp`:`sms`in e&&e.sms!==void 0?`sms`:`webpush`}function fe(e){return typeof e==`string`?e.includes(`@`)?{email:e}:{whatsapp:e}:e}function F(e){let t=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(e);if(!t)return null;let[n,r]=[Number(t[1]),Number(t[2])];return n===0||n===10||n===127||n===100&&r>=64&&r<=127||n===169&&r===254||n===172&&r>=16&&r<=31||n===192&&r===168||n===198&&(r===18||r===19)||n>=224}function I(e){if(!e.startsWith(`[`))return null;let t=e.slice(1,-1).toLowerCase(),n=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(t);return n?.[1]?F(n[1])??!0:t===`::`||t===`::1`||t.startsWith(`::ffff:`)||/^f[cd]/.test(t)||/^fe[89ab]/.test(t)||t.startsWith(`ff`)}function L(e){try{return new URL(e)}catch{return null}}const R={pdf:`application/pdf`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,csv:`text/csv`,txt:`text/plain`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,xls:`application/vnd.ms-excel`,xlsx:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,ppt:`application/vnd.ms-powerpoint`,pptx:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,odt:`application/vnd.oasis.opendocument.text`,ods:`application/vnd.oasis.opendocument.spreadsheet`,zip:`application/zip`,ics:`text/calendar`,mp4:`video/mp4`,"3gp":`video/3gpp`,aac:`audio/aac`,m4a:`audio/mp4`,mp3:`audio/mpeg`,amr:`audio/amr`,ogg:`audio/ogg`,opus:`audio/ogg`};function z(e){return(e.split(`;`)[0]??``).trim().toLowerCase()}function B(e){let t=e.lastIndexOf(`.`);return t<=0||t===e.length-1?``:e.slice(t+1).toLowerCase()}function V(e){let t=z(e);for(let e of f)if(p[e].includes(t))return e;return null}function pe(e){return R[B(e.trim())]}const me=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*(\s*;.*)?$/i,he=/^[A-Za-z0-9+/]*={0,2}$/,ge=/[/\\\u0000-\u001f\u007f]/;var H=class{code;message;detail;constructor(e,t,n){this.code=e,this.message=t,this.detail=n}};function U(e,t,n=t){throw new H(e,t,n)}function _e(e,t){let n=e=>U(`ATTACHMENT_URL_NOT_ALLOWED`,`The attachment URL is not allowed: ${e}.`,`${t}.url ${e}`);e.length>2048&&n(`must be at most ${o} characters long`);let r=L(e)??n(`must be a valid URL`);r.protocol!==`https:`&&n(`must use https`),(r.username||r.password)&&n(`must not contain credentials`),r.port&&r.port!==`443`&&n(`must use the default port`);let i=r.hostname.toLowerCase().replace(/\.$/,``);(i===`localhost`||i.endsWith(`.localhost`)||i.endsWith(`.local`)||i.endsWith(`.internal`))&&n(`must not point to a local host`),!i.startsWith(`[`)&&!i.includes(`.`)&&n(`must use a fully qualified host name`),(F(i)||I(i))&&n(`must not point to a private address`)}async function ve(e,t){let n=e=>U(`ATTACHMENT_INVALID`,`The attachment is invalid.`,e);typeof e==`object`&&e||n(`${t} must be an object`);let{filename:r,disposition:i,contentId:a}=e;(typeof r!=`string`||r.trim()===``)&&n(`${t}.filename is required`),r.length>255&&n(`${t}.filename must be at most 255 characters long`),ge.test(r)&&n(`${t}.filename must not contain path separators or control characters`);let o=`url`in e&&e.url!==void 0;o===(`content`in e&&e.content!==void 0)&&n(`${t} must have exactly one of url or content`),i!==void 0&&!c.includes(i)&&n(`${t}.disposition must be one of attachment, inline`),a!==void 0&&(typeof a!=`string`||a===``||a.length>255)&&n(`${t}.contentId must be a non-empty string of at most 255 characters`),i===`inline`&&(a??``).trim()===``&&n(`${t}.contentId is required for inline attachments`);let s={...i===void 0?{}:{disposition:i},...a===void 0?{}:{contentId:a}},l=e=>e===void 0||e.trim()===``?n(`${t}.contentType is required`):(me.test(e)||n(`${t}.contentType must be a type/subtype MIME type`),e);if(o){let{url:i}=e;return typeof i==`string`?(_e(i,t),{body:{filename:r,contentType:l(e.contentType),url:i,...s},size:null}):n(`${t}.url must be a string`)}let{content:u}=e,d,f,p;if(typeof u==`string`)u.length%4==0&&he.test(u)||n(`${t}.content must be valid base64`),d=u,f=le(u);else{let e;if(u instanceof Uint8Array)e=u;else if(u instanceof ArrayBuffer)e=new Uint8Array(u);else if(ArrayBuffer.isView(u))e=new Uint8Array(u.buffer,u.byteOffset,u.byteLength);else if(ue(u))p=u.type||void 0,e=new Uint8Array(await u.arrayBuffer());else return n(`${t}.content must be a Uint8Array, ArrayBuffer, Blob or base64 string`);d=ce(e),f=e.byteLength}return{body:{filename:r,contentType:l(e.contentType??p??pe(r)),content:d,...s},size:f}}function ye(e,t,r){if(e===`email`){t.length>10&&U(`ATTACHMENTS_LIMIT_EXCEEDED`,`An email accepts at most 10 attachments.`);let e=0;t.forEach(({body:t,size:n},r)=>{let i=`attachments.${r}`;u.includes(z(t.contentType))||U(`ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED`,`The attachment content type is not allowed for email.`,`${i}.contentType ${z(t.contentType)} is not allowed`),d.includes(B(t.filename.trim()))&&U(`ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED`,`The attachment file extension is not allowed.`,`${i}.filename has a blocked extension`),e+=n??0}),e>20971520&&U(`ATTACHMENT_TOO_LARGE`,`Email attachments must add up to at most ${n} bytes.`);return}t.length>1&&U(`ATTACHMENTS_LIMIT_EXCEEDED`,`A WhatsApp message accepts at most 1 attachment.`);let[i]=t;if(!i)return;let o=`attachments.0`;(i.body.disposition!==void 0||i.body.contentId!==void 0)&&U(`ATTACHMENT_INVALID`,`The attachment is invalid.`,`${o}.disposition and contentId are email-only`);let s=V(i.body.contentType);s||U(`ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED`,`The attachment content type is not allowed for WhatsApp.`,`${o}.contentType ${z(i.body.contentType)} is not allowed`);let c=m[s];i.size!==null&&i.size>c&&U(`ATTACHMENT_TOO_LARGE`,`WhatsApp ${s} attachments must be at most ${c} bytes.`),r!==void 0&&s===`audio`&&U(`WHATSAPP_CAPTION_INVALID`,`WhatsApp audio does not accept a caption.`,`content must be empty for audio attachments`),r!==void 0&&r.length>1024&&U(`WHATSAPP_CAPTION_INVALID`,`A WhatsApp caption must be at most ${a} characters long.`,`content must be at most ${a} characters long`)}async function be(e,t,n=``){try{let n=de(e.to);n!==`email`&&n!==`whatsapp`&&U(`ATTACHMENTS_NOT_SUPPORTED_FOR_CHANNEL`,`Attachments are not supported for the ${n} channel.`),e.providerTemplate!==void 0&&U(`ATTACHMENTS_PROVIDER_TEMPLATE_CONFLICT`,`Attachments cannot be combined with providerTemplate.`),Array.isArray(t)||U(`ATTACHMENT_INVALID`,`The attachment is invalid.`,`attachments must be an array`);let r=[];for(let[e,n]of t.entries())r.push(await ve(n,`attachments.${e}`));return ye(n,r,e.content),O(r.map(({body:e})=>e))}catch(e){if(!(e instanceof H))throw e;return k(new g({code:e.code,message:e.message,status:400,errors:[`${n}${e.detail}`]}))}}function xe(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}async function W(e,t=``){let{to:n,sendAt:r,attachments:i,...a}=e,{idempotencyKey:o,...s}=a,c=fe(n),l;if(i!==void 0&&i.length>0){let e=await be({to:c,content:s.content,providerTemplate:s.providerTemplate},i,t);if(e.error)return k(e.error);l=e.data}return O(xe({...s,to:c,sendAt:N(r),attachments:l}))}var G=class{http;constructor(e){this.http=e}async send(e,t){let n=await W(e);return n.error?k(n.error):this.http.request({method:`POST`,path:`/messages`,body:n.data,...e.idempotencyKey===void 0?{}:{idempotencyKey:e.idempotencyKey},...t?{options:t}:{}})}async batch(e,t){let{idempotencyKey:n,...r}=t??{},i=[];for(let[t,n]of e.entries()){let e=await W(n,`${t}.`);if(e.error)return k(e.error);i.push(e.data)}return this.http.request({method:`POST`,path:`/messages/batch`,body:i,...n===void 0?{}:{idempotencyKey:n},...t?{options:r}:{}})}async create(e,t){return this.send(e,t)}async retry(e,t,n){return this.http.request({method:`POST`,path:`/messages/${encodeURIComponent(e)}/retry`,idempotencyKey:t.idempotencyKey,...n?{options:n}:{}})}async get(e,t){return this.http.request({method:`GET`,path:`/messages/${encodeURIComponent(e)}`,...t?{options:t}:{}})}async retrieve(e,t){return this.get(e,t)}async list(e={},t){let{data:n,error:r}=await this.http.request({method:`GET`,path:`/messages`,query:se(e),...t?{options:t}:{}});return r?{data:null,error:r}:{data:new M(n,n=>this.list({...e,cursor:n},t)),error:null}}},K=class{messages;constructor(e){this.messages=e}async send(e,t){let{to:n,...r}=e;return this.messages.send({...r,to:typeof n==`string`?{sms:n}:n},t)}async batch(e,t){return this.messages.batch(e.map(({to:e,...t})=>({...t,to:typeof e==`string`?{sms:e}:e})),t)}},q=class{http;constructor(e){this.http=e}create(e,t){return this.http.request({method:`POST`,path:`/suppressions`,body:e,...t?{options:t}:{}})}batch(e,t){return this.http.request({method:`POST`,path:`/suppressions/batch`,body:e,...t?{options:t}:{}})}get(e,t){return this.http.request({method:`GET`,path:`/suppressions/${encodeURIComponent(e)}`,...t?{options:t}:{}})}list(e={},t){return this.http.request({method:`GET`,path:`/suppressions`,query:{email:e.email,reason:e.reason,limit:e.limit,cursor:e.cursor},...t?{options:t}:{}})}delete(e,t){return this.http.request({method:`DELETE`,path:`/suppressions/${encodeURIComponent(e)}`,...t?{options:t}:{}})}batchDelete(e,t){return this.http.request({method:`POST`,path:`/suppressions/batch/delete`,body:e,...t?{options:t}:{}})}},J=class{messages;http;constructor(e,t){this.messages=e,this.http=t}async createSubscriptionToken(e,t){return this.http.request({method:`POST`,path:`/webpush/subscription-tokens`,body:e,...t?{options:t}:{}})}async send(e,t){let{to:n,...r}=e;return this.messages.send({...r,to:{webpush:typeof n==`string`?{recipientId:n}:n}},t)}async batch(e,t){return this.messages.batch(e.map(({to:e,...t})=>({...t,to:{webpush:typeof e==`string`?{recipientId:e}:e}})),t)}},Y=class{messages;constructor(e){this.messages=e}async send(e,t){let{to:n,...r}=e;return this.messages.send({...r,to:typeof n==`string`?{whatsapp:n}:n},t)}async batch(e,t){return this.messages.batch(e.map(({to:e,...t})=>({...t,to:typeof e==`string`?{whatsapp:e}:e})),t)}},X=class{http;constructor(e){this.http=e}list(e={},t){return this.http.request({method:`GET`,path:`/whatsapp-templates`,query:{senderId:e.senderId},...t?{options:t}:{}})}get(e,t){return this.http.request({method:`GET`,path:`/whatsapp-templates/${encodeURIComponent(e)}`,...t?{options:t}:{}})}create(e,t){return this.http.request({method:`POST`,path:`/whatsapp-templates`,body:e,...t?{options:t}:{}})}update(e,t,n){return this.http.request({method:`PATCH`,path:`/whatsapp-templates/${encodeURIComponent(e)}`,body:t,...n?{options:n}:{}})}submit(e,t,n){return this.http.request({method:`POST`,path:`/whatsapp-templates/${encodeURIComponent(e)}/submit`,body:t,...n?{options:n}:{}})}sync(e,t){return this.http.request({method:`POST`,path:`/whatsapp-templates/sync`,body:e,...t?{options:t}:{}})}};function Se(e){return(globalThis.process?.env?.[e])?.trim()||void 0}var Z=class{messages;emails;whatsapp;whatsappTemplates;sms;webPush;suppressions;constructor(e){let t=typeof e==`string`?{secret:e}:e,n=t.secret?.trim();if(!n)throw Error("Messaging: `secret` é obrigatório. Use a API key do projeto, por exemplo new Messaging({ secret: process.env.MESSAGING_API_KEY }).");let r=new oe({secret:n,baseUrl:(t.baseUrl??Se(`MESSAGING_BASE_URL`)??`https://api.messaging.rockfeller.com.br`).replace(/\/+$/,``),timeout:t.timeout??3e4,maxRetries:t.maxRetries??2,headers:t.headers??{},fetch:t.fetch??((e,t)=>globalThis.fetch(e,t))});this.messages=new G(r),this.emails=new j(this.messages),this.whatsapp=new Y(this.messages),this.whatsappTemplates=new X(r),this.sms=new K(this.messages),this.webPush=new J(this.messages,r),this.suppressions=new q(r)}};const Ce=[`email`,`whatsapp`,`sms`,`webpush`],we=[`resend`,`unosend`,`twilio`,`meta`,`evolution`],Te=[`normal`,`low`],Ee=[`accepted`,`canceled`,`processing`,`sent`,`delivered`,`complained`,`bounced`,`suppressed`,`failed`],De=[`pending`,`canceled`,`processing`,`sent`,`delivered`,`complained`,`bounced`,`suppressed`,`failed`],Oe=[`delivered`,`complained`],Q=[`bounced`,`suppressed`,`failed`],$=[`canceled`,`delivered`,`complained`,`bounced`,`suppressed`,`failed`];function ke(e){return $.includes(e)}const Ae=[`sent`,`failed`,`unknown`],je=[`email.sent`,`email.delivered`,`email.delivery_delayed`,`email.opened`,`email.clicked`,`email.bounced`,`email.complained`,`email.failed`,`email.suppressed`,`whatsapp.sent`,`whatsapp.delivered`,`whatsapp.read`,`whatsapp.failed`,`sms.sent`,`sms.delivered`,`sms.failed`,`sms.bounced`,`webpush.sent`,`webpush.failed`,`webpush.expired`],Me=[`manual`,`bounce`,`complaint`,`provider_suppressed`],Ne=[`api`,`dashboard`,`automatic`],Pe=[`MARKETING`,`UTILITY`,`AUTHENTICATION`],Fe=[`DRAFT`,`SUBMITTING`,`SUBMISSION_UNKNOWN`,`PENDING`,`APPROVED`,`REJECTED`,`PAUSED`,`DISABLED`,`DELETED`];exports.ATTACHMENT_FILENAME_MAX_LENGTH=255,exports.ATTACHMENT_URL_MAX_LENGTH=o,exports.AuthenticationError=_,exports.BLOCKED_ATTACHMENT_EXTENSIONS=d,exports.ConnectionError=S,exports.DEFAULT_BASE_URL=`https://api.messaging.rockfeller.com.br`,exports.DEFAULT_MAX_RETRIES=2,exports.DEFAULT_TIMEOUT_MS=3e4,exports.EMAIL_ATTACHMENTS_MAX_COUNT=10,exports.EMAIL_ATTACHMENTS_MAX_TOTAL_BYTES=n,exports.EMAIL_ATTACHMENT_CONTENT_TYPES=u,exports.EMAIL_ATTACHMENT_DISPOSITIONS=c,exports.Emails=j,exports.MESSAGE_ATTACHMENT_SOURCES=s,exports.MESSAGE_ATTEMPT_OUTCOMES=Ae,exports.MESSAGE_BATCH_MAX_SIZE=100,exports.MESSAGE_BODY_MAX_BYTES=262144,exports.MESSAGE_DELIVERED_STATUSES=Oe,exports.MESSAGE_DELIVERY_STATUSES=De,exports.MESSAGE_DELIVERY_TERMINAL_STATUSES=$,exports.MESSAGE_EVENT_TYPES=je,exports.MESSAGE_JSON_MAX_BYTES=65536,exports.MESSAGE_LIST_DEFAULT_LIMIT=25,exports.MESSAGE_LIST_MAX_LIMIT=100,exports.MESSAGE_PRIORITIES=Te,exports.MESSAGE_STATUSES=Ee,exports.MESSAGE_SUBJECT_MAX_LENGTH=998,exports.MESSAGE_UNDELIVERED_STATUSES=Q,exports.MESSAGING_ERROR_CODES=ee,exports.Messages=G,exports.MessagesPage=M,exports.Messaging=Z,exports.default=Z,exports.MessagingError=h,exports.NotFoundError=y,exports.PROVIDER_CHANNELS=Ce,exports.PROVIDER_IDS=we,exports.PermissionError=v,exports.RECIPIENT_SUPPRESSED_FAILURE_CODE=`RECIPIENT_SUPPRESSED`,exports.RateLimitError=b,exports.SMS_CONTENT_MAX_LENGTH=1600,exports.SUPPRESSION_BATCH_MAX_SIZE=100,exports.SUPPRESSION_LIST_DEFAULT_LIMIT=50,exports.SUPPRESSION_LIST_MAX_LIMIT=100,exports.SUPPRESSION_NOTE_MAX_LENGTH=500,exports.SUPPRESSION_REASONS=Me,exports.SUPPRESSION_SOURCES=Ne,exports.ServerError=x,exports.Sms=K,exports.Suppressions=q,exports.TimeoutError=C,exports.VERSION=A,exports.ValidationError=g,exports.WHATSAPP_ATTACHMENTS_MAX_COUNT=1,exports.WHATSAPP_CAPTION_MAX_LENGTH=a,exports.WHATSAPP_IMAGE_MAX_BYTES=r,exports.WHATSAPP_MEDIA_KINDS=f,exports.WHATSAPP_MEDIA_MAX_BYTES=i,exports.WHATSAPP_MEDIA_MAX_BYTES_BY_KIND=m,exports.WHATSAPP_MEDIA_TYPES=p,exports.WHATSAPP_TEMPLATE_CATEGORIES=Pe,exports.WHATSAPP_TEMPLATE_STATUSES=Fe,exports.WebPush=J,exports.WhatsApp=Y,exports.WhatsAppTemplates=X,exports.failure=k,exports.isMessagingError=w,exports.isTerminalDeliveryStatus=ke,exports.success=O;
|
|
@@ -83,7 +83,7 @@ type QueryValue = string | number | boolean | Date | ReadonlyArray<string | numb
|
|
|
83
83
|
* `code` é mais seguro do que ler a `message`: a frase muda, o código é
|
|
84
84
|
* contrato.
|
|
85
85
|
*/
|
|
86
|
-
export declare const MESSAGING_ERROR_CODES: readonly ["UNAUTHENTICATED", "INVALID_API_KEY", "ACTIVE_PROJECT_REQUIRED", "PROJECT_ROLE_REQUIRED", "VALIDATION_ERROR", "FROM_DOMAIN_NOT_VERIFIED", "SENDER_NOT_FOUND", "WHATSAPP_TEMPLATE_NOT_FOUND", "WHATSAPP_TEMPLATE_CONFLICT", "WHATSAPP_TEMPLATE_PROVIDER_UNSUPPORTED", "WHATSAPP_TEMPLATE_SUBMISSION_FAILED", "WHATSAPP_TEMPLATE_SYNC_FAILED", "WHATSAPP_TEMPLATE_INVALID_STATE", "WHATSAPP_TEMPLATE_BODY_CONFLICT", "ATTACHMENTS_NOT_SUPPORTED_FOR_CHANNEL", "ATTACHMENTS_PROVIDER_TEMPLATE_CONFLICT", "ATTACHMENT_INVALID", "ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED", "ATTACHMENT_TOO_LARGE", "ATTACHMENTS_LIMIT_EXCEEDED", "ATTACHMENT_URL_NOT_ALLOWED", "WHATSAPP_CAPTION_INVALID", "PAYLOAD_TOO_LARGE", "ATTACHMENT_STORAGE_UNAVAILABLE", "ATTACHMENT_STORAGE_NOT_CONFIGURED", "ATTACHMENT_EXPIRED", "MESSAGE_NOT_FOUND", "MESSAGE_NOT_RETRYABLE", "MESSAGE_CONTENT_EXPIRED", "IDEMPOTENCY_KEY_REUSED", "ROUTE_NOT_FOUND", "INTERNAL_SERVER_ERROR", "RATE_LIMIT_EXCEEDED", "CONNECTION_ERROR", "TIMEOUT", "UNEXPECTED_RESPONSE"];
|
|
86
|
+
export declare const MESSAGING_ERROR_CODES: readonly ["UNAUTHENTICATED", "INVALID_API_KEY", "ACTIVE_PROJECT_REQUIRED", "PROJECT_ROLE_REQUIRED", "VALIDATION_ERROR", "FROM_DOMAIN_NOT_VERIFIED", "SENDER_NOT_FOUND", "WHATSAPP_TEMPLATE_NOT_FOUND", "WHATSAPP_TEMPLATE_CONFLICT", "WHATSAPP_TEMPLATE_PROVIDER_UNSUPPORTED", "WHATSAPP_TEMPLATE_SUBMISSION_FAILED", "WHATSAPP_TEMPLATE_SYNC_FAILED", "WHATSAPP_TEMPLATE_INVALID_STATE", "WHATSAPP_TEMPLATE_BODY_CONFLICT", "ATTACHMENTS_NOT_SUPPORTED_FOR_CHANNEL", "ATTACHMENTS_PROVIDER_TEMPLATE_CONFLICT", "ATTACHMENT_INVALID", "ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED", "ATTACHMENT_TOO_LARGE", "ATTACHMENTS_LIMIT_EXCEEDED", "ATTACHMENT_URL_NOT_ALLOWED", "WHATSAPP_CAPTION_INVALID", "PAYLOAD_TOO_LARGE", "ATTACHMENT_STORAGE_UNAVAILABLE", "ATTACHMENT_STORAGE_NOT_CONFIGURED", "ATTACHMENT_EXPIRED", "MESSAGE_NOT_FOUND", "SUPPRESSION_NOT_FOUND", "MESSAGE_NOT_RETRYABLE", "MESSAGE_CONTENT_EXPIRED", "IDEMPOTENCY_KEY_REUSED", "ROUTE_NOT_FOUND", "INTERNAL_SERVER_ERROR", "RATE_LIMIT_EXCEEDED", "CONNECTION_ERROR", "TIMEOUT", "UNEXPECTED_RESPONSE"];
|
|
87
87
|
/** {@link MESSAGING_ERROR_CODES} */
|
|
88
88
|
type MessagingErrorCode = (typeof MESSAGING_ERROR_CODES)[number];
|
|
89
89
|
/** Dados que acompanham toda falha. */
|
|
@@ -143,7 +143,7 @@ export declare class MessagingError extends Error {
|
|
|
143
143
|
toJSON(): {
|
|
144
144
|
errors?: unknown[];
|
|
145
145
|
name: string;
|
|
146
|
-
code: "UNAUTHENTICATED" | "INVALID_API_KEY" | "ACTIVE_PROJECT_REQUIRED" | "PROJECT_ROLE_REQUIRED" | "VALIDATION_ERROR" | "FROM_DOMAIN_NOT_VERIFIED" | "SENDER_NOT_FOUND" | "WHATSAPP_TEMPLATE_NOT_FOUND" | "WHATSAPP_TEMPLATE_CONFLICT" | "WHATSAPP_TEMPLATE_PROVIDER_UNSUPPORTED" | "WHATSAPP_TEMPLATE_SUBMISSION_FAILED" | "WHATSAPP_TEMPLATE_SYNC_FAILED" | "WHATSAPP_TEMPLATE_INVALID_STATE" | "WHATSAPP_TEMPLATE_BODY_CONFLICT" | "ATTACHMENTS_NOT_SUPPORTED_FOR_CHANNEL" | "ATTACHMENTS_PROVIDER_TEMPLATE_CONFLICT" | "ATTACHMENT_INVALID" | "ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED" | "ATTACHMENT_TOO_LARGE" | "ATTACHMENTS_LIMIT_EXCEEDED" | "ATTACHMENT_URL_NOT_ALLOWED" | "WHATSAPP_CAPTION_INVALID" | "PAYLOAD_TOO_LARGE" | "ATTACHMENT_STORAGE_UNAVAILABLE" | "ATTACHMENT_STORAGE_NOT_CONFIGURED" | "ATTACHMENT_EXPIRED" | "MESSAGE_NOT_FOUND" | "MESSAGE_NOT_RETRYABLE" | "MESSAGE_CONTENT_EXPIRED" | "IDEMPOTENCY_KEY_REUSED" | "ROUTE_NOT_FOUND" | "INTERNAL_SERVER_ERROR" | "RATE_LIMIT_EXCEEDED" | "CONNECTION_ERROR" | "TIMEOUT" | "UNEXPECTED_RESPONSE" | (string & Record<never, never>);
|
|
146
|
+
code: "UNAUTHENTICATED" | "INVALID_API_KEY" | "ACTIVE_PROJECT_REQUIRED" | "PROJECT_ROLE_REQUIRED" | "VALIDATION_ERROR" | "FROM_DOMAIN_NOT_VERIFIED" | "SENDER_NOT_FOUND" | "WHATSAPP_TEMPLATE_NOT_FOUND" | "WHATSAPP_TEMPLATE_CONFLICT" | "WHATSAPP_TEMPLATE_PROVIDER_UNSUPPORTED" | "WHATSAPP_TEMPLATE_SUBMISSION_FAILED" | "WHATSAPP_TEMPLATE_SYNC_FAILED" | "WHATSAPP_TEMPLATE_INVALID_STATE" | "WHATSAPP_TEMPLATE_BODY_CONFLICT" | "ATTACHMENTS_NOT_SUPPORTED_FOR_CHANNEL" | "ATTACHMENTS_PROVIDER_TEMPLATE_CONFLICT" | "ATTACHMENT_INVALID" | "ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED" | "ATTACHMENT_TOO_LARGE" | "ATTACHMENTS_LIMIT_EXCEEDED" | "ATTACHMENT_URL_NOT_ALLOWED" | "WHATSAPP_CAPTION_INVALID" | "PAYLOAD_TOO_LARGE" | "ATTACHMENT_STORAGE_UNAVAILABLE" | "ATTACHMENT_STORAGE_NOT_CONFIGURED" | "ATTACHMENT_EXPIRED" | "MESSAGE_NOT_FOUND" | "SUPPRESSION_NOT_FOUND" | "MESSAGE_NOT_RETRYABLE" | "MESSAGE_CONTENT_EXPIRED" | "IDEMPOTENCY_KEY_REUSED" | "ROUTE_NOT_FOUND" | "INTERNAL_SERVER_ERROR" | "RATE_LIMIT_EXCEEDED" | "CONNECTION_ERROR" | "TIMEOUT" | "UNEXPECTED_RESPONSE" | (string & Record<never, never>);
|
|
147
147
|
message: string;
|
|
148
148
|
status: number;
|
|
149
149
|
};
|
|
@@ -224,7 +224,7 @@ interface HttpClientConfig {
|
|
|
224
224
|
fetch: FetchLike;
|
|
225
225
|
}
|
|
226
226
|
interface RequestInput {
|
|
227
|
-
method: 'GET' | 'POST' | 'PATCH';
|
|
227
|
+
method: 'GET' | 'POST' | 'PATCH' | 'DELETE';
|
|
228
228
|
path: string;
|
|
229
229
|
query?: Record<string, QueryValue>;
|
|
230
230
|
body?: unknown;
|
|
@@ -1483,6 +1483,111 @@ export declare class Sms {
|
|
|
1483
1483
|
/** Envia de 1 a 100 SMS em uma única requisição atômica. */
|
|
1484
1484
|
batch(options: BatchSendSmsInput[], requestOptions?: BatchRequestOptions): Promise<Result<AcceptedBatchMessage[]>>;
|
|
1485
1485
|
}
|
|
1486
|
+
/**
|
|
1487
|
+
* Por que o endereço entrou na lista de supressão.
|
|
1488
|
+
*
|
|
1489
|
+
* - `manual`: alguém adicionou pela API ou pela dashboard.
|
|
1490
|
+
* - `bounce`: o provedor disse que o endereço não existe (bounce permanente).
|
|
1491
|
+
* - `complaint`: o destinatário marcou um e-mail como spam.
|
|
1492
|
+
* - `provider_suppressed`: o provedor recusou por histórico ruim do endereço.
|
|
1493
|
+
*/
|
|
1494
|
+
export declare const SUPPRESSION_REASONS: readonly ["manual", "bounce", "complaint", "provider_suppressed"];
|
|
1495
|
+
type SuppressionReason = (typeof SUPPRESSION_REASONS)[number];
|
|
1496
|
+
/** Por onde a entrada chegou: API, dashboard ou evento do provedor. */
|
|
1497
|
+
export declare const SUPPRESSION_SOURCES: readonly ["api", "dashboard", "automatic"];
|
|
1498
|
+
type SuppressionSource = (typeof SUPPRESSION_SOURCES)[number];
|
|
1499
|
+
/**
|
|
1500
|
+
* `failureCode` da entrega bloqueada pela lista do projeto.
|
|
1501
|
+
*
|
|
1502
|
+
* @remarks
|
|
1503
|
+
* O estado é `suppressed`, o mesmo da supressão feita pelo provedor; é este
|
|
1504
|
+
* código que separa "a plataforma bloqueou" de "o provedor recusou".
|
|
1505
|
+
*/
|
|
1506
|
+
export declare const RECIPIENT_SUPPRESSED_FAILURE_CODE = "RECIPIENT_SUPPRESSED";
|
|
1507
|
+
/** Entrada da lista de supressão. O e-mail vem sempre em minúsculas. */
|
|
1508
|
+
interface Suppression {
|
|
1509
|
+
id: string;
|
|
1510
|
+
email: string;
|
|
1511
|
+
reason: SuppressionReason | LooseString;
|
|
1512
|
+
source: SuppressionSource | LooseString;
|
|
1513
|
+
note: string | null;
|
|
1514
|
+
/** Mensagem cujo evento do provedor colocou o endereço na lista (só automáticas). */
|
|
1515
|
+
messageId: string | null;
|
|
1516
|
+
createdAt: IsoDateTime;
|
|
1517
|
+
}
|
|
1518
|
+
interface DeletedSuppression extends Suppression {
|
|
1519
|
+
deleted: true;
|
|
1520
|
+
}
|
|
1521
|
+
interface CreateSuppressionOptions {
|
|
1522
|
+
email: string;
|
|
1523
|
+
/** Anotação livre, até 500 caracteres. */
|
|
1524
|
+
note?: string;
|
|
1525
|
+
}
|
|
1526
|
+
interface BatchCreateSuppressionsOptions {
|
|
1527
|
+
/** De 1 a 100 endereços. Um inválido recusa o lote inteiro. */
|
|
1528
|
+
emails: string[];
|
|
1529
|
+
/** Aplicada a todas as entradas novas do lote. */
|
|
1530
|
+
note?: string;
|
|
1531
|
+
}
|
|
1532
|
+
interface BatchCreateSuppressionsPayload {
|
|
1533
|
+
/** Entraram agora, na ordem enviada. */
|
|
1534
|
+
created: Suppression[];
|
|
1535
|
+
/** Já estavam na lista e voltam como estavam. */
|
|
1536
|
+
existing: Suppression[];
|
|
1537
|
+
}
|
|
1538
|
+
/** Exatamente um dos dois, de 1 a 100 itens. */
|
|
1539
|
+
type BatchDeleteSuppressionsOptions = {
|
|
1540
|
+
emails: string[];
|
|
1541
|
+
ids?: never;
|
|
1542
|
+
} | {
|
|
1543
|
+
ids: string[];
|
|
1544
|
+
emails?: never;
|
|
1545
|
+
};
|
|
1546
|
+
interface BatchDeleteSuppressionsPayload {
|
|
1547
|
+
deleted: Suppression[];
|
|
1548
|
+
/** Ids ou e-mails pedidos que não estavam na lista. */
|
|
1549
|
+
notFound: string[];
|
|
1550
|
+
}
|
|
1551
|
+
interface ListSuppressionsOptions {
|
|
1552
|
+
/** Casa com qualquer parte do endereço. */
|
|
1553
|
+
email?: string;
|
|
1554
|
+
reason?: SuppressionReason | readonly SuppressionReason[];
|
|
1555
|
+
/** De 1 a 100; o padrão é 50. */
|
|
1556
|
+
limit?: number;
|
|
1557
|
+
/** `nextCursor` da página anterior. */
|
|
1558
|
+
cursor?: string;
|
|
1559
|
+
}
|
|
1560
|
+
interface SuppressionListPayload {
|
|
1561
|
+
suppressions: Suppression[];
|
|
1562
|
+
nextCursor: string | null;
|
|
1563
|
+
}
|
|
1564
|
+
/**
|
|
1565
|
+
* Lista de supressão de e-mail do projeto.
|
|
1566
|
+
*
|
|
1567
|
+
* @remarks
|
|
1568
|
+
* Um endereço na lista não recebe mais e-mail do projeto: o envio continua
|
|
1569
|
+
* aceito (202), mas a entrega termina em `suppressed` com `failureCode`
|
|
1570
|
+
* `RECIPIENT_SUPPRESSED`, sem chegar ao provedor. Bounces permanentes,
|
|
1571
|
+
* reclamações de spam e supressões do provedor entram sozinhos.
|
|
1572
|
+
*
|
|
1573
|
+
* Consultar exige API key de escopo `read`; adicionar e remover, `write`.
|
|
1574
|
+
*/
|
|
1575
|
+
export declare class Suppressions {
|
|
1576
|
+
private readonly http;
|
|
1577
|
+
constructor(http: HttpClient);
|
|
1578
|
+
/** Adiciona um endereço. Idempotente: se já estiver na lista, devolve a entrada atual sem alterá-la. */
|
|
1579
|
+
create(options: CreateSuppressionOptions, requestOptions?: RequestOptions): Promise<Result<Suppression>>;
|
|
1580
|
+
/** Adiciona de 1 a 100 endereços. Atômico: um endereço inválido recusa o lote inteiro. */
|
|
1581
|
+
batch(options: BatchCreateSuppressionsOptions, requestOptions?: RequestOptions): Promise<Result<BatchCreateSuppressionsPayload>>;
|
|
1582
|
+
/** Uma entrada, pelo id ou pelo endereço. Fora da lista, `SUPPRESSION_NOT_FOUND`. */
|
|
1583
|
+
get(idOrEmail: string, requestOptions?: RequestOptions): Promise<Result<Suppression>>;
|
|
1584
|
+
/** As entradas, da mais recente para a mais antiga. */
|
|
1585
|
+
list(options?: ListSuppressionsOptions, requestOptions?: RequestOptions): Promise<Result<SuppressionListPayload>>;
|
|
1586
|
+
/** Remove uma entrada, pelo id ou pelo endereço, de qualquer motivo. */
|
|
1587
|
+
delete(idOrEmail: string, requestOptions?: RequestOptions): Promise<Result<DeletedSuppression>>;
|
|
1588
|
+
/** Remove de 1 a 100 entradas por `emails` ou por `ids`; o que não estava na lista volta em `notFound`. */
|
|
1589
|
+
batchDelete(options: BatchDeleteSuppressionsOptions, requestOptions?: RequestOptions): Promise<Result<BatchDeleteSuppressionsPayload>>;
|
|
1590
|
+
}
|
|
1486
1591
|
/**
|
|
1487
1592
|
* Envio por web push, com o canal já decidido.
|
|
1488
1593
|
*
|
|
@@ -1616,25 +1721,53 @@ type WhatsAppTemplateComponent = {
|
|
|
1616
1721
|
phone_number: string;
|
|
1617
1722
|
}>;
|
|
1618
1723
|
};
|
|
1619
|
-
|
|
1724
|
+
/**
|
|
1725
|
+
* Componentes de um template de autenticação (código de verificação).
|
|
1726
|
+
*
|
|
1727
|
+
* @remarks
|
|
1728
|
+
* A Meta escreve o texto no idioma do template ("*{{1}}* é seu código de
|
|
1729
|
+
* verificação."): o corpo só diz se leva o aviso de segurança, o rodapé só a
|
|
1730
|
+
* validade (1 a 90 minutos) e o único botão é o de copiar o código. No envio,
|
|
1731
|
+
* o código vai como parâmetro do corpo e do botão `url` de índice `0`.
|
|
1732
|
+
*/
|
|
1733
|
+
type WhatsAppAuthenticationTemplateComponent = {
|
|
1734
|
+
type: 'BODY';
|
|
1735
|
+
add_security_recommendation?: boolean;
|
|
1736
|
+
} | {
|
|
1737
|
+
type: 'FOOTER';
|
|
1738
|
+
code_expiration_minutes: number;
|
|
1739
|
+
} | {
|
|
1740
|
+
type: 'BUTTONS';
|
|
1741
|
+
buttons: [{
|
|
1742
|
+
type: 'OTP';
|
|
1743
|
+
otp_type: 'COPY_CODE';
|
|
1744
|
+
text?: string;
|
|
1745
|
+
}];
|
|
1746
|
+
};
|
|
1747
|
+
export declare const WHATSAPP_TEMPLATE_CATEGORIES: readonly ["MARKETING", "UTILITY", "AUTHENTICATION"];
|
|
1620
1748
|
type WhatsAppTemplateCategory = (typeof WHATSAPP_TEMPLATE_CATEGORIES)[number];
|
|
1621
1749
|
export declare const WHATSAPP_TEMPLATE_STATUSES: readonly ["DRAFT", "SUBMITTING", "SUBMISSION_UNKNOWN", "PENDING", "APPROVED", "REJECTED", "PAUSED", "DISABLED", "DELETED"];
|
|
1622
1750
|
type WhatsAppTemplateStatus = (typeof WHATSAPP_TEMPLATE_STATUSES)[number];
|
|
1623
|
-
interface
|
|
1751
|
+
interface WhatsAppTemplateBaseOptions {
|
|
1624
1752
|
senderId: string;
|
|
1625
1753
|
name: string;
|
|
1626
1754
|
language: string;
|
|
1627
|
-
category: WhatsAppTemplateCategory;
|
|
1628
|
-
components: WhatsAppTemplateComponent[];
|
|
1629
1755
|
}
|
|
1630
|
-
type
|
|
1756
|
+
type CreateWhatsAppTemplateOptions = WhatsAppTemplateBaseOptions & ({
|
|
1757
|
+
category: 'MARKETING' | 'UTILITY';
|
|
1758
|
+
components: WhatsAppTemplateComponent[];
|
|
1759
|
+
} | {
|
|
1760
|
+
category: 'AUTHENTICATION';
|
|
1761
|
+
components: WhatsAppAuthenticationTemplateComponent[];
|
|
1762
|
+
});
|
|
1763
|
+
type UpdateWhatsAppTemplateOptions = (CreateWhatsAppTemplateOptions extends (infer Option) ? Option extends unknown ? Omit<Option, 'senderId'> : never : never) & {
|
|
1631
1764
|
expectedUpdatedAt: IsoDateTime;
|
|
1632
1765
|
};
|
|
1633
1766
|
interface SubmitWhatsAppTemplateOptions {
|
|
1634
1767
|
/** The updatedAt of the draft reviewed for approval. */
|
|
1635
1768
|
expectedUpdatedAt: IsoDateTime;
|
|
1636
1769
|
}
|
|
1637
|
-
interface WhatsAppTemplate extends
|
|
1770
|
+
interface WhatsAppTemplate extends WhatsAppTemplateBaseOptions {
|
|
1638
1771
|
category: WhatsAppTemplateCategory | LooseString;
|
|
1639
1772
|
/** Meta imports may include media, authentication or other unsupported components. */
|
|
1640
1773
|
components: unknown[];
|
|
@@ -1754,6 +1887,8 @@ export declare class Messaging {
|
|
|
1754
1887
|
readonly sms: Sms;
|
|
1755
1888
|
/** Envio por web push, com o canal já decidido. */
|
|
1756
1889
|
readonly webPush: WebPush;
|
|
1890
|
+
/** Lista de supressão de e-mail do projeto. */
|
|
1891
|
+
readonly suppressions: Suppressions;
|
|
1757
1892
|
constructor(config: MessagingConfig | string);
|
|
1758
1893
|
}
|
|
1759
1894
|
/** Quantas mensagens `messages.list` devolve por página quando você não diz. */
|
|
@@ -1768,8 +1903,16 @@ export declare const MESSAGE_BODY_MAX_BYTES: number;
|
|
|
1768
1903
|
export declare const SMS_CONTENT_MAX_LENGTH = 1600;
|
|
1769
1904
|
/** Limite de `data` e `metadata` já serializados, em bytes. */
|
|
1770
1905
|
export declare const MESSAGE_JSON_MAX_BYTES: number;
|
|
1906
|
+
/** Quantos endereços `suppressions.batch` e `suppressions.batchDelete` aceitam por chamada. */
|
|
1907
|
+
export declare const SUPPRESSION_BATCH_MAX_SIZE = 100;
|
|
1908
|
+
/** Quantas entradas `suppressions.list` devolve por página quando você não diz. */
|
|
1909
|
+
export declare const SUPPRESSION_LIST_DEFAULT_LIMIT = 50;
|
|
1910
|
+
/** Teto de `limit` em `suppressions.list`. */
|
|
1911
|
+
export declare const SUPPRESSION_LIST_MAX_LIMIT = 100;
|
|
1912
|
+
/** Limite da `note` de uma entrada da lista de supressão, em caracteres. */
|
|
1913
|
+
export declare const SUPPRESSION_NOTE_MAX_LENGTH = 500;
|
|
1771
1914
|
/** Limite do `subject`, em caracteres. */
|
|
1772
1915
|
export declare const MESSAGE_SUBJECT_MAX_LENGTH = 998;
|
|
1773
1916
|
/** Versão do pacote `franchising`, a mesma do `package.json`. */
|
|
1774
|
-
export declare const VERSION = "0.
|
|
1775
|
-
export { type AcceptedBatchMessage, type AcceptedDelivery, type AcceptedMessage, type AcceptedMessageRetry, type AcceptedWebPushDelivery, type AttachmentContent, type AttachmentContentInput, type AttachmentInput, type AttachmentUrlInput, type BatchRequestOptions, type BatchSendEmailInput, type BatchSendMessageOptions, type BatchSendSmsInput, type BatchSendWebPushInput, type BatchSendWhatsAppInput, type CreateWebPushSubscriptionTokenInput, type CreateWhatsAppTemplateOptions, type EmailAttachmentDisposition, type EmailAttachmentInput, type EmailAttachmentOptions, type EmailDestination, type FetchLike, type IsoDateTime, type JsonObject, type ListMessagesOptions, type ListedMessage, type ListedMessageChannel, type LooseString, type Message, type MessageAttachment, type MessageAttachmentSource, type MessageAttempt, type MessageAttemptOutcome, type MessageChannel, type MessageDeliveryStatus, type MessageDestination, type MessageEvent, type MessageEventType, type MessageListPayload, type MessagePriority, type MessageRetry, type MessageStatus, Messaging as default, type MessagingConfig, type MessagingErrorCode, type MessagingErrorOptions, type ProviderChannel, type ProviderId, type RequestOptions, type Result, type RetryMessageOptions, type SendEmailInput, type SendEmailOptions, type SendMessageOptions, type SendSmsInput, type SendSmsOptions, type SendWebPushInput, type SendWebPushOptions, type SendWhatsAppInput, type SendWhatsAppOptions, type SmsDestination, type SubmitWhatsAppTemplateOptions, type UpdateWhatsAppTemplateOptions, type WebPushDestination, type WebPushSubscriptionToken, type WebPushTarget, type WhatsAppAttachmentInput, type WhatsAppDestination, type WhatsAppMediaKind, type WhatsAppProviderTemplate, type WhatsAppTemplate, type WhatsAppTemplateCategory, type WhatsAppTemplateComponent, type WhatsAppTemplateStatus };
|
|
1917
|
+
export declare const VERSION = "0.4.0";
|
|
1918
|
+
export { type AcceptedBatchMessage, type AcceptedDelivery, type AcceptedMessage, type AcceptedMessageRetry, type AcceptedWebPushDelivery, type AttachmentContent, type AttachmentContentInput, type AttachmentInput, type AttachmentUrlInput, type BatchCreateSuppressionsOptions, type BatchCreateSuppressionsPayload, type BatchDeleteSuppressionsOptions, type BatchDeleteSuppressionsPayload, type BatchRequestOptions, type BatchSendEmailInput, type BatchSendMessageOptions, type BatchSendSmsInput, type BatchSendWebPushInput, type BatchSendWhatsAppInput, type CreateSuppressionOptions, type CreateWebPushSubscriptionTokenInput, type CreateWhatsAppTemplateOptions, type DeletedSuppression, type EmailAttachmentDisposition, type EmailAttachmentInput, type EmailAttachmentOptions, type EmailDestination, type FetchLike, type IsoDateTime, type JsonObject, type ListMessagesOptions, type ListSuppressionsOptions, type ListedMessage, type ListedMessageChannel, type LooseString, type Message, type MessageAttachment, type MessageAttachmentSource, type MessageAttempt, type MessageAttemptOutcome, type MessageChannel, type MessageDeliveryStatus, type MessageDestination, type MessageEvent, type MessageEventType, type MessageListPayload, type MessagePriority, type MessageRetry, type MessageStatus, Messaging as default, type MessagingConfig, type MessagingErrorCode, type MessagingErrorOptions, type ProviderChannel, type ProviderId, type RequestOptions, type Result, type RetryMessageOptions, type SendEmailInput, type SendEmailOptions, type SendMessageOptions, type SendSmsInput, type SendSmsOptions, type SendWebPushInput, type SendWebPushOptions, type SendWhatsAppInput, type SendWhatsAppOptions, type SmsDestination, type SubmitWhatsAppTemplateOptions, type Suppression, type SuppressionListPayload, type SuppressionReason, type SuppressionSource, type UpdateWhatsAppTemplateOptions, type WebPushDestination, type WebPushSubscriptionToken, type WebPushTarget, type WhatsAppAttachmentInput, type WhatsAppAuthenticationTemplateComponent, type WhatsAppDestination, type WhatsAppMediaKind, type WhatsAppProviderTemplate, type WhatsAppTemplate, type WhatsAppTemplateCategory, type WhatsAppTemplateComponent, type WhatsAppTemplateStatus };
|
|
@@ -83,7 +83,7 @@ type QueryValue = string | number | boolean | Date | ReadonlyArray<string | numb
|
|
|
83
83
|
* `code` é mais seguro do que ler a `message`: a frase muda, o código é
|
|
84
84
|
* contrato.
|
|
85
85
|
*/
|
|
86
|
-
export declare const MESSAGING_ERROR_CODES: readonly ["UNAUTHENTICATED", "INVALID_API_KEY", "ACTIVE_PROJECT_REQUIRED", "PROJECT_ROLE_REQUIRED", "VALIDATION_ERROR", "FROM_DOMAIN_NOT_VERIFIED", "SENDER_NOT_FOUND", "WHATSAPP_TEMPLATE_NOT_FOUND", "WHATSAPP_TEMPLATE_CONFLICT", "WHATSAPP_TEMPLATE_PROVIDER_UNSUPPORTED", "WHATSAPP_TEMPLATE_SUBMISSION_FAILED", "WHATSAPP_TEMPLATE_SYNC_FAILED", "WHATSAPP_TEMPLATE_INVALID_STATE", "WHATSAPP_TEMPLATE_BODY_CONFLICT", "ATTACHMENTS_NOT_SUPPORTED_FOR_CHANNEL", "ATTACHMENTS_PROVIDER_TEMPLATE_CONFLICT", "ATTACHMENT_INVALID", "ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED", "ATTACHMENT_TOO_LARGE", "ATTACHMENTS_LIMIT_EXCEEDED", "ATTACHMENT_URL_NOT_ALLOWED", "WHATSAPP_CAPTION_INVALID", "PAYLOAD_TOO_LARGE", "ATTACHMENT_STORAGE_UNAVAILABLE", "ATTACHMENT_STORAGE_NOT_CONFIGURED", "ATTACHMENT_EXPIRED", "MESSAGE_NOT_FOUND", "MESSAGE_NOT_RETRYABLE", "MESSAGE_CONTENT_EXPIRED", "IDEMPOTENCY_KEY_REUSED", "ROUTE_NOT_FOUND", "INTERNAL_SERVER_ERROR", "RATE_LIMIT_EXCEEDED", "CONNECTION_ERROR", "TIMEOUT", "UNEXPECTED_RESPONSE"];
|
|
86
|
+
export declare const MESSAGING_ERROR_CODES: readonly ["UNAUTHENTICATED", "INVALID_API_KEY", "ACTIVE_PROJECT_REQUIRED", "PROJECT_ROLE_REQUIRED", "VALIDATION_ERROR", "FROM_DOMAIN_NOT_VERIFIED", "SENDER_NOT_FOUND", "WHATSAPP_TEMPLATE_NOT_FOUND", "WHATSAPP_TEMPLATE_CONFLICT", "WHATSAPP_TEMPLATE_PROVIDER_UNSUPPORTED", "WHATSAPP_TEMPLATE_SUBMISSION_FAILED", "WHATSAPP_TEMPLATE_SYNC_FAILED", "WHATSAPP_TEMPLATE_INVALID_STATE", "WHATSAPP_TEMPLATE_BODY_CONFLICT", "ATTACHMENTS_NOT_SUPPORTED_FOR_CHANNEL", "ATTACHMENTS_PROVIDER_TEMPLATE_CONFLICT", "ATTACHMENT_INVALID", "ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED", "ATTACHMENT_TOO_LARGE", "ATTACHMENTS_LIMIT_EXCEEDED", "ATTACHMENT_URL_NOT_ALLOWED", "WHATSAPP_CAPTION_INVALID", "PAYLOAD_TOO_LARGE", "ATTACHMENT_STORAGE_UNAVAILABLE", "ATTACHMENT_STORAGE_NOT_CONFIGURED", "ATTACHMENT_EXPIRED", "MESSAGE_NOT_FOUND", "SUPPRESSION_NOT_FOUND", "MESSAGE_NOT_RETRYABLE", "MESSAGE_CONTENT_EXPIRED", "IDEMPOTENCY_KEY_REUSED", "ROUTE_NOT_FOUND", "INTERNAL_SERVER_ERROR", "RATE_LIMIT_EXCEEDED", "CONNECTION_ERROR", "TIMEOUT", "UNEXPECTED_RESPONSE"];
|
|
87
87
|
/** {@link MESSAGING_ERROR_CODES} */
|
|
88
88
|
type MessagingErrorCode = (typeof MESSAGING_ERROR_CODES)[number];
|
|
89
89
|
/** Dados que acompanham toda falha. */
|
|
@@ -143,7 +143,7 @@ export declare class MessagingError extends Error {
|
|
|
143
143
|
toJSON(): {
|
|
144
144
|
errors?: unknown[];
|
|
145
145
|
name: string;
|
|
146
|
-
code: "UNAUTHENTICATED" | "INVALID_API_KEY" | "ACTIVE_PROJECT_REQUIRED" | "PROJECT_ROLE_REQUIRED" | "VALIDATION_ERROR" | "FROM_DOMAIN_NOT_VERIFIED" | "SENDER_NOT_FOUND" | "WHATSAPP_TEMPLATE_NOT_FOUND" | "WHATSAPP_TEMPLATE_CONFLICT" | "WHATSAPP_TEMPLATE_PROVIDER_UNSUPPORTED" | "WHATSAPP_TEMPLATE_SUBMISSION_FAILED" | "WHATSAPP_TEMPLATE_SYNC_FAILED" | "WHATSAPP_TEMPLATE_INVALID_STATE" | "WHATSAPP_TEMPLATE_BODY_CONFLICT" | "ATTACHMENTS_NOT_SUPPORTED_FOR_CHANNEL" | "ATTACHMENTS_PROVIDER_TEMPLATE_CONFLICT" | "ATTACHMENT_INVALID" | "ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED" | "ATTACHMENT_TOO_LARGE" | "ATTACHMENTS_LIMIT_EXCEEDED" | "ATTACHMENT_URL_NOT_ALLOWED" | "WHATSAPP_CAPTION_INVALID" | "PAYLOAD_TOO_LARGE" | "ATTACHMENT_STORAGE_UNAVAILABLE" | "ATTACHMENT_STORAGE_NOT_CONFIGURED" | "ATTACHMENT_EXPIRED" | "MESSAGE_NOT_FOUND" | "MESSAGE_NOT_RETRYABLE" | "MESSAGE_CONTENT_EXPIRED" | "IDEMPOTENCY_KEY_REUSED" | "ROUTE_NOT_FOUND" | "INTERNAL_SERVER_ERROR" | "RATE_LIMIT_EXCEEDED" | "CONNECTION_ERROR" | "TIMEOUT" | "UNEXPECTED_RESPONSE" | (string & Record<never, never>);
|
|
146
|
+
code: "UNAUTHENTICATED" | "INVALID_API_KEY" | "ACTIVE_PROJECT_REQUIRED" | "PROJECT_ROLE_REQUIRED" | "VALIDATION_ERROR" | "FROM_DOMAIN_NOT_VERIFIED" | "SENDER_NOT_FOUND" | "WHATSAPP_TEMPLATE_NOT_FOUND" | "WHATSAPP_TEMPLATE_CONFLICT" | "WHATSAPP_TEMPLATE_PROVIDER_UNSUPPORTED" | "WHATSAPP_TEMPLATE_SUBMISSION_FAILED" | "WHATSAPP_TEMPLATE_SYNC_FAILED" | "WHATSAPP_TEMPLATE_INVALID_STATE" | "WHATSAPP_TEMPLATE_BODY_CONFLICT" | "ATTACHMENTS_NOT_SUPPORTED_FOR_CHANNEL" | "ATTACHMENTS_PROVIDER_TEMPLATE_CONFLICT" | "ATTACHMENT_INVALID" | "ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED" | "ATTACHMENT_TOO_LARGE" | "ATTACHMENTS_LIMIT_EXCEEDED" | "ATTACHMENT_URL_NOT_ALLOWED" | "WHATSAPP_CAPTION_INVALID" | "PAYLOAD_TOO_LARGE" | "ATTACHMENT_STORAGE_UNAVAILABLE" | "ATTACHMENT_STORAGE_NOT_CONFIGURED" | "ATTACHMENT_EXPIRED" | "MESSAGE_NOT_FOUND" | "SUPPRESSION_NOT_FOUND" | "MESSAGE_NOT_RETRYABLE" | "MESSAGE_CONTENT_EXPIRED" | "IDEMPOTENCY_KEY_REUSED" | "ROUTE_NOT_FOUND" | "INTERNAL_SERVER_ERROR" | "RATE_LIMIT_EXCEEDED" | "CONNECTION_ERROR" | "TIMEOUT" | "UNEXPECTED_RESPONSE" | (string & Record<never, never>);
|
|
147
147
|
message: string;
|
|
148
148
|
status: number;
|
|
149
149
|
};
|
|
@@ -224,7 +224,7 @@ interface HttpClientConfig {
|
|
|
224
224
|
fetch: FetchLike;
|
|
225
225
|
}
|
|
226
226
|
interface RequestInput {
|
|
227
|
-
method: 'GET' | 'POST' | 'PATCH';
|
|
227
|
+
method: 'GET' | 'POST' | 'PATCH' | 'DELETE';
|
|
228
228
|
path: string;
|
|
229
229
|
query?: Record<string, QueryValue>;
|
|
230
230
|
body?: unknown;
|
|
@@ -1483,6 +1483,111 @@ export declare class Sms {
|
|
|
1483
1483
|
/** Envia de 1 a 100 SMS em uma única requisição atômica. */
|
|
1484
1484
|
batch(options: BatchSendSmsInput[], requestOptions?: BatchRequestOptions): Promise<Result<AcceptedBatchMessage[]>>;
|
|
1485
1485
|
}
|
|
1486
|
+
/**
|
|
1487
|
+
* Por que o endereço entrou na lista de supressão.
|
|
1488
|
+
*
|
|
1489
|
+
* - `manual`: alguém adicionou pela API ou pela dashboard.
|
|
1490
|
+
* - `bounce`: o provedor disse que o endereço não existe (bounce permanente).
|
|
1491
|
+
* - `complaint`: o destinatário marcou um e-mail como spam.
|
|
1492
|
+
* - `provider_suppressed`: o provedor recusou por histórico ruim do endereço.
|
|
1493
|
+
*/
|
|
1494
|
+
export declare const SUPPRESSION_REASONS: readonly ["manual", "bounce", "complaint", "provider_suppressed"];
|
|
1495
|
+
type SuppressionReason = (typeof SUPPRESSION_REASONS)[number];
|
|
1496
|
+
/** Por onde a entrada chegou: API, dashboard ou evento do provedor. */
|
|
1497
|
+
export declare const SUPPRESSION_SOURCES: readonly ["api", "dashboard", "automatic"];
|
|
1498
|
+
type SuppressionSource = (typeof SUPPRESSION_SOURCES)[number];
|
|
1499
|
+
/**
|
|
1500
|
+
* `failureCode` da entrega bloqueada pela lista do projeto.
|
|
1501
|
+
*
|
|
1502
|
+
* @remarks
|
|
1503
|
+
* O estado é `suppressed`, o mesmo da supressão feita pelo provedor; é este
|
|
1504
|
+
* código que separa "a plataforma bloqueou" de "o provedor recusou".
|
|
1505
|
+
*/
|
|
1506
|
+
export declare const RECIPIENT_SUPPRESSED_FAILURE_CODE = "RECIPIENT_SUPPRESSED";
|
|
1507
|
+
/** Entrada da lista de supressão. O e-mail vem sempre em minúsculas. */
|
|
1508
|
+
interface Suppression {
|
|
1509
|
+
id: string;
|
|
1510
|
+
email: string;
|
|
1511
|
+
reason: SuppressionReason | LooseString;
|
|
1512
|
+
source: SuppressionSource | LooseString;
|
|
1513
|
+
note: string | null;
|
|
1514
|
+
/** Mensagem cujo evento do provedor colocou o endereço na lista (só automáticas). */
|
|
1515
|
+
messageId: string | null;
|
|
1516
|
+
createdAt: IsoDateTime;
|
|
1517
|
+
}
|
|
1518
|
+
interface DeletedSuppression extends Suppression {
|
|
1519
|
+
deleted: true;
|
|
1520
|
+
}
|
|
1521
|
+
interface CreateSuppressionOptions {
|
|
1522
|
+
email: string;
|
|
1523
|
+
/** Anotação livre, até 500 caracteres. */
|
|
1524
|
+
note?: string;
|
|
1525
|
+
}
|
|
1526
|
+
interface BatchCreateSuppressionsOptions {
|
|
1527
|
+
/** De 1 a 100 endereços. Um inválido recusa o lote inteiro. */
|
|
1528
|
+
emails: string[];
|
|
1529
|
+
/** Aplicada a todas as entradas novas do lote. */
|
|
1530
|
+
note?: string;
|
|
1531
|
+
}
|
|
1532
|
+
interface BatchCreateSuppressionsPayload {
|
|
1533
|
+
/** Entraram agora, na ordem enviada. */
|
|
1534
|
+
created: Suppression[];
|
|
1535
|
+
/** Já estavam na lista e voltam como estavam. */
|
|
1536
|
+
existing: Suppression[];
|
|
1537
|
+
}
|
|
1538
|
+
/** Exatamente um dos dois, de 1 a 100 itens. */
|
|
1539
|
+
type BatchDeleteSuppressionsOptions = {
|
|
1540
|
+
emails: string[];
|
|
1541
|
+
ids?: never;
|
|
1542
|
+
} | {
|
|
1543
|
+
ids: string[];
|
|
1544
|
+
emails?: never;
|
|
1545
|
+
};
|
|
1546
|
+
interface BatchDeleteSuppressionsPayload {
|
|
1547
|
+
deleted: Suppression[];
|
|
1548
|
+
/** Ids ou e-mails pedidos que não estavam na lista. */
|
|
1549
|
+
notFound: string[];
|
|
1550
|
+
}
|
|
1551
|
+
interface ListSuppressionsOptions {
|
|
1552
|
+
/** Casa com qualquer parte do endereço. */
|
|
1553
|
+
email?: string;
|
|
1554
|
+
reason?: SuppressionReason | readonly SuppressionReason[];
|
|
1555
|
+
/** De 1 a 100; o padrão é 50. */
|
|
1556
|
+
limit?: number;
|
|
1557
|
+
/** `nextCursor` da página anterior. */
|
|
1558
|
+
cursor?: string;
|
|
1559
|
+
}
|
|
1560
|
+
interface SuppressionListPayload {
|
|
1561
|
+
suppressions: Suppression[];
|
|
1562
|
+
nextCursor: string | null;
|
|
1563
|
+
}
|
|
1564
|
+
/**
|
|
1565
|
+
* Lista de supressão de e-mail do projeto.
|
|
1566
|
+
*
|
|
1567
|
+
* @remarks
|
|
1568
|
+
* Um endereço na lista não recebe mais e-mail do projeto: o envio continua
|
|
1569
|
+
* aceito (202), mas a entrega termina em `suppressed` com `failureCode`
|
|
1570
|
+
* `RECIPIENT_SUPPRESSED`, sem chegar ao provedor. Bounces permanentes,
|
|
1571
|
+
* reclamações de spam e supressões do provedor entram sozinhos.
|
|
1572
|
+
*
|
|
1573
|
+
* Consultar exige API key de escopo `read`; adicionar e remover, `write`.
|
|
1574
|
+
*/
|
|
1575
|
+
export declare class Suppressions {
|
|
1576
|
+
private readonly http;
|
|
1577
|
+
constructor(http: HttpClient);
|
|
1578
|
+
/** Adiciona um endereço. Idempotente: se já estiver na lista, devolve a entrada atual sem alterá-la. */
|
|
1579
|
+
create(options: CreateSuppressionOptions, requestOptions?: RequestOptions): Promise<Result<Suppression>>;
|
|
1580
|
+
/** Adiciona de 1 a 100 endereços. Atômico: um endereço inválido recusa o lote inteiro. */
|
|
1581
|
+
batch(options: BatchCreateSuppressionsOptions, requestOptions?: RequestOptions): Promise<Result<BatchCreateSuppressionsPayload>>;
|
|
1582
|
+
/** Uma entrada, pelo id ou pelo endereço. Fora da lista, `SUPPRESSION_NOT_FOUND`. */
|
|
1583
|
+
get(idOrEmail: string, requestOptions?: RequestOptions): Promise<Result<Suppression>>;
|
|
1584
|
+
/** As entradas, da mais recente para a mais antiga. */
|
|
1585
|
+
list(options?: ListSuppressionsOptions, requestOptions?: RequestOptions): Promise<Result<SuppressionListPayload>>;
|
|
1586
|
+
/** Remove uma entrada, pelo id ou pelo endereço, de qualquer motivo. */
|
|
1587
|
+
delete(idOrEmail: string, requestOptions?: RequestOptions): Promise<Result<DeletedSuppression>>;
|
|
1588
|
+
/** Remove de 1 a 100 entradas por `emails` ou por `ids`; o que não estava na lista volta em `notFound`. */
|
|
1589
|
+
batchDelete(options: BatchDeleteSuppressionsOptions, requestOptions?: RequestOptions): Promise<Result<BatchDeleteSuppressionsPayload>>;
|
|
1590
|
+
}
|
|
1486
1591
|
/**
|
|
1487
1592
|
* Envio por web push, com o canal já decidido.
|
|
1488
1593
|
*
|
|
@@ -1616,25 +1721,53 @@ type WhatsAppTemplateComponent = {
|
|
|
1616
1721
|
phone_number: string;
|
|
1617
1722
|
}>;
|
|
1618
1723
|
};
|
|
1619
|
-
|
|
1724
|
+
/**
|
|
1725
|
+
* Componentes de um template de autenticação (código de verificação).
|
|
1726
|
+
*
|
|
1727
|
+
* @remarks
|
|
1728
|
+
* A Meta escreve o texto no idioma do template ("*{{1}}* é seu código de
|
|
1729
|
+
* verificação."): o corpo só diz se leva o aviso de segurança, o rodapé só a
|
|
1730
|
+
* validade (1 a 90 minutos) e o único botão é o de copiar o código. No envio,
|
|
1731
|
+
* o código vai como parâmetro do corpo e do botão `url` de índice `0`.
|
|
1732
|
+
*/
|
|
1733
|
+
type WhatsAppAuthenticationTemplateComponent = {
|
|
1734
|
+
type: 'BODY';
|
|
1735
|
+
add_security_recommendation?: boolean;
|
|
1736
|
+
} | {
|
|
1737
|
+
type: 'FOOTER';
|
|
1738
|
+
code_expiration_minutes: number;
|
|
1739
|
+
} | {
|
|
1740
|
+
type: 'BUTTONS';
|
|
1741
|
+
buttons: [{
|
|
1742
|
+
type: 'OTP';
|
|
1743
|
+
otp_type: 'COPY_CODE';
|
|
1744
|
+
text?: string;
|
|
1745
|
+
}];
|
|
1746
|
+
};
|
|
1747
|
+
export declare const WHATSAPP_TEMPLATE_CATEGORIES: readonly ["MARKETING", "UTILITY", "AUTHENTICATION"];
|
|
1620
1748
|
type WhatsAppTemplateCategory = (typeof WHATSAPP_TEMPLATE_CATEGORIES)[number];
|
|
1621
1749
|
export declare const WHATSAPP_TEMPLATE_STATUSES: readonly ["DRAFT", "SUBMITTING", "SUBMISSION_UNKNOWN", "PENDING", "APPROVED", "REJECTED", "PAUSED", "DISABLED", "DELETED"];
|
|
1622
1750
|
type WhatsAppTemplateStatus = (typeof WHATSAPP_TEMPLATE_STATUSES)[number];
|
|
1623
|
-
interface
|
|
1751
|
+
interface WhatsAppTemplateBaseOptions {
|
|
1624
1752
|
senderId: string;
|
|
1625
1753
|
name: string;
|
|
1626
1754
|
language: string;
|
|
1627
|
-
category: WhatsAppTemplateCategory;
|
|
1628
|
-
components: WhatsAppTemplateComponent[];
|
|
1629
1755
|
}
|
|
1630
|
-
type
|
|
1756
|
+
type CreateWhatsAppTemplateOptions = WhatsAppTemplateBaseOptions & ({
|
|
1757
|
+
category: 'MARKETING' | 'UTILITY';
|
|
1758
|
+
components: WhatsAppTemplateComponent[];
|
|
1759
|
+
} | {
|
|
1760
|
+
category: 'AUTHENTICATION';
|
|
1761
|
+
components: WhatsAppAuthenticationTemplateComponent[];
|
|
1762
|
+
});
|
|
1763
|
+
type UpdateWhatsAppTemplateOptions = (CreateWhatsAppTemplateOptions extends (infer Option) ? Option extends unknown ? Omit<Option, 'senderId'> : never : never) & {
|
|
1631
1764
|
expectedUpdatedAt: IsoDateTime;
|
|
1632
1765
|
};
|
|
1633
1766
|
interface SubmitWhatsAppTemplateOptions {
|
|
1634
1767
|
/** The updatedAt of the draft reviewed for approval. */
|
|
1635
1768
|
expectedUpdatedAt: IsoDateTime;
|
|
1636
1769
|
}
|
|
1637
|
-
interface WhatsAppTemplate extends
|
|
1770
|
+
interface WhatsAppTemplate extends WhatsAppTemplateBaseOptions {
|
|
1638
1771
|
category: WhatsAppTemplateCategory | LooseString;
|
|
1639
1772
|
/** Meta imports may include media, authentication or other unsupported components. */
|
|
1640
1773
|
components: unknown[];
|
|
@@ -1754,6 +1887,8 @@ export declare class Messaging {
|
|
|
1754
1887
|
readonly sms: Sms;
|
|
1755
1888
|
/** Envio por web push, com o canal já decidido. */
|
|
1756
1889
|
readonly webPush: WebPush;
|
|
1890
|
+
/** Lista de supressão de e-mail do projeto. */
|
|
1891
|
+
readonly suppressions: Suppressions;
|
|
1757
1892
|
constructor(config: MessagingConfig | string);
|
|
1758
1893
|
}
|
|
1759
1894
|
/** Quantas mensagens `messages.list` devolve por página quando você não diz. */
|
|
@@ -1768,8 +1903,16 @@ export declare const MESSAGE_BODY_MAX_BYTES: number;
|
|
|
1768
1903
|
export declare const SMS_CONTENT_MAX_LENGTH = 1600;
|
|
1769
1904
|
/** Limite de `data` e `metadata` já serializados, em bytes. */
|
|
1770
1905
|
export declare const MESSAGE_JSON_MAX_BYTES: number;
|
|
1906
|
+
/** Quantos endereços `suppressions.batch` e `suppressions.batchDelete` aceitam por chamada. */
|
|
1907
|
+
export declare const SUPPRESSION_BATCH_MAX_SIZE = 100;
|
|
1908
|
+
/** Quantas entradas `suppressions.list` devolve por página quando você não diz. */
|
|
1909
|
+
export declare const SUPPRESSION_LIST_DEFAULT_LIMIT = 50;
|
|
1910
|
+
/** Teto de `limit` em `suppressions.list`. */
|
|
1911
|
+
export declare const SUPPRESSION_LIST_MAX_LIMIT = 100;
|
|
1912
|
+
/** Limite da `note` de uma entrada da lista de supressão, em caracteres. */
|
|
1913
|
+
export declare const SUPPRESSION_NOTE_MAX_LENGTH = 500;
|
|
1771
1914
|
/** Limite do `subject`, em caracteres. */
|
|
1772
1915
|
export declare const MESSAGE_SUBJECT_MAX_LENGTH = 998;
|
|
1773
1916
|
/** Versão do pacote `franchising`, a mesma do `package.json`. */
|
|
1774
|
-
export declare const VERSION = "0.
|
|
1775
|
-
export { type AcceptedBatchMessage, type AcceptedDelivery, type AcceptedMessage, type AcceptedMessageRetry, type AcceptedWebPushDelivery, type AttachmentContent, type AttachmentContentInput, type AttachmentInput, type AttachmentUrlInput, type BatchRequestOptions, type BatchSendEmailInput, type BatchSendMessageOptions, type BatchSendSmsInput, type BatchSendWebPushInput, type BatchSendWhatsAppInput, type CreateWebPushSubscriptionTokenInput, type CreateWhatsAppTemplateOptions, type EmailAttachmentDisposition, type EmailAttachmentInput, type EmailAttachmentOptions, type EmailDestination, type FetchLike, type IsoDateTime, type JsonObject, type ListMessagesOptions, type ListedMessage, type ListedMessageChannel, type LooseString, type Message, type MessageAttachment, type MessageAttachmentSource, type MessageAttempt, type MessageAttemptOutcome, type MessageChannel, type MessageDeliveryStatus, type MessageDestination, type MessageEvent, type MessageEventType, type MessageListPayload, type MessagePriority, type MessageRetry, type MessageStatus, Messaging as default, type MessagingConfig, type MessagingErrorCode, type MessagingErrorOptions, type ProviderChannel, type ProviderId, type RequestOptions, type Result, type RetryMessageOptions, type SendEmailInput, type SendEmailOptions, type SendMessageOptions, type SendSmsInput, type SendSmsOptions, type SendWebPushInput, type SendWebPushOptions, type SendWhatsAppInput, type SendWhatsAppOptions, type SmsDestination, type SubmitWhatsAppTemplateOptions, type UpdateWhatsAppTemplateOptions, type WebPushDestination, type WebPushSubscriptionToken, type WebPushTarget, type WhatsAppAttachmentInput, type WhatsAppDestination, type WhatsAppMediaKind, type WhatsAppProviderTemplate, type WhatsAppTemplate, type WhatsAppTemplateCategory, type WhatsAppTemplateComponent, type WhatsAppTemplateStatus };
|
|
1917
|
+
export declare const VERSION = "0.4.0";
|
|
1918
|
+
export { type AcceptedBatchMessage, type AcceptedDelivery, type AcceptedMessage, type AcceptedMessageRetry, type AcceptedWebPushDelivery, type AttachmentContent, type AttachmentContentInput, type AttachmentInput, type AttachmentUrlInput, type BatchCreateSuppressionsOptions, type BatchCreateSuppressionsPayload, type BatchDeleteSuppressionsOptions, type BatchDeleteSuppressionsPayload, type BatchRequestOptions, type BatchSendEmailInput, type BatchSendMessageOptions, type BatchSendSmsInput, type BatchSendWebPushInput, type BatchSendWhatsAppInput, type CreateSuppressionOptions, type CreateWebPushSubscriptionTokenInput, type CreateWhatsAppTemplateOptions, type DeletedSuppression, type EmailAttachmentDisposition, type EmailAttachmentInput, type EmailAttachmentOptions, type EmailDestination, type FetchLike, type IsoDateTime, type JsonObject, type ListMessagesOptions, type ListSuppressionsOptions, type ListedMessage, type ListedMessageChannel, type LooseString, type Message, type MessageAttachment, type MessageAttachmentSource, type MessageAttempt, type MessageAttemptOutcome, type MessageChannel, type MessageDeliveryStatus, type MessageDestination, type MessageEvent, type MessageEventType, type MessageListPayload, type MessagePriority, type MessageRetry, type MessageStatus, Messaging as default, type MessagingConfig, type MessagingErrorCode, type MessagingErrorOptions, type ProviderChannel, type ProviderId, type RequestOptions, type Result, type RetryMessageOptions, type SendEmailInput, type SendEmailOptions, type SendMessageOptions, type SendSmsInput, type SendSmsOptions, type SendWebPushInput, type SendWebPushOptions, type SendWhatsAppInput, type SendWhatsAppOptions, type SmsDestination, type SubmitWhatsAppTemplateOptions, type Suppression, type SuppressionListPayload, type SuppressionReason, type SuppressionSource, type UpdateWhatsAppTemplateOptions, type WebPushDestination, type WebPushSubscriptionToken, type WebPushTarget, type WhatsAppAttachmentInput, type WhatsAppAuthenticationTemplateComponent, type WhatsAppDestination, type WhatsAppMediaKind, type WhatsAppProviderTemplate, type WhatsAppTemplate, type WhatsAppTemplateCategory, type WhatsAppTemplateComponent, type WhatsAppTemplateStatus };
|
package/dist/messaging/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"../version-B0ADow60.js";const t=1048576,n=10,r=20*t,i=1,a=5*t,o=10*t,s=1024,c=2048,l=255,u=[`upload`,`url`],d=[`attachment`,`inline`],f=[`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/vnd.ms-powerpoint`,`application/vnd.openxmlformats-officedocument.presentationml.presentation`],p=[`application/pdf`,`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`text/csv`,`text/plain`,...f,`application/vnd.oasis.opendocument.text`,`application/vnd.oasis.opendocument.spreadsheet`,`application/zip`,`text/calendar`],m=/* @__PURE__ */ `apk.app.bat.cmd.com.cpl.dll.dmg.exe.hta.jar.js.jse.lnk.msi.msp.pif.ps1.reg.scr.sh.vb.vbe.vbs.wsf.wsh`.split(`.`),h=[`image`,`video`,`audio`,`document`],g={image:[`image/jpeg`,`image/png`],video:[`video/mp4`,`video/3gpp`],audio:[`audio/aac`,`audio/mp4`,`audio/mpeg`,`audio/amr`,`audio/ogg`],document:[`application/pdf`,...f,`text/plain`,`text/csv`,`application/zip`]},_={image:a,video:o,audio:o,document:o},ee=/* @__PURE__ */ `UNAUTHENTICATED.INVALID_API_KEY.ACTIVE_PROJECT_REQUIRED.PROJECT_ROLE_REQUIRED.VALIDATION_ERROR.FROM_DOMAIN_NOT_VERIFIED.SENDER_NOT_FOUND.WHATSAPP_TEMPLATE_NOT_FOUND.WHATSAPP_TEMPLATE_CONFLICT.WHATSAPP_TEMPLATE_PROVIDER_UNSUPPORTED.WHATSAPP_TEMPLATE_SUBMISSION_FAILED.WHATSAPP_TEMPLATE_SYNC_FAILED.WHATSAPP_TEMPLATE_INVALID_STATE.WHATSAPP_TEMPLATE_BODY_CONFLICT.ATTACHMENTS_NOT_SUPPORTED_FOR_CHANNEL.ATTACHMENTS_PROVIDER_TEMPLATE_CONFLICT.ATTACHMENT_INVALID.ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED.ATTACHMENT_TOO_LARGE.ATTACHMENTS_LIMIT_EXCEEDED.ATTACHMENT_URL_NOT_ALLOWED.WHATSAPP_CAPTION_INVALID.PAYLOAD_TOO_LARGE.ATTACHMENT_STORAGE_UNAVAILABLE.ATTACHMENT_STORAGE_NOT_CONFIGURED.ATTACHMENT_EXPIRED.MESSAGE_NOT_FOUND.MESSAGE_NOT_RETRYABLE.MESSAGE_CONTENT_EXPIRED.IDEMPOTENCY_KEY_REUSED.ROUTE_NOT_FOUND.INTERNAL_SERVER_ERROR.RATE_LIMIT_EXCEEDED.CONNECTION_ERROR.TIMEOUT.UNEXPECTED_RESPONSE`.split(`.`);var v=class extends Error{name=`MessagingError`;code;status;errors;constructor(e){super(e.message,{cause:e.cause}),this.code=e.code,this.status=e.status,this.errors=e.errors}get retryable(){return this.status===0||this.status===408||this.status===429||this.status>=500}toJSON(){return{name:this.name,code:this.code,message:this.message,status:this.status,...this.errors?{errors:this.errors}:{}}}},y=class extends v{name=`ValidationError`},b=class extends v{name=`AuthenticationError`},x=class extends v{name=`PermissionError`},S=class extends v{name=`NotFoundError`},C=class extends v{name=`RateLimitError`;retryAfter;constructor(e){super(e),this.retryAfter=e.retryAfter}},w=class extends v{name=`ServerError`},T=class extends v{name=`ConnectionError`},E=class extends v{name=`TimeoutError`};function te(e){return e instanceof v}function ne(e){let t={code:e.code,message:e.message,status:e.status,...e.errors?{errors:e.errors}:{}};return e.status===429?new C({...t,...e.retryAfter===void 0?{}:{retryAfter:e.retryAfter}}):e.status>=500?new w(t):e.status===401?new b(t):e.status===403?new x(t):e.status===404?new S(t):e.status===400||e.status===422?new y(t):new v(t)}function re(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e))if(r!==void 0){if(Array.isArray(r))for(let e of r)t.append(n,String(e));else t.append(n,r instanceof Date?r.toISOString():String(r))}let n=t.toString();return n?`?${n}`:``}const D=8e3,ie=e=>new Promise(t=>setTimeout(t,e));function ae(e,t){if(t!==void 0)return Math.min(t*1e3,D);let n=Math.min(500*2**e,D);return Math.round(n*(.5+Math.random()*.5))}function oe(e){if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t;let n=Date.parse(e);if(!Number.isNaN(n))return Math.max(0,Math.round((n-Date.now())/1e3))}function O(e){if(e.length===1)return e[0];let t=AbortSignal.any;if(t)return t(e);let n=new AbortController;for(let t of e){if(t.aborted){n.abort(t.reason);break}t.addEventListener(`abort`,()=>n.abort(t.reason),{once:!0})}return n.signal}function k(e){return{data:e,error:null}}function A(e){return{data:null,error:e}}const j=e,se=`rockdev-messaging-node/${j}`,ce=3e4,le=2;var ue=class{config;constructor(e){this.config=e}async request(e){let t=`${this.config.baseUrl}/v1${e.path}${e.query?re(e.query):``}`,n=e.method===`GET`||e.idempotencyKey!==void 0?this.config.maxRetries:0,r;for(let i=0;i<=n;i+=1){let a=await this.attempt(t,e);if(a.error===null)return a;if(r=a.error,!a.error.retryable||e.options?.signal?.aborted||i===n)break;await ie(ae(i,a.error.retryAfter))}return A(r)}async attempt(e,t){let n=t.options?.timeout??this.config.timeout,r=new AbortController,i=setTimeout(()=>r.abort(),n),a=[r.signal];t.options?.signal&&a.push(t.options.signal);let o;try{o=await this.config.fetch(e,{method:t.method,headers:this.headers(t),signal:O(a),...t.body===void 0?{}:{body:JSON.stringify(t.body)}})}catch(e){return t.options?.signal?.aborted?A(new v({code:`CONNECTION_ERROR`,message:`The request was aborted by the caller.`,status:0,cause:e})):r.signal.aborted?A(new E({code:`TIMEOUT`,message:`The request did not complete within ${n}ms.`,status:0,cause:e})):A(new T({code:`CONNECTION_ERROR`,message:e instanceof Error?e.message:`The request could not reach the Messaging API.`,status:0,cause:e}))}finally{clearTimeout(i)}return this.parse(o)}headers(e){let t=e=>Object.fromEntries(Object.entries(e).filter(([e])=>e.toLowerCase()!==`idempotency-key`));return{accept:`application/json`,authorization:`Bearer ${this.config.secret}`,"user-agent":se,...e.body===void 0?{}:{"content-type":`application/json`},...t(this.config.headers),...t(e.options?.headers??{}),...e.idempotencyKey===void 0?{}:{"idempotency-key":e.idempotencyKey}}}async parse(e){let t=await e.text().catch(()=>``),n;try{n=t?JSON.parse(t):void 0}catch{n=void 0}if(!e.ok){let t=oe(e.headers.get(`retry-after`));return A(ne({code:n?.code??`INTERNAL_SERVER_ERROR`,message:n?.message??`The Messaging API responded with ${e.status}.`,status:e.status,...n?.errors?{errors:n.errors}:{},...t===void 0?{}:{retryAfter:t}}))}return!n||n.data===void 0?A(new v({code:`UNEXPECTED_RESPONSE`,message:`The Messaging API responded without the expected body.`,status:e.status})):k(n.data)}},M=class{messages;constructor(e){this.messages=e}async send(e,t){let{to:n,...r}=e;return this.messages.send({...r,to:typeof n==`string`?{email:n}:n},t)}async batch(e,t){return this.messages.batch(e.map(({to:e,...t})=>({...t,to:typeof e==`string`?{email:e}:e})),t)}},N=class e{fetchPage;messages;nextCursor;constructor(e,t){this.fetchPage=t,this.messages=e.messages,this.nextCursor=e.nextCursor}get hasMore(){return this.nextCursor!==null}async next(){return this.nextCursor===null?{data:new e({messages:[],nextCursor:null},this.fetchPage),error:null}:this.fetchPage(this.nextCursor)}async*[Symbol.asyncIterator](){let e=this;for(;;){for(let t of e.messages)yield t;if(!e.hasMore)return;let{data:t,error:n}=await e.next();if(n)throw n;e=t}}};function P(e){if(e!==void 0)return e instanceof Date?e.toISOString():e}function de(e){return{status:e.status,channel:e.channel,to:e.to,search:e.search,scheduled:e.scheduled,createdAfter:P(e.createdAfter),createdBefore:P(e.createdBefore),limit:e.limit,cursor:e.cursor}}const F=24576;function fe(e){if(typeof e.toBase64==`function`)return e.toBase64();let t=globalThis.Buffer;if(t)return t.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`);let n=``;for(let t=0;t<e.length;t+=F){let r=e.subarray(t,t+F),i=``;for(let e=0;e<r.length;e+=1)i+=String.fromCharCode(r[e]);n+=btoa(i)}return n}function pe(e){let t=e.endsWith(`==`)?2:+!!e.endsWith(`=`);return e.length/4*3-t}function I(e){return typeof Blob<`u`&&e instanceof Blob}function L(e){return`email`in e&&e.email!==void 0?`email`:`whatsapp`in e&&e.whatsapp!==void 0?`whatsapp`:`sms`in e&&e.sms!==void 0?`sms`:`webpush`}function R(e){return typeof e==`string`?e.includes(`@`)?{email:e}:{whatsapp:e}:e}function z(e){let t=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(e);if(!t)return null;let[n,r]=[Number(t[1]),Number(t[2])];return n===0||n===10||n===127||n===100&&r>=64&&r<=127||n===169&&r===254||n===172&&r>=16&&r<=31||n===192&&r===168||n===198&&(r===18||r===19)||n>=224}function B(e){if(!e.startsWith(`[`))return null;let t=e.slice(1,-1).toLowerCase(),n=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(t);return n?.[1]?z(n[1])??!0:t===`::`||t===`::1`||t.startsWith(`::ffff:`)||/^f[cd]/.test(t)||/^fe[89ab]/.test(t)||t.startsWith(`ff`)}function me(e){try{return new URL(e)}catch{return null}}const he={pdf:`application/pdf`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,csv:`text/csv`,txt:`text/plain`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,xls:`application/vnd.ms-excel`,xlsx:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,ppt:`application/vnd.ms-powerpoint`,pptx:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,odt:`application/vnd.oasis.opendocument.text`,ods:`application/vnd.oasis.opendocument.spreadsheet`,zip:`application/zip`,ics:`text/calendar`,mp4:`video/mp4`,"3gp":`video/3gpp`,aac:`audio/aac`,m4a:`audio/mp4`,mp3:`audio/mpeg`,amr:`audio/amr`,ogg:`audio/ogg`,opus:`audio/ogg`};function V(e){return(e.split(`;`)[0]??``).trim().toLowerCase()}function H(e){let t=e.lastIndexOf(`.`);return t<=0||t===e.length-1?``:e.slice(t+1).toLowerCase()}function ge(e){let t=V(e);for(let e of h)if(g[e].includes(t))return e;return null}function _e(e){return he[H(e.trim())]}const ve=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*(\s*;.*)?$/i,ye=/^[A-Za-z0-9+/]*={0,2}$/,be=/[/\\\u0000-\u001f\u007f]/;var U=class{code;message;detail;constructor(e,t,n){this.code=e,this.message=t,this.detail=n}};function W(e,t,n=t){throw new U(e,t,n)}function xe(e,t){let n=e=>W(`ATTACHMENT_URL_NOT_ALLOWED`,`The attachment URL is not allowed: ${e}.`,`${t}.url ${e}`);e.length>2048&&n(`must be at most ${c} characters long`);let r=me(e)??n(`must be a valid URL`);r.protocol!==`https:`&&n(`must use https`),(r.username||r.password)&&n(`must not contain credentials`),r.port&&r.port!==`443`&&n(`must use the default port`);let i=r.hostname.toLowerCase().replace(/\.$/,``);(i===`localhost`||i.endsWith(`.localhost`)||i.endsWith(`.local`)||i.endsWith(`.internal`))&&n(`must not point to a local host`),!i.startsWith(`[`)&&!i.includes(`.`)&&n(`must use a fully qualified host name`),(z(i)||B(i))&&n(`must not point to a private address`)}async function Se(e,t){let n=e=>W(`ATTACHMENT_INVALID`,`The attachment is invalid.`,e);typeof e==`object`&&e||n(`${t} must be an object`);let{filename:r,disposition:i,contentId:a}=e;(typeof r!=`string`||r.trim()===``)&&n(`${t}.filename is required`),r.length>255&&n(`${t}.filename must be at most 255 characters long`),be.test(r)&&n(`${t}.filename must not contain path separators or control characters`);let o=`url`in e&&e.url!==void 0;o===(`content`in e&&e.content!==void 0)&&n(`${t} must have exactly one of url or content`),i!==void 0&&!d.includes(i)&&n(`${t}.disposition must be one of attachment, inline`),a!==void 0&&(typeof a!=`string`||a===``||a.length>255)&&n(`${t}.contentId must be a non-empty string of at most 255 characters`),i===`inline`&&(a??``).trim()===``&&n(`${t}.contentId is required for inline attachments`);let s={...i===void 0?{}:{disposition:i},...a===void 0?{}:{contentId:a}},c=e=>e===void 0||e.trim()===``?n(`${t}.contentType is required`):(ve.test(e)||n(`${t}.contentType must be a type/subtype MIME type`),e);if(o){let{url:i}=e;return typeof i==`string`?(xe(i,t),{body:{filename:r,contentType:c(e.contentType),url:i,...s},size:null}):n(`${t}.url must be a string`)}let{content:l}=e,u,f,p;if(typeof l==`string`)l.length%4==0&&ye.test(l)||n(`${t}.content must be valid base64`),u=l,f=pe(l);else{let e;if(l instanceof Uint8Array)e=l;else if(l instanceof ArrayBuffer)e=new Uint8Array(l);else if(ArrayBuffer.isView(l))e=new Uint8Array(l.buffer,l.byteOffset,l.byteLength);else if(I(l))p=l.type||void 0,e=new Uint8Array(await l.arrayBuffer());else return n(`${t}.content must be a Uint8Array, ArrayBuffer, Blob or base64 string`);u=fe(e),f=e.byteLength}return{body:{filename:r,contentType:c(e.contentType??p??_e(r)),content:u,...s},size:f}}function Ce(e,t,n){if(e===`email`){t.length>10&&W(`ATTACHMENTS_LIMIT_EXCEEDED`,`An email accepts at most 10 attachments.`);let e=0;t.forEach(({body:t,size:n},r)=>{let i=`attachments.${r}`;p.includes(V(t.contentType))||W(`ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED`,`The attachment content type is not allowed for email.`,`${i}.contentType ${V(t.contentType)} is not allowed`),m.includes(H(t.filename.trim()))&&W(`ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED`,`The attachment file extension is not allowed.`,`${i}.filename has a blocked extension`),e+=n??0}),e>20971520&&W(`ATTACHMENT_TOO_LARGE`,`Email attachments must add up to at most ${r} bytes.`);return}t.length>1&&W(`ATTACHMENTS_LIMIT_EXCEEDED`,`A WhatsApp message accepts at most 1 attachment.`);let[i]=t;if(!i)return;let a=`attachments.0`;(i.body.disposition!==void 0||i.body.contentId!==void 0)&&W(`ATTACHMENT_INVALID`,`The attachment is invalid.`,`${a}.disposition and contentId are email-only`);let o=ge(i.body.contentType);o||W(`ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED`,`The attachment content type is not allowed for WhatsApp.`,`${a}.contentType ${V(i.body.contentType)} is not allowed`);let c=_[o];i.size!==null&&i.size>c&&W(`ATTACHMENT_TOO_LARGE`,`WhatsApp ${o} attachments must be at most ${c} bytes.`),n!==void 0&&o===`audio`&&W(`WHATSAPP_CAPTION_INVALID`,`WhatsApp audio does not accept a caption.`,`content must be empty for audio attachments`),n!==void 0&&n.length>1024&&W(`WHATSAPP_CAPTION_INVALID`,`A WhatsApp caption must be at most ${s} characters long.`,`content must be at most ${s} characters long`)}async function we(e,t,n=``){try{let n=L(e.to);n!==`email`&&n!==`whatsapp`&&W(`ATTACHMENTS_NOT_SUPPORTED_FOR_CHANNEL`,`Attachments are not supported for the ${n} channel.`),e.providerTemplate!==void 0&&W(`ATTACHMENTS_PROVIDER_TEMPLATE_CONFLICT`,`Attachments cannot be combined with providerTemplate.`),Array.isArray(t)||W(`ATTACHMENT_INVALID`,`The attachment is invalid.`,`attachments must be an array`);let r=[];for(let[e,n]of t.entries())r.push(await Se(n,`attachments.${e}`));return Ce(n,r,e.content),k(r.map(({body:e})=>e))}catch(e){if(!(e instanceof U))throw e;return A(new y({code:e.code,message:e.message,status:400,errors:[`${n}${e.detail}`]}))}}function Te(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}async function G(e,t=``){let{to:n,sendAt:r,attachments:i,...a}=e,{idempotencyKey:o,...s}=a,c=R(n),l;if(i!==void 0&&i.length>0){let e=await we({to:c,content:s.content,providerTemplate:s.providerTemplate},i,t);if(e.error)return A(e.error);l=e.data}return k(Te({...s,to:c,sendAt:P(r),attachments:l}))}var K=class{http;constructor(e){this.http=e}async send(e,t){let n=await G(e);return n.error?A(n.error):this.http.request({method:`POST`,path:`/messages`,body:n.data,...e.idempotencyKey===void 0?{}:{idempotencyKey:e.idempotencyKey},...t?{options:t}:{}})}async batch(e,t){let{idempotencyKey:n,...r}=t??{},i=[];for(let[t,n]of e.entries()){let e=await G(n,`${t}.`);if(e.error)return A(e.error);i.push(e.data)}return this.http.request({method:`POST`,path:`/messages/batch`,body:i,...n===void 0?{}:{idempotencyKey:n},...t?{options:r}:{}})}async create(e,t){return this.send(e,t)}async retry(e,t,n){return this.http.request({method:`POST`,path:`/messages/${encodeURIComponent(e)}/retry`,idempotencyKey:t.idempotencyKey,...n?{options:n}:{}})}async get(e,t){return this.http.request({method:`GET`,path:`/messages/${encodeURIComponent(e)}`,...t?{options:t}:{}})}async retrieve(e,t){return this.get(e,t)}async list(e={},t){let{data:n,error:r}=await this.http.request({method:`GET`,path:`/messages`,query:de(e),...t?{options:t}:{}});return r?{data:null,error:r}:{data:new N(n,n=>this.list({...e,cursor:n},t)),error:null}}},q=class{messages;constructor(e){this.messages=e}async send(e,t){let{to:n,...r}=e;return this.messages.send({...r,to:typeof n==`string`?{sms:n}:n},t)}async batch(e,t){return this.messages.batch(e.map(({to:e,...t})=>({...t,to:typeof e==`string`?{sms:e}:e})),t)}},J=class{messages;http;constructor(e,t){this.messages=e,this.http=t}async createSubscriptionToken(e,t){return this.http.request({method:`POST`,path:`/webpush/subscription-tokens`,body:e,...t?{options:t}:{}})}async send(e,t){let{to:n,...r}=e;return this.messages.send({...r,to:{webpush:typeof n==`string`?{recipientId:n}:n}},t)}async batch(e,t){return this.messages.batch(e.map(({to:e,...t})=>({...t,to:{webpush:typeof e==`string`?{recipientId:e}:e}})),t)}},Y=class{messages;constructor(e){this.messages=e}async send(e,t){let{to:n,...r}=e;return this.messages.send({...r,to:typeof n==`string`?{whatsapp:n}:n},t)}async batch(e,t){return this.messages.batch(e.map(({to:e,...t})=>({...t,to:typeof e==`string`?{whatsapp:e}:e})),t)}},X=class{http;constructor(e){this.http=e}list(e={},t){return this.http.request({method:`GET`,path:`/whatsapp-templates`,query:{senderId:e.senderId},...t?{options:t}:{}})}get(e,t){return this.http.request({method:`GET`,path:`/whatsapp-templates/${encodeURIComponent(e)}`,...t?{options:t}:{}})}create(e,t){return this.http.request({method:`POST`,path:`/whatsapp-templates`,body:e,...t?{options:t}:{}})}update(e,t,n){return this.http.request({method:`PATCH`,path:`/whatsapp-templates/${encodeURIComponent(e)}`,body:t,...n?{options:n}:{}})}submit(e,t,n){return this.http.request({method:`POST`,path:`/whatsapp-templates/${encodeURIComponent(e)}/submit`,body:t,...n?{options:n}:{}})}sync(e,t){return this.http.request({method:`POST`,path:`/whatsapp-templates/sync`,body:e,...t?{options:t}:{}})}};function Ee(e){return(globalThis.process?.env?.[e])?.trim()||void 0}const De=`https://api.messaging.rockfeller.com.br`;var Z=class{messages;emails;whatsapp;whatsappTemplates;sms;webPush;constructor(e){let t=typeof e==`string`?{secret:e}:e,n=t.secret?.trim();if(!n)throw Error("Messaging: `secret` é obrigatório. Use a API key do projeto, por exemplo new Messaging({ secret: process.env.MESSAGING_API_KEY }).");let r=new ue({secret:n,baseUrl:(t.baseUrl??Ee(`MESSAGING_BASE_URL`)??`https://api.messaging.rockfeller.com.br`).replace(/\/+$/,``),timeout:t.timeout??3e4,maxRetries:t.maxRetries??2,headers:t.headers??{},fetch:t.fetch??((e,t)=>globalThis.fetch(e,t))});this.messages=new K(r),this.emails=new M(this.messages),this.whatsapp=new Y(this.messages),this.whatsappTemplates=new X(r),this.sms=new q(this.messages),this.webPush=new J(this.messages,r)}};const Oe=25,ke=100,Ae=100,je=262144,Me=1600,Ne=65536,Pe=998,Fe=[`email`,`whatsapp`,`sms`,`webpush`],Q=[`resend`,`unosend`,`twilio`,`meta`,`evolution`],Ie=[`normal`,`low`],Le=[`accepted`,`canceled`,`processing`,`sent`,`delivered`,`complained`,`bounced`,`suppressed`,`failed`],Re=[`pending`,`canceled`,`processing`,`sent`,`delivered`,`complained`,`bounced`,`suppressed`,`failed`],ze=[`delivered`,`complained`],Be=[`bounced`,`suppressed`,`failed`],$=[`canceled`,`delivered`,`complained`,`bounced`,`suppressed`,`failed`];function Ve(e){return $.includes(e)}const He=[`sent`,`failed`,`unknown`],Ue=[`email.sent`,`email.delivered`,`email.delivery_delayed`,`email.opened`,`email.clicked`,`email.bounced`,`email.complained`,`email.failed`,`email.suppressed`,`whatsapp.sent`,`whatsapp.delivered`,`whatsapp.read`,`whatsapp.failed`,`sms.sent`,`sms.delivered`,`sms.failed`,`sms.bounced`,`webpush.sent`,`webpush.failed`,`webpush.expired`],We=[`MARKETING`,`UTILITY`],Ge=[`DRAFT`,`SUBMITTING`,`SUBMISSION_UNKNOWN`,`PENDING`,`APPROVED`,`REJECTED`,`PAUSED`,`DISABLED`,`DELETED`];export{l as ATTACHMENT_FILENAME_MAX_LENGTH,c as ATTACHMENT_URL_MAX_LENGTH,b as AuthenticationError,m as BLOCKED_ATTACHMENT_EXTENSIONS,T as ConnectionError,De as DEFAULT_BASE_URL,le as DEFAULT_MAX_RETRIES,ce as DEFAULT_TIMEOUT_MS,n as EMAIL_ATTACHMENTS_MAX_COUNT,r as EMAIL_ATTACHMENTS_MAX_TOTAL_BYTES,p as EMAIL_ATTACHMENT_CONTENT_TYPES,d as EMAIL_ATTACHMENT_DISPOSITIONS,M as Emails,u as MESSAGE_ATTACHMENT_SOURCES,He as MESSAGE_ATTEMPT_OUTCOMES,Ae as MESSAGE_BATCH_MAX_SIZE,je as MESSAGE_BODY_MAX_BYTES,ze as MESSAGE_DELIVERED_STATUSES,Re as MESSAGE_DELIVERY_STATUSES,$ as MESSAGE_DELIVERY_TERMINAL_STATUSES,Ue as MESSAGE_EVENT_TYPES,Ne as MESSAGE_JSON_MAX_BYTES,Oe as MESSAGE_LIST_DEFAULT_LIMIT,ke as MESSAGE_LIST_MAX_LIMIT,Ie as MESSAGE_PRIORITIES,Le as MESSAGE_STATUSES,Pe as MESSAGE_SUBJECT_MAX_LENGTH,Be as MESSAGE_UNDELIVERED_STATUSES,ee as MESSAGING_ERROR_CODES,K as Messages,N as MessagesPage,Z as Messaging,Z as default,v as MessagingError,S as NotFoundError,Fe as PROVIDER_CHANNELS,Q as PROVIDER_IDS,x as PermissionError,C as RateLimitError,Me as SMS_CONTENT_MAX_LENGTH,w as ServerError,q as Sms,E as TimeoutError,j as VERSION,y as ValidationError,i as WHATSAPP_ATTACHMENTS_MAX_COUNT,s as WHATSAPP_CAPTION_MAX_LENGTH,a as WHATSAPP_IMAGE_MAX_BYTES,h as WHATSAPP_MEDIA_KINDS,o as WHATSAPP_MEDIA_MAX_BYTES,_ as WHATSAPP_MEDIA_MAX_BYTES_BY_KIND,g as WHATSAPP_MEDIA_TYPES,We as WHATSAPP_TEMPLATE_CATEGORIES,Ge as WHATSAPP_TEMPLATE_STATUSES,J as WebPush,Y as WhatsApp,X as WhatsAppTemplates,A as failure,te as isMessagingError,Ve as isTerminalDeliveryStatus,k as success};
|
|
1
|
+
import{t as e}from"../version-DiXfOKVT.js";const t=1048576,n=10,r=20*t,i=1,a=5*t,o=10*t,s=1024,c=2048,l=255,u=[`upload`,`url`],d=[`attachment`,`inline`],f=[`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/vnd.ms-powerpoint`,`application/vnd.openxmlformats-officedocument.presentationml.presentation`],p=[`application/pdf`,`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`text/csv`,`text/plain`,...f,`application/vnd.oasis.opendocument.text`,`application/vnd.oasis.opendocument.spreadsheet`,`application/zip`,`text/calendar`],m=/* @__PURE__ */ `apk.app.bat.cmd.com.cpl.dll.dmg.exe.hta.jar.js.jse.lnk.msi.msp.pif.ps1.reg.scr.sh.vb.vbe.vbs.wsf.wsh`.split(`.`),h=[`image`,`video`,`audio`,`document`],g={image:[`image/jpeg`,`image/png`],video:[`video/mp4`,`video/3gpp`],audio:[`audio/aac`,`audio/mp4`,`audio/mpeg`,`audio/amr`,`audio/ogg`],document:[`application/pdf`,...f,`text/plain`,`text/csv`,`application/zip`]},_={image:a,video:o,audio:o,document:o},ee=/* @__PURE__ */ `UNAUTHENTICATED.INVALID_API_KEY.ACTIVE_PROJECT_REQUIRED.PROJECT_ROLE_REQUIRED.VALIDATION_ERROR.FROM_DOMAIN_NOT_VERIFIED.SENDER_NOT_FOUND.WHATSAPP_TEMPLATE_NOT_FOUND.WHATSAPP_TEMPLATE_CONFLICT.WHATSAPP_TEMPLATE_PROVIDER_UNSUPPORTED.WHATSAPP_TEMPLATE_SUBMISSION_FAILED.WHATSAPP_TEMPLATE_SYNC_FAILED.WHATSAPP_TEMPLATE_INVALID_STATE.WHATSAPP_TEMPLATE_BODY_CONFLICT.ATTACHMENTS_NOT_SUPPORTED_FOR_CHANNEL.ATTACHMENTS_PROVIDER_TEMPLATE_CONFLICT.ATTACHMENT_INVALID.ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED.ATTACHMENT_TOO_LARGE.ATTACHMENTS_LIMIT_EXCEEDED.ATTACHMENT_URL_NOT_ALLOWED.WHATSAPP_CAPTION_INVALID.PAYLOAD_TOO_LARGE.ATTACHMENT_STORAGE_UNAVAILABLE.ATTACHMENT_STORAGE_NOT_CONFIGURED.ATTACHMENT_EXPIRED.MESSAGE_NOT_FOUND.SUPPRESSION_NOT_FOUND.MESSAGE_NOT_RETRYABLE.MESSAGE_CONTENT_EXPIRED.IDEMPOTENCY_KEY_REUSED.ROUTE_NOT_FOUND.INTERNAL_SERVER_ERROR.RATE_LIMIT_EXCEEDED.CONNECTION_ERROR.TIMEOUT.UNEXPECTED_RESPONSE`.split(`.`);var v=class extends Error{name=`MessagingError`;code;status;errors;constructor(e){super(e.message,{cause:e.cause}),this.code=e.code,this.status=e.status,this.errors=e.errors}get retryable(){return this.status===0||this.status===408||this.status===429||this.status>=500}toJSON(){return{name:this.name,code:this.code,message:this.message,status:this.status,...this.errors?{errors:this.errors}:{}}}},y=class extends v{name=`ValidationError`},b=class extends v{name=`AuthenticationError`},x=class extends v{name=`PermissionError`},S=class extends v{name=`NotFoundError`},C=class extends v{name=`RateLimitError`;retryAfter;constructor(e){super(e),this.retryAfter=e.retryAfter}},w=class extends v{name=`ServerError`},T=class extends v{name=`ConnectionError`},E=class extends v{name=`TimeoutError`};function te(e){return e instanceof v}function ne(e){let t={code:e.code,message:e.message,status:e.status,...e.errors?{errors:e.errors}:{}};return e.status===429?new C({...t,...e.retryAfter===void 0?{}:{retryAfter:e.retryAfter}}):e.status>=500?new w(t):e.status===401?new b(t):e.status===403?new x(t):e.status===404?new S(t):e.status===400||e.status===422?new y(t):new v(t)}function re(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e))if(r!==void 0){if(Array.isArray(r))for(let e of r)t.append(n,String(e));else t.append(n,r instanceof Date?r.toISOString():String(r))}let n=t.toString();return n?`?${n}`:``}const D=8e3,ie=e=>new Promise(t=>setTimeout(t,e));function ae(e,t){if(t!==void 0)return Math.min(t*1e3,D);let n=Math.min(500*2**e,D);return Math.round(n*(.5+Math.random()*.5))}function oe(e){if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t;let n=Date.parse(e);if(!Number.isNaN(n))return Math.max(0,Math.round((n-Date.now())/1e3))}function O(e){if(e.length===1)return e[0];let t=AbortSignal.any;if(t)return t(e);let n=new AbortController;for(let t of e){if(t.aborted){n.abort(t.reason);break}t.addEventListener(`abort`,()=>n.abort(t.reason),{once:!0})}return n.signal}function k(e){return{data:e,error:null}}function A(e){return{data:null,error:e}}const j=e,se=`rockdev-messaging-node/${j}`,ce=3e4,le=2;var ue=class{config;constructor(e){this.config=e}async request(e){let t=`${this.config.baseUrl}/v1${e.path}${e.query?re(e.query):``}`,n=e.method===`GET`||e.idempotencyKey!==void 0?this.config.maxRetries:0,r;for(let i=0;i<=n;i+=1){let a=await this.attempt(t,e);if(a.error===null)return a;if(r=a.error,!a.error.retryable||e.options?.signal?.aborted||i===n)break;await ie(ae(i,a.error.retryAfter))}return A(r)}async attempt(e,t){let n=t.options?.timeout??this.config.timeout,r=new AbortController,i=setTimeout(()=>r.abort(),n),a=[r.signal];t.options?.signal&&a.push(t.options.signal);let o;try{o=await this.config.fetch(e,{method:t.method,headers:this.headers(t),signal:O(a),...t.body===void 0?{}:{body:JSON.stringify(t.body)}})}catch(e){return t.options?.signal?.aborted?A(new v({code:`CONNECTION_ERROR`,message:`The request was aborted by the caller.`,status:0,cause:e})):r.signal.aborted?A(new E({code:`TIMEOUT`,message:`The request did not complete within ${n}ms.`,status:0,cause:e})):A(new T({code:`CONNECTION_ERROR`,message:e instanceof Error?e.message:`The request could not reach the Messaging API.`,status:0,cause:e}))}finally{clearTimeout(i)}return this.parse(o)}headers(e){let t=e=>Object.fromEntries(Object.entries(e).filter(([e])=>e.toLowerCase()!==`idempotency-key`));return{accept:`application/json`,authorization:`Bearer ${this.config.secret}`,"user-agent":se,...e.body===void 0?{}:{"content-type":`application/json`},...t(this.config.headers),...t(e.options?.headers??{}),...e.idempotencyKey===void 0?{}:{"idempotency-key":e.idempotencyKey}}}async parse(e){let t=await e.text().catch(()=>``),n;try{n=t?JSON.parse(t):void 0}catch{n=void 0}if(!e.ok){let t=oe(e.headers.get(`retry-after`));return A(ne({code:n?.code??`INTERNAL_SERVER_ERROR`,message:n?.message??`The Messaging API responded with ${e.status}.`,status:e.status,...n?.errors?{errors:n.errors}:{},...t===void 0?{}:{retryAfter:t}}))}return!n||n.data===void 0?A(new v({code:`UNEXPECTED_RESPONSE`,message:`The Messaging API responded without the expected body.`,status:e.status})):k(n.data)}},M=class{messages;constructor(e){this.messages=e}async send(e,t){let{to:n,...r}=e;return this.messages.send({...r,to:typeof n==`string`?{email:n}:n},t)}async batch(e,t){return this.messages.batch(e.map(({to:e,...t})=>({...t,to:typeof e==`string`?{email:e}:e})),t)}},N=class e{fetchPage;messages;nextCursor;constructor(e,t){this.fetchPage=t,this.messages=e.messages,this.nextCursor=e.nextCursor}get hasMore(){return this.nextCursor!==null}async next(){return this.nextCursor===null?{data:new e({messages:[],nextCursor:null},this.fetchPage),error:null}:this.fetchPage(this.nextCursor)}async*[Symbol.asyncIterator](){let e=this;for(;;){for(let t of e.messages)yield t;if(!e.hasMore)return;let{data:t,error:n}=await e.next();if(n)throw n;e=t}}};function P(e){if(e!==void 0)return e instanceof Date?e.toISOString():e}function de(e){return{status:e.status,channel:e.channel,to:e.to,search:e.search,scheduled:e.scheduled,createdAfter:P(e.createdAfter),createdBefore:P(e.createdBefore),limit:e.limit,cursor:e.cursor}}const F=24576;function fe(e){if(typeof e.toBase64==`function`)return e.toBase64();let t=globalThis.Buffer;if(t)return t.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`);let n=``;for(let t=0;t<e.length;t+=F){let r=e.subarray(t,t+F),i=``;for(let e=0;e<r.length;e+=1)i+=String.fromCharCode(r[e]);n+=btoa(i)}return n}function pe(e){let t=e.endsWith(`==`)?2:+!!e.endsWith(`=`);return e.length/4*3-t}function me(e){return typeof Blob<`u`&&e instanceof Blob}function I(e){return`email`in e&&e.email!==void 0?`email`:`whatsapp`in e&&e.whatsapp!==void 0?`whatsapp`:`sms`in e&&e.sms!==void 0?`sms`:`webpush`}function L(e){return typeof e==`string`?e.includes(`@`)?{email:e}:{whatsapp:e}:e}function R(e){let t=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(e);if(!t)return null;let[n,r]=[Number(t[1]),Number(t[2])];return n===0||n===10||n===127||n===100&&r>=64&&r<=127||n===169&&r===254||n===172&&r>=16&&r<=31||n===192&&r===168||n===198&&(r===18||r===19)||n>=224}function z(e){if(!e.startsWith(`[`))return null;let t=e.slice(1,-1).toLowerCase(),n=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(t);return n?.[1]?R(n[1])??!0:t===`::`||t===`::1`||t.startsWith(`::ffff:`)||/^f[cd]/.test(t)||/^fe[89ab]/.test(t)||t.startsWith(`ff`)}function he(e){try{return new URL(e)}catch{return null}}const ge={pdf:`application/pdf`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,csv:`text/csv`,txt:`text/plain`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,xls:`application/vnd.ms-excel`,xlsx:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,ppt:`application/vnd.ms-powerpoint`,pptx:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,odt:`application/vnd.oasis.opendocument.text`,ods:`application/vnd.oasis.opendocument.spreadsheet`,zip:`application/zip`,ics:`text/calendar`,mp4:`video/mp4`,"3gp":`video/3gpp`,aac:`audio/aac`,m4a:`audio/mp4`,mp3:`audio/mpeg`,amr:`audio/amr`,ogg:`audio/ogg`,opus:`audio/ogg`};function B(e){return(e.split(`;`)[0]??``).trim().toLowerCase()}function V(e){let t=e.lastIndexOf(`.`);return t<=0||t===e.length-1?``:e.slice(t+1).toLowerCase()}function _e(e){let t=B(e);for(let e of h)if(g[e].includes(t))return e;return null}function ve(e){return ge[V(e.trim())]}const ye=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*(\s*;.*)?$/i,be=/^[A-Za-z0-9+/]*={0,2}$/,xe=/[/\\\u0000-\u001f\u007f]/;var H=class{code;message;detail;constructor(e,t,n){this.code=e,this.message=t,this.detail=n}};function U(e,t,n=t){throw new H(e,t,n)}function Se(e,t){let n=e=>U(`ATTACHMENT_URL_NOT_ALLOWED`,`The attachment URL is not allowed: ${e}.`,`${t}.url ${e}`);e.length>2048&&n(`must be at most ${c} characters long`);let r=he(e)??n(`must be a valid URL`);r.protocol!==`https:`&&n(`must use https`),(r.username||r.password)&&n(`must not contain credentials`),r.port&&r.port!==`443`&&n(`must use the default port`);let i=r.hostname.toLowerCase().replace(/\.$/,``);(i===`localhost`||i.endsWith(`.localhost`)||i.endsWith(`.local`)||i.endsWith(`.internal`))&&n(`must not point to a local host`),!i.startsWith(`[`)&&!i.includes(`.`)&&n(`must use a fully qualified host name`),(R(i)||z(i))&&n(`must not point to a private address`)}async function Ce(e,t){let n=e=>U(`ATTACHMENT_INVALID`,`The attachment is invalid.`,e);typeof e==`object`&&e||n(`${t} must be an object`);let{filename:r,disposition:i,contentId:a}=e;(typeof r!=`string`||r.trim()===``)&&n(`${t}.filename is required`),r.length>255&&n(`${t}.filename must be at most 255 characters long`),xe.test(r)&&n(`${t}.filename must not contain path separators or control characters`);let o=`url`in e&&e.url!==void 0;o===(`content`in e&&e.content!==void 0)&&n(`${t} must have exactly one of url or content`),i!==void 0&&!d.includes(i)&&n(`${t}.disposition must be one of attachment, inline`),a!==void 0&&(typeof a!=`string`||a===``||a.length>255)&&n(`${t}.contentId must be a non-empty string of at most 255 characters`),i===`inline`&&(a??``).trim()===``&&n(`${t}.contentId is required for inline attachments`);let s={...i===void 0?{}:{disposition:i},...a===void 0?{}:{contentId:a}},c=e=>e===void 0||e.trim()===``?n(`${t}.contentType is required`):(ye.test(e)||n(`${t}.contentType must be a type/subtype MIME type`),e);if(o){let{url:i}=e;return typeof i==`string`?(Se(i,t),{body:{filename:r,contentType:c(e.contentType),url:i,...s},size:null}):n(`${t}.url must be a string`)}let{content:l}=e,u,f,p;if(typeof l==`string`)l.length%4==0&&be.test(l)||n(`${t}.content must be valid base64`),u=l,f=pe(l);else{let e;if(l instanceof Uint8Array)e=l;else if(l instanceof ArrayBuffer)e=new Uint8Array(l);else if(ArrayBuffer.isView(l))e=new Uint8Array(l.buffer,l.byteOffset,l.byteLength);else if(me(l))p=l.type||void 0,e=new Uint8Array(await l.arrayBuffer());else return n(`${t}.content must be a Uint8Array, ArrayBuffer, Blob or base64 string`);u=fe(e),f=e.byteLength}return{body:{filename:r,contentType:c(e.contentType??p??ve(r)),content:u,...s},size:f}}function we(e,t,n){if(e===`email`){t.length>10&&U(`ATTACHMENTS_LIMIT_EXCEEDED`,`An email accepts at most 10 attachments.`);let e=0;t.forEach(({body:t,size:n},r)=>{let i=`attachments.${r}`;p.includes(B(t.contentType))||U(`ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED`,`The attachment content type is not allowed for email.`,`${i}.contentType ${B(t.contentType)} is not allowed`),m.includes(V(t.filename.trim()))&&U(`ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED`,`The attachment file extension is not allowed.`,`${i}.filename has a blocked extension`),e+=n??0}),e>20971520&&U(`ATTACHMENT_TOO_LARGE`,`Email attachments must add up to at most ${r} bytes.`);return}t.length>1&&U(`ATTACHMENTS_LIMIT_EXCEEDED`,`A WhatsApp message accepts at most 1 attachment.`);let[i]=t;if(!i)return;let a=`attachments.0`;(i.body.disposition!==void 0||i.body.contentId!==void 0)&&U(`ATTACHMENT_INVALID`,`The attachment is invalid.`,`${a}.disposition and contentId are email-only`);let o=_e(i.body.contentType);o||U(`ATTACHMENT_CONTENT_TYPE_NOT_ALLOWED`,`The attachment content type is not allowed for WhatsApp.`,`${a}.contentType ${B(i.body.contentType)} is not allowed`);let c=_[o];i.size!==null&&i.size>c&&U(`ATTACHMENT_TOO_LARGE`,`WhatsApp ${o} attachments must be at most ${c} bytes.`),n!==void 0&&o===`audio`&&U(`WHATSAPP_CAPTION_INVALID`,`WhatsApp audio does not accept a caption.`,`content must be empty for audio attachments`),n!==void 0&&n.length>1024&&U(`WHATSAPP_CAPTION_INVALID`,`A WhatsApp caption must be at most ${s} characters long.`,`content must be at most ${s} characters long`)}async function Te(e,t,n=``){try{let n=I(e.to);n!==`email`&&n!==`whatsapp`&&U(`ATTACHMENTS_NOT_SUPPORTED_FOR_CHANNEL`,`Attachments are not supported for the ${n} channel.`),e.providerTemplate!==void 0&&U(`ATTACHMENTS_PROVIDER_TEMPLATE_CONFLICT`,`Attachments cannot be combined with providerTemplate.`),Array.isArray(t)||U(`ATTACHMENT_INVALID`,`The attachment is invalid.`,`attachments must be an array`);let r=[];for(let[e,n]of t.entries())r.push(await Ce(n,`attachments.${e}`));return we(n,r,e.content),k(r.map(({body:e})=>e))}catch(e){if(!(e instanceof H))throw e;return A(new y({code:e.code,message:e.message,status:400,errors:[`${n}${e.detail}`]}))}}function Ee(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}async function W(e,t=``){let{to:n,sendAt:r,attachments:i,...a}=e,{idempotencyKey:o,...s}=a,c=L(n),l;if(i!==void 0&&i.length>0){let e=await Te({to:c,content:s.content,providerTemplate:s.providerTemplate},i,t);if(e.error)return A(e.error);l=e.data}return k(Ee({...s,to:c,sendAt:P(r),attachments:l}))}var G=class{http;constructor(e){this.http=e}async send(e,t){let n=await W(e);return n.error?A(n.error):this.http.request({method:`POST`,path:`/messages`,body:n.data,...e.idempotencyKey===void 0?{}:{idempotencyKey:e.idempotencyKey},...t?{options:t}:{}})}async batch(e,t){let{idempotencyKey:n,...r}=t??{},i=[];for(let[t,n]of e.entries()){let e=await W(n,`${t}.`);if(e.error)return A(e.error);i.push(e.data)}return this.http.request({method:`POST`,path:`/messages/batch`,body:i,...n===void 0?{}:{idempotencyKey:n},...t?{options:r}:{}})}async create(e,t){return this.send(e,t)}async retry(e,t,n){return this.http.request({method:`POST`,path:`/messages/${encodeURIComponent(e)}/retry`,idempotencyKey:t.idempotencyKey,...n?{options:n}:{}})}async get(e,t){return this.http.request({method:`GET`,path:`/messages/${encodeURIComponent(e)}`,...t?{options:t}:{}})}async retrieve(e,t){return this.get(e,t)}async list(e={},t){let{data:n,error:r}=await this.http.request({method:`GET`,path:`/messages`,query:de(e),...t?{options:t}:{}});return r?{data:null,error:r}:{data:new N(n,n=>this.list({...e,cursor:n},t)),error:null}}},K=class{messages;constructor(e){this.messages=e}async send(e,t){let{to:n,...r}=e;return this.messages.send({...r,to:typeof n==`string`?{sms:n}:n},t)}async batch(e,t){return this.messages.batch(e.map(({to:e,...t})=>({...t,to:typeof e==`string`?{sms:e}:e})),t)}},q=class{http;constructor(e){this.http=e}create(e,t){return this.http.request({method:`POST`,path:`/suppressions`,body:e,...t?{options:t}:{}})}batch(e,t){return this.http.request({method:`POST`,path:`/suppressions/batch`,body:e,...t?{options:t}:{}})}get(e,t){return this.http.request({method:`GET`,path:`/suppressions/${encodeURIComponent(e)}`,...t?{options:t}:{}})}list(e={},t){return this.http.request({method:`GET`,path:`/suppressions`,query:{email:e.email,reason:e.reason,limit:e.limit,cursor:e.cursor},...t?{options:t}:{}})}delete(e,t){return this.http.request({method:`DELETE`,path:`/suppressions/${encodeURIComponent(e)}`,...t?{options:t}:{}})}batchDelete(e,t){return this.http.request({method:`POST`,path:`/suppressions/batch/delete`,body:e,...t?{options:t}:{}})}},J=class{messages;http;constructor(e,t){this.messages=e,this.http=t}async createSubscriptionToken(e,t){return this.http.request({method:`POST`,path:`/webpush/subscription-tokens`,body:e,...t?{options:t}:{}})}async send(e,t){let{to:n,...r}=e;return this.messages.send({...r,to:{webpush:typeof n==`string`?{recipientId:n}:n}},t)}async batch(e,t){return this.messages.batch(e.map(({to:e,...t})=>({...t,to:{webpush:typeof e==`string`?{recipientId:e}:e}})),t)}},Y=class{messages;constructor(e){this.messages=e}async send(e,t){let{to:n,...r}=e;return this.messages.send({...r,to:typeof n==`string`?{whatsapp:n}:n},t)}async batch(e,t){return this.messages.batch(e.map(({to:e,...t})=>({...t,to:typeof e==`string`?{whatsapp:e}:e})),t)}},X=class{http;constructor(e){this.http=e}list(e={},t){return this.http.request({method:`GET`,path:`/whatsapp-templates`,query:{senderId:e.senderId},...t?{options:t}:{}})}get(e,t){return this.http.request({method:`GET`,path:`/whatsapp-templates/${encodeURIComponent(e)}`,...t?{options:t}:{}})}create(e,t){return this.http.request({method:`POST`,path:`/whatsapp-templates`,body:e,...t?{options:t}:{}})}update(e,t,n){return this.http.request({method:`PATCH`,path:`/whatsapp-templates/${encodeURIComponent(e)}`,body:t,...n?{options:n}:{}})}submit(e,t,n){return this.http.request({method:`POST`,path:`/whatsapp-templates/${encodeURIComponent(e)}/submit`,body:t,...n?{options:n}:{}})}sync(e,t){return this.http.request({method:`POST`,path:`/whatsapp-templates/sync`,body:e,...t?{options:t}:{}})}};function De(e){return(globalThis.process?.env?.[e])?.trim()||void 0}const Oe=`https://api.messaging.rockfeller.com.br`;var Z=class{messages;emails;whatsapp;whatsappTemplates;sms;webPush;suppressions;constructor(e){let t=typeof e==`string`?{secret:e}:e,n=t.secret?.trim();if(!n)throw Error("Messaging: `secret` é obrigatório. Use a API key do projeto, por exemplo new Messaging({ secret: process.env.MESSAGING_API_KEY }).");let r=new ue({secret:n,baseUrl:(t.baseUrl??De(`MESSAGING_BASE_URL`)??`https://api.messaging.rockfeller.com.br`).replace(/\/+$/,``),timeout:t.timeout??3e4,maxRetries:t.maxRetries??2,headers:t.headers??{},fetch:t.fetch??((e,t)=>globalThis.fetch(e,t))});this.messages=new G(r),this.emails=new M(this.messages),this.whatsapp=new Y(this.messages),this.whatsappTemplates=new X(r),this.sms=new K(this.messages),this.webPush=new J(this.messages,r),this.suppressions=new q(r)}};const ke=25,Ae=100,je=100,Me=262144,Ne=1600,Pe=65536,Fe=100,Ie=50,Le=100,Re=500,ze=998,Be=[`email`,`whatsapp`,`sms`,`webpush`],Ve=[`resend`,`unosend`,`twilio`,`meta`,`evolution`],He=[`normal`,`low`],Q=[`accepted`,`canceled`,`processing`,`sent`,`delivered`,`complained`,`bounced`,`suppressed`,`failed`],Ue=[`pending`,`canceled`,`processing`,`sent`,`delivered`,`complained`,`bounced`,`suppressed`,`failed`],We=[`delivered`,`complained`],Ge=[`bounced`,`suppressed`,`failed`],$=[`canceled`,`delivered`,`complained`,`bounced`,`suppressed`,`failed`];function Ke(e){return $.includes(e)}const qe=[`sent`,`failed`,`unknown`],Je=[`email.sent`,`email.delivered`,`email.delivery_delayed`,`email.opened`,`email.clicked`,`email.bounced`,`email.complained`,`email.failed`,`email.suppressed`,`whatsapp.sent`,`whatsapp.delivered`,`whatsapp.read`,`whatsapp.failed`,`sms.sent`,`sms.delivered`,`sms.failed`,`sms.bounced`,`webpush.sent`,`webpush.failed`,`webpush.expired`],Ye=[`manual`,`bounce`,`complaint`,`provider_suppressed`],Xe=[`api`,`dashboard`,`automatic`],Ze=`RECIPIENT_SUPPRESSED`,Qe=[`MARKETING`,`UTILITY`,`AUTHENTICATION`],$e=[`DRAFT`,`SUBMITTING`,`SUBMISSION_UNKNOWN`,`PENDING`,`APPROVED`,`REJECTED`,`PAUSED`,`DISABLED`,`DELETED`];export{l as ATTACHMENT_FILENAME_MAX_LENGTH,c as ATTACHMENT_URL_MAX_LENGTH,b as AuthenticationError,m as BLOCKED_ATTACHMENT_EXTENSIONS,T as ConnectionError,Oe as DEFAULT_BASE_URL,le as DEFAULT_MAX_RETRIES,ce as DEFAULT_TIMEOUT_MS,n as EMAIL_ATTACHMENTS_MAX_COUNT,r as EMAIL_ATTACHMENTS_MAX_TOTAL_BYTES,p as EMAIL_ATTACHMENT_CONTENT_TYPES,d as EMAIL_ATTACHMENT_DISPOSITIONS,M as Emails,u as MESSAGE_ATTACHMENT_SOURCES,qe as MESSAGE_ATTEMPT_OUTCOMES,je as MESSAGE_BATCH_MAX_SIZE,Me as MESSAGE_BODY_MAX_BYTES,We as MESSAGE_DELIVERED_STATUSES,Ue as MESSAGE_DELIVERY_STATUSES,$ as MESSAGE_DELIVERY_TERMINAL_STATUSES,Je as MESSAGE_EVENT_TYPES,Pe as MESSAGE_JSON_MAX_BYTES,ke as MESSAGE_LIST_DEFAULT_LIMIT,Ae as MESSAGE_LIST_MAX_LIMIT,He as MESSAGE_PRIORITIES,Q as MESSAGE_STATUSES,ze as MESSAGE_SUBJECT_MAX_LENGTH,Ge as MESSAGE_UNDELIVERED_STATUSES,ee as MESSAGING_ERROR_CODES,G as Messages,N as MessagesPage,Z as Messaging,Z as default,v as MessagingError,S as NotFoundError,Be as PROVIDER_CHANNELS,Ve as PROVIDER_IDS,x as PermissionError,Ze as RECIPIENT_SUPPRESSED_FAILURE_CODE,C as RateLimitError,Ne as SMS_CONTENT_MAX_LENGTH,Fe as SUPPRESSION_BATCH_MAX_SIZE,Ie as SUPPRESSION_LIST_DEFAULT_LIMIT,Le as SUPPRESSION_LIST_MAX_LIMIT,Re as SUPPRESSION_NOTE_MAX_LENGTH,Ye as SUPPRESSION_REASONS,Xe as SUPPRESSION_SOURCES,w as ServerError,K as Sms,q as Suppressions,E as TimeoutError,j as VERSION,y as ValidationError,i as WHATSAPP_ATTACHMENTS_MAX_COUNT,s as WHATSAPP_CAPTION_MAX_LENGTH,a as WHATSAPP_IMAGE_MAX_BYTES,h as WHATSAPP_MEDIA_KINDS,o as WHATSAPP_MEDIA_MAX_BYTES,_ as WHATSAPP_MEDIA_MAX_BYTES_BY_KIND,g as WHATSAPP_MEDIA_TYPES,Qe as WHATSAPP_TEMPLATE_CATEGORIES,$e as WHATSAPP_TEMPLATE_STATUSES,J as WebPush,Y as WhatsApp,X as WhatsAppTemplates,A as failure,te as isMessagingError,Ke as isTerminalDeliveryStatus,k as success};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return`0.
|
|
1
|
+
Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return`0.4.0`}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=`0.4.0`;export{e as t};
|
package/package.json
CHANGED
package/dist/version-B0ADow60.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e=`0.2.0`;export{e as t};
|