@getjusto/team-cli 0.0.3 → 0.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.js +256 -62
- package/package.json +1 -1
package/bin/cli.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
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
|
|
4
|
-
`)}function
|
|
2
|
+
var H={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"}},re="prod";function be(e){re=e}function ye(){return re}function B(e){return H[e][re]}function qe(e){let o=[],r={},t={};for(let i=0;i<e.length;i++)if(e[i].startsWith("--")&&e[i+1]&&!e[i+1].startsWith("--")){let n=e[i].slice(2);if(r[n]=e[i+1],!t[n])t[n]=[];t[n].push(e[i+1]),i++}else if(e[i].startsWith("--"))r[e[i].slice(2)]="true";else o.push(e[i]);return{positional:o,flags:r,arrayFlags:t}}function T(e,o){let r=e[o];if(!r)throw Error(`--${o} es requerido.`);return r}import{existsSync as ie,mkdirSync as vo,readFileSync as Uo,writeFileSync as Qo,unlinkSync as No}from"node:fs";import{join as Ce}from"node:path";import{homedir as Po}from"node:os";var te=Ce(Po(),".justo-team");function ne(){let e=ye(),o=e==="prod"?"credentials.json":`credentials.${e}.json`;return Ce(te,o)}function So(){if(!ie(te))vo(te,{recursive:!0})}function D(e){So(),Qo(ne(),JSON.stringify(e,null,2))}function g(){let e=ne();if(!ie(e))return null;try{let o=Uo(e,"utf-8");return JSON.parse(o)}catch{return null}}function ae(){let e=ne();if(ie(e))No(e)}import{existsSync as Ie,readFileSync as Oo,writeFileSync as Wo,mkdirSync as Go}from"node:fs";import{join as he}from"node:path";import{homedir as Jo}from"node:os";function Bo(){let e=he(Jo(),".justo-team"),o=he(e,"device-id");if(Ie(o))return Oo(o,"utf-8").trim();let r=crypto.randomUUID();if(!Ie(e))Go(e,{recursive:!0});return Wo(o,r),r}var je={required:({label:e})=>`${e} no es opcional`,notAString:({label:e})=>`${e} no es un texto`,notANumber:({label:e})=>`${e} no es un número`,notAnInteger:({label:e})=>`${e} no es un número entero`,notABoolean:({label:e})=>`${e} no es un valor verdadero o falso`,notAnEmail:({label:e})=>`${e} no es un email`,notAnId:({label:e})=>`${e} no es un ID válido`,notADate:({label:e})=>`${e} no es una fecha válida`,notAnArray:({label:e})=>`${e} no es un arreglo`,notAnObject:({label:e})=>`${e} no es un objeto`,stringTooShort:({label:e})=>`${e} no tiene el largo suficiente`,stringTooLong:"El largo es mayor al permitido",numberTooSmall:({label:e})=>`${e} es un número muy pequeño`,numberTooBig:({label:e})=>`${e} es un número muy grande`,notInSchema:({label:e})=>`${e} no esta permitido`,notUnique:({label:e})=>`${e} no es único`,notFound:({label:e})=>`${e} 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 To(e,o){let r=je[e];if(!r)return`${o}: ${e}`;if(typeof r==="function")return r({label:o});return r}function $e(e){return Object.entries(e).map(([o,r])=>To(r,o)).join(", ")}function _o(e){if(e.error==="validationError"&&e.validationErrors)return $e(e.validationErrors);if(e.extensions?.code==="PermissionsError"){let i=e.extensions.info?.type;if(i?.includes("User doesn't have permissions for "))return`Tu usuario no tiene permisos para [${i.split("User doesn't have permissions for ")[1]}]`;return e.message}if(e.validationErrors)return`${e.message} (${$e(e.validationErrors)})`;let o=e.message||"Error desconocido",r=je[o];if(r)return typeof r==="function"?r({label:""}).trim():r;let t=e.error||e.code||e.type;return t?`${o} [${t}]`:o}function Fo(e){try{return JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()).exp*1000<Date.now()}catch{return!0}}async function Mo(){let e=g();if(!e?.refreshToken)return null;let o=`${B("auth")}/refresh-token`,t=await(await fetch(o,{method:"POST",headers:{"X-ORION-REFRESH":e.refreshToken}})).json();if(!t.token)return null;return D({...e,token:t.token}),t.token}async function Xo(){let e=g();if(!e?.token)return;if(!Fo(e.token))return e.token;return await Mo()??void 0}async function c(e){let o=`${B(e.service)}/graphql`,r=await Xo(),t={"Content-Type":"application/json","X-ORION-DEVICEID":Bo(),"X-ORION-PLATFORM":"web"};if(r)t["x-orion-jwt"]=r;let i;try{i=await fetch(o,{method:"POST",headers:t,body:JSON.stringify({query:e.query,variables:e.variables}),signal:AbortSignal.timeout(15000)})}catch{throw Error("La solicitud tardó demasiado. Intenta de nuevo.")}let n=await i.json();if(n.errors?.length)throw Error(_o(n.errors[0]));if(!n.data)throw Error("No data returned from server");return n.data}import{createInterface as Yo}from"node:readline";function _(e){let o=Yo({input:process.stdin,output:process.stderr});return new Promise((r)=>{o.question(e,(t)=>{o.close(),r(t.trim())})})}var Zo={comma:",",tab:"\t",pipe:"|"},Y=Zo.comma;function Ae(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}function zo(e){return e==="true"||e==="false"||e==="null"}function h(e){if(e===null)return null;if(typeof e==="object"&&e!==null&&"toJSON"in e&&typeof e.toJSON==="function"){let o=e.toJSON();if(o!==e)return h(o)}if(typeof e==="string"||typeof e==="boolean")return e;if(typeof e==="number"){if(Object.is(e,-0))return 0;if(!Number.isFinite(e))return null;return e}if(typeof e==="bigint"){if(e>=Number.MIN_SAFE_INTEGER&&e<=Number.MAX_SAFE_INTEGER)return Number(e);return e.toString()}if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(h);if(e instanceof Set)return Array.from(e).map(h);if(e instanceof Map)return Object.fromEntries(Array.from(e,([o,r])=>[String(o),h(r)]));if(Ho(e)){let o={};for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r))o[r]=h(e[r]);return o}return null}function U(e){return e===null||typeof e==="string"||typeof e==="number"||typeof e==="boolean"}function A(e){return Array.isArray(e)}function b(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function F(e){return Object.keys(e).length===0}function Ho(e){if(e===null||typeof e!=="object")return!1;let o=Object.getPrototypeOf(e);return o===null||o===Object.prototype}function M(e){return e.length===0||e.every((o)=>U(o))}function Do(e){return e.length===0||e.every((o)=>A(o))}function xe(e){return e.length===0||e.every((o)=>b(o))}function ko(e){return/^[A-Z_][\w.]*$/i.test(e)}function Ko(e){return/^[A-Z_]\w*$/i.test(e)}function Vo(e,o=Y){if(!e)return!1;if(e!==e.trim())return!1;if(zo(e)||Lo(e))return!1;if(e.includes(":"))return!1;if(e.includes('"')||e.includes("\\"))return!1;if(/[[\]{}]/.test(e))return!1;if(/[\n\r\t]/.test(e))return!1;if(e.includes(o))return!1;if(e.startsWith("-"))return!1;return!0}function Lo(e){return/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(e)||/^0\d+$/.test(e)}var nt=Symbol("quotedKey");function er(e,o,r,t,i,n,a){if(t.keyFolding!=="safe")return;if(!b(o))return;let{segments:s,tail:u,leafValue:f}=or(e,o,a??t.flattenDepth);if(s.length<2)return;if(!s.every((E)=>Ko(E)))return;let p=rr(s),v=n?`${n}.${p}`:p;if(r.includes(p))return;if(i&&i.has(v))return;return{foldedKey:p,remainder:u,leafValue:f,segmentCount:s.length}}function or(e,o,r){let t=[e],i=o;while(t.length<r){if(!b(i))break;let n=Object.keys(i);if(n.length!==1)break;let a=n[0],s=i[a];t.push(a),i=s}if(!b(i)||F(i))return{segments:t,tail:void 0,leafValue:i};return{segments:t,tail:i,leafValue:i}}function rr(e){return e.join(".")}function S(e,o){if(e===null)return"null";if(typeof e==="boolean")return String(e);if(typeof e==="number")return String(e);return tr(e,o)}function tr(e,o=Y){if(Vo(e,o))return e;return`"${Ae(e)}"`}function X(e){if(ko(e))return e;return`"${Ae(e)}"`}function Re(e,o=Y){return e.map((r)=>S(r,o)).join(o)}function $(e,o){let r=o?.key,t=o?.fields,i=o?.delimiter??",",n="";if(r)n+=X(r);if(n+=`[${e}${i!==Y?i:""}]`,t){let a=t.map((s)=>X(s));n+=`{${a.join(i)}}`}return n+=":",n}function*ir(e,o,r){if(U(e)){let t=S(e,o.delimiter);if(t!=="")yield t;return}if(A(e))yield*se(void 0,e,r,o);else if(b(e))yield*P(e,r,o)}function*P(e,o,r,t,i,n){let a=Object.keys(e);if(o===0&&!t)t=new Set(a.filter((u)=>u.includes(".")));let s=n??r.flattenDepth;for(let[u,f]of Object.entries(e))yield*nr(u,f,o,r,a,t,i,s)}function*nr(e,o,r,t,i,n,a,s){let u=a?`${a}.${e}`:e,f=s??t.flattenDepth;if(t.keyFolding==="safe"&&i){let v=er(e,o,i,t,n,a,f);if(v){let{foldedKey:E,remainder:J,leafValue:N,segmentCount:Ao}=v,oe=X(E);if(J===void 0){if(U(N)){yield w(r,`${oe}: ${S(N,t.delimiter)}`,t.indent);return}else if(A(N)){yield*se(E,N,r,t);return}else if(b(N)&&F(N)){yield w(r,`${oe}:`,t.indent);return}}if(b(J)){yield w(r,`${oe}:`,t.indent);let xo=f-Ao,Ro=a?`${a}.${E}`:E;yield*P(J,r+1,t,n,Ro,xo);return}}}let p=X(e);if(U(o))yield w(r,`${p}: ${S(o,t.delimiter)}`,t.indent);else if(A(o))yield*se(e,o,r,t);else if(b(o)){if(yield w(r,`${p}:`,t.indent),!F(o))yield*P(o,r+1,t,n,u,f)}}function*se(e,o,r,t){if(o.length===0){yield w(r,$(0,{key:e,delimiter:t.delimiter}),t.indent);return}if(M(o)){yield w(r,K(o,t.delimiter,e),t.indent);return}if(Do(o)){if(o.every((i)=>M(i))){yield*ar(e,o,r,t);return}}if(xe(o)){let i=ve(o);if(i)yield*sr(e,o,i,r,t);else yield*Ee(e,o,r,t);return}yield*Ee(e,o,r,t)}function*ar(e,o,r,t){yield w(r,$(o.length,{key:e,delimiter:t.delimiter}),t.indent);for(let i of o)if(M(i)){let n=K(i,t.delimiter);yield C(r+1,n,t.indent)}}function K(e,o,r){let t=$(e.length,{key:r,delimiter:o}),i=Re(e,o);if(e.length===0)return t;return`${t} ${i}`}function*sr(e,o,r,t,i){yield w(t,$(o.length,{key:e,fields:r,delimiter:i.delimiter}),i.indent),yield*Ue(o,r,t+1,i)}function ve(e){if(e.length===0)return;let o=e[0],r=Object.keys(o);if(r.length===0)return;if(cr(e,r))return r}function cr(e,o){for(let r of e){if(Object.keys(r).length!==o.length)return!1;for(let t of o){if(!(t in r))return!1;if(!U(r[t]))return!1}}return!0}function*Ue(e,o,r,t){for(let i of e)yield w(r,Re(o.map((n)=>i[n]),t.delimiter),t.indent)}function*Ee(e,o,r,t){yield w(r,$(o.length,{key:e,delimiter:t.delimiter}),t.indent);for(let i of o)yield*ce(i,r+1,t)}function*mr(e,o,r){if(F(e)){yield w(o,"-",r.indent);return}let t=Object.entries(e),[i,n]=t[0],a=t.slice(1);if(A(n)&&xe(n)){let u=ve(n);if(u){if(yield C(o,$(n.length,{key:i,fields:u,delimiter:r.delimiter}),r.indent),yield*Ue(n,u,o+2,r),a.length>0)yield*P(Object.fromEntries(a),o+1,r);return}}let s=X(i);if(U(n))yield C(o,`${s}: ${S(n,r.delimiter)}`,r.indent);else if(A(n))if(n.length===0)yield C(o,`${s}${$(0,{delimiter:r.delimiter})}`,r.indent);else if(M(n))yield C(o,`${s}${K(n,r.delimiter)}`,r.indent);else{yield C(o,`${s}${$(n.length,{delimiter:r.delimiter})}`,r.indent);for(let u of n)yield*ce(u,o+2,r)}else if(b(n)){if(yield C(o,`${s}:`,r.indent),!F(n))yield*P(n,o+2,r)}if(a.length>0)yield*P(Object.fromEntries(a),o+1,r)}function*ce(e,o,r){if(U(e))yield C(o,S(e,r.delimiter),r.indent);else if(A(e))if(M(e))yield C(o,K(e,r.delimiter),r.indent);else{yield C(o,$(e.length,{delimiter:r.delimiter}),r.indent);for(let t of e)yield*ce(t,o+1,r)}else if(b(e))yield*mr(e,o,r)}function w(e,o,r){return" ".repeat(r*e)+o}function C(e,o,r){return w(e,"- "+o,r)}function ur(e,o){let r=o("",e,[]);if(r===void 0)return k(e,o,[]);return k(h(r),o,[])}function k(e,o,r){if(b(e))return dr(e,o,r);if(A(e))return lr(e,o,r);return e}function dr(e,o,r){let t={};for(let[i,n]of Object.entries(e)){let a=[...r,i],s=o(i,n,a);if(s===void 0)continue;t[i]=k(h(s),o,a)}return t}function lr(e,o,r){let t=[];for(let i=0;i<e.length;i++){let n=e[i],a=[...r,i],s=o(String(i),n,a);if(s===void 0)continue;let u=h(s);t.push(k(u,o,a))}return t}function me(e,o){return Array.from(gr(e,o)).join(`
|
|
3
|
+
`)}function gr(e,o){let r=h(e),t=pr(o);return ir(t.replacer?ur(r,t.replacer):r,t,0)}function pr(e){return{indent:e?.indent??2,delimiter:e?.delimiter??Y,keyFolding:e?.keyFolding??"off",flattenDepth:e?.flattenDepth??Number.POSITIVE_INFINITY,replacer:e?.replacer}}function wr(e){let o=e.format??"toon";if(o!=="toon"&&o!=="json")throw Error("--format debe ser toon o json.");return o}function Qe(e,o){if(wr(o)==="json"){console.log(JSON.stringify(e,null,2));return}console.log(me(e))}function d(e){process.stdout.write(`${e}
|
|
4
|
+
`)}function Ne(e,o){let t={ok:!1,error:e instanceof Error?e.message:String(e)};if((o.format==="json"?"json":"toon")==="json"){console.error(JSON.stringify(t,null,2));return}console.error(me(t))}function y(e){process.stderr.write(e)}async function Pe(e){return(await c({service:"auth",query:`mutation ($email: String!) {
|
|
5
5
|
requestLoginCode(email: $email)
|
|
6
|
-
}`,variables:{email:
|
|
6
|
+
}`,variables:{email:e}})).requestLoginCode}async function Se(e,o,r){let t=await c({service:"auth",query:`mutation ($email: String!, $token: String!, $code: String!) {
|
|
7
7
|
loginWithCode(email: $email, token: $token, code: $code) {
|
|
8
8
|
token
|
|
9
9
|
refreshToken
|
|
10
10
|
}
|
|
11
|
-
}`,variables:{email:
|
|
12
|
-
`);let
|
|
13
|
-
`);let
|
|
14
|
-
`);let
|
|
11
|
+
}`,variables:{email:e,token:o,code:r.toUpperCase()}});D({email:e,token:t.loginWithCode.token,refreshToken:t.loginWithCode.refreshToken}),await fr()}async function fr(){if(!(await c({service:"main",query:"query { me { roles } }"})).me?.roles?.length)throw ae(),Error("Solo miembros del equipo Justo pueden usar esta herramienta.")}async function Oe(){let e=await _("Email: ");y(`Enviando codigo de verificacion...
|
|
12
|
+
`);let o=await Pe(e);y(`Codigo enviado a tu email.
|
|
13
|
+
`);let r=await _("Codigo: ");return await Se(e,o,r),{ok:!0,authenticated:!0,email:e}}async function We(e){let o=T(e,"email"),r=T(e,"token"),t=T(e,"code");return await Se(o,r,t),{ok:!0,authenticated:!0,email:o}}async function Ge(e){let o=T(e,"email");y(`Enviando codigo de verificacion...
|
|
14
|
+
`);let r=await Pe(o);return{ok:!0,email:o,token:r,nextCommand:`npx @getjusto/team-cli auth login-with-token --email ${o} --token ${r} --code <CODIGO>`}}async function Je(){return ae(),{ok:!0,authenticated:!1}}async function Be(){let e=g();if(!e)return{authenticated:!1,loginCommand:"npx @getjusto/team-cli@latest auth login"};return{authenticated:!0,email:e.email}}function ue(){return`team-cli auth
|
|
15
15
|
|
|
16
16
|
Gestion de sesion.
|
|
17
17
|
|
|
@@ -37,23 +37,40 @@ Subcomandos:
|
|
|
37
37
|
|
|
38
38
|
login-with-token
|
|
39
39
|
Iniciar sesion sin prompts.
|
|
40
|
-
Uso: team-cli auth login-with-token --email <email> --token <token> --code <codigo>`}var
|
|
40
|
+
Uso: team-cli auth login-with-token --email <email> --token <token> --code <codigo>`}var de=["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"],Te=`
|
|
41
|
+
query ResolverInfo($name: ID!, $mutation: Boolean!) {
|
|
42
|
+
params(name: $name, mutation: $mutation) {
|
|
43
|
+
name
|
|
44
|
+
params
|
|
45
|
+
result
|
|
46
|
+
basicResultQuery
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
`;function br(e){if(!e)throw Error("Uso: team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]");if(!de.includes(e))throw Error(`Servicio "${e}" no válido. Servicios disponibles: ${de.join(", ")}`)}async function yr(e,o){let r;try{let t=await c({service:e,query:Te,variables:{name:o,mutation:!1}});return{service:e,operationName:o,operationType:"query",info:t.params}}catch(t){r=t}try{let t=await c({service:e,query:Te,variables:{name:o,mutation:!0}});return{service:e,operationName:o,operationType:"mutation",info:t.params}}catch(t){let i=r instanceof Error?r.message:"",n=t instanceof Error?t.message:"";if(i.includes('Cannot query field "params"')||n.includes('Cannot query field "params"'))throw Error(`El servicio "${e}" no expone metadata de resolvers por GraphQL.`);throw r instanceof Error?r:t}}async function _e(e,o){let r=e[1],t=e[2],i=e[2];if(!g())throw Error("Debes iniciar sesión primero. Usa: team-cli auth login");if(br(r),t==="info"){let s=e[3];if(!s)throw Error("Uso: team-cli graphql <servicio> info <queryName|mutationName> [--format toon|json]");return await yr(r,s)}if(!i)throw Error("Uso: team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]");let n;if(o.variables)try{n=JSON.parse(o.variables)}catch{throw Error("Las variables deben ser un JSON válido.")}return await c({service:r,query:i,variables:n})}function Fe(){return`team-cli graphql
|
|
41
50
|
|
|
42
51
|
Ejecutar queries y mutations GraphQL.
|
|
43
52
|
|
|
44
53
|
Uso:
|
|
45
54
|
team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]
|
|
55
|
+
team-cli graphql <servicio> info <queryName|mutationName> [--format toon|json]
|
|
46
56
|
|
|
47
57
|
Ejemplos:
|
|
48
58
|
team-cli graphql main 'query { me { _id roles } }'
|
|
49
59
|
team-cli graphql main 'query($id: ID) { user(userId: $id) { _id } }' --variables '{"id": "abc123"}'
|
|
50
60
|
team-cli graphql main 'query { me { _id } }' --format json
|
|
61
|
+
team-cli graphql main info website
|
|
62
|
+
team-cli graphql webdata info setWebsiteTheme --format json
|
|
51
63
|
|
|
52
64
|
Servicios disponibles:
|
|
53
|
-
${
|
|
65
|
+
${de.join(", ")}
|
|
66
|
+
|
|
67
|
+
Comando info:
|
|
68
|
+
Consulta la metadata publicada por OrionJS para un query o mutation.
|
|
69
|
+
Devuelve el tipo de operación, los params serializados, el resultado y un basicResultQuery.
|
|
70
|
+
Si no indicas si es query o mutation, la CLI prueba ambas automáticamente.
|
|
54
71
|
|
|
55
72
|
Formato:
|
|
56
|
-
Por defecto usa toon. Usa --format json para JSON estándar.`}function
|
|
73
|
+
Por defecto usa toon. Usa --format json para JSON estándar.`}function qr(e){return e.replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,"")}function Cr(e){return e.includes(".")||e.startsWith("http://")||e.startsWith("https://")}async function O(e){if(Cr(e)){let o=qr(e),r=await fetch(`${B("main")}/website-id/${o}`,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw Error(`No se encontro el sitio "${o}"`);let t=await r.json();if(!t.websiteId)throw Error(`No se pudo resolver el websiteId para "${o}"`);return{input:e,websiteId:t.websiteId,targetType:"domain"}}return{input:e,websiteId:e,targetType:"websiteId"}}async function Me(e){let o=await c({service:"main",query:`query ($websiteId: ID) {
|
|
57
74
|
website(websiteId: $websiteId) {
|
|
58
75
|
_id
|
|
59
76
|
name
|
|
@@ -65,7 +82,7 @@ Formato:
|
|
|
65
82
|
timezone
|
|
66
83
|
defaultMenuId
|
|
67
84
|
}
|
|
68
|
-
}`,variables:{websiteId:
|
|
85
|
+
}`,variables:{websiteId:e}});if(!o.website)throw Error(`No se encontro el website "${e}"`);return o.website}function Ir(){if(!g())throw Error("Debes iniciar sesión primero. Usa: team-cli auth login")}async function Xe(e){if(Ir(),!e)throw Error("Uso: team-cli admin <websiteId|domain> show");let o=await O(e),r=await Me(o.websiteId);return{context:o,website:r}}function V(){return`team-cli admin
|
|
69
86
|
|
|
70
87
|
Comandos administrativos con contexto de website.
|
|
71
88
|
|
|
@@ -87,7 +104,7 @@ Modulos:
|
|
|
87
104
|
|
|
88
105
|
coupons
|
|
89
106
|
Administrar cupones y sus códigos.
|
|
90
|
-
Uso: team-cli admin <websiteId|domain> coupons <accion> [opciones]`}var
|
|
107
|
+
Uso: team-cli admin <websiteId|domain> coupons <accion> [opciones]`}var Ye=`
|
|
91
108
|
availableAtPeriods
|
|
92
109
|
closedDays
|
|
93
110
|
closedUntilDate
|
|
@@ -103,7 +120,7 @@ Modulos:
|
|
|
103
120
|
fromMinute
|
|
104
121
|
toMinute
|
|
105
122
|
}
|
|
106
|
-
`,
|
|
123
|
+
`,L=`
|
|
107
124
|
_id
|
|
108
125
|
websiteId
|
|
109
126
|
name
|
|
@@ -138,13 +155,13 @@ Modulos:
|
|
|
138
155
|
requiredBINs
|
|
139
156
|
extraRequirementsForPaymentTypes
|
|
140
157
|
schedule {
|
|
141
|
-
${
|
|
158
|
+
${Ye}
|
|
142
159
|
}
|
|
143
160
|
scheduleAtUse {
|
|
144
|
-
${
|
|
161
|
+
${Ye}
|
|
145
162
|
}
|
|
146
163
|
codesCode
|
|
147
|
-
`,
|
|
164
|
+
`,Ze=`
|
|
148
165
|
_id
|
|
149
166
|
code
|
|
150
167
|
couponId
|
|
@@ -153,12 +170,12 @@ Modulos:
|
|
|
153
170
|
sentToEmail
|
|
154
171
|
totalRedemptions
|
|
155
172
|
createdAt
|
|
156
|
-
`;function
|
|
173
|
+
`;function le(){if(!g())throw Error("Debes iniciar sesión primero. Usa: team-cli auth login")}function W(e,o){let r=e[o];if(!r)throw Error(`--${o} es requerido.`);try{return JSON.parse(r)}catch{throw Error(`--${o} debe ser un JSON válido.`)}}function I(e,o){let r=e[o];if(!r)return;let t=Number.parseInt(r,10);if(Number.isNaN(t))throw Error(`--${o} debe ser un número entero.`);return t}function ze(e,o){let r=e[o];if(!r)return;if(r==="true")return!0;if(r==="false")return!1;throw Error(`--${o} debe ser true o false.`)}async function q(e){if(le(),!e)throw Error("Debes indicar <websiteId|domain>.");return O(e)}async function j(e,o){let r=await c({service:"main",query:`query ($couponId: ID) {
|
|
157
174
|
coupon(couponId: $couponId) {
|
|
158
175
|
_id
|
|
159
176
|
websiteId
|
|
160
177
|
}
|
|
161
|
-
}`,variables:{couponId:
|
|
178
|
+
}`,variables:{couponId:e}});if(!r.coupon)throw Error(`No se encontró el cupón "${e}"`);if(r.coupon.websiteId!==o)throw Error(`El cupón "${e}" no pertenece al website seleccionado.`);return r.coupon}async function He(e,o){le();let r=e[2]??o.filter;if(!r)throw Error("Debes indicar un término de búsqueda. Uso: team-cli admin search <texto>");let t=I(o,"limit"),i=I(o,"page"),n=ze(o,"only-active"),a=await c({service:"main",query:`query ($filter: String, $limit: BigInt, $page: BigInt, $onlyActiveWebsites: Boolean) {
|
|
162
179
|
websites(filter: $filter, limit: $limit, page: $page, onlyActiveWebsites: $onlyActiveWebsites) {
|
|
163
180
|
items {
|
|
164
181
|
_id
|
|
@@ -174,7 +191,7 @@ Modulos:
|
|
|
174
191
|
hasNextPage
|
|
175
192
|
hasPreviousPage
|
|
176
193
|
}
|
|
177
|
-
}`,variables:{filter:
|
|
194
|
+
}`,variables:{filter:r,limit:t,page:i,onlyActiveWebsites:n}});return{searchTerm:r,websites:a.websites.items??[],pagination:{totalCount:a.websites.totalCount??0,totalPages:a.websites.totalPages??0,hasNextPage:Boolean(a.websites.hasNextPage),hasPreviousPage:Boolean(a.websites.hasPreviousPage),page:i??1,limit:t??null}}}function De(){return`team-cli admin search
|
|
178
195
|
|
|
179
196
|
Buscar websites en admin.
|
|
180
197
|
|
|
@@ -194,7 +211,7 @@ Opciones:
|
|
|
194
211
|
Ejemplos:
|
|
195
212
|
team-cli admin search milas
|
|
196
213
|
team-cli admin search buffalo --limit 5
|
|
197
|
-
team-cli admin search pizza --only-active true`}function
|
|
214
|
+
team-cli admin search pizza --only-active true`}function hr(){if(!g())throw Error("Debes iniciar sesión primero. Usa: team-cli auth login")}function $r(e){let o=[e.address?.streetAddress,e.address?.extendedAddress,e.address?.locality].filter(Boolean);if(!o.length)return null;return o.join(", ")}async function ke(e){if(hr(),!e)throw Error("Uso: team-cli admin <websiteId|domain> stores list");let o=await O(e),t=((await c({service:"main",query:`query ($websiteId: ID) {
|
|
198
215
|
stores(websiteId: $websiteId) {
|
|
199
216
|
items {
|
|
200
217
|
_id
|
|
@@ -206,11 +223,11 @@ Ejemplos:
|
|
|
206
223
|
}
|
|
207
224
|
}
|
|
208
225
|
}
|
|
209
|
-
}`,variables:{websiteId:
|
|
210
|
-
createCoupon(${
|
|
211
|
-
${
|
|
226
|
+
}`,variables:{websiteId:o.websiteId}})).stores.items??[]).map((i)=>({_id:i._id,name:i.name,address:$r(i)})).sort((i,n)=>i.name.localeCompare(n.name,"es",{sensitivity:"base"}));return{context:o,stores:t,totalCount:t.length}}var Ke={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 jr(e){let o=Object.entries(e).filter(([,n])=>n!==void 0),r=o.map(([n])=>n).filter((n)=>!Ke[n]);if(r.length)throw Error(`Campos no soportados para create: ${r.join(", ")}`);let t=o.map(([n])=>`$${n}: ${Ke[n]}`).join(", "),i=o.map(([n])=>`${n}: $${n}`).join(", ");return`mutation (${t}) {
|
|
227
|
+
createCoupon(${i}) {
|
|
228
|
+
${L}
|
|
212
229
|
}
|
|
213
|
-
}`}async function
|
|
230
|
+
}`}async function Ve(e,o){let r=await q(e),t=I(o,"limit"),i=I(o,"page"),n=o.filter,a=await c({service:"main",query:`query ($websiteId: ID, $filter: String, $limit: BigInt, $page: BigInt) {
|
|
214
231
|
coupons(websiteId: $websiteId, filter: $filter, limit: $limit, page: $page) {
|
|
215
232
|
items {
|
|
216
233
|
_id
|
|
@@ -230,17 +247,17 @@ Ejemplos:
|
|
|
230
247
|
hasNextPage
|
|
231
248
|
hasPreviousPage
|
|
232
249
|
}
|
|
233
|
-
}`,variables:{websiteId:
|
|
250
|
+
}`,variables:{websiteId:r.websiteId,filter:n,limit:t,page:i}});return{context:r,coupons:a.coupons.items??[],pagination:{totalCount:a.coupons.totalCount??0,totalPages:a.coupons.totalPages??0,hasNextPage:Boolean(a.coupons.hasNextPage),hasPreviousPage:Boolean(a.coupons.hasPreviousPage),page:i??1,limit:t??null}}}async function Le(e,o){let r=await q(e);await j(o,r.websiteId);let t=await c({service:"main",query:`query ($couponId: ID) {
|
|
234
251
|
coupon(couponId: $couponId) {
|
|
235
|
-
${
|
|
252
|
+
${L}
|
|
236
253
|
}
|
|
237
|
-
}`,variables:{couponId:
|
|
254
|
+
}`,variables:{couponId:o}});return{context:r,coupon:t.coupon}}async function eo(e,o){let r=await q(e),t=W(o,"input");if(t.websiteId&&t.websiteId!==r.websiteId)throw Error("El websiteId del input no coincide con el website seleccionado.");let i={...t,websiteId:r.websiteId},n=jr(i),a=await c({service:"main",query:n,variables:i});return{context:r,coupon:a.createCoupon}}async function oo(e,o,r){let t=await q(e);await j(o,t.websiteId);let i=W(r,"input"),n=await c({service:"main",query:`mutation ($couponId: ID, $coupon: UpdateCouponInput) {
|
|
238
255
|
updateCoupon(couponId: $couponId, coupon: $coupon) {
|
|
239
|
-
${
|
|
256
|
+
${L}
|
|
240
257
|
}
|
|
241
|
-
}`,variables:{couponId:
|
|
258
|
+
}`,variables:{couponId:o,coupon:i}});return{context:t,coupon:n.updateCoupon}}async function ro(e,o){let r=await q(e);await j(o,r.websiteId);let t=await c({service:"main",query:`mutation ($couponsIds: [ID]) {
|
|
242
259
|
deleteCoupons(couponsIds: $couponsIds, globalCoupon: false)
|
|
243
|
-
}`,variables:{couponsIds:[
|
|
260
|
+
}`,variables:{couponsIds:[o]}});return{context:r,couponId:o,deleted:t.deleteCoupons}}function Z(){return`team-cli admin coupons
|
|
244
261
|
|
|
245
262
|
Administracion de cupones para el website seleccionado.
|
|
246
263
|
|
|
@@ -288,7 +305,7 @@ Acciones:
|
|
|
288
305
|
Uso: team-cli admin <web> coupons codes delete <couponId> --ids '["id1","id2"]'
|
|
289
306
|
|
|
290
307
|
Nota:
|
|
291
|
-
El schema actual no expone update para coupon codes.`}function
|
|
308
|
+
El schema actual no expone update para coupon codes.`}function to(){return`team-cli admin coupons create
|
|
292
309
|
|
|
293
310
|
Crea un cupón para el website seleccionado.
|
|
294
311
|
|
|
@@ -337,7 +354,7 @@ Ejemplo con schedule:
|
|
|
337
354
|
Tips:
|
|
338
355
|
Usa comillas simples afuera del JSON en shell.
|
|
339
356
|
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
|
|
357
|
+
Si necesitas el shape exacto de un cupón existente, parte con: team-cli admin <web> coupons show <couponId>`}function io(){return`team-cli admin coupons update
|
|
341
358
|
|
|
342
359
|
Actualiza un cupón existente.
|
|
343
360
|
|
|
@@ -379,23 +396,23 @@ Ejemplo reemplazando restricciones:
|
|
|
379
396
|
team-cli admin <web> coupons update <couponId> --input '{"requiresStoresIds":["store1"],"requiresPaymentTypes":["card"]}'
|
|
380
397
|
|
|
381
398
|
Tip:
|
|
382
|
-
Primero mira el cupón actual con: team-cli admin <web> coupons show <couponId>`}function
|
|
399
|
+
Primero mira el cupón actual con: team-cli admin <web> coupons show <couponId>`}function Er(e){if(!Array.isArray(e))throw Error("--input debe ser un arreglo JSON.");return e.map((o)=>{if(!o||typeof o!=="object"||typeof o.code!=="string")throw Error('Cada item de --input debe tener al menos { "code": "..." }.');if(o.userEmail!=null&&typeof o.userEmail!=="string")throw Error("userEmail debe ser string cuando viene informado.");return{code:o.code,userEmail:o.userEmail}})}function Ar(e){if(!Array.isArray(e)||e.some((o)=>typeof o!=="string"))throw Error("--ids debe ser un arreglo JSON de strings.");return e}async function no(e,o,r){let t=await q(e);await j(o,t.websiteId);let i=I(r,"limit"),n=I(r,"page"),a=r.filter,s=await c({service:"main",query:`query ($couponId: ID, $filter: String, $limit: BigInt, $page: BigInt) {
|
|
383
400
|
couponCodes(couponId: $couponId, filter: $filter, limit: $limit, page: $page) {
|
|
384
401
|
items {
|
|
385
|
-
${
|
|
402
|
+
${Ze}
|
|
386
403
|
}
|
|
387
404
|
totalCount
|
|
388
405
|
totalPages
|
|
389
406
|
hasNextPage
|
|
390
407
|
hasPreviousPage
|
|
391
408
|
}
|
|
392
|
-
}`,variables:{couponId:
|
|
409
|
+
}`,variables:{couponId:o,filter:a,limit:i,page:n}});return{context:t,couponId:o,codes:s.couponCodes.items??[],pagination:{totalCount:s.couponCodes.totalCount??0,totalPages:s.couponCodes.totalPages??0,hasNextPage:Boolean(s.couponCodes.hasNextPage),hasPreviousPage:Boolean(s.couponCodes.hasPreviousPage),page:n??1,limit:i??null}}}async function ao(e,o,r){let t=await q(e);await j(o,t.websiteId);let i=Er(W(r,"input")),n=i.some((s)=>s.userEmail),a=await c({service:"main",query:`mutation ($couponId: ID, $codesWithEmail: [CodeWithEmailInput], $useCodeWithEmail: Boolean) {
|
|
393
410
|
createCouponCodes(couponId: $couponId, codesWithEmail: $codesWithEmail, useCodeWithEmail: $useCodeWithEmail)
|
|
394
|
-
}`,variables:{couponId:
|
|
411
|
+
}`,variables:{couponId:o,codesWithEmail:i,useCodeWithEmail:n}});return{context:t,couponId:o,requestedCount:i.length,result:a.createCouponCodes}}async function so(e,o,r){let t=await q(e);await j(o,t.websiteId);let i=I(r,"quantity");if(!i)throw Error("--quantity es requerido.");let n=await c({service:"main",query:`mutation ($couponId: ID, $couponQuantity: Float, $couponCodePrefix: String) {
|
|
395
412
|
createRandomCouponCodes(couponId: $couponId, couponQuantity: $couponQuantity, couponCodePrefix: $couponCodePrefix)
|
|
396
|
-
}`,variables:{couponId:
|
|
413
|
+
}`,variables:{couponId:o,couponQuantity:i,couponCodePrefix:r.prefix}});return{context:t,couponId:o,quantity:i,prefix:r.prefix??null,result:n.createRandomCouponCodes}}async function co(e,o,r){let t=await q(e);await j(o,t.websiteId);let i=Ar(W(r,"ids")),n=await c({service:"main",query:`mutation ($couponId: ID, $couponCodesIds: [ID]) {
|
|
397
414
|
deleteCouponCodes(couponId: $couponId, couponCodesIds: $couponCodesIds, globalCoupon: false)
|
|
398
|
-
}`,variables:{couponId:
|
|
415
|
+
}`,variables:{couponId:o,couponCodesIds:i}});return{context:t,couponId:o,deleted:n.deleteCouponCodes,couponCodesIds:i}}function mo(){return`team-cli admin coupons codes create
|
|
399
416
|
|
|
400
417
|
Crea códigos explícitos para un cupón.
|
|
401
418
|
|
|
@@ -418,30 +435,96 @@ Ejemplo:
|
|
|
418
435
|
|
|
419
436
|
Notas:
|
|
420
437
|
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
|
|
438
|
+
couponId se valida contra el website seleccionado antes de ejecutar la mutation.`}import{writeFileSync as Wr}from"node:fs";import{mkdtempSync as xr,readFileSync as Rr,rmSync as vr,writeFileSync as Ur}from"node:fs";import{tmpdir as Qr}from"node:os";import{join as uo}from"node:path";import{spawnSync as Nr}from"node:child_process";function Pr(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function lo(e,o){if(e==null)return;if(!Array.isArray(e)||e.some((r)=>typeof r!=="string"))throw Error(`${o} debe ser un arreglo de strings.`);return e}function Sr(e){if(!Array.isArray(e))throw Error("variables debe ser un arreglo.");return e.map((o,r)=>{if(!o||typeof o!=="object"||Array.isArray(o))throw Error(`variables[${r}] debe ser un objeto.`);let t=o;if(typeof t.key!=="string"||!t.key)throw Error(`variables[${r}].key debe ser un string no vacío.`);if(typeof t.fieldType!=="string"||!t.fieldType)throw Error(`variables[${r}].fieldType debe ser un string no vacío.`);if(t.fieldParams!=null&&typeof t.fieldParams!=="string")throw Error(`variables[${r}].fieldParams debe ser un string.`);return{key:t.key,fieldType:t.fieldType,fieldParams:typeof t.fieldParams==="string"?t.fieldParams:void 0}})}function Or(e){if(!e||typeof e!=="object"||Array.isArray(e))throw Error("El archivo editado debe contener un objeto JSON.");let o=e;if(typeof o.name!=="string"||!o.name.trim())throw Error("name debe ser un string no vacío.");if(o.description!=null&&typeof o.description!=="string")throw Error("description debe ser un string.");if(typeof o.collection!=="string"||!o.collection.trim())throw Error("collection debe ser un string no vacío.");if(typeof o.pipeline!=="string")throw Error("pipeline debe ser un string.");return{name:o.name.trim(),description:o.description?.trim()||void 0,collection:o.collection.trim(),allowedUsersIds:lo(o.allowedUsersIds,"allowedUsersIds")??[],tags:lo(o.tags,"tags")??[],pipeline:o.pipeline,variables:Sr(o.variables)}}function go(e){let o=process.env.VISUAL||process.env.EDITOR||"vi",r=xr(uo(Qr(),"team-cli-query-")),t=uo(r,"aggregation-query.json");Ur(t,`${JSON.stringify(e,null,2)}
|
|
439
|
+
`);let i=`${o} ${Pr(t)}`,n=Nr(i,{shell:!0,stdio:"inherit"});if(n.error)throw Error(`No se pudo abrir el editor "${o}": ${n.error.message}`);if(n.status!==0)throw Error(`El editor terminó con código ${n.status}.`);try{let a=Rr(t,"utf-8");if(!a.trim())throw Error("El archivo quedó vacío.");let s;try{s=JSON.parse(a)}catch{throw Error("El archivo editado no contiene JSON válido.")}return Or(s)}finally{vr(r,{recursive:!0,force:!0})}}function x(){if(!g())throw Error("Debes iniciar sesión primero. Usa: team-cli auth login")}function Q(e,o){let r=e[3];if(!r)throw Error(`Uso: ${o}`);return r}function ee(e){if(!e.params)return{};try{return JSON.parse(e.params)}catch{throw Error("--params debe ser un JSON válido.")}}function ge(e){if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return{value:e}}}async function z(e){return(await c({service:"data",query:`query ($aggregationQueryId: String) {
|
|
422
440
|
aggregationQuery(aggregationQueryId: $aggregationQueryId) {
|
|
423
441
|
_id
|
|
424
442
|
name
|
|
425
443
|
description
|
|
426
444
|
collection
|
|
427
445
|
currentVersionIndex
|
|
446
|
+
allowedUsersIds
|
|
447
|
+
tags
|
|
448
|
+
pipeline
|
|
428
449
|
variables {
|
|
429
450
|
key
|
|
430
451
|
fieldType
|
|
431
452
|
fieldParams
|
|
432
453
|
}
|
|
433
454
|
}
|
|
434
|
-
}`,variables:{aggregationQueryId:
|
|
435
|
-
|
|
455
|
+
}`,variables:{aggregationQueryId:e}})).aggregationQuery}function po(e){return{name:e.name,description:e.description,collection:e.collection,allowedUsersIds:e.allowedUsersIds??[],tags:e.tags??[],pipeline:e.pipeline,variables:e.variables??[]}}async function pe(e,o){let r=await c({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
|
|
456
|
+
testAggregationQuery(aggregationQueryId: $aggregationQueryId, params: $params)
|
|
457
|
+
}`,variables:{aggregationQueryId:e,params:o}});return ge(r.testAggregationQuery)}async function we(e,o){await c({service:"data",query:`mutation ($aggregationQueryId: String, $aggregationQuery: UpdateAggregationQueryInput) {
|
|
458
|
+
updateAggregationQuery(
|
|
459
|
+
aggregationQueryId: $aggregationQueryId
|
|
460
|
+
aggregationQuery: $aggregationQuery
|
|
461
|
+
) {
|
|
462
|
+
_id
|
|
463
|
+
name
|
|
464
|
+
description
|
|
465
|
+
collection
|
|
466
|
+
allowedUsersIds
|
|
467
|
+
tags
|
|
468
|
+
currentVersionIndex
|
|
469
|
+
}
|
|
470
|
+
}`,variables:{aggregationQueryId:e,aggregationQuery:{name:o.name,description:o.description,collection:o.collection,allowedUsersIds:o.allowedUsersIds,tags:o.tags}}}),await c({service:"data",query:`mutation ($aggregationQueryId: String, $pipeline: String, $variables: [AggregationQueryVariableInput]) {
|
|
471
|
+
addAggregationQueryVersion(
|
|
472
|
+
aggregationQueryId: $aggregationQueryId
|
|
473
|
+
pipeline: $pipeline
|
|
474
|
+
variables: $variables
|
|
475
|
+
) {
|
|
476
|
+
_id
|
|
477
|
+
currentVersionIndex
|
|
478
|
+
}
|
|
479
|
+
}`,variables:{aggregationQueryId:e,pipeline:o.pipeline,variables:o.variables}})}async function wo(){return(await c({service:"data",query:`mutation {
|
|
480
|
+
createAggregationQuery {
|
|
481
|
+
_id
|
|
482
|
+
name
|
|
483
|
+
description
|
|
484
|
+
collection
|
|
485
|
+
currentVersionIndex
|
|
486
|
+
allowedUsersIds
|
|
487
|
+
tags
|
|
436
488
|
pipeline
|
|
489
|
+
variables {
|
|
490
|
+
key
|
|
491
|
+
fieldType
|
|
492
|
+
fieldParams
|
|
493
|
+
}
|
|
437
494
|
}
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
|
|
495
|
+
}`})).createAggregationQuery}function Gr(e){if(!Array.isArray(e))throw Error("El preview del query debe devolver un arreglo para usar AI edit.");return e}async function Jr(e){let o=await c({service:"messenger",query:`mutation generateAdminQuery(
|
|
496
|
+
$prompt: String
|
|
497
|
+
$name: String
|
|
498
|
+
$description: String
|
|
499
|
+
$fullCollectionName: String
|
|
500
|
+
$variables: [JSON]
|
|
501
|
+
$pipeline: String
|
|
502
|
+
$preview: [JSON]
|
|
503
|
+
) {
|
|
504
|
+
generateAdminQuery(
|
|
505
|
+
prompt: $prompt
|
|
506
|
+
name: $name
|
|
507
|
+
description: $description
|
|
508
|
+
fullCollectionName: $fullCollectionName
|
|
509
|
+
variables: $variables
|
|
510
|
+
pipeline: $pipeline
|
|
511
|
+
preview: $preview
|
|
512
|
+
canUseVariables: true
|
|
513
|
+
) {
|
|
514
|
+
responseText
|
|
515
|
+
fullCollectionName
|
|
516
|
+
pipeline
|
|
517
|
+
variables
|
|
518
|
+
aggregationDescription
|
|
519
|
+
aggregationName
|
|
520
|
+
}
|
|
521
|
+
}`,variables:e});if(!o.generateAdminQuery?.pipeline||!o.generateAdminQuery.fullCollectionName)throw Error("La IA no devolvió una versión válida del query.");return o.generateAdminQuery}async function fo(){return x(),await wo()}async function bo(e){x();let o=Q(e,"team-cli data queries edit <queryId>"),r=await z(o),t=go(po(r));return await we(o,t),{ok:!0,queryId:o,name:t.name,collection:t.collection}}async function yo(e,o){x();let r=Q(e,"team-cli data queries ai-edit <queryId> --prompt '<texto>' [--params '<json>']"),t=await z(r),i=o.prompt||await _("Describe los cambios para la IA: ");if(!i)throw Error("Debes indicar un prompt para AI edit.");let n=ee(o),a;if(o.params){y(`Obteniendo preview del query actual...
|
|
522
|
+
`);try{let u=await pe(r,n);a=Gr(u)}catch(u){let f=u instanceof Error?u.message:String(u);throw Error(`No se pudo obtener el preview para AI edit: ${f}`)}}y(`Generando propuesta con IA...
|
|
523
|
+
`);let s=await Jr({prompt:i,fullCollectionName:t.collection,pipeline:t.pipeline,preview:a,description:t.description,name:t.name,variables:t.variables});return await we(r,{name:t.name==="Nuevo query"?s.aggregationName||t.name:t.name,description:t.description||s.aggregationDescription,collection:s.fullCollectionName,allowedUsersIds:t.allowedUsersIds??[],tags:t.tags??[],pipeline:s.pipeline,variables:s.variables??[]}),{ok:!0,queryId:r,responseText:s.responseText,collection:s.fullCollectionName,name:s.aggregationName,description:s.aggregationDescription}}async function qo(e){x();let o=Q(e,"team-cli data queries view <queryId>");return await z(o)}async function Co(e){x();let o=Q(e,"team-cli data queries view-pipeline <queryId>"),r=await z(o);return{queryId:o,pipeline:r.pipeline}}async function Io(e,o){x();let r=Q(e,"team-cli data queries preview <queryId> --params '<json>'"),t=ee(o),i=await pe(r,t);return ge(i)}function Br(e){return new Promise((o)=>setTimeout(o,e))}async function ho(e,o){x();let r=Q(e,"team-cli data queries download <queryId> --params '<json>'"),t=ee(o);if(!o.path)throw Error("--path es requerido. Ejemplo: --path resultado.xlsx");y(`Iniciando descarga...
|
|
441
524
|
`);let n=(await c({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
|
|
442
525
|
downloadAggregationQueryData(aggregationQueryId: $aggregationQueryId, params: $params)
|
|
443
|
-
}`,variables:{aggregationQueryId:
|
|
444
|
-
`);let a=null;while(!a){await
|
|
526
|
+
}`,variables:{aggregationQueryId:r,params:t}})).downloadAggregationQueryData;y(`Reporte en proceso (${n})...
|
|
527
|
+
`);let a=null;while(!a){await Br(1000);let f=await c({service:"data",query:`query ($id: String) {
|
|
445
528
|
getAsyncReport(id: $id) {
|
|
446
529
|
_id
|
|
447
530
|
status
|
|
@@ -449,16 +532,34 @@ Notas:
|
|
|
449
532
|
fileUrl
|
|
450
533
|
}
|
|
451
534
|
getAsyncReportRecordsCount(id: $id)
|
|
452
|
-
}`,variables:{id:n}}),
|
|
453
|
-
|
|
454
|
-
`);let
|
|
535
|
+
}`,variables:{id:n}}),p=f.getAsyncReport,v=f.getAsyncReportRecordsCount;if(p.status==="error")throw Error("El reporte falló al generarse.");if(p.fileUrl)a=p.fileUrl;else{let E=p.estimatedRecordsCount?` (~${p.estimatedRecordsCount} registros)`:"",J=v!=null?` ${v} procesados`:"";y(`\rGenerando...${E}${J}`)}}y(`
|
|
536
|
+
Descargando archivo...
|
|
537
|
+
`);let s=await fetch(a);if(!s.ok)throw Error(`Error descargando archivo: ${s.status}`);let u=Buffer.from(await s.arrayBuffer());return Wr(o.path,u),{ok:!0,queryId:r,asyncReportId:n,outputPath:o.path,fileUrl:a}}function fe(){return`team-cli data
|
|
455
538
|
|
|
456
539
|
Comandos de datos y reportes.
|
|
457
540
|
|
|
541
|
+
Recomendado:
|
|
542
|
+
Si necesitas obtener data y no existe un query listo, usa create + ai-edit.
|
|
543
|
+
Flujo sugerido: create -> ai-edit -> preview -> download.
|
|
544
|
+
|
|
458
545
|
Uso:
|
|
459
546
|
team-cli data queries <subcomando> [opciones]
|
|
460
547
|
|
|
461
548
|
Subcomandos:
|
|
549
|
+
create
|
|
550
|
+
Crear un query nuevo.
|
|
551
|
+
Devuelve el _id para seguir con edit, ai-edit, view o preview.
|
|
552
|
+
|
|
553
|
+
edit <queryId>
|
|
554
|
+
Editar un query manualmente en tu editor local usando JSON.
|
|
555
|
+
Campos editables: name, description, collection, allowedUsersIds, tags, pipeline, variables.
|
|
556
|
+
El pipeline debe quedar como string con un array JavaScript válido.
|
|
557
|
+
|
|
558
|
+
ai-edit <queryId>
|
|
559
|
+
Editar un query con IA.
|
|
560
|
+
Uso: team-cli data queries ai-edit <queryId> --prompt '<texto>' [--params '<json>'] [--format toon|json]
|
|
561
|
+
Si envías --params, primero se ejecuta preview y esos resultados se adjuntan al prompt.
|
|
562
|
+
|
|
462
563
|
view <queryId>
|
|
463
564
|
Ver informacion de un query.
|
|
464
565
|
|
|
@@ -475,19 +576,26 @@ Subcomandos:
|
|
|
475
576
|
|
|
476
577
|
Opciones:
|
|
477
578
|
--params '<json>' Parametros del query. Default: {}
|
|
579
|
+
--prompt '<texto>' Prompt para ai-edit. Si no viene, se pide interactivamente.
|
|
478
580
|
--format <toon|json>
|
|
479
581
|
--path <filepath> Requerido para download
|
|
480
582
|
|
|
481
583
|
Ejemplos:
|
|
482
|
-
team-cli data queries
|
|
483
|
-
team-cli data queries
|
|
584
|
+
team-cli data queries create
|
|
585
|
+
team-cli data queries edit abc123
|
|
586
|
+
team-cli data queries ai-edit abc123 --prompt 'Filtra solo ordenes canceladas'
|
|
587
|
+
team-cli data queries ai-edit abc123 --prompt 'Ajusta el pipeline' --params '{"websiteId":"w1"}'
|
|
484
588
|
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
|
|
589
|
+
team-cli data queries download abc123 --params '{"startDate": "2026-01-01"}' --path resultado.xlsx`}var Tr=["local","develop","prod"];function $o(){return Object.keys(H)}function _r(){return $o().map((e)=>{return[`- \`${e}\``,...Tr.map((r)=>{let t=H[e][r];return` - ${r}: \`${t}/graphql\``})].join(`
|
|
486
590
|
`)}).join(`
|
|
487
|
-
`)}function
|
|
591
|
+
`)}function Fr(){let o=$o().join(", "),r=_r();return`# @getjusto/team-cli
|
|
488
592
|
|
|
489
593
|
CLI tool for Justo team members. Authenticated access to Justo's GraphQL services and data queries.
|
|
490
594
|
|
|
595
|
+
Recommended approach for data requests:
|
|
596
|
+
- if you need to obtain data and there is no existing query ready to use, prefer \`data queries create\` followed by \`data queries ai-edit\`
|
|
597
|
+
- recommended flow: \`create -> ai-edit -> preview -> download\`
|
|
598
|
+
|
|
491
599
|
## Prerequisites
|
|
492
600
|
|
|
493
601
|
The CLI must be authenticated. Check with:
|
|
@@ -513,7 +621,7 @@ npx @getjusto/team-cli auth login
|
|
|
513
621
|
npx @getjusto/team-cli graphql <service> '<query>' [--variables '<json>'] [--format toon|json]
|
|
514
622
|
\`\`\`
|
|
515
623
|
|
|
516
|
-
Available services: ${
|
|
624
|
+
Available services: ${o}.
|
|
517
625
|
|
|
518
626
|
Examples:
|
|
519
627
|
\`\`\`bash
|
|
@@ -522,6 +630,33 @@ npx @getjusto/team-cli graphql main 'query($id: ID) { user(userId: $id) { _id }
|
|
|
522
630
|
npx @getjusto/team-cli graphql tabs 'query { tab(tabId: "t123") { _id status } }' --format json
|
|
523
631
|
\`\`\`
|
|
524
632
|
|
|
633
|
+
### graphql info — Inspect query/mutation params and result metadata
|
|
634
|
+
|
|
635
|
+
Use this before writing the final GraphQL call when you only know the operation name, or when someone shares a curl and you need to understand the params expected by the resolver.
|
|
636
|
+
|
|
637
|
+
\`\`\`bash
|
|
638
|
+
npx @getjusto/team-cli graphql <service> info <queryName|mutationName> [--format toon|json]
|
|
639
|
+
\`\`\`
|
|
640
|
+
|
|
641
|
+
What it returns:
|
|
642
|
+
- \`operationType\` — whether Orion exposed it as query or mutation
|
|
643
|
+
- \`info.params\` — serialized params schema, including optional fields and GraphQL scalar types
|
|
644
|
+
- \`info.result\` — top-level result model/type name when available
|
|
645
|
+
- \`info.basicResultQuery\` — a starter field selection you can reuse in the final GraphQL document
|
|
646
|
+
|
|
647
|
+
Examples:
|
|
648
|
+
\`\`\`bash
|
|
649
|
+
npx @getjusto/team-cli graphql main info website
|
|
650
|
+
npx @getjusto/team-cli graphql auth info requestLoginCode --format json
|
|
651
|
+
\`\`\`
|
|
652
|
+
|
|
653
|
+
Recommended workflow for converting a curl into team-cli:
|
|
654
|
+
1. Identify the service from the GraphQL URL.
|
|
655
|
+
2. If you know the operation name, inspect it first with \`graphql <service> info <name>\`.
|
|
656
|
+
3. Use \`info.params\` to build the variables object.
|
|
657
|
+
4. Use \`info.basicResultQuery\` as the starting selection set.
|
|
658
|
+
5. Run the final command with \`graphql <service> '<queryOrMutation>' --variables '<json>'\`.
|
|
659
|
+
|
|
525
660
|
### GraphQL Service Map
|
|
526
661
|
|
|
527
662
|
Use this when someone shares a GraphQL \`curl\` and you need to map the URL to the correct \`team-cli graphql <service>\` value.
|
|
@@ -531,7 +666,7 @@ Rule:
|
|
|
531
666
|
- In \`team-cli\`, you pass the service name only, not the full URL.
|
|
532
667
|
|
|
533
668
|
Service name to endpoint map:
|
|
534
|
-
${
|
|
669
|
+
${r}
|
|
535
670
|
|
|
536
671
|
Example conversion:
|
|
537
672
|
\`\`\`bash
|
|
@@ -540,6 +675,9 @@ curl 'https://tabs.service.getjusto.com/graphql' \\
|
|
|
540
675
|
-H 'content-type: application/json' \\
|
|
541
676
|
--data-raw '{"query":"query { tab(tabId: \\"t123\\") { _id status } }"}'
|
|
542
677
|
|
|
678
|
+
# inspect the resolver first
|
|
679
|
+
npx @getjusto/team-cli graphql tabs info tab
|
|
680
|
+
|
|
543
681
|
# team-cli
|
|
544
682
|
npx @getjusto/team-cli graphql tabs 'query { tab(tabId: "t123") { _id status } }'
|
|
545
683
|
\`\`\`
|
|
@@ -588,6 +726,60 @@ npx @getjusto/team-cli data queries view <queryId>
|
|
|
588
726
|
|
|
589
727
|
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
728
|
|
|
729
|
+
### data queries create — Create a new admin query
|
|
730
|
+
|
|
731
|
+
\`\`\`bash
|
|
732
|
+
npx @getjusto/team-cli data queries create [--format toon|json]
|
|
733
|
+
\`\`\`
|
|
734
|
+
|
|
735
|
+
Creates a new aggregation query in the data service. The default query is usually named \`Nuevo query\` and points to \`justo.users\`. Use the returned \`_id\` with \`edit\`, \`ai-edit\`, \`view\`, \`preview\`, or \`download\`.
|
|
736
|
+
|
|
737
|
+
### data queries edit — Edit a query manually in the local editor
|
|
738
|
+
|
|
739
|
+
\`\`\`bash
|
|
740
|
+
npx @getjusto/team-cli data queries edit <queryId> [--format toon|json]
|
|
741
|
+
\`\`\`
|
|
742
|
+
|
|
743
|
+
Opens a temporary JSON document in \`$VISUAL\`, \`$EDITOR\`, or \`vi\`. The editable payload includes:
|
|
744
|
+
- \`name\`
|
|
745
|
+
- \`description\`
|
|
746
|
+
- \`collection\`
|
|
747
|
+
- \`allowedUsersIds\`
|
|
748
|
+
- \`tags\`
|
|
749
|
+
- \`pipeline\`
|
|
750
|
+
- \`variables\`
|
|
751
|
+
|
|
752
|
+
Validation rules:
|
|
753
|
+
- the file must remain valid JSON
|
|
754
|
+
- \`pipeline\` must be a string containing the JavaScript array used by the aggregation query
|
|
755
|
+
- \`variables\` must be an array of objects with \`key\`, \`fieldType\`, and optional \`fieldParams\`
|
|
756
|
+
|
|
757
|
+
Example:
|
|
758
|
+
\`\`\`bash
|
|
759
|
+
EDITOR=nvim npx @getjusto/team-cli data queries edit 69b201547b944d8cc8b7e663
|
|
760
|
+
\`\`\`
|
|
761
|
+
|
|
762
|
+
### data queries ai-edit — Edit a query with AI
|
|
763
|
+
|
|
764
|
+
\`\`\`bash
|
|
765
|
+
npx @getjusto/team-cli data queries ai-edit <queryId> --prompt '<text>' [--params '<json>'] [--format toon|json]
|
|
766
|
+
\`\`\`
|
|
767
|
+
|
|
768
|
+
Uses Messenger's \`generateAdminQuery\` flow to rewrite the collection, pipeline, variables, and, when appropriate, suggested name/description.
|
|
769
|
+
|
|
770
|
+
Notes:
|
|
771
|
+
- \`--prompt\` is required unless you want the CLI to ask interactively
|
|
772
|
+
- if you pass \`--params\`, the CLI first runs \`preview\` on the current query and sends those rows to the AI as context
|
|
773
|
+
- if preview fails, the command stops with a clear error instead of silently continuing
|
|
774
|
+
- if the AI returns an invalid response, the command fails before saving
|
|
775
|
+
|
|
776
|
+
Example:
|
|
777
|
+
\`\`\`bash
|
|
778
|
+
npx @getjusto/team-cli data queries ai-edit 69b201547b944d8cc8b7e663 \\
|
|
779
|
+
--prompt 'Show the latest created users with _id, email and createdAt' \\
|
|
780
|
+
--format json
|
|
781
|
+
\`\`\`
|
|
782
|
+
|
|
591
783
|
### data queries view-pipeline — View query pipeline code
|
|
592
784
|
|
|
593
785
|
\`\`\`bash
|
|
@@ -618,14 +810,16 @@ Default output is TOON (Token-Oriented Object Notation), a compact human-readabl
|
|
|
618
810
|
|
|
619
811
|
## Typical Workflow
|
|
620
812
|
|
|
621
|
-
1.
|
|
622
|
-
2.
|
|
623
|
-
3.
|
|
624
|
-
|
|
813
|
+
1. Create a query: \`data queries create\`
|
|
814
|
+
2. Edit it manually with \`data queries edit <id>\` or ask AI with \`data queries ai-edit <id> --prompt '...'\`
|
|
815
|
+
3. View the final metadata and pipeline: \`data queries view <id>\` and \`data queries view-pipeline <id>\`
|
|
816
|
+
4. Preview with params when needed: \`data queries preview <id> --params '{"startDate": "2026-01-01"}'\`
|
|
817
|
+
5. Download full data: \`data queries download <id> --params '{"startDate": "2026-01-01"}' --path output.xlsx\`
|
|
818
|
+
`}function jo(){return{skill:Fr()}}var{positional:l,flags:m}=qe(process.argv.slice(2));if(m.env)be(m.env);var G=l[0],R=l[1];function Eo(){let e=g();return`team-cli
|
|
625
819
|
|
|
626
820
|
Herramienta CLI para el equipo Justo.
|
|
627
821
|
|
|
628
|
-
${
|
|
822
|
+
${e?`Sesión: ${e.email}`:"Sesión: no iniciada"}
|
|
629
823
|
|
|
630
824
|
Uso:
|
|
631
825
|
team-cli <comando> [opciones]
|
|
@@ -650,4 +844,4 @@ Opciones globales:
|
|
|
650
844
|
--env <local|develop|prod>
|
|
651
845
|
--version
|
|
652
846
|
--help
|
|
653
|
-
--format <toon|json>`}async function
|
|
847
|
+
--format <toon|json>`}async function Mr(){try{let e;if(m.version)e={version:"0.0.5"};else if(m.help&&!G){d(Eo());return}else if(G==="auth")if(R==="--help"||m.help){d(ue());return}else if(R==="login")e=await Oe();else if(R==="login-with-token")e=await We(m);else if(R==="request-code")e=await Ge(m);else if(R==="logout")e=await Je();else if(R==="status")e=await Be();else{d(ue());return}else if(G==="admin"){let o=l[1],r=l[2],t=l[3],i=l[4];if(!o||o==="--help"){d(V());return}else if(o==="search"&&m.help){d(De());return}else if(o==="search")e=await He(l,m);else if(!r||r==="--help"){d(V());return}else if(r==="show")e=await Xe(o);else if(r==="stores"&&t==="list")e=await ke(o);else if(r==="coupons"&&(!t||t==="--help")){d(Z());return}else if(r==="coupons"&&t==="create"&&m.help){d(to());return}else if(r==="coupons"&&t==="update"&&m.help){d(io());return}else if(r==="coupons"&&t==="codes"&&l[4]==="create"&&m.help){d(mo());return}else if(r==="coupons"&&m.help){d(Z());return}else if(r==="coupons"&&t==="list")e=await Ve(o,m);else if(r==="coupons"&&t==="show"){if(!i)throw Error("Uso: team-cli admin <web> coupons show <couponId>");e=await Le(o,i)}else if(r==="coupons"&&t==="create")e=await eo(o,m);else if(r==="coupons"&&t==="update"){if(!i)throw Error("Uso: team-cli admin <web> coupons update <couponId> --input '<json>'");e=await oo(o,i,m)}else if(r==="coupons"&&t==="delete"){if(!i)throw Error("Uso: team-cli admin <web> coupons delete <couponId>");e=await ro(o,i)}else if(r==="coupons"&&t==="codes"){let n=l[4],a=l[5];if(!n||n==="--help"){d(Z());return}else if(n==="list"){if(!a)throw Error("Uso: team-cli admin <web> coupons codes list <couponId>");e=await no(o,a,m)}else if(n==="create"){if(!a)throw Error("Uso: team-cli admin <web> coupons codes create <couponId> --input '<json>'");e=await ao(o,a,m)}else if(n==="create-random"){if(!a)throw Error("Uso: team-cli admin <web> coupons codes create-random <couponId> --quantity <n>");e=await so(o,a,m)}else if(n==="delete"){if(!a)throw Error(`Uso: team-cli admin <web> coupons codes delete <couponId> --ids '["id1"]'`);e=await co(o,a,m)}else{d(Z());return}}else{d(V());return}}else if(G==="graphql")if(R==="--help"||m.help){d(Fe());return}else e=await _e(l,m);else if(G==="get-skill")e=jo();else if(G==="data"){let o=l[1],r=l[2];if(m.help||R==="--help"){d(fe());return}else if(o==="queries"&&r==="create")e=await fo();else if(o==="queries"&&r==="edit")e=await bo(l);else if(o==="queries"&&r==="ai-edit")e=await yo(l,m);else if(o==="queries"&&r==="view")e=await qo(l);else if(o==="queries"&&r==="view-pipeline")e=await Co(l);else if(o==="queries"&&r==="preview")e=await Io(l,m);else if(o==="queries"&&r==="download")e=await ho(l,m);else{d(fe());return}}else{d(Eo());return}if(e!==void 0)Qe(e,m)}catch(e){Ne(e,m),process.exit(1)}}Mr();
|