blink 1.1.21 → 1.1.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import{__commonJSMin as e,__require as t,__toESM as n}from"./chunk-D9KrCrVq.js";import{import_websocket as r}from"./wrapper-B0SBsJWP.js";import{findNearestEntry as i,migrateDataToBlink as a,require_main as o,resolveConfig as s}from"./util-k3x8m_i5.js";import{Client as c,M as l,Y as u,pD as d,ve as f,ye as p}from"./dist-Ceoe3h7v.js";import{loginIfNeeded as m}from"./auth-BilZuH-1.js";import{source_default as h}from"./util-CUfifM0g.js";import{require_ignore as g}from"./ignore-NA4V6Pjc.js";import{getDevhookID as _,resetDevhookID as ee}from"./create-slack-app-CyVPwWsG.js";import{setupSlackAppCommand as v}from"./setup-slack-app-DagQxNol.js";import{randomUUID as y}from"crypto";import{basename as b,dirname as te,join as x,relative as S}from"node:path";import{existsSync as ne}from"node:fs";import{mkdir as C,readdir as w,writeFile as T}from"fs/promises";import{readFile as E,stat as D}from"node:fs/promises";import{inspect as re}from"node:util";var O=e((e=>{var t=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},n=class extends t{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};e.CommanderError=t,e.InvalidArgumentError=n})),k=e((e=>{let{InvalidArgumentError:t}=O();var n=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}e.Argument=n,e.humanReadableArgName=r})),A=e((e=>{let{humanReadableArgName:t}=k();var n=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(e=>t(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(n?` `+n:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
2
+ import{__commonJSMin as e,__require as t,__toESM as n}from"./chunk-D9KrCrVq.js";import{import_websocket as r}from"./wrapper-B0SBsJWP.js";import{findNearestEntry as i,migrateDataToBlink as a,require_main as o,resolveConfig as s}from"./util-k3x8m_i5.js";import{Client as c,M as l,Y as u,pD as d,ve as f,ye as p}from"./dist-Ceoe3h7v.js";import{loginIfNeeded as m}from"./auth-DbpOUCTO.js";import{source_default as h}from"./util-CUfifM0g.js";import{require_ignore as g}from"./ignore-NA4V6Pjc.js";import{getDevhookID as _,resetDevhookID as ee}from"./create-slack-app-CyVPwWsG.js";import{setupSlackAppCommand as v}from"./setup-slack-app-DagQxNol.js";import{randomUUID as y}from"crypto";import{basename as b,dirname as te,join as x,relative as S}from"node:path";import{existsSync as ne}from"node:fs";import{mkdir as C,readdir as w,writeFile as re}from"fs/promises";import{readFile as T,stat as E}from"node:fs/promises";import{inspect as ie}from"node:util";var D=e((e=>{var t=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},n=class extends t{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};e.CommanderError=t,e.InvalidArgumentError=n})),O=e((e=>{let{InvalidArgumentError:t}=D();var n=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}e.Argument=n,e.humanReadableArgName=r})),k=e((e=>{let{humanReadableArgName:t}=O();var n=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(e=>t(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(n?` `+n:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
3
3
  `)}displayWidth(e){return r(e).length}styleTitle(e){return e}styleUsage(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e===`[command]`?this.styleSubcommandText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleCommandText(e)).join(` `)}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleSubcommandText(e)).join(` `)}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let i=` `.repeat(2);if(!n)return i+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),o=(this.helpWidth??80)-t-2-2,s;return s=o<this.minWidthToWrap||r.preformatted(n)?n:r.boxWrap(n,o).replace(/\n/g,`
4
4
  `+` `.repeat(t+2)),i+a+` `.repeat(2)+s.replace(/\n/g,`\n${i}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,i=[];return n.forEach(e=>{let n=e.match(r);if(n===null){i.push(``);return}let a=[n.shift()],o=this.displayWidth(a[0]);n.forEach(e=>{let n=this.displayWidth(e);if(o+n<=t){a.push(e),o+=n;return}i.push(a.join(``));let r=e.trimStart();a=[r],o=this.displayWidth(r)}),i.push(a.join(``))}),i.join(`
5
- `)}};function r(e){return e.replace(/\x1b\[\d*(;\d*)*m/g,``)}e.Help=n,e.stripColor=r})),j=e((e=>{let{InvalidArgumentError:t}=O();var n=class{constructor(e,t){this.flags=e,this.description=t||``,this.required=e.includes(`<`),this.optional=e.includes(`[`),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=a(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith(`--no-`)),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e==`string`&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}name(){return this.long?this.long.replace(/^--/,``):this.short.replace(/^-/,``)}attributeName(){return this.negate?i(this.name().replace(/^no-/,``)):i(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},r=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r===void 0?!1:r;return t.negate===(i===e)}};function i(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function a(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,a=e.split(/[ |,]+/).concat(`guard`);if(r.test(a[0])&&(t=a.shift()),i.test(a[0])&&(n=a.shift()),!t&&r.test(a[0])&&(t=a.shift()),!t&&i.test(a[0])&&(t=n,n=a.shift()),a[0].startsWith(`-`)){let t=a[0],n=`option creation failed due to '${t}' in option flags '${e}'`;throw/^-[^-][^-]/.test(t)?Error(`${n}
5
+ `)}};function r(e){return e.replace(/\x1b\[\d*(;\d*)*m/g,``)}e.Help=n,e.stripColor=r})),A=e((e=>{let{InvalidArgumentError:t}=D();var n=class{constructor(e,t){this.flags=e,this.description=t||``,this.required=e.includes(`<`),this.optional=e.includes(`[`),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=a(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith(`--no-`)),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e==`string`&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}name(){return this.long?this.long.replace(/^--/,``):this.short.replace(/^-/,``)}attributeName(){return this.negate?i(this.name().replace(/^no-/,``)):i(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},r=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r===void 0?!1:r;return t.negate===(i===e)}};function i(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function a(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,a=e.split(/[ |,]+/).concat(`guard`);if(r.test(a[0])&&(t=a.shift()),i.test(a[0])&&(n=a.shift()),!t&&r.test(a[0])&&(t=a.shift()),!t&&i.test(a[0])&&(t=n,n=a.shift()),a[0].startsWith(`-`)){let t=a[0],n=`option creation failed due to '${t}' in option flags '${e}'`;throw/^-[^-][^-]/.test(t)?Error(`${n}
6
6
  - a short flag is a single dash and a single character
7
7
  - either use a single dash and a single character (for a short flag)
8
8
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):r.test(t)?Error(`${n}
9
9
  - too many short flags`):i.test(t)?Error(`${n}
10
10
  - too many long flags`):Error(`${n}
11
- - unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}e.Option=n,e.DualOptions=r})),M=e((e=>{function t(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let t=0;t<=e.length;t++)n[t]=[t];for(let e=0;e<=t.length;e++)n[0][e]=e;for(let r=1;r<=t.length;r++)for(let i=1;i<=e.length;i++){let a=1;a=e[i-1]===t[r-1]?0:1,n[i][r]=Math.min(n[i-1][r]+1,n[i][r-1]+1,n[i-1][r-1]+a),i>1&&r>1&&e[i-1]===t[r-2]&&e[i-2]===t[r-1]&&(n[i][r]=Math.min(n[i][r],n[i-2][r-2]+1))}return n[e.length][t.length]}function n(e,n){if(!n||n.length===0)return``;n=Array.from(new Set(n));let r=e.startsWith(`--`);r&&(e=e.slice(2),n=n.map(e=>e.slice(2)));let i=[],a=3;return n.forEach(n=>{if(n.length<=1)return;let r=t(e,n),o=Math.max(e.length,n.length);(o-r)/o>.4&&(r<a?(a=r,i=[n]):r===a&&i.push(n))}),i.sort((e,t)=>e.localeCompare(t)),r&&(i=i.map(e=>`--${e}`)),i.length>1?`\n(Did you mean one of ${i.join(`, `)}?)`:i.length===1?`\n(Did you mean ${i[0]}?)`:``}e.suggestSimilar=n})),N=e((e=>{let n=t(`node:events`).EventEmitter,r=t(`node:child_process`),i=t(`node:path`),a=t(`node:fs`),o=t(`node:process`),{Argument:s,humanReadableArgName:c}=k(),{CommanderError:l}=O(),{Help:u,stripColor:d}=A(),{Option:f,DualOptions:p}=j(),{suggestSimilar:m}=M();var h=class e extends n{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||``,this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description=``,this._summary=``,this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>o.stdout.write(e),writeErr:e=>o.stderr.write(e),outputError:(e,t)=>t(e),getOutHelpWidth:()=>o.stdout.isTTY?o.stdout.columns:void 0,getErrHelpWidth:()=>o.stderr.isTTY?o.stderr.columns:void 0,getOutHasColors:()=>_()??(o.stdout.isTTY&&o.stdout.hasColors?.()),getErrHasColors:()=>_()??(o.stderr.isTTY&&o.stderr.hasColors?.()),stripColor:e=>d(e)},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(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,i=n;typeof r==`object`&&r&&(i=r,r=null),i||={};let[,a,o]=e.match(/([^ ]+) *(.*)/),s=this.createCommand(a);return r&&(s.description(r),s._executableHandler=!0),i.isDefault&&(this._defaultCommandName=s._name),s._hidden=!!(i.noHelp||i.hidden),s._executableFile=i.executableFile||null,o&&s.arguments(o),this._registerCommand(s),s.parent=this,s.copyInheritedSettings(this),r?this:s}createCommand(t){return new e(t)}createHelp(){return Object.assign(new u,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!=`string`&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
11
+ - unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}e.Option=n,e.DualOptions=r})),j=e((e=>{function t(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let t=0;t<=e.length;t++)n[t]=[t];for(let e=0;e<=t.length;e++)n[0][e]=e;for(let r=1;r<=t.length;r++)for(let i=1;i<=e.length;i++){let a=1;a=e[i-1]===t[r-1]?0:1,n[i][r]=Math.min(n[i-1][r]+1,n[i][r-1]+1,n[i-1][r-1]+a),i>1&&r>1&&e[i-1]===t[r-2]&&e[i-2]===t[r-1]&&(n[i][r]=Math.min(n[i][r],n[i-2][r-2]+1))}return n[e.length][t.length]}function n(e,n){if(!n||n.length===0)return``;n=Array.from(new Set(n));let r=e.startsWith(`--`);r&&(e=e.slice(2),n=n.map(e=>e.slice(2)));let i=[],a=3;return n.forEach(n=>{if(n.length<=1)return;let r=t(e,n),o=Math.max(e.length,n.length);(o-r)/o>.4&&(r<a?(a=r,i=[n]):r===a&&i.push(n))}),i.sort((e,t)=>e.localeCompare(t)),r&&(i=i.map(e=>`--${e}`)),i.length>1?`\n(Did you mean one of ${i.join(`, `)}?)`:i.length===1?`\n(Did you mean ${i[0]}?)`:``}e.suggestSimilar=n})),ae=e((e=>{let n=t(`node:events`).EventEmitter,r=t(`node:child_process`),i=t(`node:path`),a=t(`node:fs`),o=t(`node:process`),{Argument:s,humanReadableArgName:c}=O(),{CommanderError:l}=D(),{Help:u,stripColor:d}=k(),{Option:f,DualOptions:p}=A(),{suggestSimilar:m}=j();var h=class e extends n{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||``,this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description=``,this._summary=``,this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>o.stdout.write(e),writeErr:e=>o.stderr.write(e),outputError:(e,t)=>t(e),getOutHelpWidth:()=>o.stdout.isTTY?o.stdout.columns:void 0,getErrHelpWidth:()=>o.stderr.isTTY?o.stderr.columns:void 0,getOutHasColors:()=>_()??(o.stdout.isTTY&&o.stdout.hasColors?.()),getErrHasColors:()=>_()??(o.stderr.isTTY&&o.stderr.hasColors?.()),stripColor:e=>d(e)},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(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,i=n;typeof r==`object`&&r&&(i=r,r=null),i||={};let[,a,o]=e.match(/([^ ]+) *(.*)/),s=this.createCommand(a);return r&&(s.description(r),s._executableHandler=!0),i.isDefault&&(this._defaultCommandName=s._name),s._hidden=!!(i.noHelp||i.hidden),s._executableFile=i.executableFile||null,o&&s.arguments(o),this._registerCommand(s),s.parent=this,s.copyInheritedSettings(this),r?this:s}createCommand(t){return new e(t)}createHelp(){return Object.assign(new u,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!=`string`&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
12
12
  - specify the name in Command constructor or using .name()`);return t||={},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new s(e,t)}argument(e,t,n,r){let i=this.createArgument(e,t);return typeof n==`function`?i.default(r).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==`boolean`)return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let[,n,r]=(e??`help [command]`).match(/([^ ]+) *(.*)/),i=t??`display help for command`,a=this.createCommand(n);return a.helpOption(!1),r&&a.arguments(r),i&&a.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=a,(e||t)&&this._initCommandGroup(a),this}addHelpCommand(e,t){return typeof e==`object`?(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this):(this.helpCommand(e,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(e,t){let n=[`preSubcommand`,`preAction`,`postAction`];if(!n.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
13
13
  Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=e=>{if(e.code!==`commander.executeSubCommandAsync`)throw e},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new l(e,t,n)),o.exit(e)}action(e){return this._actionHandler=t=>{let n=this.registeredArguments.length,r=t.slice(0,n);return this._storeOptionsAsProperties?r[n]=this:r[n]=this.opts(),r.push(this),e.apply(this,r)},this}createOption(e,t){return new f(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(e){if(e.code===`commander.invalidArgument`){let t=`${r} ${e.message}`;this.error(t,{exitCode:e.exitCode,code:e.code})}throw e}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
14
14
  - already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=e=>[e.name()].concat(e.aliases()),n=t(e).find(e=>this._findCommand(e));if(n){let r=t(this._findCommand(n)).join(`|`),i=t(e).join(`|`);throw Error(`cannot add command '${i}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let t=e.long.replace(/^--no-/,`--`);this._findOption(t)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,`default`)}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,`default`);let r=(t,r,i)=>{t==null&&e.presetArg!==void 0&&(t=e.presetArg);let a=this.getOptionValue(n);t!==null&&e.parseArg?t=this._callParseArg(e,t,a,r):t!==null&&e.variadic&&(t=e._collectValue(t,a)),t??=e.negate?!1:e.isBoolean()||e.optional?!0:``,this.setOptionValueWithSource(n,t,i)};return this.on(`option:`+t,t=>{let n=`error: option '${e.flags}' argument '${t}' is invalid.`;r(t,n,`cli`)}),e.envVar&&this.on(`optionEnv:`+t,t=>{let n=`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`;r(t,n,`env`)}),this}_optionEx(e,t,n,r,i){if(typeof t==`object`&&t instanceof f)throw Error(`To add an Option object use addOption() instead of option() or requiredOption()`);let a=this.createOption(t,n);if(a.makeOptionMandatory(!!e.mandatory),typeof r==`function`)a.default(i).argParser(r);else if(r instanceof RegExp){let e=r;r=(t,n)=>{let r=e.exec(t);return r?r[0]:n},a.default(i).argParser(r)}else a.default(r);return this.addOption(a)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error(`call .storeOptionsAsProperties() before adding options`);if(Object.keys(this._optionValues).length)throw Error(`call .storeOptionsAsProperties() before setting option values`);return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error(`first parameter to parse must be array or undefined`);if(t||={},e===void 0&&t.from===void 0){o.versions?.electron&&(t.from=`electron`);let e=o.execArgv??[];(e.includes(`-e`)||e.includes(`--eval`)||e.includes(`-p`)||e.includes(`--print`))&&(t.from=`eval`)}e===void 0&&(e=o.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case`node`:this._scriptPath=e[1],n=e.slice(2);break;case`electron`:o.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case`user`:n=e.slice(0);break;case`eval`:n=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||`program`,n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
@@ -17,9 +17,9 @@ Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._life
17
17
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
18
18
  - ${r}`;throw Error(i)}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function c(e,t){let n=i.resolve(e,t);if(a.existsSync(n))return n;if(s.includes(i.extname(t)))return;let r=s.find(e=>a.existsSync(`${n}${e}`));if(r)return`${n}${r}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let u=e._executableFile||`${this._name}-${e._name}`,d=this._executableDir||``;if(this._scriptPath){let e;try{e=a.realpathSync(this._scriptPath)}catch{e=this._scriptPath}d=i.resolve(i.dirname(e),d)}if(d){let t=c(d,u);if(!t&&!e._executableFile&&this._scriptPath){let n=i.basename(this._scriptPath,i.extname(this._scriptPath));n!==this._name&&(t=c(d,`${n}-${e._name}`))}u=t||u}n=s.includes(i.extname(u));let f;o.platform===`win32`?(this._checkForMissingExecutable(u,d,e._name),t.unshift(u),t=g(o.execArgv).concat(t),f=r.spawn(o.execPath,t,{stdio:`inherit`})):n?(t.unshift(u),t=g(o.execArgv).concat(t),f=r.spawn(o.argv[0],t,{stdio:`inherit`})):f=r.spawn(u,t,{stdio:`inherit`}),f.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{o.on(e,()=>{f.killed===!1&&f.exitCode===null&&f.kill(e)})});let p=this._exitCallback;f.on(`close`,e=>{e??=1,p?p(new l(e,`commander.executeSubCommandAsync`,`(close)`)):o.exit(e)}),f.on(`error`,t=>{if(t.code===`ENOENT`)this._checkForMissingExecutable(u,d,e._name);else if(t.code===`EACCES`)throw Error(`'${u}' not executable`);if(!p)o.exit(1);else{let e=new l(1,`commander.executeSubCommandAsync`,`(error)`);e.nestedError=t,p(e)}}),this.runningCommand=f}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,`preSubcommand`),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??`--help`])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(e,t,n)=>{let r=t;if(t!==null&&e.parseArg){let i=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;r=this._callParseArg(e,t,n,i)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((t,r)=>e(n,r,t),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then==`function`?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(e=>e._lifeCycleHooks[t]!==void 0).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{r.push({hookedCommand:e,callback:t})})}),t===`postAction`&&r.reverse(),r.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(e=>{r=this._chainOrCall(r,()=>e(this,t))}),r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let n;return n=this._chainOrCallHooks(n,`preAction`),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(i,e,t)})),n=this._chainOrCallHooks(n,`postAction`),n}if(this.parent?.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand(`*`))return this._dispatchSubcommand(`*`,e,t);this.listenerCount(`command:*`)?this.emit(`command:*`,e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(e=>{let t=e.attributeName();return this.getOptionValue(t)===void 0?!1:this.getOptionValueSource(t)!==`default`});e.filter(e=>e.conflictsWith.length>0).forEach(t=>{let n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function i(e){return e.length>1&&e[0]===`-`}let a=e=>/^-\d*\.?\d+(e[+-]?\d+)?$/.test(e)?!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e))):!1,o=null,s=null,c=0;for(;c<e.length||s;){let l=s??e[c++];if(s=null,l===`--`){r===n&&r.push(l),r.push(...e.slice(c));break}if(o&&(!i(l)||a(l))){this.emit(`option:${o.name()}`,l);continue}if(o=null,i(l)){let t=this._findOption(l);if(t){if(t.required){let n=e[c++];n===void 0&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,n)}else if(t.optional){let n=null;c<e.length&&(!i(e[c])||a(e[c]))&&(n=e[c++]),this.emit(`option:${t.name()}`,n)}else this.emit(`option:${t.name()}`);o=t.variadic?t:null;continue}}if(l.length>2&&l[0]===`-`&&l[1]!==`-`){let e=this._findOption(`-${l[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,l.slice(2)):(this.emit(`option:${e.name()}`),s=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let e=l.indexOf(`=`),t=this._findOption(l.slice(0,e));if(t&&(t.required||t.optional)){this.emit(`option:${t.name()}`,l.slice(e+1));continue}}if(r===t&&i(l)&&!(this.commands.length===0&&a(l))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),n.push(...e.slice(c));break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}else if(this._defaultCommandName){n.push(l,...e.slice(c));break}}if(this._passThroughOptions){r.push(l,...e.slice(c));break}r.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
19
19
  `),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in o.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||[`default`,`config`,`env`].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,o.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new p(this.options),t=e=>this.getOptionValue(e)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(e));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],`implied`)})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:`commander.missingArgument`})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:`commander.optionMissingArgument`})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:`commander.missingMandatoryOptionValue`})}_conflictingOption(e,t){let n=e=>{let t=e.attributeName(),n=this.getOptionValue(t),r=this.options.find(e=>e.negate&&t===e.attributeName()),i=this.options.find(e=>!e.negate&&t===e.attributeName());return r&&(r.presetArg===void 0&&n===!1||r.presetArg!==void 0&&n===r.presetArg)?r:i||e},r=e=>{let t=n(e),r=t.attributeName();return this.getOptionValueSource(r)===`env`?`environment variable '${t.envVar}'`:`option '${t.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:`commander.conflictingOption`})}unknownOption(e){if(this._allowUnknownOption)return;let t=``;if(e.startsWith(`--`)&&this._showSuggestionAfterError){let n=[],r=this;do{let e=r.createHelp().visibleOptions(r).filter(e=>e.long).map(e=>e.long);n=n.concat(e),r=r.parent}while(r&&!r._enablePositionalOptions);t=m(e,n)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:`commander.unknownOption`})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?``:`s`,r=`error: too many arguments${this.parent?` for '${this.name()}'`:``}. Expected ${t} argument${n} but got ${e.length}.`;this.error(r,{code:`commander.excessArguments`})}unknownCommand(){let e=this.args[0],t=``;if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=m(e,n)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:`commander.unknownCommand`})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t||=`-V, --version`,n||=`output the version number`;let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on(`option:`+r.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,`commander.version`,e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw Error(`Command alias can't be the same as its name`);let n=this.parent?._findCommand(e);if(n){let t=[n.name()].concat(n.aliases()).join(`|`);throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(e=>c(e));return[].concat(this.options.length||this._helpOption!==null?`[options]`:[],this.commands.length?`[command]`:[],this.registeredArguments.length?e:[]).join(` `)}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??``:(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??``:(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??``:(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=i.basename(e,i.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e||={};let t=!!e.error,n,r,i;return t?(n=e=>this._outputConfiguration.writeErr(e),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:e=>(r||(e=this._outputConfiguration.stripColor(e)),n(e)),hasColors:r,helpWidth:i}}outputHelp(e){let t;typeof e==`function`&&(t=e,e=void 0);let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(e=>e.emit(`beforeAllHelp`,r)),this.emit(`beforeHelp`,r);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),typeof i!=`string`&&!Buffer.isBuffer(i)))throw Error(`outputHelp callback must return a string or a Buffer`);n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit(`afterHelp`,r),this._getCommandAndAncestors().forEach(e=>e.emit(`afterAllHelp`,r))}helpOption(e,t){return typeof e==`boolean`?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??`-h, --help`,t??`display help for command`),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(o.exitCode??0);t===0&&e&&typeof e!=`function`&&e.error&&(t=1),this._exit(t,`commander.help`,`(outputHelp)`)}addHelpText(e,t){let n=[`beforeAll`,`before`,`after`,`afterAll`];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
20
- Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function g(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function _(){if(o.env.NO_COLOR||o.env.FORCE_COLOR===`0`||o.env.FORCE_COLOR===`false`)return!1;if(o.env.FORCE_COLOR||o.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=h,e.useColor=_}));const{program:P,createCommand:ie,createArgument:ae,createOption:oe,CommanderError:F,InvalidArgumentError:se,InvalidOptionArgumentError:ce,Command:I,Argument:le,Option:L,Help:R}=n(e((e=>{let{Argument:t}=k(),{Command:n}=N(),{CommanderError:r,InvalidArgumentError:i}=O(),{Help:a}=A(),{Option:o}=j();e.program=new n,e.createCommand=e=>new n(e),e.createOption=(e,t)=>new o(e,t),e.createArgument=(e,n)=>new t(e,n),e.Command=n,e.Option=o,e.Argument=t,e.Help=a,e.CommanderError=r,e.InvalidArgumentError=i,e.InvalidOptionArgumentError=i}))(),1).default;var z=`1.1.21`;async function B(e){e||=process.cwd();let t=s(e);await t.build({cwd:e,entry:t.entry,outdir:t.outdir,watch:!1,onStart:()=>{console.log(`Building agent...`)},onResult:e=>{`error`in e&&(console.error(e.error),process.exit(1));for(let t of e.warnings)console.warn(t.message);console.log(`Built agent to ${e.entry}`)}})}var V=n(o(),1),H=n(g(),1);async function U(e,t){e||=process.cwd(),await a(e);let n=await m(),r=new c({authToken:n,fetch:(e,t)=>{let n=new Headers(t?.headers);return n.set(`x-blink-cli-version`,z),fetch(e,{...t,headers:n})}}),o=await i(e,`package.json`);if(!o)throw Error(`package.json not found`);let l=await E(o,`utf-8`),g=JSON.parse(l),v=te(o),y=x(v,`.blink`,`config.json`),C={};if(ne(y)){let e=await E(y,`utf-8`);C=JSON.parse(e)}let O;if(C?.organizationId)try{O=(await r.organizations.get(C.organizationId)).name}catch{C.organizationId=void 0}if(!C?.organizationId){let e=await r.organizations.list();if(e.length===1)C.organizationId=e[0].id,O=e[0].name;else{let t=await f({message:`Which organization should contain this agent?`,options:e.map(e=>({value:e.id,label:e.name}))});if(d(t))return;C.organizationId=t,O=e.find(e=>e.id===t).name,console.log()}}let k,A=!1,j=!1;if(C?.agentId)try{k=(await r.agents.get(C.agentId)).name}catch{C.agentId=void 0}if(!C?.agentId)try{let e=await r.organizations.agents.get({organization_id:C.organizationId,agent_name:g.name});C.agentId=e.id,k=e.name}catch{A=!0,k=g.name}A?console.log(h.bold(`blink■`)+` creating agent `+O+`/`+k):console.log(h.bold(`blink■`)+` deploying agent `+O+`/`+k);let M=Date.now(),N=s(v),P=await new Promise((e,t)=>{N.build({cwd:v,entry:N.entry,outdir:N.outdir,watch:!1,onStart:()=>{},onResult:t=>{e(t)}}).catch(t)});if(!P)throw Error(`Failed to build agent`);if(`error`in P)throw Error(P.error.message);let ie=Date.now()-M;console.log(h.gray(`Built ${h.dim(`(${ie}ms)`)}`));let ae=await w(P.outdir),oe=Object.fromEntries(ae.map(e=>[x(P.outdir,e),e])),F=x(e,`README.md`);await W(F)&&(oe[F]=`README.md`);let se=await fe(v),ce=Object.fromEntries(se.map(e=>[e,S(v,e)])),I=Object.entries(oe),le=Object.entries(ce),L=[...I,...le],R=L.length,B=0,V=0,H=0,U=Array(R);await de(L,10,async([e,t],n)=>{let i=(await D(e)).size,a=++B;q(`${h.dim(`[${a}/${R}]`)} Uploading ${t} (${K(i)})...`);let o=await E(e),s=await r.files.upload(new File([Buffer.from(o)],t));U[n]={path:t,id:s.id},V+=1,H+=i}),q(h.gray(`Uploaded ${R} ${R===1?`file`:`files`} ${h.dim(`(${K(H)})`)}`)),process.stdout.write(`
21
- `);let J=U.filter(Boolean),Y=J.slice(0,I.length),pe=J.slice(I.length),X=await G(x(e,`.env.production`));if(A){let t=x(e,`.env.local`),n=x(e,`.env.production`),r=await G(t),i=Object.keys(r).filter(e=>!X[e]);if(i.length>0){console.log(`
22
- `+h.cyan(`Environment Variables`)),console.log(h.dim(` Missing ${i.length} var${i.length===1?``:`s`} in .env.production: ${i.join(`, `)}`));let e=await p({message:`Copy missing vars from .env.local to .env.production?`,initialValue:!0});if(d(e))return;if(console.log(),e){for(let e of i)X[e]=r[e];await T(n,`# Environment variables for production deployment\n${Object.entries(X).map(([e,t])=>`${e}=${t}`).join(`
23
- `)}`,`utf-8`)}}let a=_(e);if(a){let e=`https://${a}.blink.host`;console.log(`
24
- `+h.cyan(`Webhook Tunnel`)),console.log(h.dim(` Current: ${e} → local dev`)),console.log(h.dim(` After: ${e} → production`)),console.log(h.dim(` Migrating will keep your webhooks working in production`));let t=await p({message:`Migrate tunnel to production?`});if(d(t))return;console.log(),t&&(j=!0)}}let Z=Object.entries(X);if(A){let t=_(e),n=await r.agents.create({name:g.name,organization_id:C.organizationId,request_id:j?t:void 0,entrypoint:b(P.entry),output_files:Y,source_files:pe,env:Z.map(([e,t])=>({key:e,value:t,target:[`production`,`preview`],secret:!0}))});C.agentId=n.id,k=n.name;let i=`https://blink.so/${O}/${k}`;console.log(h.gray(`Agent created ${h.dim(i)}`))}else if(Z.length>0){let e=0;for(let[t,n]of Z)await r.agents.env.create({agent_id:C.agentId,key:t,value:n,target:[`production`,`preview`],secret:!0,upsert:!0}),q(`${h.dim(`[${++e}/${Z.length}]`)} Updating environment variable: ${t} ${h.dim(`(.env.production)`)}`);q(h.gray(`Updated ${Z.length} environment ${Z.length===1?`variable`:`variables`} ${h.dim(`(.env.production)`)}`)),process.stdout.write(`
25
- `)}let me=await G(x(e,`.env.local`)),he=Object.keys(me).filter(e=>!Object.keys(X).includes(e));if(he.length>0){console.log(`Warning: The following environment variables are set in .env.local but not in .env.production:`);for(let e of he)console.log(`- ${e}`);let e=await p({message:`Do you want to deploy anyway?`});if(e===!1||d(e))return}let ge=A?(await r.agents.deployments.list({agent_id:C.agentId})).items[0]:await r.agents.deployments.create({agent_id:C.agentId,target:`production`,entrypoint:b(P.entry),output_files:Y,source_files:pe,message:t?.message}),Q=`https://blink.so/${O}/${k}/deployments/${ge.number}`;console.log(h.gray(`View Deployment ${h.dim(Q)}`)),await ue(y,C);let $=u();$.start(`Waiting for deployment to be live...`);try{for(;;){let t=await r.agents.deployments.get({agent_id:C.agentId,deployment_id:ge.id});if(t.status===`success`){$.stop(),A?(console.log(`Your agent is live.`),console.log(h.dim(Q))):(console.log(`Deployed. All new chats will use this version.`),console.log(h.dim(Q))),j&&(ee(e),console.log(h.yellow(`Note:`)+` To continue developing locally with webhooks, you'll need to reconfigure external services (Slack, GitHub, etc.)`),Object.keys(me).some(e=>e.toLowerCase().includes(`slack`))&&console.log(`Run ${h.cyan(`blink setup slack-app`)} to create a new Slack app for development.`));break}if(t.status===`failed`){$.stop(`Failed`+(t.error_message?`: ${t.error_message}`:``)),console.log(),console.log(`Logs: `+h.dim(Q));return}await new Promise(e=>setTimeout(e,500))}}catch(e){$.stop(`Failed to poll deployment status`),console.log(),console.log(`Error: `+re(e)),console.log(`Logs: `+h.dim(Q))}}const W=async e=>{try{return await D(e),!0}catch{return!1}};async function G(e){return await W(e)?(0,V.parse)(await E(e,`utf-8`)):{}}async function ue(e,t){await C(te(e),{recursive:!0}),await T(e,JSON.stringify({_:`This file can be source controlled. It contains no secrets.`,...t},null,2),`utf-8`)}async function de(e,t,n){let r=Array(e.length),i=0,a=Array(Math.min(t,e.length)).fill(0).map(async()=>{for(;;){let t=i++;if(t>=e.length)break;r[t]=await n(e[t],t)}});return await Promise.all(a),r}function K(e){if(e===0)return`0B`;let t=1024,n=[`B`,`KB`,`MB`,`GB`,`TB`],r=Math.floor(Math.log(e)/Math.log(t)),i=e/t**+r;return`${i.toFixed(i>=100?0:i>=10?1:2)}${n[r]}`}function q(e){if(process.stdout.isTTY)try{process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(e);return}catch{}console.log(e)}async function fe(e){let t=[],n=(0,H.default)().add([`.git`,`node_modules`,`.blink`,`.env`,`.env.*`]),r=x(e,`.gitignore`);if(await W(r)){let e=await E(r,`utf-8`);n.add(e)}async function i(r,a=e){let o=await w(r,{withFileTypes:!0});for(let e of o){let o=x(r,e.name),s=S(a,o);n.ignores(s)||(e.isDirectory()?await i(o,a):e.isFile()&&t.push(o))}}return await i(e),t}if(globalThis.WebSocket||(globalThis.WebSocket=r.default),globalThis.Bun!==void 0){let e=t(`perf_hooks`);e.monitorEventLoopDelay=()=>({enable:()=>{}})}globalThis.crypto||(globalThis.crypto={}),globalThis.crypto.randomUUID||(globalThis.crypto.randomUUID=()=>y()),P.name(`blink`).description(`Blink is a runtime for building and deploying AI agents.`).version(z).action(()=>{P.outputHelp()});const J=e=>async(...t)=>{let{default:n}=await e();return n(...t)};P.command(`init [directory]`).description(`Initialize a new Blink agent.`).action(J(()=>import(`./init-BuMKmaaZ.js`))),P.command(`dev [directory] [options]`).description(`Start a development server for your agent.`).action(J(()=>import(`./dev-DRWR8F1H.js`))),P.command(`deploy [directory]`).description(`Deploy your agent to the Blink Cloud.`).option(`-m, --message <message>`,`Message for this deployment`).action(U),P.command(`build [directory]`).description(`Build your agent for production.`).action(B),P.command(`setup`).description(`Set up integrations for your agent.`).command(`slack-app [directory]`).description(`Set up Slack app integration`).action(v),P.command(`telemetry [boolean]`).description(`Enable or disable telemetry.`),P.command(`start [directory]`).description("Starts the Blink runtime in production mode. The agent must be compiled with `blink build` first."),P.command(`run <message...>`).description(`Run your agent programmatically and get the response.`).option(`-d, --directory <directory>`,`Directory to run the agent from (default: current directory)`).option(`-c, --chat <chat>`,`Chat key to use (default: 'default')`).action(J(()=>import(`./run-DF1dwAY_.js`))),P.command(`connect`,{hidden:!0}).description(`Connect compute to the Blink Cloud.`).action(J(()=>import(`./connect-DWScpJzS.js`))),P.command(`chat`,{hidden:!0}).description(`Start a Blink chat connected to your machine.`).action(J(()=>import(`./chat-CAtArOPl.js`))),P.command(`login`).description(`Log in to the Blink Cloud.`).action(J(()=>import(`./login-Bbj133_1.js`))),P.configureOutput({writeErr:e=>{let t=e.replace(/\x1b\[[0-9;]*m/g,``);l.error(t.trim())}}),process.on(`unhandledRejection`,e=>{l.error(e?.message||String(e)),process.exit(1)}),P.parse(process.argv);export{};
20
+ Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function g(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function _(){if(o.env.NO_COLOR||o.env.FORCE_COLOR===`0`||o.env.FORCE_COLOR===`false`)return!1;if(o.env.FORCE_COLOR||o.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=h,e.useColor=_}));const{program:M,createCommand:N,createArgument:oe,createOption:se,CommanderError:ce,InvalidArgumentError:P,InvalidOptionArgumentError:le,Command:ue,Argument:F,Option:de,Help:I}=n(e((e=>{let{Argument:t}=O(),{Command:n}=ae(),{CommanderError:r,InvalidArgumentError:i}=D(),{Help:a}=k(),{Option:o}=A();e.program=new n,e.createCommand=e=>new n(e),e.createOption=(e,t)=>new o(e,t),e.createArgument=(e,n)=>new t(e,n),e.Command=n,e.Option=o,e.Argument=t,e.Help=a,e.CommanderError=r,e.InvalidArgumentError=i,e.InvalidOptionArgumentError=i}))(),1).default;var L=`1.1.22`;async function R(e){e||=process.cwd();let t=s(e);await t.build({cwd:e,entry:t.entry,outdir:t.outdir,watch:!1,onStart:()=>{console.log(`Building agent...`)},onResult:e=>{`error`in e&&(console.error(e.error),process.exit(1));for(let t of e.warnings)console.warn(t.message);console.log(`Built agent to ${e.entry}`)}})}var z=n(o(),1),B=n(g(),1);async function V(e,t){e||=process.cwd();let n=process.env.CI===`true`||!process.stdout.isTTY;await a(e);let r=await m(),o=new c({authToken:r,fetch:(e,t)=>{let n=new Headers(t?.headers);return n.set(`x-blink-cli-version`,L),fetch(e,{...t,headers:n})}}),l=await i(e,`package.json`);if(!l)throw Error(`package.json not found`);let g=await T(l,`utf-8`),v=JSON.parse(g),y=te(l),C=x(y,`.blink`,`config.json`),D={};if(ne(C)){let e=await T(C,`utf-8`);D=JSON.parse(e)}process.env.BLINK_ORGANIZATION_ID&&(D.organizationId=process.env.BLINK_ORGANIZATION_ID),process.env.BLINK_AGENT_ID&&(D.agentId=process.env.BLINK_AGENT_ID);let O;if(D?.organizationId)try{O=(await o.organizations.get(D.organizationId)).name}catch{D.organizationId=void 0}if(!D?.organizationId){let e=await o.organizations.list();if(e.length===1)D.organizationId=e[0].id,O=e[0].name;else if(n)throw Error(`Multiple organizations found. To use CI mode, please deploy in interactive mode first to select an organization and generate .blink/config.json`);else{let t=await f({message:`Which organization should contain this agent?`,options:e.map(e=>({value:e.id,label:e.name}))});if(d(t))return;D.organizationId=t,O=e.find(e=>e.id===t).name,console.log()}}let k,A=!1,j=!1;if(D?.agentId)try{k=(await o.agents.get(D.agentId)).name}catch{D.agentId=void 0}if(!D?.agentId)try{let e=await o.organizations.agents.get({organization_id:D.organizationId,agent_name:v.name});D.agentId=e.id,k=e.name}catch{A=!0,k=v.name}A?console.log(h.bold(`blink■`)+` creating agent `+O+`/`+k):console.log(h.bold(`blink■`)+` deploying agent `+O+`/`+k);let ae=Date.now(),M=s(y),N=await new Promise((e,t)=>{M.build({cwd:y,entry:M.entry,outdir:M.outdir,watch:!1,onStart:()=>{},onResult:t=>{e(t)}}).catch(t)});if(!N)throw Error(`Failed to build agent`);if(`error`in N)throw Error(N.error.message);let oe=Date.now()-ae;console.log(h.gray(`Built ${h.dim(`(${oe}ms)`)}`));let se=await w(N.outdir),ce=Object.fromEntries(se.map(e=>[x(N.outdir,e),e])),P=x(e,`README.md`);await H(P)&&(ce[P]=`README.md`);let le=await me(y),ue=Object.fromEntries(le.map(e=>[e,S(y,e)])),F=Object.entries(ce),de=Object.entries(ue),I=[...F,...de],R=I.length,z=0,B=0,V=0,K=Array(R);await pe(I,10,async([e,t],n)=>{let r=(await E(e)).size,i=++z;G(`${h.dim(`[${i}/${R}]`)} Uploading ${t} (${W(r)})...`);let a=await T(e),s=await o.files.upload(new File([Buffer.from(a)],t));K[n]={path:t,id:s.id},B+=1,V+=r}),G(h.gray(`Uploaded ${R} ${R===1?`file`:`files`} ${h.dim(`(${W(V)})`)}`)),process.stdout.write(`
21
+ `);let q=K.filter(Boolean),he=q.slice(0,F.length),ge=q.slice(F.length),J=await U(x(e,`.env.production`));if(A){let t=x(e,`.env.local`),r=x(e,`.env.production`),i=await U(t),a=Object.keys(i).filter(e=>!J[e]);if(a.length>0)if(n)console.log(h.yellow(`Warning:`)+` Missing ${a.length} var${a.length===1?``:`s`} in .env.production: ${a.join(`, `)}`),console.log(h.dim(` Skipping in CI mode. Set these in .env.production if needed.`));else{console.log(`
22
+ `+h.cyan(`Environment Variables`)),console.log(h.dim(` Missing ${a.length} var${a.length===1?``:`s`} in .env.production: ${a.join(`, `)}`));let e=await p({message:`Copy missing vars from .env.local to .env.production?`,initialValue:!0});if(d(e))return;if(console.log(),e){for(let e of a)J[e]=i[e];await re(r,`# Environment variables for production deployment\n${Object.entries(J).map(([e,t])=>`${e}=${t}`).join(`
23
+ `)}`,`utf-8`)}}let o=_(e);if(o)if(n)console.log(h.dim(` Skipping webhook tunnel migration in CI mode`));else{let e=`https://${o}.blink.host`;console.log(`
24
+ `+h.cyan(`Webhook Tunnel`)),console.log(h.dim(` Current: ${e} → local dev`)),console.log(h.dim(` After: ${e} → production`)),console.log(h.dim(` Migrating will keep your webhooks working in production`));let t=await p({message:`Migrate tunnel to production?`});if(d(t))return;console.log(),t&&(j=!0)}}let Y=Object.entries(J);if(A){let t=_(e),n=await o.agents.create({name:v.name,organization_id:D.organizationId,request_id:j?t:void 0,entrypoint:b(N.entry),output_files:he,source_files:ge,env:Y.map(([e,t])=>({key:e,value:t,target:[`production`,`preview`],secret:!0}))});D.agentId=n.id,k=n.name;let r=`https://blink.so/${O}/${k}`;console.log(h.gray(`Agent created ${h.dim(r)}`))}else if(Y.length>0){let e=0;for(let[t,n]of Y)await o.agents.env.create({agent_id:D.agentId,key:t,value:n,target:[`production`,`preview`],secret:!0,upsert:!0}),G(`${h.dim(`[${++e}/${Y.length}]`)} Updating environment variable: ${t} ${h.dim(`(.env.production)`)}`);G(h.gray(`Updated ${Y.length} environment ${Y.length===1?`variable`:`variables`} ${h.dim(`(.env.production)`)}`)),process.stdout.write(`
25
+ `)}let X=await U(x(e,`.env.local`)),Z=Object.keys(X).filter(e=>!Object.keys(J).includes(e));if(Z.length>0)if(n){console.log(h.yellow(`Warning:`)+` The following environment variables are set in .env.local but not in .env.production:`);for(let e of Z)console.log(`- ${e}`);console.log(h.dim(` Continuing deployment in CI mode`))}else{console.log(`Warning: The following environment variables are set in .env.local but not in .env.production:`);for(let e of Z)console.log(`- ${e}`);let e=await p({message:`Do you want to deploy anyway?`});if(e===!1||d(e))return}let _e=A?(await o.agents.deployments.list({agent_id:D.agentId})).items[0]:await o.agents.deployments.create({agent_id:D.agentId,target:`production`,entrypoint:b(N.entry),output_files:he,source_files:ge,message:t?.message}),Q=`https://blink.so/${O}/${k}/deployments/${_e.number}`;console.log(h.gray(`View Deployment ${h.dim(Q)}`)),n||await fe(C,D);let $=u();$.start(`Waiting for deployment to be live...`);try{for(;;){let t=await o.agents.deployments.get({agent_id:D.agentId,deployment_id:_e.id});if(t.status===`success`){$.stop(),A?(console.log(`Your agent is live.`),console.log(h.dim(Q))):(console.log(`Deployed. All new chats will use this version.`),console.log(h.dim(Q))),j&&(ee(e),console.log(h.yellow(`Note:`)+` To continue developing locally with webhooks, you'll need to reconfigure external services (Slack, GitHub, etc.)`),Object.keys(X).some(e=>e.toLowerCase().includes(`slack`))&&console.log(`Run ${h.cyan(`blink setup slack-app`)} to create a new Slack app for development.`));break}if(t.status===`failed`){$.stop(`Failed`+(t.error_message?`: ${t.error_message}`:``)),console.log(),console.log(`Logs: `+h.dim(Q));return}await new Promise(e=>setTimeout(e,500))}}catch(e){$.stop(`Failed to poll deployment status`),console.log(),console.log(`Error: `+ie(e)),console.log(`Logs: `+h.dim(Q))}}const H=async e=>{try{return await E(e),!0}catch{return!1}};async function U(e){return await H(e)?(0,z.parse)(await T(e,`utf-8`)):{}}async function fe(e,t){await C(te(e),{recursive:!0}),await re(e,JSON.stringify({_:`This file can be source controlled. It contains no secrets.`,...t},null,2),`utf-8`)}async function pe(e,t,n){let r=Array(e.length),i=0,a=Array(Math.min(t,e.length)).fill(0).map(async()=>{for(;;){let t=i++;if(t>=e.length)break;r[t]=await n(e[t],t)}});return await Promise.all(a),r}function W(e){if(e===0)return`0B`;let t=1024,n=[`B`,`KB`,`MB`,`GB`,`TB`],r=Math.floor(Math.log(e)/Math.log(t)),i=e/t**+r;return`${i.toFixed(i>=100?0:i>=10?1:2)}${n[r]}`}function G(e){if(process.stdout.isTTY)try{process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(e);return}catch{}console.log(e)}async function me(e){let t=[],n=(0,B.default)().add([`.git`,`node_modules`,`.blink`,`.env`,`.env.*`]),r=x(e,`.gitignore`);if(await H(r)){let e=await T(r,`utf-8`);n.add(e)}async function i(r,a=e){let o=await w(r,{withFileTypes:!0});for(let e of o){let o=x(r,e.name),s=S(a,o);n.ignores(s)||(e.isDirectory()?await i(o,a):e.isFile()&&t.push(o))}}return await i(e),t}if(globalThis.WebSocket||(globalThis.WebSocket=r.default),globalThis.Bun!==void 0){let e=t(`perf_hooks`);e.monitorEventLoopDelay=()=>({enable:()=>{}})}globalThis.crypto||(globalThis.crypto={}),globalThis.crypto.randomUUID||(globalThis.crypto.randomUUID=()=>y()),M.name(`blink`).description(`Blink is a runtime for building and deploying AI agents.`).version(L).action(()=>{M.outputHelp()});const K=e=>async(...t)=>{let{default:n}=await e();return n(...t)};M.command(`init [directory]`).description(`Initialize a new Blink agent.`).action(K(()=>import(`./init-Ciwa_eM0.js`))),M.command(`dev [directory] [options]`).description(`Start a development server for your agent.`).action(K(()=>import(`./dev-BSh59jdn.js`))),M.command(`deploy [directory]`).description(`Deploy your agent to the Blink Cloud.`).option(`-m, --message <message>`,`Message for this deployment`).action(V),M.command(`build [directory]`).description(`Build your agent for production.`).action(R),M.command(`setup`).description(`Set up integrations for your agent.`).command(`slack-app [directory]`).description(`Set up Slack app integration`).action(v),M.command(`telemetry [boolean]`).description(`Enable or disable telemetry.`),M.command(`start [directory]`).description("Starts the Blink runtime in production mode. The agent must be compiled with `blink build` first."),M.command(`run <message...>`).description(`Run your agent programmatically and get the response.`).option(`-d, --directory <directory>`,`Directory to run the agent from (default: current directory)`).option(`-c, --chat <chat>`,`Chat key to use (default: 'default')`).action(K(()=>import(`./run-CZZ6WAdr.js`))),M.command(`connect`,{hidden:!0}).description(`Connect compute to the Blink Cloud.`).action(K(()=>import(`./connect-DWScpJzS.js`))),M.command(`chat`,{hidden:!0}).description(`Start a Blink chat connected to your machine.`).action(K(()=>import(`./chat-CAtArOPl.js`))),M.command(`login`).description(`Log in to the Blink Cloud.`).action(K(()=>import(`./login-BDP8JC4X.js`))),M.configureOutput({writeErr:e=>{let t=e.replace(/\x1b\[[0-9;]*m/g,``);l.error(t.trim())}}),process.on(`unhandledRejection`,e=>{l.error(e?.message||String(e)),process.exit(1)}),M.parse(process.argv);export{};
@@ -1,4 +1,4 @@
1
- import{__commonJSMin as e,__require as t,__toESM as n}from"./chunk-D9KrCrVq.js";import{Ie as r,M as i,Se as a,he as o,pD as s,ve as c,xe as l,ye as u}from"./dist-Ceoe3h7v.js";import"./util-CUfifM0g.js";import"./create-slack-app-CyVPwWsG.js";import{setupSlackApp as d}from"./setup-slack-app-DagQxNol.js";import{templates as f}from"./init-templates-B9PG-9Ei.js";import{basename as p,join as m}from"path";import{readFile as h,readdir as g,writeFile as _}from"fs/promises";import{spawn as v}from"child_process";var y=e((e=>{e.__esModule=!0,e.extend=a,e.indexOf=l,e.escapeExpression=u,e.isEmpty=d,e.createFrame=f,e.blockParams=p,e.appendContextPath=m;var t={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#x27;`,"`":`&#x60;`,"=":`&#x3D;`},n=/[&<>"'`=]/g,r=/[&<>"'`=]/;function i(e){return t[e]}function a(e){for(var t=1;t<arguments.length;t++)for(var n in arguments[t])Object.prototype.hasOwnProperty.call(arguments[t],n)&&(e[n]=arguments[t][n]);return e}var o=Object.prototype.toString;e.toString=o;var s=function(e){return typeof e==`function`};s(/x/)&&(e.isFunction=s=function(e){return typeof e==`function`&&o.call(e)===`[object Function]`}),e.isFunction=s;var c=Array.isArray||function(e){return e&&typeof e==`object`?o.call(e)===`[object Array]`:!1};e.isArray=c;function l(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}function u(e){if(typeof e!=`string`){if(e&&e.toHTML)return e.toHTML();if(e==null)return``;if(!e)return e+``;e=``+e}return r.test(e)?e.replace(n,i):e}function d(e){return!e&&e!==0?!0:!!(c(e)&&e.length===0)}function f(e){var t=a({},e);return t._parent=e,t}function p(e,t){return e.path=t,e}function m(e,t){return(e?e+`.`:``)+t}})),b=e(((e,t)=>{e.__esModule=!0;var n=[`description`,`fileName`,`lineNumber`,`endLineNumber`,`message`,`name`,`number`,`stack`];function r(e,t){var i=t&&t.loc,a=void 0,o=void 0,s=void 0,c=void 0;i&&(a=i.start.line,o=i.end.line,s=i.start.column,c=i.end.column,e+=` - `+a+`:`+s);for(var l=Error.prototype.constructor.call(this,e),u=0;u<n.length;u++)this[n[u]]=l[n[u]];Error.captureStackTrace&&Error.captureStackTrace(this,r);try{i&&(this.lineNumber=a,this.endLineNumber=o,Object.defineProperty?(Object.defineProperty(this,`column`,{value:s,enumerable:!0}),Object.defineProperty(this,`endColumn`,{value:c,enumerable:!0})):(this.column=s,this.endColumn=c))}catch{}}r.prototype=Error(),e.default=r,t.exports=e.default})),x=e(((e,t)=>{e.__esModule=!0;var n=y();e.default=function(e){e.registerHelper(`blockHelperMissing`,function(t,r){var i=r.inverse,a=r.fn;if(t===!0)return a(this);if(t===!1||t==null)return i(this);if(n.isArray(t))return t.length>0?(r.ids&&=[r.name],e.helpers.each(t,r)):i(this);if(r.data&&r.ids){var o=n.createFrame(r.data);o.contextPath=n.appendContextPath(r.data.contextPath,r.name),r={data:o}}return a(t,r)})},t.exports=e.default})),S=e(((e,t)=>{e.__esModule=!0;function n(e){return e&&e.__esModule?e:{default:e}}var r=y(),i=b(),a=n(i);e.default=function(e){e.registerHelper(`each`,function(e,t){if(!t)throw new a.default(`Must pass iterator to #each`);var n=t.fn,i=t.inverse,o=0,s=``,c=void 0,l=void 0;t.data&&t.ids&&(l=r.appendContextPath(t.data.contextPath,t.ids[0])+`.`),r.isFunction(e)&&(e=e.call(this)),t.data&&(c=r.createFrame(t.data));function u(t,i,a){c&&(c.key=t,c.index=i,c.first=i===0,c.last=!!a,l&&(c.contextPath=l+t)),s+=n(e[t],{data:c,blockParams:r.blockParams([e[t],t],[l+t,null])})}if(e&&typeof e==`object`)if(r.isArray(e))for(var d=e.length;o<d;o++)o in e&&u(o,o,o===e.length-1);else if(typeof Symbol==`function`&&e[Symbol.iterator]){for(var f=[],p=e[Symbol.iterator](),m=p.next();!m.done;m=p.next())f.push(m.value);e=f;for(var d=e.length;o<d;o++)u(o,o,o===e.length-1)}else (function(){var t=void 0;Object.keys(e).forEach(function(e){t!==void 0&&u(t,o-1),t=e,o++}),t!==void 0&&u(t,o-1,!0)})();return o===0&&(s=i(this)),s})},t.exports=e.default})),C=e(((e,t)=>{e.__esModule=!0;function n(e){return e&&e.__esModule?e:{default:e}}var r=b(),i=n(r);e.default=function(e){e.registerHelper(`helperMissing`,function(){if(arguments.length!==1)throw new i.default(`Missing helper: "`+arguments[arguments.length-1].name+`"`)})},t.exports=e.default})),w=e(((e,t)=>{e.__esModule=!0;function n(e){return e&&e.__esModule?e:{default:e}}var r=y(),i=b(),a=n(i);e.default=function(e){e.registerHelper(`if`,function(e,t){if(arguments.length!=2)throw new a.default(`#if requires exactly one argument`);return r.isFunction(e)&&(e=e.call(this)),!t.hash.includeZero&&!e||r.isEmpty(e)?t.inverse(this):t.fn(this)}),e.registerHelper(`unless`,function(t,n){if(arguments.length!=2)throw new a.default(`#unless requires exactly one argument`);return e.helpers.if.call(this,t,{fn:n.inverse,inverse:n.fn,hash:n.hash})})},t.exports=e.default})),T=e(((e,t)=>{e.__esModule=!0,e.default=function(e){e.registerHelper(`log`,function(){for(var t=[void 0],n=arguments[arguments.length-1],r=0;r<arguments.length-1;r++)t.push(arguments[r]);var i=1;n.hash.level==null?n.data&&n.data.level!=null&&(i=n.data.level):i=n.hash.level,t[0]=i,e.log.apply(e,t)})},t.exports=e.default})),E=e(((e,t)=>{e.__esModule=!0,e.default=function(e){e.registerHelper(`lookup`,function(e,t,n){return e&&n.lookupProperty(e,t)})},t.exports=e.default})),D=e(((e,t)=>{e.__esModule=!0;function n(e){return e&&e.__esModule?e:{default:e}}var r=y(),i=b(),a=n(i);e.default=function(e){e.registerHelper(`with`,function(e,t){if(arguments.length!=2)throw new a.default(`#with requires exactly one argument`);r.isFunction(e)&&(e=e.call(this));var n=t.fn;if(r.isEmpty(e))return t.inverse(this);var i=t.data;return t.data&&t.ids&&(i=r.createFrame(t.data),i.contextPath=r.appendContextPath(t.data.contextPath,t.ids[0])),n(e,{data:i,blockParams:r.blockParams([e],[i&&i.contextPath])})})},t.exports=e.default})),O=e((e=>{e.__esModule=!0,e.registerDefaultHelpers=g,e.moveHelperToHooks=_;function t(e){return e&&e.__esModule?e:{default:e}}var n=x(),r=t(n),i=S(),a=t(i),o=C(),s=t(o),c=w(),l=t(c),u=T(),d=t(u),f=E(),p=t(f),m=D(),h=t(m);function g(e){r.default(e),a.default(e),s.default(e),l.default(e),d.default(e),p.default(e),h.default(e)}function _(e,t,n){e.helpers[t]&&(e.hooks[t]=e.helpers[t],n||delete e.helpers[t])}})),k=e(((e,t)=>{e.__esModule=!0;var n=y();e.default=function(e){e.registerDecorator(`inline`,function(e,t,r,i){var a=e;return t.partials||(t.partials={},a=function(i,a){var o=r.partials;r.partials=n.extend({},o,t.partials);var s=e(i,a);return r.partials=o,s}),t.partials[i.args[0]]=i.fn,a})},t.exports=e.default})),ee=e((e=>{e.__esModule=!0,e.registerDefaultDecorators=i;function t(e){return e&&e.__esModule?e:{default:e}}var n=k(),r=t(n);function i(e){r.default(e)}})),A=e(((e,t)=>{e.__esModule=!0;var n=y(),r={methodMap:[`debug`,`info`,`warn`,`error`],level:`info`,lookupLevel:function(e){if(typeof e==`string`){var t=n.indexOf(r.methodMap,e.toLowerCase());e=t>=0?t:parseInt(e,10)}return e},log:function(e){if(e=r.lookupLevel(e),typeof console<`u`&&r.lookupLevel(r.level)<=e){var t=r.methodMap[e];console[t]||(t=`log`);var n=[...arguments].slice(1);console[t].apply(console,n)}}};e.default=r,t.exports=e.default})),j=e((e=>{e.__esModule=!0,e.createNewLookupObject=n;var t=y();function n(){var e=[...arguments];return t.extend.apply(void 0,[Object.create(null)].concat(e))}})),M=e((e=>{e.__esModule=!0,e.createProtoAccessControl=o,e.resultIsAllowed=s,e.resetLoggedProperties=u;function t(e){return e&&e.__esModule?e:{default:e}}var n=j(),r=A(),i=t(r),a=Object.create(null);function o(e){var t=Object.create(null);t.constructor=!1,t.__defineGetter__=!1,t.__defineSetter__=!1,t.__lookupGetter__=!1;var r=Object.create(null);return r.__proto__=!1,{properties:{whitelist:n.createNewLookupObject(r,e.allowedProtoProperties),defaultValue:e.allowProtoPropertiesByDefault},methods:{whitelist:n.createNewLookupObject(t,e.allowedProtoMethods),defaultValue:e.allowProtoMethodsByDefault}}}function s(e,t,n){return c(typeof e==`function`?t.methods:t.properties,n)}function c(e,t){return e.whitelist[t]===void 0?e.defaultValue===void 0?(l(t),!1):e.defaultValue:e.whitelist[t]===!0}function l(e){a[e]!==!0&&(a[e]=!0,i.default.log(`error`,`Handlebars: Access has been denied to resolve the property "`+e+`" because it is not an "own property" of its parent.
1
+ import{__commonJSMin as e,__require as t,__toESM as n}from"./chunk-D9KrCrVq.js";import{Ie as r,M as i,Se as a,he as o,pD as s,ve as c,xe as l,ye as u}from"./dist-Ceoe3h7v.js";import"./util-CUfifM0g.js";import"./create-slack-app-CyVPwWsG.js";import{setupSlackApp as d}from"./setup-slack-app-DagQxNol.js";import{templates as f}from"./init-templates-By3gx42M.js";import{basename as p,join as m}from"path";import{readFile as h,readdir as g,writeFile as _}from"fs/promises";import{spawn as v}from"child_process";var y=e((e=>{e.__esModule=!0,e.extend=a,e.indexOf=l,e.escapeExpression=u,e.isEmpty=d,e.createFrame=f,e.blockParams=p,e.appendContextPath=m;var t={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#x27;`,"`":`&#x60;`,"=":`&#x3D;`},n=/[&<>"'`=]/g,r=/[&<>"'`=]/;function i(e){return t[e]}function a(e){for(var t=1;t<arguments.length;t++)for(var n in arguments[t])Object.prototype.hasOwnProperty.call(arguments[t],n)&&(e[n]=arguments[t][n]);return e}var o=Object.prototype.toString;e.toString=o;var s=function(e){return typeof e==`function`};s(/x/)&&(e.isFunction=s=function(e){return typeof e==`function`&&o.call(e)===`[object Function]`}),e.isFunction=s;var c=Array.isArray||function(e){return e&&typeof e==`object`?o.call(e)===`[object Array]`:!1};e.isArray=c;function l(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}function u(e){if(typeof e!=`string`){if(e&&e.toHTML)return e.toHTML();if(e==null)return``;if(!e)return e+``;e=``+e}return r.test(e)?e.replace(n,i):e}function d(e){return!e&&e!==0?!0:!!(c(e)&&e.length===0)}function f(e){var t=a({},e);return t._parent=e,t}function p(e,t){return e.path=t,e}function m(e,t){return(e?e+`.`:``)+t}})),b=e(((e,t)=>{e.__esModule=!0;var n=[`description`,`fileName`,`lineNumber`,`endLineNumber`,`message`,`name`,`number`,`stack`];function r(e,t){var i=t&&t.loc,a=void 0,o=void 0,s=void 0,c=void 0;i&&(a=i.start.line,o=i.end.line,s=i.start.column,c=i.end.column,e+=` - `+a+`:`+s);for(var l=Error.prototype.constructor.call(this,e),u=0;u<n.length;u++)this[n[u]]=l[n[u]];Error.captureStackTrace&&Error.captureStackTrace(this,r);try{i&&(this.lineNumber=a,this.endLineNumber=o,Object.defineProperty?(Object.defineProperty(this,`column`,{value:s,enumerable:!0}),Object.defineProperty(this,`endColumn`,{value:c,enumerable:!0})):(this.column=s,this.endColumn=c))}catch{}}r.prototype=Error(),e.default=r,t.exports=e.default})),x=e(((e,t)=>{e.__esModule=!0;var n=y();e.default=function(e){e.registerHelper(`blockHelperMissing`,function(t,r){var i=r.inverse,a=r.fn;if(t===!0)return a(this);if(t===!1||t==null)return i(this);if(n.isArray(t))return t.length>0?(r.ids&&=[r.name],e.helpers.each(t,r)):i(this);if(r.data&&r.ids){var o=n.createFrame(r.data);o.contextPath=n.appendContextPath(r.data.contextPath,r.name),r={data:o}}return a(t,r)})},t.exports=e.default})),S=e(((e,t)=>{e.__esModule=!0;function n(e){return e&&e.__esModule?e:{default:e}}var r=y(),i=b(),a=n(i);e.default=function(e){e.registerHelper(`each`,function(e,t){if(!t)throw new a.default(`Must pass iterator to #each`);var n=t.fn,i=t.inverse,o=0,s=``,c=void 0,l=void 0;t.data&&t.ids&&(l=r.appendContextPath(t.data.contextPath,t.ids[0])+`.`),r.isFunction(e)&&(e=e.call(this)),t.data&&(c=r.createFrame(t.data));function u(t,i,a){c&&(c.key=t,c.index=i,c.first=i===0,c.last=!!a,l&&(c.contextPath=l+t)),s+=n(e[t],{data:c,blockParams:r.blockParams([e[t],t],[l+t,null])})}if(e&&typeof e==`object`)if(r.isArray(e))for(var d=e.length;o<d;o++)o in e&&u(o,o,o===e.length-1);else if(typeof Symbol==`function`&&e[Symbol.iterator]){for(var f=[],p=e[Symbol.iterator](),m=p.next();!m.done;m=p.next())f.push(m.value);e=f;for(var d=e.length;o<d;o++)u(o,o,o===e.length-1)}else (function(){var t=void 0;Object.keys(e).forEach(function(e){t!==void 0&&u(t,o-1),t=e,o++}),t!==void 0&&u(t,o-1,!0)})();return o===0&&(s=i(this)),s})},t.exports=e.default})),C=e(((e,t)=>{e.__esModule=!0;function n(e){return e&&e.__esModule?e:{default:e}}var r=b(),i=n(r);e.default=function(e){e.registerHelper(`helperMissing`,function(){if(arguments.length!==1)throw new i.default(`Missing helper: "`+arguments[arguments.length-1].name+`"`)})},t.exports=e.default})),w=e(((e,t)=>{e.__esModule=!0;function n(e){return e&&e.__esModule?e:{default:e}}var r=y(),i=b(),a=n(i);e.default=function(e){e.registerHelper(`if`,function(e,t){if(arguments.length!=2)throw new a.default(`#if requires exactly one argument`);return r.isFunction(e)&&(e=e.call(this)),!t.hash.includeZero&&!e||r.isEmpty(e)?t.inverse(this):t.fn(this)}),e.registerHelper(`unless`,function(t,n){if(arguments.length!=2)throw new a.default(`#unless requires exactly one argument`);return e.helpers.if.call(this,t,{fn:n.inverse,inverse:n.fn,hash:n.hash})})},t.exports=e.default})),T=e(((e,t)=>{e.__esModule=!0,e.default=function(e){e.registerHelper(`log`,function(){for(var t=[void 0],n=arguments[arguments.length-1],r=0;r<arguments.length-1;r++)t.push(arguments[r]);var i=1;n.hash.level==null?n.data&&n.data.level!=null&&(i=n.data.level):i=n.hash.level,t[0]=i,e.log.apply(e,t)})},t.exports=e.default})),E=e(((e,t)=>{e.__esModule=!0,e.default=function(e){e.registerHelper(`lookup`,function(e,t,n){return e&&n.lookupProperty(e,t)})},t.exports=e.default})),D=e(((e,t)=>{e.__esModule=!0;function n(e){return e&&e.__esModule?e:{default:e}}var r=y(),i=b(),a=n(i);e.default=function(e){e.registerHelper(`with`,function(e,t){if(arguments.length!=2)throw new a.default(`#with requires exactly one argument`);r.isFunction(e)&&(e=e.call(this));var n=t.fn;if(r.isEmpty(e))return t.inverse(this);var i=t.data;return t.data&&t.ids&&(i=r.createFrame(t.data),i.contextPath=r.appendContextPath(t.data.contextPath,t.ids[0])),n(e,{data:i,blockParams:r.blockParams([e],[i&&i.contextPath])})})},t.exports=e.default})),O=e((e=>{e.__esModule=!0,e.registerDefaultHelpers=g,e.moveHelperToHooks=_;function t(e){return e&&e.__esModule?e:{default:e}}var n=x(),r=t(n),i=S(),a=t(i),o=C(),s=t(o),c=w(),l=t(c),u=T(),d=t(u),f=E(),p=t(f),m=D(),h=t(m);function g(e){r.default(e),a.default(e),s.default(e),l.default(e),d.default(e),p.default(e),h.default(e)}function _(e,t,n){e.helpers[t]&&(e.hooks[t]=e.helpers[t],n||delete e.helpers[t])}})),k=e(((e,t)=>{e.__esModule=!0;var n=y();e.default=function(e){e.registerDecorator(`inline`,function(e,t,r,i){var a=e;return t.partials||(t.partials={},a=function(i,a){var o=r.partials;r.partials=n.extend({},o,t.partials);var s=e(i,a);return r.partials=o,s}),t.partials[i.args[0]]=i.fn,a})},t.exports=e.default})),ee=e((e=>{e.__esModule=!0,e.registerDefaultDecorators=i;function t(e){return e&&e.__esModule?e:{default:e}}var n=k(),r=t(n);function i(e){r.default(e)}})),A=e(((e,t)=>{e.__esModule=!0;var n=y(),r={methodMap:[`debug`,`info`,`warn`,`error`],level:`info`,lookupLevel:function(e){if(typeof e==`string`){var t=n.indexOf(r.methodMap,e.toLowerCase());e=t>=0?t:parseInt(e,10)}return e},log:function(e){if(e=r.lookupLevel(e),typeof console<`u`&&r.lookupLevel(r.level)<=e){var t=r.methodMap[e];console[t]||(t=`log`);var n=[...arguments].slice(1);console[t].apply(console,n)}}};e.default=r,t.exports=e.default})),j=e((e=>{e.__esModule=!0,e.createNewLookupObject=n;var t=y();function n(){var e=[...arguments];return t.extend.apply(void 0,[Object.create(null)].concat(e))}})),M=e((e=>{e.__esModule=!0,e.createProtoAccessControl=o,e.resultIsAllowed=s,e.resetLoggedProperties=u;function t(e){return e&&e.__esModule?e:{default:e}}var n=j(),r=A(),i=t(r),a=Object.create(null);function o(e){var t=Object.create(null);t.constructor=!1,t.__defineGetter__=!1,t.__defineSetter__=!1,t.__lookupGetter__=!1;var r=Object.create(null);return r.__proto__=!1,{properties:{whitelist:n.createNewLookupObject(r,e.allowedProtoProperties),defaultValue:e.allowProtoPropertiesByDefault},methods:{whitelist:n.createNewLookupObject(t,e.allowedProtoMethods),defaultValue:e.allowProtoMethodsByDefault}}}function s(e,t,n){return c(typeof e==`function`?t.methods:t.properties,n)}function c(e,t){return e.whitelist[t]===void 0?e.defaultValue===void 0?(l(t),!1):e.defaultValue:e.whitelist[t]===!0}function l(e){a[e]!==!0&&(a[e]=!0,i.default.log(`error`,`Handlebars: Access has been denied to resolve the property "`+e+`" because it is not an "own property" of its parent.
2
2
  You can add a runtime option to disable the check or this warning:
3
3
  See https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access for details`))}function u(){Object.keys(a).forEach(function(e){delete a[e]})}})),N=e((e=>{e.__esModule=!0,e.HandlebarsEnvironment=d;function t(e){return e&&e.__esModule?e:{default:e}}var n=y(),r=b(),i=t(r),a=O(),o=ee(),s=A(),c=t(s),l=M();e.VERSION=`4.7.8`,e.COMPILER_REVISION=8,e.LAST_COMPATIBLE_COMPILER_REVISION=7,e.REVISION_CHANGES={1:`<= 1.0.rc.2`,2:`== 1.0.0-rc.3`,3:`== 1.0.0-rc.4`,4:`== 1.x.x`,5:`== 2.0.0-alpha.x`,6:`>= 2.0.0-beta.1`,7:`>= 4.0.0 <4.3.0`,8:`>= 4.3.0`};var u=`[object Object]`;function d(e,t,n){this.helpers=e||{},this.partials=t||{},this.decorators=n||{},a.registerDefaultHelpers(this),o.registerDefaultDecorators(this)}d.prototype={constructor:d,logger:c.default,log:c.default.log,registerHelper:function(e,t){if(n.toString.call(e)===u){if(t)throw new i.default(`Arg not supported with multiple helpers`);n.extend(this.helpers,e)}else this.helpers[e]=t},unregisterHelper:function(e){delete this.helpers[e]},registerPartial:function(e,t){if(n.toString.call(e)===u)n.extend(this.partials,e);else{if(t===void 0)throw new i.default(`Attempting to register a partial called "`+e+`" as undefined`);this.partials[e]=t}},unregisterPartial:function(e){delete this.partials[e]},registerDecorator:function(e,t){if(n.toString.call(e)===u){if(t)throw new i.default(`Arg not supported with multiple decorators`);n.extend(this.decorators,e)}else this.decorators[e]=t},unregisterDecorator:function(e){delete this.decorators[e]},resetLoggedPropertyAccesses:function(){l.resetLoggedProperties()}},e.log=c.default.log,e.createFrame=n.createFrame,e.logger=c.default})),P=e(((e,t)=>{e.__esModule=!0;function n(e){this.string=e}n.prototype.toString=n.prototype.toHTML=function(){return``+this.string},e.default=n,t.exports=e.default})),F=e((e=>{e.__esModule=!0,e.wrapHelper=t;function t(e,t){return typeof e==`function`?function(){var n=arguments[arguments.length-1];return arguments[arguments.length-1]=t(n),e.apply(this,arguments)}:e}})),I=e((e=>{e.__esModule=!0,e.checkRevision=d,e.template=f,e.wrapProgram=p,e.resolvePartial=m,e.invokePartial=h,e.noop=g;function t(e){return e&&e.__esModule?e:{default:e}}function n(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}var r=y(),i=n(r),a=b(),o=t(a),s=N(),c=O(),l=F(),u=M();function d(e){var t=e&&e[0]||1,n=s.COMPILER_REVISION;if(!(t>=s.LAST_COMPATIBLE_COMPILER_REVISION&&t<=s.COMPILER_REVISION))if(t<s.LAST_COMPATIBLE_COMPILER_REVISION){var r=s.REVISION_CHANGES[n],i=s.REVISION_CHANGES[t];throw new o.default(`Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version (`+r+`) or downgrade your runtime to an older version (`+i+`).`)}else throw new o.default(`Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version (`+e[1]+`).`)}function f(e,t){if(!t)throw new o.default(`No environment passed to template`);if(!e||!e.main)throw new o.default(`Unknown template object: `+typeof e);e.main.decorator=e.main_d,t.VM.checkRevision(e.compiler);var n=e.compiler&&e.compiler[0]===7;function r(n,r,a){a.hash&&(r=i.extend({},r,a.hash),a.ids&&(a.ids[0]=!0)),n=t.VM.resolvePartial.call(this,n,r,a);var s=i.extend({},a,{hooks:this.hooks,protoAccessControl:this.protoAccessControl}),c=t.VM.invokePartial.call(this,n,r,s);if(c==null&&t.compile&&(a.partials[a.name]=t.compile(n,e.compilerOptions,t),c=a.partials[a.name](r,s)),c!=null){if(a.indent){for(var l=c.split(`
4
4
  `),u=0,d=l.length;u<d&&!(!l[u]&&u+1===d);u++)l[u]=a.indent+l[u];c=l.join(`
@@ -248,7 +248,8 @@ import { openai } from "@ai-sdk/openai";
248
248
  model: anthropic("claude-sonnet-4.5", {
249
249
  apiKey: process.env.ANTHROPIC_API_KEY,
250
250
  });
251
- model: openai("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
251
+ // Use chat API for OpenAI models - it's more reliable than the responses API
252
+ model: openai.chat("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
252
253
  \`\`\`
253
254
 
254
255
  **Note about Edit Mode:** Edit mode (this agent) automatically selects models in this priority:
@@ -786,7 +787,8 @@ import { openai } from "@ai-sdk/openai";
786
787
  model: anthropic("claude-sonnet-4.5", {
787
788
  apiKey: process.env.ANTHROPIC_API_KEY,
788
789
  });
789
- model: openai("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
790
+ // Use chat API for OpenAI models - it's more reliable than the responses API
791
+ model: openai.chat("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
790
792
  \`\`\`
791
793
 
792
794
  **Note about Edit Mode:** Edit mode (this agent) automatically selects models in this priority:
@@ -0,0 +1 @@
1
+ import"./dist-Ceoe3h7v.js";import{login as e}from"./auth-DbpOUCTO.js";import"./util-CUfifM0g.js";async function t(){await e()}export{t as default};
@@ -1 +1 @@
1
- import{__toESM as e}from"./chunk-D9KrCrVq.js";import{findNearestEntry as t,migrateDataToBlink as n,require_main as r,resolveConfig as i}from"./util-k3x8m_i5.js";import"./dist-Ceoe3h7v.js";import{getAuthToken as a}from"./auth-BilZuH-1.js";import"./util-CUfifM0g.js";import{ChatManager as o,Client as s}from"./chat-manager-DfVg04yc.js";import{spawn as c}from"node:child_process";import{join as l,resolve as u}from"node:path";import{existsSync as d}from"node:fs";import{readFile as f}from"node:fs/promises";import{createServer as p}from"node:net";async function m(e){let t=e.env?.PORT??await h(),n=e.env?.HOST??`127.0.0.1`,r=`http://${n}:${t}`,i={...e.env??process.env,PORT:t.toString(),HOST:n},a=c(e.command,e.args,{stdio:`pipe`,env:i});e.signal?.addEventListener(`abort`,()=>{try{a.kill()}catch{}},{once:!0});let o=new AbortController,l=[o.signal];e.signal&&l.push(e.signal);let u=AbortSignal.any(l);a.stdout.on(`data`,t=>{e.onStdout?.(Buffer.from(t).toString(`utf-8`))});let d=``;a.stderr.on(`data`,t=>{o.signal.aborted||(d+=Buffer.from(t).toString(`utf-8`)),e.onStderr?.(Buffer.from(t).toString(`utf-8`))}),a.on(`error`,e=>{o.abort(e)}),a.on(`exit`,(t,n)=>{o.signal.aborted?e.onExit?.(t,n):o.abort()});let f=new s({baseUrl:r}),p=0;for(;!u.aborted;){try{await f.health();break}catch{}if(await new Promise(e=>setTimeout(e,p*5)),p++,p>100)throw Error(`Health endpoint timed out`)}if(u.aborted)throw u.reason;return o.abort(),{client:f,dispose:()=>{a.kill()}}}async function h(){let e=p();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}var g=e(r(),1);async function _(e,r={}){if(!r.directory){let e=process.cwd();try{i(e),r.directory=e}catch{let n=await t(e,`.blink`);n&&d(l(n,`build`))&&(n=void 0),n?r.directory=n:r.directory=e}}await n(r.directory);let s=i(r.directory),c={};try{c=(0,g.parse)(await f(l(r.directory,`.env.local`),`utf-8`))}catch{}let p=await a(),h=await m({command:`node`,args:[`--experimental-strip-types`,`--no-deprecation`,s.entry],env:{...process.env,...c,BLINK_TOKEN:p}});console.log(`Agent spawned`);let _=u(r?.directory??process.cwd(),`.blink`,`chats`),v=new o({chatId:r?.chat,chatsDirectory:_});v.setAgent(h.client);try{let t=new Promise(e=>{let t=v.subscribe(n=>{(n.status===`idle`||n.status===`error`)&&(t(),e())})});await v.sendMessages([{id:crypto.randomUUID(),created_at:new Date().toISOString(),metadata:void 0,parts:[{type:`text`,text:e.join(` `)}],role:`user`,mode:`run`}]),await t;let n=v.getState();n.error&&console.error(`Error:`,n.error),console.log(`Final state:`,n.messages.pop())}finally{v.dispose(),h.dispose()}}export{_ as default};
1
+ import{__toESM as e}from"./chunk-D9KrCrVq.js";import{findNearestEntry as t,migrateDataToBlink as n,require_main as r,resolveConfig as i}from"./util-k3x8m_i5.js";import"./dist-Ceoe3h7v.js";import{getAuthToken as a}from"./auth-DbpOUCTO.js";import"./util-CUfifM0g.js";import{ChatManager as o,Client as s}from"./chat-manager-GWR_v50X.js";import{spawn as c}from"node:child_process";import{join as l,resolve as u}from"node:path";import{existsSync as d}from"node:fs";import{readFile as f}from"node:fs/promises";import{createServer as p}from"node:net";async function m(e){let t=e.env?.PORT??await h(),n=e.env?.HOST??`127.0.0.1`,r=`http://${n}:${t}`,i={...e.env??process.env,PORT:t.toString(),HOST:n},a=c(e.command,e.args,{stdio:`pipe`,env:i});e.signal?.addEventListener(`abort`,()=>{try{a.kill()}catch{}},{once:!0});let o=new AbortController,l=[o.signal];e.signal&&l.push(e.signal);let u=AbortSignal.any(l);a.stdout.on(`data`,t=>{e.onStdout?.(Buffer.from(t).toString(`utf-8`))});let d=``;a.stderr.on(`data`,t=>{o.signal.aborted||(d+=Buffer.from(t).toString(`utf-8`)),e.onStderr?.(Buffer.from(t).toString(`utf-8`))}),a.on(`error`,e=>{o.abort(e)}),a.on(`exit`,(t,n)=>{o.signal.aborted?e.onExit?.(t,n):o.abort()});let f=new s({baseUrl:r}),p=0;for(;!u.aborted;){try{await f.health();break}catch{}if(await new Promise(e=>setTimeout(e,p*5)),p++,p>100)throw Error(`Health endpoint timed out`)}if(u.aborted)throw u.reason;return o.abort(),{client:f,dispose:()=>{a.kill()}}}async function h(){let e=p();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}var g=e(r(),1);async function _(e,r={}){if(!r.directory){let e=process.cwd();try{i(e),r.directory=e}catch{let n=await t(e,`.blink`);n&&d(l(n,`build`))&&(n=void 0),n?r.directory=n:r.directory=e}}await n(r.directory);let s=i(r.directory),c={};try{c=(0,g.parse)(await f(l(r.directory,`.env.local`),`utf-8`))}catch{}let p=await a(),h=await m({command:`node`,args:[`--experimental-strip-types`,`--no-deprecation`,s.entry],env:{...process.env,...c,BLINK_TOKEN:p}});console.log(`Agent spawned`);let _=u(r?.directory??process.cwd(),`.blink`,`chats`),v=new o({chatId:r?.chat,chatsDirectory:_,onError:e=>{console.error(`Error:`,e)}});v.setAgent(h.client);try{let t=new Promise(e=>{let t=v.subscribe(n=>{(n.status===`idle`||n.status===`error`)&&(t(),e())})});await v.sendMessages([{id:crypto.randomUUID(),created_at:new Date().toISOString(),metadata:void 0,parts:[{type:`text`,text:e.join(` `)}],role:`user`,mode:`run`}]),await t;let n=v.getState();console.log(`Final state:`,n.messages.pop())}finally{v.dispose(),h.dispose()}}export{_ as default};