@getjusto/team-cli 0.0.13 → 0.0.14

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 +199 -87
  2. package/package.json +1 -1
package/bin/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
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) {
2
+ function bc(c){let o=[],a={},t={};for(let m=0;m<c.length;m++)if(c[m].startsWith("--")&&c[m+1]&&!c[m+1].startsWith("--")){let s=c[m].slice(2);if(a[s]=c[m+1],!t[s])t[s]=[];t[s].push(c[m+1]),m++}else if(c[m].startsWith("--"))a[c[m].slice(2)]="true";else o.push(c[m]);return{positional:o,flags:a,arrayFlags:t}}function ic(c,o){let a=c[o];if(!a)throw Error(`--${o} es requerido.`);return a}var Om={comma:",",tab:"\t",pipe:"|"},uc=Om.comma;function vo(c){return c.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}function bm(c){return c==="true"||c==="false"||c==="null"}function v(c){if(c===null)return null;if(typeof c==="object"&&c!==null&&"toJSON"in c&&typeof c.toJSON==="function"){let o=c.toJSON();if(o!==c)return v(o)}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(v);if(c instanceof Set)return Array.from(c).map(v);if(c instanceof Map)return Object.fromEntries(Array.from(c,([o,a])=>[String(o),v(a)]));if(Bm(c)){let o={};for(let a in c)if(Object.prototype.hasOwnProperty.call(c,a))o[a]=v(c[a]);return o}return null}function Cc(c){return c===null||typeof c==="string"||typeof c==="number"||typeof c==="boolean"}function pc(c){return Array.isArray(c)}function e(c){return c!==null&&typeof c==="object"&&!Array.isArray(c)}function Kc(c){return Object.keys(c).length===0}function Bm(c){if(c===null||typeof c!=="object")return!1;let o=Object.getPrototypeOf(c);return o===null||o===Object.prototype}function _c(c){return c.length===0||c.every((o)=>Cc(o))}function vm(c){return c.length===0||c.every((o)=>pc(o))}function xo(c){return c.length===0||c.every((o)=>e(o))}function xm(c){return/^[A-Z_][\w.]*$/i.test(c)}function fm(c){return/^[A-Z_]\w*$/i.test(c)}function cs(c,o=uc){if(!c)return!1;if(c!==c.trim())return!1;if(bm(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(o))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 jw=Symbol("quotedKey");function as(c,o,a,t,m,s,r){if(t.keyFolding!=="safe")return;if(!e(o))return;let{segments:w,tail:n,leafValue:l}=ts(c,o,r??t.flattenDepth);if(w.length<2)return;if(!w.every((J)=>fm(J)))return;let g=ms(w),j=s?`${s}.${g}`:g;if(a.includes(g))return;if(m&&m.has(j))return;return{foldedKey:g,remainder:n,leafValue:l,segmentCount:w.length}}function ts(c,o,a){let t=[c],m=o;while(t.length<a){if(!e(m))break;let s=Object.keys(m);if(s.length!==1)break;let r=s[0],w=m[r];t.push(r),m=w}if(!e(m)||Kc(m))return{segments:t,tail:void 0,leafValue:m};return{segments:t,tail:m,leafValue:m}}function ms(c){return c.join(".")}function Pc(c,o){if(c===null)return"null";if(typeof c==="boolean")return String(c);if(typeof c==="number")return String(c);return ss(c,o)}function ss(c,o=uc){if(cs(c,o))return c;return`"${vo(c)}"`}function Ec(c){if(xm(c))return c;return`"${vo(c)}"`}function fo(c,o=uc){return c.map((a)=>Pc(a,o)).join(o)}function x(c,o){let a=o?.key,t=o?.fields,m=o?.delimiter??",",s="";if(a)s+=Ec(a);if(s+=`[${c}${m!==uc?m:""}]`,t){let r=t.map((w)=>Ec(w));s+=`{${r.join(m)}}`}return s+=":",s}function*rs(c,o,a){if(Cc(c)){let t=Pc(c,o.delimiter);if(t!=="")yield t;return}if(pc(c))yield*Jo(void 0,c,a,o);else if(e(c))yield*Rc(c,a,o)}function*Rc(c,o,a,t,m,s){let r=Object.keys(c);if(o===0&&!t)t=new Set(r.filter((n)=>n.includes(".")));let w=s??a.flattenDepth;for(let[n,l]of Object.entries(c))yield*ps(n,l,o,a,r,t,m,w)}function*ps(c,o,a,t,m,s,r,w){let n=r?`${r}.${c}`:c,l=w??t.flattenDepth;if(t.keyFolding==="safe"&&m){let j=as(c,o,m,t,s,r,l);if(j){let{foldedKey:J,remainder:F,leafValue:A,segmentCount:P}=j,Z=Ec(J);if(F===void 0){if(Cc(A)){yield u(a,`${Z}: ${Pc(A,t.delimiter)}`,t.indent);return}else if(pc(A)){yield*Jo(J,A,a,t);return}else if(e(A)&&Kc(A)){yield u(a,`${Z}:`,t.indent);return}}if(e(F)){yield u(a,`${Z}:`,t.indent);let G=l-P,T=r?`${r}.${J}`:J;yield*Rc(F,a+1,t,s,T,G);return}}}let g=Ec(c);if(Cc(o))yield u(a,`${g}: ${Pc(o,t.delimiter)}`,t.indent);else if(pc(o))yield*Jo(c,o,a,t);else if(e(o)){if(yield u(a,`${g}:`,t.indent),!Kc(o))yield*Rc(o,a+1,t,s,n,l)}}function*Jo(c,o,a,t){if(o.length===0){yield u(a,x(0,{key:c,delimiter:t.delimiter}),t.indent);return}if(_c(o)){yield u(a,vc(o,t.delimiter,c),t.indent);return}if(vm(o)){if(o.every((m)=>_c(m))){yield*ws(c,o,a,t);return}}if(xo(o)){let m=ca(o);if(m)yield*ns(c,o,m,a,t);else yield*Bo(c,o,a,t);return}yield*Bo(c,o,a,t)}function*ws(c,o,a,t){yield u(a,x(o.length,{key:c,delimiter:t.delimiter}),t.indent);for(let m of o)if(_c(m)){let s=vc(m,t.delimiter);yield O(a+1,s,t.indent)}}function vc(c,o,a){let t=x(c.length,{key:a,delimiter:o}),m=fo(c,o);if(c.length===0)return t;return`${t} ${m}`}function*ns(c,o,a,t,m){yield u(t,x(o.length,{key:c,fields:a,delimiter:m.delimiter}),m.indent),yield*oa(o,a,t+1,m)}function ca(c){if(c.length===0)return;let o=c[0],a=Object.keys(o);if(a.length===0)return;if(gs(c,a))return a}function gs(c,o){for(let a of c){if(Object.keys(a).length!==o.length)return!1;for(let t of o){if(!(t in a))return!1;if(!Cc(a[t]))return!1}}return!0}function*oa(c,o,a,t){for(let m of c)yield u(a,fo(o.map((s)=>m[s]),t.delimiter),t.indent)}function*Bo(c,o,a,t){yield u(a,x(o.length,{key:c,delimiter:t.delimiter}),t.indent);for(let m of o)yield*Ro(m,a+1,t)}function*ls(c,o,a){if(Kc(c)){yield u(o,"-",a.indent);return}let t=Object.entries(c),[m,s]=t[0],r=t.slice(1);if(pc(s)&&xo(s)){let n=ca(s);if(n){if(yield O(o,x(s.length,{key:m,fields:n,delimiter:a.delimiter}),a.indent),yield*oa(s,n,o+2,a),r.length>0)yield*Rc(Object.fromEntries(r),o+1,a);return}}let w=Ec(m);if(Cc(s))yield O(o,`${w}: ${Pc(s,a.delimiter)}`,a.indent);else if(pc(s))if(s.length===0)yield O(o,`${w}${x(0,{delimiter:a.delimiter})}`,a.indent);else if(_c(s))yield O(o,`${w}${vc(s,a.delimiter)}`,a.indent);else{yield O(o,`${w}${x(s.length,{delimiter:a.delimiter})}`,a.indent);for(let n of s)yield*Ro(n,o+2,a)}else if(e(s)){if(yield O(o,`${w}:`,a.indent),!Kc(s))yield*Rc(s,o+2,a)}if(r.length>0)yield*Rc(Object.fromEntries(r),o+1,a)}function*Ro(c,o,a){if(Cc(c))yield O(o,Pc(c,a.delimiter),a.indent);else if(pc(c))if(_c(c))yield O(o,vc(c,a.delimiter),a.indent);else{yield O(o,x(c.length,{delimiter:a.delimiter}),a.indent);for(let t of c)yield*Ro(t,o+1,a)}else if(e(c))yield*ls(c,o,a)}function u(c,o,a){return" ".repeat(a*c)+o}function O(c,o,a){return u(c,"- "+o,a)}function Cs(c,o){let a=o("",c,[]);if(a===void 0)return Bc(c,o,[]);return Bc(v(a),o,[])}function Bc(c,o,a){if(e(c))return $s(c,o,a);if(pc(c))return qs(c,o,a);return c}function $s(c,o,a){let t={};for(let[m,s]of Object.entries(c)){let r=[...a,m],w=o(m,s,r);if(w===void 0)continue;t[m]=Bc(v(w),o,r)}return t}function qs(c,o,a){let t=[];for(let m=0;m<c.length;m++){let s=c[m],r=[...a,m],w=o(String(m),s,r);if(w===void 0)continue;let n=v(w);t.push(Bc(n,o,r))}return t}function Po(c,o){return Array.from(js(c,o)).join(`
3
+ `)}function js(c,o){let a=v(c),t=Qs(o);return rs(t.replacer?Cs(a,t.replacer):a,t,0)}function Qs(c){return{indent:c?.indent??2,delimiter:c?.delimiter??uc,keyFolding:c?.keyFolding??"off",flattenDepth:c?.flattenDepth??Number.POSITIVE_INFINITY,replacer:c?.replacer}}function As(c){let o=c.format??"toon";if(o!=="toon"&&o!=="json")throw Error("--format debe ser toon o json.");return o}function aa(c,o){if(As(o)==="json"){console.log(JSON.stringify(c,null,2));return}console.log(Po(c))}function ta(c){process.stdout.write(`${c}
4
+ `)}function ma(c,o){let t={ok:!1,error:c instanceof Error?c.message:String(c)};if((o.format==="json"?"json":"toon")==="json"){console.error(JSON.stringify(t,null,2));return}console.error(Po(t))}function k(c){process.stderr.write(c)}import{existsSync as fc,mkdirSync as Ps,readFileSync as ra,writeFileSync as Ws,unlinkSync as Gs}from"node:fs";import{join as pa}from"node:path";import{homedir as Ms}from"node:os";import{AsyncLocalStorage as Js}from"node:async_hooks";var Rs=new Js;function N(){return Rs.getStore()}var xc={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"}},Wo="prod";function sa(c){Wo=c}function Wc(){let c=process.env.JUSTO_TEAM_CLI_ENV;if(c)return c;let o=N()?.environment;if(o)return o;return Wo}function U(c){return xc[c][Wo]}var Go=pa(Ms(),".justo-team");function wa(c){let o=c==="prod"?"credentials.json":`credentials.${c}.json`;return pa(Go,o)}function Mo(){return wa(Wc())}function Is(){if(!fc(Go))Ps(Go,{recursive:!0})}function co(c){let o=N();if(o&&o.canPersistCredentials===!1)throw Error("Este entorno no permite guardar credenciales.");Is(),Ws(Mo(),JSON.stringify(c,null,2))}function Y(){let c=process.env.JUSTO_TEAM_CLI_TOKEN,o=process.env.JUSTO_TEAM_CLI_EMAIL,a=process.env.JUSTO_TEAM_CLI_REFRESH_TOKEN;if(c&&o)return{email:o,token:c,refreshToken:a||""};let t=N()?.credentials;if(t!==void 0)return t?{email:t.email,token:t.token,refreshToken:t.refreshToken||""}:null;let m=Mo();if(!fc(m))return null;try{let s=ra(m,"utf-8");return JSON.parse(s)}catch{return null}}function na(c){let o=wa(c);if(!fc(o))return null;try{let a=ra(o,"utf-8");return JSON.parse(a)}catch{return null}}function Io(){let c=N();if(c&&c.canPersistCredentials===!1)throw Error("Este entorno no permite borrar credenciales.");let o=Mo();if(fc(o))Gs(o)}import{existsSync as ga,readFileSync as Xs,writeFileSync as Zs,mkdirSync as Hs}from"node:fs";import{join as la}from"node:path";import{homedir as Fs}from"node:os";function Ys(){let c=process.env.JUSTO_TEAM_CLI_DEVICE_ID;if(c)return c;let o=N()?.deviceId;if(o)return o;let a=la(Fs(),".justo-team"),t=la(a,"device-id");if(ga(t))return Xs(t,"utf-8").trim();let m=crypto.randomUUID();if(!ga(a))Hs(a,{recursive:!0});return Zs(t,m),m}var $a={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 hs(c,o){let a=$a[c];if(!a)return`${o}: ${c}`;if(typeof a==="function")return a({label:o});return a}function Ca(c){return Object.entries(c).map(([o,a])=>hs(a,o)).join(", ")}function Us(c){if(c.error==="validationError"&&c.validationErrors)return Ca(c.validationErrors);if(c.extensions?.code==="PermissionsError"){let m=c.extensions.info?.type;if(m?.includes("User doesn't have permissions for "))return`Tu usuario no tiene permisos para [${m.split("User doesn't have permissions for ")[1]}]`;return c.message}if(c.validationErrors)return`${c.message} (${Ca(c.validationErrors)})`;let o=c.message||"Error desconocido",a=$a[o];if(a)return typeof a==="function"?a({label:""}).trim():a;let t=c.error||c.code||c.type;return t?`${o} [${t}]`:o}function Ts(c){try{return JSON.parse(Buffer.from(c.split(".")[1],"base64").toString()).exp*1000<Date.now()}catch{return!0}}async function is(){let c=Y();if(!c?.refreshToken)return null;let o=`${U("auth")}/refresh-token`,t=await(await fetch(o,{method:"POST",headers:{"X-ORION-REFRESH":c.refreshToken}})).json();if(!t.token)return null;if(N()?.canPersistCredentials!==!1)co({...c,token:t.token});return t.token}async function oo(){let c=Y();if(!c?.token)return;if(!Ts(c.token))return c.token;return await is()??void 0}async function Gc(c="application/json"){let o=await oo(),a={"Content-Type":c,"X-ORION-DEVICEID":Ys(),"X-ORION-PLATFORM":"web"};if(o)a["x-orion-jwt"]=o;return a}async function R(c){let o=`${U(c.service)}/graphql`,a=await Gc(),t;try{t=await fetch(o,{method:"POST",headers:a,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 m=await t.json();if(m.errors?.length)throw Error(Us(m.errors[0]));if(!m.data)throw Error("No data returned from server");return m.data}function Ks(c){return c.replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,"")}function _s(c){return c.includes(".")||c.startsWith("http://")||c.startsWith("https://")}async function Mc(c){if(_s(c)){let o=Ks(c),a=await fetch(`${U("main")}/website-id/${o}`,{signal:AbortSignal.timeout(1e4)});if(!a.ok)throw Error(`No se encontro el sitio "${o}"`);let t=await a.json();if(!t.websiteId)throw Error(`No se pudo resolver el websiteId para "${o}"`);return{input:c,websiteId:t.websiteId,targetType:"domain"}}return{input:c,websiteId:c,targetType:"websiteId"}}async function qa(c){let o=await R({service:"main",query:`query ($websiteId: ID) {
5
5
  website(websiteId: $websiteId) {
6
6
  _id
7
7
  name
@@ -13,7 +13,7 @@ function bc(c){let a=[],o={},m={};for(let s=0;s<c.length;s++)if(c[s].startsWith(
13
13
  timezone
14
14
  defaultMenuId
15
15
  }
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
16
+ }`,variables:{websiteId:c}});if(!o.website)throw Error(`No se encontro el website "${c}"`);return o.website}function Es(){if(!Y())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 ja(c){if(Es(),!c)throw Error("Uso: team-cli admin <websiteId|domain> show");let o=await Mc(c),a=await qa(o.websiteId);return{context:o,website:a}}function ao(){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 jo=`
38
+ Uso: team-cli admin <websiteId|domain> coupons <accion> [opciones]`}var Qa=`
39
39
  availableAtPeriods
40
40
  closedDays
41
41
  closedUntilDate
@@ -51,7 +51,7 @@ Modulos:
51
51
  fromMinute
52
52
  toMinute
53
53
  }
54
- `,ma=`
54
+ `,to=`
55
55
  _id
56
56
  websiteId
57
57
  name
@@ -86,13 +86,13 @@ Modulos:
86
86
  requiredBINs
87
87
  extraRequirementsForPaymentTypes
88
88
  schedule {
89
- ${jo}
89
+ ${Qa}
90
90
  }
91
91
  scheduleAtUse {
92
- ${jo}
92
+ ${Qa}
93
93
  }
94
94
  codesCode
95
- `,Qo=`
95
+ `,Aa=`
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 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) {
104
+ `;function Xo(){if(!Y())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,o){let a=c[o];if(!a)throw Error(`--${o} es requerido.`);try{return JSON.parse(a)}catch{throw Error(`--${o} debe ser un JSON válido.`)}}function b(c,o){let a=c[o];if(!a)return;let t=Number.parseInt(a,10);if(Number.isNaN(t))throw Error(`--${o} debe ser un número entero.`);return t}function Ja(c,o){let a=c[o];if(!a)return;if(a==="true")return!0;if(a==="false")return!1;throw Error(`--${o} debe ser true o false.`)}async function d(c){if(Xo(),!c)throw Error("Debes indicar <websiteId|domain>.");return Mc(c)}async function f(c,o){let a=await R({service:"main",query:`query ($couponId: ID) {
105
105
  coupon(couponId: $couponId) {
106
106
  _id
107
107
  websiteId
108
108
  }
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) {
109
+ }`,variables:{couponId:c}});if(!a.coupon)throw Error(`No se encontró el cupón "${c}"`);if(a.coupon.websiteId!==o)throw Error(`El cupón "${c}" no pertenece al website seleccionado.`);return a.coupon}function us(c){if(!Array.isArray(c))throw Error("--input debe ser un arreglo JSON.");return c.map((o)=>{if(!o||typeof o!=="object"||typeof o.code!=="string")throw Error('Cada item de --input debe tener al menos { "code": "..." }.');if(o.userEmail!=null&&typeof o.userEmail!=="string")throw Error("userEmail debe ser string cuando viene informado.");return{code:o.code,userEmail:o.userEmail}})}function ks(c){if(!Array.isArray(c)||c.some((o)=>typeof o!=="string"))throw Error("--ids debe ser un arreglo JSON de strings.");return c}async function Ra(c,o,a){let t=await d(c);await f(o,t.websiteId);let m=b(a,"limit"),s=b(a,"page"),r=a.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
- ${Qo}
112
+ ${Aa}
113
113
  }
114
114
  totalCount
115
115
  totalPages
116
116
  hasNextPage
117
117
  hasPreviousPage
118
118
  }
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) {
119
+ }`,variables:{couponId:o,filter:r,limit:m,page:s}});return{context:t,couponId:o,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:s??1,limit:m??null}}}async function Pa(c,o,a){let t=await d(c);await f(o,t.websiteId);let m=us(Ic(a,"input")),s=m.some((w)=>w.userEmail),r=await R({service:"main",query:`mutation ($couponId: ID, $codesWithEmail: [CodeWithEmailInput], $useCodeWithEmail: Boolean) {
120
120
  createCouponCodes(couponId: $couponId, codesWithEmail: $codesWithEmail, useCodeWithEmail: $useCodeWithEmail)
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) {
121
+ }`,variables:{couponId:o,codesWithEmail:m,useCodeWithEmail:s}});return{context:t,couponId:o,requestedCount:m.length,result:r.createCouponCodes}}async function Wa(c,o,a){let t=await d(c);await f(o,t.websiteId);let m=b(a,"quantity");if(!m)throw Error("--quantity es requerido.");let s=await R({service:"main",query:`mutation ($couponId: ID, $couponQuantity: Float, $couponCodePrefix: String) {
122
122
  createRandomCouponCodes(couponId: $couponId, couponQuantity: $couponQuantity, couponCodePrefix: $couponCodePrefix)
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]) {
123
+ }`,variables:{couponId:o,couponQuantity:m,couponCodePrefix:a.prefix}});return{context:t,couponId:o,quantity:m,prefix:a.prefix??null,result:s.createRandomCouponCodes}}async function Ga(c,o,a){let t=await d(c);await f(o,t.websiteId);let m=ks(Ic(a,"ids")),s=await R({service:"main",query:`mutation ($couponId: ID, $couponCodesIds: [ID]) {
124
124
  deleteCouponCodes(couponId: $couponId, couponCodesIds: $couponCodesIds, globalCoupon: false)
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
125
+ }`,variables:{couponId:o,couponCodesIds:m}});return{context:t,couponId:o,deleted:s.deleteCouponCodes,couponCodesIds:m}}function Ma(){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 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}
148
+ couponId se valida contra el website seleccionado antes de ejecutar la mutation.`}var Ia={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 Ds(c){let o=Object.entries(c).filter(([,s])=>s!==void 0),a=o.map(([s])=>s).filter((s)=>!Ia[s]);if(a.length)throw Error(`Campos no soportados para create: ${a.join(", ")}`);let t=o.map(([s])=>`$${s}: ${Ia[s]}`).join(", "),m=o.map(([s])=>`${s}: $${s}`).join(", ");return`mutation (${t}) {
149
+ createCoupon(${m}) {
150
+ ${to}
151
151
  }
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) {
152
+ }`}async function Xa(c,o){let a=await d(c),t=b(o,"limit"),m=b(o,"page"),s=o.filter,r=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: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) {
172
+ }`,variables:{websiteId:a.websiteId,filter:s,limit:t,page:m}});return{context:a,coupons:r.coupons.items??[],pagination:{totalCount:r.coupons.totalCount??0,totalPages:r.coupons.totalPages??0,hasNextPage:Boolean(r.coupons.hasNextPage),hasPreviousPage:Boolean(r.coupons.hasPreviousPage),page:m??1,limit:t??null}}}async function Za(c,o){let a=await d(c);await f(o,a.websiteId);let t=await R({service:"main",query:`query ($couponId: ID) {
173
173
  coupon(couponId: $couponId) {
174
- ${ma}
174
+ ${to}
175
175
  }
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) {
176
+ }`,variables:{couponId:o}});return{context:a,coupon:t.coupon}}async function Ha(c,o){let a=await d(c),t=Ic(o,"input");if(t.websiteId&&t.websiteId!==a.websiteId)throw Error("El websiteId del input no coincide con el website seleccionado.");let m={...t,websiteId:a.websiteId},s=Ds(m),r=await R({service:"main",query:s,variables:m});return{context:a,coupon:r.createCoupon}}async function Fa(c,o,a){let t=await d(c);await f(o,t.websiteId);let m=Ic(a,"input"),s=await R({service:"main",query:`mutation ($couponId: ID, $coupon: UpdateCouponInput) {
177
177
  updateCoupon(couponId: $couponId, coupon: $coupon) {
178
- ${ma}
178
+ ${to}
179
179
  }
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]) {
180
+ }`,variables:{couponId:o,coupon:m}});return{context:t,coupon:s.updateCoupon}}async function Ya(c,o){let a=await d(c);await f(o,a.websiteId);let t=await R({service:"main",query:`mutation ($couponsIds: [ID]) {
181
181
  deleteCoupons(couponsIds: $couponsIds, globalCoupon: false)
182
- }`,variables:{couponsIds:[a]}});return{context:o,couponId:a,deleted:m.deleteCoupons}}function Vc(){return`team-cli admin coupons
182
+ }`,variables:{couponsIds:[o]}});return{context:a,couponId:o,deleted:t.deleteCoupons}}function kc(){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 Yo(){return`team-cli admin coupons create
230
+ El schema actual no expone update para coupon codes.`}function ha(){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 Fo(){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 Ua(){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 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) {
321
+ Primero mira el cupón actual con: team-cli admin <web> coupons show <couponId>`}async function Ta(c,o){Xo();let a=c[2]??o.filter;if(!a)throw Error("Debes indicar un término de búsqueda. Uso: team-cli admin search <texto>");let t=b(o,"limit"),m=b(o,"page"),s=Ja(o,"only-active"),r=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: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
337
+ }`,variables:{filter:a,limit:t,page:m,onlyActiveWebsites:s}});return{searchTerm:a,websites:r.websites.items??[],pagination:{totalCount:r.websites.totalCount??0,totalPages:r.websites.totalPages??0,hasNextPage:Boolean(r.websites.hasNextPage),hasPreviousPage:Boolean(r.websites.hasPreviousPage),page:m??1,limit:t??null}}}function ia(){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 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) {
357
+ team-cli admin search pizza --only-active true`}function Vs(){if(!Y())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 ys(c){let o=[c.address?.streetAddress,c.address?.extendedAddress,c.address?.locality].filter(Boolean);if(!o.length)return null;return o.join(", ")}async function Ka(c){if(Vs(),!c)throw Error("Uso: team-cli admin <websiteId|domain> stores list");let o=await Mc(c),t=((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: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!) {
369
+ }`,variables:{websiteId:o.websiteId}})).stores.items??[]).map((m)=>({_id:m._id,name:m.name,address:ys(m)})).sort((m,s)=>m.name.localeCompare(s.name,"es",{sensitivity:"base"}));return{context:o,stores:t,totalCount:t.length}}import{createInterface as zs}from"node:readline";function Xc(c){if(process.env.JUSTO_TEAM_CLI_INTERACTIVE==="false")throw Error("Este entorno no soporta prompts interactivos.");if(N()?.interactive===!1)throw Error("Este entorno no soporta prompts interactivos.");let o=zs({input:process.stdin,output:process.stderr});return new Promise((a)=>{o.question(c,(t)=>{o.close(),a(t.trim())})})}async function _a(c){return(await R({service:"auth",query:`mutation ($email: String!) {
370
370
  requestLoginCode(email: $email)
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!) {
371
+ }`,variables:{email:c}})).requestLoginCode}async function Ea(c,o,a){let t=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: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
376
+ }`,variables:{email:c,token:o,code:a.toUpperCase()}});co({email:c,token:t.loginWithCode.token,refreshToken:t.loginWithCode.refreshToken}),await Ss()}async function Ss(){if(!(await R({service:"main",query:"query { me { roles } }"})).me?.roles?.length)throw Io(),Error("Solo miembros del equipo Justo pueden usar esta herramienta.")}async function ua(){let c=await Xc("Email: ");k(`Enviando codigo de verificacion...
377
+ `);let o=await _a(c);k(`Codigo enviado a tu email.
378
+ `);let a=await Xc("Codigo: ");return await Ea(c,o,a),{ok:!0,authenticated:!0,email:c}}async function ka(c){let o=ic(c,"email"),a=ic(c,"token"),t=ic(c,"code");return await Ea(o,a,t),{ok:!0,authenticated:!0,email:o}}async function Da(c){let o=ic(c,"email");k(`Enviando codigo de verificacion...
379
+ `);let a=await _a(o);return{ok:!0,email:o,token:a,nextCommand:`npx @getjusto/team-cli auth login-with-token --email ${o} --token ${a} --code <CODIGO>`}}async function Va(){return Io(),{ok:!0,authenticated:!1}}async function ya(){let c=Y();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 Zo(){return`team-cli auth
380
380
 
381
381
  Gestion de sesion.
382
382
 
@@ -402,8 +402,8 @@ 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{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) {
405
+ Uso: team-cli auth login-with-token --email <email> --token <token> --code <codigo>`}import{writeFileSync as fs}from"node:fs";import{mkdtempSync as es,readFileSync as Ns,rmSync as ds,writeFileSync as Ls}from"node:fs";import{tmpdir as Os}from"node:os";import{join as za}from"node:path";import{spawnSync as bs}from"node:child_process";function Bs(c){return`'${c.replaceAll("'",`'"'"'`)}'`}function Sa(c,o){if(c==null)return;if(!Array.isArray(c)||c.some((a)=>typeof a!=="string"))throw Error(`${o} debe ser un arreglo de strings.`);return c}function vs(c){if(!Array.isArray(c))throw Error("variables debe ser un arreglo.");return c.map((o,a)=>{if(!o||typeof o!=="object"||Array.isArray(o))throw Error(`variables[${a}] debe ser un objeto.`);let t=o;if(typeof t.key!=="string"||!t.key)throw Error(`variables[${a}].key debe ser un string no vacío.`);if(typeof t.fieldType!=="string"||!t.fieldType)throw Error(`variables[${a}].fieldType debe ser un string no vacío.`);if(t.fieldParams!=null&&typeof t.fieldParams!=="string")throw Error(`variables[${a}].fieldParams debe ser un string.`);return{key:t.key,fieldType:t.fieldType,fieldParams:typeof t.fieldParams==="string"?t.fieldParams:void 0}})}function xs(c){if(!c||typeof c!=="object"||Array.isArray(c))throw Error("El archivo editado debe contener un objeto JSON.");let o=c;if(typeof o.name!=="string"||!o.name.trim())throw Error("name debe ser un string no vacío.");if(o.description!=null&&typeof o.description!=="string")throw Error("description debe ser un string.");if(typeof o.collection!=="string"||!o.collection.trim())throw Error("collection debe ser un string no vacío.");if(typeof o.pipeline!=="string")throw Error("pipeline debe ser un string.");return{name:o.name.trim(),description:o.description?.trim()||void 0,collection:o.collection.trim(),allowedUsersIds:Sa(o.allowedUsersIds,"allowedUsersIds")??[],tags:Sa(o.tags,"tags")??[],pipeline:o.pipeline,variables:vs(o.variables)}}function ea(c){let o=process.env.VISUAL||process.env.EDITOR||"vi",a=es(za(Os(),"team-cli-query-")),t=za(a,"aggregation-query.json");Ls(t,`${JSON.stringify(c,null,2)}
406
+ `);let m=`${o} ${Bs(t)}`,s=bs(m,{shell:!0,stdio:"inherit"});if(s.error)throw Error(`No se pudo abrir el editor "${o}": ${s.error.message}`);if(s.status!==0)throw Error(`El editor terminó con código ${s.status}.`);try{let r=Ns(t,"utf-8");if(!r.trim())throw Error("El archivo quedó vacío.");let w;try{w=JSON.parse(r)}catch{throw Error("El archivo editado no contiene JSON válido.")}return xs(w)}finally{ds(a,{recursive:!0,force:!0})}}function z(){if(!Y())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,o){let a=c[3];if(!a)throw Error(`Uso: ${o}`);return a}function Zc(c){if(!c.params)return{};try{return JSON.parse(c.params)}catch{throw Error("--params debe ser un JSON válido.")}}function Ho(c){let o=c.limit;if(!o)throw Error("--limit es requerido. Ejemplo: --limit 1000");let a=Number(o);if(!Number.isInteger(a)||a<=0)throw Error("--limit debe ser un entero positivo.");return a}function Na(c){let o=c.emails;if(!o)throw Error("--emails es requerido. Ejemplo: --emails ana@justo.com,bob@justo.com");let a=o.split(",").map((m)=>m.trim().toLowerCase()).filter(Boolean);if(!a.length)throw Error("--emails debe contener al menos un email.");let t=a.find((m)=>!m.includes("@"));if(t)throw Error(`Email inválido: ${t}`);return[...new Set(a)]}function Fo(c){if(typeof c!=="string")return c;try{return JSON.parse(c)}catch{return{value:c}}}async function Hc(c){return(await R({service:"data",query:`query ($aggregationQueryId: String) {
407
407
  aggregationQuery(aggregationQueryId: $aggregationQueryId) {
408
408
  _id
409
409
  name
@@ -419,7 +419,7 @@ Subcomandos:
419
419
  fieldParams
420
420
  }
421
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) {
422
+ }`,variables:{aggregationQueryId:c}})).aggregationQuery}async function da(c){return await Promise.all(c.map(async(a)=>{let m=(await R({service:"main",query:`query ($filter: String, $limit: BigInt) {
423
423
  justoUsers(filter: $filter, limit: $limit) {
424
424
  items {
425
425
  _id
@@ -427,11 +427,11 @@ Subcomandos:
427
427
  fullName
428
428
  }
429
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) {
430
+ }`,variables:{filter:a,limit:10}})).justoUsers?.items?.find((s)=>s.email?.toLowerCase()===a);if(!m?._id)throw Error(`No encontramos un usuario de Justo para ${a}`);return m}))}function La(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 Yo(c,o){let a=await R({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
431
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]) {
432
+ }`,variables:{aggregationQueryId:c,params:o}});return Fo(a.testAggregationQuery)}async function Oa(c){let o=await fetch(`${U("data")}/execute-pipeline`,{method:"POST",headers:await Gc(),body:JSON.stringify({collection:c.collection,pipeline:c.pipeline,params:c.queryParams,limit:c.limit}),signal:AbortSignal.timeout(75000)});if(!o.ok){let a=await o.text();throw Error(ba(a)||"No se pudo ejecutar el pipeline.")}return await o.json()}function ba(c){try{return JSON.parse(c).error||c}catch{return c}}async function Ba(c,o,a){let t=await fetch(`${U("data")}/aggregation-queries/${c}/run`,{method:"POST",headers:await Gc(),body:JSON.stringify({params:o,limit:a}),signal:AbortSignal.timeout(315000)});if(!t.ok){let l=await t.text();throw Error(ba(l)||"No se pudo ejecutar el query.")}if(!t.body)throw Error("El servidor no devolvió un stream de datos.");let m=t.body.getReader(),s=new TextDecoder,r="",w=0;while(!0){let{done:l,value:g}=await m.read();if(l)break;let j=s.decode(g,{stream:!0});process.stdout.write(j),r+=j;let J=r.indexOf(`
433
+ `);while(J>=0){if(r.slice(0,J).trim())w++;r=r.slice(J+1),J=r.indexOf(`
434
+ `)}}let n=s.decode();if(n)process.stdout.write(n),r+=n;if(r.trim())w++;return{ok:!0,queryId:c,limit:a,rows:w}}async function ho(c,o){await Uo(c,{name:o.name,description:o.description,collection:o.collection,allowedUsersIds:o.allowedUsersIds,tags:o.tags}),await R({service:"data",query:`mutation ($aggregationQueryId: String, $pipeline: String, $variables: [AggregationQueryVariableInput]) {
435
435
  addAggregationQueryVersion(
436
436
  aggregationQueryId: $aggregationQueryId
437
437
  pipeline: $pipeline
@@ -440,7 +440,7 @@ Subcomandos:
440
440
  _id
441
441
  currentVersionIndex
442
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) {
443
+ }`,variables:{aggregationQueryId:c,pipeline:o.pipeline,variables:o.variables}})}async function Uo(c,o){await R({service:"data",query:`mutation ($aggregationQueryId: String, $aggregationQuery: UpdateAggregationQueryInput) {
444
444
  updateAggregationQuery(
445
445
  aggregationQueryId: $aggregationQueryId
446
446
  aggregationQuery: $aggregationQuery
@@ -453,7 +453,7 @@ Subcomandos:
453
453
  tags
454
454
  currentVersionIndex
455
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 {
456
+ }`,variables:{aggregationQueryId:c,aggregationQuery:{name:o.name,description:o.description,collection:o.collection,allowedUsersIds:o.allowedUsersIds,tags:o.tags}}})}async function va(){return(await R({service:"data",query:`mutation {
457
457
  createAggregationQuery {
458
458
  _id
459
459
  name
@@ -469,7 +469,7 @@ Subcomandos:
469
469
  fieldParams
470
470
  }
471
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(
472
+ }`})).createAggregationQuery}function cr(c){if(!Array.isArray(c))throw Error("El preview del query debe devolver un arreglo para usar AI edit.");return c}async function or(c){let o=await R({service:"messenger",query:`mutation generateAdminQuery(
473
473
  $prompt: String
474
474
  $name: String
475
475
  $description: String
@@ -495,17 +495,17 @@ Subcomandos:
495
495
  aggregationDescription
496
496
  aggregationName
497
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) {
498
+ }`,variables:c});if(!o.generateAdminQuery?.pipeline||!o.generateAdminQuery.fullCollectionName)throw Error("La IA no devolvió una versión válida del query.");return o.generateAdminQuery}async function ar(c){let o=await R({service:"messenger",timeoutMs:120000,query:`mutation explainAdminQuery($prompt: String) {
499
499
  explainAdminQuery(prompt: $prompt) {
500
500
  responseText
501
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) {
502
+ }`,variables:{prompt:c}});if(!o.explainAdminQuery?.responseText)throw Error("La IA no devolvió una explicación válida.");return o.explainAdminQuery}async function xa(){return z(),await va()}async function fa(c){z();let o=c.prompt||await Xc("Explica qué query quieres investigar o construir: ");if(!o)throw Error("Debes indicar un prompt para explain.");return(await ar(o)).responseText}async function ct(c){if(z(),!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 o=c.limit?Ho(c):void 0;return await Oa({collection:c.collection,pipeline:c.pipeline,queryParams:Zc(c),limit:o})}async function ot(c){z();let o=cc(c,"team-cli data queries edit <queryId>"),a=await Hc(o),t=ea(La(a));return await ho(o,t),{ok:!0,queryId:o,name:t.name,collection:t.collection}}async function at(c,o){z();let a=cc(c,"team-cli data queries ai-edit <queryId> --prompt '<texto>' [--params '<json>']"),t=await Hc(a),m=o.prompt||await Xc("Describe los cambios para la IA: ");if(!m)throw Error("Debes indicar un prompt para AI edit.");let s=Zc(o),r;if(o.params){k(`Obteniendo preview del query actual...
503
+ `);try{let n=await Yo(a,s);r=cr(n)}catch(n){let l=n instanceof Error?n.message:String(n);throw Error(`No se pudo obtener el preview para AI edit: ${l}`)}}k(`Generando propuesta con IA...
504
+ `);let w=await or({prompt:m,fullCollectionName:t.collection,pipeline:t.pipeline,preview:r,description:t.description,name:t.name,variables:t.variables});return await ho(a,{name:t.name==="Nuevo query"?w.aggregationName||t.name:t.name,description:t.description||w.aggregationDescription,collection:w.fullCollectionName,allowedUsersIds:t.allowedUsersIds??[],tags:t.tags??[],pipeline:w.pipeline,variables:w.variables??[]}),{ok:!0,queryId:a,responseText:w.responseText,collection:w.fullCollectionName,name:w.aggregationName,description:w.aggregationDescription}}async function tt(c){z();let o=cc(c,"team-cli data queries view <queryId>");return await Hc(o)}async function mt(c){z();let o=cc(c,"team-cli data queries view-pipeline <queryId>"),a=await Hc(o);return{queryId:o,pipeline:a.pipeline}}async function st(c,o){z();let a=cc(c,"team-cli data queries preview <queryId> --params '<json>'"),t=Zc(o),m=await Yo(a,t);return Fo(m)}async function rt(c,o){z();let a=cc(c,"team-cli data queries run <queryId> --limit <n> --params '<json>'"),t=Zc(o),m=Ho(o);return await Ba(a,t,m),{__streamHandled:!0}}async function pt(c,o){z();let a=cc(c,"team-cli data queries add-viewers <queryId> --emails 'ana@justo.com,bob@justo.com'"),t=Na(o),m=await Hc(a),s=await da(t),r=[...new Set([...m.allowedUsersIds??[],...s.map((w)=>w._id)])];return await Uo(a,{name:m.name,description:m.description,collection:m.collection,allowedUsersIds:r,tags:m.tags??[]}),{ok:!0,queryId:a,addedViewers:s.map((w)=>({_id:w._id,email:w.email,fullName:w.fullName})),allowedUsersIds:r}}function tr(c){return new Promise((o)=>setTimeout(o,c))}async function wt(c,o){z();let a=cc(c,"team-cli data queries download <queryId> --params '<json>'"),t=Zc(o);if(!o.path)throw Error("--path es requerido. Ejemplo: --path resultado.xlsx");k(`Iniciando descarga...
505
+ `);let s=(await R({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
506
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) {
507
+ }`,variables:{aggregationQueryId:a,params:t}})).downloadAggregationQueryData;k(`Reporte en proceso (${s})...
508
+ `);let r=null;while(!r){await tr(1000);let l=await R({service:"data",query:`query ($id: String) {
509
509
  getAsyncReport(id: $id) {
510
510
  _id
511
511
  status
@@ -513,9 +513,9 @@ Subcomandos:
513
513
  fileUrl
514
514
  }
515
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(`
516
+ }`,variables:{id:s}}),g=l.getAsyncReport,j=l.getAsyncReportRecordsCount;if(g.status==="error")throw Error("El reporte falló al generarse.");if(g.fileUrl)r=g.fileUrl;else{let J=g.estimatedRecordsCount?` (~${g.estimatedRecordsCount} registros)`:"",F=j!=null?` ${j} procesados`:"";k(`\rGenerando...${J}${F}`)}}k(`
517
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
518
+ `);let w=await fetch(r);if(!w.ok)throw Error(`Error descargando archivo: ${w.status}`);let n=Buffer.from(await w.arrayBuffer());return fs(o.path,n),{ok:!0,queryId:a,asyncReportId:s,outputPath:o.path,fileUrl:r}}function To(){return`team-cli data
519
519
 
520
520
  Comandos de datos y reportes.
521
521
 
@@ -615,7 +615,119 @@ Ejemplos:
615
615
  team-cli data queries preview abc123 --params '{"startDate": "2026-01-01"}'
616
616
  team-cli data queries run abc123 --limit 1000 --params '{"startDate": "2026-01-01"}'
617
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=`
618
+ team-cli data queries add-viewers abc123 --emails 'ana@justo.com,bob@justo.com'`}function nt(c,o){let a=o;while(a<c.length){let t=c[a];if(/\s/.test(t)){a+=1;continue}if(t==="#"){let m=c.indexOf(`
619
+ `,a);if(m===-1)return c.length;a=m+1;continue}return a}return a}function gt(c,o){let a=/^[_A-Za-z][_0-9A-Za-z]*/.exec(c.slice(o));if(!a)return null;return{name:a[0],end:o+a[0].length}}function lt(c){let o=c.replace(/^\uFEFF/,""),a=nt(o,0);if(a>=o.length)return{type:"unknown"};if(o[a]==="{")return{type:"query"};let t=gt(o,a);if(!t)return{type:"unknown"};if(!["query","mutation","subscription"].includes(t.name))return{type:"unknown"};a=nt(o,t.end);let s=gt(o,a)?.name;return{type:t.name,name:s}}import{spawnSync as $t}from"node:child_process";import{stdin as mr,stdout as Ct}from"node:process";import{createInterface as sr}from"node:readline/promises";function rr(c){if(!c)return"{}";return JSON.stringify(c,null,2)}function pr(c,o){if(c.length<=o)return c;return`${c.slice(0,o)}
620
+
621
+ [Contenido truncado en esta ventana]`}function qt(c){return["Esta operación puede modificar datos.","",`Servicio: ${c.service}`,`Ambiente: ${c.environment}`,`Operación: ${c.operationName??"mutation"}`,`Endpoint: ${c.endpoint}`].join(`
622
+ `)}function io(c){return["Query:",c.query,"","Variables:",rr(c.variables)].join(`
623
+ `)}function wr(c){let o=pr(`${qt(c)}
624
+
625
+ ${io(c)}`,7000),a=`
626
+ on run argv
627
+ set dialogMessage to item 1 of argv
628
+ display dialog dialogMessage buttons {"Cancelar", "Ejecutar"} default button "Cancelar" cancel button "Cancelar" with title "Confirmar mutation GraphQL" with icon caution
629
+ return button returned of result
630
+ end run
631
+ `,t=$t("osascript",["-e",`
632
+ on run argv
633
+ set dialogMessage to item 1 of argv
634
+ display dialog dialogMessage buttons {"Cancelar", "Ejecutar"} default button "Cancelar" cancel button "Cancelar" with title "Confirmar mutation GraphQL" with icon caution
635
+ return button returned of result
636
+ end run
637
+ `,o],{encoding:"utf8"});if(t.error)return null;return t.status===0&&t.stdout.trim()==="Ejecutar"}function nr(c){let a={service:c.service,environment:c.environment,operationName:c.operationName??"mutation",endpoint:c.endpoint,details:io(c)},t=$t("powershell.exe",["-STA","-NoProfile","-Command",`
638
+ Add-Type -AssemblyName System.Windows.Forms
639
+ Add-Type -AssemblyName System.Drawing
640
+
641
+ $payload = [Console]::In.ReadToEnd() | ConvertFrom-Json
642
+ $form = New-Object System.Windows.Forms.Form
643
+ $form.Text = "Confirmar mutation GraphQL"
644
+ $form.StartPosition = "CenterScreen"
645
+ $form.Size = New-Object System.Drawing.Size(840, 620)
646
+ $form.MinimumSize = New-Object System.Drawing.Size(720, 520)
647
+
648
+ $title = New-Object System.Windows.Forms.Label
649
+ $title.Text = "Confirmar mutation GraphQL"
650
+ $title.Font = New-Object System.Drawing.Font("Segoe UI", 15, [System.Drawing.FontStyle]::Bold)
651
+ $title.AutoSize = $true
652
+ $title.Location = New-Object System.Drawing.Point(18, 16)
653
+ $form.Controls.Add($title)
654
+
655
+ $subtitle = New-Object System.Windows.Forms.Label
656
+ $subtitle.Text = "Esta operación puede modificar datos. Revisa lo que se va a ejecutar."
657
+ $subtitle.AutoSize = $true
658
+ $subtitle.Location = New-Object System.Drawing.Point(20, 50)
659
+ $form.Controls.Add($subtitle)
660
+
661
+ $summary = New-Object System.Windows.Forms.TableLayoutPanel
662
+ $summary.ColumnCount = 4
663
+ $summary.RowCount = 2
664
+ $summary.Location = New-Object System.Drawing.Point(20, 82)
665
+ $summary.Size = New-Object System.Drawing.Size(780, 72)
666
+ $summary.CellBorderStyle = "Single"
667
+ $summary.Anchor = "Top, Left, Right"
668
+ $form.Controls.Add($summary)
669
+
670
+ $labels = @("Servicio", "Ambiente", "Operación", "Endpoint")
671
+ $values = @($payload.service, $payload.environment, $payload.operationName, $payload.endpoint)
672
+ for ($i = 0; $i -lt 4; $i++) {
673
+ $label = New-Object System.Windows.Forms.Label
674
+ $label.Text = $labels[$i]
675
+ $label.Font = New-Object System.Drawing.Font("Segoe UI", 8, [System.Drawing.FontStyle]::Bold)
676
+ $label.ForeColor = [System.Drawing.Color]::SlateGray
677
+ $label.Dock = "Fill"
678
+ $summary.Controls.Add($label, $i, 0)
679
+
680
+ $value = New-Object System.Windows.Forms.Label
681
+ $value.Text = $values[$i]
682
+ $value.AutoEllipsis = $true
683
+ $value.Dock = "Fill"
684
+ $summary.Controls.Add($value, $i, 1)
685
+ }
686
+
687
+ $detailsLabel = New-Object System.Windows.Forms.Label
688
+ $detailsLabel.Text = "Query y variables"
689
+ $detailsLabel.Font = New-Object System.Drawing.Font("Segoe UI", 9, [System.Drawing.FontStyle]::Bold)
690
+ $detailsLabel.AutoSize = $true
691
+ $detailsLabel.Location = New-Object System.Drawing.Point(20, 172)
692
+ $form.Controls.Add($detailsLabel)
693
+
694
+ $textBox = New-Object System.Windows.Forms.TextBox
695
+ $textBox.Multiline = $true
696
+ $textBox.ReadOnly = $true
697
+ $textBox.ScrollBars = "Both"
698
+ $textBox.WordWrap = $false
699
+ $textBox.Font = New-Object System.Drawing.Font("Consolas", 10)
700
+ $textBox.Text = $payload.details
701
+ $textBox.Location = New-Object System.Drawing.Point(20, 196)
702
+ $textBox.Size = New-Object System.Drawing.Size(780, 310)
703
+ $textBox.Anchor = "Top, Bottom, Left, Right"
704
+ $form.Controls.Add($textBox)
705
+
706
+ $executeButton = New-Object System.Windows.Forms.Button
707
+ $executeButton.Text = "Ejecutar"
708
+ $executeButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
709
+ $executeButton.Size = New-Object System.Drawing.Size(104, 34)
710
+ $executeButton.Location = New-Object System.Drawing.Point(696, 526)
711
+ $executeButton.Anchor = "Bottom, Right"
712
+ $form.Controls.Add($executeButton)
713
+
714
+ $cancelButton = New-Object System.Windows.Forms.Button
715
+ $cancelButton.Text = "Cancelar"
716
+ $cancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
717
+ $cancelButton.Size = New-Object System.Drawing.Size(104, 34)
718
+ $cancelButton.Location = New-Object System.Drawing.Point(580, 526)
719
+ $cancelButton.Anchor = "Bottom, Right"
720
+ $form.Controls.Add($cancelButton)
721
+
722
+ $form.CancelButton = $cancelButton
723
+ $result = $form.ShowDialog()
724
+ if ($result -eq [System.Windows.Forms.DialogResult]::OK) { exit 0 }
725
+ exit 2
726
+ `],{input:JSON.stringify(a),encoding:"utf8"});if(t.error)return null;if(t.status===0)return!0;if(t.status===2)return!1;return null}async function gr(c){if(!process.stdin.isTTY||!process.stdout.isTTY)return null;Ct.write(`${qt(c)}
727
+
728
+ ${io(c)}
729
+
730
+ `);let o=sr({input:mr,output:Ct});try{return(await o.question('Ejecutar mutation? Escribe "si" para confirmar: ')).trim().toLowerCase()==="si"}finally{o.close()}}async function jt(c){let o={...c,environment:Wc(),endpoint:`${U(c.service)}/graphql`},a=null;if(process.platform==="darwin")a=wr(o);if(process.platform==="win32")a=nr(o);if(a===null)a=await gr(o);if(a===null)throw Error("No se pudo abrir una confirmación para ejecutar el mutation.");if(!a)throw Error("Mutation rechazada por el usuario. No se ejecutó ninguna llamada.")}var Qt=["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"],At=`
619
731
  query ResolverInfo($name: ID!, $mutation: Boolean!) {
620
732
  params(name: $name, mutation: $mutation) {
621
733
  name
@@ -624,8 +736,8 @@ Ejemplos:
624
736
  basicResultQuery
625
737
  }
626
738
  }
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
739
+ `;function lr(c){if(!c)throw Error("Uso: team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]");if(!Qt.includes(c))throw Error(`Servicio "${c}" no válido. Servicios disponibles: ${Qt.join(", ")}`)}async function Cr(c,o){let a;try{let t=await R({service:c,query:At,variables:{name:o,mutation:!1}});return{service:c,operationName:o,operationType:"query",info:t.params}}catch(t){a=t}try{let t=await R({service:c,query:At,variables:{name:o,mutation:!0}});return{service:c,operationName:o,operationType:"mutation",info:t.params}}catch(t){let m=a instanceof Error?a.message:"",s=t instanceof Error?t.message:"";if(m.includes('Cannot query field "params"')||s.includes('Cannot query field "params"'))throw Error(`El servicio "${c}" no expone metadata de resolvers por GraphQL.`);throw a instanceof Error?a:t}}async function Jt(c,o){let a=c[1],t=c[2],m=c[2];if(!Y())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(lr(a),t==="info"){let n=c[3];if(!n)throw Error("Uso: team-cli graphql <servicio> info <queryName|mutationName> [--format toon|json]");return await Cr(a,n)}if(!m)throw Error("Uso: team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]");let s;if(o.variables)try{s=JSON.parse(o.variables)}catch{throw Error("Las variables deben ser un JSON válido.")}let r=lt(m);if(r.type==="mutation")await jt({service:a,query:m,variables:s,operationName:r.name});return await R({service:a,query:m,variables:s})}function Rt(){return Object.keys(xc)}function $r(){return Rt().map((c)=>{let o=xc[c].prod;return`- \`${c}\`: \`${o}/graphql\``}).join(`
740
+ `)}function Pt(){let o=Rt().join(", "),a=$r();return`team-cli graphql
629
741
 
630
742
  Ejecutar queries y mutations GraphQL.
631
743
 
@@ -643,7 +755,7 @@ Formato:
643
755
 
644
756
 
645
757
 
646
- Servicios disponibles: ${a}.
758
+ Servicios disponibles: ${o}.
647
759
 
648
760
  Ejemplos:
649
761
  \`\`\`bash
@@ -676,13 +788,13 @@ npx @getjusto/team-cli graphql auth info requestLoginCode --format json
676
788
 
677
789
  Usa esto para mapear una URL GraphQL al valor correcto de \`team-cli graphql <service>\`.
678
790
 
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'
791
+ ${a}`}import{existsSync as mw,mkdirSync as sw,readdirSync as rw}from"node:fs";import{resolve as im}from"node:path";import{randomBytes as qr}from"crypto";var jr=(()=>{let c=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag).get;return(o)=>c.call(o)})();function Kt(c){return jr(c)==="Uint8Array"}function Qr(c){return typeof c==="object"&&c!=null&&Symbol.toStringTag in c&&(c[Symbol.toStringTag]==="ArrayBuffer"||c[Symbol.toStringTag]==="SharedArrayBuffer")}function Ar(c){return c instanceof RegExp||Object.prototype.toString.call(c)==="[object RegExp]"}function _t(c){return typeof c==="object"&&c!=null&&Symbol.toStringTag in c&&c[Symbol.toStringTag]==="Map"}function Jr(c){return c instanceof Date||Object.prototype.toString.call(c)==="[object Date]"}function V(c,o){return JSON.stringify(c,(a,t)=>{if(typeof t==="bigint")return{$numberLong:`${t}`};else if(_t(t))return Object.fromEntries(t);return t})}function Rr(c){if(c!=null&&typeof c==="object"&&"stylize"in c&&typeof c.stylize==="function")return c.stylize}var Vo=6,Et=Symbol.for("@@mdb.bson.version"),yo=2147483647,zo=-2147483648,ut=Math.pow(2,63)-1,kt=-Math.pow(2,63),Pr=Math.pow(2,53),Wr=-Math.pow(2,53);var Dt=4,en=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 C extends Error{get bsonError(){return!0}get name(){return"BSONError"}constructor(c,o){super(c,o)}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 Vt extends C{get name(){return"BSONVersionError"}constructor(){super(`Unsupported BSON version, bson types must be from bson ${Vo}.x.x`)}}class Do extends C{get name(){return"BSONRuntimeError"}constructor(c){super(c)}}class oc extends C{get name(){return"BSONOffsetError"}constructor(c,o,a){super(`${c}. offset: ${o}`,a);this.offset=o}}var Wt,Gt;function yt(c,o,a,t){if(t){Wt??=new TextDecoder("utf8",{fatal:!0});try{return Wt.decode(c.subarray(o,a))}catch(m){throw new C("Invalid UTF-8 string in BSON document",{cause:m})}}return Gt??=new TextDecoder("utf8",{fatal:!1}),Gt.decode(c.subarray(o,a))}function zt(c,o,a){if(c.length===0)return"";let t=a-o;if(t===0)return"";if(t>20)return null;if(t===1&&c[o]<128)return String.fromCharCode(c[o]);if(t===2&&c[o]<128&&c[o+1]<128)return String.fromCharCode(c[o])+String.fromCharCode(c[o+1]);if(t===3&&c[o]<128&&c[o+1]<128&&c[o+2]<128)return String.fromCharCode(c[o])+String.fromCharCode(c[o+1])+String.fromCharCode(c[o+2]);let m=[];for(let s=o;s<a;s++){let r=c[s];if(r>127)return null;m.push(r)}return String.fromCharCode(...m)}function Gr(c,o,a){if(o.length===0)return 0;if(o.length>25)return null;if(c.length-a<o.length)return null;for(let t=0,m=a;t<o.length;t++,m++){let s=o.charCodeAt(t);if(s>127)return null;c[m]=s}return o.length}var nc={toLocalBufferType(c){if(Buffer.isBuffer(c))return c;if(ArrayBuffer.isView(c))return Buffer.from(c.buffer,c.byteOffset,c.byteLength);let o=c?.[Symbol.toStringTag]??Object.prototype.toString.call(c);if(o==="ArrayBuffer"||o==="SharedArrayBuffer"||o==="[object ArrayBuffer]"||o==="[object SharedArrayBuffer]")return Buffer.from(c);throw new C("Cannot create Buffer from the passed potentialBuffer.")},allocate(c){return Buffer.alloc(c)},allocateUnsafe(c){return Buffer.allocUnsafe(c)},equals(c,o){return nc.toLocalBufferType(c).equals(o)},fromNumberArray(c){return Buffer.from(c)},fromBase64(c){return Buffer.from(c,"base64")},toBase64(c){return nc.toLocalBufferType(c).toString("base64")},fromISO88591(c){return Buffer.from(c,"binary")},toISO88591(c){return nc.toLocalBufferType(c).toString("binary")},fromHex(c){return Buffer.from(c,"hex")},toHex(c){return nc.toLocalBufferType(c).toString("hex")},toUTF8(c,o,a,t){let m=a-o<=20?zt(c,o,a):null;if(m!=null)return m;let s=nc.toLocalBufferType(c).toString("utf8",o,a);if(t){for(let r=0;r<s.length;r++)if(s.charCodeAt(r)===65533){yt(c,o,a,!0);break}}return s},utf8ByteLength(c){return Buffer.byteLength(c,"utf8")},encodeUTF8Into(c,o,a){let t=Gr(c,o,a);if(t!=null)return t;return nc.toLocalBufferType(c).write(o,a,void 0,"utf8")},randomBytes:qr,swap32(c){return nc.toLocalBufferType(c).swap32()}};function Mr(){let{navigator:c}=globalThis;return typeof c==="object"&&c.product==="ReactNative"}function Ir(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 Xr=(()=>{let{crypto:c}=globalThis;if(c!=null&&typeof c.getRandomValues==="function")return(o)=>{return c.getRandomValues(yc.allocate(o))};else{if(Mr()){let{console:o}=globalThis;o?.warn?.("BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.")}return Ir}})(),Mt=/(\d|[a-f])/i,yc={toLocalBufferType(c){let o=c?.[Symbol.toStringTag]??Object.prototype.toString.call(c);if(o==="Uint8Array")return c;if(ArrayBuffer.isView(c))return new Uint8Array(c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength));if(o==="ArrayBuffer"||o==="SharedArrayBuffer"||o==="[object ArrayBuffer]"||o==="[object SharedArrayBuffer]")return new Uint8Array(c);throw new C("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,o){if(c.byteLength!==o.byteLength)return!1;for(let a=0;a<c.byteLength;a++)if(c[a]!==o[a])return!1;return!0},fromNumberArray(c){return Uint8Array.from(c)},fromBase64(c){return Uint8Array.from(atob(c),(o)=>o.charCodeAt(0))},toBase64(c){return btoa(yc.toISO88591(c))},fromISO88591(c){return Uint8Array.from(c,(o)=>o.charCodeAt(0)&255)},toISO88591(c){return Array.from(Uint16Array.from(c),(o)=>String.fromCharCode(o)).join("")},fromHex(c){let o=c.length%2===0?c:c.slice(0,c.length-1),a=[];for(let t=0;t<o.length;t+=2){let m=o[t],s=o[t+1];if(!Mt.test(m))break;if(!Mt.test(s))break;let r=Number.parseInt(`${m}${s}`,16);a.push(r)}return Uint8Array.from(a)},toHex(c){return Array.from(c,(o)=>o.toString(16).padStart(2,"0")).join("")},toUTF8(c,o,a,t){let m=a-o<=20?zt(c,o,a):null;if(m!=null)return m;return yt(c,o,a,t)},utf8ByteLength(c){return new TextEncoder().encode(c).byteLength},encodeUTF8Into(c,o,a){let t=new TextEncoder().encode(o);return c.set(t,a),t.byteLength},randomBytes:Xr,swap32(c){if(c.length%4!==0)throw RangeError("Buffer size must be a multiple of 32-bits");for(let o=0;o<c.length;o+=4){let a=c[o],t=c[o+1],m=c[o+2],s=c[o+3];c[o]=s,c[o+1]=m,c[o+2]=t,c[o+3]=a}return c}},Zr=typeof Buffer==="function"&&Buffer.prototype?._isBuffer!==!0,q=Zr?nc:yc;class y{get[Et](){return Vo}[Symbol.for("nodejs.util.inspect.custom")](c,o,a){return this.inspect(c,o,a)}}var Yc=new Float64Array(1),W=new Uint8Array(Yc.buffer,0,8);Yc[0]=-1;var Ko=W[7]===0,qc={isBigEndian:Ko,getNonnegativeInt32LE(c,o){if(c[o+3]>127)throw RangeError(`Size cannot be negative at offset: ${o}`);return c[o]|c[o+1]<<8|c[o+2]<<16|c[o+3]<<24},getInt32LE(c,o){return c[o]|c[o+1]<<8|c[o+2]<<16|c[o+3]<<24},getUint32LE(c,o){return c[o]+c[o+1]*256+c[o+2]*65536+c[o+3]*16777216},getUint32BE(c,o){return c[o+3]+c[o+2]*256+c[o+1]*65536+c[o]*16777216},getBigInt64LE(c,o){let a=BigInt(c[o+4]+c[o+5]*256+c[o+6]*65536+(c[o+7]<<24)),t=BigInt(c[o]+c[o+1]*256+c[o+2]*65536+c[o+3]*16777216);return(a<<BigInt(32))+t},getFloat64LE:Ko?(c,o)=>{return W[7]=c[o],W[6]=c[o+1],W[5]=c[o+2],W[4]=c[o+3],W[3]=c[o+4],W[2]=c[o+5],W[1]=c[o+6],W[0]=c[o+7],Yc[0]}:(c,o)=>{return W[0]=c[o],W[1]=c[o+1],W[2]=c[o+2],W[3]=c[o+3],W[4]=c[o+4],W[5]=c[o+5],W[6]=c[o+6],W[7]=c[o+7],Yc[0]},setInt32BE(c,o,a){return c[o+3]=a,a>>>=8,c[o+2]=a,a>>>=8,c[o+1]=a,a>>>=8,c[o]=a,4},setInt32LE(c,o,a){return c[o]=a,a>>>=8,c[o+1]=a,a>>>=8,c[o+2]=a,a>>>=8,c[o+3]=a,4},setBigInt64LE(c,o,a){let t=BigInt(4294967295),m=Number(a&t);c[o]=m,m>>=8,c[o+1]=m,m>>=8,c[o+2]=m,m>>=8,c[o+3]=m;let s=Number(a>>BigInt(32)&t);return c[o+4]=s,s>>=8,c[o+5]=s,s>>=8,c[o+6]=s,s>>=8,c[o+7]=s,8},setFloat64LE:Ko?(c,o,a)=>{return Yc[0]=a,c[o]=W[7],c[o+1]=W[6],c[o+2]=W[5],c[o+3]=W[4],c[o+4]=W[3],c[o+5]=W[2],c[o+6]=W[1],c[o+7]=W[0],8}:(c,o,a)=>{return Yc[0]=a,c[o]=W[0],c[o+1]=W[1],c[o+2]=W[2],c[o+3]=W[3],c[o+4]=W[4],c[o+5]=W[5],c[o+6]=W[6],c[o+7]=W[7],8}};class Q extends y{get _bsontype(){return"Binary"}constructor(c,o){super();if(c!=null&&typeof c==="string"&&!ArrayBuffer.isView(c)&&!Qr(c)&&!Array.isArray(c))throw new C("Binary can only be constructed from Uint8Array or number[]");if(this.sub_type=o??Q.BSON_BINARY_SUBTYPE_DEFAULT,c==null)this.buffer=q.allocate(Q.BUFFER_SIZE),this.position=0;else this.buffer=Array.isArray(c)?q.fromNumberArray(c):q.toLocalBufferType(c),this.position=this.buffer.byteLength}put(c){if(typeof c==="string"&&c.length!==1)throw new C("only accepts single character String");else if(typeof c!=="number"&&c.length!==1)throw new C("only accepts single character Uint8Array or Array");let o;if(typeof c==="string")o=c.charCodeAt(0);else if(typeof c==="number")o=c;else o=c[0];if(o<0||o>255)throw new C("only accepts number in a valid unsigned byte range 0-255");if(this.buffer.byteLength>this.position)this.buffer[this.position++]=o;else{let a=q.allocate(Q.BUFFER_SIZE+this.buffer.length);a.set(this.buffer,0),this.buffer=a,this.buffer[this.position++]=o}}write(c,o){if(o=typeof o==="number"?o:this.position,this.buffer.byteLength<o+c.length){let a=q.allocate(this.buffer.byteLength+c.length);a.set(this.buffer,0),this.buffer=a}if(ArrayBuffer.isView(c))this.buffer.set(q.toLocalBufferType(c),o),this.position=o+c.byteLength>this.position?o+c.length:this.position;else if(typeof c==="string")throw new C("input cannot be string")}read(c,o){o=o&&o>0?o:this.position;let a=c+o;return this.buffer.subarray(c,a>this.position?this.position:a)}value(){return this.buffer.length===this.position?this.buffer:this.buffer.subarray(0,this.position)}length(){return this.position}toJSON(){return q.toBase64(this.buffer.subarray(0,this.position))}toString(c){if(c==="hex")return q.toHex(this.buffer.subarray(0,this.position));if(c==="base64")return q.toBase64(this.buffer.subarray(0,this.position));if(c==="utf8"||c==="utf-8")return q.toUTF8(this.buffer,0,this.position,!1);return q.toUTF8(this.buffer,0,this.position,!1)}toExtendedJSON(c){if(c=c||{},this.sub_type===Q.SUBTYPE_VECTOR)wc(this);let o=q.toBase64(this.buffer),a=Number(this.sub_type).toString(16);if(c.legacy)return{$binary:o,$type:a.length===1?"0"+a:a};return{$binary:{base64:o,subType:a.length===1?"0"+a:a}}}toUUID(){if(this.sub_type===Q.SUBTYPE_UUID)return new K(this.buffer.subarray(0,this.position));throw new C(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Q.SUBTYPE_UUID}" is currently supported.`)}static createFromHexString(c,o){return new Q(q.fromHex(c),o)}static createFromBase64(c,o){return new Q(q.fromBase64(c),o)}static fromExtendedJSON(c,o){o=o||{};let a,t;if("$binary"in c){if(o.legacy&&typeof c.$binary==="string"&&"$type"in c)t=c.$type?parseInt(c.$type,16):0,a=q.fromBase64(c.$binary);else if(typeof c.$binary!=="string")t=c.$binary.subType?parseInt(c.$binary.subType,16):0,a=q.fromBase64(c.$binary.base64)}else if("$uuid"in c)t=4,a=K.bytesFromString(c.$uuid);if(!a)throw new C(`Unexpected Binary Extended JSON format ${JSON.stringify(c)}`);return t===Dt?new K(a):new Q(a,t)}inspect(c,o,a){a??=V;let t=q.toBase64(this.buffer.subarray(0,this.position)),m=a(t,o),s=a(this.sub_type,o);return`Binary.createFromBase64(${m}, ${s})`}toInt8Array(){if(this.sub_type!==Q.SUBTYPE_VECTOR)throw new C("Binary sub_type is not Vector");if(this.buffer[0]!==Q.VECTOR_TYPE.Int8)throw new C("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!==Q.SUBTYPE_VECTOR)throw new C("Binary sub_type is not Vector");if(this.buffer[0]!==Q.VECTOR_TYPE.Float32)throw new C("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(qc.isBigEndian)q.swap32(c);return new Float32Array(c.buffer)}toPackedBits(){if(this.sub_type!==Q.SUBTYPE_VECTOR)throw new C("Binary sub_type is not Vector");if(this.buffer[0]!==Q.VECTOR_TYPE.PackedBit)throw new C("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!==Q.SUBTYPE_VECTOR)throw new C("Binary sub_type is not Vector");if(this.buffer[0]!==Q.VECTOR_TYPE.PackedBit)throw new C("Binary datatype field is not packed bit");wc(this);let o=(this.length()-2)*8-this.buffer[1],a=new Int8Array(o);for(let t=0;t<a.length;t++){let m=t/8|0,s=this.buffer[m+2],r=7-t%8,w=s>>r&1;a[t]=w}return a}static fromInt8Array(c){let o=q.allocate(c.byteLength+2);o[0]=Q.VECTOR_TYPE.Int8,o[1]=0;let a=new Uint8Array(c.buffer,c.byteOffset,c.byteLength);o.set(a,2);let t=new this(o,this.SUBTYPE_VECTOR);return wc(t),t}static fromFloat32Array(c){let o=q.allocate(c.byteLength+2);o[0]=Q.VECTOR_TYPE.Float32,o[1]=0;let a=new Uint8Array(c.buffer,c.byteOffset,c.byteLength);if(o.set(a,2),qc.isBigEndian)q.swap32(new Uint8Array(o.buffer,2));let t=new this(o,this.SUBTYPE_VECTOR);return wc(t),t}static fromPackedBits(c,o=0){let a=q.allocate(c.byteLength+2);a[0]=Q.VECTOR_TYPE.PackedBit,a[1]=o,a.set(c,2);let t=new this(a,this.SUBTYPE_VECTOR);return wc(t),t}static fromBits(c){let o=c.length+7>>>3,a=new Uint8Array(o+2);a[0]=Q.VECTOR_TYPE.PackedBit;let t=c.length%8;a[1]=t===0?0:8-t;for(let m=0;m<c.length;m++){let s=m>>>3,r=c[m];if(r!==0&&r!==1)throw new C(`Invalid bit value at ${m}: must be 0 or 1, found ${c[m]}`);if(r===0)continue;let w=7-m%8;a[s+2]|=r<<w}return new this(a,Q.SUBTYPE_VECTOR)}}Q.BSON_BINARY_SUBTYPE_DEFAULT=0;Q.BUFFER_SIZE=256;Q.SUBTYPE_DEFAULT=0;Q.SUBTYPE_FUNCTION=1;Q.SUBTYPE_BYTE_ARRAY=2;Q.SUBTYPE_UUID_OLD=3;Q.SUBTYPE_UUID=4;Q.SUBTYPE_MD5=5;Q.SUBTYPE_ENCRYPTED=6;Q.SUBTYPE_COLUMN=7;Q.SUBTYPE_SENSITIVE=8;Q.SUBTYPE_VECTOR=9;Q.SUBTYPE_USER_DEFINED=128;Q.VECTOR_TYPE=Object.freeze({Int8:3,Float32:39,PackedBit:16});function wc(c){if(c.sub_type!==Q.SUBTYPE_VECTOR)return;let o=c.position,a=c.buffer[0],t=c.buffer[1];if((a===Q.VECTOR_TYPE.Float32||a===Q.VECTOR_TYPE.Int8)&&t!==0)throw new C("Invalid Vector: padding must be zero for int8 and float32 vectors");if(a===Q.VECTOR_TYPE.Float32){if(o!==0&&o-2!==0&&(o-2)%4!==0)throw new C("Invalid Vector: Float32 vector must contain a multiple of 4 bytes")}if(a===Q.VECTOR_TYPE.PackedBit&&t!==0&&o===2)throw new C("Invalid Vector: padding must be zero for packed bit vectors that are empty");if(a===Q.VECTOR_TYPE.PackedBit&&t>7)throw new C(`Invalid Vector: padding must be a value between 0 and 7. found: ${t}`)}var _o=16,Hr=/^[0-9A-F]{32}$/i,Fr=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;class K extends Q{constructor(c){let o;if(c==null)o=K.generate();else if(c instanceof K)o=q.toLocalBufferType(new Uint8Array(c.buffer));else if(ArrayBuffer.isView(c)&&c.byteLength===_o)o=q.toLocalBufferType(c);else if(typeof c==="string")o=K.bytesFromString(c);else throw new C("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(o,Dt)}get id(){return this.buffer}set id(c){this.buffer=c}toHexString(c=!0){if(c)return[q.toHex(this.buffer.subarray(0,4)),q.toHex(this.buffer.subarray(4,6)),q.toHex(this.buffer.subarray(6,8)),q.toHex(this.buffer.subarray(8,10)),q.toHex(this.buffer.subarray(10,16))].join("-");return q.toHex(this.buffer)}toString(c){if(c==="hex")return q.toHex(this.id);if(c==="base64")return q.toBase64(this.id);return this.toHexString()}toJSON(){return this.toHexString()}equals(c){if(!c)return!1;if(c instanceof K)return q.equals(c.id,this.id);try{return q.equals(new K(c).id,this.id)}catch{return!1}}toBinary(){return new Q(this.id,Q.SUBTYPE_UUID)}static generate(){let c=q.randomBytes(_o);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 K.isValidUUIDString(c);if(Kt(c))return c.byteLength===_o;return c._bsontype==="Binary"&&c.sub_type===this.SUBTYPE_UUID&&c.buffer.byteLength===16}static createFromHexString(c){let o=K.bytesFromString(c);return new K(o)}static createFromBase64(c){return new K(q.fromBase64(c))}static bytesFromString(c){if(!K.isValidUUIDString(c))throw new C("UUID string representation must be 32 hex digits or canonical hyphenated representation");return q.fromHex(c.replace(/-/g,""))}static isValidUUIDString(c){return Hr.test(c)||Fr.test(c)}inspect(c,o,a){return a??=V,`new UUID(${a(this.toHexString(),o)})`}}class zc extends y{get _bsontype(){return"Code"}constructor(c,o){super();this.code=c.toString(),this.scope=o??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 zc(c.$code,c.$scope)}inspect(c,o,a){a??=V;let t=a(this.code,o),m=t.includes(`
792
+ `);if(this.scope!=null)t+=`,${m?`
793
+ `:" "}${a(this.scope,o)}`;let s=m&&this.scope===null;return`new Code(${m?`
794
+ `:""}${t}${s?`
795
+ `:""})`}}function Yr(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 y{get _bsontype(){return"DBRef"}constructor(c,o,a,t){super();let m=c.split(".");if(m.length===2)a=m.shift(),c=m.shift();this.collection=c,this.oid=o,this.db=a,this.fields=t||{}}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 o={$ref:this.collection,$id:this.oid};if(c.legacy)return o;if(this.db)o.$db=this.db;return o=Object.assign(o,this.fields),o}static fromExtendedJSON(c){let o=Object.assign({},c);return delete o.$ref,delete o.$id,delete o.$db,new Uc(c.$ref,c.$id,c.$db,o)}inspect(c,o,a){a??=V;let t=[a(this.namespace,o),a(this.oid,o),...this.db?[a(this.db,o)]:[],...Object.keys(this.fields).length>0?[a(this.fields,o)]:[]];return t[1]=a===V?`new ObjectId(${t[1]})`:t[1],`new DBRef(${t.join(", ")})`}}function St(c){if(c==="")return c;let o=0,a=c[o]==="-",t=c[o]==="+";if(t||a)o+=1;let m=!1;for(;o<c.length&&c[o]==="0";++o)m=!0;if(!m)return t?c.slice(1):c;return`${a?"-":""}${c.length===o?"0":c.slice(o)}`}function hr(c,o){o=o??10;let a="0123456789abcdefghijklmnopqrstuvwxyz".slice(0,o);return new RegExp(`[^-+${a}]`,"i").test(c)?!1:c}var S=void 0;try{S=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 It=65536,Ur=16777216,hc=It*It,et=hc*hc,Tr=et/2,Xt={},Zt={},ir=20,Kr=/^(\+?0|(\+|-)?[1-9][0-9]*)$/;class p extends y{get _bsontype(){return"Long"}get __isLong__(){return!0}constructor(c=0,o,a){super();let t=typeof o==="boolean"?o:Boolean(a),m=typeof o==="number"?o:0,s=typeof c==="string"?p.fromString(c,t):typeof c==="bigint"?p.fromBigInt(c,t):{low:c|0,high:m|0,unsigned:t};this.low=s.low,this.high=s.high,this.unsigned=s.unsigned}static fromBits(c,o,a){return new p(c,o,a)}static fromInt(c,o){let a,t,m;if(o){if(c>>>=0,m=0<=c&&c<256){if(t=Zt[c],t)return t}if(a=p.fromBits(c,(c|0)<0?-1:0,!0),m)Zt[c]=a;return a}else{if(c|=0,m=-128<=c&&c<128){if(t=Xt[c],t)return t}if(a=p.fromBits(c,c<0?-1:0,!1),m)Xt[c]=a;return a}}static fromNumber(c,o){if(isNaN(c))return o?p.UZERO:p.ZERO;if(o){if(c<0)return p.UZERO;if(c>=et)return p.MAX_UNSIGNED_VALUE}else{if(c<=-9223372036854776000)return p.MIN_VALUE;if(c+1>=Tr)return p.MAX_VALUE}if(c<0)return p.fromNumber(-c,o).neg();return p.fromBits(c%hc|0,c/hc|0,o)}static fromBigInt(c,o){let a=BigInt(4294967295),t=BigInt(32);return new p(Number(c&a),Number(c>>t&a),o)}static _fromString(c,o,a){if(c.length===0)throw new C("empty string");if(a<2||36<a)throw new C("radix");let t;if((t=c.indexOf("-"))>0)throw new C("interior hyphen");else if(t===0)return p._fromString(c.substring(1),o,a).neg();let m=p.fromNumber(Math.pow(a,8)),s=p.ZERO;for(let r=0;r<c.length;r+=8){let w=Math.min(8,c.length-r),n=parseInt(c.substring(r,r+w),a);if(w<8){let l=p.fromNumber(Math.pow(a,w));s=s.mul(l).add(p.fromNumber(n))}else s=s.mul(m),s=s.add(p.fromNumber(n))}return s.unsigned=o,s}static fromStringStrict(c,o,a){let t=!1;if(typeof o==="number")a=o,o=!1;else t=!!o;if(a??=10,c.trim()!==c)throw new C(`Input: '${c}' contains leading and/or trailing whitespace`);if(!hr(c,a))throw new C(`Input: '${c}' contains invalid characters for radix: ${a}`);let m=St(c),s=p._fromString(m,t,a);if(s.toString(a).toLowerCase()!==m.toLowerCase())throw new C(`Input: ${c} is not representable as ${s.unsigned?"an unsigned":"a signed"} 64-bit Long ${a!=null?`with radix: ${a}`:""}`);return s}static fromString(c,o,a){let t=!1;if(typeof o==="number")a=o,o=!1;else t=!!o;if(a??=10,c==="NaN"&&a<24)return p.ZERO;else if((c==="Infinity"||c==="+Infinity"||c==="-Infinity")&&a<35)return p.ZERO;return p._fromString(c,t,a)}static fromBytes(c,o,a){return a?p.fromBytesLE(c,o):p.fromBytesBE(c,o)}static fromBytesLE(c,o){return new p(c[0]|c[1]<<8|c[2]<<16|c[3]<<24,c[4]|c[5]<<8|c[6]<<16|c[7]<<24,o)}static fromBytesBE(c,o){return new p(c[4]<<24|c[5]<<16|c[6]<<8|c[7],c[0]<<24|c[1]<<16|c[2]<<8|c[3],o)}static isLong(c){return c!=null&&typeof c==="object"&&"__isLong__"in c&&c.__isLong__===!0}static fromValue(c,o){if(typeof c==="number")return p.fromNumber(c,o);if(typeof c==="string")return p.fromString(c,o);return p.fromBits(c.low,c.high,typeof o==="boolean"?o:c.unsigned)}add(c){if(!p.isLong(c))c=p.fromValue(c);let o=this.high>>>16,a=this.high&65535,t=this.low>>>16,m=this.low&65535,s=c.high>>>16,r=c.high&65535,w=c.low>>>16,n=c.low&65535,l=0,g=0,j=0,J=0;return J+=m+n,j+=J>>>16,J&=65535,j+=t+w,g+=j>>>16,j&=65535,g+=a+r,l+=g>>>16,g&=65535,l+=o+s,l&=65535,p.fromBits(j<<16|J,l<<16|g,this.unsigned)}and(c){if(!p.isLong(c))c=p.fromValue(c);return p.fromBits(this.low&c.low,this.high&c.high,this.unsigned)}compare(c){if(!p.isLong(c))c=p.fromValue(c);if(this.eq(c))return 0;let o=this.isNegative(),a=c.isNegative();if(o&&!a)return-1;if(!o&&a)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(!p.isLong(c))c=p.fromValue(c);if(c.isZero())throw new C("division by zero");if(S){if(!this.unsigned&&this.high===-2147483648&&c.low===-1&&c.high===-1)return this;let m=(this.unsigned?S.div_u:S.div_s)(this.low,this.high,c.low,c.high);return p.fromBits(m,S.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?p.UZERO:p.ZERO;let o,a,t;if(!this.unsigned){if(this.eq(p.MIN_VALUE))if(c.eq(p.ONE)||c.eq(p.NEG_ONE))return p.MIN_VALUE;else if(c.eq(p.MIN_VALUE))return p.ONE;else if(o=this.shr(1).div(c).shl(1),o.eq(p.ZERO))return c.isNegative()?p.ONE:p.NEG_ONE;else return a=this.sub(c.mul(o)),t=o.add(a.div(c)),t;else if(c.eq(p.MIN_VALUE))return this.unsigned?p.UZERO:p.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();t=p.ZERO}else{if(!c.unsigned)c=c.toUnsigned();if(c.gt(this))return p.UZERO;if(c.gt(this.shru(1)))return p.UONE;t=p.UZERO}a=this;while(a.gte(c)){o=Math.max(1,Math.floor(a.toNumber()/c.toNumber()));let m=Math.ceil(Math.log(o)/Math.LN2),s=m<=48?1:Math.pow(2,m-48),r=p.fromNumber(o),w=r.mul(c);while(w.isNegative()||w.gt(a))o-=s,r=p.fromNumber(o,this.unsigned),w=r.mul(c);if(r.isZero())r=p.ONE;t=t.add(r),a=a.sub(w)}return t}div(c){return this.divide(c)}equals(c){if(!p.isLong(c))c=p.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(p.MIN_VALUE)?64:this.neg().getNumBitsAbs();let c=this.high!==0?this.high:this.low,o;for(o=31;o>0;o--)if((c&1<<o)!==0)break;return this.high!==0?o+33:o+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(!p.isLong(c))c=p.fromValue(c);if(S){let o=(this.unsigned?S.rem_u:S.rem_s)(this.low,this.high,c.low,c.high);return p.fromBits(o,S.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 p.ZERO;if(!p.isLong(c))c=p.fromValue(c);if(S){let F=S.mul(this.low,this.high,c.low,c.high);return p.fromBits(F,S.get_high(),this.unsigned)}if(c.isZero())return p.ZERO;if(this.eq(p.MIN_VALUE))return c.isOdd()?p.MIN_VALUE:p.ZERO;if(c.eq(p.MIN_VALUE))return this.isOdd()?p.MIN_VALUE:p.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(p.TWO_PWR_24)&&c.lt(p.TWO_PWR_24))return p.fromNumber(this.toNumber()*c.toNumber(),this.unsigned);let o=this.high>>>16,a=this.high&65535,t=this.low>>>16,m=this.low&65535,s=c.high>>>16,r=c.high&65535,w=c.low>>>16,n=c.low&65535,l=0,g=0,j=0,J=0;return J+=m*n,j+=J>>>16,J&=65535,j+=t*n,g+=j>>>16,j&=65535,j+=m*w,g+=j>>>16,j&=65535,g+=a*n,l+=g>>>16,g&=65535,g+=t*w,l+=g>>>16,g&=65535,g+=m*r,l+=g>>>16,g&=65535,l+=o*n+a*w+t*r+m*s,l&=65535,p.fromBits(j<<16|J,l<<16|g,this.unsigned)}mul(c){return this.multiply(c)}negate(){if(!this.unsigned&&this.eq(p.MIN_VALUE))return p.MIN_VALUE;return this.not().add(p.ONE)}neg(){return this.negate()}not(){return p.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(!p.isLong(c))c=p.fromValue(c);return p.fromBits(this.low|c.low,this.high|c.high,this.unsigned)}shiftLeft(c){if(p.isLong(c))c=c.toInt();if((c&=63)===0)return this;else if(c<32)return p.fromBits(this.low<<c,this.high<<c|this.low>>>32-c,this.unsigned);else return p.fromBits(0,this.low<<c-32,this.unsigned)}shl(c){return this.shiftLeft(c)}shiftRight(c){if(p.isLong(c))c=c.toInt();if((c&=63)===0)return this;else if(c<32)return p.fromBits(this.low>>>c|this.high<<32-c,this.high>>c,this.unsigned);else return p.fromBits(this.high>>c-32,this.high>=0?0:-1,this.unsigned)}shr(c){return this.shiftRight(c)}shiftRightUnsigned(c){if(p.isLong(c))c=c.toInt();if(c&=63,c===0)return this;else{let o=this.high;if(c<32){let a=this.low;return p.fromBits(a>>>c|o<<32-c,o>>>c,this.unsigned)}else if(c===32)return p.fromBits(o,0,this.unsigned);else return p.fromBits(o>>>c-32,0,this.unsigned)}}shr_u(c){return this.shiftRightUnsigned(c)}shru(c){return this.shiftRightUnsigned(c)}subtract(c){if(!p.isLong(c))c=p.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)*hc+(this.low>>>0);return this.high*hc+(this.low>>>0)}toBigInt(){return BigInt(this.toString())}toBytes(c){return c?this.toBytesLE():this.toBytesBE()}toBytesLE(){let c=this.high,o=this.low;return[o&255,o>>>8&255,o>>>16&255,o>>>24,c&255,c>>>8&255,c>>>16&255,c>>>24]}toBytesBE(){let c=this.high,o=this.low;return[c>>>24,c>>>16&255,c>>>8&255,c&255,o>>>24,o>>>16&255,o>>>8&255,o&255]}toSigned(){if(!this.unsigned)return this;return p.fromBits(this.low,this.high,!1)}toString(c){if(c=c||10,c<2||36<c)throw new C("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(p.MIN_VALUE)){let m=p.fromNumber(c),s=this.div(m),r=s.mul(m).sub(this);return s.toString(c)+r.toInt().toString(c)}else return"-"+this.neg().toString(c);let o=p.fromNumber(Math.pow(c,6),this.unsigned),a=this,t="";while(!0){let m=a.div(o),r=(a.sub(m.mul(o)).toInt()>>>0).toString(c);if(a=m,a.isZero())return r+t;else{while(r.length<6)r="0"+r;t=""+r+t}}}toUnsigned(){if(this.unsigned)return this;return p.fromBits(this.low,this.high,!0)}xor(c){if(!p.isLong(c))c=p.fromValue(c);return p.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,o){let{useBigInt64:a=!1,relaxed:t=!0}={...o};if(c.$numberLong.length>ir)throw new C("$numberLong string is too long");if(!Kr.test(c.$numberLong))throw new C(`$numberLong string "${c.$numberLong}" is in an invalid format`);if(a){let s=BigInt(c.$numberLong);return BigInt.asIntN(64,s)}let m=p.fromString(c.$numberLong);if(t)return m.toNumber();return m}inspect(c,o,a){a??=V;let t=a(this.toString(),o),m=this.unsigned?`, ${a(this.unsigned,o)}`:"";return`new Long(${t}${m})`}}p.TWO_PWR_24=p.fromInt(Ur);p.MAX_UNSIGNED_VALUE=p.fromBits(-1,-1,!0);p.ZERO=p.fromInt(0);p.UZERO=p.fromInt(0,!0);p.ONE=p.fromInt(1);p.UONE=p.fromInt(1,!0);p.NEG_ONE=p.fromInt(-1);p.MAX_VALUE=p.fromBits(-1,2147483647,!1);p.MIN_VALUE=p.fromBits(0,-2147483648,!1);var _r=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/,Er=/^(\+|-)?(Infinity|inf)$/i,ur=/^(\+|-)?NaN$/i,Fc=6111,Dc=-6176,Ht=6176,Ft=34,Eo=q.fromNumberArray([124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),Yt=q.fromNumberArray([248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),ht=q.fromNumberArray([120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),kr=/^([-+])?(\d+)?$/,Dr=31,Ut=16383,Vr=30,yr=31;function Tt(c){return!isNaN(parseInt(c,10))}function zr(c){let o=p.fromNumber(1e9),a=p.fromNumber(0);if(!c.parts[0]&&!c.parts[1]&&!c.parts[2]&&!c.parts[3])return{quotient:c,rem:a};for(let t=0;t<=3;t++)a=a.shiftLeft(32),a=a.add(new p(c.parts[t],0)),c.parts[t]=a.div(o).low,a=a.modulo(o);return{quotient:c,rem:a}}function Sr(c,o){if(!c&&!o)return{high:p.fromNumber(0),low:p.fromNumber(0)};let a=c.shiftRightUnsigned(32),t=new p(c.getLowBits(),0),m=o.shiftRightUnsigned(32),s=new p(o.getLowBits(),0),r=a.multiply(m),w=a.multiply(s),n=t.multiply(m),l=t.multiply(s);return r=r.add(w.shiftRightUnsigned(32)),w=new p(w.getLowBits(),0).add(n).add(l.shiftRightUnsigned(32)),r=r.add(w.shiftRightUnsigned(32)),l=w.shiftLeft(32).add(new p(l.getLowBits(),0)),{high:r,low:l}}function er(c,o){let a=c.high>>>0,t=o.high>>>0;if(a<t)return!0;else if(a===t){let m=c.low>>>0,s=o.low>>>0;if(m<s)return!0}return!1}function L(c,o){throw new C(`"${c}" is not a valid Decimal128 string - ${o}`)}class D extends y{get _bsontype(){return"Decimal128"}constructor(c){super();if(typeof c==="string")this.bytes=D.fromString(c).bytes;else if(c instanceof Uint8Array||Kt(c)){if(c.byteLength!==16)throw new C("Decimal128 must take a Buffer of 16 bytes");this.bytes=c}else throw new C("Decimal128 must take a Buffer or string")}static fromString(c){return D._fromString(c,{allowRounding:!1})}static fromStringWithRounding(c){return D._fromString(c,{allowRounding:!0})}static _fromString(c,o){let a=!1,t=!1,m=!1,s=!1,r=0,w=0,n=0,l=0,g=0,j=[0],J=0,F=0,A=0,P=0,Z=new p(0,0),G=new p(0,0),T=0,$=0;if(c.length>=7000)throw new C(""+c+" not a valid Decimal128 string");let i=c.match(_r),dm=c.match(Er),Lm=c.match(ur);if(!i&&!dm&&!Lm||c.length===0)throw new C(""+c+" not a valid Decimal128 string");if(i){let I=i[2],Ac=i[4],Jc=i[5],E=i[6];if(Ac&&E===void 0)L(c,"missing exponent power");if(Ac&&I===void 0)L(c,"missing exponent base");if(Ac===void 0&&(Jc||E))L(c,"missing e before exponent")}if(c[$]==="+"||c[$]==="-")t=!0,a=c[$++]==="-";if(!Tt(c[$])&&c[$]!=="."){if(c[$]==="i"||c[$]==="I")return new D(a?Yt:ht);else if(c[$]==="N")return new D(Eo)}while(Tt(c[$])||c[$]==="."){if(c[$]==="."){if(m)L(c,"contains multiple periods");m=!0,$=$+1;continue}if(J<Ft){if(c[$]!=="0"||s){if(!s)g=w;s=!0,j[F++]=parseInt(c[$],10),J=J+1}}if(s)n=n+1;if(m)l=l+1;w=w+1,$=$+1}if(m&&!w)throw new C(""+c+" not a valid Decimal128 string");if(c[$]==="e"||c[$]==="E"){let I=c.substr(++$).match(kr);if(!I||!I[2])return new D(Eo);P=parseInt(I[0],10),$=$+I[0].length}if(c[$])return new D(Eo);if(!J)j[0]=0,n=1,J=1,r=0;else if(A=J-1,r=n,r!==1)while(c[g+r-1+Number(t)+Number(m)]==="0")r=r-1;if(P<=l&&l>P+16384)P=Dc;else P=P-l;while(P>Fc){if(A=A+1,A>=Ft){if(r===0){P=Fc;break}L(c,"overflow")}P=P-1}if(o.allowRounding){while(P<Dc||J<n){if(A===0&&r<J){P=Dc,r=0;break}if(J<n)n=n-1;else A=A-1;if(P<Fc)P=P+1;else{if(j.join("").match(/^0+$/)){P=Fc;break}L(c,"overflow")}}if(A+1<r){let I=w;if(m)g=g+1,I=I+1;if(t)g=g+1,I=I+1;let Ac=parseInt(c[g+A+1],10),Jc=0;if(Ac>=5){if(Jc=1,Ac===5){Jc=j[A]%2===1?1:0;for(let E=g+A+2;E<I;E++)if(parseInt(c[E],10)){Jc=1;break}}}if(Jc){let E=A;for(;E>=0;E--)if(++j[E]>9){if(j[E]=0,E===0)if(P<Fc)P=P+1,j[E]=1;else return new D(a?Yt:ht)}else break}}}else{while(P<Dc||J<n){if(A===0){if(r===0){P=Dc;break}L(c,"exponent underflow")}if(J<n){if(c[n-1+Number(t)+Number(m)]!=="0"&&r!==0)L(c,"inexact rounding");n=n-1}else{if(j[A]!==0)L(c,"inexact rounding");A=A-1}if(P<Fc)P=P+1;else L(c,"overflow")}if(A+1<r){if(m)g=g+1;if(t)g=g+1;if(parseInt(c[g+A+1],10)!==0)L(c,"inexact rounding")}}if(Z=p.fromNumber(0),G=p.fromNumber(0),r===0)Z=p.fromNumber(0),G=p.fromNumber(0);else if(A<17){let I=0;G=p.fromNumber(j[I++]),Z=new p(0,0);for(;I<=A;I++)G=G.multiply(p.fromNumber(10)),G=G.add(p.fromNumber(j[I]))}else{let I=0;Z=p.fromNumber(j[I++]);for(;I<=A-17;I++)Z=Z.multiply(p.fromNumber(10)),Z=Z.add(p.fromNumber(j[I]));G=p.fromNumber(j[I++]);for(;I<=A;I++)G=G.multiply(p.fromNumber(10)),G=G.add(p.fromNumber(j[I]))}let B=Sr(Z,p.fromString("100000000000000000"));if(B.low=B.low.add(G),er(B.low,G))B.high=B.high.add(p.fromNumber(1));T=P+Ht;let M={low:p.fromNumber(0),high:p.fromNumber(0)};if(B.high.shiftRightUnsigned(49).and(p.fromNumber(1)).equals(p.fromNumber(1)))M.high=M.high.or(p.fromNumber(3).shiftLeft(61)),M.high=M.high.or(p.fromNumber(T).and(p.fromNumber(16383).shiftLeft(47))),M.high=M.high.or(B.high.and(p.fromNumber(140737488355327)));else M.high=M.high.or(p.fromNumber(T&16383).shiftLeft(49)),M.high=M.high.or(B.high.and(p.fromNumber(562949953421311)));if(M.low=B.low,a)M.high=M.high.or(p.fromString("9223372036854775808"));let h=q.allocateUnsafe(16);return $=0,h[$++]=M.low.low&255,h[$++]=M.low.low>>8&255,h[$++]=M.low.low>>16&255,h[$++]=M.low.low>>24&255,h[$++]=M.low.high&255,h[$++]=M.low.high>>8&255,h[$++]=M.low.high>>16&255,h[$++]=M.low.high>>24&255,h[$++]=M.high.low&255,h[$++]=M.high.low>>8&255,h[$++]=M.high.low>>16&255,h[$++]=M.high.low>>24&255,h[$++]=M.high.high&255,h[$++]=M.high.high>>8&255,h[$++]=M.high.high>>16&255,h[$++]=M.high.high>>24&255,new D(h)}toString(){let c,o=0,a=Array(36);for(let $=0;$<a.length;$++)a[$]=0;let t=0,m=!1,s,r={parts:[0,0,0,0]},w,n,l=[];t=0;let g=this.bytes,j=g[t++]|g[t++]<<8|g[t++]<<16|g[t++]<<24,J=g[t++]|g[t++]<<8|g[t++]<<16|g[t++]<<24,F=g[t++]|g[t++]<<8|g[t++]<<16|g[t++]<<24,A=g[t++]|g[t++]<<8|g[t++]<<16|g[t++]<<24;if(t=0,{low:new p(j,J),high:new p(F,A)}.high.lessThan(p.ZERO))l.push("-");let Z=A>>26&Dr;if(Z>>3===3)if(Z===Vr)return l.join("")+"Infinity";else if(Z===yr)return"NaN";else c=A>>15&Ut,s=8+(A>>14&1);else s=A>>14&7,c=A>>17&Ut;let G=c-Ht;if(r.parts[0]=(A&16383)+((s&15)<<14),r.parts[1]=F,r.parts[2]=J,r.parts[3]=j,r.parts[0]===0&&r.parts[1]===0&&r.parts[2]===0&&r.parts[3]===0)m=!0;else for(n=3;n>=0;n--){let $=0,i=zr(r);if(r=i.quotient,$=i.rem.low,!$)continue;for(w=8;w>=0;w--)a[n*9+w]=$%10,$=Math.floor($/10)}if(m)o=1,a[t]=0;else{o=36;while(!a[t])o=o-1,t=t+1}let T=o-1+G;if(T>=34||T<=-7||G>0){if(o>34){if(l.push("0"),G>0)l.push(`E+${G}`);else if(G<0)l.push(`E${G}`);return l.join("")}if(l.push(`${a[t++]}`),o=o-1,o)l.push(".");for(let $=0;$<o;$++)l.push(`${a[t++]}`);if(l.push("E"),T>0)l.push(`+${T}`);else l.push(`${T}`)}else if(G>=0)for(let $=0;$<o;$++)l.push(`${a[t++]}`);else{let $=o+G;if($>0)for(let i=0;i<$;i++)l.push(`${a[t++]}`);else l.push("0");l.push(".");while($++<0)l.push("0");for(let i=0;i<o-Math.max($-1,0);i++)l.push(`${a[t++]}`)}return l.join("")}toJSON(){return{$numberDecimal:this.toString()}}toExtendedJSON(){return{$numberDecimal:this.toString()}}static fromExtendedJSON(c){return D.fromString(c.$numberDecimal)}inspect(c,o,a){return a??=V,`new Decimal128(${a(this.toString(),o)})`}}class tc extends y{get _bsontype(){return"Double"}constructor(c){super();if(c instanceof Number)c=c.valueOf();this.value=+c}static fromString(c){let o=Number(c);if(c==="NaN")return new tc(NaN);if(c==="Infinity")return new tc(1/0);if(c==="-Infinity")return new tc(-1/0);if(!Number.isFinite(o))throw new C(`Input: ${c} is not representable as a Double`);if(c.trim()!==c)throw new C(`Input: '${c}' contains whitespace`);if(c==="")throw new C("Input is an empty string");if(/[^-0-9.+eE]/.test(c))throw new C(`Input: '${c}' is not in decimal or exponential notation`);return new tc(o)}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,o){let a=parseFloat(c.$numberDouble);return o&&o.relaxed?a:new tc(a)}inspect(c,o,a){return a??=V,`new Double(${a(this.value,o)})`}}class Tc extends y{get _bsontype(){return"Int32"}constructor(c){super();if(c instanceof Number)c=c.valueOf();this.value=+c|0}static fromString(c){let o=St(c),a=Number(c);if(yo<a)throw new C(`Input: '${c}' is larger than the maximum value for Int32`);else if(zo>a)throw new C(`Input: '${c}' is smaller than the minimum value for Int32`);else if(!Number.isSafeInteger(a))throw new C(`Input: '${c}' is not a safe integer`);else if(a.toString()!==o)throw new C(`Input: '${c}' is not a valid Int32 string`);return new Tc(a)}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,o){return o&&o.relaxed?parseInt(c.$numberInt,10):new Tc(c.$numberInt)}inspect(c,o,a){return a??=V,`new Int32(${a(this.value,o)})`}}class mo extends y{get _bsontype(){return"MaxKey"}toExtendedJSON(){return{$maxKey:1}}static fromExtendedJSON(){return new mo}inspect(){return"new MaxKey()"}}class so extends y{get _bsontype(){return"MinKey"}toExtendedJSON(){return{$minKey:1}}static fromExtendedJSON(){return new so}inspect(){return"new MinKey()"}}var $c=null,Vc=new WeakMap;class H extends y{get _bsontype(){return"ObjectId"}constructor(c){super();let o;if(typeof c==="object"&&c&&"id"in c){if(typeof c.id!=="string"&&!ArrayBuffer.isView(c.id))throw new C("Argument passed in must have an id that is of type string or Buffer");if("toHexString"in c&&typeof c.toHexString==="function")o=q.fromHex(c.toHexString());else o=c.id}else o=c;if(o==null||typeof o==="number")this.buffer=H.generate(typeof o==="number"?o:void 0);else if(ArrayBuffer.isView(o)&&o.byteLength===12)this.buffer=q.toLocalBufferType(o);else if(typeof o==="string")if(H.validateHexString(o)){if(this.buffer=q.fromHex(o),H.cacheHexString)Vc.set(this,o)}else throw new C("input must be a 24 character hex string, 12 byte Uint8Array, or an integer");else throw new C("Argument passed in does not match the accepted types")}get id(){return this.buffer}set id(c){if(this.buffer=c,H.cacheHexString)Vc.set(this,q.toHex(c))}static validateHexString(c){if(c?.length!==24)return!1;for(let o=0;o<24;o++){let a=c.charCodeAt(o);if(a>=48&&a<=57||a>=97&&a<=102||a>=65&&a<=70)continue;return!1}return!0}toHexString(){if(H.cacheHexString){let o=Vc.get(this);if(o)return o}let c=q.toHex(this.id);if(H.cacheHexString)Vc.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 o=H.getInc(),a=q.allocateUnsafe(12);if(qc.setInt32BE(a,0,c),$c===null)$c=q.randomBytes(5);return a[4]=$c[0],a[5]=$c[1],a[6]=$c[2],a[7]=$c[3],a[8]=$c[4],a[11]=o&255,a[10]=o>>8&255,a[9]=o>>16&255,a}toString(c){if(c==="base64")return q.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]&&q.equals(this.buffer,c.buffer);if(typeof c==="string")return c.toLowerCase()===this.toHexString();if(typeof c==="object"&&typeof c.toHexString==="function"){let o=c.toHexString(),a=this.toHexString();return typeof o==="string"&&o.toLowerCase()===a}return!1}getTimestamp(){let c=new Date,o=qc.getUint32BE(this.buffer,0);return c.setTime(Math.floor(o)*1000),c}static createPk(){return new H}serializeInto(c,o){return c[o]=this.buffer[0],c[o+1]=this.buffer[1],c[o+2]=this.buffer[2],c[o+3]=this.buffer[3],c[o+4]=this.buffer[4],c[o+5]=this.buffer[5],c[o+6]=this.buffer[6],c[o+7]=this.buffer[7],c[o+8]=this.buffer[8],c[o+9]=this.buffer[9],c[o+10]=this.buffer[10],c[o+11]=this.buffer[11],12}static createFromTime(c){let o=q.allocate(12);for(let a=11;a>=4;a--)o[a]=0;return qc.setInt32BE(o,0,c),new H(o)}static createFromHexString(c){if(c?.length!==24)throw new C("hex string must be 24 characters");return new H(q.fromHex(c))}static createFromBase64(c){if(c?.length!==16)throw new C("base64 string must be 16 characters");return new H(q.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&&Vc.has(this)}inspect(c,o,a){return a??=V,`new ObjectId(${a(this.toHexString(),o)})`}}H.index=Math.floor(Math.random()*16777215);function Nr(c){return c.split("").sort().join("")}class sc extends y{get _bsontype(){return"BSONRegExp"}constructor(c,o){super();if(this.pattern=c,this.options=Nr(o??""),this.pattern.indexOf("\x00")!==-1)throw new C(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`);if(this.options.indexOf("\x00")!==-1)throw new C(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`);for(let a=0;a<this.options.length;a++)if(!(this.options[a]==="i"||this.options[a]==="m"||this.options[a]==="x"||this.options[a]==="l"||this.options[a]==="s"||this.options[a]==="u"))throw new C(`The regular expression option [${this.options[a]}] 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 sc(c.$regex,sc.parseOptions(c.$options));if("$regularExpression"in c)return new sc(c.$regularExpression.pattern,sc.parseOptions(c.$regularExpression.options));throw new C(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(c)}`)}inspect(c,o,a){let t=Rr(o)??((r)=>r);a??=V;let m=t(a(this.pattern),"regexp"),s=t(a(this.options),"regexp");return`new BSONRegExp(${m}, ${s})`}}class ro extends y{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 ro(c.$symbol)}inspect(c,o,a){return a??=V,`new BSONSymbol(${a(this.value,o)})`}}var dr=p;class mc extends dr{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(p.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 C("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 C("Timestamp constructed from { t, i } must provide i as a number");let o=Number(c.t),a=Number(c.i);if(o<0||Number.isNaN(o))throw new C("Timestamp constructed from { t, i } must provide a positive t");if(a<0||Number.isNaN(a))throw new C("Timestamp constructed from { t, i } must provide a positive i");if(o>4294967295)throw new C("Timestamp constructed from { t, i } must provide t equal or less than uint32 max");if(a>4294967295)throw new C("Timestamp constructed from { t, i } must provide i equal or less than uint32 max");super(a,o,!0)}else throw new C("A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }")}toJSON(){return{$timestamp:this.toString()}}static fromInt(c){return new mc(p.fromInt(c,!0))}static fromNumber(c){return new mc(p.fromNumber(c,!0))}static fromBits(c,o){return new mc({i:c,t:o})}static fromString(c,o){return new mc(p.fromString(c,!0,o))}toExtendedJSON(){return{$timestamp:{t:this.t,i:this.i}}}static fromExtendedJSON(c){let o=p.isLong(c.$timestamp.i)?c.$timestamp.i.getLowBitsUnsigned():c.$timestamp.i,a=p.isLong(c.$timestamp.t)?c.$timestamp.t.getLowBitsUnsigned():c.$timestamp.t;return new mc({t:a,i:o})}inspect(c,o,a){a??=V;let t=a(this.t,o),m=a(this.i,o);return`new Timestamp({ t: ${t}, i: ${m} })`}}mc.MAX_VALUE=p.MAX_UNSIGNED_VALUE;var Nn=p.fromNumber(Pr),dn=p.fromNumber(Wr);function Lr(c){return c!=null&&typeof c==="object"&&"_bsontype"in c&&typeof c._bsontype==="string"}var Or={$oid:H,$binary:Q,$uuid:Q,$symbol:ro,$numberInt:Tc,$numberDecimal:D,$numberDouble:tc,$numberLong:p,$minKey:so,$maxKey:mo,$regex:sc,$regularExpression:sc,$timestamp:mc};function Nt(c,o={}){if(typeof c==="number"){let t=c<=yo&&c>=zo,m=c<=ut&&c>=kt;if(o.relaxed||o.legacy)return c;if(Number.isInteger(c)&&!Object.is(c,-0)){if(t)return new Tc(c);if(m){if(o.useBigInt64)return BigInt(c);return p.fromNumber(c)}}return new tc(c)}if(c==null||typeof c!=="object")return c;if(c.$undefined)return null;let a=Object.keys(c).filter((t)=>t.startsWith("$")&&c[t]!=null);for(let t=0;t<a.length;t++){let m=Or[a[t]];if(m)return m.fromExtendedJSON(c,o)}if(c.$date!=null){let t=c.$date,m=new Date;if(o.legacy)if(typeof t==="number")m.setTime(t);else if(typeof t==="string")m.setTime(Date.parse(t));else if(typeof t==="bigint")m.setTime(Number(t));else throw new Do(`Unrecognized type for EJSON date: ${typeof t}`);else if(typeof t==="string")m.setTime(Date.parse(t));else if(p.isLong(t))m.setTime(t.toNumber());else if(typeof t==="number"&&o.relaxed)m.setTime(t);else if(typeof t==="bigint")m.setTime(Number(t));else throw new Do(`Unrecognized type for EJSON date: ${typeof t}`);return m}if(c.$code!=null){let t=Object.assign({},c);if(c.$scope)t.$scope=Nt(c.$scope);return zc.fromExtendedJSON(c)}if(Yr(c)||c.$dbPointer){let t=c.$ref?c:c.$dbPointer;if(t instanceof Uc)return t;let m=Object.keys(t).filter((r)=>r.startsWith("$")),s=!0;if(m.forEach((r)=>{if(["$ref","$id","$db"].indexOf(r)===-1)s=!1}),s)return Uc.fromExtendedJSON(t)}return c}function br(c,o){return c.map((a,t)=>{o.seenObjects.push({propertyName:`index ${t}`,obj:null});try{return ac(a,o)}finally{o.seenObjects.pop()}})}function it(c){let o=c.toISOString();return c.getUTCMilliseconds()!==0?o:o.slice(0,-5)+"Z"}function ac(c,o){if(c instanceof Map||_t(c)){let a=Object.create(null);for(let[t,m]of c){if(typeof t!=="string")throw new C("Can only serialize maps with string keys");a[t]=m}return ac(a,o)}if((typeof c==="object"||typeof c==="function")&&c!==null){let a=o.seenObjects.findIndex((t)=>t.obj===c);if(a!==-1){let t=o.seenObjects.map((g)=>g.propertyName),m=t.slice(0,a).map((g)=>`${g} -> `).join(""),s=t[a],r=" -> "+t.slice(a+1,t.length-1).map((g)=>`${g} -> `).join(""),w=t[t.length-1],n=" ".repeat(m.length+s.length/2),l="-".repeat(r.length+(s.length+w.length)/2-1);throw new C(`Converting circular structure to EJSON:
796
+ ${m}${s}${r}${w}
797
+ ${n}\\${l}/`)}o.seenObjects[o.seenObjects.length-1].obj=c}if(Array.isArray(c))return br(c,o);if(c===void 0)return null;if(c instanceof Date||Jr(c)){let a=c.getTime(),t=a>-1&&a<253402318800000;if(o.legacy)return o.relaxed&&t?{$date:c.getTime()}:{$date:it(c)};return o.relaxed&&t?{$date:it(c)}:{$date:{$numberLong:c.getTime().toString()}}}if(typeof c==="number"&&(!o.relaxed||!isFinite(c))){if(Number.isInteger(c)&&!Object.is(c,-0)){if(c>=zo&&c<=yo)return{$numberInt:c.toString()};if(c>=kt&&c<=ut)return{$numberLong:c.toString()}}return{$numberDouble:Object.is(c,-0)?"-0.0":c.toString()}}if(typeof c==="bigint"){if(!o.relaxed)return{$numberLong:BigInt.asIntN(64,c).toString()};return Number(BigInt.asIntN(64,c))}if(c instanceof RegExp||Ar(c)){let a=c.flags;if(a===void 0){let m=c.toString().match(/[gimuy]*$/);if(m)a=m[0]}return new sc(c.source,a).toExtendedJSON(o)}if(c!=null&&typeof c==="object")return vr(c,o);return c}var Br={Binary:(c)=>new Q(c.value(),c.sub_type),Code:(c)=>new zc(c.code,c.scope),DBRef:(c)=>new Uc(c.collection||c.namespace,c.oid,c.db,c.fields),Decimal128:(c)=>new D(c.bytes),Double:(c)=>new tc(c.value),Int32:(c)=>new Tc(c.value),Long:(c)=>p.fromBits(c.low!=null?c.low:c.low_,c.low!=null?c.high:c.high_,c.low!=null?c.unsigned:c.unsigned_),MaxKey:()=>new mo,MinKey:()=>new so,ObjectId:(c)=>new H(c),BSONRegExp:(c)=>new sc(c.pattern,c.options),BSONSymbol:(c)=>new ro(c.value),Timestamp:(c)=>mc.fromBits(c.low,c.high)};function vr(c,o){if(c==null||typeof c!=="object")throw new C("not an object instance");let a=c._bsontype;if(typeof a>"u"){let t={};for(let m of Object.keys(c)){o.seenObjects.push({propertyName:m,obj:null});try{let s=ac(c[m],o);if(m==="__proto__")Object.defineProperty(t,m,{value:s,writable:!0,enumerable:!0,configurable:!0});else t[m]=s}finally{o.seenObjects.pop()}}return t}else if(c!=null&&typeof c==="object"&&typeof c._bsontype==="string"&&c[Et]!==Vo)throw new Vt;else if(Lr(c)){let t=c;if(typeof t.toExtendedJSON!=="function"){let m=Br[c._bsontype];if(!m)throw new C("Unrecognized or invalid _bsontype: "+c._bsontype);t=m(t)}if(a==="Code"&&t.scope)t=new zc(t.code,ac(t.scope,o));else if(a==="DBRef"&&t.oid)t=new Uc(ac(t.collection,o),ac(t.oid,o),ac(t.db,o),ac(t.fields,o));return t.toExtendedJSON(o)}else throw new C("_bsontype must be a string, but was: "+typeof a)}function dt(c,o){let a={useBigInt64:o?.useBigInt64??!1,relaxed:o?.relaxed??!0,legacy:o?.legacy??!1};return JSON.parse(c,(t,m)=>{if(t.indexOf("\x00")!==-1)throw new C(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(t)}`);return Nt(m,a)})}function Lt(c,o,a,t){if(a!=null&&typeof a==="object")t=a,a=0;if(o!=null&&typeof o==="object"&&!Array.isArray(o))t=o,o=void 0,a=0;let m=Object.assign({relaxed:!0,legacy:!1},t,{seenObjects:[{propertyName:"(root)",obj:null}]}),s=ac(c,m);return JSON.stringify(s,o,a)}function xr(c,o){return o=o||{},JSON.parse(Lt(c,o))}function fr(c,o){return o=o||{},dt(JSON.stringify(c),o)}var gc=Object.create(null);gc.parse=dt;gc.stringify=Lt;gc.serialize=xr;gc.deserialize=fr;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 uo(c,o){try{return qc.getNonnegativeInt32LE(c,o)}catch(a){throw new oc("BSON size cannot be negative",o,{cause:a})}}function ko(c,o){let a=o;for(;c[a]!==0;a++);if(a===c.length-1)throw new oc("Null terminator not found",o);return a}function cp(c,o=0){if(o??=0,c.length<5)throw new oc(`Input must be at least 5 bytes, got ${c.length} bytes`,o);let a=uo(c,o);if(a>c.length-o)throw new oc(`Parsed documentSize (${a} bytes) does not match input length (${c.length} bytes)`,o);if(c[o+a-1]!==0)throw new oc("BSON documents must end in 0x00",o+a);let t=[],m=o+4;while(m<=a+o){let s=c[m];if(m+=1,s===0){if(m-o!==a)throw new oc("Invalid 0x00 type byte",m);break}let r=m,w=ko(c,m)-r;m+=w+1;let n;if(s===X.double||s===X.long||s===X.date||s===X.timestamp)n=8;else if(s===X.int)n=4;else if(s===X.objectId)n=12;else if(s===X.decimal)n=16;else if(s===X.bool)n=1;else if(s===X.null||s===X.undefined||s===X.maxKey||s===X.minKey)n=0;else if(s===X.regex)n=ko(c,ko(c,m)+1)+1-m;else if(s===X.object||s===X.array||s===X.javascriptWithScope)n=uo(c,m);else if(s===X.string||s===X.binData||s===X.dbPointer||s===X.javascript||s===X.symbol){if(n=uo(c,m)+4,s===X.binData)n+=1;if(s===X.dbPointer)n+=12}else throw new oc(`Invalid 0x${s.toString(16).padStart(2,"0")} type byte`,m);if(n>a)throw new oc("value reports length larger than document",m);t.push([s,r,w,m,n]),m+=n}return t}var po=Object.create(null);po.parseToElements=cp;po.ByteUtils=q;po.NumberUtils=qc;Object.freeze(po);var op=17825792,Ln=q.allocate(op);import{execFileSync as ap}from"node:child_process";import{existsSync as go,mkdirSync as tp,readdirSync as mp,readFileSync as lo,rmSync as eo,writeFileSync as rc}from"node:fs";import{basename as ft,dirname as cm,join as _,resolve as om}from"node:path";var So=".justo-space.json";function Ot(){return{template:"react-vite-shadcn",version:2,collections:{}}}function wo(){return process.execPath}function jc(c){if(process.platform==="win32")return`${c}.cmd`;return c}var no="iUzDOAFCUx33tmT6OCea",Sc="VITE_JUSTO_MAP_TILER_TOKEN";function bt(){return`import {useState, type FormEvent} from 'react'
686
798
  import {Badge} from '@/components/ui/badge'
687
799
  import {Button} from '@/components/ui/button'
688
800
  import {Card, CardContent, CardDescription, CardHeader, CardTitle} from '@/components/ui/card'
@@ -700,8 +812,8 @@ import {justoCli} from '@/lib/justo'
700
812
  const defaultCommand = 'auth status'
701
813
  const queryExample = "data queries preview <queryId> --params '{\\"limit\\":10}'"
702
814
  const mapTilerToken =
703
- (import.meta.env as {${uc}?: string}).${uc} ||
704
- '${Ca}'
815
+ (import.meta.env as {${Sc}?: string}).${Sc} ||
816
+ '${no}'
705
817
  const chartData = [
706
818
  {day: 'Lun', sessions: 12},
707
819
  {day: 'Mar', sessions: 18},
@@ -912,7 +1024,7 @@ export function App() {
912
1024
  }
913
1025
 
914
1026
  export default App
915
- `}function um(){return`type JustoCliFunction = <T = unknown>(command: string) => Promise<T>
1027
+ `}function Bt(){return`type JustoCliFunction = <T = unknown>(command: string) => Promise<T>
916
1028
  type JustoStreamFunction = <T = unknown>(
917
1029
  command: string,
918
1030
  onRow: (row: T) => Promise<void> | void,
@@ -1054,7 +1166,7 @@ export async function justoStream<T = unknown>(
1054
1166
  }
1055
1167
 
1056
1168
  ensurePreviewWindowJusto()
1057
- `}function Lm(c){return`# ${c}
1169
+ `}function vt(c){return`# ${c}
1058
1170
 
1059
1171
  Starter de Justo Spaces generado por \`team-cli spaces init\`.
1060
1172
 
@@ -1090,7 +1202,7 @@ Tip:
1090
1202
  - después de \`spaces init\`, haz un initial commit para fijar el scaffold base
1091
1203
  - después de cada publish, haz commit para que el repo refleje exactamente lo que quedó publicado
1092
1204
  - 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'\`
1093
- `}function Nm(){return`import {StrictMode} from 'react'
1205
+ `}function xt(){return`import {StrictMode} from 'react'
1094
1206
  import {createRoot} from 'react-dom/client'
1095
1207
  import App from './App.tsx'
1096
1208
  import './index.css'
@@ -1101,13 +1213,13 @@ createRoot(document.getElementById('root')!).render(
1101
1213
  <App />
1102
1214
  </StrictMode>,
1103
1215
  )
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\`:
1216
+ `}function ec(c,o,a){ap(c,o,{cwd:a,stdio:"inherit",env:{...process.env,CI:"1"}})}function sp(c){if(!c)throw Error("Falta --path. Ejemplo: team-cli spaces init --path ./mi-space-app");let o=om(c);if(go(o)){if(mp(o).length>0)throw Error(`La carpeta ya existe y no está vacía: ${o}`);eo(o,{recursive:!0,force:!0})}return tp(cm(o),{recursive:!0}),o}function rp(c){let o=_(c,"vite.config.ts"),a=lo(o,"utf-8");if(a.includes("base: './'"))return;let t=a.replace("export default defineConfig({",`export default defineConfig({
1217
+ base: './',`);rc(o,t)}function pp(c){let o=_(c,"tsconfig.app.json"),t=lo(o,"utf-8").replace('"noUnusedLocals": true,','"noUnusedLocals": false,').replace('"noUnusedParameters": true,','"noUnusedParameters": false,');rc(o,t)}function wp(c){let o=_(c,"package.json"),a=JSON.parse(lo(o,"utf-8"));a.dependencies=a.dependencies||{},a.devDependencies=a.devDependencies||{},a.dependencies.leaflet="^1.9.4",a.dependencies["react-leaflet"]="^5.0.0",a.devDependencies["@types/leaflet"]="^1.9.20",a.justoSpaceApp=!0,rc(o,`${JSON.stringify(a,null,2)}
1218
+ `)}function np(c){let o=_(c,"src","index.css"),a=lo(o,"utf-8");if(a.includes("leaflet/dist/leaflet.css"))return;rc(o,`@import "leaflet/dist/leaflet.css";
1219
+ ${a}`)}function gp(c){let o=ft(c);rc(_(c,"README.md"),vt(o)),rc(_(c,"src","App.tsx"),bt()),rc(_(c,"src","main.tsx"),xt()),rc(_(c,"src","lib","justo.ts"),Bt()),rc(_(c,So),`${JSON.stringify(Ot(),null,2)}
1220
+ `),eo(_(c,".git"),{recursive:!0,force:!0})}function lp(c){ec("git",["init"],c)}function Cp(c){eo(_(c,"package-lock.json"),{force:!0})}function No(c){let o=om(c);if(!go(o))throw Error(`No existe la app del space: ${o}`);if(!go(_(o,So)))throw Error("Este publish solo acepta apps creadas con team-cli spaces init. Debes apuntar al root de esa app.");return o}function am(c){let o=No(c);ec(jc("yarn"),["build"],o);let a=_(o,"dist");if(!go(_(a,"index.html")))throw Error("El build no generó dist/index.html");return a}function tm(c){let o=sp(c),a=cm(o),t=ft(o);return ec(jc("npx"),["shadcn@latest","init","-t","vite","-d","-y","-n",t],a),ec(jc("npx"),["shadcn@latest","add","-a","-y"],o),Cp(o),wp(o),ec(jc("yarn"),["install"],o),rp(o),pp(o),np(o),gp(o),lp(o),{path:o,nextSteps:[`cd ${o}`,'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 pm,readFileSync as wm,statSync as nm}from"node:fs";import{gzipSync as Wp}from"node:zlib";import{join as gm,relative as lm,resolve as sm}from"node:path";import{existsSync as $p,readFileSync as qp}from"node:fs";import{join as jp}from"node:path";var Qp=[".git","node_modules","dist",".justo-space-preview",".DS_Store"];function Ap(c){return c.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}function Jp(c){let o="";for(let a=0;a<c.length;a++){let t=c[a],m=c[a+1];if(t==="*"){if(m==="*"){o+=".*",a+=1;continue}o+="[^/]*";continue}if(t==="?"){o+="[^/]";continue}o+=Ap(t)}return o}function Rp(c){let o=c.trim();if(!o||o.startsWith("#"))return null;let a=o.startsWith("!"),t=a?o.slice(1).trim():o;if(!t)return null;let m=t.endsWith("/"),s=t.replace(/^\/+/,"").replace(/\/+$/,"");if(!s)return null;let r=s.includes("/"),w=Jp(s),n=r?`^${w}${m?"(?:/.*)?":""}$`:`(?:^|/)${w}${m?"(?:/.*)?":"(?:$|/)"}`;return{negate:a,directoryOnly:m,regex:new RegExp(n)}}function Pp(c){let o=jp(c,".gitignore"),a=[...Qp];if($p(o))a.push(...qp(o,"utf-8").split(/\r?\n/));return a.map(Rp).filter((t)=>Boolean(t))}function mm(c){let o=Pp(c);return(a,t)=>{let m=a.replaceAll("\\","/").replace(/^\/+/,""),s=!1;for(let r of o){if(!r.regex.test(m))continue;s=!r.negate}return s}}var Co=512,Gp=2,Mp="repo",Ip="dist";function Xp(c){let o=c.replaceAll("\\","/");if(o.startsWith("/")||o.includes("../"))throw Error(`Ruta inválida en el space: ${c}`);return o}function Zp(c){let o=Xp(c);if(Buffer.from(o).length<=100)return{name:o,prefix:""};let t=o.lastIndexOf("/");if(t<=0)throw Error(`La ruta es demasiado larga para el paquete del space: ${c}`);let m=o.slice(0,t),s=o.slice(t+1);if(Buffer.from(m).length>155||Buffer.from(s).length>100)throw Error(`La ruta es demasiado larga para el paquete del space: ${c}`);return{name:s,prefix:m}}function Qc(c,o,a,t){let m=Buffer.from(t);m.copy(c,o,0,Math.min(m.length,a))}function Nc(c,o,a,t){let m=Math.max(0,Math.trunc(t)).toString(8).padStart(a-1,"0");Qc(c,o,a,`${m}\x00`)}function Hp(c){let o=Buffer.alloc(Co,0),{name:a,prefix:t}=Zp(c.path);Qc(o,0,100,a),Nc(o,100,8,c.mode),Nc(o,108,8,0),Nc(o,116,8,0),Nc(o,124,12,c.content.length),Nc(o,136,12,c.mtime),o.fill(32,148,156),Qc(o,156,1,"0"),Qc(o,257,6,"ustar"),Qc(o,263,2,"00"),Qc(o,345,155,t);let m=0;for(let r of o)m+=r;let s=`${m.toString(8).padStart(6,"0")}\x00 `;return Qc(o,148,8,s),o}function Fp(c){let o=c%Co;return o===0?0:Co-o}function Cm(c,o=c){return pm(o,{withFileTypes:!0}).sort((t,m)=>t.name.localeCompare(m.name)).flatMap((t)=>{let m=gm(o,t.name);if(t.isDirectory())return Cm(c,m);if(!t.isFile())return[];let s=lm(c,m),r=nm(m);return[{path:s,content:wm(m),mode:r.mode&511,mtime:Math.floor(r.mtimeMs/1000)}]})}function rm(c,o){return c.map((a)=>({...a,path:`${o}/${a.path.replaceAll("\\","/")}`}))}function $m(c,o=c){let a=mm(c);return pm(o,{withFileTypes:!0}).sort((m,s)=>m.name.localeCompare(s.name)).flatMap((m)=>{let s=gm(o,m.name),r=lm(c,s).replaceAll("\\","/");if(a(r,m.isDirectory()))return[];if(m.isDirectory())return $m(c,s);if(!m.isFile())return[];let w=nm(s);return[{path:r,content:wm(s),mode:w.mode&511,mtime:Math.floor(w.mtimeMs/1000)}]})}function qm(c,o){let a=sm(c),t=sm(o),m=[...rm($m(a),Mp),...rm(Cm(t),Ip)];if(!m.length)throw Error("El build del space no contiene archivos para publicar");let s=[];for(let r of m){s.push(Hp(r)),s.push(r.content);let w=Fp(r.content.length);if(w>0)s.push(Buffer.alloc(w,0))}return s.push(Buffer.alloc(Co*Gp,0)),Wp(Buffer.concat(s))}import{mkdirSync as jm,writeFileSync as Yp}from"node:fs";import{dirname as hp,join as Up,normalize as Tp,sep as Qm}from"node:path";import{gunzipSync as ip}from"node:zlib";var dc=512;function $o(c,o,a){let t=c.subarray(o,o+a),m=t.indexOf(0);return(m>=0?t.subarray(0,m):t).toString("utf-8").trim()}function Kp(c,o,a){let t=$o(c,o,a).replaceAll("\x00","").trim();if(!t)return 0;return Number.parseInt(t,8)}function _p(c){let o=c%dc;return o===0?0:dc-o}function Ep(c){let o=$o(c,0,100),a=$o(c,345,155);return a?`${a}/${o}`:o}function up(c){let o=Tp(c);if(!c||c.startsWith("/")||o.startsWith("..")||o.includes(`${Qm}..${Qm}`)||o==="..")throw Error("El paquete del space contiene rutas inválidas")}function Am(c,o,a){let t=ip(c),m=o.replaceAll("\\","/").replace(/^\/+|\/+$/g,""),s=`${m}/`,r=0,w=0;while(r+dc<=t.length){let n=t.subarray(r,r+dc),l=n.every((Z)=>Z===0);if(r+=dc,l)break;let g=Ep(n),j=$o(n,156,1)||"0",J=Kp(n,124,12),F=t.subarray(r,r+J);if(r+=J+_p(J),!g.startsWith(s))continue;let A=g.slice(s.length);if(!A)continue;up(A);let P=Up(a,...A.split("/"));if(j==="5"){jm(P,{recursive:!0});continue}if(j!=="0")continue;jm(hp(P),{recursive:!0}),Yp(P,F),w+=1}if(!w)throw Error(`El paquete del space no contiene la carpeta ${m}/`);return w}import{spawn as jo}from"node:child_process";import{createServer as Xm}from"node:http";import{existsSync as kp,mkdirSync as Dp,openSync as Vp,readFileSync as yp,rmSync as zp,writeFileSync as Sp}from"node:fs";import{dirname as ep,join as Qo,resolve as Zm}from"node:path";import{request as Np}from"node:http";import{request as dp}from"node:https";function Jm(c){let o=[],a="",t=null,m=!1;for(let s of c){if(m){a+=s,m=!1;continue}if(s==="\\"){m=!0;continue}if(t){if(s===t)t=null;else a+=s;continue}if(s==='"'||s==="'"){t=s;continue}if(/\s/.test(s)){if(a)o.push(a),a="";continue}a+=s}if(t)throw Error("Comando inválido: falta cerrar una comilla");if(a)o.push(a);return o}var Lp=".justo-space-preview",Op="preview.json",bp=30000;function Ao(c){return Qo(c,Lp)}function Hm(c){return Qo(Ao(c),Op)}function Rm(c){return Qo(Ao(c),"bridge.log")}function Pm(c){return Qo(Ao(c),"vite.log")}function Fm(c){Dp(Ao(c),{recursive:!0})}function qo(c){if(!c)return;try{process.kill(c,"SIGTERM")}catch{return}}function Bp(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 vp(c,o){if(!o)return{attempted:!1,opened:!1};let a=Bp(c);return await new Promise((t)=>{let m=jo(a.command,a.args,{stdio:"ignore",detached:!0});m.once("error",()=>{t({attempted:!0,opened:!1,message:"No se pudo abrir el navegador por defecto automáticamente. Abre la URL manualmente."})}),m.once("spawn",()=>{m.unref(),t({attempted:!0,opened:!0})})})}function xp(c){let o=Hm(c);if(!kp(o))return;try{let a=JSON.parse(yp(o,"utf-8"));qo(a.appPid),qo(a.bridgePid)}catch{}zp(o,{force:!0})}function Wm(){return new Promise((c,o)=>{let a=Xm();a.listen(0,"127.0.0.1",()=>{let t=a.address();if(!t||typeof t==="string"){a.close(),o(Error("No se pudo obtener un puerto libre"));return}let{port:m}=t;a.close((s)=>{if(s){o(s);return}c(m)})}),a.on("error",o)})}function Gm(c){return new Promise((o)=>setTimeout(o,c))}function fp(c){return new Promise((o,a)=>{let s=(new URL(c).protocol==="https:"?dp:Np)(c,{method:"GET"},(r)=>{o(r.statusCode||0),r.resume()});s.on("error",a),s.end()})}async function Mm(c,o=bp){let a=Date.now();while(Date.now()-a<o){try{if(await fp(c)>0)return}catch{await Gm(500);continue}await Gm(500)}throw Error(`Timeout esperando que el preview responda en ${c}`)}function cw(c){return Fm(ep(c)),Vp(c,"a")}function Im(c,o,a,t,m){let s=cw(t),r=jo(c,o,{cwd:a,detached:!0,stdio:["ignore",s,s],env:{...process.env,...m}});if(!r.pid)throw Error(`No se pudo iniciar el proceso ${c}`);return r.unref(),r.pid}function Ym(){let c=na("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 ow(c){let o=[];for await(let a of c)o.push(Buffer.isBuffer(a)?a:Buffer.from(a));return Buffer.concat(o).toString("utf-8")}function Lc(c,o,a){c.writeHead(o,{"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(a))}function Lo(c){let o=c.trim(),a=new Set([0]);for(let m=0;m<o.length;m++)if(o[m]==="{"||o[m]==="[")a.add(m);let t=[...a].sort((m,s)=>s-m);for(let m of t)try{return JSON.parse(o.slice(m))}catch{continue}return o}function hm(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 aw(c,o){return{VITE_JUSTO_CLI_ENDPOINT:c,VITE_JUSTO_STREAM_ENDPOINT:o,VITE_JUSTO_CLI_MODE:"preview",[Sc]:no}}function tw(c,o,a,t){return new Promise((m,s)=>{let r=jo(wo(),[o,"--env","prod",...t,"--format","json"],{cwd:process.cwd(),env:hm(a),stdio:["ignore","pipe","pipe"]}),w="";r.stdout.on("data",(n)=>{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(n)}),r.stderr.on("data",(n)=>{w+=Buffer.from(n).toString("utf-8")}),r.on("error",s),r.on("close",(n)=>{if(!n){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(),m();return}let l=Lo(w.trim());s(Error(l.error||w.trim()||"justoStream failed"))})})}async function Um(c){let o=Number(c.port);if(!o)throw Error("Falta --port para el bridge interno de preview");let a=Ym(),t=Zm(c["cli-path"]||process.argv[1]||""),m=Xm(async(s,r)=>{if(s.method==="OPTIONS"){Lc(r,200,{ok:!0});return}if(s.method==="GET"&&s.url==="/__justo/health"){Lc(r,200,{ok:!0});return}if(s.method!=="POST"||s.url!=="/__justo/cli"&&s.url!=="/__justo/stream"){Lc(r,404,{ok:!1,error:"Not found"});return}try{let w=await ow(s),l=JSON.parse(w||"{}").command;if(!l)throw Error("Debes indicar un comando");let g=Array.isArray(l)?l:Jm(l);if(s.url==="/__justo/stream"){await tw(r,t,a,g);return}let j=await new Promise((J,F)=>{let A=jo(wo(),[t,"--env","prod",...g,"--format","json"],{cwd:process.cwd(),env:hm(a),stdio:["ignore","pipe","pipe"]}),P=[],Z=[];A.stdout.on("data",(G)=>P.push(Buffer.from(G))),A.stderr.on("data",(G)=>Z.push(Buffer.from(G))),A.on("error",F),A.on("close",(G)=>{let T=Buffer.concat(P).toString("utf-8")||Buffer.concat(Z).toString("utf-8");if(G&&G!==0){let $=Lo(T);F(Error($.error||T||"justoCli failed"));return}J(Lo(T))})});Lc(r,200,{result:j})}catch(w){let n=w instanceof Error?w.message:"Unexpected error";Lc(r,400,{error:n})}});await new Promise((s,r)=>{m.listen(o,"127.0.0.1",()=>s()),m.on("error",r)}),k(`Space preview bridge listening on http://127.0.0.1:${o}
1221
+ `),await new Promise((s,r)=>{m.on("close",()=>s()),m.on("error",r)})}async function Tm(c){let o=c.path;if(!o)throw Error("Falta --path. Ejemplo: team-cli spaces preview --path ./mi-space-app");let a=No(o);Ym(),Fm(a),xp(a);let t=Number(c.port)||await Wm(),m=Number(c["bridge-port"])||await Wm(),s=c.open==="true",r=`http://127.0.0.1:${t}`,w=`http://127.0.0.1:${m}/__justo/cli`,n=`http://127.0.0.1:${m}/__justo/stream`,l=Zm(process.argv[1]||""),g=Im(wo(),[l,"__spaces-preview-bridge","--port",String(m),"--cli-path",l],process.cwd(),Rm(a),{}),j=Im(jc("yarn"),["dev","--host","127.0.0.1","--port",String(t)],a,Pm(a),aw(w,n));try{await Mm(`http://127.0.0.1:${m}/__justo/health`),await Mm(r)}catch(A){throw qo(j),qo(g),A}let J={appPid:j,bridgePid:g,previewUrl:r,bridgeUrl:w,streamUrl:n,cliEnv:"prod"};Sp(Hm(a),`${JSON.stringify(J,null,2)}
1222
+ `);let F=await vp(r,s);return{ok:!0,path:a,previewUrl:r,bridgeUrl:w,streamUrl:n,cliEnv:"prod",appPid:j,bridgePid:g,logs:{app:Pm(a),bridge:Rm(a)},open:F}}function pw(c){try{return gc.parse(c)}catch{throw Error("El valor de --operation debe ser JSON/EJSON válido")}}function Oc(){if(!Y())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 lc(c,o,a){let t=c[o];if(!t)throw Error(`Falta --${o}. Ejemplo: ${a}`);return t}function Km(c,o){let a=c[2];if(!a)throw Error(`Uso: ${o}`);return a}function Oo(){let c=Wc();if(c==="local")return"http://intra.localhost:5173";if(c==="develop")return"https://intra.bejusto.com";return"https://intra.getjusto.com"}function ww(){return`Configuración de collections en \`.justo-space.json\`:
1111
1223
  - \`spaces publish\` lee \`repo/.justo-space.json\`, valida \`collections\` y sincroniza índices
1112
1224
  - cada collection lógica debe existir en \`collections\`
1113
1225
  - los nombres válidos usan solo letras, números y guion bajo
@@ -1146,7 +1258,7 @@ Reglas de índices:
1146
1258
  - cada índice debe tener \`name\` y \`key\`
1147
1259
  - puedes usar opciones comunes de Mongo como \`unique\`, \`sparse\`, \`expireAfterSeconds\` y \`partialFilterExpression\`
1148
1260
  - 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
1261
+ `}function nw(){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 gw(c,o){let a=await oo(),t=await fetch(`${U("data")}/spaces/publish/${c}`,{method:"POST",headers:{"Content-Type":"application/gzip",...a?{"X-ORION-JWT":a}:{}},body:o}),m=await t.json();if(!t.ok||m.error)throw Error(m.error||"No se pudo publicar el space.");return m}async function lw(c){let o=await oo(),a=await fetch(`${U("data")}/spaces/fork/${c}`,{method:"GET",headers:o?{"X-ORION-JWT":o}:{}});if(!a.ok){let t=await a.json().catch(()=>({}));throw Error(t.error||"No se pudo descargar el repo del space.")}return Buffer.from(await a.arrayBuffer())}function Cw(c){let o=im(c);if(mw(o)&&rw(o).length>0)throw Error(`La carpeta ya existe y no está vacía: ${o}`);return sw(o,{recursive:!0}),o}function bo(){return`team-cli spaces
1150
1262
 
1151
1263
  Spaces son aplicaciones internas en React, pensadas para que las construyan agentes.
1152
1264
  El flujo oficial parte con \`spaces init\` y \`spaces publish\` solo acepta apps creadas así.
@@ -1172,9 +1284,9 @@ Cada space:
1172
1284
  - el archivo \`.justo-space.json\` puede declarar \`collections\` para que el publish sincronice índices en Mongo
1173
1285
  - esas collections se exponen con \`team-cli spaces db\` usando el prefijo físico \`spaces.<slug_sanitized>.<collection>\`
1174
1286
 
1175
- ${Or()}
1287
+ ${ww()}
1176
1288
 
1177
- ${br()}
1289
+ ${nw()}
1178
1290
 
1179
1291
  Flujo sugerido para agentes:
1180
1292
  1. \`team-cli spaces init --path ./mi-space-app\`
@@ -1184,7 +1296,7 @@ Flujo sugerido para agentes:
1184
1296
  5. desarrollar la app React dentro de esa carpeta
1185
1297
  6. \`team-cli spaces publish <spaceId> --path ./mi-space-app\`
1186
1298
  7. hacer commit del repo después de publicar
1187
- 8. abrir \`${da()}/spaces/<slug>\`
1299
+ 8. abrir \`${Oo()}/spaces/<slug>\`
1188
1300
  9. si necesitas retomarlo en otra carpeta: \`team-cli spaces fork <slug> --path ./mi-space-app\`
1189
1301
 
1190
1302
  Slugs:
@@ -1258,7 +1370,7 @@ Comandos:
1258
1370
  - \`spaces fork <slug> --path ./mi-space-app\`
1259
1371
  - \`spaces archive <spaceId>\`
1260
1372
  - \`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) {
1373
+ `}async function _m(c){let o=lc(c,"path","team-cli spaces init --path ./mi-space-app");return tm(o)}async function Em(c){return await Tm(c)}async function um(c){Oc();let o=lc(c,"name","team-cli spaces create --name 'Mi space' --description '...' --slug dashboard-1234"),a=lc(c,"description","team-cli spaces create --name 'Mi space' --description 'Sitio interno' --slug dashboard-1234"),t=lc(c,"slug","team-cli spaces create --name 'Mi space' --description '...' --slug dashboard-1234"),m=await R({service:"data",query:`mutation ($name: String, $description: String, $slug: String) {
1262
1374
  createSpace(name: $name, description: $description, slug: $slug) {
1263
1375
  _id
1264
1376
  name
@@ -1269,7 +1381,7 @@ Comandos:
1269
1381
  createdByEmail
1270
1382
  createdById
1271
1383
  }
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) {
1384
+ }`,variables:{name:o,description:a,slug:t}});return{...m.createSpace,intraUrl:`${Oo()}/spaces/${m.createSpace.slug}`,serveUrl:`${U("data")}/spaces/${m.createSpace.slug}`}}async function km(c,o){Oc();let a=Km(c,"team-cli spaces publish <spaceId> --path ./mi-space-app"),t=lc(o,"path","team-cli spaces publish <spaceId> --path ./mi-space-app"),m=am(t),s=qm(t,m),r=await gw(a,s);return{...r,intraUrl:r.slug?`${Oo()}/spaces/${r.slug}`:void 0,serveUrl:r.slug?`${U("data")}/spaces/${r.slug}`:void 0,builtFrom:im(t)}}async function Dm(c,o){Oc();let a=c[2];if(!a)throw Error("Uso: team-cli spaces fork <slug> --path ./mi-space-app");let t=Cw(o.path||`./${a}`),m=await lw(a),s=Am(m,"repo",t);return{ok:!0,slug:a,path:t,extractedFiles:s,nextSteps:[`cd ${t}`,"yarn install","team-cli spaces preview --path . --open"]}}async function Vm(c){Oc();let o=Km(c,"team-cli spaces archive <spaceId>");return(await R({service:"data",query:`mutation ($spaceId: String) {
1273
1385
  archiveSpace(spaceId: $spaceId) {
1274
1386
  _id
1275
1387
  name
@@ -1281,7 +1393,7 @@ Comandos:
1281
1393
  createdById
1282
1394
  archivedAt
1283
1395
  }
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
1396
+ }`,variables:{spaceId:o}})).archiveSpace}async function ym(c){Oc();let o=lc(c,"slug",`team-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{"type":"find","filter":{}}'`),a=lc(c,"collection",`team-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{"type":"find","filter":{}}'`),t=lc(c,"operation",`team-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{"type":"find","filter":{}}'`),m=gc.serialize(pw(t)),s=await Gc(),r=await fetch(`${U("data")}/spaces/${encodeURIComponent(o)}/db`,{method:"POST",headers:s,body:JSON.stringify({collection:a,operation:m})}),w=await r.json().catch(()=>({}));if(!r.ok||w.error)throw Error(w.error||"No se pudo ejecutar spaces db");return w.result}function zm(c){return`team-cli
1285
1397
 
1286
1398
  Herramienta CLI para el equipo Justo.
1287
1399
 
@@ -1342,4 +1454,4 @@ Si todavía no sabes bien dónde vive la data, primero usa \`data explain\` para
1342
1454
  Cuando ya tengas claro un pipeline y solo quieras probarlo una vez, usa \`data execute\`.
1343
1455
  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\`.
1344
1456
 
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();
1457
+ `}function Sm(){let c=Y(),o=c?`Sesión: ${c.email}`:"Sesión: no iniciada";return zm(o)}async function em(c){let{positional:o,flags:a}=bc(c);if(a.env)sa(a.env);let t=o[0],m=o[1];if(t==="__spaces-preview-bridge")return await Um(a);if(a.version)return{version:"0.0.14"};if(a.help&&!t)return Sm();if(t==="auth"){if(m==="--help"||a.help)return Zo();if(m==="login")return await ua();if(m==="login-with-token")return await ka(a);if(m==="request-code")return await Da(a);if(m==="logout")return await Va();if(m==="status")return await ya();return Zo()}if(t==="admin"){let s=o[1],r=o[2],w=o[3],n=o[4];if(!s||s==="--help")return ao();if(s==="search"&&a.help)return ia();if(s==="search")return await Ta(o,a);if(!r||r==="--help")return ao();if(r==="show")return await ja(s);if(r==="stores"&&w==="list")return await Ka(s);if(r==="coupons"&&(!w||w==="--help"))return kc();if(r==="coupons"&&w==="create"&&a.help)return ha();if(r==="coupons"&&w==="update"&&a.help)return Ua();if(r==="coupons"&&w==="codes"&&o[4]==="create"&&a.help)return Ma();if(r==="coupons"&&a.help)return kc();if(r==="coupons"&&w==="list")return await Xa(s,a);if(r==="coupons"&&w==="show"){if(!n)throw Error("Uso: team-cli admin <web> coupons show <couponId>");return await Za(s,n)}if(r==="coupons"&&w==="create")return await Ha(s,a);if(r==="coupons"&&w==="update"){if(!n)throw Error("Uso: team-cli admin <web> coupons update <couponId> --input '<json>'");return await Fa(s,n,a)}if(r==="coupons"&&w==="delete"){if(!n)throw Error("Uso: team-cli admin <web> coupons delete <couponId>");return await Ya(s,n)}if(r==="coupons"&&w==="codes"){let l=o[4],g=o[5];if(!l||l==="--help")return kc();if(l==="list"){if(!g)throw Error("Uso: team-cli admin <web> coupons codes list <couponId>");return await Ra(s,g,a)}if(l==="create"){if(!g)throw Error("Uso: team-cli admin <web> coupons codes create <couponId> --input '<json>'");return await Pa(s,g,a)}if(l==="create-random"){if(!g)throw Error("Uso: team-cli admin <web> coupons codes create-random <couponId> --quantity <n>");return await Wa(s,g,a)}if(l==="delete"){if(!g)throw Error(`Uso: team-cli admin <web> coupons codes delete <couponId> --ids '["id1"]'`);return await Ga(s,g,a)}return kc()}return ao()}if(t==="graphql"){if(m==="--help"||a.help)return Pt();return await Jt(o,a)}if(t==="data"){let s=o[1],r=o[2];if(a.help||m==="--help")return To();if(s==="explain")return await fa(a);if(s==="execute")return await ct(a);if(s==="queries"&&r==="create")return await xa();if(s==="queries"&&r==="edit")return await ot(o);if(s==="queries"&&r==="ai-edit")return await at(o,a);if(s==="queries"&&r==="view")return await tt(o);if(s==="queries"&&r==="view-pipeline")return await mt(o);if(s==="queries"&&r==="preview")return await st(o,a);if(s==="queries"&&r==="run")return await rt(o,a);if(s==="queries"&&r==="add-viewers")return await pt(o,a);if(s==="queries"&&r==="download")return await wt(o,a);return To()}if(t==="spaces"){let s=o[1];if(!s||s==="--help"||a.help)return bo();if(s==="init")return await _m(a);if(s==="create")return await um(a);if(s==="preview")return await Em(a);if(s==="publish")return await km(o,a);if(s==="fork")return await Dm(o,a);if(s==="archive")return await Vm(o);if(s==="db")return await ym(a);return bo()}return Sm()}var{flags:Nm}=bc(process.argv.slice(2));async function $w(){try{let c=await em(process.argv.slice(2));if(c&&typeof c==="object"&&"__streamHandled"in c&&c.__streamHandled)return;if(typeof c==="string"){ta(c);return}aa(c,Nm)}catch(c){ma(c,Nm),process.exit(1)}}$w();