resend-cli 2.9.0 → 2.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/cli.cjs +86 -86
- package/package.json +2 -2
- package/skills/resend-cli/SKILL.md +2 -2
- package/skills/resend-cli/references/emails.md +4 -2
package/dist/cli.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Ju=Object.create;var hi=Object.defineProperty;var Vu=Object.getOwnPropertyDescriptor;var zu=Object.getOwnPropertyNames;var Yu=Object.getPrototypeOf,Xu=Object.prototype.hasOwnProperty;var ge=(e,t,o)=>()=>{if(o)throw o[0];try{return e&&(t=e(e=0)),t}catch(i){throw o=[i],i}};var xe=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(o){throw t=0,o}},Lt=(e,t)=>{for(var o in t)hi(e,o,{get:t[o],enumerable:!0})},Zu=(e,t,o,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of zu(t))!Xu.call(e,r)&&r!==o&&hi(e,r,{get:()=>t[r],enumerable:!(i=Vu(t,r))||i.enumerable});return e};var ue=(e,t,o)=>(o=e!=null?Ju(Yu(e)):{},Zu(t||!e||!e.__esModule?hi(o,"default",{value:e,enumerable:!0}):o,e));var Wt=xe(bi=>{var go=class extends Error{constructor(t,o,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=o,this.exitCode=t,this.nestedError=void 0}},Ai=class extends go{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};bi.CommanderError=go;bi.InvalidArgumentError=Ai});var ho=xe(yi=>{var{InvalidArgumentError:ed}=Wt(),Ci=class{constructor(t,o){switch(this.description=o||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(t,o){return o===this.defaultValue||!Array.isArray(o)?[t]:(o.push(t),o)}default(t,o){return this.defaultValue=t,this.defaultValueDescription=o,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(o,i)=>{if(!this.argChoices.includes(o))throw new ed(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(o,i):o},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function td(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}yi.Argument=Ci;yi.humanReadableArgName=td});var Ki=xe(Si=>{var{humanReadableArgName:od}=ho(),Ui=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){let o=t.commands.filter(r=>!r._hidden),i=t._getHelpCommand();return i&&!i._hidden&&o.push(i),this.sortSubcommands&&o.sort((r,n)=>r.name().localeCompare(n.name())),o}compareOptions(t,o){let i=r=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,"");return i(t).localeCompare(i(o))}visibleOptions(t){let o=t.options.filter(r=>!r.hidden),i=t._getHelpOption();if(i&&!i.hidden){let r=i.short&&t._findOption(i.short),n=i.long&&t._findOption(i.long);!r&&!n?o.push(i):i.long&&!n?o.push(t.createOption(i.long,i.description)):i.short&&!r&&o.push(t.createOption(i.short,i.description))}return this.sortOptions&&o.sort(this.compareOptions),o}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let o=[];for(let i=t.parent;i;i=i.parent){let r=i.options.filter(n=>!n.hidden);o.push(...r)}return this.sortOptions&&o.sort(this.compareOptions),o}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(o=>{o.description=o.description||t._argsDescription[o.name()]||""}),t.registeredArguments.find(o=>o.description)?t.registeredArguments:[]}subcommandTerm(t){let o=t.registeredArguments.map(i=>od(i)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(o?" "+o:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,o){return o.visibleCommands(t).reduce((i,r)=>Math.max(i,this.displayWidth(o.styleSubcommandTerm(o.subcommandTerm(r)))),0)}longestOptionTermLength(t,o){return o.visibleOptions(t).reduce((i,r)=>Math.max(i,this.displayWidth(o.styleOptionTerm(o.optionTerm(r)))),0)}longestGlobalOptionTermLength(t,o){return o.visibleGlobalOptions(t).reduce((i,r)=>Math.max(i,this.displayWidth(o.styleOptionTerm(o.optionTerm(r)))),0)}longestArgumentTermLength(t,o){return o.visibleArguments(t).reduce((i,r)=>Math.max(i,this.displayWidth(o.styleArgumentTerm(o.argumentTerm(r)))),0)}commandUsage(t){let o=t._name;t._aliases[0]&&(o=o+"|"+t._aliases[0]);let i="";for(let r=t.parent;r;r=r.parent)i=r.name()+" "+i;return i+o+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let o=[];if(t.argChoices&&o.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&o.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&o.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&o.push(`env: ${t.envVar}`),o.length>0){let i=`(${o.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}argumentDescription(t){let o=[];if(t.argChoices&&o.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&o.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),o.length>0){let i=`(${o.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}formatItemList(t,o,i){return o.length===0?[]:[i.styleTitle(t),...o,""]}groupItems(t,o,i){let r=new Map;return t.forEach(n=>{let s=i(n);r.has(s)||r.set(s,[])}),o.forEach(n=>{let s=i(n);r.has(s)||r.set(s,[]),r.get(s).push(n)}),r}formatHelp(t,o){let i=o.padWidth(t,o),r=o.helpWidth??80;function n(u,f){return o.formatItem(u,i,f,o)}let s=[`${o.styleTitle("Usage:")} ${o.styleUsage(o.commandUsage(t))}`,""],a=o.commandDescription(t);a.length>0&&(s=s.concat([o.boxWrap(o.styleCommandDescription(a),r),""]));let l=o.visibleArguments(t).map(u=>n(o.styleArgumentTerm(o.argumentTerm(u)),o.styleArgumentDescription(o.argumentDescription(u))));if(s=s.concat(this.formatItemList("Arguments:",l,o)),this.groupItems(t.options,o.visibleOptions(t),u=>u.helpGroupHeading??"Options:").forEach((u,f)=>{let
|
|
2
|
+
"use strict";var Ju=Object.create;var hi=Object.defineProperty;var Vu=Object.getOwnPropertyDescriptor;var zu=Object.getOwnPropertyNames;var Yu=Object.getPrototypeOf,Xu=Object.prototype.hasOwnProperty;var ge=(e,t,o)=>()=>{if(o)throw o[0];try{return e&&(t=e(e=0)),t}catch(i){throw o=[i],i}};var xe=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(o){throw t=0,o}},Lt=(e,t)=>{for(var o in t)hi(e,o,{get:t[o],enumerable:!0})},Zu=(e,t,o,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of zu(t))!Xu.call(e,r)&&r!==o&&hi(e,r,{get:()=>t[r],enumerable:!(i=Vu(t,r))||i.enumerable});return e};var ue=(e,t,o)=>(o=e!=null?Ju(Yu(e)):{},Zu(t||!e||!e.__esModule?hi(o,"default",{value:e,enumerable:!0}):o,e));var Wt=xe(bi=>{var go=class extends Error{constructor(t,o,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=o,this.exitCode=t,this.nestedError=void 0}},Ai=class extends go{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};bi.CommanderError=go;bi.InvalidArgumentError=Ai});var ho=xe(yi=>{var{InvalidArgumentError:ed}=Wt(),Ci=class{constructor(t,o){switch(this.description=o||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(t,o){return o===this.defaultValue||!Array.isArray(o)?[t]:(o.push(t),o)}default(t,o){return this.defaultValue=t,this.defaultValueDescription=o,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(o,i)=>{if(!this.argChoices.includes(o))throw new ed(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(o,i):o},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function td(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}yi.Argument=Ci;yi.humanReadableArgName=td});var Ki=xe(Si=>{var{humanReadableArgName:od}=ho(),Ui=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){let o=t.commands.filter(r=>!r._hidden),i=t._getHelpCommand();return i&&!i._hidden&&o.push(i),this.sortSubcommands&&o.sort((r,n)=>r.name().localeCompare(n.name())),o}compareOptions(t,o){let i=r=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,"");return i(t).localeCompare(i(o))}visibleOptions(t){let o=t.options.filter(r=>!r.hidden),i=t._getHelpOption();if(i&&!i.hidden){let r=i.short&&t._findOption(i.short),n=i.long&&t._findOption(i.long);!r&&!n?o.push(i):i.long&&!n?o.push(t.createOption(i.long,i.description)):i.short&&!r&&o.push(t.createOption(i.short,i.description))}return this.sortOptions&&o.sort(this.compareOptions),o}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let o=[];for(let i=t.parent;i;i=i.parent){let r=i.options.filter(n=>!n.hidden);o.push(...r)}return this.sortOptions&&o.sort(this.compareOptions),o}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(o=>{o.description=o.description||t._argsDescription[o.name()]||""}),t.registeredArguments.find(o=>o.description)?t.registeredArguments:[]}subcommandTerm(t){let o=t.registeredArguments.map(i=>od(i)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(o?" "+o:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,o){return o.visibleCommands(t).reduce((i,r)=>Math.max(i,this.displayWidth(o.styleSubcommandTerm(o.subcommandTerm(r)))),0)}longestOptionTermLength(t,o){return o.visibleOptions(t).reduce((i,r)=>Math.max(i,this.displayWidth(o.styleOptionTerm(o.optionTerm(r)))),0)}longestGlobalOptionTermLength(t,o){return o.visibleGlobalOptions(t).reduce((i,r)=>Math.max(i,this.displayWidth(o.styleOptionTerm(o.optionTerm(r)))),0)}longestArgumentTermLength(t,o){return o.visibleArguments(t).reduce((i,r)=>Math.max(i,this.displayWidth(o.styleArgumentTerm(o.argumentTerm(r)))),0)}commandUsage(t){let o=t._name;t._aliases[0]&&(o=o+"|"+t._aliases[0]);let i="";for(let r=t.parent;r;r=r.parent)i=r.name()+" "+i;return i+o+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let o=[];if(t.argChoices&&o.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&o.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&o.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&o.push(`env: ${t.envVar}`),o.length>0){let i=`(${o.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}argumentDescription(t){let o=[];if(t.argChoices&&o.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&o.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),o.length>0){let i=`(${o.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}formatItemList(t,o,i){return o.length===0?[]:[i.styleTitle(t),...o,""]}groupItems(t,o,i){let r=new Map;return t.forEach(n=>{let s=i(n);r.has(s)||r.set(s,[])}),o.forEach(n=>{let s=i(n);r.has(s)||r.set(s,[]),r.get(s).push(n)}),r}formatHelp(t,o){let i=o.padWidth(t,o),r=o.helpWidth??80;function n(u,f){return o.formatItem(u,i,f,o)}let s=[`${o.styleTitle("Usage:")} ${o.styleUsage(o.commandUsage(t))}`,""],a=o.commandDescription(t);a.length>0&&(s=s.concat([o.boxWrap(o.styleCommandDescription(a),r),""]));let l=o.visibleArguments(t).map(u=>n(o.styleArgumentTerm(o.argumentTerm(u)),o.styleArgumentDescription(o.argumentDescription(u))));if(s=s.concat(this.formatItemList("Arguments:",l,o)),this.groupItems(t.options,o.visibleOptions(t),u=>u.helpGroupHeading??"Options:").forEach((u,f)=>{let A=u.map(h=>n(o.styleOptionTerm(o.optionTerm(h)),o.styleOptionDescription(o.optionDescription(h))));s=s.concat(this.formatItemList(f,A,o))}),o.showGlobalOptions){let u=o.visibleGlobalOptions(t).map(f=>n(o.styleOptionTerm(o.optionTerm(f)),o.styleOptionDescription(o.optionDescription(f))));s=s.concat(this.formatItemList("Global Options:",u,o))}return this.groupItems(t.commands,o.visibleCommands(t),u=>u.helpGroup()||"Commands:").forEach((u,f)=>{let A=u.map(h=>n(o.styleSubcommandTerm(o.subcommandTerm(h)),o.styleSubcommandDescription(o.subcommandDescription(h))));s=s.concat(this.formatItemList(f,A,o))}),s.join(`
|
|
3
3
|
`)}displayWidth(t){return Ir(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map(o=>o==="[options]"?this.styleOptionText(o):o==="[command]"?this.styleSubcommandText(o):o[0]==="["||o[0]==="<"?this.styleArgumentText(o):this.styleCommandText(o)).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map(o=>o==="[options]"?this.styleOptionText(o):o[0]==="["||o[0]==="<"?this.styleArgumentText(o):this.styleSubcommandText(o)).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,o){return Math.max(o.longestOptionTermLength(t,o),o.longestGlobalOptionTermLength(t,o),o.longestSubcommandTermLength(t,o),o.longestArgumentTermLength(t,o))}preformatted(t){return/\n[^\S\r\n]/.test(t)}formatItem(t,o,i,r){let s=" ".repeat(2);if(!i)return s+t;let a=t.padEnd(o+t.length-r.displayWidth(t)),l=2,c=(this.helpWidth??80)-o-l-2,u;return c<this.minWidthToWrap||r.preformatted(i)?u=i:u=r.boxWrap(i,c).replace(/\n/g,`
|
|
4
4
|
`+" ".repeat(o+l)),s+a+" ".repeat(l)+u.replace(/\n/g,`
|
|
5
5
|
${s}`)}boxWrap(t,o){if(o<this.minWidthToWrap)return t;let i=t.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,n=[];return i.forEach(s=>{let a=s.match(r);if(a===null){n.push("");return}let l=[a.shift()],d=this.displayWidth(l[0]);a.forEach(c=>{let u=this.displayWidth(c);if(d+u<=o){l.push(c),d+=u;return}n.push(l.join(""));let f=c.trimStart();l=[f],d=this.displayWidth(f)}),n.push(l.join(""))}),n.join(`
|
|
@@ -11,20 +11,20 @@ ${s}`)}boxWrap(t,o){if(o<this.minWidthToWrap)return t;let i=t.split(/\r\n|\n/),r
|
|
|
11
11
|
- too many long flags`):new Error(`${a}
|
|
12
12
|
- unrecognised flag format`)}if(t===void 0&&o===void 0)throw new Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:o}}xi.Option=vi;xi.DualOptions=wi});var Hr=xe($r=>{function nd(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let o=[];for(let i=0;i<=e.length;i++)o[i]=[i];for(let i=0;i<=t.length;i++)o[0][i]=i;for(let i=1;i<=t.length;i++)for(let r=1;r<=e.length;r++){let n=1;e[r-1]===t[i-1]?n=0:n=1,o[r][i]=Math.min(o[r-1][i]+1,o[r][i-1]+1,o[r-1][i-1]+n),r>1&&i>1&&e[r-1]===t[i-2]&&e[r-2]===t[i-1]&&(o[r][i]=Math.min(o[r][i],o[r-2][i-2]+1))}return o[e.length][t.length]}function sd(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let o=e.startsWith("--");o&&(e=e.slice(2),t=t.map(s=>s.slice(2)));let i=[],r=3,n=.4;return t.forEach(s=>{if(s.length<=1)return;let a=nd(e,s),l=Math.max(e.length,s.length);(l-a)/l>n&&(a<r?(r=a,i=[s]):a===r&&i.push(s))}),i.sort((s,a)=>s.localeCompare(a)),o&&(i=i.map(s=>`--${s}`)),i.length>1?`
|
|
13
13
|
(Did you mean one of ${i.join(", ")}?)`:i.length===1?`
|
|
14
|
-
(Did you mean ${i[0]}?)`:""}$r.suggestSimilar=sd});var qr=xe(
|
|
14
|
+
(Did you mean ${i[0]}?)`:""}$r.suggestSimilar=sd});var qr=xe(Bi=>{var ad=require("node:events").EventEmitter,ki=require("node:child_process"),Ye=require("node:path"),Ao=require("node:fs"),W=require("node:process"),{Argument:ld,humanReadableArgName:cd}=ho(),{CommanderError:Ri}=Wt(),{Help:ud,stripColor:dd}=Ki(),{Option:Gr,DualOptions:pd}=Fi(),{suggestSimilar:Qr}=Hr(),_i=class e extends ad{constructor(t){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=t||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:o=>W.stdout.write(o),writeErr:o=>W.stderr.write(o),outputError:(o,i)=>i(o),getOutHelpWidth:()=>W.stdout.isTTY?W.stdout.columns:void 0,getErrHelpWidth:()=>W.stderr.isTTY?W.stderr.columns:void 0,getOutHasColors:()=>Di()??(W.stdout.isTTY&&W.stdout.hasColors?.()),getErrHasColors:()=>Di()??(W.stderr.isTTY&&W.stderr.hasColors?.()),stripColor:o=>dd(o)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(t){return this._outputConfiguration=t._outputConfiguration,this._helpOption=t._helpOption,this._helpCommand=t._helpCommand,this._helpConfiguration=t._helpConfiguration,this._exitCallback=t._exitCallback,this._storeOptionsAsProperties=t._storeOptionsAsProperties,this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue,this._allowExcessArguments=t._allowExcessArguments,this._enablePositionalOptions=t._enablePositionalOptions,this._showHelpAfterError=t._showHelpAfterError,this._showSuggestionAfterError=t._showSuggestionAfterError,this}_getCommandAndAncestors(){let t=[];for(let o=this;o;o=o.parent)t.push(o);return t}command(t,o,i){let r=o,n=i;typeof r=="object"&&r!==null&&(n=r,r=null),n=n||{};let[,s,a]=t.match(/([^ ]+) *(.*)/),l=this.createCommand(s);return r&&(l.description(r),l._executableHandler=!0),n.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(n.noHelp||n.hidden),l._executableFile=n.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),r?this:l}createCommand(t){return new e(t)}createHelp(){return Object.assign(new ud,this.configureHelp())}configureHelp(t){return t===void 0?this._helpConfiguration:(this._helpConfiguration=t,this)}configureOutput(t){return t===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...t},this)}showHelpAfterError(t=!0){return typeof t!="string"&&(t=!!t),this._showHelpAfterError=t,this}showSuggestionAfterError(t=!0){return this._showSuggestionAfterError=!!t,this}addCommand(t,o){if(!t._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
15
15
|
- specify the name in Command constructor or using .name()`);return o=o||{},o.isDefault&&(this._defaultCommandName=t._name),(o.noHelp||o.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,o){return new ld(t,o)}argument(t,o,i,r){let n=this.createArgument(t,o);return typeof i=="function"?n.default(r).argParser(i):n.default(i),this.addArgument(n),this}arguments(t){return t.trim().split(/ +/).forEach(o=>{this.argument(o)}),this}addArgument(t){let o=this.registeredArguments.slice(-1)[0];if(o?.variadic)throw new Error(`only the last argument can be variadic '${o.name()}'`);if(t.required&&t.defaultValue!==void 0&&t.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${t.name()}'`);return this.registeredArguments.push(t),this}helpCommand(t,o){if(typeof t=="boolean")return this._addImplicitHelpCommand=t,t&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let i=t??"help [command]",[,r,n]=i.match(/([^ ]+) *(.*)/),s=o??"display help for command",a=this.createCommand(r);return a.helpOption(!1),n&&a.arguments(n),s&&a.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=a,(t||o)&&this._initCommandGroup(a),this}addHelpCommand(t,o){return typeof t!="object"?(this.helpCommand(t,o),this):(this._addImplicitHelpCommand=!0,this._helpCommand=t,this._initCommandGroup(t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(t,o){let i=["preSubcommand","preAction","postAction"];if(!i.includes(t))throw new Error(`Unexpected value for event passed to hook : '${t}'.
|
|
16
16
|
Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(o):this._lifeCycleHooks[t]=[o],this}exitOverride(t){return t?this._exitCallback=t:this._exitCallback=o=>{if(o.code!=="commander.executeSubCommandAsync")throw o},this}_exit(t,o,i){this._exitCallback&&this._exitCallback(new Ri(t,o,i)),W.exit(t)}action(t){let o=i=>{let r=this.registeredArguments.length,n=i.slice(0,r);return this._storeOptionsAsProperties?n[r]=this:n[r]=this.opts(),n.push(this),t.apply(this,n)};return this._actionHandler=o,this}createOption(t,o){return new Gr(t,o)}_callParseArg(t,o,i,r){try{return t.parseArg(o,i)}catch(n){if(n.code==="commander.invalidArgument"){let s=`${r} ${n.message}`;this.error(s,{exitCode:n.exitCode,code:n.code})}throw n}}_registerOption(t){let o=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(o){let i=t.long&&this._findOption(t.long)?t.long:t.short;throw new Error(`Cannot add option '${t.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'
|
|
17
17
|
- already used by option '${o.flags}'`)}this._initOptionGroup(t),this.options.push(t)}_registerCommand(t){let o=r=>[r.name()].concat(r.aliases()),i=o(t).find(r=>this._findCommand(r));if(i){let r=o(this._findCommand(i)).join("|"),n=o(t).join("|");throw new Error(`cannot add command '${n}' as already have command '${r}'`)}this._initCommandGroup(t),this.commands.push(t)}addOption(t){this._registerOption(t);let o=t.name(),i=t.attributeName();if(t.negate){let n=t.long.replace(/^--no-/,"--");this._findOption(n)||this.setOptionValueWithSource(i,t.defaultValue===void 0?!0:t.defaultValue,"default")}else t.defaultValue!==void 0&&this.setOptionValueWithSource(i,t.defaultValue,"default");let r=(n,s,a)=>{n==null&&t.presetArg!==void 0&&(n=t.presetArg);let l=this.getOptionValue(i);n!==null&&t.parseArg?n=this._callParseArg(t,n,l,s):n!==null&&t.variadic&&(n=t._collectValue(n,l)),n==null&&(t.negate?n=!1:t.isBoolean()||t.optional?n=!0:n=""),this.setOptionValueWithSource(i,n,a)};return this.on("option:"+o,n=>{let s=`error: option '${t.flags}' argument '${n}' is invalid.`;r(n,s,"cli")}),t.envVar&&this.on("optionEnv:"+o,n=>{let s=`error: option '${t.flags}' value '${n}' from env '${t.envVar}' is invalid.`;r(n,s,"env")}),this}_optionEx(t,o,i,r,n){if(typeof o=="object"&&o instanceof Gr)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(o,i);if(s.makeOptionMandatory(!!t.mandatory),typeof r=="function")s.default(n).argParser(r);else if(r instanceof RegExp){let a=r;r=(l,d)=>{let c=a.exec(l);return c?c[0]:d},s.default(n).argParser(r)}else s.default(r);return this.addOption(s)}option(t,o,i,r){return this._optionEx({},t,o,i,r)}requiredOption(t,o,i,r){return this._optionEx({mandatory:!0},t,o,i,r)}combineFlagAndOptionalValue(t=!0){return this._combineFlagAndOptionalValue=!!t,this}allowUnknownOption(t=!0){return this._allowUnknownOption=!!t,this}allowExcessArguments(t=!0){return this._allowExcessArguments=!!t,this}enablePositionalOptions(t=!0){return this._enablePositionalOptions=!!t,this}passThroughOptions(t=!0){return this._passThroughOptions=!!t,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(t=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!t,this}getOptionValue(t){return this._storeOptionsAsProperties?this[t]:this._optionValues[t]}setOptionValue(t,o){return this.setOptionValueWithSource(t,o,void 0)}setOptionValueWithSource(t,o,i){return this._storeOptionsAsProperties?this[t]=o:this._optionValues[t]=o,this._optionValueSources[t]=i,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let o;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(t)!==void 0&&(o=i.getOptionValueSource(t))}),o}_prepareUserArgs(t,o){if(t!==void 0&&!Array.isArray(t))throw new Error("first parameter to parse must be array or undefined");if(o=o||{},t===void 0&&o.from===void 0){W.versions?.electron&&(o.from="electron");let r=W.execArgv??[];(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))&&(o.from="eval")}t===void 0&&(t=W.argv),this.rawArgs=t.slice();let i;switch(o.from){case void 0:case"node":this._scriptPath=t[1],i=t.slice(2);break;case"electron":W.defaultApp?(this._scriptPath=t[1],i=t.slice(2)):i=t.slice(1);break;case"user":i=t.slice(0);break;case"eval":i=t.slice(1);break;default:throw new Error(`unexpected parse option { from: '${o.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(t,o){this._prepareForParse();let i=this._prepareUserArgs(t,o);return this._parseCommand([],i),this}async parseAsync(t,o){this._prepareForParse();let i=this._prepareUserArgs(t,o);return await this._parseCommand([],i),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
18
18
|
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(t,o,i){if(Ao.existsSync(t))return;let r=o?`searched for local subcommand relative to directory '${o}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",n=`'${t}' does not exist
|
|
19
19
|
- if '${i}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
20
20
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
21
|
-
- ${r}`;throw new Error(n)}_executeSubCommand(t,o){o=o.slice();let i=!1,r=[".js",".ts",".tsx",".mjs",".cjs"];function n(c,u){let f=Ye.resolve(c,u);if(Ao.existsSync(f))return f;if(r.includes(Ye.extname(u)))return;let
|
|
21
|
+
- ${r}`;throw new Error(n)}_executeSubCommand(t,o){o=o.slice();let i=!1,r=[".js",".ts",".tsx",".mjs",".cjs"];function n(c,u){let f=Ye.resolve(c,u);if(Ao.existsSync(f))return f;if(r.includes(Ye.extname(u)))return;let A=r.find(h=>Ao.existsSync(`${f}${h}`));if(A)return`${f}${A}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=t._executableFile||`${this._name}-${t._name}`,a=this._executableDir||"";if(this._scriptPath){let c;try{c=Ao.realpathSync(this._scriptPath)}catch{c=this._scriptPath}a=Ye.resolve(Ye.dirname(c),a)}if(a){let c=n(a,s);if(!c&&!t._executableFile&&this._scriptPath){let u=Ye.basename(this._scriptPath,Ye.extname(this._scriptPath));u!==this._name&&(c=n(a,`${u}-${t._name}`))}s=c||s}i=r.includes(Ye.extname(s));let l;W.platform!=="win32"?i?(o.unshift(s),o=Nr(W.execArgv).concat(o),l=ki.spawn(W.argv[0],o,{stdio:"inherit"})):l=ki.spawn(s,o,{stdio:"inherit"}):(this._checkForMissingExecutable(s,a,t._name),o.unshift(s),o=Nr(W.execArgv).concat(o),l=ki.spawn(W.execPath,o,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(u=>{W.on(u,()=>{l.killed===!1&&l.exitCode===null&&l.kill(u)})});let d=this._exitCallback;l.on("close",c=>{c=c??1,d?d(new Ri(c,"commander.executeSubCommandAsync","(close)")):W.exit(c)}),l.on("error",c=>{if(c.code==="ENOENT")this._checkForMissingExecutable(s,a,t._name);else if(c.code==="EACCES")throw new Error(`'${s}' not executable`);if(!d)W.exit(1);else{let u=new Ri(1,"commander.executeSubCommandAsync","(error)");u.nestedError=c,d(u)}}),this.runningCommand=l}_dispatchSubcommand(t,o,i){let r=this._findCommand(t);r||this.help({error:!0}),r._prepareForParse();let n;return n=this._chainOrCallSubCommandHook(n,r,"preSubcommand"),n=this._chainOrCall(n,()=>{if(r._executableHandler)this._executeSubCommand(r,o.concat(i));else return r._parseCommand(o,i)}),n}_dispatchHelpCommand(t){t||this.help();let o=this._findCommand(t);return o&&!o._executableHandler&&o.help(),this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((t,o)=>{t.required&&this.args[o]==null&&this.missingArgument(t.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let t=(i,r,n)=>{let s=r;if(r!==null&&i.parseArg){let a=`error: command-argument value '${r}' is invalid for argument '${i.name()}'.`;s=this._callParseArg(i,r,n,a)}return s};this._checkNumberOfArguments();let o=[];this.registeredArguments.forEach((i,r)=>{let n=i.defaultValue;i.variadic?r<this.args.length?(n=this.args.slice(r),i.parseArg&&(n=n.reduce((s,a)=>t(i,a,s),i.defaultValue))):n===void 0&&(n=[]):r<this.args.length&&(n=this.args[r],i.parseArg&&(n=t(i,n,i.defaultValue))),o[r]=n}),this.processedArgs=o}_chainOrCall(t,o){return t?.then&&typeof t.then=="function"?t.then(()=>o()):o()}_chainOrCallHooks(t,o){let i=t,r=[];return this._getCommandAndAncestors().reverse().filter(n=>n._lifeCycleHooks[o]!==void 0).forEach(n=>{n._lifeCycleHooks[o].forEach(s=>{r.push({hookedCommand:n,callback:s})})}),o==="postAction"&&r.reverse(),r.forEach(n=>{i=this._chainOrCall(i,()=>n.callback(n.hookedCommand,this))}),i}_chainOrCallSubCommandHook(t,o,i){let r=t;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(n=>{r=this._chainOrCall(r,()=>n(this,o))}),r}_parseCommand(t,o){let i=this.parseOptions(o);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(i.operands),o=i.unknown,this.args=t.concat(o),t&&this._findCommand(t[0]))return this._dispatchSubcommand(t[0],t.slice(1),o);if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(t[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(o),this._dispatchSubcommand(this._defaultCommandName,t,o);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},n=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let s;return s=this._chainOrCallHooks(s,"preAction"),s=this._chainOrCall(s,()=>this._actionHandler(this.processedArgs)),this.parent&&(s=this._chainOrCall(s,()=>{this.parent.emit(n,t,o)})),s=this._chainOrCallHooks(s,"postAction"),s}if(this.parent?.listenerCount(n))r(),this._processArguments(),this.parent.emit(n,t,o);else if(t.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",t,o);this.listenerCount("command:*")?this.emit("command:*",t,o):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(t){if(t)return this.commands.find(o=>o._name===t||o._aliases.includes(t))}_findOption(t){return this.options.find(o=>o.is(t))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(t=>{t.options.forEach(o=>{o.mandatory&&t.getOptionValue(o.attributeName())===void 0&&t.missingMandatoryOptionValue(o)})})}_checkForConflictingLocalOptions(){let t=this.options.filter(i=>{let r=i.attributeName();return this.getOptionValue(r)===void 0?!1:this.getOptionValueSource(r)!=="default"});t.filter(i=>i.conflictsWith.length>0).forEach(i=>{let r=t.find(n=>i.conflictsWith.includes(n.attributeName()));r&&this._conflictingOption(i,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(t=>{t._checkForConflictingLocalOptions()})}parseOptions(t){let o=[],i=[],r=o;function n(c){return c.length>1&&c[0]==="-"}let s=c=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(c)?!this._getCommandAndAncestors().some(u=>u.options.map(f=>f.short).some(f=>/^-\d$/.test(f))):!1,a=null,l=null,d=0;for(;d<t.length||l;){let c=l??t[d++];if(l=null,c==="--"){r===i&&r.push(c),r.push(...t.slice(d));break}if(a&&(!n(c)||s(c))){this.emit(`option:${a.name()}`,c);continue}if(a=null,n(c)){let u=this._findOption(c);if(u){if(u.required){let f=t[d++];f===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,f)}else if(u.optional){let f=null;d<t.length&&(!n(t[d])||s(t[d]))&&(f=t[d++]),this.emit(`option:${u.name()}`,f)}else this.emit(`option:${u.name()}`);a=u.variadic?u:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let u=this._findOption(`-${c[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,c.slice(2)):(this.emit(`option:${u.name()}`),l=`-${c.slice(2)}`);continue}}if(/^--[^=]+=/.test(c)){let u=c.indexOf("="),f=this._findOption(c.slice(0,u));if(f&&(f.required||f.optional)){this.emit(`option:${f.name()}`,c.slice(u+1));continue}}if(r===o&&n(c)&&!(this.commands.length===0&&s(c))&&(r=i),(this._enablePositionalOptions||this._passThroughOptions)&&o.length===0&&i.length===0){if(this._findCommand(c)){o.push(c),i.push(...t.slice(d));break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){o.push(c,...t.slice(d));break}else if(this._defaultCommandName){i.push(c,...t.slice(d));break}}if(this._passThroughOptions){r.push(c,...t.slice(d));break}r.push(c)}return{operands:o,unknown:i}}opts(){if(this._storeOptionsAsProperties){let t={},o=this.options.length;for(let i=0;i<o;i++){let r=this.options[i].attributeName();t[r]=r===this._versionOptionName?this._version:this[r]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((t,o)=>Object.assign(t,o.opts()),{})}error(t,o){this._outputConfiguration.outputError(`${t}
|
|
22
22
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
23
23
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
24
24
|
`),this.outputHelp({error:!0}));let i=o||{},r=i.exitCode||1,n=i.code||"commander.error";this._exit(r,n,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in W.env){let o=t.attributeName();(this.getOptionValue(o)===void 0||["default","config","env"].includes(this.getOptionValueSource(o)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,W.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new pd(this.options),o=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&o(i.attributeName())&&t.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(r=>!o(r)).forEach(r=>{this.setOptionValueWithSource(r,i.implied[r],"implied")})})}missingArgument(t){let o=`error: missing required argument '${t}'`;this.error(o,{code:"commander.missingArgument"})}optionMissingArgument(t){let o=`error: option '${t.flags}' argument missing`;this.error(o,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){let o=`error: required option '${t.flags}' not specified`;this.error(o,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,o){let i=s=>{let a=s.attributeName(),l=this.getOptionValue(a),d=this.options.find(u=>u.negate&&a===u.attributeName()),c=this.options.find(u=>!u.negate&&a===u.attributeName());return d&&(d.presetArg===void 0&&l===!1||d.presetArg!==void 0&&l===d.presetArg)?d:c||s},r=s=>{let a=i(s),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},n=`error: ${r(t)} cannot be used with ${r(o)}`;this.error(n,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let o="";if(t.startsWith("--")&&this._showSuggestionAfterError){let r=[],n=this;do{let s=n.createHelp().visibleOptions(n).filter(a=>a.long).map(a=>a.long);r=r.concat(s),n=n.parent}while(n&&!n._enablePositionalOptions);o=Qr(t,r)}let i=`error: unknown option '${t}'${o}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;let o=this.registeredArguments.length,i=o===1?"":"s",n=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${o} argument${i} but got ${t.length}.`;this.error(n,{code:"commander.excessArguments"})}unknownCommand(){let t=this.args[0],o="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach(n=>{r.push(n.name()),n.alias()&&r.push(n.alias())}),o=Qr(t,r)}let i=`error: unknown command '${t}'${o}`;this.error(i,{code:"commander.unknownCommand"})}version(t,o,i){if(t===void 0)return this._version;this._version=t,o=o||"-V, --version",i=i||"output the version number";let r=this.createOption(o,i);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.name(),()=>{this._outputConfiguration.writeOut(`${t}
|
|
25
25
|
`),this._exit(0,"commander.version",t)}),this}description(t,o){return t===void 0&&o===void 0?this._description:(this._description=t,o&&(this._argsDescription=o),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===void 0)return this._aliases[0];let o=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(o=this.commands[this.commands.length-1]),t===o._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(t);if(i){let r=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${r}'`)}return o._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(o=>this.alias(o)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;let o=this.registeredArguments.map(i=>cd(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?o:[]).join(" ")}return this._usage=t,this}name(t){return t===void 0?this._name:(this._name=t,this)}helpGroup(t){return t===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=t,this)}commandsGroup(t){return t===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=t,this)}optionsGroup(t){return t===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=t,this)}_initOptionGroup(t){this._defaultOptionGroup&&!t.helpGroupHeading&&t.helpGroup(this._defaultOptionGroup)}_initCommandGroup(t){this._defaultCommandGroup&&!t.helpGroup()&&t.helpGroup(this._defaultCommandGroup)}nameFromFilename(t){return this._name=Ye.basename(t,Ye.extname(t)),this}executableDir(t){return t===void 0?this._executableDir:(this._executableDir=t,this)}helpInformation(t){let o=this.createHelp(),i=this._getOutputContext(t);o.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let r=o.formatHelp(this,o);return i.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(t){t=t||{};let o=!!t.error,i,r,n;return o?(i=a=>this._outputConfiguration.writeErr(a),r=this._outputConfiguration.getErrHasColors(),n=this._outputConfiguration.getErrHelpWidth()):(i=a=>this._outputConfiguration.writeOut(a),r=this._outputConfiguration.getOutHasColors(),n=this._outputConfiguration.getOutHelpWidth()),{error:o,write:a=>(r||(a=this._outputConfiguration.stripColor(a)),i(a)),hasColors:r,helpWidth:n}}outputHelp(t){let o;typeof t=="function"&&(o=t,t=void 0);let i=this._getOutputContext(t),r={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let n=this.helpInformation({error:i.error});if(o&&(n=o(n),typeof n!="string"&&!Buffer.isBuffer(n)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(n),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",r))}helpOption(t,o){return typeof t=="boolean"?(t?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(t??"-h, --help",o??"display help for command"),(t||o)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(t){return this._helpOption=t,this._initOptionGroup(t),this}help(t){this.outputHelp(t);let o=Number(W.exitCode??0);o===0&&t&&typeof t!="function"&&t.error&&(o=1),this._exit(o,"commander.help","(outputHelp)")}addHelpText(t,o){let i=["beforeAll","before","after","afterAll"];if(!i.includes(t))throw new Error(`Unexpected value for position to addHelpText.
|
|
26
26
|
Expecting one of '${i.join("', '")}'`);let r=`${t}Help`;return this.on(r,n=>{let s;typeof o=="function"?s=o({error:n.error,command:n.command}):s=o,s&&n.write(`${s}
|
|
27
|
-
`)}),this}_outputHelpIfRequested(t){let o=this._getHelpOption();o&&t.find(r=>o.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Nr(e){return e.map(t=>{if(!t.startsWith("--inspect"))return t;let o,i="127.0.0.1",r="9229",n;return(n=t.match(/^(--inspect(-brk)?)$/))!==null?o=n[1]:(n=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(o=n[1],/^\d+$/.test(n[3])?r=n[3]:i=n[3]):(n=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(o=n[1],i=n[3],r=n[4]),o&&r!=="0"?`${o}=${i}:${parseInt(r)+1}`:t})}function Di(){if(W.env.NO_COLOR||W.env.FORCE_COLOR==="0"||W.env.FORCE_COLOR==="false")return!1;if(W.env.FORCE_COLOR||W.env.CLICOLOR_FORCE!==void 0)return!0}Ei.Command=_i;Ei.useColor=Di});var Jr=xe(Te=>{var{Argument:Mr}=ho(),{Command:Bi}=qr(),{CommanderError:md,InvalidArgumentError:Lr}=Wt(),{Help:fd}=Ki(),{Option:Wr}=Fi();Te.program=new Bi;Te.createCommand=e=>new Bi(e);Te.createOption=(e,t)=>new Wr(e,t);Te.createArgument=(e,t)=>new Mr(e,t);Te.Command=Bi;Te.Option=Wr;Te.Argument=Mr;Te.Help=fd;Te.CommanderError=md;Te.InvalidArgumentError=Lr;Te.InvalidOptionArgumentError=Lr});var zr=xe((_e,Vr)=>{var He=Jr();_e=Vr.exports={};_e.program=new He.Command;_e.Argument=He.Argument;_e.Command=He.Command;_e.CommanderError=He.CommanderError;_e.Help=He.Help;_e.InvalidArgumentError=He.InvalidArgumentError;_e.InvalidOptionArgumentError=He.InvalidArgumentError;_e.Option=He.Option;_e.createCommand=e=>new He.Command(e);_e.createOption=(e,t)=>new He.Option(e,t);_e.createArgument=(e,t)=>new He.Argument(e,t)});var qe=xe((Wf,Oi)=>{var Co=process||{},Zr=Co.argv||[],bo=Co.env||{},gd=!(bo.NO_COLOR||Zr.includes("--no-color"))&&(!!bo.FORCE_COLOR||Zr.includes("--color")||Co.platform==="win32"||(Co.stdout||{}).isTTY&&bo.TERM!=="dumb"||!!bo.CI),hd=(e,t,o=e)=>i=>{let r=""+i,n=r.indexOf(t,e.length);return~n?e+Ad(r,t,o,n)+t:e+r+t},Ad=(e,t,o,i)=>{let r="",n=0;do r+=e.substring(n,i)+o,n=i+t.length,i=e.indexOf(t,n);while(~i);return r+e.substring(n)},en=(e=gd)=>{let t=e?hd:()=>String;return{isColorSupported:e,reset:t("\x1B[0m","\x1B[0m"),bold:t("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:t("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:t("\x1B[3m","\x1B[23m"),underline:t("\x1B[4m","\x1B[24m"),inverse:t("\x1B[7m","\x1B[27m"),hidden:t("\x1B[8m","\x1B[28m"),strikethrough:t("\x1B[9m","\x1B[29m"),black:t("\x1B[30m","\x1B[39m"),red:t("\x1B[31m","\x1B[39m"),green:t("\x1B[32m","\x1B[39m"),yellow:t("\x1B[33m","\x1B[39m"),blue:t("\x1B[34m","\x1B[39m"),magenta:t("\x1B[35m","\x1B[39m"),cyan:t("\x1B[36m","\x1B[39m"),white:t("\x1B[37m","\x1B[39m"),gray:t("\x1B[90m","\x1B[39m"),bgBlack:t("\x1B[40m","\x1B[49m"),bgRed:t("\x1B[41m","\x1B[49m"),bgGreen:t("\x1B[42m","\x1B[49m"),bgYellow:t("\x1B[43m","\x1B[49m"),bgBlue:t("\x1B[44m","\x1B[49m"),bgMagenta:t("\x1B[45m","\x1B[49m"),bgCyan:t("\x1B[46m","\x1B[49m"),bgWhite:t("\x1B[47m","\x1B[49m"),blackBright:t("\x1B[90m","\x1B[39m"),redBright:t("\x1B[91m","\x1B[39m"),greenBright:t("\x1B[92m","\x1B[39m"),yellowBright:t("\x1B[93m","\x1B[39m"),blueBright:t("\x1B[94m","\x1B[39m"),magentaBright:t("\x1B[95m","\x1B[39m"),cyanBright:t("\x1B[96m","\x1B[39m"),whiteBright:t("\x1B[97m","\x1B[39m"),bgBlackBright:t("\x1B[100m","\x1B[49m"),bgRedBright:t("\x1B[101m","\x1B[49m"),bgGreenBright:t("\x1B[102m","\x1B[49m"),bgYellowBright:t("\x1B[103m","\x1B[49m"),bgBlueBright:t("\x1B[104m","\x1B[49m"),bgMagentaBright:t("\x1B[105m","\x1B[49m"),bgCyanBright:t("\x1B[106m","\x1B[49m"),bgWhiteBright:t("\x1B[107m","\x1B[49m")}};Oi.exports=en();Oi.exports.createColors=en});var $i=xe((og,hn)=>{"use strict";var Pi={to(e,t){return t?`\x1B[${t+1};${e+1}H`:`\x1B[${e+1}G`},move(e,t){let o="";return e<0?o+=`\x1B[${-e}D`:e>0&&(o+=`\x1B[${e}C`),t<0?o+=`\x1B[${-t}A`:t>0&&(o+=`\x1B[${t}B`),o},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},Od={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},Td={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let o=0;o<e;o++)t+=this.line+(o<e-1?Pi.up():"");return e&&(t+=Pi.left),t}};hn.exports={cursor:Pi,scroll:Od,erase:Td,beep:"\x07"}});var Mi,Dn=ge(()=>{Mi={name:"resend-cli",version:"2.9.0",description:"The official CLI for Resend",license:"MIT",repository:{type:"git",url:"https://github.com/resend/resend-cli"},homepage:"https://github.com/resend/resend-cli#readme",keywords:["cli","resend","email","api","tanstack-intent"],engines:{node:">=22"},packageManager:"pnpm@11.8.0",files:["dist/cli.cjs","skills/"],type:"module",bin:{resend:"./dist/cli.cjs"},scripts:{dev:"tsx src/cli.ts","dev:watch":"tsx --watch src/cli.ts",build:"node scripts/build.mjs","build:bin":"pnpm build && pkg dist/cli.cjs --config package.json --compress Brotli --target node24 --output dist/resend",lint:"biome check .","lint:fix":"biome check --write .",typecheck:"tsc --noEmit",test:"vitest run","test:e2e":"vitest run --config vitest.config.e2e.ts",prepack:"pnpm install && pnpm build && node scripts/verify-bundle.mjs"},dependencies:{"@clack/prompts":"1.4.0","@commander-js/extra-typings":"14.0.0",commander:"14.0.3",esbuild:"0.28.1","esbuild-wasm":"0.28.0",picocolors:"1.1.1",resend:"6.18.0-canary.0"},pkg:{scripts:["node_modules/esbuild-wasm/bin/esbuild","node_modules/esbuild-wasm/wasm_exec.js","node_modules/esbuild-wasm/wasm_exec_node.js"],assets:["node_modules/esbuild-wasm/esbuild.wasm"]},devDependencies:{"@biomejs/biome":"2.4.11","@types/node":"24.12.4","@yao-pkg/pkg":"6.20.0",tsx:"4.22.4",typescript:"5.9.3",vitest:"4.1.9"}}});var re,En,bt=ge(()=>{"use strict";Dn();re=Mi.version,En=Mi.name});var Nn=xe(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.timingSafeEqual=void 0;function Qn(e,t=""){if(!e)throw new Error(t)}function pp(e,t){if(e.byteLength!==t.byteLength)return!1;e instanceof DataView||(e=new DataView(ArrayBuffer.isView(e)?e.buffer:e)),t instanceof DataView||(t=new DataView(ArrayBuffer.isView(t)?t.buffer:t)),Qn(e instanceof DataView),Qn(t instanceof DataView);let o=e.byteLength,i=0,r=-1;for(;++r<o;)i|=e.getUint8(r)^t.getUint8(r);return i===0}Eo.timingSafeEqual=pp});var Ln=xe(Ee=>{"use strict";var mp=Ee&&Ee.__extends||(function(){var e=function(t,o){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,r){i.__proto__=r}||function(i,r){for(var n in r)r.hasOwnProperty(n)&&(i[n]=r[n])},e(t,o)};return function(t,o){e(t,o);function i(){this.constructor=t}t.prototype=o===null?Object.create(o):(i.prototype=o.prototype,new i)}})();Object.defineProperty(Ee,"__esModule",{value:!0});var ae=256,er=(function(){function e(t){t===void 0&&(t="="),this._paddingCharacter=t}return e.prototype.encodedLength=function(t){return this._paddingCharacter?(t+2)/3*4|0:(t*8+5)/6|0},e.prototype.encode=function(t){for(var o="",i=0;i<t.length-2;i+=3){var r=t[i]<<16|t[i+1]<<8|t[i+2];o+=this._encodeByte(r>>>18&63),o+=this._encodeByte(r>>>12&63),o+=this._encodeByte(r>>>6&63),o+=this._encodeByte(r>>>0&63)}var n=t.length-i;if(n>0){var r=t[i]<<16|(n===2?t[i+1]<<8:0);o+=this._encodeByte(r>>>18&63),o+=this._encodeByte(r>>>12&63),n===2?o+=this._encodeByte(r>>>6&63):o+=this._paddingCharacter||"",o+=this._paddingCharacter||""}return o},e.prototype.maxDecodedLength=function(t){return this._paddingCharacter?t/4*3|0:(t*6+7)/8|0},e.prototype.decodedLength=function(t){return this.maxDecodedLength(t.length-this._getPaddingLength(t))},e.prototype.decode=function(t){if(t.length===0)return new Uint8Array(0);for(var o=this._getPaddingLength(t),i=t.length-o,r=new Uint8Array(this.maxDecodedLength(i)),n=0,s=0,a=0,l=0,d=0,c=0,u=0;s<i-4;s+=4)l=this._decodeChar(t.charCodeAt(s+0)),d=this._decodeChar(t.charCodeAt(s+1)),c=this._decodeChar(t.charCodeAt(s+2)),u=this._decodeChar(t.charCodeAt(s+3)),r[n++]=l<<2|d>>>4,r[n++]=d<<4|c>>>2,r[n++]=c<<6|u,a|=l&ae,a|=d&ae,a|=c&ae,a|=u&ae;if(s<i-1&&(l=this._decodeChar(t.charCodeAt(s)),d=this._decodeChar(t.charCodeAt(s+1)),r[n++]=l<<2|d>>>4,a|=l&ae,a|=d&ae),s<i-2&&(c=this._decodeChar(t.charCodeAt(s+2)),r[n++]=d<<4|c>>>2,a|=c&ae),s<i-3&&(u=this._decodeChar(t.charCodeAt(s+3)),r[n++]=c<<6|u,a|=u&ae),a!==0)throw new Error("Base64Coder: incorrect characters for decoding");return r},e.prototype._encodeByte=function(t){var o=t;return o+=65,o+=25-t>>>8&6,o+=51-t>>>8&-75,o+=61-t>>>8&-15,o+=62-t>>>8&3,String.fromCharCode(o)},e.prototype._decodeChar=function(t){var o=ae;return o+=(42-t&t-44)>>>8&-ae+t-43+62,o+=(46-t&t-48)>>>8&-ae+t-47+63,o+=(47-t&t-58)>>>8&-ae+t-48+52,o+=(64-t&t-91)>>>8&-ae+t-65+0,o+=(96-t&t-123)>>>8&-ae+t-97+26,o},e.prototype._getPaddingLength=function(t){var o=0;if(this._paddingCharacter){for(var i=t.length-1;i>=0&&t[i]===this._paddingCharacter;i--)o++;if(t.length<4||o>2)throw new Error("Base64Coder: incorrect padding")}return o},e})();Ee.Coder=er;var io=new er;function fp(e){return io.encode(e)}Ee.encode=fp;function gp(e){return io.decode(e)}Ee.decode=gp;var qn=(function(e){mp(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype._encodeByte=function(o){var i=o;return i+=65,i+=25-o>>>8&6,i+=51-o>>>8&-75,i+=61-o>>>8&-13,i+=62-o>>>8&49,String.fromCharCode(i)},t.prototype._decodeChar=function(o){var i=ae;return i+=(44-o&o-46)>>>8&-ae+o-45+62,i+=(94-o&o-96)>>>8&-ae+o-95+63,i+=(47-o&o-58)>>>8&-ae+o-48+52,i+=(64-o&o-91)>>>8&-ae+o-65+0,i+=(96-o&o-123)>>>8&-ae+o-97+26,i},t})(er);Ee.URLSafeCoder=qn;var Mn=new qn;function hp(e){return Mn.encode(e)}Ee.encodeURLSafe=hp;function Ap(e){return Mn.decode(e)}Ee.decodeURLSafe=Ap;Ee.encodedLength=function(e){return io.encodedLength(e)};Ee.maxDecodedLength=function(e){return io.maxDecodedLength(e)};Ee.decodedLength=function(e){return io.decodedLength(e)}});var Jn=xe((Wn,Bo)=>{(function(e,t){var o={};t(o);var i=o.default;for(var r in o)i[r]=o[r];typeof Bo=="object"&&typeof Bo.exports=="object"?Bo.exports=i:typeof define=="function"&&define.amd?define(function(){return i}):e.sha256=i})(Wn,function(e){"use strict";e.__esModule=!0,e.digestLength=32,e.blockSize=64;var t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function o(u,f,b,h,A){for(var S,v,K,w,N,k,T,D,F,j,Ce,ie,ht;A>=64;){for(S=f[0],v=f[1],K=f[2],w=f[3],N=f[4],k=f[5],T=f[6],D=f[7],j=0;j<16;j++)Ce=h+j*4,u[j]=(b[Ce]&255)<<24|(b[Ce+1]&255)<<16|(b[Ce+2]&255)<<8|b[Ce+3]&255;for(j=16;j<64;j++)F=u[j-2],ie=(F>>>17|F<<15)^(F>>>19|F<<13)^F>>>10,F=u[j-15],ht=(F>>>7|F<<25)^(F>>>18|F<<14)^F>>>3,u[j]=(ie+u[j-7]|0)+(ht+u[j-16]|0);for(j=0;j<64;j++)ie=(((N>>>6|N<<26)^(N>>>11|N<<21)^(N>>>25|N<<7))+(N&k^~N&T)|0)+(D+(t[j]+u[j]|0)|0)|0,ht=((S>>>2|S<<30)^(S>>>13|S<<19)^(S>>>22|S<<10))+(S&v^S&K^v&K)|0,D=T,T=k,k=N,N=w+ie|0,w=K,K=v,v=S,S=ie+ht|0;f[0]+=S,f[1]+=v,f[2]+=K,f[3]+=w,f[4]+=N,f[5]+=k,f[6]+=T,f[7]+=D,h+=64,A-=64}return h}var i=(function(){function u(){this.digestLength=e.digestLength,this.blockSize=e.blockSize,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return u.prototype.reset=function(){return this.state[0]=1779033703,this.state[1]=3144134277,this.state[2]=1013904242,this.state[3]=2773480762,this.state[4]=1359893119,this.state[5]=2600822924,this.state[6]=528734635,this.state[7]=1541459225,this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this},u.prototype.clean=function(){for(var f=0;f<this.buffer.length;f++)this.buffer[f]=0;for(var f=0;f<this.temp.length;f++)this.temp[f]=0;this.reset()},u.prototype.update=function(f,b){if(b===void 0&&(b=f.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");var h=0;if(this.bytesHashed+=b,this.bufferLength>0){for(;this.bufferLength<64&&b>0;)this.buffer[this.bufferLength++]=f[h++],b--;this.bufferLength===64&&(o(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(b>=64&&(h=o(this.temp,this.state,f,h,b),b%=64);b>0;)this.buffer[this.bufferLength++]=f[h++],b--;return this},u.prototype.finish=function(f){if(!this.finished){var b=this.bytesHashed,h=this.bufferLength,A=b/536870912|0,S=b<<3,v=b%64<56?64:128;this.buffer[h]=128;for(var K=h+1;K<v-8;K++)this.buffer[K]=0;this.buffer[v-8]=A>>>24&255,this.buffer[v-7]=A>>>16&255,this.buffer[v-6]=A>>>8&255,this.buffer[v-5]=A>>>0&255,this.buffer[v-4]=S>>>24&255,this.buffer[v-3]=S>>>16&255,this.buffer[v-2]=S>>>8&255,this.buffer[v-1]=S>>>0&255,o(this.temp,this.state,this.buffer,0,v),this.finished=!0}for(var K=0;K<8;K++)f[K*4+0]=this.state[K]>>>24&255,f[K*4+1]=this.state[K]>>>16&255,f[K*4+2]=this.state[K]>>>8&255,f[K*4+3]=this.state[K]>>>0&255;return this},u.prototype.digest=function(){var f=new Uint8Array(this.digestLength);return this.finish(f),f},u.prototype._saveState=function(f){for(var b=0;b<this.state.length;b++)f[b]=this.state[b]},u.prototype._restoreState=function(f,b){for(var h=0;h<this.state.length;h++)this.state[h]=f[h];this.bytesHashed=b,this.finished=!1,this.bufferLength=0},u})();e.Hash=i;var r=(function(){function u(f){this.inner=new i,this.outer=new i,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var b=new Uint8Array(this.blockSize);if(f.length>this.blockSize)new i().update(f).finish(b).clean();else for(var h=0;h<f.length;h++)b[h]=f[h];for(var h=0;h<b.length;h++)b[h]^=54;this.inner.update(b);for(var h=0;h<b.length;h++)b[h]^=106;this.outer.update(b),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate);for(var h=0;h<b.length;h++)b[h]=0}return u.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},u.prototype.clean=function(){for(var f=0;f<this.istate.length;f++)this.ostate[f]=this.istate[f]=0;this.inner.clean(),this.outer.clean()},u.prototype.update=function(f){return this.inner.update(f),this},u.prototype.finish=function(f){return this.outer.finished?this.outer.finish(f):(this.inner.finish(f),this.outer.update(f,this.digestLength).finish(f)),this},u.prototype.digest=function(){var f=new Uint8Array(this.digestLength);return this.finish(f),f},u})();e.HMAC=r;function n(u){var f=new i().update(u),b=f.digest();return f.clean(),b}e.hash=n,e.default=n;function s(u,f){var b=new r(u).update(f),h=b.digest();return b.clean(),h}e.hmac=s;function a(u,f,b,h){var A=h[0];if(A===0)throw new Error("hkdf: cannot expand more");f.reset(),A>1&&f.update(u),b&&f.update(b),f.update(h),f.finish(u),h[0]++}var l=new Uint8Array(e.digestLength);function d(u,f,b,h){f===void 0&&(f=l),h===void 0&&(h=32);for(var A=new Uint8Array([1]),S=s(f,u),v=new r(S),K=new Uint8Array(v.digestLength),w=K.length,N=new Uint8Array(h),k=0;k<h;k++)w===K.length&&(a(K,v,b,A),w=0),N[k]=K[w++];return v.clean(),K.fill(0),A.fill(0),N}e.hkdf=d;function c(u,f,b,h){for(var A=new r(u),S=A.digestLength,v=new Uint8Array(4),K=new Uint8Array(S),w=new Uint8Array(S),N=new Uint8Array(h),k=0;k*S<h;k++){var T=k+1;v[0]=T>>>24&255,v[1]=T>>>16&255,v[2]=T>>>8&255,v[3]=T>>>0&255,A.reset(),A.update(f),A.update(v),A.finish(w);for(var D=0;D<S;D++)K[D]=w[D];for(var D=2;D<=b;D++){A.reset(),A.update(w).finish(w);for(var F=0;F<S;F++)K[F]^=w[F]}for(var D=0;D<S&&k*S+D<h;D++)N[k*S+D]=K[D]}for(var k=0;k<S;k++)K[k]=w[k]=0;for(var k=0;k<4;k++)v[k]=0;return A.clean(),N}e.pbkdf2=c})});var Yn=xe(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.Webhook=Ft.WebhookVerificationError=void 0;var bp=Nn(),Vn=Ln(),Cp=Jn(),zn=300,tr=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype),this.name="ExtendableError",this.stack=new Error(t).stack}},at=class e extends tr{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype),this.name="WebhookVerificationError"}};Ft.WebhookVerificationError=at;var Oo=class e{constructor(t,o){if(!t)throw new Error("Secret can't be empty.");if(o?.format==="raw")t instanceof Uint8Array?this.key=t:this.key=Uint8Array.from(t,i=>i.charCodeAt(0));else{if(typeof t!="string")throw new Error("Expected secret to be of type string");t.startsWith(e.prefix)&&(t=t.substring(e.prefix.length)),this.key=Vn.decode(t)}}verify(t,o){let i={};for(let f of Object.keys(o))i[f.toLowerCase()]=o[f];let r=i["webhook-id"],n=i["webhook-signature"],s=i["webhook-timestamp"];if(!n||!r||!s)throw new at("Missing required headers");let a=this.verifyTimestamp(s),d=this.sign(r,a,t).split(",")[1],c=n.split(" "),u=new globalThis.TextEncoder;for(let f of c){let[b,h]=f.split(",");if(b==="v1"&&(0,bp.timingSafeEqual)(u.encode(h),u.encode(d)))return JSON.parse(t.toString())}throw new at("No matching signature found")}sign(t,o,i){if(typeof i!="string")if(i.constructor.name==="Buffer")i=i.toString();else throw new Error("Expected payload to be of type string or Buffer.");let r=new TextEncoder,n=Math.floor(o.getTime()/1e3),s=r.encode(`${t}.${n}.${i}`);return`v1,${Vn.encode(Cp.hmac(this.key,s))}`}verifyTimestamp(t){let o=Math.floor(Date.now()/1e3),i=parseInt(t,10);if(isNaN(i))throw new at("Invalid Signature Headers");if(o-i>zn)throw new at("Message timestamp too old");if(i>o+zn)throw new at("Message timestamp too new");return new Date(i*1e3)}};Ft.Webhook=Oo;Oo.prefix="whsec_"});var To,cs=ge(()=>{"use strict";To=class extends Error{constructor(t){super(`Credentials file is corrupted or contains invalid JSON: ${t}
|
|
27
|
+
`)}),this}_outputHelpIfRequested(t){let o=this._getHelpOption();o&&t.find(r=>o.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Nr(e){return e.map(t=>{if(!t.startsWith("--inspect"))return t;let o,i="127.0.0.1",r="9229",n;return(n=t.match(/^(--inspect(-brk)?)$/))!==null?o=n[1]:(n=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(o=n[1],/^\d+$/.test(n[3])?r=n[3]:i=n[3]):(n=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(o=n[1],i=n[3],r=n[4]),o&&r!=="0"?`${o}=${i}:${parseInt(r)+1}`:t})}function Di(){if(W.env.NO_COLOR||W.env.FORCE_COLOR==="0"||W.env.FORCE_COLOR==="false")return!1;if(W.env.FORCE_COLOR||W.env.CLICOLOR_FORCE!==void 0)return!0}Bi.Command=_i;Bi.useColor=Di});var Jr=xe(Te=>{var{Argument:Mr}=ho(),{Command:Ei}=qr(),{CommanderError:md,InvalidArgumentError:Lr}=Wt(),{Help:fd}=Ki(),{Option:Wr}=Fi();Te.program=new Ei;Te.createCommand=e=>new Ei(e);Te.createOption=(e,t)=>new Wr(e,t);Te.createArgument=(e,t)=>new Mr(e,t);Te.Command=Ei;Te.Option=Wr;Te.Argument=Mr;Te.Help=fd;Te.CommanderError=md;Te.InvalidArgumentError=Lr;Te.InvalidOptionArgumentError=Lr});var zr=xe((_e,Vr)=>{var He=Jr();_e=Vr.exports={};_e.program=new He.Command;_e.Argument=He.Argument;_e.Command=He.Command;_e.CommanderError=He.CommanderError;_e.Help=He.Help;_e.InvalidArgumentError=He.InvalidArgumentError;_e.InvalidOptionArgumentError=He.InvalidArgumentError;_e.Option=He.Option;_e.createCommand=e=>new He.Command(e);_e.createOption=(e,t)=>new He.Option(e,t);_e.createArgument=(e,t)=>new He.Argument(e,t)});var qe=xe((Wf,Oi)=>{var Co=process||{},Zr=Co.argv||[],bo=Co.env||{},gd=!(bo.NO_COLOR||Zr.includes("--no-color"))&&(!!bo.FORCE_COLOR||Zr.includes("--color")||Co.platform==="win32"||(Co.stdout||{}).isTTY&&bo.TERM!=="dumb"||!!bo.CI),hd=(e,t,o=e)=>i=>{let r=""+i,n=r.indexOf(t,e.length);return~n?e+Ad(r,t,o,n)+t:e+r+t},Ad=(e,t,o,i)=>{let r="",n=0;do r+=e.substring(n,i)+o,n=i+t.length,i=e.indexOf(t,n);while(~i);return r+e.substring(n)},en=(e=gd)=>{let t=e?hd:()=>String;return{isColorSupported:e,reset:t("\x1B[0m","\x1B[0m"),bold:t("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:t("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:t("\x1B[3m","\x1B[23m"),underline:t("\x1B[4m","\x1B[24m"),inverse:t("\x1B[7m","\x1B[27m"),hidden:t("\x1B[8m","\x1B[28m"),strikethrough:t("\x1B[9m","\x1B[29m"),black:t("\x1B[30m","\x1B[39m"),red:t("\x1B[31m","\x1B[39m"),green:t("\x1B[32m","\x1B[39m"),yellow:t("\x1B[33m","\x1B[39m"),blue:t("\x1B[34m","\x1B[39m"),magenta:t("\x1B[35m","\x1B[39m"),cyan:t("\x1B[36m","\x1B[39m"),white:t("\x1B[37m","\x1B[39m"),gray:t("\x1B[90m","\x1B[39m"),bgBlack:t("\x1B[40m","\x1B[49m"),bgRed:t("\x1B[41m","\x1B[49m"),bgGreen:t("\x1B[42m","\x1B[49m"),bgYellow:t("\x1B[43m","\x1B[49m"),bgBlue:t("\x1B[44m","\x1B[49m"),bgMagenta:t("\x1B[45m","\x1B[49m"),bgCyan:t("\x1B[46m","\x1B[49m"),bgWhite:t("\x1B[47m","\x1B[49m"),blackBright:t("\x1B[90m","\x1B[39m"),redBright:t("\x1B[91m","\x1B[39m"),greenBright:t("\x1B[92m","\x1B[39m"),yellowBright:t("\x1B[93m","\x1B[39m"),blueBright:t("\x1B[94m","\x1B[39m"),magentaBright:t("\x1B[95m","\x1B[39m"),cyanBright:t("\x1B[96m","\x1B[39m"),whiteBright:t("\x1B[97m","\x1B[39m"),bgBlackBright:t("\x1B[100m","\x1B[49m"),bgRedBright:t("\x1B[101m","\x1B[49m"),bgGreenBright:t("\x1B[102m","\x1B[49m"),bgYellowBright:t("\x1B[103m","\x1B[49m"),bgBlueBright:t("\x1B[104m","\x1B[49m"),bgMagentaBright:t("\x1B[105m","\x1B[49m"),bgCyanBright:t("\x1B[106m","\x1B[49m"),bgWhiteBright:t("\x1B[107m","\x1B[49m")}};Oi.exports=en();Oi.exports.createColors=en});var $i=xe((og,hn)=>{"use strict";var Pi={to(e,t){return t?`\x1B[${t+1};${e+1}H`:`\x1B[${e+1}G`},move(e,t){let o="";return e<0?o+=`\x1B[${-e}D`:e>0&&(o+=`\x1B[${e}C`),t<0?o+=`\x1B[${-t}A`:t>0&&(o+=`\x1B[${t}B`),o},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},Od={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},Td={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let o=0;o<e;o++)t+=this.line+(o<e-1?Pi.up():"");return e&&(t+=Pi.left),t}};hn.exports={cursor:Pi,scroll:Od,erase:Td,beep:"\x07"}});var Mi,Dn=ge(()=>{Mi={name:"resend-cli",version:"2.10.0",description:"The official CLI for Resend",license:"MIT",repository:{type:"git",url:"https://github.com/resend/resend-cli"},homepage:"https://github.com/resend/resend-cli#readme",keywords:["cli","resend","email","api","tanstack-intent"],engines:{node:">=22"},packageManager:"pnpm@11.8.0",files:["dist/cli.cjs","skills/"],type:"module",bin:{resend:"./dist/cli.cjs"},scripts:{dev:"tsx src/cli.ts","dev:watch":"tsx --watch src/cli.ts",build:"node scripts/build.mjs","build:bin":"pnpm build && pkg dist/cli.cjs --config package.json --compress Brotli --target node24 --output dist/resend",lint:"biome check .","lint:fix":"biome check --write .",typecheck:"tsc --noEmit",test:"vitest run","test:e2e":"vitest run --config vitest.config.e2e.ts",prepack:"pnpm install && pnpm build && node scripts/verify-bundle.mjs"},dependencies:{"@clack/prompts":"1.4.0","@commander-js/extra-typings":"14.0.0",commander:"14.0.3",esbuild:"0.28.1","esbuild-wasm":"0.28.0",picocolors:"1.1.1",resend:"6.18.0"},pkg:{scripts:["node_modules/esbuild-wasm/bin/esbuild","node_modules/esbuild-wasm/wasm_exec.js","node_modules/esbuild-wasm/wasm_exec_node.js"],assets:["node_modules/esbuild-wasm/esbuild.wasm"]},devDependencies:{"@biomejs/biome":"2.4.11","@types/node":"24.12.4","@yao-pkg/pkg":"6.20.0",tsx:"4.22.4",typescript:"5.9.3",vitest:"4.1.9"}}});var re,Bn,bt=ge(()=>{"use strict";Dn();re=Mi.version,Bn=Mi.name});var Nn=xe(Bo=>{"use strict";Object.defineProperty(Bo,"__esModule",{value:!0});Bo.timingSafeEqual=void 0;function Qn(e,t=""){if(!e)throw new Error(t)}function pp(e,t){if(e.byteLength!==t.byteLength)return!1;e instanceof DataView||(e=new DataView(ArrayBuffer.isView(e)?e.buffer:e)),t instanceof DataView||(t=new DataView(ArrayBuffer.isView(t)?t.buffer:t)),Qn(e instanceof DataView),Qn(t instanceof DataView);let o=e.byteLength,i=0,r=-1;for(;++r<o;)i|=e.getUint8(r)^t.getUint8(r);return i===0}Bo.timingSafeEqual=pp});var Ln=xe(Be=>{"use strict";var mp=Be&&Be.__extends||(function(){var e=function(t,o){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,r){i.__proto__=r}||function(i,r){for(var n in r)r.hasOwnProperty(n)&&(i[n]=r[n])},e(t,o)};return function(t,o){e(t,o);function i(){this.constructor=t}t.prototype=o===null?Object.create(o):(i.prototype=o.prototype,new i)}})();Object.defineProperty(Be,"__esModule",{value:!0});var ae=256,er=(function(){function e(t){t===void 0&&(t="="),this._paddingCharacter=t}return e.prototype.encodedLength=function(t){return this._paddingCharacter?(t+2)/3*4|0:(t*8+5)/6|0},e.prototype.encode=function(t){for(var o="",i=0;i<t.length-2;i+=3){var r=t[i]<<16|t[i+1]<<8|t[i+2];o+=this._encodeByte(r>>>18&63),o+=this._encodeByte(r>>>12&63),o+=this._encodeByte(r>>>6&63),o+=this._encodeByte(r>>>0&63)}var n=t.length-i;if(n>0){var r=t[i]<<16|(n===2?t[i+1]<<8:0);o+=this._encodeByte(r>>>18&63),o+=this._encodeByte(r>>>12&63),n===2?o+=this._encodeByte(r>>>6&63):o+=this._paddingCharacter||"",o+=this._paddingCharacter||""}return o},e.prototype.maxDecodedLength=function(t){return this._paddingCharacter?t/4*3|0:(t*6+7)/8|0},e.prototype.decodedLength=function(t){return this.maxDecodedLength(t.length-this._getPaddingLength(t))},e.prototype.decode=function(t){if(t.length===0)return new Uint8Array(0);for(var o=this._getPaddingLength(t),i=t.length-o,r=new Uint8Array(this.maxDecodedLength(i)),n=0,s=0,a=0,l=0,d=0,c=0,u=0;s<i-4;s+=4)l=this._decodeChar(t.charCodeAt(s+0)),d=this._decodeChar(t.charCodeAt(s+1)),c=this._decodeChar(t.charCodeAt(s+2)),u=this._decodeChar(t.charCodeAt(s+3)),r[n++]=l<<2|d>>>4,r[n++]=d<<4|c>>>2,r[n++]=c<<6|u,a|=l&ae,a|=d&ae,a|=c&ae,a|=u&ae;if(s<i-1&&(l=this._decodeChar(t.charCodeAt(s)),d=this._decodeChar(t.charCodeAt(s+1)),r[n++]=l<<2|d>>>4,a|=l&ae,a|=d&ae),s<i-2&&(c=this._decodeChar(t.charCodeAt(s+2)),r[n++]=d<<4|c>>>2,a|=c&ae),s<i-3&&(u=this._decodeChar(t.charCodeAt(s+3)),r[n++]=c<<6|u,a|=u&ae),a!==0)throw new Error("Base64Coder: incorrect characters for decoding");return r},e.prototype._encodeByte=function(t){var o=t;return o+=65,o+=25-t>>>8&6,o+=51-t>>>8&-75,o+=61-t>>>8&-15,o+=62-t>>>8&3,String.fromCharCode(o)},e.prototype._decodeChar=function(t){var o=ae;return o+=(42-t&t-44)>>>8&-ae+t-43+62,o+=(46-t&t-48)>>>8&-ae+t-47+63,o+=(47-t&t-58)>>>8&-ae+t-48+52,o+=(64-t&t-91)>>>8&-ae+t-65+0,o+=(96-t&t-123)>>>8&-ae+t-97+26,o},e.prototype._getPaddingLength=function(t){var o=0;if(this._paddingCharacter){for(var i=t.length-1;i>=0&&t[i]===this._paddingCharacter;i--)o++;if(t.length<4||o>2)throw new Error("Base64Coder: incorrect padding")}return o},e})();Be.Coder=er;var io=new er;function fp(e){return io.encode(e)}Be.encode=fp;function gp(e){return io.decode(e)}Be.decode=gp;var qn=(function(e){mp(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype._encodeByte=function(o){var i=o;return i+=65,i+=25-o>>>8&6,i+=51-o>>>8&-75,i+=61-o>>>8&-13,i+=62-o>>>8&49,String.fromCharCode(i)},t.prototype._decodeChar=function(o){var i=ae;return i+=(44-o&o-46)>>>8&-ae+o-45+62,i+=(94-o&o-96)>>>8&-ae+o-95+63,i+=(47-o&o-58)>>>8&-ae+o-48+52,i+=(64-o&o-91)>>>8&-ae+o-65+0,i+=(96-o&o-123)>>>8&-ae+o-97+26,i},t})(er);Be.URLSafeCoder=qn;var Mn=new qn;function hp(e){return Mn.encode(e)}Be.encodeURLSafe=hp;function Ap(e){return Mn.decode(e)}Be.decodeURLSafe=Ap;Be.encodedLength=function(e){return io.encodedLength(e)};Be.maxDecodedLength=function(e){return io.maxDecodedLength(e)};Be.decodedLength=function(e){return io.decodedLength(e)}});var Jn=xe((Wn,Eo)=>{(function(e,t){var o={};t(o);var i=o.default;for(var r in o)i[r]=o[r];typeof Eo=="object"&&typeof Eo.exports=="object"?Eo.exports=i:typeof define=="function"&&define.amd?define(function(){return i}):e.sha256=i})(Wn,function(e){"use strict";e.__esModule=!0,e.digestLength=32,e.blockSize=64;var t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function o(u,f,A,h,b){for(var S,v,K,w,N,k,T,D,F,j,Ce,ie,ht;b>=64;){for(S=f[0],v=f[1],K=f[2],w=f[3],N=f[4],k=f[5],T=f[6],D=f[7],j=0;j<16;j++)Ce=h+j*4,u[j]=(A[Ce]&255)<<24|(A[Ce+1]&255)<<16|(A[Ce+2]&255)<<8|A[Ce+3]&255;for(j=16;j<64;j++)F=u[j-2],ie=(F>>>17|F<<15)^(F>>>19|F<<13)^F>>>10,F=u[j-15],ht=(F>>>7|F<<25)^(F>>>18|F<<14)^F>>>3,u[j]=(ie+u[j-7]|0)+(ht+u[j-16]|0);for(j=0;j<64;j++)ie=(((N>>>6|N<<26)^(N>>>11|N<<21)^(N>>>25|N<<7))+(N&k^~N&T)|0)+(D+(t[j]+u[j]|0)|0)|0,ht=((S>>>2|S<<30)^(S>>>13|S<<19)^(S>>>22|S<<10))+(S&v^S&K^v&K)|0,D=T,T=k,k=N,N=w+ie|0,w=K,K=v,v=S,S=ie+ht|0;f[0]+=S,f[1]+=v,f[2]+=K,f[3]+=w,f[4]+=N,f[5]+=k,f[6]+=T,f[7]+=D,h+=64,b-=64}return h}var i=(function(){function u(){this.digestLength=e.digestLength,this.blockSize=e.blockSize,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return u.prototype.reset=function(){return this.state[0]=1779033703,this.state[1]=3144134277,this.state[2]=1013904242,this.state[3]=2773480762,this.state[4]=1359893119,this.state[5]=2600822924,this.state[6]=528734635,this.state[7]=1541459225,this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this},u.prototype.clean=function(){for(var f=0;f<this.buffer.length;f++)this.buffer[f]=0;for(var f=0;f<this.temp.length;f++)this.temp[f]=0;this.reset()},u.prototype.update=function(f,A){if(A===void 0&&(A=f.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");var h=0;if(this.bytesHashed+=A,this.bufferLength>0){for(;this.bufferLength<64&&A>0;)this.buffer[this.bufferLength++]=f[h++],A--;this.bufferLength===64&&(o(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(A>=64&&(h=o(this.temp,this.state,f,h,A),A%=64);A>0;)this.buffer[this.bufferLength++]=f[h++],A--;return this},u.prototype.finish=function(f){if(!this.finished){var A=this.bytesHashed,h=this.bufferLength,b=A/536870912|0,S=A<<3,v=A%64<56?64:128;this.buffer[h]=128;for(var K=h+1;K<v-8;K++)this.buffer[K]=0;this.buffer[v-8]=b>>>24&255,this.buffer[v-7]=b>>>16&255,this.buffer[v-6]=b>>>8&255,this.buffer[v-5]=b>>>0&255,this.buffer[v-4]=S>>>24&255,this.buffer[v-3]=S>>>16&255,this.buffer[v-2]=S>>>8&255,this.buffer[v-1]=S>>>0&255,o(this.temp,this.state,this.buffer,0,v),this.finished=!0}for(var K=0;K<8;K++)f[K*4+0]=this.state[K]>>>24&255,f[K*4+1]=this.state[K]>>>16&255,f[K*4+2]=this.state[K]>>>8&255,f[K*4+3]=this.state[K]>>>0&255;return this},u.prototype.digest=function(){var f=new Uint8Array(this.digestLength);return this.finish(f),f},u.prototype._saveState=function(f){for(var A=0;A<this.state.length;A++)f[A]=this.state[A]},u.prototype._restoreState=function(f,A){for(var h=0;h<this.state.length;h++)this.state[h]=f[h];this.bytesHashed=A,this.finished=!1,this.bufferLength=0},u})();e.Hash=i;var r=(function(){function u(f){this.inner=new i,this.outer=new i,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var A=new Uint8Array(this.blockSize);if(f.length>this.blockSize)new i().update(f).finish(A).clean();else for(var h=0;h<f.length;h++)A[h]=f[h];for(var h=0;h<A.length;h++)A[h]^=54;this.inner.update(A);for(var h=0;h<A.length;h++)A[h]^=106;this.outer.update(A),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate);for(var h=0;h<A.length;h++)A[h]=0}return u.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},u.prototype.clean=function(){for(var f=0;f<this.istate.length;f++)this.ostate[f]=this.istate[f]=0;this.inner.clean(),this.outer.clean()},u.prototype.update=function(f){return this.inner.update(f),this},u.prototype.finish=function(f){return this.outer.finished?this.outer.finish(f):(this.inner.finish(f),this.outer.update(f,this.digestLength).finish(f)),this},u.prototype.digest=function(){var f=new Uint8Array(this.digestLength);return this.finish(f),f},u})();e.HMAC=r;function n(u){var f=new i().update(u),A=f.digest();return f.clean(),A}e.hash=n,e.default=n;function s(u,f){var A=new r(u).update(f),h=A.digest();return A.clean(),h}e.hmac=s;function a(u,f,A,h){var b=h[0];if(b===0)throw new Error("hkdf: cannot expand more");f.reset(),b>1&&f.update(u),A&&f.update(A),f.update(h),f.finish(u),h[0]++}var l=new Uint8Array(e.digestLength);function d(u,f,A,h){f===void 0&&(f=l),h===void 0&&(h=32);for(var b=new Uint8Array([1]),S=s(f,u),v=new r(S),K=new Uint8Array(v.digestLength),w=K.length,N=new Uint8Array(h),k=0;k<h;k++)w===K.length&&(a(K,v,A,b),w=0),N[k]=K[w++];return v.clean(),K.fill(0),b.fill(0),N}e.hkdf=d;function c(u,f,A,h){for(var b=new r(u),S=b.digestLength,v=new Uint8Array(4),K=new Uint8Array(S),w=new Uint8Array(S),N=new Uint8Array(h),k=0;k*S<h;k++){var T=k+1;v[0]=T>>>24&255,v[1]=T>>>16&255,v[2]=T>>>8&255,v[3]=T>>>0&255,b.reset(),b.update(f),b.update(v),b.finish(w);for(var D=0;D<S;D++)K[D]=w[D];for(var D=2;D<=A;D++){b.reset(),b.update(w).finish(w);for(var F=0;F<S;F++)K[F]^=w[F]}for(var D=0;D<S&&k*S+D<h;D++)N[k*S+D]=K[D]}for(var k=0;k<S;k++)K[k]=w[k]=0;for(var k=0;k<4;k++)v[k]=0;return b.clean(),N}e.pbkdf2=c})});var Yn=xe(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.Webhook=Ft.WebhookVerificationError=void 0;var bp=Nn(),Vn=Ln(),Cp=Jn(),zn=300,tr=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype),this.name="ExtendableError",this.stack=new Error(t).stack}},at=class e extends tr{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype),this.name="WebhookVerificationError"}};Ft.WebhookVerificationError=at;var Oo=class e{constructor(t,o){if(!t)throw new Error("Secret can't be empty.");if(o?.format==="raw")t instanceof Uint8Array?this.key=t:this.key=Uint8Array.from(t,i=>i.charCodeAt(0));else{if(typeof t!="string")throw new Error("Expected secret to be of type string");t.startsWith(e.prefix)&&(t=t.substring(e.prefix.length)),this.key=Vn.decode(t)}}verify(t,o){let i={};for(let f of Object.keys(o))i[f.toLowerCase()]=o[f];let r=i["webhook-id"],n=i["webhook-signature"],s=i["webhook-timestamp"];if(!n||!r||!s)throw new at("Missing required headers");let a=this.verifyTimestamp(s),d=this.sign(r,a,t).split(",")[1],c=n.split(" "),u=new globalThis.TextEncoder;for(let f of c){let[A,h]=f.split(",");if(A==="v1"&&(0,bp.timingSafeEqual)(u.encode(h),u.encode(d)))return JSON.parse(t.toString())}throw new at("No matching signature found")}sign(t,o,i){if(typeof i!="string")if(i.constructor.name==="Buffer")i=i.toString();else throw new Error("Expected payload to be of type string or Buffer.");let r=new TextEncoder,n=Math.floor(o.getTime()/1e3),s=r.encode(`${t}.${n}.${i}`);return`v1,${Vn.encode(Cp.hmac(this.key,s))}`}verifyTimestamp(t){let o=Math.floor(Date.now()/1e3),i=parseInt(t,10);if(isNaN(i))throw new at("Invalid Signature Headers");if(o-i>zn)throw new at("Message timestamp too old");if(i>o+zn)throw new at("Message timestamp too new");return new Date(i*1e3)}};Ft.Webhook=Oo;Oo.prefix="whsec_"});var To,cs=ge(()=>{"use strict";To=class extends Error{constructor(t){super(`Credentials file is corrupted or contains invalid JSON: ${t}
|
|
28
28
|
The file has been preserved for manual inspection.
|
|
29
29
|
To fix: either repair the JSON manually, or delete the file and run: resend login`),this.name="CorruptedCredentialsError"}}});var ir={};Lt(ir,{FileBackend:()=>or});var or,rr=ge(()=>{"use strict";he();or=class{name="plaintext file";isSecure=!1;async get(t,o){let i=Ue();if(!i)return null;let r=i.profiles[o];return(r?.type==="api_key"?r.api_key:null)??null}async set(t,o,i){nr(i,o)}async delete(t,o){try{return us(o),!0}catch{return!1}}async isAvailable(){return!0}}});var ps={};Lt(ps,{MacOSBackend:()=>ar});function sr(e,t){return new Promise(o=>{(0,ds.execFile)(e,t,{timeout:5e3},(i,r,n)=>{let s=i&&"code"in i?i.code:0;o({stdout:r??"",stderr:n??"",code:s})})})}var ds,ar,ms=ge(()=>{"use strict";ds=require("node:child_process");ar=class{name="macOS Keychain";isSecure=!0;async get(t,o){let{stdout:i,stderr:r,code:n}=await sr("/usr/bin/security",["find-generic-password","-s",t,"-a",o,"-w"]);if(n===44)return null;if(n!==0)throw new Error(`Failed to read from macOS Keychain (exit code ${n}): ${r.trim()}`);return i.trim()||null}async set(t,o,i){let{code:r,stderr:n}=await sr("/usr/bin/security",["add-generic-password","-s",t,"-a",o,"-w",i,"-U"]);if(r!==0)throw new Error(`Failed to store credential in macOS Keychain: ${n.trim()}`)}async delete(t,o){let{code:i}=await sr("/usr/bin/security",["delete-generic-password","-s",t,"-a",o]);return i===0}async isAvailable(){return process.platform==="darwin"}}});var fs={};Lt(fs,{LinuxBackend:()=>lr});function jo(e,t,o){return new Promise(i=>{(0,Io.execFile)(e,t,{timeout:o?.timeout??5e3},(r,n,s)=>{let a=r&&"code"in r?r.code:0;i({stdout:n??"",stderr:s??"",code:a})})})}function tm(e,t,o){return new Promise(i=>{let r=(0,Io.spawn)(e,t,{stdio:["pipe","ignore","pipe"],timeout:5e3}),n="";r.stderr?.on("data",s=>{n+=s.toString()}),r.on("close",s=>{i({code:s,stderr:n})}),r.on("error",()=>{i({code:1,stderr:"Failed to spawn process"})}),r.stdin?.on("error",()=>{}),r.stdin?.write(o),r.stdin?.end()})}var Io,lr,gs=ge(()=>{"use strict";Io=require("node:child_process");lr=class{name="Secret Service (libsecret)";isSecure=!0;async get(t,o){let{stdout:i,code:r}=await jo("secret-tool",["lookup","service",t,"account",o]);return r!==0||!i.trim()?null:i.trim()}async set(t,o,i){let{code:r,stderr:n}=await tm("secret-tool",["store",`--label=Resend CLI (${o})`,"service",t,"account",o],i);if(r!==0)throw new Error(`Failed to store credential in Secret Service: ${n.trim()}`)}async delete(t,o){let{code:i}=await jo("secret-tool",["clear","service",t,"account",o]);return i===0}async isAvailable(){if(process.platform!=="linux"||(await jo("which",["secret-tool"])).code!==0)return!1;let o=await jo("secret-tool",["lookup","service","__resend_cli_probe__"],{timeout:3e3});return o.code===0||o.code===1}}});var hs={};Lt(hs,{WindowsBackend:()=>cr});function Po(e){return new Promise(t=>{(0,$o.execFile)("powershell.exe",["-NoProfile","-NonInteractive","-Command",e],{timeout:1e4},(o,i,r)=>{let n=o&&"code"in o?o.code:0;t({stdout:i??"",stderr:r??"",code:n})})})}function om(e,t){return new Promise(o=>{let i=(0,$o.spawn)("powershell.exe",["-NoProfile","-NonInteractive","-Command",e],{stdio:["pipe","pipe","pipe"],timeout:1e4}),r="",n="";i.stdout?.on("data",s=>{r+=s.toString()}),i.stderr?.on("data",s=>{n+=s.toString()}),i.on("close",s=>{o({stdout:r,stderr:n,code:s})}),i.on("error",()=>{o({stdout:"",stderr:"Failed to spawn process",code:1})}),i.stdin?.on("error",()=>{}),i.stdin?.write(t),i.stdin?.end()})}function lt(e){return e.replace(/'/g,"''")}var $o,no,cr,As=ge(()=>{"use strict";$o=require("node:child_process");no=`
|
|
30
30
|
try { $null = [Windows.Security.Credentials.PasswordVault] } catch {
|
|
@@ -128,7 +128,7 @@ To fix: either repair the JSON manually, or delete the file and run: resend logi
|
|
|
128
128
|
<p>${o}</p>
|
|
129
129
|
</main>
|
|
130
130
|
</body>
|
|
131
|
-
</html>`}function _s(){let e=mr((0,so.randomBytes)(64)),t=mr((0,so.createHash)("sha256").update(e).digest()),o=mr((0,so.randomBytes)(24));return{codeVerifier:e,codeChallenge:t,state:o}}function Ds(){return new Promise((e,t)=>{let o,i,r=new Promise((a,l)=>{o=a,i=l}),n=(0,xs.createServer)((a,l)=>{let d=new URL(a.url??"/","http://127.0.0.1");if(d.pathname!=="/oauth/callback"){l.writeHead(404,{Connection:"close"}),l.end();return}let c=d.searchParams.get("code"),u=d.searchParams.get("state"),f=d.searchParams.get("error"),
|
|
131
|
+
</html>`}function _s(){let e=mr((0,so.randomBytes)(64)),t=mr((0,so.createHash)("sha256").update(e).digest()),o=mr((0,so.randomBytes)(24));return{codeVerifier:e,codeChallenge:t,state:o}}function Ds(){return new Promise((e,t)=>{let o,i,r=new Promise((a,l)=>{o=a,i=l}),n=(0,xs.createServer)((a,l)=>{let d=new URL(a.url??"/","http://127.0.0.1");if(d.pathname!=="/oauth/callback"){l.writeHead(404,{Connection:"close"}),l.end();return}let c=d.searchParams.get("code"),u=d.searchParams.get("state"),f=d.searchParams.get("error"),A=f?`Authorization denied: ${f}`:!c||!u?"Missing code or state in OAuth callback":null,h=ws(A?{heading:"Authentication failed",message:`${A}. Return to your terminal and try again.`}:{heading:"Authentication complete",message:"You can close this tab and return to your terminal."});l.writeHead(200,{"Content-Type":"text/html; charset=utf-8",Connection:"close"}),l.end(h,()=>{a.socket.destroy()}),n.close(),clearTimeout(s),A?i(new Error(A)):c&&u&&o({code:c,state:u})}),s=setTimeout(()=>{n.close(),i(new Error("OAuth login timed out after 5 minutes. Please try again."))},300*1e3);n.listen(0,"127.0.0.1",()=>{let{port:a}=n.address();e({port:a,waitForCallback:r})}),n.on("error",t)})}async function Bs(e){let t=await ks(`${e.baseUrl}/oauth/token`,new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:e.code,redirect_uri:e.redirectUri,code_verifier:e.codeVerifier}),"Token exchange");if(!t.ok){let o="";try{let i=await t.json();o=i.error_description??i.error??""}catch{}throw new Error(`Token exchange failed (${t.status})${o?`: ${o}`:""}`)}return Fs(await t.json())}var so,xs,Ho,pr,lm,cm,gr,um,Go=ge(()=>{"use strict";so=require("node:crypto"),xs=require("node:http");he();vs();Ho="7136aa0b-625c-4c9c-8820-e9784c8eb141",pr="Received an invalid access token from Resend. Please run `resend login` to authenticate again.";lm=3e4,cm=60,gr="OAuthNetworkError";um=`<svg class="logo" role="img" aria-label="Resend" fill="none" viewBox="0 0 78 78" xmlns="http://www.w3.org/2000/svg">
|
|
132
132
|
<rect x="1" y="1" width="76" height="76" rx="21" stroke="#FDFDFD" stroke-opacity="0.1" stroke-width="2" />
|
|
133
133
|
<path d="M43.0184 21C49.9908 21 54.1374 25.1467 54.1374 30.6513C54.1374 36.1558 49.9908 40.3025 43.0184 40.3025H39.4953L57 57H44.6329L31.3118 44.3394C30.3578 43.4587 29.9174 42.4312 29.9174 41.5506C29.9174 40.3029 30.7984 39.202 32.4864 38.7249L39.3485 36.8897C41.954 36.1925 43.7522 34.1741 43.7522 31.5319C43.7522 28.3027 41.1098 26.4312 37.8438 26.4312H21V21H43.0184Z" fill="url(#resend_cli_logo_a)" />
|
|
134
134
|
<path d="M54.1375 30.6513C54.1374 25.1467 49.9908 21 43.0184 21V20.55C46.5934 20.55 49.4879 21.6142 51.4941 23.4275C53.4405 25.1867 54.5189 27.6229 54.5844 30.3832L54.5875 30.6513C54.5875 33.5218 53.5032 36.0591 51.4941 37.875C49.5505 39.6317 46.7734 40.6853 43.3515 40.7495L43.0184 40.7525H40.619L58.1237 57.45H44.4532L44.3231 57.3261L31.0064 44.6694C29.978 43.7199 29.4675 42.579 29.4674 41.5506C29.4674 40.0491 30.5379 38.8082 32.3643 38.292L32.37 38.2903L39.2321 36.4551C41.6742 35.8016 43.3023 33.9377 43.3023 31.5319C43.3023 30.0523 42.7022 28.9051 41.7383 28.1191C40.7652 27.3258 39.3949 26.8812 37.8438 26.8812H20.55V20.55H43.0184V21H21V26.4312H37.8438C41.1098 26.4312 43.7522 28.3027 43.7523 31.5319C43.7523 34.1741 41.954 36.1925 39.3485 36.8897L32.4865 38.7249C30.7984 39.202 29.9174 40.3029 29.9174 41.5506C29.9175 42.4312 30.3578 43.4587 31.3118 44.3393L44.633 57H57.0001L39.4953 40.3025H43.0184C49.9909 40.3025 54.1375 36.1558 54.1375 30.6513Z" fill="url(#resend_cli_logo_b)" />
|
|
@@ -142,14 +142,14 @@ To fix: either repair the JSON manually, or delete the file and run: resend logi
|
|
|
142
142
|
<stop offset="1" stop-color="#ADADAD" />
|
|
143
143
|
</linearGradient>
|
|
144
144
|
</defs>
|
|
145
|
-
</svg>`});var
|
|
146
|
-
`,384),(0,
|
|
147
|
-
Create a full access key at https://resend.com/api-keys`;ct=()=>(0,Rt.join)(Ie(),"credentials.json.lock")});function U(){return!(!process.stdin.isTTY||!process.stdout.isTTY||process.env.CI==="true"||process.env.CI==="1"||process.env.GITHUB_ACTIONS||process.env.TERM==="dumb")}var et,J=ge(()=>{"use strict";et=process.platform!=="win32"||!!process.env.WT_SESSION||process.env.TERM_PROGRAM==="vscode"});function Tl(){return(0,Ol.join)(Ie(),"update-state.json")}function qm(){try{return JSON.parse((0,Gt.readFileSync)(Tl(),"utf-8"))}catch{return null}}function Mm(e){(0,Gt.mkdirSync)(Ie(),{recursive:!0,mode:448}),(0,Gt.writeFileSync)(Tl(),JSON.stringify(e),{mode:384})}function ci(e,t){let o=d=>d.replace(/^v/,"").split(".").map(Number),[i,r,n]=o(e),[s,a,l]=o(t);return s!==i?s>i:a!==r?a>r:l>n}async function Fr(){try{let e=await fetch(xr,{headers:{Accept:"application/vnd.github.v3+json"},signal:AbortSignal.timeout(5e3)});if(!e.ok)return null;let t=await e.json();if(t.prerelease||t.draft)return null;let o=t.tag_name?.replace(/^v/,"");return!o||!/^\d+\.\d+\.\d+$/.test(o)?null:o}catch{return null}}function Lm(e){return!!(e?.json||process.env.RESEND_NO_UPDATE_NOTIFIER==="1"||process.env.CI==="true"||process.env.CI==="1"||process.env.GITHUB_ACTIONS||!process.stdout.isTTY)}function jl(){let e=ui();return e.startsWith("npm")?"npm":e.startsWith("brew")?"homebrew":e.startsWith("curl")||e.startsWith("irm")?"install-script":"manual"}function ui(){let e=process.execPath||process.argv[0]||"",t=process.argv[1]||"";return process.env.npm_execpath||/node_modules/.test(t)||/node_modules/.test(e)?"npm install -g resend-cli":/\/(Cellar|homebrew)\//i.test(e)?"brew update && brew upgrade resend":/[/\\]\.resend[/\\]bin[/\\]/.test(e)?process.platform==="win32"?"irm https://resend.com/install.ps1 | iex":"curl -fsSL https://resend.com/install.sh | bash":"https://github.com/resend/resend-cli/releases/latest"}function
|
|
148
|
-
`)}async function Il(e){if(Lm(e))return;let t=qm(),o=Date.now();if(t&&o-t.lastChecked<Nm){ci(re,t.latestVersion)&&process.stderr.write(
|
|
145
|
+
</svg>`});var Es,Ke,Os,Ts,dm,js=ge(()=>{"use strict";Es=require("node:crypto"),Ke=require("node:fs"),Os=require("node:path"),Ts=(e,t,o)=>{let i=`${e}.tmp.${process.pid}.${(0,Es.randomUUID)()}`;try{let r=(0,Ke.openSync)(i,"w",o);try{(0,Ke.writeSync)(r,t),(0,Ke.fsyncSync)(r)}finally{(0,Ke.closeSync)(r)}(0,Ke.renameSync)(i,e),dm((0,Os.dirname)(e))}catch(r){try{(0,Ke.unlinkSync)(i)}catch{}throw r}},dm=e=>{if(process.platform!=="win32")try{let t=(0,Ke.openSync)(e,"r");try{(0,Ke.fsyncSync)(t)}finally{(0,Ke.closeSync)(t)}}catch{}}});function Ie(){return process.env.XDG_CONFIG_HOME?(0,Rt.join)(process.env.XDG_CONFIG_HOME,"resend"):process.platform==="win32"&&process.env.APPDATA?(0,Rt.join)(process.env.APPDATA,"resend"):(0,Rt.join)((0,$s.homedir)(),".config","resend")}function Ut(){return(0,Rt.join)(Ie(),"credentials.json")}function Is(e){return e.type==="oauth_grant"?Ar(e)?{type:"oauth_grant",...e}:{type:"oauth_grant",scope:typeof e.scope=="string"?e.scope:""}:{type:"api_key",...e.api_key!==void 0?{api_key:e.api_key}:{},...e.permission?{permission:e.permission}:{}}}function hr(){try{return Ue()}catch{return null}}function Ue(){let e=Ut();if(!(0,Ee.existsSync)(e))return null;let t=(0,Ee.readFileSync)(e,"utf-8");if(t.trim().length===0)return null;let o;try{o=JSON.parse(t)}catch{throw new To(e)}if(typeof o=="object"&&o!==null&&"api_key"in o&&!("profiles"in o)&&!("teams"in o))return{active_profile:"default",profiles:{default:{type:"api_key",api_key:o.api_key}}};if("profiles"in o){let i=o.storage==="keychain"?"secure_storage":o.storage,r=o.profiles;return{active_profile:o.active_profile??"default",...i?{storage:i}:{},profiles:Object.fromEntries(Object.entries(r).map(([n,s])=>[n,Is(s)]))}}if("teams"in o){let i=o.teams;return{active_profile:o.active_team??"default",profiles:Object.fromEntries(Object.entries(i).map(([r,n])=>[r,Is(n)]))}}return null}function ut(e){let t=Ie();(0,Ee.mkdirSync)(t,{recursive:!0,mode:448});let o=Ut();return Ts(o,`${JSON.stringify(e,null,2)}
|
|
146
|
+
`,384),(0,Ee.chmodSync)(o,384),o}function No(e){if(e)return e;let t=process.env.RESEND_PROFILE;if(t)return t;let o=Ue();return o?.active_profile?o.active_profile:"default"}function nr(e,t,o){let i=t||"default",r=le(i);if(r)throw new Error(r);return Ze(ct(),()=>{let n=Ue()||{active_profile:"default",profiles:{}},s={...n.profiles,[i]:{type:"api_key",api_key:e,...o&&{permission:o}}},a={...n,profiles:s,...Object.keys(s).length===1?{active_profile:i}:{}};return ut(a)})}function us(e){return Ze(ct(),()=>{let t=Ue();if(!t)throw new Error("No credentials file found.");let o=e||No();if(!t.profiles[o])throw new Error(`Profile "${o}" not found. Available profiles: ${Object.keys(t.profiles).join(", ")}`);let{[o]:i,...r}=t.profiles;if(Object.keys(r).length===0){let s=Ut();return(0,Ee.unlinkSync)(s),s}let n=t.active_profile===o?Object.keys(r)[0]||"default":t.active_profile;return ut({...t,active_profile:n,profiles:r})})}function ao(e){let t=le(e);if(t)throw new Error(t);Ze(ct(),()=>{let o=Ue();if(!o)throw new Error("No credentials file found. Run: resend login");if(!o.profiles[e])throw new Error(`Profile "${e}" not found. Available profiles: ${Object.keys(o.profiles).join(", ")}`);ut({...o,active_profile:e})})}function ve(){let e=Ue();return e?Object.keys(e.profiles).map(t=>({name:t,active:t===e.active_profile})):[]}function le(e){if(!e||e.length===0)return"Profile name must not be empty";if(e.length>64)return"Profile name must be 64 characters or fewer";if(!/^[a-zA-Z0-9._-]+$/.test(e))return"Profile name must contain only letters, numbers, dots, dashes, and underscores"}function dt(e){return e.length<=7?`${e.slice(0,3)}...`:`${e.slice(0,3)}...${e.slice(-4)}`}function Ar(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.access_token=="string"&&typeof t.access_token_expires_at=="number"&&typeof t.refresh_token=="string"&&typeof t.scope=="string"}function pm(e){return Ar(e)?e:null}function mm(e){let t;try{t=JSON.parse(e)}catch{t=null}if(!Ar(t))throw new Error("Stored OAuth credentials are invalid. Please run `resend login` to authenticate again.");return t}async function St(e,t,o){if(e)return{type:"api_key",key:e,source:"flag"};let i=process.env.RESEND_API_KEY;if(i)return{type:"api_key",key:i,source:"env"};let r=Ue(),n=t||process.env.RESEND_PROFILE||r?.active_profile||"default";if(r?.storage==="secure_storage"&&r.profiles[n]){let s=r.profiles[n],l=await(await Xe()).get(Ge,n);if(l){if(s.type==="oauth_grant"){let d=mm(l);return Ps(d,n,"secure_storage",o)}return{type:"api_key",key:l,source:"secure_storage",profile:n,permission:s.permission}}}if(r){let s=r.profiles[n];if(s?.type==="api_key"&&s.api_key)return{type:"api_key",key:s.api_key,source:"config",profile:n,permission:s.permission};if(s?.type==="oauth_grant"){let a=pm(s);if(a)return Ps(a,n,"config",o)}}return null}async function Ps(e,t,o,i){if(i?.refresh===!1)return{type:"oauth_grant",access_token:e.access_token,profile:t,scope:e.scope,source:o};let{access_token:r,scope:n}=await Rs(e,t);return{type:"oauth_grant",access_token:r,profile:t,scope:n,source:o}}async function Hs(e,t,o){let i=t||"default",r=le(i);if(r)throw new Error(r);let n=await Xe();return n.isSecure?{configPath:await Ze(ct(),async()=>{await n.set(Ge,i,e);let a=Ue()||{active_profile:"default",profiles:{}},l={...a.profiles,[i]:{type:"api_key",...o&&{permission:o}}};return ut({...a,storage:"secure_storage",profiles:l,...Object.keys(l).length===1?{active_profile:i}:{}})}),backend:n}:{configPath:nr(e,i,o),backend:n}}async function Qo(e,t){let o=t||"default",i=le(o);if(i)throw new Error(i);let r=await Xe();return{configPath:await Ze(ct(),async()=>{let s=Ue()||{active_profile:"default",profiles:{}},a=r.isSecure?{type:"oauth_grant",scope:e.scope}:{type:"oauth_grant",...e};r.isSecure&&await r.set(Ge,o,JSON.stringify(e));let l={...s.profiles,[o]:a};try{return ut({...s,storage:r.isSecure?"secure_storage":"file",profiles:l,...Object.keys(l).length===1?{active_profile:o}:{}})}catch(d){throw r.isSecure&&await r.delete(Ge,o).catch(()=>{}),d}}),backend:r}}async function qo(e){return Ze(ct(),async()=>{let t=Ue(),o=e||process.env.RESEND_PROFILE||t?.active_profile||"default";if(!t?.profiles[o])throw new Error(t?`Profile "${o}" not found. Available profiles: ${Object.keys(t.profiles).join(", ")}`:"No credentials file found.");if(t.storage==="secure_storage"){let s=await Xe();if(s.isSecure&&!await s.delete(Ge,o))throw new Error(`Failed to remove API key for profile "${o}" from ${s.name}. Credential may still exist in secure storage.`)}let{[o]:i,...r}=t.profiles;if(Object.keys(r).length===0){let s=Ut();return(0,Ee.unlinkSync)(s),s}let n=t.active_profile===o?Object.keys(r)[0]||"default":t.active_profile;return ut({...t,active_profile:n,profiles:r})})}async function Gs(){return Ze(ct(),async()=>{let e=hr(),t=Ut();if(e?.storage==="secure_storage"){let o=await Xe();if(o.isSecure){let i=Object.keys(e.profiles),r=await Promise.all(i.map(s=>o.delete(Ge,s))),n=i.filter((s,a)=>!r[a]);if(n.length>0){let s=Object.fromEntries(Object.entries(e.profiles).filter(([l])=>!r[i.indexOf(l)])),a=Object.keys(s);throw ut({...e,active_profile:e.active_profile&&s[e.active_profile]?e.active_profile:a[0]??"default",profiles:s}),new Error(`Failed to remove API keys from ${o.name} for profiles: ${n.join(", ")}. Credentials may still exist in secure storage.`)}}}return(0,Ee.existsSync)(t)&&(0,Ee.unlinkSync)(t),t})}async function Mo(e,t){if(e===t)return;let o=le(t);if(o)throw new Error(o);await Ze(ct(),async()=>{let i=Ue();if(!i)throw new Error("No credentials file found. Run: resend login");if(!i.profiles[e])throw new Error(`Profile "${e}" not found. Available profiles: ${Object.keys(i.profiles).join(", ")}`);if(i.profiles[t])throw new Error(`Profile "${t}" already exists.`);if(i.storage==="secure_storage"){let s=await Xe();if(s.isSecure){let a=await s.get(Ge,e);if(a&&(await s.set(Ge,t,a),!await s.delete(Ge,e))){let d=await s.delete(Ge,t);throw new Error(d?`Failed to remove old credential "${e}" from ${s.name} during rename. The rename has been rolled back.`:`Failed to remove old credential "${e}" from ${s.name} during rename. Rollback also failed \u2014 credential "${t}" may still exist in secure storage.`)}}}let{[e]:r,...n}=i.profiles;ut({...i,active_profile:i.active_profile===e?t:i.active_profile,profiles:{...n,[t]:r}})})}var Ee,$s,Rt,_t,ct,he=ge(()=>{"use strict";Ee=require("node:fs"),$s=require("node:os"),Rt=require("node:path");cs();ur();Ss();Go();js();_t=`Sending-only keys work with: emails send, emails batch, broadcasts send.
|
|
147
|
+
Create a full access key at https://resend.com/api-keys`;ct=()=>(0,Rt.join)(Ie(),"credentials.json.lock")});function U(){return!(!process.stdin.isTTY||!process.stdout.isTTY||process.env.CI==="true"||process.env.CI==="1"||process.env.GITHUB_ACTIONS||process.env.TERM==="dumb")}var et,J=ge(()=>{"use strict";et=process.platform!=="win32"||!!process.env.WT_SESSION||process.env.TERM_PROGRAM==="vscode"});function Tl(){return(0,Ol.join)(Ie(),"update-state.json")}function qm(){try{return JSON.parse((0,Gt.readFileSync)(Tl(),"utf-8"))}catch{return null}}function Mm(e){(0,Gt.mkdirSync)(Ie(),{recursive:!0,mode:448}),(0,Gt.writeFileSync)(Tl(),JSON.stringify(e),{mode:384})}function ci(e,t){let o=d=>d.replace(/^v/,"").split(".").map(Number),[i,r,n]=o(e),[s,a,l]=o(t);return s!==i?s>i:a!==r?a>r:l>n}async function Fr(){try{let e=await fetch(xr,{headers:{Accept:"application/vnd.github.v3+json"},signal:AbortSignal.timeout(5e3)});if(!e.ok)return null;let t=await e.json();if(t.prerelease||t.draft)return null;let o=t.tag_name?.replace(/^v/,"");return!o||!/^\d+\.\d+\.\d+$/.test(o)?null:o}catch{return null}}function Lm(e){return!!(e?.json||process.env.RESEND_NO_UPDATE_NOTIFIER==="1"||process.env.CI==="true"||process.env.CI==="1"||process.env.GITHUB_ACTIONS||!process.stdout.isTTY)}function jl(){let e=ui();return e.startsWith("npm")?"npm":e.startsWith("brew")?"homebrew":e.startsWith("curl")||e.startsWith("irm")?"install-script":"manual"}function ui(){let e=process.execPath||process.argv[0]||"",t=process.argv[1]||"";return process.env.npm_execpath||/node_modules/.test(t)||/node_modules/.test(e)?"npm install -g resend-cli":/\/(Cellar|homebrew)\//i.test(e)?"brew update && brew upgrade resend":/[/\\]\.resend[/\\]bin[/\\]/.test(e)?process.platform==="win32"?"irm https://resend.com/install.ps1 | iex":"curl -fsSL https://resend.com/install.sh | bash":"https://github.com/resend/resend-cli/releases/latest"}function El(e){let t=ui(),o=t.startsWith("http"),i="\x1B[2m",r="\x1B[33m",n="\x1B[36m",s="\x1B[0m",a=["",`${i}Update available: ${r}v${re}${s}${i} \u2192 ${n}v${e}${s}`,`${i}${o?"Visit":"Run"}: ${n}${t}${s}`];return process.platform==="win32"&&a.push(`${i}Or download from: ${n}https://github.com/resend/resend-cli/releases/latest${s}`),a.push(""),a.join(`
|
|
148
|
+
`)}async function Il(e){if(Lm(e))return;let t=qm(),o=Date.now();if(t&&o-t.lastChecked<Nm){ci(re,t.latestVersion)&&process.stderr.write(El(t.latestVersion));return}let i=await Fr();i&&(Mm({lastChecked:o,latestVersion:i}),ci(re,i)&&process.stderr.write(El(i)))}var Gt,Ol,Nm,xr,fo=ge(()=>{"use strict";Gt=require("node:fs"),Ol=require("node:path");he();bt();Nm=3600*1e3,xr="https://api.github.com/repos/resend/resend-cli/releases/latest"});var qu={};Lt(qu,{flushFromFile:()=>Rf,flushPayload:()=>Nu,getOrCreateAnonymousId:()=>Qu,getSpoolDir:()=>Er,isDisabled:()=>Gu,trackCommand:()=>Or});function vf(){return Kf[process.platform]??process.platform}function Er(){let e=(0,Ne.join)(Ie(),"telemetry-spool");return(0,M.mkdirSync)(e,{recursive:!0,mode:448}),e}function Gu(){return!Hu||process.env.DO_NOT_TRACK==="1"||process.env.RESEND_TELEMETRY_DISABLED==="1"}function Qu(){let e=Ie(),t=(0,Ne.join)(e,"telemetry-id");try{let i=(0,M.readFileSync)(t,"utf-8").trim();if(i)return i}catch{}let o=crypto.randomUUID();return(0,M.mkdirSync)(e,{recursive:!0,mode:448}),(0,M.writeFileSync)(t,o,{mode:384}),o}function wf(e){if(!e)return;let t=Ie(),o=(0,Ne.join)(t,"telemetry-notice-shown");(0,M.existsSync)(o)||((0,M.mkdirSync)(t,{recursive:!0,mode:448}),(0,M.writeFileSync)(o,"",{mode:384}),process.stderr.write(`
|
|
149
149
|
Resend collects anonymous CLI usage data to improve the tool.
|
|
150
150
|
To opt out: export RESEND_TELEMETRY_DISABLED=1
|
|
151
151
|
|
|
152
|
-
`))}function Or(e,t){if(!Gu())try{let o=U()&&!t.json;wf(o);let i=Qu(),r={command:e,cli_version:re,os:vf(),node_version:process.version,interactive:o,install_method:jl()};t.flags?.length&&(r.flags=t.flags),t.globalFlags?.length&&(r.global_flags=t.globalFlags);let n=crypto.randomUUID(),s=JSON.stringify({api_key:Hu,distinct_id:i,event:"cli.used",properties:r,_nonce:n}),a=
|
|
152
|
+
`))}function Or(e,t){if(!Gu())try{let o=U()&&!t.json;wf(o);let i=Qu(),r={command:e,cli_version:re,os:vf(),node_version:process.version,interactive:o,install_method:jl()};t.flags?.length&&(r.flags=t.flags),t.globalFlags?.length&&(r.global_flags=t.globalFlags);let n=crypto.randomUUID(),s=JSON.stringify({api_key:Hu,distinct_id:i,event:"cli.used",properties:r,_nonce:n}),a=Er(),l=(0,Ne.join)(a,`resend-telemetry-${crypto.randomUUID()}.json`),d=(0,M.openSync)(l,M.constants.O_CREAT|M.constants.O_EXCL|M.constants.O_WRONLY|(M.constants.O_NOFOLLOW??0),384);try{(0,M.writeFileSync)(d,s)}finally{(0,M.closeSync)(d)}let c="pkg"in process,u=c?["telemetry","flush",l]:process.execArgv.concat([process.argv[1],"telemetry","flush",l]);(0,$u.spawn)(process.execPath,u,{detached:!0,stdio:"ignore",env:{...process.env,RESEND_TELEMETRY_DISABLED:"1",...c?{PKG_EXECPATH:""}:{}}}).unref()}catch{}}async function Nu(e){let t=JSON.parse(e);if(!xf(t))throw new Error("invalid telemetry payload schema");let{_nonce:o,...i}=t,r=JSON.stringify(i),n=await fetch(Sf,{method:"POST",headers:{"Content-Type":"application/json"},body:r,signal:AbortSignal.timeout(3e3)});if(!n.ok)throw new Error(`telemetry flush failed: ${n.status}`)}async function Rf(e){let t=(0,Ne.join)(e),o=Er(),i=(0,Ne.basename)(t);if((0,Ne.dirname)(t)!==o||!kf.test(i)||(0,M.realpathSync)((0,Ne.dirname)(t))!==(0,M.realpathSync)(o))throw new Error("invalid telemetry flush path");let r=(0,M.openSync)(t,M.constants.O_RDONLY|M.constants.O_NOFOLLOW),n;try{let s=(0,M.fstatSync)(r);if(!s.isFile()||s.nlink!==1)throw new Error("invalid telemetry flush path");n=(0,M.readFileSync)(r,"utf-8")}finally{(0,M.closeSync)(r)}try{await Nu(n)}finally{(0,M.unlinkSync)(t)}}var $u,M,Ne,Hu,Sf,Kf,Pu,xf,Ff,kf,Tr=ge(()=>{"use strict";$u=require("node:child_process"),M=require("node:fs"),Ne=require("node:path");he();J();fo();bt();Hu="phc_AgEBpcQTRsBl3UgQX2U8XvimTlgdXG6YEhfvJl2cUfc",Sf="https://us.i.posthog.com/capture/",Kf={darwin:"macOS",win32:"Windows",linux:"Linux"};Pu=new Set(["api_key","distinct_id","event","properties","_nonce"]),xf=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e,o=Object.keys(t);return o.length!==Pu.size||o.some(i=>!Pu.has(i))?!1:typeof t.api_key=="string"&&typeof t.distinct_id=="string"&&t.event==="cli.used"&&typeof t.properties=="object"&&t.properties!==null&&!Array.isArray(t.properties)&&typeof t._nonce=="string"&&t._nonce.length>0};Ff="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",kf=new RegExp(`^resend-telemetry-${Ff}\\.json$`)});var Yr=ue(zr(),1),{program:Pf,createCommand:$f,createArgument:Hf,createOption:Gf,CommanderError:Qf,InvalidArgumentError:Nf,InvalidOptionArgumentError:qf,Command:p,Argument:Xr,Option:V,Help:Mf}=Yr.default;var Mt=ue(qe(),1);var bd=`Global options:
|
|
153
153
|
--api-key <key> API key (or set RESEND_API_KEY env var)
|
|
154
154
|
-p, --profile <name> Profile to use (overrides RESEND_PROFILE)
|
|
155
155
|
--json Force JSON output (also auto-enabled when stdout is piped)
|
|
@@ -164,10 +164,10 @@ ${e.examples.map(o=>` $ ${o}`).join(`
|
|
|
164
164
|
`)}`),`
|
|
165
165
|
${t.join(`
|
|
166
166
|
|
|
167
|
-
`)}`}var So=require("node:util"),Jt=require("node:process");var An=ue(require("node:readline"),1);var tn=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let o=0;for(e.lastIndex=0;e.test(t);)o+=1;return t.length-o}})(),on=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,rn=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;var Ud=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Sd=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,nn=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Kd=/\t{1,1000}/y,sn=/[\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?))*/yu,vd=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,wd=/\p{M}+/gu,xd={limit:1/0,ellipsis:""},an=(e,t={},o={})=>{let i=t.limit??1/0,r=t.ellipsis??"",n=t?.ellipsisWidth??(r?an(r,xd,o).width:0),s=0,a=o.controlWidth??0,l=o.tabWidth??8,d=o.emojiWidth??2,c=2,u=o.regularWidth??1,f=o.wideWidth??c,
|
|
168
|
-
`),c=!1;for(let u=0;u<d.length;u++){let f=d[u];if(i+=f,c)c=!1;else if(c=f>="\uD800"&&f<="\uDBFF",c)continue;if(f===yo||f===mn){cn.lastIndex=u+1;let h=cn.exec(d)?.groups;if(h?.code!==void 0){let
|
|
169
|
-
`){n&&(i+=pn(""));let
|
|
170
|
-
`&&(r&&un(r)&&(i+=dn(r)),n&&(i+=pn(n)))}return i},
|
|
167
|
+
`)}`}var So=require("node:util"),Jt=require("node:process");var An=ue(require("node:readline"),1);var tn=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let o=0;for(e.lastIndex=0;e.test(t);)o+=1;return t.length-o}})(),on=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,rn=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;var Ud=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Sd=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,nn=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Kd=/\t{1,1000}/y,sn=/[\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?))*/yu,vd=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,wd=/\p{M}+/gu,xd={limit:1/0,ellipsis:""},an=(e,t={},o={})=>{let i=t.limit??1/0,r=t.ellipsis??"",n=t?.ellipsisWidth??(r?an(r,xd,o).width:0),s=0,a=o.controlWidth??0,l=o.tabWidth??8,d=o.emojiWidth??2,c=2,u=o.regularWidth??1,f=o.wideWidth??c,A=[[vd,u],[Ud,s],[Sd,a],[Kd,l],[sn,d],[nn,f]],h=0,b=0,S=e.length,v=0,K=!1,w=S,N=Math.max(0,i-n),k=0,T=0,D=0,F=0;e:for(;;){if(T>k||b>=S&&b>h){let j=e.slice(k,T)||e.slice(h,b);v=0;for(let Ce of j.replaceAll(wd,"")){let ie=Ce.codePointAt(0)||0;if(on(ie)?F=c:rn(ie)?F=f:F=u,D+F>N&&(w=Math.min(w,Math.max(k,h)+v)),D+F>i){K=!0;break e}v+=Ce.length,D+=F}k=T=0}if(b>=S)break e;for(let j=0,Ce=A.length;j<Ce;j++){let[ie,ht]=A[j];if(ie.lastIndex=b,ie.test(e)){if(v=ie===nn?tn(e.slice(b,ie.lastIndex)):ie===sn?1:ie.lastIndex-b,F=v*ht,D+F>N&&(w=Math.min(w,b+Math.floor((N-D)/ht))),D+F>i){K=!0;break e}D+=F,k=h,T=b,b=h=ie.lastIndex;continue e}}b+=1}return{width:K?N:D,index:K?w:S,truncated:K,ellipsed:K&&i>=n}},ln=an;var Fd={limit:1/0,ellipsis:"",ellipsisWidth:0},kd=(e,t={})=>ln(e,Fd,t).width,Me=kd;var yo="\x1B",mn="\x9B",Rd=39,ji="\x07",fn="[",_d="]",gn="m",Ii=`${_d}8;;`,cn=new RegExp(`(?:\\${fn}(?<code>\\d+)m|\\${Ii}(?<uri>.*)${ji})`,"y"),un=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},dn=e=>`${yo}${fn}${e}${gn}`,pn=e=>`${yo}${Ii}${e}${ji}`,Ti=(e,t,o)=>{let i=t[Symbol.iterator](),r=!1,n=!1,s=e.at(-1),a=s===void 0?0:Me(s),l=i.next(),d=i.next(),c=0;for(;!l.done;){let u=l.value,f=Me(u);a+f<=o?e[e.length-1]+=u:(e.push(u),a=0),(u===yo||u===mn)&&(r=!0,n=t.startsWith(Ii,c+1)),r?n?u===ji&&(r=!1,n=!1):u===gn&&(r=!1):(a+=f,a===o&&!d.done&&(e.push(""),a=0)),l=d,d=i.next(),c+=u.length}s=e.at(-1),!a&&s!==void 0&&s.length&&e.length>1&&(e[e.length-2]+=e.pop())},Dd=e=>{let t=e.split(" "),o=t.length;for(;o&&!Me(t[o-1]);)o--;return o===t.length?e:t.slice(0,o).join(" ")+t.slice(o).join("")},Bd=(e,t,o={})=>{if(o.trim!==!1&&e.trim()==="")return"";let i="",r,n,s=e.split(" "),a=[""],l=0;for(let u=0;u<s.length;u++){let f=s[u];if(o.trim!==!1){let h=a.at(-1)??"",b=h.trimStart();h.length!==b.length&&(a[a.length-1]=b,l=Me(b))}u!==0&&(l>=t&&(o.wordWrap===!1||o.trim===!1)&&(a.push(""),l=0),(l||o.trim===!1)&&(a[a.length-1]+=" ",l++));let A=Me(f);if(o.hard&&A>t){let h=t-l,b=1+Math.floor((A-h-1)/t);Math.floor((A-1)/t)<b&&a.push(""),Ti(a,f,t),l=Me(a.at(-1)??"");continue}if(l+A>t&&l&&A){if(o.wordWrap===!1&&l<t){Ti(a,f,t),l=Me(a.at(-1)??"");continue}a.push(""),l=0}if(l+A>t&&o.wordWrap===!1){Ti(a,f,t),l=Me(a.at(-1)??"");continue}a[a.length-1]+=f,l+=A}o.trim!==!1&&(a=a.map(u=>Dd(u)));let d=a.join(`
|
|
168
|
+
`),c=!1;for(let u=0;u<d.length;u++){let f=d[u];if(i+=f,c)c=!1;else if(c=f>="\uD800"&&f<="\uDBFF",c)continue;if(f===yo||f===mn){cn.lastIndex=u+1;let h=cn.exec(d)?.groups;if(h?.code!==void 0){let b=Number.parseFloat(h.code);r=b===Rd?void 0:b}else h?.uri!==void 0&&(n=h.uri.length===0?void 0:h.uri)}if(d[u+1]===`
|
|
169
|
+
`){n&&(i+=pn(""));let A=r?un(r):void 0;r&&A&&(i+=dn(A))}else f===`
|
|
170
|
+
`&&(r&&un(r)&&(i+=dn(r)),n&&(i+=pn(n)))}return i},Ed=/\r?\n/;function vt(e,t,o){return String(e).normalize().split(Ed).map(i=>Bd(i,t,o)).join(`
|
|
171
171
|
`)}var De=ue($i(),1);function At(e,t,o){if(!o.some(s=>!s.disabled))return e;let i=e+t,r=Math.max(o.length-1,0),n=i<0?r:i>r?0:i;return o[n].disabled?At(n,t<0?-1:1,o):n}var jd=["up","down","left","right","space","enter","cancel"],Id=["January","February","March","April","May","June","July","August","September","October","November","December"],ye={actions:new Set(jd),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...Id],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(e,t)=>`There are only ${e} days in ${t}`,afterMin:e=>`Date must be on or after ${e.toISOString().slice(0,10)}`,beforeMax:e=>`Date must be on or before ${e.toISOString().slice(0,10)}`}}};function bn(e,t){if(typeof e=="string")return ye.aliases.get(e)===t;for(let o of e)if(o!==void 0&&bn(o,t))return!0;return!1}function Pd(e,t){if(e===t)return;let o=e.split(`
|
|
172
172
|
`),i=t.split(`
|
|
173
173
|
`),r=Math.max(o.length,i.length),n=[];for(let s=0;s<r;s++)o[s]!==i[s]&&n.push(s);return{lines:n,numLinesBefore:o.length,numLinesAfter:i.length,numLines:r}}var rg=globalThis.process.platform.startsWith("win"),Hi=Symbol("clack:cancel");function x(e){return e===Hi}function Uo(e,t){let o=e;o.isTTY&&o.setRawMode(t)}var Gi=e=>"columns"in e&&typeof e.columns=="number"?e.columns:80,Qi=e=>"rows"in e&&typeof e.rows=="number"?e.rows:20;function it(e,t,o,i=o,r=o,n){let s=Gi(e??Jt.stdout);return vt(t,s-o.length,{hard:!0,trim:!1}).split(`
|
|
@@ -177,8 +177,8 @@ ${t.join(`
|
|
|
177
177
|
`).length-1;this.output.write(De.cursor.move(-999,e*-1))}render(){let e=vt(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(De.cursor.hide);else{let t=Pd(this._prevFrame,e),o=Qi(this.output);if(this.restoreCursor(),t){let i=Math.max(0,t.numLinesAfter-o),r=Math.max(0,t.numLinesBefore-o),n=t.lines.find(s=>s>=i);if(n===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(De.cursor.move(0,n-r)),this.output.write(De.erase.lines(1));let s=e.split(`
|
|
178
178
|
`);this.output.write(s[n]),this._prevFrame=e,this.output.write(De.cursor.move(0,s.length-n-1));return}else if(t.lines.length>1){if(i<r)n=i;else{let a=n-r;a>0&&this.output.write(De.cursor.move(0,a))}this.output.write(De.erase.down());let s=e.split(`
|
|
179
179
|
`).slice(n);this.output.write(s.join(`
|
|
180
|
-
`)),this._prevFrame=e;return}}this.output.write(De.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}};var Ko=class extends Vt{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",o=>{this.output.write(De.cursor.move(0,-1)),this.value=o,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};var Cn=class extends Vt{options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(e=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,t=this.value!==void 0&&this.value.length===e.length;this.value=t?[]:e.map(o=>o.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter(o=>!e.includes(o.value));this.value=t.map(o=>o.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter(t=>t!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let t=Math.max(this.options.findIndex(({value:o})=>o===e.cursorAt),0);this.cursor=this.options[t].disabled?At(t,1,this.options):t,this.on("key",o=>{o==="a"&&this.toggleAll(),o==="i"&&this.toggleInvert()}),this.on("cursor",o=>{switch(o){case"left":case"up":this.cursor=At(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=At(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},vo=class extends Vt{_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let t=this.userInput;if(this.cursor>=t.length)return`${this.masked}${(0,So.styleText)(["inverse","hidden"],"_")}`;let o=this.masked,i=o.slice(0,this.cursor),r=o.slice(this.cursor);return`${i}${(0,So.styleText)("inverse",r[0])}${r.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:t,...o}){super(o),this._mask=t??"\u2022",this.on("userInput",i=>{this._setValue(i)})}},wo=class extends Vt{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t){super(t,!1),this.options=t.options;let o=this.options.findIndex(({value:r})=>r===t.initialValue),i=o===-1?0:o;this.cursor=this.options[i].disabled?At(i,1,this.options):i,this.changeValue(),this.on("cursor",r=>{switch(r){case"left":case"up":this.cursor=At(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=At(this.cursor,1,this.options);break}this.changeValue()})}};var xo=class extends Vt{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${this.userInput}\u2588`;let o=t.slice(0,this.cursor),[i,...r]=t.slice(this.cursor);return`${o}${(0,So.styleText)("inverse",i)}${r.join("")}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",o=>{this._setValue(o)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}};var C=require("node:util"),je=ue(require("node:process"),1);var Kn=ue($i(),1);function $d(){return je.default.platform!=="win32"?je.default.env.TERM!=="linux":!!je.default.env.CI||!!je.default.env.WT_SESSION||!!je.default.env.TERMINUS_SUBLIME||je.default.env.ConEmuTask==="{cmd::Cmder}"||je.default.env.TERM_PROGRAM==="Terminus-Sublime"||je.default.env.TERM_PROGRAM==="vscode"||je.default.env.TERM==="xterm-256color"||je.default.env.TERM==="alacritty"||je.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Hd=$d();var z=(e,t)=>Hd?e:t,Gd=z("\u25C6","*"),Qd=z("\u25A0","x"),Nd=z("\u25B2","x"),vn=z("\u25C7","o"),qd=z("\u250C","T"),G=z("\u2502","|"),Le=z("\u2514","\u2014"),bg=z("\u2510","T"),Cg=z("\u2518","\u2014"),Ni=z("\u25CF",">"),ko=z("\u25CB"," "),Md=z("\u25FB","[\u2022]"),yn=z("\u25FC","[+]"),Un=z("\u25FB","[ ]"),Ld=z("\u25AA","\u2022"),yg=z("\u2500","-"),Ug=z("\u256E","+"),Sg=z("\u251C","+"),Kg=z("\u256F","+"),vg=z("\u2570","+"),wg=z("\u256D","+"),Wd=z("\u25CF","\u2022"),Jd=z("\u25C6","*"),Vd=z("\u25B2","!"),zd=z("\u25A0","x"),Yt=e=>{switch(e){case"initial":case"active":return(0,C.styleText)("cyan",Gd);case"cancel":return(0,C.styleText)("red",Qd);case"error":return(0,C.styleText)("yellow",Nd);case"submit":return(0,C.styleText)("green",vn)}},wn=e=>{switch(e){case"initial":case"active":return(0,C.styleText)("cyan",G);case"cancel":return(0,C.styleText)("red",G);case"error":return(0,C.styleText)("yellow",G);case"submit":return(0,C.styleText)("green",G)}},Sn=(e,t,o,i,r,n=!1)=>{let s=t,a=0;if(n)for(let l=i-1;l>=o&&(s-=e[l].length,a++,!(s<=r));l--);else for(let l=o;l<i&&(s-=e[l].length,a++,!(s<=r));l++);return{lineCount:s,removals:a}},qi=({cursor:e,options:t,style:o,output:i=process.stdout,maxItems:r=Number.POSITIVE_INFINITY,columnPadding:n=0,rowPadding:s=4})=>{let a=Gi(i)-n,l=Qi(i),d=(0,C.styleText)("dim","..."),c=Math.max(l-s,0),u=Math.max(Math.min(r,c),5),f=0;e>=u-3&&(f=Math.max(Math.min(e-u+3,t.length-u),0));let
|
|
181
|
-
`);S.push(T),v+=T.length}if(v>c){let k=0,T=0,D=v,F=e-K,j=c,Ce=()=>Sn(S,D,0,F,j),ie=()=>Sn(S,D,F+1,S.length,j,!0);
|
|
180
|
+
`)),this._prevFrame=e;return}}this.output.write(De.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}};var Ko=class extends Vt{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",o=>{this.output.write(De.cursor.move(0,-1)),this.value=o,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};var Cn=class extends Vt{options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(e=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,t=this.value!==void 0&&this.value.length===e.length;this.value=t?[]:e.map(o=>o.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter(o=>!e.includes(o.value));this.value=t.map(o=>o.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter(t=>t!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let t=Math.max(this.options.findIndex(({value:o})=>o===e.cursorAt),0);this.cursor=this.options[t].disabled?At(t,1,this.options):t,this.on("key",o=>{o==="a"&&this.toggleAll(),o==="i"&&this.toggleInvert()}),this.on("cursor",o=>{switch(o){case"left":case"up":this.cursor=At(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=At(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},vo=class extends Vt{_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let t=this.userInput;if(this.cursor>=t.length)return`${this.masked}${(0,So.styleText)(["inverse","hidden"],"_")}`;let o=this.masked,i=o.slice(0,this.cursor),r=o.slice(this.cursor);return`${i}${(0,So.styleText)("inverse",r[0])}${r.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:t,...o}){super(o),this._mask=t??"\u2022",this.on("userInput",i=>{this._setValue(i)})}},wo=class extends Vt{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t){super(t,!1),this.options=t.options;let o=this.options.findIndex(({value:r})=>r===t.initialValue),i=o===-1?0:o;this.cursor=this.options[i].disabled?At(i,1,this.options):i,this.changeValue(),this.on("cursor",r=>{switch(r){case"left":case"up":this.cursor=At(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=At(this.cursor,1,this.options);break}this.changeValue()})}};var xo=class extends Vt{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${this.userInput}\u2588`;let o=t.slice(0,this.cursor),[i,...r]=t.slice(this.cursor);return`${o}${(0,So.styleText)("inverse",i)}${r.join("")}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",o=>{this._setValue(o)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}};var C=require("node:util"),je=ue(require("node:process"),1);var Kn=ue($i(),1);function $d(){return je.default.platform!=="win32"?je.default.env.TERM!=="linux":!!je.default.env.CI||!!je.default.env.WT_SESSION||!!je.default.env.TERMINUS_SUBLIME||je.default.env.ConEmuTask==="{cmd::Cmder}"||je.default.env.TERM_PROGRAM==="Terminus-Sublime"||je.default.env.TERM_PROGRAM==="vscode"||je.default.env.TERM==="xterm-256color"||je.default.env.TERM==="alacritty"||je.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Hd=$d();var z=(e,t)=>Hd?e:t,Gd=z("\u25C6","*"),Qd=z("\u25A0","x"),Nd=z("\u25B2","x"),vn=z("\u25C7","o"),qd=z("\u250C","T"),G=z("\u2502","|"),Le=z("\u2514","\u2014"),bg=z("\u2510","T"),Cg=z("\u2518","\u2014"),Ni=z("\u25CF",">"),ko=z("\u25CB"," "),Md=z("\u25FB","[\u2022]"),yn=z("\u25FC","[+]"),Un=z("\u25FB","[ ]"),Ld=z("\u25AA","\u2022"),yg=z("\u2500","-"),Ug=z("\u256E","+"),Sg=z("\u251C","+"),Kg=z("\u256F","+"),vg=z("\u2570","+"),wg=z("\u256D","+"),Wd=z("\u25CF","\u2022"),Jd=z("\u25C6","*"),Vd=z("\u25B2","!"),zd=z("\u25A0","x"),Yt=e=>{switch(e){case"initial":case"active":return(0,C.styleText)("cyan",Gd);case"cancel":return(0,C.styleText)("red",Qd);case"error":return(0,C.styleText)("yellow",Nd);case"submit":return(0,C.styleText)("green",vn)}},wn=e=>{switch(e){case"initial":case"active":return(0,C.styleText)("cyan",G);case"cancel":return(0,C.styleText)("red",G);case"error":return(0,C.styleText)("yellow",G);case"submit":return(0,C.styleText)("green",G)}},Sn=(e,t,o,i,r,n=!1)=>{let s=t,a=0;if(n)for(let l=i-1;l>=o&&(s-=e[l].length,a++,!(s<=r));l--);else for(let l=o;l<i&&(s-=e[l].length,a++,!(s<=r));l++);return{lineCount:s,removals:a}},qi=({cursor:e,options:t,style:o,output:i=process.stdout,maxItems:r=Number.POSITIVE_INFINITY,columnPadding:n=0,rowPadding:s=4})=>{let a=Gi(i)-n,l=Qi(i),d=(0,C.styleText)("dim","..."),c=Math.max(l-s,0),u=Math.max(Math.min(r,c),5),f=0;e>=u-3&&(f=Math.max(Math.min(e-u+3,t.length-u),0));let A=u<t.length&&f>0,h=u<t.length&&f+u<t.length,b=Math.min(f+u,t.length),S=[],v=0;A&&v++,h&&v++;let K=f+(A?1:0),w=b-(h?1:0);for(let k=K;k<w;k++){let T=vt(o(t[k],k===e),a,{hard:!0,trim:!1}).split(`
|
|
181
|
+
`);S.push(T),v+=T.length}if(v>c){let k=0,T=0,D=v,F=e-K,j=c,Ce=()=>Sn(S,D,0,F,j),ie=()=>Sn(S,D,F+1,S.length,j,!0);A?({lineCount:D,removals:k}=Ce(),D>j&&(h||(j-=1),{lineCount:D,removals:T}=ie())):(h||(j-=1),{lineCount:D,removals:T}=ie(),D>j&&(j-=1,{lineCount:D,removals:k}=Ce())),k>0&&(A=!0,S.splice(0,k)),T>0&&(h=!0,S.splice(S.length-T,T))}let N=[];A&&N.push(d);for(let k of S)for(let T of k)N.push(T);return h&&N.push(d),N};var rt=e=>{let t=e.active??"Yes",o=e.inactive??"No";return new Ko({active:t,inactive:o,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let i=e.withGuide??ye.withGuide,r=`${Yt(this.state)} `,n=i?`${(0,C.styleText)("gray",G)} `:"",s=it(e.output,e.message,n,r),a=`${i?`${(0,C.styleText)("gray",G)}
|
|
182
182
|
`:""}${s}
|
|
183
183
|
`,l=this.value?t:o;switch(this.state){case"submit":{let d=i?`${(0,C.styleText)("gray",G)} `:"";return`${a}${d}${(0,C.styleText)("dim",l)}`}case"cancel":{let d=i?`${(0,C.styleText)("gray",G)} `:"";return`${a}${d}${(0,C.styleText)(["strikethrough","dim"],l)}${i?`
|
|
184
184
|
${(0,C.styleText)("gray",G)}`:""}`}default:{let d=i?`${(0,C.styleText)("cyan",G)} `:"",c=i?(0,C.styleText)("cyan",Le):"";return`${a}${d}${this.value?`${(0,C.styleText)("green",Ni)} ${t}`:`${(0,C.styleText)("dim",ko)} ${(0,C.styleText)("dim",t)}`}${e.vertical?i?`
|
|
@@ -186,7 +186,7 @@ ${(0,C.styleText)("cyan",G)} `:`
|
|
|
186
186
|
`:` ${(0,C.styleText)("dim","/")} `}${this.value?`${(0,C.styleText)("dim",ko)} ${(0,C.styleText)("dim",o)}`:`${(0,C.styleText)("green",Ni)} ${o}`}
|
|
187
187
|
${c}
|
|
188
188
|
`}}}}).prompt()};var xn=async(e,t)=>{let o={},i=Object.keys(e);for(let r of i){let n=e[r],s=await n({results:o})?.catch(a=>{throw a});if(typeof t?.onCancel=="function"&&x(s)){o[r]="canceled",t.onCancel({results:o});continue}o[r]=s}return o};var X={message:(e=[],{symbol:t=(0,C.styleText)("gray",G),secondarySymbol:o=(0,C.styleText)("gray",G),output:i=process.stdout,spacing:r=1,withGuide:n}={})=>{let s=[],a=n??ye.withGuide,l=a?o:"",d=a?`${t} `:"",c=a?`${o} `:"";for(let f=0;f<r;f++)s.push(l);let u=Array.isArray(e)?e:e.split(`
|
|
189
|
-
`);if(u.length>0){let[f,...
|
|
189
|
+
`);if(u.length>0){let[f,...A]=u;f.length>0?s.push(`${d}${f}`):s.push(a?t:"");for(let h of A)h.length>0?s.push(`${c}${h}`):s.push(a?o:"")}i.write(`${s.join(`
|
|
190
190
|
`)}
|
|
191
191
|
`)},info:(e,t)=>{X.message(e,{...t,symbol:(0,C.styleText)("blue",Wd)})},success:(e,t)=>{X.message(e,{...t,symbol:(0,C.styleText)("green",Jd)})},step:(e,t)=>{X.message(e,{...t,symbol:(0,C.styleText)("green",vn)})},warn:(e,t)=>{X.message(e,{...t,symbol:(0,C.styleText)("yellow",Vd)})},warning:(e,t)=>{X.warn(e,t)},error:(e,t)=>{X.message(e,{...t,symbol:(0,C.styleText)("red",zd)})}},Fn=(e="",t)=>{let o=t?.output??process.stdout,i=t?.withGuide??ye.withGuide?`${(0,C.styleText)("gray",Le)} `:"";o.write(`${i}${(0,C.styleText)("red",e)}
|
|
192
192
|
|
|
@@ -201,7 +201,7 @@ ${(0,C.styleText)("reset",(0,C.styleText)("dim",`Press ${(0,C.styleText)(["gray"
|
|
|
201
201
|
`:""}${r}
|
|
202
202
|
`,s=this.value??[],a=(l,d)=>{if(l.disabled)return t(l,"disabled");let c=s.includes(l.value);return d&&c?t(l,"active-selected"):c?t(l,"selected"):t(l,d?"active":"inactive")};switch(this.state){case"submit":{let l=this.options.filter(({value:c})=>s.includes(c)).map(c=>t(c,"submitted")).join((0,C.styleText)("dim",", "))||(0,C.styleText)("dim","none"),d=it(e.output,l,i?`${(0,C.styleText)("gray",G)} `:"");return`${n}${d}`}case"cancel":{let l=this.options.filter(({value:c})=>s.includes(c)).map(c=>t(c,"cancelled")).join((0,C.styleText)("dim",", "));if(l.trim()==="")return`${n}${(0,C.styleText)("gray",G)}`;let d=it(e.output,l,i?`${(0,C.styleText)("gray",G)} `:"");return`${n}${d}${i?`
|
|
203
203
|
${(0,C.styleText)("gray",G)}`:""}`}case"error":{let l=i?`${(0,C.styleText)("yellow",G)} `:"",d=this.error.split(`
|
|
204
|
-
`).map((f,
|
|
204
|
+
`).map((f,A)=>A===0?`${i?`${(0,C.styleText)("yellow",Le)} `:""}${(0,C.styleText)("yellow",f)}`:` ${f}`).join(`
|
|
205
205
|
`),c=n.split(`
|
|
206
206
|
`).length,u=d.split(`
|
|
207
207
|
`).length+1;return`${n}${l}${qi({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:l.length,rowPadding:c+u,style:a}).join(`
|
|
@@ -237,7 +237,7 @@ ${l}${s}
|
|
|
237
237
|
`}case"submit":{let s=n?` ${(0,C.styleText)("dim",n)}`:"",a=t?(0,C.styleText)("gray",G):"";return`${o}${a}${s}`}case"cancel":{let s=n?` ${(0,C.styleText)(["strikethrough","dim"],n)}`:"",a=t?(0,C.styleText)("gray",G):"";return`${o}${a}${s}${n.trim()?`
|
|
238
238
|
${a}`:""}`}default:{let s=t?`${(0,C.styleText)("cyan",G)} `:"",a=t?(0,C.styleText)("cyan",Le):"";return`${o}${s}${r}
|
|
239
239
|
${a}
|
|
240
|
-
`}}}}).prompt();var co=ue(qe(),1);bt();process.env.RESEND_USER_AGENT=`resend-cli:${re}`;var nt=new TextEncoder,
|
|
240
|
+
`}}}}).prompt();var co=ue(qe(),1);bt();process.env.RESEND_USER_AGENT=`resend-cli:${re}`;var nt=new TextEncoder,En="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Xt=new Uint8Array(256);for(let e=0;e<En.length;e++)Xt[En.charCodeAt(e)]=e;function _o(e){let t=Math.ceil(e.length/4)*3,o=e.length,i=0;e.length%4===3?t--:e.length%4===2?t-=2:e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);let r=new ArrayBuffer(t),n=new Uint8Array(r);for(let s=0;s<o;s+=4){let a=Xt[e.charCodeAt(s)],l=Xt[e.charCodeAt(s+1)],d=Xt[e.charCodeAt(s+2)],c=Xt[e.charCodeAt(s+3)];n[i++]=a<<2|l>>4,n[i++]=(l&15)<<4|d>>2,n[i++]=(d&3)<<6|c&63}return r}var Xd=new Map([["iso-8859-8-i","iso-8859-8"],["iso-8859-8-e","iso-8859-8"]]);function wt(e){e=(e||"utf8").trim().toLowerCase(),e=Xd.get(e)||e;let t;try{t=new TextDecoder(e)}catch{t=new TextDecoder("windows-1252")}return t}async function st(e){if("arrayBuffer"in e)return await e.arrayBuffer();let t=new FileReader;return new Promise((o,i)=>{t.onload=function(r){o(r.target.result)},t.onerror=function(r){i(t.error)},t.readAsArrayBuffer(e)})}function On(e){return e>=48&&e<=57||e>=97&&e<=102||e>=65&&e<=70?String.fromCharCode(e):!1}function Zd(e,t,o){let i=e.indexOf("*");i>=0&&(e=e.substr(0,i)),t=t.toUpperCase();let r;if(t==="Q"){o=o.replace(/=\s+([0-9a-fA-F])/g,"=$1").replace(/[_\s]/g," ");let n=nt.encode(o),s=[];for(let l=0,d=n.length;l<d;l++){let c=n[l];if(l<=d-2&&c===61){let u=On(n[l+1]),f=On(n[l+2]);if(u&&f){let A=parseInt(u+f,16);s.push(A),l+=2;continue}}s.push(c)}r=new ArrayBuffer(s.length);let a=new DataView(r);for(let l=0,d=s.length;l<d;l++)a.setUint8(l,s[l])}else t==="B"?r=_o(o.replace(/[^a-zA-Z0-9\+\/=]+/g,"")):r=nt.encode(o);return wt(e).decode(r)}function Ct(e){let t=!0,o=!1;for(;!o;){let i=(e||"").toString().replace(/(=\?([^?]+)\?[Bb]\?([^?]*)\?=)\s*(?==\?([^?]+)\?[Bb]\?[^?]*\?=)/g,(r,n,s,a,l)=>t&&s===l&&a.length%4===0&&!/=$/.test(a)?n+"__\0JOIN\0__":r).replace(/(=\?([^?]+)\?[Qq]\?[^?]*\?=)\s*(?==\?([^?]+)\?[Qq]\?[^?]*\?=)/g,(r,n,s,a)=>t&&s===a?n+"__\0JOIN\0__":r).replace(/(\?=)?__\x00JOIN\x00__(=\?([^?]+)\?[QqBb]\?)?/g,"").replace(/(=\?[^?]+\?[QqBb]\?[^?]*\?=)\s+(?==\?[^?]+\?[QqBb]\?[^?]*\?=)/g,"$1").replace(/=\?([\w_\-*]+)\?([QqBb])\?([^?]*)\?=/g,(r,n,s,a)=>Zd(n,s,a));if(t&&i.indexOf("\uFFFD")>=0)t=!1;else return i}}function ep(e,t){t=t||"utf-8";let o=[];for(let n=0;n<e.length;n++){let s=e.charAt(n);if(s==="%"&&/^[a-f0-9]{2}/i.test(e.substr(n+1,2))){let a=e.substr(n+1,2);n+=2,o.push(parseInt(a,16))}else if(s.charCodeAt(0)>126){s=nt.encode(s);for(let a=0;a<s.length;a++)o.push(s[a])}else o.push(s.charCodeAt(0))}let i=new ArrayBuffer(o.length),r=new DataView(i);for(let n=0,s=o.length;n<s;n++)r.setUint8(n,o[n]);return wt(t).decode(i)}function Tn(e){let t=new Map;Object.keys(e.params).forEach(o=>{let i=o.match(/\*((\d+)\*?)?$/);if(!i)return;let r=o.substr(0,i.index).toLowerCase(),n=Number(i[2])||0,s;t.has(r)?s=t.get(r):(s={charset:!1,values:[]},t.set(r,s));let a=e.params[o];n===0&&i[0].charAt(i[0].length-1)==="*"&&(i=a.match(/^([^']*)'[^']*'(.*)$/))&&(s.charset=i[1]||"utf-8",a=i[2]),s.values.push({nr:n,value:a}),delete e.params[o]}),t.forEach((o,i)=>{e.params[i]=ep(o.values.sort((r,n)=>r.nr-n.nr).map(r=>r.value).join(""),o.charset)})}var Zt=class{constructor(){this.chunks=[]}update(t){this.chunks.push(t),this.chunks.push(`
|
|
241
241
|
`)}finalize(){return st(new Blob(this.chunks,{type:"application/octet-stream"}))}};var eo=class{constructor(t){t=t||{},this.decoder=t.decoder||new TextDecoder,this.maxChunkSize=100*1024,this.chunks=[],this.remainder=""}update(t){let o=this.decoder.decode(t);if(o=o.replace(/[^a-zA-Z0-9+\/]+/g,""),this.remainder+=o,this.remainder.length>=this.maxChunkSize){let i=Math.floor(this.remainder.length/4)*4,r;i===this.remainder.length?(r=this.remainder,this.remainder=""):(r=this.remainder.substr(0,i),this.remainder=this.remainder.substr(i)),r.length&&this.chunks.push(_o(r))}}finalize(){return this.remainder&&!/^=+$/.test(this.remainder)&&this.chunks.push(_o(this.remainder)),st(new Blob(this.chunks,{type:"application/octet-stream"}))}};var jn=/^=[a-f0-9]{2}$/i,tp=/(?==[a-f0-9]{2})/i,op=/=\r?\n/g,ip=/=[a-fA-F0-9]?$/,to=class{constructor(t){t=t||{},this.decoder=t.decoder||new TextDecoder,this.maxChunkSize=100*1024,this.remainder="",this.chunks=[]}decodeQPBytes(t){let o=new ArrayBuffer(t.length),i=new DataView(o);for(let r=0,n=t.length;r<n;r++)i.setUint8(r,parseInt(t[r],16));return o}decodeChunks(t){t=t.replace(op,"");let o=t.split(tp),i=[];for(let r of o){if(r.charAt(0)!=="="){i.length&&(this.chunks.push(this.decodeQPBytes(i)),i=[]),this.chunks.push(r);continue}if(r.length===3){jn.test(r)?i.push(r.substr(1)):(i.length&&(this.chunks.push(this.decodeQPBytes(i)),i=[]),this.chunks.push(r));continue}if(r.length>3){let n=r.substr(0,3);jn.test(n)?(i.push(r.substr(1,2)),this.chunks.push(this.decodeQPBytes(i)),i=[],r=r.substr(3),this.chunks.push(r)):(i.length&&(this.chunks.push(this.decodeQPBytes(i)),i=[]),this.chunks.push(r))}}i.length&&this.chunks.push(this.decodeQPBytes(i))}update(t){let o=this.decoder.decode(t)+`
|
|
242
242
|
`;if(o=this.remainder+o,o.length<this.maxChunkSize){this.remainder=o;return}this.remainder="";let i=o.match(ip);if(i){if(i.index===0){this.remainder=o;return}this.remainder=o.substr(i.index),o=o.substr(0,i.index)}this.decodeChunks(o)}finalize(){return this.remainder.length&&(this.decodeChunks(this.remainder),this.remainder=""),st(new Blob(this.chunks,{type:"application/octet-stream"}))}};var rp=wt(),xt=class{constructor(t){if(this.options=t||{},this.postalMime=this.options.postalMime,this.root=!!this.options.parentNode,this.childNodes=[],this.options.parentNode){if(this.parentNode=this.options.parentNode,this.depth=this.parentNode.depth+1,this.depth>this.options.maxNestingDepth)throw new Error(`Maximum MIME nesting depth of ${this.options.maxNestingDepth} levels exceeded`);this.options.parentNode.childNodes.push(this)}else this.depth=0;this.state="header",this.headerLines=[],this.headerSize=0;let i=(this.options.parentMultipartType||null)==="digest"?"message/rfc822":"text/plain";this.contentType={value:i,default:!0},this.contentTransferEncoding={value:"8bit"},this.contentDisposition={value:""},this.headers=[],this.contentDecoder=!1}setupContentDecoder(t){/base64/i.test(t)?this.contentDecoder=new eo:/quoted-printable/i.test(t)?this.contentDecoder=new to({decoder:wt(this.contentType.parsed.params.charset)}):this.contentDecoder=new Zt}async finalize(){if(this.state==="finished")return;this.state==="header"&&this.processHeaders();let t=this.postalMime.boundaries;for(let o=t.length-1;o>=0;o--)if(t[o].node===this){t.splice(o,1);break}await this.finalizeChildNodes(),this.content=this.contentDecoder?await this.contentDecoder.finalize():null,this.state="finished"}async finalizeChildNodes(){for(let t of this.childNodes)await t.finalize()}stripComments(t){let o="",i=0,r=!1,n=!1;for(let s=0;s<t.length;s++){let a=t.charAt(s);if(r){i===0&&(o+=a),r=!1;continue}if(a==="\\"){r=!0,i===0&&(o+=a);continue}if(a==='"'&&i===0){n=!n,o+=a;continue}if(!n){if(a==="("){i++;continue}if(a===")"&&i>0){i--;continue}}i===0&&(o+=a)}return o}parseStructuredHeader(t){t=this.stripComments(t);let o={value:!1,params:{}},i=!1,r="",n="value",s=!1,a=!1,l;for(let d=0,c=t.length;d<c;d++)switch(l=t.charAt(d),n){case"key":if(l==="="){i=r.trim().toLowerCase(),n="value",r="";break}r+=l;break;case"value":if(a)r+=l;else if(l==="\\"){a=!0;continue}else s&&l===s?s=!1:!s&&l==='"'?s=l:!s&&l===";"?(i===!1?o.value=r.trim():o.params[i]=r.trim(),n="key",r=""):r+=l;a=!1;break}return r=r.trim(),n==="value"?i===!1?o.value=r:o.params[i]=r:r&&(o.params[r.toLowerCase()]=""),o.value&&(o.value=o.value.toLowerCase()),Tn(o),o}decodeFlowedText(t,o){return t.split(/\r?\n/).reduce((i,r)=>i.endsWith(" ")&&i!=="-- "&&!i.endsWith(`
|
|
243
243
|
-- `)?o?i.slice(0,-1)+r:i+r:i+`
|
|
@@ -265,24 +265,24 @@ ${r}
|
|
|
265
265
|
`&&(t=" "),(t.charCodeAt(0)>=33||[" "," "].includes(t))&&(this.node.value+=t),this.escaped=!1}},cp=50;function Xi(e,t){t=t||{};let o=t._depth||0;if(o>cp)return[];let r=new Yi(e).tokenize(),n=[],s=[],a=[];if(r.forEach(l=>{l.type==="operator"&&(l.value===","||l.value===";")?(s.length&&n.push(s),s=[]):s.push(l)}),s.length&&n.push(s),n.forEach(l=>{l=lp(l,o),l.length&&(a=a.concat(l))}),t.flatten){let l=[],d=c=>{c.forEach(u=>{if(u.group)return d(u.group);l.push(u)})};return d(a),l}return a}var Do=Xi;function Gn(e){for(var t="",o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=new Uint8Array(e),r=i.byteLength,n=r%3,s=r-n,a,l,d,c,u,f=0;f<s;f=f+3)u=i[f]<<16|i[f+1]<<8|i[f+2],a=(u&16515072)>>18,l=(u&258048)>>12,d=(u&4032)>>6,c=u&63,t+=o[a]+o[l]+o[d]+o[c];return n==1?(u=i[s],a=(u&252)>>2,l=(u&3)<<4,t+=o[a]+o[l]+"=="):n==2&&(u=i[s]<<8|i[s+1],a=(u&64512)>>10,l=(u&1008)>>4,d=(u&15)<<2,t+=o[a]+o[l]+o[d]+"="),t}var up=256,dp=2*1024*1024;function Zi(e){return e.replace(/-(.)/g,(t,o)=>o.toUpperCase())}var oo=class e{static parse(t,o){return new e(o).parse(t)}constructor(t){this.options=t||{},this.mimeOptions={maxNestingDepth:this.options.maxNestingDepth||up,maxHeadersSize:this.options.maxHeadersSize||dp},this.root=this.currentNode=new xt({postalMime:this,...this.mimeOptions}),this.boundaries=[],this.textContent={},this.attachments=[],this.attachmentEncoding=(this.options.attachmentEncoding||"").toString().replace(/[-_\s]/g,"").trim().toLowerCase()||"arraybuffer",this.started=!1}async finalize(){await this.root.finalize()}async processLine(t,o){let i=this.boundaries;if(i.length&&t.length>2&&t[0]===45&&t[1]===45)for(let r=i.length-1;r>=0;r--){let n=i[r];if(t.length<n.value.length+2)continue;let s=!0;for(let c=0;c<n.value.length;c++)if(t[c+2]!==n.value[c]){s=!1;break}if(!s)continue;let a=n.value.length+2,l=!1;t.length>=n.value.length+4&&t[n.value.length+2]===45&&t[n.value.length+3]===45&&(l=!0,a=n.value.length+4);let d=!0;for(let c=a;c<t.length;c++)if(t[c]!==32&&t[c]!==9){d=!1;break}if(d)return l?(await n.node.finalize(),this.currentNode=n.node.parentNode||this.root):(await n.node.finalizeChildNodes(),this.currentNode=new xt({postalMime:this,parentNode:n.node,parentMultipartType:n.node.contentType.multipart,...this.mimeOptions})),o?this.finalize():void 0}if(this.currentNode.feed(t),o)return this.finalize()}readLine(){let t=this.readPos,o=this.readPos;for(;this.readPos<this.av.length;){let i=this.av[this.readPos++];if(i!==13&&i!==10&&(o=this.readPos),i===10)return{bytes:new Uint8Array(this.buf,t,o-t),done:this.readPos>=this.av.length}}return{bytes:new Uint8Array(this.buf,t,o-t),done:this.readPos>=this.av.length}}async processNodeTree(){let t={},o=new Set,i=this.textMap=new Map,r=this.forceRfc822Attachments(),n=async(s,a,l)=>{if(a=a||!1,l=l||!1,s.contentType.multipart)s.contentType.multipart==="alternative"?a=s:s.contentType.multipart==="related"&&(l=s);else if(this.isInlineMessageRfc822(s)&&!r){let d=new e;s.subMessage=await d.parse(s.content),i.has(s)||i.set(s,{});let c=i.get(s);(s.subMessage.text||!s.subMessage.html)&&(c.plain=c.plain||[],c.plain.push({type:"subMessage",value:s.subMessage}),o.add("plain")),s.subMessage.html&&(c.html=c.html||[],c.html.push({type:"subMessage",value:s.subMessage}),o.add("html")),d.textMap&&d.textMap.forEach((u,f)=>{i.set(f,u)});for(let u of s.subMessage.attachments||[])this.attachments.push(u)}else if(this.isInlineTextNode(s)){let d=s.contentType.parsed.value.substr(s.contentType.parsed.value.indexOf("/")+1),c=a||s;i.has(c)||i.set(c,{});let u=i.get(c);u[d]=u[d]||[],u[d].push({type:"text",value:s.getTextContent()}),o.add(d)}else if(s.content){let d=s.contentDisposition?.parsed?.params?.filename||s.contentType.parsed.params.name||null,c={filename:d?Ct(d):null,mimeType:s.contentType.parsed.value,disposition:s.contentDisposition?.parsed?.value||null};switch(l&&s.contentId&&(c.related=!0),s.contentDescription&&(c.description=s.contentDescription),s.contentId&&(c.contentId=s.contentId),s.contentType.parsed.value){case"text/calendar":case"application/ics":{s.contentType.parsed.params.method&&(c.method=s.contentType.parsed.params.method.toString().toUpperCase().trim());let u=s.getTextContent().replace(/\r?\n/g,`
|
|
266
266
|
`).replace(/\n*$/,`
|
|
267
267
|
`);c.content=nt.encode(u);break}default:c.content=s.content}this.attachments.push(c)}for(let d of s.childNodes)await n(d,a,l)};await n(this.root,!1,!1),i.forEach(s=>{o.forEach(a=>{if(t[a]||(t[a]=[]),s[a])s[a].forEach(l=>{switch(l.type){case"text":t[a].push(l.value);break;case"subMessage":switch(a){case"html":t[a].push(zi(l.value));break;case"plain":t[a].push(Vi(l.value));break}break}});else{let l;switch(a){case"html":l="plain";break;case"plain":l="html";break}(s[l]||[]).forEach(d=>{switch(d.type){case"text":switch(a){case"html":t[a].push(In(d.value));break;case"plain":t[a].push(Pn(d.value));break}break;case"subMessage":switch(a){case"html":t[a].push(zi(d.value));break;case"plain":t[a].push(Vi(d.value));break}break}})}})}),Object.keys(t).forEach(s=>{t[s]=t[s].join(`
|
|
268
|
-
`)}),this.textContent=t}isInlineTextNode(t){if(t.contentDisposition?.parsed?.value==="attachment")return!1;switch(t.contentType.parsed?.value){case"text/html":case"text/plain":return!0;default:return!1}}isInlineMessageRfc822(t){return t.contentType.parsed?.value!=="message/rfc822"?!1:(t.contentDisposition?.parsed?.value||(this.options.rfc822Attachments?"attachment":"inline"))==="inline"}forceRfc822Attachments(){if(this.options.forceRfc822Attachments)return!0;let t=!1,o=i=>{i.contentType.multipart||i.contentType.parsed&&["message/delivery-status","message/feedback-report"].includes(i.contentType.parsed.value)&&(t=!0);for(let r of i.childNodes)o(r)};return o(this.root),t}async resolveStream(t){let o=0,i=[],r=t.getReader();for(;;){let{done:a,value:l}=await r.read();if(a)break;i.push(l),o+=l.length}let n=new Uint8Array(o),s=0;for(let a of i)n.set(a,s),s+=a.length;return n}async parse(t){if(this.started)throw new Error("Can not reuse parser, create a new PostalMime object");for(this.started=!0,t&&typeof t.getReader=="function"&&(t=await this.resolveStream(t)),t=t||new ArrayBuffer(0),typeof t=="string"&&(t=nt.encode(t)),(t instanceof Blob||Object.prototype.toString.call(t)==="[object Blob]")&&(t=await st(t)),t.buffer instanceof ArrayBuffer&&(t=new Uint8Array(t).buffer),this.buf=t,this.av=new Uint8Array(t),this.readPos=0;this.readPos<this.av.length;){let r=this.readLine();await this.processLine(r.bytes,r.done)}await this.processNodeTree();let o={headers:this.root.headers.map(r=>({key:r.key,originalKey:r.originalKey,value:r.value})).reverse()};for(let r of["from","sender"]){let n=this.root.headers.find(s=>s.key===r);if(n&&n.value){let s=Do(n.value);s&&s.length&&(o[r]=s[0])}}for(let r of["delivered-to","return-path"]){let n=this.root.headers.find(s=>s.key===r);if(n&&n.value){let s=Do(n.value);if(s&&s.length&&s[0].address){let a=Zi(r);o[a]=s[0].address}}}for(let r of["to","cc","bcc","reply-to"]){let n=this.root.headers.filter(a=>a.key===r),s=[];if(n.filter(a=>a&&a.value).map(a=>Do(a.value)).forEach(a=>s=s.concat(a||[])),s&&s.length){let a=Zi(r);o[a]=s}}for(let r of["subject","message-id","in-reply-to","references"]){let n=this.root.headers.find(s=>s.key===r);if(n&&n.value){let s=Zi(r);o[s]=Ct(n.value)}}let i=this.root.headers.find(r=>r.key==="date");if(i){let r=new Date(i.value);r.toString()==="Invalid Date"?r=i.value:r=r.toISOString(),o.date=r}switch(this.textContent?.html&&(o.html=this.textContent.html),this.textContent?.plain&&(o.text=this.textContent.plain),o.attachments=this.attachments,o.headerLines=(this.root.rawHeaderLines||[]).slice().reverse(),this.attachmentEncoding){case"arraybuffer":break;case"base64":for(let n of o.attachments||[])n?.content&&(n.content=Gn(n.content),n.encoding="base64");break;case"utf8":let r=new TextDecoder("utf8");for(let n of o.attachments||[])n?.content&&(n.content=r.decode(n.content),n.encoding="utf8");break;default:throw new Error("Unknown attachment encoding")}return o}};var ns=ue(Yn(),1),yp="6.18.0-canary.0";function se(e){let t=new URLSearchParams;return e.limit!==void 0&&t.set("limit",e.limit.toString()),"after"in e&&e.after!==void 0&&t.set("after",e.after),"before"in e&&e.before!==void 0&&t.set("before",e.before),t.toString()}var Up=class{constructor(e){this.resend=e}async create(e,t={}){return await this.resend.post("/api-keys",e,t)}async list(e={}){let t=se(e),o=t?`/api-keys?${t}`:"/api-keys";return await this.resend.get(o)}async remove(e){return await this.resend.delete(`/api-keys/${e}`)}},Sp=class{constructor(e){this.resend=e}async get(e){return await this.resend.get(`/automations/${e.automationId}/runs/${e.runId}`)}async list(e){let t=se(e),o=new URLSearchParams(t);if(e.status){let n=Array.isArray(e.status)?e.status.join(","):e.status;o.set("status",n)}let i=o.toString(),r=i?`/automations/${e.automationId}/runs?${i}`:`/automations/${e.automationId}/runs`;return await this.resend.get(r)}};function ss(e){switch(e.type){case"trigger":return{key:e.key,type:e.type,config:{event_name:e.config.eventName}};case"delay":return{key:e.key,type:e.type,config:e.config};case"send_email":return{key:e.key,type:e.type,config:{template:e.config.template,subject:e.config.subject,from:e.config.from,reply_to:e.config.replyTo}};case"wait_for_event":return{key:e.key,type:e.type,config:{event_name:e.config.eventName,timeout:e.config.timeout,filter_rule:e.config.filterRule}};case"condition":return{key:e.key,type:e.type,config:e.config};case"contact_update":return{key:e.key,type:e.type,config:{first_name:e.config.firstName,last_name:e.config.lastName,unsubscribed:e.config.unsubscribed,properties:e.config.properties}};case"contact_delete":return{key:e.key,type:e.type,config:e.config};case"add_to_segment":return{key:e.key,type:e.type,config:{segment_id:e.config.segmentId}}}}function as(e){return{from:e.from,to:e.to,type:e.type}}function Kp(e){return{name:e.name,status:e.status,steps:e.steps.map(ss),connections:e.connections.map(as)}}function vp(e){return{event:e.event,contact_id:e.contactId,email:e.email,payload:e.payload}}var wp=class{constructor(e){this.resend=e,this.runs=new Sp(this.resend)}async create(e){return await this.resend.post("/automations",Kp(e))}async list(e={}){let t=[se(e)];e.status&&t.push(`status=${encodeURIComponent(e.status)}`);let o=t.filter(Boolean).join("&"),i=o?`/automations?${o}`:"/automations";return await this.resend.get(i)}async get(e){return await this.resend.get(`/automations/${e}`)}async remove(e){return await this.resend.delete(`/automations/${e}`)}async update(e,t){let o={};return t.name!==void 0&&(o.name=t.name),t.status!==void 0&&(o.status=t.status),t.steps!==void 0&&(o.steps=t.steps.map(ss)),t.connections!==void 0&&(o.connections=t.connections.map(as)),await this.resend.patch(`/automations/${e}`,o)}async stop(e){return await this.resend.post(`/automations/${e}/stop`)}};function xp(e){return e?.map(t=>({content:t.content,filename:t.filename,path:t.path,content_type:t.contentType,content_id:t.contentId}))}function ls(e){return{attachments:xp(e.attachments),bcc:e.bcc,cc:e.cc,from:e.from,headers:e.headers,html:e.html,reply_to:e.replyTo,scheduled_at:e.scheduledAt,subject:e.subject,tags:e.tags,text:e.text,to:e.to,template:e.template?{id:e.template.id,variables:e.template.variables}:void 0,topic_id:e.topicId}}async function ro(e){let t;try{({render:t}=await import("@react-email/render"))}catch{throw new Error("Failed to render React component. Make sure to install `@react-email/render` or `@react-email/components`.")}return t(e)}var Fp=class{constructor(e){this.resend=e}async send(e,t){return this.create(e,t)}async create(e,t){let o=[];for(let i of e)i.react&&(i.html=await ro(i.react),i.react=void 0),o.push(ls(i));return await this.resend.post("/emails/batch",o,{...t,headers:{"x-batch-validation":t?.batchValidation??"strict",...t?.headers}})}},kp=class{constructor(e){this.resend=e}async create(e,t={}){let o=e.react?await ro(e.react):e.html;return await this.resend.post("/broadcasts",{name:e.name,segment_id:e.segmentId,audience_id:e.audienceId,preview_text:e.previewText,from:e.from,html:o,reply_to:e.replyTo,subject:e.subject,text:e.text,topic_id:e.topicId,send:e.send,scheduled_at:e.scheduledAt},t)}async send(e,t){return await this.resend.post(`/broadcasts/${e}/send`,{scheduled_at:t?.scheduledAt})}async list(e={}){let t=se(e),o=t?`/broadcasts?${t}`:"/broadcasts";return await this.resend.get(o)}async get(e){return await this.resend.get(`/broadcasts/${e}`)}async remove(e){return await this.resend.delete(`/broadcasts/${e}`)}async update(e,t){let o=t.react?await ro(t.react):t.html;return await this.resend.patch(`/broadcasts/${e}`,{name:t.name,segment_id:t.segmentId,audience_id:t.audienceId,from:t.from,html:o,text:t.text,subject:t.subject,reply_to:t.replyTo,preview_text:t.previewText,topic_id:t.topicId})}};function Xn(e){return{id:e.id,key:e.key,createdAt:e.created_at,type:e.type,fallbackValue:e.fallback_value}}function Zn(e){return"key"in e?{key:e.key,type:e.type,fallback_value:e.fallbackValue}:{fallback_value:e.fallbackValue}}var Rp=class{constructor(e){this.resend=e}async create(e){let t=Zn(e);return await this.resend.post("/contact-properties",t)}async list(e={}){let t=se(e),o=t?`/contact-properties?${t}`:"/contact-properties",i=await this.resend.get(o);return i.data?{data:{...i.data,data:i.data.data.map(r=>Xn(r))},headers:i.headers,error:null}:i}async get(e){if(!e)return{data:null,headers:null,error:{message:"Missing `id` field.",statusCode:null,name:"missing_required_field"}};let t=await this.resend.get(`/contact-properties/${e}`);return t.data?{data:{object:"contact_property",...Xn(t.data)},headers:t.headers,error:null}:t}async update(e){if(!e.id)return{data:null,headers:null,error:{message:"Missing `id` field.",statusCode:null,name:"missing_required_field"}};let t=Zn(e);return await this.resend.patch(`/contact-properties/${e.id}`,t)}async remove(e){return e?await this.resend.delete(`/contact-properties/${e}`):{data:null,headers:null,error:{message:"Missing `id` field.",statusCode:null,name:"missing_required_field"}}}},_p=class{constructor(e){this.resend=e}async create(e,t={}){let o=this.buildCreateFormData(e);return this.resend.post("/contacts/imports",o,t)}async list(e={}){let t=new URLSearchParams(se(e));e.status!==void 0&&t.set("status",e.status);let o=t.toString(),i=o?`/contacts/imports?${o}`:"/contacts/imports";return this.resend.get(i)}async get(e){return this.resend.get(`/contacts/imports/${e}`)}buildCreateFormData(e){let t=new FormData;return t.append("file",e.file),this.appendField(t,"column_map",this.buildColumnMap(e.columnMap??null)),this.appendField(t,"on_conflict",e.onConflict??null),this.appendField(t,"segments",e.segments??null),this.appendField(t,"topics",e.topics??null),t}buildColumnMap(e){return e===null?null:{email:e.email,first_name:e.firstName,last_name:e.lastName,unsubscribed:e.unsubscribed,properties:e.properties}}appendField(e,t,o){o!==null&&e.append(t,typeof o=="string"?o:JSON.stringify(o))}},Dp=class{constructor(e){this.resend=e}async list(e){if(!e.contactId&&!e.email)return{data:null,headers:null,error:{message:"Missing `id` or `email` field.",statusCode:null,name:"missing_required_field"}};let t=e.email?e.email:e.contactId,o=se(e),i=o?`/contacts/${t}/segments?${o}`:`/contacts/${t}/segments`;return await this.resend.get(i)}async add(e){if(!e.contactId&&!e.email)return{data:null,headers:null,error:{message:"Missing `id` or `email` field.",statusCode:null,name:"missing_required_field"}};let t=e.email?e.email:e.contactId;return this.resend.post(`/contacts/${t}/segments/${e.segmentId}`)}async remove(e){if(!e.contactId&&!e.email)return{data:null,headers:null,error:{message:"Missing `id` or `email` field.",statusCode:null,name:"missing_required_field"}};let t=e.email?e.email:e.contactId;return this.resend.delete(`/contacts/${t}/segments/${e.segmentId}`)}},Ep=class{constructor(e){this.resend=e}async update(e){if(!e.id&&!e.email)return{data:null,headers:null,error:{message:"Missing `id` or `email` field.",statusCode:null,name:"missing_required_field"}};let t=e.email?e.email:e.id;return this.resend.patch(`/contacts/${t}/topics`,e.topics)}async list(e){if(!e.id&&!e.email)return{data:null,headers:null,error:{message:"Missing `id` or `email` field.",statusCode:null,name:"missing_required_field"}};let t=e.email?e.email:e.id,o=se(e),i=o?`/contacts/${t}/topics?${o}`:`/contacts/${t}/topics`;return this.resend.get(i)}},Bp=class{constructor(e){this.resend=e,this.imports=new _p(this.resend),this.topics=new Ep(this.resend),this.segments=new Dp(this.resend)}async create(e,t={}){return"audienceId"in e?"segments"in e||"topics"in e?{data:null,headers:null,error:{message:"`audienceId` is deprecated, and cannot be used together with `segments` or `topics`. Use `segments` instead to add one or more segments to the new contact.",statusCode:null,name:"invalid_parameter"}}:await this.resend.post(`/audiences/${e.audienceId}/contacts`,{unsubscribed:e.unsubscribed,email:e.email,first_name:e.firstName,last_name:e.lastName,properties:e.properties},t):await this.resend.post("/contacts",{unsubscribed:e.unsubscribed,email:e.email,first_name:e.firstName,last_name:e.lastName,properties:e.properties,segments:e.segments,topics:e.topics},t)}async list(e={}){let t=e.segmentId??e.audienceId;if(!t){let r=se(e),n=r?`/contacts?${r}`:"/contacts";return await this.resend.get(n)}let o=se(e),i=o?`/segments/${t}/contacts?${o}`:`/segments/${t}/contacts`;return await this.resend.get(i)}async get(e){return typeof e=="string"?this.resend.get(`/contacts/${e}`):!e.id&&!e.email?{data:null,headers:null,error:{message:"Missing `id` or `email` field.",statusCode:null,name:"missing_required_field"}}:e.audienceId?this.resend.get(`/audiences/${e.audienceId}/contacts/${e?.email?e?.email:e?.id}`):this.resend.get(`/contacts/${e?.email?e?.email:e?.id}`)}async update(e){return!e.id&&!e.email?{data:null,headers:null,error:{message:"Missing `id` or `email` field.",statusCode:null,name:"missing_required_field"}}:e.audienceId?await this.resend.patch(`/audiences/${e.audienceId}/contacts/${e?.email?e?.email:e?.id}`,{unsubscribed:e.unsubscribed,first_name:e.firstName,last_name:e.lastName,properties:e.properties}):await this.resend.patch(`/contacts/${e?.email?e?.email:e?.id}`,{unsubscribed:e.unsubscribed,first_name:e.firstName,last_name:e.lastName,properties:e.properties})}async remove(e){return typeof e=="string"?this.resend.delete(`/contacts/${e}`):!e.id&&!e.email?{data:null,headers:null,error:{message:"Missing `id` or `email` field.",statusCode:null,name:"missing_required_field"}}:e.audienceId?this.resend.delete(`/audiences/${e.audienceId}/contacts/${e?.email?e?.email:e?.id}`):this.resend.delete(`/contacts/${e?.email?e?.email:e?.id}`)}};function Op(e){return{name:e.name,region:e.region,custom_return_path:e.customReturnPath,capabilities:e.capabilities,open_tracking:e.openTracking,click_tracking:e.clickTracking,tls:e.tls,tracking_subdomain:e.trackingSubdomain}}var Tp=class{constructor(e){this.resend=e}async create(e,t={}){return await this.resend.post("/domains/claim",{name:e.name,region:e.region,custom_return_path:e.customReturnPath,open_tracking:e.openTracking,click_tracking:e.clickTracking,tracking_subdomain:e.trackingSubdomain},t)}async get(e){return await this.resend.get(`/domains/${e}/claim`)}async verify(e){return await this.resend.post(`/domains/${e}/claim/verify`)}},jp=class{constructor(e){this.resend=e,this.claims=new Tp(this.resend)}async create(e,t={}){return await this.resend.post("/domains",Op(e),t)}async list(e={}){let t=se(e),o=t?`/domains?${t}`:"/domains";return await this.resend.get(o)}async get(e){return await this.resend.get(`/domains/${e}`)}async update(e){return await this.resend.patch(`/domains/${e.id}`,{click_tracking:e.clickTracking,open_tracking:e.openTracking,tls:e.tls,capabilities:e.capabilities,tracking_subdomain:e.trackingSubdomain})}async remove(e){return await this.resend.delete(`/domains/${e}`)}async verify(e){return await this.resend.post(`/domains/${e}/verify`)}},Ip=class{constructor(e){this.resend=e}async get(e){let{emailId:t,id:o}=e;return await this.resend.get(`/emails/${t}/attachments/${o}`)}async list(e){let{emailId:t}=e,o=se(e),i=o?`/emails/${t}/attachments?${o}`:`/emails/${t}/attachments`;return await this.resend.get(i)}},Pp=class{constructor(e){this.resend=e}async get(e){let{emailId:t,id:o}=e;return await this.resend.get(`/emails/receiving/${t}/attachments/${o}`)}async list(e){let{emailId:t}=e,o=se(e),i=o?`/emails/receiving/${t}/attachments?${o}`:`/emails/receiving/${t}/attachments`;return await this.resend.get(i)}},$p=class{constructor(e){this.resend=e,this.attachments=new Pp(e)}async get(e,t={}){let o=new URLSearchParams;t.html_format!==void 0&&o.set("html_format",t.html_format);let i=o.toString(),r=i?`/emails/receiving/${e}?${i}`:`/emails/receiving/${e}`;return await this.resend.get(r)}async list(e={}){let t=se(e),o=t?`/emails/receiving?${t}`:"/emails/receiving";return await this.resend.get(o)}async forward(e,t={}){let{emailId:o,to:i,from:r}=e,n=e.passthrough!==!1,s=await this.get(o);if(s.error)return{data:null,error:s.error,headers:s.headers};let a=s.data,l=a.subject||"(no subject)";if(n)return this.forwardPassthrough(a,{to:i,from:r,subject:l},t);let d=l.startsWith("Fwd:")?l:`Fwd: ${l}`;return this.forwardWrapped(a,{to:i,from:r,subject:d,text:"text"in e?e.text:void 0,html:"html"in e?e.html:void 0},t)}async forwardPassthrough(e,t,o){let{to:i,from:r,subject:n}=t;if(!e.raw?.download_url)return{data:null,error:{name:"validation_error",message:"Raw email content is not available for this email",statusCode:400},headers:null};let s=await fetch(e.raw.download_url);if(!s.ok)return{data:null,error:{name:"application_error",message:"Failed to download raw email content",statusCode:s.status},headers:null};let a=await s.text(),l=await oo.parse(a,{attachmentEncoding:"base64"}),d=l.attachments.map(c=>{let u=c.contentId?c.contentId.replace(/^<|>$/g,""):void 0;return{filename:c.filename,content:c.content.toString(),content_type:c.mimeType,content_id:u||void 0}});return await this.resend.post("/emails",{from:r,to:i,subject:n,text:l.text||void 0,html:l.html||void 0,attachments:d.length>0?d:void 0},o)}async forwardWrapped(e,t,o){let{to:i,from:r,subject:n,text:s,html:a}=t;if(!e.raw?.download_url)return{data:null,error:{name:"validation_error",message:"Raw email content is not available for this email",statusCode:400},headers:null};let l=await fetch(e.raw.download_url);if(!l.ok)return{data:null,error:{name:"application_error",message:"Failed to download raw email content",statusCode:l.status},headers:null};let d=await l.text();return await this.resend.post("/emails",{from:r,to:i,subject:n,text:s,html:a,attachments:[{filename:"forwarded_message.eml",content:Buffer.from(d).toString("base64"),content_type:"message/rfc822"}]},o)}},Hp=class{constructor(e){this.resend=e,this.attachments=new Ip(e),this.receiving=new $p(e)}async send(e,t={}){return this.create(e,t)}async create(e,t={}){let o={...e};return e.react&&(o.html=await ro(e.react)),await this.resend.post("/emails",ls(o),t)}async get(e){return await this.resend.get(`/emails/${e}`)}async list(e={}){let t=se(e),o=t?`/emails?${t}`:"/emails";return await this.resend.get(o)}async update(e){return await this.resend.patch(`/emails/${e.id}`,{scheduled_at:e.scheduledAt})}async cancel(e){return await this.resend.post(`/emails/${e}/cancel`)}},Gp=class{constructor(e){this.resend=e}async send(e){return await this.resend.post("/events/send",vp(e))}async create(e){return await this.resend.post("/events",e)}async get(e){return await this.resend.get(`/events/${encodeURIComponent(e)}`)}async list(e={}){let t=se(e),o=t?`/events?${t}`:"/events";return await this.resend.get(o)}async update(e,t){return await this.resend.patch(`/events/${encodeURIComponent(e)}`,t)}async remove(e){return await this.resend.delete(`/events/${encodeURIComponent(e)}`)}},Qp=class{constructor(e){this.resend=e}async list(e={}){let t=se(e),o=t?`/logs?${t}`:"/logs";return await this.resend.get(o)}async get(e){return await this.resend.get(`/logs/${e}`)}},Np=class{constructor(e){this.resend=e}async list(e={}){let t=se(e),o=t?`/oauth/grants?${t}`:"/oauth/grants";return await this.resend.get(o)}async revoke(e){return await this.resend.delete(`/oauth/grants/${e}`)}},qp=class{constructor(e){this.resend=e}async create(e,t={}){return await this.resend.post("/segments",e,t)}async list(e={}){let t=se(e),o=t?`/segments?${t}`:"/segments";return await this.resend.get(o)}async get(e){return await this.resend.get(`/segments/${e}`)}async remove(e){return await this.resend.delete(`/segments/${e}`)}},Mp=class{constructor(e){this.resend=e}async add(e){return this.resend.post("/suppressions/batch/add",e)}async remove(e){return this.resend.post("/suppressions/batch/remove",e)}},es=()=>({data:null,headers:null,error:{message:"Missing `id` field.",statusCode:null,name:"missing_required_field"}}),Lp=class{constructor(e){this.resend=e,this.batch=new Mp(e)}async add(e){return this.resend.post("/suppressions",e)}async list(e={}){let t=Wp(e),o=t?`/suppressions?${t}`:"/suppressions";return this.resend.get(o)}async get(e){return e?this.resend.get(`/suppressions/${encodeURIComponent(e)}`):es()}async remove(e){return e?this.resend.delete(`/suppressions/${encodeURIComponent(e)}`):es()}};function Wp(e){let{origin:t,...o}=e,i=new URLSearchParams(se(o));return t&&i.set("origin",t),i.toString()}function Jp(e={}){let t=new URLSearchParams;return e.before&&t.set("before",e.before),e.after&&t.set("after",e.after),e.limit&&t.set("limit",e.limit.toString()),t.size>0?`?${t.toString()}`:""}function Vp(e){return e?.map(t=>({key:t.key,type:t.type,fallback_value:t.fallbackValue}))}function ts(e){return{name:"name"in e?e.name:void 0,subject:e.subject,html:e.html,text:e.text,alias:e.alias,from:e.from,reply_to:e.replyTo,variables:Vp(e.variables)}}var os=class{constructor(e,t){this.promise=e,this.publishFn=t}then(e,t){return this.promise.then(e,t)}async publish(){let{data:e,error:t}=await this.promise;return t?{data:null,headers:null,error:t}:this.publishFn(e.id)}},zp=class{constructor(e){this.resend=e}create(e){return new os(this.performCreate(e),this.publish.bind(this))}async performCreate(e){let t={...e};return e.react&&(t.html=await ro(e.react)),this.resend.post("/templates",ts(t))}async remove(e){return await this.resend.delete(`/templates/${e}`)}async get(e){return await this.resend.get(`/templates/${e}`)}async list(e={}){return this.resend.get(`/templates${Jp(e)}`)}duplicate(e){return new os(this.resend.post(`/templates/${e}/duplicate`),this.publish.bind(this))}async publish(e){return await this.resend.post(`/templates/${e}/publish`)}async update(e,t){return await this.resend.patch(`/templates/${e}`,ts(t))}},Yp=class{constructor(e){this.resend=e}async create(e){let{defaultSubscription:t,...o}=e;return await this.resend.post("/topics",{...o,default_subscription:t})}async list(){return await this.resend.get("/topics")}async get(e){return e?await this.resend.get(`/topics/${e}`):{data:null,headers:null,error:{message:"Missing `id` field.",statusCode:null,name:"missing_required_field"}}}async update(e){return e.id?await this.resend.patch(`/topics/${e.id}`,e):{data:null,headers:null,error:{message:"Missing `id` field.",statusCode:null,name:"missing_required_field"}}}async remove(e){return e?await this.resend.delete(`/topics/${e}`):{data:null,headers:null,error:{message:"Missing `id` field.",statusCode:null,name:"missing_required_field"}}}},Xp=class{constructor(e){this.resend=e}async create(e,t={}){return await this.resend.post("/webhooks",e,t)}async get(e){return await this.resend.get(`/webhooks/${e}`)}async list(e={}){let t=se(e),o=t?`/webhooks?${t}`:"/webhooks";return await this.resend.get(o)}async update(e,t){return await this.resend.patch(`/webhooks/${e}`,t)}async remove(e){return await this.resend.delete(`/webhooks/${e}`)}verify(e){return new ns.Webhook(e.webhookSecret).verify(e.payload,{"webhook-id":e.headers.id,"webhook-timestamp":e.headers.timestamp,"webhook-signature":e.headers.signature})}},is="https://api.resend.com",rs=`resend-node:${yp}`;function Zp(){return typeof process<"u"&&process.env&&process.env.RESEND_BASE_URL||is}function em(){return typeof process<"u"&&process.env&&process.env.RESEND_USER_AGENT||rs}var kt=class{constructor(e,t){if(this.key=e,this.segments=new qp(this),this.apiKeys=new Up(this),this.audiences=this.segments,this.automations=new wp(this),this.batch=new Fp(this),this.broadcasts=new kp(this),this.contactProperties=new Rp(this),this.contacts=new Bp(this),this.domains=new jp(this),this.emails=new Hp(this),this.events=new Gp(this),this.logs=new Qp(this),this.oauthGrants=new Np(this),this.suppressions=new Lp(this),this.templates=new zp(this),this.topics=new Yp(this),this.webhooks=new Xp(this),!e&&(typeof process<"u"&&process.env&&(this.key=process.env.RESEND_API_KEY),!this.key))throw new Error('Missing API key. Pass it to the constructor `new Resend("re_123")`');this.baseUrl=t?.baseUrl??Zp(),this.userAgent=t?.userAgent??em(),this.headers=new Headers({Authorization:`Bearer ${this.key}`,"User-Agent":this.userAgent,"Content-Type":"application/json"})}logError(e,t,o){typeof process<"u"&&process.env&&process.env.NODE_ENV!=="production"&&console.error("[Resend API Error]:",{...o!==void 0&&{status:o},error:e,path:t})}async fetchRequest(e,t={}){try{let o=await fetch(`${this.baseUrl}${e}`,t);if(!o.ok)try{let i=await o.text(),r=JSON.parse(i);return this.logError(r,e,o.status),{data:null,error:r,headers:Object.fromEntries(o.headers.entries())}}catch(i){if(i instanceof SyntaxError){let n={name:"application_error",statusCode:o.status,message:"Internal server error. We are unable to process your request right now, please try again later."};return this.logError(n,e,o.status),{data:null,error:n,headers:Object.fromEntries(o.headers.entries())}}let r={message:o.statusText,statusCode:o.status,name:"application_error"};if(i instanceof Error){let n={...r,message:i.message};return this.logError(n,e,o.status),{data:null,error:n,headers:Object.fromEntries(o.headers.entries())}}return this.logError(r,e,o.status),{data:null,error:r,headers:Object.fromEntries(o.headers.entries())}}return{data:await o.json(),error:null,headers:Object.fromEntries(o.headers.entries())}}catch{let o={name:"application_error",statusCode:null,message:"Unable to fetch data. The request could not be resolved."};return this.logError(o,e),{data:null,error:o,headers:null}}}async post(e,t,o={}){let i=new Headers(this.headers),r=typeof FormData<"u"&&t instanceof FormData;if(r&&i.delete("Content-Type"),o.headers)for(let[s,a]of new Headers(o.headers).entries())i.set(s,a);o.idempotencyKey&&i.set("Idempotency-Key",o.idempotencyKey);let n={method:"POST",body:r?t:JSON.stringify(t),...o,headers:i};return this.fetchRequest(e,n)}async get(e,t={}){let o=new Headers(this.headers);if(t.headers)for(let[r,n]of new Headers(t.headers).entries())o.set(r,n);let i={method:"GET",...t,headers:o};return this.fetchRequest(e,i)}async put(e,t,o={}){let i=new Headers(this.headers);if(o.headers)for(let[n,s]of new Headers(o.headers).entries())i.set(n,s);let r={method:"PUT",body:JSON.stringify(t),...o,headers:i};return this.fetchRequest(e,r)}async patch(e,t,o={}){let i=new Headers(this.headers);if(o.headers)for(let[n,s]of new Headers(o.headers).entries())i.set(n,s);let r={method:"PATCH",body:JSON.stringify(t),...o,headers:i};return this.fetchRequest(e,r)}async delete(e,t,o={}){let i=new Headers(this.headers);if(o.headers)for(let[n,s]of new Headers(o.headers).entries())i.set(n,s);let r={method:"DELETE",body:t===void 0?void 0:JSON.stringify(t),...o,headers:i};return this.fetchRequest(e,r)}};he();var br=ue(qe(),1);function q(e,t){return e instanceof Error?e.message:t}function Qs(e){return!!(e||!process.stdout.isTTY)}function B(e,t={}){Qs(t.json)?console.log(JSON.stringify(e,null,2)):console.log(typeof e=="string"?e:JSON.stringify(e,null,2)),t.exitCode!==void 0&&process.exit(t.exitCode)}var fm=new Set(["content-type","retry-after"]);function gm(e){let t={};for(let[o,i]of Object.entries(e)){let r=o.toLowerCase();(fm.has(r)||r.startsWith("x-"))&&(t[r]=i)}return t}function g(e,t={}){let o=t.exitCode??1,i=e.headers&&Object.keys(e.headers).length>0?gm(e.headers):void 0,r=i!==void 0&&Object.keys(i).length>0;if(Qs(t.json)){let n={message:e.message,code:e.code??"unknown"};typeof e.statusCode=="number"&&(n.statusCode=e.statusCode),r&&(n.headers=i),typeof e.body=="string"&&e.body.length>0&&(n.body=e.body),console.error(JSON.stringify({error:n},null,2))}else{console.error(`${br.default.red("Error:")} ${e.message}`);let n=[];if(typeof e.statusCode=="number"&&n.push(`HTTP ${e.statusCode}`),r)for(let[s,a]of Object.entries(i))n.push(`${s}: ${a}`);n.length>0&&console.error(br.default.dim(`[${n.join("; ")}]`))}process.exit(o)}var Ns={sending_access:0,full_access:1};function hm(e,t){return Ns[e]>=Ns[t]}async function Y(e,t){let o=e.profile;try{let i=await St(e.apiKey,o);if(!i){if(o){let s=ve();if(!s.some(l=>l.name===o))throw new Error(`Profile "${o}" not found. Available profiles: ${s.map(l=>l.name).join(", ")||"(none)"}`)}throw new Error("No API key found. Set RESEND_API_KEY, use --api-key, or run: resend login")}let r;if(i.type==="api_key")r=i.permission;else{let s=i.scope.split(" ").filter(Boolean);s.includes("full_access")?r="full_access":s.includes("emails:send")?r="sending_access":g({message:`Unrecognized credential scope${i.scope?` "${i.scope}"`:""}. Run \`resend login\` to re-authenticate.`,code:"unrecognized_scope"},{json:e.json})}if(r){let s=t?.permission??"full_access";hm(r,s)||g({message:`This command requires full access. Your current credential has sending access only.
|
|
269
|
-
${_t}`,code:"insufficient_permissions"},{json:e.json})}let n=i.type==="api_key"?i.key:i.access_token;return new kt(n)}catch(i){g({message:q(i,"Failed to create client"),code:"auth_error"},{json:e.json})}}var qs=130;function Am(){process.stderr.isTTY&&process.stderr.write("\r\x1B[2K"),console.error("Cancelled."),process.exit(qs)}var Dt;function Ms(){Dt=Am,process.on("SIGINT",Dt),process.on("uncaughtException",e=>{g({message:q(e,"An unexpected error occurred"),code:"unexpected_error"},{}),process.exit(1)})}function Lo(e){Dt&&process.removeListener("SIGINT",Dt),Dt=e,process.on("SIGINT",Dt)}function
|
|
268
|
+
`)}),this.textContent=t}isInlineTextNode(t){if(t.contentDisposition?.parsed?.value==="attachment")return!1;switch(t.contentType.parsed?.value){case"text/html":case"text/plain":return!0;default:return!1}}isInlineMessageRfc822(t){return t.contentType.parsed?.value!=="message/rfc822"?!1:(t.contentDisposition?.parsed?.value||(this.options.rfc822Attachments?"attachment":"inline"))==="inline"}forceRfc822Attachments(){if(this.options.forceRfc822Attachments)return!0;let t=!1,o=i=>{i.contentType.multipart||i.contentType.parsed&&["message/delivery-status","message/feedback-report"].includes(i.contentType.parsed.value)&&(t=!0);for(let r of i.childNodes)o(r)};return o(this.root),t}async resolveStream(t){let o=0,i=[],r=t.getReader();for(;;){let{done:a,value:l}=await r.read();if(a)break;i.push(l),o+=l.length}let n=new Uint8Array(o),s=0;for(let a of i)n.set(a,s),s+=a.length;return n}async parse(t){if(this.started)throw new Error("Can not reuse parser, create a new PostalMime object");for(this.started=!0,t&&typeof t.getReader=="function"&&(t=await this.resolveStream(t)),t=t||new ArrayBuffer(0),typeof t=="string"&&(t=nt.encode(t)),(t instanceof Blob||Object.prototype.toString.call(t)==="[object Blob]")&&(t=await st(t)),t.buffer instanceof ArrayBuffer&&(t=new Uint8Array(t).buffer),this.buf=t,this.av=new Uint8Array(t),this.readPos=0;this.readPos<this.av.length;){let r=this.readLine();await this.processLine(r.bytes,r.done)}await this.processNodeTree();let o={headers:this.root.headers.map(r=>({key:r.key,originalKey:r.originalKey,value:r.value})).reverse()};for(let r of["from","sender"]){let n=this.root.headers.find(s=>s.key===r);if(n&&n.value){let s=Do(n.value);s&&s.length&&(o[r]=s[0])}}for(let r of["delivered-to","return-path"]){let n=this.root.headers.find(s=>s.key===r);if(n&&n.value){let s=Do(n.value);if(s&&s.length&&s[0].address){let a=Zi(r);o[a]=s[0].address}}}for(let r of["to","cc","bcc","reply-to"]){let n=this.root.headers.filter(a=>a.key===r),s=[];if(n.filter(a=>a&&a.value).map(a=>Do(a.value)).forEach(a=>s=s.concat(a||[])),s&&s.length){let a=Zi(r);o[a]=s}}for(let r of["subject","message-id","in-reply-to","references"]){let n=this.root.headers.find(s=>s.key===r);if(n&&n.value){let s=Zi(r);o[s]=Ct(n.value)}}let i=this.root.headers.find(r=>r.key==="date");if(i){let r=new Date(i.value);r.toString()==="Invalid Date"?r=i.value:r=r.toISOString(),o.date=r}switch(this.textContent?.html&&(o.html=this.textContent.html),this.textContent?.plain&&(o.text=this.textContent.plain),o.attachments=this.attachments,o.headerLines=(this.root.rawHeaderLines||[]).slice().reverse(),this.attachmentEncoding){case"arraybuffer":break;case"base64":for(let n of o.attachments||[])n?.content&&(n.content=Gn(n.content),n.encoding="base64");break;case"utf8":let r=new TextDecoder("utf8");for(let n of o.attachments||[])n?.content&&(n.content=r.decode(n.content),n.encoding="utf8");break;default:throw new Error("Unknown attachment encoding")}return o}};var ns=ue(Yn(),1),yp="6.18.0";function se(e){let t=new URLSearchParams;return e.limit!==void 0&&t.set("limit",e.limit.toString()),"after"in e&&e.after!==void 0&&t.set("after",e.after),"before"in e&&e.before!==void 0&&t.set("before",e.before),t.toString()}var Up=class{constructor(e){this.resend=e}async create(e,t={}){return await this.resend.post("/api-keys",e,t)}async list(e={}){let t=se(e),o=t?`/api-keys?${t}`:"/api-keys";return await this.resend.get(o)}async remove(e){return await this.resend.delete(`/api-keys/${e}`)}},Sp=class{constructor(e){this.resend=e}async get(e){return await this.resend.get(`/automations/${e.automationId}/runs/${e.runId}`)}async list(e){let t=se(e),o=new URLSearchParams(t);if(e.status){let n=Array.isArray(e.status)?e.status.join(","):e.status;o.set("status",n)}let i=o.toString(),r=i?`/automations/${e.automationId}/runs?${i}`:`/automations/${e.automationId}/runs`;return await this.resend.get(r)}};function ss(e){switch(e.type){case"trigger":return{key:e.key,type:e.type,config:{event_name:e.config.eventName}};case"delay":return{key:e.key,type:e.type,config:e.config};case"send_email":return{key:e.key,type:e.type,config:{template:e.config.template,subject:e.config.subject,from:e.config.from,reply_to:e.config.replyTo}};case"wait_for_event":return{key:e.key,type:e.type,config:{event_name:e.config.eventName,timeout:e.config.timeout,filter_rule:e.config.filterRule}};case"condition":return{key:e.key,type:e.type,config:e.config};case"contact_update":return{key:e.key,type:e.type,config:{first_name:e.config.firstName,last_name:e.config.lastName,unsubscribed:e.config.unsubscribed,properties:e.config.properties}};case"contact_delete":return{key:e.key,type:e.type,config:e.config};case"add_to_segment":return{key:e.key,type:e.type,config:{segment_id:e.config.segmentId}}}}function as(e){return{from:e.from,to:e.to,type:e.type}}function Kp(e){return{name:e.name,status:e.status,steps:e.steps.map(ss),connections:e.connections.map(as)}}function vp(e){return{event:e.event,contact_id:e.contactId,email:e.email,payload:e.payload}}var wp=class{constructor(e){this.resend=e,this.runs=new Sp(this.resend)}async create(e){return await this.resend.post("/automations",Kp(e))}async list(e={}){let t=[se(e)];e.status&&t.push(`status=${encodeURIComponent(e.status)}`);let o=t.filter(Boolean).join("&"),i=o?`/automations?${o}`:"/automations";return await this.resend.get(i)}async get(e){return await this.resend.get(`/automations/${e}`)}async remove(e){return await this.resend.delete(`/automations/${e}`)}async update(e,t){let o={};return t.name!==void 0&&(o.name=t.name),t.status!==void 0&&(o.status=t.status),t.steps!==void 0&&(o.steps=t.steps.map(ss)),t.connections!==void 0&&(o.connections=t.connections.map(as)),await this.resend.patch(`/automations/${e}`,o)}async stop(e){return await this.resend.post(`/automations/${e}/stop`)}};function xp(e){return e?.map(t=>({content:t.content,filename:t.filename,path:t.path,content_type:t.contentType,content_id:t.contentId}))}function ls(e){return{attachments:xp(e.attachments),bcc:e.bcc,cc:e.cc,from:e.from,headers:e.headers,html:e.html,reply_to:e.replyTo,scheduled_at:e.scheduledAt,subject:e.subject,tags:e.tags,text:e.text,to:e.to,template:e.template?{id:e.template.id,variables:e.template.variables}:void 0,topic_id:e.topicId}}async function ro(e){let t;try{({render:t}=await import("@react-email/render"))}catch{throw new Error("Failed to render React component. Make sure to install `@react-email/render` or `@react-email/components`.")}return t(e)}var Fp=class{constructor(e){this.resend=e}async send(e,t){return this.create(e,t)}async create(e,t){let o=[];for(let i of e)i.react&&(i.html=await ro(i.react),i.react=void 0),o.push(ls(i));return await this.resend.post("/emails/batch",o,{...t,headers:{"x-batch-validation":t?.batchValidation??"strict",...t?.headers}})}},kp=class{constructor(e){this.resend=e}async create(e,t={}){let o=e.react?await ro(e.react):e.html;return await this.resend.post("/broadcasts",{name:e.name,segment_id:e.segmentId,audience_id:e.audienceId,preview_text:e.previewText,from:e.from,html:o,reply_to:e.replyTo,subject:e.subject,text:e.text,topic_id:e.topicId,send:e.send,scheduled_at:e.scheduledAt},t)}async send(e,t){return await this.resend.post(`/broadcasts/${e}/send`,{scheduled_at:t?.scheduledAt})}async list(e={}){let t=se(e),o=t?`/broadcasts?${t}`:"/broadcasts";return await this.resend.get(o)}async get(e){return await this.resend.get(`/broadcasts/${e}`)}async remove(e){return await this.resend.delete(`/broadcasts/${e}`)}async update(e,t){let o=t.react?await ro(t.react):t.html;return await this.resend.patch(`/broadcasts/${e}`,{name:t.name,segment_id:t.segmentId,audience_id:t.audienceId,from:t.from,html:o,text:t.text,subject:t.subject,reply_to:t.replyTo,preview_text:t.previewText,topic_id:t.topicId})}};function Xn(e){return{id:e.id,key:e.key,createdAt:e.created_at,type:e.type,fallbackValue:e.fallback_value}}function Zn(e){return"key"in e?{key:e.key,type:e.type,fallback_value:e.fallbackValue}:{fallback_value:e.fallbackValue}}var Rp=class{constructor(e){this.resend=e}async create(e){let t=Zn(e);return await this.resend.post("/contact-properties",t)}async list(e={}){let t=se(e),o=t?`/contact-properties?${t}`:"/contact-properties",i=await this.resend.get(o);return i.data?{data:{...i.data,data:i.data.data.map(r=>Xn(r))},headers:i.headers,error:null}:i}async get(e){if(!e)return{data:null,headers:null,error:{message:"Missing `id` field.",statusCode:null,name:"missing_required_field"}};let t=await this.resend.get(`/contact-properties/${e}`);return t.data?{data:{object:"contact_property",...Xn(t.data)},headers:t.headers,error:null}:t}async update(e){if(!e.id)return{data:null,headers:null,error:{message:"Missing `id` field.",statusCode:null,name:"missing_required_field"}};let t=Zn(e);return await this.resend.patch(`/contact-properties/${e.id}`,t)}async remove(e){return e?await this.resend.delete(`/contact-properties/${e}`):{data:null,headers:null,error:{message:"Missing `id` field.",statusCode:null,name:"missing_required_field"}}}},_p=class{constructor(e){this.resend=e}async create(e,t={}){let o=this.buildCreateFormData(e);return this.resend.post("/contacts/imports",o,t)}async list(e={}){let t=new URLSearchParams(se(e));e.status!==void 0&&t.set("status",e.status);let o=t.toString(),i=o?`/contacts/imports?${o}`:"/contacts/imports";return this.resend.get(i)}async get(e){return this.resend.get(`/contacts/imports/${e}`)}buildCreateFormData(e){let t=new FormData;return t.append("file",e.file),this.appendField(t,"column_map",this.buildColumnMap(e.columnMap??null)),this.appendField(t,"on_conflict",e.onConflict??null),this.appendField(t,"segments",e.segments??null),this.appendField(t,"topics",e.topics??null),t}buildColumnMap(e){return e===null?null:{email:e.email,first_name:e.firstName,last_name:e.lastName,unsubscribed:e.unsubscribed,properties:e.properties}}appendField(e,t,o){o!==null&&e.append(t,typeof o=="string"?o:JSON.stringify(o))}},Dp=class{constructor(e){this.resend=e}async list(e){if(!e.contactId&&!e.email)return{data:null,headers:null,error:{message:"Missing `id` or `email` field.",statusCode:null,name:"missing_required_field"}};let t=e.email?e.email:e.contactId,o=se(e),i=o?`/contacts/${t}/segments?${o}`:`/contacts/${t}/segments`;return await this.resend.get(i)}async add(e){if(!e.contactId&&!e.email)return{data:null,headers:null,error:{message:"Missing `id` or `email` field.",statusCode:null,name:"missing_required_field"}};let t=e.email?e.email:e.contactId;return this.resend.post(`/contacts/${t}/segments/${e.segmentId}`)}async remove(e){if(!e.contactId&&!e.email)return{data:null,headers:null,error:{message:"Missing `id` or `email` field.",statusCode:null,name:"missing_required_field"}};let t=e.email?e.email:e.contactId;return this.resend.delete(`/contacts/${t}/segments/${e.segmentId}`)}},Bp=class{constructor(e){this.resend=e}async update(e){if(!e.id&&!e.email)return{data:null,headers:null,error:{message:"Missing `id` or `email` field.",statusCode:null,name:"missing_required_field"}};let t=e.email?e.email:e.id;return this.resend.patch(`/contacts/${t}/topics`,e.topics)}async list(e){if(!e.id&&!e.email)return{data:null,headers:null,error:{message:"Missing `id` or `email` field.",statusCode:null,name:"missing_required_field"}};let t=e.email?e.email:e.id,o=se(e),i=o?`/contacts/${t}/topics?${o}`:`/contacts/${t}/topics`;return this.resend.get(i)}},Ep=class{constructor(e){this.resend=e,this.imports=new _p(this.resend),this.topics=new Bp(this.resend),this.segments=new Dp(this.resend)}async create(e,t={}){return"audienceId"in e?"segments"in e||"topics"in e?{data:null,headers:null,error:{message:"`audienceId` is deprecated, and cannot be used together with `segments` or `topics`. Use `segments` instead to add one or more segments to the new contact.",statusCode:null,name:"invalid_parameter"}}:await this.resend.post(`/audiences/${e.audienceId}/contacts`,{unsubscribed:e.unsubscribed,email:e.email,first_name:e.firstName,last_name:e.lastName,properties:e.properties},t):await this.resend.post("/contacts",{unsubscribed:e.unsubscribed,email:e.email,first_name:e.firstName,last_name:e.lastName,properties:e.properties,segments:e.segments,topics:e.topics},t)}async list(e={}){let t=e.segmentId??e.audienceId;if(!t){let r=se(e),n=r?`/contacts?${r}`:"/contacts";return await this.resend.get(n)}let o=se(e),i=o?`/segments/${t}/contacts?${o}`:`/segments/${t}/contacts`;return await this.resend.get(i)}async get(e){return typeof e=="string"?this.resend.get(`/contacts/${e}`):!e.id&&!e.email?{data:null,headers:null,error:{message:"Missing `id` or `email` field.",statusCode:null,name:"missing_required_field"}}:e.audienceId?this.resend.get(`/audiences/${e.audienceId}/contacts/${e?.email?e?.email:e?.id}`):this.resend.get(`/contacts/${e?.email?e?.email:e?.id}`)}async update(e){return!e.id&&!e.email?{data:null,headers:null,error:{message:"Missing `id` or `email` field.",statusCode:null,name:"missing_required_field"}}:e.audienceId?await this.resend.patch(`/audiences/${e.audienceId}/contacts/${e?.email?e?.email:e?.id}`,{unsubscribed:e.unsubscribed,first_name:e.firstName,last_name:e.lastName,properties:e.properties}):await this.resend.patch(`/contacts/${e?.email?e?.email:e?.id}`,{unsubscribed:e.unsubscribed,first_name:e.firstName,last_name:e.lastName,properties:e.properties})}async remove(e){return typeof e=="string"?this.resend.delete(`/contacts/${e}`):!e.id&&!e.email?{data:null,headers:null,error:{message:"Missing `id` or `email` field.",statusCode:null,name:"missing_required_field"}}:e.audienceId?this.resend.delete(`/audiences/${e.audienceId}/contacts/${e?.email?e?.email:e?.id}`):this.resend.delete(`/contacts/${e?.email?e?.email:e?.id}`)}};function Op(e){return{name:e.name,region:e.region,custom_return_path:e.customReturnPath,capabilities:e.capabilities,open_tracking:e.openTracking,click_tracking:e.clickTracking,tls:e.tls,tracking_subdomain:e.trackingSubdomain}}var Tp=class{constructor(e){this.resend=e}async create(e,t={}){return await this.resend.post("/domains/claim",{name:e.name,region:e.region,custom_return_path:e.customReturnPath,open_tracking:e.openTracking,click_tracking:e.clickTracking,tracking_subdomain:e.trackingSubdomain},t)}async get(e){return await this.resend.get(`/domains/${e}/claim`)}async verify(e){return await this.resend.post(`/domains/${e}/claim/verify`)}},jp=class{constructor(e){this.resend=e,this.claims=new Tp(this.resend)}async create(e,t={}){return await this.resend.post("/domains",Op(e),t)}async list(e={}){let t=se(e),o=t?`/domains?${t}`:"/domains";return await this.resend.get(o)}async get(e){return await this.resend.get(`/domains/${e}`)}async update(e){return await this.resend.patch(`/domains/${e.id}`,{click_tracking:e.clickTracking,open_tracking:e.openTracking,tls:e.tls,capabilities:e.capabilities,tracking_subdomain:e.trackingSubdomain})}async remove(e){return await this.resend.delete(`/domains/${e}`)}async verify(e){return await this.resend.post(`/domains/${e}/verify`)}},Ip=class{constructor(e){this.resend=e}async get(e){let{emailId:t,id:o}=e;return await this.resend.get(`/emails/${t}/attachments/${o}`)}async list(e){let{emailId:t}=e,o=se(e),i=o?`/emails/${t}/attachments?${o}`:`/emails/${t}/attachments`;return await this.resend.get(i)}},Pp=class{constructor(e){this.resend=e}async get(e){let{emailId:t,id:o}=e;return await this.resend.get(`/emails/receiving/${t}/attachments/${o}`)}async list(e){let{emailId:t}=e,o=se(e),i=o?`/emails/receiving/${t}/attachments?${o}`:`/emails/receiving/${t}/attachments`;return await this.resend.get(i)}},$p=class{constructor(e){this.resend=e,this.attachments=new Pp(e)}async get(e,t={}){let o=new URLSearchParams;t.html_format!==void 0&&o.set("html_format",t.html_format);let i=o.toString(),r=i?`/emails/receiving/${e}?${i}`:`/emails/receiving/${e}`;return await this.resend.get(r)}async list(e={}){let t=se(e),o=t?`/emails/receiving?${t}`:"/emails/receiving";return await this.resend.get(o)}async forward(e,t={}){let{emailId:o,to:i,from:r}=e,n=e.passthrough!==!1,s=await this.get(o);if(s.error)return{data:null,error:s.error,headers:s.headers};let a=s.data,l=a.subject||"(no subject)";if(n)return this.forwardPassthrough(a,{to:i,from:r,subject:l},t);let d=l.startsWith("Fwd:")?l:`Fwd: ${l}`;return this.forwardWrapped(a,{to:i,from:r,subject:d,text:"text"in e?e.text:void 0,html:"html"in e?e.html:void 0},t)}async forwardPassthrough(e,t,o){let{to:i,from:r,subject:n}=t;if(!e.raw?.download_url)return{data:null,error:{name:"validation_error",message:"Raw email content is not available for this email",statusCode:400},headers:null};let s=await fetch(e.raw.download_url);if(!s.ok)return{data:null,error:{name:"application_error",message:"Failed to download raw email content",statusCode:s.status},headers:null};let a=await s.text(),l=await oo.parse(a,{attachmentEncoding:"base64"}),d=l.attachments.map(c=>{let u=c.contentId?c.contentId.replace(/^<|>$/g,""):void 0;return{filename:c.filename,content:c.content.toString(),content_type:c.mimeType,content_id:u||void 0}});return await this.resend.post("/emails",{from:r,to:i,subject:n,text:l.text||void 0,html:l.html||void 0,attachments:d.length>0?d:void 0},o)}async forwardWrapped(e,t,o){let{to:i,from:r,subject:n,text:s,html:a}=t;if(!e.raw?.download_url)return{data:null,error:{name:"validation_error",message:"Raw email content is not available for this email",statusCode:400},headers:null};let l=await fetch(e.raw.download_url);if(!l.ok)return{data:null,error:{name:"application_error",message:"Failed to download raw email content",statusCode:l.status},headers:null};let d=await l.text();return await this.resend.post("/emails",{from:r,to:i,subject:n,text:s,html:a,attachments:[{filename:"forwarded_message.eml",content:Buffer.from(d).toString("base64"),content_type:"message/rfc822"}]},o)}},Hp=class{constructor(e){this.resend=e,this.attachments=new Ip(e),this.receiving=new $p(e)}async send(e,t={}){return this.create(e,t)}async create(e,t={}){let o={...e};return e.react&&(o.html=await ro(e.react)),await this.resend.post("/emails",ls(o),t)}async get(e){return await this.resend.get(`/emails/${e}`)}async list(e={}){let t=se(e),o=t?`/emails?${t}`:"/emails";return await this.resend.get(o)}async update(e){return await this.resend.patch(`/emails/${e.id}`,{scheduled_at:e.scheduledAt})}async cancel(e){return await this.resend.post(`/emails/${e}/cancel`)}},Gp=class{constructor(e){this.resend=e}async send(e){return await this.resend.post("/events/send",vp(e))}async create(e){return await this.resend.post("/events",e)}async get(e){return await this.resend.get(`/events/${encodeURIComponent(e)}`)}async list(e={}){let t=se(e),o=t?`/events?${t}`:"/events";return await this.resend.get(o)}async update(e,t){return await this.resend.patch(`/events/${encodeURIComponent(e)}`,t)}async remove(e){return await this.resend.delete(`/events/${encodeURIComponent(e)}`)}},Qp=class{constructor(e){this.resend=e}async list(e={}){let t=se(e),o=t?`/logs?${t}`:"/logs";return await this.resend.get(o)}async get(e){return await this.resend.get(`/logs/${e}`)}},Np=class{constructor(e){this.resend=e}async list(e={}){let t=se(e),o=t?`/oauth/grants?${t}`:"/oauth/grants";return await this.resend.get(o)}async revoke(e){return await this.resend.delete(`/oauth/grants/${e}`)}},qp=class{constructor(e){this.resend=e}async create(e,t={}){return await this.resend.post("/segments",e,t)}async list(e={}){let t=se(e),o=t?`/segments?${t}`:"/segments";return await this.resend.get(o)}async get(e){return await this.resend.get(`/segments/${e}`)}async remove(e){return await this.resend.delete(`/segments/${e}`)}},Mp=class{constructor(e){this.resend=e}async add(e){return this.resend.post("/suppressions/batch/add",e)}async remove(e){return this.resend.post("/suppressions/batch/remove",e)}},es=()=>({data:null,headers:null,error:{message:"Missing `id` field.",statusCode:null,name:"missing_required_field"}}),Lp=class{constructor(e){this.resend=e,this.batch=new Mp(e)}async add(e){return this.resend.post("/suppressions",e)}async list(e={}){let t=Wp(e),o=t?`/suppressions?${t}`:"/suppressions";return this.resend.get(o)}async get(e){return e?this.resend.get(`/suppressions/${encodeURIComponent(e)}`):es()}async remove(e){return e?this.resend.delete(`/suppressions/${encodeURIComponent(e)}`):es()}};function Wp(e){let{origin:t,...o}=e,i=new URLSearchParams(se(o));return t&&i.set("origin",t),i.toString()}function Jp(e={}){let t=new URLSearchParams;return e.before&&t.set("before",e.before),e.after&&t.set("after",e.after),e.limit&&t.set("limit",e.limit.toString()),t.size>0?`?${t.toString()}`:""}function Vp(e){return e?.map(t=>({key:t.key,type:t.type,fallback_value:t.fallbackValue}))}function ts(e){return{name:"name"in e?e.name:void 0,subject:e.subject,html:e.html,text:e.text,alias:e.alias,from:e.from,reply_to:e.replyTo,variables:Vp(e.variables)}}var os=class{constructor(e,t){this.promise=e,this.publishFn=t}then(e,t){return this.promise.then(e,t)}async publish(){let{data:e,error:t}=await this.promise;return t?{data:null,headers:null,error:t}:this.publishFn(e.id)}},zp=class{constructor(e){this.resend=e}create(e){return new os(this.performCreate(e),this.publish.bind(this))}async performCreate(e){let t={...e};return e.react&&(t.html=await ro(e.react)),this.resend.post("/templates",ts(t))}async remove(e){return await this.resend.delete(`/templates/${e}`)}async get(e){return await this.resend.get(`/templates/${e}`)}async list(e={}){return this.resend.get(`/templates${Jp(e)}`)}duplicate(e){return new os(this.resend.post(`/templates/${e}/duplicate`),this.publish.bind(this))}async publish(e){return await this.resend.post(`/templates/${e}/publish`)}async update(e,t){return await this.resend.patch(`/templates/${e}`,ts(t))}},Yp=class{constructor(e){this.resend=e}async create(e){let{defaultSubscription:t,...o}=e;return await this.resend.post("/topics",{...o,default_subscription:t})}async list(){return await this.resend.get("/topics")}async get(e){return e?await this.resend.get(`/topics/${e}`):{data:null,headers:null,error:{message:"Missing `id` field.",statusCode:null,name:"missing_required_field"}}}async update(e){return e.id?await this.resend.patch(`/topics/${e.id}`,e):{data:null,headers:null,error:{message:"Missing `id` field.",statusCode:null,name:"missing_required_field"}}}async remove(e){return e?await this.resend.delete(`/topics/${e}`):{data:null,headers:null,error:{message:"Missing `id` field.",statusCode:null,name:"missing_required_field"}}}},Xp=class{constructor(e){this.resend=e}async create(e,t={}){return await this.resend.post("/webhooks",e,t)}async get(e){return await this.resend.get(`/webhooks/${e}`)}async list(e={}){let t=se(e),o=t?`/webhooks?${t}`:"/webhooks";return await this.resend.get(o)}async update(e,t){return await this.resend.patch(`/webhooks/${e}`,t)}async remove(e){return await this.resend.delete(`/webhooks/${e}`)}verify(e){return new ns.Webhook(e.webhookSecret).verify(e.payload,{"webhook-id":e.headers.id,"webhook-timestamp":e.headers.timestamp,"webhook-signature":e.headers.signature})}},is="https://api.resend.com",rs=`resend-node:${yp}`;function Zp(){return typeof process<"u"&&process.env&&process.env.RESEND_BASE_URL||is}function em(){return typeof process<"u"&&process.env&&process.env.RESEND_USER_AGENT||rs}var kt=class{constructor(e,t){if(this.key=e,this.segments=new qp(this),this.apiKeys=new Up(this),this.audiences=this.segments,this.automations=new wp(this),this.batch=new Fp(this),this.broadcasts=new kp(this),this.contactProperties=new Rp(this),this.contacts=new Ep(this),this.domains=new jp(this),this.emails=new Hp(this),this.events=new Gp(this),this.logs=new Qp(this),this.oauthGrants=new Np(this),this.suppressions=new Lp(this),this.templates=new zp(this),this.topics=new Yp(this),this.webhooks=new Xp(this),!e&&(typeof process<"u"&&process.env&&(this.key=process.env.RESEND_API_KEY),!this.key))throw new Error('Missing API key. Pass it to the constructor `new Resend("re_123")`');this.baseUrl=t?.baseUrl??Zp(),this.userAgent=t?.userAgent??em(),this.headers=new Headers({Authorization:`Bearer ${this.key}`,"User-Agent":this.userAgent,"Content-Type":"application/json"})}logError(e,t,o){typeof process<"u"&&process.env&&process.env.NODE_ENV!=="production"&&console.error("[Resend API Error]:",{...o!==void 0&&{status:o},error:e,path:t})}async fetchRequest(e,t={}){try{let o=await fetch(`${this.baseUrl}${e}`,t);if(!o.ok)try{let i=await o.text(),r=JSON.parse(i);return this.logError(r,e,o.status),{data:null,error:r,headers:Object.fromEntries(o.headers.entries())}}catch(i){if(i instanceof SyntaxError){let n={name:"application_error",statusCode:o.status,message:"Internal server error. We are unable to process your request right now, please try again later."};return this.logError(n,e,o.status),{data:null,error:n,headers:Object.fromEntries(o.headers.entries())}}let r={message:o.statusText,statusCode:o.status,name:"application_error"};if(i instanceof Error){let n={...r,message:i.message};return this.logError(n,e,o.status),{data:null,error:n,headers:Object.fromEntries(o.headers.entries())}}return this.logError(r,e,o.status),{data:null,error:r,headers:Object.fromEntries(o.headers.entries())}}return{data:await o.json(),error:null,headers:Object.fromEntries(o.headers.entries())}}catch{let o={name:"application_error",statusCode:null,message:"Unable to fetch data. The request could not be resolved."};return this.logError(o,e),{data:null,error:o,headers:null}}}async post(e,t,o={}){let i=new Headers(this.headers),r=typeof FormData<"u"&&t instanceof FormData;if(r&&i.delete("Content-Type"),o.headers)for(let[s,a]of new Headers(o.headers).entries())i.set(s,a);o.idempotencyKey&&i.set("Idempotency-Key",o.idempotencyKey);let n={method:"POST",body:r?t:JSON.stringify(t),...o,headers:i};return this.fetchRequest(e,n)}async get(e,t={}){let o=new Headers(this.headers);if(t.headers)for(let[r,n]of new Headers(t.headers).entries())o.set(r,n);let i={method:"GET",...t,headers:o};return this.fetchRequest(e,i)}async put(e,t,o={}){let i=new Headers(this.headers);if(o.headers)for(let[n,s]of new Headers(o.headers).entries())i.set(n,s);let r={method:"PUT",body:JSON.stringify(t),...o,headers:i};return this.fetchRequest(e,r)}async patch(e,t,o={}){let i=new Headers(this.headers);if(o.headers)for(let[n,s]of new Headers(o.headers).entries())i.set(n,s);let r={method:"PATCH",body:JSON.stringify(t),...o,headers:i};return this.fetchRequest(e,r)}async delete(e,t,o={}){let i=new Headers(this.headers);if(o.headers)for(let[n,s]of new Headers(o.headers).entries())i.set(n,s);let r={method:"DELETE",body:t===void 0?void 0:JSON.stringify(t),...o,headers:i};return this.fetchRequest(e,r)}};he();var br=ue(qe(),1);function q(e,t){return e instanceof Error?e.message:t}function Qs(e){return!!(e||!process.stdout.isTTY)}function E(e,t={}){Qs(t.json)?console.log(JSON.stringify(e,null,2)):console.log(typeof e=="string"?e:JSON.stringify(e,null,2)),t.exitCode!==void 0&&process.exit(t.exitCode)}var fm=new Set(["content-type","retry-after"]);function gm(e){let t={};for(let[o,i]of Object.entries(e)){let r=o.toLowerCase();(fm.has(r)||r.startsWith("x-"))&&(t[r]=i)}return t}function g(e,t={}){let o=t.exitCode??1,i=e.headers&&Object.keys(e.headers).length>0?gm(e.headers):void 0,r=i!==void 0&&Object.keys(i).length>0;if(Qs(t.json)){let n={message:e.message,code:e.code??"unknown"};typeof e.statusCode=="number"&&(n.statusCode=e.statusCode),r&&(n.headers=i),typeof e.body=="string"&&e.body.length>0&&(n.body=e.body),console.error(JSON.stringify({error:n},null,2))}else{console.error(`${br.default.red("Error:")} ${e.message}`);let n=[];if(typeof e.statusCode=="number"&&n.push(`HTTP ${e.statusCode}`),r)for(let[s,a]of Object.entries(i))n.push(`${s}: ${a}`);n.length>0&&console.error(br.default.dim(`[${n.join("; ")}]`))}process.exit(o)}var Ns={sending_access:0,full_access:1};function hm(e,t){return Ns[e]>=Ns[t]}async function Y(e,t){let o=e.profile;try{let i=await St(e.apiKey,o);if(!i){if(o){let s=ve();if(!s.some(l=>l.name===o))throw new Error(`Profile "${o}" not found. Available profiles: ${s.map(l=>l.name).join(", ")||"(none)"}`)}throw new Error("No API key found. Set RESEND_API_KEY, use --api-key, or run: resend login")}let r;if(i.type==="api_key")r=i.permission;else{let s=i.scope.split(" ").filter(Boolean);s.includes("full_access")?r="full_access":s.includes("emails:send")?r="sending_access":g({message:`Unrecognized credential scope${i.scope?` "${i.scope}"`:""}. Run \`resend login\` to re-authenticate.`,code:"unrecognized_scope"},{json:e.json})}if(r){let s=t?.permission??"full_access";hm(r,s)||g({message:`This command requires full access. Your current credential has sending access only.
|
|
269
|
+
${_t}`,code:"insufficient_permissions"},{json:e.json})}let n=i.type==="api_key"?i.key:i.access_token;return new kt(n)}catch(i){g({message:q(i,"Failed to create client"),code:"auth_error"},{json:e.json})}}var qs=130;function Am(){process.stderr.isTTY&&process.stderr.write("\r\x1B[2K"),console.error("Cancelled."),process.exit(qs)}var Dt;function Ms(){Dt=Am,process.on("SIGINT",Dt),process.on("uncaughtException",e=>{g({message:q(e,"An unexpected error occurred"),code:"unexpected_error"},{}),process.exit(1)})}function Lo(e){Dt&&process.removeListener("SIGINT",Dt),Dt=e,process.on("SIGINT",Dt)}function Bt(){return qs}he();var Wo=ue(qe(),1);J();var Ls=[1,2,4],bm=Ls.length,Cm=new Set(["internal_server_error","service_unavailable","gateway_timeout"]),ym=(e,t)=>!!(e==="rate_limit_exceeded"||t&&e!==void 0&&Cm.has(e)),Um=e=>{let t=e?.["retry-after"];if(!t)return;let o=Number(t);if(Number.isFinite(o)&&o>=0)return o;let i=Date.parse(t);if(!Number.isNaN(i)){let r=(i-Date.now())/1e3;return r>0?r:0}},Sm=e=>new Promise(t=>setTimeout(t,e)),lo=async(e,t,o=0)=>{let i=await e(),r=t?.retryTransient??!1;if(i.error&&o<bm&&ym(i.error.name,r)){let n=Um(i.headers)??Ls[o];return t?.onRetry?.(o,n,i.error.name??""),await Sm(n*1e3),lo(e,t,o+1)}return i};var Ws=(e,t)=>new Promise((o,i)=>{let r=setTimeout(()=>{i(new Error(`Request timed out after ${t/1e3}s`))},t);r.unref(),e.then(n=>{clearTimeout(r),o(n)},n=>{clearTimeout(r),i(n)})});var vm=et?String.fromCodePoint(10004):"v",wm=et?String.fromCodePoint(9888):"!",xm=et?String.fromCodePoint(10007):"x",Fm=["\u2839","\u2838","\u2834","\u2826","\u2807","\u280F","\u2819","\u2839"],km=80;async function de(e,t,o,i,r={}){let n=ne(e,i.quiet);try{let{data:s,error:a,headers:l}=await lo(()=>Ws(t(),3e4),{retryTransient:r.retryTransient,onRetry:(d,c,u)=>{n.update(u==="rate_limit_exceeded"?`Rate limited, retrying in ${c}s...`:`Server error, retrying in ${c}s...`)}});return a&&(n.stop(),g({message:a.message,code:o,statusCode:a.statusCode,headers:l},{json:i.json})),s===null&&(n.stop(),g({message:"Unexpected empty response",code:o,headers:l},{json:i.json})),n.stop(),s}catch(s){return n.stop(),g({message:q(s,"Unknown error"),code:o},{json:i.json})}}function ne(e,t){if(t||!U())return{update(a){},stop(a){},clear(){},warn(a){},fail(a){}};let o=et?Fm:["-","\\","|","/"],i=km,r=0,n=e,s=setInterval(()=>{process.stderr.write(`\r\x1B[2K ${o[r++%o.length]} ${n}`)},i);return{update(a){n=a},stop(a){clearInterval(s),a?process.stderr.write(`\r\x1B[2K ${Wo.default.green(vm)} ${a}
|
|
270
270
|
`):process.stderr.write("\r\x1B[2K")},clear(){clearInterval(s),process.stderr.write("\r\x1B[2K")},warn(a){clearInterval(s),process.stderr.write(`\r\x1B[2K ${Wo.default.yellow(wm)} ${a}
|
|
271
271
|
`)},fail(a){clearInterval(s),process.stderr.write(`\r\x1B[2K ${Wo.default.red(xm)} ${a}
|
|
272
|
-
`)}}}J();function R(e){Fn(e),process.exit(
|
|
272
|
+
`)}}}J();function R(e){Fn(e),process.exit(Bt())}async function Jo(e,t,o){(!U()||o.json)&&g({message:"Use --yes to confirm deletion in non-interactive mode.",code:"confirmation_required"},{json:o.json});let i=await rt({message:t});(x(i)||!i)&&R("Deletion cancelled.")}async function Vo(e,t){let o=le(e);if(!o)return e;if(!U()||t.json)return g({message:`Profile "${e}" has an invalid name: ${o}`,code:"invalid_profile_name"},{json:t.json}),null;X.warn(`Profile "${e}" has an invalid name: ${o}`);let i=await Z({message:"Enter a new name for this profile:",placeholder:e.replace(/[^a-zA-Z0-9._-]/g,"-"),validate:r=>le(r)});x(i)&&R("Rename cancelled.");try{await Mo(e,i)}catch(r){return g({message:q(r,"Failed to rename profile"),code:"rename_failed"},{json:t.json}),null}return X.success(`Profile renamed to '${i}'.`),i}async function O(e,t,o,i){if(e!==void 0)return e;(!U()||i.json)&&g(o,{json:i.json});let r=await Z({message:t.message,placeholder:t.placeholder,defaultValue:t.defaultValue,validate:t.validate??(n=>!t.defaultValue&&(!n||n.length===0)?`${t.message} is required`:void 0)});return x(r)&&R("Cancelled."),r}async function Et(e,t,o,i){if(e!==void 0)return e;(!U()||i.json)&&g(o,{json:i.json});let r=await ce({message:t.message,options:t.options});return x(r)&&R("Cancelled."),r}async function zs(e,t,o){let i=t.filter(s=>s.required!==!1&&e[s.flag]==="");if(i.length>0){let s=i.map(a=>`--${a.flag}`).join(", ");g({message:`Empty value for required flags: ${s}`,code:"invalid_options"},{json:o.json})}let r=t.filter(s=>s.required!==!1&&!e[s.flag]);if(r.length===0)return e;if(!U()||o.json){let s=r.map(a=>`--${a.flag}`).join(", ");g({message:`Missing required flags: ${s}`,code:"missing_flags"},{json:o.json})}let n=await xn(Object.fromEntries(r.map(s=>[s.flag,()=>Z({message:s.message,placeholder:s.placeholder,defaultValue:s.defaultValue,validate:s.validate??(a=>!s.defaultValue&&(!a||a.length===0)?`${s.message} is required`:void 0)})])),{onCancel:()=>R("Operation cancelled.")});return{...e,...n}}var Rm=20,Js="__fetch_more__",Vs="__none__";async function te(e,t,o,i){if(e)return{id:e,label:e};let r=i?.optional??!1;if(!U()||o.json){if(r)return;g({message:"Missing required argument: id",code:"missing_id"},{json:o.json})}let n=await Y(o),s=[];for(;;){let a=s.at(-1)?.id,l=ne(s.length===0?`Fetching ${t.resourcePlural}...`:`Fetching more ${t.resourcePlural}...`,o.quiet),d=await t.fetchItems(n,{limit:Rm,...a&&{after:a}});if(d.error||!d.data){if(r){l.clear();return}l.fail(`Failed to fetch ${t.resourcePlural}`),g({message:d.error?.message??"Unexpected empty response",code:"list_error"},{json:o.json})}s.push(...d.data.data);let c=d.data.has_more??!1,u=t.filter?s.filter(t.filter):s;if(u.length===0&&!c&&r){l.clear();return}if(l.stop(s.length===u.length?`${t.resourcePlural} fetched`:`More ${t.resourcePlural} fetched`),u.length===0&&!c&&(X.warn(`No ${t.resourcePlural} found.`),g({message:`No ${t.resourcePlural} found.`,code:"no_items"},{json:o.json})),u.length===0&&c&&!r)continue;let f=u.map(b=>({item:b,...t.display(b)})),A=f.map(({item:b,label:S,hint:v})=>({value:b.id,label:S,hint:v}));r&&A.unshift({value:Vs,label:"None"}),c&&A.push({value:Js,label:"Fetch more..."});let h=await ce({message:`Select a ${t.resource}`,options:A});if(x(h)&&R("Cancelled."),h===Vs)return;if(h!==Js){let b=f.find(({item:S})=>S.id===h);return{id:h,label:b?.label??h}}}}async function y(e,t,o,i){return(await te(e,t,o,i))?.id}var Ys=require("node:util"),_m=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]|\r(?!\n)/g,we=e=>(0,Ys.stripVTControlCharacters)(String(e)).replace(_m,"");function Ot(e){return typeof e=="string"?we(e):Array.isArray(e)?e.map(Ot):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,o])=>[t,Ot(o)])):e}J();async function Q(e,t){let o=e.permission?{permission:e.permission}:void 0,i=await Y(t,o),r=await de(e.loading,()=>e.sdkCall(i),"fetch_error",t,{retryTransient:!0});!t.json&&U()?e.onInteractive(Ot(r)):E(r,{json:t.json})}async function ee(e,t,o,i){let r=o.permission?{permission:o.permission}:void 0,n=await Y(i,r);t||await Jo(e,o.confirmMessage,i),await de(o.loading,()=>o.sdkCall(n),"delete_error",i),!i.json&&U()?console.log(o.successMsg):E({object:o.object,id:e,deleted:!0},{json:i.json})}async function L(e,t){let o=e.permission?{permission:e.permission}:void 0,i=await Y(t,o),r=await de(e.loading,()=>e.sdkCall(i),"create_error",t);!t.json&&U()?e.onInteractive(Ot(r)):E(r,{json:t.json})}async function I(e,t){let o=e.permission?{permission:e.permission}:void 0,i=await Y(t,o),r=await de(e.loading,()=>e.sdkCall(i),e.errorCode,t,{retryTransient:e.retryTransient});!t.json&&U()?console.log(e.successMsg):E(r,{json:t.json})}async function _(e,t){let o=e.permission?{permission:e.permission}:void 0,i=await Y(t,o),r=await de(e.loading,()=>e.sdkCall(i),"list_error",t,{retryTransient:!0});!t.json&&U()?e.onInteractive(Ot(r)):E(r,{json:t.json})}J();J();var pe=et?{h:String.fromCodePoint(9472),v:String.fromCodePoint(9474),tl:String.fromCodePoint(9484),tr:String.fromCodePoint(9488),bl:String.fromCodePoint(9492),br:String.fromCodePoint(9496),lm:String.fromCodePoint(9500),rm:String.fromCodePoint(9508),tm:String.fromCodePoint(9516),bm:String.fromCodePoint(9524),mm:String.fromCodePoint(9532)}:{h:"-",v:"|",tl:"+",tr:"+",bl:"+",br:"+",lm:"+",rm:"+",tm:"+",bm:"+",mm:"+"};function Dm(){return process.stdout.columns}function Bm(e,t,o){let i=Math.max(...e.map(n=>n.length)),r=Math.max(20,Math.min(o,60));return t.map((n,s)=>{let a=String(s+1),l=`${pe.h}${pe.h} ${a} ${pe.h.repeat(Math.max(0,r-a.length-4))}`,d=e.map((c,u)=>` ${c.padEnd(i)} ${n[u]}`);return[l,...d].join(`
|
|
273
273
|
`)}).join(`
|
|
274
274
|
|
|
275
|
-
`)}function
|
|
275
|
+
`)}function B(e,t,o="(no results)"){if(t.length===0)return o;let i=t.map(c=>c.map(we)),r=e.map((c,u)=>Math.max(c.length,...i.map(f=>f[u].length))),n=Dm();if(n!==void 0&&r.reduce((u,f)=>u+f,0)+3*r.length+1>n)return Bm(e,i,n);let s=pe.tl+r.map(c=>pe.h.repeat(c+2)).join(pe.tm)+pe.tr,a=pe.lm+r.map(c=>pe.h.repeat(c+2)).join(pe.mm)+pe.rm,l=pe.bl+r.map(c=>pe.h.repeat(c+2)).join(pe.bm)+pe.br,d=c=>pe.v+" "+c.map((u,f)=>u.padEnd(r[f])).join(` ${pe.v} `)+" "+pe.v;return[s,d(e),a,...i.map(d),l].join(`
|
|
276
276
|
`)}J();var Cr=et?String.fromCodePoint(9472):"-";function zo(e,t){return e.length===0?"(no DNS records)":e.map(i=>{let r=i.name?i.name.includes(".")?i.name:`${i.name}.${t}`:t;return[`${Cr}${Cr} ${i.type} ${Cr.repeat(40)}`,` Name ${r}`,` TTL ${i.ttl}`,` Value ${i.value}`].join(`
|
|
277
277
|
`)}).join(`
|
|
278
278
|
|
|
279
|
-
`)}function Xs(e){let t=e.map(o=>[o.name,o.status,o.region,o.id]);return
|
|
279
|
+
`)}function Xs(e){let t=e.map(o=>[o.name,o.status,o.region,o.id]);return B(["Name","Status","Region","ID"],t,"(no domains)")}function Zs(e){switch(e){case"verified":return"\u2713 Verified";case"pending":return"\u23F3 Pending";case"not_started":return"\u25CB Not started";case"partially_verified":return"\u25D0 Partially verified";case"partially_failed":return"\u25D0 Partially failed";case"failed":case"temporary_failure":return"\u2717 Failed";default:return e}}var ke={resource:"domain",resourcePlural:"domains",fetchItems:(e,{limit:t,after:o})=>e.domains.list({limit:t,...o&&{after:o}}),display:e=>({label:e.name,hint:e.id})};var ea=new p("create").description("Create a new API key and display the token (shown once \u2014 store it immediately)").option("--name <name>","API key name (max 50 characters)").addOption(new V("--permission <permission>","Permission level").choices(["full_access","sending_access"])).option("--domain-id <id>","Restrict a sending_access key to a single domain ID").addHelpText("after",m({context:`Non-interactive: --name is required (no prompts when stdin/stdout is not a TTY).
|
|
280
280
|
|
|
281
281
|
Permissions:
|
|
282
282
|
full_access Full API access (default)
|
|
283
283
|
sending_access Send-only access; optionally scope to a domain with --domain-id`,output:` {"id":"<id>","token":"<token>"}
|
|
284
284
|
The token is only returned at creation time and cannot be retrieved again.`,errorCodes:["auth_error","missing_name","invalid_flags","create_error"],examples:['resend api-keys create --name "Production"','resend api-keys create --name "CI Token" --permission sending_access','resend api-keys create --name "Domain Token" --permission sending_access --domain-id <domain-id>','resend api-keys create --name "Production" --json']})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=e.name,r=e.permission;if(!i){(!U()||o.json)&&g({message:"Missing --name flag.",code:"missing_name"},{json:o.json});let s=await Z({message:"Key name",placeholder:"e.g. My API Key",validate:l=>{if(!l)return"Name is required";if(l.length>50)return"Name must be 50 characters or less"}});x(s)&&R("Cancelled."),i=s;let a=await ce({message:"Permission level",options:[{value:"full_access",label:"Full access"},{value:"sending_access",label:"Sending access only"}]});x(a)&&R("Cancelled."),r=a}let n=e.domainId;n!==void 0&&r!=="sending_access"&&g({message:"--domain-id requires --permission sending_access",code:"invalid_flags"},{json:o.json}),!n&&r==="sending_access"&&(n=await y(void 0,ke,o,{optional:!0})),await L({loading:"Creating API key...",sdkCall:s=>s.apiKeys.create({name:i,...r&&{permission:r},...n&&{domain_id:n}}),onInteractive:s=>{console.log(` ${co.default.gray("Name:")} ${i}`),console.log(` ${co.default.gray("ID:")} ${s.id}`),console.log(` ${co.default.gray("Token:")} ${s.token}`),console.log(`
|
|
285
|
-
${co.default.yellow("\u26A0")} Store this token now \u2014 it cannot be retrieved again.`)}},o)});var ta={resource:"API key",resourcePlural:"API keys",fetchItems:(e,{limit:t,after:o})=>e.apiKeys.list({limit:t,...o&&{after:o}}),display:e=>({label:e.name,hint:e.id})};function oa(e){let t=e.map(o=>[o.name,o.id,o.created_at,o.last_used_at??""]);return
|
|
285
|
+
${co.default.yellow("\u26A0")} Store this token now \u2014 it cannot be retrieved again.`)}},o)});var ta={resource:"API key",resourcePlural:"API keys",fetchItems:(e,{limit:t,after:o})=>e.apiKeys.list({limit:t,...o&&{after:o}}),display:e=>({label:e.name,hint:e.id})};function oa(e){let t=e.map(o=>[o.name,o.id,o.created_at,o.last_used_at??""]);return B(["Name","ID","Created","Last used"],t,"(no API keys)")}var ia=new p("delete").alias("rm").description("Delete an API key \u2014 any services using it will immediately lose access").argument("[id]","API key ID").option("--yes","Skip confirmation prompt").addHelpText("after",m({context:`Non-interactive: --yes is required to confirm deletion when stdin/stdout is not a TTY.
|
|
286
286
|
|
|
287
287
|
Warning: Deleting a key is immediate and irreversible. Any service using this key
|
|
288
288
|
will stop authenticating instantly. The current key (used to call this command)
|
|
@@ -294,16 +294,16 @@ $ resend ${t} ${n} ${r}${s}${d}${a}${l}`)}var ra=new p("list").alias("ls").descr
|
|
|
294
294
|
Tokens are never included in list responses.`,errorCodes:["auth_error","invalid_limit","list_error"],examples:["resend api-keys list","resend api-keys list --limit 25 --json","resend api-keys list --after <cursor> --json"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=P(e.limit,o),r=$(i,e.after,e.before,o);await _({loading:"Fetching API keys...",sdkCall:n=>n.apiKeys.list(r),onInteractive:n=>{console.log(oa(n.data)),H(n,"api-keys list",{limit:i,before:e.before,apiKey:o.apiKey,profile:o.profile})}},o)});var na=new p("api-keys").description("Manage API keys for authentication").addHelpText("after",m({context:`Security notes:
|
|
295
295
|
- Tokens are only shown at creation time and cannot be retrieved again.
|
|
296
296
|
- Use sending_access keys with --domain-id for per-domain CI tokens.
|
|
297
|
-
- Deleting a key is immediate \u2014 any service using it loses access instantly.`,examples:["resend api-keys list",'resend api-keys create --name "Production"','resend api-keys create --name "CI Token" --permission sending_access --domain-id <domain-id>',"resend api-keys delete <id> --yes"]})).addCommand(ea).addCommand(ra,{isDefault:!0}).addCommand(ia);he();J();function
|
|
297
|
+
- Deleting a key is immediate \u2014 any service using it loses access instantly.`,examples:["resend api-keys list",'resend api-keys create --name "Production"','resend api-keys create --name "CI Token" --permission sending_access --domain-id <domain-id>',"resend api-keys delete <id> --yes"]})).addCommand(ea).addCommand(ra,{isDefault:!0}).addCommand(ia);he();J();function Em(e){let t=ve();if(e.json){E({profiles:t},{json:!0});return}if(t.length===0){console.log("No profiles configured. Run: resend login");return}U()&&console.log(`
|
|
298
298
|
Profiles
|
|
299
|
-
`);let o=!1;for(let i of t){let r=i.active?" (active)":"",n=le(i.name)!==void 0;n&&(o=!0),console.log(` ${i.active?"\u25B8":" "} ${i.name}${r}${n?" (invalid name)":""}`)}o&&U()&&console.log("\n Profiles with invalid names can be renamed via `resend auth rename`."),U()&&console.log("")}var sa=new p("list").description("List all profiles").action((e,t)=>{
|
|
300
|
-
${d.toString()}`);let u=ne("Waiting for browser authentication...",e.quiet),f;try{f=await s}catch(w){u.fail("Authentication failed"),g({message:q(w,"Authentication failed"),code:"oauth_error"},{json:e.json})}f.state!==i&&(u.fail("Authentication failed"),g({message:"State mismatch in OAuth callback. Possible CSRF attack.",code:"oauth_state_mismatch"},{json:e.json})),u.stop("Browser authentication complete");let
|
|
301
|
-
${_t}`),c==="browser"&&(await Yo(yr)?X.info(`Opened ${yr}`):X.warn(`Could not open browser. Visit ${yr} manually.`));let u=await _n({message:"Enter your Resend API key:",validate:f=>{if(!f)return"API key is required";if(!f.startsWith("re_"))return"API key must start with re_"}});x(u)&&R("Login cancelled."),i=u.trim()}(!i||!i.startsWith("re_"))&&g({message:"Invalid API key format. Key must start with re_",code:"invalid_key_format"},{json:o.json});let r=ne("Validating API key...",o.quiet),n="full_access";try{let c=new kt(i),{error:u}=await c.domains.list();if(u){let f=u;f.name==="restricted_api_key"?(n="sending_access",r.warn("API key is valid (sending access only)")):(r.fail("API key validation failed"),g({message:f.message||"Failed to validate API key",code:"validation_failed"},{json:o.json}))}else r.stop("API key is valid (full access)")}catch(c){r.fail("API key validation failed"),g({message:q(c,"Failed to validate API key"),code:"validation_failed"},{json:o.json})}let s=await la(o,"Save API key to which profile?"),{configPath:a,backend:l}=await Hs(i,s,n),d=s||"default";if(s)try{ao(d)}catch(c){g({message:q(c,"Failed to switch profile"),code:"switch_failed"},{json:o.json})}o.json?
|
|
299
|
+
`);let o=!1;for(let i of t){let r=i.active?" (active)":"",n=le(i.name)!==void 0;n&&(o=!0),console.log(` ${i.active?"\u25B8":" "} ${i.name}${r}${n?" (invalid name)":""}`)}o&&U()&&console.log("\n Profiles with invalid names can be renamed via `resend auth rename`."),U()&&console.log("")}var sa=new p("list").description("List all profiles").action((e,t)=>{Em(t.optsWithGlobals())});var aa=require("node:child_process"),uo=ue(qe(),1),Qe="https://resend.com";function Yo(e){return new Promise(t=>{let o=process.platform==="win32"?"cmd.exe":process.platform==="darwin"?"open":"xdg-open",i=e.replaceAll('"',""),r=process.platform==="win32"?["/c","start",'""',`"${i}"`]:[e];(0,aa.execFile)(o,r,{timeout:5e3,windowsVerbatimArguments:!0},n=>t(!n))})}async function Re(e,t){let o=await Yo(e);t?.json||t?.quiet||(o?console.log(uo.default.dim("Opened"),uo.default.blue(e)):console.warn(uo.default.yellow("Could not open browser. Visit this link:"),uo.default.blue(e)))}var me={emails:`${Qe}/emails`,logs:`${Qe}/logs`,log:e=>`${Qe}/logs/${e}`,templates:`${Qe}/templates`,template:e=>`${Qe}/templates/${e}`,broadcasts:`${Qe}/broadcasts`,broadcast:e=>`${Qe}/broadcasts/${e}`,documentation:`${Qe}/docs`,automations:`${Qe}/automations`,automation:e=>`${Qe}/automations/${e}/editor`,events:`${Qe}/automations/events`};he();Go();J();var yr="https://resend.com/api-keys?new=true";async function la(e,t){let o=e.profile!==void 0?e.profile.trim():void 0;if(o!==void 0){let r=le(o);return r&&g({message:r,code:"invalid_profile_name"},{json:e.json}),o}if(!U()||e.json)return o;let i=ve();if(i.length>0){let r=[...i.map(s=>({value:s.name,label:`${s.name} (overwrite)`,hint:le(s.name)?"invalid name":void 0})),{value:"__new__",label:"+ Create new profile"}],n=await ce({message:t,options:r});if(x(n)&&R("Login cancelled."),n==="__new__"){let s=await Z({message:"Enter a name for the new profile:",validate:l=>le((l??"").trim())});if(x(s)&&R("Login cancelled."),o=(s??"").trim()||"default",i.some(l=>l.name===o)){let l=await rt({message:`Profile '${o}' already exists. Overwrite?`});(x(l)||!l)&&R("Login cancelled.")}}else if(le(n)){let s=await Vo(n,e);if(!s)return;o=s}else o=n}else o="default";return o}function ca(e){let{noun:t,profileLabel:o,configPath:i,backend:r}=e,n=r.isSecure?`in ${r.name}`:`at ${i}`,s=`${t} stored for profile '${o}' ${n}`;if(U()?Ro(s):console.log(s),!r.isSecure&&process.platform==="linux"){let a="Tip: Install libsecret-tools and a Secret Service provider (e.g. gnome-keyring) to store credentials in secure storage instead of a plaintext file.";U()?X.info(a):console.log(a)}}async function Om(e){let{codeVerifier:t,codeChallenge:o,state:i}=_s(),r=ne("Starting local callback server...",e.quiet),n,s;try{({port:n,waitForCallback:s}=await Ds()),r.stop("")}catch(w){r.fail("Failed to start callback server"),g({message:q(w,"Failed to start callback server"),code:"oauth_error"},{json:e.json})}let a=`http://127.0.0.1:${n}/oauth/callback`,l=process.env.RESEND_BASE_URL??"https://api.resend.com",d=new URL(`${l}/oauth/authorize`);d.search=new URLSearchParams({client_id:Ho,response_type:"code",redirect_uri:a,scope:"full_access",state:i,code_challenge:o,code_challenge_method:"S256"}).toString(),await Yo(d.toString())?X.info("Browser opened. Complete authentication to continue."):X.warn(`Could not open browser. Visit this URL to authenticate:
|
|
300
|
+
${d.toString()}`);let u=ne("Waiting for browser authentication...",e.quiet),f;try{f=await s}catch(w){u.fail("Authentication failed"),g({message:q(w,"Authentication failed"),code:"oauth_error"},{json:e.json})}f.state!==i&&(u.fail("Authentication failed"),g({message:"State mismatch in OAuth callback. Possible CSRF attack.",code:"oauth_state_mismatch"},{json:e.json})),u.stop("Browser authentication complete");let A=ne("Exchanging authorization code...",e.quiet),h;try{h=await Bs({code:f.code,codeVerifier:t,redirectUri:a,clientId:Ho,baseUrl:l})}catch(w){A.fail("Token exchange failed"),g({message:q(w,"Token exchange failed"),code:"oauth_error"},{json:e.json})}A.stop("Authenticated successfully");let b=await la(e,"Save credentials to which profile?"),S=b||"default",{configPath:v,backend:K}=await Qo({access_token:h.access_token,access_token_expires_at:fr(h.access_token),refresh_token:h.refresh_token,scope:h.scope},b);if(b)try{ao(S)}catch(w){g({message:q(w,"Failed to switch profile"),code:"switch_failed"},{json:e.json})}e.json?E({success:!0,config_path:v,profile:S,storage:K.name,scope:h.scope},{json:!0}):ca({noun:"Credentials",profileLabel:S,configPath:v,backend:K})}var Xo=new p("login").description("Save a Resend API key").option("--key <key>","API key to store (required in non-interactive mode)").addHelpText("after",m({setup:!0,context:"Non-interactive: --key is required (no prompts will appear when stdin/stdout is not a TTY).",output:' {"success":true,"config_path":"<path>","profile":"<name>"}',errorCodes:["missing_key","invalid_key_format","validation_failed","invalid_profile_name","switch_failed","write_failed","oauth_error","oauth_state_mismatch"],examples:["resend login --key re_123456789","resend login (interactive \u2014 prompts and opens browser)","RESEND_API_KEY=re_123 resend emails send ... (skip login; use env var directly)"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=typeof e.key=="string"?e.key.trim():e.key;if(!i){(!U()||o.json)&&g({message:"Missing --key flag. Provide your API key in non-interactive mode.",code:"missing_key"},{json:o.json}),kn("Resend Authentication");let c=await ce({message:"How would you like to authenticate?",options:[{value:"oauth",label:"Login with Resend (opens browser)"},{value:"browser",label:"Get API key from resend.com (opens browser)"},{value:"manual",label:"Enter API key manually"}]});if(x(c)&&R("Login cancelled."),c==="oauth"){await Om(o);return}X.info(`Use a full access API key for complete CLI access.
|
|
301
|
+
${_t}`),c==="browser"&&(await Yo(yr)?X.info(`Opened ${yr}`):X.warn(`Could not open browser. Visit ${yr} manually.`));let u=await _n({message:"Enter your Resend API key:",validate:f=>{if(!f)return"API key is required";if(!f.startsWith("re_"))return"API key must start with re_"}});x(u)&&R("Login cancelled."),i=u.trim()}(!i||!i.startsWith("re_"))&&g({message:"Invalid API key format. Key must start with re_",code:"invalid_key_format"},{json:o.json});let r=ne("Validating API key...",o.quiet),n="full_access";try{let c=new kt(i),{error:u}=await c.domains.list();if(u){let f=u;f.name==="restricted_api_key"?(n="sending_access",r.warn("API key is valid (sending access only)")):(r.fail("API key validation failed"),g({message:f.message||"Failed to validate API key",code:"validation_failed"},{json:o.json}))}else r.stop("API key is valid (full access)")}catch(c){r.fail("API key validation failed"),g({message:q(c,"Failed to validate API key"),code:"validation_failed"},{json:o.json})}let s=await la(o,"Save API key to which profile?"),{configPath:a,backend:l}=await Hs(i,s,n),d=s||"default";if(s)try{ao(d)}catch(c){g({message:q(c,"Failed to switch profile"),code:"switch_failed"},{json:o.json})}o.json?E({success:!0,config_path:a,profile:d,storage:l.name,permission:n},{json:!0}):ca({noun:"API key",profileLabel:d,configPath:a,backend:l})});var ua=require("node:fs");he();J();var Zo=new p("logout").description("Remove your saved Resend API key").addHelpText("after",m({setup:!0,context:`Removes the saved API key from secure storage and the credentials file.
|
|
302
302
|
|
|
303
303
|
When --profile is specified, only that profile's entry is removed.
|
|
304
304
|
When no profile is specified, all profiles are removed.
|
|
305
305
|
|
|
306
|
-
If no credentials file exists, exits cleanly with no error.`,output:' {"success":true,"config_path":"<path>"}',errorCodes:["remove_failed"],examples:["resend logout","resend logout --profile staging","resend logout --json"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=Ut(),r=hr();if(!r&&!(0,ua.existsSync)(i)){!o.json&&U()?console.log("No saved credentials found. Nothing to remove."):
|
|
306
|
+
If no credentials file exists, exits cleanly with no error.`,output:' {"success":true,"config_path":"<path>"}',errorCodes:["remove_failed"],examples:["resend logout","resend logout --profile staging","resend logout --json"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=Ut(),r=hr();if(!r&&!(0,ua.existsSync)(i)){!o.json&&U()?console.log("No saved credentials found. Nothing to remove."):E({success:!0,already_logged_out:!0},{json:o.json});return}let n=o.profile,s=!n,a=n??"all";if(!s&&r&&!r.profiles[a]&&g({message:`Profile "${a}" not found. Available profiles: ${Object.keys(r.profiles).join(", ")}`,code:"remove_failed"},{json:o.json}),!o.json&&U()){let l=s?"Remove all saved API keys?":`Remove saved API key for profile '${a}'?`,d=await rt({message:l});(x(d)||!d)&&R("Logout cancelled.")}try{s?await Gs():await qo(a)}catch(l){g({message:q(l,"Failed to remove credentials"),code:"remove_failed"},{json:o.json})}if(!o.json&&U()){let l=s?"Logged out. All API keys removed.":`Logged out. API key removed for profile '${a}'.`;Ro(l)}else E({success:!0,config_path:i,profile:s?"all":a},{json:o.json})});he();J();async function Tm(e,t){let o=e;if(!o){if(!U()||t.json){g({message:"Missing profile name. Provide a profile name in non-interactive mode.",code:"missing_name"},{json:t.json});return}let i=ve();if(i.length===0){g({message:"No profiles configured. Run `resend login` first.",code:"no_profiles"},{json:t.json});return}let r=await ce({message:"Remove which profile?",options:i.map(n=>({value:n.name,label:n.name,hint:n.active?"active":void 0}))});x(r)&&R("Remove cancelled."),o=r}if(!t.json&&U()){let i=await rt({message:`Remove profile '${o}' and its API key?`});(x(i)||!i)&&R("Remove cancelled.")}try{await qo(o)}catch(i){g({message:q(i,"Failed to remove profile"),code:"remove_failed"},{json:t.json});return}t.json?E({success:!0,removed_profile:o},{json:!0}):console.log(`Profile '${o}' removed.`)}var da=new p("remove").description("Remove a profile").argument("[name]","Profile name to remove").action(async(e,t,o)=>{await Tm(e,o.optsWithGlobals())});he();J();async function jm(e,t,o){let i=e,r=t;if(!i){if(!U()||o.json){g({message:"Missing profile name. Provide old and new names in non-interactive mode.",code:"missing_name"},{json:o.json});return}let n=ve();if(n.length===0){g({message:"No profiles configured. Run `resend login` first.",code:"no_profiles"},{json:o.json});return}let s=await ce({message:"Rename which profile?",options:n.map(a=>({value:a.name,label:a.name,hint:a.active?"active":le(a.name)?"invalid name":void 0}))});x(s)&&R("Rename cancelled."),i=s}if(!r){if(!U()||o.json){g({message:"Missing new name. Provide old and new names in non-interactive mode.",code:"missing_name"},{json:o.json});return}let n=await Z({message:`Enter new name for '${i}':`,placeholder:i.replace(/[^a-zA-Z0-9._-]/g,"-"),validate:s=>le(s)});x(n)&&R("Rename cancelled."),r=n}try{await Mo(i,r)}catch(n){g({message:q(n,"Failed to rename profile"),code:"rename_failed"},{json:o.json});return}o.json?E({success:!0,old_name:i,new_name:r},{json:!0}):console.log(`Profile '${i}' renamed to '${r}'.`)}var pa=new p("rename").description("Rename a profile").argument("[old-name]","Current profile name").argument("[new-name]","New profile name").action(async(e,t,o,i)=>{await jm(e,t,i.optsWithGlobals())});he();J();async function Im(e,t){let o=e;if(!o){if(!U()||t.json){g({message:"Missing profile name. Provide a profile name in non-interactive mode.",code:"missing_name"},{json:t.json});return}let n=ve();if(n.length===0){g({message:"No profiles configured. Run `resend login` first.",code:"no_profiles"},{json:t.json});return}let s=await ce({message:"Switch to which profile?",options:n.map(a=>({value:a.name,label:a.name,hint:a.active?"active":le(a.name)?"invalid name":void 0}))});x(s)&&R("Switch cancelled."),o=s}if(ve().some(n=>n.name===o)){let n=await Vo(o,t);if(!n)return;o=n}try{ao(o)}catch(n){g({message:q(n,"Failed to switch profile"),code:"switch_failed"},{json:t.json});return}t.json?E({success:!0,active_profile:o},{json:!0}):console.log(`Switched to profile '${o}'.`)}var ma=new p("switch").description("Switch the active profile").argument("[name]","Profile name to switch to").action(async(e,t,o)=>{await Im(e,o.optsWithGlobals())});var fa=new p("auth").description("Manage authentication and profiles").addHelpText("after",m({setup:!0,context:`Environment variables:
|
|
307
307
|
RESEND_API_KEY API key (overrides stored credentials)
|
|
308
308
|
RESEND_PROFILE Profile name (overrides config default)
|
|
309
309
|
RESEND_CREDENTIAL_STORE Storage method: "secure_storage" or "file"`,examples:["resend login","resend login --key re_123456789","resend logout","resend auth list","resend auth switch staging","resend auth rename staging production","resend auth remove staging"]})).addCommand(Xo).addCommand(Zo).addCommand(sa,{isDefault:!0}).addCommand(ma).addCommand(pa).addCommand(da);var Ur=require("node:fs");function oe(e,t){if(e==="-"){process.stdin.isTTY&&g({message:"No input piped to stdin",code:"stdin_read_error"},{json:t.json});try{return(0,Ur.readFileSync)(0,"utf-8")}catch{g({message:"Failed to read from stdin",code:"stdin_read_error"},{json:t.json})}}try{return(0,Ur.readFileSync)(e,"utf-8")}catch{g({message:`Failed to read file: ${e}`,code:"file_read_error"},{json:t.json})}}function Kt(e,t,o){if(e!==void 0)try{return JSON.parse(e)}catch(i){g({message:`Invalid JSON for ${t}: ${i instanceof Error?i.message:"parse error"}`,code:"invalid_json"},{json:o.json})}}var ga=new p("create").description("Create a new automation").option("--name <name>","Automation name").addOption(new V("--status <status>","Initial status").choices(["enabled","disabled"])).option("--steps <json>","Steps array as JSON string").option("--connections <json>","Connections array as JSON string").option("--file <path>",'Path to a JSON file containing the full automation payload (use "-" for stdin)').addHelpText("after",m({context:`Non-interactive: --name and --steps/--connections (or --file) are required.
|
|
@@ -314,17 +314,17 @@ Payload format:
|
|
|
314
314
|
When using --file, --name/--status/--steps/--connections flags override file values.
|
|
315
315
|
|
|
316
316
|
Step types: trigger, delay, send_email, wait_for_event, condition
|
|
317
|
-
Connection types: default, condition_met, condition_not_met, timeout, event_received`,output:' {"object":"automation","id":"<id>"}',errorCodes:["auth_error","missing_name","missing_steps","missing_connections","invalid_json","file_read_error","create_error"],examples:["resend automations create --file automation.json","cat automation.json | resend automations create --file -","resend automations create --file automation.json --status disabled",`resend automations create --name "Welcome Flow" --steps '[...]' --connections '[...]'`]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i={};if(e.file){let l=oe(e.file,o);try{i=JSON.parse(l)}catch(d){g({message:`Invalid JSON in --file: ${d instanceof Error?d.message:"parse error"}`,code:"invalid_json"},{json:o.json})}(typeof i!="object"||i===null||Array.isArray(i))&&g({message:"--file must contain a JSON object with automation properties (name, steps, connections).",code:"invalid_json"},{json:o.json})}let r=await O(e.name??i.name,{message:"Automation name",placeholder:"e.g. Welcome Flow"},{message:"Missing --name flag.",code:"missing_name"},o),n=Kt(e.steps,"--steps",o)??i.steps;(!n||!Array.isArray(n)||n.length===0)&&g({message:"Missing or empty steps. Provide --steps as a JSON array or use --file.",code:"missing_steps"},{json:o.json});let s=Kt(e.connections,"--connections",o)??i.connections;s||g({message:"Missing connections. Provide --connections as a JSON array or use --file (empty array is valid for single-step automations).",code:"missing_connections"},{json:o.json}),Array.isArray(s)||g({message:"--connections must be a JSON array.",code:"invalid_json"},{json:o.json});let a=e.status??i.status;await L({loading:"Creating automation...",sdkCall:l=>l.automations.create({name:r,steps:n,connections:s,...a&&{status:a}}),onInteractive:l=>{console.log(`Automation created: ${l.id}`)}},o)});function ha(e){let t=e.map(o=>[o.name,Sr(o.status),o.created_at,o.id]);return
|
|
317
|
+
Connection types: default, condition_met, condition_not_met, timeout, event_received`,output:' {"object":"automation","id":"<id>"}',errorCodes:["auth_error","missing_name","missing_steps","missing_connections","invalid_json","file_read_error","create_error"],examples:["resend automations create --file automation.json","cat automation.json | resend automations create --file -","resend automations create --file automation.json --status disabled",`resend automations create --name "Welcome Flow" --steps '[...]' --connections '[...]'`]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i={};if(e.file){let l=oe(e.file,o);try{i=JSON.parse(l)}catch(d){g({message:`Invalid JSON in --file: ${d instanceof Error?d.message:"parse error"}`,code:"invalid_json"},{json:o.json})}(typeof i!="object"||i===null||Array.isArray(i))&&g({message:"--file must contain a JSON object with automation properties (name, steps, connections).",code:"invalid_json"},{json:o.json})}let r=await O(e.name??i.name,{message:"Automation name",placeholder:"e.g. Welcome Flow"},{message:"Missing --name flag.",code:"missing_name"},o),n=Kt(e.steps,"--steps",o)??i.steps;(!n||!Array.isArray(n)||n.length===0)&&g({message:"Missing or empty steps. Provide --steps as a JSON array or use --file.",code:"missing_steps"},{json:o.json});let s=Kt(e.connections,"--connections",o)??i.connections;s||g({message:"Missing connections. Provide --connections as a JSON array or use --file (empty array is valid for single-step automations).",code:"missing_connections"},{json:o.json}),Array.isArray(s)||g({message:"--connections must be a JSON array.",code:"invalid_json"},{json:o.json});let a=e.status??i.status;await L({loading:"Creating automation...",sdkCall:l=>l.automations.create({name:r,steps:n,connections:s,...a&&{status:a}}),onInteractive:l=>{console.log(`Automation created: ${l.id}`)}},o)});function ha(e){let t=e.map(o=>[o.name,Sr(o.status),o.created_at,o.id]);return B(["Name","Status","Created","ID"],t,"(no automations)")}function Sr(e){switch(e){case"enabled":return"\u2713 Enabled";case"disabled":return"\u25CB Disabled";default:return e}}var Je={resource:"automation",resourcePlural:"automations",fetchItems:(e,{limit:t,after:o})=>e.automations.list({limit:t,...o&&{after:o}}),display:e=>({label:e.name,hint:e.id})};var Aa=new p("delete").alias("rm").description("Delete an automation").argument("[id]","Automation ID").option("--yes","Skip confirmation prompt").addHelpText("after",m({context:"Non-interactive: --yes is required to confirm deletion when stdin/stdout is not a TTY.",output:' {"object":"automation","id":"<id>","deleted":true}',errorCodes:["auth_error","confirmation_required","delete_error"],examples:["resend automations delete <id> --yes","resend automations delete <id> --yes --json"]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await y(e,Je,i);await ee(r,!!t.yes,{confirmMessage:`Delete automation ${r}?
|
|
318
318
|
This cannot be undone.`,loading:"Deleting automation...",object:"automation",successMsg:"Automation deleted",sdkCall:n=>n.automations.remove(r)},i)});var ba=new p("get").description("Retrieve an automation with its steps and connections").argument("[id]","Automation ID").addHelpText("after",m({output:` Full automation object including steps and connections arrays.
|
|
319
319
|
|
|
320
320
|
Automation status values: enabled | disabled`,errorCodes:["auth_error","fetch_error"],examples:["resend automations get <id>","resend automations get <id> --json"]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await y(e,Je,i);await Q({loading:"Fetching automation...",sdkCall:n=>n.automations.get(r),onInteractive:n=>{if(console.log(`${n.name} \u2014 ${Sr(n.status)}`),console.log(`ID: ${n.id}`),console.log(`Created: ${n.created_at}`),n.updated_at&&console.log(`Updated: ${n.updated_at}`),n.steps.length>0){console.log(`
|
|
321
|
-
Steps:`);let s=n.steps.map(a=>[a.key,a.type]);console.log(
|
|
322
|
-
Connections:`);let s=n.connections.map(a=>[a.from,a.to,a.type]);console.log(
|
|
321
|
+
Steps:`);let s=n.steps.map(a=>[a.key,a.type]);console.log(B(["Key","Type"],s,"(no steps)"))}if(n.connections.length>0){console.log(`
|
|
322
|
+
Connections:`);let s=n.connections.map(a=>[a.from,a.to,a.type]);console.log(B(["From","To","Type"],s,"(no connections)"))}}},i)});var Ca=new p("list").alias("ls").description("List all automations").option("--limit <n>","Maximum number of automations to return (1-100)","10").option("--after <cursor>","Return automations after this cursor (next page)").option("--before <cursor>","Return automations before this cursor (previous page)").addHelpText("after",m({output:' {"object":"list","data":[...],"has_more":true}',errorCodes:["auth_error","invalid_limit","list_error"],examples:["resend automations list","resend automations list --limit 25 --json","resend automations list --after <cursor> --json"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=P(e.limit,o),r=$(i,e.after,e.before,o);await _({loading:"Fetching automations...",sdkCall:n=>n.automations.list(r),onInteractive:n=>{console.log(ha(n.data)),H(n,"automations list",{limit:i,before:e.before,apiKey:o.apiKey,profile:o.profile})}},o)});var ya=new p("open").description("Open an automation or the automations list in the Resend dashboard").argument("[id]","Automation ID \u2014 omit to open the automations list").addHelpText("after",m({context:`Opens the Resend dashboard in your default browser.
|
|
323
323
|
With an ID: opens that automation's editor.
|
|
324
|
-
Without an ID: opens the automations list.`,examples:["resend automations open","resend automations open 019d4ef1-8266-71d4-a1aa-60ce5d0eaea7"]})).action(async(e,t,o)=>{let i=e?me.automation(e):me.automations,r=o.optsWithGlobals();await Re(i,r)});var Ua=new p("get").description("Retrieve details of a specific automation run").option("--automation-id <id>","Automation ID").option("--run-id <id>","Run ID").addHelpText("after",m({output:" Full automation run object with status, trigger, and timestamps.",errorCodes:["auth_error","missing_automation_id","missing_run_id","fetch_error"],examples:["resend automations runs get --automation-id <id> --run-id <id>","resend automations runs get --automation-id <id> --run-id <id> --json"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=await O(e.automationId,{message:"Automation ID"},{message:"Missing --automation-id flag.",code:"missing_automation_id"},o),r=await O(e.runId,{message:"Run ID"},{message:"Missing --run-id flag.",code:"missing_run_id"},o);await Q({loading:"Fetching automation run...",sdkCall:n=>n.automations.runs.get({automationId:i,runId:r}),onInteractive:n=>{console.log(`Run: ${n.id}`),console.log(`Status: ${n.status}`),n.started_at&&console.log(`Started: ${n.started_at}`),n.completed_at&&console.log(`Completed: ${n.completed_at}`),console.log(`Created: ${n.created_at}`)}},o)});var Sa=new p("list").alias("ls").description("List runs for an automation").argument("[automation-id]","Automation ID").option("--status <status>","Filter by status (running, completed, failed, cancelled). Comma-separated.").option("--limit <n>","Maximum number of runs to return (1-100)","10").option("--after <cursor>","Return runs after this cursor (next page)").option("--before <cursor>","Return runs before this cursor (previous page)").addHelpText("after",m({output:' {"object":"list","data":[...],"has_more":true}',errorCodes:["auth_error","missing_id","invalid_limit","list_error"],examples:["resend automations runs <automation-id>","resend automations runs list <automation-id>","resend automations runs list <automation-id> --status running","resend automations runs list <automation-id> --limit 25 --json"]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await y(e,Je,i),n=P(t.limit,i),s=$(n,t.after,t.before,i);await _({loading:"Fetching automation runs...",sdkCall:a=>a.automations.runs.list({automationId:r,...s,...t.status?{status:t.status}:{}}),onInteractive:a=>{let l=a.data.map(d=>[d.id,d.status,d.started_at??"-",d.completed_at??"-"]);console.log(
|
|
324
|
+
Without an ID: opens the automations list.`,examples:["resend automations open","resend automations open 019d4ef1-8266-71d4-a1aa-60ce5d0eaea7"]})).action(async(e,t,o)=>{let i=e?me.automation(e):me.automations,r=o.optsWithGlobals();await Re(i,r)});var Ua=new p("get").description("Retrieve details of a specific automation run").option("--automation-id <id>","Automation ID").option("--run-id <id>","Run ID").addHelpText("after",m({output:" Full automation run object with status, trigger, and timestamps.",errorCodes:["auth_error","missing_automation_id","missing_run_id","fetch_error"],examples:["resend automations runs get --automation-id <id> --run-id <id>","resend automations runs get --automation-id <id> --run-id <id> --json"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=await O(e.automationId,{message:"Automation ID"},{message:"Missing --automation-id flag.",code:"missing_automation_id"},o),r=await O(e.runId,{message:"Run ID"},{message:"Missing --run-id flag.",code:"missing_run_id"},o);await Q({loading:"Fetching automation run...",sdkCall:n=>n.automations.runs.get({automationId:i,runId:r}),onInteractive:n=>{console.log(`Run: ${n.id}`),console.log(`Status: ${n.status}`),n.started_at&&console.log(`Started: ${n.started_at}`),n.completed_at&&console.log(`Completed: ${n.completed_at}`),console.log(`Created: ${n.created_at}`)}},o)});var Sa=new p("list").alias("ls").description("List runs for an automation").argument("[automation-id]","Automation ID").option("--status <status>","Filter by status (running, completed, failed, cancelled). Comma-separated.").option("--limit <n>","Maximum number of runs to return (1-100)","10").option("--after <cursor>","Return runs after this cursor (next page)").option("--before <cursor>","Return runs before this cursor (previous page)").addHelpText("after",m({output:' {"object":"list","data":[...],"has_more":true}',errorCodes:["auth_error","missing_id","invalid_limit","list_error"],examples:["resend automations runs <automation-id>","resend automations runs list <automation-id>","resend automations runs list <automation-id> --status running","resend automations runs list <automation-id> --limit 25 --json"]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await y(e,Je,i),n=P(t.limit,i),s=$(n,t.after,t.before,i);await _({loading:"Fetching automation runs...",sdkCall:a=>a.automations.runs.list({automationId:r,...s,...t.status?{status:t.status}:{}}),onInteractive:a=>{let l=a.data.map(d=>[d.id,d.status,d.started_at??"-",d.completed_at??"-"]);console.log(B(["ID","Status","Started","Completed"],l,"(no runs)")),H(a,`automations runs list ${r}`,{limit:n,before:t.before,apiKey:i.apiKey,profile:i.profile})}},i)});var Ka=new p("runs").description("Manage automation runs").addHelpText("after",m({context:`Runs represent individual executions of an automation.
|
|
325
325
|
Each run is triggered by an event and progresses through the automation's steps.
|
|
326
326
|
|
|
327
|
-
Run status values: running | completed | failed | cancelled`,examples:["resend automations runs <automation-id>","resend automations runs list <automation-id> --limit 25","resend automations runs get --automation-id <id> --run-id <id>"]})).addCommand(Sa,{isDefault:!0}).addCommand(Ua);var va=new p("stop").description("Stop a running automation").argument("[id]","Automation ID").addHelpText("after",m({context:"Stops a running automation by setting its status to disabled and cancelling active runs.",output:' {"object":"automation","id":"<id>","status":"disabled"}',errorCodes:["auth_error","stop_error"],examples:["resend automations stop <id>","resend automations stop <id> --json"]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await y(e,Je,i);await I({loading:"Stopping automation...",sdkCall:n=>n.automations.stop(r),errorCode:"stop_error",successMsg:"Automation stopped"},i)});var wa=new p("update").description("Update an automation status (enable or disable)").argument("[id]","Automation ID").addOption(new V("--status <status>","New status").choices(["enabled","disabled"])).addHelpText("after",m({output:' {"object":"automation","id":"<id>","status":"<status>"}',errorCodes:["auth_error","missing_status","update_error"],examples:["resend automations update <id> --status enabled","resend automations update <id> --status disabled --json"]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await y(e,Je,i),n=await
|
|
327
|
+
Run status values: running | completed | failed | cancelled`,examples:["resend automations runs <automation-id>","resend automations runs list <automation-id> --limit 25","resend automations runs get --automation-id <id> --run-id <id>"]})).addCommand(Sa,{isDefault:!0}).addCommand(Ua);var va=new p("stop").description("Stop a running automation").argument("[id]","Automation ID").addHelpText("after",m({context:"Stops a running automation by setting its status to disabled and cancelling active runs.",output:' {"object":"automation","id":"<id>","status":"disabled"}',errorCodes:["auth_error","stop_error"],examples:["resend automations stop <id>","resend automations stop <id> --json"]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await y(e,Je,i);await I({loading:"Stopping automation...",sdkCall:n=>n.automations.stop(r),errorCode:"stop_error",successMsg:"Automation stopped"},i)});var wa=new p("update").description("Update an automation status (enable or disable)").argument("[id]","Automation ID").addOption(new V("--status <status>","New status").choices(["enabled","disabled"])).addHelpText("after",m({output:' {"object":"automation","id":"<id>","status":"<status>"}',errorCodes:["auth_error","missing_status","update_error"],examples:["resend automations update <id> --status enabled","resend automations update <id> --status disabled --json"]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await y(e,Je,i),n=await Et(t.status,{message:"Status",options:[{value:"enabled",label:"Enabled"},{value:"disabled",label:"Disabled"}]},{message:"Missing --status flag.",code:"missing_status"},i);await I({loading:"Updating automation...",sdkCall:s=>s.automations.update(r,{status:n}),errorCode:"update_error",successMsg:`Automation updated: ${r} (${n})`},i)});var xa=new p("automations").description("Manage automations").addHelpText("after",m({context:`Automations are event-driven workflows composed of steps and connections.
|
|
328
328
|
|
|
329
329
|
Steps define the actions (trigger, delay, send_email, wait_for_event, condition).
|
|
330
330
|
Connections define the flow between steps (default, condition_met, condition_not_met, timeout, event_received).
|
|
@@ -334,10 +334,10 @@ Lifecycle:
|
|
|
334
334
|
2. resend automations update <id> --status enabled
|
|
335
335
|
3. resend automations stop <id> (stop automation)
|
|
336
336
|
4. resend automations runs <id> (inspect runs)
|
|
337
|
-
5. resend automations open <id> (view in dashboard)`,examples:["resend automations list",'resend automations create --name "Welcome Flow" --file workflow.json',"resend automations get <id>","resend automations update <id> --status enabled","resend automations stop <id>","resend automations delete <id> --yes","resend automations runs <automation-id>","resend automations runs get --automation-id <id> --run-id <id>","resend automations open <id>"]})).addCommand(ga).addCommand(ba).addCommand(Ca,{isDefault:!0}).addCommand(wa).addCommand(Aa).addCommand(va).addCommand(ya).addCommand(Ka);async function ei(e){try{let{data:t,error:o}=await e.domains.list();return o||!t?[]:t.data.filter(i=>i.status==="verified"&&i.capabilities.sending==="enabled").map(i=>i.name)}catch{return[]}}var Pm=["noreply","hello"];async function ti(e){let t;if(e.length===1)t=e[0];else{let r=await ce({message:"Select a verified domain",options:e.map(n=>({value:n,label:n}))});x(r)&&R("Send cancelled."),t=r}let o=Pm.map(r=>({value:`${r}@${t}`,label:`${r}@${t}`}));o.push({value:null,label:"Custom address..."});let i=await ce({message:`From address (@${t})`,options:o});if(x(i)&&R("Send cancelled."),i===null){let r=await Z({message:"From address",placeholder:`e.g. you@${t}`,validate:n=>!n||!n.includes("@")?"Enter a valid email address":void 0});return x(r)&&R("Send cancelled."),r}return i}var jt=require("node:fs"),ja=require("node:path");var oi=require("node:fs"),
|
|
337
|
+
5. resend automations open <id> (view in dashboard)`,examples:["resend automations list",'resend automations create --name "Welcome Flow" --file workflow.json',"resend automations get <id>","resend automations update <id> --status enabled","resend automations stop <id>","resend automations delete <id> --yes","resend automations runs <automation-id>","resend automations runs get --automation-id <id> --run-id <id>","resend automations open <id>"]})).addCommand(ga).addCommand(ba).addCommand(Ca,{isDefault:!0}).addCommand(wa).addCommand(Aa).addCommand(va).addCommand(ya).addCommand(Ka);async function ei(e){try{let{data:t,error:o}=await e.domains.list();return o||!t?[]:t.data.filter(i=>i.status==="verified"&&i.capabilities.sending==="enabled").map(i=>i.name)}catch{return[]}}var Pm=["noreply","hello"];async function ti(e){let t;if(e.length===1)t=e[0];else{let r=await ce({message:"Select a verified domain",options:e.map(n=>({value:n,label:n}))});x(r)&&R("Send cancelled."),t=r}let o=Pm.map(r=>({value:`${r}@${t}`,label:`${r}@${t}`}));o.push({value:null,label:"Custom address..."});let i=await ce({message:`From address (@${t})`,options:o});if(x(i)&&R("Send cancelled."),i===null){let r=await Z({message:"From address",placeholder:`e.g. you@${t}`,validate:n=>!n||!n.includes("@")?"Enter a valid email address":void 0});return x(r)&&R("Send cancelled."),r}return i}var jt=require("node:fs"),ja=require("node:path");var oi=require("node:fs"),Ba=require("node:os"),Tt=ue(require("node:path"),1);function Fa(){return"pkg"in process?require("esbuild-wasm"):require("esbuild")}var Ra=require("node:fs"),_a=ue(require("node:path"),1);function ka(e){return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}var Da=e=>({name:"rendering-utilities-exporter",setup:t=>{t.onLoad({filter:new RegExp(e.map(o=>ka(o)).join("|"))},async({path:o})=>({contents:`${await Ra.promises.readFile(o,"utf8")};
|
|
338
338
|
export { render } from 'react-email-module-that-will-export-render'
|
|
339
339
|
export { createElement as reactEmailCreateReactElement } from 'react';
|
|
340
|
-
`,loader:_a.default.extname(o).slice(1)})),t.onResolve({filter:/^react-email-module-that-will-export-render$/},async o=>{let i={kind:"import-statement",importer:o.importer,resolveDir:o.resolveDir,namespace:o.namespace},r=await t.resolve("react-email",i);return r.errors.length===0||(r=await t.resolve("@react-email/components",i),r.errors.length===0)||(r=await t.resolve("@react-email/render",i),r.errors.length>0&&r.errors[0]&&(r.errors[0].text="Failed to import `render` from `react-email` (6.0+), `@react-email/components` (5.x), or `@react-email/render`. Install one of them in your project.")),r})}});async function
|
|
340
|
+
`,loader:_a.default.extname(o).slice(1)})),t.onResolve({filter:/^react-email-module-that-will-export-render$/},async o=>{let i={kind:"import-statement",importer:o.importer,resolveDir:o.resolveDir,namespace:o.namespace},r=await t.resolve("react-email",i);return r.errors.length===0||(r=await t.resolve("@react-email/components",i),r.errors.length===0)||(r=await t.resolve("@react-email/render",i),r.errors.length>0&&r.errors[0]&&(r.errors[0].text="Failed to import `render` from `react-email` (6.0+), `@react-email/components` (5.x), or `@react-email/render`. Install one of them in your project.")),r})}});async function Ea(e){let t=Tt.default.resolve(e),o=(0,oi.mkdtempSync)(Tt.default.join((0,Ba.tmpdir)(),"resend-react-email-"));try{let{build:n}=Fa();await n({bundle:!0,entryPoints:[t],format:"cjs",jsx:"automatic",logLevel:"silent",outExtension:{".js":".cjs"},outdir:o,platform:"node",plugins:[Da([t])],write:!0})}catch(n){throw(0,oi.rmSync)(o,{recursive:!0,force:!0}),n}let i=Tt.default.basename(t,Tt.default.extname(t));return{cjsPath:Tt.default.join(o,`${i}.cjs`),tmpDir:o}}var Oa=require("node:module");async function Ta(e){let t=(0,Oa.createRequire)(e);delete t.cache[e];let o=t(e);return o.render(o.reactEmailCreateReactElement(o.default,{}),{})}var Kr=e=>{e&&(0,jt.rmSync)(e,{recursive:!0,force:!0})},Pe=async(e,t)=>{if(e.trim()==="")return g({message:"--react-email path cannot be empty",code:"react_email_build_error"},{json:t.json});let o=(0,ja.resolve)(e);if(!(0,jt.existsSync)(o))return g({message:`File not found: ${e}`,code:"react_email_build_error"},{json:t.json});if(!(0,jt.statSync)(o).isFile())return g({message:`--react-email path must be a file, got a directory: ${e}`,code:"react_email_build_error"},{json:t.json});let i=ne("Bundling React Email template...",t.quiet),r;try{let n=await Ea(e);r=n.tmpDir,i.stop("Bundled React Email template");let s=ne("Rendering React Email template...",t.quiet);try{let a=await Ta(n.cjsPath);return s.stop("Rendered React Email template"),Kr(r),a}catch(a){return s.fail("Failed to render React Email template"),Kr(r),g({message:q(a,"Failed to render React Email template"),code:"react_email_render_error"},{json:t.json})}}catch(n){return i.fail("Failed to bundle React Email template"),Kr(r),g({message:q(n,"Failed to bundle React Email template"),code:"react_email_build_error"},{json:t.json})}};J();var $e={resource:"segment",resourcePlural:"segments",fetchItems:(e,{limit:t,after:o})=>e.segments.list({limit:t,...o&&{after:o}}),display:e=>({label:e.name,hint:e.id})};function ii(e){let t=e.map(o=>[o.name,o.id,o.created_at]);return B(["Name","ID","Created"],t,"(no segments)")}var pt={resource:"topic",resourcePlural:"topics",fetchItems:e=>e.topics.list().then(t=>({...t,data:t.data?{data:t.data.data,has_more:!1}:null})),display:e=>({label:e.name,hint:e.id})};function Ia(e){let t=e.map(o=>[o.name,o.description??"",o.id,o.created_at]);return B(["Name","Description","ID","Created"],t,"(no topics)")}var Pa=new p("create").description("Create a broadcast draft (or send immediately with --send)").option("--from <address>","Sender address \u2014 required").option("--subject <subject>","Email subject \u2014 required").option("--segment-id <id>","Target segment ID \u2014 required").option("--html <html>","HTML body (supports {{{FIRST_NAME|fallback}}} triple-brace variable interpolation)").option("--html-file <path>",'Path to an HTML file for the body (use "-" for stdin, supports {{{FIRST_NAME|fallback}}} variable interpolation)').option("--text <text>","Plain-text body").option("--text-file <path>",'Path to a plain-text file for the body (use "-" for stdin)').option("--react-email <path>","Path to a React Email template (.tsx) to bundle, render, and use as HTML body").option("--name <name>","Internal label for the broadcast (optional)").option("--reply-to <address>","Reply-to address (optional)").option("--preview-text <text>","Preview text shown in inbox below the subject line (optional)").option("--topic-id <id>","Associate with a topic for subscription filtering (optional)").option("--send","Send immediately on create instead of saving as draft").option("--scheduled-at <datetime>",'Schedule delivery \u2014 ISO 8601 or natural language e.g. "in 1 hour", "tomorrow at 9am ET" (only valid with --send)').option("--dry-run","Validate input and print the create request JSON without calling the API (interactive: type segment/topic IDs; lists are not fetched)").addHelpText("after",m({context:`Non-interactive: --from, --subject, and --segment-id are required.
|
|
341
341
|
Body: provide at least one of --html, --html-file, --text, --text-file, or --react-email.
|
|
342
342
|
|
|
343
343
|
Use --dry-run to print the request JSON without creating a broadcast.
|
|
@@ -349,7 +349,7 @@ Variable interpolation:
|
|
|
349
349
|
Scheduling:
|
|
350
350
|
Use --scheduled-at with --send to schedule delivery.
|
|
351
351
|
Accepts ISO 8601 (e.g. 2026-08-05T11:52:01Z) or natural language (e.g. "in 1 hour").
|
|
352
|
-
--scheduled-at without --send is ignored.`,output:' {"id":"<broadcast-id>"}',errorCodes:["auth_error","missing_from","missing_subject","missing_segment","missing_body","file_read_error","invalid_options","stdin_read_error","react_email_build_error","react_email_render_error","create_error"],examples:['resend broadcasts create --from onboarding@resend.
|
|
352
|
+
--scheduled-at without --send is ignored.`,output:' {"id":"<broadcast-id>"}',errorCodes:["auth_error","missing_from","missing_subject","missing_segment","missing_body","file_read_error","invalid_options","stdin_read_error","react_email_build_error","react_email_render_error","create_error"],examples:['resend broadcasts create --from onboarding@resend.dev --subject "Weekly Update" --segment-id 7b1e0a3d-4c5f-4e8a-9b2d-1a3c5e7f9b2d --html "<p>Hello {{{FIRST_NAME|there}}}</p>"','resend broadcasts create --from onboarding@resend.dev --subject "Launch" --segment-id 7b1e0a3d-4c5f-4e8a-9b2d-1a3c5e7f9b2d --html-file ./email.html --send','resend broadcasts create --from onboarding@resend.dev --subject "Launch" --segment-id 7b1e0a3d-4c5f-4e8a-9b2d-1a3c5e7f9b2d --text "Hello!" --send --scheduled-at "tomorrow at 9am ET"']})).action(async(e,t)=>{let o=t.optsWithGlobals();e.htmlFile==="-"&&e.textFile==="-"&&g({message:"Cannot read both --html-file and --text-file from stdin. Pipe to one and pass the other as a file path.",code:"invalid_options"},{json:o.json}),e.reactEmail&&(e.html||e.htmlFile)&&g({message:"Cannot use --react-email with --html or --html-file",code:"invalid_options"},{json:o.json}),e.html!==void 0&&e.htmlFile!==void 0&&g({message:"--html and --html-file are mutually exclusive.",code:"invalid_options"},{json:o.json}),e.text!==void 0&&e.textFile!==void 0&&g({message:"--text and --text-file are mutually exclusive.",code:"invalid_options"},{json:o.json});let i=e.from,r=e.subject,n=e.segmentId;if(!i&&U()&&!o.json&&!e.dryRun){let c=await Y(o),u=await ei(c);u.length>0&&(i=await ti(u))}if(!i){(!U()||o.json)&&g({message:"Missing --from flag.",code:"missing_from"},{json:o.json});let c=await Z({message:"From address",placeholder:"e.g. onboarding@resend.dev",validate:u=>u?void 0:"Required"});x(c)&&R("Cancelled."),i=c}if(!r){(!U()||o.json)&&g({message:"Missing --subject flag.",code:"missing_subject"},{json:o.json});let c=await Z({message:"Subject",placeholder:"e.g. Weekly Newsletter",validate:u=>u?void 0:"Required"});x(c)&&R("Cancelled."),r=c}if(!n)if((!U()||o.json)&&g({message:"Missing --segment-id flag.",code:"missing_segment"},{json:o.json}),e.dryRun){let c=await Z({message:"Segment ID",placeholder:"e.g. 7b1e0a3d-4c5f-4e8a-9b2d-1a3c5e7f9b2d",validate:u=>u?void 0:"Required"});x(c)&&R("Cancelled."),n=c}else n=await y(void 0,$e,o);let s=e.reactEmail?await Pe(e.reactEmail,o):e.htmlFile?oe(e.htmlFile,o):e.html,a=e.textFile?oe(e.textFile,o):e.text;if(!s&&!a){(!U()||o.json)&&g({message:"Missing body. Provide --html, --html-file, --text, --text-file, or --react-email.",code:"missing_body"},{json:o.json});let c=await Z({message:"Body (plain text)",placeholder:"e.g. Hello {{{FIRST_NAME|there}}}!",validate:u=>u?void 0:"Required"});x(c)&&R("Cancelled."),a=c}let l=e.topicId;if(!l&&U()&&!o.json)if(e.dryRun){let c=await Z({message:"Topic ID (optional)",placeholder:"Press Enter to skip"});x(c)&&R("Cancelled."),l=c.trim()||void 0}else l=await y(void 0,pt,o,{optional:!0});let d={from:i,subject:r,segmentId:n,...s&&{html:s},...a&&{text:a},...e.name&&{name:e.name},...e.replyTo&&{replyTo:e.replyTo},...e.previewText&&{previewText:e.previewText},...l&&{topicId:l},...e.send&&{send:!0},...e.send&&e.scheduledAt&&{scheduledAt:e.scheduledAt}};if(e.dryRun){E({dryRun:!0,request:d},{json:o.json});return}await L({loading:"Creating broadcast...",sdkCall:c=>c.broadcasts.create(d),onInteractive:c=>{e.send?e.scheduledAt?console.log(`Broadcast scheduled: ${c.id}`):console.log(`Broadcast sent: ${c.id}`):(console.log(`Broadcast created: ${c.id}`),console.log("Status: draft"),console.log(`Send it with: resend broadcasts send ${c.id}`))}},o)});function vr(e){switch(e){case"draft":return"\u25CB Draft";case"queued":return"\u23F3 Queued";case"sent":return"\u2713 Sent";default:return e}}var It={resource:"broadcast",resourcePlural:"broadcasts",fetchItems:(e,{limit:t,after:o})=>e.broadcasts.list({limit:t,...o&&{after:o}}),display:e=>({label:e.name??"(untitled)",hint:e.id})},$a={resource:"broadcast",resourcePlural:"broadcasts",fetchItems:(e,{limit:t,after:o})=>e.broadcasts.list({limit:t,...o&&{after:o}}),display:e=>({label:e.name??"(untitled)",hint:`${vr(e.status)} ${e.id}`}),filter:e=>e.status==="draft"};function Ha(e){let t=e.map(o=>[o.name??"(untitled)",o.status,o.created_at,o.id]);return B(["Name","Status","Created","ID"],t,"(no broadcasts)")}var Ga=new p("delete").alias("rm").description("Delete a broadcast \u2014 draft broadcasts are removed; scheduled broadcasts are cancelled before delivery").argument("[id]","Broadcast ID").option("--yes","Skip confirmation prompt").addHelpText("after",m({context:`Warning: Deleting a scheduled broadcast cancels its delivery immediately.
|
|
353
353
|
Only draft and scheduled broadcasts can be deleted; sent broadcasts cannot.
|
|
354
354
|
|
|
355
355
|
Non-interactive: --yes is required to confirm deletion when stdin/stdout is not a TTY.`,output:' {"object":"broadcast","id":"<id>","deleted":true}',errorCodes:["auth_error","confirmation_required","delete_error"],examples:["resend broadcasts delete d1c2b3a4-5e6f-7a8b-9c0d-e1f2a3b4c5d6 --yes","resend broadcasts delete d1c2b3a4-5e6f-7a8b-9c0d-e1f2a3b4c5d6 --yes --json"]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await te(e,It,i);await ee(r.id,!!t.yes,{confirmMessage:`Delete broadcast "${r.label}"?
|
|
@@ -368,7 +368,7 @@ If the broadcast is already sent or sending, the API will return an error.
|
|
|
368
368
|
|
|
369
369
|
Variable interpolation:
|
|
370
370
|
HTML bodies support triple-brace syntax for contact properties.
|
|
371
|
-
Example: {{{FIRST_NAME|Friend}}} \u2014 uses FIRST_NAME or falls back to "Friend".`,output:' {"id":"<broadcast-id>"}',errorCodes:["auth_error","no_changes","file_read_error","invalid_options","stdin_read_error","react_email_build_error","react_email_render_error","update_error"],examples:['resend broadcasts update d1c2b3a4-5e6f-7a8b-9c0d-e1f2a3b4c5d6 --subject "Updated Subject"',"resend broadcasts update d1c2b3a4-5e6f-7a8b-9c0d-e1f2a3b4c5d6 --html-file ./new-email.html",'resend broadcasts update d1c2b3a4-5e6f-7a8b-9c0d-e1f2a3b4c5d6 --name "Q1 Newsletter" --from "onboarding@resend.
|
|
371
|
+
Example: {{{FIRST_NAME|Friend}}} \u2014 uses FIRST_NAME or falls back to "Friend".`,output:' {"id":"<broadcast-id>"}',errorCodes:["auth_error","no_changes","file_read_error","invalid_options","stdin_read_error","react_email_build_error","react_email_render_error","update_error"],examples:['resend broadcasts update d1c2b3a4-5e6f-7a8b-9c0d-e1f2a3b4c5d6 --subject "Updated Subject"',"resend broadcasts update d1c2b3a4-5e6f-7a8b-9c0d-e1f2a3b4c5d6 --html-file ./new-email.html",'resend broadcasts update d1c2b3a4-5e6f-7a8b-9c0d-e1f2a3b4c5d6 --name "Q1 Newsletter" --from "onboarding@resend.dev" --json','echo "<p>New content</p>" | resend broadcasts update d1c2b3a4-5e6f-7a8b-9c0d-e1f2a3b4c5d6 --html-file -']})).action(async(e,t,o)=>{let i=o.optsWithGlobals();t.from==null&&t.subject==null&&t.html==null&&t.htmlFile==null&&t.text==null&&t.textFile==null&&t.reactEmail==null&&t.name==null&&g({message:"Provide at least one option to update: --from, --subject, --html, --html-file, --text, --text-file, --react-email, or --name.",code:"no_changes"},{json:i.json}),t.htmlFile==="-"&&t.textFile==="-"&&g({message:"Cannot read both --html-file and --text-file from stdin. Pipe to one and pass the other as a file path.",code:"invalid_options"},{json:i.json}),t.reactEmail!=null&&(t.html!=null||t.htmlFile!=null)&&g({message:"Cannot use --react-email with --html or --html-file",code:"invalid_options"},{json:i.json}),t.html!=null&&t.htmlFile!=null&&g({message:"--html and --html-file are mutually exclusive.",code:"invalid_options"},{json:i.json}),t.text!=null&&t.textFile!=null&&g({message:"--text and --text-file are mutually exclusive.",code:"invalid_options"},{json:i.json});let r=await y(e,It,i),n=t.reactEmail!=null?await Pe(t.reactEmail,i):t.htmlFile!=null?oe(t.htmlFile,i):t.html,s=t.textFile!=null?oe(t.textFile,i):t.text;await I({loading:"Updating broadcast...",sdkCall:a=>a.broadcasts.update(r,{...t.from!=null&&{from:t.from},...t.subject!=null&&{subject:t.subject},...n!=null&&{html:n},...s!=null&&{text:s},...t.name!=null&&{name:t.name}}),errorCode:"update_error",successMsg:`Broadcast updated: ${r}`},i)});var Wa=new p("broadcasts").description("Manage broadcasts").addHelpText("after",m({context:`Lifecycle:
|
|
372
372
|
Broadcasts follow a draft \u2192 send flow:
|
|
373
373
|
1. create \u2014 creates a draft (or sends immediately with --send)
|
|
374
374
|
2. send \u2014 sends an API-created draft (dashboard broadcasts cannot be sent via API)
|
|
@@ -379,12 +379,12 @@ Template variables:
|
|
|
379
379
|
Example: {{{FIRST_NAME|Friend}}} \u2014 uses FIRST_NAME or falls back to "Friend".
|
|
380
380
|
|
|
381
381
|
Scheduling:
|
|
382
|
-
--scheduled-at accepts ISO 8601 or natural language e.g. "in 1 hour", "tomorrow at 9am ET".`,examples:["resend broadcasts list",'resend broadcasts create --from onboarding@resend.
|
|
383
|
-
`)}function za(e){let t=mo(e,"",[]),o=[],i=e.name;o.push(`#compdef ${i}`),o.push(`# zsh completion for ${i}`),o.push(`# Generated by: ${i} completion zsh`),o.push(""),o.push(`_${i}() {`),o.push(" local cur prev cmd_path"),o.push(' cur="${words[$CURRENT]}"'),o.push(' prev="${words[$CURRENT-1]}"'),o.push("");let n=wr(e).join("|");o.push(' cmd_path=""'),o.push(" for ((i=2; i < CURRENT; i++)); do"),o.push(' case "${words[$i]}" in'),n&&o.push(` ${n}) ((i++)) ;;`),o.push(" -*) ;;"),o.push(' *) cmd_path="${cmd_path:+$cmd_path }${words[$i]}" ;;'),o.push(" esac"),o.push(" done"),o.push(""),o.push(' case "$cmd_path" in');for(let s of t){let a=s.path===e.name?"":s.path.replace(`${e.name} `,""),l=s.options.filter(f=>f.choices&&f.long),d=s.options.filter(f=>f.long),c=s.subcommands.length>0;o.push(` "${a}")`);let u=s.options.filter(f=>f.takesValue&&!f.choices);if(l.length>0||u.length>0){o.push(' case "$prev" in');for(let f of l)o.push(` ${f.long}) compadd -- ${f.choices?.join(" ")}; return ;;`);if(u.length>0){let f=u.flatMap(
|
|
382
|
+
--scheduled-at accepts ISO 8601 or natural language e.g. "in 1 hour", "tomorrow at 9am ET".`,examples:["resend broadcasts list",'resend broadcasts create --from onboarding@resend.dev --subject "Launch" --segment-id 7b1e0a3d-4c5f-4e8a-9b2d-1a3c5e7f9b2d --html "<p>Hi {{{FIRST_NAME|there}}}</p>"',"resend broadcasts send d1c2b3a4-5e6f-7a8b-9c0d-e1f2a3b4c5d6",'resend broadcasts send d1c2b3a4-5e6f-7a8b-9c0d-e1f2a3b4c5d6 --scheduled-at "in 1 hour"',"resend broadcasts get d1c2b3a4-5e6f-7a8b-9c0d-e1f2a3b4c5d6",'resend broadcasts update d1c2b3a4-5e6f-7a8b-9c0d-e1f2a3b4c5d6 --subject "Updated Subject"',"resend broadcasts delete d1c2b3a4-5e6f-7a8b-9c0d-e1f2a3b4c5d6 --yes","resend broadcasts open","resend broadcasts open d1c2b3a4-5e6f-7a8b-9c0d-e1f2a3b4c5d6"]})).addCommand(Pa).addCommand(qa).addCommand(Ma).addCommand(Qa).addCommand(Na,{isDefault:!0}).addCommand(La).addCommand(Ga);function po(e){let t=[];for(let i of e.commands)i._hidden||t.push(po(i));let o=[];for(let i of e.options)i.hidden||o.push({long:i.long,short:i.short,description:i.description,takesValue:i.required||i.optional,choices:i.argChoices});return{name:e.name(),aliases:e.aliases(),description:e.description(),subcommands:t,options:o}}function mo(e,t,o){let i=t?`${t} ${e.name}`:e.name,r=[],n=[];for(let a of e.subcommands){n.push({name:a.name,description:a.description});for(let l of a.aliases)n.push({name:l,description:a.description})}let s=[...e.options,...o];r.push({path:i,subcommands:n,options:s});for(let a of e.subcommands)r.push(...mo(a,i,o));return r}function wr(e){let t=new Set;function o(i){for(let r of i.options)r.takesValue&&(r.long&&t.add(r.long),r.short&&t.add(r.short));for(let r of i.subcommands)o(r)}return o(e),[...t]}function Va(e){let t=mo(e,"",[]),o=[],i=e.name;o.push(`# bash completion for ${i}`),o.push(`# Generated by: ${i} completion bash`),o.push(""),o.push(`_${i}_completions() {`),o.push(" local cur prev words cword"),o.push(" if type _init_completion &>/dev/null; then _init_completion || return; else"),o.push(' cur="${COMP_WORDS[COMP_CWORD]}"'),o.push(' prev="${COMP_WORDS[COMP_CWORD-1]}"'),o.push(' words=("${COMP_WORDS[@]}")'),o.push(" cword=$COMP_CWORD"),o.push(" fi"),o.push("");let n=wr(e).join("|");o.push(' local cmd_path=""'),o.push(" local i=1"),o.push(" while [ $i -lt $cword ]; do"),o.push(' case "${words[$i]}" in'),n&&o.push(` ${n}) i=$((i + 1)) ;;`),o.push(" -*) ;;"),o.push(' *) cmd_path="${cmd_path:+$cmd_path }${words[$i]}" ;;'),o.push(" esac"),o.push(" i=$((i + 1))"),o.push(" done"),o.push(""),o.push(' case "$cmd_path" in');for(let s of t){let a=s.path===e.name?"":s.path.replace(`${e.name} `,""),l=s.options.filter(b=>b.choices&&b.long),d=s.options.map(b=>b.long).filter(Boolean).join(" "),c=s.subcommands.map(b=>b.name).join(" "),u=l.length>0,f=d.length>0,A=c.length>0;if(!u&&!f&&!A)continue;o.push(` "${a}")`);let h=s.options.filter(b=>b.takesValue&&!b.choices);if(u||h.length>0){o.push(' case "$prev" in');for(let b of l)o.push(` ${b.long}) COMPREPLY=($(compgen -W "${b.choices?.join(" ")}" -- "$cur")); return ;;`);if(h.length>0){let b=h.flatMap(S=>[S.long,S.short].filter(Boolean)).join("|");o.push(` ${b}) return ;;`)}o.push(" esac")}f&&(o.push(' if [[ "$cur" == -* ]]; then'),o.push(` COMPREPLY=($(compgen -W "${d}" -- "$cur")); return`),o.push(" fi")),A&&o.push(` COMPREPLY=($(compgen -W "${c}" -- "$cur"))`),o.push(" ;;")}return o.push(" esac"),o.push("}"),o.push(""),o.push(`complete -o default -F _${i}_completions ${i}`),o.join(`
|
|
383
|
+
`)}function za(e){let t=mo(e,"",[]),o=[],i=e.name;o.push(`#compdef ${i}`),o.push(`# zsh completion for ${i}`),o.push(`# Generated by: ${i} completion zsh`),o.push(""),o.push(`_${i}() {`),o.push(" local cur prev cmd_path"),o.push(' cur="${words[$CURRENT]}"'),o.push(' prev="${words[$CURRENT-1]}"'),o.push("");let n=wr(e).join("|");o.push(' cmd_path=""'),o.push(" for ((i=2; i < CURRENT; i++)); do"),o.push(' case "${words[$i]}" in'),n&&o.push(` ${n}) ((i++)) ;;`),o.push(" -*) ;;"),o.push(' *) cmd_path="${cmd_path:+$cmd_path }${words[$i]}" ;;'),o.push(" esac"),o.push(" done"),o.push(""),o.push(' case "$cmd_path" in');for(let s of t){let a=s.path===e.name?"":s.path.replace(`${e.name} `,""),l=s.options.filter(f=>f.choices&&f.long),d=s.options.filter(f=>f.long),c=s.subcommands.length>0;o.push(` "${a}")`);let u=s.options.filter(f=>f.takesValue&&!f.choices);if(l.length>0||u.length>0){o.push(' case "$prev" in');for(let f of l)o.push(` ${f.long}) compadd -- ${f.choices?.join(" ")}; return ;;`);if(u.length>0){let f=u.flatMap(A=>[A.long,A.short].filter(Boolean)).join("|");o.push(` ${f}) _files; return ;;`)}o.push(" esac")}if(d.length>0){o.push(' if [[ "$cur" == -* ]]; then');let f=d.map(A=>`"${A.long}:${Ja(A.description)}"`).join(" ");o.push(` local -a opts=(${f}); _describe 'option' opts; return`),o.push(" fi")}if(c){let f=s.subcommands.map(A=>`"${A.name}:${Ja(A.description)}"`).join(" ");o.push(` local -a cmds=(${f}); _describe 'command' cmds`)}else o.push(" _files");o.push(" ;;")}return o.push(" esac"),o.push("}"),o.push(""),o.push(`compdef _${i} ${i}`),o.join(`
|
|
384
384
|
`)}function Ya(e){let t=e.name,o=mo(e,"",[]),i=[];i.push(`# fish completion for ${t}`),i.push(`# Generated by: ${t} completion fish`),i.push("");let r=o[0];for(let n of r.subcommands)i.push(`complete -c ${t} -n "__fish_use_subcommand" -a "${n.name}" -d "${ri(n.description)}"`);for(let n of e.options)if(n.long){let s=n.long.replace("--",""),a=`complete -c ${t} -l "${s}"`;n.short&&(a+=` -s "${n.short.replace("-","")}"`),n.takesValue&&(a+=" -r"),n.choices&&(a+=` -a "${n.choices.join(" ")}"`),a+=` -d "${ri(n.description)}"`,i.push(a)}for(let n of o.slice(1)){let s=n.path.split(" ").slice(1),l=`__fish_seen_subcommand_from ${s[s.length-1]}`;for(let d of n.subcommands)i.push(`complete -c ${t} -n "${l}" -a "${d.name}" -d "${ri(d.description)}"`);for(let d of n.options)if(d.long){let c=d.long.replace("--",""),u=`complete -c ${t} -n "${l}" -l "${c}"`;d.short&&(u+=` -s "${d.short.replace("-","")}"`),d.takesValue&&(u+=" -r"),d.choices&&(u+=` -a "${d.choices.join(" ")}"`),u+=` -d "${ri(d.description)}"`,i.push(u)}}return i.join(`
|
|
385
|
-
`)}function Ja(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/:/g,"\\:")}function ri(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Xa(e){let t=e.name,o=mo(e,"",[]),i=[];i.push(`# PowerShell completion for ${t}`),i.push(`# Generated by: ${t} completion powershell`),i.push(""),i.push(`Register-ArgumentCompleter -Native -CommandName ${t} -ScriptBlock {`),i.push(" param($wordToComplete, $commandAst, $cursorPosition)"),i.push(""),i.push(' $words = $commandAst.ToString().Substring(0, $cursorPosition) -split "\\s+"');let n=wr(e).map(s=>`"${s}"`).join(", ");i.push(" $cmdPath = @()"),i.push(` $valueFlags = @(${n})`),i.push(" for ($i = 1; $i -lt $words.Count - 1; $i++) {"),i.push(" if ($valueFlags -contains $words[$i]) { $i++; continue }"),i.push(' if ($words[$i] -notlike "-*") { $cmdPath += $words[$i] }'),i.push(" }"),i.push(' $joined = $cmdPath -join " "'),i.push(" $cur = $words[-1]"),i.push(' if ($words.Count -eq 1) { $cur = "" }'),i.push(""),i.push(' $prev = if ($words.Count -ge 2) { $words[-2] } else { "" }'),i.push(""),i.push(" switch ($joined) {");for(let s of o){let a=s.path===e.name?"":s.path.replace(`${e.name} `,""),l=s.options.filter(
|
|
385
|
+
`)}function Ja(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/:/g,"\\:")}function ri(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Xa(e){let t=e.name,o=mo(e,"",[]),i=[];i.push(`# PowerShell completion for ${t}`),i.push(`# Generated by: ${t} completion powershell`),i.push(""),i.push(`Register-ArgumentCompleter -Native -CommandName ${t} -ScriptBlock {`),i.push(" param($wordToComplete, $commandAst, $cursorPosition)"),i.push(""),i.push(' $words = $commandAst.ToString().Substring(0, $cursorPosition) -split "\\s+"');let n=wr(e).map(s=>`"${s}"`).join(", ");i.push(" $cmdPath = @()"),i.push(` $valueFlags = @(${n})`),i.push(" for ($i = 1; $i -lt $words.Count - 1; $i++) {"),i.push(" if ($valueFlags -contains $words[$i]) { $i++; continue }"),i.push(' if ($words[$i] -notlike "-*") { $cmdPath += $words[$i] }'),i.push(" }"),i.push(' $joined = $cmdPath -join " "'),i.push(" $cur = $words[-1]"),i.push(' if ($words.Count -eq 1) { $cur = "" }'),i.push(""),i.push(' $prev = if ($words.Count -ge 2) { $words[-2] } else { "" }'),i.push(""),i.push(" switch ($joined) {");for(let s of o){let a=s.path===e.name?"":s.path.replace(`${e.name} `,""),l=s.options.filter(b=>b.choices&&b.long),d=s.options.map(b=>b.long).filter(Boolean).map(b=>`"${b}"`).join(", "),c=s.subcommands.map(b=>`"${b.name}"`).join(", "),u=l.length>0,f=d.length>0,A=c.length>0;if(!u&&!f&&!A)continue;i.push(` "${a}" {`);let h=s.options.filter(b=>b.takesValue&&!b.choices);if(u||h.length>0){i.push(" switch ($prev) {");for(let b of l){let S=b.choices?.map(v=>`"${v}"`).join(", ");i.push(` "${b.long}" { @(${S}) | Where-Object { $_ -like "$cur*" } | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_) }; return }`)}if(h.length>0){let b=h.flatMap(S=>[S.long,S.short].filter(Boolean)).map(S=>`"${S}"`).join(", ");i.push(` { $_ -in @(${b}) } { return }`)}i.push(" }")}f&&(i.push(' if ($cur -like "-*") {'),i.push(` @(${d}) | Where-Object { $_ -like "$cur*" } | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_) }; return`),i.push(" }")),A&&i.push(` @(${c}) | Where-Object { $_ -like "$cur*" } | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_) }`),i.push(" }")}return i.push(" }"),i.push("}"),i.join(`
|
|
386
386
|
`)}var Za=new p("commands").description("Print the full command tree as JSON (for agents and tooling)").addHelpText("after",m({context:`Outputs every subcommand, option, and description from the CLI definition.
|
|
387
|
-
In machine mode (piped, CI, or --json), the tree is JSON you can feed to agents or scripts.`,examples:["resend commands","resend commands --json",'resend commands | jq ".subcommands[].name"']})).action((e,t)=>{let o=t.parent;if(!o)throw new Error("commands must be registered on the root program");let i=t.optsWithGlobals(),r=po(o);
|
|
387
|
+
In machine mode (piped, CI, or --json), the tree is JSON you can feed to agents or scripts.`,examples:["resend commands","resend commands --json",'resend commands | jq ".subcommands[].name"']})).action((e,t)=>{let o=t.parent;if(!o)throw new Error("commands must be registered on the root program");let i=t.optsWithGlobals(),r=po(o);E(r,{json:i.json})});var fe=require("node:fs"),mt=require("node:os"),Oe=require("node:path");J();var ol=["bash","zsh","fish","powershell"],ni="# resend shell completion";function $m(){let e=process.env.SHELL;if(e){let t=(0,Oe.basename)(e);if(t==="bash")return"bash";if(t==="zsh")return"zsh";if(t==="fish")return"fish"}if(process.env.PSModulePath)return"powershell"}async function Hm(e){if(e)return e;let t=$m();if(t)return t;U()||(process.stderr.write(`error: could not detect shell. Pass the shell name explicitly.
|
|
388
388
|
`),process.exit(1));let o=await ce({message:"Which shell do you use?",options:ol.map(i=>({value:i,label:i}))});return x(o)&&R("Cancelled."),o}function el(e){switch(e){case"bash":return process.platform==="darwin"?(0,Oe.join)((0,mt.homedir)(),".bash_profile"):(0,Oe.join)((0,mt.homedir)(),".bashrc");case"zsh":return(0,Oe.join)((0,mt.homedir)(),".zshrc");case"powershell":return process.platform==="win32"?(0,Oe.join)((0,mt.homedir)(),"Documents","PowerShell","Microsoft.PowerShell_profile.ps1"):(0,Oe.join)((0,mt.homedir)(),".config","powershell","Microsoft.PowerShell_profile.ps1")}}function Gm(e,t){switch(e){case"bash":return Va(t);case"zsh":return za(t);case"fish":return Ya(t);case"powershell":return Xa(t)}}function tl(e,t,o){(0,fe.existsSync)(e)||(0,fe.mkdirSync)(e,{recursive:!0});let i=(0,Oe.join)(e,t);return(0,fe.writeFileSync)(i,`${o}
|
|
389
389
|
`),i}function Qm(e,t){switch(e){case"zsh":{let o=(0,Oe.join)((0,mt.homedir)(),".zsh","completions"),i=tl(o,"_resend",t);X.success(`Completions written to ${i}`);let r=el(e),n=!0;if((0,fe.existsSync)(r)&&(0,fe.readFileSync)(r,"utf8").includes(o)&&(n=!1),n){let s=`${ni}
|
|
390
390
|
fpath=(${o} $fpath)
|
|
@@ -425,7 +425,7 @@ Reserved keys (cannot be used): FIRST_NAME, LAST_NAME, EMAIL, UNSUBSCRIBE_URL
|
|
|
425
425
|
|
|
426
426
|
Non-interactive: --key and --type are required. --fallback-value is optional.
|
|
427
427
|
Warning: do not create properties with reserved key names \u2014 they will conflict with
|
|
428
|
-
built-in contact fields and may cause unexpected behavior in broadcasts.`,output:' {"object":"contact_property","id":"<id>"}',errorCodes:["auth_error","missing_key","missing_type","invalid_fallback_value","create_error"],examples:["resend contact-properties create --key company_name --type string",'resend contact-properties create --key company_name --type string --fallback-value "Unknown"',"resend contact-properties create --key employee_count --type number --fallback-value 0","resend contact-properties create --key department --type string --json"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=await O(e.key,{message:"Property key",placeholder:"e.g. company_name"},{message:"Missing --key flag.",code:"missing_key"},o),r=await
|
|
428
|
+
built-in contact fields and may cause unexpected behavior in broadcasts.`,output:' {"object":"contact_property","id":"<id>"}',errorCodes:["auth_error","missing_key","missing_type","invalid_fallback_value","create_error"],examples:["resend contact-properties create --key company_name --type string",'resend contact-properties create --key company_name --type string --fallback-value "Unknown"',"resend contact-properties create --key employee_count --type number --fallback-value 0","resend contact-properties create --key department --type string --json"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=await O(e.key,{message:"Property key",placeholder:"e.g. company_name"},{message:"Missing --key flag.",code:"missing_key"},o),r=await Et(e.type,{message:"Property data type",options:[{value:"string",label:"string \u2014 text values"},{value:"number",label:"number \u2014 numeric values"}]},{message:"Missing --type flag.",code:"missing_type"},o),n;if(e.fallbackValue!==void 0)if(r==="number"){let a=parseFloat(e.fallbackValue);Number.isNaN(a)&&g({message:"--fallback-value must be a valid number for number-type properties.",code:"invalid_fallback_value"},{json:o.json}),n=a}else n=e.fallbackValue;let s={key:i,type:r,...n!==void 0&&{fallbackValue:n}};await L({loading:"Creating contact property...",sdkCall:a=>a.contactProperties.create(s),onInteractive:a=>{console.log(`Contact property created: ${a.id}`)}},o)});var Pt={resource:"contact property",resourcePlural:"contact properties",fetchItems:(e,{limit:t,after:o})=>e.contactProperties.list({limit:t,...o&&{after:o}}),display:e=>({label:`${e.key} (${e.type})`,hint:e.id})};function nl(e){let t=e.map(o=>[o.key,o.type,o.fallbackValue!=null?String(o.fallbackValue):"",o.id,o.createdAt]);return B(["Key","Type","Fallback Value","ID","Created"],t,"(no contact properties)")}var sl=new p("delete").alias("rm").description("Delete a contact property definition").argument("[id]","Contact property UUID").option("--yes","Skip the confirmation prompt (required in non-interactive mode)").addHelpText("after",m({context:`WARNING: Deleting a property definition removes that property value from ALL contacts
|
|
429
429
|
permanently. This cannot be undone, and any broadcasts that reference this property key
|
|
430
430
|
via {{{PROPERTY_NAME}}} will render an empty string or their inline fallback instead.
|
|
431
431
|
|
|
@@ -468,7 +468,7 @@ Supported types:
|
|
|
468
468
|
number \u2014 numeric values (useful for counts, scores, thresholds)
|
|
469
469
|
|
|
470
470
|
Note: property keys and types are immutable after creation. Only the fallback value can
|
|
471
|
-
be updated. Deleting a property removes it from all contacts.`,examples:["resend contact-properties list","resend contact-properties create --key company_name --type string",'resend contact-properties create --key plan --type string --fallback-value "free"',"resend contact-properties create --key score --type number --fallback-value 0","resend contact-properties get b4a3c2d1-6e5f-8a7b-0c9d-2e1f4a3b6c5d",'resend contact-properties update b4a3c2d1-6e5f-8a7b-0c9d-2e1f4a3b6c5d --fallback-value "Unknown"',"resend contact-properties update b4a3c2d1-6e5f-8a7b-0c9d-2e1f4a3b6c5d --clear-fallback-value","resend contact-properties delete b4a3c2d1-6e5f-8a7b-0c9d-2e1f4a3b6c5d --yes"]})).addCommand(rl).addCommand(al).addCommand(ll,{isDefault:!0}).addCommand(cl).addCommand(sl);function si(e){let t=e.map(o=>[o.email,o.first_name??"",o.last_name??"",o.unsubscribed?"yes":"no",o.id]);return
|
|
471
|
+
be updated. Deleting a property removes it from all contacts.`,examples:["resend contact-properties list","resend contact-properties create --key company_name --type string",'resend contact-properties create --key plan --type string --fallback-value "free"',"resend contact-properties create --key score --type number --fallback-value 0","resend contact-properties get b4a3c2d1-6e5f-8a7b-0c9d-2e1f4a3b6c5d",'resend contact-properties update b4a3c2d1-6e5f-8a7b-0c9d-2e1f4a3b6c5d --fallback-value "Unknown"',"resend contact-properties update b4a3c2d1-6e5f-8a7b-0c9d-2e1f4a3b6c5d --clear-fallback-value","resend contact-properties delete b4a3c2d1-6e5f-8a7b-0c9d-2e1f4a3b6c5d --yes"]})).addCommand(rl).addCommand(al).addCommand(ll,{isDefault:!0}).addCommand(cl).addCommand(sl);function si(e){let t=e.map(o=>[o.email,o.first_name??"",o.last_name??"",o.unsubscribed?"yes":"no",o.id]);return B(["Email","First Name","Last Name","Unsubscribed","ID"],t,"(no contacts)")}function dl(e){let t=e.map(o=>[o.name,o.subscription,o.id,o.description??""]);return B(["Name","Subscription","ID","Description"],t,"(no topic subscriptions)")}var Ae={resource:"contact",resourcePlural:"contacts",fetchItems:(e,{limit:t,after:o})=>e.contacts.list({limit:t,...o&&{after:o}}),display:e=>({label:e.email,hint:e.id})};function $t(e){return e.includes("@")?{email:e}:{id:e}}function Ht(e){return e.includes("@")?{email:e}:{contactId:e}}function ai(e,t){let o;try{o=JSON.parse(e)}catch{g({message:"Invalid --topics JSON. Expected an array of {id, subscription} objects.",code:"invalid_topics"},{json:t.json})}return Array.isArray(o)||g({message:"Invalid --topics JSON. Expected an array of {id, subscription} objects.",code:"invalid_topics"},{json:t.json}),o}function li(e,t){if(e)try{return JSON.parse(e)}catch{g({message:"Invalid --properties JSON.",code:"invalid_properties"},{json:t.json})}}var pl=new p("add-segment").description("Add a contact to a segment").argument("[contactId]","Contact UUID or email address").option("--segment-id <id>","Segment ID to add the contact to (required)").addHelpText("after",m({context:`The <contactId> argument accepts either a UUID or an email address.
|
|
472
472
|
|
|
473
473
|
Non-interactive: --segment-id is required.`,output:' {"id":"<segment-membership-id>"}',errorCodes:["auth_error","missing_segment_id","add_segment_error"],examples:["resend contacts add-segment e169aa45-1ecf-4183-9955-b1499d5701d3 --segment-id 78261eea-8f8b-4381-83c6-79fa7120f1cf","resend contacts add-segment steve.wozniak@gmail.com --segment-id 78261eea-8f8b-4381-83c6-79fa7120f1cf --json"]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await y(e,Ae,i),n=await y(t.segmentId,$e,i),s={...Ht(r),segmentId:n};await I({loading:"Adding contact to segment...",sdkCall:a=>a.contacts.segments.add(s),errorCode:"add_segment_error",successMsg:`Contact added to segment: ${n}`},i)});J();var ml=new p("create").description("Create a new contact").option("--email <email>","Contact email address (required)").option("--first-name <name>","First name").option("--last-name <name>","Last name").option("--unsubscribed","Globally unsubscribe the contact from all broadcasts").option("--properties <json>",`Custom properties as a JSON string (e.g. '{"company":"Acme"}')`).option("--segment-id <id...>","Segment ID to add the contact to on creation (repeatable: --segment-id abc --segment-id def)").addHelpText("after",m({context:`Non-interactive: --email is required. All other flags are optional.
|
|
474
474
|
|
|
@@ -491,7 +491,7 @@ This cannot be undone.`,loading:"Deleting contact...",object:"contact",successMs
|
|
|
491
491
|
"created_at": "2026-01-01T00:00:00.000Z",
|
|
492
492
|
"unsubscribed": false,
|
|
493
493
|
"properties": {}
|
|
494
|
-
}`,errorCodes:["auth_error","fetch_error"],examples:["resend contacts get e169aa45-1ecf-4183-9955-b1499d5701d3","resend contacts get steve.wozniak@gmail.com","resend contacts get e169aa45-1ecf-4183-9955-b1499d5701d3 --json"]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await y(e,Ae,i);await Q({loading:"Fetching contact...",sdkCall:n=>n.contacts.get(r),onInteractive:n=>{let s=[n.first_name,n.last_name].filter(Boolean).join(" ");console.log(`${n.email}${s?` (${s})`:""}`),console.log(`ID: ${n.id}`),console.log(`Created: ${n.created_at}`),console.log(`Unsubscribed: ${n.unsubscribed?"yes":"no"}`);let a=Object.entries(n.properties??{});if(a.length>0){console.log("Properties:");for(let[l,d]of a)console.log(` ${l}: ${d.value}`)}}},i)});var Cl=require("node:fs"),yl=require("node:path");function hl(e){let t=e.map(o=>[o.status,String(o.counts.total),String(o.counts.created),String(o.counts.updated),String(o.counts.skipped),String(o.counts.failed),o.created_at,o.id]);return
|
|
494
|
+
}`,errorCodes:["auth_error","fetch_error"],examples:["resend contacts get e169aa45-1ecf-4183-9955-b1499d5701d3","resend contacts get steve.wozniak@gmail.com","resend contacts get e169aa45-1ecf-4183-9955-b1499d5701d3 --json"]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await y(e,Ae,i);await Q({loading:"Fetching contact...",sdkCall:n=>n.contacts.get(r),onInteractive:n=>{let s=[n.first_name,n.last_name].filter(Boolean).join(" ");console.log(`${n.email}${s?` (${s})`:""}`),console.log(`ID: ${n.id}`),console.log(`Created: ${n.created_at}`),console.log(`Unsubscribed: ${n.unsubscribed?"yes":"no"}`);let a=Object.entries(n.properties??{});if(a.length>0){console.log("Properties:");for(let[l,d]of a)console.log(` ${l}: ${d.value}`)}}},i)});var Cl=require("node:fs"),yl=require("node:path");function hl(e){let t=e.map(o=>[o.status,String(o.counts.total),String(o.counts.created),String(o.counts.updated),String(o.counts.skipped),String(o.counts.failed),o.created_at,o.id]);return B(["Status","Total","Created","Updated","Skipped","Failed","Created At","ID"],t,"(no contact imports)")}var Al={resource:"contact import",resourcePlural:"contact imports",fetchItems:(e,{limit:t,after:o})=>e.contacts.imports.list({limit:t,...o&&{after:o}}),display:e=>({label:`${e.status} - ${e.counts.total} contacts`,hint:e.id})};function bl(e,t){if(!e)return;let o;try{o=JSON.parse(e)}catch{g({message:"Invalid --column-map JSON.",code:"invalid_column_map"},{json:t.json})}return(typeof o!="object"||o===null||Array.isArray(o))&&g({message:"Invalid --column-map JSON. Expected an object mapping contact fields to CSV column headers.",code:"invalid_column_map"},{json:t.json}),o}var Ul=new p("create").description("Import contacts in bulk from a local CSV file").option("--file <path>","Path to the CSV file to import (required)").option("--column-map <json>",`Map CSV columns to contact fields as a JSON object (e.g. '{"email":"Email","firstName":"First Name"}')`).addOption(new V("--on-conflict <strategy>","How to handle contacts that already exist").choices(["upsert","skip"])).option("--segment-id <id...>","Segment ID to add imported contacts to (repeatable: --segment-id abc --segment-id def)").option("--topics <json>","Topic subscriptions as a JSON array of {id, subscription} objects").addHelpText("after",m({context:`Non-interactive: --file is required. All other flags are optional.
|
|
495
495
|
|
|
496
496
|
The CSV file is uploaded as multipart form data (max 100MB).
|
|
497
497
|
|
|
@@ -549,7 +549,7 @@ Topics JSON format:
|
|
|
549
549
|
subscription values: "opt_in" | "opt_out"
|
|
550
550
|
|
|
551
551
|
This operation replaces all topic subscriptions for the specified topics.
|
|
552
|
-
Topics not included in the array are left unchanged.`,output:' {"id":"<contact-id>"}',errorCodes:["auth_error","missing_topics","invalid_topics","update_topics_error"],examples:[`resend contacts update-topics e169aa45-1ecf-4183-9955-b1499d5701d3 --topics '[{"id":"b6d24b8e-af0b-4c3c-be0c-359bbd97381e","subscription":"opt_in"}]'`,`resend contacts update-topics steve.wozniak@gmail.com --topics '[{"id":"b6d24b8e-af0b-4c3c-be0c-359bbd97381e","subscription":"opt_out"},{"id":"07d84122-7224-4881-9c31-1c048e204602","subscription":"opt_in"}]' --json`]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await y(e,Ae,i),n=await Y(i),s=t.topics;if(!s){(!U()||i.json)&&g({message:"Missing --topics flag.",code:"missing_topics"},{json:i.json});let d=await Z({message:`Topics JSON (e.g. '[{"id":"topic-uuid","subscription":"opt_in"}]')`,placeholder:'[{"id":"topic-uuid","subscription":"opt_in"}]',validate:c=>c?void 0:"Required"});x(d)&&R("Cancelled."),s=d}let a=ai(s,i),l=await de("Updating topic subscriptions...",()=>n.contacts.topics.update({...$t(r),topics:a}),"update_topics_error",i);!i.json&&U()?console.log(`Topic subscriptions updated for contact: ${r}`):
|
|
552
|
+
Topics not included in the array are left unchanged.`,output:' {"id":"<contact-id>"}',errorCodes:["auth_error","missing_topics","invalid_topics","update_topics_error"],examples:[`resend contacts update-topics e169aa45-1ecf-4183-9955-b1499d5701d3 --topics '[{"id":"b6d24b8e-af0b-4c3c-be0c-359bbd97381e","subscription":"opt_in"}]'`,`resend contacts update-topics steve.wozniak@gmail.com --topics '[{"id":"b6d24b8e-af0b-4c3c-be0c-359bbd97381e","subscription":"opt_out"},{"id":"07d84122-7224-4881-9c31-1c048e204602","subscription":"opt_in"}]' --json`]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await y(e,Ae,i),n=await Y(i),s=t.topics;if(!s){(!U()||i.json)&&g({message:"Missing --topics flag.",code:"missing_topics"},{json:i.json});let d=await Z({message:`Topics JSON (e.g. '[{"id":"topic-uuid","subscription":"opt_in"}]')`,placeholder:'[{"id":"topic-uuid","subscription":"opt_in"}]',validate:c=>c?void 0:"Required"});x(d)&&R("Cancelled."),s=d}let a=ai(s,i),l=await de("Updating topic subscriptions...",()=>n.contacts.topics.update({...$t(r),topics:a}),"update_topics_error",i);!i.json&&U()?console.log(`Topic subscriptions updated for contact: ${r}`):E(l,{json:i.json})});var Dl=new p("contacts").description("Manage contacts").addHelpText("after",m({context:`Contacts are global entities (not audience-scoped since the 2025 migration).
|
|
553
553
|
Each contact is identified by a UUID or email address \u2014 both are accepted in all subcommands.
|
|
554
554
|
|
|
555
555
|
Properties:
|
|
@@ -566,7 +566,7 @@ Segments:
|
|
|
566
566
|
Manage membership with "resend contacts add-segment" and "resend contacts remove-segment".
|
|
567
567
|
|
|
568
568
|
Imports:
|
|
569
|
-
Bulk-import contacts from a CSV file with "resend contacts imports create --file <path>".`,examples:["resend contacts list","resend contacts create --email steve.wozniak@gmail.com --first-name Steve","resend contacts get e169aa45-1ecf-4183-9955-b1499d5701d3","resend contacts get steve.wozniak@gmail.com","resend contacts update acme@example.com --unsubscribed","resend contacts delete e169aa45-1ecf-4183-9955-b1499d5701d3 --yes","resend contacts segments steve.wozniak@gmail.com","resend contacts add-segment steve.wozniak@gmail.com --segment-id 78261eea-8f8b-4381-83c6-79fa7120f1cf","resend contacts remove-segment steve.wozniak@gmail.com 78261eea-8f8b-4381-83c6-79fa7120f1cf","resend contacts topics steve.wozniak@gmail.com",`resend contacts update-topics steve.wozniak@gmail.com --topics '[{"id":"b6d24b8e-af0b-4c3c-be0c-359bbd97381e","subscription":"opt_in"}]'`,"resend contacts imports create --file ./contacts.csv"]})).addCommand(ml).addCommand(gl).addCommand(wl,{isDefault:!0}).addCommand(Rl).addCommand(fl).addCommand(Fl).addCommand(pl).addCommand(xl).addCommand(kl).addCommand(_l).addCommand(vl);var
|
|
569
|
+
Bulk-import contacts from a CSV file with "resend contacts imports create --file <path>".`,examples:["resend contacts list","resend contacts create --email steve.wozniak@gmail.com --first-name Steve","resend contacts get e169aa45-1ecf-4183-9955-b1499d5701d3","resend contacts get steve.wozniak@gmail.com","resend contacts update acme@example.com --unsubscribed","resend contacts delete e169aa45-1ecf-4183-9955-b1499d5701d3 --yes","resend contacts segments steve.wozniak@gmail.com","resend contacts add-segment steve.wozniak@gmail.com --segment-id 78261eea-8f8b-4381-83c6-79fa7120f1cf","resend contacts remove-segment steve.wozniak@gmail.com 78261eea-8f8b-4381-83c6-79fa7120f1cf","resend contacts topics steve.wozniak@gmail.com",`resend contacts update-topics steve.wozniak@gmail.com --topics '[{"id":"b6d24b8e-af0b-4c3c-be0c-359bbd97381e","subscription":"opt_in"}]'`,"resend contacts imports create --file ./contacts.csv"]})).addCommand(ml).addCommand(gl).addCommand(wl,{isDefault:!0}).addCommand(Rl).addCommand(fl).addCommand(Fl).addCommand(pl).addCommand(xl).addCommand(kl).addCommand(_l).addCommand(vl);var Bl=new p("docs").description("Open the Resend documentation in your browser").addHelpText("after",m({context:"Opens https://resend.com/docs in your default browser.",examples:["resend docs"]})).action(async(e,t)=>{let o=t.optsWithGlobals();await Re(me.documentation,o)});he();ur();Go();J();fo();bt();var kr="TimeoutError",Pl=(e,t)=>{let o,i=new Promise((r,n)=>{o=setTimeout(()=>{let s=new Error(`Operation timed out after ${t}ms`);s.name=kr,n(s)},t)});return Promise.race([e,i]).finally(()=>{clearTimeout(o)})};var Wm=5e3;function Jm(e){return e instanceof Error&&e.name===gr}async function Vm(){try{let e=await fetch(xr,{headers:{Accept:"application/vnd.github.v3+json"},signal:AbortSignal.timeout(5e3)});if(!e.ok)return{name:"CLI Version",status:"warn",message:`v${re} (could not check for updates)`};let t=await e.json();if(t.prerelease||t.draft)return{name:"CLI Version",status:"warn",message:`v${re} (could not check for updates)`};let o=t.tag_name?.replace(/^v/,"")??"unknown";return o===re?{name:"CLI Version",status:"pass",message:`v${re} (latest)`}:{name:"CLI Version",status:"warn",message:`v${re} (latest: v${o})`,detail:"Update available"}}catch{return{name:"CLI Version",status:"warn",message:`v${re} (could not check for updates)`}}}async function zm(e){let t;try{t=await St(e,void 0,{refresh:!1})}catch(n){return{name:"API Key",status:"fail",message:q(n,"Authentication failed"),detail:"Run: resend login"}}if(!t)return{name:"API Key",status:"fail",message:"No API key found",detail:"Run: resend login"};let o=t.type==="api_key"?t.key:t.access_token,i=t.profile?`, profile: ${t.profile}`:"",r=t.type==="oauth_grant"?`${t.source} (oauth)`:t.source;return{name:"API Key",status:"pass",message:`${dt(o)} (source: ${r}${i})`}}async function Ym(e){let t;try{t=await St(e)}catch(r){let n=Jm(r);return{name:"API Validation",status:n?"warn":"fail",message:q(r,"Authentication failed"),...n?{}:{detail:"Run: resend login"}}}if(!t)return{name:"API Validation",status:"fail",message:"Skipped \u2014 no API key"};let o=t.type==="api_key"?t.key:t.access_token,i=t.type==="api_key"?"API key":"credential";try{let r=new kt(o),{data:n,error:s}=await Pl(r.domains.list(),Wm);if(s){let c=s;return c.name==="restricted_api_key"?{name:"API Validation",status:"warn",message:`Sending-only ${i}`,detail:_t}:c.name==="application_error"?{name:"API Validation",status:"warn",message:"Network error. Check your connection and try again"}:{name:"API Validation",status:"fail",message:`Invalid ${i}: ${s.message}`}}let a=n?.data??[],l=a.filter(c=>c.status==="verified"),d=a.filter(c=>c.status!=="verified");return a.length===0?{name:"Domains",status:"warn",message:"No domains configured",detail:"Add a domain at https://resend.com/domains"}:l.length===0?{name:"Domains",status:"warn",message:`${d.length} domain(s) pending verification`,detail:a.map(c=>`${c.name} (${c.status})`).join(", ")}:{name:"Domains",status:"pass",message:`${l.length} verified, ${d.length} pending`,detail:a.map(c=>`${c.name} (${c.status})`).join(", ")}}catch(r){return r instanceof Error&&r.name===kr?{name:"API Validation",status:"warn",message:"Request timed out"}:{name:"API Validation",status:"fail",message:q(r,`Failed to validate ${i}`)}}}var $l=new p("doctor").description("Check CLI version, API key, and domain status").addHelpText("after",m({setup:!0,context:`Checks performed:
|
|
570
570
|
CLI Version Is the installed version up to date?
|
|
571
571
|
API Key Is a key present (--api-key, RESEND_API_KEY, or credentials file)?
|
|
572
572
|
Credential Storage Which backend is storing credentials (secure storage vs plaintext file)?
|
|
@@ -581,7 +581,7 @@ Imports:
|
|
|
581
581
|
status values: "pass" | "warn" | "fail"
|
|
582
582
|
Exit code 1 if any check has status "fail"`,examples:["resend doctor","resend doctor --json"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=[],r=U()&&!o.json;r&&console.log(`
|
|
583
583
|
Resend Doctor
|
|
584
|
-
`);let n=r?ne("Checking CLI version..."):null,s=await Vm();i.push(s),s.status==="warn"?n?.warn(s.message):n?.stop(s.message),n=r?ne("Checking API key..."):null;let a=await zm(o.apiKey);i.push(a),a.status==="fail"?n?.fail(a.message):n?.stop(a.message),n=r?ne("Checking credential storage..."):null;let l=await Xe(),d=Ue(),c=l.isSecure,u={name:"Credential Storage",status:c?"pass":"warn",message:c?l.name:"plaintext file",...!c&&process.env.RESEND_CREDENTIAL_STORE!=="file"&&(d?.storage==="secure_storage"||process.env.RESEND_CREDENTIAL_STORE==="secure_storage")?{detail:"Secure backend unavailable despite secure storage preference \u2014 falling back to plaintext"}:{}};i.push(u),u.status==="warn"?n?.warn(u.message):n?.stop(u.message),n=r?ne("Validating API key & domains..."):null;let f=await Ym(o.apiKey);i.push(f),f.status==="fail"?n?.fail(f.message):f.status==="warn"?n?.warn(f.message):n?.stop(f.message);let
|
|
584
|
+
`);let n=r?ne("Checking CLI version..."):null,s=await Vm();i.push(s),s.status==="warn"?n?.warn(s.message):n?.stop(s.message),n=r?ne("Checking API key..."):null;let a=await zm(o.apiKey);i.push(a),a.status==="fail"?n?.fail(a.message):n?.stop(a.message),n=r?ne("Checking credential storage..."):null;let l=await Xe(),d=Ue(),c=l.isSecure,u={name:"Credential Storage",status:c?"pass":"warn",message:c?l.name:"plaintext file",...!c&&process.env.RESEND_CREDENTIAL_STORE!=="file"&&(d?.storage==="secure_storage"||process.env.RESEND_CREDENTIAL_STORE==="secure_storage")?{detail:"Secure backend unavailable despite secure storage preference \u2014 falling back to plaintext"}:{}};i.push(u),u.status==="warn"?n?.warn(u.message):n?.stop(u.message),n=r?ne("Validating API key & domains..."):null;let f=await Ym(o.apiKey);i.push(f),f.status==="fail"?n?.fail(f.message):f.status==="warn"?n?.warn(f.message):n?.stop(f.message);let A=i.some(h=>h.status==="fail");!o.json&&U()?console.log(""):E({ok:!A,checks:i},{json:o.json}),A&&process.exit(1)});var Hl=new p("create").description("Start a claim for a domain another Resend account has verified").option("--name <domain>","Domain name to claim (e.g. example.com)").addOption(new V("--region <region>","Sending region").choices(["us-east-1","eu-west-1","sa-east-1","ap-northeast-1"])).option("--tracking-subdomain <subdomain>","Subdomain for click and open tracking (e.g. track)").option("--custom-return-path <subdomain>","Subdomain for the Return-Path address (e.g. bounce)").option("--open-tracking","Enable open tracking").option("--no-open-tracking","Disable open tracking").option("--click-tracking","Enable click tracking").option("--no-click-tracking","Disable click tracking").addHelpText("after",m({context:"Non-interactive: --name is required (no prompts when stdin/stdout is not a TTY)",output:" domain_claim object with the placeholder domain_id and the TXT record to add to DNS.",errorCodes:["auth_error","missing_name","create_error"],examples:["resend domains claim create --name example.com","resend domains claim create --name example.com --region eu-west-1","resend domains claim create --name example.com --json"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=await O(e.name,{message:"Domain name to claim",placeholder:"example.com"},{message:"Missing --name flag.",code:"missing_name"},o);await L({loading:"Starting domain claim...",sdkCall:r=>r.domains.claims.create({name:i,...e.region&&{region:e.region},...e.customReturnPath!==void 0&&{customReturnPath:e.customReturnPath},...e.openTracking!==void 0&&{openTracking:e.openTracking},...e.clickTracking!==void 0&&{clickTracking:e.clickTracking},...e.trackingSubdomain!==void 0&&{trackingSubdomain:e.trackingSubdomain}}),onInteractive:r=>{console.log(`Claim started for ${r.name} (claim id: ${r.id}, domain id: ${r.domain_id})`),console.log(`Status: ${r.status}`),console.log(`
|
|
585
585
|
Add this TXT record at your DNS provider:`),console.log(` ${r.record.name} TXT ${r.record.value}`),console.log(`
|
|
586
586
|
Then run \`resend domains claim verify ${r.domain_id}\`.`)}},o)});var Gl=new p("get").description("Retrieve the latest claim for a domain").argument("[id]","Domain ID (the placeholder domain created by the claim)").addHelpText("after",m({output:` domain_claim object: status, domain_id, the TXT record, blocked_reason, expires_at.
|
|
587
587
|
|
|
@@ -605,7 +605,7 @@ Poll the status with: resend domains get <id>`,output:' {"object":"domain","id"
|
|
|
605
605
|
1. resend domains create --name example.com (get DNS records)
|
|
606
606
|
2. Configure DNS records at your DNS provider
|
|
607
607
|
3. resend domains verify <id> (trigger verification)
|
|
608
|
-
4. resend domains get <id> (poll until "verified")`,examples:["resend domains list","resend domains create --name example.com --region us-east-1","resend domains verify 4dd369bc-aa82-4ff3-97de-514ae3000ee0","resend domains get 4dd369bc-aa82-4ff3-97de-514ae3000ee0","resend domains update <id> --tls enforced --open-tracking","resend domains delete <id> --yes","resend domains claim create --name example.com"]})).addCommand(ql).addCommand(Vl).addCommand(Ll).addCommand(Wl,{isDefault:!0}).addCommand(Jl).addCommand(Ml).addCommand(Nl);var Ve={resource:"email",resourcePlural:"emails",fetchItems:(e,{limit:t,after:o})=>e.emails.list({limit:t,...o&&{after:o}}),display:e=>({label:e.subject||"(no subject)",hint:e.id})};function Yl(e){return{resource:"attachment",resourcePlural:"attachments",fetchItems:(t,{limit:o,after:i})=>t.emails.attachments.list({emailId:e,limit:o,...i&&{after:i}}),display:t=>({label:t.filename??"(unnamed)",hint:t.id})}}function di(e){let t=e.map(o=>[o.filename??"(unnamed)",o.content_type,String(o.size),o.id]);return
|
|
608
|
+
4. resend domains get <id> (poll until "verified")`,examples:["resend domains list","resend domains create --name example.com --region us-east-1","resend domains verify 4dd369bc-aa82-4ff3-97de-514ae3000ee0","resend domains get 4dd369bc-aa82-4ff3-97de-514ae3000ee0","resend domains update <id> --tls enforced --open-tracking","resend domains delete <id> --yes","resend domains claim create --name example.com"]})).addCommand(ql).addCommand(Vl).addCommand(Ll).addCommand(Wl,{isDefault:!0}).addCommand(Jl).addCommand(Ml).addCommand(Nl);var Ve={resource:"email",resourcePlural:"emails",fetchItems:(e,{limit:t,after:o})=>e.emails.list({limit:t,...o&&{after:o}}),display:e=>({label:e.subject||"(no subject)",hint:e.id})};function Yl(e){return{resource:"attachment",resourcePlural:"attachments",fetchItems:(t,{limit:o,after:i})=>t.emails.attachments.list({emailId:e,limit:o,...i&&{after:i}}),display:t=>({label:t.filename??"(unnamed)",hint:t.id})}}function di(e){let t=e.map(o=>[o.filename??"(unnamed)",o.content_type,String(o.size),o.id]);return B(["Filename","Content-Type","Size (bytes)","ID"],t,"(no attachments)")}var Xl=new p("attachment").description("Retrieve a single attachment from a sent (outbound) email").argument("[emailId]","Email UUID").argument("[attachmentId]","Attachment UUID").addHelpText("after",m({context:`The download_url is a signed URL that expires in ~1 hour. Download the file directly:
|
|
609
609
|
resend emails attachment <emailId> <attachmentId> --json | jq -r .download_url | xargs curl -O`,output:' {"object":"attachment","id":"<uuid>","filename":"invoice.pdf","size":51200,"content_type":"application/pdf","content_disposition":"attachment","content_id":null,"download_url":"<signed-url>","expires_at":"<iso-date>"}',errorCodes:["auth_error","fetch_error"],examples:["resend emails attachment <email-id> <attachment-id>","resend emails attachment <email-id> <attachment-id> --json"]})).action(async(e,t,o,i)=>{let r=i.optsWithGlobals(),n=await y(e,Ve,r),s=await y(t,Yl(n),r);await Q({loading:"Fetching attachment...",sdkCall:a=>a.emails.attachments.get({emailId:n,id:s}),onInteractive:a=>{console.log(`${a.filename??"(unnamed)"}`),console.log(`ID: ${a.id}`),console.log(`Content-Type: ${a.content_type}`),console.log(`Size: ${a.size} bytes`),console.log(`Disposition: ${a.content_disposition}`),console.log(`Download URL: ${a.download_url}`),console.log(`Expires: ${a.expires_at}`)}},r)});var Zl=new p("attachments").description("List attachments on a sent (outbound) email").argument("[emailId]","Email UUID").option("--limit <n>","Maximum number of attachments to return (1-100)","10").option("--after <cursor>","Return attachments after this cursor (next page)").option("--before <cursor>","Return attachments before this cursor (previous page)").addHelpText("after",m({context:`Each attachment has a download_url (signed, expires ~1 hour).
|
|
610
610
|
Use the attachment sub-command to retrieve a single attachment with its download URL:
|
|
611
611
|
resend emails attachment <emailId> <attachmentId>
|
|
@@ -613,21 +613,21 @@ Use the attachment sub-command to retrieve a single attachment with its download
|
|
|
613
613
|
content_disposition: "inline" means the attachment is embedded in the HTML body (e.g. an image).
|
|
614
614
|
content_disposition: "attachment" means it is a standalone file download.`,output:' {"object":"list","has_more":false,"data":[{"id":"<uuid>","filename":"invoice.pdf","size":51200,"content_type":"application/pdf","content_disposition":"attachment","content_id":null,"download_url":"<url>","expires_at":"<iso-date>"}]}',errorCodes:["auth_error","invalid_limit","list_error"],examples:["resend emails attachments <email-id>","resend emails attachments <email-id> --json","resend emails attachments <email-id> --limit 25 --json"]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await y(e,Ve,i),n=P(t.limit,i),s=$(n,t.after,t.before,i);await _({loading:"Fetching attachments...",sdkCall:a=>a.emails.attachments.list({emailId:r,...s}),onInteractive:a=>{console.log(di(a.data)),H(a,`emails attachments ${r}`,{limit:n,before:t.before,apiKey:i.apiKey,profile:i.profile})}},i)});J();var ec=new p("batch").description("Send up to 100 emails in a single API request from a JSON file").option("--file <path>",'Path to a JSON file containing an array of email objects (use "-" for stdin; required in non-interactive mode)').option("--react-email <path>","Path to a React Email template (.tsx) \u2014 rendered HTML is set on every email in the batch").option("--idempotency-key <key>","Deduplicate this batch request using this key").addOption(new V("--batch-validation <mode>","Validation mode: strict (default, fail all on error) or permissive (partial success)").choices(["strict","permissive"])).addHelpText("after",m({context:`Non-interactive: --file
|
|
615
615
|
Limit: 100 emails per request (API hard limit \u2014 warned if exceeded)
|
|
616
|
-
Unsupported per-email fields: attachments
|
|
616
|
+
Unsupported per-email fields: attachments
|
|
617
617
|
|
|
618
618
|
File format (--file path):
|
|
619
619
|
[
|
|
620
|
-
{"from":"onboarding@resend.
|
|
621
|
-
{"from":"onboarding@resend.
|
|
622
|
-
]`,output:' [{"id":"<email-id>"},{"id":"<email-id>"}]',errorCodes:["auth_error","missing_file","file_read_error","stdin_read_error","invalid_json","invalid_format","react_email_build_error","react_email_render_error","batch_error"],examples:["resend emails batch --file ./emails.json","resend emails batch --file ./emails.json --batch-validation permissive",`echo '[{"from":"onboarding@resend.
|
|
623
|
-
${
|
|
620
|
+
{"from":"onboarding@resend.dev","to":["delivered@resend.dev"],"subject":"Hello","text":"Hi"},
|
|
621
|
+
{"from":"onboarding@resend.dev","to":["delivered@resend.dev"],"subject":"Hello","html":"<b>Hi</b>","scheduled_at":"in 1 hour","tags":[{"name":"campaign","value":"welcome"}]}
|
|
622
|
+
]`,output:' [{"id":"<email-id>"},{"id":"<email-id>"}]',errorCodes:["auth_error","missing_file","file_read_error","stdin_read_error","invalid_json","invalid_format","react_email_build_error","react_email_render_error","batch_error"],examples:["resend emails batch --file ./emails.json","resend emails batch --file ./emails.json --batch-validation permissive",`echo '[{"from":"onboarding@resend.dev","to":["delivered@resend.dev"],"subject":"Hi","text":"Hello"}]' | resend emails batch --file -`]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=await Y(o,{permission:"sending_access"}),r=await O(e.file,{message:"Path to JSON file",placeholder:"./emails.json"},{message:"Missing --file flag. Provide a JSON file with an array of email objects.",code:"missing_file"},o),n=oe(r,o),s;try{s=JSON.parse(n)}catch{g({message:"File content is not valid JSON.",code:"invalid_json"},{json:o.json})}Array.isArray(s)||g({message:"File content must be a JSON array of email objects.",code:"invalid_format"},{json:o.json});let a=s;if(a.length>100&&console.warn(`Warning: ${a.length} emails exceeds the 100-email limit. The API may reject this request.`),e.reactEmail){let f=await Pe(e.reactEmail,o);for(let A of a)A.html=f}let l={reply_to:"replyTo",scheduled_at:"scheduledAt",topic_id:"topicId"};for(let f=0;f<a.length;f++){let A=a[f];(A===null||typeof A!="object"||Array.isArray(A))&&g({message:`Email at index ${f} must be a JSON object.`,code:"invalid_format"},{json:o.json}),"attachments"in A&&g({message:`Email at index ${f} contains "attachments", which is not supported in batch sends.`,code:"batch_error"},{json:o.json});let h=A;for(let[b,S]of Object.entries(l))b in h&&(h[S]??=h[b],delete h[b])}let d=await de("Sending batch...",()=>{let f={...e.idempotencyKey&&{idempotencyKey:e.idempotencyKey},...e.batchValidation&&{batchValidation:e.batchValidation}};return i.batch.send(a,Object.keys(f).length>0?f:void 0)},"batch_error",o),c=d.data,u=d.errors;if(!o.json&&U()){console.log(`Sent ${c.length} email${c.length===1?"":"s"}`);for(let f of c)console.log(` ${f.id}`);if(u&&u.length>0){console.warn(`
|
|
623
|
+
${u.length} email${u.length===1?"":"s"} failed:`);for(let f of u)console.warn(` [${f.index}] ${f.message}`)}}else E(u&&u.length>0?{data:c,errors:u}:c,{json:o.json})});var tc=new p("cancel").description("Cancel a scheduled email").argument("[id]","Email ID").addHelpText("after",m({output:' {"object":"email","id":"<email-id>"}',errorCodes:["auth_error","cancel_error"],examples:["resend emails cancel <email-id>","resend emails cancel <email-id> --json"]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await y(e,Ve,i);await I({loading:"Cancelling email...",sdkCall:n=>n.emails.cancel(r),errorCode:"cancel_error",successMsg:`Email cancelled: ${r}`},i)});var oc=new p("get").description("Retrieve a sent email by ID").argument("[id]","Email ID").addHelpText("after",m({output:' {"object":"email","id":"<uuid>","message_id":"<111-222-333@email.example.com>","from":"onboarding@resend.dev","to":["delivered@resend.dev"],"subject":"Hello","html":"<p>Hi</p>","text":"Hi","last_event":"delivered","created_at":"<iso-date>","scheduled_at":null,"bcc":null,"cc":null,"reply_to":null}',errorCodes:["auth_error","fetch_error"],examples:["resend emails get <email-id>","resend emails get <email-id> --json"]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await y(e,Ve,i);await Q({loading:"Fetching email...",sdkCall:n=>n.emails.get(r),onInteractive:n=>{console.log(`From: ${n.from}`),console.log(`To: ${n.to.join(", ")}`),console.log(`Subject: ${n.subject}`),console.log(`Message-ID: ${n.message_id}`),console.log(`Status: ${n.last_event}`),console.log(`Date: ${n.created_at}`),n.scheduled_at&&console.log(`Scheduled: ${n.scheduled_at}`)}},i)});function Xm(e){let t=e.map(o=>{let i=o.to.join(", "),r=i.length>40?`${i.slice(0,37)}...`:i,n=o.subject.length>50?`${o.subject.slice(0,47)}...`:o.subject;return[o.from,r,n,o.last_event??"\u2014",o.created_at,o.id]});return B(["From","To","Subject","Status","Created","ID"],t,"(no sent emails)")}var ic=new p("list").alias("ls").description('List sent emails \u2014 returns summary (use "get <id>" for full details)').option("--limit <n>","Maximum number of emails to return (1-100)","10").option("--after <cursor>","Cursor for forward pagination \u2014 list items after this ID").option("--before <cursor>","Cursor for backward pagination \u2014 list items before this ID").addHelpText("after",m({context:"Lists emails sent by your team. For emails received by your domain, use: resend emails receiving list",output:' {"object":"list","has_more":false,"data":[{"id":"...","message_id":"<111-222-333@email.example.com>","to":["..."],"from":"...","subject":"...","created_at":"...","last_event":"delivered|opened|...","scheduled_at":null}]}',errorCodes:["auth_error","invalid_limit","list_error"],examples:["resend emails list","resend emails list --limit 5","resend emails list --after <email-id> --limit 10","resend emails list --json"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=P(e.limit,o),r=$(i,e.after,e.before,o);await _({loading:"Fetching sent emails...",sdkCall:n=>n.emails.list(r),onInteractive:n=>{console.log(Xm(n.data)),H(n,"emails list",{limit:i,before:e.before,apiKey:o.apiKey,profile:o.profile})}},o)});var ft={resource:"received email",resourcePlural:"received emails",fetchItems:(e,{limit:t,after:o})=>e.emails.receiving.list({limit:t,...o&&{after:o}}),display:e=>({label:e.subject||"(no subject)",hint:e.id})};function rc(e){return{resource:"attachment",resourcePlural:"attachments",fetchItems:(t,{limit:o,after:i})=>t.emails.receiving.attachments.list({emailId:e,limit:o,...i&&{after:i}}),display:t=>({label:t.filename??"(unnamed)",hint:t.id})}}function nc(e){let t=e.map(o=>{let i=o.to.join(", "),r=i.length>40?`${i.slice(0,37)}...`:i,n=o.subject.length>50?`${o.subject.slice(0,47)}...`:o.subject;return[o.from,r,n,o.created_at,o.id]});return B(["From","To","Subject","Created At","ID"],t,"(no received emails)")}var sc=new p("attachment").description("Retrieve a single attachment from a received (inbound) email").argument("[emailId]","Received email UUID").argument("[attachmentId]","Attachment UUID").addHelpText("after",m({context:`The download_url is a signed URL that expires in ~1 hour. Download the file directly:
|
|
624
624
|
resend emails receiving attachment <emailId> <attachmentId> --json | jq -r .download_url | xargs curl -O`,output:' {"object":"attachment","id":"<uuid>","filename":"invoice.pdf","size":51200,"content_type":"application/pdf","content_disposition":"attachment","content_id":null,"download_url":"<signed-url>","expires_at":"<iso-date>"}',errorCodes:["auth_error","fetch_error"],examples:["resend emails receiving attachment <email-id> <attachment-id>","resend emails receiving attachment <email-id> <attachment-id> --json"]})).action(async(e,t,o,i)=>{let r=i.optsWithGlobals(),n=await y(e,ft,r),s=await y(t,rc(n),r);await Q({loading:"Fetching attachment...",sdkCall:a=>a.emails.receiving.attachments.get({emailId:n,id:s}),onInteractive:a=>{console.log(`${a.filename??"(unnamed)"}`),console.log(`ID: ${a.id}`),console.log(`Content-Type: ${a.content_type}`),console.log(`Size: ${a.size} bytes`),console.log(`Disposition: ${a.content_disposition}`),console.log(`Download URL: ${a.download_url}`),console.log(`Expires: ${a.expires_at}`)}},r)});var ac=new p("attachments").description("List attachments on a received (inbound) email").argument("[emailId]","Received email UUID").option("--limit <n>","Maximum number of attachments to return (1-100)","10").option("--after <cursor>","Return attachments after this cursor (next page)").option("--before <cursor>","Return attachments before this cursor (previous page)").addHelpText("after",m({context:`Each attachment has a download_url (signed, expires ~1 hour).
|
|
625
625
|
Use the attachment sub-command to retrieve a single attachment with its download URL:
|
|
626
626
|
resend emails receiving attachment <emailId> <attachmentId>
|
|
627
627
|
|
|
628
628
|
content_disposition: "inline" means the attachment is embedded in the HTML body (e.g. an image).
|
|
629
629
|
content_disposition: "attachment" means it is a standalone file download.`,output:' {"object":"list","has_more":false,"data":[{"id":"<uuid>","filename":"invoice.pdf","size":51200,"content_type":"application/pdf","content_disposition":"attachment","content_id":null,"download_url":"<url>","expires_at":"<iso-date>"}]}',errorCodes:["auth_error","invalid_limit","list_error"],examples:["resend emails receiving attachments <email-id>","resend emails receiving attachments <email-id> --json","resend emails receiving attachments <email-id> --limit 25 --json"]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await y(e,ft,i),n=P(t.limit,i),s=$(n,t.after,t.before,i);await _({loading:"Fetching attachments...",sdkCall:a=>a.emails.receiving.attachments.list({emailId:r,...s}),onInteractive:a=>{console.log(di(a.data)),H(a,`emails receiving attachments ${r}`,{limit:n,before:t.before,apiKey:i.apiKey,profile:i.profile})}},i)});var lc=new p("forward").description("Forward a received email").argument("[id]","Received email ID").requiredOption("--to <addresses...>","Recipient address(es)").requiredOption("--from <address>","Sender address").addHelpText("after",m({context:`Required: --to, --from
|
|
630
|
-
Forwards the original email content (passthrough mode).`,output:' {"id":"<email-id>"}',errorCodes:["auth_error","create_error"],examples:["resend emails receiving forward <email-id> --to delivered@resend.
|
|
630
|
+
Forwards the original email content (passthrough mode).`,output:' {"id":"<email-id>"}',errorCodes:["auth_error","create_error"],examples:["resend emails receiving forward <email-id> --to delivered@resend.dev --from onboarding@resend.dev","resend emails receiving forward <email-id> --to delivered@resend.dev --from onboarding@resend.dev --json"]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await y(e,ft,i);await L({loading:"Forwarding email...",sdkCall:n=>n.emails.receiving.forward({emailId:r,to:t.to,from:t.from}),onInteractive:n=>{console.log(`Email forwarded: ${n.id}`)}},i)});var cc=new p("get").description("Retrieve a single received (inbound) email with full details including HTML, text, and headers").argument("[id]","Received email UUID").addHelpText("after",m({context:`The raw.download_url field is a signed URL (expires ~1 hour) containing the full RFC 2822
|
|
631
631
|
MIME message. Pipe it to curl to save the original email:
|
|
632
632
|
resend emails receiving get <id> --json | jq -r .raw.download_url | xargs curl > email.eml
|
|
633
633
|
|
|
@@ -646,20 +646,20 @@ interval and prints each new email as it arrives.
|
|
|
646
646
|
Interactive output shows one line per email. When piped (or with --json),
|
|
647
647
|
output is NDJSON (one JSON object per line).
|
|
648
648
|
|
|
649
|
-
Ctrl+C exits cleanly.`,examples:["resend emails receiving listen","resend emails receiving listen --interval 10","resend emails receiving listen --json | head -3"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=Number.parseInt(e.interval??"5",10);(Number.isNaN(i)||i<2)&&g({message:"Polling interval must be at least 2 seconds.",code:"invalid_interval"},{json:o.json});let r=await Y(o),n=o.json||!U(),s=ne("Connecting...",o.quiet||n),a=dc(),l=0;try{let{data:
|
|
649
|
+
Ctrl+C exits cleanly.`,examples:["resend emails receiving listen","resend emails receiving listen --interval 10","resend emails receiving listen --json | head -3"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=Number.parseInt(e.interval??"5",10);(Number.isNaN(i)||i<2)&&g({message:"Polling interval must be at least 2 seconds.",code:"invalid_interval"},{json:o.json});let r=await Y(o),n=o.json||!U(),s=ne("Connecting...",o.quiet||n),a=dc(),l=0;try{let{data:b,error:S}=await r.emails.receiving.list({limit:1});(S||!b)&&(s.fail("Failed to connect"),g({message:S?.message??"Unexpected empty response",code:"list_error"},{json:o.json}));for(let v of b.data)a.add(v.id);s.stop("Ready")}catch(b){s.fail("Failed to connect"),g({message:q(b,"Unknown error"),code:"list_error"},{json:o.json})}n||(process.stderr.write(`
|
|
650
650
|
`),process.stderr.write(` ${tt.default.bold("Polling:")} every ${i}s
|
|
651
651
|
`),process.stderr.write(`
|
|
652
652
|
Listening for new inbound emails. Press Ctrl+C to stop.
|
|
653
653
|
|
|
654
|
-
`));let d=
|
|
655
|
-
`),l>=5&&g({message:"Exiting after 5 consecutive API failures.",code:"poll_error"},{json:o.json})},c=async(
|
|
656
|
-
`)},
|
|
654
|
+
`));let d=b=>{l++,n||process.stderr.write(`${tt.default.dim(`[${_r()}]`)} ${tt.default.yellow("Warning:")} ${b}
|
|
655
|
+
`),l>=5&&g({message:"Exiting after 5 consecutive API failures.",code:"poll_error"},{json:o.json})},c=async(b,S,v)=>{if(v<=0)return{emails:S,hasMore:!0};let K=b?{limit:Rr,after:b}:{limit:Rr},{data:w,error:N}=await lo(()=>r.emails.receiving.list(K));if(N||!w)return{emails:S,error:N?.message??"Empty response",hasMore:!1};let{newEmails:k,foundSeen:T}=ef(w.data,a),D=[...S,...k];if(T||!w.has_more)return{emails:D,hasMore:!1};let F=w.data[w.data.length-1]?.id;return F?c(F,D,v-1):{emails:D,hasMore:!0}},u,f=()=>{let b=`Hit page cap of ${pc*Rr} emails this poll; remaining will be picked up next tick.`;n?console.log(JSON.stringify({warning:"page_cap_reached",message:b})):process.stderr.write(`${tt.default.dim(`[${_r()}]`)} ${tt.default.yellow("Warning:")} ${b}
|
|
656
|
+
`)},A=async()=>{try{let b=await c(void 0,[],pc);b.error&&d(b.error),b.hasMore&&f();let S=b.emails.toReversed();for(let v of S)a.add(v.id);if(b.emails.length>0){l=0;for(let v of S)Zm(v,n)}else b.error||(l=0)}catch(b){d(q(b,"Unknown error"))}finally{u=setTimeout(A,i*1e3)}};u=setTimeout(A,i*1e3);let h=()=>{clearTimeout(u),n||process.stderr.write(`
|
|
657
657
|
Stopped listening.
|
|
658
|
-
`),process.exit(
|
|
659
|
-
resend domains update <id> --receiving enabled`,examples:["resend emails receiving list","resend emails receiving listen","resend emails receiving get <email-id>","resend emails receiving attachments <email-id>","resend emails receiving attachment <email-id> <attachment-id>","resend emails receiving forward <email-id> --to delivered@resend.
|
|
660
|
-
Use --dry-run to print the request JSON without sending (attachments show filename and byteLength only).`,output:' {"id":"<email-id>"}',errorCodes:["auth_error","missing_body","file_read_error","invalid_options","stdin_read_error","invalid_header","invalid_tag","invalid_var","template_body_conflict","template_attachment_conflict","react_email_build_error","react_email_render_error","send_error"],examples:['resend emails send --from onboarding@resend.
|
|
658
|
+
`),process.exit(Bt())};Lo(h),process.on("SIGTERM",h),await new Promise(()=>{})});var fc=new p("receiving").description("Manage received (inbound) emails \u2014 requires domain receiving to be enabled").addHelpText("after",m({context:`Receiving must be enabled on the domain first:
|
|
659
|
+
resend domains update <id> --receiving enabled`,examples:["resend emails receiving list","resend emails receiving listen","resend emails receiving get <email-id>","resend emails receiving attachments <email-id>","resend emails receiving attachment <email-id> <attachment-id>","resend emails receiving forward <email-id> --to delivered@resend.dev --from onboarding@resend.dev"]})).addCommand(uc,{isDefault:!0}).addCommand(cc).addCommand(mc).addCommand(ac).addCommand(sc).addCommand(lc);var gc=require("node:fs"),hc=require("node:path");J();function tf(e){let{attachments:t,...o}=e;return t?.length?{...o,attachments:t.map(i=>({filename:i.filename,byteLength:Buffer.isBuffer(i.content)?i.content.byteLength:Buffer.byteLength(String(i.content),"utf8")}))}:o}var Ac=new p("send").description("Send an email").option("--from <address>","Sender address (required unless using --template)").option("--to <addresses...>","Recipient address(es) (required)").option("--subject <subject>","Email subject (required unless using --template)").option("--html <html>","HTML body").option("--html-file <path>",'Path to an HTML file for the body (use "-" for stdin)').option("--text <text>","Plain-text body").option("--text-file <path>",'Path to a plain-text file for the body (use "-" for stdin)').option("--react-email <path>","Path to a React Email template (.tsx) to bundle, render, and send").option("--cc <addresses...>","CC recipients").option("--bcc <addresses...>","BCC recipients").option("--reply-to <address>","Reply-to address").option("--scheduled-at <datetime>",'Schedule email for later \u2014 ISO 8601 or natural language e.g. "in 1 hour", "tomorrow at 9am ET"').option("--attachment <paths...>","File path(s) to attach").option("--headers <key=value...>","Custom headers as key=value pairs (e.g. X-Entity-Ref-ID=123)").option("--tags <name=value...>","Email tags as name=value pairs (e.g. category=marketing)").option("--idempotency-key <key>","Deduplicate this send request using this key").option("--dry-run","Validate input and print the request JSON without calling the API (interactive: verified-domain list is not fetched)").option("--template <id>","Template ID to use").option("--var <key=value...>","Template variables as key=value pairs (repeatable, e.g. --var name=John --var count=42)").addHelpText("after",m({context:`Required: --to and either --template, --react-email, or (--from, --subject, and one of --text | --text-file | --html | --html-file).
|
|
660
|
+
Use --dry-run to print the request JSON without sending (attachments show filename and byteLength only).`,output:' {"id":"<email-id>"}',errorCodes:["auth_error","missing_body","file_read_error","invalid_options","stdin_read_error","invalid_header","invalid_tag","invalid_var","template_body_conflict","template_attachment_conflict","react_email_build_error","react_email_render_error","send_error"],examples:['resend emails send --from onboarding@resend.dev --to delivered@resend.dev --subject "Hello" --text "Hi"','resend emails send --from onboarding@resend.dev --to delivered@resend.dev --subject "Hello" --html "<b>Hi</b>"','resend emails send --from onboarding@resend.dev --to delivered@resend.dev --subject "Hello" --text "Hi" --attachment ./report.pdf',"resend emails send --template tmpl_123 --to delivered@resend.dev"]})).action(async(e,t)=>{let o=t.optsWithGlobals();e.htmlFile==="-"&&e.textFile==="-"&&g({message:"Cannot read both --html-file and --text-file from stdin. Pipe to one and pass the other as a file path.",code:"invalid_options"},{json:o.json}),e.from===""&&g({message:"--from cannot be empty",code:"invalid_options"},{json:o.json});let i=!!e.template;e.var&&!i&&g({message:"--var can only be used with --template",code:"invalid_var"},{json:o.json}),e.reactEmail&&(e.html||e.htmlFile||i)&&g({message:"Cannot use --react-email with --html, --html-file, or --template",code:"invalid_options"},{json:o.json}),i&&(e.html||e.htmlFile||e.text||e.textFile)&&g({message:"Cannot use --template with --html, --html-file, --text, or --text-file",code:"template_body_conflict"},{json:o.json}),i&&e.attachment&&g({message:"Cannot use --attachment with --template",code:"template_attachment_conflict"},{json:o.json});let r=e.var?Object.fromEntries(e.var.map(K=>{let w=K.indexOf("=");w<1&&g({message:`Invalid var format: "${K}". Expected key=value.`,code:"invalid_var"},{json:o.json});let N=K.slice(0,w),k=K.slice(w+1);return[N,k]})):void 0,n=e.from;if(!e.dryRun&&!n&&!i&&U()&&!o.json){let K=await Y(o,{permission:"sending_access"}),w=await ei(K);w.length>0&&(n=await ti(w))}let s=[{flag:"from",message:"From address",placeholder:"onboarding@resend.dev",defaultValue:"onboarding@resend.dev",required:!i},{flag:"to",message:"To address",placeholder:"delivered@resend.dev",defaultValue:"delivered@resend.dev"},{flag:"subject",message:"Subject",placeholder:"Hello!",defaultValue:"Hello!",required:!i}],a=await zs({from:n,to:e.to?.[0],subject:e.subject},s,o),l=e.html,d=e.text;e.htmlFile&&(e.html&&process.stderr.write(`Warning: both --html and --html-file provided; using --html-file
|
|
661
661
|
`),l=oe(e.htmlFile,o)),e.textFile&&(e.text&&process.stderr.write(`Warning: both --text and --text-file provided; using --text-file
|
|
662
|
-
`),d=oe(e.textFile,o)),e.reactEmail&&(l=await Pe(e.reactEmail,o));let c=d;!i&&!e.reactEmail&&!l&&!d&&(c=await O(void 0,{message:"Email body (plain text)",placeholder:"Hello, World!",defaultValue:"Hello, World!"},{message:"Missing email body. Provide --html, --html-file, --text, --text-file, or --react-email",code:"missing_body"},o));let u=e.to??[a.to],f=e.attachment?.map(K=>{try{let w=(0,gc.readFileSync)(K);return{filename:(0,hc.basename)(K),content:w}}catch{return g({message:`Failed to read file: ${K}`,code:"file_read_error"},{json:o.json})}}),
|
|
662
|
+
`),d=oe(e.textFile,o)),e.reactEmail&&(l=await Pe(e.reactEmail,o));let c=d;!i&&!e.reactEmail&&!l&&!d&&(c=await O(void 0,{message:"Email body (plain text)",placeholder:"Hello, World!",defaultValue:"Hello, World!"},{message:"Missing email body. Provide --html, --html-file, --text, --text-file, or --react-email",code:"missing_body"},o));let u=e.to??[a.to],f=e.attachment?.map(K=>{try{let w=(0,gc.readFileSync)(K);return{filename:(0,hc.basename)(K),content:w}}catch{return g({message:`Failed to read file: ${K}`,code:"file_read_error"},{json:o.json})}}),A=e.headers?Object.fromEntries(e.headers.map(K=>{let w=K.indexOf("=");return w<1&&g({message:`Invalid header format: "${K}". Expected key=value.`,code:"invalid_header"},{json:o.json}),[K.slice(0,w),K.slice(w+1)]})):void 0,h=e.tags?.map(K=>{let w=K.indexOf("=");return w<1&&g({message:`Invalid tag format: "${K}". Expected name=value.`,code:"invalid_tag"},{json:o.json}),{name:K.slice(0,w),value:K.slice(w+1)}}),b;if(i?b={template:{id:e.template,...r&&{variables:r}},to:u,...a.from&&{from:a.from},...a.subject&&{subject:a.subject},...e.cc&&{cc:e.cc},...e.bcc&&{bcc:e.bcc},...e.replyTo&&{replyTo:e.replyTo},...e.scheduledAt&&{scheduledAt:e.scheduledAt},...A&&{headers:A},...h&&{tags:h}}:b={from:a.from,to:u,subject:a.subject,...l&&{html:l},...c&&{text:c},...e.cc&&{cc:e.cc},...e.bcc&&{bcc:e.bcc},...e.replyTo&&{replyTo:e.replyTo},...e.scheduledAt&&{scheduledAt:e.scheduledAt},...f&&{attachments:f},...A&&{headers:A},...h&&{tags:h}},e.dryRun){E({dryRun:!0,request:tf(b)},{json:o.json});return}let S=await Y(o,{permission:"sending_access"}),v=await de(e.scheduledAt?"Scheduling email...":"Sending email...",()=>S.emails.send(b,e.idempotencyKey?{idempotencyKey:e.idempotencyKey}:void 0),"send_error",o);!o.json&&U()?e.scheduledAt?console.log(`Email scheduled: ${v.id}`):console.log(`Email sent: ${v.id}`):E(v,{json:o.json})});var bc=new p("update").description("Update a scheduled email").argument("[id]","Email ID").requiredOption("--scheduled-at <datetime>","New scheduled date in ISO 8601 format (e.g. 2024-08-05T11:52:01.858Z)").addHelpText("after",m({context:"Required: --scheduled-at",output:' {"object":"email","id":"<email-id>"}',errorCodes:["auth_error","update_error"],examples:["resend emails update <email-id> --scheduled-at 2024-08-05T11:52:01.858Z","resend emails update <email-id> --scheduled-at 2024-08-05T11:52:01.858Z --json"]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await y(e,Ve,i);await I({loading:"Updating email...",sdkCall:n=>n.emails.update({id:r,scheduledAt:t.scheduledAt}),errorCode:"update_error",successMsg:`Email updated: ${r}`},i)});var Cc=new p("emails").description("Send and manage emails").addHelpText("after",m({examples:['resend emails send --from onboarding@resend.dev --to delivered@resend.dev --subject "Hello" --text "Hi"',"resend emails get <email-id>","resend emails batch --file ./emails.json","resend emails cancel <email-id>","resend emails attachments <email-id>","resend emails attachment <email-id> <attachment-id>","resend emails receiving list","resend emails receiving forward <email-id> --to delivered@resend.dev --from onboarding@resend.dev"]})).addCommand(ic,{isDefault:!0}).addCommand(Ac).addCommand(oc).addCommand(ec).addCommand(tc).addCommand(bc).addCommand(Zl).addCommand(Xl).addCommand(fc);var of=new Set(["string","number","boolean","date"]);function Dr(e){if(!e)return"(none)";let t=Object.entries(e);return t.length===0?"(empty)":t.map(([o,i])=>`${o}:${i}`).join(", ")}function yc(e){let t=e.map(o=>[o.name,Dr(o.schema),o.created_at,o.id]);return B(["Name","Schema","Created","ID"],t,"(no events)")}function pi(e,t){if(e==="null")return null;let o=Kt(e,"--schema",t);(typeof o!="object"||o===null||Array.isArray(o))&&g({message:"--schema must be a JSON object mapping field names to types (string | number | boolean | date).",code:"invalid_schema"},{json:t.json});for(let[i,r]of Object.entries(o))(typeof r!="string"||!of.has(r))&&g({message:`Invalid schema type for "${i}": "${r}". Must be one of: string, number, boolean, date.`,code:"invalid_schema"},{json:t.json});return o}var Qt={resource:"event",resourcePlural:"events",fetchItems:(e,{limit:t,after:o})=>e.events.list({limit:t,...o&&{after:o}}),display:e=>({label:e.name,hint:e.id})};var Uc=new p("create").description("Create a new event definition").option("--name <name>","Event name (e.g. user.signed_up)").option("--schema <json>","Schema as JSON mapping field names to types (string | number | boolean | date)").addHelpText("after",m({context:`Non-interactive: --name is required. --schema is optional.
|
|
663
663
|
|
|
664
664
|
Schema format:
|
|
665
665
|
A JSON object mapping field names to type strings.
|
|
@@ -673,7 +673,7 @@ Contact targeting:
|
|
|
673
673
|
|
|
674
674
|
Payload:
|
|
675
675
|
Optional JSON object with event-specific data.
|
|
676
|
-
Must match the event's schema if one is defined.`,output:' {"object":"event","event":"<name>"}',errorCodes:["auth_error","missing_event","missing_contact","conflicting_contact","invalid_json","send_error"],examples:['resend events send --event "user.signed_up" --contact-id <id>','resend events send --event "user.signed_up" --email user@example.com',`resend events send --event "order.completed" --contact-id <id> --payload '{"amount":99,"currency":"usd"}'`]})).action(async(e,t)=>{let o=t.optsWithGlobals();e.contactId!==void 0&&e.email!==void 0&&g({message:"Cannot use both --contact-id and --email. Provide only one.",code:"conflicting_contact"},{json:o.json});let i=await O(e.event,{message:"Event name",placeholder:"e.g. user.signed_up"},{message:"Missing --event flag.",code:"missing_event"},o),r=e.contactId,n=e.email;!r&&!n&&(await
|
|
676
|
+
Must match the event's schema if one is defined.`,output:' {"object":"event","event":"<name>"}',errorCodes:["auth_error","missing_event","missing_contact","conflicting_contact","invalid_json","send_error"],examples:['resend events send --event "user.signed_up" --contact-id <id>','resend events send --event "user.signed_up" --email user@example.com',`resend events send --event "order.completed" --contact-id <id> --payload '{"amount":99,"currency":"usd"}'`]})).action(async(e,t)=>{let o=t.optsWithGlobals();e.contactId!==void 0&&e.email!==void 0&&g({message:"Cannot use both --contact-id and --email. Provide only one.",code:"conflicting_contact"},{json:o.json});let i=await O(e.event,{message:"Event name",placeholder:"e.g. user.signed_up"},{message:"Missing --event flag.",code:"missing_event"},o),r=e.contactId,n=e.email;!r&&!n&&(await Et(void 0,{message:"Identify contact by",options:[{value:"contact-id",label:"Contact ID"},{value:"email",label:"Email address"}]},{message:"Missing --contact-id or --email flag.",code:"missing_contact"},o)==="contact-id"?r=await O(void 0,{message:"Contact ID"},{message:"Missing contact ID.",code:"missing_contact"},o):n=await O(void 0,{message:"Email address",placeholder:"user@example.com"},{message:"Missing email.",code:"missing_contact"},o));let s=Kt(e.payload,"--payload",o),a=r?{event:i,contactId:r,...s&&{payload:s}}:{event:i,email:n,...s&&{payload:s}};await I({loading:"Sending event...",sdkCall:l=>l.events.send(a),errorCode:"send_error",successMsg:`Event sent: ${i}`},o)});J();var Fc=new p("update").description("Update an event schema").argument("[id]","Event ID").option("--schema <json>",'New schema as JSON (or "null" to clear the schema)').addHelpText("after",m({context:`Non-interactive: --schema is required. Pass "null" to remove the schema.
|
|
677
677
|
|
|
678
678
|
Schema format:
|
|
679
679
|
A JSON object mapping field names to type strings.
|
|
@@ -687,14 +687,14 @@ Lifecycle:
|
|
|
687
687
|
3. resend events list
|
|
688
688
|
4. resend events get <id>
|
|
689
689
|
5. resend events update <id> --schema '{"plan":"string","trial":"boolean"}'
|
|
690
|
-
6. resend events delete <id> --yes`,examples:["resend events list",'resend events create --name "user.signed_up"',`resend events create --name "order.completed" --schema '{"amount":"number","currency":"string"}'`,"resend events get <id>",`resend events update <id> --schema '{"plan":"string"}'`,"resend events update <id> --schema null","resend events delete <id> --yes",'resend events send --event "user.signed_up" --contact-id <id>',`resend events send --event "user.signed_up" --email user@example.com --payload '{"plan":"pro"}'`]})).addCommand(Uc).addCommand(Kc).addCommand(vc,{isDefault:!0}).addCommand(Fc).addCommand(Sc).addCommand(wc).addCommand(xc);function Rc(e){let t=e.map(o=>[o.method,o.endpoint,String(o.response_status),o.created_at,o.id]);return
|
|
690
|
+
6. resend events delete <id> --yes`,examples:["resend events list",'resend events create --name "user.signed_up"',`resend events create --name "order.completed" --schema '{"amount":"number","currency":"string"}'`,"resend events get <id>",`resend events update <id> --schema '{"plan":"string"}'`,"resend events update <id> --schema null","resend events delete <id> --yes",'resend events send --event "user.signed_up" --contact-id <id>',`resend events send --event "user.signed_up" --email user@example.com --payload '{"plan":"pro"}'`]})).addCommand(Uc).addCommand(Kc).addCommand(vc,{isDefault:!0}).addCommand(Fc).addCommand(Sc).addCommand(wc).addCommand(xc);function Rc(e){let t=e.map(o=>[o.method,o.endpoint,String(o.response_status),o.created_at,o.id]);return B(["Method","Endpoint","Status","Created","ID"],t,"(no logs)")}var _c={resource:"log",resourcePlural:"logs",fetchItems:(e,{limit:t,after:o})=>e.logs.list({limit:t,...o&&{after:o}}),display:e=>({label:`${e.method} ${e.endpoint}`,hint:e.id})};var Dc=new p("get").description("Retrieve a single API request log with full request/response bodies").argument("[id]","Log ID").addHelpText("after",m({output:" Full log object including request_body and response_body.",errorCodes:["auth_error","fetch_error"],examples:["resend logs get 3d4a472d-bc6d-4dd2-aa9d-d3d11b549e55","resend logs get 3d4a472d-bc6d-4dd2-aa9d-d3d11b549e55 --json"]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await y(e,_c,i);await Q({loading:"Fetching log...",sdkCall:n=>n.logs.get(r),onInteractive:n=>{console.log(`${n.method} ${n.endpoint} \u2014 ${n.response_status}`),console.log(`ID: ${n.id}`),console.log(`Created: ${n.created_at}`),console.log(`User-Agent: ${n.user_agent??"(none)"}`),n.request_body&&console.log(`
|
|
691
691
|
Request Body:
|
|
692
692
|
${JSON.stringify(n.request_body,null,2)}`),n.response_body&&console.log(`
|
|
693
693
|
Response Body:
|
|
694
|
-
${JSON.stringify(n.response_body,null,2)}`)}},i)});var
|
|
695
|
-
The list response does not include request/response bodies \u2014 use "resend logs get <id>" for that.`,errorCodes:["auth_error","invalid_limit","list_error"],examples:["resend logs list","resend logs list --limit 25 --json","resend logs list --after <cursor> --json"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=P(e.limit,o),r=$(i,e.after,e.before,o);await _({loading:"Fetching logs...",sdkCall:n=>n.logs.list(r),onInteractive:n=>{console.log(Rc(n.data)),H(n,"logs list",{limit:i,before:e.before,apiKey:o.apiKey,profile:o.profile})}},o)});var
|
|
694
|
+
${JSON.stringify(n.response_body,null,2)}`)}},i)});var Bc=new p("list").alias("ls").description("List API request logs").option("--limit <n>","Maximum number of logs to return (1-100)","10").option("--after <cursor>","Return logs after this cursor (next page)").option("--before <cursor>","Return logs before this cursor (previous page)").addHelpText("after",m({output:` {"object":"list","data":[...],"has_more":true}
|
|
695
|
+
The list response does not include request/response bodies \u2014 use "resend logs get <id>" for that.`,errorCodes:["auth_error","invalid_limit","list_error"],examples:["resend logs list","resend logs list --limit 25 --json","resend logs list --after <cursor> --json"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=P(e.limit,o),r=$(i,e.after,e.before,o);await _({loading:"Fetching logs...",sdkCall:n=>n.logs.list(r),onInteractive:n=>{console.log(Rc(n.data)),H(n,"logs list",{limit:i,before:e.before,apiKey:o.apiKey,profile:o.profile})}},o)});var Ec=new p("open").description("Open a log or the logs list in the Resend dashboard").argument("[id]","Log ID \u2014 omit to open the logs list").addHelpText("after",m({context:`Opens the Resend dashboard in your default browser.
|
|
696
696
|
With an ID: opens that log's detail page.
|
|
697
|
-
Without an ID: opens the logs list.`,examples:["resend logs open","resend logs open 3d4a472d-bc6d-4dd2-aa9d-d3d11b549e55"]})).action(async(e,t,o)=>{let i=e?me.log(e):me.logs,r=o.optsWithGlobals();await Re(i,r)});var Oc=new p("logs").description("View API request logs").addHelpText("after",m({examples:["resend logs list","resend logs list --limit 25 --json","resend logs get 3d4a472d-bc6d-4dd2-aa9d-d3d11b549e55","resend logs open","resend logs open 3d4a472d-bc6d-4dd2-aa9d-d3d11b549e55"]})).addCommand(Dc).addCommand(
|
|
697
|
+
Without an ID: opens the logs list.`,examples:["resend logs open","resend logs open 3d4a472d-bc6d-4dd2-aa9d-d3d11b549e55"]})).action(async(e,t,o)=>{let i=e?me.log(e):me.logs,r=o.optsWithGlobals();await Re(i,r)});var Oc=new p("logs").description("View API request logs").addHelpText("after",m({examples:["resend logs list","resend logs list --limit 25 --json","resend logs get 3d4a472d-bc6d-4dd2-aa9d-d3d11b549e55","resend logs open","resend logs open 3d4a472d-bc6d-4dd2-aa9d-d3d11b549e55"]})).addCommand(Dc).addCommand(Bc,{isDefault:!0}).addCommand(Ec);var Tc={resource:"OAuth grant",resourcePlural:"OAuth grants",fetchItems:(e,{limit:t,after:o})=>e.oauthGrants.list({limit:t,...o&&{after:o}}),display:e=>({label:e.client.name,hint:e.id})};function jc(e){let t=e.map(o=>[o.client.name,o.id,o.scopes.join(", "),o.created_at,o.revoked_at??""]);return B(["Client","ID","Scopes","Created","Revoked"],t,"(no OAuth grants)")}var Ic=new p("list").alias("ls").description("List OAuth grants for the team (both active and revoked), including each grant's client, scopes, and revocation status").option("--limit <n>","Maximum number of OAuth grants to return (1-100)","10").option("--after <cursor>","Cursor for forward pagination \u2014 list items after this ID").option("--before <cursor>","Cursor for backward pagination \u2014 list items before this ID").addHelpText("after",m({output:` {"object":"list","has_more":false,"data":[{"id":"<id>","client_id":"<id>","scopes":["<scope>"],"created_at":"<date>","revoked_at":"<date>|null","revoked_reason":"<reason>|null","client":{"name":"<name>","logo_uri":"<url>|null"}}]}
|
|
698
698
|
Revoked grants have non-null revoked_at and revoked_reason.`,errorCodes:["auth_error","invalid_limit","list_error"],examples:["resend oauth-grants list","resend oauth-grants list --limit 25 --json","resend oauth-grants list --after <cursor> --json"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=P(e.limit,o),r=$(i,e.after,e.before,o);await _({loading:"Fetching OAuth grants...",sdkCall:n=>n.oauthGrants.list(r),onInteractive:n=>{console.log(jc(n.data)),H(n,"oauth-grants list",{limit:i,before:e.before,apiKey:o.apiKey,profile:o.profile})}},o)});var Pc=new p("revoke").description("Revoke an OAuth grant \u2014 every access and refresh token issued under it stops working immediately").argument("[id]","OAuth grant ID").option("--yes","Skip confirmation prompt").addHelpText("after",m({context:`Non-interactive: --yes is required to confirm revocation when stdin/stdout is not a TTY.
|
|
699
699
|
|
|
700
700
|
Any team API key can revoke any of the team's grants. Revocation is immediate and
|
|
@@ -730,20 +730,20 @@ Segment membership is managed through the contacts namespace:
|
|
|
730
730
|
resend contacts remove-segment <contactId> <segmentId>
|
|
731
731
|
resend contacts segments <contactId>
|
|
732
732
|
|
|
733
|
-
There is no "update" endpoint \u2014 to rename a segment, delete it and recreate.`,examples:["resend segments list",'resend segments create --name "Newsletter Subscribers"',"resend segments get 78261eea-8f8b-4381-83c6-79fa7120f1cf","resend segments contacts 78261eea-8f8b-4381-83c6-79fa7120f1cf","resend segments delete 78261eea-8f8b-4381-83c6-79fa7120f1cf --yes"]})).addCommand(Gc).addCommand(Qc).addCommand(qc).addCommand(Mc,{isDefault:!0}).addCommand(Nc);var tu=ue(qe(),1);var
|
|
733
|
+
There is no "update" endpoint \u2014 to rename a segment, delete it and recreate.`,examples:["resend segments list",'resend segments create --name "Newsletter Subscribers"',"resend segments get 78261eea-8f8b-4381-83c6-79fa7120f1cf","resend segments contacts 78261eea-8f8b-4381-83c6-79fa7120f1cf","resend segments delete 78261eea-8f8b-4381-83c6-79fa7120f1cf --yes"]})).addCommand(Gc).addCommand(Qc).addCommand(qc).addCommand(Mc,{isDefault:!0}).addCommand(Nc);var tu=ue(qe(),1);var Br=ue(qe(),1);var Wc=new p("add").description("Suppress an email address so it stops receiving your emails").argument("[email]","Email address to suppress").addHelpText("after",m({context:`Non-interactive: <email> is required (no prompts when stdin/stdout is not a TTY).
|
|
734
734
|
|
|
735
735
|
A suppressed address is skipped on future sends. Added this way, the entry has
|
|
736
|
-
origin "manual". Use "suppressions delete" to remove it again.`,output:' {"object":"suppression","id":"<id>"}',errorCodes:["auth_error","missing_email","create_error"],examples:["resend suppressions add spam@example.com","resend suppressions add spam@example.com --json"]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await O(e,{message:"Email to suppress",placeholder:"e.g. spam@example.com"},{message:"Missing <email> argument.",code:"missing_email"},i);await L({loading:"Suppressing address...",sdkCall:n=>n.suppressions.add({email:r}),onInteractive:n=>{console.log(` ${
|
|
736
|
+
origin "manual". Use "suppressions delete" to remove it again.`,output:' {"object":"suppression","id":"<id>"}',errorCodes:["auth_error","missing_email","create_error"],examples:["resend suppressions add spam@example.com","resend suppressions add spam@example.com --json"]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await O(e,{message:"Email to suppress",placeholder:"e.g. spam@example.com"},{message:"Missing <email> argument.",code:"missing_email"},i);await L({loading:"Suppressing address...",sdkCall:n=>n.suppressions.add({email:r}),onInteractive:n=>{console.log(` ${Br.default.gray("Email:")} ${r}`),console.log(` ${Br.default.gray("ID:")} ${n.id}`)}},i)});J();function mi(e,t){let o;try{o=JSON.parse(e)}catch{g({message:"File content is not valid JSON.",code:"invalid_json"},{json:t.json})}Array.isArray(o)||g({message:"File content must be a JSON array of strings.",code:"invalid_format"},{json:t.json});let i=o;for(let r=0;r<i.length;r++)(typeof i[r]!="string"||i[r]==="")&&g({message:`Item at index ${r} must be a non-empty string.`,code:"invalid_format"},{json:t.json});return i}var Jc=new p("add").description("Suppress up to 100 email addresses from a JSON file in one request").option("--file <path>",'Path to a JSON file containing an array of email strings (use "-" for stdin; required in non-interactive mode)').addHelpText("after",m({context:`Non-interactive: --file
|
|
737
737
|
Limit: 100 emails per request (API hard limit \u2014 warned if exceeded)
|
|
738
738
|
|
|
739
739
|
File format (--file path):
|
|
740
|
-
["spam@example.com", "bounce@example.com"]`,output:' {"data":[{"object":"suppression","id":"<id>"}]}',errorCodes:["auth_error","missing_file","file_read_error","stdin_read_error","invalid_json","invalid_format","create_error"],examples:["resend suppressions batch add --file ./emails.json",`echo '["a@example.com","b@example.com"]' | resend suppressions batch add --file -`]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=await Y(o),r=await O(e.file,{message:"Path to JSON file",placeholder:"./emails.json"},{message:"Missing --file flag. Provide a JSON file with an array of email strings.",code:"missing_file"},o),n=oe(r,o),s=mi(n,o);s.length>100&&console.warn(`Warning: ${s.length} emails exceeds the 100-email limit. The API may reject this request.`);let a=await de("Suppressing addresses...",()=>i.suppressions.batch.add({emails:s}),"create_error",o);if(!o.json&&U()){console.log(`Suppressed ${a.data.length} address${a.data.length===1?"":"es"}`);for(let l of a.data)console.log(` ${l.id}`)}else
|
|
740
|
+
["spam@example.com", "bounce@example.com"]`,output:' {"data":[{"object":"suppression","id":"<id>"}]}',errorCodes:["auth_error","missing_file","file_read_error","stdin_read_error","invalid_json","invalid_format","create_error"],examples:["resend suppressions batch add --file ./emails.json",`echo '["a@example.com","b@example.com"]' | resend suppressions batch add --file -`]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=await Y(o),r=await O(e.file,{message:"Path to JSON file",placeholder:"./emails.json"},{message:"Missing --file flag. Provide a JSON file with an array of email strings.",code:"missing_file"},o),n=oe(r,o),s=mi(n,o);s.length>100&&console.warn(`Warning: ${s.length} emails exceeds the 100-email limit. The API may reject this request.`);let a=await de("Suppressing addresses...",()=>i.suppressions.batch.add({emails:s}),"create_error",o);if(!o.json&&U()){console.log(`Suppressed ${a.data.length} address${a.data.length===1?"":"es"}`);for(let l of a.data)console.log(` ${l.id}`)}else E(a,{json:o.json})});J();var Vc=new p("remove").alias("rm").description("Remove up to 100 suppressions from a JSON file in one request").option("--file <path>",'Path to a JSON file containing an array of email strings (use "-" for stdin; required in non-interactive mode)').option("--ids","Treat the file entries as suppression IDs instead of email addresses").addHelpText("after",m({context:`Non-interactive: --file
|
|
741
741
|
Limit: 100 entries per request (API hard limit \u2014 warned if exceeded)
|
|
742
742
|
By default entries are treated as email addresses; pass --ids to remove by suppression ID.
|
|
743
743
|
|
|
744
744
|
File format (--file path):
|
|
745
|
-
["spam@example.com", "bounce@example.com"]`,output:' {"data":[{"object":"suppression","id":"<id>","deleted":true}]}',errorCodes:["auth_error","missing_file","file_read_error","stdin_read_error","invalid_json","invalid_format","delete_error"],examples:["resend suppressions batch remove --file ./emails.json","resend suppressions batch remove --file ./ids.json --ids",`echo '["a@example.com","b@example.com"]' | resend suppressions batch rm --file -`]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=await Y(o),r=await O(e.file,{message:"Path to JSON file",placeholder:"./emails.json"},{message:"Missing --file flag. Provide a JSON file with an array of strings.",code:"missing_file"},o),n=oe(r,o),s=mi(n,o);s.length>100&&console.warn(`Warning: ${s.length} entries exceeds the 100-entry limit. The API may reject this request.`);let a=await de("Removing suppressions...",()=>i.suppressions.batch.remove(e.ids?{ids:s}:{emails:s}),"delete_error",o);if(!o.json&&U()){console.log(`Removed ${a.data.length} suppression${a.data.length===1?"":"s"}`);for(let l of a.data)console.log(` ${l.id}`)}else
|
|
746
|
-
"add" always operates on emails. "remove" defaults to emails; pass --ids to remove by ID.`,examples:["resend suppressions batch add --file ./emails.json","resend suppressions batch remove --file ./emails.json","resend suppressions batch remove --file ./ids.json --ids"]})).addCommand(Jc).addCommand(Vc);var fi={resource:"suppression",resourcePlural:"suppressions",fetchItems:(e,{limit:t,after:o})=>e.suppressions.list({limit:t,...o&&{after:o}}),display:e=>({label:e.email,hint:e.id})};function Yc(e){let t=e.map(o=>[o.email,o.id,o.origin,o.created_at]);return
|
|
745
|
+
["spam@example.com", "bounce@example.com"]`,output:' {"data":[{"object":"suppression","id":"<id>","deleted":true}]}',errorCodes:["auth_error","missing_file","file_read_error","stdin_read_error","invalid_json","invalid_format","delete_error"],examples:["resend suppressions batch remove --file ./emails.json","resend suppressions batch remove --file ./ids.json --ids",`echo '["a@example.com","b@example.com"]' | resend suppressions batch rm --file -`]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=await Y(o),r=await O(e.file,{message:"Path to JSON file",placeholder:"./emails.json"},{message:"Missing --file flag. Provide a JSON file with an array of strings.",code:"missing_file"},o),n=oe(r,o),s=mi(n,o);s.length>100&&console.warn(`Warning: ${s.length} entries exceeds the 100-entry limit. The API may reject this request.`);let a=await de("Removing suppressions...",()=>i.suppressions.batch.remove(e.ids?{ids:s}:{emails:s}),"delete_error",o);if(!o.json&&U()){console.log(`Removed ${a.data.length} suppression${a.data.length===1?"":"s"}`);for(let l of a.data)console.log(` ${l.id}`)}else E(a,{json:o.json})});var zc=new p("batch").description("Suppress or remove many addresses in a single request").addHelpText("after",m({context:`Batch operations read a JSON array of strings from --file (up to 100 per request).
|
|
746
|
+
"add" always operates on emails. "remove" defaults to emails; pass --ids to remove by ID.`,examples:["resend suppressions batch add --file ./emails.json","resend suppressions batch remove --file ./emails.json","resend suppressions batch remove --file ./ids.json --ids"]})).addCommand(Jc).addCommand(Vc);var fi={resource:"suppression",resourcePlural:"suppressions",fetchItems:(e,{limit:t,after:o})=>e.suppressions.list({limit:t,...o&&{after:o}}),display:e=>({label:e.email,hint:e.id})};function Yc(e){let t=e.map(o=>[o.email,o.id,o.origin,o.created_at]);return B(["Email","ID","Origin","Created"],t,"(no suppressions)")}var Xc=new p("delete").alias("rm").description("Remove a suppression so the address can receive your emails again").argument("[id-or-email]","Suppression ID or the suppressed email address").option("--yes","Skip confirmation prompt").addHelpText("after",m({context:`Non-interactive: --yes is required to confirm removal when stdin/stdout is not a TTY.
|
|
747
747
|
|
|
748
748
|
Removing a suppression means future sends to this address are no longer skipped.`,output:' {"object":"suppression","id":"<id>","deleted":true}',errorCodes:["auth_error","confirmation_required","delete_error"],examples:["resend suppressions delete spam@example.com --yes","resend suppressions rm 78261eea-8f8b-4381-83c6-79fa7120f1cf --yes --json"]})).action(async(e,t,o)=>{let i=o.optsWithGlobals(),r=await te(e,fi,i);await ee(r.id,!!t.yes,{confirmMessage:`Remove suppression "${r.label}"?
|
|
749
749
|
ID: ${r.id}
|
|
@@ -755,7 +755,7 @@ Suppressions block future sends to an address. Entries have an origin:
|
|
|
755
755
|
complaint added automatically after a spam complaint
|
|
756
756
|
manual added by you via "suppressions add"
|
|
757
757
|
|
|
758
|
-
get/delete accept either a suppression ID or the email address.`,examples:["resend suppressions list","resend suppressions add spam@example.com","resend suppressions get spam@example.com","resend suppressions delete spam@example.com --yes","resend suppressions batch add --file ./emails.json"]})).addCommand(eu,{isDefault:!0}).addCommand(Wc).addCommand(Zc).addCommand(Xc).addCommand(zc);J();function gi(e){return e.map(t=>{let[o,i,...r]=t.split(":");if(!o)throw new Error(`Invalid --var "${t}": key is required.`);if(i!=="string"&&i!=="number")throw new Error(`Invalid --var "${t}": type must be "string" or "number".`);let n=r.length?r.join(":"):void 0;if(n!=null&&n==="")throw new Error(`Invalid --var "${t}": fallback value cannot be empty.`);let s=n;if(i==="number"){if(s!=null&&Number.isNaN(Number(s)))throw new Error(`Invalid --var "${t}": fallback "${s}" is not a valid number.`);return{key:o,type:"number",...s!=null?{fallbackValue:Number(s)}:{}}}return{key:o,type:"string",...s!=null?{fallbackValue:s}:{}}})}var ze={resource:"template",resourcePlural:"templates",fetchItems:(e,{limit:t,after:o})=>e.templates.list({limit:t,...o&&{after:o}}),display:e=>({label:e.name,hint:e.id})};function iu(e){let t=e.map(o=>[o.name,o.status,o.alias??"",o.id,o.created_at]);return
|
|
758
|
+
get/delete accept either a suppression ID or the email address.`,examples:["resend suppressions list","resend suppressions add spam@example.com","resend suppressions get spam@example.com","resend suppressions delete spam@example.com --yes","resend suppressions batch add --file ./emails.json"]})).addCommand(eu,{isDefault:!0}).addCommand(Wc).addCommand(Zc).addCommand(Xc).addCommand(zc);J();function gi(e){return e.map(t=>{let[o,i,...r]=t.split(":");if(!o)throw new Error(`Invalid --var "${t}": key is required.`);if(i!=="string"&&i!=="number")throw new Error(`Invalid --var "${t}": type must be "string" or "number".`);let n=r.length?r.join(":"):void 0;if(n!=null&&n==="")throw new Error(`Invalid --var "${t}": fallback value cannot be empty.`);let s=n;if(i==="number"){if(s!=null&&Number.isNaN(Number(s)))throw new Error(`Invalid --var "${t}": fallback "${s}" is not a valid number.`);return{key:o,type:"number",...s!=null?{fallbackValue:Number(s)}:{}}}return{key:o,type:"string",...s!=null?{fallbackValue:s}:{}}})}var ze={resource:"template",resourcePlural:"templates",fetchItems:(e,{limit:t,after:o})=>e.templates.list({limit:t,...o&&{after:o}}),display:e=>({label:e.name,hint:e.id})};function iu(e){let t=e.map(o=>[o.name,o.status,o.alias??"",o.id,o.created_at]);return B(["Name","Status","Alias","ID","Created"],t,"(no templates)")}var ru=new p("create").description("Create a new template").option("--name <name>","Template name \u2014 required").option("--html <html>","HTML body").option("--html-file <path>",'Path to an HTML file for the body (use "-" for stdin)').option("--subject <subject>","Email subject").option("--text <text>","Plain-text body").option("--text-file <path>",'Path to a plain-text file for the body (use "-" for stdin)').option("--react-email <path>","Path to a React Email template (.tsx) to bundle, render, and use as HTML body").option("--from <address>","Sender address").option("--reply-to <address>","Reply-to address").option("--alias <alias>","Template alias for lookup by name").option("--var <var...>","Template variable: KEY:type or KEY:type:fallback (repeatable)").addHelpText("after",m({context:`Creates a new draft template. Use "resend templates publish" to make it available for sending.
|
|
759
759
|
|
|
760
760
|
--name is required. Body: provide --html, --html-file, or --react-email. Optionally add --text or --text-file for plain-text.
|
|
761
761
|
|
|
@@ -829,9 +829,9 @@ Contact topic subscriptions are managed via the contacts namespace:
|
|
|
829
829
|
resend contacts topics <contactId>
|
|
830
830
|
resend contacts update-topics <contactId> --topic-id <id> --subscription opt_in`,examples:["resend topics list",'resend topics create --name "Product Updates"','resend topics create --name "Weekly Digest" --default-subscription opt_out',"resend topics get 78261eea-8f8b-4381-83c6-79fa7120f1cf",'resend topics update 78261eea-8f8b-4381-83c6-79fa7120f1cf --name "Security Alerts"',"resend topics delete 78261eea-8f8b-4381-83c6-79fa7120f1cf --yes"]})).addCommand(mu).addCommand(gu).addCommand(hu,{isDefault:!0}).addCommand(Au).addCommand(fu);J();fo();bt();var Cu=new p("update").description("Check for available CLI updates").addHelpText("after",m({context:`Checks the latest release on GitHub (bypasses the cache).
|
|
831
831
|
Shows the current version, latest version, and how to upgrade.`,output:` {"current":"1.4.0","latest":"1.5.0","update_available":true,"upgrade_command":"npm install -g resend-cli"}
|
|
832
|
-
{"current":"1.5.0","latest":"1.5.0","update_available":false}`,examples:["resend update","resend update --json"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),r=U()&&!o.json?ne("Checking for updates..."):null,n=await Fr();if(!n){r?.fail("Could not check for updates"),g({message:"Could not reach GitHub releases",code:"fetch_failed"},{json:o.json});return}let s=ci(re,n),a=ui();if(o.json||!U()){
|
|
832
|
+
{"current":"1.5.0","latest":"1.5.0","update_available":false}`,examples:["resend update","resend update --json"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),r=U()&&!o.json?ne("Checking for updates..."):null,n=await Fr();if(!n){r?.fail("Could not check for updates"),g({message:"Could not reach GitHub releases",code:"fetch_failed"},{json:o.json});return}let s=ci(re,n),a=ui();if(o.json||!U()){E({current:re,latest:n,update_available:s,...s?{upgrade_command:a}:{}},{json:o.json});return}if(s){let l=a.startsWith("http");r?.warn(`Update available: v${re} \u2192 v${n}`),console.log(`
|
|
833
833
|
${l?"Visit":"Run"}: \x1B[36m${a}\x1B[0m
|
|
834
|
-
`)}else r?.stop(`Already up to date (v${re})`)});J();var ot=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.failed","email.scheduled","email.suppressed","email.received","contact.created","contact.updated","contact.deleted","domain.created","domain.updated","domain.deleted"];function Nt(e){return e.flatMap(t=>t.split(",")).map(t=>t.trim()).filter(Boolean)}var qt={resource:"webhook",resourcePlural:"webhooks",fetchItems:(e,{limit:t,after:o})=>e.webhooks.list({limit:t,...o&&{after:o}}),display:e=>({label:e.endpoint,hint:e.id})};function yu(e){let t=e.map(o=>{let i=(o.events??[]).join(", "),r=i.length>60?`${i.slice(0,57)}...`:i;return[o.endpoint,r,o.status,o.id]});return
|
|
834
|
+
`)}else r?.stop(`Already up to date (v${re})`)});J();var ot=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.failed","email.scheduled","email.suppressed","email.received","contact.created","contact.updated","contact.deleted","domain.created","domain.updated","domain.deleted"];function Nt(e){return e.flatMap(t=>t.split(",")).map(t=>t.trim()).filter(Boolean)}var qt={resource:"webhook",resourcePlural:"webhooks",fetchItems:(e,{limit:t,after:o})=>e.webhooks.list({limit:t,...o&&{after:o}}),display:e=>({label:e.endpoint,hint:e.id})};function yu(e){let t=e.map(o=>{let i=(o.events??[]).join(", "),r=i.length>60?`${i.slice(0,57)}...`:i;return[o.endpoint,r,o.status,o.id]});return B(["Endpoint","Events","Status","ID"],t,"(no webhooks)")}var Uu=new p("create").description("Register a new webhook endpoint to receive real-time event notifications").option("--endpoint <endpoint>","HTTPS URL to receive webhook events (required)").option("--events <events...>",'Event types to subscribe to (comma or space-separated). Use "all" for all 17 events.').addHelpText("after",m({context:`Webhooks deliver real-time event notifications to your HTTPS endpoint.
|
|
835
835
|
Events fire per-recipient: a batch email to 3 recipients generates 3 email.sent events.
|
|
836
836
|
|
|
837
837
|
--endpoint must use HTTPS.
|
|
@@ -876,19 +876,19 @@ points to the local server port. The CLI will:
|
|
|
876
876
|
5. Delete the temporary webhook on exit (Ctrl+C)
|
|
877
877
|
|
|
878
878
|
Important: your tunnel must forward traffic to the same port as --port (default 4318).
|
|
879
|
-
For example, if using ngrok: ngrok http 4318`,examples:["resend webhooks listen --url https://example.ngrok-free.app","resend webhooks listen --url https://example.ngrok-free.app --forward-to localhost:3000/webhook","resend webhooks listen --url https://example.ngrok-free.app --events email.sent email.bounced","resend webhooks listen --url https://example.ngrok-free.app --port 8080"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=await O(e.url,{message:"Public tunnel URL",placeholder:"https://example.ngrok-free.app",validate:h=>{if(!h)return"URL is required";if(!h.startsWith("https://")&&!h.startsWith("http://"))return"URL must start with http:// or https://"}},{message:"Missing --url flag.",code:"missing_url"},o),r=Number.parseInt(e.port??"4318",10);(Number.isNaN(r)||r<1||r>65535)&&g({message:"Invalid port number.",code:"invalid_port"},{json:o.json});let n=e.events?.length?Nt(e.events):void 0,s;n?.includes("all")?s=ot:n?.length?s=n:s=ot;let a=await Y(o),l=o.json||!U(),d=(0,xu.createServer)(async(h,
|
|
879
|
+
For example, if using ngrok: ngrok http 4318`,examples:["resend webhooks listen --url https://example.ngrok-free.app","resend webhooks listen --url https://example.ngrok-free.app --forward-to localhost:3000/webhook","resend webhooks listen --url https://example.ngrok-free.app --events email.sent email.bounced","resend webhooks listen --url https://example.ngrok-free.app --port 8080"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=await O(e.url,{message:"Public tunnel URL",placeholder:"https://example.ngrok-free.app",validate:h=>{if(!h)return"URL is required";if(!h.startsWith("https://")&&!h.startsWith("http://"))return"URL must start with http:// or https://"}},{message:"Missing --url flag.",code:"missing_url"},o),r=Number.parseInt(e.port??"4318",10);(Number.isNaN(r)||r<1||r>65535)&&g({message:"Invalid port number.",code:"invalid_port"},{json:o.json});let n=e.events?.length?Nt(e.events):void 0,s;n?.includes("all")?s=ot:n?.length?s=n:s=ot;let a=await Y(o),l=o.json||!U(),d=(0,xu.createServer)(async(h,b)=>{try{if(h.method!=="POST"){b.writeHead(405).end("Method not allowed");return}let S=await uf(h),v;try{v=JSON.parse(S)}catch{b.writeHead(400).end("Invalid JSON");return}let K={};for(let F of Fu){let j=h.headers[F];K[F]=Array.isArray(j)?j[0]:j}let{type:w,resourceId:N,detail:k}=sf(v),T;if(e.forwardTo)try{let{status:F}=await cf(e.forwardTo,S,K);T={status:F}}catch(F){let j=F instanceof DOMException&&F.name==="TimeoutError";T={error:F instanceof Error?F.message:"Unknown error",timeout:j}}if(l){let F={timestamp:new Date().toISOString(),type:w,resource_id:N,payload:v};e.forwardTo&&T&&(F.forwarded="error"in T?{url:e.forwardTo,error:T.error}:{url:e.forwardTo,status:T.status}),console.log(JSON.stringify(F))}else{let F=be.default.dim(`[${nf()}]`),j=w.padEnd(20),Ce=N.padEnd(14);if(process.stderr.write(`${F} ${be.default.bold(j)} ${be.default.cyan(Ce)} ${k}
|
|
880
880
|
`),e.forwardTo&&T){let ie=e.forwardTo.startsWith("http")?e.forwardTo:`http://${e.forwardTo}`;"error"in T?process.stderr.write(`${be.default.dim(" -> POST")} ${ie} ${be.default.red(`[Error: ${T.error}]`)}
|
|
881
881
|
`):process.stderr.write(`${be.default.dim(" -> POST")} ${ie} ${be.default.dim(`[${af(T.status)}]`)}
|
|
882
|
-
`)}}let D=wu(T);
|
|
882
|
+
`)}}let D=wu(T);b.writeHead(D.status).end(D.body)}catch{b.headersSent||b.writeHead(500).end("Internal error")}});try{await new Promise((h,b)=>{d.on("error",b),d.listen(r,h)})}catch(h){g({message:h instanceof Error?`Failed to start local server on port ${r}: ${h.message}`:`Failed to start local server on port ${r}`,code:"server_listen_error"},{json:o.json})}let c=ne("Setting up webhook listener...",o.quiet),u;try{let{data:h,error:b}=await a.webhooks.create({endpoint:i,events:s});(b||!h)&&(c.fail("Failed to create webhook"),d.close(),g({message:b?.message??"Unexpected empty response",code:"create_error"},{json:o.json})),u=h.id}catch(h){c.fail("Failed to create webhook"),d.close(),g({message:h instanceof Error?h.message:"Unknown error",code:"create_error"},{json:o.json})}if(c.stop("Webhook listener ready"),!l){let h=s.length===ot.length?"all events":s.length<=3?s.join(", "):`${s.slice(0,3).join(", ")} (+${s.length-3} more)`;if(process.stderr.write(`
|
|
883
883
|
`),process.stderr.write(` ${be.default.bold("Webhook:")} ${u}
|
|
884
884
|
`),process.stderr.write(` ${be.default.bold("Endpoint:")} ${i}
|
|
885
885
|
`),process.stderr.write(` ${be.default.bold("Events:")} ${h}
|
|
886
886
|
`),process.stderr.write(` ${be.default.bold("Server:")} http://localhost:${r}
|
|
887
|
-
`),e.forwardTo){let
|
|
887
|
+
`),e.forwardTo){let b=e.forwardTo.startsWith("http")?e.forwardTo:`http://${e.forwardTo}`;process.stderr.write(` ${be.default.bold("Forward:")} ${b}
|
|
888
888
|
`)}process.stderr.write(`
|
|
889
889
|
Ready! Listening for webhook events. Press Ctrl+C to stop.
|
|
890
890
|
|
|
891
|
-
`)}let f=!1,
|
|
891
|
+
`)}let f=!1,A=async()=>{f||(f=!0,await df(a,u,d),process.exit(Bt()))};Lo(A),process.on("SIGTERM",A),await new Promise(()=>{})});var Ru=new p("update").description("Update a webhook's endpoint URL, event subscriptions, or enabled status").argument("[id]","Webhook UUID").option("--endpoint <endpoint>","New HTTPS URL for this webhook").option("--events <events...>",'Replace the full event subscription list (comma or space-separated). Use "all" for all 17 events.').addOption(new V("--status <status>","Enable or disable event delivery for this webhook").choices(["enabled","disabled"])).addHelpText("after",m({context:`At least one of --endpoint, --events, or --status must be provided.
|
|
892
892
|
|
|
893
893
|
--events replaces the entire event list (it is not additive).
|
|
894
894
|
Use "all" as a shorthand for all 17 event types.
|
|
@@ -907,9 +907,9 @@ Event categories (17 total):
|
|
|
907
907
|
|
|
908
908
|
Signature verification (Svix):
|
|
909
909
|
Each delivery includes headers: svix-id, svix-timestamp, svix-signature
|
|
910
|
-
Verify payloads in your application using: resend.webhooks.verify({ payload, headers, webhookSecret })`,examples:["resend webhooks list","resend webhooks create --endpoint https://app.example.com/hooks/resend --events all","resend webhooks get wh_abc123","resend webhooks update wh_abc123 --status disabled","resend webhooks delete wh_abc123 --yes"]})).addCommand(Uu).addCommand(Ku).addCommand(ku).addCommand(vu,{isDefault:!0}).addCommand(Ru).addCommand(Su);var
|
|
911
|
-
Shows which profile is active and where the active credential comes from.`,output:' {"authenticated":true,"profile":"production","api_key":"re_...abcd","source":"config","config_path":"/Users/you/.config/resend/credentials.json"}\n {"error":{"message":"Not authenticated.\\nRun `resend login` to get started.","code":"not_authenticated"}}',examples:["resend whoami","resend whoami --json","resend whoami --profile production"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=o.profile,r=await St(o.apiKey,i,{refresh:!1});if(!r){let f=i||No(i),
|
|
912
|
-
Available profiles: ${
|
|
910
|
+
Verify payloads in your application using: resend.webhooks.verify({ payload, headers, webhookSecret })`,examples:["resend webhooks list","resend webhooks create --endpoint https://app.example.com/hooks/resend --events all","resend webhooks get wh_abc123","resend webhooks update wh_abc123 --status disabled","resend webhooks delete wh_abc123 --yes"]})).addCommand(Uu).addCommand(Ku).addCommand(ku).addCommand(vu,{isDefault:!0}).addCommand(Ru).addCommand(Su);var Bu=require("node:path");he();J();var Du={flag:"flag",env:"environment variable",config:"config file",secure_storage:"secure storage"},pf={full_access:"full access",sending_access:"sending access"},Eu=new p("whoami").description("Show current authentication status").addHelpText("after",m({setup:!0,context:`Local only \u2014 no network calls.
|
|
911
|
+
Shows which profile is active and where the active credential comes from.`,output:' {"authenticated":true,"profile":"production","api_key":"re_...abcd","source":"config","config_path":"/Users/you/.config/resend/credentials.json"}\n {"error":{"message":"Not authenticated.\\nRun `resend login` to get started.","code":"not_authenticated"}}',examples:["resend whoami","resend whoami --json","resend whoami --profile production"]})).action(async(e,t)=>{let o=t.optsWithGlobals(),i=o.profile,r=await St(o.apiKey,i,{refresh:!1});if(!r){let f=i||No(i),A=ve(),h=A.some(K=>K.name===f),b=i||process.env.RESEND_PROFILE,S=b&&!h?`Profile "${f}" not found.
|
|
912
|
+
Available profiles: ${A.map(K=>K.name).join(", ")||"(none)"}`:"Not authenticated.\nRun `resend login` to get started.",v=b&&!h?"profile_not_found":"not_authenticated";o.json||!U()?g({message:S,code:v},{json:o.json}):g({message:S,code:v},{json:!1})}let n=r.profile??No(i),s=(0,Bu.join)(Ie(),"credentials.json"),a=r.type==="api_key"?r.key:r.access_token,l=r.source,d=r.type==="api_key"?r.permission:void 0;if(o.json||!U()){E({authenticated:!0,profile:n,api_key:dt(a),source:l,...d&&{permission:d},config_path:s},{json:o.json});return}let c=r.type==="oauth_grant"?`${Du[l]} (oauth)`:Du[l],u=d?pf[d]:void 0;console.log(""),console.log(` Profile: ${n}`),console.log(r.type==="oauth_grant"?` Token: ${dt(a)}`:` API Key: ${dt(a)}`),console.log(` Source: ${c}`),u&&console.log(` Access: ${u}`),console.log(` Config: ${s}`),console.log("")});function Ou(e,t={}){let o=t.getArgv??(()=>process.argv.slice(2)),i=[],r=[e];for(;r.length>0;){let n=r.pop();if(!n)break;i.push(n);for(let s of n.commands)r.push(s)}for(let n of i){let a=n.configureOutput().outputError??((l,d)=>d(l));n.configureOutput({outputError:(l,d)=>{a(mf(l,e,o()),d)}})}}function mf(e,t,o){if(!gf(e))return e;let i=ff(t,o);return i?hf(e,i):e}function ff(e,t){let o=e,i=[];for(let r=0;r<t.length;r+=1){let n=t[r];if(!n||n==="--")return;let s=r;if(n.startsWith("-")&&n!=="-"){let d=n.startsWith("--")?n.split("=",1)[0]:n.length>2?n.slice(0,2):n,c;for(let u of Af(o)){for(let f of u.createHelp().visibleOptions(u))if(f.long===d||f.short===d){c=f;break}if(c)break}if(!c)s=void 0;else if(!c.required&&!c.optional)s=r+1;else if(c.variadic)s=t.length;else if(n.startsWith("--")&&n.includes("="))s=r+1;else if(!n.startsWith("--")&&n.length>2)s=r+1;else{let u=t[r+1];c.optional&&(u===void 0||u.startsWith("-"))?s=r+1:s=Math.min(r+2,t.length)}}if(s===void 0)return;if(s!==r){r=s-1;continue}if(n.startsWith("-"))return;let a=bf(o).find(d=>ju(d).has(n));if(a){o=a,i.push(a.name());continue}let l=Cf(n,Tu(o)).map(d=>[e.name(),...i,d.name()].join(" "));return l.length===0?void 0:{unknownCommand:n,suggestions:l}}}function gf(e){return/^error: unknown command /.test(e)||/^error: too many arguments/.test(e)}function hf(e,t){let o=e.endsWith(`
|
|
913
913
|
`)?`
|
|
914
914
|
`:"",{suggestions:i}=t,r=i.length===1?"Did you mean this?":"Did you mean one of these?",n=i.map(s=>` ${s}`).join(`
|
|
915
915
|
`);return`error: unknown command '${t.unknownCommand}'
|
|
@@ -918,7 +918,7 @@ ${r}
|
|
|
918
918
|
${n}${o}`}function Af(e){let t=[];for(let o=e;o;o=o.parent)t.push(o);return t}function Tu(e){return e.createHelp().visibleCommands(e).filter(t=>!t._hidden)}function bf(e){let t=[...e.commands];for(let o of Tu(e))t.includes(o)||t.push(o);return t}function ju(e){return new Set([e.name(),...e.aliases()])}function Cf(e,t){let o=t.map(r=>{let n=Number.POSITIVE_INFINITY;for(let s of ju(r)){if(s.length<=1)continue;let a=yf(e,s,3),l=Math.max(e.length,s.length),d=(l-a)/l;a<=3&&d>.4&&a<n&&(n=a)}return{command:r,distance:n}}).filter(r=>Number.isFinite(r.distance));if(o.length===0)return[];let i=Math.min(...o.map(r=>r.distance));return o.filter(r=>r.distance===i).sort((r,n)=>r.command.name().localeCompare(n.command.name())).map(r=>r.command)}function yf(e,t,o=Number.POSITIVE_INFINITY){if(Math.abs(e.length-t.length)>o)return Math.max(e.length,t.length);let i=[];for(let r=0;r<=e.length;r+=1)i[r]=[r];for(let r=0;r<=t.length;r+=1)i[0][r]=r;for(let r=1;r<=t.length;r+=1)for(let n=1;n<=e.length;n+=1){let s=e[n-1]===t[r-1]?0:1;i[n][r]=Math.min(i[n-1][r]+1,i[n][r-1]+1,i[n-1][r-1]+s),n>1&&r>1&&e[n-1]===t[r-2]&&e[n-2]===t[r-1]&&(i[n][r]=Math.min(i[n][r],i[n-2][r-2]+1))}return i[e.length][t.length]}var Uf=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557"," \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551"," \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551"," \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D"," \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u255D "];function Iu(){process.stdout.write(`
|
|
919
919
|
`);for(let e of Uf)process.stdout.write(`${e}
|
|
920
920
|
`);process.stdout.write(`
|
|
921
|
-
`)}Tr();fo();bt();Ms();var jr="",Mu=[],Lu=[],gt=new p().name("resend").description("Resend CLI \u2014 email for developers").configureHelp({showGlobalOptions:!0,styleTitle:e=>Mt.default.gray(e)}).configureOutput({writeErr:e=>{process.stderr.write(e.replace(/^error:/,()=>Mt.default.red("error:")))}}).helpCommand(!0).version(`${
|
|
921
|
+
`)}Tr();fo();bt();Ms();var jr="",Mu=[],Lu=[],gt=new p().name("resend").description("Resend CLI \u2014 email for developers").configureHelp({showGlobalOptions:!0,styleTitle:e=>Mt.default.gray(e)}).configureOutput({writeErr:e=>{process.stderr.write(e.replace(/^error:/,()=>Mt.default.red("error:")))}}).helpCommand(!0).version(`${Bn} v${re}`,"-v, --version","Output the current version").option("--api-key <key>","Resend API key (overrides env/config)").option("-p, --profile <name>","Profile to use (overrides RESEND_PROFILE)").option("--json","Force JSON output").option("-q, --quiet","Suppress spinners and status output (implies --json)").option("--insecure-storage","Save API key as plaintext instead of secure storage").hook("preAction",(e,t)=>{let o=[];for(let r=t;r?.parent;r=r.parent)o.unshift(r.name());jr=o.join(" ");let i=r=>r.options.filter(n=>r.getOptionValueSource(n.attributeName())==="cli").map(n=>n.long?.replace(/^--/,"")??n.short?.replace(/^-/,"")??"").filter(Boolean);Mu=i(t),Lu=i(e),t.optsWithGlobals().quiet&&e.setOptionValue("json",!0),t.optsWithGlobals().insecureStorage&&(process.env.RESEND_CREDENTIAL_STORE="file")}).addHelpText("after",`
|
|
922
922
|
${Mt.default.gray("Examples:")}
|
|
923
923
|
|
|
924
924
|
- Login to Resend
|
|
@@ -928,4 +928,4 @@ ${Mt.default.gray("Examples:")}
|
|
|
928
928
|
- Send an email
|
|
929
929
|
|
|
930
930
|
${Mt.default.blue("$ resend emails send")}
|
|
931
|
-
`).action(()=>{process.stdout.isTTY&&Iu();let e=gt.opts();e.apiKey&&g({message:"--api-key is a per-command override and was not saved. To store your API key, run `resend login`.",code:"missing_command"},{json:e.json}),gt.help()}).addCommand(Xo).addCommand(Cc).addCommand(Wa).addCommand(xa).addCommand(kc).addCommand(pu).addCommand(Dl).addCommand(ul).addCommand(Lc).addCommand(bu).addCommand(zl).addCommand(Oc).addCommand(ou).addCommand(na).addCommand(_u).addCommand($c).addCommand(fa).addCommand(Zo).addCommand(
|
|
931
|
+
`).action(()=>{process.stdout.isTTY&&Iu();let e=gt.opts();e.apiKey&&g({message:"--api-key is a per-command override and was not saved. To store your API key, run `resend login`.",code:"missing_command"},{json:e.json}),gt.help()}).addCommand(Xo).addCommand(Cc).addCommand(Wa).addCommand(xa).addCommand(kc).addCommand(pu).addCommand(Dl).addCommand(ul).addCommand(Lc).addCommand(bu).addCommand(zl).addCommand(Oc).addCommand(ou).addCommand(na).addCommand(_u).addCommand($c).addCommand(fa).addCommand(Zo).addCommand(Eu).addCommand($l).addCommand(Hc).addCommand(Bl).addCommand(Cu).addCommand(Za).addCommand(il),Wu=new p("telemetry").description("Telemetry management").helpCommand(!1);Wu.command("flush").argument("<file>").action(async e=>{let{flushFromFile:t}=await Promise.resolve().then(()=>(Tr(),qu));await t(e)});gt.addCommand(Wu,{hidden:!0});Ou(gt);gt.parseAsync().then(()=>{let e=gt.args[0];if(e==="update"||e==="telemetry")return;jr&&Or(jr,{...gt.opts(),flags:Mu,globalFlags:Lu});let t=gt.opts();Il({json:!!(t.json||t.quiet)}).catch(()=>{})}).catch(e=>{g({message:q(e,"An unexpected error occurred"),code:"unexpected_error"})});
|