@getjusto/team-cli 0.0.11 → 0.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/bin/cli.js +382 -329
  2. package/package.json +2 -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 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) {
2
+ function bc(c){let a=[],o={},m={};for(let s=0;s<c.length;s++)if(c[s].startsWith("--")&&c[s+1]&&!c[s+1].startsWith("--")){let t=c[s].slice(2);if(o[t]=c[s+1],!m[t])m[t]=[];m[t].push(c[s+1]),s++}else if(c[s].startsWith("--"))o[c[s].slice(2)]="true";else a.push(c[s]);return{positional:a,flags:o,arrayFlags:m}}function hc(c,a){let o=c[a];if(!o)throw Error(`--${a} es requerido.`);return o}var ys={comma:",",tab:"\t",pipe:"|"},kc=ys.comma;function Ba(c){return c.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}function Ss(c){return c==="true"||c==="false"||c==="null"}function e(c){if(c===null)return null;if(typeof c==="object"&&c!==null&&"toJSON"in c&&typeof c.toJSON==="function"){let a=c.toJSON();if(a!==c)return e(a)}if(typeof c==="string"||typeof c==="boolean")return c;if(typeof c==="number"){if(Object.is(c,-0))return 0;if(!Number.isFinite(c))return null;return c}if(typeof c==="bigint"){if(c>=Number.MIN_SAFE_INTEGER&&c<=Number.MAX_SAFE_INTEGER)return Number(c);return c.toString()}if(c instanceof Date)return c.toISOString();if(Array.isArray(c))return c.map(e);if(c instanceof Set)return Array.from(c).map(e);if(c instanceof Map)return Object.fromEntries(Array.from(c,([a,o])=>[String(a),e(o)]));if(us(c)){let a={};for(let o in c)if(Object.prototype.hasOwnProperty.call(c,o))a[o]=e(c[o]);return a}return null}function $c(c){return c===null||typeof c==="string"||typeof c==="number"||typeof c==="boolean"}function rc(c){return Array.isArray(c)}function N(c){return c!==null&&typeof c==="object"&&!Array.isArray(c)}function Kc(c){return Object.keys(c).length===0}function us(c){if(c===null||typeof c!=="object")return!1;let a=Object.getPrototypeOf(c);return a===null||a===Object.prototype}function _c(c){return c.length===0||c.every((a)=>$c(a))}function Ls(c){return c.length===0||c.every((a)=>rc(a))}function va(c){return c.length===0||c.every((a)=>N(a))}function Ns(c){return/^[A-Z_][\w.]*$/i.test(c)}function is(c){return/^[A-Z_]\w*$/i.test(c)}function ds(c,a=kc){if(!c)return!1;if(c!==c.trim())return!1;if(Ss(c)||Os(c))return!1;if(c.includes(":"))return!1;if(c.includes('"')||c.includes("\\"))return!1;if(/[[\]{}]/.test(c))return!1;if(/[\n\r\t]/.test(c))return!1;if(c.includes(a))return!1;if(c.startsWith("-"))return!1;return!0}function Os(c){return/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(c)||/^0\d+$/.test(c)}var cw=Symbol("quotedKey");function bs(c,a,o,m,s,t,p){if(m.keyFolding!=="safe")return;if(!N(a))return;let{segments:w,tail:C,leafValue:q}=Bs(c,a,p??m.flattenDepth);if(w.length<2)return;if(!w.every((A)=>is(A)))return;let g=vs(w),Q=t?`${t}.${g}`:g;if(o.includes(g))return;if(s&&s.has(Q))return;return{foldedKey:g,remainder:C,leafValue:q,segmentCount:w.length}}function Bs(c,a,o){let m=[c],s=a;while(m.length<o){if(!N(s))break;let t=Object.keys(s);if(t.length!==1)break;let p=t[0],w=s[p];m.push(p),s=w}if(!N(s)||Kc(s))return{segments:m,tail:void 0,leafValue:s};return{segments:m,tail:s,leafValue:s}}function vs(c){return c.join(".")}function Pc(c,a){if(c===null)return"null";if(typeof c==="boolean")return String(c);if(typeof c==="number")return String(c);return es(c,a)}function es(c,a=kc){if(ds(c,a))return c;return`"${Ba(c)}"`}function Ec(c){if(Ns(c))return c;return`"${Ba(c)}"`}function ea(c,a=kc){return c.map((o)=>Pc(o,a)).join(a)}function x(c,a){let o=a?.key,m=a?.fields,s=a?.delimiter??",",t="";if(o)t+=Ec(o);if(t+=`[${c}${s!==kc?s:""}]`,m){let p=m.map((w)=>Ec(w));t+=`{${p.join(s)}}`}return t+=":",t}function*xs(c,a,o){if($c(c)){let m=Pc(c,a.delimiter);if(m!=="")yield m;return}if(rc(c))yield*Aa(void 0,c,o,a);else if(N(c))yield*Rc(c,o,a)}function*Rc(c,a,o,m,s,t){let p=Object.keys(c);if(a===0&&!m)m=new Set(p.filter((C)=>C.includes(".")));let w=t??o.flattenDepth;for(let[C,q]of Object.entries(c))yield*fs(C,q,a,o,p,m,s,w)}function*fs(c,a,o,m,s,t,p,w){let C=p?`${p}.${c}`:c,q=w??m.flattenDepth;if(m.keyFolding==="safe"&&s){let Q=bs(c,a,s,m,t,p,q);if(Q){let{foldedKey:A,remainder:Y,leafValue:J,segmentCount:P}=Q,Z=Ec(A);if(Y===void 0){if($c(J)){yield V(o,`${Z}: ${Pc(J,m.delimiter)}`,m.indent);return}else if(rc(J)){yield*Aa(A,J,o,m);return}else if(N(J)&&Kc(J)){yield V(o,`${Z}:`,m.indent);return}}if(N(Y)){yield V(o,`${Z}:`,m.indent);let G=q-P,T=p?`${p}.${A}`:A;yield*Rc(Y,o+1,m,t,T,G);return}}}let g=Ec(c);if($c(a))yield V(o,`${g}: ${Pc(a,m.delimiter)}`,m.indent);else if(rc(a))yield*Aa(c,a,o,m);else if(N(a)){if(yield V(o,`${g}:`,m.indent),!Kc(a))yield*Rc(a,o+1,m,t,C,q)}}function*Aa(c,a,o,m){if(a.length===0){yield V(o,x(0,{key:c,delimiter:m.delimiter}),m.indent);return}if(_c(a)){yield V(o,vc(a,m.delimiter,c),m.indent);return}if(Ls(a)){if(a.every((s)=>_c(s))){yield*ct(c,a,o,m);return}}if(va(a)){let s=xa(a);if(s)yield*at(c,a,s,o,m);else yield*ba(c,a,o,m);return}yield*ba(c,a,o,m)}function*ct(c,a,o,m){yield V(o,x(a.length,{key:c,delimiter:m.delimiter}),m.indent);for(let s of a)if(_c(s)){let t=vc(s,m.delimiter);yield b(o+1,t,m.indent)}}function vc(c,a,o){let m=x(c.length,{key:o,delimiter:a}),s=ea(c,a);if(c.length===0)return m;return`${m} ${s}`}function*at(c,a,o,m,s){yield V(m,x(a.length,{key:c,fields:o,delimiter:s.delimiter}),s.indent),yield*fa(a,o,m+1,s)}function xa(c){if(c.length===0)return;let a=c[0],o=Object.keys(a);if(o.length===0)return;if(ot(c,o))return o}function ot(c,a){for(let o of c){if(Object.keys(o).length!==a.length)return!1;for(let m of a){if(!(m in o))return!1;if(!$c(o[m]))return!1}}return!0}function*fa(c,a,o,m){for(let s of c)yield V(o,ea(a.map((t)=>s[t]),m.delimiter),m.indent)}function*ba(c,a,o,m){yield V(o,x(a.length,{key:c,delimiter:m.delimiter}),m.indent);for(let s of a)yield*Ra(s,o+1,m)}function*mt(c,a,o){if(Kc(c)){yield V(a,"-",o.indent);return}let m=Object.entries(c),[s,t]=m[0],p=m.slice(1);if(rc(t)&&va(t)){let C=xa(t);if(C){if(yield b(a,x(t.length,{key:s,fields:C,delimiter:o.delimiter}),o.indent),yield*fa(t,C,a+2,o),p.length>0)yield*Rc(Object.fromEntries(p),a+1,o);return}}let w=Ec(s);if($c(t))yield b(a,`${w}: ${Pc(t,o.delimiter)}`,o.indent);else if(rc(t))if(t.length===0)yield b(a,`${w}${x(0,{delimiter:o.delimiter})}`,o.indent);else if(_c(t))yield b(a,`${w}${vc(t,o.delimiter)}`,o.indent);else{yield b(a,`${w}${x(t.length,{delimiter:o.delimiter})}`,o.indent);for(let C of t)yield*Ra(C,a+2,o)}else if(N(t)){if(yield b(a,`${w}:`,o.indent),!Kc(t))yield*Rc(t,a+2,o)}if(p.length>0)yield*Rc(Object.fromEntries(p),a+1,o)}function*Ra(c,a,o){if($c(c))yield b(a,Pc(c,o.delimiter),o.indent);else if(rc(c))if(_c(c))yield b(a,vc(c,o.delimiter),o.indent);else{yield b(a,x(c.length,{delimiter:o.delimiter}),o.indent);for(let m of c)yield*Ra(m,a+1,o)}else if(N(c))yield*mt(c,a,o)}function V(c,a,o){return" ".repeat(o*c)+a}function b(c,a,o){return V(c,"- "+a,o)}function st(c,a){let o=a("",c,[]);if(o===void 0)return Bc(c,a,[]);return Bc(e(o),a,[])}function Bc(c,a,o){if(N(c))return tt(c,a,o);if(rc(c))return pt(c,a,o);return c}function tt(c,a,o){let m={};for(let[s,t]of Object.entries(c)){let p=[...o,s],w=a(s,t,p);if(w===void 0)continue;m[s]=Bc(e(w),a,p)}return m}function pt(c,a,o){let m=[];for(let s=0;s<c.length;s++){let t=c[s],p=[...o,s],w=a(String(s),t,p);if(w===void 0)continue;let C=e(w);m.push(Bc(C,a,p))}return m}function Pa(c,a){return Array.from(rt(c,a)).join(`
3
+ `)}function rt(c,a){let o=e(c),m=wt(a);return xs(m.replacer?st(o,m.replacer):o,m,0)}function wt(c){return{indent:c?.indent??2,delimiter:c?.delimiter??kc,keyFolding:c?.keyFolding??"off",flattenDepth:c?.flattenDepth??Number.POSITIVE_INFINITY,replacer:c?.replacer}}function Ct(c){let a=c.format??"toon";if(a!=="toon"&&a!=="json")throw Error("--format debe ser toon o json.");return a}function co(c,a){if(Ct(a)==="json"){console.log(JSON.stringify(c,null,2));return}console.log(Pa(c))}function ao(c){process.stdout.write(`${c}
4
+ `)}function oo(c,a){let m={ok:!1,error:c instanceof Error?c.message:String(c)};if((a.format==="json"?"json":"toon")==="json"){console.error(JSON.stringify(m,null,2));return}console.error(Pa(m))}function D(c){process.stderr.write(c)}import{existsSync as fc,mkdirSync as $t,readFileSync as so,writeFileSync as lt,unlinkSync as jt}from"node:fs";import{join as to}from"node:path";import{homedir as Qt}from"node:os";import{AsyncLocalStorage as gt}from"node:async_hooks";var qt=new gt;function i(){return qt.getStore()}var ec={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"}},Wa="prod";function mo(c){Wa=c}function xc(){let c=process.env.JUSTO_TEAM_CLI_ENV;if(c)return c;let a=i()?.environment;if(a)return a;return Wa}function K(c){return ec[c][Wa]}var Ga=to(Qt(),".justo-team");function po(c){let a=c==="prod"?"credentials.json":`credentials.${c}.json`;return to(Ga,a)}function Ia(){return po(xc())}function nt(){if(!fc(Ga))$t(Ga,{recursive:!0})}function ca(c){let a=i();if(a&&a.canPersistCredentials===!1)throw Error("Este entorno no permite guardar credenciales.");nt(),lt(Ia(),JSON.stringify(c,null,2))}function F(){let c=process.env.JUSTO_TEAM_CLI_TOKEN,a=process.env.JUSTO_TEAM_CLI_EMAIL,o=process.env.JUSTO_TEAM_CLI_REFRESH_TOKEN;if(c&&a)return{email:a,token:c,refreshToken:o||""};let m=i()?.credentials;if(m!==void 0)return m?{email:m.email,token:m.token,refreshToken:m.refreshToken||""}:null;let s=Ia();if(!fc(s))return null;try{let t=so(s,"utf-8");return JSON.parse(t)}catch{return null}}function ro(c){let a=po(c);if(!fc(a))return null;try{let o=so(a,"utf-8");return JSON.parse(o)}catch{return null}}function Ma(){let c=i();if(c&&c.canPersistCredentials===!1)throw Error("Este entorno no permite borrar credenciales.");let a=Ia();if(fc(a))jt(a)}import{existsSync as wo,readFileSync as Jt,writeFileSync as At,mkdirSync as Rt}from"node:fs";import{join as Co}from"node:path";import{homedir as Pt}from"node:os";function Wt(){let c=process.env.JUSTO_TEAM_CLI_DEVICE_ID;if(c)return c;let a=i()?.deviceId;if(a)return a;let o=Co(Pt(),".justo-team"),m=Co(o,"device-id");if(wo(m))return Jt(m,"utf-8").trim();let s=crypto.randomUUID();if(!wo(o))Rt(o,{recursive:!0});return At(m,s),s}var qo={required:({label:c})=>`${c} no es opcional`,notAString:({label:c})=>`${c} no es un texto`,notANumber:({label:c})=>`${c} no es un número`,notAnInteger:({label:c})=>`${c} no es un número entero`,notABoolean:({label:c})=>`${c} no es un valor verdadero o falso`,notAnEmail:({label:c})=>`${c} no es un email`,notAnId:({label:c})=>`${c} no es un ID válido`,notADate:({label:c})=>`${c} no es una fecha válida`,notAnArray:({label:c})=>`${c} no es un arreglo`,notAnObject:({label:c})=>`${c} no es un objeto`,stringTooShort:({label:c})=>`${c} no tiene el largo suficiente`,stringTooLong:"El largo es mayor al permitido",numberTooSmall:({label:c})=>`${c} es un número muy pequeño`,numberTooBig:({label:c})=>`${c} es un número muy grande`,notInSchema:({label:c})=>`${c} no esta permitido`,notUnique:({label:c})=>`${c} no es único`,notFound:({label:c})=>`${c} 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 Gt(c,a){let o=qo[c];if(!o)return`${a}: ${c}`;if(typeof o==="function")return o({label:a});return o}function go(c){return Object.entries(c).map(([a,o])=>Gt(o,a)).join(", ")}function It(c){if(c.error==="validationError"&&c.validationErrors)return go(c.validationErrors);if(c.extensions?.code==="PermissionsError"){let s=c.extensions.info?.type;if(s?.includes("User doesn't have permissions for "))return`Tu usuario no tiene permisos para [${s.split("User doesn't have permissions for ")[1]}]`;return c.message}if(c.validationErrors)return`${c.message} (${go(c.validationErrors)})`;let a=c.message||"Error desconocido",o=qo[a];if(o)return typeof o==="function"?o({label:""}).trim():o;let m=c.error||c.code||c.type;return m?`${a} [${m}]`:a}function Mt(c){try{return JSON.parse(Buffer.from(c.split(".")[1],"base64").toString()).exp*1000<Date.now()}catch{return!0}}async function Xt(){let c=F();if(!c?.refreshToken)return null;let a=`${K("auth")}/refresh-token`,m=await(await fetch(a,{method:"POST",headers:{"X-ORION-REFRESH":c.refreshToken}})).json();if(!m.token)return null;if(i()?.canPersistCredentials!==!1)ca({...c,token:m.token});return m.token}async function aa(){let c=F();if(!c?.token)return;if(!Mt(c.token))return c.token;return await Xt()??void 0}async function Wc(c="application/json"){let a=await aa(),o={"Content-Type":c,"X-ORION-DEVICEID":Wt(),"X-ORION-PLATFORM":"web"};if(a)o["x-orion-jwt"]=a;return o}async function R(c){let a=`${K(c.service)}/graphql`,o=await Wc(),m;try{m=await fetch(a,{method:"POST",headers:o,body:JSON.stringify({query:c.query,variables:c.variables}),signal:AbortSignal.timeout(c.timeoutMs||15000)})}catch{throw Error("La solicitud tardó demasiado. Intenta de nuevo.")}let s=await m.json();if(s.errors?.length)throw Error(It(s.errors[0]));if(!s.data)throw Error("No data returned from server");return s.data}function Zt(c){return c.replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,"")}function Ht(c){return c.includes(".")||c.startsWith("http://")||c.startsWith("https://")}async function Gc(c){if(Ht(c)){let a=Zt(c),o=await fetch(`${K("main")}/website-id/${a}`,{signal:AbortSignal.timeout(1e4)});if(!o.ok)throw Error(`No se encontro el sitio "${a}"`);let m=await o.json();if(!m.websiteId)throw Error(`No se pudo resolver el websiteId para "${a}"`);return{input:c,websiteId:m.websiteId,targetType:"domain"}}return{input:c,websiteId:c,targetType:"websiteId"}}async function $o(c){let a=await R({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 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
16
+ }`,variables:{websiteId:c}});if(!a.website)throw Error(`No se encontro el website "${c}"`);return a.website}function Yt(){if(!F())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 lo(c){if(Yt(),!c)throw Error("Uso: team-cli admin <websiteId|domain> show");let a=await Gc(c),o=await $o(a.websiteId);return{context:a,website:o}}function oa(){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 pr=`
38
+ Uso: team-cli admin <websiteId|domain> coupons <accion> [opciones]`}var jo=`
39
39
  availableAtPeriods
40
40
  closedDays
41
41
  closedUntilDate
@@ -51,7 +51,7 @@ Modulos:
51
51
  fromMinute
52
52
  toMinute
53
53
  }
54
- `,fe=`
54
+ `,ma=`
55
55
  _id
56
56
  websiteId
57
57
  name
@@ -86,13 +86,13 @@ Modulos:
86
86
  requiredBINs
87
87
  extraRequirementsForPaymentTypes
88
88
  schedule {
89
- ${pr}
89
+ ${jo}
90
90
  }
91
91
  scheduleAtUse {
92
- ${pr}
92
+ ${jo}
93
93
  }
94
94
  codesCode
95
- `,gr=`
95
+ `,Qo=`
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 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) {
104
+ `;function Xa(){if(!F())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 Ic(c,a){let o=c[a];if(!o)throw Error(`--${a} es requerido.`);try{return JSON.parse(o)}catch{throw Error(`--${a} debe ser un JSON válido.`)}}function B(c,a){let o=c[a];if(!o)return;let m=Number.parseInt(o,10);if(Number.isNaN(m))throw Error(`--${a} debe ser un número entero.`);return m}function no(c,a){let o=c[a];if(!o)return;if(o==="true")return!0;if(o==="false")return!1;throw Error(`--${a} debe ser true o false.`)}async function d(c){if(Xa(),!c)throw Error("Debes indicar <websiteId|domain>.");return Gc(c)}async function f(c,a){let o=await R({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 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) {
109
+ }`,variables:{couponId:c}});if(!o.coupon)throw Error(`No se encontró el cupón "${c}"`);if(o.coupon.websiteId!==a)throw Error(`El cupón "${c}" no pertenece al website seleccionado.`);return o.coupon}function Ft(c){if(!Array.isArray(c))throw Error("--input debe ser un arreglo JSON.");return c.map((a)=>{if(!a||typeof a!=="object"||typeof a.code!=="string")throw Error('Cada item de --input debe tener al menos { "code": "..." }.');if(a.userEmail!=null&&typeof a.userEmail!=="string")throw Error("userEmail debe ser string cuando viene informado.");return{code:a.code,userEmail:a.userEmail}})}function Ut(c){if(!Array.isArray(c)||c.some((a)=>typeof a!=="string"))throw Error("--ids debe ser un arreglo JSON de strings.");return c}async function Jo(c,a,o){let m=await d(c);await f(a,m.websiteId);let s=B(o,"limit"),t=B(o,"page"),p=o.filter,w=await R({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
- ${gr}
112
+ ${Qo}
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 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) {
119
+ }`,variables:{couponId:a,filter:p,limit:s,page:t}});return{context:m,couponId:a,codes:w.couponCodes.items??[],pagination:{totalCount:w.couponCodes.totalCount??0,totalPages:w.couponCodes.totalPages??0,hasNextPage:Boolean(w.couponCodes.hasNextPage),hasPreviousPage:Boolean(w.couponCodes.hasPreviousPage),page:t??1,limit:s??null}}}async function Ao(c,a,o){let m=await d(c);await f(a,m.websiteId);let s=Ft(Ic(o,"input")),t=s.some((w)=>w.userEmail),p=await R({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 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) {
121
+ }`,variables:{couponId:a,codesWithEmail:s,useCodeWithEmail:t}});return{context:m,couponId:a,requestedCount:s.length,result:p.createCouponCodes}}async function Ro(c,a,o){let m=await d(c);await f(a,m.websiteId);let s=B(o,"quantity");if(!s)throw Error("--quantity es requerido.");let t=await R({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 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]) {
123
+ }`,variables:{couponId:a,couponQuantity:s,couponCodePrefix:o.prefix}});return{context:m,couponId:a,quantity:s,prefix:o.prefix??null,result:t.createRandomCouponCodes}}async function Po(c,a,o){let m=await d(c);await f(a,m.websiteId);let s=Ut(Ic(o,"ids")),t=await R({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 qr(){return`team-cli admin coupons codes create
125
+ }`,variables:{couponId:a,couponCodesIds:s}});return{context:m,couponId:a,deleted:t.deleteCouponCodes,couponCodesIds:s}}function Wo(){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 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
- createCoupon(${a}) {
150
- ${fe}
148
+ couponId se valida contra el website seleccionado antes de ejecutar la mutation.`}var Go={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 Tt(c){let a=Object.entries(c).filter(([,t])=>t!==void 0),o=a.map(([t])=>t).filter((t)=>!Go[t]);if(o.length)throw Error(`Campos no soportados para create: ${o.join(", ")}`);let m=a.map(([t])=>`$${t}: ${Go[t]}`).join(", "),s=a.map(([t])=>`${t}: $${t}`).join(", ");return`mutation (${m}) {
149
+ createCoupon(${s}) {
150
+ ${ma}
151
151
  }
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) {
152
+ }`}async function Io(c,a){let o=await d(c),m=B(a,"limit"),s=B(a,"page"),t=a.filter,p=await R({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 S(e);await A(r,t.websiteId);let o=await u({service:"main",query:`query ($couponId: ID) {
172
+ }`,variables:{websiteId:o.websiteId,filter:t,limit:m,page:s}});return{context:o,coupons:p.coupons.items??[],pagination:{totalCount:p.coupons.totalCount??0,totalPages:p.coupons.totalPages??0,hasNextPage:Boolean(p.coupons.hasNextPage),hasPreviousPage:Boolean(p.coupons.hasPreviousPage),page:s??1,limit:m??null}}}async function Mo(c,a){let o=await d(c);await f(a,o.websiteId);let m=await R({service:"main",query:`query ($couponId: ID) {
173
173
  coupon(couponId: $couponId) {
174
- ${fe}
174
+ ${ma}
175
175
  }
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) {
176
+ }`,variables:{couponId:a}});return{context:o,coupon:m.coupon}}async function Xo(c,a){let o=await d(c),m=Ic(a,"input");if(m.websiteId&&m.websiteId!==o.websiteId)throw Error("El websiteId del input no coincide con el website seleccionado.");let s={...m,websiteId:o.websiteId},t=Tt(s),p=await R({service:"main",query:t,variables:s});return{context:o,coupon:p.createCoupon}}async function Zo(c,a,o){let m=await d(c);await f(a,m.websiteId);let s=Ic(o,"input"),t=await R({service:"main",query:`mutation ($couponId: ID, $coupon: UpdateCouponInput) {
177
177
  updateCoupon(couponId: $couponId, coupon: $coupon) {
178
- ${fe}
178
+ ${ma}
179
179
  }
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]) {
180
+ }`,variables:{couponId:a,coupon:s}});return{context:m,coupon:t.updateCoupon}}async function Ho(c,a){let o=await d(c);await f(a,o.websiteId);let m=await R({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 K(){return`team-cli admin coupons
182
+ }`,variables:{couponsIds:[a]}});return{context:o,couponId:a,deleted:m.deleteCoupons}}function Vc(){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 vr(){return`team-cli admin coupons create
230
+ El schema actual no expone update para coupon codes.`}function Yo(){return`team-cli admin coupons create
231
231
 
232
232
  Crea un cupón para el website seleccionado.
233
233
 
@@ -276,7 +276,7 @@ Ejemplo con schedule:
276
276
  Tips:
277
277
  Usa comillas simples afuera del JSON en shell.
278
278
  Usa arrays JSON reales para ids o listas.
279
- Si necesitas el shape exacto de un cupón existente, parte con: team-cli admin <web> coupons show <couponId>`}function jr(){return`team-cli admin coupons update
279
+ Si necesitas el shape exacto de un cupón existente, parte con: team-cli admin <web> coupons show <couponId>`}function Fo(){return`team-cli admin coupons update
280
280
 
281
281
  Actualiza un cupón existente.
282
282
 
@@ -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 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) {
321
+ Primero mira el cupón actual con: team-cli admin <web> coupons show <couponId>`}async function Uo(c,a){Xa();let o=c[2]??a.filter;if(!o)throw Error("Debes indicar un término de búsqueda. Uso: team-cli admin search <texto>");let m=B(a,"limit"),s=B(a,"page"),t=no(a,"only-active"),p=await R({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 Rr(){return`team-cli admin search
337
+ }`,variables:{filter:o,limit:m,page:s,onlyActiveWebsites:t}});return{searchTerm:o,websites:p.websites.items??[],pagination:{totalCount:p.websites.totalCount??0,totalPages:p.websites.totalPages??0,hasNextPage:Boolean(p.websites.hasNextPage),hasPreviousPage:Boolean(p.websites.hasPreviousPage),page:s??1,limit:m??null}}}function To(){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 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) {
357
+ team-cli admin search pizza --only-active true`}function ht(){if(!F())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 Kt(c){let a=[c.address?.streetAddress,c.address?.extendedAddress,c.address?.locality].filter(Boolean);if(!a.length)return null;return a.join(", ")}async function ho(c){if(ht(),!c)throw Error("Uso: team-cli admin <websiteId|domain> stores list");let a=await Gc(c),m=((await R({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: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!) {
369
+ }`,variables:{websiteId:a.websiteId}})).stores.items??[]).map((s)=>({_id:s._id,name:s.name,address:Kt(s)})).sort((s,t)=>s.name.localeCompare(t.name,"es",{sensitivity:"base"}));return{context:a,stores:m,totalCount:m.length}}import{createInterface as _t}from"node:readline";function Mc(c){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 a=_t({input:process.stdin,output:process.stderr});return new Promise((o)=>{a.question(c,(m)=>{a.close(),o(m.trim())})})}async function Ko(c){return(await R({service:"auth",query:`mutation ($email: String!) {
370
370
  requestLoginCode(email: $email)
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!) {
371
+ }`,variables:{email:c}})).requestLoginCode}async function _o(c,a,o){let m=await R({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 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
376
+ }`,variables:{email:c,token:a,code:o.toUpperCase()}});ca({email:c,token:m.loginWithCode.token,refreshToken:m.loginWithCode.refreshToken}),await Et()}async function Et(){if(!(await R({service:"main",query:"query { me { roles } }"})).me?.roles?.length)throw Ma(),Error("Solo miembros del equipo Justo pueden usar esta herramienta.")}async function Eo(){let c=await Mc("Email: ");D(`Enviando codigo de verificacion...
377
+ `);let a=await Ko(c);D(`Codigo enviado a tu email.
378
+ `);let o=await Mc("Codigo: ");return await _o(c,a,o),{ok:!0,authenticated:!0,email:c}}async function ko(c){let a=hc(c,"email"),o=hc(c,"token"),m=hc(c,"code");return await _o(a,o,m),{ok:!0,authenticated:!0,email:a}}async function Vo(c){let a=hc(c,"email");D(`Enviando codigo de verificacion...
379
+ `);let o=await Ko(a);return{ok:!0,email:a,token:o,nextCommand:`npx @getjusto/team-cli auth login-with-token --email ${a} --token ${o} --code <CODIGO>`}}async function Do(){return Ma(),{ok:!0,authenticated:!1}}async function zo(){let c=F();if(!c)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:c.email}}function Za(){return`team-cli auth
380
380
 
381
381
  Gestion de sesion.
382
382
 
@@ -402,7 +402,287 @@ 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 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'
405
+ Uso: team-cli auth login-with-token --email <email> --token <token> --code <codigo>`}import{writeFileSync as it}from"node:fs";import{mkdtempSync as kt,readFileSync as Vt,rmSync as Dt,writeFileSync as zt}from"node:fs";import{tmpdir as yt}from"node:os";import{join as yo}from"node:path";import{spawnSync as St}from"node:child_process";function ut(c){return`'${c.replaceAll("'",`'"'"'`)}'`}function So(c,a){if(c==null)return;if(!Array.isArray(c)||c.some((o)=>typeof o!=="string"))throw Error(`${a} debe ser un arreglo de strings.`);return c}function Lt(c){if(!Array.isArray(c))throw Error("variables debe ser un arreglo.");return c.map((a,o)=>{if(!a||typeof a!=="object"||Array.isArray(a))throw Error(`variables[${o}] debe ser un objeto.`);let m=a;if(typeof m.key!=="string"||!m.key)throw Error(`variables[${o}].key debe ser un string no vacío.`);if(typeof m.fieldType!=="string"||!m.fieldType)throw Error(`variables[${o}].fieldType debe ser un string no vacío.`);if(m.fieldParams!=null&&typeof m.fieldParams!=="string")throw Error(`variables[${o}].fieldParams debe ser un string.`);return{key:m.key,fieldType:m.fieldType,fieldParams:typeof m.fieldParams==="string"?m.fieldParams:void 0}})}function Nt(c){if(!c||typeof c!=="object"||Array.isArray(c))throw Error("El archivo editado debe contener un objeto JSON.");let a=c;if(typeof a.name!=="string"||!a.name.trim())throw Error("name debe ser un string no vacío.");if(a.description!=null&&typeof a.description!=="string")throw Error("description debe ser un string.");if(typeof a.collection!=="string"||!a.collection.trim())throw Error("collection debe ser un string no vacío.");if(typeof a.pipeline!=="string")throw Error("pipeline debe ser un string.");return{name:a.name.trim(),description:a.description?.trim()||void 0,collection:a.collection.trim(),allowedUsersIds:So(a.allowedUsersIds,"allowedUsersIds")??[],tags:So(a.tags,"tags")??[],pipeline:a.pipeline,variables:Lt(a.variables)}}function uo(c){let a=process.env.VISUAL||process.env.EDITOR||"vi",o=kt(yo(yt(),"team-cli-query-")),m=yo(o,"aggregation-query.json");zt(m,`${JSON.stringify(c,null,2)}
406
+ `);let s=`${a} ${ut(m)}`,t=St(s,{shell:!0,stdio:"inherit"});if(t.error)throw Error(`No se pudo abrir el editor "${a}": ${t.error.message}`);if(t.status!==0)throw Error(`El editor terminó con código ${t.status}.`);try{let p=Vt(m,"utf-8");if(!p.trim())throw Error("El archivo quedó vacío.");let w;try{w=JSON.parse(p)}catch{throw Error("El archivo editado no contiene JSON válido.")}return Nt(w)}finally{Dt(o,{recursive:!0,force:!0})}}function u(){if(!F())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 cc(c,a){let o=c[3];if(!o)throw Error(`Uso: ${a}`);return o}function Xc(c){if(!c.params)return{};try{return JSON.parse(c.params)}catch{throw Error("--params debe ser un JSON válido.")}}function Ha(c){let a=c.limit;if(!a)throw Error("--limit es requerido. Ejemplo: --limit 1000");let o=Number(a);if(!Number.isInteger(o)||o<=0)throw Error("--limit debe ser un entero positivo.");return o}function Lo(c){let a=c.emails;if(!a)throw Error("--emails es requerido. Ejemplo: --emails ana@justo.com,bob@justo.com");let o=a.split(",").map((s)=>s.trim().toLowerCase()).filter(Boolean);if(!o.length)throw Error("--emails debe contener al menos un email.");let m=o.find((s)=>!s.includes("@"));if(m)throw Error(`Email inválido: ${m}`);return[...new Set(o)]}function Ya(c){if(typeof c!=="string")return c;try{return JSON.parse(c)}catch{return{value:c}}}async function Zc(c){return(await R({service:"data",query:`query ($aggregationQueryId: String) {
407
+ aggregationQuery(aggregationQueryId: $aggregationQueryId) {
408
+ _id
409
+ name
410
+ description
411
+ collection
412
+ currentVersionIndex
413
+ allowedUsersIds
414
+ tags
415
+ pipeline
416
+ variables {
417
+ key
418
+ fieldType
419
+ fieldParams
420
+ }
421
+ }
422
+ }`,variables:{aggregationQueryId:c}})).aggregationQuery}async function No(c){return await Promise.all(c.map(async(o)=>{let s=(await R({service:"main",query:`query ($filter: String, $limit: BigInt) {
423
+ justoUsers(filter: $filter, limit: $limit) {
424
+ items {
425
+ _id
426
+ email
427
+ fullName
428
+ }
429
+ }
430
+ }`,variables:{filter:o,limit:10}})).justoUsers?.items?.find((t)=>t.email?.toLowerCase()===o);if(!s?._id)throw Error(`No encontramos un usuario de Justo para ${o}`);return s}))}function io(c){return{name:c.name,description:c.description,collection:c.collection,allowedUsersIds:c.allowedUsersIds??[],tags:c.tags??[],pipeline:c.pipeline,variables:c.variables??[]}}async function Fa(c,a){let o=await R({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
431
+ testAggregationQuery(aggregationQueryId: $aggregationQueryId, params: $params)
432
+ }`,variables:{aggregationQueryId:c,params:a}});return Ya(o.testAggregationQuery)}async function Oo(c){let a=await fetch(`${K("data")}/execute-pipeline`,{method:"POST",headers:await Wc(),body:JSON.stringify({collection:c.collection,pipeline:c.pipeline,params:c.queryParams,limit:c.limit}),signal:AbortSignal.timeout(75000)});if(!a.ok){let o=await a.text();throw Error(bo(o)||"No se pudo ejecutar el pipeline.")}return await a.json()}function bo(c){try{return JSON.parse(c).error||c}catch{return c}}async function Bo(c,a,o){let m=await fetch(`${K("data")}/aggregation-queries/${c}/run`,{method:"POST",headers:await Wc(),body:JSON.stringify({params:a,limit:o}),signal:AbortSignal.timeout(315000)});if(!m.ok){let q=await m.text();throw Error(bo(q)||"No se pudo ejecutar el query.")}if(!m.body)throw Error("El servidor no devolvió un stream de datos.");let s=m.body.getReader(),t=new TextDecoder,p="",w=0;while(!0){let{done:q,value:g}=await s.read();if(q)break;let Q=t.decode(g,{stream:!0});process.stdout.write(Q),p+=Q;let A=p.indexOf(`
433
+ `);while(A>=0){if(p.slice(0,A).trim())w++;p=p.slice(A+1),A=p.indexOf(`
434
+ `)}}let C=t.decode();if(C)process.stdout.write(C),p+=C;if(p.trim())w++;return{ok:!0,queryId:c,limit:o,rows:w}}async function Ua(c,a){await Ta(c,{name:a.name,description:a.description,collection:a.collection,allowedUsersIds:a.allowedUsersIds,tags:a.tags}),await R({service:"data",query:`mutation ($aggregationQueryId: String, $pipeline: String, $variables: [AggregationQueryVariableInput]) {
435
+ addAggregationQueryVersion(
436
+ aggregationQueryId: $aggregationQueryId
437
+ pipeline: $pipeline
438
+ variables: $variables
439
+ ) {
440
+ _id
441
+ currentVersionIndex
442
+ }
443
+ }`,variables:{aggregationQueryId:c,pipeline:a.pipeline,variables:a.variables}})}async function Ta(c,a){await R({service:"data",query:`mutation ($aggregationQueryId: String, $aggregationQuery: UpdateAggregationQueryInput) {
444
+ updateAggregationQuery(
445
+ aggregationQueryId: $aggregationQueryId
446
+ aggregationQuery: $aggregationQuery
447
+ ) {
448
+ _id
449
+ name
450
+ description
451
+ collection
452
+ allowedUsersIds
453
+ tags
454
+ currentVersionIndex
455
+ }
456
+ }`,variables:{aggregationQueryId:c,aggregationQuery:{name:a.name,description:a.description,collection:a.collection,allowedUsersIds:a.allowedUsersIds,tags:a.tags}}})}async function vo(){return(await R({service:"data",query:`mutation {
457
+ createAggregationQuery {
458
+ _id
459
+ name
460
+ description
461
+ collection
462
+ currentVersionIndex
463
+ allowedUsersIds
464
+ tags
465
+ pipeline
466
+ variables {
467
+ key
468
+ fieldType
469
+ fieldParams
470
+ }
471
+ }
472
+ }`})).createAggregationQuery}function dt(c){if(!Array.isArray(c))throw Error("El preview del query debe devolver un arreglo para usar AI edit.");return c}async function Ot(c){let a=await R({service:"messenger",query:`mutation generateAdminQuery(
473
+ $prompt: String
474
+ $name: String
475
+ $description: String
476
+ $fullCollectionName: String
477
+ $variables: [JSON]
478
+ $pipeline: String
479
+ $preview: [JSON]
480
+ ) {
481
+ generateAdminQuery(
482
+ prompt: $prompt
483
+ name: $name
484
+ description: $description
485
+ fullCollectionName: $fullCollectionName
486
+ variables: $variables
487
+ pipeline: $pipeline
488
+ preview: $preview
489
+ canUseVariables: true
490
+ ) {
491
+ responseText
492
+ fullCollectionName
493
+ pipeline
494
+ variables
495
+ aggregationDescription
496
+ aggregationName
497
+ }
498
+ }`,variables:c});if(!a.generateAdminQuery?.pipeline||!a.generateAdminQuery.fullCollectionName)throw Error("La IA no devolvió una versión válida del query.");return a.generateAdminQuery}async function bt(c){let a=await R({service:"messenger",timeoutMs:120000,query:`mutation explainAdminQuery($prompt: String) {
499
+ explainAdminQuery(prompt: $prompt) {
500
+ responseText
501
+ }
502
+ }`,variables:{prompt:c}});if(!a.explainAdminQuery?.responseText)throw Error("La IA no devolvió una explicación válida.");return a.explainAdminQuery}async function eo(){return u(),await vo()}async function xo(c){u();let a=c.prompt||await Mc("Explica qué query quieres investigar o construir: ");if(!a)throw Error("Debes indicar un prompt para explain.");return(await bt(a)).responseText}async function fo(c){if(u(),!c.collection)throw Error("Debes indicar --collection con formato db.collection. Ejemplo: --collection justo.users");if(!c.pipeline)throw Error("Debes indicar --pipeline. Ejemplo: --pipeline '[{$limit: 5}]'");let a=c.limit?Ha(c):void 0;return await Oo({collection:c.collection,pipeline:c.pipeline,queryParams:Xc(c),limit:a})}async function cm(c){u();let a=cc(c,"team-cli data queries edit <queryId>"),o=await Zc(a),m=uo(io(o));return await Ua(a,m),{ok:!0,queryId:a,name:m.name,collection:m.collection}}async function am(c,a){u();let o=cc(c,"team-cli data queries ai-edit <queryId> --prompt '<texto>' [--params '<json>']"),m=await Zc(o),s=a.prompt||await Mc("Describe los cambios para la IA: ");if(!s)throw Error("Debes indicar un prompt para AI edit.");let t=Xc(a),p;if(a.params){D(`Obteniendo preview del query actual...
503
+ `);try{let C=await Fa(o,t);p=dt(C)}catch(C){let q=C instanceof Error?C.message:String(C);throw Error(`No se pudo obtener el preview para AI edit: ${q}`)}}D(`Generando propuesta con IA...
504
+ `);let w=await Ot({prompt:s,fullCollectionName:m.collection,pipeline:m.pipeline,preview:p,description:m.description,name:m.name,variables:m.variables});return await Ua(o,{name:m.name==="Nuevo query"?w.aggregationName||m.name:m.name,description:m.description||w.aggregationDescription,collection:w.fullCollectionName,allowedUsersIds:m.allowedUsersIds??[],tags:m.tags??[],pipeline:w.pipeline,variables:w.variables??[]}),{ok:!0,queryId:o,responseText:w.responseText,collection:w.fullCollectionName,name:w.aggregationName,description:w.aggregationDescription}}async function om(c){u();let a=cc(c,"team-cli data queries view <queryId>");return await Zc(a)}async function mm(c){u();let a=cc(c,"team-cli data queries view-pipeline <queryId>"),o=await Zc(a);return{queryId:a,pipeline:o.pipeline}}async function sm(c,a){u();let o=cc(c,"team-cli data queries preview <queryId> --params '<json>'"),m=Xc(a),s=await Fa(o,m);return Ya(s)}async function tm(c,a){u();let o=cc(c,"team-cli data queries run <queryId> --limit <n> --params '<json>'"),m=Xc(a),s=Ha(a);return await Bo(o,m,s),{__streamHandled:!0}}async function pm(c,a){u();let o=cc(c,"team-cli data queries add-viewers <queryId> --emails 'ana@justo.com,bob@justo.com'"),m=Lo(a),s=await Zc(o),t=await No(m),p=[...new Set([...s.allowedUsersIds??[],...t.map((w)=>w._id)])];return await Ta(o,{name:s.name,description:s.description,collection:s.collection,allowedUsersIds:p,tags:s.tags??[]}),{ok:!0,queryId:o,addedViewers:t.map((w)=>({_id:w._id,email:w.email,fullName:w.fullName})),allowedUsersIds:p}}function Bt(c){return new Promise((a)=>setTimeout(a,c))}async function rm(c,a){u();let o=cc(c,"team-cli data queries download <queryId> --params '<json>'"),m=Xc(a);if(!a.path)throw Error("--path es requerido. Ejemplo: --path resultado.xlsx");D(`Iniciando descarga...
505
+ `);let t=(await R({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
506
+ downloadAggregationQueryData(aggregationQueryId: $aggregationQueryId, params: $params)
507
+ }`,variables:{aggregationQueryId:o,params:m}})).downloadAggregationQueryData;D(`Reporte en proceso (${t})...
508
+ `);let p=null;while(!p){await Bt(1000);let q=await R({service:"data",query:`query ($id: String) {
509
+ getAsyncReport(id: $id) {
510
+ _id
511
+ status
512
+ estimatedRecordsCount
513
+ fileUrl
514
+ }
515
+ getAsyncReportRecordsCount(id: $id)
516
+ }`,variables:{id:t}}),g=q.getAsyncReport,Q=q.getAsyncReportRecordsCount;if(g.status==="error")throw Error("El reporte falló al generarse.");if(g.fileUrl)p=g.fileUrl;else{let A=g.estimatedRecordsCount?` (~${g.estimatedRecordsCount} registros)`:"",Y=Q!=null?` ${Q} procesados`:"";D(`\rGenerando...${A}${Y}`)}}D(`
517
+ Descargando archivo...
518
+ `);let w=await fetch(p);if(!w.ok)throw Error(`Error descargando archivo: ${w.status}`);let C=Buffer.from(await w.arrayBuffer());return it(a.path,C),{ok:!0,queryId:o,asyncReportId:t,outputPath:a.path,fileUrl:p}}function ha(){return`team-cli data
519
+
520
+ Comandos de datos y reportes.
521
+
522
+ Recomendado:
523
+ Si necesitas obtener data y no existe un query listo, usa explain -> create -> ai-edit.
524
+ Flujo sugerido: explain -> create -> ai-edit -> preview -> run o download.
525
+ Usa queries cuando quieras que la consulta quede guardada, versionada y compartible.
526
+ Usa execute solo para correr un pipeline una vez.
527
+ Para spaces, prefiere siempre queries guardados en vez de execute directo.
528
+ Siempre que puedas, prefiere varias queries simples antes que un solo pipeline con lookup.
529
+ Para dashboards suele ser mejor resolver joins en la UI o con queries separadas.
530
+ Caso común:
531
+ 1. Usa explain para investigar servicio, colección, fields o resolvers.
532
+ 2. Usa execute para probar un pipeline una sola vez.
533
+ 3. Si lo vas a reutilizar, conviértelo en query guardado con create + ai-edit.
534
+
535
+ Uso:
536
+ team-cli data <subcomando> [opciones]
537
+
538
+ Subcomandos:
539
+ explain
540
+ Pedir una explicación guiada para investigar cómo construir un query o cómo consultar datos por GraphQL usando el subagente de repo.
541
+ Uso: team-cli data explain --prompt '<texto>' [--format toon|json]
542
+ Solo disponible para usuarios con rol queries.
543
+
544
+ execute
545
+ Ejecutar un pipeline directo sin crear un query guardado.
546
+ Piensa en esto como ejecución ad-hoc de una sola vez.
547
+ Solo lectura: bloquea stages de escritura como $out y $merge.
548
+ Usa timeout de 1 minuto, read preference secondaryPreferred y requiere rol queries.
549
+ Para spaces y dashboards compartibles, prefiere queries guardados con data queries create + ai-edit.
550
+ Uso: team-cli data execute --collection <db.collection> --pipeline '<array js>' [--params '<json>'] [--limit <n>] [--format toon|json]
551
+
552
+ queries
553
+ Administrar y ejecutar aggregation queries guardados.
554
+
555
+ Uso de queries:
556
+ team-cli data queries <subcomando> [opciones]
557
+
558
+ Subcomandos de queries:
559
+ create
560
+ Crear un query nuevo.
561
+ Devuelve el _id para seguir con edit, ai-edit, view o preview.
562
+
563
+ edit <queryId>
564
+ Editar un query manualmente en tu editor local usando JSON.
565
+ Campos editables: name, description, collection, allowedUsersIds, tags, pipeline, variables.
566
+ El pipeline debe quedar como string con un array JavaScript válido.
567
+
568
+ ai-edit <queryId>
569
+ Editar un query con IA.
570
+ Uso: team-cli data queries ai-edit <queryId> --prompt '<texto>' [--params '<json>'] [--format toon|json]
571
+ Si envías --params, primero se ejecuta preview y esos resultados se adjuntan al prompt.
572
+
573
+ view <queryId>
574
+ Ver informacion de un query.
575
+
576
+ view-pipeline <queryId>
577
+ Ver el pipeline de un query.
578
+
579
+ preview <queryId>
580
+ Ejecutar un query de prueba.
581
+ Uso: team-cli data queries preview <queryId> --params '<json>' [--format toon|json]
582
+
583
+ run <queryId>
584
+ Ejecutar un query completo en streaming NDJSON.
585
+ Usa timeout de 5 minutos y read preference secondaryPreferred.
586
+ Uso: team-cli data queries run <queryId> --limit <n> [--params '<json>']
587
+
588
+ download <queryId>
589
+ Descargar resultado completo como Excel.
590
+ Uso: team-cli data queries download <queryId> --path <filepath> [--params '<json>'] [--format toon|json]
591
+
592
+ add-viewers <queryId>
593
+ Agregar personas con acceso a un query usando sus emails de Justo.
594
+ Uso: team-cli data queries add-viewers <queryId> --emails 'ana@justo.com,bob@justo.com'
595
+ Esto actualiza allowedUsersIds sin cambiar el pipeline ni crear una versión nueva.
596
+
597
+ Opciones:
598
+ --params '<json>' Parametros del query. Default: {}
599
+ --limit <n> Requerido para run. En execute es opcional y limita resultados.
600
+ --emails '<csv>' Requerido para add-viewers. Lista separada por comas.
601
+ --prompt '<texto>' Prompt para ai-edit. Si no viene, se pide interactivamente.
602
+ --collection <db.collection> Requerido para execute.
603
+ --pipeline '<array js>' Requerido para execute.
604
+ --format <toon|json> Usa toon por defecto cuando el comando lo ejecute un agente como Codex o Claude.
605
+ --path <filepath> Requerido para download
606
+
607
+ Ejemplos:
608
+ team-cli data explain --prompt 'Quiero entender dónde viven los campos de courier de los pedidos'
609
+ team-cli data explain --prompt 'Quiero saber cómo consultar tabs por GraphQL y qué resolvers mirar'
610
+ team-cli data execute --collection justo.users --pipeline '[{$limit: 5}, {$project: {_id: 1, createdAt: 1}}]'
611
+ team-cli data queries create
612
+ team-cli data queries edit abc123
613
+ team-cli data queries ai-edit abc123 --prompt 'Filtra solo ordenes canceladas'
614
+ team-cli data queries ai-edit abc123 --prompt 'Ajusta el pipeline' --params '{"websiteId":"w1"}'
615
+ team-cli data queries preview abc123 --params '{"startDate": "2026-01-01"}'
616
+ team-cli data queries run abc123 --limit 1000 --params '{"startDate": "2026-01-01"}'
617
+ team-cli data queries download abc123 --params '{"startDate": "2026-01-01"}' --path resultado.xlsx
618
+ team-cli data queries add-viewers abc123 --emails 'ana@justo.com,bob@justo.com'`}var wm=["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"],Cm=`
619
+ query ResolverInfo($name: ID!, $mutation: Boolean!) {
620
+ params(name: $name, mutation: $mutation) {
621
+ name
622
+ params
623
+ result
624
+ basicResultQuery
625
+ }
626
+ }
627
+ `;function vt(c){if(!c)throw Error("Uso: team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]");if(!wm.includes(c))throw Error(`Servicio "${c}" no válido. Servicios disponibles: ${wm.join(", ")}`)}async function et(c,a){let o;try{let m=await R({service:c,query:Cm,variables:{name:a,mutation:!1}});return{service:c,operationName:a,operationType:"query",info:m.params}}catch(m){o=m}try{let m=await R({service:c,query:Cm,variables:{name:a,mutation:!0}});return{service:c,operationName:a,operationType:"mutation",info:m.params}}catch(m){let s=o instanceof Error?o.message:"",t=m instanceof Error?m.message:"";if(s.includes('Cannot query field "params"')||t.includes('Cannot query field "params"'))throw Error(`El servicio "${c}" no expone metadata de resolvers por GraphQL.`);throw o instanceof Error?o:m}}async function gm(c,a){let o=c[1],m=c[2],s=c[2];if(!F())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(vt(o),m==="info"){let w=c[3];if(!w)throw Error("Uso: team-cli graphql <servicio> info <queryName|mutationName> [--format toon|json]");return await et(o,w)}if(!s)throw Error("Uso: team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]");let t;if(a.variables)try{t=JSON.parse(a.variables)}catch{throw Error("Las variables deben ser un JSON válido.")}return await R({service:o,query:s,variables:t})}function qm(){return Object.keys(ec)}function xt(){return qm().map((c)=>{let a=ec[c].prod;return`- \`${c}\`: \`${a}/graphql\``}).join(`
628
+ `)}function $m(){let a=qm().join(", "),o=xt();return`team-cli graphql
629
+
630
+ Ejecutar queries y mutations GraphQL.
631
+
632
+ Uso:
633
+ team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]
634
+ team-cli graphql <servicio> info <queryName|mutationName> [--format toon|json]
635
+
636
+ Comando info:
637
+ Consulta la metadata publicada por OrionJS para un query o mutation.
638
+ Devuelve el tipo de operación, los params serializados, el resultado y un basicResultQuery.
639
+ Si no indicas si es query o mutation, la CLI prueba ambas automáticamente.
640
+
641
+ Formato:
642
+ Por defecto usa toon. Usa --format json para JSON estándar.
643
+
644
+
645
+
646
+ Servicios disponibles: ${a}.
647
+
648
+ Ejemplos:
649
+ \`\`\`bash
650
+ npx @getjusto/team-cli graphql main 'query { me { _id roles } }'
651
+ npx @getjusto/team-cli graphql main 'query($id: ID) { user(userId: $id) { _id } }' --variables '{"id": "abc123"}'
652
+ npx @getjusto/team-cli graphql tabs 'query { tab(tabId: "t123") { _id status } }' --format json
653
+ \`\`\`
654
+
655
+ ### graphql info
656
+
657
+ Úsalo cuando conoces el nombre del resolver pero no su contrato exacto.
658
+
659
+ \`\`\`bash
660
+ npx @getjusto/team-cli graphql <service> info <queryName|mutationName> [--format toon|json]
661
+ \`\`\`
662
+
663
+ Devuelve:
664
+ - \`operationType\`
665
+ - \`info.params\`
666
+ - \`info.result\`
667
+ - \`info.basicResultQuery\`
668
+
669
+ Ejemplos:
670
+ \`\`\`bash
671
+ npx @getjusto/team-cli graphql main info website
672
+ npx @getjusto/team-cli graphql auth info requestLoginCode --format json
673
+ \`\`\`
674
+
675
+ ### Mapa de servicios GraphQL
676
+
677
+ Usa esto para mapear una URL GraphQL al valor correcto de \`team-cli graphql <service>\`.
678
+
679
+ ${o}`}import{existsSync as Lr,mkdirSync as Nr,readdirSync as ir}from"node:fs";import{resolve as Xs}from"node:path";import{randomBytes as ft}from"crypto";var cp=(()=>{let c=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag).get;return(a)=>c.call(a)})();function Zm(c){return cp(c)==="Uint8Array"}function ap(c){return typeof c==="object"&&c!=null&&Symbol.toStringTag in c&&(c[Symbol.toStringTag]==="ArrayBuffer"||c[Symbol.toStringTag]==="SharedArrayBuffer")}function op(c){return c instanceof RegExp||Object.prototype.toString.call(c)==="[object RegExp]"}function Hm(c){return typeof c==="object"&&c!=null&&Symbol.toStringTag in c&&c[Symbol.toStringTag]==="Map"}function mp(c){return c instanceof Date||Object.prototype.toString.call(c)==="[object Date]"}function y(c,a){return JSON.stringify(c,(o,m)=>{if(typeof m==="bigint")return{$numberLong:`${m}`};else if(Hm(m))return Object.fromEntries(m);return m})}function sp(c){if(c!=null&&typeof c==="object"&&"stylize"in c&&typeof c.stylize==="function")return c.stylize}var za=6,Ym=Symbol.for("@@mdb.bson.version"),ya=2147483647,Sa=-2147483648,Fm=Math.pow(2,63)-1,Um=-Math.pow(2,63),tp=Math.pow(2,53),pp=-Math.pow(2,53);var Tm=4,PC=Object.freeze({double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:-1,maxKey:127});class $ extends Error{get bsonError(){return!0}get name(){return"BSONError"}constructor(c,a){super(c,a)}static isBSONError(c){return c!=null&&typeof c==="object"&&"bsonError"in c&&c.bsonError===!0&&"name"in c&&"message"in c&&"stack"in c}}class hm extends ${get name(){return"BSONVersionError"}constructor(){super(`Unsupported BSON version, bson types must be from bson ${za}.x.x`)}}class Da extends ${get name(){return"BSONRuntimeError"}constructor(c){super(c)}}class ac extends ${get name(){return"BSONOffsetError"}constructor(c,a,o){super(`${c}. offset: ${a}`,o);this.offset=a}}var lm,jm;function Km(c,a,o,m){if(m){lm??=new TextDecoder("utf8",{fatal:!0});try{return lm.decode(c.subarray(a,o))}catch(s){throw new $("Invalid UTF-8 string in BSON document",{cause:s})}}return jm??=new TextDecoder("utf8",{fatal:!1}),jm.decode(c.subarray(a,o))}function _m(c,a,o){if(c.length===0)return"";let m=o-a;if(m===0)return"";if(m>20)return null;if(m===1&&c[a]<128)return String.fromCharCode(c[a]);if(m===2&&c[a]<128&&c[a+1]<128)return String.fromCharCode(c[a])+String.fromCharCode(c[a+1]);if(m===3&&c[a]<128&&c[a+1]<128&&c[a+2]<128)return String.fromCharCode(c[a])+String.fromCharCode(c[a+1])+String.fromCharCode(c[a+2]);let s=[];for(let t=a;t<o;t++){let p=c[t];if(p>127)return null;s.push(p)}return String.fromCharCode(...s)}function rp(c,a,o){if(a.length===0)return 0;if(a.length>25)return null;if(c.length-o<a.length)return null;for(let m=0,s=o;m<a.length;m++,s++){let t=a.charCodeAt(m);if(t>127)return null;c[s]=t}return a.length}var Cc={toLocalBufferType(c){if(Buffer.isBuffer(c))return c;if(ArrayBuffer.isView(c))return Buffer.from(c.buffer,c.byteOffset,c.byteLength);let a=c?.[Symbol.toStringTag]??Object.prototype.toString.call(c);if(a==="ArrayBuffer"||a==="SharedArrayBuffer"||a==="[object ArrayBuffer]"||a==="[object SharedArrayBuffer]")return Buffer.from(c);throw new $("Cannot create Buffer from the passed potentialBuffer.")},allocate(c){return Buffer.alloc(c)},allocateUnsafe(c){return Buffer.allocUnsafe(c)},equals(c,a){return Cc.toLocalBufferType(c).equals(a)},fromNumberArray(c){return Buffer.from(c)},fromBase64(c){return Buffer.from(c,"base64")},toBase64(c){return Cc.toLocalBufferType(c).toString("base64")},fromISO88591(c){return Buffer.from(c,"binary")},toISO88591(c){return Cc.toLocalBufferType(c).toString("binary")},fromHex(c){return Buffer.from(c,"hex")},toHex(c){return Cc.toLocalBufferType(c).toString("hex")},toUTF8(c,a,o,m){let s=o-a<=20?_m(c,a,o):null;if(s!=null)return s;let t=Cc.toLocalBufferType(c).toString("utf8",a,o);if(m){for(let p=0;p<t.length;p++)if(t.charCodeAt(p)===65533){Km(c,a,o,!0);break}}return t},utf8ByteLength(c){return Buffer.byteLength(c,"utf8")},encodeUTF8Into(c,a,o){let m=rp(c,a,o);if(m!=null)return m;return Cc.toLocalBufferType(c).write(a,o,void 0,"utf8")},randomBytes:ft,swap32(c){return Cc.toLocalBufferType(c).swap32()}};function wp(){let{navigator:c}=globalThis;return typeof c==="object"&&c.product==="ReactNative"}function Cp(c){if(c<0)throw RangeError(`The argument 'byteLength' is invalid. Received ${c}`);return yc.fromNumberArray(Array.from({length:c},()=>Math.floor(Math.random()*256)))}var gp=(()=>{let{crypto:c}=globalThis;if(c!=null&&typeof c.getRandomValues==="function")return(a)=>{return c.getRandomValues(yc.allocate(a))};else{if(wp()){let{console:a}=globalThis;a?.warn?.("BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.")}return Cp}})(),Qm=/(\d|[a-f])/i,yc={toLocalBufferType(c){let a=c?.[Symbol.toStringTag]??Object.prototype.toString.call(c);if(a==="Uint8Array")return c;if(ArrayBuffer.isView(c))return new Uint8Array(c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength));if(a==="ArrayBuffer"||a==="SharedArrayBuffer"||a==="[object ArrayBuffer]"||a==="[object SharedArrayBuffer]")return new Uint8Array(c);throw new $("Cannot make a Uint8Array from passed potentialBuffer.")},allocate(c){if(typeof c!=="number")throw TypeError(`The "size" argument must be of type number. Received ${String(c)}`);return new Uint8Array(c)},allocateUnsafe(c){return yc.allocate(c)},equals(c,a){if(c.byteLength!==a.byteLength)return!1;for(let o=0;o<c.byteLength;o++)if(c[o]!==a[o])return!1;return!0},fromNumberArray(c){return Uint8Array.from(c)},fromBase64(c){return Uint8Array.from(atob(c),(a)=>a.charCodeAt(0))},toBase64(c){return btoa(yc.toISO88591(c))},fromISO88591(c){return Uint8Array.from(c,(a)=>a.charCodeAt(0)&255)},toISO88591(c){return Array.from(Uint16Array.from(c),(a)=>String.fromCharCode(a)).join("")},fromHex(c){let a=c.length%2===0?c:c.slice(0,c.length-1),o=[];for(let m=0;m<a.length;m+=2){let s=a[m],t=a[m+1];if(!Qm.test(s))break;if(!Qm.test(t))break;let p=Number.parseInt(`${s}${t}`,16);o.push(p)}return Uint8Array.from(o)},toHex(c){return Array.from(c,(a)=>a.toString(16).padStart(2,"0")).join("")},toUTF8(c,a,o,m){let s=o-a<=20?_m(c,a,o):null;if(s!=null)return s;return Km(c,a,o,m)},utf8ByteLength(c){return new TextEncoder().encode(c).byteLength},encodeUTF8Into(c,a,o){let m=new TextEncoder().encode(a);return c.set(m,o),m.byteLength},randomBytes:gp,swap32(c){if(c.length%4!==0)throw RangeError("Buffer size must be a multiple of 32-bits");for(let a=0;a<c.length;a+=4){let o=c[a],m=c[a+1],s=c[a+2],t=c[a+3];c[a]=t,c[a+1]=s,c[a+2]=m,c[a+3]=o}return c}},qp=typeof Buffer==="function"&&Buffer.prototype?._isBuffer!==!0,j=qp?Cc:yc;class S{get[Ym](){return za}[Symbol.for("nodejs.util.inspect.custom")](c,a,o){return this.inspect(c,a,o)}}var Yc=new Float64Array(1),W=new Uint8Array(Yc.buffer,0,8);Yc[0]=-1;var Ka=W[7]===0,jc={isBigEndian:Ka,getNonnegativeInt32LE(c,a){if(c[a+3]>127)throw RangeError(`Size cannot be negative at offset: ${a}`);return c[a]|c[a+1]<<8|c[a+2]<<16|c[a+3]<<24},getInt32LE(c,a){return c[a]|c[a+1]<<8|c[a+2]<<16|c[a+3]<<24},getUint32LE(c,a){return c[a]+c[a+1]*256+c[a+2]*65536+c[a+3]*16777216},getUint32BE(c,a){return c[a+3]+c[a+2]*256+c[a+1]*65536+c[a]*16777216},getBigInt64LE(c,a){let o=BigInt(c[a+4]+c[a+5]*256+c[a+6]*65536+(c[a+7]<<24)),m=BigInt(c[a]+c[a+1]*256+c[a+2]*65536+c[a+3]*16777216);return(o<<BigInt(32))+m},getFloat64LE:Ka?(c,a)=>{return W[7]=c[a],W[6]=c[a+1],W[5]=c[a+2],W[4]=c[a+3],W[3]=c[a+4],W[2]=c[a+5],W[1]=c[a+6],W[0]=c[a+7],Yc[0]}:(c,a)=>{return W[0]=c[a],W[1]=c[a+1],W[2]=c[a+2],W[3]=c[a+3],W[4]=c[a+4],W[5]=c[a+5],W[6]=c[a+6],W[7]=c[a+7],Yc[0]},setInt32BE(c,a,o){return c[a+3]=o,o>>>=8,c[a+2]=o,o>>>=8,c[a+1]=o,o>>>=8,c[a]=o,4},setInt32LE(c,a,o){return c[a]=o,o>>>=8,c[a+1]=o,o>>>=8,c[a+2]=o,o>>>=8,c[a+3]=o,4},setBigInt64LE(c,a,o){let m=BigInt(4294967295),s=Number(o&m);c[a]=s,s>>=8,c[a+1]=s,s>>=8,c[a+2]=s,s>>=8,c[a+3]=s;let t=Number(o>>BigInt(32)&m);return c[a+4]=t,t>>=8,c[a+5]=t,t>>=8,c[a+6]=t,t>>=8,c[a+7]=t,8},setFloat64LE:Ka?(c,a,o)=>{return Yc[0]=o,c[a]=W[7],c[a+1]=W[6],c[a+2]=W[5],c[a+3]=W[4],c[a+4]=W[3],c[a+5]=W[2],c[a+6]=W[1],c[a+7]=W[0],8}:(c,a,o)=>{return Yc[0]=o,c[a]=W[0],c[a+1]=W[1],c[a+2]=W[2],c[a+3]=W[3],c[a+4]=W[4],c[a+5]=W[5],c[a+6]=W[6],c[a+7]=W[7],8}};class n extends S{get _bsontype(){return"Binary"}constructor(c,a){super();if(c!=null&&typeof c==="string"&&!ArrayBuffer.isView(c)&&!ap(c)&&!Array.isArray(c))throw new $("Binary can only be constructed from Uint8Array or number[]");if(this.sub_type=a??n.BSON_BINARY_SUBTYPE_DEFAULT,c==null)this.buffer=j.allocate(n.BUFFER_SIZE),this.position=0;else this.buffer=Array.isArray(c)?j.fromNumberArray(c):j.toLocalBufferType(c),this.position=this.buffer.byteLength}put(c){if(typeof c==="string"&&c.length!==1)throw new $("only accepts single character String");else if(typeof c!=="number"&&c.length!==1)throw new $("only accepts single character Uint8Array or Array");let a;if(typeof c==="string")a=c.charCodeAt(0);else if(typeof c==="number")a=c;else a=c[0];if(a<0||a>255)throw new $("only accepts number in a valid unsigned byte range 0-255");if(this.buffer.byteLength>this.position)this.buffer[this.position++]=a;else{let o=j.allocate(n.BUFFER_SIZE+this.buffer.length);o.set(this.buffer,0),this.buffer=o,this.buffer[this.position++]=a}}write(c,a){if(a=typeof a==="number"?a:this.position,this.buffer.byteLength<a+c.length){let o=j.allocate(this.buffer.byteLength+c.length);o.set(this.buffer,0),this.buffer=o}if(ArrayBuffer.isView(c))this.buffer.set(j.toLocalBufferType(c),a),this.position=a+c.byteLength>this.position?a+c.length:this.position;else if(typeof c==="string")throw new $("input cannot be string")}read(c,a){a=a&&a>0?a:this.position;let o=c+a;return this.buffer.subarray(c,o>this.position?this.position:o)}value(){return this.buffer.length===this.position?this.buffer:this.buffer.subarray(0,this.position)}length(){return this.position}toJSON(){return j.toBase64(this.buffer.subarray(0,this.position))}toString(c){if(c==="hex")return j.toHex(this.buffer.subarray(0,this.position));if(c==="base64")return j.toBase64(this.buffer.subarray(0,this.position));if(c==="utf8"||c==="utf-8")return j.toUTF8(this.buffer,0,this.position,!1);return j.toUTF8(this.buffer,0,this.position,!1)}toExtendedJSON(c){if(c=c||{},this.sub_type===n.SUBTYPE_VECTOR)wc(this);let a=j.toBase64(this.buffer),o=Number(this.sub_type).toString(16);if(c.legacy)return{$binary:a,$type:o.length===1?"0"+o:o};return{$binary:{base64:a,subType:o.length===1?"0"+o:o}}}toUUID(){if(this.sub_type===n.SUBTYPE_UUID)return new _(this.buffer.subarray(0,this.position));throw new $(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${n.SUBTYPE_UUID}" is currently supported.`)}static createFromHexString(c,a){return new n(j.fromHex(c),a)}static createFromBase64(c,a){return new n(j.fromBase64(c),a)}static fromExtendedJSON(c,a){a=a||{};let o,m;if("$binary"in c){if(a.legacy&&typeof c.$binary==="string"&&"$type"in c)m=c.$type?parseInt(c.$type,16):0,o=j.fromBase64(c.$binary);else if(typeof c.$binary!=="string")m=c.$binary.subType?parseInt(c.$binary.subType,16):0,o=j.fromBase64(c.$binary.base64)}else if("$uuid"in c)m=4,o=_.bytesFromString(c.$uuid);if(!o)throw new $(`Unexpected Binary Extended JSON format ${JSON.stringify(c)}`);return m===Tm?new _(o):new n(o,m)}inspect(c,a,o){o??=y;let m=j.toBase64(this.buffer.subarray(0,this.position)),s=o(m,a),t=o(this.sub_type,a);return`Binary.createFromBase64(${s}, ${t})`}toInt8Array(){if(this.sub_type!==n.SUBTYPE_VECTOR)throw new $("Binary sub_type is not Vector");if(this.buffer[0]!==n.VECTOR_TYPE.Int8)throw new $("Binary datatype field is not Int8");return wc(this),new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toFloat32Array(){if(this.sub_type!==n.SUBTYPE_VECTOR)throw new $("Binary sub_type is not Vector");if(this.buffer[0]!==n.VECTOR_TYPE.Float32)throw new $("Binary datatype field is not Float32");wc(this);let c=new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position));if(jc.isBigEndian)j.swap32(c);return new Float32Array(c.buffer)}toPackedBits(){if(this.sub_type!==n.SUBTYPE_VECTOR)throw new $("Binary sub_type is not Vector");if(this.buffer[0]!==n.VECTOR_TYPE.PackedBit)throw new $("Binary datatype field is not packed bit");return wc(this),new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toBits(){if(this.sub_type!==n.SUBTYPE_VECTOR)throw new $("Binary sub_type is not Vector");if(this.buffer[0]!==n.VECTOR_TYPE.PackedBit)throw new $("Binary datatype field is not packed bit");wc(this);let a=(this.length()-2)*8-this.buffer[1],o=new Int8Array(a);for(let m=0;m<o.length;m++){let s=m/8|0,t=this.buffer[s+2],p=7-m%8,w=t>>p&1;o[m]=w}return o}static fromInt8Array(c){let a=j.allocate(c.byteLength+2);a[0]=n.VECTOR_TYPE.Int8,a[1]=0;let o=new Uint8Array(c.buffer,c.byteOffset,c.byteLength);a.set(o,2);let m=new this(a,this.SUBTYPE_VECTOR);return wc(m),m}static fromFloat32Array(c){let a=j.allocate(c.byteLength+2);a[0]=n.VECTOR_TYPE.Float32,a[1]=0;let o=new Uint8Array(c.buffer,c.byteOffset,c.byteLength);if(a.set(o,2),jc.isBigEndian)j.swap32(new Uint8Array(a.buffer,2));let m=new this(a,this.SUBTYPE_VECTOR);return wc(m),m}static fromPackedBits(c,a=0){let o=j.allocate(c.byteLength+2);o[0]=n.VECTOR_TYPE.PackedBit,o[1]=a,o.set(c,2);let m=new this(o,this.SUBTYPE_VECTOR);return wc(m),m}static fromBits(c){let a=c.length+7>>>3,o=new Uint8Array(a+2);o[0]=n.VECTOR_TYPE.PackedBit;let m=c.length%8;o[1]=m===0?0:8-m;for(let s=0;s<c.length;s++){let t=s>>>3,p=c[s];if(p!==0&&p!==1)throw new $(`Invalid bit value at ${s}: must be 0 or 1, found ${c[s]}`);if(p===0)continue;let w=7-s%8;o[t+2]|=p<<w}return new this(o,n.SUBTYPE_VECTOR)}}n.BSON_BINARY_SUBTYPE_DEFAULT=0;n.BUFFER_SIZE=256;n.SUBTYPE_DEFAULT=0;n.SUBTYPE_FUNCTION=1;n.SUBTYPE_BYTE_ARRAY=2;n.SUBTYPE_UUID_OLD=3;n.SUBTYPE_UUID=4;n.SUBTYPE_MD5=5;n.SUBTYPE_ENCRYPTED=6;n.SUBTYPE_COLUMN=7;n.SUBTYPE_SENSITIVE=8;n.SUBTYPE_VECTOR=9;n.SUBTYPE_USER_DEFINED=128;n.VECTOR_TYPE=Object.freeze({Int8:3,Float32:39,PackedBit:16});function wc(c){if(c.sub_type!==n.SUBTYPE_VECTOR)return;let a=c.position,o=c.buffer[0],m=c.buffer[1];if((o===n.VECTOR_TYPE.Float32||o===n.VECTOR_TYPE.Int8)&&m!==0)throw new $("Invalid Vector: padding must be zero for int8 and float32 vectors");if(o===n.VECTOR_TYPE.Float32){if(a!==0&&a-2!==0&&(a-2)%4!==0)throw new $("Invalid Vector: Float32 vector must contain a multiple of 4 bytes")}if(o===n.VECTOR_TYPE.PackedBit&&m!==0&&a===2)throw new $("Invalid Vector: padding must be zero for packed bit vectors that are empty");if(o===n.VECTOR_TYPE.PackedBit&&m>7)throw new $(`Invalid Vector: padding must be a value between 0 and 7. found: ${m}`)}var _a=16,$p=/^[0-9A-F]{32}$/i,lp=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;class _ extends n{constructor(c){let a;if(c==null)a=_.generate();else if(c instanceof _)a=j.toLocalBufferType(new Uint8Array(c.buffer));else if(ArrayBuffer.isView(c)&&c.byteLength===_a)a=j.toLocalBufferType(c);else if(typeof c==="string")a=_.bytesFromString(c);else throw new $("Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).");super(a,Tm)}get id(){return this.buffer}set id(c){this.buffer=c}toHexString(c=!0){if(c)return[j.toHex(this.buffer.subarray(0,4)),j.toHex(this.buffer.subarray(4,6)),j.toHex(this.buffer.subarray(6,8)),j.toHex(this.buffer.subarray(8,10)),j.toHex(this.buffer.subarray(10,16))].join("-");return j.toHex(this.buffer)}toString(c){if(c==="hex")return j.toHex(this.id);if(c==="base64")return j.toBase64(this.id);return this.toHexString()}toJSON(){return this.toHexString()}equals(c){if(!c)return!1;if(c instanceof _)return j.equals(c.id,this.id);try{return j.equals(new _(c).id,this.id)}catch{return!1}}toBinary(){return new n(this.id,n.SUBTYPE_UUID)}static generate(){let c=j.randomBytes(_a);return c[6]=c[6]&15|64,c[8]=c[8]&63|128,c}static isValid(c){if(!c)return!1;if(typeof c==="string")return _.isValidUUIDString(c);if(Zm(c))return c.byteLength===_a;return c._bsontype==="Binary"&&c.sub_type===this.SUBTYPE_UUID&&c.buffer.byteLength===16}static createFromHexString(c){let a=_.bytesFromString(c);return new _(a)}static createFromBase64(c){return new _(j.fromBase64(c))}static bytesFromString(c){if(!_.isValidUUIDString(c))throw new $("UUID string representation must be 32 hex digits or canonical hyphenated representation");return j.fromHex(c.replace(/-/g,""))}static isValidUUIDString(c){return $p.test(c)||lp.test(c)}inspect(c,a,o){return o??=y,`new UUID(${o(this.toHexString(),a)})`}}class Sc extends S{get _bsontype(){return"Code"}constructor(c,a){super();this.code=c.toString(),this.scope=a??null}toJSON(){if(this.scope!=null)return{code:this.code,scope:this.scope};return{code:this.code}}toExtendedJSON(){if(this.scope)return{$code:this.code,$scope:this.scope};return{$code:this.code}}static fromExtendedJSON(c){return new Sc(c.$code,c.$scope)}inspect(c,a,o){o??=y;let m=o(this.code,a),s=m.includes(`
680
+ `);if(this.scope!=null)m+=`,${s?`
681
+ `:" "}${o(this.scope,a)}`;let t=s&&this.scope===null;return`new Code(${s?`
682
+ `:""}${m}${t?`
683
+ `:""})`}}function jp(c){return c!=null&&typeof c==="object"&&"$id"in c&&c.$id!=null&&"$ref"in c&&typeof c.$ref==="string"&&(!("$db"in c)||("$db"in c)&&typeof c.$db==="string")}class Uc extends S{get _bsontype(){return"DBRef"}constructor(c,a,o,m){super();let s=c.split(".");if(s.length===2)o=s.shift(),c=s.shift();this.collection=c,this.oid=a,this.db=o,this.fields=m||{}}get namespace(){return this.collection}set namespace(c){this.collection=c}toJSON(){let c=Object.assign({$ref:this.collection,$id:this.oid},this.fields);if(this.db!=null)c.$db=this.db;return c}toExtendedJSON(c){c=c||{};let a={$ref:this.collection,$id:this.oid};if(c.legacy)return a;if(this.db)a.$db=this.db;return a=Object.assign(a,this.fields),a}static fromExtendedJSON(c){let a=Object.assign({},c);return delete a.$ref,delete a.$id,delete a.$db,new Uc(c.$ref,c.$id,c.$db,a)}inspect(c,a,o){o??=y;let m=[o(this.namespace,a),o(this.oid,a),...this.db?[o(this.db,a)]:[],...Object.keys(this.fields).length>0?[o(this.fields,a)]:[]];return m[1]=o===y?`new ObjectId(${m[1]})`:m[1],`new DBRef(${m.join(", ")})`}}function Em(c){if(c==="")return c;let a=0,o=c[a]==="-",m=c[a]==="+";if(m||o)a+=1;let s=!1;for(;a<c.length&&c[a]==="0";++a)s=!0;if(!s)return m?c.slice(1):c;return`${o?"-":""}${c.length===a?"0":c.slice(a)}`}function Qp(c,a){a=a??10;let o="0123456789abcdefghijklmnopqrstuvwxyz".slice(0,a);return new RegExp(`[^-+${o}]`,"i").test(c)?!1:c}var L=void 0;try{L=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}var nm=65536,np=16777216,Fc=nm*nm,km=Fc*Fc,Jp=km/2,Jm={},Am={},Ap=20,Rp=/^(\+?0|(\+|-)?[1-9][0-9]*)$/;class r extends S{get _bsontype(){return"Long"}get __isLong__(){return!0}constructor(c=0,a,o){super();let m=typeof a==="boolean"?a:Boolean(o),s=typeof a==="number"?a:0,t=typeof c==="string"?r.fromString(c,m):typeof c==="bigint"?r.fromBigInt(c,m):{low:c|0,high:s|0,unsigned:m};this.low=t.low,this.high=t.high,this.unsigned=t.unsigned}static fromBits(c,a,o){return new r(c,a,o)}static fromInt(c,a){let o,m,s;if(a){if(c>>>=0,s=0<=c&&c<256){if(m=Am[c],m)return m}if(o=r.fromBits(c,(c|0)<0?-1:0,!0),s)Am[c]=o;return o}else{if(c|=0,s=-128<=c&&c<128){if(m=Jm[c],m)return m}if(o=r.fromBits(c,c<0?-1:0,!1),s)Jm[c]=o;return o}}static fromNumber(c,a){if(isNaN(c))return a?r.UZERO:r.ZERO;if(a){if(c<0)return r.UZERO;if(c>=km)return r.MAX_UNSIGNED_VALUE}else{if(c<=-9223372036854776000)return r.MIN_VALUE;if(c+1>=Jp)return r.MAX_VALUE}if(c<0)return r.fromNumber(-c,a).neg();return r.fromBits(c%Fc|0,c/Fc|0,a)}static fromBigInt(c,a){let o=BigInt(4294967295),m=BigInt(32);return new r(Number(c&o),Number(c>>m&o),a)}static _fromString(c,a,o){if(c.length===0)throw new $("empty string");if(o<2||36<o)throw new $("radix");let m;if((m=c.indexOf("-"))>0)throw new $("interior hyphen");else if(m===0)return r._fromString(c.substring(1),a,o).neg();let s=r.fromNumber(Math.pow(o,8)),t=r.ZERO;for(let p=0;p<c.length;p+=8){let w=Math.min(8,c.length-p),C=parseInt(c.substring(p,p+w),o);if(w<8){let q=r.fromNumber(Math.pow(o,w));t=t.mul(q).add(r.fromNumber(C))}else t=t.mul(s),t=t.add(r.fromNumber(C))}return t.unsigned=a,t}static fromStringStrict(c,a,o){let m=!1;if(typeof a==="number")o=a,a=!1;else m=!!a;if(o??=10,c.trim()!==c)throw new $(`Input: '${c}' contains leading and/or trailing whitespace`);if(!Qp(c,o))throw new $(`Input: '${c}' contains invalid characters for radix: ${o}`);let s=Em(c),t=r._fromString(s,m,o);if(t.toString(o).toLowerCase()!==s.toLowerCase())throw new $(`Input: ${c} is not representable as ${t.unsigned?"an unsigned":"a signed"} 64-bit Long ${o!=null?`with radix: ${o}`:""}`);return t}static fromString(c,a,o){let m=!1;if(typeof a==="number")o=a,a=!1;else m=!!a;if(o??=10,c==="NaN"&&o<24)return r.ZERO;else if((c==="Infinity"||c==="+Infinity"||c==="-Infinity")&&o<35)return r.ZERO;return r._fromString(c,m,o)}static fromBytes(c,a,o){return o?r.fromBytesLE(c,a):r.fromBytesBE(c,a)}static fromBytesLE(c,a){return new r(c[0]|c[1]<<8|c[2]<<16|c[3]<<24,c[4]|c[5]<<8|c[6]<<16|c[7]<<24,a)}static fromBytesBE(c,a){return new r(c[4]<<24|c[5]<<16|c[6]<<8|c[7],c[0]<<24|c[1]<<16|c[2]<<8|c[3],a)}static isLong(c){return c!=null&&typeof c==="object"&&"__isLong__"in c&&c.__isLong__===!0}static fromValue(c,a){if(typeof c==="number")return r.fromNumber(c,a);if(typeof c==="string")return r.fromString(c,a);return r.fromBits(c.low,c.high,typeof a==="boolean"?a:c.unsigned)}add(c){if(!r.isLong(c))c=r.fromValue(c);let a=this.high>>>16,o=this.high&65535,m=this.low>>>16,s=this.low&65535,t=c.high>>>16,p=c.high&65535,w=c.low>>>16,C=c.low&65535,q=0,g=0,Q=0,A=0;return A+=s+C,Q+=A>>>16,A&=65535,Q+=m+w,g+=Q>>>16,Q&=65535,g+=o+p,q+=g>>>16,g&=65535,q+=a+t,q&=65535,r.fromBits(Q<<16|A,q<<16|g,this.unsigned)}and(c){if(!r.isLong(c))c=r.fromValue(c);return r.fromBits(this.low&c.low,this.high&c.high,this.unsigned)}compare(c){if(!r.isLong(c))c=r.fromValue(c);if(this.eq(c))return 0;let a=this.isNegative(),o=c.isNegative();if(a&&!o)return-1;if(!a&&o)return 1;if(!this.unsigned)return this.sub(c).isNegative()?-1:1;return c.high>>>0>this.high>>>0||c.high===this.high&&c.low>>>0>this.low>>>0?-1:1}comp(c){return this.compare(c)}divide(c){if(!r.isLong(c))c=r.fromValue(c);if(c.isZero())throw new $("division by zero");if(L){if(!this.unsigned&&this.high===-2147483648&&c.low===-1&&c.high===-1)return this;let s=(this.unsigned?L.div_u:L.div_s)(this.low,this.high,c.low,c.high);return r.fromBits(s,L.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?r.UZERO:r.ZERO;let a,o,m;if(!this.unsigned){if(this.eq(r.MIN_VALUE))if(c.eq(r.ONE)||c.eq(r.NEG_ONE))return r.MIN_VALUE;else if(c.eq(r.MIN_VALUE))return r.ONE;else if(a=this.shr(1).div(c).shl(1),a.eq(r.ZERO))return c.isNegative()?r.ONE:r.NEG_ONE;else return o=this.sub(c.mul(a)),m=a.add(o.div(c)),m;else if(c.eq(r.MIN_VALUE))return this.unsigned?r.UZERO:r.ZERO;if(this.isNegative()){if(c.isNegative())return this.neg().div(c.neg());return this.neg().div(c).neg()}else if(c.isNegative())return this.div(c.neg()).neg();m=r.ZERO}else{if(!c.unsigned)c=c.toUnsigned();if(c.gt(this))return r.UZERO;if(c.gt(this.shru(1)))return r.UONE;m=r.UZERO}o=this;while(o.gte(c)){a=Math.max(1,Math.floor(o.toNumber()/c.toNumber()));let s=Math.ceil(Math.log(a)/Math.LN2),t=s<=48?1:Math.pow(2,s-48),p=r.fromNumber(a),w=p.mul(c);while(w.isNegative()||w.gt(o))a-=t,p=r.fromNumber(a,this.unsigned),w=p.mul(c);if(p.isZero())p=r.ONE;m=m.add(p),o=o.sub(w)}return m}div(c){return this.divide(c)}equals(c){if(!r.isLong(c))c=r.fromValue(c);if(this.unsigned!==c.unsigned&&this.high>>>31===1&&c.high>>>31===1)return!1;return this.high===c.high&&this.low===c.low}eq(c){return this.equals(c)}getHighBits(){return this.high}getHighBitsUnsigned(){return this.high>>>0}getLowBits(){return this.low}getLowBitsUnsigned(){return this.low>>>0}getNumBitsAbs(){if(this.isNegative())return this.eq(r.MIN_VALUE)?64:this.neg().getNumBitsAbs();let c=this.high!==0?this.high:this.low,a;for(a=31;a>0;a--)if((c&1<<a)!==0)break;return this.high!==0?a+33:a+1}greaterThan(c){return this.comp(c)>0}gt(c){return this.greaterThan(c)}greaterThanOrEqual(c){return this.comp(c)>=0}gte(c){return this.greaterThanOrEqual(c)}ge(c){return this.greaterThanOrEqual(c)}isEven(){return(this.low&1)===0}isNegative(){return!this.unsigned&&this.high<0}isOdd(){return(this.low&1)===1}isPositive(){return this.unsigned||this.high>=0}isZero(){return this.high===0&&this.low===0}lessThan(c){return this.comp(c)<0}lt(c){return this.lessThan(c)}lessThanOrEqual(c){return this.comp(c)<=0}lte(c){return this.lessThanOrEqual(c)}modulo(c){if(!r.isLong(c))c=r.fromValue(c);if(L){let a=(this.unsigned?L.rem_u:L.rem_s)(this.low,this.high,c.low,c.high);return r.fromBits(a,L.get_high(),this.unsigned)}return this.sub(this.div(c).mul(c))}mod(c){return this.modulo(c)}rem(c){return this.modulo(c)}multiply(c){if(this.isZero())return r.ZERO;if(!r.isLong(c))c=r.fromValue(c);if(L){let Y=L.mul(this.low,this.high,c.low,c.high);return r.fromBits(Y,L.get_high(),this.unsigned)}if(c.isZero())return r.ZERO;if(this.eq(r.MIN_VALUE))return c.isOdd()?r.MIN_VALUE:r.ZERO;if(c.eq(r.MIN_VALUE))return this.isOdd()?r.MIN_VALUE:r.ZERO;if(this.isNegative())if(c.isNegative())return this.neg().mul(c.neg());else return this.neg().mul(c).neg();else if(c.isNegative())return this.mul(c.neg()).neg();if(this.lt(r.TWO_PWR_24)&&c.lt(r.TWO_PWR_24))return r.fromNumber(this.toNumber()*c.toNumber(),this.unsigned);let a=this.high>>>16,o=this.high&65535,m=this.low>>>16,s=this.low&65535,t=c.high>>>16,p=c.high&65535,w=c.low>>>16,C=c.low&65535,q=0,g=0,Q=0,A=0;return A+=s*C,Q+=A>>>16,A&=65535,Q+=m*C,g+=Q>>>16,Q&=65535,Q+=s*w,g+=Q>>>16,Q&=65535,g+=o*C,q+=g>>>16,g&=65535,g+=m*w,q+=g>>>16,g&=65535,g+=s*p,q+=g>>>16,g&=65535,q+=a*C+o*w+m*p+s*t,q&=65535,r.fromBits(Q<<16|A,q<<16|g,this.unsigned)}mul(c){return this.multiply(c)}negate(){if(!this.unsigned&&this.eq(r.MIN_VALUE))return r.MIN_VALUE;return this.not().add(r.ONE)}neg(){return this.negate()}not(){return r.fromBits(~this.low,~this.high,this.unsigned)}notEquals(c){return!this.equals(c)}neq(c){return this.notEquals(c)}ne(c){return this.notEquals(c)}or(c){if(!r.isLong(c))c=r.fromValue(c);return r.fromBits(this.low|c.low,this.high|c.high,this.unsigned)}shiftLeft(c){if(r.isLong(c))c=c.toInt();if((c&=63)===0)return this;else if(c<32)return r.fromBits(this.low<<c,this.high<<c|this.low>>>32-c,this.unsigned);else return r.fromBits(0,this.low<<c-32,this.unsigned)}shl(c){return this.shiftLeft(c)}shiftRight(c){if(r.isLong(c))c=c.toInt();if((c&=63)===0)return this;else if(c<32)return r.fromBits(this.low>>>c|this.high<<32-c,this.high>>c,this.unsigned);else return r.fromBits(this.high>>c-32,this.high>=0?0:-1,this.unsigned)}shr(c){return this.shiftRight(c)}shiftRightUnsigned(c){if(r.isLong(c))c=c.toInt();if(c&=63,c===0)return this;else{let a=this.high;if(c<32){let o=this.low;return r.fromBits(o>>>c|a<<32-c,a>>>c,this.unsigned)}else if(c===32)return r.fromBits(a,0,this.unsigned);else return r.fromBits(a>>>c-32,0,this.unsigned)}}shr_u(c){return this.shiftRightUnsigned(c)}shru(c){return this.shiftRightUnsigned(c)}subtract(c){if(!r.isLong(c))c=r.fromValue(c);return this.add(c.neg())}sub(c){return this.subtract(c)}toInt(){return this.unsigned?this.low>>>0:this.low}toNumber(){if(this.unsigned)return(this.high>>>0)*Fc+(this.low>>>0);return this.high*Fc+(this.low>>>0)}toBigInt(){return BigInt(this.toString())}toBytes(c){return c?this.toBytesLE():this.toBytesBE()}toBytesLE(){let c=this.high,a=this.low;return[a&255,a>>>8&255,a>>>16&255,a>>>24,c&255,c>>>8&255,c>>>16&255,c>>>24]}toBytesBE(){let c=this.high,a=this.low;return[c>>>24,c>>>16&255,c>>>8&255,c&255,a>>>24,a>>>16&255,a>>>8&255,a&255]}toSigned(){if(!this.unsigned)return this;return r.fromBits(this.low,this.high,!1)}toString(c){if(c=c||10,c<2||36<c)throw new $("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(r.MIN_VALUE)){let s=r.fromNumber(c),t=this.div(s),p=t.mul(s).sub(this);return t.toString(c)+p.toInt().toString(c)}else return"-"+this.neg().toString(c);let a=r.fromNumber(Math.pow(c,6),this.unsigned),o=this,m="";while(!0){let s=o.div(a),p=(o.sub(s.mul(a)).toInt()>>>0).toString(c);if(o=s,o.isZero())return p+m;else{while(p.length<6)p="0"+p;m=""+p+m}}}toUnsigned(){if(this.unsigned)return this;return r.fromBits(this.low,this.high,!0)}xor(c){if(!r.isLong(c))c=r.fromValue(c);return r.fromBits(this.low^c.low,this.high^c.high,this.unsigned)}eqz(){return this.isZero()}le(c){return this.lessThanOrEqual(c)}toExtendedJSON(c){if(c&&c.relaxed)return this.toNumber();return{$numberLong:this.toString()}}static fromExtendedJSON(c,a){let{useBigInt64:o=!1,relaxed:m=!0}={...a};if(c.$numberLong.length>Ap)throw new $("$numberLong string is too long");if(!Rp.test(c.$numberLong))throw new $(`$numberLong string "${c.$numberLong}" is in an invalid format`);if(o){let t=BigInt(c.$numberLong);return BigInt.asIntN(64,t)}let s=r.fromString(c.$numberLong);if(m)return s.toNumber();return s}inspect(c,a,o){o??=y;let m=o(this.toString(),a),s=this.unsigned?`, ${o(this.unsigned,a)}`:"";return`new Long(${m}${s})`}}r.TWO_PWR_24=r.fromInt(np);r.MAX_UNSIGNED_VALUE=r.fromBits(-1,-1,!0);r.ZERO=r.fromInt(0);r.UZERO=r.fromInt(0,!0);r.ONE=r.fromInt(1);r.UONE=r.fromInt(1,!0);r.NEG_ONE=r.fromInt(-1);r.MAX_VALUE=r.fromBits(-1,2147483647,!1);r.MIN_VALUE=r.fromBits(0,-2147483648,!1);var Pp=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/,Wp=/^(\+|-)?(Infinity|inf)$/i,Gp=/^(\+|-)?NaN$/i,Hc=6111,Dc=-6176,Rm=6176,Pm=34,Ea=j.fromNumberArray([124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),Wm=j.fromNumberArray([248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),Gm=j.fromNumberArray([120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),Ip=/^([-+])?(\d+)?$/,Mp=31,Im=16383,Xp=30,Zp=31;function Mm(c){return!isNaN(parseInt(c,10))}function Hp(c){let a=r.fromNumber(1e9),o=r.fromNumber(0);if(!c.parts[0]&&!c.parts[1]&&!c.parts[2]&&!c.parts[3])return{quotient:c,rem:o};for(let m=0;m<=3;m++)o=o.shiftLeft(32),o=o.add(new r(c.parts[m],0)),c.parts[m]=o.div(a).low,o=o.modulo(a);return{quotient:c,rem:o}}function Yp(c,a){if(!c&&!a)return{high:r.fromNumber(0),low:r.fromNumber(0)};let o=c.shiftRightUnsigned(32),m=new r(c.getLowBits(),0),s=a.shiftRightUnsigned(32),t=new r(a.getLowBits(),0),p=o.multiply(s),w=o.multiply(t),C=m.multiply(s),q=m.multiply(t);return p=p.add(w.shiftRightUnsigned(32)),w=new r(w.getLowBits(),0).add(C).add(q.shiftRightUnsigned(32)),p=p.add(w.shiftRightUnsigned(32)),q=w.shiftLeft(32).add(new r(q.getLowBits(),0)),{high:p,low:q}}function Fp(c,a){let o=c.high>>>0,m=a.high>>>0;if(o<m)return!0;else if(o===m){let s=c.low>>>0,t=a.low>>>0;if(s<t)return!0}return!1}function O(c,a){throw new $(`"${c}" is not a valid Decimal128 string - ${a}`)}class z extends S{get _bsontype(){return"Decimal128"}constructor(c){super();if(typeof c==="string")this.bytes=z.fromString(c).bytes;else if(c instanceof Uint8Array||Zm(c)){if(c.byteLength!==16)throw new $("Decimal128 must take a Buffer of 16 bytes");this.bytes=c}else throw new $("Decimal128 must take a Buffer or string")}static fromString(c){return z._fromString(c,{allowRounding:!1})}static fromStringWithRounding(c){return z._fromString(c,{allowRounding:!0})}static _fromString(c,a){let o=!1,m=!1,s=!1,t=!1,p=0,w=0,C=0,q=0,g=0,Q=[0],A=0,Y=0,J=0,P=0,Z=new r(0,0),G=new r(0,0),T=0,l=0;if(c.length>=7000)throw new $(""+c+" not a valid Decimal128 string");let h=c.match(Pp),Ds=c.match(Wp),zs=c.match(Gp);if(!h&&!Ds&&!zs||c.length===0)throw new $(""+c+" not a valid Decimal128 string");if(h){let M=h[2],Jc=h[4],Ac=h[5],k=h[6];if(Jc&&k===void 0)O(c,"missing exponent power");if(Jc&&M===void 0)O(c,"missing exponent base");if(Jc===void 0&&(Ac||k))O(c,"missing e before exponent")}if(c[l]==="+"||c[l]==="-")m=!0,o=c[l++]==="-";if(!Mm(c[l])&&c[l]!=="."){if(c[l]==="i"||c[l]==="I")return new z(o?Wm:Gm);else if(c[l]==="N")return new z(Ea)}while(Mm(c[l])||c[l]==="."){if(c[l]==="."){if(s)O(c,"contains multiple periods");s=!0,l=l+1;continue}if(A<Pm){if(c[l]!=="0"||t){if(!t)g=w;t=!0,Q[Y++]=parseInt(c[l],10),A=A+1}}if(t)C=C+1;if(s)q=q+1;w=w+1,l=l+1}if(s&&!w)throw new $(""+c+" not a valid Decimal128 string");if(c[l]==="e"||c[l]==="E"){let M=c.substr(++l).match(Ip);if(!M||!M[2])return new z(Ea);P=parseInt(M[0],10),l=l+M[0].length}if(c[l])return new z(Ea);if(!A)Q[0]=0,C=1,A=1,p=0;else if(J=A-1,p=C,p!==1)while(c[g+p-1+Number(m)+Number(s)]==="0")p=p-1;if(P<=q&&q>P+16384)P=Dc;else P=P-q;while(P>Hc){if(J=J+1,J>=Pm){if(p===0){P=Hc;break}O(c,"overflow")}P=P-1}if(a.allowRounding){while(P<Dc||A<C){if(J===0&&p<A){P=Dc,p=0;break}if(A<C)C=C-1;else J=J-1;if(P<Hc)P=P+1;else{if(Q.join("").match(/^0+$/)){P=Hc;break}O(c,"overflow")}}if(J+1<p){let M=w;if(s)g=g+1,M=M+1;if(m)g=g+1,M=M+1;let Jc=parseInt(c[g+J+1],10),Ac=0;if(Jc>=5){if(Ac=1,Jc===5){Ac=Q[J]%2===1?1:0;for(let k=g+J+2;k<M;k++)if(parseInt(c[k],10)){Ac=1;break}}}if(Ac){let k=J;for(;k>=0;k--)if(++Q[k]>9){if(Q[k]=0,k===0)if(P<Hc)P=P+1,Q[k]=1;else return new z(o?Wm:Gm)}else break}}}else{while(P<Dc||A<C){if(J===0){if(p===0){P=Dc;break}O(c,"exponent underflow")}if(A<C){if(c[C-1+Number(m)+Number(s)]!=="0"&&p!==0)O(c,"inexact rounding");C=C-1}else{if(Q[J]!==0)O(c,"inexact rounding");J=J-1}if(P<Hc)P=P+1;else O(c,"overflow")}if(J+1<p){if(s)g=g+1;if(m)g=g+1;if(parseInt(c[g+J+1],10)!==0)O(c,"inexact rounding")}}if(Z=r.fromNumber(0),G=r.fromNumber(0),p===0)Z=r.fromNumber(0),G=r.fromNumber(0);else if(J<17){let M=0;G=r.fromNumber(Q[M++]),Z=new r(0,0);for(;M<=J;M++)G=G.multiply(r.fromNumber(10)),G=G.add(r.fromNumber(Q[M]))}else{let M=0;Z=r.fromNumber(Q[M++]);for(;M<=J-17;M++)Z=Z.multiply(r.fromNumber(10)),Z=Z.add(r.fromNumber(Q[M]));G=r.fromNumber(Q[M++]);for(;M<=J;M++)G=G.multiply(r.fromNumber(10)),G=G.add(r.fromNumber(Q[M]))}let v=Yp(Z,r.fromString("100000000000000000"));if(v.low=v.low.add(G),Fp(v.low,G))v.high=v.high.add(r.fromNumber(1));T=P+Rm;let I={low:r.fromNumber(0),high:r.fromNumber(0)};if(v.high.shiftRightUnsigned(49).and(r.fromNumber(1)).equals(r.fromNumber(1)))I.high=I.high.or(r.fromNumber(3).shiftLeft(61)),I.high=I.high.or(r.fromNumber(T).and(r.fromNumber(16383).shiftLeft(47))),I.high=I.high.or(v.high.and(r.fromNumber(140737488355327)));else I.high=I.high.or(r.fromNumber(T&16383).shiftLeft(49)),I.high=I.high.or(v.high.and(r.fromNumber(562949953421311)));if(I.low=v.low,o)I.high=I.high.or(r.fromString("9223372036854775808"));let U=j.allocateUnsafe(16);return l=0,U[l++]=I.low.low&255,U[l++]=I.low.low>>8&255,U[l++]=I.low.low>>16&255,U[l++]=I.low.low>>24&255,U[l++]=I.low.high&255,U[l++]=I.low.high>>8&255,U[l++]=I.low.high>>16&255,U[l++]=I.low.high>>24&255,U[l++]=I.high.low&255,U[l++]=I.high.low>>8&255,U[l++]=I.high.low>>16&255,U[l++]=I.high.low>>24&255,U[l++]=I.high.high&255,U[l++]=I.high.high>>8&255,U[l++]=I.high.high>>16&255,U[l++]=I.high.high>>24&255,new z(U)}toString(){let c,a=0,o=Array(36);for(let l=0;l<o.length;l++)o[l]=0;let m=0,s=!1,t,p={parts:[0,0,0,0]},w,C,q=[];m=0;let g=this.bytes,Q=g[m++]|g[m++]<<8|g[m++]<<16|g[m++]<<24,A=g[m++]|g[m++]<<8|g[m++]<<16|g[m++]<<24,Y=g[m++]|g[m++]<<8|g[m++]<<16|g[m++]<<24,J=g[m++]|g[m++]<<8|g[m++]<<16|g[m++]<<24;if(m=0,{low:new r(Q,A),high:new r(Y,J)}.high.lessThan(r.ZERO))q.push("-");let Z=J>>26&Mp;if(Z>>3===3)if(Z===Xp)return q.join("")+"Infinity";else if(Z===Zp)return"NaN";else c=J>>15&Im,t=8+(J>>14&1);else t=J>>14&7,c=J>>17&Im;let G=c-Rm;if(p.parts[0]=(J&16383)+((t&15)<<14),p.parts[1]=Y,p.parts[2]=A,p.parts[3]=Q,p.parts[0]===0&&p.parts[1]===0&&p.parts[2]===0&&p.parts[3]===0)s=!0;else for(C=3;C>=0;C--){let l=0,h=Hp(p);if(p=h.quotient,l=h.rem.low,!l)continue;for(w=8;w>=0;w--)o[C*9+w]=l%10,l=Math.floor(l/10)}if(s)a=1,o[m]=0;else{a=36;while(!o[m])a=a-1,m=m+1}let T=a-1+G;if(T>=34||T<=-7||G>0){if(a>34){if(q.push("0"),G>0)q.push(`E+${G}`);else if(G<0)q.push(`E${G}`);return q.join("")}if(q.push(`${o[m++]}`),a=a-1,a)q.push(".");for(let l=0;l<a;l++)q.push(`${o[m++]}`);if(q.push("E"),T>0)q.push(`+${T}`);else q.push(`${T}`)}else if(G>=0)for(let l=0;l<a;l++)q.push(`${o[m++]}`);else{let l=a+G;if(l>0)for(let h=0;h<l;h++)q.push(`${o[m++]}`);else q.push("0");q.push(".");while(l++<0)q.push("0");for(let h=0;h<a-Math.max(l-1,0);h++)q.push(`${o[m++]}`)}return q.join("")}toJSON(){return{$numberDecimal:this.toString()}}toExtendedJSON(){return{$numberDecimal:this.toString()}}static fromExtendedJSON(c){return z.fromString(c.$numberDecimal)}inspect(c,a,o){return o??=y,`new Decimal128(${o(this.toString(),a)})`}}class mc extends S{get _bsontype(){return"Double"}constructor(c){super();if(c instanceof Number)c=c.valueOf();this.value=+c}static fromString(c){let a=Number(c);if(c==="NaN")return new mc(NaN);if(c==="Infinity")return new mc(1/0);if(c==="-Infinity")return new mc(-1/0);if(!Number.isFinite(a))throw new $(`Input: ${c} is not representable as a Double`);if(c.trim()!==c)throw new $(`Input: '${c}' contains whitespace`);if(c==="")throw new $("Input is an empty string");if(/[^-0-9.+eE]/.test(c))throw new $(`Input: '${c}' is not in decimal or exponential notation`);return new mc(a)}valueOf(){return this.value}toJSON(){return this.value}toString(c){return this.value.toString(c)}toExtendedJSON(c){if(c&&(c.legacy||c.relaxed&&isFinite(this.value)))return this.value;if(Object.is(Math.sign(this.value),-0))return{$numberDouble:"-0.0"};return{$numberDouble:Number.isInteger(this.value)?this.value.toFixed(1):this.value.toString()}}static fromExtendedJSON(c,a){let o=parseFloat(c.$numberDouble);return a&&a.relaxed?o:new mc(o)}inspect(c,a,o){return o??=y,`new Double(${o(this.value,a)})`}}class Tc extends S{get _bsontype(){return"Int32"}constructor(c){super();if(c instanceof Number)c=c.valueOf();this.value=+c|0}static fromString(c){let a=Em(c),o=Number(c);if(ya<o)throw new $(`Input: '${c}' is larger than the maximum value for Int32`);else if(Sa>o)throw new $(`Input: '${c}' is smaller than the minimum value for Int32`);else if(!Number.isSafeInteger(o))throw new $(`Input: '${c}' is not a safe integer`);else if(o.toString()!==a)throw new $(`Input: '${c}' is not a valid Int32 string`);return new Tc(o)}valueOf(){return this.value}toString(c){return this.value.toString(c)}toJSON(){return this.value}toExtendedJSON(c){if(c&&(c.relaxed||c.legacy))return this.value;return{$numberInt:this.value.toString()}}static fromExtendedJSON(c,a){return a&&a.relaxed?parseInt(c.$numberInt,10):new Tc(c.$numberInt)}inspect(c,a,o){return o??=y,`new Int32(${o(this.value,a)})`}}class sa extends S{get _bsontype(){return"MaxKey"}toExtendedJSON(){return{$maxKey:1}}static fromExtendedJSON(){return new sa}inspect(){return"new MaxKey()"}}class ta extends S{get _bsontype(){return"MinKey"}toExtendedJSON(){return{$minKey:1}}static fromExtendedJSON(){return new ta}inspect(){return"new MinKey()"}}var lc=null,zc=new WeakMap;class H extends S{get _bsontype(){return"ObjectId"}constructor(c){super();let a;if(typeof c==="object"&&c&&"id"in c){if(typeof c.id!=="string"&&!ArrayBuffer.isView(c.id))throw new $("Argument passed in must have an id that is of type string or Buffer");if("toHexString"in c&&typeof c.toHexString==="function")a=j.fromHex(c.toHexString());else a=c.id}else a=c;if(a==null||typeof a==="number")this.buffer=H.generate(typeof a==="number"?a:void 0);else if(ArrayBuffer.isView(a)&&a.byteLength===12)this.buffer=j.toLocalBufferType(a);else if(typeof a==="string")if(H.validateHexString(a)){if(this.buffer=j.fromHex(a),H.cacheHexString)zc.set(this,a)}else throw new $("input must be a 24 character hex string, 12 byte Uint8Array, or an integer");else throw new $("Argument passed in does not match the accepted types")}get id(){return this.buffer}set id(c){if(this.buffer=c,H.cacheHexString)zc.set(this,j.toHex(c))}static validateHexString(c){if(c?.length!==24)return!1;for(let a=0;a<24;a++){let o=c.charCodeAt(a);if(o>=48&&o<=57||o>=97&&o<=102||o>=65&&o<=70)continue;return!1}return!0}toHexString(){if(H.cacheHexString){let a=zc.get(this);if(a)return a}let c=j.toHex(this.id);if(H.cacheHexString)zc.set(this,c);return c}static getInc(){return H.index=(H.index+1)%16777215}static generate(c){if(typeof c!=="number")c=Math.floor(Date.now()/1000);let a=H.getInc(),o=j.allocateUnsafe(12);if(jc.setInt32BE(o,0,c),lc===null)lc=j.randomBytes(5);return o[4]=lc[0],o[5]=lc[1],o[6]=lc[2],o[7]=lc[3],o[8]=lc[4],o[11]=a&255,o[10]=a>>8&255,o[9]=a>>16&255,o}toString(c){if(c==="base64")return j.toBase64(this.id);if(c==="hex")return this.toHexString();return this.toHexString()}toJSON(){return this.toHexString()}static is(c){return c!=null&&typeof c==="object"&&"_bsontype"in c&&c._bsontype==="ObjectId"}equals(c){if(c===void 0||c===null)return!1;if(H.is(c))return this.buffer[11]===c.buffer[11]&&j.equals(this.buffer,c.buffer);if(typeof c==="string")return c.toLowerCase()===this.toHexString();if(typeof c==="object"&&typeof c.toHexString==="function"){let a=c.toHexString(),o=this.toHexString();return typeof a==="string"&&a.toLowerCase()===o}return!1}getTimestamp(){let c=new Date,a=jc.getUint32BE(this.buffer,0);return c.setTime(Math.floor(a)*1000),c}static createPk(){return new H}serializeInto(c,a){return c[a]=this.buffer[0],c[a+1]=this.buffer[1],c[a+2]=this.buffer[2],c[a+3]=this.buffer[3],c[a+4]=this.buffer[4],c[a+5]=this.buffer[5],c[a+6]=this.buffer[6],c[a+7]=this.buffer[7],c[a+8]=this.buffer[8],c[a+9]=this.buffer[9],c[a+10]=this.buffer[10],c[a+11]=this.buffer[11],12}static createFromTime(c){let a=j.allocate(12);for(let o=11;o>=4;o--)a[o]=0;return jc.setInt32BE(a,0,c),new H(a)}static createFromHexString(c){if(c?.length!==24)throw new $("hex string must be 24 characters");return new H(j.fromHex(c))}static createFromBase64(c){if(c?.length!==16)throw new $("base64 string must be 16 characters");return new H(j.fromBase64(c))}static isValid(c){if(c==null)return!1;if(typeof c==="string")return H.validateHexString(c);try{return new H(c),!0}catch{return!1}}toExtendedJSON(){if(this.toHexString)return{$oid:this.toHexString()};return{$oid:this.toString("hex")}}static fromExtendedJSON(c){return new H(c.$oid)}isCached(){return H.cacheHexString&&zc.has(this)}inspect(c,a,o){return o??=y,`new ObjectId(${o(this.toHexString(),a)})`}}H.index=Math.floor(Math.random()*16777215);function Up(c){return c.split("").sort().join("")}class tc extends S{get _bsontype(){return"BSONRegExp"}constructor(c,a){super();if(this.pattern=c,this.options=Up(a??""),this.pattern.indexOf("\x00")!==-1)throw new $(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`);if(this.options.indexOf("\x00")!==-1)throw new $(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`);for(let o=0;o<this.options.length;o++)if(!(this.options[o]==="i"||this.options[o]==="m"||this.options[o]==="x"||this.options[o]==="l"||this.options[o]==="s"||this.options[o]==="u"))throw new $(`The regular expression option [${this.options[o]}] is not supported`)}static parseOptions(c){return c?c.split("").sort().join(""):""}toExtendedJSON(c){if(c=c||{},c.legacy)return{$regex:this.pattern,$options:this.options};return{$regularExpression:{pattern:this.pattern,options:this.options}}}static fromExtendedJSON(c){if("$regex"in c)if(typeof c.$regex!=="string"){if(c.$regex._bsontype==="BSONRegExp")return c}else return new tc(c.$regex,tc.parseOptions(c.$options));if("$regularExpression"in c)return new tc(c.$regularExpression.pattern,tc.parseOptions(c.$regularExpression.options));throw new $(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(c)}`)}inspect(c,a,o){let m=sp(a)??((p)=>p);o??=y;let s=m(o(this.pattern),"regexp"),t=m(o(this.options),"regexp");return`new BSONRegExp(${s}, ${t})`}}class pa extends S{get _bsontype(){return"BSONSymbol"}constructor(c){super();this.value=c}valueOf(){return this.value}toString(){return this.value}toJSON(){return this.value}toExtendedJSON(){return{$symbol:this.value}}static fromExtendedJSON(c){return new pa(c.$symbol)}inspect(c,a,o){return o??=y,`new BSONSymbol(${o(this.value,a)})`}}var Tp=r;class sc extends Tp{get _bsontype(){return"Timestamp"}get i(){return this.low>>>0}get t(){return this.high>>>0}constructor(c){if(c==null)super(0,0,!0);else if(typeof c==="bigint")super(c,!0);else if(r.isLong(c))super(c.low,c.high,!0);else if(typeof c==="object"&&"t"in c&&"i"in c){if(typeof c.t!=="number"&&(typeof c.t!=="object"||c.t._bsontype!=="Int32"))throw new $("Timestamp constructed from { t, i } must provide t as a number");if(typeof c.i!=="number"&&(typeof c.i!=="object"||c.i._bsontype!=="Int32"))throw new $("Timestamp constructed from { t, i } must provide i as a number");let a=Number(c.t),o=Number(c.i);if(a<0||Number.isNaN(a))throw new $("Timestamp constructed from { t, i } must provide a positive t");if(o<0||Number.isNaN(o))throw new $("Timestamp constructed from { t, i } must provide a positive i");if(a>4294967295)throw new $("Timestamp constructed from { t, i } must provide t equal or less than uint32 max");if(o>4294967295)throw new $("Timestamp constructed from { t, i } must provide i equal or less than uint32 max");super(o,a,!0)}else throw new $("A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }")}toJSON(){return{$timestamp:this.toString()}}static fromInt(c){return new sc(r.fromInt(c,!0))}static fromNumber(c){return new sc(r.fromNumber(c,!0))}static fromBits(c,a){return new sc({i:c,t:a})}static fromString(c,a){return new sc(r.fromString(c,!0,a))}toExtendedJSON(){return{$timestamp:{t:this.t,i:this.i}}}static fromExtendedJSON(c){let a=r.isLong(c.$timestamp.i)?c.$timestamp.i.getLowBitsUnsigned():c.$timestamp.i,o=r.isLong(c.$timestamp.t)?c.$timestamp.t.getLowBitsUnsigned():c.$timestamp.t;return new sc({t:o,i:a})}inspect(c,a,o){o??=y;let m=o(this.t,a),s=o(this.i,a);return`new Timestamp({ t: ${m}, i: ${s} })`}}sc.MAX_VALUE=r.MAX_UNSIGNED_VALUE;var WC=r.fromNumber(tp),GC=r.fromNumber(pp);function hp(c){return c!=null&&typeof c==="object"&&"_bsontype"in c&&typeof c._bsontype==="string"}var Kp={$oid:H,$binary:n,$uuid:n,$symbol:pa,$numberInt:Tc,$numberDecimal:z,$numberDouble:mc,$numberLong:r,$minKey:ta,$maxKey:sa,$regex:tc,$regularExpression:tc,$timestamp:sc};function Vm(c,a={}){if(typeof c==="number"){let m=c<=ya&&c>=Sa,s=c<=Fm&&c>=Um;if(a.relaxed||a.legacy)return c;if(Number.isInteger(c)&&!Object.is(c,-0)){if(m)return new Tc(c);if(s){if(a.useBigInt64)return BigInt(c);return r.fromNumber(c)}}return new mc(c)}if(c==null||typeof c!=="object")return c;if(c.$undefined)return null;let o=Object.keys(c).filter((m)=>m.startsWith("$")&&c[m]!=null);for(let m=0;m<o.length;m++){let s=Kp[o[m]];if(s)return s.fromExtendedJSON(c,a)}if(c.$date!=null){let m=c.$date,s=new Date;if(a.legacy)if(typeof m==="number")s.setTime(m);else if(typeof m==="string")s.setTime(Date.parse(m));else if(typeof m==="bigint")s.setTime(Number(m));else throw new Da(`Unrecognized type for EJSON date: ${typeof m}`);else if(typeof m==="string")s.setTime(Date.parse(m));else if(r.isLong(m))s.setTime(m.toNumber());else if(typeof m==="number"&&a.relaxed)s.setTime(m);else if(typeof m==="bigint")s.setTime(Number(m));else throw new Da(`Unrecognized type for EJSON date: ${typeof m}`);return s}if(c.$code!=null){let m=Object.assign({},c);if(c.$scope)m.$scope=Vm(c.$scope);return Sc.fromExtendedJSON(c)}if(jp(c)||c.$dbPointer){let m=c.$ref?c:c.$dbPointer;if(m instanceof Uc)return m;let s=Object.keys(m).filter((p)=>p.startsWith("$")),t=!0;if(s.forEach((p)=>{if(["$ref","$id","$db"].indexOf(p)===-1)t=!1}),t)return Uc.fromExtendedJSON(m)}return c}function _p(c,a){return c.map((o,m)=>{a.seenObjects.push({propertyName:`index ${m}`,obj:null});try{return oc(o,a)}finally{a.seenObjects.pop()}})}function Xm(c){let a=c.toISOString();return c.getUTCMilliseconds()!==0?a:a.slice(0,-5)+"Z"}function oc(c,a){if(c instanceof Map||Hm(c)){let o=Object.create(null);for(let[m,s]of c){if(typeof m!=="string")throw new $("Can only serialize maps with string keys");o[m]=s}return oc(o,a)}if((typeof c==="object"||typeof c==="function")&&c!==null){let o=a.seenObjects.findIndex((m)=>m.obj===c);if(o!==-1){let m=a.seenObjects.map((g)=>g.propertyName),s=m.slice(0,o).map((g)=>`${g} -> `).join(""),t=m[o],p=" -> "+m.slice(o+1,m.length-1).map((g)=>`${g} -> `).join(""),w=m[m.length-1],C=" ".repeat(s.length+t.length/2),q="-".repeat(p.length+(t.length+w.length)/2-1);throw new $(`Converting circular structure to EJSON:
684
+ ${s}${t}${p}${w}
685
+ ${C}\\${q}/`)}a.seenObjects[a.seenObjects.length-1].obj=c}if(Array.isArray(c))return _p(c,a);if(c===void 0)return null;if(c instanceof Date||mp(c)){let o=c.getTime(),m=o>-1&&o<253402318800000;if(a.legacy)return a.relaxed&&m?{$date:c.getTime()}:{$date:Xm(c)};return a.relaxed&&m?{$date:Xm(c)}:{$date:{$numberLong:c.getTime().toString()}}}if(typeof c==="number"&&(!a.relaxed||!isFinite(c))){if(Number.isInteger(c)&&!Object.is(c,-0)){if(c>=Sa&&c<=ya)return{$numberInt:c.toString()};if(c>=Um&&c<=Fm)return{$numberLong:c.toString()}}return{$numberDouble:Object.is(c,-0)?"-0.0":c.toString()}}if(typeof c==="bigint"){if(!a.relaxed)return{$numberLong:BigInt.asIntN(64,c).toString()};return Number(BigInt.asIntN(64,c))}if(c instanceof RegExp||op(c)){let o=c.flags;if(o===void 0){let s=c.toString().match(/[gimuy]*$/);if(s)o=s[0]}return new tc(c.source,o).toExtendedJSON(a)}if(c!=null&&typeof c==="object")return kp(c,a);return c}var Ep={Binary:(c)=>new n(c.value(),c.sub_type),Code:(c)=>new Sc(c.code,c.scope),DBRef:(c)=>new Uc(c.collection||c.namespace,c.oid,c.db,c.fields),Decimal128:(c)=>new z(c.bytes),Double:(c)=>new mc(c.value),Int32:(c)=>new Tc(c.value),Long:(c)=>r.fromBits(c.low!=null?c.low:c.low_,c.low!=null?c.high:c.high_,c.low!=null?c.unsigned:c.unsigned_),MaxKey:()=>new sa,MinKey:()=>new ta,ObjectId:(c)=>new H(c),BSONRegExp:(c)=>new tc(c.pattern,c.options),BSONSymbol:(c)=>new pa(c.value),Timestamp:(c)=>sc.fromBits(c.low,c.high)};function kp(c,a){if(c==null||typeof c!=="object")throw new $("not an object instance");let o=c._bsontype;if(typeof o>"u"){let m={};for(let s of Object.keys(c)){a.seenObjects.push({propertyName:s,obj:null});try{let t=oc(c[s],a);if(s==="__proto__")Object.defineProperty(m,s,{value:t,writable:!0,enumerable:!0,configurable:!0});else m[s]=t}finally{a.seenObjects.pop()}}return m}else if(c!=null&&typeof c==="object"&&typeof c._bsontype==="string"&&c[Ym]!==za)throw new hm;else if(hp(c)){let m=c;if(typeof m.toExtendedJSON!=="function"){let s=Ep[c._bsontype];if(!s)throw new $("Unrecognized or invalid _bsontype: "+c._bsontype);m=s(m)}if(o==="Code"&&m.scope)m=new Sc(m.code,oc(m.scope,a));else if(o==="DBRef"&&m.oid)m=new Uc(oc(m.collection,a),oc(m.oid,a),oc(m.db,a),oc(m.fields,a));return m.toExtendedJSON(a)}else throw new $("_bsontype must be a string, but was: "+typeof o)}function Dm(c,a){let o={useBigInt64:a?.useBigInt64??!1,relaxed:a?.relaxed??!0,legacy:a?.legacy??!1};return JSON.parse(c,(m,s)=>{if(m.indexOf("\x00")!==-1)throw new $(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(m)}`);return Vm(s,o)})}function zm(c,a,o,m){if(o!=null&&typeof o==="object")m=o,o=0;if(a!=null&&typeof a==="object"&&!Array.isArray(a))m=a,a=void 0,o=0;let s=Object.assign({relaxed:!0,legacy:!1},m,{seenObjects:[{propertyName:"(root)",obj:null}]}),t=oc(c,s);return JSON.stringify(t,a,o)}function Vp(c,a){return a=a||{},JSON.parse(zm(c,a))}function Dp(c,a){return a=a||{},Dm(JSON.stringify(c),a)}var gc=Object.create(null);gc.parse=Dm;gc.stringify=zm;gc.serialize=Vp;gc.deserialize=Dp;Object.freeze(gc);var X={double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:255,maxKey:127};function ka(c,a){try{return jc.getNonnegativeInt32LE(c,a)}catch(o){throw new ac("BSON size cannot be negative",a,{cause:o})}}function Va(c,a){let o=a;for(;c[o]!==0;o++);if(o===c.length-1)throw new ac("Null terminator not found",a);return o}function zp(c,a=0){if(a??=0,c.length<5)throw new ac(`Input must be at least 5 bytes, got ${c.length} bytes`,a);let o=ka(c,a);if(o>c.length-a)throw new ac(`Parsed documentSize (${o} bytes) does not match input length (${c.length} bytes)`,a);if(c[a+o-1]!==0)throw new ac("BSON documents must end in 0x00",a+o);let m=[],s=a+4;while(s<=o+a){let t=c[s];if(s+=1,t===0){if(s-a!==o)throw new ac("Invalid 0x00 type byte",s);break}let p=s,w=Va(c,s)-p;s+=w+1;let C;if(t===X.double||t===X.long||t===X.date||t===X.timestamp)C=8;else if(t===X.int)C=4;else if(t===X.objectId)C=12;else if(t===X.decimal)C=16;else if(t===X.bool)C=1;else if(t===X.null||t===X.undefined||t===X.maxKey||t===X.minKey)C=0;else if(t===X.regex)C=Va(c,Va(c,s)+1)+1-s;else if(t===X.object||t===X.array||t===X.javascriptWithScope)C=ka(c,s);else if(t===X.string||t===X.binData||t===X.dbPointer||t===X.javascript||t===X.symbol){if(C=ka(c,s)+4,t===X.binData)C+=1;if(t===X.dbPointer)C+=12}else throw new ac(`Invalid 0x${t.toString(16).padStart(2,"0")} type byte`,s);if(C>o)throw new ac("value reports length larger than document",s);m.push([t,p,w,s,C]),s+=C}return m}var ra=Object.create(null);ra.parseToElements=zp;ra.ByteUtils=j;ra.NumberUtils=jc;Object.freeze(ra);var yp=17825792,IC=j.allocate(yp);import{execFileSync as Sp}from"node:child_process";import{existsSync as ga,mkdirSync as up,readdirSync as Lp,readFileSync as qa,rmSync as La,writeFileSync as pc}from"node:fs";import{basename as im,dirname as dm,join as E,resolve as Om}from"node:path";var ua=".justo-space.json";function ym(){return{template:"react-vite-shadcn",version:2,collections:{}}}function wa(){return process.execPath}function Qc(c){if(process.platform==="win32")return`${c}.cmd`;return c}var Ca="iUzDOAFCUx33tmT6OCea",uc="VITE_JUSTO_MAP_TILER_TOKEN";function Sm(){return`import {useState, type FormEvent} from 'react'
406
686
  import {Badge} from '@/components/ui/badge'
407
687
  import {Button} from '@/components/ui/button'
408
688
  import {Card, CardContent, CardDescription, CardHeader, CardTitle} from '@/components/ui/card'
@@ -420,8 +700,8 @@ import {justoCli} from '@/lib/justo'
420
700
  const defaultCommand = 'auth status'
421
701
  const queryExample = "data queries preview <queryId> --params '{\\"limit\\":10}'"
422
702
  const mapTilerToken =
423
- (import.meta.env as {${L}?: string}).${L} ||
424
- '${we}'
703
+ (import.meta.env as {${uc}?: string}).${uc} ||
704
+ '${Ca}'
425
705
  const chartData = [
426
706
  {day: 'Lun', sessions: 12},
427
707
  {day: 'Mar', sessions: 18},
@@ -632,7 +912,7 @@ export function App() {
632
912
  }
633
913
 
634
914
  export default App
635
- `}function Wr(){return`type JustoCliFunction = <T = unknown>(command: string) => Promise<T>
915
+ `}function um(){return`type JustoCliFunction = <T = unknown>(command: string) => Promise<T>
636
916
  type JustoStreamFunction = <T = unknown>(
637
917
  command: string,
638
918
  onRow: (row: T) => Promise<void> | void,
@@ -774,7 +1054,7 @@ export async function justoStream<T = unknown>(
774
1054
  }
775
1055
 
776
1056
  ensurePreviewWindowJusto()
777
- `}function Mr(e){return`# ${e}
1057
+ `}function Lm(c){return`# ${c}
778
1058
 
779
1059
  Starter de Justo Spaces generado por \`team-cli spaces init\`.
780
1060
 
@@ -806,304 +1086,67 @@ Flujo recomendado:
806
1086
  Tip:
807
1087
  - usa \`spaces preview --open\` para abrir el dashboard en el navegador por defecto y mostrárselo al usuario mientras lo iteras
808
1088
  - \`spaces publish\` sube el repo del space sin \`node_modules\` ni otros archivos ignorados por git, además del build listo para servir
1089
+ - si necesitas escritura en Mongo, declara las collections en \`.justo-space.json\` y usa \`team-cli spaces db\`
809
1090
  - después de \`spaces init\`, haz un initial commit para fijar el scaffold base
810
1091
  - después de cada publish, haz commit para que el repo refleje exactamente lo que quedó publicado
811
1092
  - 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 Gr(){return`import {StrictMode} from 'react'
1093
+ `}function Nm(){return`import {StrictMode} from 'react'
813
1094
  import {createRoot} from 'react-dom/client'
814
1095
  import App from './App.tsx'
815
1096
  import './index.css'
816
1097
  import './lib/justo'
817
- import {ThemeProvider} from '@/components/theme-provider.tsx'
818
1098
 
819
1099
  createRoot(document.getElementById('root')!).render(
820
1100
  <StrictMode>
821
- <ThemeProvider defaultTheme="light">
822
- <App />
823
- </ThemeProvider>
1101
+ <App />
824
1102
  </StrictMode>,
825
1103
  )
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
- aggregationQuery(aggregationQueryId: $aggregationQueryId) {
835
- _id
836
- name
837
- description
838
- collection
839
- currentVersionIndex
840
- allowedUsersIds
841
- tags
842
- pipeline
843
- variables {
844
- key
845
- fieldType
846
- fieldParams
847
- }
848
- }
849
- }`,variables:{aggregationQueryId:e}})).aggregationQuery}async function gt(e){return await Promise.all(e.map(async(t)=>{let a=(await u({service:"main",query:`query ($filter: String, $limit: BigInt) {
850
- justoUsers(filter: $filter, limit: $limit) {
851
- items {
852
- _id
853
- email
854
- fullName
855
- }
1104
+ `}function Lc(c,a,o){Sp(c,a,{cwd:o,stdio:"inherit",env:{...process.env,CI:"1"}})}function Np(c){if(!c)throw Error("Falta --path. Ejemplo: team-cli spaces init --path ./mi-space-app");let a=Om(c);if(ga(a)){if(Lp(a).length>0)throw Error(`La carpeta ya existe y no está vacía: ${a}`);La(a,{recursive:!0,force:!0})}return up(dm(a),{recursive:!0}),a}function ip(c){let a=E(c,"vite.config.ts"),o=qa(a,"utf-8");if(o.includes("base: './'"))return;let m=o.replace("export default defineConfig({",`export default defineConfig({
1105
+ base: './',`);pc(a,m)}function dp(c){let a=E(c,"tsconfig.app.json"),m=qa(a,"utf-8").replace('"noUnusedLocals": true,','"noUnusedLocals": false,').replace('"noUnusedParameters": true,','"noUnusedParameters": false,');pc(a,m)}function Op(c){let a=E(c,"package.json"),o=JSON.parse(qa(a,"utf-8"));o.dependencies=o.dependencies||{},o.devDependencies=o.devDependencies||{},o.dependencies.leaflet="^1.9.4",o.dependencies["react-leaflet"]="^5.0.0",o.devDependencies["@types/leaflet"]="^1.9.20",o.justoSpaceApp=!0,pc(a,`${JSON.stringify(o,null,2)}
1106
+ `)}function bp(c){let a=E(c,"src","index.css"),o=qa(a,"utf-8");if(o.includes("leaflet/dist/leaflet.css"))return;pc(a,`@import "leaflet/dist/leaflet.css";
1107
+ ${o}`)}function Bp(c){let a=im(c);pc(E(c,"README.md"),Lm(a)),pc(E(c,"src","App.tsx"),Sm()),pc(E(c,"src","main.tsx"),Nm()),pc(E(c,"src","lib","justo.ts"),um()),pc(E(c,ua),`${JSON.stringify(ym(),null,2)}
1108
+ `),La(E(c,".git"),{recursive:!0,force:!0})}function vp(c){Lc("git",["init"],c)}function ep(c){La(E(c,"package-lock.json"),{force:!0})}function Na(c){let a=Om(c);if(!ga(a))throw Error(`No existe la app del space: ${a}`);if(!ga(E(a,ua)))throw Error("Este publish solo acepta apps creadas con team-cli spaces init. Debes apuntar al root de esa app.");return a}function bm(c){let a=Na(c);Lc(Qc("yarn"),["build"],a);let o=E(a,"dist");if(!ga(E(o,"index.html")))throw Error("El build no generó dist/index.html");return o}function Bm(c){let a=Np(c),o=dm(a),m=im(a);return Lc(Qc("npx"),["shadcn@latest","init","-t","vite","-d","-y","-n",m],o),Lc(Qc("npx"),["shadcn@latest","add","-a","-y"],a),ep(a),Op(a),Lc(Qc("yarn"),["install"],a),ip(a),dp(a),bp(a),Bp(a),vp(a),{path:a,nextSteps:[`cd ${a}`,'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"']}}import{readdirSync as fm,readFileSync as cs,statSync as as}from"node:fs";import{gzipSync as pr}from"node:zlib";import{join as os,relative as ms,resolve as em}from"node:path";import{existsSync as xp,readFileSync as fp}from"node:fs";import{join as cr}from"node:path";var ar=[".git","node_modules","dist",".justo-space-preview",".DS_Store"];function or(c){return c.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}function mr(c){let a="";for(let o=0;o<c.length;o++){let m=c[o],s=c[o+1];if(m==="*"){if(s==="*"){a+=".*",o+=1;continue}a+="[^/]*";continue}if(m==="?"){a+="[^/]";continue}a+=or(m)}return a}function sr(c){let a=c.trim();if(!a||a.startsWith("#"))return null;let o=a.startsWith("!"),m=o?a.slice(1).trim():a;if(!m)return null;let s=m.endsWith("/"),t=m.replace(/^\/+/,"").replace(/\/+$/,"");if(!t)return null;let p=t.includes("/"),w=mr(t),C=p?`^${w}${s?"(?:/.*)?":""}$`:`(?:^|/)${w}${s?"(?:/.*)?":"(?:$|/)"}`;return{negate:o,directoryOnly:s,regex:new RegExp(C)}}function tr(c){let a=cr(c,".gitignore"),o=[...ar];if(xp(a))o.push(...fp(a,"utf-8").split(/\r?\n/));return o.map(sr).filter((m)=>Boolean(m))}function vm(c){let a=tr(c);return(o,m)=>{let s=o.replaceAll("\\","/").replace(/^\/+/,""),t=!1;for(let p of a){if(!p.regex.test(s))continue;t=!p.negate}return t}}var $a=512,rr=2,wr="repo",Cr="dist";function gr(c){let a=c.replaceAll("\\","/");if(a.startsWith("/")||a.includes("../"))throw Error(`Ruta inválida en el space: ${c}`);return a}function qr(c){let a=gr(c);if(Buffer.from(a).length<=100)return{name:a,prefix:""};let m=a.lastIndexOf("/");if(m<=0)throw Error(`La ruta es demasiado larga para el paquete del space: ${c}`);let s=a.slice(0,m),t=a.slice(m+1);if(Buffer.from(s).length>155||Buffer.from(t).length>100)throw Error(`La ruta es demasiado larga para el paquete del space: ${c}`);return{name:t,prefix:s}}function nc(c,a,o,m){let s=Buffer.from(m);s.copy(c,a,0,Math.min(s.length,o))}function Nc(c,a,o,m){let s=Math.max(0,Math.trunc(m)).toString(8).padStart(o-1,"0");nc(c,a,o,`${s}\x00`)}function $r(c){let a=Buffer.alloc($a,0),{name:o,prefix:m}=qr(c.path);nc(a,0,100,o),Nc(a,100,8,c.mode),Nc(a,108,8,0),Nc(a,116,8,0),Nc(a,124,12,c.content.length),Nc(a,136,12,c.mtime),a.fill(32,148,156),nc(a,156,1,"0"),nc(a,257,6,"ustar"),nc(a,263,2,"00"),nc(a,345,155,m);let s=0;for(let p of a)s+=p;let t=`${s.toString(8).padStart(6,"0")}\x00 `;return nc(a,148,8,t),a}function lr(c){let a=c%$a;return a===0?0:$a-a}function ss(c,a=c){return fm(a,{withFileTypes:!0}).sort((m,s)=>m.name.localeCompare(s.name)).flatMap((m)=>{let s=os(a,m.name);if(m.isDirectory())return ss(c,s);if(!m.isFile())return[];let t=ms(c,s),p=as(s);return[{path:t,content:cs(s),mode:p.mode&511,mtime:Math.floor(p.mtimeMs/1000)}]})}function xm(c,a){return c.map((o)=>({...o,path:`${a}/${o.path.replaceAll("\\","/")}`}))}function ts(c,a=c){let o=vm(c);return fm(a,{withFileTypes:!0}).sort((s,t)=>s.name.localeCompare(t.name)).flatMap((s)=>{let t=os(a,s.name),p=ms(c,t).replaceAll("\\","/");if(o(p,s.isDirectory()))return[];if(s.isDirectory())return ts(c,t);if(!s.isFile())return[];let w=as(t);return[{path:p,content:cs(t),mode:w.mode&511,mtime:Math.floor(w.mtimeMs/1000)}]})}function ps(c,a){let o=em(c),m=em(a),s=[...xm(ts(o),wr),...xm(ss(m),Cr)];if(!s.length)throw Error("El build del space no contiene archivos para publicar");let t=[];for(let p of s){t.push($r(p)),t.push(p.content);let w=lr(p.content.length);if(w>0)t.push(Buffer.alloc(w,0))}return t.push(Buffer.alloc($a*rr,0)),pr(Buffer.concat(t))}import{mkdirSync as rs,writeFileSync as jr}from"node:fs";import{dirname as Qr,join as nr,normalize as Jr,sep as ws}from"node:path";import{gunzipSync as Ar}from"node:zlib";var ic=512;function la(c,a,o){let m=c.subarray(a,a+o),s=m.indexOf(0);return(s>=0?m.subarray(0,s):m).toString("utf-8").trim()}function Rr(c,a,o){let m=la(c,a,o).replaceAll("\x00","").trim();if(!m)return 0;return Number.parseInt(m,8)}function Pr(c){let a=c%ic;return a===0?0:ic-a}function Wr(c){let a=la(c,0,100),o=la(c,345,155);return o?`${o}/${a}`:a}function Gr(c){let a=Jr(c);if(!c||c.startsWith("/")||a.startsWith("..")||a.includes(`${ws}..${ws}`)||a==="..")throw Error("El paquete del space contiene rutas inválidas")}function Cs(c,a,o){let m=Ar(c),s=a.replaceAll("\\","/").replace(/^\/+|\/+$/g,""),t=`${s}/`,p=0,w=0;while(p+ic<=m.length){let C=m.subarray(p,p+ic),q=C.every((Z)=>Z===0);if(p+=ic,q)break;let g=Wr(C),Q=la(C,156,1)||"0",A=Rr(C,124,12),Y=m.subarray(p,p+A);if(p+=A+Pr(A),!g.startsWith(t))continue;let J=g.slice(t.length);if(!J)continue;Gr(J);let P=nr(o,...J.split("/"));if(Q==="5"){rs(P,{recursive:!0});continue}if(Q!=="0")continue;rs(Qr(P),{recursive:!0}),jr(P,Y),w+=1}if(!w)throw Error(`El paquete del space no contiene la carpeta ${s}/`);return w}import{spawn as Qa}from"node:child_process";import{createServer as Js}from"node:http";import{existsSync as Ir,mkdirSync as Mr,openSync as Xr,readFileSync as Zr,rmSync as Hr,writeFileSync as Yr}from"node:fs";import{dirname as Fr,join as na,resolve as As}from"node:path";import{request as Ur}from"node:http";import{request as Tr}from"node:https";function gs(c){let a=[],o="",m=null,s=!1;for(let t of c){if(s){o+=t,s=!1;continue}if(t==="\\"){s=!0;continue}if(m){if(t===m)m=null;else o+=t;continue}if(t==='"'||t==="'"){m=t;continue}if(/\s/.test(t)){if(o)a.push(o),o="";continue}o+=t}if(m)throw Error("Comando inválido: falta cerrar una comilla");if(o)a.push(o);return a}var hr=".justo-space-preview",Kr="preview.json",_r=30000;function Ja(c){return na(c,hr)}function Rs(c){return na(Ja(c),Kr)}function qs(c){return na(Ja(c),"bridge.log")}function $s(c){return na(Ja(c),"vite.log")}function Ps(c){Mr(Ja(c),{recursive:!0})}function ja(c){if(!c)return;try{process.kill(c,"SIGTERM")}catch{return}}function Er(c){if(process.platform==="darwin")return{command:"open",args:[c]};if(process.platform==="win32")return{command:"cmd",args:["/c","start","",c]};return{command:"xdg-open",args:[c]}}async function kr(c,a){if(!a)return{attempted:!1,opened:!1};let o=Er(c);return await new Promise((m)=>{let s=Qa(o.command,o.args,{stdio:"ignore",detached:!0});s.once("error",()=>{m({attempted:!0,opened:!1,message:"No se pudo abrir el navegador por defecto automáticamente. Abre la URL manualmente."})}),s.once("spawn",()=>{s.unref(),m({attempted:!0,opened:!0})})})}function Vr(c){let a=Rs(c);if(!Ir(a))return;try{let o=JSON.parse(Zr(a,"utf-8"));ja(o.appPid),ja(o.bridgePid)}catch{}Hr(a,{force:!0})}function ls(){return new Promise((c,a)=>{let o=Js();o.listen(0,"127.0.0.1",()=>{let m=o.address();if(!m||typeof m==="string"){o.close(),a(Error("No se pudo obtener un puerto libre"));return}let{port:s}=m;o.close((t)=>{if(t){a(t);return}c(s)})}),o.on("error",a)})}function js(c){return new Promise((a)=>setTimeout(a,c))}function Dr(c){return new Promise((a,o)=>{let t=(new URL(c).protocol==="https:"?Tr:Ur)(c,{method:"GET"},(p)=>{a(p.statusCode||0),p.resume()});t.on("error",o),t.end()})}async function Qs(c,a=_r){let o=Date.now();while(Date.now()-o<a){try{if(await Dr(c)>0)return}catch{await js(500);continue}await js(500)}throw Error(`Timeout esperando que el preview responda en ${c}`)}function zr(c){return Ps(Fr(c)),Xr(c,"a")}function ns(c,a,o,m,s){let t=zr(m),p=Qa(c,a,{cwd:o,detached:!0,stdio:["ignore",t,t],env:{...process.env,...s}});if(!p.pid)throw Error(`No se pudo iniciar el proceso ${c}`);return p.unref(),p.pid}function Ws(){let c=ro("prod");if(!c)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 c}async function yr(c){let a=[];for await(let o of c)a.push(Buffer.isBuffer(o)?o:Buffer.from(o));return Buffer.concat(a).toString("utf-8")}function dc(c,a,o){c.writeHead(a,{"Content-Type":"application/json; charset=utf-8","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Content-Type","Access-Control-Allow-Methods":"POST,OPTIONS,GET"}),c.end(JSON.stringify(o))}function ia(c){let a=c.trim(),o=new Set([0]);for(let s=0;s<a.length;s++)if(a[s]==="{"||a[s]==="[")o.add(s);let m=[...o].sort((s,t)=>t-s);for(let s of m)try{return JSON.parse(a.slice(s))}catch{continue}return a}function Gs(c){return{...process.env,NODE_OPTIONS:"",__JUSTO_REPL_PORT:"",JUSTO_TEAM_CLI_EMAIL:c.email,JUSTO_TEAM_CLI_TOKEN:c.token,JUSTO_TEAM_CLI_REFRESH_TOKEN:c.refreshToken,JUSTO_TEAM_CLI_INTERACTIVE:"false",JUSTO_TEAM_CLI_DEVICE_ID:"spaces-preview"}}function Sr(c,a){return{VITE_JUSTO_CLI_ENDPOINT:c,VITE_JUSTO_STREAM_ENDPOINT:a,VITE_JUSTO_CLI_MODE:"preview",[uc]:Ca}}function ur(c,a,o,m){return new Promise((s,t)=>{let p=Qa(wa(),[a,"--env","prod",...m,"--format","json"],{cwd:process.cwd(),env:Gs(o),stdio:["ignore","pipe","pipe"]}),w="";p.stdout.on("data",(C)=>{if(!c.headersSent)c.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"});c.write(C)}),p.stderr.on("data",(C)=>{w+=Buffer.from(C).toString("utf-8")}),p.on("error",t),p.on("close",(C)=>{if(!C){if(!c.headersSent)c.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"});c.end(),s();return}let q=ia(w.trim());t(Error(q.error||w.trim()||"justoStream failed"))})})}async function Is(c){let a=Number(c.port);if(!a)throw Error("Falta --port para el bridge interno de preview");let o=Ws(),m=As(c["cli-path"]||process.argv[1]||""),s=Js(async(t,p)=>{if(t.method==="OPTIONS"){dc(p,200,{ok:!0});return}if(t.method==="GET"&&t.url==="/__justo/health"){dc(p,200,{ok:!0});return}if(t.method!=="POST"||t.url!=="/__justo/cli"&&t.url!=="/__justo/stream"){dc(p,404,{ok:!1,error:"Not found"});return}try{let w=await yr(t),q=JSON.parse(w||"{}").command;if(!q)throw Error("Debes indicar un comando");let g=Array.isArray(q)?q:gs(q);if(t.url==="/__justo/stream"){await ur(p,m,o,g);return}let Q=await new Promise((A,Y)=>{let J=Qa(wa(),[m,"--env","prod",...g,"--format","json"],{cwd:process.cwd(),env:Gs(o),stdio:["ignore","pipe","pipe"]}),P=[],Z=[];J.stdout.on("data",(G)=>P.push(Buffer.from(G))),J.stderr.on("data",(G)=>Z.push(Buffer.from(G))),J.on("error",Y),J.on("close",(G)=>{let T=Buffer.concat(P).toString("utf-8")||Buffer.concat(Z).toString("utf-8");if(G&&G!==0){let l=ia(T);Y(Error(l.error||T||"justoCli failed"));return}A(ia(T))})});dc(p,200,{result:Q})}catch(w){let C=w instanceof Error?w.message:"Unexpected error";dc(p,400,{error:C})}});await new Promise((t,p)=>{s.listen(a,"127.0.0.1",()=>t()),s.on("error",p)}),D(`Space preview bridge listening on http://127.0.0.1:${a}
1109
+ `),await new Promise((t,p)=>{s.on("close",()=>t()),s.on("error",p)})}async function Ms(c){let a=c.path;if(!a)throw Error("Falta --path. Ejemplo: team-cli spaces preview --path ./mi-space-app");let o=Na(a);Ws(),Ps(o),Vr(o);let m=Number(c.port)||await ls(),s=Number(c["bridge-port"])||await ls(),t=c.open==="true",p=`http://127.0.0.1:${m}`,w=`http://127.0.0.1:${s}/__justo/cli`,C=`http://127.0.0.1:${s}/__justo/stream`,q=As(process.argv[1]||""),g=ns(wa(),[q,"__spaces-preview-bridge","--port",String(s),"--cli-path",q],process.cwd(),qs(o),{}),Q=ns(Qc("yarn"),["dev","--host","127.0.0.1","--port",String(m)],o,$s(o),Sr(w,C));try{await Qs(`http://127.0.0.1:${s}/__justo/health`),await Qs(p)}catch(J){throw ja(Q),ja(g),J}let A={appPid:Q,bridgePid:g,previewUrl:p,bridgeUrl:w,streamUrl:C,cliEnv:"prod"};Yr(Rs(o),`${JSON.stringify(A,null,2)}
1110
+ `);let Y=await kr(p,t);return{ok:!0,path:o,previewUrl:p,bridgeUrl:w,streamUrl:C,cliEnv:"prod",appPid:Q,bridgePid:g,logs:{app:$s(o),bridge:qs(o)},open:Y}}function dr(c){try{return gc.parse(c)}catch{throw Error("El valor de --operation debe ser JSON/EJSON válido")}}function Oc(){if(!F())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 qc(c,a,o){let m=c[a];if(!m)throw Error(`Falta --${a}. Ejemplo: ${o}`);return m}function Zs(c,a){let o=c[2];if(!o)throw Error(`Uso: ${a}`);return o}function da(){let c=xc();if(c==="local")return"http://intra.localhost:5173";if(c==="develop")return"https://intra.bejusto.com";return"https://intra.getjusto.com"}function Or(){return`Configuración de collections en \`.justo-space.json\`:
1111
+ - \`spaces publish\` lee \`repo/.justo-space.json\`, valida \`collections\` y sincroniza índices
1112
+ - cada collection lógica debe existir en \`collections\`
1113
+ - los nombres válidos usan solo letras, números y guion bajo
1114
+ - la collection física en Mongo queda como \`spaces.<slug_sanitized>.<collection>\`
1115
+ - el \`slug\` se sanitiza reemplazando todo lo no alfanumérico por \`_\`
1116
+ - si una collection deja de existir en \`.justo-space.json\`, no se borran sus datos, pero deja de estar autorizada para \`spaces db\`
1117
+
1118
+ Ejemplo completo:
1119
+ \`\`\`json
1120
+ {
1121
+ "template": "react-vite-shadcn",
1122
+ "version": 2,
1123
+ "collections": {
1124
+ "events": {
1125
+ "indexes": [
1126
+ {
1127
+ "name": "createdAt_desc",
1128
+ "key": {
1129
+ "createdAt": -1
856
1130
  }
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
- testAggregationQuery(aggregationQueryId: $aggregationQueryId, params: $params)
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
- `);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 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
- addAggregationQueryVersion(
863
- aggregationQueryId: $aggregationQueryId
864
- pipeline: $pipeline
865
- variables: $variables
866
- ) {
867
- _id
868
- currentVersionIndex
869
- }
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
- updateAggregationQuery(
872
- aggregationQueryId: $aggregationQueryId
873
- aggregationQuery: $aggregationQuery
874
- ) {
875
- _id
876
- name
877
- description
878
- collection
879
- allowedUsersIds
880
- tags
881
- currentVersionIndex
882
- }
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
- createAggregationQuery {
885
- _id
886
- name
887
- description
888
- collection
889
- currentVersionIndex
890
- allowedUsersIds
891
- tags
892
- pipeline
893
- variables {
894
- key
895
- fieldType
896
- fieldParams
1131
+ },
1132
+ {
1133
+ "name": "eventId_1",
1134
+ "key": {
1135
+ "eventId": 1
1136
+ },
1137
+ "unique": true
897
1138
  }
898
- }
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
- $prompt: String
901
- $name: String
902
- $description: String
903
- $fullCollectionName: String
904
- $variables: [JSON]
905
- $pipeline: String
906
- $preview: [JSON]
907
- ) {
908
- generateAdminQuery(
909
- prompt: $prompt
910
- name: $name
911
- description: $description
912
- fullCollectionName: $fullCollectionName
913
- variables: $variables
914
- pipeline: $pipeline
915
- preview: $preview
916
- canUseVariables: true
917
- ) {
918
- responseText
919
- fullCollectionName
920
- pipeline
921
- variables
922
- aggregationDescription
923
- aggregationName
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 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...
932
- `);let i=(await u({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
933
- downloadAggregationQueryData(aggregationQueryId: $aggregationQueryId, params: $params)
934
- }`,variables:{aggregationQueryId:t,params:o}})).downloadAggregationQueryData;C(`Reporte en proceso (${i})...
935
- `);let n=null;while(!n){await Ya(1000);let l=await u({service:"data",query:`query ($id: String) {
936
- getAsyncReport(id: $id) {
937
- _id
938
- status
939
- estimatedRecordsCount
940
- fileUrl
941
- }
942
- getAsyncReportRecordsCount(id: $id)
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(`
944
- Descargando archivo...
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
946
-
947
- Comandos de datos y reportes.
948
-
949
- Recomendado:
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.
955
- Siempre que puedas, prefiere varias queries simples antes que un solo pipeline con lookup.
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.
961
-
962
- Uso:
963
- team-cli data <subcomando> [opciones]
964
-
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:
986
- create
987
- Crear un query nuevo.
988
- Devuelve el _id para seguir con edit, ai-edit, view o preview.
989
-
990
- edit <queryId>
991
- Editar un query manualmente en tu editor local usando JSON.
992
- Campos editables: name, description, collection, allowedUsersIds, tags, pipeline, variables.
993
- El pipeline debe quedar como string con un array JavaScript válido.
994
-
995
- ai-edit <queryId>
996
- Editar un query con IA.
997
- Uso: team-cli data queries ai-edit <queryId> --prompt '<texto>' [--params '<json>'] [--format toon|json]
998
- Si envías --params, primero se ejecuta preview y esos resultados se adjuntan al prompt.
999
-
1000
- view <queryId>
1001
- Ver informacion de un query.
1002
-
1003
- view-pipeline <queryId>
1004
- Ver el pipeline de un query.
1005
-
1006
- preview <queryId>
1007
- Ejecutar un query de prueba.
1008
- Uso: team-cli data queries preview <queryId> --params '<json>' [--format toon|json]
1009
-
1010
- run <queryId>
1011
- Ejecutar un query completo en streaming NDJSON.
1012
- Usa timeout de 5 minutos y read preference secondaryPreferred.
1013
- Uso: team-cli data queries run <queryId> --limit <n> [--params '<json>']
1014
-
1015
- download <queryId>
1016
- Descargar resultado completo como Excel.
1017
- Uso: team-cli data queries download <queryId> --path <filepath> [--params '<json>'] [--format toon|json]
1018
-
1019
- add-viewers <queryId>
1020
- Agregar personas con acceso a un query usando sus emails de Justo.
1021
- Uso: team-cli data queries add-viewers <queryId> --emails 'ana@justo.com,bob@justo.com'
1022
- Esto actualiza allowedUsersIds sin cambiar el pipeline ni crear una versión nueva.
1023
-
1024
- Opciones:
1025
- --params '<json>' Parametros del query. Default: {}
1026
- --limit <n> Requerido para run. En execute es opcional y limita resultados.
1027
- --emails '<csv>' Requerido para add-viewers. Lista separada por comas.
1028
- --prompt '<texto>' Prompt para ai-edit. Si no viene, se pide interactivamente.
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.
1032
- --path <filepath> Requerido para download
1033
-
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}}]'
1038
- team-cli data queries create
1039
- team-cli data queries edit abc123
1040
- team-cli data queries ai-edit abc123 --prompt 'Filtra solo ordenes canceladas'
1041
- team-cli data queries ai-edit abc123 --prompt 'Ajusta el pipeline' --params '{"websiteId":"w1"}'
1042
- team-cli data queries preview abc123 --params '{"startDate": "2026-01-01"}'
1043
- team-cli data queries run abc123 --limit 1000 --params '{"startDate": "2026-01-01"}'
1044
- team-cli data queries download abc123 --params '{"startDate": "2026-01-01"}' --path resultado.xlsx
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=`
1046
- query ResolverInfo($name: ID!, $mutation: Boolean!) {
1047
- params(name: $name, mutation: $mutation) {
1048
- name
1049
- params
1050
- result
1051
- basicResultQuery
1139
+ ]
1052
1140
  }
1053
1141
  }
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
1056
-
1057
- Ejecutar queries y mutations GraphQL.
1058
-
1059
- Uso:
1060
- team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]
1061
- team-cli graphql <servicio> info <queryName|mutationName> [--format toon|json]
1062
-
1063
- Comando info:
1064
- Consulta la metadata publicada por OrionJS para un query o mutation.
1065
- Devuelve el tipo de operación, los params serializados, el resultado y un basicResultQuery.
1066
- Si no indicas si es query o mutation, la CLI prueba ambas automáticamente.
1067
-
1068
- Formato:
1069
- Por defecto usa toon. Usa --format json para JSON estándar.
1070
-
1071
-
1072
-
1073
- Servicios disponibles: ${r}.
1074
-
1075
- Ejemplos:
1076
- \`\`\`bash
1077
- npx @getjusto/team-cli graphql main 'query { me { _id roles } }'
1078
- npx @getjusto/team-cli graphql main 'query($id: ID) { user(userId: $id) { _id } }' --variables '{"id": "abc123"}'
1079
- npx @getjusto/team-cli graphql tabs 'query { tab(tabId: "t123") { _id status } }' --format json
1080
- \`\`\`
1081
-
1082
- ### graphql info
1083
-
1084
- Úsalo cuando conoces el nombre del resolver pero no su contrato exacto.
1085
-
1086
- \`\`\`bash
1087
- npx @getjusto/team-cli graphql <service> info <queryName|mutationName> [--format toon|json]
1088
- \`\`\`
1089
-
1090
- Devuelve:
1091
- - \`operationType\`
1092
- - \`info.params\`
1093
- - \`info.result\`
1094
- - \`info.basicResultQuery\`
1095
-
1096
- Ejemplos:
1097
- \`\`\`bash
1098
- npx @getjusto/team-cli graphql main info website
1099
- npx @getjusto/team-cli graphql auth info requestLoginCode --format json
1142
+ }
1100
1143
  \`\`\`
1101
1144
 
1102
- ### Mapa de servicios GraphQL
1103
-
1104
- Usa esto para mapear una URL GraphQL al valor correcto de \`team-cli graphql <service>\`.
1105
-
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
1145
+ Reglas de índices:
1146
+ - cada índice debe tener \`name\` y \`key\`
1147
+ - puedes usar opciones comunes de Mongo como \`unique\`, \`sparse\`, \`expireAfterSeconds\` y \`partialFilterExpression\`
1148
+ - en cada publish, los índices declarados se recrean en modo estricto para esa collection
1149
+ `}function br(){return"Acceso a Mongo con `spaces db`:\n- comando: `team-cli spaces db --slug <slug> --collection <collection> --operation '<EJSON>'`\n- el backend valida que el space exista, que no esté archivado y que la collection esté declarada\n- el acceso queda restringido siempre a una sola collection del space\n- cualquier usuario autenticado de Justo con al menos un rol puede usarlo\n- no necesitas conectar Mongo directo desde el space ni desde el CLI\n\nOperaciones permitidas:\n- `find`, `findOne`, `insertOne`, `insertMany`\n- `updateOne`, `updateMany`, `replaceOne`\n- `deleteOne`, `deleteMany`\n- `countDocuments`, `distinct`, `aggregate`\n- `findOneAndUpdate`, `findOneAndDelete`, `findOneAndReplace`\n- `bulkWrite`\n\nPayload esperado por operación:\n- `find`: `filter`, opcional `projection`, `sort`, `skip`, `limit`\n- `findOne`: `filter`, opcional `projection`, `sort`\n- `insertOne`: `document`\n- `insertMany`: `documents`, opcional `ordered`\n- `updateOne` y `updateMany`: `filter`, `update`, opcional `upsert`, `arrayFilters`\n- `replaceOne`: `filter`, `replacement`, opcional `upsert`\n- `deleteOne` y `deleteMany`: `filter`\n- `countDocuments`: `filter`\n- `distinct`: `field`, opcional `filter`\n- `aggregate`: `pipeline`, opcional `allowDiskUse`, `maxTimeMS`\n- `findOneAndUpdate`: `filter`, `update`, opcional `upsert`, `returnDocument`, `projection`, `sort`, `arrayFilters`\n- `findOneAndDelete`: `filter`, opcional `projection`, `sort`\n- `findOneAndReplace`: `filter`, `replacement`, opcional `upsert`, `returnDocument`, `projection`, `sort`\n- `bulkWrite`: `operations`, opcional `ordered`\n\nEjemplos:\n```bash\nteam-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{\"type\":\"find\",\"filter\":{},\"limit\":10}'\n\nteam-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{\"type\":\"insertOne\",\"document\":{\"eventId\":\"evt-1\",\"name\":\"Evento demo\"}}'\n\nteam-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{\"type\":\"updateOne\",\"filter\":{\"eventId\":\"evt-1\"},\"update\":{\"$set\":{\"name\":\"Evento actualizado\"}}}'\n\nteam-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{\"type\":\"aggregate\",\"pipeline\":[{\"$match\":{\"eventId\":\"evt-1\"}},{\"$project\":{\"_id\":0,\"name\":1}}]}'\n```\n\nEJSON:\n- usa EJSON cuando necesites tipos BSON como `ObjectId` o `Date`\n- ejemplo con fecha:\n```bash\nteam-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{\"type\":\"insertOne\",\"document\":{\"createdAt\":{\"$date\":\"2026-03-16T21:05:00.000Z\"}}}'\n```\n- ejemplo con object id:\n```bash\nteam-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{\"type\":\"findOne\",\"filter\":{\"_id\":{\"$oid\":\"65f4c55e8b6a5d4db9f1a123\"}}}'\n```\n"}async function Br(c,a){let o=await aa(),m=await fetch(`${K("data")}/spaces/publish/${c}`,{method:"POST",headers:{"Content-Type":"application/gzip",...o?{"X-ORION-JWT":o}:{}},body:a}),s=await m.json();if(!m.ok||s.error)throw Error(s.error||"No se pudo publicar el space.");return s}async function vr(c){let a=await aa(),o=await fetch(`${K("data")}/spaces/fork/${c}`,{method:"GET",headers:a?{"X-ORION-JWT":a}:{}});if(!o.ok){let m=await o.json().catch(()=>({}));throw Error(m.error||"No se pudo descargar el repo del space.")}return Buffer.from(await o.arrayBuffer())}function er(c){let a=Xs(c);if(Lr(a)&&ir(a).length>0)throw Error(`La carpeta ya existe y no está vacía: ${a}`);return Nr(a,{recursive:!0}),a}function Oa(){return`team-cli spaces
1107
1150
 
1108
1151
  Spaces son aplicaciones internas en React, pensadas para que las construyan agentes.
1109
1152
  El flujo oficial parte con \`spaces init\` y \`spaces publish\` solo acepta apps creadas así.
@@ -1126,6 +1169,12 @@ Cada space:
1126
1169
  - para queries grandes también reciben \`window.justo.stream(command, onRow)\`
1127
1170
  - \`window.justo.stream(...)\` consume NDJSON, parsea cada fila a JSON y llama tu callback
1128
1171
  - \`spaces init\`, \`spaces preview\` y \`spaces publish\` funcionan en macOS, Linux y Windows sin depender de \`tar\` global
1172
+ - el archivo \`.justo-space.json\` puede declarar \`collections\` para que el publish sincronice índices en Mongo
1173
+ - esas collections se exponen con \`team-cli spaces db\` usando el prefijo físico \`spaces.<slug_sanitized>.<collection>\`
1174
+
1175
+ ${Or()}
1176
+
1177
+ ${br()}
1129
1178
 
1130
1179
  Flujo sugerido para agentes:
1131
1180
  1. \`team-cli spaces init --path ./mi-space-app\`
@@ -1135,7 +1184,7 @@ Flujo sugerido para agentes:
1135
1184
  5. desarrollar la app React dentro de esa carpeta
1136
1185
  6. \`team-cli spaces publish <spaceId> --path ./mi-space-app\`
1137
1186
  7. hacer commit del repo después de publicar
1138
- 8. abrir \`${De()}/spaces/<slug>\`
1187
+ 8. abrir \`${da()}/spaces/<slug>\`
1139
1188
  9. si necesitas retomarlo en otra carpeta: \`team-cli spaces fork <slug> --path ./mi-space-app\`
1140
1189
 
1141
1190
  Slugs:
@@ -1190,6 +1239,9 @@ import {justoCli, justoStream} from '@/lib/justo'
1190
1239
 
1191
1240
  const me = await justoCli("graphql main 'query { me { _id email roles } }'")
1192
1241
  const rows = await justoCli("data queries preview <queryId> --params '{\\"limit\\":10}'")
1242
+ const events = await justoCli(
1243
+ \`spaces db --slug usuario:dashboard-1234 --collection events --operation '{"type":"find","filter":{},"limit":10}'\`,
1244
+ )
1193
1245
  await justoStream(
1194
1246
  "data queries run <queryId> --limit 1000 --params '{\\"websiteId\\":\\"w1\\"}'",
1195
1247
  row => {
@@ -1205,7 +1257,8 @@ Comandos:
1205
1257
  - \`spaces publish <spaceId> --path ./mi-space-app\`
1206
1258
  - \`spaces fork <slug> --path ./mi-space-app\`
1207
1259
  - \`spaces archive <spaceId>\`
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) {
1260
+ - \`spaces db --slug <slug> --collection events --operation '{"type":"find","filter":{}}'\`
1261
+ `}async function Hs(c){let a=qc(c,"path","team-cli spaces init --path ./mi-space-app");return Bm(a)}async function Ys(c){return await Ms(c)}async function Fs(c){Oc();let a=qc(c,"name","team-cli spaces create --name 'Mi space' --description '...' --slug dashboard-1234"),o=qc(c,"description","team-cli spaces create --name 'Mi space' --description 'Sitio interno' --slug dashboard-1234"),m=qc(c,"slug","team-cli spaces create --name 'Mi space' --description '...' --slug dashboard-1234"),s=await R({service:"data",query:`mutation ($name: String, $description: String, $slug: String) {
1209
1262
  createSpace(name: $name, description: $description, slug: $slug) {
1210
1263
  _id
1211
1264
  name
@@ -1216,7 +1269,7 @@ Comandos:
1216
1269
  createdByEmail
1217
1270
  createdById
1218
1271
  }
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) {
1272
+ }`,variables:{name:a,description:o,slug:m}});return{...s.createSpace,intraUrl:`${da()}/spaces/${s.createSpace.slug}`,serveUrl:`${K("data")}/spaces/${s.createSpace.slug}`}}async function Us(c,a){Oc();let o=Zs(c,"team-cli spaces publish <spaceId> --path ./mi-space-app"),m=qc(a,"path","team-cli spaces publish <spaceId> --path ./mi-space-app"),s=bm(m),t=ps(m,s),p=await Br(o,t);return{...p,intraUrl:p.slug?`${da()}/spaces/${p.slug}`:void 0,serveUrl:p.slug?`${K("data")}/spaces/${p.slug}`:void 0,builtFrom:Xs(m)}}async function Ts(c,a){Oc();let o=c[2];if(!o)throw Error("Uso: team-cli spaces fork <slug> --path ./mi-space-app");let m=er(a.path||`./${o}`),s=await vr(o),t=Cs(s,"repo",m);return{ok:!0,slug:o,path:m,extractedFiles:t,nextSteps:[`cd ${m}`,"yarn install","team-cli spaces preview --path . --open"]}}async function hs(c){Oc();let a=Zs(c,"team-cli spaces archive <spaceId>");return(await R({service:"data",query:`mutation ($spaceId: String) {
1220
1273
  archiveSpace(spaceId: $spaceId) {
1221
1274
  _id
1222
1275
  name
@@ -1228,11 +1281,11 @@ Comandos:
1228
1281
  createdById
1229
1282
  archivedAt
1230
1283
  }
1231
- }`,variables:{spaceId:r}})).archiveSpace}function ao(e){return`team-cli
1284
+ }`,variables:{spaceId:a}})).archiveSpace}async function Ks(c){Oc();let a=qc(c,"slug",`team-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{"type":"find","filter":{}}'`),o=qc(c,"collection",`team-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{"type":"find","filter":{}}'`),m=qc(c,"operation",`team-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{"type":"find","filter":{}}'`),s=gc.serialize(dr(m)),t=await Wc(),p=await fetch(`${K("data")}/spaces/${encodeURIComponent(a)}/db`,{method:"POST",headers:t,body:JSON.stringify({collection:o,operation:s})}),w=await p.json().catch(()=>({}));if(!p.ok||w.error)throw Error(w.error||"No se pudo ejecutar spaces db");return w.result}function _s(c){return`team-cli
1232
1285
 
1233
1286
  Herramienta CLI para el equipo Justo.
1234
1287
 
1235
- ${e}
1288
+ ${c}
1236
1289
 
1237
1290
  Si necesitas obtener data y no existe un query listo, usa create + ai-edit.
1238
1291
  Flujo sugerido: create -> ai-edit -> preview -> run o download.
@@ -1260,7 +1313,7 @@ Cada grupo de comandos tiene su propia ayuda. Usa \`--help\` para ver los comand
1260
1313
  - \`graphql\` — Ejecutar queries y mutations GraphQL
1261
1314
  - \`admin\` — Comandos administrativos con contexto de website
1262
1315
  - \`data\` — Datos y reportes. Puede obtener data de todas las bases de datos de Justo
1263
- - \`spaces\` — Crea apps React para Spaces con \`spaces init\`, publícalas con \`spaces publish\` y compártelas en intra.
1316
+ - \`spaces\` — Crea apps React para Spaces con \`spaces init\`, publícalas con \`spaces publish\`, compártelas en intra y usa \`spaces db\` para collections declaradas del space.
1264
1317
 
1265
1318
  ## Tips
1266
1319
 
@@ -1289,4 +1342,4 @@ Si todavía no sabes bien dónde vive la data, primero usa \`data explain\` para
1289
1342
  Cuando ya tengas claro un pipeline y solo quieras probarlo una vez, usa \`data execute\`.
1290
1343
  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
1344
 
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();
1345
+ `}function Es(){let c=F(),a=c?`Sesión: ${c.email}`:"Sesión: no iniciada";return _s(a)}async function ks(c){let{positional:a,flags:o}=bc(c);if(o.env)mo(o.env);let m=a[0],s=a[1];if(m==="__spaces-preview-bridge")return await Is(o);if(o.version)return{version:"0.0.13"};if(o.help&&!m)return Es();if(m==="auth"){if(s==="--help"||o.help)return Za();if(s==="login")return await Eo();if(s==="login-with-token")return await ko(o);if(s==="request-code")return await Vo(o);if(s==="logout")return await Do();if(s==="status")return await zo();return Za()}if(m==="admin"){let t=a[1],p=a[2],w=a[3],C=a[4];if(!t||t==="--help")return oa();if(t==="search"&&o.help)return To();if(t==="search")return await Uo(a,o);if(!p||p==="--help")return oa();if(p==="show")return await lo(t);if(p==="stores"&&w==="list")return await ho(t);if(p==="coupons"&&(!w||w==="--help"))return Vc();if(p==="coupons"&&w==="create"&&o.help)return Yo();if(p==="coupons"&&w==="update"&&o.help)return Fo();if(p==="coupons"&&w==="codes"&&a[4]==="create"&&o.help)return Wo();if(p==="coupons"&&o.help)return Vc();if(p==="coupons"&&w==="list")return await Io(t,o);if(p==="coupons"&&w==="show"){if(!C)throw Error("Uso: team-cli admin <web> coupons show <couponId>");return await Mo(t,C)}if(p==="coupons"&&w==="create")return await Xo(t,o);if(p==="coupons"&&w==="update"){if(!C)throw Error("Uso: team-cli admin <web> coupons update <couponId> --input '<json>'");return await Zo(t,C,o)}if(p==="coupons"&&w==="delete"){if(!C)throw Error("Uso: team-cli admin <web> coupons delete <couponId>");return await Ho(t,C)}if(p==="coupons"&&w==="codes"){let q=a[4],g=a[5];if(!q||q==="--help")return Vc();if(q==="list"){if(!g)throw Error("Uso: team-cli admin <web> coupons codes list <couponId>");return await Jo(t,g,o)}if(q==="create"){if(!g)throw Error("Uso: team-cli admin <web> coupons codes create <couponId> --input '<json>'");return await Ao(t,g,o)}if(q==="create-random"){if(!g)throw Error("Uso: team-cli admin <web> coupons codes create-random <couponId> --quantity <n>");return await Ro(t,g,o)}if(q==="delete"){if(!g)throw Error(`Uso: team-cli admin <web> coupons codes delete <couponId> --ids '["id1"]'`);return await Po(t,g,o)}return Vc()}return oa()}if(m==="graphql"){if(s==="--help"||o.help)return $m();return await gm(a,o)}if(m==="data"){let t=a[1],p=a[2];if(o.help||s==="--help")return ha();if(t==="explain")return await xo(o);if(t==="execute")return await fo(o);if(t==="queries"&&p==="create")return await eo();if(t==="queries"&&p==="edit")return await cm(a);if(t==="queries"&&p==="ai-edit")return await am(a,o);if(t==="queries"&&p==="view")return await om(a);if(t==="queries"&&p==="view-pipeline")return await mm(a);if(t==="queries"&&p==="preview")return await sm(a,o);if(t==="queries"&&p==="run")return await tm(a,o);if(t==="queries"&&p==="add-viewers")return await pm(a,o);if(t==="queries"&&p==="download")return await rm(a,o);return ha()}if(m==="spaces"){let t=a[1];if(!t||t==="--help"||o.help)return Oa();if(t==="init")return await Hs(o);if(t==="create")return await Fs(o);if(t==="preview")return await Ys(o);if(t==="publish")return await Us(a,o);if(t==="fork")return await Ts(a,o);if(t==="archive")return await hs(a);if(t==="db")return await Ks(o);return Oa()}return Es()}var{flags:Vs}=bc(process.argv.slice(2));async function xr(){try{let c=await ks(process.argv.slice(2));if(c&&typeof c==="object"&&"__streamHandled"in c&&c.__streamHandled)return;if(typeof c==="string"){ao(c);return}co(c,Vs)}catch(c){oo(c,Vs),process.exit(1)}}xr();