@getjusto/team-cli 0.0.9 → 0.0.11
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 +120 -75
- package/package.json +1 -1
package/bin/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
function ie(e){let r=[],t={},o={};for(let a=0;a<e.length;a++)if(e[a].startsWith("--")&&e[a+1]&&!e[a+1].startsWith("--")){let i=e[a].slice(2);if(t[i]=e[a+1],!o[i])o[i]=[];o[i].push(e[a+1]),a++}else if(e[a].startsWith("--"))t[e[a].slice(2)]="true";else r.push(e[a]);return{positional:r,flags:t,arrayFlags:o}}function
|
|
3
|
-
`)}function
|
|
4
|
-
`)}function
|
|
2
|
+
function ie(e){let r=[],t={},o={};for(let a=0;a<e.length;a++)if(e[a].startsWith("--")&&e[a+1]&&!e[a+1].startsWith("--")){let i=e[a].slice(2);if(t[i]=e[a+1],!o[i])o[i]=[];o[i].push(e[a+1]),a++}else if(e[a].startsWith("--"))t[e[a].slice(2)]="true";else r.push(e[a]);return{positional:r,flags:t,arrayFlags:o}}function k(e,r){let t=e[r];if(!t)throw Error(`--${r} es requerido.`);return t}var uo={comma:",",tab:"\t",pipe:"|"},V=uo.comma;function He(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}function lo(e){return e==="true"||e==="false"||e==="null"}function v(e){if(e===null)return null;if(typeof e==="object"&&e!==null&&"toJSON"in e&&typeof e.toJSON==="function"){let r=e.toJSON();if(r!==e)return v(r)}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(v);if(e instanceof Set)return Array.from(e).map(v);if(e instanceof Map)return Object.fromEntries(Array.from(e,([r,t])=>[String(r),v(t)]));if(mo(e)){let r={};for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))r[t]=v(e[t]);return r}return null}function P(e){return e===null||typeof e==="string"||typeof e==="number"||typeof e==="boolean"}function Q(e){return Array.isArray(e)}function x(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function H(e){return Object.keys(e).length===0}function mo(e){if(e===null||typeof e!=="object")return!1;let r=Object.getPrototypeOf(e);return r===null||r===Object.prototype}function Z(e){return e.length===0||e.every((r)=>P(r))}function po(e){return e.length===0||e.every((r)=>Q(r))}function Ze(e){return e.length===0||e.every((r)=>x(r))}function go(e){return/^[A-Z_][\w.]*$/i.test(e)}function fo(e){return/^[A-Z_]\w*$/i.test(e)}function wo(e,r=V){if(!e)return!1;if(e!==e.trim())return!1;if(lo(e)||bo(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(r))return!1;if(e.startsWith("-"))return!1;return!0}function bo(e){return/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(e)||/^0\d+$/.test(e)}var Oi=Symbol("quotedKey");function yo(e,r,t,o,a,i,n){if(o.keyFolding!=="safe")return;if(!x(r))return;let{segments:s,tail:c,leafValue:l}=Co(e,r,n??o.flattenDepth);if(s.length<2)return;if(!s.every((d)=>fo(d)))return;let m=qo(s),p=i?`${i}.${m}`:m;if(t.includes(m))return;if(a&&a.has(p))return;return{foldedKey:m,remainder:c,leafValue:l,segmentCount:s.length}}function Co(e,r,t){let o=[e],a=r;while(o.length<t){if(!x(a))break;let i=Object.keys(a);if(i.length!==1)break;let n=i[0],s=a[n];o.push(n),a=s}if(!x(a)||H(a))return{segments:o,tail:void 0,leafValue:a};return{segments:o,tail:a,leafValue:a}}function qo(e){return e.join(".")}function W(e,r){if(e===null)return"null";if(typeof e==="boolean")return String(e);if(typeof e==="number")return String(e);return ho(e,r)}function ho(e,r=V){if(wo(e,r))return e;return`"${He(e)}"`}function Y(e){if(go(e))return e;return`"${He(e)}"`}function Ye(e,r=V){return e.map((t)=>W(t,r)).join(r)}function j(e,r){let t=r?.key,o=r?.fields,a=r?.delimiter??",",i="";if(t)i+=Y(t);if(i+=`[${e}${a!==V?a:""}]`,o){let n=o.map((s)=>Y(s));i+=`{${n.join(a)}}`}return i+=":",i}function*xo(e,r,t){if(P(e)){let o=W(e,r.delimiter);if(o!=="")yield o;return}if(Q(e))yield*ve(void 0,e,t,r);else if(x(e))yield*J(e,t,r)}function*J(e,r,t,o,a,i){let n=Object.keys(e);if(r===0&&!o)o=new Set(n.filter((c)=>c.includes(".")));let s=i??t.flattenDepth;for(let[c,l]of Object.entries(e))yield*Io(c,l,r,t,n,o,a,s)}function*Io(e,r,t,o,a,i,n,s){let c=n?`${n}.${e}`:e,l=s??o.flattenDepth;if(o.keyFolding==="safe"&&a){let p=yo(e,r,a,o,i,n,l);if(p){let{foldedKey:d,remainder:b,leafValue:f,segmentCount:T}=p,O=Y(d);if(b===void 0){if(P(f)){yield y(t,`${O}: ${W(f,o.delimiter)}`,o.indent);return}else if(Q(f)){yield*ve(d,f,t,o);return}else if(x(f)&&H(f)){yield y(t,`${O}:`,o.indent);return}}if(x(b)){yield y(t,`${O}:`,o.indent);let U=l-T,X=n?`${n}.${d}`:d;yield*J(b,t+1,o,i,X,U);return}}}let m=Y(e);if(P(r))yield y(t,`${m}: ${W(r,o.delimiter)}`,o.indent);else if(Q(r))yield*ve(e,r,t,o);else if(x(r)){if(yield y(t,`${m}:`,o.indent),!H(r))yield*J(r,t+1,o,i,c,l)}}function*ve(e,r,t,o){if(r.length===0){yield y(t,j(0,{key:e,delimiter:o.delimiter}),o.indent);return}if(Z(r)){yield y(t,se(r,o.delimiter,e),o.indent);return}if(po(r)){if(r.every((a)=>Z(a))){yield*So(e,r,t,o);return}}if(Ze(r)){let a=Ve(r);if(a)yield*$o(e,r,a,t,o);else yield*ke(e,r,t,o);return}yield*ke(e,r,t,o)}function*So(e,r,t,o){yield y(t,j(r.length,{key:e,delimiter:o.delimiter}),o.indent);for(let a of r)if(Z(a)){let i=se(a,o.delimiter);yield $(t+1,i,o.indent)}}function se(e,r,t){let o=j(e.length,{key:t,delimiter:r}),a=Ye(e,r);if(e.length===0)return o;return`${o} ${a}`}function*$o(e,r,t,o,a){yield y(o,j(r.length,{key:e,fields:t,delimiter:a.delimiter}),a.indent),yield*Ke(r,t,o+1,a)}function Ve(e){if(e.length===0)return;let r=e[0],t=Object.keys(r);if(t.length===0)return;if(Eo(e,t))return t}function Eo(e,r){for(let t of e){if(Object.keys(t).length!==r.length)return!1;for(let o of r){if(!(o in t))return!1;if(!P(t[o]))return!1}}return!0}function*Ke(e,r,t,o){for(let a of e)yield y(t,Ye(r.map((i)=>a[i]),o.delimiter),o.indent)}function*ke(e,r,t,o){yield y(t,j(r.length,{key:e,delimiter:o.delimiter}),o.indent);for(let a of r)yield*je(a,t+1,o)}function*vo(e,r,t){if(H(e)){yield y(r,"-",t.indent);return}let o=Object.entries(e),[a,i]=o[0],n=o.slice(1);if(Q(i)&&Ze(i)){let c=Ve(i);if(c){if(yield $(r,j(i.length,{key:a,fields:c,delimiter:t.delimiter}),t.indent),yield*Ke(i,c,r+2,t),n.length>0)yield*J(Object.fromEntries(n),r+1,t);return}}let s=Y(a);if(P(i))yield $(r,`${s}: ${W(i,t.delimiter)}`,t.indent);else if(Q(i))if(i.length===0)yield $(r,`${s}${j(0,{delimiter:t.delimiter})}`,t.indent);else if(Z(i))yield $(r,`${s}${se(i,t.delimiter)}`,t.indent);else{yield $(r,`${s}${j(i.length,{delimiter:t.delimiter})}`,t.indent);for(let c of i)yield*je(c,r+2,t)}else if(x(i)){if(yield $(r,`${s}:`,t.indent),!H(i))yield*J(i,r+2,t)}if(n.length>0)yield*J(Object.fromEntries(n),r+1,t)}function*je(e,r,t){if(P(e))yield $(r,W(e,t.delimiter),t.indent);else if(Q(e))if(Z(e))yield $(r,se(e,t.delimiter),t.indent);else{yield $(r,j(e.length,{delimiter:t.delimiter}),t.indent);for(let o of e)yield*je(o,r+1,t)}else if(x(e))yield*vo(e,r,t)}function y(e,r,t){return" ".repeat(t*e)+r}function $(e,r,t){return y(e,"- "+r,t)}function jo(e,r){let t=r("",e,[]);if(t===void 0)return ne(e,r,[]);return ne(v(t),r,[])}function ne(e,r,t){if(x(e))return Ao(e,r,t);if(Q(e))return Ro(e,r,t);return e}function Ao(e,r,t){let o={};for(let[a,i]of Object.entries(e)){let n=[...t,a],s=r(a,i,n);if(s===void 0)continue;o[a]=ne(v(s),r,n)}return o}function Ro(e,r,t){let o=[];for(let a=0;a<e.length;a++){let i=e[a],n=[...t,a],s=r(String(a),i,n);if(s===void 0)continue;let c=v(s);o.push(ne(c,r,n))}return o}function Ae(e,r){return Array.from(No(e,r)).join(`
|
|
3
|
+
`)}function No(e,r){let t=v(e),o=To(r);return xo(o.replacer?jo(t,o.replacer):t,o,0)}function To(e){return{indent:e?.indent??2,delimiter:e?.delimiter??V,keyFolding:e?.keyFolding??"off",flattenDepth:e?.flattenDepth??Number.POSITIVE_INFINITY,replacer:e?.replacer}}function Oo(e){let r=e.format??"toon";if(r!=="toon"&&r!=="json")throw Error("--format debe ser toon o json.");return r}function Le(e,r){if(Oo(r)==="json"){console.log(JSON.stringify(e,null,2));return}console.log(Ae(e))}function er(e){process.stdout.write(`${e}
|
|
4
|
+
`)}function rr(e,r){let o={ok:!1,error:e instanceof Error?e.message:String(e)};if((r.format==="json"?"json":"toon")==="json"){console.error(JSON.stringify(o,null,2));return}console.error(Ae(o))}function C(e){process.stderr.write(e)}import{existsSync as le,mkdirSync as Po,readFileSync as or,writeFileSync as _o,unlinkSync as Bo}from"node:fs";import{join as ar}from"node:path";import{homedir as Jo}from"node:os";import{AsyncLocalStorage as Uo}from"node:async_hooks";var Qo=new Uo;function I(){return Qo.getStore()}var ce={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 tr(e){Re=e}function ue(){let e=process.env.JUSTO_TEAM_CLI_ENV;if(e)return e;let r=I()?.environment;if(r)return r;return Re}function q(e){return ce[e][Re]}var Ne=ar(Jo(),".justo-team");function ir(e){let r=e==="prod"?"credentials.json":`credentials.${e}.json`;return ar(Ne,r)}function Te(){return ir(ue())}function Wo(){if(!le(Ne))Po(Ne,{recursive:!0})}function me(e){let r=I();if(r&&r.canPersistCredentials===!1)throw Error("Este entorno no permite guardar credenciales.");Wo(),_o(Te(),JSON.stringify(e,null,2))}function g(){let e=process.env.JUSTO_TEAM_CLI_TOKEN,r=process.env.JUSTO_TEAM_CLI_EMAIL,t=process.env.JUSTO_TEAM_CLI_REFRESH_TOKEN;if(e&&r)return{email:r,token:e,refreshToken:t||""};let o=I()?.credentials;if(o!==void 0)return o?{email:o.email,token:o.token,refreshToken:o.refreshToken||""}:null;let a=Te();if(!le(a))return null;try{let i=or(a,"utf-8");return JSON.parse(i)}catch{return null}}function nr(e){let r=ir(e);if(!le(r))return null;try{let t=or(r,"utf-8");return JSON.parse(t)}catch{return null}}function Oe(){let e=I();if(e&&e.canPersistCredentials===!1)throw Error("Este entorno no permite borrar credenciales.");let r=Te();if(le(r))Bo(r)}import{existsSync as sr,readFileSync as Mo,writeFileSync as Go,mkdirSync as Fo}from"node:fs";import{join as cr}from"node:path";import{homedir as zo}from"node:os";function Do(){let e=process.env.JUSTO_TEAM_CLI_DEVICE_ID;if(e)return e;let r=I()?.deviceId;if(r)return r;let t=cr(zo(),".justo-team"),o=cr(t,"device-id");if(sr(o))return Mo(o,"utf-8").trim();let a=crypto.randomUUID();if(!sr(t))Fo(t,{recursive:!0});return Go(o,a),a}var lr={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 Xo(e,r){let t=lr[e];if(!t)return`${r}: ${e}`;if(typeof t==="function")return t({label:r});return t}function ur(e){return Object.entries(e).map(([r,t])=>Xo(t,r)).join(", ")}function ko(e){if(e.error==="validationError"&&e.validationErrors)return ur(e.validationErrors);if(e.extensions?.code==="PermissionsError"){let a=e.extensions.info?.type;if(a?.includes("User doesn't have permissions for "))return`Tu usuario no tiene permisos para [${a.split("User doesn't have permissions for ")[1]}]`;return e.message}if(e.validationErrors)return`${e.message} (${ur(e.validationErrors)})`;let r=e.message||"Error desconocido",t=lr[r];if(t)return typeof t==="function"?t({label:""}).trim():t;let o=e.error||e.code||e.type;return o?`${r} [${o}]`:r}function Ho(e){try{return JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()).exp*1000<Date.now()}catch{return!0}}async function Zo(){let e=g();if(!e?.refreshToken)return null;let r=`${q("auth")}/refresh-token`,o=await(await fetch(r,{method:"POST",headers:{"X-ORION-REFRESH":e.refreshToken}})).json();if(!o.token)return null;if(I()?.canPersistCredentials!==!1)me({...e,token:o.token});return o.token}async function de(){let e=g();if(!e?.token)return;if(!Ho(e.token))return e.token;return await Zo()??void 0}async function pe(e="application/json"){let r=await de(),t={"Content-Type":e,"X-ORION-DEVICEID":Do(),"X-ORION-PLATFORM":"web"};if(r)t["x-orion-jwt"]=r;return t}async function u(e){let r=`${q(e.service)}/graphql`,t=await pe(),o;try{o=await fetch(r,{method:"POST",headers:t,body:JSON.stringify({query:e.query,variables:e.variables}),signal:AbortSignal.timeout(e.timeoutMs||15000)})}catch{throw Error("La solicitud tardó demasiado. Intenta de nuevo.")}let a=await o.json();if(a.errors?.length)throw Error(ko(a.errors[0]));if(!a.data)throw Error("No data returned from server");return a.data}function Yo(e){return e.replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,"")}function Vo(e){return e.includes(".")||e.startsWith("http://")||e.startsWith("https://")}async function M(e){if(Vo(e)){let r=Yo(e),t=await fetch(`${q("main")}/website-id/${r}`,{signal:AbortSignal.timeout(1e4)});if(!t.ok)throw Error(`No se encontro el sitio "${r}"`);let o=await t.json();if(!o.websiteId)throw Error(`No se pudo resolver el websiteId para "${r}"`);return{input:e,websiteId:o.websiteId,targetType:"domain"}}return{input:e,websiteId:e,targetType:"websiteId"}}async function mr(e){let r=await u({service:"main",query:`query ($websiteId: ID) {
|
|
5
5
|
website(websiteId: $websiteId) {
|
|
6
6
|
_id
|
|
7
7
|
name
|
|
@@ -13,7 +13,7 @@ function ie(e){let r=[],t={},o={};for(let a=0;a<e.length;a++)if(e[a].startsWith(
|
|
|
13
13
|
timezone
|
|
14
14
|
defaultMenuId
|
|
15
15
|
}
|
|
16
|
-
}`,variables:{websiteId:e}});if(!r.website)throw Error(`No se encontro el website "${e}"`);return r.website}function
|
|
16
|
+
}`,variables:{websiteId:e}});if(!r.website)throw Error(`No se encontro el website "${e}"`);return r.website}function Ko(){if(!g())throw Error("Debes iniciar sesión primero. Recomendado: team-cli auth request-code --email <email> y luego team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>")}async function dr(e){if(Ko(),!e)throw Error("Uso: team-cli admin <websiteId|domain> show");let r=await M(e),t=await mr(r.websiteId);return{context:r,website:t}}function ge(){return`team-cli admin
|
|
17
17
|
|
|
18
18
|
Comandos administrativos con contexto de website.
|
|
19
19
|
|
|
@@ -35,7 +35,7 @@ Modulos:
|
|
|
35
35
|
|
|
36
36
|
coupons
|
|
37
37
|
Administrar cupones y sus códigos.
|
|
38
|
-
Uso: team-cli admin <websiteId|domain> coupons <accion> [opciones]`}var
|
|
38
|
+
Uso: team-cli admin <websiteId|domain> coupons <accion> [opciones]`}var pr=`
|
|
39
39
|
availableAtPeriods
|
|
40
40
|
closedDays
|
|
41
41
|
closedUntilDate
|
|
@@ -51,7 +51,7 @@ Modulos:
|
|
|
51
51
|
fromMinute
|
|
52
52
|
toMinute
|
|
53
53
|
}
|
|
54
|
-
`,
|
|
54
|
+
`,fe=`
|
|
55
55
|
_id
|
|
56
56
|
websiteId
|
|
57
57
|
name
|
|
@@ -86,13 +86,13 @@ Modulos:
|
|
|
86
86
|
requiredBINs
|
|
87
87
|
extraRequirementsForPaymentTypes
|
|
88
88
|
schedule {
|
|
89
|
-
${
|
|
89
|
+
${pr}
|
|
90
90
|
}
|
|
91
91
|
scheduleAtUse {
|
|
92
|
-
${
|
|
92
|
+
${pr}
|
|
93
93
|
}
|
|
94
94
|
codesCode
|
|
95
|
-
`,
|
|
95
|
+
`,gr=`
|
|
96
96
|
_id
|
|
97
97
|
code
|
|
98
98
|
couponId
|
|
@@ -101,28 +101,28 @@ Modulos:
|
|
|
101
101
|
sentToEmail
|
|
102
102
|
totalRedemptions
|
|
103
103
|
createdAt
|
|
104
|
-
`;function Ue(){if(!g())throw Error("Debes iniciar sesión primero. Recomendado: team-cli auth request-code --email <email> y luego team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>")}function G(e,r){let t=e[r];if(!t)throw Error(`--${r} es requerido.`);try{return JSON.parse(t)}catch{throw Error(`--${r} debe ser un JSON válido.`)}}function
|
|
104
|
+
`;function Ue(){if(!g())throw Error("Debes iniciar sesión primero. Recomendado: team-cli auth request-code --email <email> y luego team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>")}function G(e,r){let t=e[r];if(!t)throw Error(`--${r} es requerido.`);try{return JSON.parse(t)}catch{throw Error(`--${r} debe ser un JSON válido.`)}}function E(e,r){let t=e[r];if(!t)return;let o=Number.parseInt(t,10);if(Number.isNaN(o))throw Error(`--${r} debe ser un número entero.`);return o}function fr(e,r){let t=e[r];if(!t)return;if(t==="true")return!0;if(t==="false")return!1;throw Error(`--${r} debe ser true o false.`)}async function S(e){if(Ue(),!e)throw Error("Debes indicar <websiteId|domain>.");return M(e)}async function A(e,r){let t=await u({service:"main",query:`query ($couponId: ID) {
|
|
105
105
|
coupon(couponId: $couponId) {
|
|
106
106
|
_id
|
|
107
107
|
websiteId
|
|
108
108
|
}
|
|
109
|
-
}`,variables:{couponId:e}});if(!t.coupon)throw Error(`No se encontró el cupón "${e}"`);if(t.coupon.websiteId!==r)throw Error(`El cupón "${e}" no pertenece al website seleccionado.`);return t.coupon}function
|
|
109
|
+
}`,variables:{couponId:e}});if(!t.coupon)throw Error(`No se encontró el cupón "${e}"`);if(t.coupon.websiteId!==r)throw Error(`El cupón "${e}" no pertenece al website seleccionado.`);return t.coupon}function Lo(e){if(!Array.isArray(e))throw Error("--input debe ser un arreglo JSON.");return e.map((r)=>{if(!r||typeof r!=="object"||typeof r.code!=="string")throw Error('Cada item de --input debe tener al menos { "code": "..." }.');if(r.userEmail!=null&&typeof r.userEmail!=="string")throw Error("userEmail debe ser string cuando viene informado.");return{code:r.code,userEmail:r.userEmail}})}function ea(e){if(!Array.isArray(e)||e.some((r)=>typeof r!=="string"))throw Error("--ids debe ser un arreglo JSON de strings.");return e}async function wr(e,r,t){let o=await S(e);await A(r,o.websiteId);let a=E(t,"limit"),i=E(t,"page"),n=t.filter,s=await u({service:"main",query:`query ($couponId: ID, $filter: String, $limit: BigInt, $page: BigInt) {
|
|
110
110
|
couponCodes(couponId: $couponId, filter: $filter, limit: $limit, page: $page) {
|
|
111
111
|
items {
|
|
112
|
-
${
|
|
112
|
+
${gr}
|
|
113
113
|
}
|
|
114
114
|
totalCount
|
|
115
115
|
totalPages
|
|
116
116
|
hasNextPage
|
|
117
117
|
hasPreviousPage
|
|
118
118
|
}
|
|
119
|
-
}`,variables:{couponId:r,filter:n,limit:a,page:i}});return{context:o,couponId:r,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:i??1,limit:a??null}}}async function
|
|
119
|
+
}`,variables:{couponId:r,filter:n,limit:a,page:i}});return{context:o,couponId:r,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:i??1,limit:a??null}}}async function br(e,r,t){let o=await S(e);await A(r,o.websiteId);let a=Lo(G(t,"input")),i=a.some((s)=>s.userEmail),n=await u({service:"main",query:`mutation ($couponId: ID, $codesWithEmail: [CodeWithEmailInput], $useCodeWithEmail: Boolean) {
|
|
120
120
|
createCouponCodes(couponId: $couponId, codesWithEmail: $codesWithEmail, useCodeWithEmail: $useCodeWithEmail)
|
|
121
|
-
}`,variables:{couponId:r,codesWithEmail:a,useCodeWithEmail:i}});return{context:o,couponId:r,requestedCount:a.length,result:n.createCouponCodes}}async function
|
|
121
|
+
}`,variables:{couponId:r,codesWithEmail:a,useCodeWithEmail:i}});return{context:o,couponId:r,requestedCount:a.length,result:n.createCouponCodes}}async function yr(e,r,t){let o=await S(e);await A(r,o.websiteId);let a=E(t,"quantity");if(!a)throw Error("--quantity es requerido.");let i=await u({service:"main",query:`mutation ($couponId: ID, $couponQuantity: Float, $couponCodePrefix: String) {
|
|
122
122
|
createRandomCouponCodes(couponId: $couponId, couponQuantity: $couponQuantity, couponCodePrefix: $couponCodePrefix)
|
|
123
|
-
}`,variables:{couponId:r,couponQuantity:a,couponCodePrefix:t.prefix}});return{context:o,couponId:r,quantity:a,prefix:t.prefix??null,result:i.createRandomCouponCodes}}async function
|
|
123
|
+
}`,variables:{couponId:r,couponQuantity:a,couponCodePrefix:t.prefix}});return{context:o,couponId:r,quantity:a,prefix:t.prefix??null,result:i.createRandomCouponCodes}}async function Cr(e,r,t){let o=await S(e);await A(r,o.websiteId);let a=ea(G(t,"ids")),i=await u({service:"main",query:`mutation ($couponId: ID, $couponCodesIds: [ID]) {
|
|
124
124
|
deleteCouponCodes(couponId: $couponId, couponCodesIds: $couponCodesIds, globalCoupon: false)
|
|
125
|
-
}`,variables:{couponId:r,couponCodesIds:a}});return{context:o,couponId:r,deleted:i.deleteCouponCodes,couponCodesIds:a}}function
|
|
125
|
+
}`,variables:{couponId:r,couponCodesIds:a}});return{context:o,couponId:r,deleted:i.deleteCouponCodes,couponCodesIds:a}}function qr(){return`team-cli admin coupons codes create
|
|
126
126
|
|
|
127
127
|
Crea códigos explícitos para un cupón.
|
|
128
128
|
|
|
@@ -145,11 +145,11 @@ Ejemplo:
|
|
|
145
145
|
|
|
146
146
|
Notas:
|
|
147
147
|
Si algún item trae userEmail, team-cli activa useCodeWithEmail automáticamente.
|
|
148
|
-
couponId se valida contra el website seleccionado antes de ejecutar la mutation.`}var hr={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
|
|
148
|
+
couponId se valida contra el website seleccionado antes de ejecutar la mutation.`}var hr={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 ra(e){let r=Object.entries(e).filter(([,i])=>i!==void 0),t=r.map(([i])=>i).filter((i)=>!hr[i]);if(t.length)throw Error(`Campos no soportados para create: ${t.join(", ")}`);let o=r.map(([i])=>`$${i}: ${hr[i]}`).join(", "),a=r.map(([i])=>`${i}: $${i}`).join(", ");return`mutation (${o}) {
|
|
149
149
|
createCoupon(${a}) {
|
|
150
|
-
${
|
|
150
|
+
${fe}
|
|
151
151
|
}
|
|
152
|
-
}`}async function
|
|
152
|
+
}`}async function xr(e,r){let t=await S(e),o=E(r,"limit"),a=E(r,"page"),i=r.filter,n=await u({service:"main",query:`query ($websiteId: ID, $filter: String, $limit: BigInt, $page: BigInt) {
|
|
153
153
|
coupons(websiteId: $websiteId, filter: $filter, limit: $limit, page: $page) {
|
|
154
154
|
items {
|
|
155
155
|
_id
|
|
@@ -169,17 +169,17 @@ Notas:
|
|
|
169
169
|
hasNextPage
|
|
170
170
|
hasPreviousPage
|
|
171
171
|
}
|
|
172
|
-
}`,variables:{websiteId:t.websiteId,filter:i,limit:o,page:a}});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:a??1,limit:o??null}}}async function Ir(e,r){let t=await
|
|
172
|
+
}`,variables:{websiteId:t.websiteId,filter:i,limit:o,page:a}});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:a??1,limit:o??null}}}async function Ir(e,r){let t=await S(e);await A(r,t.websiteId);let o=await u({service:"main",query:`query ($couponId: ID) {
|
|
173
173
|
coupon(couponId: $couponId) {
|
|
174
|
-
${
|
|
174
|
+
${fe}
|
|
175
175
|
}
|
|
176
|
-
}`,variables:{couponId:r}});return{context:t,coupon:o.coupon}}async function
|
|
176
|
+
}`,variables:{couponId:r}});return{context:t,coupon:o.coupon}}async function Sr(e,r){let t=await S(e),o=G(r,"input");if(o.websiteId&&o.websiteId!==t.websiteId)throw Error("El websiteId del input no coincide con el website seleccionado.");let a={...o,websiteId:t.websiteId},i=ra(a),n=await u({service:"main",query:i,variables:a});return{context:t,coupon:n.createCoupon}}async function $r(e,r,t){let o=await S(e);await A(r,o.websiteId);let a=G(t,"input"),i=await u({service:"main",query:`mutation ($couponId: ID, $coupon: UpdateCouponInput) {
|
|
177
177
|
updateCoupon(couponId: $couponId, coupon: $coupon) {
|
|
178
|
-
${
|
|
178
|
+
${fe}
|
|
179
179
|
}
|
|
180
|
-
}`,variables:{couponId:r,coupon:a}});return{context:o,coupon:i.updateCoupon}}async function
|
|
180
|
+
}`,variables:{couponId:r,coupon:a}});return{context:o,coupon:i.updateCoupon}}async function Er(e,r){let t=await S(e);await A(r,t.websiteId);let o=await u({service:"main",query:`mutation ($couponsIds: [ID]) {
|
|
181
181
|
deleteCoupons(couponsIds: $couponsIds, globalCoupon: false)
|
|
182
|
-
}`,variables:{couponsIds:[r]}});return{context:t,couponId:r,deleted:o.deleteCoupons}}function
|
|
182
|
+
}`,variables:{couponsIds:[r]}});return{context:t,couponId:r,deleted:o.deleteCoupons}}function K(){return`team-cli admin coupons
|
|
183
183
|
|
|
184
184
|
Administracion de cupones para el website seleccionado.
|
|
185
185
|
|
|
@@ -227,7 +227,7 @@ Acciones:
|
|
|
227
227
|
Uso: team-cli admin <web> coupons codes delete <couponId> --ids '["id1","id2"]'
|
|
228
228
|
|
|
229
229
|
Nota:
|
|
230
|
-
El schema actual no expone update para coupon codes.`}function
|
|
230
|
+
El schema actual no expone update para coupon codes.`}function vr(){return`team-cli admin coupons create
|
|
231
231
|
|
|
232
232
|
Crea un cupón para el website seleccionado.
|
|
233
233
|
|
|
@@ -318,7 +318,7 @@ Ejemplo reemplazando restricciones:
|
|
|
318
318
|
team-cli admin <web> coupons update <couponId> --input '{"requiresStoresIds":["store1"],"requiresPaymentTypes":["card"]}'
|
|
319
319
|
|
|
320
320
|
Tip:
|
|
321
|
-
Primero mira el cupón actual con: team-cli admin <web> coupons show <couponId>`}async function
|
|
321
|
+
Primero mira el cupón actual con: team-cli admin <web> coupons show <couponId>`}async function Ar(e,r){Ue();let t=e[2]??r.filter;if(!t)throw Error("Debes indicar un término de búsqueda. Uso: team-cli admin search <texto>");let o=E(r,"limit"),a=E(r,"page"),i=fr(r,"only-active"),n=await u({service:"main",query:`query ($filter: String, $limit: BigInt, $page: BigInt, $onlyActiveWebsites: Boolean) {
|
|
322
322
|
websites(filter: $filter, limit: $limit, page: $page, onlyActiveWebsites: $onlyActiveWebsites) {
|
|
323
323
|
items {
|
|
324
324
|
_id
|
|
@@ -334,7 +334,7 @@ Tip:
|
|
|
334
334
|
hasNextPage
|
|
335
335
|
hasPreviousPage
|
|
336
336
|
}
|
|
337
|
-
}`,variables:{filter:t,limit:o,page:a,onlyActiveWebsites:i}});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:a??1,limit:o??null}}}function
|
|
337
|
+
}`,variables:{filter:t,limit:o,page:a,onlyActiveWebsites:i}});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:a??1,limit:o??null}}}function Rr(){return`team-cli admin search
|
|
338
338
|
|
|
339
339
|
Buscar websites en admin.
|
|
340
340
|
|
|
@@ -354,7 +354,7 @@ Opciones:
|
|
|
354
354
|
Ejemplos:
|
|
355
355
|
team-cli admin search milas
|
|
356
356
|
team-cli admin search buffalo --limit 5
|
|
357
|
-
team-cli admin search pizza --only-active true`}function
|
|
357
|
+
team-cli admin search pizza --only-active true`}function ta(){if(!g())throw Error("Debes iniciar sesión primero. Recomendado: team-cli auth request-code --email <email> y luego team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>")}function oa(e){let r=[e.address?.streetAddress,e.address?.extendedAddress,e.address?.locality].filter(Boolean);if(!r.length)return null;return r.join(", ")}async function Nr(e){if(ta(),!e)throw Error("Uso: team-cli admin <websiteId|domain> stores list");let r=await M(e),o=((await u({service:"main",query:`query ($websiteId: ID) {
|
|
358
358
|
stores(websiteId: $websiteId) {
|
|
359
359
|
items {
|
|
360
360
|
_id
|
|
@@ -366,17 +366,17 @@ Ejemplos:
|
|
|
366
366
|
}
|
|
367
367
|
}
|
|
368
368
|
}
|
|
369
|
-
}`,variables:{websiteId:r.websiteId}})).stores.items??[]).map((a)=>({_id:a._id,name:a.name,address:
|
|
369
|
+
}`,variables:{websiteId:r.websiteId}})).stores.items??[]).map((a)=>({_id:a._id,name:a.name,address:oa(a)})).sort((a,i)=>a.name.localeCompare(i.name,"es",{sensitivity:"base"}));return{context:r,stores:o,totalCount:o.length}}import{createInterface as aa}from"node:readline";function F(e){if(process.env.JUSTO_TEAM_CLI_INTERACTIVE==="false")throw Error("Este entorno no soporta prompts interactivos.");if(I()?.interactive===!1)throw Error("Este entorno no soporta prompts interactivos.");let r=aa({input:process.stdin,output:process.stderr});return new Promise((t)=>{r.question(e,(o)=>{r.close(),t(o.trim())})})}async function Tr(e){return(await u({service:"auth",query:`mutation ($email: String!) {
|
|
370
370
|
requestLoginCode(email: $email)
|
|
371
|
-
}`,variables:{email:e}})).requestLoginCode}async function
|
|
371
|
+
}`,variables:{email:e}})).requestLoginCode}async function Or(e,r,t){let o=await u({service:"auth",query:`mutation ($email: String!, $token: String!, $code: String!) {
|
|
372
372
|
loginWithCode(email: $email, token: $token, code: $code) {
|
|
373
373
|
token
|
|
374
374
|
refreshToken
|
|
375
375
|
}
|
|
376
|
-
}`,variables:{email:e,token:r,code:t.toUpperCase()}});me({email:e,token:o.loginWithCode.token,refreshToken:o.loginWithCode.refreshToken}),await
|
|
377
|
-
`);let r=await
|
|
378
|
-
`);let t=await
|
|
379
|
-
`);let t=await
|
|
376
|
+
}`,variables:{email:e,token:r,code:t.toUpperCase()}});me({email:e,token:o.loginWithCode.token,refreshToken:o.loginWithCode.refreshToken}),await ia()}async function ia(){if(!(await u({service:"main",query:"query { me { roles } }"})).me?.roles?.length)throw Oe(),Error("Solo miembros del equipo Justo pueden usar esta herramienta.")}async function Ur(){let e=await F("Email: ");C(`Enviando codigo de verificacion...
|
|
377
|
+
`);let r=await Tr(e);C(`Codigo enviado a tu email.
|
|
378
|
+
`);let t=await F("Codigo: ");return await Or(e,r,t),{ok:!0,authenticated:!0,email:e}}async function Qr(e){let r=k(e,"email"),t=k(e,"token"),o=k(e,"code");return await Or(r,t,o),{ok:!0,authenticated:!0,email:r}}async function Pr(e){let r=k(e,"email");C(`Enviando codigo de verificacion...
|
|
379
|
+
`);let t=await Tr(r);return{ok:!0,email:r,token:t,nextCommand:`npx @getjusto/team-cli auth login-with-token --email ${r} --token ${t} --code <CODIGO>`}}async function _r(){return Oe(),{ok:!0,authenticated:!1}}async function Br(){let e=g();if(!e)return{authenticated:!1,loginCommand:"npx @getjusto/team-cli auth request-code --email <email>",nextCommand:"npx @getjusto/team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>"};return{authenticated:!0,email:e.email}}function Qe(){return`team-cli auth
|
|
380
380
|
|
|
381
381
|
Gestion de sesion.
|
|
382
382
|
|
|
@@ -402,7 +402,7 @@ Subcomandos:
|
|
|
402
402
|
|
|
403
403
|
login-with-token
|
|
404
404
|
Iniciar sesion sin prompts. Recomendado para agentes.
|
|
405
|
-
Uso: team-cli auth login-with-token --email <email> --token <token> --code <codigo>`}import{spawn as he}from"node:child_process";import{createServer as
|
|
405
|
+
Uso: team-cli auth login-with-token --email <email> --token <token> --code <codigo>`}import{spawn as he}from"node:child_process";import{createServer as tt}from"node:http";import{existsSync as ba,mkdirSync as ya,openSync as Ca,readFileSync as qa,rmSync as ha,writeFileSync as xa}from"node:fs";import{dirname as Ia,join as xe,resolve as ot}from"node:path";import{request as Sa}from"node:http";import{request as $a}from"node:https";import{execFileSync as na}from"node:child_process";import{existsSync as ye,mkdirSync as sa,readFileSync as Ce,readdirSync as ca,rmSync as Pe,writeFileSync as R}from"node:fs";import{basename as Fr,dirname as zr,join as w,resolve as Dr}from"node:path";var we="iUzDOAFCUx33tmT6OCea",L="VITE_JUSTO_MAP_TILER_TOKEN";function Jr(){return`import {useState, type FormEvent} from 'react'
|
|
406
406
|
import {Badge} from '@/components/ui/badge'
|
|
407
407
|
import {Button} from '@/components/ui/button'
|
|
408
408
|
import {Card, CardContent, CardDescription, CardHeader, CardTitle} from '@/components/ui/card'
|
|
@@ -420,8 +420,8 @@ import {justoCli} from '@/lib/justo'
|
|
|
420
420
|
const defaultCommand = 'auth status'
|
|
421
421
|
const queryExample = "data queries preview <queryId> --params '{\\"limit\\":10}'"
|
|
422
422
|
const mapTilerToken =
|
|
423
|
-
(import.meta.env as {${
|
|
424
|
-
'${
|
|
423
|
+
(import.meta.env as {${L}?: string}).${L} ||
|
|
424
|
+
'${we}'
|
|
425
425
|
const chartData = [
|
|
426
426
|
{day: 'Lun', sessions: 12},
|
|
427
427
|
{day: 'Mar', sessions: 18},
|
|
@@ -774,7 +774,7 @@ export async function justoStream<T = unknown>(
|
|
|
774
774
|
}
|
|
775
775
|
|
|
776
776
|
ensurePreviewWindowJusto()
|
|
777
|
-
`}function
|
|
777
|
+
`}function Mr(e){return`# ${e}
|
|
778
778
|
|
|
779
779
|
Starter de Justo Spaces generado por \`team-cli spaces init\`.
|
|
780
780
|
|
|
@@ -809,7 +809,7 @@ Tip:
|
|
|
809
809
|
- después de \`spaces init\`, haz un initial commit para fijar el scaffold base
|
|
810
810
|
- después de cada publish, haz commit para que el repo refleje exactamente lo que quedó publicado
|
|
811
811
|
- si alguien necesita ver el dashboard y no puede cargar data, comparte las queries del dashboard con \`team-cli data queries add-viewers <queryId> --emails 'persona@justo.com'\`
|
|
812
|
-
`}function
|
|
812
|
+
`}function Gr(){return`import {StrictMode} from 'react'
|
|
813
813
|
import {createRoot} from 'react-dom/client'
|
|
814
814
|
import App from './App.tsx'
|
|
815
815
|
import './index.css'
|
|
@@ -823,14 +823,14 @@ createRoot(document.getElementById('root')!).render(
|
|
|
823
823
|
</ThemeProvider>
|
|
824
824
|
</StrictMode>,
|
|
825
825
|
)
|
|
826
|
-
`}function
|
|
827
|
-
base: './',`);R(r,o)}function
|
|
828
|
-
`)}function
|
|
829
|
-
${t}`)}function
|
|
830
|
-
`),
|
|
831
|
-
`),await new Promise((i,n)=>{a.on("close",()=>i()),a.on("error",n)})}async function
|
|
832
|
-
`);let b=await
|
|
833
|
-
`);let a=`${r} ${
|
|
826
|
+
`}function be(){return process.execPath}function _(e){if(process.platform==="win32")return`${e}.cmd`;return e}var Xr=".justo-space.json";function ee(e,r,t){na(e,r,{cwd:t,stdio:"inherit",env:{...process.env,CI:"1"}})}function ua(e){if(!e)throw Error("Falta --path. Ejemplo: team-cli spaces init --path ./mi-space-app");let r=Dr(e);if(ye(r)){if(ca(r).length>0)throw Error(`La carpeta ya existe y no está vacía: ${r}`);Pe(r,{recursive:!0,force:!0})}return sa(zr(r),{recursive:!0}),r}function la(e){let r=w(e,"vite.config.ts"),t=Ce(r,"utf-8");if(t.includes("base: './'"))return;let o=t.replace("export default defineConfig({",`export default defineConfig({
|
|
827
|
+
base: './',`);R(r,o)}function ma(e){let r=w(e,"tsconfig.app.json"),o=Ce(r,"utf-8").replace('"noUnusedLocals": true,','"noUnusedLocals": false,').replace('"noUnusedParameters": true,','"noUnusedParameters": false,');R(r,o)}function da(e){let r=w(e,"package.json"),t=JSON.parse(Ce(r,"utf-8"));t.dependencies=t.dependencies||{},t.devDependencies=t.devDependencies||{},t.dependencies.leaflet="^1.9.4",t.dependencies["react-leaflet"]="^5.0.0",t.devDependencies["@types/leaflet"]="^1.9.20",t.justoSpaceApp=!0,R(r,`${JSON.stringify(t,null,2)}
|
|
828
|
+
`)}function pa(e){let r=w(e,"src","index.css"),t=Ce(r,"utf-8");if(t.includes("leaflet/dist/leaflet.css"))return;R(r,`@import "leaflet/dist/leaflet.css";
|
|
829
|
+
${t}`)}function ga(e){let r=Fr(e);R(w(e,"README.md"),Mr(r)),R(w(e,"src","App.tsx"),Jr()),R(w(e,"src","main.tsx"),Gr()),R(w(e,"src","lib","justo.ts"),Wr()),R(w(e,Xr),`${JSON.stringify({template:"react-vite-shadcn",version:1},null,2)}
|
|
830
|
+
`),Pe(w(e,".git"),{recursive:!0,force:!0})}function fa(e){ee("git",["init"],e)}function wa(e){Pe(w(e,"package-lock.json"),{force:!0})}function _e(e){let r=Dr(e);if(!ye(r))throw Error(`No existe la app del space: ${r}`);if(!ye(w(r,Xr)))throw Error("Este publish solo acepta apps creadas con team-cli spaces init. Debes apuntar al root de esa app.");return r}function kr(e){let r=_e(e);ee(_("yarn"),["build"],r);let t=w(r,"dist");if(!ye(w(t,"index.html")))throw Error("El build no generó dist/index.html");return t}function Hr(e){let r=ua(e),t=zr(r),o=Fr(r);return ee(_("npx"),["shadcn@latest","init","-t","vite","-d","-y","-n",o],t),ee(_("npx"),["shadcn@latest","add","-a","-y"],r),wa(r),da(r),ee(_("yarn"),["install"],r),la(r),ma(r),pa(r),ga(r),fa(r),{path:r,nextSteps:[`cd ${r}`,'git add . && git commit -m "chore: initial space scaffold"',"team-cli spaces create --name '...' --description '...' --slug dashboard-1234","team-cli spaces publish <spaceId> --path .",'git add . && git commit -m "feat: update published space"']}}function Zr(e){let r=[],t="",o=null,a=!1;for(let i of e){if(a){t+=i,a=!1;continue}if(i==="\\"){a=!0;continue}if(o){if(i===o)o=null;else t+=i;continue}if(i==='"'||i==="'"){o=i;continue}if(/\s/.test(i)){if(t)r.push(t),t="";continue}t+=i}if(o)throw Error("Comando inválido: falta cerrar una comilla");if(t)r.push(t);return r}var Ea=".justo-space-preview",va="preview.json",ja=30000;function Ie(e){return xe(e,Ea)}function at(e){return xe(Ie(e),va)}function Yr(e){return xe(Ie(e),"bridge.log")}function Vr(e){return xe(Ie(e),"vite.log")}function it(e){ya(Ie(e),{recursive:!0})}function qe(e){if(!e)return;try{process.kill(e,"SIGTERM")}catch{return}}function Aa(e){if(process.platform==="darwin")return{command:"open",args:[e]};if(process.platform==="win32")return{command:"cmd",args:["/c","start","",e]};return{command:"xdg-open",args:[e]}}async function Ra(e,r){if(!r)return{attempted:!1,opened:!1};let t=Aa(e);return await new Promise((o)=>{let a=he(t.command,t.args,{stdio:"ignore",detached:!0});a.once("error",()=>{o({attempted:!0,opened:!1,message:"No se pudo abrir el navegador por defecto automáticamente. Abre la URL manualmente."})}),a.once("spawn",()=>{a.unref(),o({attempted:!0,opened:!0})})})}function Na(e){let r=at(e);if(!ba(r))return;try{let t=JSON.parse(qa(r,"utf-8"));qe(t.appPid),qe(t.bridgePid)}catch{}ha(r,{force:!0})}function Kr(){return new Promise((e,r)=>{let t=tt();t.listen(0,"127.0.0.1",()=>{let o=t.address();if(!o||typeof o==="string"){t.close(),r(Error("No se pudo obtener un puerto libre"));return}let{port:a}=o;t.close((i)=>{if(i){r(i);return}e(a)})}),t.on("error",r)})}function Lr(e){return new Promise((r)=>setTimeout(r,e))}function Ta(e){return new Promise((r,t)=>{let i=(new URL(e).protocol==="https:"?$a:Sa)(e,{method:"GET"},(n)=>{r(n.statusCode||0),n.resume()});i.on("error",t),i.end()})}async function et(e,r=ja){let t=Date.now();while(Date.now()-t<r){try{if(await Ta(e)>0)return}catch{await Lr(500);continue}await Lr(500)}throw Error(`Timeout esperando que el preview responda en ${e}`)}function Oa(e){return it(Ia(e)),Ca(e,"a")}function rt(e,r,t,o,a){let i=Oa(o),n=he(e,r,{cwd:t,detached:!0,stdio:["ignore",i,i],env:{...process.env,...a}});if(!n.pid)throw Error(`No se pudo iniciar el proceso ${e}`);return n.unref(),n.pid}function nt(){let e=nr("prod");if(!e)throw Error("Debes iniciar sesión en prod antes de usar spaces preview. Recomendado: team-cli auth request-code --email <email> y luego team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>");return e}async function Ua(e){let r=[];for await(let t of e)r.push(Buffer.isBuffer(t)?t:Buffer.from(t));return Buffer.concat(r).toString("utf-8")}function re(e,r,t){e.writeHead(r,{"Content-Type":"application/json; charset=utf-8","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Content-Type","Access-Control-Allow-Methods":"POST,OPTIONS,GET"}),e.end(JSON.stringify(t))}function Be(e){let r=e.trim(),t=new Set([0]);for(let a=0;a<r.length;a++)if(r[a]==="{"||r[a]==="[")t.add(a);let o=[...t].sort((a,i)=>i-a);for(let a of o)try{return JSON.parse(r.slice(a))}catch{continue}return r}function st(e){return{...process.env,NODE_OPTIONS:"",__JUSTO_REPL_PORT:"",JUSTO_TEAM_CLI_EMAIL:e.email,JUSTO_TEAM_CLI_TOKEN:e.token,JUSTO_TEAM_CLI_REFRESH_TOKEN:e.refreshToken,JUSTO_TEAM_CLI_INTERACTIVE:"false",JUSTO_TEAM_CLI_DEVICE_ID:"spaces-preview"}}function Qa(e,r){return{VITE_JUSTO_CLI_ENDPOINT:e,VITE_JUSTO_STREAM_ENDPOINT:r,VITE_JUSTO_CLI_MODE:"preview",[L]:we}}function Pa(e,r,t,o){return new Promise((a,i)=>{let n=he(be(),[r,"--env","prod",...o,"--format","json"],{cwd:process.cwd(),env:st(t),stdio:["ignore","pipe","pipe"]}),s="";n.stdout.on("data",(c)=>{if(!e.headersSent)e.writeHead(200,{"Content-Type":"application/x-ndjson; charset=utf-8","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Content-Type","Access-Control-Allow-Methods":"POST,OPTIONS,GET"});e.write(c)}),n.stderr.on("data",(c)=>{s+=Buffer.from(c).toString("utf-8")}),n.on("error",i),n.on("close",(c)=>{if(!c){if(!e.headersSent)e.writeHead(200,{"Content-Type":"application/x-ndjson; charset=utf-8","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Content-Type","Access-Control-Allow-Methods":"POST,OPTIONS,GET"});e.end(),a();return}let l=Be(s.trim());i(Error(l.error||s.trim()||"justoStream failed"))})})}async function ct(e){let r=Number(e.port);if(!r)throw Error("Falta --port para el bridge interno de preview");let t=nt(),o=ot(e["cli-path"]||process.argv[1]||""),a=tt(async(i,n)=>{if(i.method==="OPTIONS"){re(n,200,{ok:!0});return}if(i.method==="GET"&&i.url==="/__justo/health"){re(n,200,{ok:!0});return}if(i.method!=="POST"||i.url!=="/__justo/cli"&&i.url!=="/__justo/stream"){re(n,404,{ok:!1,error:"Not found"});return}try{let s=await Ua(i),l=JSON.parse(s||"{}").command;if(!l)throw Error("Debes indicar un comando");let m=Array.isArray(l)?l:Zr(l);if(i.url==="/__justo/stream"){await Pa(n,o,t,m);return}let p=await new Promise((d,b)=>{let f=he(be(),[o,"--env","prod",...m,"--format","json"],{cwd:process.cwd(),env:st(t),stdio:["ignore","pipe","pipe"]}),T=[],O=[];f.stdout.on("data",(U)=>T.push(Buffer.from(U))),f.stderr.on("data",(U)=>O.push(Buffer.from(U))),f.on("error",b),f.on("close",(U)=>{let X=Buffer.concat(T).toString("utf-8")||Buffer.concat(O).toString("utf-8");if(U&&U!==0){let co=Be(X);b(Error(co.error||X||"justoCli failed"));return}d(Be(X))})});re(n,200,{result:p})}catch(s){let c=s instanceof Error?s.message:"Unexpected error";re(n,400,{error:c})}});await new Promise((i,n)=>{a.listen(r,"127.0.0.1",()=>i()),a.on("error",n)}),C(`Space preview bridge listening on http://127.0.0.1:${r}
|
|
831
|
+
`),await new Promise((i,n)=>{a.on("close",()=>i()),a.on("error",n)})}async function ut(e){let r=e.path;if(!r)throw Error("Falta --path. Ejemplo: team-cli spaces preview --path ./mi-space-app");let t=_e(r);nt(),it(t),Na(t);let o=Number(e.port)||await Kr(),a=Number(e["bridge-port"])||await Kr(),i=e.open==="true",n=`http://127.0.0.1:${o}`,s=`http://127.0.0.1:${a}/__justo/cli`,c=`http://127.0.0.1:${a}/__justo/stream`,l=ot(process.argv[1]||""),m=rt(be(),[l,"__spaces-preview-bridge","--port",String(a),"--cli-path",l],process.cwd(),Yr(t),{}),p=rt(_("yarn"),["dev","--host","127.0.0.1","--port",String(o)],t,Vr(t),Qa(s,c));try{await et(`http://127.0.0.1:${a}/__justo/health`),await et(n)}catch(f){throw qe(p),qe(m),f}let d={appPid:p,bridgePid:m,previewUrl:n,bridgeUrl:s,streamUrl:c,cliEnv:"prod"};xa(at(t),`${JSON.stringify(d,null,2)}
|
|
832
|
+
`);let b=await Ra(n,i);return{ok:!0,path:t,previewUrl:n,bridgeUrl:s,streamUrl:c,cliEnv:"prod",appPid:p,bridgePid:m,logs:{app:Vr(t),bridge:Yr(t)},open:b}}import{writeFileSync as Xa}from"node:fs";import{mkdtempSync as _a,readFileSync as Ba,rmSync as Ja,writeFileSync as Wa}from"node:fs";import{tmpdir as Ma}from"node:os";import{join as lt}from"node:path";import{spawnSync as Ga}from"node:child_process";function Fa(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function mt(e,r){if(e==null)return;if(!Array.isArray(e)||e.some((t)=>typeof t!=="string"))throw Error(`${r} debe ser un arreglo de strings.`);return e}function za(e){if(!Array.isArray(e))throw Error("variables debe ser un arreglo.");return e.map((r,t)=>{if(!r||typeof r!=="object"||Array.isArray(r))throw Error(`variables[${t}] debe ser un objeto.`);let o=r;if(typeof o.key!=="string"||!o.key)throw Error(`variables[${t}].key debe ser un string no vacío.`);if(typeof o.fieldType!=="string"||!o.fieldType)throw Error(`variables[${t}].fieldType debe ser un string no vacío.`);if(o.fieldParams!=null&&typeof o.fieldParams!=="string")throw Error(`variables[${t}].fieldParams debe ser un string.`);return{key:o.key,fieldType:o.fieldType,fieldParams:typeof o.fieldParams==="string"?o.fieldParams:void 0}})}function Da(e){if(!e||typeof e!=="object"||Array.isArray(e))throw Error("El archivo editado debe contener un objeto JSON.");let r=e;if(typeof r.name!=="string"||!r.name.trim())throw Error("name debe ser un string no vacío.");if(r.description!=null&&typeof r.description!=="string")throw Error("description debe ser un string.");if(typeof r.collection!=="string"||!r.collection.trim())throw Error("collection debe ser un string no vacío.");if(typeof r.pipeline!=="string")throw Error("pipeline debe ser un string.");return{name:r.name.trim(),description:r.description?.trim()||void 0,collection:r.collection.trim(),allowedUsersIds:mt(r.allowedUsersIds,"allowedUsersIds")??[],tags:mt(r.tags,"tags")??[],pipeline:r.pipeline,variables:za(r.variables)}}function dt(e){let r=process.env.VISUAL||process.env.EDITOR||"vi",t=_a(lt(Ma(),"team-cli-query-")),o=lt(t,"aggregation-query.json");Wa(o,`${JSON.stringify(e,null,2)}
|
|
833
|
+
`);let a=`${r} ${Fa(o)}`,i=Ga(a,{shell:!0,stdio:"inherit"});if(i.error)throw Error(`No se pudo abrir el editor "${r}": ${i.error.message}`);if(i.status!==0)throw Error(`El editor terminó con código ${i.status}.`);try{let n=Ba(o,"utf-8");if(!n.trim())throw Error("El archivo quedó vacío.");let s;try{s=JSON.parse(n)}catch{throw Error("El archivo editado no contiene JSON válido.")}return Da(s)}finally{Ja(t,{recursive:!0,force:!0})}}function h(){if(!g())throw Error("Debes iniciar sesión primero. Recomendado: team-cli auth request-code --email <email> y luego team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>")}function N(e,r){let t=e[3];if(!t)throw Error(`Uso: ${r}`);return t}function z(e){if(!e.params)return{};try{return JSON.parse(e.params)}catch{throw Error("--params debe ser un JSON válido.")}}function Je(e){let r=e.limit;if(!r)throw Error("--limit es requerido. Ejemplo: --limit 1000");let t=Number(r);if(!Number.isInteger(t)||t<=0)throw Error("--limit debe ser un entero positivo.");return t}function pt(e){let r=e.emails;if(!r)throw Error("--emails es requerido. Ejemplo: --emails ana@justo.com,bob@justo.com");let t=r.split(",").map((a)=>a.trim().toLowerCase()).filter(Boolean);if(!t.length)throw Error("--emails debe contener al menos un email.");let o=t.find((a)=>!a.includes("@"));if(o)throw Error(`Email inválido: ${o}`);return[...new Set(t)]}function We(e){if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return{value:e}}}async function D(e){return(await u({service:"data",query:`query ($aggregationQueryId: String) {
|
|
834
834
|
aggregationQuery(aggregationQueryId: $aggregationQueryId) {
|
|
835
835
|
_id
|
|
836
836
|
name
|
|
@@ -854,11 +854,11 @@ ${t}`)}function la(e){let r=Gr(e);R(w(e,"README.md"),Pr(r)),R(w(e,"src","App.tsx
|
|
|
854
854
|
fullName
|
|
855
855
|
}
|
|
856
856
|
}
|
|
857
|
-
}`,variables:{filter:t,limit:10}})).justoUsers?.items?.find((i)=>i.email?.toLowerCase()===t);if(!a?._id)throw Error(`No encontramos un usuario de Justo para ${t}`);return a}))}function ft(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
|
|
857
|
+
}`,variables:{filter:t,limit:10}})).justoUsers?.items?.find((i)=>i.email?.toLowerCase()===t);if(!a?._id)throw Error(`No encontramos un usuario de Justo para ${t}`);return a}))}function ft(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 Me(e,r){let t=await u({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
|
|
858
858
|
testAggregationQuery(aggregationQueryId: $aggregationQueryId, params: $params)
|
|
859
|
-
}`,variables:{aggregationQueryId:e,params:r}});return We(t.testAggregationQuery)}function
|
|
859
|
+
}`,variables:{aggregationQueryId:e,params:r}});return We(t.testAggregationQuery)}async function wt(e){let r=await fetch(`${q("data")}/execute-pipeline`,{method:"POST",headers:await pe(),body:JSON.stringify({collection:e.collection,pipeline:e.pipeline,params:e.queryParams,limit:e.limit}),signal:AbortSignal.timeout(75000)});if(!r.ok){let t=await r.text();throw Error(bt(t)||"No se pudo ejecutar el pipeline.")}return await r.json()}function bt(e){try{return JSON.parse(e).error||e}catch{return e}}async function yt(e,r,t){let o=await fetch(`${q("data")}/aggregation-queries/${e}/run`,{method:"POST",headers:await pe(),body:JSON.stringify({params:r,limit:t}),signal:AbortSignal.timeout(315000)});if(!o.ok){let l=await o.text();throw Error(bt(l)||"No se pudo ejecutar el query.")}if(!o.body)throw Error("El servidor no devolvió un stream de datos.");let a=o.body.getReader(),i=new TextDecoder,n="",s=0;while(!0){let{done:l,value:m}=await a.read();if(l)break;let p=i.decode(m,{stream:!0});process.stdout.write(p),n+=p;let d=n.indexOf(`
|
|
860
860
|
`);while(d>=0){if(n.slice(0,d).trim())s++;n=n.slice(d+1),d=n.indexOf(`
|
|
861
|
-
`)}}let c=i.decode();if(c)process.stdout.write(c),n+=c;if(n.trim())s++;return{ok:!0,queryId:e,limit:t,rows:s}}async function
|
|
861
|
+
`)}}let c=i.decode();if(c)process.stdout.write(c),n+=c;if(n.trim())s++;return{ok:!0,queryId:e,limit:t,rows:s}}async function Ge(e,r){await Fe(e,{name:r.name,description:r.description,collection:r.collection,allowedUsersIds:r.allowedUsersIds,tags:r.tags}),await u({service:"data",query:`mutation ($aggregationQueryId: String, $pipeline: String, $variables: [AggregationQueryVariableInput]) {
|
|
862
862
|
addAggregationQueryVersion(
|
|
863
863
|
aggregationQueryId: $aggregationQueryId
|
|
864
864
|
pipeline: $pipeline
|
|
@@ -867,7 +867,7 @@ ${t}`)}function la(e){let r=Gr(e);R(w(e,"README.md"),Pr(r)),R(w(e,"src","App.tsx
|
|
|
867
867
|
_id
|
|
868
868
|
currentVersionIndex
|
|
869
869
|
}
|
|
870
|
-
}`,variables:{aggregationQueryId:e,pipeline:r.pipeline,variables:r.variables}})}async function
|
|
870
|
+
}`,variables:{aggregationQueryId:e,pipeline:r.pipeline,variables:r.variables}})}async function Fe(e,r){await u({service:"data",query:`mutation ($aggregationQueryId: String, $aggregationQuery: UpdateAggregationQueryInput) {
|
|
871
871
|
updateAggregationQuery(
|
|
872
872
|
aggregationQueryId: $aggregationQueryId
|
|
873
873
|
aggregationQuery: $aggregationQuery
|
|
@@ -880,7 +880,7 @@ ${t}`)}function la(e){let r=Gr(e);R(w(e,"README.md"),Pr(r)),R(w(e,"src","App.tsx
|
|
|
880
880
|
tags
|
|
881
881
|
currentVersionIndex
|
|
882
882
|
}
|
|
883
|
-
}`,variables:{aggregationQueryId:e,aggregationQuery:{name:r.name,description:r.description,collection:r.collection,allowedUsersIds:r.allowedUsersIds,tags:r.tags}}})}async function
|
|
883
|
+
}`,variables:{aggregationQueryId:e,aggregationQuery:{name:r.name,description:r.description,collection:r.collection,allowedUsersIds:r.allowedUsersIds,tags:r.tags}}})}async function Ct(){return(await u({service:"data",query:`mutation {
|
|
884
884
|
createAggregationQuery {
|
|
885
885
|
_id
|
|
886
886
|
name
|
|
@@ -896,7 +896,7 @@ ${t}`)}function la(e){let r=Gr(e);R(w(e,"README.md"),Pr(r)),R(w(e,"src","App.tsx
|
|
|
896
896
|
fieldParams
|
|
897
897
|
}
|
|
898
898
|
}
|
|
899
|
-
}`})).createAggregationQuery}function
|
|
899
|
+
}`})).createAggregationQuery}function ka(e){if(!Array.isArray(e))throw Error("El preview del query debe devolver un arreglo para usar AI edit.");return e}async function Ha(e){let r=await u({service:"messenger",query:`mutation generateAdminQuery(
|
|
900
900
|
$prompt: String
|
|
901
901
|
$name: String
|
|
902
902
|
$description: String
|
|
@@ -922,13 +922,17 @@ ${t}`)}function la(e){let r=Gr(e);R(w(e,"README.md"),Pr(r)),R(w(e,"src","App.tsx
|
|
|
922
922
|
aggregationDescription
|
|
923
923
|
aggregationName
|
|
924
924
|
}
|
|
925
|
-
}`,variables:e});if(!r.generateAdminQuery?.pipeline||!r.generateAdminQuery.fullCollectionName)throw Error("La IA no devolvió una versión válida del query.");return r.generateAdminQuery}async function
|
|
926
|
-
|
|
927
|
-
|
|
925
|
+
}`,variables:e});if(!r.generateAdminQuery?.pipeline||!r.generateAdminQuery.fullCollectionName)throw Error("La IA no devolvió una versión válida del query.");return r.generateAdminQuery}async function Za(e){let r=await u({service:"messenger",timeoutMs:120000,query:`mutation explainAdminQuery($prompt: String) {
|
|
926
|
+
explainAdminQuery(prompt: $prompt) {
|
|
927
|
+
responseText
|
|
928
|
+
}
|
|
929
|
+
}`,variables:{prompt:e}});if(!r.explainAdminQuery?.responseText)throw Error("La IA no devolvió una explicación válida.");return r.explainAdminQuery}async function qt(){return h(),await Ct()}async function ht(e){h();let r=e.prompt||await F("Explica qué query quieres investigar o construir: ");if(!r)throw Error("Debes indicar un prompt para explain.");return(await Za(r)).responseText}async function xt(e){if(h(),!e.collection)throw Error("Debes indicar --collection con formato db.collection. Ejemplo: --collection justo.users");if(!e.pipeline)throw Error("Debes indicar --pipeline. Ejemplo: --pipeline '[{$limit: 5}]'");let r=e.limit?Je(e):void 0;return await wt({collection:e.collection,pipeline:e.pipeline,queryParams:z(e),limit:r})}async function It(e){h();let r=N(e,"team-cli data queries edit <queryId>"),t=await D(r),o=dt(ft(t));return await Ge(r,o),{ok:!0,queryId:r,name:o.name,collection:o.collection}}async function St(e,r){h();let t=N(e,"team-cli data queries ai-edit <queryId> --prompt '<texto>' [--params '<json>']"),o=await D(t),a=r.prompt||await F("Describe los cambios para la IA: ");if(!a)throw Error("Debes indicar un prompt para AI edit.");let i=z(r),n;if(r.params){C(`Obteniendo preview del query actual...
|
|
930
|
+
`);try{let c=await Me(t,i);n=ka(c)}catch(c){let l=c instanceof Error?c.message:String(c);throw Error(`No se pudo obtener el preview para AI edit: ${l}`)}}C(`Generando propuesta con IA...
|
|
931
|
+
`);let s=await Ha({prompt:a,fullCollectionName:o.collection,pipeline:o.pipeline,preview:n,description:o.description,name:o.name,variables:o.variables});return await Ge(t,{name:o.name==="Nuevo query"?s.aggregationName||o.name:o.name,description:o.description||s.aggregationDescription,collection:s.fullCollectionName,allowedUsersIds:o.allowedUsersIds??[],tags:o.tags??[],pipeline:s.pipeline,variables:s.variables??[]}),{ok:!0,queryId:t,responseText:s.responseText,collection:s.fullCollectionName,name:s.aggregationName,description:s.aggregationDescription}}async function $t(e){h();let r=N(e,"team-cli data queries view <queryId>");return await D(r)}async function Et(e){h();let r=N(e,"team-cli data queries view-pipeline <queryId>"),t=await D(r);return{queryId:r,pipeline:t.pipeline}}async function vt(e,r){h();let t=N(e,"team-cli data queries preview <queryId> --params '<json>'"),o=z(r),a=await Me(t,o);return We(a)}async function jt(e,r){h();let t=N(e,"team-cli data queries run <queryId> --limit <n> --params '<json>'"),o=z(r),a=Je(r);return await yt(t,o,a),{__streamHandled:!0}}async function At(e,r){h();let t=N(e,"team-cli data queries add-viewers <queryId> --emails 'ana@justo.com,bob@justo.com'"),o=pt(r),a=await D(t),i=await gt(o),n=[...new Set([...a.allowedUsersIds??[],...i.map((s)=>s._id)])];return await Fe(t,{name:a.name,description:a.description,collection:a.collection,allowedUsersIds:n,tags:a.tags??[]}),{ok:!0,queryId:t,addedViewers:i.map((s)=>({_id:s._id,email:s.email,fullName:s.fullName})),allowedUsersIds:n}}function Ya(e){return new Promise((r)=>setTimeout(r,e))}async function Rt(e,r){h();let t=N(e,"team-cli data queries download <queryId> --params '<json>'"),o=z(r);if(!r.path)throw Error("--path es requerido. Ejemplo: --path resultado.xlsx");C(`Iniciando descarga...
|
|
928
932
|
`);let i=(await u({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
|
|
929
933
|
downloadAggregationQueryData(aggregationQueryId: $aggregationQueryId, params: $params)
|
|
930
934
|
}`,variables:{aggregationQueryId:t,params:o}})).downloadAggregationQueryData;C(`Reporte en proceso (${i})...
|
|
931
|
-
`);let n=null;while(!n){await
|
|
935
|
+
`);let n=null;while(!n){await Ya(1000);let l=await u({service:"data",query:`query ($id: String) {
|
|
932
936
|
getAsyncReport(id: $id) {
|
|
933
937
|
_id
|
|
934
938
|
status
|
|
@@ -938,20 +942,47 @@ ${t}`)}function la(e){let r=Gr(e);R(w(e,"README.md"),Pr(r)),R(w(e,"src","App.tsx
|
|
|
938
942
|
getAsyncReportRecordsCount(id: $id)
|
|
939
943
|
}`,variables:{id:i}}),m=l.getAsyncReport,p=l.getAsyncReportRecordsCount;if(m.status==="error")throw Error("El reporte falló al generarse.");if(m.fileUrl)n=m.fileUrl;else{let d=m.estimatedRecordsCount?` (~${m.estimatedRecordsCount} registros)`:"",b=p!=null?` ${p} procesados`:"";C(`\rGenerando...${d}${b}`)}}C(`
|
|
940
944
|
Descargando archivo...
|
|
941
|
-
`);let s=await fetch(n);if(!s.ok)throw Error(`Error descargando archivo: ${s.status}`);let c=Buffer.from(await s.arrayBuffer());return
|
|
945
|
+
`);let s=await fetch(n);if(!s.ok)throw Error(`Error descargando archivo: ${s.status}`);let c=Buffer.from(await s.arrayBuffer());return Xa(r.path,c),{ok:!0,queryId:t,asyncReportId:i,outputPath:r.path,fileUrl:n}}function ze(){return`team-cli data
|
|
942
946
|
|
|
943
947
|
Comandos de datos y reportes.
|
|
944
948
|
|
|
945
949
|
Recomendado:
|
|
946
|
-
Si necesitas obtener data y no existe un query listo, usa create
|
|
947
|
-
Flujo sugerido: create -> ai-edit -> preview -> run o download.
|
|
950
|
+
Si necesitas obtener data y no existe un query listo, usa explain -> create -> ai-edit.
|
|
951
|
+
Flujo sugerido: explain -> create -> ai-edit -> preview -> run o download.
|
|
952
|
+
Usa queries cuando quieras que la consulta quede guardada, versionada y compartible.
|
|
953
|
+
Usa execute solo para correr un pipeline una vez.
|
|
954
|
+
Para spaces, prefiere siempre queries guardados en vez de execute directo.
|
|
948
955
|
Siempre que puedas, prefiere varias queries simples antes que un solo pipeline con lookup.
|
|
949
956
|
Para dashboards suele ser mejor resolver joins en la UI o con queries separadas.
|
|
957
|
+
Caso común:
|
|
958
|
+
1. Usa explain para investigar servicio, colección, fields o resolvers.
|
|
959
|
+
2. Usa execute para probar un pipeline una sola vez.
|
|
960
|
+
3. Si lo vas a reutilizar, conviértelo en query guardado con create + ai-edit.
|
|
950
961
|
|
|
951
962
|
Uso:
|
|
952
|
-
team-cli data
|
|
963
|
+
team-cli data <subcomando> [opciones]
|
|
953
964
|
|
|
954
965
|
Subcomandos:
|
|
966
|
+
explain
|
|
967
|
+
Pedir una explicación guiada para investigar cómo construir un query o cómo consultar datos por GraphQL usando el subagente de repo.
|
|
968
|
+
Uso: team-cli data explain --prompt '<texto>' [--format toon|json]
|
|
969
|
+
Solo disponible para usuarios con rol queries.
|
|
970
|
+
|
|
971
|
+
execute
|
|
972
|
+
Ejecutar un pipeline directo sin crear un query guardado.
|
|
973
|
+
Piensa en esto como ejecución ad-hoc de una sola vez.
|
|
974
|
+
Solo lectura: bloquea stages de escritura como $out y $merge.
|
|
975
|
+
Usa timeout de 1 minuto, read preference secondaryPreferred y requiere rol queries.
|
|
976
|
+
Para spaces y dashboards compartibles, prefiere queries guardados con data queries create + ai-edit.
|
|
977
|
+
Uso: team-cli data execute --collection <db.collection> --pipeline '<array js>' [--params '<json>'] [--limit <n>] [--format toon|json]
|
|
978
|
+
|
|
979
|
+
queries
|
|
980
|
+
Administrar y ejecutar aggregation queries guardados.
|
|
981
|
+
|
|
982
|
+
Uso de queries:
|
|
983
|
+
team-cli data queries <subcomando> [opciones]
|
|
984
|
+
|
|
985
|
+
Subcomandos de queries:
|
|
955
986
|
create
|
|
956
987
|
Crear un query nuevo.
|
|
957
988
|
Devuelve el _id para seguir con edit, ai-edit, view o preview.
|
|
@@ -992,13 +1023,18 @@ Subcomandos:
|
|
|
992
1023
|
|
|
993
1024
|
Opciones:
|
|
994
1025
|
--params '<json>' Parametros del query. Default: {}
|
|
995
|
-
--limit <n> Requerido para run.
|
|
1026
|
+
--limit <n> Requerido para run. En execute es opcional y limita resultados.
|
|
996
1027
|
--emails '<csv>' Requerido para add-viewers. Lista separada por comas.
|
|
997
1028
|
--prompt '<texto>' Prompt para ai-edit. Si no viene, se pide interactivamente.
|
|
998
|
-
--
|
|
1029
|
+
--collection <db.collection> Requerido para execute.
|
|
1030
|
+
--pipeline '<array js>' Requerido para execute.
|
|
1031
|
+
--format <toon|json> Usa toon por defecto cuando el comando lo ejecute un agente como Codex o Claude.
|
|
999
1032
|
--path <filepath> Requerido para download
|
|
1000
1033
|
|
|
1001
1034
|
Ejemplos:
|
|
1035
|
+
team-cli data explain --prompt 'Quiero entender dónde viven los campos de courier de los pedidos'
|
|
1036
|
+
team-cli data explain --prompt 'Quiero saber cómo consultar tabs por GraphQL y qué resolvers mirar'
|
|
1037
|
+
team-cli data execute --collection justo.users --pipeline '[{$limit: 5}, {$project: {_id: 1, createdAt: 1}}]'
|
|
1002
1038
|
team-cli data queries create
|
|
1003
1039
|
team-cli data queries edit abc123
|
|
1004
1040
|
team-cli data queries ai-edit abc123 --prompt 'Filtra solo ordenes canceladas'
|
|
@@ -1006,7 +1042,7 @@ Ejemplos:
|
|
|
1006
1042
|
team-cli data queries preview abc123 --params '{"startDate": "2026-01-01"}'
|
|
1007
1043
|
team-cli data queries run abc123 --limit 1000 --params '{"startDate": "2026-01-01"}'
|
|
1008
1044
|
team-cli data queries download abc123 --params '{"startDate": "2026-01-01"}' --path resultado.xlsx
|
|
1009
|
-
team-cli data queries add-viewers abc123 --emails 'ana@justo.com,bob@justo.com'`}var
|
|
1045
|
+
team-cli data queries add-viewers abc123 --emails 'ana@justo.com,bob@justo.com'`}var Nt=["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"],Tt=`
|
|
1010
1046
|
query ResolverInfo($name: ID!, $mutation: Boolean!) {
|
|
1011
1047
|
params(name: $name, mutation: $mutation) {
|
|
1012
1048
|
name
|
|
@@ -1015,8 +1051,8 @@ Ejemplos:
|
|
|
1015
1051
|
basicResultQuery
|
|
1016
1052
|
}
|
|
1017
1053
|
}
|
|
1018
|
-
`;function
|
|
1019
|
-
`)}function
|
|
1054
|
+
`;function Va(e){if(!e)throw Error("Uso: team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]");if(!Nt.includes(e))throw Error(`Servicio "${e}" no válido. Servicios disponibles: ${Nt.join(", ")}`)}async function Ka(e,r){let t;try{let o=await u({service:e,query:Tt,variables:{name:r,mutation:!1}});return{service:e,operationName:r,operationType:"query",info:o.params}}catch(o){t=o}try{let o=await u({service:e,query:Tt,variables:{name:r,mutation:!0}});return{service:e,operationName:r,operationType:"mutation",info:o.params}}catch(o){let a=t instanceof Error?t.message:"",i=o instanceof Error?o.message:"";if(a.includes('Cannot query field "params"')||i.includes('Cannot query field "params"'))throw Error(`El servicio "${e}" no expone metadata de resolvers por GraphQL.`);throw t instanceof Error?t:o}}async function Ot(e,r){let t=e[1],o=e[2],a=e[2];if(!g())throw Error("Debes iniciar sesión primero. Recomendado: team-cli auth request-code --email <email> y luego team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>");if(Va(t),o==="info"){let s=e[3];if(!s)throw Error("Uso: team-cli graphql <servicio> info <queryName|mutationName> [--format toon|json]");return await Ka(t,s)}if(!a)throw Error("Uso: team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]");let i;if(r.variables)try{i=JSON.parse(r.variables)}catch{throw Error("Las variables deben ser un JSON válido.")}return await u({service:t,query:a,variables:i})}function Ut(){return Object.keys(ce)}function La(){return Ut().map((e)=>{let r=ce[e].prod;return`- \`${e}\`: \`${r}/graphql\``}).join(`
|
|
1055
|
+
`)}function Qt(){let r=Ut().join(", "),t=La();return`team-cli graphql
|
|
1020
1056
|
|
|
1021
1057
|
Ejecutar queries y mutations GraphQL.
|
|
1022
1058
|
|
|
@@ -1067,7 +1103,7 @@ npx @getjusto/team-cli graphql auth info requestLoginCode --format json
|
|
|
1067
1103
|
|
|
1068
1104
|
Usa esto para mapear una URL GraphQL al valor correcto de \`team-cli graphql <service>\`.
|
|
1069
1105
|
|
|
1070
|
-
${t}`}import{existsSync as
|
|
1106
|
+
${t}`}import{existsSync as $i,mkdirSync as Ei,readdirSync as vi}from"node:fs";import{resolve as Yt}from"node:path";import{readdirSync as Jt,readFileSync as Wt,statSync as Mt}from"node:fs";import{gzipSync as ci}from"node:zlib";import{join as Gt,relative as Ft,resolve as _t}from"node:path";import{existsSync as ei,readFileSync as ri}from"node:fs";import{join as ti}from"node:path";var oi=[".git","node_modules","dist",".justo-space-preview",".DS_Store"];function ai(e){return e.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}function ii(e){let r="";for(let t=0;t<e.length;t++){let o=e[t],a=e[t+1];if(o==="*"){if(a==="*"){r+=".*",t+=1;continue}r+="[^/]*";continue}if(o==="?"){r+="[^/]";continue}r+=ai(o)}return r}function ni(e){let r=e.trim();if(!r||r.startsWith("#"))return null;let t=r.startsWith("!"),o=t?r.slice(1).trim():r;if(!o)return null;let a=o.endsWith("/"),i=o.replace(/^\/+/,"").replace(/\/+$/,"");if(!i)return null;let n=i.includes("/"),s=ii(i),c=n?`^${s}${a?"(?:/.*)?":""}$`:`(?:^|/)${s}${a?"(?:/.*)?":"(?:$|/)"}`;return{negate:t,directoryOnly:a,regex:new RegExp(c)}}function si(e){let r=ti(e,".gitignore"),t=[...oi];if(ei(r))t.push(...ri(r,"utf-8").split(/\r?\n/));return t.map(ni).filter((o)=>Boolean(o))}function Pt(e){let r=si(e);return(t,o)=>{let a=t.replaceAll("\\","/").replace(/^\/+/,""),i=!1;for(let n of r){if(!n.regex.test(a))continue;i=!n.negate}return i}}var Se=512,ui=2,li="repo",mi="dist";function di(e){let r=e.replaceAll("\\","/");if(r.startsWith("/")||r.includes("../"))throw Error(`Ruta inválida en el space: ${e}`);return r}function pi(e){let r=di(e);if(Buffer.from(r).length<=100)return{name:r,prefix:""};let o=r.lastIndexOf("/");if(o<=0)throw Error(`La ruta es demasiado larga para el paquete del space: ${e}`);let a=r.slice(0,o),i=r.slice(o+1);if(Buffer.from(a).length>155||Buffer.from(i).length>100)throw Error(`La ruta es demasiado larga para el paquete del space: ${e}`);return{name:i,prefix:a}}function B(e,r,t,o){let a=Buffer.from(o);a.copy(e,r,0,Math.min(a.length,t))}function te(e,r,t,o){let a=Math.max(0,Math.trunc(o)).toString(8).padStart(t-1,"0");B(e,r,t,`${a}\x00`)}function gi(e){let r=Buffer.alloc(Se,0),{name:t,prefix:o}=pi(e.path);B(r,0,100,t),te(r,100,8,e.mode),te(r,108,8,0),te(r,116,8,0),te(r,124,12,e.content.length),te(r,136,12,e.mtime),r.fill(32,148,156),B(r,156,1,"0"),B(r,257,6,"ustar"),B(r,263,2,"00"),B(r,345,155,o);let a=0;for(let n of r)a+=n;let i=`${a.toString(8).padStart(6,"0")}\x00 `;return B(r,148,8,i),r}function fi(e){let r=e%Se;return r===0?0:Se-r}function zt(e,r=e){return Jt(r,{withFileTypes:!0}).sort((o,a)=>o.name.localeCompare(a.name)).flatMap((o)=>{let a=Gt(r,o.name);if(o.isDirectory())return zt(e,a);if(!o.isFile())return[];let i=Ft(e,a),n=Mt(a);return[{path:i,content:Wt(a),mode:n.mode&511,mtime:Math.floor(n.mtimeMs/1000)}]})}function Bt(e,r){return e.map((t)=>({...t,path:`${r}/${t.path.replaceAll("\\","/")}`}))}function Dt(e,r=e){let t=Pt(e);return Jt(r,{withFileTypes:!0}).sort((a,i)=>a.name.localeCompare(i.name)).flatMap((a)=>{let i=Gt(r,a.name),n=Ft(e,i).replaceAll("\\","/");if(t(n,a.isDirectory()))return[];if(a.isDirectory())return Dt(e,i);if(!a.isFile())return[];let s=Mt(i);return[{path:n,content:Wt(i),mode:s.mode&511,mtime:Math.floor(s.mtimeMs/1000)}]})}function Xt(e,r){let t=_t(e),o=_t(r),a=[...Bt(Dt(t),li),...Bt(zt(o),mi)];if(!a.length)throw Error("El build del space no contiene archivos para publicar");let i=[];for(let n of a){i.push(gi(n)),i.push(n.content);let s=fi(n.content.length);if(s>0)i.push(Buffer.alloc(s,0))}return i.push(Buffer.alloc(Se*ui,0)),ci(Buffer.concat(i))}import{mkdirSync as kt,writeFileSync as wi}from"node:fs";import{dirname as bi,join as yi,normalize as Ci,sep as Ht}from"node:path";import{gunzipSync as qi}from"node:zlib";var oe=512;function $e(e,r,t){let o=e.subarray(r,r+t),a=o.indexOf(0);return(a>=0?o.subarray(0,a):o).toString("utf-8").trim()}function hi(e,r,t){let o=$e(e,r,t).replaceAll("\x00","").trim();if(!o)return 0;return Number.parseInt(o,8)}function xi(e){let r=e%oe;return r===0?0:oe-r}function Ii(e){let r=$e(e,0,100),t=$e(e,345,155);return t?`${t}/${r}`:r}function Si(e){let r=Ci(e);if(!e||e.startsWith("/")||r.startsWith("..")||r.includes(`${Ht}..${Ht}`)||r==="..")throw Error("El paquete del space contiene rutas inválidas")}function Zt(e,r,t){let o=qi(e),a=r.replaceAll("\\","/").replace(/^\/+|\/+$/g,""),i=`${a}/`,n=0,s=0;while(n+oe<=o.length){let c=o.subarray(n,n+oe),l=c.every((O)=>O===0);if(n+=oe,l)break;let m=Ii(c),p=$e(c,156,1)||"0",d=hi(c,124,12),b=o.subarray(n,n+d);if(n+=d+xi(d),!m.startsWith(i))continue;let f=m.slice(i.length);if(!f)continue;Si(f);let T=yi(t,...f.split("/"));if(p==="5"){kt(T,{recursive:!0});continue}if(p!=="0")continue;kt(bi(T),{recursive:!0}),wi(T,b),s+=1}if(!s)throw Error(`El paquete del space no contiene la carpeta ${a}/`);return s}function Ee(){if(!g())throw Error("Debes iniciar sesión primero. Recomendado: team-cli auth request-code --email <email> y luego team-cli auth login-with-token --email <email> --token <token> --code <CODIGO>")}function ae(e,r,t){let o=e[r];if(!o)throw Error(`Falta --${r}. Ejemplo: ${t}`);return o}function Vt(e,r){let t=e[2];if(!t)throw Error(`Uso: ${r}`);return t}function De(){let e=ue();if(e==="local")return"http://intra.localhost:5173";if(e==="develop")return"https://intra.bejusto.com";return"https://intra.getjusto.com"}async function ji(e,r){let t=await de(),o=await fetch(`${q("data")}/spaces/publish/${e}`,{method:"POST",headers:{"Content-Type":"application/gzip",...t?{"X-ORION-JWT":t}:{}},body:r}),a=await o.json();if(!o.ok||a.error)throw Error(a.error||"No se pudo publicar el space.");return a}async function Ai(e){let r=await de(),t=await fetch(`${q("data")}/spaces/fork/${e}`,{method:"GET",headers:r?{"X-ORION-JWT":r}:{}});if(!t.ok){let o=await t.json().catch(()=>({}));throw Error(o.error||"No se pudo descargar el repo del space.")}return Buffer.from(await t.arrayBuffer())}function Ri(e){let r=Yt(e);if($i(r)&&vi(r).length>0)throw Error(`La carpeta ya existe y no está vacía: ${r}`);return Ei(r,{recursive:!0}),r}function Xe(){return`team-cli spaces
|
|
1071
1107
|
|
|
1072
1108
|
Spaces son aplicaciones internas en React, pensadas para que las construyan agentes.
|
|
1073
1109
|
El flujo oficial parte con \`spaces init\` y \`spaces publish\` solo acepta apps creadas así.
|
|
@@ -1099,7 +1135,7 @@ Flujo sugerido para agentes:
|
|
|
1099
1135
|
5. desarrollar la app React dentro de esa carpeta
|
|
1100
1136
|
6. \`team-cli spaces publish <spaceId> --path ./mi-space-app\`
|
|
1101
1137
|
7. hacer commit del repo después de publicar
|
|
1102
|
-
8. abrir \`${
|
|
1138
|
+
8. abrir \`${De()}/spaces/<slug>\`
|
|
1103
1139
|
9. si necesitas retomarlo en otra carpeta: \`team-cli spaces fork <slug> --path ./mi-space-app\`
|
|
1104
1140
|
|
|
1105
1141
|
Slugs:
|
|
@@ -1169,7 +1205,7 @@ Comandos:
|
|
|
1169
1205
|
- \`spaces publish <spaceId> --path ./mi-space-app\`
|
|
1170
1206
|
- \`spaces fork <slug> --path ./mi-space-app\`
|
|
1171
1207
|
- \`spaces archive <spaceId>\`
|
|
1172
|
-
`}async function
|
|
1208
|
+
`}async function Kt(e){let r=ae(e,"path","team-cli spaces init --path ./mi-space-app");return Hr(r)}async function Lt(e){return await ut(e)}async function eo(e){Ee();let r=ae(e,"name","team-cli spaces create --name 'Mi space' --description '...' --slug dashboard-1234"),t=ae(e,"description","team-cli spaces create --name 'Mi space' --description 'Sitio interno' --slug dashboard-1234"),o=ae(e,"slug","team-cli spaces create --name 'Mi space' --description '...' --slug dashboard-1234"),a=await u({service:"data",query:`mutation ($name: String, $description: String, $slug: String) {
|
|
1173
1209
|
createSpace(name: $name, description: $description, slug: $slug) {
|
|
1174
1210
|
_id
|
|
1175
1211
|
name
|
|
@@ -1180,7 +1216,7 @@ Comandos:
|
|
|
1180
1216
|
createdByEmail
|
|
1181
1217
|
createdById
|
|
1182
1218
|
}
|
|
1183
|
-
}`,variables:{name:r,description:t,slug:o}});return{...a.createSpace,intraUrl:`${
|
|
1219
|
+
}`,variables:{name:r,description:t,slug:o}});return{...a.createSpace,intraUrl:`${De()}/spaces/${a.createSpace.slug}`,serveUrl:`${q("data")}/spaces/${a.createSpace.slug}`}}async function ro(e,r){Ee();let t=Vt(e,"team-cli spaces publish <spaceId> --path ./mi-space-app"),o=ae(r,"path","team-cli spaces publish <spaceId> --path ./mi-space-app"),a=kr(o),i=Xt(o,a),n=await ji(t,i);return{...n,intraUrl:n.slug?`${De()}/spaces/${n.slug}`:void 0,serveUrl:n.slug?`${q("data")}/spaces/${n.slug}`:void 0,builtFrom:Yt(o)}}async function to(e,r){Ee();let t=e[2];if(!t)throw Error("Uso: team-cli spaces fork <slug> --path ./mi-space-app");let o=Ri(r.path||`./${t}`),a=await Ai(t),i=Zt(a,"repo",o);return{ok:!0,slug:t,path:o,extractedFiles:i,nextSteps:[`cd ${o}`,"yarn install","team-cli spaces preview --path . --open"]}}async function oo(e){Ee();let r=Vt(e,"team-cli spaces archive <spaceId>");return(await u({service:"data",query:`mutation ($spaceId: String) {
|
|
1184
1220
|
archiveSpace(spaceId: $spaceId) {
|
|
1185
1221
|
_id
|
|
1186
1222
|
name
|
|
@@ -1192,7 +1228,7 @@ Comandos:
|
|
|
1192
1228
|
createdById
|
|
1193
1229
|
archivedAt
|
|
1194
1230
|
}
|
|
1195
|
-
}`,variables:{spaceId:r}})).archiveSpace}function
|
|
1231
|
+
}`,variables:{spaceId:r}})).archiveSpace}function ao(e){return`team-cli
|
|
1196
1232
|
|
|
1197
1233
|
Herramienta CLI para el equipo Justo.
|
|
1198
1234
|
|
|
@@ -1212,7 +1248,7 @@ npx @getjusto/team-cli auth login-with-token --email <email> --token <token> --c
|
|
|
1212
1248
|
## Opciones globales
|
|
1213
1249
|
|
|
1214
1250
|
- \`--env <local|develop|prod>\` — Environment (default: prod)
|
|
1215
|
-
- \`--format toon|json\` — Output format (default: toon)
|
|
1251
|
+
- \`--format toon|json\` — Output format (default: toon). \`toon\` es el formato recomendado para agentes como Codex o Claude. Usa \`json\` solo si realmente necesitas JSON estricto.
|
|
1216
1252
|
- \`--version\`
|
|
1217
1253
|
- \`--help\`
|
|
1218
1254
|
|
|
@@ -1237,11 +1273,20 @@ npx @getjusto/team-cli admin search <text> [--limit <n>] [--page <n>] [--only-ac
|
|
|
1237
1273
|
|
|
1238
1274
|
### Crea queries para usar en los dashboards
|
|
1239
1275
|
|
|
1240
|
-
Crea queries personalizadas usando \`create\` y \`ai-edit\` para generar consultas a la base de datos y luego crear un dashboard que las use
|
|
1276
|
+
Crea queries personalizadas usando \`data explain\`, \`data queries create\` y \`data queries ai-edit\` para generar consultas a la base de datos y luego crear un dashboard que las use
|
|
1241
1277
|
para mostrar datos. Usa \`preview\` para iterar rápido, \`run\` para consumir NDJSON en streaming y \`download\` para Excel.
|
|
1278
|
+
\`data explain\` también sirve para investigar cómo consultar datos por GraphQL, qué servicio mirar, qué resolvers existen y qué fields parecen relevantes.
|
|
1279
|
+
Usa \`data queries\` cuando quieras que la consulta quede guardada, versionada y compartible. Usa \`data execute\` solo para ejecutar un pipeline una vez.
|
|
1280
|
+
Para construir \`spaces\`, prefiere siempre queries guardados. \`data execute\` sirve para exploración puntual, no como backend principal del dashboard.
|
|
1242
1281
|
También puedes usar queries para poblar selectores y otras partes de la interfaz del space.
|
|
1243
1282
|
Siempre que puedas, prefiere varias queries simples antes que un solo query con \`lookup\`.
|
|
1244
1283
|
Eso suele ser más fácil de iterar, más claro para agentes y menos frágil para dashboards.
|
|
1245
1284
|
Si el usuario pide compartir un dashboard con otra persona, normalmente lo que hay que hacer es compartir las queries que usa ese dashboard con \`data queries add-viewers\`.
|
|
1246
1285
|
|
|
1247
|
-
|
|
1286
|
+
### Caso común: explain + execute
|
|
1287
|
+
|
|
1288
|
+
Si todavía no sabes bien dónde vive la data, primero usa \`data explain\` para investigar servicio, colección, fields o resolvers relevantes.
|
|
1289
|
+
Cuando ya tengas claro un pipeline y solo quieras probarlo una vez, usa \`data execute\`.
|
|
1290
|
+
Si ese resultado lo vas a reutilizar en un dashboard o un space, después conviértelo en un query guardado con \`data queries create\` + \`data queries ai-edit\`.
|
|
1291
|
+
|
|
1292
|
+
`}function io(){let e=g(),r=e?`Sesión: ${e.email}`:"Sesión: no iniciada";return ao(r)}async function no(e){let{positional:r,flags:t}=ie(e);if(t.env)tr(t.env);let o=r[0],a=r[1];if(o==="__spaces-preview-bridge")return await ct(t);if(t.version)return{version:"0.0.11"};if(t.help&&!o)return io();if(o==="auth"){if(a==="--help"||t.help)return Qe();if(a==="login")return await Ur();if(a==="login-with-token")return await Qr(t);if(a==="request-code")return await Pr(t);if(a==="logout")return await _r();if(a==="status")return await Br();return Qe()}if(o==="admin"){let i=r[1],n=r[2],s=r[3],c=r[4];if(!i||i==="--help")return ge();if(i==="search"&&t.help)return Rr();if(i==="search")return await Ar(r,t);if(!n||n==="--help")return ge();if(n==="show")return await dr(i);if(n==="stores"&&s==="list")return await Nr(i);if(n==="coupons"&&(!s||s==="--help"))return K();if(n==="coupons"&&s==="create"&&t.help)return vr();if(n==="coupons"&&s==="update"&&t.help)return jr();if(n==="coupons"&&s==="codes"&&r[4]==="create"&&t.help)return qr();if(n==="coupons"&&t.help)return K();if(n==="coupons"&&s==="list")return await xr(i,t);if(n==="coupons"&&s==="show"){if(!c)throw Error("Uso: team-cli admin <web> coupons show <couponId>");return await Ir(i,c)}if(n==="coupons"&&s==="create")return await Sr(i,t);if(n==="coupons"&&s==="update"){if(!c)throw Error("Uso: team-cli admin <web> coupons update <couponId> --input '<json>'");return await $r(i,c,t)}if(n==="coupons"&&s==="delete"){if(!c)throw Error("Uso: team-cli admin <web> coupons delete <couponId>");return await Er(i,c)}if(n==="coupons"&&s==="codes"){let l=r[4],m=r[5];if(!l||l==="--help")return K();if(l==="list"){if(!m)throw Error("Uso: team-cli admin <web> coupons codes list <couponId>");return await wr(i,m,t)}if(l==="create"){if(!m)throw Error("Uso: team-cli admin <web> coupons codes create <couponId> --input '<json>'");return await br(i,m,t)}if(l==="create-random"){if(!m)throw Error("Uso: team-cli admin <web> coupons codes create-random <couponId> --quantity <n>");return await yr(i,m,t)}if(l==="delete"){if(!m)throw Error(`Uso: team-cli admin <web> coupons codes delete <couponId> --ids '["id1"]'`);return await Cr(i,m,t)}return K()}return ge()}if(o==="graphql"){if(a==="--help"||t.help)return Qt();return await Ot(r,t)}if(o==="data"){let i=r[1],n=r[2];if(t.help||a==="--help")return ze();if(i==="explain")return await ht(t);if(i==="execute")return await xt(t);if(i==="queries"&&n==="create")return await qt();if(i==="queries"&&n==="edit")return await It(r);if(i==="queries"&&n==="ai-edit")return await St(r,t);if(i==="queries"&&n==="view")return await $t(r);if(i==="queries"&&n==="view-pipeline")return await Et(r);if(i==="queries"&&n==="preview")return await vt(r,t);if(i==="queries"&&n==="run")return await jt(r,t);if(i==="queries"&&n==="add-viewers")return await At(r,t);if(i==="queries"&&n==="download")return await Rt(r,t);return ze()}if(o==="spaces"){let i=r[1];if(!i||i==="--help"||t.help)return Xe();if(i==="init")return await Kt(t);if(i==="create")return await eo(t);if(i==="preview")return await Lt(t);if(i==="publish")return await ro(r,t);if(i==="fork")return await to(r,t);if(i==="archive")return await oo(r);return Xe()}return io()}var{flags:so}=ie(process.argv.slice(2));async function Ni(){try{let e=await no(process.argv.slice(2));if(e&&typeof e==="object"&&"__streamHandled"in e&&e.__streamHandled)return;if(typeof e==="string"){er(e);return}Le(e,so)}catch(e){rr(e,so),process.exit(1)}}Ni();
|