@getjusto/team-cli 0.0.12 → 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.
- package/bin/cli.js +242 -86
- package/package.json +1 -1
package/bin/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
function
|
|
3
|
-
`)}function
|
|
4
|
-
`)}function
|
|
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=[],m={},o={};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(!
|
|
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
|
|
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
|
-
`,
|
|
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
|
-
${
|
|
89
|
+
${Qa}
|
|
90
90
|
}
|
|
91
91
|
scheduleAtUse {
|
|
92
|
-
${
|
|
92
|
+
${Qa}
|
|
93
93
|
}
|
|
94
94
|
codesCode
|
|
95
|
-
`,
|
|
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
|
|
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(!
|
|
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
|
-
${
|
|
112
|
+
${Aa}
|
|
113
113
|
}
|
|
114
114
|
totalCount
|
|
115
115
|
totalPages
|
|
116
116
|
hasNextPage
|
|
117
117
|
hasPreviousPage
|
|
118
118
|
}
|
|
119
|
-
}`,variables:{couponId:
|
|
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:
|
|
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:
|
|
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:
|
|
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
|
|
149
|
-
createCoupon(${
|
|
150
|
-
${
|
|
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
|
|
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:
|
|
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
|
-
${
|
|
174
|
+
${to}
|
|
175
175
|
}
|
|
176
|
-
}`,variables:{couponId:
|
|
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
|
-
${
|
|
178
|
+
${to}
|
|
179
179
|
}
|
|
180
|
-
}`,variables:{couponId:
|
|
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:[
|
|
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
|
|
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
|
|
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
|
|
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:
|
|
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
|
|
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:
|
|
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
|
|
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:
|
|
377
|
-
`);let
|
|
378
|
-
`);let
|
|
379
|
-
`);let
|
|
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
|
|
406
|
-
`);let
|
|
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
|
|
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:
|
|
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:
|
|
433
|
-
`);while(
|
|
434
|
-
`)}}let
|
|
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:
|
|
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:
|
|
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
|
|
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(!
|
|
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(!
|
|
503
|
-
`);try{let
|
|
504
|
-
`);let
|
|
505
|
-
`);let
|
|
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:
|
|
508
|
-
`);let
|
|
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:
|
|
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
|
|
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'`}
|
|
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
|
|
628
|
-
`)}function
|
|
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: ${
|
|
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
|
-
${m}`}import{existsSync as Np,mkdirSync as up,readdirSync as Op}from"node:fs";import{resolve as Ms}from"node:path";import{randomBytes as ft}from"crypto";var cw=(()=>{let c=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag).get;return(a)=>c.call(a)})();function Mo(c){return cw(c)==="Uint8Array"}function aw(c){return typeof c==="object"&&c!=null&&Symbol.toStringTag in c&&(c[Symbol.toStringTag]==="ArrayBuffer"||c[Symbol.toStringTag]==="SharedArrayBuffer")}function mw(c){return c instanceof RegExp||Object.prototype.toString.call(c)==="[object RegExp]"}function Ho(c){return typeof c==="object"&&c!=null&&Symbol.toStringTag in c&&c[Symbol.toStringTag]==="Map"}function ow(c){return c instanceof Date||Object.prototype.toString.call(c)==="[object Date]"}function y(c,a){return JSON.stringify(c,(m,o)=>{if(typeof o==="bigint")return{$numberLong:`${o}`};else if(Ho(o))return Object.fromEntries(o);return o})}function sw(c){if(c!=null&&typeof c==="object"&&"stylize"in c&&typeof c.stylize==="function")return c.stylize}var za=6,Yo=Symbol.for("@@mdb.bson.version"),ya=2147483647,Sa=-2147483648,Fo=Math.pow(2,63)-1,Uo=-Math.pow(2,63),tw=Math.pow(2,53),ww=-Math.pow(2,53);var To=4,RC=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 no 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,m){super(`${c}. offset: ${a}`,m);this.offset=a}}var $o,Qo;function ho(c,a,m,o){if(o){$o??=new TextDecoder("utf8",{fatal:!0});try{return $o.decode(c.subarray(a,m))}catch(s){throw new $("Invalid UTF-8 string in BSON document",{cause:s})}}return Qo??=new TextDecoder("utf8",{fatal:!1}),Qo.decode(c.subarray(a,m))}function Ko(c,a,m){if(c.length===0)return"";let o=m-a;if(o===0)return"";if(o>20)return null;if(o===1&&c[a]<128)return String.fromCharCode(c[a]);if(o===2&&c[a]<128&&c[a+1]<128)return String.fromCharCode(c[a])+String.fromCharCode(c[a+1]);if(o===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<m;t++){let w=c[t];if(w>127)return null;s.push(w)}return String.fromCharCode(...s)}function pw(c,a,m){if(a.length===0)return 0;if(a.length>25)return null;if(c.length-m<a.length)return null;for(let o=0,s=m;o<a.length;o++,s++){let t=a.charCodeAt(o);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,m,o){let s=m-a<=20?Ko(c,a,m):null;if(s!=null)return s;let t=Cc.toLocalBufferType(c).toString("utf8",a,m);if(o){for(let w=0;w<t.length;w++)if(t.charCodeAt(w)===65533){ho(c,a,m,!0);break}}return t},utf8ByteLength(c){return Buffer.byteLength(c,"utf8")},encodeUTF8Into(c,a,m){let o=pw(c,a,m);if(o!=null)return o;return Cc.toLocalBufferType(c).write(a,m,void 0,"utf8")},randomBytes:ft,swap32(c){return Cc.toLocalBufferType(c).swap32()}};function rw(){let{navigator:c}=globalThis;return typeof c==="object"&&c.product==="ReactNative"}function Cw(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 qw=(()=>{let{crypto:c}=globalThis;if(c!=null&&typeof c.getRandomValues==="function")return(a)=>{return c.getRandomValues(yc.allocate(a))};else{if(rw()){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 Cw}})(),jo=/(\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 m=0;m<c.byteLength;m++)if(c[m]!==a[m])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),m=[];for(let o=0;o<a.length;o+=2){let s=a[o],t=a[o+1];if(!jo.test(s))break;if(!jo.test(t))break;let w=Number.parseInt(`${s}${t}`,16);m.push(w)}return Uint8Array.from(m)},toHex(c){return Array.from(c,(a)=>a.toString(16).padStart(2,"0")).join("")},toUTF8(c,a,m,o){let s=m-a<=20?Ko(c,a,m):null;if(s!=null)return s;return ho(c,a,m,o)},utf8ByteLength(c){return new TextEncoder().encode(c).byteLength},encodeUTF8Into(c,a,m){let o=new TextEncoder().encode(a);return c.set(o,m),o.byteLength},randomBytes:qw,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 m=c[a],o=c[a+1],s=c[a+2],t=c[a+3];c[a]=t,c[a+1]=s,c[a+2]=o,c[a+3]=m}return c}},gw=typeof Buffer==="function"&&Buffer.prototype?._isBuffer!==!0,j=gw?Cc:yc;class S{get[Yo](){return za}[Symbol.for("nodejs.util.inspect.custom")](c,a,m){return this.inspect(c,a,m)}}var Fc=new Float64Array(1),G=new Uint8Array(Fc.buffer,0,8);Fc[0]=-1;var Ka=G[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 m=BigInt(c[a+4]+c[a+5]*256+c[a+6]*65536+(c[a+7]<<24)),o=BigInt(c[a]+c[a+1]*256+c[a+2]*65536+c[a+3]*16777216);return(m<<BigInt(32))+o},getFloat64LE:Ka?(c,a)=>{return G[7]=c[a],G[6]=c[a+1],G[5]=c[a+2],G[4]=c[a+3],G[3]=c[a+4],G[2]=c[a+5],G[1]=c[a+6],G[0]=c[a+7],Fc[0]}:(c,a)=>{return G[0]=c[a],G[1]=c[a+1],G[2]=c[a+2],G[3]=c[a+3],G[4]=c[a+4],G[5]=c[a+5],G[6]=c[a+6],G[7]=c[a+7],Fc[0]},setInt32BE(c,a,m){return c[a+3]=m,m>>>=8,c[a+2]=m,m>>>=8,c[a+1]=m,m>>>=8,c[a]=m,4},setInt32LE(c,a,m){return c[a]=m,m>>>=8,c[a+1]=m,m>>>=8,c[a+2]=m,m>>>=8,c[a+3]=m,4},setBigInt64LE(c,a,m){let o=BigInt(4294967295),s=Number(m&o);c[a]=s,s>>=8,c[a+1]=s,s>>=8,c[a+2]=s,s>>=8,c[a+3]=s;let t=Number(m>>BigInt(32)&o);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,m)=>{return Fc[0]=m,c[a]=G[7],c[a+1]=G[6],c[a+2]=G[5],c[a+3]=G[4],c[a+4]=G[3],c[a+5]=G[2],c[a+6]=G[1],c[a+7]=G[0],8}:(c,a,m)=>{return Fc[0]=m,c[a]=G[0],c[a+1]=G[1],c[a+2]=G[2],c[a+3]=G[3],c[a+4]=G[4],c[a+5]=G[5],c[a+6]=G[6],c[a+7]=G[7],8}};class A extends S{get _bsontype(){return"Binary"}constructor(c,a){super();if(c!=null&&typeof c==="string"&&!ArrayBuffer.isView(c)&&!aw(c)&&!Array.isArray(c))throw new $("Binary can only be constructed from Uint8Array or number[]");if(this.sub_type=a??A.BSON_BINARY_SUBTYPE_DEFAULT,c==null)this.buffer=j.allocate(A.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 m=j.allocate(A.BUFFER_SIZE+this.buffer.length);m.set(this.buffer,0),this.buffer=m,this.buffer[this.position++]=a}}write(c,a){if(a=typeof a==="number"?a:this.position,this.buffer.byteLength<a+c.length){let m=j.allocate(this.buffer.byteLength+c.length);m.set(this.buffer,0),this.buffer=m}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 m=c+a;return this.buffer.subarray(c,m>this.position?this.position:m)}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===A.SUBTYPE_VECTOR)rc(this);let a=j.toBase64(this.buffer),m=Number(this.sub_type).toString(16);if(c.legacy)return{$binary:a,$type:m.length===1?"0"+m:m};return{$binary:{base64:a,subType:m.length===1?"0"+m:m}}}toUUID(){if(this.sub_type===A.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 "${A.SUBTYPE_UUID}" is currently supported.`)}static createFromHexString(c,a){return new A(j.fromHex(c),a)}static createFromBase64(c,a){return new A(j.fromBase64(c),a)}static fromExtendedJSON(c,a){a=a||{};let m,o;if("$binary"in c){if(a.legacy&&typeof c.$binary==="string"&&"$type"in c)o=c.$type?parseInt(c.$type,16):0,m=j.fromBase64(c.$binary);else if(typeof c.$binary!=="string")o=c.$binary.subType?parseInt(c.$binary.subType,16):0,m=j.fromBase64(c.$binary.base64)}else if("$uuid"in c)o=4,m=_.bytesFromString(c.$uuid);if(!m)throw new $(`Unexpected Binary Extended JSON format ${JSON.stringify(c)}`);return o===To?new _(m):new A(m,o)}inspect(c,a,m){m??=y;let o=j.toBase64(this.buffer.subarray(0,this.position)),s=m(o,a),t=m(this.sub_type,a);return`Binary.createFromBase64(${s}, ${t})`}toInt8Array(){if(this.sub_type!==A.SUBTYPE_VECTOR)throw new $("Binary sub_type is not Vector");if(this.buffer[0]!==A.VECTOR_TYPE.Int8)throw new $("Binary datatype field is not Int8");return rc(this),new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toFloat32Array(){if(this.sub_type!==A.SUBTYPE_VECTOR)throw new $("Binary sub_type is not Vector");if(this.buffer[0]!==A.VECTOR_TYPE.Float32)throw new $("Binary datatype field is not Float32");rc(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!==A.SUBTYPE_VECTOR)throw new $("Binary sub_type is not Vector");if(this.buffer[0]!==A.VECTOR_TYPE.PackedBit)throw new $("Binary datatype field is not packed bit");return rc(this),new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toBits(){if(this.sub_type!==A.SUBTYPE_VECTOR)throw new $("Binary sub_type is not Vector");if(this.buffer[0]!==A.VECTOR_TYPE.PackedBit)throw new $("Binary datatype field is not packed bit");rc(this);let a=(this.length()-2)*8-this.buffer[1],m=new Int8Array(a);for(let o=0;o<m.length;o++){let s=o/8|0,t=this.buffer[s+2],w=7-o%8,r=t>>w&1;m[o]=r}return m}static fromInt8Array(c){let a=j.allocate(c.byteLength+2);a[0]=A.VECTOR_TYPE.Int8,a[1]=0;let m=new Uint8Array(c.buffer,c.byteOffset,c.byteLength);a.set(m,2);let o=new this(a,this.SUBTYPE_VECTOR);return rc(o),o}static fromFloat32Array(c){let a=j.allocate(c.byteLength+2);a[0]=A.VECTOR_TYPE.Float32,a[1]=0;let m=new Uint8Array(c.buffer,c.byteOffset,c.byteLength);if(a.set(m,2),jc.isBigEndian)j.swap32(new Uint8Array(a.buffer,2));let o=new this(a,this.SUBTYPE_VECTOR);return rc(o),o}static fromPackedBits(c,a=0){let m=j.allocate(c.byteLength+2);m[0]=A.VECTOR_TYPE.PackedBit,m[1]=a,m.set(c,2);let o=new this(m,this.SUBTYPE_VECTOR);return rc(o),o}static fromBits(c){let a=c.length+7>>>3,m=new Uint8Array(a+2);m[0]=A.VECTOR_TYPE.PackedBit;let o=c.length%8;m[1]=o===0?0:8-o;for(let s=0;s<c.length;s++){let t=s>>>3,w=c[s];if(w!==0&&w!==1)throw new $(`Invalid bit value at ${s}: must be 0 or 1, found ${c[s]}`);if(w===0)continue;let r=7-s%8;m[t+2]|=w<<r}return new this(m,A.SUBTYPE_VECTOR)}}A.BSON_BINARY_SUBTYPE_DEFAULT=0;A.BUFFER_SIZE=256;A.SUBTYPE_DEFAULT=0;A.SUBTYPE_FUNCTION=1;A.SUBTYPE_BYTE_ARRAY=2;A.SUBTYPE_UUID_OLD=3;A.SUBTYPE_UUID=4;A.SUBTYPE_MD5=5;A.SUBTYPE_ENCRYPTED=6;A.SUBTYPE_COLUMN=7;A.SUBTYPE_SENSITIVE=8;A.SUBTYPE_VECTOR=9;A.SUBTYPE_USER_DEFINED=128;A.VECTOR_TYPE=Object.freeze({Int8:3,Float32:39,PackedBit:16});function rc(c){if(c.sub_type!==A.SUBTYPE_VECTOR)return;let a=c.position,m=c.buffer[0],o=c.buffer[1];if((m===A.VECTOR_TYPE.Float32||m===A.VECTOR_TYPE.Int8)&&o!==0)throw new $("Invalid Vector: padding must be zero for int8 and float32 vectors");if(m===A.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(m===A.VECTOR_TYPE.PackedBit&&o!==0&&a===2)throw new $("Invalid Vector: padding must be zero for packed bit vectors that are empty");if(m===A.VECTOR_TYPE.PackedBit&&o>7)throw new $(`Invalid Vector: padding must be a value between 0 and 7. found: ${o}`)}var _a=16,$w=/^[0-9A-F]{32}$/i,Qw=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;class _ extends A{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,To)}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 A(this.id,A.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(Mo(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 $w.test(c)||Qw.test(c)}inspect(c,a,m){return m??=y,`new UUID(${m(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,m){m??=y;let o=m(this.code,a),s=o.includes(`
|
|
680
|
-
`);if(this.scope!=null)
|
|
681
|
-
`:" "}${
|
|
682
|
-
`:""}${
|
|
683
|
-
`:""})`}}function jw(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 Tc extends S{get _bsontype(){return"DBRef"}constructor(c,a,m,o){super();let s=c.split(".");if(s.length===2)m=s.shift(),c=s.shift();this.collection=c,this.oid=a,this.db=m,this.fields=o||{}}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 Tc(c.$ref,c.$id,c.$db,a)}inspect(c,a,m){m??=y;let o=[m(this.namespace,a),m(this.oid,a),...this.db?[m(this.db,a)]:[],...Object.keys(this.fields).length>0?[m(this.fields,a)]:[]];return o[1]=m===y?`new ObjectId(${o[1]})`:o[1],`new DBRef(${o.join(", ")})`}}function _o(c){if(c==="")return c;let a=0,m=c[a]==="-",o=c[a]==="+";if(o||m)a+=1;let s=!1;for(;a<c.length&&c[a]==="0";++a)s=!0;if(!s)return o?c.slice(1):c;return`${m?"-":""}${c.length===a?"0":c.slice(a)}`}function Jw(c,a){a=a??10;let m="0123456789abcdefghijklmnopqrstuvwxyz".slice(0,a);return new RegExp(`[^-+${m}]`,"i").test(c)?!1:c}var N=void 0;try{N=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 Jo=65536,Aw=16777216,Uc=Jo*Jo,Eo=Uc*Uc,Pw=Eo/2,Ao={},Po={},Rw=20,lw=/^(\+?0|(\+|-)?[1-9][0-9]*)$/;class p extends S{get _bsontype(){return"Long"}get __isLong__(){return!0}constructor(c=0,a,m){super();let o=typeof a==="boolean"?a:Boolean(m),s=typeof a==="number"?a:0,t=typeof c==="string"?p.fromString(c,o):typeof c==="bigint"?p.fromBigInt(c,o):{low:c|0,high:s|0,unsigned:o};this.low=t.low,this.high=t.high,this.unsigned=t.unsigned}static fromBits(c,a,m){return new p(c,a,m)}static fromInt(c,a){let m,o,s;if(a){if(c>>>=0,s=0<=c&&c<256){if(o=Po[c],o)return o}if(m=p.fromBits(c,(c|0)<0?-1:0,!0),s)Po[c]=m;return m}else{if(c|=0,s=-128<=c&&c<128){if(o=Ao[c],o)return o}if(m=p.fromBits(c,c<0?-1:0,!1),s)Ao[c]=m;return m}}static fromNumber(c,a){if(isNaN(c))return a?p.UZERO:p.ZERO;if(a){if(c<0)return p.UZERO;if(c>=Eo)return p.MAX_UNSIGNED_VALUE}else{if(c<=-9223372036854776000)return p.MIN_VALUE;if(c+1>=Pw)return p.MAX_VALUE}if(c<0)return p.fromNumber(-c,a).neg();return p.fromBits(c%Uc|0,c/Uc|0,a)}static fromBigInt(c,a){let m=BigInt(4294967295),o=BigInt(32);return new p(Number(c&m),Number(c>>o&m),a)}static _fromString(c,a,m){if(c.length===0)throw new $("empty string");if(m<2||36<m)throw new $("radix");let o;if((o=c.indexOf("-"))>0)throw new $("interior hyphen");else if(o===0)return p._fromString(c.substring(1),a,m).neg();let s=p.fromNumber(Math.pow(m,8)),t=p.ZERO;for(let w=0;w<c.length;w+=8){let r=Math.min(8,c.length-w),C=parseInt(c.substring(w,w+r),m);if(r<8){let g=p.fromNumber(Math.pow(m,r));t=t.mul(g).add(p.fromNumber(C))}else t=t.mul(s),t=t.add(p.fromNumber(C))}return t.unsigned=a,t}static fromStringStrict(c,a,m){let o=!1;if(typeof a==="number")m=a,a=!1;else o=!!a;if(m??=10,c.trim()!==c)throw new $(`Input: '${c}' contains leading and/or trailing whitespace`);if(!Jw(c,m))throw new $(`Input: '${c}' contains invalid characters for radix: ${m}`);let s=_o(c),t=p._fromString(s,o,m);if(t.toString(m).toLowerCase()!==s.toLowerCase())throw new $(`Input: ${c} is not representable as ${t.unsigned?"an unsigned":"a signed"} 64-bit Long ${m!=null?`with radix: ${m}`:""}`);return t}static fromString(c,a,m){let o=!1;if(typeof a==="number")m=a,a=!1;else o=!!a;if(m??=10,c==="NaN"&&m<24)return p.ZERO;else if((c==="Infinity"||c==="+Infinity"||c==="-Infinity")&&m<35)return p.ZERO;return p._fromString(c,o,m)}static fromBytes(c,a,m){return m?p.fromBytesLE(c,a):p.fromBytesBE(c,a)}static fromBytesLE(c,a){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,a)}static fromBytesBE(c,a){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],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 p.fromNumber(c,a);if(typeof c==="string")return p.fromString(c,a);return p.fromBits(c.low,c.high,typeof a==="boolean"?a:c.unsigned)}add(c){if(!p.isLong(c))c=p.fromValue(c);let a=this.high>>>16,m=this.high&65535,o=this.low>>>16,s=this.low&65535,t=c.high>>>16,w=c.high&65535,r=c.low>>>16,C=c.low&65535,g=0,q=0,J=0,R=0;return R+=s+C,J+=R>>>16,R&=65535,J+=o+r,q+=J>>>16,J&=65535,q+=m+w,g+=q>>>16,q&=65535,g+=a+t,g&=65535,p.fromBits(J<<16|R,g<<16|q,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 a=this.isNegative(),m=c.isNegative();if(a&&!m)return-1;if(!a&&m)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 $("division by zero");if(N){if(!this.unsigned&&this.high===-2147483648&&c.low===-1&&c.high===-1)return this;let s=(this.unsigned?N.div_u:N.div_s)(this.low,this.high,c.low,c.high);return p.fromBits(s,N.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?p.UZERO:p.ZERO;let a,m,o;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(a=this.shr(1).div(c).shl(1),a.eq(p.ZERO))return c.isNegative()?p.ONE:p.NEG_ONE;else return m=this.sub(c.mul(a)),o=a.add(m.div(c)),o;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();o=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;o=p.UZERO}m=this;while(m.gte(c)){a=Math.max(1,Math.floor(m.toNumber()/c.toNumber()));let s=Math.ceil(Math.log(a)/Math.LN2),t=s<=48?1:Math.pow(2,s-48),w=p.fromNumber(a),r=w.mul(c);while(r.isNegative()||r.gt(m))a-=t,w=p.fromNumber(a,this.unsigned),r=w.mul(c);if(w.isZero())w=p.ONE;o=o.add(w),m=m.sub(r)}return o}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,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(!p.isLong(c))c=p.fromValue(c);if(N){let a=(this.unsigned?N.rem_u:N.rem_s)(this.low,this.high,c.low,c.high);return p.fromBits(a,N.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(N){let F=N.mul(this.low,this.high,c.low,c.high);return p.fromBits(F,N.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 a=this.high>>>16,m=this.high&65535,o=this.low>>>16,s=this.low&65535,t=c.high>>>16,w=c.high&65535,r=c.low>>>16,C=c.low&65535,g=0,q=0,J=0,R=0;return R+=s*C,J+=R>>>16,R&=65535,J+=o*C,q+=J>>>16,J&=65535,J+=s*r,q+=J>>>16,J&=65535,q+=m*C,g+=q>>>16,q&=65535,q+=o*r,g+=q>>>16,q&=65535,q+=s*w,g+=q>>>16,q&=65535,g+=a*C+m*r+o*w+s*t,g&=65535,p.fromBits(J<<16|R,g<<16|q,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 a=this.high;if(c<32){let m=this.low;return p.fromBits(m>>>c|a<<32-c,a>>>c,this.unsigned)}else if(c===32)return p.fromBits(a,0,this.unsigned);else return p.fromBits(a>>>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)*Uc+(this.low>>>0);return this.high*Uc+(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 p.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(p.MIN_VALUE)){let s=p.fromNumber(c),t=this.div(s),w=t.mul(s).sub(this);return t.toString(c)+w.toInt().toString(c)}else return"-"+this.neg().toString(c);let a=p.fromNumber(Math.pow(c,6),this.unsigned),m=this,o="";while(!0){let s=m.div(a),w=(m.sub(s.mul(a)).toInt()>>>0).toString(c);if(m=s,m.isZero())return w+o;else{while(w.length<6)w="0"+w;o=""+w+o}}}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,a){let{useBigInt64:m=!1,relaxed:o=!0}={...a};if(c.$numberLong.length>Rw)throw new $("$numberLong string is too long");if(!lw.test(c.$numberLong))throw new $(`$numberLong string "${c.$numberLong}" is in an invalid format`);if(m){let t=BigInt(c.$numberLong);return BigInt.asIntN(64,t)}let s=p.fromString(c.$numberLong);if(o)return s.toNumber();return s}inspect(c,a,m){m??=y;let o=m(this.toString(),a),s=this.unsigned?`, ${m(this.unsigned,a)}`:"";return`new Long(${o}${s})`}}p.TWO_PWR_24=p.fromInt(Aw);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 Ww=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/,Gw=/^(\+|-)?(Infinity|inf)$/i,Iw=/^(\+|-)?NaN$/i,Yc=6111,Dc=-6176,Ro=6176,lo=34,Ea=j.fromNumberArray([124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),Wo=j.fromNumberArray([248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),Go=j.fromNumberArray([120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),Xw=/^([-+])?(\d+)?$/,Zw=31,Io=16383,Mw=30,Hw=31;function Xo(c){return!isNaN(parseInt(c,10))}function Yw(c){let a=p.fromNumber(1e9),m=p.fromNumber(0);if(!c.parts[0]&&!c.parts[1]&&!c.parts[2]&&!c.parts[3])return{quotient:c,rem:m};for(let o=0;o<=3;o++)m=m.shiftLeft(32),m=m.add(new p(c.parts[o],0)),c.parts[o]=m.div(a).low,m=m.modulo(a);return{quotient:c,rem:m}}function Fw(c,a){if(!c&&!a)return{high:p.fromNumber(0),low:p.fromNumber(0)};let m=c.shiftRightUnsigned(32),o=new p(c.getLowBits(),0),s=a.shiftRightUnsigned(32),t=new p(a.getLowBits(),0),w=m.multiply(s),r=m.multiply(t),C=o.multiply(s),g=o.multiply(t);return w=w.add(r.shiftRightUnsigned(32)),r=new p(r.getLowBits(),0).add(C).add(g.shiftRightUnsigned(32)),w=w.add(r.shiftRightUnsigned(32)),g=r.shiftLeft(32).add(new p(g.getLowBits(),0)),{high:w,low:g}}function Uw(c,a){let m=c.high>>>0,o=a.high>>>0;if(m<o)return!0;else if(m===o){let s=c.low>>>0,t=a.low>>>0;if(s<t)return!0}return!1}function i(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||Mo(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 m=!1,o=!1,s=!1,t=!1,w=0,r=0,C=0,g=0,q=0,J=[0],R=0,F=0,P=0,W=0,H=new p(0,0),I=new p(0,0),n=0,Q=0;if(c.length>=7000)throw new $(""+c+" not a valid Decimal128 string");let h=c.match(Ww),Ds=c.match(Gw),zs=c.match(Iw);if(!h&&!Ds&&!zs||c.length===0)throw new $(""+c+" not a valid Decimal128 string");if(h){let Z=h[2],Pc=h[4],Rc=h[5],k=h[6];if(Pc&&k===void 0)i(c,"missing exponent power");if(Pc&&Z===void 0)i(c,"missing exponent base");if(Pc===void 0&&(Rc||k))i(c,"missing e before exponent")}if(c[Q]==="+"||c[Q]==="-")o=!0,m=c[Q++]==="-";if(!Xo(c[Q])&&c[Q]!=="."){if(c[Q]==="i"||c[Q]==="I")return new z(m?Wo:Go);else if(c[Q]==="N")return new z(Ea)}while(Xo(c[Q])||c[Q]==="."){if(c[Q]==="."){if(s)i(c,"contains multiple periods");s=!0,Q=Q+1;continue}if(R<lo){if(c[Q]!=="0"||t){if(!t)q=r;t=!0,J[F++]=parseInt(c[Q],10),R=R+1}}if(t)C=C+1;if(s)g=g+1;r=r+1,Q=Q+1}if(s&&!r)throw new $(""+c+" not a valid Decimal128 string");if(c[Q]==="e"||c[Q]==="E"){let Z=c.substr(++Q).match(Xw);if(!Z||!Z[2])return new z(Ea);W=parseInt(Z[0],10),Q=Q+Z[0].length}if(c[Q])return new z(Ea);if(!R)J[0]=0,C=1,R=1,w=0;else if(P=R-1,w=C,w!==1)while(c[q+w-1+Number(o)+Number(s)]==="0")w=w-1;if(W<=g&&g>W+16384)W=Dc;else W=W-g;while(W>Yc){if(P=P+1,P>=lo){if(w===0){W=Yc;break}i(c,"overflow")}W=W-1}if(a.allowRounding){while(W<Dc||R<C){if(P===0&&w<R){W=Dc,w=0;break}if(R<C)C=C-1;else P=P-1;if(W<Yc)W=W+1;else{if(J.join("").match(/^0+$/)){W=Yc;break}i(c,"overflow")}}if(P+1<w){let Z=r;if(s)q=q+1,Z=Z+1;if(o)q=q+1,Z=Z+1;let Pc=parseInt(c[q+P+1],10),Rc=0;if(Pc>=5){if(Rc=1,Pc===5){Rc=J[P]%2===1?1:0;for(let k=q+P+2;k<Z;k++)if(parseInt(c[k],10)){Rc=1;break}}}if(Rc){let k=P;for(;k>=0;k--)if(++J[k]>9){if(J[k]=0,k===0)if(W<Yc)W=W+1,J[k]=1;else return new z(m?Wo:Go)}else break}}}else{while(W<Dc||R<C){if(P===0){if(w===0){W=Dc;break}i(c,"exponent underflow")}if(R<C){if(c[C-1+Number(o)+Number(s)]!=="0"&&w!==0)i(c,"inexact rounding");C=C-1}else{if(J[P]!==0)i(c,"inexact rounding");P=P-1}if(W<Yc)W=W+1;else i(c,"overflow")}if(P+1<w){if(s)q=q+1;if(o)q=q+1;if(parseInt(c[q+P+1],10)!==0)i(c,"inexact rounding")}}if(H=p.fromNumber(0),I=p.fromNumber(0),w===0)H=p.fromNumber(0),I=p.fromNumber(0);else if(P<17){let Z=0;I=p.fromNumber(J[Z++]),H=new p(0,0);for(;Z<=P;Z++)I=I.multiply(p.fromNumber(10)),I=I.add(p.fromNumber(J[Z]))}else{let Z=0;H=p.fromNumber(J[Z++]);for(;Z<=P-17;Z++)H=H.multiply(p.fromNumber(10)),H=H.add(p.fromNumber(J[Z]));I=p.fromNumber(J[Z++]);for(;Z<=P;Z++)I=I.multiply(p.fromNumber(10)),I=I.add(p.fromNumber(J[Z]))}let v=Fw(H,p.fromString("100000000000000000"));if(v.low=v.low.add(I),Uw(v.low,I))v.high=v.high.add(p.fromNumber(1));n=W+Ro;let X={low:p.fromNumber(0),high:p.fromNumber(0)};if(v.high.shiftRightUnsigned(49).and(p.fromNumber(1)).equals(p.fromNumber(1)))X.high=X.high.or(p.fromNumber(3).shiftLeft(61)),X.high=X.high.or(p.fromNumber(n).and(p.fromNumber(16383).shiftLeft(47))),X.high=X.high.or(v.high.and(p.fromNumber(140737488355327)));else X.high=X.high.or(p.fromNumber(n&16383).shiftLeft(49)),X.high=X.high.or(v.high.and(p.fromNumber(562949953421311)));if(X.low=v.low,m)X.high=X.high.or(p.fromString("9223372036854775808"));let T=j.allocateUnsafe(16);return Q=0,T[Q++]=X.low.low&255,T[Q++]=X.low.low>>8&255,T[Q++]=X.low.low>>16&255,T[Q++]=X.low.low>>24&255,T[Q++]=X.low.high&255,T[Q++]=X.low.high>>8&255,T[Q++]=X.low.high>>16&255,T[Q++]=X.low.high>>24&255,T[Q++]=X.high.low&255,T[Q++]=X.high.low>>8&255,T[Q++]=X.high.low>>16&255,T[Q++]=X.high.low>>24&255,T[Q++]=X.high.high&255,T[Q++]=X.high.high>>8&255,T[Q++]=X.high.high>>16&255,T[Q++]=X.high.high>>24&255,new z(T)}toString(){let c,a=0,m=Array(36);for(let Q=0;Q<m.length;Q++)m[Q]=0;let o=0,s=!1,t,w={parts:[0,0,0,0]},r,C,g=[];o=0;let q=this.bytes,J=q[o++]|q[o++]<<8|q[o++]<<16|q[o++]<<24,R=q[o++]|q[o++]<<8|q[o++]<<16|q[o++]<<24,F=q[o++]|q[o++]<<8|q[o++]<<16|q[o++]<<24,P=q[o++]|q[o++]<<8|q[o++]<<16|q[o++]<<24;if(o=0,{low:new p(J,R),high:new p(F,P)}.high.lessThan(p.ZERO))g.push("-");let H=P>>26&Zw;if(H>>3===3)if(H===Mw)return g.join("")+"Infinity";else if(H===Hw)return"NaN";else c=P>>15&Io,t=8+(P>>14&1);else t=P>>14&7,c=P>>17&Io;let I=c-Ro;if(w.parts[0]=(P&16383)+((t&15)<<14),w.parts[1]=F,w.parts[2]=R,w.parts[3]=J,w.parts[0]===0&&w.parts[1]===0&&w.parts[2]===0&&w.parts[3]===0)s=!0;else for(C=3;C>=0;C--){let Q=0,h=Yw(w);if(w=h.quotient,Q=h.rem.low,!Q)continue;for(r=8;r>=0;r--)m[C*9+r]=Q%10,Q=Math.floor(Q/10)}if(s)a=1,m[o]=0;else{a=36;while(!m[o])a=a-1,o=o+1}let n=a-1+I;if(n>=34||n<=-7||I>0){if(a>34){if(g.push("0"),I>0)g.push(`E+${I}`);else if(I<0)g.push(`E${I}`);return g.join("")}if(g.push(`${m[o++]}`),a=a-1,a)g.push(".");for(let Q=0;Q<a;Q++)g.push(`${m[o++]}`);if(g.push("E"),n>0)g.push(`+${n}`);else g.push(`${n}`)}else if(I>=0)for(let Q=0;Q<a;Q++)g.push(`${m[o++]}`);else{let Q=a+I;if(Q>0)for(let h=0;h<Q;h++)g.push(`${m[o++]}`);else g.push("0");g.push(".");while(Q++<0)g.push("0");for(let h=0;h<a-Math.max(Q-1,0);h++)g.push(`${m[o++]}`)}return g.join("")}toJSON(){return{$numberDecimal:this.toString()}}toExtendedJSON(){return{$numberDecimal:this.toString()}}static fromExtendedJSON(c){return z.fromString(c.$numberDecimal)}inspect(c,a,m){return m??=y,`new Decimal128(${m(this.toString(),a)})`}}class oc 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 oc(NaN);if(c==="Infinity")return new oc(1/0);if(c==="-Infinity")return new oc(-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 oc(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 m=parseFloat(c.$numberDouble);return a&&a.relaxed?m:new oc(m)}inspect(c,a,m){return m??=y,`new Double(${m(this.value,a)})`}}class nc 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=_o(c),m=Number(c);if(ya<m)throw new $(`Input: '${c}' is larger than the maximum value for Int32`);else if(Sa>m)throw new $(`Input: '${c}' is smaller than the minimum value for Int32`);else if(!Number.isSafeInteger(m))throw new $(`Input: '${c}' is not a safe integer`);else if(m.toString()!==a)throw new $(`Input: '${c}' is not a valid Int32 string`);return new nc(m)}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 nc(c.$numberInt)}inspect(c,a,m){return m??=y,`new Int32(${m(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 Qc=null,zc=new WeakMap;class Y 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=Y.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(Y.validateHexString(a)){if(this.buffer=j.fromHex(a),Y.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,Y.cacheHexString)zc.set(this,j.toHex(c))}static validateHexString(c){if(c?.length!==24)return!1;for(let a=0;a<24;a++){let m=c.charCodeAt(a);if(m>=48&&m<=57||m>=97&&m<=102||m>=65&&m<=70)continue;return!1}return!0}toHexString(){if(Y.cacheHexString){let a=zc.get(this);if(a)return a}let c=j.toHex(this.id);if(Y.cacheHexString)zc.set(this,c);return c}static getInc(){return Y.index=(Y.index+1)%16777215}static generate(c){if(typeof c!=="number")c=Math.floor(Date.now()/1000);let a=Y.getInc(),m=j.allocateUnsafe(12);if(jc.setInt32BE(m,0,c),Qc===null)Qc=j.randomBytes(5);return m[4]=Qc[0],m[5]=Qc[1],m[6]=Qc[2],m[7]=Qc[3],m[8]=Qc[4],m[11]=a&255,m[10]=a>>8&255,m[9]=a>>16&255,m}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(Y.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(),m=this.toHexString();return typeof a==="string"&&a.toLowerCase()===m}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 Y}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 m=11;m>=4;m--)a[m]=0;return jc.setInt32BE(a,0,c),new Y(a)}static createFromHexString(c){if(c?.length!==24)throw new $("hex string must be 24 characters");return new Y(j.fromHex(c))}static createFromBase64(c){if(c?.length!==16)throw new $("base64 string must be 16 characters");return new Y(j.fromBase64(c))}static isValid(c){if(c==null)return!1;if(typeof c==="string")return Y.validateHexString(c);try{return new Y(c),!0}catch{return!1}}toExtendedJSON(){if(this.toHexString)return{$oid:this.toHexString()};return{$oid:this.toString("hex")}}static fromExtendedJSON(c){return new Y(c.$oid)}isCached(){return Y.cacheHexString&&zc.has(this)}inspect(c,a,m){return m??=y,`new ObjectId(${m(this.toHexString(),a)})`}}Y.index=Math.floor(Math.random()*16777215);function Tw(c){return c.split("").sort().join("")}class tc extends S{get _bsontype(){return"BSONRegExp"}constructor(c,a){super();if(this.pattern=c,this.options=Tw(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 m=0;m<this.options.length;m++)if(!(this.options[m]==="i"||this.options[m]==="m"||this.options[m]==="x"||this.options[m]==="l"||this.options[m]==="s"||this.options[m]==="u"))throw new $(`The regular expression option [${this.options[m]}] 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,m){let o=sw(a)??((w)=>w);m??=y;let s=o(m(this.pattern),"regexp"),t=o(m(this.options),"regexp");return`new BSONRegExp(${s}, ${t})`}}class wa 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 wa(c.$symbol)}inspect(c,a,m){return m??=y,`new BSONSymbol(${m(this.value,a)})`}}var nw=p;class sc extends nw{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 $("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),m=Number(c.i);if(a<0||Number.isNaN(a))throw new $("Timestamp constructed from { t, i } must provide a positive t");if(m<0||Number.isNaN(m))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(m>4294967295)throw new $("Timestamp constructed from { t, i } must provide i equal or less than uint32 max");super(m,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(p.fromInt(c,!0))}static fromNumber(c){return new sc(p.fromNumber(c,!0))}static fromBits(c,a){return new sc({i:c,t:a})}static fromString(c,a){return new sc(p.fromString(c,!0,a))}toExtendedJSON(){return{$timestamp:{t:this.t,i:this.i}}}static fromExtendedJSON(c){let a=p.isLong(c.$timestamp.i)?c.$timestamp.i.getLowBitsUnsigned():c.$timestamp.i,m=p.isLong(c.$timestamp.t)?c.$timestamp.t.getLowBitsUnsigned():c.$timestamp.t;return new sc({t:m,i:a})}inspect(c,a,m){m??=y;let o=m(this.t,a),s=m(this.i,a);return`new Timestamp({ t: ${o}, i: ${s} })`}}sc.MAX_VALUE=p.MAX_UNSIGNED_VALUE;var lC=p.fromNumber(tw),WC=p.fromNumber(ww);function hw(c){return c!=null&&typeof c==="object"&&"_bsontype"in c&&typeof c._bsontype==="string"}var Kw={$oid:Y,$binary:A,$uuid:A,$symbol:wa,$numberInt:nc,$numberDecimal:z,$numberDouble:oc,$numberLong:p,$minKey:ta,$maxKey:sa,$regex:tc,$regularExpression:tc,$timestamp:sc};function ko(c,a={}){if(typeof c==="number"){let o=c<=ya&&c>=Sa,s=c<=Fo&&c>=Uo;if(a.relaxed||a.legacy)return c;if(Number.isInteger(c)&&!Object.is(c,-0)){if(o)return new nc(c);if(s){if(a.useBigInt64)return BigInt(c);return p.fromNumber(c)}}return new oc(c)}if(c==null||typeof c!=="object")return c;if(c.$undefined)return null;let m=Object.keys(c).filter((o)=>o.startsWith("$")&&c[o]!=null);for(let o=0;o<m.length;o++){let s=Kw[m[o]];if(s)return s.fromExtendedJSON(c,a)}if(c.$date!=null){let o=c.$date,s=new Date;if(a.legacy)if(typeof o==="number")s.setTime(o);else if(typeof o==="string")s.setTime(Date.parse(o));else if(typeof o==="bigint")s.setTime(Number(o));else throw new Da(`Unrecognized type for EJSON date: ${typeof o}`);else if(typeof o==="string")s.setTime(Date.parse(o));else if(p.isLong(o))s.setTime(o.toNumber());else if(typeof o==="number"&&a.relaxed)s.setTime(o);else if(typeof o==="bigint")s.setTime(Number(o));else throw new Da(`Unrecognized type for EJSON date: ${typeof o}`);return s}if(c.$code!=null){let o=Object.assign({},c);if(c.$scope)o.$scope=ko(c.$scope);return Sc.fromExtendedJSON(c)}if(jw(c)||c.$dbPointer){let o=c.$ref?c:c.$dbPointer;if(o instanceof Tc)return o;let s=Object.keys(o).filter((w)=>w.startsWith("$")),t=!0;if(s.forEach((w)=>{if(["$ref","$id","$db"].indexOf(w)===-1)t=!1}),t)return Tc.fromExtendedJSON(o)}return c}function _w(c,a){return c.map((m,o)=>{a.seenObjects.push({propertyName:`index ${o}`,obj:null});try{return mc(m,a)}finally{a.seenObjects.pop()}})}function Zo(c){let a=c.toISOString();return c.getUTCMilliseconds()!==0?a:a.slice(0,-5)+"Z"}function mc(c,a){if(c instanceof Map||Ho(c)){let m=Object.create(null);for(let[o,s]of c){if(typeof o!=="string")throw new $("Can only serialize maps with string keys");m[o]=s}return mc(m,a)}if((typeof c==="object"||typeof c==="function")&&c!==null){let m=a.seenObjects.findIndex((o)=>o.obj===c);if(m!==-1){let o=a.seenObjects.map((q)=>q.propertyName),s=o.slice(0,m).map((q)=>`${q} -> `).join(""),t=o[m],w=" -> "+o.slice(m+1,o.length-1).map((q)=>`${q} -> `).join(""),r=o[o.length-1],C=" ".repeat(s.length+t.length/2),g="-".repeat(w.length+(t.length+r.length)/2-1);throw new $(`Converting circular structure to EJSON:
|
|
684
|
-
${
|
|
685
|
-
${
|
|
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 {${
|
|
704
|
-
'${
|
|
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
|
|
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
|
|
1169
|
+
`}function vt(c){return`# ${c}
|
|
1058
1170
|
|
|
1059
1171
|
Starter de Justo Spaces generado por \`team-cli spaces init\`.
|
|
1060
1172
|
|
|
@@ -1086,10 +1198,11 @@ Flujo recomendado:
|
|
|
1086
1198
|
Tip:
|
|
1087
1199
|
- usa \`spaces preview --open\` para abrir el dashboard en el navegador por defecto y mostrárselo al usuario mientras lo iteras
|
|
1088
1200
|
- \`spaces publish\` sube el repo del space sin \`node_modules\` ni otros archivos ignorados por git, además del build listo para servir
|
|
1201
|
+
- si necesitas escritura en Mongo, declara las collections en \`.justo-space.json\` y usa \`team-cli spaces db\`
|
|
1089
1202
|
- después de \`spaces init\`, haz un initial commit para fijar el scaffold base
|
|
1090
1203
|
- después de cada publish, haz commit para que el repo refleje exactamente lo que quedó publicado
|
|
1091
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'\`
|
|
1092
|
-
`}function
|
|
1205
|
+
`}function xt(){return`import {StrictMode} from 'react'
|
|
1093
1206
|
import {createRoot} from 'react-dom/client'
|
|
1094
1207
|
import App from './App.tsx'
|
|
1095
1208
|
import './index.css'
|
|
@@ -1100,13 +1213,52 @@ createRoot(document.getElementById('root')!).render(
|
|
|
1100
1213
|
<App />
|
|
1101
1214
|
</StrictMode>,
|
|
1102
1215
|
)
|
|
1103
|
-
`}function
|
|
1104
|
-
base: './',`);
|
|
1105
|
-
`)}function
|
|
1106
|
-
${
|
|
1107
|
-
`),Na(E(c,".git"),{recursive:!0,force:!0})}function vw(c){Nc("git",["init"],c)}function xw(c){Na(E(c,"package-lock.json"),{force:!0})}function ua(c){let a=io(c);if(!qa(a))throw Error(`No existe la app del space: ${a}`);if(!qa(E(a,La)))throw Error("Este publish solo acepta apps creadas con team-cli spaces init. Debes apuntar al root de esa app.");return a}function Bo(c){let a=ua(c);Nc(Jc("yarn"),["build"],a);let m=E(a,"dist");if(!qa(E(m,"index.html")))throw Error("El build no generó dist/index.html");return m}function bo(c){let a=uw(c),m=Oo(a),o=uo(a);return Nc(Jc("npx"),["shadcn@latest","init","-t","vite","-d","-y","-n",o],m),Nc(Jc("npx"),["shadcn@latest","add","-a","-y"],a),xw(a),iw(a),Nc(Jc("yarn"),["install"],a),Ow(a),dw(a),Bw(a),bw(a),vw(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 fo,readFileSync as cs,statSync as as}from"node:fs";import{gzipSync as wp}from"node:zlib";import{join as ms,relative as os,resolve as xo}from"node:path";import{existsSync as ew,readFileSync as fw}from"node:fs";import{join as cp}from"node:path";var ap=[".git","node_modules","dist",".justo-space-preview",".DS_Store"];function mp(c){return c.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}function op(c){let a="";for(let m=0;m<c.length;m++){let o=c[m],s=c[m+1];if(o==="*"){if(s==="*"){a+=".*",m+=1;continue}a+="[^/]*";continue}if(o==="?"){a+="[^/]";continue}a+=mp(o)}return a}function sp(c){let a=c.trim();if(!a||a.startsWith("#"))return null;let m=a.startsWith("!"),o=m?a.slice(1).trim():a;if(!o)return null;let s=o.endsWith("/"),t=o.replace(/^\/+/,"").replace(/\/+$/,"");if(!t)return null;let w=t.includes("/"),r=op(t),C=w?`^${r}${s?"(?:/.*)?":""}$`:`(?:^|/)${r}${s?"(?:/.*)?":"(?:$|/)"}`;return{negate:m,directoryOnly:s,regex:new RegExp(C)}}function tp(c){let a=cp(c,".gitignore"),m=[...ap];if(ew(a))m.push(...fw(a,"utf-8").split(/\r?\n/));return m.map(sp).filter((o)=>Boolean(o))}function vo(c){let a=tp(c);return(m,o)=>{let s=m.replaceAll("\\","/").replace(/^\/+/,""),t=!1;for(let w of a){if(!w.regex.test(s))continue;t=!w.negate}return t}}var $a=512,pp=2,rp="repo",Cp="dist";function qp(c){let a=c.replaceAll("\\","/");if(a.startsWith("/")||a.includes("../"))throw Error(`Ruta inválida en el space: ${c}`);return a}function gp(c){let a=qp(c);if(Buffer.from(a).length<=100)return{name:a,prefix:""};let o=a.lastIndexOf("/");if(o<=0)throw Error(`La ruta es demasiado larga para el paquete del space: ${c}`);let s=a.slice(0,o),t=a.slice(o+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 Ac(c,a,m,o){let s=Buffer.from(o);s.copy(c,a,0,Math.min(s.length,m))}function uc(c,a,m,o){let s=Math.max(0,Math.trunc(o)).toString(8).padStart(m-1,"0");Ac(c,a,m,`${s}\x00`)}function $p(c){let a=Buffer.alloc($a,0),{name:m,prefix:o}=gp(c.path);Ac(a,0,100,m),uc(a,100,8,c.mode),uc(a,108,8,0),uc(a,116,8,0),uc(a,124,12,c.content.length),uc(a,136,12,c.mtime),a.fill(32,148,156),Ac(a,156,1,"0"),Ac(a,257,6,"ustar"),Ac(a,263,2,"00"),Ac(a,345,155,o);let s=0;for(let w of a)s+=w;let t=`${s.toString(8).padStart(6,"0")}\x00 `;return Ac(a,148,8,t),a}function Qp(c){let a=c%$a;return a===0?0:$a-a}function ss(c,a=c){return fo(a,{withFileTypes:!0}).sort((o,s)=>o.name.localeCompare(s.name)).flatMap((o)=>{let s=ms(a,o.name);if(o.isDirectory())return ss(c,s);if(!o.isFile())return[];let t=os(c,s),w=as(s);return[{path:t,content:cs(s),mode:w.mode&511,mtime:Math.floor(w.mtimeMs/1000)}]})}function eo(c,a){return c.map((m)=>({...m,path:`${a}/${m.path.replaceAll("\\","/")}`}))}function ts(c,a=c){let m=vo(c);return fo(a,{withFileTypes:!0}).sort((s,t)=>s.name.localeCompare(t.name)).flatMap((s)=>{let t=ms(a,s.name),w=os(c,t).replaceAll("\\","/");if(m(w,s.isDirectory()))return[];if(s.isDirectory())return ts(c,t);if(!s.isFile())return[];let r=as(t);return[{path:w,content:cs(t),mode:r.mode&511,mtime:Math.floor(r.mtimeMs/1000)}]})}function ws(c,a){let m=xo(c),o=xo(a),s=[...eo(ts(m),rp),...eo(ss(o),Cp)];if(!s.length)throw Error("El build del space no contiene archivos para publicar");let t=[];for(let w of s){t.push($p(w)),t.push(w.content);let r=Qp(w.content.length);if(r>0)t.push(Buffer.alloc(r,0))}return t.push(Buffer.alloc($a*pp,0)),wp(Buffer.concat(t))}import{mkdirSync as ps,writeFileSync as jp}from"node:fs";import{dirname as Jp,join as Ap,normalize as Pp,sep as rs}from"node:path";import{gunzipSync as Rp}from"node:zlib";var Oc=512;function Qa(c,a,m){let o=c.subarray(a,a+m),s=o.indexOf(0);return(s>=0?o.subarray(0,s):o).toString("utf-8").trim()}function lp(c,a,m){let o=Qa(c,a,m).replaceAll("\x00","").trim();if(!o)return 0;return Number.parseInt(o,8)}function Wp(c){let a=c%Oc;return a===0?0:Oc-a}function Gp(c){let a=Qa(c,0,100),m=Qa(c,345,155);return m?`${m}/${a}`:a}function Ip(c){let a=Pp(c);if(!c||c.startsWith("/")||a.startsWith("..")||a.includes(`${rs}..${rs}`)||a==="..")throw Error("El paquete del space contiene rutas inválidas")}function Cs(c,a,m){let o=Rp(c),s=a.replaceAll("\\","/").replace(/^\/+|\/+$/g,""),t=`${s}/`,w=0,r=0;while(w+Oc<=o.length){let C=o.subarray(w,w+Oc),g=C.every((H)=>H===0);if(w+=Oc,g)break;let q=Gp(C),J=Qa(C,156,1)||"0",R=lp(C,124,12),F=o.subarray(w,w+R);if(w+=R+Wp(R),!q.startsWith(t))continue;let P=q.slice(t.length);if(!P)continue;Ip(P);let W=Ap(m,...P.split("/"));if(J==="5"){ps(W,{recursive:!0});continue}if(J!=="0")continue;ps(Jp(W),{recursive:!0}),jp(W,F),r+=1}if(!r)throw Error(`El paquete del space no contiene la carpeta ${s}/`);return r}import{spawn as Ja}from"node:child_process";import{createServer as Ps}from"node:http";import{existsSync as Xp,mkdirSync as Zp,openSync as Mp,readFileSync as Hp,rmSync as Yp,writeFileSync as Fp}from"node:fs";import{dirname as Up,join as Aa,resolve as Rs}from"node:path";import{request as Tp}from"node:http";import{request as np}from"node:https";function qs(c){let a=[],m="",o=null,s=!1;for(let t of c){if(s){m+=t,s=!1;continue}if(t==="\\"){s=!0;continue}if(o){if(t===o)o=null;else m+=t;continue}if(t==='"'||t==="'"){o=t;continue}if(/\s/.test(t)){if(m)a.push(m),m="";continue}m+=t}if(o)throw Error("Comando inválido: falta cerrar una comilla");if(m)a.push(m);return a}var hp=".justo-space-preview",Kp="preview.json",_p=30000;function Pa(c){return Aa(c,hp)}function ls(c){return Aa(Pa(c),Kp)}function gs(c){return Aa(Pa(c),"bridge.log")}function $s(c){return Aa(Pa(c),"vite.log")}function Ws(c){Zp(Pa(c),{recursive:!0})}function ja(c){if(!c)return;try{process.kill(c,"SIGTERM")}catch{return}}function Ep(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 kp(c,a){if(!a)return{attempted:!1,opened:!1};let m=Ep(c);return await new Promise((o)=>{let s=Ja(m.command,m.args,{stdio:"ignore",detached:!0});s.once("error",()=>{o({attempted:!0,opened:!1,message:"No se pudo abrir el navegador por defecto automáticamente. Abre la URL manualmente."})}),s.once("spawn",()=>{s.unref(),o({attempted:!0,opened:!0})})})}function Vp(c){let a=ls(c);if(!Xp(a))return;try{let m=JSON.parse(Hp(a,"utf-8"));ja(m.appPid),ja(m.bridgePid)}catch{}Yp(a,{force:!0})}function Qs(){return new Promise((c,a)=>{let m=Ps();m.listen(0,"127.0.0.1",()=>{let o=m.address();if(!o||typeof o==="string"){m.close(),a(Error("No se pudo obtener un puerto libre"));return}let{port:s}=o;m.close((t)=>{if(t){a(t);return}c(s)})}),m.on("error",a)})}function js(c){return new Promise((a)=>setTimeout(a,c))}function Dp(c){return new Promise((a,m)=>{let t=(new URL(c).protocol==="https:"?np:Tp)(c,{method:"GET"},(w)=>{a(w.statusCode||0),w.resume()});t.on("error",m),t.end()})}async function Js(c,a=_p){let m=Date.now();while(Date.now()-m<a){try{if(await Dp(c)>0)return}catch{await js(500);continue}await js(500)}throw Error(`Timeout esperando que el preview responda en ${c}`)}function zp(c){return Ws(Up(c)),Mp(c,"a")}function As(c,a,m,o,s){let t=zp(o),w=Ja(c,a,{cwd:m,detached:!0,stdio:["ignore",t,t],env:{...process.env,...s}});if(!w.pid)throw Error(`No se pudo iniciar el proceso ${c}`);return w.unref(),w.pid}function Gs(){let c=pm("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 yp(c){let a=[];for await(let m of c)a.push(Buffer.isBuffer(m)?m:Buffer.from(m));return Buffer.concat(a).toString("utf-8")}function dc(c,a,m){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(m))}function Oa(c){let a=c.trim(),m=new Set([0]);for(let s=0;s<a.length;s++)if(a[s]==="{"||a[s]==="[")m.add(s);let o=[...m].sort((s,t)=>t-s);for(let s of o)try{return JSON.parse(a.slice(s))}catch{continue}return a}function Is(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 Sp(c,a){return{VITE_JUSTO_CLI_ENDPOINT:c,VITE_JUSTO_STREAM_ENDPOINT:a,VITE_JUSTO_CLI_MODE:"preview",[Lc]:Ca}}function Lp(c,a,m,o){return new Promise((s,t)=>{let w=Ja(ra(),[a,"--env","prod",...o,"--format","json"],{cwd:process.cwd(),env:Is(m),stdio:["ignore","pipe","pipe"]}),r="";w.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)}),w.stderr.on("data",(C)=>{r+=Buffer.from(C).toString("utf-8")}),w.on("error",t),w.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 g=Oa(r.trim());t(Error(g.error||r.trim()||"justoStream failed"))})})}async function Xs(c){let a=Number(c.port);if(!a)throw Error("Falta --port para el bridge interno de preview");let m=Gs(),o=Rs(c["cli-path"]||process.argv[1]||""),s=Ps(async(t,w)=>{if(t.method==="OPTIONS"){dc(w,200,{ok:!0});return}if(t.method==="GET"&&t.url==="/__justo/health"){dc(w,200,{ok:!0});return}if(t.method!=="POST"||t.url!=="/__justo/cli"&&t.url!=="/__justo/stream"){dc(w,404,{ok:!1,error:"Not found"});return}try{let r=await yp(t),g=JSON.parse(r||"{}").command;if(!g)throw Error("Debes indicar un comando");let q=Array.isArray(g)?g:qs(g);if(t.url==="/__justo/stream"){await Lp(w,o,m,q);return}let J=await new Promise((R,F)=>{let P=Ja(ra(),[o,"--env","prod",...q,"--format","json"],{cwd:process.cwd(),env:Is(m),stdio:["ignore","pipe","pipe"]}),W=[],H=[];P.stdout.on("data",(I)=>W.push(Buffer.from(I))),P.stderr.on("data",(I)=>H.push(Buffer.from(I))),P.on("error",F),P.on("close",(I)=>{let n=Buffer.concat(W).toString("utf-8")||Buffer.concat(H).toString("utf-8");if(I&&I!==0){let Q=Oa(n);F(Error(Q.error||n||"justoCli failed"));return}R(Oa(n))})});dc(w,200,{result:J})}catch(r){let C=r instanceof Error?r.message:"Unexpected error";dc(w,400,{error:C})}});await new Promise((t,w)=>{s.listen(a,"127.0.0.1",()=>t()),s.on("error",w)}),D(`Space preview bridge listening on http://127.0.0.1:${a}
|
|
1108
|
-
`),await new Promise((
|
|
1109
|
-
`);let F=await
|
|
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\`:
|
|
1223
|
+
- \`spaces publish\` lee \`repo/.justo-space.json\`, valida \`collections\` y sincroniza índices
|
|
1224
|
+
- cada collection lógica debe existir en \`collections\`
|
|
1225
|
+
- los nombres válidos usan solo letras, números y guion bajo
|
|
1226
|
+
- la collection física en Mongo queda como \`spaces.<slug_sanitized>.<collection>\`
|
|
1227
|
+
- el \`slug\` se sanitiza reemplazando todo lo no alfanumérico por \`_\`
|
|
1228
|
+
- si una collection deja de existir en \`.justo-space.json\`, no se borran sus datos, pero deja de estar autorizada para \`spaces db\`
|
|
1229
|
+
|
|
1230
|
+
Ejemplo completo:
|
|
1231
|
+
\`\`\`json
|
|
1232
|
+
{
|
|
1233
|
+
"template": "react-vite-shadcn",
|
|
1234
|
+
"version": 2,
|
|
1235
|
+
"collections": {
|
|
1236
|
+
"events": {
|
|
1237
|
+
"indexes": [
|
|
1238
|
+
{
|
|
1239
|
+
"name": "createdAt_desc",
|
|
1240
|
+
"key": {
|
|
1241
|
+
"createdAt": -1
|
|
1242
|
+
}
|
|
1243
|
+
},
|
|
1244
|
+
{
|
|
1245
|
+
"name": "eventId_1",
|
|
1246
|
+
"key": {
|
|
1247
|
+
"eventId": 1
|
|
1248
|
+
},
|
|
1249
|
+
"unique": true
|
|
1250
|
+
}
|
|
1251
|
+
]
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
\`\`\`
|
|
1256
|
+
|
|
1257
|
+
Reglas de índices:
|
|
1258
|
+
- cada índice debe tener \`name\` y \`key\`
|
|
1259
|
+
- puedes usar opciones comunes de Mongo como \`unique\`, \`sparse\`, \`expireAfterSeconds\` y \`partialFilterExpression\`
|
|
1260
|
+
- en cada publish, los índices declarados se recrean en modo estricto para esa collection
|
|
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
|
|
1110
1262
|
|
|
1111
1263
|
Spaces son aplicaciones internas en React, pensadas para que las construyan agentes.
|
|
1112
1264
|
El flujo oficial parte con \`spaces init\` y \`spaces publish\` solo acepta apps creadas así.
|
|
@@ -1132,6 +1284,10 @@ Cada space:
|
|
|
1132
1284
|
- el archivo \`.justo-space.json\` puede declarar \`collections\` para que el publish sincronice índices en Mongo
|
|
1133
1285
|
- esas collections se exponen con \`team-cli spaces db\` usando el prefijo físico \`spaces.<slug_sanitized>.<collection>\`
|
|
1134
1286
|
|
|
1287
|
+
${ww()}
|
|
1288
|
+
|
|
1289
|
+
${nw()}
|
|
1290
|
+
|
|
1135
1291
|
Flujo sugerido para agentes:
|
|
1136
1292
|
1. \`team-cli spaces init --path ./mi-space-app\`
|
|
1137
1293
|
2. hacer initial commit del repo nuevo
|
|
@@ -1140,7 +1296,7 @@ Flujo sugerido para agentes:
|
|
|
1140
1296
|
5. desarrollar la app React dentro de esa carpeta
|
|
1141
1297
|
6. \`team-cli spaces publish <spaceId> --path ./mi-space-app\`
|
|
1142
1298
|
7. hacer commit del repo después de publicar
|
|
1143
|
-
8. abrir \`${
|
|
1299
|
+
8. abrir \`${Oo()}/spaces/<slug>\`
|
|
1144
1300
|
9. si necesitas retomarlo en otra carpeta: \`team-cli spaces fork <slug> --path ./mi-space-app\`
|
|
1145
1301
|
|
|
1146
1302
|
Slugs:
|
|
@@ -1196,7 +1352,7 @@ import {justoCli, justoStream} from '@/lib/justo'
|
|
|
1196
1352
|
const me = await justoCli("graphql main 'query { me { _id email roles } }'")
|
|
1197
1353
|
const rows = await justoCli("data queries preview <queryId> --params '{\\"limit\\":10}'")
|
|
1198
1354
|
const events = await justoCli(
|
|
1199
|
-
|
|
1355
|
+
\`spaces db --slug usuario:dashboard-1234 --collection events --operation '{"type":"find","filter":{},"limit":10}'\`,
|
|
1200
1356
|
)
|
|
1201
1357
|
await justoStream(
|
|
1202
1358
|
"data queries run <queryId> --limit 1000 --params '{\\"websiteId\\":\\"w1\\"}'",
|
|
@@ -1214,7 +1370,7 @@ Comandos:
|
|
|
1214
1370
|
- \`spaces fork <slug> --path ./mi-space-app\`
|
|
1215
1371
|
- \`spaces archive <spaceId>\`
|
|
1216
1372
|
- \`spaces db --slug <slug> --collection events --operation '{"type":"find","filter":{}}'\`
|
|
1217
|
-
`}async function
|
|
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) {
|
|
1218
1374
|
createSpace(name: $name, description: $description, slug: $slug) {
|
|
1219
1375
|
_id
|
|
1220
1376
|
name
|
|
@@ -1225,7 +1381,7 @@ Comandos:
|
|
|
1225
1381
|
createdByEmail
|
|
1226
1382
|
createdById
|
|
1227
1383
|
}
|
|
1228
|
-
}`,variables:{name:
|
|
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) {
|
|
1229
1385
|
archiveSpace(spaceId: $spaceId) {
|
|
1230
1386
|
_id
|
|
1231
1387
|
name
|
|
@@ -1237,7 +1393,7 @@ Comandos:
|
|
|
1237
1393
|
createdById
|
|
1238
1394
|
archivedAt
|
|
1239
1395
|
}
|
|
1240
|
-
}`,variables:{spaceId:
|
|
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
|
|
1241
1397
|
|
|
1242
1398
|
Herramienta CLI para el equipo Justo.
|
|
1243
1399
|
|
|
@@ -1269,7 +1425,7 @@ Cada grupo de comandos tiene su propia ayuda. Usa \`--help\` para ver los comand
|
|
|
1269
1425
|
- \`graphql\` — Ejecutar queries y mutations GraphQL
|
|
1270
1426
|
- \`admin\` — Comandos administrativos con contexto de website
|
|
1271
1427
|
- \`data\` — Datos y reportes. Puede obtener data de todas las bases de datos de Justo
|
|
1272
|
-
- \`spaces\` — Crea apps React para Spaces con \`spaces init\`, publícalas con \`spaces publish
|
|
1428
|
+
- \`spaces\` — Crea apps React para Spaces con \`spaces init\`, publícalas con \`spaces publish\`, compártelas en intra y usa \`spaces db\` para collections declaradas del space.
|
|
1273
1429
|
|
|
1274
1430
|
## Tips
|
|
1275
1431
|
|
|
@@ -1298,4 +1454,4 @@ Si todavía no sabes bien dónde vive la data, primero usa \`data explain\` para
|
|
|
1298
1454
|
Cuando ya tengas claro un pipeline y solo quieras probarlo una vez, usa \`data execute\`.
|
|
1299
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\`.
|
|
1300
1456
|
|
|
1301
|
-
`}function
|
|
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();
|