@hotglue/cli
Version:
hotglue CLI tools
34 lines • 104 kB
JavaScript
#!/usr/bin/env node
import e,{readFileSync as t,writeFile as n,statSync as o,existsSync as s,createWriteStream as r}from"fs";import a,{resolve as i,normalize as c}from"path";import l,{homedir as d}from"os";import u from"yargs";import{format as f,inspect as p}from"util";import"assert";import{fileURLToPath as g}from"url";import{mkdir as y,writeFile as h,readdir as m,readFile as b,stat as w}from"fs/promises";import{cosmiconfig as $}from"cosmiconfig";import v from"chalk";import j from"aws-sdk";import k from"debug";import _ from"yaml";import E from"cli-table";import O from"ora";import x from"micromatch";import S from"axios";import"progress";import{mkdir as I}from"node:fs/promises";import T from"crypto";function A(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var F,U,N,D,R,P,C,B={};function K(){if(F)return B;F=1;const t=e,n=a,o=l;function s(e){console.log(`[dotenv][DEBUG] ${e}`)}const r=/^\s*([\w.-]+)\s*=\s*("[^"]*"|'[^']*'|[^#]*)?(\s*|\s*#.*)?$/,i=/\\n/g,c=/\r\n|\n|\r/;function d(e,t){const n=Boolean(t&&t.debug),o={};return e.toString().split(c).forEach(function(e,t){const a=e.match(r);if(null!=a){const e=a[1];let t=a[2]||"";const n=t.length-1,s='"'===t[0]&&'"'===t[n];"'"===t[0]&&"'"===t[n]||s?(t=t.substring(1,n),s&&(t=t.replace(i,"\n"))):t=t.trim(),o[e]=t}else if(n){const n=e.trim();n.length&&"#"!==n[0]&&s(`Failed to match key and value when parsing line ${t+1}: ${e}`)}}),o}return B.config=function(e){let r=n.resolve(process.cwd(),".env"),a="utf8";const i=Boolean(e&&e.debug),c=Boolean(e&&e.override);var l;e&&(null!=e.path&&(r="~"===(l=e.path)[0]?n.join(o.homedir(),l.slice(1)):l),null!=e.encoding&&(a=e.encoding));try{const e=d(t.readFileSync(r,{encoding:a}),{debug:i});return Object.keys(e).forEach(function(t){Object.prototype.hasOwnProperty.call(process.env,t)?(!0===c&&(process.env[t]=e[t]),i&&s(!0===c?`"${t}" is already defined in \`process.env\` and WAS overwritten`:`"${t}" is already defined in \`process.env\` and was NOT overwritten`)):process.env[t]=e[t]}),{parsed:e}}catch(e){return i&&s(`Failed to load ${r} ${e.message}`),{error:e}}},B.parse=d,B}function M(){return process.versions.electron&&!process.defaultApp?0:1}
/**
* @license
* Copyright (c) 2016, Contributors
* SPDX-License-Identifier: ISC
*/
function L(e){if(e!==e.toLowerCase()&&e!==e.toUpperCase()||(e=e.toLowerCase()),-1===e.indexOf("-")&&-1===e.indexOf("_"))return e;{let t="",n=!1;const o=e.match(/^-+/);for(let s=o?o[0].length:0;s<e.length;s++){let o=e.charAt(s);n&&(n=!1,o=o.toUpperCase()),0===s||"-"!==o&&"_"!==o?"-"!==o&&"_"!==o&&(t+=o):n=!0}return t}}
/**
* @license
* Copyright (c) 2016, Contributors
* SPDX-License-Identifier: ISC
*/
let z;P||(P=1,K().config(Object.assign({},function(){if(N)return U;N=1;const e={};return null!=process.env.DOTENV_CONFIG_ENCODING&&(e.encoding=process.env.DOTENV_CONFIG_ENCODING),null!=process.env.DOTENV_CONFIG_PATH&&(e.path=process.env.DOTENV_CONFIG_PATH),null!=process.env.DOTENV_CONFIG_DEBUG&&(e.debug=process.env.DOTENV_CONFIG_DEBUG),null!=process.env.DOTENV_CONFIG_OVERRIDE&&(e.override=process.env.DOTENV_CONFIG_OVERRIDE),U=e}(),function(){if(R)return D;R=1;const e=/^dotenv_config_(encoding|path|debug|override)=(.+)$/;return D=function(t){return t.reduce(function(t,n){const o=n.match(e);return o&&(t[o[1]]=o[2]),t},{})}}()(process.argv)))),function(e){e.BOOLEAN="boolean",e.STRING="string",e.NUMBER="number",e.ARRAY="array"}(C||(C={}));function J(e){return void 0!==e?e+1:1}function q(e){return"__proto__"===e?"___proto___":e}
/**
* @fileoverview Main entrypoint for libraries using yargs-parser in Node.js
* CJS and ESM environments.
*
* @license
* Copyright (c) 2016, Contributors
* SPDX-License-Identifier: ISC
*/
const V=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):12;if(process&&process.version){if(Number(process.version.match(/v([^.]+)/)[1])<V)throw Error(`yargs parser supports a minimum Node.js version of ${V}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}const W=process?process.env:{};new class{constructor(e){z=e}parse(e,t){const n=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},t),o=
/**
* @license
* Copyright (c) 2016, Contributors
* SPDX-License-Identifier: ISC
*/
function(e){if(Array.isArray(e))return e.map(e=>"string"!=typeof e?e+"":e);e=e.trim();let t=0,n=null,o=null,s=null;const r=[];for(let a=0;a<e.length;a++)n=o,o=e.charAt(a)," "!==o||s?(o===s?s=null:"'"!==o&&'"'!==o||s||(s=o),r[t]||(r[t]=""),r[t]+=o):" "!==n&&t++;return r}
/**
* @license
* Copyright (c) 2016, Contributors
* SPDX-License-Identifier: ISC
*/(e),s="string"==typeof e,r=function(e){const t=[],n=Object.create(null);let o=!0;Object.keys(e).forEach(function(n){t.push([].concat(e[n],n))});for(;o;){o=!1;for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++){if(t[e].filter(function(e){return-1!==t[n].indexOf(e)}).length){t[e]=t[e].concat(t[n]),t.splice(n,1),o=!0;break}}}return t.forEach(function(e){const t=(e=e.filter(function(e,t,n){return n.indexOf(e)===t})).pop();void 0!==t&&"string"==typeof t&&(n[t]=e)}),n}(Object.assign(Object.create(null),n.alias)),a=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":"no-","parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},n.configuration),i=Object.assign(Object.create(null),n.default),c=n.configObjects||[],l=n.envPrefix,d=a["populate--"],u=d?"--":"_",f=Object.create(null),p=Object.create(null),g=n.__||z.format,y={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},h=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,m=new RegExp("^--"+a["negation-prefix"]+"(.+)");[].concat(n.array||[]).filter(Boolean).forEach(function(e){const t="object"==typeof e?e.key:e,n=Object.keys(e).map(function(e){return{boolean:"bools",string:"strings",number:"numbers"}[e]}).filter(Boolean).pop();n&&(y[n][t]=!0),y.arrays[t]=!0,y.keys.push(t)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(e){y.bools[e]=!0,y.keys.push(e)}),[].concat(n.string||[]).filter(Boolean).forEach(function(e){y.strings[e]=!0,y.keys.push(e)}),[].concat(n.number||[]).filter(Boolean).forEach(function(e){y.numbers[e]=!0,y.keys.push(e)}),[].concat(n.count||[]).filter(Boolean).forEach(function(e){y.counts[e]=!0,y.keys.push(e)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(e){y.normalize[e]=!0,y.keys.push(e)}),"object"==typeof n.narg&&Object.entries(n.narg).forEach(([e,t])=>{"number"==typeof t&&(y.nargs[e]=t,y.keys.push(e))}),"object"==typeof n.coerce&&Object.entries(n.coerce).forEach(([e,t])=>{"function"==typeof t&&(y.coercions[e]=t,y.keys.push(e))}),void 0!==n.config&&(Array.isArray(n.config)||"string"==typeof n.config?[].concat(n.config).filter(Boolean).forEach(function(e){y.configs[e]=!0}):"object"==typeof n.config&&Object.entries(n.config).forEach(([e,t])=>{"boolean"!=typeof t&&"function"!=typeof t||(y.configs[e]=t)})),function(...e){e.forEach(function(e){Object.keys(e||{}).forEach(function(e){y.aliases[e]||(y.aliases[e]=[].concat(r[e]||[]),y.aliases[e].concat(e).forEach(function(t){if(/-/.test(t)&&a["camel-case-expansion"]){const n=L(t);n!==e&&-1===y.aliases[e].indexOf(n)&&(y.aliases[e].push(n),f[n]=!0)}}),y.aliases[e].concat(e).forEach(function(t){if(t.length>1&&/[A-Z]/.test(t)&&a["camel-case-expansion"]){const n=function(e,t){const n=e.toLowerCase();t=t||"-";let o="";for(let s=0;s<e.length;s++){const r=n.charAt(s),a=e.charAt(s);o+=r!==a&&s>0?`${t}${n.charAt(s)}`:a}return o}(t,"-");n!==e&&-1===y.aliases[e].indexOf(n)&&(y.aliases[e].push(n),f[n]=!0)}}),y.aliases[e].forEach(function(t){y.aliases[t]=[e].concat(y.aliases[e].filter(function(e){return t!==e}))}))})})}(n.key,r,n.default,y.arrays),Object.keys(i).forEach(function(e){(y.aliases[e]||[]).forEach(function(t){i[t]=i[e]})});let b=null;Object.keys(y.counts).find(e=>N(e,y.arrays)?(b=Error(g("Invalid configuration: %s, opts.count excludes opts.array.",e)),!0):!!N(e,y.nargs)&&(b=Error(g("Invalid configuration: %s, opts.count excludes opts.narg.",e)),!0));let w=[];const $=Object.assign(Object.create(null),{_:[]}),v={};for(let e=0;e<o.length;e++){const t=o[e],n=t.replace(/^-{3,}/,"---");let s,r,i,c,l,d;if("--"!==t&&R(t))j(t);else{if(n.match(/---+(=|$)/)){j(t);continue}if(t.match(/^--.+=/)||!a["short-option-groups"]&&t.match(/^-.+=/))c=t.match(/^--?([^=]+)=([\s\S]*)$/),null!==c&&Array.isArray(c)&&c.length>=3&&(N(c[1],y.arrays)?e=_(e,c[1],o,c[2]):!1!==N(c[1],y.nargs)?e=k(e,c[1],o,c[2]):E(c[1],c[2],!0));else if(t.match(m)&&a["boolean-negation"])c=t.match(m),null!==c&&Array.isArray(c)&&c.length>=2&&(r=c[1],E(r,!!N(r,y.arrays)&&[!1]));else if(t.match(/^--.+/)||!a["short-option-groups"]&&t.match(/^-[^-]+/))c=t.match(/^--?(.+)/),null!==c&&Array.isArray(c)&&c.length>=2&&(r=c[1],N(r,y.arrays)?e=_(e,r,o):!1!==N(r,y.nargs)?e=k(e,r,o):(l=o[e+1],void 0===l||l.match(/^-/)&&!l.match(h)||N(r,y.bools)||N(r,y.counts)?/^(true|false)$/.test(l)?(E(r,l),e++):E(r,P(r)):(E(r,l),e++)));else if(t.match(/^-.\..+=/))c=t.match(/^-([^=]+)=([\s\S]*)$/),null!==c&&Array.isArray(c)&&c.length>=3&&E(c[1],c[2]);else if(t.match(/^-.\..+/)&&!t.match(h))l=o[e+1],c=t.match(/^-(.\..+)/),null!==c&&Array.isArray(c)&&c.length>=2&&(r=c[1],void 0===l||l.match(/^-/)||N(r,y.bools)||N(r,y.counts)?E(r,P(r)):(E(r,l),e++));else if(t.match(/^-[^-]+/)&&!t.match(h)){i=t.slice(1,-1).split(""),s=!1;for(let n=0;n<i.length;n++){if(l=t.slice(n+2),i[n+1]&&"="===i[n+1]){d=t.slice(n+3),r=i[n],N(r,y.arrays)?e=_(e,r,o,d):!1!==N(r,y.nargs)?e=k(e,r,o,d):E(r,d),s=!0;break}if("-"!==l){if(/[A-Za-z]/.test(i[n])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(l)&&!1===N(l,y.bools)){E(i[n],l),s=!0;break}if(i[n+1]&&i[n+1].match(/\W/)){E(i[n],l),s=!0;break}E(i[n],P(i[n]))}else E(i[n],l)}r=t.slice(-1)[0],s||"-"===r||(N(r,y.arrays)?e=_(e,r,o):!1!==N(r,y.nargs)?e=k(e,r,o):(l=o[e+1],void 0===l||/^(-|--)[^-]/.test(l)&&!l.match(h)||N(r,y.bools)||N(r,y.counts)?/^(true|false)$/.test(l)?(E(r,l),e++):E(r,P(r)):(E(r,l),e++)))}else if(t.match(/^-[0-9]$/)&&t.match(h)&&N(t.slice(1),y.bools))r=t.slice(1),E(r,P(r));else{if("--"===t){w=o.slice(e+1);break}if(a["halt-at-non-option"]){w=o.slice(e);break}j(t)}}}function j(e){const t=S("_",e);"string"!=typeof t&&"number"!=typeof t||$._.push(t)}function k(e,t,n,o){let s,r=N(t,y.nargs);if(r="number"!=typeof r||isNaN(r)?1:r,0===r)return B(o)||(b=Error(g("Argument unexpected for: %s",t))),E(t,P(t)),e;let i=B(o)?0:1;if(a["nargs-eats-options"])n.length-(e+1)+i<r&&(b=Error(g("Not enough arguments following: %s",t))),i=r;else{for(s=e+1;s<n.length&&(!n[s].match(/^-[^0-9]/)||n[s].match(h)||R(n[s]));s++)i++;i<r&&(b=Error(g("Not enough arguments following: %s",t)))}let c=Math.min(i,r);for(!B(o)&&c>0&&(E(t,o),c--),s=e+1;s<c+e+1;s++)E(t,n[s]);return e+c}function _(e,t,n,o){let r=[],c=o||n[e+1];const l=N(t,y.nargs);if(N(t,y.bools)&&!/^(true|false)$/.test(c))r.push(!0);else if(B(c)||B(o)&&/^-/.test(c)&&!h.test(c)&&!R(c)){if(void 0!==i[t]){const e=i[t];r=Array.isArray(e)?e:[e]}}else{B(o)||r.push(x(t,o,!0));for(let o=e+1;o<n.length&&!(!a["greedy-arrays"]&&r.length>0||l&&"number"==typeof l&&r.length>=l)&&(c=n[o],!/^-/.test(c)||h.test(c)||R(c));o++)e=o,r.push(x(t,c,s))}return"number"==typeof l&&(l&&r.length<l||isNaN(l)&&0===r.length)&&(b=Error(g("Not enough arguments following: %s",t))),E(t,r),e}function E(e,t,n=s){if(/-/.test(e)&&a["camel-case-expansion"]){const t=e.split(".").map(function(e){return L(e)}).join(".");O(e,t)}const o=x(e,t,n),r=e.split(".");if(U($,r,o),y.aliases[e]&&y.aliases[e].forEach(function(e){const t=e.split(".");U($,t,o)}),r.length>1&&a["dot-notation"]&&(y.aliases[r[0]]||[]).forEach(function(t){let n=t.split(".");const s=[].concat(r);s.shift(),n=n.concat(s),(y.aliases[e]||[]).includes(n.join("."))||U($,n,o)}),N(e,y.normalize)&&!N(e,y.arrays)){[e].concat(y.aliases[e]||[]).forEach(function(e){Object.defineProperty(v,e,{enumerable:!0,get:()=>t,set(e){t="string"==typeof e?z.normalize(e):e}})})}}function O(e,t){y.aliases[e]&&y.aliases[e].length||(y.aliases[e]=[t],f[t]=!0),y.aliases[t]&&y.aliases[t].length||O(t,e)}function x(e,t,n){n&&(t=function(e){return"string"!=typeof e||"'"!==e[0]&&'"'!==e[0]||e[e.length-1]!==e[0]?e:e.substring(1,e.length-1)}(t)),(N(e,y.bools)||N(e,y.counts))&&"string"==typeof t&&(t="true"===t);let o=Array.isArray(t)?t.map(function(t){return S(e,t)}):S(e,t);return N(e,y.counts)&&(B(o)||"boolean"==typeof o)&&(o=J()),N(e,y.normalize)&&N(e,y.arrays)&&(o=Array.isArray(t)?t.map(e=>z.normalize(e)):z.normalize(t)),o}function S(e,t){if(!a["parse-positional-numbers"]&&"_"===e)return t;if(!N(e,y.strings)&&!N(e,y.bools)&&!Array.isArray(t)){(null!=(n=t)&&("number"==typeof n||!!/^0x[0-9a-f]+$/i.test(n)||!/^0[^.]/.test(n)&&/^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(n))&&a["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${t}`)))||!B(t)&&N(e,y.numbers))&&(t=Number(t))}var n;return t}function I(e,t){Object.keys(e).forEach(function(n){const o=e[n],s=t?t+"."+n:n;"object"==typeof o&&null!==o&&!Array.isArray(o)&&a["dot-notation"]?I(o,s):(!F($,s.split("."))||N(s,y.arrays)&&a["combine-arrays"])&&E(s,o)})}function T(e,t){if(void 0===l)return;const n="string"==typeof l?l:"",o=z.env();Object.keys(o).forEach(function(s){if(""===n||0===s.lastIndexOf(n,0)){const r=s.split("__").map(function(e,t){return 0===t&&(e=e.substring(n.length)),L(e)});(t&&y.configs[r.join(".")]||!t)&&!F(e,r)&&E(r.join("."),o[s])}})}function A(e,t,n,o=!1){Object.keys(n).forEach(function(s){F(e,s.split("."))||(U(e,s.split("."),n[s]),o&&(p[s]=!0),(t[s]||[]).forEach(function(t){F(e,t.split("."))||U(e,t.split("."),n[s])}))})}function F(e,t){let n=e;a["dot-notation"]||(t=[t.join(".")]),t.slice(0,-1).forEach(function(e){n=n[e]||{}});const o=t[t.length-1];return"object"==typeof n&&o in n}function U(e,t,n){let o=e;a["dot-notation"]||(t=[t.join(".")]),t.slice(0,-1).forEach(function(e){e=q(e),"object"==typeof o&&void 0===o[e]&&(o[e]={}),"object"!=typeof o[e]||Array.isArray(o[e])?(Array.isArray(o[e])?o[e].push({}):o[e]=[o[e],{}],o=o[e][o[e].length-1]):o=o[e]});const s=q(t[t.length-1]),r=N(t.join("."),y.arrays),i=Array.isArray(n);let c=a["duplicate-arguments-array"];!c&&N(s,y.nargs)&&(c=!0,(!B(o[s])&&1===y.nargs[s]||Array.isArray(o[s])&&o[s].length===y.nargs[s])&&(o[s]=void 0)),n===J()?o[s]=J(o[s]):Array.isArray(o[s])?c&&r&&i?o[s]=a["flatten-duplicate-arrays"]?o[s].concat(n):(Array.isArray(o[s][0])?o[s]:[o[s]]).concat([n]):c||Boolean(r)!==Boolean(i)?o[s]=o[s].concat([n]):o[s]=n:void 0===o[s]&&r?o[s]=i?n:[n]:!c||void 0===o[s]||N(s,y.counts)||N(s,y.bools)?o[s]=n:o[s]=[o[s],n]}function N(e,t){const n=[].concat(y.aliases[e]||[],e),o=Object.keys(t),s=n.find(e=>o.includes(e));return!!s&&t[s]}function D(e){const t=Object.keys(y);return[].concat(t.map(e=>y[e])).some(function(t){return Array.isArray(t)?t.includes(e):t[e]})}function R(e){return a["unknown-options-as-args"]&&function(e){if(e=e.replace(/^-{3,}/,"--"),e.match(h))return!1;if(function(e){if(e.match(h)||!e.match(/^-[^-]+/))return!1;let t,n=!0;const o=e.slice(1).split("");for(let s=0;s<o.length;s++){if(t=e.slice(s+2),!D(o[s])){n=!1;break}if(o[s+1]&&"="===o[s+1]||"-"===t||/[A-Za-z]/.test(o[s])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(t)||o[s+1]&&o[s+1].match(/\W/))break}return n}(e))return!1;return!function(e,...t){return[].concat(...t).some(function(t){const n=e.match(t);return n&&D(n[1])})}(e,/^-+([^=]+?)=[\s\S]*$/,m,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}(e)}function P(e){return N(e,y.bools)||N(e,y.counts)||!(`${e}`in i)?(t=function(e){let t=C.BOOLEAN;return N(e,y.strings)?t=C.STRING:N(e,y.numbers)?t=C.NUMBER:N(e,y.bools)?t=C.BOOLEAN:N(e,y.arrays)&&(t=C.ARRAY),t}(e),{[C.BOOLEAN]:!0,[C.STRING]:"",[C.NUMBER]:void 0,[C.ARRAY]:[]}[t]):i[e];var t}function B(e){return void 0===e}return T($,!0),T($,!1),function(e){const t=Object.create(null);A(t,y.aliases,i),Object.keys(y.configs).forEach(function(n){const o=e[n]||t[n];if(o)try{let e=null;const t=z.resolve(z.cwd(),o),s=y.configs[n];if("function"==typeof s){try{e=s(t)}catch(t){e=t}if(e instanceof Error)return void(b=e)}else e=z.require(t);I(e)}catch(t){"PermissionDenied"===t.name?b=t:e[n]&&(b=Error(g("Invalid JSON config file: %s",o)))}})}($),void 0!==c&&c.forEach(function(e){I(e)}),A($,y.aliases,i,!0),function(e){let t;const n=new Set;Object.keys(e).forEach(function(o){if(!n.has(o)&&(t=N(o,y.coercions),"function"==typeof t))try{const s=S(o,t(e[o]));[].concat(y.aliases[o]||[],o).forEach(t=>{n.add(t),e[t]=s})}catch(e){b=e}})}($),a["set-placeholder-key"]&&function(e){y.keys.forEach(t=>{~t.indexOf(".")||void 0===e[t]&&(e[t]=void 0)})}($),Object.keys(y.counts).forEach(function(e){F($,e.split("."))||E(e,0)}),d&&w.length&&($[u]=[]),w.forEach(function(e){$[u].push(e)}),a["camel-case-expansion"]&&a["strip-dashed"]&&Object.keys($).filter(e=>"--"!==e&&e.includes("-")).forEach(e=>{delete $[e]}),a["strip-aliased"]&&[].concat(...Object.keys(r).map(e=>r[e])).forEach(e=>{a["camel-case-expansion"]&&e.includes("-")&&delete $[e.split(".").map(e=>L(e)).join(".")],delete $[e]}),{aliases:Object.assign({},y.aliases),argv:Object.assign(v,$),configuration:a,defaulted:Object.assign({},p),error:b,newAliases:Object.assign({},f)}}}({cwd:process.cwd,env:()=>W,format:f,normalize:c,resolve:i,require:e=>{if("undefined"!=typeof require)return require(e);if(e.match(/\.json$/))return JSON.parse(t(e,"utf8"));throw Error("only .json config files are supported in ESM")}});var Y={fs:{readFileSync:t,writeFile:n},format:f,resolve:i,exists:e=>{try{return o(e).isFile()}catch(e){return!1}}};let G;class Q{constructor(e){e=e||{},this.directory=e.directory||"./locales",this.updateFiles="boolean"!=typeof e.updateFiles||e.updateFiles,this.locale=e.locale||"en",this.fallbackToLanguage="boolean"!=typeof e.fallbackToLanguage||e.fallbackToLanguage,this.cache=Object.create(null),this.writeQueue=[]}__(...e){if("string"!=typeof arguments[0])return this._taggedLiteral(arguments[0],...arguments);const t=e.shift();let n=function(){};return"function"==typeof e[e.length-1]&&(n=e.pop()),n=n||function(){},this.cache[this.locale]||this._readLocaleFile(),!this.cache[this.locale][t]&&this.updateFiles?(this.cache[this.locale][t]=t,this._enqueueWrite({directory:this.directory,locale:this.locale,cb:n})):n(),G.format.apply(G.format,[this.cache[this.locale][t]||t].concat(e))}__n(){const e=Array.prototype.slice.call(arguments),t=e.shift(),n=e.shift(),o=e.shift();let s=function(){};"function"==typeof e[e.length-1]&&(s=e.pop()),this.cache[this.locale]||this._readLocaleFile();let r=1===o?t:n;if(this.cache[this.locale][t]){r=this.cache[this.locale][t][1===o?"one":"other"]}!this.cache[this.locale][t]&&this.updateFiles?(this.cache[this.locale][t]={one:t,other:n},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:s})):s();const a=[r];return~r.indexOf("%d")&&a.push(o),G.format.apply(G.format,a.concat(e))}setLocale(e){this.locale=e}getLocale(){return this.locale}updateLocale(e){this.cache[this.locale]||this._readLocaleFile();for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(this.cache[this.locale][t]=e[t])}_taggedLiteral(e,...t){let n="";return e.forEach(function(e,o){const s=t[o+1];n+=e,void 0!==s&&(n+="%s")}),this.__.apply(this,[n].concat([].slice.call(t,1)))}_enqueueWrite(e){this.writeQueue.push(e),1===this.writeQueue.length&&this._processWriteQueue()}_processWriteQueue(){const e=this,t=this.writeQueue[0],n=t.directory,o=t.locale,s=t.cb,r=this._resolveLocaleFile(n,o),a=JSON.stringify(this.cache[o],null,2);G.fs.writeFile(r,a,"utf-8",function(t){e.writeQueue.shift(),e.writeQueue.length>0&&e._processWriteQueue(),s(t)})}_readLocaleFile(){let e={};const t=this._resolveLocaleFile(this.directory,this.locale);try{G.fs.readFileSync&&(e=JSON.parse(G.fs.readFileSync(t,"utf-8")))}catch(n){if(n instanceof SyntaxError&&(n.message="syntax error in "+t),"ENOENT"!==n.code)throw n;e={}}this.cache[this.locale]=e}_resolveLocaleFile(e,t){let n=G.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf("_")){const o=G.resolve(e,"./",t.split("_")[0]+".json");this._fileExistsSync(o)&&(n=o)}return n}_fileExistsSync(e){return G.exists(e)}}let H;try{H=g(import.meta.url)}catch(e){H=process.cwd()}H.split("node_modules")[0]||process.cwd(),process.cwd,process.exit,process.nextTick,void 0!==process.stdout.columns&&process.stdout.columns,function(e,t){G=t;const n=new Q(e);n.__.bind(n),n.__n.bind(n),n.setLocale.bind(n),n.getLocale.bind(n),n.updateLocale.bind(n),n.locale}({directory:i(H,"../../../locales"),updateFiles:!1},Y);const Z={hg:{appName:"hotglue",clientApiBaseUri:process.env.HOTGLUE_CLIENT_API_BASE_URI||"https://api.hotglue.com",defaultConfigFileName:"config.yaml"}},X={},ee=()=>a.resolve(d(),`.${Z.hg.appName}`,Z.hg.defaultConfigFileName),te=async()=>{const{appName:e}=Z.hg;try{return await $(e).load(ee())||{}}catch(e){return{}}},ne=async()=>{const{appName:e}=Z.hg,t=$(e,{searchPlaces:[`${e}.yaml`,`.${e}.yaml`,`.${e}rc.yaml`,`.${e}rc.yml`,`.${e}rc`,`.${e}rc.json`,`.${e}rc.js`]});try{return await t.search()||{}}catch(e){throw console.log(e),new Error(`Malformed configuration file: ${e.message}`)}},oe={primary:e=>v.whiteBright(e),secondary:e=>v.white(e),info:e=>v.green(e),warn:e=>v.yellow(e),error:e=>v.redBright(e),success:e=>v.greenBright(e)};let se=oe,re="primary";function ae(e){return se={...oe,...e},fe}function ie(e){process.stdout.write(e)}const ce=(e,t=re)=>{if(!e)return"";if("string"==typeof e)return se[t]?se[t](e):se[re](e);const n=p(e,{colors:!0});return se[t]?se[t](n):n};function le(...e){return console.log(...e),fe}function de(e,t){return ie(ce(e,t)),ie("\n"),fe}function ue(e,t){return ie(ce(e,t)),fe}const fe={cl:le,pr:de,pp:ue,setTheme:ae,setDefault:function(e="primary"){return se[e]&&(re=e),fe}},pe=e=>{console.log(JSON.stringify(e))},ge=k("hotglue-cli");function ye(e){return ge.extend(e)}const he=ye("commands:config:set"),me="set <setting> <value>";var be=Object.freeze({__proto__:null,builder:async e=>(he("builder",me,e),e.option("setting",{describe:"The configuration parameter you wish to set",type:"string"}).option("value",{describe:"The configuration parameter's value",type:"string"}),e),command:me,desc:"Set configuration key-value pairs",handler:async e=>{he("handler",me,e);const{json:t,setting:n,value:o}=e;if(["apikey"].includes(n))try{const e=await te();e&&e.config?!t&&ue("Updating profile config file..."):!t&&ue("Creating profile config file...");const s=e&&e.config?{...e.config,[n]:o}:{[n]:o},r=_.stringify(s),i=e&&e.filepath?e.filepath:ee();await(async(e,t)=>{await y(a.dirname(e),{recursive:!0}),await h(e,t)})(i,r),t?pe({status:"success"}):ue("Done").pr()}catch(e){t?pe({status:"error",error:e}):console.log(e)}else t?pe({status:"error",error:"Invalid settings parameter"}):console.error("Invalid settings parameter")}});const we=[be],$e=ye("commands:config"),ve="config [action]";var je=Object.freeze({__proto__:null,builder:async function(e){return $e("builder",ve),e.command(we)},command:ve,desc:"Configure your hotglue CLI",handler:async function(e){$e("handler",ve,e);const{action:t}=e;if(!t)try{const e=await te();e.config&&0!==Object.keys(e.config).length||de("No profile configuration found. Run config set to configure the hotglue CLI.");const t=new E({head:["Setting","Value","Config File","Type"]});e.config&&Object.entries(e.config).forEach(([n,o])=>t.push([n,o,e.filepath,"Profile"]));const n=await ne();n.config&&Object.entries(n.config).forEach(([e,o])=>t.push([e,o,a.relative(process.cwd(),n.filepath),"Project"])),t.length>0&&console.log(t.toString())}catch(e){throw console.log(e),e}}}),ke={env:{config:{describe:"Environment Id",type:"string",alias:["e"]},demandText:'The "env" parameter (Environment Id) is required. Either pass here using `-e [env_id]` or add an env property in your rc file.'},apikey:{config:{describe:"API key",type:"string",alias:["k"]},demandText:"API key is required. Either pass here using -k [key] or configure your profile using config set."},dataFilePath:{config:{describe:"Singer data file path",type:"string",alias:["data","data-file-path"],default:"data.singer"}},json:{config:{describe:"Makes the output format to be JSON",type:"boolean",default:!1},demandText:""},tenant:{config:{describe:"Tenant (user) ID",type:"string",alias:["u"]},demandText:"TenantId is required. You can pass it using -u [tenantId]."},flow:{config:{describe:"Flow ID",type:"string",alias:["f"]},demandText:"FlowId is required. You can pass it using -f [flow_id]."},tap:{config:{describe:"Tap name",type:"string",alias:["t"]},demandText:"Tap name is required. You can pass it using -t <tap_name>."},connector:{config:{describe:"Connector ID",type:"string",alias:["c"]},demandText:"Connector ID is required. You can pass it using -c <connector>."},all:{config:{describe:"Run command for all taps/connectors",type:"boolean",default:!1,alias:["a"]},demandText:'This "all" flag is required. You can pass it using -a or --all.'},jobroot:{config:{describe:"Job Root (S3 prefix)",type:"string",alias:["j"]},demandText:"JobRoot key is required. You can pass it using -j [job_root]."},count:{config:{describe:"Max returned records",type:"number"}},downloadTo:{config:{describe:"Download folder",default:".",type:"string",alias:["d"]},demandText:"A destination folder is required. You can pass it using -d [folder] and can be either relative from cwd or absolute."},sourceFolder:{config:{describe:"Source folder",type:"string",default:".",alias:["s"]},demandText:""},configFilePath:{config:{describe:"Config file path",type:"string",default:"./config.json",alias:["p"]},demandText:'Local path of the config (with .json extension). Example: "/home/hotglue/config.json"'},overwrite:{config:{describe:"Overwrite existing",type:"boolean",default:!1,alias:["o"]},demandText:""},cleanup:{config:{describe:"Clean up target prior to action",type:"boolean",default:!1,alias:["c"]},demandText:""}};const _e=ye("base"),Ee=async e=>{_e("builder");const t=await(async()=>{const e=await te(),t=await ne();return{...X,...e.config,...t.config}})();return e.option("apikey",ke.apikey.config).option("env",ke.env.config).option("json",ke.json.config).config(t).demandOption(["env"],ke.env.demandText).demandOption(["apikey"],ke.apikey.demandText).strictCommands()},Oe=ye("utils.js"),xe=async(e,t,n=[])=>{const{includeSymLinks:o,recursive:s,filter:r}=t,{matcher:i}=r,c=a.resolve(e),l=await m(c,{withFileTypes:!0});for(const e of l){const r=a.resolve(c,e.name);e.isSymbolicLink()&&!o||(!i||i(r)?e.isFile()?n.push(a.resolve(c,e.name)):e.isDirectory()&&s&&await xe(a.resolve(c,e.name),t,n):Oe("skip",r))}return n},Se=async(e,t)=>{const n={includeSymLinks:!1,recursive:!1,filter:{},...t},{pattern:o}=n.filter;return o&&(n.filter.matcher=x.matcher(o,{dot:!0})),xe(e,n)},Ie=(e,t)=>{Oe("filter-in",e);const{pattern:n}={...t};let o=e;return n&&(o=x(o,n)),Oe("filter-out",o),o};const Te=e=>{const t=[];return new Promise((n,o)=>{e.on("error",o),e.on("data",e=>t.push(Buffer.from(e))),e.on("end",()=>n(Buffer.concat(t).toString("utf8")))})},Ae=(e,t=10)=>{const n=[];for(let o=0;o<e.length;o+=t){const s=e.slice(o,o+t);n.push(s)}return n},Fe=async({debug:e,baseUri:t,env:n,apiKey:o})=>{const s=new URL(`${t}/${n}/resetAvailableEntities`),{data:r}=await S.delete(s,{headers:{"x-api-key":o,"Content-type":"application/json"}});e({data:r})},Ue=async({debug:e,baseUri:t,task:n,env:o,apikey:s,...r})=>{const a=new URL(`${t}/credentials/${n}/${o}`);r&&Object.entries(r).forEach(([e,t])=>{a.searchParams.set(e,t)});const i=a.toString();e&&e("uri:",i);const{data:c}=await S.get(i,{headers:{"x-api-key":s}}),{accessKeyId:l,secretAccessKey:d,sessionToken:u}=c;return{accessKeyId:l,secretAccessKey:d,sessionToken:u}},Ne=async({debug:e,baseUri:t,env:n,apikey:o})=>{const s=`${t}/tenants/${n}`;e("requesting:",s);const{data:r}=await S.get(s,{headers:{"x-api-key":o}});return e("response-data",r),r},De=async({debug:e,baseUri:t,env:n,flow:o,apikey:s})=>{const r={"x-api-key":s},a=new URL(`${t}/${n}/${o}/supportedSources`).toString();e&&e("uri:",a);const{data:i}=await S.get(a,{headers:r});return i},Re=async({debug:e,baseUri:t,env:n,flow:o,apikey:s})=>{const r={"x-api-key":s},a=new URL(`${t}/v2/${n}/${o}/supportedConnectors`).toString();e&&e("uri:",a);const{data:i}=await S.get(a,{headers:r});return i},Pe=async({debug:e,baseUri:t,env:n,flow:o,tenant:s,apikey:r,config:a})=>{const i=new URL(`${t}/${n}/${o}/${s}/linkedSources`);a&&i.searchParams.set("config","true");const c={"x-api-key":r},l=i.toString();e&&e("uri:",l);const{data:d}=await S.get(l,{headers:c});return d},Ce=async({debug:e,baseUri:t,env:n,flow:o,tenant:s,apikey:r,config:a})=>{const i=new URL(`${t}/v2/${n}/${o}/${s}/linkedConnectors`);a&&i.searchParams.set("config","true");const c={"x-api-key":r},l=i.toString();e&&e("uri:",l);const{data:d}=await S.get(l,{headers:c});return d},Be=async({debug:e,baseUri:t,env:n,flow:o,tenant:s,apikey:r,connectorId:a,config:i})=>{const c={"x-api-key":r},l=new URL(`${t}/${n}/${o}/${s}/linkedSources`).toString(),d={tap:a,config:i};e&&e("uri:",l);const{data:u}=await S.patch(l,d,{headers:c});return u},Ke=async({debug:e,baseUri:t,env:n,flow:o,tenant:s,apikey:r,connectorId:a,config:i})=>{const c={"x-api-key":r},l=new URL(`${t}/v2/${n}/${o}/${s}/linkedConnectors`).toString(),d={connector_id:a,config:i};e&&e("uri:",l);const{data:u}=await S.patch(l,d,{headers:c});return u},Me=async({debug:e,baseUri:t,env:n,apikey:o})=>{const s={"x-api-key":o},r=new URL(`${t}/${n}/flows/supported`).toString();e&&e("uri:",r);const{data:a}=await S.get(r,{headers:s});return a},Le=async({debug:e,baseUri:t,env:n,flow:o,apikey:s})=>{const r={"x-api-key":s},a=new URL(`${t}/${n}/flows/${o}/supported`).toString();e&&e("uri:",a);const{data:i}=await S.get(a,{headers:r});return i},ze=async({debug:e,baseUri:t,env:n,apikey:o,from:s,to:r,count:a=1e4,...i})=>{const c={"x-api-key":o},l="string"==typeof a?parseInt(a,10):a;let d=[],u=0,f=1,p=!0;for(;p;){const o=new URL(`${t}/${n}/jobs`);o.searchParams.set("from",s),r&&o.searchParams.set("to",r),o.searchParams.set("count",l.toString()),o.searchParams.set("page",f.toString()),i&&Object.entries(i).forEach(([e,t])=>{null!=t&&"count"!==e&&"page"!==e&&o.searchParams.set(e,t)}),o.searchParams.set("include_export_details","false"),o.searchParams.set("skip_cache","true");const a=o.toString();e&&e(`Fetching page ${f}, uri:`,a);const{data:g}=await S.get(a,{headers:c});e&&e(`Page ${f} response:`,{jobsCount:g.jobs?.length||0,total:g.total||0});const y=g.jobs||[];d=d.concat(y),1===f&&(u=g.total||0),y.length<l?p=!1:f++}return e&&e(`Fetched ${d.length} jobs across ${f} page(s)`),{jobs:d,total:u}},Je=async({debug:e,baseUri:t,env:n,apikey:o,tenant:s,flow:r,...a})=>{const i={"x-api-key":o},c=new URL(`${t}/${n}/${r}/${s}/jobs/retrigger`).toString(),l=a;e&&e("uri:",c),e&&e("payload:",l);const{data:d}=await S.post(c,l,{headers:i});return d},qe=async({debug:e,baseUri:t,env:n,flow:o,user_id:s,apikey:r,schedule_expression:a,state:i,job_type:c,connector_id:l,extra_args:d})=>{const u={"x-api-key":r},f=new URL(`${t}/${n}/${o}/${s}/jobs/schedule`).toString(),p={schedule_expression:a,state:i};c&&(p.job_type=c),l&&(p.connector_id=l),d&&Object.assign(p,d),e&&e("uri:",f),e&&e("body:",p);const{data:g}=await S.put(f,p,{headers:u});return g},Ve=async({debug:e,baseUri:t,env:n,flow:o,user_id:s,apikey:r,job_root:a,include_export_details:i=!1})=>{const c=new URL(`${t}/${n}/${o}/${s}/jobs/status`);c.searchParams.set("job_root",a),c.searchParams.set("include_export_details",i?"true":"false");const l={"x-api-key":r},d=c.toString();e&&e("uri:",d);const{data:u}=await S.get(d,{headers:l});return u},We=k("commands:env:validators"),Ye=async(e,t,n,o,s)=>{if(!Array.isArray(e))throw new Error("availableSources.json must be an array of objects");const r=(await Promise.all(o.filter(e=>1==e.version).map(async e=>await De({debug:We,baseUri:t,env:s,flow:e.id,apikey:n})))).flat(),a=e.map(e=>{if(!e.tap)throw new Error(`Source ${JSON.stringify(e)} has no tap id`);return e.tap}),i=a.filter((e,t)=>a.indexOf(e)!==t);if(i.length>0)throw new Error(`Duplicate source id(s) found in availableSources.json: ${i.join(", ")}. All sources must have a unique tap id.`);const c=r.filter(e=>e.isForked&&!a.includes(e.tap));if(c.length>0)throw new Error(`Sources ${c.map(e=>e.label).join(", ")} are linked, but missing from your availableSources.json`)},Ge=async(e,t,n,o,s)=>{if(!Array.isArray(e))throw new Error("availableTargets.json must be an array of objects");const r=(await Promise.all(o.filter(e=>1==e.version).map(async e=>{const o=await(async({debug:e,baseUri:t,env:n,flow:o,apikey:s})=>{const r={"x-api-key":s},a=new URL(`${t}/${n}/${o}/supportedTargets`).toString();e&&e("uri:",a);const{data:i}=await S.get(a,{headers:r});return i})({debug:We,baseUri:t,env:s,flow:e.id,apikey:n});return o}))).flat(),a=e.map(e=>{if(!e.target)throw new Error(`Target ${JSON.stringify(e)} has no target id`);return e.target}),i=a.filter((e,t)=>a.indexOf(e)!==t);if(i.length>0)throw new Error(`Duplicate target id(s) found in availableTargets.json: ${i.join(", ")}. All targets must have a unique target id.`);const c=r.filter(e=>e.isForked&&!a.includes(e.target));if(c.length>0)throw new Error(`Targets ${c.map(e=>e.label).join(", ")} are linked, but missing from your availableTargets.json`)},Qe=async(e,t,n,o,s)=>{if(!Array.isArray(e))throw new Error("availableConnectors.json must be an array of objects");const r=(await Promise.all(o.filter(e=>2==e.version).map(async e=>await Re({debug:We,baseUri:t,env:s,flow:e.id,apikey:n})))).flat(),a=e.map(e=>{if(!e.id)throw new Error(`Connector ${JSON.stringify(e)} has no id`);return e.id}),i=a.filter((e,t)=>a.indexOf(e)!==t);if(i.length>0)throw new Error(`Duplicate connector id(s) found in availableConnectors.json: ${i.join(", ")}. All connectors must have a unique id.`);const c=r.filter(e=>e.isForked&&!a.includes(e.id));if(c.length>0)throw new Error(`Connectors ${c.map(e=>e.id).join(", ")} are linked, but missing from your availableConnectors.json`)},He=ye("commands:env:deploy"),Ze="deploy";var Xe=Object.freeze({__proto__:null,builder:async e=>(He("builder",Ze),e.option("sourceFolder",ke.sourceFolder.config).demandOption("sourceFolder",ke.sourceFolder.demandText)),command:Ze,desc:"Deploy Environment settings",handler:async e=>{He("handler",Ze,e);const{hg:t,json:n,apikey:o,env:s,sourceFolder:r}=e,{clientApiBaseUri:i}=t,c=a.resolve(process.cwd(),r);let l,d=O();try{l=ce(`Scanning ${ce(c,"info")} for deployable files`),!n&&d.start(ce(`In progress: ${l}...`,"secondary"));const e=await Se(c,{filter:{pattern:"((**/requirements.txt)|(**/availableSources.json)|(**/availableTargets.json)|(**/availableConnectors.json)|(**/customTaps.json))"}});if(0===e.length)return void(n?pe({status:"error",error:"There are no files to deploy at the specified location!"}):(d.fail(ce(`Error: ${l}.`,"secondary")),de(ce(`Message: ${ce("There are no files to deploy at the specified location!")}`,"secondary"))));!n&&d.succeed(ce(`Finished: ${l}.`,"secondary"));for(const t of e)if(t.endsWith(".json"))try{const e=await b(t,{encoding:"utf-8"});JSON.parse(e)}catch(e){throw new Error(`File ${t} is not a valid JSON: ${String(e)}`)}const t=await Me({debug:He,baseUri:i,env:s,apikey:o});for(const n of e){if(n.endsWith("availableSources.json")){const e=JSON.parse(await b(n,{encoding:"utf-8"}));await Ye(e,i,o,t,s)}if(n.endsWith("availableTargets.json")){const e=JSON.parse(await b(n,{encoding:"utf-8"}));await Ge(e,i,o,t,s)}if(n.endsWith("availableConnectors.json")){const e=JSON.parse(await b(n,{encoding:"utf-8"}));await Qe(e,i,o,t,s)}}l=ce("Verifying user and authorizing"),!n&&d.start(ce(`In progress: ${l}...`,"secondary"));const{accessKeyId:r,secretAccessKey:u,sessionToken:f}=await Ue({debug:He,baseUri:i,task:"env-deploy",env:s,apikey:o});!n&&d.succeed(ce(`Finished: ${l}.`,"secondary"));const p=new j.S3({accessKeyId:r,secretAccessKey:u,sessionToken:f});l=ce("Deploying environment files"),!n&&d.info(ce(`Info: ${l}.`,"secondary"));const g="config/",y=new E({head:["File","Status"]});for await(const t of e){const e=a.basename(t);l=ce(`Pushing file: ${ce(e,"info")}`),!n&&d.start(ce(`In progress: ${l}...`,"secondary"));const r={Bucket:s,Key:`${g}${e}`,Body:await b(t)},c=await p.putObject(r).promise();!n&&d.succeed(ce(`Finished: ${l}.`,"secondary")),He("s3-put-res",c),y.push([e,"Deployed"]),await Fe({debug:He,baseUri:i,env:s,apiKey:o})}n?pe({status:"success",deployedFiles:e}):le(y.toString())}catch(e){!n&&d.fail(ce(`Error: ${l}.`,"secondary")),de(ce(`Message: ${ce(e.message)}`,"secondary")),He(e),e&&e.response&&e.response.data&&He("response",e.response.data),process.exit(1)}}});const et=ye("commands:env:download"),tt="download";var nt=Object.freeze({__proto__:null,builder:async e=>(et("builder",tt),e.option("downloadTo",ke.downloadTo.config)),command:tt,desc:"Download Environment settings",handler:async e=>{et("handler",tt,e);const{hg:t,json:n,apikey:o,env:s,downloadTo:r}=e,{clientApiBaseUri:i}=t,c=a.resolve(process.cwd(),r);let l,d=O();try{l=ce("Verifying user and authorizing"),!n&&d.start(ce(`In progress: ${l}...`,"secondary"));const{accessKeyId:e,secretAccessKey:t,sessionToken:r}=await Ue({debug:et,baseUri:i,task:"env-download",env:s,apikey:o});!n&&d.succeed(ce(`Finished: ${l}.`,"secondary"));const u=new j.S3({accessKeyId:e,secretAccessKey:t,sessionToken:r});l=ce(`Scanning environment ${ce(s,"info")}`),!n&&d.start(ce(`In progress: ${l}...`,"secondary"));const f={Bucket:s,Prefix:"config/"},{Contents:p}=await u.listObjectsV2(f).promise();!n&&d.succeed(ce(`Finished: ${l}.`,"secondary")),et("s3-files",p);const g=p?Ie(p.map(e=>e.Key),{pattern:"((*/requirements.txt)|(*/availableSources.json)|(*/availableTargets.json)|(*/availableConnectors.json)|(*/customTaps.json))"}):[];if(!g||0===g.length)return void(n?pe({status:"success",downloadedFiles:[]}):d.warn(ce(`Warning: ${ce("Nothing to download!")}`,"secondary")));l=ce(`Downloading to ${ce(c,"info")}`),!n&&d.info(ce(`Info: ${l}.`,"secondary"));const m=new E({head:["File","Status"]});for await(const e of g){const t=a.basename(e),o=a.resolve(c,t);et("local-file",o),await y(a.dirname(o),{recursive:!0}),l=ce(`Downloading file: ${ce(t,"info")}`),!n&&d.start(ce(`In progress: ${l}...`,"secondary"));const r=u.getObject({Bucket:s,Key:e}).createReadStream();await h(o,await Te(r)),!n&&d.succeed(ce(`Finished: ${l}.`,"secondary")),m.push([t,"Downloaded"])}n?pe({status:"success",downloadedFiles:g}):le(m.toString())}catch(e){n?pe({status:"error",error:e}):(d.fail(ce(`Error: ${l}.`,"secondary")),de(ce(`Message: ${ce(e.message)}`,"secondary")),et(e),e&&e.response&&e.response.data&&et("response",e.response.data)),process.exit(1)}}});const ot=[Xe,nt],st=ye("commands:env"),rt="env <action>";var at=Object.freeze({__proto__:null,builder:async function(e){st("builder",rt);return(await Ee(e)).command(ot)},command:rt,desc:"Manage environment settings",handler:async function(e){st("handler",rt,e)}});const it=async(e,t,n,o)=>{try{const s=e.getObject({Bucket:t,Key:`${n}/flows/${o}/flow.json`}).createReadStream(),r=await Te(s);return 2===JSON.parse(r).version}catch(e){return!1}},ct=async(e,t,n,o,s=void 0)=>s??await it(e,t,n,o)?"connectors":"taps",lt=ye("commands:etl:delete"),dt="delete";var ut=Object.freeze({__proto__:null,builder:async e=>(lt("builder",dt),e.option("flow",ke.flow.config).demandOption("flow",ke.flow.demandText).option("tap",ke.tap.config).demandOption("tap",ke.tap.demandText).option("tenant",{...ke.tenant.config}).demandOption("tenant",ke.tenant.demandText)),command:dt,desc:"Delete ETL scripts",handler:async e=>{lt("handler",dt,e);const{hg:t,json:n,apikey:o,env:s,flow:r,tap:a,tenant:i}=e,{clientApiBaseUri:c}=t;let l,d=O();try{l=ce(`Deleting ETL scripts for Tenant ${ce(i,"info")} Flow ${ce(r,"info")} and Tap ${ce(a,"info")} to ${ce(s,"info")}`),!n&&d.info(ce(`Info: ${l}.`,"secondary")),l=ce("Verifying user and authorizing"),!n&&d.start(ce(`In progress: ${l}...`,"secondary"));const{accessKeyId:e,secretAccessKey:t,sessionToken:u}=await Ue({debug:lt,baseUri:c,task:"etl-deploy",env:s,tenant:i,flow:r,tap:a,apikey:o}),f=new j.S3({accessKeyId:e,secretAccessKey:t,sessionToken:u});!n&&d.succeed(ce(`Finished: ${l}.`,"secondary")),l=ce("Deleting ETL scripts"),!n&&d.start(ce(`In progress: ${l}...`,"secondary"));const p=`${i}/flows/${r}/${await ct(f,s,i,r)}/${a}/etl/`,g=await f.listObjectsV2({Bucket:s,Prefix:p}).promise();if(lt("s3-list-objects-res",g),g.Contents?.length>0){const e=await f.deleteObjects({Bucket:s,Delete:{Objects:g.Contents.map(e=>({Key:e.Key}))}}).promise();lt("s3-list-objects-res",e)}const y=await f.deleteObject({Bucket:s,Key:p}).promise();if(lt("s3-delete-object-res",y),!n&&d.succeed(ce(`Finished: ${l}.`,"secondary")),g.Contents?.length>0){const e=new E({head:["File","Status"]});g.Contents.filter(({Key:e})=>e!==p).forEach(({Key:t})=>{const n=t.split("/"),o=n[n.length-1];e.push([o,ce("Deleted","info")])}),n?pe({status:"success",deletedObjects:(g.Contents??[]).map(({Key:e})=>e)}):le(e.toString())}else l=ce("There was no file or folder to be deleted"),n?pe({status:"success",deletedObjects:[]}):d.info(ce(`Info: ${l}.`,"secondary"))}catch(e){n?pe({status:"error",error:e}):(d.fail(ce(`Error: ${l}.`,"secondary")),de(ce(`Message: ${ce(e.message)}`,"secondary")),lt(e),e&&e.response&&e.response.data&<("response",e.response.data)),process.exit(1)}}});const ft=ye("commands:etl:deploy"),pt="deploy";var gt=Object.freeze({__proto__:null,builder:async e=>(ft("builder",pt),e.option("flow",ke.flow.config).demandOption("flow",ke.flow.demandText).option("tap",ke.tap.config).option("all",ke.all.config).option("tenant",{...ke.tenant.config,default:"default"}).option("sourceFolder",ke.sourceFolder.config).demandOption("sourceFolder",ke.sourceFolder.demandText)),command:pt,desc:"Deploy ETL scripts",handler:async e=>{ft("handler",pt,e);const{hg:t,json:n,apikey:o,env:s,flow:r,tap:i,all:c,tenant:l,sourceFolder:d}=e,{clientApiBaseUri:u}=t;if(!c&&!i)throw new Error(`${ke.tap.demandText} Or you can pass the --all flag to run this command for all taps/connectors.`);let f,p=O();const g=a.resolve(process.cwd(),d);try{f=ce(`Deploying script for Tenant ${ce(l,"info")} Flow ${ce(r,"info")}${i?` and Tap ${ce(i,"info")}`:""} to ${ce(s,"info")}`),!n&&p.info(ce(`Info: ${f}.`,"secondary"));const e=await Se(g,{recursive:!0,filter:{pattern:"!((**/sync-output)|(**/etl-output)|(**/snapshots))"}});if(0===e.length)return void(n?pe({status:"error",error:"There are no files to deploy at the specified location!"}):p.fail(ce(`Error: ${ce("There are no files to deploy at the specified location!")}.`,"secondary")));(e=>{const t=["config.json","source-config.json","target-config.json","catalog.json","target-catalog.json","state.json"],n=["sync-output","snapshots","etl-output",".venv"];for(const o of e){if(t.includes(o))throw new Error(`File ${o} is a reserved file name and cannot be used in the ETL script.`);const e=n.find(e=>o.startsWith(`${e}/`));if(e)throw new Error(`Directory ${e} is a reserved directory name and cannot be used in the ETL script.`)}})(e.map(e=>a.relative(d,e))),f=ce("Verifying user and authorizing"),!n&&p.start(ce(`In progress: ${f}...`,"secondary"));const t={debug:ft,baseUri:u,task:"etl-deploy",env:s,tenant:l,flow:r,apikey:o};i&&(t.tap=i);const{accessKeyId:c,secretAccessKey:y,sessionToken:h}=await Ue(t);!n&&p.succeed(ce(`Finished: ${f}.`,"secondary"));const m=new j.S3({accessKeyId:c,secretAccessKey:y,sessionToken:h}),w=await it(m,s,l,r);f=ce("Validating flow and tap location"),!n&&p.start(ce(`In progress: ${f}...`,"secondary"));const $=(await Me({debug:ft,baseUri:u,apikey:o,env:s})).find(({id:e})=>e===r);let v=[];try{if("default"===l||$?.type){if(v=((w?await Re({debug:ft,baseUri:u,env:s,flow:r,apikey:o}):await De({debug:ft,baseUri:u,env:s,flow:r,apikey:o}))??[]).filter(e=>!i||e[w?"id":"tap"]===i),i&&0===v.length)throw new Error("Tap is not supported")}else{if(v=((w?await Ce({debug:ft,baseUri:u,env:s,flow:r,tenant:l,apikey:o}):await Pe({debug:ft,baseUri:u,env:s,flow:r,tenant:l,apikey:o}))??[]).filter(e=>!i||e[w?"id":"tap"]===i),i&&0===v.length)throw new Error("Tap is not linked")}}catch(e){throw ft("err",e),new Error("Target location doesn't exist. Check your tenant, flow and tap arguments.")}!n&&p.succeed(ce(`Finished: ${f}.`,"secondary"));const k=new E({head:["File","Status"]});for(const t of v){const o=t[w?"id":"tap"];f=ce(`Preparing ${o} deployment target`),!n&&p.start(ce(`In progress: ${f}...`,"secondary"));const i=`${l}/flows/${r}/${await ct(null,null,null,null,w)}/${o}/etl/`,{Contents:c}=await m.listObjectsV2({Bucket:s,Prefix:`${i}`}).promise();!n&&p.succeed(ce(`Finished: ${f}.`,"secondary")),ft("contents",c);const u=c.map(e=>({Key:e.Key}));if(u.length>0){f=ce(`Removing old ${o} ETL files`),!n&&p.start(ce(`In progress: ${f}...`,"secondary"));const e={Bucket:s,Delete:{Objects:u,Quiet:!0}};await m.deleteObjects(e).promise(),u.forEach(({Key:e})=>k.push([`${o}/${e.substring(i.length)}`,ce("Deleted","warn")])),!n&&p.succeed(ce(`Finished: ${f}.`,"secondary"))}for await(const t of e){const e="win32"===process.platform?a.relative(d,t).replace(/\\/g,"/"):a.relative(d,t),r=`${i}${e}`;f=ce(`Deploying file: ${ce(`${o}/${e}`,"info")}`),!n&&p.start(ce(`In progress: ${f}...`,"secondary"));const c={Bucket:s,Key:r,Body:await b(t)},l=await m.putObject(c).promise();!n&&p.succeed(ce(`Finished: ${f}.`,"secondary")),ft("s3-put-res",l),k.push([`${o}/${e}`,ce("Deployed","info")])}}n?pe({status:"success",deployedFiles:e}):le(k.toString())}catch(e){n?pe({status:"error",error:e}):(p.fail(ce(`Error: ${f}.`,"secondary")),de(ce(`Message: ${ce(e.message)}`,"secondary")),ft(e),e&&e.response&&e.response.data&&ft("response",e.response.data)),process.exit(1)}}});const yt=ye("commands:etl:download"),ht="download";var mt=Object.freeze({__proto__:null,builder:async e=>(yt("builder",ht),e.option("flow",ke.flow.config).demandOption("flow",ke.flow.demandText).option("tap",ke.tap.config).demandOption("tap",ke.tap.demandText).option("downloadTo",ke.downloadTo.config).demandOption("downloadTo",ke.downloadTo.demandText).option("tenant",{...ke.tenant.config,default:"default"}).option("overwrite",ke.overwrite.config).demandOption("overwrite",ke.overwrite.demandText)),command:ht,desc:"Download ETL scripts",handler:async e=>{yt("handler",ht,e);const{hg:t,json:n,apikey:o,env:r,flow:i,tap:c,tenant:l,downloadTo:d,overwrite:u}=e,{clientApiBaseUri:f}=t;let p,g=O();const m=a.resolve(process.cwd(),d);try{p=ce("Verifying user and authorizing"),!n&&g.start(ce(`In progress: ${p}...`,"secondary"));const{accessKeyId:e,secretAccessKey:t,sessionToken:d}=await Ue({debug:yt,baseUri:f,task:"etl-download",env:r,tenant:l,flow:i,tap:c,apikey:o}),b=new j.S3({accessKeyId:e,secretAccessKey:t,sessionToken:d});!n&&g.succeed(ce(`Finished: ${p}.`,"secondary")),p=ce("Scanning for downloadable files"),!n&&g.start(ce(`In progress: ${p}...`,"secondary"));const $=`${l}/flows/${i}/${await ct(b,r,l,i)}/${c}/etl/`,v={Bucket:r,Prefix:$},{Contents:k}=await b.listObjectsV2(v).promise();!n&&g.succeed(ce(`Finished: ${p}.`,"secondary")),yt("s3-list-res",k);const _=k?Ie(k.map(e=>e.Key),{pattern:"!(.ipynb_checkpoints/*)"}):[];if(!_||0===_.length)return void(n?pe({status:"success",downloadedFiles:[]}):g.warn(ce(`Warning: ${ce("Nothing to download!")}`,"secondary")));p=ce(`Downloading script files to ${ce(m,"info")}`),!n&&g.info(ce(`Info: ${p}.`,"secondary"));const O=new E({head:["File","Status"]});for await(const e of _){const t=e.substring($.length),o=a.resolve(m,t);if(yt("file",o),e.endsWith("/")){!s(o)&&await y(o,{recursive:!0});continue}if(!u)try{await w(o),yt("exists, skipping"),O.push([t,"Skipped"]);continue}catch(e){"ENOENT"!==e.code&&le(e)}p=ce(`Downloading file: ${ce(t,"info")}`),!n&&g.start(ce(`In progress: ${p}...`,"secondary")),await y(a.dirname(o),{recursive:!0});const i=b.getObject({Bucket:r,Key:e}).createReadStream();await h(o,await Te(i)),!n&&g.succeed(ce(`Finished: ${p}.`,"secondary")),O.push([t,"Downloaded"])}n?pe({status:"success",downloadedFiles:_}):le(O.toString())}catch(e){n?pe({status:"error",error:e}):(g.fail(ce(`Error: ${p}.`,"secondary")),de(ce(`Message: ${ce(e.message)}`,"secondary")),yt(e),e&&e.response&&e.response.data&&yt("response",e.response.data)),process.exit(1)}}});const bt=[ut,gt,mt],wt=ye("commands:etl"),$t="etl <action>";var vt=Object.freeze({__proto__:null,builder:async function(e){wt("builder",$t);return(await Ee(e)).command(bt)},command:$t,desc:"Manage ETL scripts",handler:async function(e){wt("handler",$t,e)}});const jt=ye("commands:flows:list"),kt="list";var _t=Object.freeze({__proto__:null,builder:async e=>(jt("builder",kt),e.option("tenant",{...ke.tenant.config})),command:kt,desc:"List flows",handler:async e=>{jt("handler",kt,e);const{hg:t,json:n,apikey:o,env:s,tenant:r}=e,{clientApiBaseUri:a}=t;let i,c=O();try{i=ce(`Retrieving ${r?`${ce(r,"info")} tenant's`:"the"} flows for environment: ${ce(s,"info")}`);const e=`${a}/${s}/flows/${r?`linked?user_id=${r}`:"supported"}`;jt("requesting:",e),!n&&c.start(ce(`In progress: ${i}...`,"secondary"));const{data:t}=await S.get(e,{headers:{"x-api-key":o}});if(!n&&c.succeed(ce(`Finished: ${i}.`,"secondary")),jt("response-data",t),!t||0===t.length)return void(n?pe([]):c.warn(ce(`Warning: ${ce("No flows for specified environment and tenant")}.`,"secondary")));if(n)pe(t);else{const e=new E({head:["ID","Name","Flow Type","Taps","Targets","Connectors"]});t.sort((e,t)=>(e.name||"").localeCompare(t.name||"")),t.forEach(t=>{return e.push([t.id,t.name||"",2==t.