@getjusto/team-cli 0.0.1 → 0.0.3

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.
Files changed (2) hide show
  1. package/bin/cli.js +616 -70
  2. package/package.json +1 -1
package/bin/cli.js CHANGED
@@ -1,41 +1,424 @@
1
1
  #!/usr/bin/env node
2
- var yg={main:{local:"http://localhost:3000",develop:"https://api.bejusto.com",prod:"https://api.getjusto.com"},auth:{local:"http://localhost:4112",develop:"https://auth.service.bejusto.com",prod:"https://auth.service.getjusto.com"},webdata:{local:"http://localhost:4125",develop:"https://webdata.service.bejusto.com",prod:"https://webdatacdn.getjusto.com"},preferences:{local:"http://localhost:4120",develop:"https://preferences.service.bejusto.com",prod:"https://preferences.service.getjusto.com"},buckets:{local:"http://localhost:4106",develop:"https://buckets.service.bejusto.com",prod:"https://buckets.service.getjusto.com"},reservations:{local:"http://localhost:4113",develop:"https://reservations.service.bejusto.com",prod:"https://reservations.service.getjusto.com"},data:{local:"http://localhost:4107",develop:"https://data.service.bejusto.com",prod:"https://data.service.getjusto.com"},finances:{local:"http://localhost:4105",develop:"https://finances.service.bejusto.com",prod:"https://finances.service.getjusto.com"},"url-shortener":{local:"http://localhost:4102",develop:"https://url-shortener.service.bejusto.com",prod:"https://url-shortener.service.getjusto.com"},files:{local:"http://localhost:4108",develop:"https://files.service.bejusto.com",prod:"https://files.service.getjusto.com"},tabs:{local:"http://localhost:4115",develop:"https://tabs.service.bejusto.com",prod:"https://tabs.service.getjusto.com"},commander:{local:"http://localhost:4109",develop:"https://commander.service.bejusto.com",prod:"https://commander.service.getjusto.com"},experiments:{local:"http://localhost:4114",develop:"https://experiments.service.bejusto.com",prod:"https://experiments.service.getjusto.com"},sales:{local:"http://localhost:4117",develop:"https://sales.service.bejusto.com",prod:"https://sales.service.getjusto.com"},delivery:{local:"http://localhost:3410",develop:"https://api-delivery.bejusto.com",prod:"https://api-delivery-2.getjusto.com"},payments:{local:"http://localhost:4118",develop:"https://payments.service.bejusto.com",prod:"https://payments.service.getjusto.com"},addresses:{local:"http://localhost:4051",develop:"https://addresses.service.bejusto.com",prod:"https://addresses.service.getjusto.com"},royalty:{local:"http://localhost:4121",develop:"https://royalty.service.bejusto.com",prod:"https://royalty.service.getjusto.com"},marketing:{local:"http://localhost:4005",develop:"https://marketing.service.bejusto.com",prod:"https://marketing.service.getjusto.com"},api:{local:"http://localhost:4119",develop:"https://api.service.bejusto.com",prod:"https://api.service.getjusto.com"},messenger:{local:"http://localhost:4122",develop:"https://messenger.service.bejusto.com",prod:"https://messenger.service.getjusto.com"},invoice:{local:"http://localhost:4123",develop:"https://invoice.service.bejusto.com",prod:"https://invoice.service.getjusto.com"},"drivers-server":{local:"http://localhost:3410",develop:"https://api-delivery.bejusto.com",prod:"https://api-delivery-2.getjusto.com"}},h="prod";function mg(g){h=g}function qg(){return h}function s(g){return yg[g][h]}function $g(g){let m=[],q={},$={};for(let j=0;j<g.length;j++)if(g[j].startsWith("--")&&g[j+1]&&!g[j+1].startsWith("--")){let C=g[j].slice(2);if(q[C]=g[j+1],!$[C])$[C]=[];$[C].push(g[j+1]),j++}else if(g[j].startsWith("--"))q[g[j].slice(2)]="true";else m.push(g[j]);return{positional:m,flags:q,arrayFlags:$}}function H(g,m){let q=g[m];if(!q)console.error(`Error: --${m} es requerido.`),process.exit(1);return q}import{existsSync as i,mkdirSync as Kg,readFileSync as xg,writeFileSync as kg,unlinkSync as Vg}from"node:fs";import{join as jg}from"node:path";import{homedir as rg}from"node:os";var o=jg(rg(),".justo-team");function l(){let g=qg(),m=g==="prod"?"credentials.json":`credentials.${g}.json`;return jg(o,m)}function Dg(){if(!i(o))Kg(o,{recursive:!0})}function K(g){Dg(),kg(l(),JSON.stringify(g,null,2))}function f(){let g=l();if(!i(g))return null;try{let m=xg(g,"utf-8");return JSON.parse(m)}catch{return null}}function d(){let g=l();if(i(g))Vg(g)}import{existsSync as Cg,readFileSync as vg,writeFileSync as Lg,mkdirSync as hg}from"node:fs";import{join as Gg}from"node:path";import{homedir as sg}from"node:os";function og(){let g=Gg(sg(),".justo-team"),m=Gg(g,"device-id");if(Cg(m))return vg(m,"utf-8").trim();let q=crypto.randomUUID();if(!Cg(g))hg(g,{recursive:!0});return Lg(m,q),q}var Qg={required:({label:g})=>`${g} no es opcional`,notAString:({label:g})=>`${g} no es un texto`,notANumber:({label:g})=>`${g} no es un número`,notAnInteger:({label:g})=>`${g} no es un número entero`,notABoolean:({label:g})=>`${g} no es un valor verdadero o falso`,notAnEmail:({label:g})=>`${g} no es un email`,notAnId:({label:g})=>`${g} no es un ID válido`,notADate:({label:g})=>`${g} no es una fecha válida`,notAnArray:({label:g})=>`${g} no es un arreglo`,notAnObject:({label:g})=>`${g} no es un objeto`,stringTooShort:({label:g})=>`${g} no tiene el largo suficiente`,stringTooLong:"El largo es mayor al permitido",numberTooSmall:({label:g})=>`${g} es un número muy pequeño`,numberTooBig:({label:g})=>`${g} es un número muy grande`,notInSchema:({label:g})=>`${g} no esta permitido`,notUnique:({label:g})=>`${g} no es único`,notFound:({label:g})=>`${g} no se encontró`,invalid:"No es válido",rateLimitExceeded:"Has excedido el límite de intentos. Intenta de nuevo más tarde.",incorrectLoginCode:"El código es incorrecto",loginCodeExpired:"El código expiró. Solicita un nuevo",loginCodeLocked:"El código se bloqueó. Genera un nuevo código para continuar",userNotFound:"No existe una cuenta con este email"};function ig(g,m){let q=Qg[g];if(!q)return`${m}: ${g}`;if(typeof q==="function")return q({label:m});return q}function Rg(g){return Object.entries(g).map(([m,q])=>ig(q,m)).join(", ")}function lg(g){if(g.error==="validationError"&&g.validationErrors)return Rg(g.validationErrors);if(g.extensions?.code==="PermissionsError"){let j=g.extensions.info?.type;if(j?.includes("User doesn't have permissions for "))return`Tu usuario no tiene permisos para [${j.split("User doesn't have permissions for ")[1]}]`;return g.message}if(g.validationErrors)return`${g.message} (${Rg(g.validationErrors)})`;let m=g.message||"Error desconocido",q=Qg[m];if(q)return typeof q==="function"?q({label:""}).trim():q;let $=g.error||g.code||g.type;return $?`${m} [${$}]`:m}function dg(g){try{return JSON.parse(Buffer.from(g.split(".")[1],"base64").toString()).exp*1000<Date.now()}catch{return!0}}async function pg(){let g=f();if(!g?.refreshToken)return null;let m=`${s("auth")}/refresh-token`,$=await(await fetch(m,{method:"POST",headers:{"X-ORION-REFRESH":g.refreshToken}})).json();if(!$.token)return null;return K({...g,token:$.token}),$.token}async function ug(){let g=f();if(!g?.token)return;if(!dg(g.token))return g.token;return await pg()??void 0}async function N(g){let m=`${s(g.service)}/graphql`,q=await ug(),$={"Content-Type":"application/json","X-ORION-DEVICEID":og(),"X-ORION-PLATFORM":"web"};if(q)$["x-orion-jwt"]=q;let j;try{j=await fetch(m,{method:"POST",headers:$,body:JSON.stringify({query:g.query,variables:g.variables}),signal:AbortSignal.timeout(15000)})}catch{throw Error("La solicitud tardó demasiado. Intenta de nuevo.")}let C=await j.json();if(C.errors?.length)throw Error(lg(C.errors[0]));if(!C.data)throw Error("No data returned from server");return C.data}import{createInterface as ag}from"node:readline";function p(g){let m=ag({input:process.stdin,output:process.stdout});return new Promise((q)=>{m.question(g,($)=>{m.close(),q($.trim())})})}async function wg(g){return(await N({service:"auth",query:`mutation ($email: String!) {
2
+ var Y={main:{local:"http://localhost:3000",develop:"https://api.bejusto.com",prod:"https://api.getjusto.com"},auth:{local:"http://localhost:4112",develop:"https://auth.service.bejusto.com",prod:"https://auth.service.getjusto.com"},webdata:{local:"http://localhost:4125",develop:"https://webdata.service.bejusto.com",prod:"https://webdatacdn.getjusto.com"},preferences:{local:"http://localhost:4120",develop:"https://preferences.service.bejusto.com",prod:"https://preferences.service.getjusto.com"},buckets:{local:"http://localhost:4106",develop:"https://buckets.service.bejusto.com",prod:"https://buckets.service.getjusto.com"},reservations:{local:"http://localhost:4113",develop:"https://reservations.service.bejusto.com",prod:"https://reservations.service.getjusto.com"},data:{local:"http://localhost:4107",develop:"https://data.service.bejusto.com",prod:"https://data.service.getjusto.com"},finances:{local:"http://localhost:4105",develop:"https://finances.service.bejusto.com",prod:"https://finances.service.getjusto.com"},"url-shortener":{local:"http://localhost:4102",develop:"https://url-shortener.service.bejusto.com",prod:"https://url-shortener.service.getjusto.com"},files:{local:"http://localhost:4108",develop:"https://files.service.bejusto.com",prod:"https://files.service.getjusto.com"},tabs:{local:"http://localhost:4115",develop:"https://tabs.service.bejusto.com",prod:"https://tabs.service.getjusto.com"},commander:{local:"http://localhost:4109",develop:"https://commander.service.bejusto.com",prod:"https://commander.service.getjusto.com"},experiments:{local:"http://localhost:4114",develop:"https://experiments.service.bejusto.com",prod:"https://experiments.service.getjusto.com"},sales:{local:"http://localhost:4117",develop:"https://sales.service.bejusto.com",prod:"https://sales.service.getjusto.com"},delivery:{local:"http://localhost:3410",develop:"https://api-delivery.bejusto.com",prod:"https://api-delivery-2.getjusto.com"},payments:{local:"http://localhost:4118",develop:"https://payments.service.bejusto.com",prod:"https://payments.service.getjusto.com"},addresses:{local:"http://localhost:4051",develop:"https://addresses.service.bejusto.com",prod:"https://addresses.service.getjusto.com"},royalty:{local:"http://localhost:4121",develop:"https://royalty.service.bejusto.com",prod:"https://royalty.service.getjusto.com"},marketing:{local:"http://localhost:4005",develop:"https://marketing.service.bejusto.com",prod:"https://marketing.service.getjusto.com"},api:{local:"http://localhost:4119",develop:"https://api.service.bejusto.com",prod:"https://api.service.getjusto.com"},messenger:{local:"http://localhost:4122",develop:"https://messenger.service.bejusto.com",prod:"https://messenger.service.getjusto.com"},invoice:{local:"http://localhost:4123",develop:"https://invoice.service.bejusto.com",prod:"https://invoice.service.getjusto.com"},"drivers-server":{local:"http://localhost:3410",develop:"https://api-delivery.bejusto.com",prod:"https://api-delivery-2.getjusto.com"}},L="prod";function lo(o){L=o}function po(){return L}function G(o){return Y[o][L]}function wo(o){let i=[],t={},r={};for(let e=0;e<o.length;e++)if(o[e].startsWith("--")&&o[e+1]&&!o[e+1].startsWith("--")){let s=o[e].slice(2);if(t[s]=o[e+1],!r[s])r[s]=[];r[s].push(o[e+1]),e++}else if(o[e].startsWith("--"))t[o[e].slice(2)]="true";else i.push(o[e]);return{positional:i,flags:t,arrayFlags:r}}function J(o,i){let t=o[i];if(!t)throw Error(`--${i} es requerido.`);return t}import{existsSync as io,mkdirSync as fi,readFileSync as bi,writeFileSync as qi,unlinkSync as Ci}from"node:fs";import{join as fo}from"node:path";import{homedir as $i}from"node:os";var oo=fo($i(),".justo-team");function to(){let o=po(),i=o==="prod"?"credentials.json":`credentials.${o}.json`;return fo(oo,i)}function Ii(){if(!io(oo))fi(oo,{recursive:!0})}function Z(o){Ii(),qi(to(),JSON.stringify(o,null,2))}function d(){let o=to();if(!io(o))return null;try{let i=bi(o,"utf-8");return JSON.parse(i)}catch{return null}}function ro(){let o=to();if(io(o))Ci(o)}import{existsSync as bo,readFileSync as ji,writeFileSync as yi,mkdirSync as hi}from"node:fs";import{join as qo}from"node:path";import{homedir as Ri}from"node:os";function Ui(){let o=qo(Ri(),".justo-team"),i=qo(o,"device-id");if(bo(i))return ji(i,"utf-8").trim();let t=crypto.randomUUID();if(!bo(o))hi(o,{recursive:!0});return yi(i,t),t}var $o={required:({label:o})=>`${o} no es opcional`,notAString:({label:o})=>`${o} no es un texto`,notANumber:({label:o})=>`${o} no es un número`,notAnInteger:({label:o})=>`${o} no es un número entero`,notABoolean:({label:o})=>`${o} no es un valor verdadero o falso`,notAnEmail:({label:o})=>`${o} no es un email`,notAnId:({label:o})=>`${o} no es un ID válido`,notADate:({label:o})=>`${o} no es una fecha válida`,notAnArray:({label:o})=>`${o} no es un arreglo`,notAnObject:({label:o})=>`${o} no es un objeto`,stringTooShort:({label:o})=>`${o} no tiene el largo suficiente`,stringTooLong:"El largo es mayor al permitido",numberTooSmall:({label:o})=>`${o} es un número muy pequeño`,numberTooBig:({label:o})=>`${o} es un número muy grande`,notInSchema:({label:o})=>`${o} no esta permitido`,notUnique:({label:o})=>`${o} no es único`,notFound:({label:o})=>`${o} no se encontró`,invalid:"No es válido",rateLimitExceeded:"Has excedido el límite de intentos. Intenta de nuevo más tarde.",incorrectLoginCode:"El código es incorrecto",loginCodeExpired:"El código expiró. Solicita un nuevo",loginCodeLocked:"El código se bloqueó. Genera un nuevo código para continuar",userNotFound:"No existe una cuenta con este email"};function xi(o,i){let t=$o[o];if(!t)return`${i}: ${o}`;if(typeof t==="function")return t({label:i});return t}function Co(o){return Object.entries(o).map(([i,t])=>xi(t,i)).join(", ")}function Ei(o){if(o.error==="validationError"&&o.validationErrors)return Co(o.validationErrors);if(o.extensions?.code==="PermissionsError"){let e=o.extensions.info?.type;if(e?.includes("User doesn't have permissions for "))return`Tu usuario no tiene permisos para [${e.split("User doesn't have permissions for ")[1]}]`;return o.message}if(o.validationErrors)return`${o.message} (${Co(o.validationErrors)})`;let i=o.message||"Error desconocido",t=$o[i];if(t)return typeof t==="function"?t({label:""}).trim():t;let r=o.error||o.code||o.type;return r?`${i} [${r}]`:i}function Pi(o){try{return JSON.parse(Buffer.from(o.split(".")[1],"base64").toString()).exp*1000<Date.now()}catch{return!0}}async function Wi(){let o=d();if(!o?.refreshToken)return null;let i=`${G("auth")}/refresh-token`,r=await(await fetch(i,{method:"POST",headers:{"X-ORION-REFRESH":o.refreshToken}})).json();if(!r.token)return null;return Z({...o,token:r.token}),r.token}async function Ni(){let o=d();if(!o?.token)return;if(!Pi(o.token))return o.token;return await Wi()??void 0}async function c(o){let i=`${G(o.service)}/graphql`,t=await Ni(),r={"Content-Type":"application/json","X-ORION-DEVICEID":Ui(),"X-ORION-PLATFORM":"web"};if(t)r["x-orion-jwt"]=t;let e;try{e=await fetch(i,{method:"POST",headers:r,body:JSON.stringify({query:o.query,variables:o.variables}),signal:AbortSignal.timeout(15000)})}catch{throw Error("La solicitud tardó demasiado. Intenta de nuevo.")}let s=await e.json();if(s.errors?.length)throw Error(Ei(s.errors[0]));if(!s.data)throw Error("No data returned from server");return s.data}import{createInterface as Ai}from"node:readline";function eo(o){let i=Ai({input:process.stdin,output:process.stderr});return new Promise((t)=>{i.question(o,(r)=>{i.close(),t(r.trim())})})}var Oi={comma:",",tab:"\t",pipe:"|"},M=Oi.comma;function jo(o){return o.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}function Si(o){return o==="true"||o==="false"||o==="null"}function h(o){if(o===null)return null;if(typeof o==="object"&&o!==null&&"toJSON"in o&&typeof o.toJSON==="function"){let i=o.toJSON();if(i!==o)return h(i)}if(typeof o==="string"||typeof o==="boolean")return o;if(typeof o==="number"){if(Object.is(o,-0))return 0;if(!Number.isFinite(o))return null;return o}if(typeof o==="bigint"){if(o>=Number.MIN_SAFE_INTEGER&&o<=Number.MAX_SAFE_INTEGER)return Number(o);return o.toString()}if(o instanceof Date)return o.toISOString();if(Array.isArray(o))return o.map(h);if(o instanceof Set)return Array.from(o).map(h);if(o instanceof Map)return Object.fromEntries(Array.from(o,([i,t])=>[String(i),h(t)]));if(Qi(o)){let i={};for(let t in o)if(Object.prototype.hasOwnProperty.call(o,t))i[t]=h(o[t]);return i}return null}function W(o){return o===null||typeof o==="string"||typeof o==="number"||typeof o==="boolean"}function E(o){return Array.isArray(o)}function w(o){return o!==null&&typeof o==="object"&&!Array.isArray(o)}function _(o){return Object.keys(o).length===0}function Qi(o){if(o===null||typeof o!=="object")return!1;let i=Object.getPrototypeOf(o);return i===null||i===Object.prototype}function F(o){return o.length===0||o.every((i)=>W(i))}function Bi(o){return o.length===0||o.every((i)=>E(i))}function yo(o){return o.length===0||o.every((i)=>w(i))}function Gi(o){return/^[A-Z_][\w.]*$/i.test(o)}function Ji(o){return/^[A-Z_]\w*$/i.test(o)}function _i(o,i=M){if(!o)return!1;if(o!==o.trim())return!1;if(Si(o)||Fi(o))return!1;if(o.includes(":"))return!1;if(o.includes('"')||o.includes("\\"))return!1;if(/[[\]{}]/.test(o))return!1;if(/[\n\r\t]/.test(o))return!1;if(o.includes(i))return!1;if(o.startsWith("-"))return!1;return!0}function Fi(o){return/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(o)||/^0\d+$/.test(o)}var St=Symbol("quotedKey");function Ti(o,i,t,r,e,s,n){if(r.keyFolding!=="safe")return;if(!w(i))return;let{segments:a,tail:u,leafValue:j}=Mi(o,i,n??r.flattenDepth);if(a.length<2)return;if(!a.every((y)=>Ji(y)))return;let b=Xi(a),q=s?`${s}.${b}`:b;if(t.includes(b))return;if(e&&e.has(q))return;return{foldedKey:b,remainder:u,leafValue:j,segmentCount:a.length}}function Mi(o,i,t){let r=[o],e=i;while(r.length<t){if(!w(e))break;let s=Object.keys(e);if(s.length!==1)break;let n=s[0],a=e[n];r.push(n),e=a}if(!w(e)||_(e))return{segments:r,tail:void 0,leafValue:e};return{segments:r,tail:e,leafValue:e}}function Xi(o){return o.join(".")}function A(o,i){if(o===null)return"null";if(typeof o==="boolean")return String(o);if(typeof o==="number")return String(o);return Yi(o,i)}function Yi(o,i=M){if(_i(o,i))return o;return`"${jo(o)}"`}function T(o){if(Gi(o))return o;return`"${jo(o)}"`}function ho(o,i=M){return o.map((t)=>A(t,i)).join(i)}function R(o,i){let t=i?.key,r=i?.fields,e=i?.delimiter??",",s="";if(t)s+=T(t);if(s+=`[${o}${e!==M?e:""}]`,r){let n=r.map((a)=>T(a));s+=`{${n.join(e)}}`}return s+=":",s}function*Zi(o,i,t){if(W(o)){let r=A(o,i.delimiter);if(r!=="")yield r;return}if(E(o))yield*so(void 0,o,t,i);else if(w(o))yield*N(o,t,i)}function*N(o,i,t,r,e,s){let n=Object.keys(o);if(i===0&&!r)r=new Set(n.filter((u)=>u.includes(".")));let a=s??t.flattenDepth;for(let[u,j]of Object.entries(o))yield*vi(u,j,i,t,n,r,e,a)}function*vi(o,i,t,r,e,s,n,a){let u=n?`${n}.${o}`:o,j=a??r.flattenDepth;if(r.keyFolding==="safe"&&e){let q=Ti(o,i,e,r,s,n,j);if(q){let{foldedKey:y,remainder:B,leafValue:x,segmentCount:li}=q,V=T(y);if(B===void 0){if(W(x)){yield p(t,`${V}: ${A(x,r.delimiter)}`,r.indent);return}else if(E(x)){yield*so(y,x,t,r);return}else if(w(x)&&_(x)){yield p(t,`${V}:`,r.indent);return}}if(w(B)){yield p(t,`${V}:`,r.indent);let pi=j-li,wi=n?`${n}.${y}`:y;yield*N(B,t+1,r,s,wi,pi);return}}}let b=T(o);if(W(i))yield p(t,`${b}: ${A(i,r.delimiter)}`,r.indent);else if(E(i))yield*so(o,i,t,r);else if(w(i)){if(yield p(t,`${b}:`,r.indent),!_(i))yield*N(i,t+1,r,s,u,j)}}function*so(o,i,t,r){if(i.length===0){yield p(t,R(0,{key:o,delimiter:r.delimiter}),r.indent);return}if(F(i)){yield p(t,z(i,r.delimiter,o),r.indent);return}if(Bi(i)){if(i.every((e)=>F(e))){yield*zi(o,i,t,r);return}}if(yo(i)){let e=Ro(i);if(e)yield*Hi(o,i,e,t,r);else yield*Io(o,i,t,r);return}yield*Io(o,i,t,r)}function*zi(o,i,t,r){yield p(t,R(i.length,{key:o,delimiter:r.delimiter}),r.indent);for(let e of i)if(F(e)){let s=z(e,r.delimiter);yield C(t+1,s,r.indent)}}function z(o,i,t){let r=R(o.length,{key:t,delimiter:i}),e=ho(o,i);if(o.length===0)return r;return`${r} ${e}`}function*Hi(o,i,t,r,e){yield p(r,R(i.length,{key:o,fields:t,delimiter:e.delimiter}),e.indent),yield*Uo(i,t,r+1,e)}function Ro(o){if(o.length===0)return;let i=o[0],t=Object.keys(i);if(t.length===0)return;if(Di(o,t))return t}function Di(o,i){for(let t of o){if(Object.keys(t).length!==i.length)return!1;for(let r of i){if(!(r in t))return!1;if(!W(t[r]))return!1}}return!0}function*Uo(o,i,t,r){for(let e of o)yield p(t,ho(i.map((s)=>e[s]),r.delimiter),r.indent)}function*Io(o,i,t,r){yield p(t,R(i.length,{key:o,delimiter:r.delimiter}),r.indent);for(let e of i)yield*no(e,t+1,r)}function*Ki(o,i,t){if(_(o)){yield p(i,"-",t.indent);return}let r=Object.entries(o),[e,s]=r[0],n=r.slice(1);if(E(s)&&yo(s)){let u=Ro(s);if(u){if(yield C(i,R(s.length,{key:e,fields:u,delimiter:t.delimiter}),t.indent),yield*Uo(s,u,i+2,t),n.length>0)yield*N(Object.fromEntries(n),i+1,t);return}}let a=T(e);if(W(s))yield C(i,`${a}: ${A(s,t.delimiter)}`,t.indent);else if(E(s))if(s.length===0)yield C(i,`${a}${R(0,{delimiter:t.delimiter})}`,t.indent);else if(F(s))yield C(i,`${a}${z(s,t.delimiter)}`,t.indent);else{yield C(i,`${a}${R(s.length,{delimiter:t.delimiter})}`,t.indent);for(let u of s)yield*no(u,i+2,t)}else if(w(s)){if(yield C(i,`${a}:`,t.indent),!_(s))yield*N(s,i+2,t)}if(n.length>0)yield*N(Object.fromEntries(n),i+1,t)}function*no(o,i,t){if(W(o))yield C(i,A(o,t.delimiter),t.indent);else if(E(o))if(F(o))yield C(i,z(o,t.delimiter),t.indent);else{yield C(i,R(o.length,{delimiter:t.delimiter}),t.indent);for(let r of o)yield*no(r,i+1,t)}else if(w(o))yield*Ki(o,i,t)}function p(o,i,t){return" ".repeat(t*o)+i}function C(o,i,t){return p(o,"- "+i,t)}function ki(o,i){let t=i("",o,[]);if(t===void 0)return v(o,i,[]);return v(h(t),i,[])}function v(o,i,t){if(w(o))return Vi(o,i,t);if(E(o))return Li(o,i,t);return o}function Vi(o,i,t){let r={};for(let[e,s]of Object.entries(o)){let n=[...t,e],a=i(e,s,n);if(a===void 0)continue;r[e]=v(h(a),i,n)}return r}function Li(o,i,t){let r=[];for(let e=0;e<o.length;e++){let s=o[e],n=[...t,e],a=i(String(e),s,n);if(a===void 0)continue;let u=h(a);r.push(v(u,i,n))}return r}function ao(o,i){return Array.from(ot(o,i)).join(`
3
+ `)}function ot(o,i){let t=h(o),r=it(i);return Zi(r.replacer?ki(t,r.replacer):t,r,0)}function it(o){return{indent:o?.indent??2,delimiter:o?.delimiter??M,keyFolding:o?.keyFolding??"off",flattenDepth:o?.flattenDepth??Number.POSITIVE_INFINITY,replacer:o?.replacer}}function tt(o){let i=o.format??"toon";if(i!=="toon"&&i!=="json")throw Error("--format debe ser toon o json.");return i}function xo(o,i){if(tt(i)==="json"){console.log(JSON.stringify(o,null,2));return}console.log(ao(o))}function g(o){process.stdout.write(`${o}
4
+ `)}function Eo(o,i){let r={ok:!1,error:o instanceof Error?o.message:String(o)};if((i.format==="json"?"json":"toon")==="json"){console.error(JSON.stringify(r,null,2));return}console.error(ao(r))}function $(o){process.stderr.write(o)}async function Po(o){return(await c({service:"auth",query:`mutation ($email: String!) {
3
5
  requestLoginCode(email: $email)
4
- }`,variables:{email:g}})).requestLoginCode}async function Wg(g,m,q){let $=await N({service:"auth",query:`mutation ($email: String!, $token: String!, $code: String!) {
6
+ }`,variables:{email:o}})).requestLoginCode}async function Wo(o,i,t){let r=await c({service:"auth",query:`mutation ($email: String!, $token: String!, $code: String!) {
5
7
  loginWithCode(email: $email, token: $token, code: $code) {
6
8
  token
7
9
  refreshToken
8
10
  }
9
- }`,variables:{email:g,token:m,code:q.toUpperCase()}});K({email:g,token:$.loginWithCode.token,refreshToken:$.loginWithCode.refreshToken}),await ng(),console.log(`Sesión iniciada como ${g}`)}async function ng(){if(!(await N({service:"main",query:"query { me { roles } }"})).me?.roles?.length)throw d(),Error("Solo miembros del equipo Justo pueden usar esta herramienta.")}async function Ng(){let g=await p("Email: ");console.log("Enviando código de verificación...");let m=await wg(g);console.log("Código enviado a tu email.");let q=await p("Código: ");await Wg(g,m,q)}async function fg(g){let m=H(g,"email"),q=H(g,"token"),$=H(g,"code");await Wg(m,q,$)}async function Ug(g){let m=H(g,"email");console.log("Enviando código de verificación...");let q=await wg(m);console.log(`Código enviado a ${m}`),console.log(`Token: ${q}`),console.log(""),console.log("Ahora ejecuta:"),console.log(` npx @getjusto/team-cli auth login-with-token --email ${m} --token ${q} --code <CÓDIGO>`)}async function Xg(){d(),console.log("Sesión cerrada.")}async function Zg(){let g=f();if(!g){console.log("No hay sesión activa."),console.log("Usa: npx @getjusto/team-cli@latest auth login");return}console.log(`Sesión activa: ${g.email}`)}function u(){console.log(`
10
- team-cli auth - Gestión de sesión
11
+ }`,variables:{email:o,token:i,code:t.toUpperCase()}});Z({email:o,token:r.loginWithCode.token,refreshToken:r.loginWithCode.refreshToken}),await rt()}async function rt(){if(!(await c({service:"main",query:"query { me { roles } }"})).me?.roles?.length)throw ro(),Error("Solo miembros del equipo Justo pueden usar esta herramienta.")}async function No(){let o=await eo("Email: ");$(`Enviando codigo de verificacion...
12
+ `);let i=await Po(o);$(`Codigo enviado a tu email.
13
+ `);let t=await eo("Codigo: ");return await Wo(o,i,t),{ok:!0,authenticated:!0,email:o}}async function Ao(o){let i=J(o,"email"),t=J(o,"token"),r=J(o,"code");return await Wo(i,t,r),{ok:!0,authenticated:!0,email:i}}async function Oo(o){let i=J(o,"email");$(`Enviando codigo de verificacion...
14
+ `);let t=await Po(i);return{ok:!0,email:i,token:t,nextCommand:`npx @getjusto/team-cli auth login-with-token --email ${i} --token ${t} --code <CODIGO>`}}async function So(){return ro(),{ok:!0,authenticated:!1}}async function Qo(){let o=d();if(!o)return{authenticated:!1,loginCommand:"npx @getjusto/team-cli@latest auth login"};return{authenticated:!0,email:o.email}}function co(){return`team-cli auth
11
15
 
12
- Comandos:
13
- login Iniciar sesión (interactivo, pide email y código)
14
- logout Cerrar sesión
15
- status Ver sesión actual
16
+ Gestion de sesion.
16
17
 
17
- Modo no interactivo:
18
- Primero solicita un código, luego úsalo para iniciar sesión:
18
+ Uso:
19
+ team-cli auth <subcomando> [opciones]
19
20
 
20
- 1. request-code --email <email>
21
- 2. login-with-token --email <email> --token <token> --code <código>
22
- `)}var tg={comma:",",tab:"\t",pipe:"|"},y=tg.comma;function Jg(g){return g.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}function eg(g){return g==="true"||g==="false"||g==="null"}function E(g){if(g===null)return null;if(typeof g==="object"&&g!==null&&"toJSON"in g&&typeof g.toJSON==="function"){let m=g.toJSON();if(m!==g)return E(m)}if(typeof g==="string"||typeof g==="boolean")return g;if(typeof g==="number"){if(Object.is(g,-0))return 0;if(!Number.isFinite(g))return null;return g}if(typeof g==="bigint"){if(g>=Number.MIN_SAFE_INTEGER&&g<=Number.MAX_SAFE_INTEGER)return Number(g);return g.toString()}if(g instanceof Date)return g.toISOString();if(Array.isArray(g))return g.map(E);if(g instanceof Set)return Array.from(g).map(E);if(g instanceof Map)return Object.fromEntries(Array.from(g,([m,q])=>[String(m),E(q)]));if(gm(g)){let m={};for(let q in g)if(Object.prototype.hasOwnProperty.call(g,q))m[q]=E(g[q]);return m}return null}function T(g){return g===null||typeof g==="string"||typeof g==="number"||typeof g==="boolean"}function S(g){return Array.isArray(g)}function U(g){return g!==null&&typeof g==="object"&&!Array.isArray(g)}function I(g){return Object.keys(g).length===0}function gm(g){if(g===null||typeof g!=="object")return!1;let m=Object.getPrototypeOf(g);return m===null||m===Object.prototype}function c(g){return g.length===0||g.every((m)=>T(m))}function mm(g){return g.length===0||g.every((m)=>S(m))}function _g(g){return g.length===0||g.every((m)=>U(m))}function qm(g){return/^[A-Z_][\w.]*$/i.test(g)}function $m(g){return/^[A-Z_]\w*$/i.test(g)}function jm(g,m=y){if(!g)return!1;if(g!==g.trim())return!1;if(eg(g)||Cm(g))return!1;if(g.includes(":"))return!1;if(g.includes('"')||g.includes("\\"))return!1;if(/[[\]{}]/.test(g))return!1;if(/[\n\r\t]/.test(g))return!1;if(g.includes(m))return!1;if(g.startsWith("-"))return!1;return!0}function Cm(g){return/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(g)||/^0\d+$/.test(g)}var om=Symbol("quotedKey");function Gm(g,m,q,$,j,C,G){if($.keyFolding!=="safe")return;if(!U(m))return;let{segments:R,tail:Q,leafValue:J}=Rm(g,m,G??$.flattenDepth);if(R.length<2)return;if(!R.every((_)=>$m(_)))return;let X=Qm(R),Z=C?`${C}.${X}`:X;if(q.includes(X))return;if(j&&j.has(Z))return;return{foldedKey:X,remainder:Q,leafValue:J,segmentCount:R.length}}function Rm(g,m,q){let $=[g],j=m;while($.length<q){if(!U(j))break;let C=Object.keys(j);if(C.length!==1)break;let G=C[0],R=j[G];$.push(G),j=R}if(!U(j)||I(j))return{segments:$,tail:void 0,leafValue:j};return{segments:$,tail:j,leafValue:j}}function Qm(g){return g.join(".")}function O(g,m){if(g===null)return"null";if(typeof g==="boolean")return String(g);if(typeof g==="number")return String(g);return wm(g,m)}function wm(g,m=y){if(jm(g,m))return g;return`"${Jg(g)}"`}function b(g){if(qm(g))return g;return`"${Jg(g)}"`}function Eg(g,m=y){return g.map((q)=>O(q,m)).join(m)}function M(g,m){let q=m?.key,$=m?.fields,j=m?.delimiter??",",C="";if(q)C+=b(q);if(C+=`[${g}${j!==y?j:""}]`,$){let G=$.map((R)=>b(R));C+=`{${G.join(j)}}`}return C+=":",C}function*Wm(g,m,q){if(T(g)){let $=O(g,m.delimiter);if($!=="")yield $;return}if(S(g))yield*a(void 0,g,q,m);else if(U(g))yield*z(g,q,m)}function*z(g,m,q,$,j,C){let G=Object.keys(g);if(m===0&&!$)$=new Set(G.filter((Q)=>Q.includes(".")));let R=C??q.flattenDepth;for(let[Q,J]of Object.entries(g))yield*Nm(Q,J,m,q,G,$,j,R)}function*Nm(g,m,q,$,j,C,G,R){let Q=G?`${G}.${g}`:g,J=R??$.flattenDepth;if($.keyFolding==="safe"&&j){let Z=Gm(g,m,j,$,C,G,J);if(Z){let{foldedKey:_,remainder:P,leafValue:A,segmentCount:Ig}=Z,L=b(_);if(P===void 0){if(T(A)){yield W(q,`${L}: ${O(A,$.delimiter)}`,$.indent);return}else if(S(A)){yield*a(_,A,q,$);return}else if(U(A)&&I(A)){yield W(q,`${L}:`,$.indent);return}}if(U(P)){yield W(q,`${L}:`,$.indent);let cg=J-Ig,bg=G?`${G}.${_}`:_;yield*z(P,q+1,$,C,bg,cg);return}}}let X=b(g);if(T(m))yield W(q,`${X}: ${O(m,$.delimiter)}`,$.indent);else if(S(m))yield*a(g,m,q,$);else if(U(m)){if(yield W(q,`${X}:`,$.indent),!I(m))yield*z(m,q+1,$,C,Q,J)}}function*a(g,m,q,$){if(m.length===0){yield W(q,M(0,{key:g,delimiter:$.delimiter}),$.indent);return}if(c(m)){yield W(q,k(m,$.delimiter,g),$.indent);return}if(mm(m)){if(m.every((j)=>c(j))){yield*fm(g,m,q,$);return}}if(_g(m)){let j=Mg(m);if(j)yield*Um(g,m,j,q,$);else yield*Yg(g,m,q,$);return}yield*Yg(g,m,q,$)}function*fm(g,m,q,$){yield W(q,M(m.length,{key:g,delimiter:$.delimiter}),$.indent);for(let j of m)if(c(j)){let C=k(j,$.delimiter);yield Y(q+1,C,$.indent)}}function k(g,m,q){let $=M(g.length,{key:q,delimiter:m}),j=Eg(g,m);if(g.length===0)return $;return`${$} ${j}`}function*Um(g,m,q,$,j){yield W($,M(m.length,{key:g,fields:q,delimiter:j.delimiter}),j.indent),yield*Bg(m,q,$+1,j)}function Mg(g){if(g.length===0)return;let m=g[0],q=Object.keys(m);if(q.length===0)return;if(Xm(g,q))return q}function Xm(g,m){for(let q of g){if(Object.keys(q).length!==m.length)return!1;for(let $ of m){if(!($ in q))return!1;if(!T(q[$]))return!1}}return!0}function*Bg(g,m,q,$){for(let j of g)yield W(q,Eg(m.map((C)=>j[C]),$.delimiter),$.indent)}function*Yg(g,m,q,$){yield W(q,M(m.length,{key:g,delimiter:$.delimiter}),$.indent);for(let j of m)yield*n(j,q+1,$)}function*Zm(g,m,q){if(I(g)){yield W(m,"-",q.indent);return}let $=Object.entries(g),[j,C]=$[0],G=$.slice(1);if(S(C)&&_g(C)){let Q=Mg(C);if(Q){if(yield Y(m,M(C.length,{key:j,fields:Q,delimiter:q.delimiter}),q.indent),yield*Bg(C,Q,m+2,q),G.length>0)yield*z(Object.fromEntries(G),m+1,q);return}}let R=b(j);if(T(C))yield Y(m,`${R}: ${O(C,q.delimiter)}`,q.indent);else if(S(C))if(C.length===0)yield Y(m,`${R}${M(0,{delimiter:q.delimiter})}`,q.indent);else if(c(C))yield Y(m,`${R}${k(C,q.delimiter)}`,q.indent);else{yield Y(m,`${R}${M(C.length,{delimiter:q.delimiter})}`,q.indent);for(let Q of C)yield*n(Q,m+2,q)}else if(U(C)){if(yield Y(m,`${R}:`,q.indent),!I(C))yield*z(C,m+2,q)}if(G.length>0)yield*z(Object.fromEntries(G),m+1,q)}function*n(g,m,q){if(T(g))yield Y(m,O(g,q.delimiter),q.indent);else if(S(g))if(c(g))yield Y(m,k(g,q.delimiter),q.indent);else{yield Y(m,M(g.length,{delimiter:q.delimiter}),q.indent);for(let $ of g)yield*n($,m+1,q)}else if(U(g))yield*Zm(g,m,q)}function W(g,m,q){return" ".repeat(q*g)+m}function Y(g,m,q){return W(g,"- "+m,q)}function Ym(g,m){let q=m("",g,[]);if(q===void 0)return x(g,m,[]);return x(E(q),m,[])}function x(g,m,q){if(U(g))return Jm(g,m,q);if(S(g))return _m(g,m,q);return g}function Jm(g,m,q){let $={};for(let[j,C]of Object.entries(g)){let G=[...q,j],R=m(j,C,G);if(R===void 0)continue;$[j]=x(E(R),m,G)}return $}function _m(g,m,q){let $=[];for(let j=0;j<g.length;j++){let C=g[j],G=[...q,j],R=m(String(j),C,G);if(R===void 0)continue;let Q=E(R);$.push(x(Q,m,G))}return $}function V(g,m){return Array.from(Em(g,m)).join(`
23
- `)}function Em(g,m){let q=E(g),$=Mm(m);return Wm($.replacer?Ym(q,$.replacer):q,$,0)}function Mm(g){return{indent:g?.indent??2,delimiter:g?.delimiter??y,keyFolding:g?.keyFolding??"off",flattenDepth:g?.flattenDepth??Number.POSITIVE_INFINITY,replacer:g?.replacer}}var t=["main","auth","webdata","preferences","buckets","reservations","data","finances","url-shortener","files","tabs","commander","experiments","sales","delivery","payments","addresses","royalty","marketing","api","messenger","invoice","drivers-server"];async function Ag(g,m){let q=g[1],$=g[2],j=m.format||"toon";if(!f())throw Error("Debes iniciar sesión primero. Usa: team-cli auth login");if(!q||!$)e(),process.exit(1);if(!t.includes(q))console.error(`Error: servicio "${q}" no válido.`),console.error(`Servicios disponibles: ${t.join(", ")}`),process.exit(1);let C;if(m.variables)try{C=JSON.parse(m.variables)}catch{throw Error("Las variables deben ser un JSON válido.")}let G=await N({service:q,query:$,variables:C});if(j==="json")console.log(JSON.stringify(G,null,2));else console.log(V(G))}function e(){console.log(`
24
- team-cli graphql - Ejecutar queries y mutations GraphQL
21
+ Subcomandos:
22
+ login
23
+ Iniciar sesion en modo interactivo.
24
+ Uso: team-cli auth login
25
25
 
26
- Uso:
27
- team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]
26
+ logout
27
+ Cerrar sesion actual.
28
+ Uso: team-cli auth logout
28
29
 
29
- Ejemplos:
30
- team-cli graphql main 'query { me { _id roles } }'
31
- team-cli graphql main 'query($id: ID) { user(userId: $id) { _id } }' --variables '{"id": "abc123"}'
32
- team-cli graphql main 'query { me { _id } }' --format json
30
+ status
31
+ Ver la sesion actual.
32
+ Uso: team-cli auth status
33
33
 
34
- El formato por defecto es TOON. Usa --format json para obtener JSON.
34
+ request-code
35
+ Solicitar codigo para login no interactivo.
36
+ Uso: team-cli auth request-code --email <email>
35
37
 
36
- Servicios disponibles:
37
- ${t.join(", ")}
38
- `)}import{writeFileSync as Bm}from"node:fs";function r(){if(!f())throw Error("Debes iniciar sesión primero. Usa: team-cli auth login")}function D(g,m){let q=g[3];if(!q)console.error(`Uso: ${m}`),process.exit(1);return q}function Sg(g){if(!g.params)return{};try{return JSON.parse(g.params)}catch{throw Error("--params debe ser un JSON válido.")}}function Fg(g,m){if((m.format||"toon")==="json")console.log(typeof g==="string"?g:JSON.stringify(g,null,2));else{let $=typeof g==="string"?JSON.parse(g):g;console.log(V($))}}async function Tg(g,m){r();let q=D(g,"team-cli data queries view <queryId>"),$=await N({service:"data",query:`query ($aggregationQueryId: String) {
38
+ login-with-token
39
+ Iniciar sesion sin prompts.
40
+ Uso: team-cli auth login-with-token --email <email> --token <token> --code <codigo>`}var mo=["main","auth","webdata","preferences","buckets","reservations","data","finances","url-shortener","files","tabs","commander","experiments","sales","delivery","payments","addresses","royalty","marketing","api","messenger","invoice","drivers-server"];async function Bo(o,i){let t=o[1],r=o[2];if(!d())throw Error("Debes iniciar sesión primero. Usa: team-cli auth login");if(!t||!r)throw Error("Uso: team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]");if(!mo.includes(t))throw Error(`Servicio "${t}" no válido. Servicios disponibles: ${mo.join(", ")}`);let e;if(i.variables)try{e=JSON.parse(i.variables)}catch{throw Error("Las variables deben ser un JSON válido.")}return await c({service:t,query:r,variables:e})}function Go(){return`team-cli graphql
41
+
42
+ Ejecutar queries y mutations GraphQL.
43
+
44
+ Uso:
45
+ team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]
46
+
47
+ Ejemplos:
48
+ team-cli graphql main 'query { me { _id roles } }'
49
+ team-cli graphql main 'query($id: ID) { user(userId: $id) { _id } }' --variables '{"id": "abc123"}'
50
+ team-cli graphql main 'query { me { _id } }' --format json
51
+
52
+ Servicios disponibles:
53
+ ${mo.join(", ")}
54
+
55
+ Formato:
56
+ Por defecto usa toon. Usa --format json para JSON estándar.`}function et(o){return o.replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,"")}function st(o){return o.includes(".")||o.startsWith("http://")||o.startsWith("https://")}async function O(o){if(st(o)){let i=et(o),t=await fetch(`${G("main")}/website-id/${i}`,{signal:AbortSignal.timeout(1e4)});if(!t.ok)throw Error(`No se encontro el sitio "${i}"`);let r=await t.json();if(!r.websiteId)throw Error(`No se pudo resolver el websiteId para "${i}"`);return{input:o,websiteId:r.websiteId,targetType:"domain"}}return{input:o,websiteId:o,targetType:"websiteId"}}async function Jo(o){let i=await c({service:"main",query:`query ($websiteId: ID) {
57
+ website(websiteId: $websiteId) {
58
+ _id
59
+ name
60
+ active
61
+ baseURL
62
+ domain
63
+ domains
64
+ countryCode
65
+ timezone
66
+ defaultMenuId
67
+ }
68
+ }`,variables:{websiteId:o}});if(!i.website)throw Error(`No se encontro el website "${o}"`);return i.website}function nt(){if(!d())throw Error("Debes iniciar sesión primero. Usa: team-cli auth login")}async function _o(o){if(nt(),!o)throw Error("Uso: team-cli admin <websiteId|domain> show");let i=await O(o),t=await Jo(i.websiteId);return{context:i,website:t}}function H(){return`team-cli admin
69
+
70
+ Comandos administrativos con contexto de website.
71
+
72
+ Uso:
73
+ team-cli admin <websiteId|domain> <modulo> <accion> [opciones]
74
+
75
+ Modulos:
76
+ show
77
+ Mostrar informacion basica del website seleccionado.
78
+ Uso: team-cli admin <websiteId|domain> show
79
+
80
+ search
81
+ Buscar websites en admin.
82
+ Uso: team-cli admin search <texto> [--limit <n>] [--page <n>]
83
+
84
+ stores list
85
+ Listar las tiendas del website seleccionado.
86
+ Uso: team-cli admin <websiteId|domain> stores list
87
+
88
+ coupons
89
+ Administrar cupones y sus códigos.
90
+ Uso: team-cli admin <websiteId|domain> coupons <accion> [opciones]`}var Fo=`
91
+ availableAtPeriods
92
+ closedDays
93
+ closedUntilDate
94
+ isAvailableNow
95
+ timezone
96
+ openPeriods {
97
+ daysOfWeek
98
+ fromMinute
99
+ toMinute
100
+ }
101
+ specialPeriods {
102
+ days
103
+ fromMinute
104
+ toMinute
105
+ }
106
+ `,D=`
107
+ _id
108
+ websiteId
109
+ name
110
+ code
111
+ active
112
+ type
113
+ description
114
+ isHidden
115
+ isBirthdayCoupon
116
+ totalRedemptions
117
+ fromDate
118
+ endDate
119
+ percentageOff
120
+ discountAmount
121
+ fixedAmount
122
+ maxRedemptions
123
+ maxRedemptionsPerUser
124
+ maxRedemptionsPerUserPerDay
125
+ minimumOrderPrice
126
+ maximumOrderPrice
127
+ applyDeliveryDiscount
128
+ deliveryDiscountType
129
+ deliveryDiscountValue
130
+ deliveryDiscountPercentage
131
+ allowedEmails
132
+ requireChannels
133
+ requiresPaymentTypes
134
+ requiresStoresIds
135
+ requiresMenusIds
136
+ requiresCategoriesIds
137
+ requiresProductsIds
138
+ requiredBINs
139
+ extraRequirementsForPaymentTypes
140
+ schedule {
141
+ ${Fo}
142
+ }
143
+ scheduleAtUse {
144
+ ${Fo}
145
+ }
146
+ codesCode
147
+ `,To=`
148
+ _id
149
+ code
150
+ couponId
151
+ websiteId
152
+ userEmail
153
+ sentToEmail
154
+ totalRedemptions
155
+ createdAt
156
+ `;function uo(){if(!d())throw Error("Debes iniciar sesión primero. Usa: team-cli auth login")}function S(o,i){let t=o[i];if(!t)throw Error(`--${i} es requerido.`);try{return JSON.parse(t)}catch{throw Error(`--${i} debe ser un JSON válido.`)}}function I(o,i){let t=o[i];if(!t)return;let r=Number.parseInt(t,10);if(Number.isNaN(r))throw Error(`--${i} debe ser un número entero.`);return r}function Mo(o,i){let t=o[i];if(!t)return;if(t==="true")return!0;if(t==="false")return!1;throw Error(`--${i} debe ser true o false.`)}async function f(o){if(uo(),!o)throw Error("Debes indicar <websiteId|domain>.");return O(o)}async function U(o,i){let t=await c({service:"main",query:`query ($couponId: ID) {
157
+ coupon(couponId: $couponId) {
158
+ _id
159
+ websiteId
160
+ }
161
+ }`,variables:{couponId:o}});if(!t.coupon)throw Error(`No se encontró el cupón "${o}"`);if(t.coupon.websiteId!==i)throw Error(`El cupón "${o}" no pertenece al website seleccionado.`);return t.coupon}async function Xo(o,i){uo();let t=o[2]??i.filter;if(!t)throw Error("Debes indicar un término de búsqueda. Uso: team-cli admin search <texto>");let r=I(i,"limit"),e=I(i,"page"),s=Mo(i,"only-active"),n=await c({service:"main",query:`query ($filter: String, $limit: BigInt, $page: BigInt, $onlyActiveWebsites: Boolean) {
162
+ websites(filter: $filter, limit: $limit, page: $page, onlyActiveWebsites: $onlyActiveWebsites) {
163
+ items {
164
+ _id
165
+ name
166
+ active
167
+ baseURL
168
+ domain
169
+ countryCode
170
+ timezone
171
+ }
172
+ totalCount
173
+ totalPages
174
+ hasNextPage
175
+ hasPreviousPage
176
+ }
177
+ }`,variables:{filter:t,limit:r,page:e,onlyActiveWebsites:s}});return{searchTerm:t,websites:n.websites.items??[],pagination:{totalCount:n.websites.totalCount??0,totalPages:n.websites.totalPages??0,hasNextPage:Boolean(n.websites.hasNextPage),hasPreviousPage:Boolean(n.websites.hasPreviousPage),page:e??1,limit:r??null}}}function Yo(){return`team-cli admin search
178
+
179
+ Buscar websites en admin.
180
+
181
+ Uso:
182
+ team-cli admin search <texto> [--limit <n>] [--page <n>] [--only-active true|false]
183
+
184
+ Opciones:
185
+ --limit <n>
186
+ Límite de resultados.
187
+
188
+ --page <n>
189
+ Página a consultar.
190
+
191
+ --only-active true|false
192
+ Filtrar solo websites activos.
193
+
194
+ Ejemplos:
195
+ team-cli admin search milas
196
+ team-cli admin search buffalo --limit 5
197
+ team-cli admin search pizza --only-active true`}function at(){if(!d())throw Error("Debes iniciar sesión primero. Usa: team-cli auth login")}function ct(o){let i=[o.address?.streetAddress,o.address?.extendedAddress,o.address?.locality].filter(Boolean);if(!i.length)return null;return i.join(", ")}async function Zo(o){if(at(),!o)throw Error("Uso: team-cli admin <websiteId|domain> stores list");let i=await O(o),r=((await c({service:"main",query:`query ($websiteId: ID) {
198
+ stores(websiteId: $websiteId) {
199
+ items {
200
+ _id
201
+ name
202
+ address {
203
+ streetAddress
204
+ extendedAddress
205
+ locality
206
+ }
207
+ }
208
+ }
209
+ }`,variables:{websiteId:i.websiteId}})).stores.items??[]).map((e)=>({_id:e._id,name:e.name,address:ct(e)})).sort((e,s)=>e.name.localeCompare(s.name,"es",{sensitivity:"base"}));return{context:i,stores:r,totalCount:r.length}}var vo={active:"Boolean",allowedEmails:"[String]",applyDeliveryDiscount:"Boolean",code:"ID",deliveryDiscountPercentage:"Float",deliveryDiscountType:"String",deliveryDiscountValue:"Float",description:"String",discountAmount:"Float",dontApplyToProductsIds:"[ID]",endDate:"Date",externalId:"String",extraRequirementsForPaymentTypes:"JSON",fixedAmount:"Float",fromDate:"Date",isBirthdayCoupon:"Boolean",isHidden:"Boolean",maxPercentageOffDiscount:"Float",maxProductsPerOrder:"Float",maxRedemptions:"Float",maxRedemptionsPerUser:"Float",maxRedemptionsPerUserPerDay:"Boolean",maximumOrderPrice:"Float",minimumOrderPrice:"Float",name:"String",onlyForNewUsers:"Boolean",onlyForProductsWithoutDiscount:"Boolean",onlyRedeemOnBirthday:"Boolean",percentageOff:"Float",requireChannels:"[ID]",requirePhoneVerification:"Boolean",requiredBINs:"[String]",requiresCategoriesIds:"[ID]",requiresMenusIds:"[ID]",requiresPaymentTypes:"[ID]",requiresProductsIds:"[ID]",requiresStoresIds:"[ID]",schedule:"ScheduleInput",scheduleAtUse:"ScheduleInput",type:"ID",websiteId:"ID"};function mt(o){let i=Object.entries(o).filter(([,s])=>s!==void 0),t=i.map(([s])=>s).filter((s)=>!vo[s]);if(t.length)throw Error(`Campos no soportados para create: ${t.join(", ")}`);let r=i.map(([s])=>`$${s}: ${vo[s]}`).join(", "),e=i.map(([s])=>`${s}: $${s}`).join(", ");return`mutation (${r}) {
210
+ createCoupon(${e}) {
211
+ ${D}
212
+ }
213
+ }`}async function zo(o,i){let t=await f(o),r=I(i,"limit"),e=I(i,"page"),s=i.filter,n=await c({service:"main",query:`query ($websiteId: ID, $filter: String, $limit: BigInt, $page: BigInt) {
214
+ coupons(websiteId: $websiteId, filter: $filter, limit: $limit, page: $page) {
215
+ items {
216
+ _id
217
+ name
218
+ code
219
+ active
220
+ type
221
+ totalRedemptions
222
+ percentageOff
223
+ discountAmount
224
+ fixedAmount
225
+ fromDate
226
+ endDate
227
+ }
228
+ totalCount
229
+ totalPages
230
+ hasNextPage
231
+ hasPreviousPage
232
+ }
233
+ }`,variables:{websiteId:t.websiteId,filter:s,limit:r,page:e}});return{context:t,coupons:n.coupons.items??[],pagination:{totalCount:n.coupons.totalCount??0,totalPages:n.coupons.totalPages??0,hasNextPage:Boolean(n.coupons.hasNextPage),hasPreviousPage:Boolean(n.coupons.hasPreviousPage),page:e??1,limit:r??null}}}async function Ho(o,i){let t=await f(o);await U(i,t.websiteId);let r=await c({service:"main",query:`query ($couponId: ID) {
234
+ coupon(couponId: $couponId) {
235
+ ${D}
236
+ }
237
+ }`,variables:{couponId:i}});return{context:t,coupon:r.coupon}}async function Do(o,i){let t=await f(o),r=S(i,"input");if(r.websiteId&&r.websiteId!==t.websiteId)throw Error("El websiteId del input no coincide con el website seleccionado.");let e={...r,websiteId:t.websiteId},s=mt(e),n=await c({service:"main",query:s,variables:e});return{context:t,coupon:n.createCoupon}}async function Ko(o,i,t){let r=await f(o);await U(i,r.websiteId);let e=S(t,"input"),s=await c({service:"main",query:`mutation ($couponId: ID, $coupon: UpdateCouponInput) {
238
+ updateCoupon(couponId: $couponId, coupon: $coupon) {
239
+ ${D}
240
+ }
241
+ }`,variables:{couponId:i,coupon:e}});return{context:r,coupon:s.updateCoupon}}async function ko(o,i){let t=await f(o);await U(i,t.websiteId);let r=await c({service:"main",query:`mutation ($couponsIds: [ID]) {
242
+ deleteCoupons(couponsIds: $couponsIds, globalCoupon: false)
243
+ }`,variables:{couponsIds:[i]}});return{context:t,couponId:i,deleted:r.deleteCoupons}}function X(){return`team-cli admin coupons
244
+
245
+ Administracion de cupones para el website seleccionado.
246
+
247
+ Uso:
248
+ team-cli admin <websiteId|domain> coupons <accion> [opciones]
249
+
250
+ Acciones:
251
+ list
252
+ Listar cupones.
253
+ Uso: team-cli admin <web> coupons list [--filter <text>] [--limit <n>] [--page <n>]
254
+
255
+ show
256
+ Ver detalle de un cupón.
257
+ Uso: team-cli admin <web> coupons show <couponId>
258
+
259
+ create
260
+ Crear un cupón usando --input con JSON.
261
+ Uso: team-cli admin <web> coupons create --input '<json>'
262
+ Ayuda detallada: team-cli admin <web> coupons create --help
263
+
264
+ update
265
+ Actualizar un cupón usando --input con JSON.
266
+ Uso: team-cli admin <web> coupons update <couponId> --input '<json>'
267
+ Ayuda detallada: team-cli admin <web> coupons update <couponId> --help
268
+
269
+ delete
270
+ Eliminar un cupón.
271
+ Uso: team-cli admin <web> coupons delete <couponId>
272
+
273
+ codes list
274
+ Listar códigos de un cupón.
275
+ Uso: team-cli admin <web> coupons codes list <couponId> [--filter <text>] [--limit <n>] [--page <n>]
276
+
277
+ codes create
278
+ Crear códigos explícitos para un cupón.
279
+ Uso: team-cli admin <web> coupons codes create <couponId> --input '<json>'
280
+ Ayuda detallada: team-cli admin <web> coupons codes create <couponId> --help
281
+
282
+ codes create-random
283
+ Crear códigos aleatorios para un cupón.
284
+ Uso: team-cli admin <web> coupons codes create-random <couponId> --quantity <n> [--prefix <text>]
285
+
286
+ codes delete
287
+ Eliminar códigos por id.
288
+ Uso: team-cli admin <web> coupons codes delete <couponId> --ids '["id1","id2"]'
289
+
290
+ Nota:
291
+ El schema actual no expone update para coupon codes.`}function Vo(){return`team-cli admin coupons create
292
+
293
+ Crea un cupón para el website seleccionado.
294
+
295
+ Uso:
296
+ team-cli admin <websiteId|domain> coupons create --input '<json>'
297
+
298
+ Como funciona:
299
+ --input recibe un objeto JSON con los campos de createCoupon.
300
+ team-cli agrega automaticamente websiteId usando el contexto seleccionado.
301
+ Si mandas websiteId dentro del JSON y no coincide con el website seleccionado, el comando falla.
302
+
303
+ Campos comunes:
304
+ name
305
+ code
306
+ type
307
+ active
308
+ description
309
+ percentageOff
310
+ discountAmount
311
+ fixedAmount
312
+ maxRedemptions
313
+ maxRedemptionsPerUser
314
+ minimumOrderPrice
315
+ maximumOrderPrice
316
+ fromDate
317
+ endDate
318
+ requiresStoresIds
319
+ requireChannels
320
+ requiresPaymentTypes
321
+ requiredBINs
322
+ schedule
323
+ scheduleAtUse
324
+
325
+ Ejemplo porcentaje:
326
+ team-cli admin <web> coupons create --input '{"name":"Promo 20","code":"PROMO20","type":"percentage","percentageOff":20,"active":true}'
327
+
328
+ Ejemplo monto fijo:
329
+ team-cli admin <web> coupons create --input '{"name":"Descuento 5000","code":"MENOS5K","type":"fixed","discountAmount":5000,"active":true}'
330
+
331
+ Ejemplo con restricciones:
332
+ team-cli admin <web> coupons create --input '{"name":"Solo retiro","code":"GOONLY","type":"fixed","discountAmount":3000,"active":true,"requiresStoresIds":["store1","store2"],"requireChannels":["web"]}'
333
+
334
+ Ejemplo con schedule:
335
+ team-cli admin <web> coupons create --input '{"name":"Happy Hour","code":"HAPPY","type":"percentage","percentageOff":15,"schedule":{"timezone":"America/Santiago","isAvailableNow":true,"openPeriods":[{"daysOfWeek":[1,2,3,4,5],"fromMinute":720,"toMinute":900}]}}'
336
+
337
+ Tips:
338
+ Usa comillas simples afuera del JSON en shell.
339
+ Usa arrays JSON reales para ids o listas.
340
+ Si necesitas el shape exacto de un cupón existente, parte con: team-cli admin <web> coupons show <couponId>`}function Lo(){return`team-cli admin coupons update
341
+
342
+ Actualiza un cupón existente.
343
+
344
+ Uso:
345
+ team-cli admin <websiteId|domain> coupons update <couponId> --input '<json>'
346
+
347
+ Como funciona:
348
+ --input recibe un objeto JSON compatible con UpdateCouponInput.
349
+ Solo envía los campos que quieras cambiar.
350
+ couponId se valida contra el website seleccionado antes de ejecutar la mutation.
351
+
352
+ Campos comunes:
353
+ name
354
+ active
355
+ description
356
+ percentageOff
357
+ discountAmount
358
+ fixedAmount
359
+ maxRedemptions
360
+ maxRedemptionsPerUser
361
+ minimumOrderPrice
362
+ maximumOrderPrice
363
+ fromDate
364
+ endDate
365
+ requiresStoresIds
366
+ requireChannels
367
+ requiresPaymentTypes
368
+ requiredBINs
369
+ schedule
370
+ scheduleAtUse
371
+
372
+ Ejemplo simple:
373
+ team-cli admin <web> coupons update <couponId> --input '{"active":false}'
374
+
375
+ Ejemplo cambiando descuento:
376
+ team-cli admin <web> coupons update <couponId> --input '{"percentageOff":25,"maxRedemptions":100}'
377
+
378
+ Ejemplo reemplazando restricciones:
379
+ team-cli admin <web> coupons update <couponId> --input '{"requiresStoresIds":["store1"],"requiresPaymentTypes":["card"]}'
380
+
381
+ Tip:
382
+ Primero mira el cupón actual con: team-cli admin <web> coupons show <couponId>`}function ut(o){if(!Array.isArray(o))throw Error("--input debe ser un arreglo JSON.");return o.map((i)=>{if(!i||typeof i!=="object"||typeof i.code!=="string")throw Error('Cada item de --input debe tener al menos { "code": "..." }.');if(i.userEmail!=null&&typeof i.userEmail!=="string")throw Error("userEmail debe ser string cuando viene informado.");return{code:i.code,userEmail:i.userEmail}})}function gt(o){if(!Array.isArray(o)||o.some((i)=>typeof i!=="string"))throw Error("--ids debe ser un arreglo JSON de strings.");return o}async function oi(o,i,t){let r=await f(o);await U(i,r.websiteId);let e=I(t,"limit"),s=I(t,"page"),n=t.filter,a=await c({service:"main",query:`query ($couponId: ID, $filter: String, $limit: BigInt, $page: BigInt) {
383
+ couponCodes(couponId: $couponId, filter: $filter, limit: $limit, page: $page) {
384
+ items {
385
+ ${To}
386
+ }
387
+ totalCount
388
+ totalPages
389
+ hasNextPage
390
+ hasPreviousPage
391
+ }
392
+ }`,variables:{couponId:i,filter:n,limit:e,page:s}});return{context:r,couponId:i,codes:a.couponCodes.items??[],pagination:{totalCount:a.couponCodes.totalCount??0,totalPages:a.couponCodes.totalPages??0,hasNextPage:Boolean(a.couponCodes.hasNextPage),hasPreviousPage:Boolean(a.couponCodes.hasPreviousPage),page:s??1,limit:e??null}}}async function ii(o,i,t){let r=await f(o);await U(i,r.websiteId);let e=ut(S(t,"input")),s=e.some((a)=>a.userEmail),n=await c({service:"main",query:`mutation ($couponId: ID, $codesWithEmail: [CodeWithEmailInput], $useCodeWithEmail: Boolean) {
393
+ createCouponCodes(couponId: $couponId, codesWithEmail: $codesWithEmail, useCodeWithEmail: $useCodeWithEmail)
394
+ }`,variables:{couponId:i,codesWithEmail:e,useCodeWithEmail:s}});return{context:r,couponId:i,requestedCount:e.length,result:n.createCouponCodes}}async function ti(o,i,t){let r=await f(o);await U(i,r.websiteId);let e=I(t,"quantity");if(!e)throw Error("--quantity es requerido.");let s=await c({service:"main",query:`mutation ($couponId: ID, $couponQuantity: Float, $couponCodePrefix: String) {
395
+ createRandomCouponCodes(couponId: $couponId, couponQuantity: $couponQuantity, couponCodePrefix: $couponCodePrefix)
396
+ }`,variables:{couponId:i,couponQuantity:e,couponCodePrefix:t.prefix}});return{context:r,couponId:i,quantity:e,prefix:t.prefix??null,result:s.createRandomCouponCodes}}async function ri(o,i,t){let r=await f(o);await U(i,r.websiteId);let e=gt(S(t,"ids")),s=await c({service:"main",query:`mutation ($couponId: ID, $couponCodesIds: [ID]) {
397
+ deleteCouponCodes(couponId: $couponId, couponCodesIds: $couponCodesIds, globalCoupon: false)
398
+ }`,variables:{couponId:i,couponCodesIds:e}});return{context:r,couponId:i,deleted:s.deleteCouponCodes,couponCodesIds:e}}function ei(){return`team-cli admin coupons codes create
399
+
400
+ Crea códigos explícitos para un cupón.
401
+
402
+ Uso:
403
+ team-cli admin <websiteId|domain> coupons codes create <couponId> --input '<json>'
404
+
405
+ Como funciona:
406
+ --input recibe un arreglo JSON.
407
+ Cada item debe tener al menos el campo code.
408
+ Opcionalmente puede incluir userEmail.
409
+
410
+ Formato esperado:
411
+ [
412
+ {"code":"BIENVENIDA1"},
413
+ {"code":"BIENVENIDA2","userEmail":"persona@ejemplo.com"}
414
+ ]
415
+
416
+ Ejemplo:
417
+ team-cli admin <web> coupons codes create <couponId> --input '[{"code":"PROMO001"},{"code":"PROMO002","userEmail":"ana@ejemplo.com"}]'
418
+
419
+ Notas:
420
+ Si algún item trae userEmail, team-cli activa useCodeWithEmail automáticamente.
421
+ couponId se valida contra el website seleccionado antes de ejecutar la mutation.`}import{writeFileSync as dt}from"node:fs";function K(){if(!d())throw Error("Debes iniciar sesión primero. Usa: team-cli auth login")}function k(o,i){let t=o[3];if(!t)throw Error(`Uso: ${i}`);return t}function si(o){if(!o.params)return{};try{return JSON.parse(o.params)}catch{throw Error("--params debe ser un JSON válido.")}}function lt(o){if(typeof o!=="string")return o;try{return JSON.parse(o)}catch{return{value:o}}}async function ni(o){K();let i=k(o,"team-cli data queries view <queryId>");return(await c({service:"data",query:`query ($aggregationQueryId: String) {
39
422
  aggregationQuery(aggregationQueryId: $aggregationQueryId) {
40
423
  _id
41
424
  name
@@ -48,15 +431,17 @@ var yg={main:{local:"http://localhost:3000",develop:"https://api.bejusto.com",pr
48
431
  fieldParams
49
432
  }
50
433
  }
51
- }`,variables:{aggregationQueryId:q}});Fg($.aggregationQuery,m)}async function zg(g,m){r();let q=D(g,"team-cli data queries view-pipeline <queryId>"),$=await N({service:"data",query:`query ($aggregationQueryId: String) {
434
+ }`,variables:{aggregationQueryId:i}})).aggregationQuery}async function ai(o){K();let i=k(o,"team-cli data queries view-pipeline <queryId>"),t=await c({service:"data",query:`query ($aggregationQueryId: String) {
52
435
  aggregationQuery(aggregationQueryId: $aggregationQueryId) {
53
436
  pipeline
54
437
  }
55
- }`,variables:{aggregationQueryId:q}});console.log($.aggregationQuery.pipeline)}async function Og(g,m){r();let q=D(g,"team-cli data queries preview <queryId> --params '<json>'"),$=Sg(m),j=await N({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
438
+ }`,variables:{aggregationQueryId:i}});return{queryId:i,pipeline:t.aggregationQuery.pipeline}}async function ci(o,i){K();let t=k(o,"team-cli data queries preview <queryId> --params '<json>'"),r=si(i),e=await c({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
56
439
  testAggregationQuery(aggregationQueryId: $aggregationQueryId, params: $params)
57
- }`,variables:{aggregationQueryId:q,params:$}});Fg(j.testAggregationQuery,m)}function Am(g){return new Promise((m)=>setTimeout(m,g))}async function Pg(g,m){r();let q=D(g,"team-cli data queries download <queryId> --params '<json>'"),$=Sg(m);if(!m.path)throw Error("--path es requerido. Ejemplo: --path resultado.xlsx");let j=m.path;console.log("Iniciando descarga...");let G=(await N({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
440
+ }`,variables:{aggregationQueryId:t,params:r}});return lt(e.testAggregationQuery)}function pt(o){return new Promise((i)=>setTimeout(i,o))}async function mi(o,i){K();let t=k(o,"team-cli data queries download <queryId> --params '<json>'"),r=si(i);if(!i.path)throw Error("--path es requerido. Ejemplo: --path resultado.xlsx");let e=i.path;$(`Iniciando descarga...
441
+ `);let n=(await c({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
58
442
  downloadAggregationQueryData(aggregationQueryId: $aggregationQueryId, params: $params)
59
- }`,variables:{aggregationQueryId:q,params:$}})).downloadAggregationQueryData;console.log(`Reporte en proceso (${G})...`);let R=null;while(!R){await Am(1000);let X=await N({service:"data",query:`query ($id: String) {
443
+ }`,variables:{aggregationQueryId:t,params:r}})).downloadAggregationQueryData;$(`Reporte en proceso (${n})...
444
+ `);let a=null;while(!a){await pt(1000);let b=await c({service:"data",query:`query ($id: String) {
60
445
  getAsyncReport(id: $id) {
61
446
  _id
62
447
  status
@@ -64,44 +449,205 @@ var yg={main:{local:"http://localhost:3000",develop:"https://api.bejusto.com",pr
64
449
  fileUrl
65
450
  }
66
451
  getAsyncReportRecordsCount(id: $id)
67
- }`,variables:{id:G}}),Z=X.getAsyncReport,_=X.getAsyncReportRecordsCount;if(Z.status==="error")throw Error("El reporte falló al generarse.");if(Z.fileUrl)R=Z.fileUrl;else{let P=Z.estimatedRecordsCount?` (~${Z.estimatedRecordsCount} registros)`:"",A=_!=null?` ${_} procesados`:"";process.stdout.write(`\rGenerando...${P}${A}`)}}process.stdout.write(`
68
- `),console.log("Descargando archivo...");let Q=await fetch(R);if(!Q.ok)throw Error(`Error descargando archivo: ${Q.status}`);let J=Buffer.from(await Q.arrayBuffer());Bm(j,J),console.log(`Archivo guardado en ${j}`)}function gg(){console.log(`
69
- team-cli data - Comandos de datos y reportes
70
-
71
- Uso:
72
- team-cli data queries <subcomando> [opciones]
73
-
74
- Subcomandos:
75
- view <queryId> Ver información de un query
76
- view-pipeline <queryId> Ver el pipeline de un query
77
- preview <queryId> Ejecutar un query de prueba (max 100 filas)
78
- download <queryId> Descargar resultado completo como Excel
79
-
80
- Opciones:
81
- --params '<json>' Parámetros del query (default: {})
82
- --format toon|json Formato de salida para view/preview (default: toon)
83
- --path <filepath> Ruta del archivo de descarga (requerido para download)
84
-
85
- Ejemplos:
86
- team-cli data queries view abc123
87
- team-cli data queries view-pipeline abc123
88
- team-cli data queries preview abc123 --params '{"startDate": "2026-01-01"}'
89
- team-cli data queries download abc123 --params '{"startDate": "2026-01-01"}' --path resultado.xlsx
90
- `)}var{positional:B,flags:w}=$g(process.argv.slice(2));if(w.env)mg(w.env);var v=B[0],F=B[1];function Hg(){let g=f(),m=g?`Sesión: ${g.email}`:"Sesión: no iniciada";console.log(`
91
- team-cli - Herramienta CLI para el equipo Justo
92
-
93
- ${m}
94
-
95
- Uso:
96
- team-cli <comando> [opciones]
97
-
98
- Comandos:
99
- auth Gestión de sesión
100
- graphql Ejecutar queries/mutations GraphQL
101
- data Datos y reportes
102
-
103
- Opciones globales:
104
- --env <local|develop|prod> Seleccionar ambiente (default: prod)
105
- --version Muestra la versión
106
- --help Muestra la ayuda
107
- `)}async function Sm(){try{if(w.version)console.log("0.0.1");else if(w.help&&!v)Hg();else if(v==="auth")if(F==="--help"||w.help)u();else if(F==="login")await Ng();else if(F==="login-with-token")await fg(w);else if(F==="request-code")await Ug(w);else if(F==="logout")await Xg();else if(F==="status")await Zg();else u();else if(v==="graphql")if(F==="--help"||w.help)e();else await Ag(B,w);else if(v==="data"){let g=B[1],m=B[2];if(w.help||F==="--help")gg();else if(g==="queries"&&m==="view")await Tg(B,w);else if(g==="queries"&&m==="view-pipeline")await zg(B,w);else if(g==="queries"&&m==="preview")await Og(B,w);else if(g==="queries"&&m==="download")await Pg(B,w);else gg()}else Hg()}catch(g){console.error(`Error: ${g instanceof Error?g.message:g}`),process.exit(1)}}Sm();
452
+ }`,variables:{id:n}}),q=b.getAsyncReport,y=b.getAsyncReportRecordsCount;if(q.status==="error")throw Error("El reporte falló al generarse.");if(q.fileUrl)a=q.fileUrl;else{let B=q.estimatedRecordsCount?` (~${q.estimatedRecordsCount} registros)`:"",x=y!=null?` ${y} procesados`:"";$(`\rGenerando...${B}${x}`)}}$(`
453
+ `),$(`Descargando archivo...
454
+ `);let u=await fetch(a);if(!u.ok)throw Error(`Error descargando archivo: ${u.status}`);let j=Buffer.from(await u.arrayBuffer());return dt(e,j),{ok:!0,queryId:t,asyncReportId:n,outputPath:e,fileUrl:a}}function go(){return`team-cli data
455
+
456
+ Comandos de datos y reportes.
457
+
458
+ Uso:
459
+ team-cli data queries <subcomando> [opciones]
460
+
461
+ Subcomandos:
462
+ view <queryId>
463
+ Ver informacion de un query.
464
+
465
+ view-pipeline <queryId>
466
+ Ver el pipeline de un query.
467
+
468
+ preview <queryId>
469
+ Ejecutar un query de prueba.
470
+ Uso: team-cli data queries preview <queryId> --params '<json>' [--format toon|json]
471
+
472
+ download <queryId>
473
+ Descargar resultado completo como Excel.
474
+ Uso: team-cli data queries download <queryId> --path <filepath> [--params '<json>'] [--format toon|json]
475
+
476
+ Opciones:
477
+ --params '<json>' Parametros del query. Default: {}
478
+ --format <toon|json>
479
+ --path <filepath> Requerido para download
480
+
481
+ Ejemplos:
482
+ team-cli data queries view abc123
483
+ team-cli data queries view-pipeline abc123
484
+ team-cli data queries preview abc123 --params '{"startDate": "2026-01-01"}'
485
+ team-cli data queries download abc123 --params '{"startDate": "2026-01-01"}' --path resultado.xlsx`}var wt=["local","develop","prod"];function ui(){return Object.keys(Y)}function ft(){return ui().map((o)=>{return[`- \`${o}\``,...wt.map((t)=>{let r=Y[o][t];return` - ${t}: \`${r}/graphql\``})].join(`
486
+ `)}).join(`
487
+ `)}function bt(){let i=ui().join(", "),t=ft();return`# @getjusto/team-cli
488
+
489
+ CLI tool for Justo team members. Authenticated access to Justo's GraphQL services and data queries.
490
+
491
+ ## Prerequisites
492
+
493
+ The CLI must be authenticated. Check with:
494
+ \`\`\`bash
495
+ npx @getjusto/team-cli auth status
496
+ \`\`\`
497
+
498
+ If not logged in, the user must log in interactively (you cannot do this):
499
+ \`\`\`bash
500
+ npx @getjusto/team-cli auth login
501
+ \`\`\`
502
+
503
+ ## Global Options
504
+
505
+ - \`--env <local|develop|prod>\` — Environment (default: prod)
506
+ - \`--format toon|json\` — Output format (default: toon)
507
+
508
+ ## Commands
509
+
510
+ ### graphql — Run arbitrary GraphQL queries/mutations
511
+
512
+ \`\`\`bash
513
+ npx @getjusto/team-cli graphql <service> '<query>' [--variables '<json>'] [--format toon|json]
514
+ \`\`\`
515
+
516
+ Available services: ${i}.
517
+
518
+ Examples:
519
+ \`\`\`bash
520
+ npx @getjusto/team-cli graphql main 'query { me { _id roles } }'
521
+ npx @getjusto/team-cli graphql main 'query($id: ID) { user(userId: $id) { _id } }' --variables '{"id": "abc123"}'
522
+ npx @getjusto/team-cli graphql tabs 'query { tab(tabId: "t123") { _id status } }' --format json
523
+ \`\`\`
524
+
525
+ ### GraphQL Service Map
526
+
527
+ Use this when someone shares a GraphQL \`curl\` and you need to map the URL to the correct \`team-cli graphql <service>\` value.
528
+
529
+ Rule:
530
+ - If the curl points to \`https://something/.../graphql\`, match that URL against the list below and use the corresponding service name.
531
+ - In \`team-cli\`, you pass the service name only, not the full URL.
532
+
533
+ Service name to endpoint map:
534
+ ${t}
535
+
536
+ Example conversion:
537
+ \`\`\`bash
538
+ # curl
539
+ curl 'https://tabs.service.getjusto.com/graphql' \\
540
+ -H 'content-type: application/json' \\
541
+ --data-raw '{"query":"query { tab(tabId: \\"t123\\") { _id status } }"}'
542
+
543
+ # team-cli
544
+ npx @getjusto/team-cli graphql tabs 'query { tab(tabId: "t123") { _id status } }'
545
+ \`\`\`
546
+
547
+ ### admin search — Search websites/brands in admin
548
+
549
+ Use this when you need to find a website first before calling other admin commands.
550
+
551
+ \`\`\`bash
552
+ npx @getjusto/team-cli admin search <text> [--limit <n>] [--page <n>] [--only-active true|false]
553
+ \`\`\`
554
+
555
+ What it returns:
556
+ - \`_id\`
557
+ - \`name\`
558
+ - \`active\`
559
+ - \`baseURL\`
560
+ - \`domain\`
561
+ - \`countryCode\`
562
+ - \`timezone\`
563
+
564
+ Typical use:
565
+ 1. Search the brand/site by name fragment.
566
+ 2. Take either the returned \`_id\` or a known domain/baseURL.
567
+ 3. Use that value in \`team-cli admin <websiteId|domain> ...\`.
568
+
569
+ Examples:
570
+ \`\`\`bash
571
+ # find the website
572
+ npx @getjusto/team-cli admin search milas --limit 5
573
+
574
+ # then use the returned website id
575
+ npx @getjusto/team-cli admin YRZjQ7L6whxfkezmF show
576
+ npx @getjusto/team-cli admin YRZjQ7L6whxfkezmF stores list
577
+ npx @getjusto/team-cli admin YRZjQ7L6whxfkezmF coupons list
578
+
579
+ # or use a domain directly
580
+ npx @getjusto/team-cli admin www.masmilas.com show
581
+ \`\`\`
582
+
583
+ ### data queries view — View query metadata and required variables
584
+
585
+ \`\`\`bash
586
+ npx @getjusto/team-cli data queries view <queryId>
587
+ \`\`\`
588
+
589
+ Returns: _id, name, description, collection, currentVersionIndex, and variables (key, fieldType, fieldParams). Use this to understand what params a query expects before running preview or download.
590
+
591
+ ### data queries view-pipeline — View query pipeline code
592
+
593
+ \`\`\`bash
594
+ npx @getjusto/team-cli data queries view-pipeline <queryId>
595
+ \`\`\`
596
+
597
+ Returns the raw JavaScript pipeline code.
598
+
599
+ ### data queries preview — Test-run a query (max 100 rows)
600
+
601
+ \`\`\`bash
602
+ npx @getjusto/team-cli data queries preview <queryId> [--params '<json>'] [--format toon|json]
603
+ \`\`\`
604
+
605
+ Executes the query with a 100-row limit. Use this to verify results before downloading.
606
+
607
+ ### data queries download — Download full query results as Excel
608
+
609
+ \`\`\`bash
610
+ npx @getjusto/team-cli data queries download <queryId> --path <filepath> [--params '<json>']
611
+ \`\`\`
612
+
613
+ \`--path\` is required. Triggers an async report, polls until complete, then downloads the Excel file.
614
+
615
+ ## Output Format
616
+
617
+ Default output is TOON (Token-Oriented Object Notation), a compact human-readable format. Use \`--format json\` for standard JSON output.
618
+
619
+ ## Typical Workflow
620
+
621
+ 1. View a query to understand its variables: \`data queries view <id>\`
622
+ 2. Preview with params: \`data queries preview <id> --params '{"startDate": "2026-01-01"}'\`
623
+ 3. Download full data: \`data queries download <id> --params '{"startDate": "2026-01-01"}' --path output.xlsx\`
624
+ `}function gi(){return{skill:bt()}}var{positional:l,flags:m}=wo(process.argv.slice(2));if(m.env)lo(m.env);var Q=l[0],P=l[1];function di(){let o=d();return`team-cli
625
+
626
+ Herramienta CLI para el equipo Justo.
627
+
628
+ ${o?`Sesión: ${o.email}`:"Sesión: no iniciada"}
629
+
630
+ Uso:
631
+ team-cli <comando> [opciones]
632
+
633
+ Comandos:
634
+ auth
635
+ Gestión de sesión.
636
+
637
+ admin
638
+ Comandos administrativos con contexto de website.
639
+
640
+ graphql
641
+ Ejecutar queries y mutations GraphQL.
642
+
643
+ data
644
+ Datos y reportes.
645
+
646
+ get-skill
647
+ Obtener skill para usar con Claude.
648
+
649
+ Opciones globales:
650
+ --env <local|develop|prod>
651
+ --version
652
+ --help
653
+ --format <toon|json>`}async function qt(){try{let o;if(m.version)o={version:"0.0.3"};else if(m.help&&!Q){g(di());return}else if(Q==="auth")if(P==="--help"||m.help){g(co());return}else if(P==="login")o=await No();else if(P==="login-with-token")o=await Ao(m);else if(P==="request-code")o=await Oo(m);else if(P==="logout")o=await So();else if(P==="status")o=await Qo();else{g(co());return}else if(Q==="admin"){let i=l[1],t=l[2],r=l[3],e=l[4];if(!i||i==="--help"){g(H());return}else if(i==="search"&&m.help){g(Yo());return}else if(i==="search")o=await Xo(l,m);else if(!t||t==="--help"){g(H());return}else if(t==="show")o=await _o(i);else if(t==="stores"&&r==="list")o=await Zo(i);else if(t==="coupons"&&(!r||r==="--help")){g(X());return}else if(t==="coupons"&&r==="create"&&m.help){g(Vo());return}else if(t==="coupons"&&r==="update"&&m.help){g(Lo());return}else if(t==="coupons"&&r==="codes"&&l[4]==="create"&&m.help){g(ei());return}else if(t==="coupons"&&m.help){g(X());return}else if(t==="coupons"&&r==="list")o=await zo(i,m);else if(t==="coupons"&&r==="show"){if(!e)throw Error("Uso: team-cli admin <web> coupons show <couponId>");o=await Ho(i,e)}else if(t==="coupons"&&r==="create")o=await Do(i,m);else if(t==="coupons"&&r==="update"){if(!e)throw Error("Uso: team-cli admin <web> coupons update <couponId> --input '<json>'");o=await Ko(i,e,m)}else if(t==="coupons"&&r==="delete"){if(!e)throw Error("Uso: team-cli admin <web> coupons delete <couponId>");o=await ko(i,e)}else if(t==="coupons"&&r==="codes"){let s=l[4],n=l[5];if(!s||s==="--help"){g(X());return}else if(s==="list"){if(!n)throw Error("Uso: team-cli admin <web> coupons codes list <couponId>");o=await oi(i,n,m)}else if(s==="create"){if(!n)throw Error("Uso: team-cli admin <web> coupons codes create <couponId> --input '<json>'");o=await ii(i,n,m)}else if(s==="create-random"){if(!n)throw Error("Uso: team-cli admin <web> coupons codes create-random <couponId> --quantity <n>");o=await ti(i,n,m)}else if(s==="delete"){if(!n)throw Error(`Uso: team-cli admin <web> coupons codes delete <couponId> --ids '["id1"]'`);o=await ri(i,n,m)}else{g(X());return}}else{g(H());return}}else if(Q==="graphql")if(P==="--help"||m.help){g(Go());return}else o=await Bo(l,m);else if(Q==="get-skill")o=gi();else if(Q==="data"){let i=l[1],t=l[2];if(m.help||P==="--help"){g(go());return}else if(i==="queries"&&t==="view")o=await ni(l);else if(i==="queries"&&t==="view-pipeline")o=await ai(l);else if(i==="queries"&&t==="preview")o=await ci(l,m);else if(i==="queries"&&t==="download")o=await mi(l,m);else{g(go());return}}else{g(di());return}if(o!==void 0)xo(o,m)}catch(o){Eo(o,m),process.exit(1)}}qt();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getjusto/team-cli",
3
- "version": "0.0.1",
3
+ "version": "0.0.3",
4
4
  "description": "CLI tool for Justo team members",
5
5
  "type": "module",
6
6
  "bin": {