@getjusto/team-cli 0.0.15 → 0.0.16
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 +359 -113
- package/package.json +3 -3
package/bin/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
function
|
|
3
|
-
`)}function
|
|
4
|
-
`)}function
|
|
2
|
+
function hC($){let C=[],q={},Q={};for(let J=0;J<$.length;J++)if($[J].startsWith("--")&&$[J+1]&&!$[J+1].startsWith("--")){let j=$[J].slice(2);if(q[j]=$[J+1],!Q[j])Q[j]=[];Q[j].push($[J+1]),J++}else if($[J].startsWith("--"))q[$[J].slice(2)]="true";else C.push($[J]);return{positional:C,flags:q,arrayFlags:Q}}function ZC($,C){let q=$[C];if(!q)throw Error(`--${C} es requerido.`);return q}var N2={comma:",",tab:"\t",pipe:"|"},wC=N2.comma;function z1($){return $.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}function g2($){return $==="true"||$==="false"||$==="null"}function q0($){if($===null)return null;if(typeof $==="object"&&$!==null&&"toJSON"in $&&typeof $.toJSON==="function"){let C=$.toJSON();if(C!==$)return q0(C)}if(typeof $==="string"||typeof $==="boolean")return $;if(typeof $==="number"){if(Object.is($,-0))return 0;if(!Number.isFinite($))return null;return $}if(typeof $==="bigint"){if($>=Number.MIN_SAFE_INTEGER&&$<=Number.MAX_SAFE_INTEGER)return Number($);return $.toString()}if($ instanceof Date)return $.toISOString();if(Array.isArray($))return $.map(q0);if($ instanceof Set)return Array.from($).map(q0);if($ instanceof Map)return Object.fromEntries(Array.from($,([C,q])=>[String(C),q0(q)]));if(k2($)){let C={};for(let q in $)if(Object.prototype.hasOwnProperty.call($,q))C[q]=q0($[q]);return C}return null}function D0($){return $===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean"}function K0($){return Array.isArray($)}function p$($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function XC($){return Object.keys($).length===0}function k2($){if($===null||typeof $!=="object")return!1;let C=Object.getPrototypeOf($);return C===null||C===Object.prototype}function YC($){return $.length===0||$.every((C)=>D0(C))}function S2($){return $.length===0||$.every((C)=>K0(C))}function _1($){return $.length===0||$.every((C)=>p$(C))}function B2($){return/^[A-Z_][\w.]*$/i.test($)}function O2($){return/^[A-Z_]\w*$/i.test($)}function y2($,C=wC){if(!$)return!1;if($!==$.trim())return!1;if(g2($)||x2($))return!1;if($.includes(":"))return!1;if($.includes('"')||$.includes("\\"))return!1;if(/[[\]{}]/.test($))return!1;if(/[\n\r\t]/.test($))return!1;if($.includes(C))return!1;if($.startsWith("-"))return!1;return!0}function x2($){return/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i.test($)||/^0\d+$/.test($)}var d4=Symbol("quotedKey");function c2($,C,q,Q,J,j,G){if(Q.keyFolding!=="safe")return;if(!p$(C))return;let{segments:W,tail:Z,leafValue:X}=v2($,C,G??Q.flattenDepth);if(W.length<2)return;if(!W.every((F)=>O2(F)))return;let Y=b2(W),H=j?`${j}.${Y}`:Y;if(q.includes(Y))return;if(J&&J.has(H))return;return{foldedKey:Y,remainder:Z,leafValue:X,segmentCount:W.length}}function v2($,C,q){let Q=[$],J=C;while(Q.length<q){if(!p$(J))break;let j=Object.keys(J);if(j.length!==1)break;let G=j[0],W=J[G];Q.push(G),J=W}if(!p$(J)||XC(J))return{segments:Q,tail:void 0,leafValue:J};return{segments:Q,tail:J,leafValue:J}}function b2($){return $.join(".")}function h0($,C){if($===null)return"null";if(typeof $==="boolean")return String($);if(typeof $==="number")return String($);return h2($,C)}function h2($,C=wC){if(y2($,C))return $;return`"${z1($)}"`}function HC($){if(B2($))return $;return`"${z1($)}"`}function V1($,C=wC){return $.map((q)=>h0(q,C)).join(C)}function Q0($,C){let q=C?.key,Q=C?.fields,J=C?.delimiter??",",j="";if(q)j+=HC(q);if(j+=`[${$}${J!==wC?J:""}]`,Q){let G=Q.map((W)=>HC(W));j+=`{${G.join(J)}}`}return j+=":",j}function*p2($,C,q){if(D0($)){let Q=h0($,C.delimiter);if(Q!=="")yield Q;return}if(K0($))yield*Aq(void 0,$,q,C);else if(p$($))yield*b0($,q,C)}function*b0($,C,q,Q,J,j){let G=Object.keys($);if(C===0&&!Q)Q=new Set(G.filter((Z)=>Z.includes(".")));let W=j??q.flattenDepth;for(let[Z,X]of Object.entries($))yield*l2(Z,X,C,q,G,Q,J,W)}function*l2($,C,q,Q,J,j,G,W){let Z=G?`${G}.${$}`:$,X=W??Q.flattenDepth;if(Q.keyFolding==="safe"&&J){let H=c2($,C,J,Q,j,G,X);if(H){let{foldedKey:F,remainder:M,leafValue:U,segmentCount:R}=H,E=HC(F);if(M===void 0){if(D0(U)){yield E$(q,`${E}: ${h0(U,Q.delimiter)}`,Q.indent);return}else if(K0(U)){yield*Aq(F,U,q,Q);return}else if(p$(U)&&XC(U)){yield E$(q,`${E}:`,Q.indent);return}}if(p$(M)){yield E$(q,`${E}:`,Q.indent);let V=X-R,I=G?`${G}.${F}`:F;yield*b0(M,q+1,Q,j,I,V);return}}}let Y=HC($);if(D0(C))yield E$(q,`${Y}: ${h0(C,Q.delimiter)}`,Q.indent);else if(K0(C))yield*Aq($,C,q,Q);else if(p$(C)){if(yield E$(q,`${Y}:`,Q.indent),!XC(C))yield*b0(C,q+1,Q,j,Z,X)}}function*Aq($,C,q,Q){if(C.length===0){yield E$(q,Q0(0,{key:$,delimiter:Q.delimiter}),Q.indent);return}if(YC(C)){yield E$(q,lC(C,Q.delimiter,$),Q.indent);return}if(S2(C)){if(C.every((J)=>YC(J))){yield*f2($,C,q,Q);return}}if(_1(C)){let J=m1(C);if(J)yield*u2($,C,J,q,Q);else yield*R1($,C,q,Q);return}yield*R1($,C,q,Q)}function*f2($,C,q,Q){yield E$(q,Q0(C.length,{key:$,delimiter:Q.delimiter}),Q.indent);for(let J of C)if(YC(J)){let j=lC(J,Q.delimiter);yield r$(q+1,j,Q.indent)}}function lC($,C,q){let Q=Q0($.length,{key:q,delimiter:C}),J=V1($,C);if($.length===0)return Q;return`${Q} ${J}`}function*u2($,C,q,Q,J){yield E$(Q,Q0(C.length,{key:$,fields:q,delimiter:J.delimiter}),J.indent),yield*I1(C,q,Q+1,J)}function m1($){if($.length===0)return;let C=$[0],q=Object.keys(C);if(q.length===0)return;if(d2($,q))return q}function d2($,C){for(let q of $){if(Object.keys(q).length!==C.length)return!1;for(let Q of C){if(!(Q in q))return!1;if(!D0(q[Q]))return!1}}return!0}function*I1($,C,q,Q){for(let J of $)yield E$(q,V1(C.map((j)=>J[j]),Q.delimiter),Q.indent)}function*R1($,C,q,Q){yield E$(q,Q0(C.length,{key:$,delimiter:Q.delimiter}),Q.indent);for(let J of C)yield*Uq(J,q+1,Q)}function*s2($,C,q){if(XC($)){yield E$(C,"-",q.indent);return}let Q=Object.entries($),[J,j]=Q[0],G=Q.slice(1);if(K0(j)&&_1(j)){let Z=m1(j);if(Z){if(yield r$(C,Q0(j.length,{key:J,fields:Z,delimiter:q.delimiter}),q.indent),yield*I1(j,Z,C+2,q),G.length>0)yield*b0(Object.fromEntries(G),C+1,q);return}}let W=HC(J);if(D0(j))yield r$(C,`${W}: ${h0(j,q.delimiter)}`,q.indent);else if(K0(j))if(j.length===0)yield r$(C,`${W}${Q0(0,{delimiter:q.delimiter})}`,q.indent);else if(YC(j))yield r$(C,`${W}${lC(j,q.delimiter)}`,q.indent);else{yield r$(C,`${W}${Q0(j.length,{delimiter:q.delimiter})}`,q.indent);for(let Z of j)yield*Uq(Z,C+2,q)}else if(p$(j)){if(yield r$(C,`${W}:`,q.indent),!XC(j))yield*b0(j,C+2,q)}if(G.length>0)yield*b0(Object.fromEntries(G),C+1,q)}function*Uq($,C,q){if(D0($))yield r$(C,h0($,q.delimiter),q.indent);else if(K0($))if(YC($))yield r$(C,lC($,q.delimiter),q.indent);else{yield r$(C,Q0($.length,{delimiter:q.delimiter}),q.indent);for(let Q of $)yield*Uq(Q,C+1,q)}else if(p$($))yield*s2($,C,q)}function E$($,C,q){return" ".repeat(q*$)+C}function r$($,C,q){return E$($,"- "+C,q)}function n2($,C){let q=C("",$,[]);if(q===void 0)return pC($,C,[]);return pC(q0(q),C,[])}function pC($,C,q){if(p$($))return a2($,C,q);if(K0($))return o2($,C,q);return $}function a2($,C,q){let Q={};for(let[J,j]of Object.entries($)){let G=[...q,J],W=C(J,j,G);if(W===void 0)continue;Q[J]=pC(q0(W),C,G)}return Q}function o2($,C,q){let Q=[];for(let J=0;J<$.length;J++){let j=$[J],G=[...q,J],W=C(String(J),j,G);if(W===void 0)continue;let Z=q0(W);Q.push(pC(Z,C,G))}return Q}function Rq($,C){return Array.from(r2($,C)).join(`
|
|
3
|
+
`)}function r2($,C){let q=q0($),Q=t2(C);return p2(Q.replacer?n2(q,Q.replacer):q,Q,0)}function t2($){return{indent:$?.indent??2,delimiter:$?.delimiter??wC,keyFolding:$?.keyFolding??"off",flattenDepth:$?.flattenDepth??Number.POSITIVE_INFINITY,replacer:$?.replacer}}function i2($){let C=$.format??"toon";if(C!=="toon"&&C!=="json")throw Error("--format debe ser toon o json.");return C}function D1($,C){if(i2(C)==="json"){console.log(JSON.stringify($,null,2));return}console.log(Rq($))}function E1($){process.stdout.write(`${$}
|
|
4
|
+
`)}function T1($,C){let Q={ok:!1,error:$ instanceof Error?$.message:String($)};if((C.format==="json"?"json":"toon")==="json"){console.error(JSON.stringify(Q,null,2));return}console.error(Rq(Q))}function T$($){process.stderr.write($)}import{existsSync as uC,mkdirSync as C6,readFileSync as g1,writeFileSync as q6,unlinkSync as Q6}from"node:fs";import{join as k1}from"node:path";import{homedir as J6}from"node:os";import{AsyncLocalStorage as e2}from"node:async_hooks";var $6=new e2;function l$(){return $6.getStore()}var fC={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"},spaces:{local:"http://localhost:4126",develop:"https://spaces.service.bejusto.com",prod:"https://spaces.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"}},L1="prod";function N1($){L1=$}function J0(){let $=process.env.JUSTO_TEAM_CLI_ENV;if($)return $;let C=l$()?.environment;if(C)return C;return L1}function U$($){return fC[$][J0()]}var zq=k1(J6(),".justo-team");function S1($){let C=$==="prod"?"credentials.json":`credentials.${$}.json`;return k1(zq,C)}function _q(){return S1(J0())}function j6(){if(!uC(zq))C6(zq,{recursive:!0})}function dC($){let C=l$();if(C&&C.canPersistCredentials===!1)throw Error("Este entorno no permite guardar credenciales.");j6(),q6(_q(),JSON.stringify($,null,2))}function X$(){let $=process.env.JUSTO_TEAM_CLI_TOKEN,C=process.env.JUSTO_TEAM_CLI_EMAIL,q=process.env.JUSTO_TEAM_CLI_REFRESH_TOKEN;if($&&C)return{email:C,token:$,refreshToken:q||""};let Q=l$()?.credentials;if(Q!==void 0)return Q?{email:Q.email,token:Q.token,refreshToken:Q.refreshToken||""}:null;let J=_q();if(!uC(J))return null;try{let j=g1(J,"utf-8");return JSON.parse(j)}catch{return null}}function B1($){let C=S1($);if(!uC(C))return null;try{let q=g1(C,"utf-8");return JSON.parse(q)}catch{return null}}function Vq(){let $=l$();if($&&$.canPersistCredentials===!1)throw Error("Este entorno no permite borrar credenciales.");let C=_q();if(uC(C))Q6(C)}import{existsSync as O1,mkdirSync as W6,readFileSync as G6,writeFileSync as Z6}from"node:fs";import{homedir as X6}from"node:os";import{join as y1}from"node:path";function Y6(){let $=process.env.JUSTO_TEAM_CLI_DEVICE_ID;if($)return $;let C=l$()?.deviceId;if(C)return C;let q=y1(X6(),".justo-team"),Q=y1(q,"device-id");if(O1(Q))return G6(Q,"utf-8").trim();let J=crypto.randomUUID();if(!O1(q))W6(q,{recursive:!0});return Z6(Q,J),J}var c1={required:({label:$})=>`${$} no es opcional`,notAString:({label:$})=>`${$} no es un texto`,notANumber:({label:$})=>`${$} no es un número`,notAnInteger:({label:$})=>`${$} no es un número entero`,notABoolean:({label:$})=>`${$} no es un valor verdadero o falso`,notAnEmail:({label:$})=>`${$} no es un email`,notAnId:({label:$})=>`${$} no es un ID válido`,notADate:({label:$})=>`${$} no es una fecha válida`,notAnArray:({label:$})=>`${$} no es un arreglo`,notAnObject:({label:$})=>`${$} no es un objeto`,stringTooShort:({label:$})=>`${$} no tiene el largo suficiente`,stringTooLong:"El largo es mayor al permitido",numberTooSmall:({label:$})=>`${$} es un número muy pequeño`,numberTooBig:({label:$})=>`${$} es un número muy grande`,notInSchema:({label:$})=>`${$} no esta permitido`,notUnique:({label:$})=>`${$} no es único`,notFound:({label:$})=>`${$} 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 H6($,C){let q=c1[$];if(!q)return`${C}: ${$}`;if(typeof q==="function")return q({label:C});return q}function x1($){return Object.entries($).map(([C,q])=>H6(q,C)).join(", ")}function w6($){if($.error==="validationError"&&$.validationErrors)return x1($.validationErrors);if($.extensions?.code==="PermissionsError"){let J=$.extensions.info?.type;if(J?.includes("User doesn't have permissions for "))return`Tu usuario no tiene permisos para [${J.split("User doesn't have permissions for ")[1]}]`;return $.message}if($.validationErrors)return`${$.message} (${x1($.validationErrors)})`;let C=$.message||"Error desconocido",q=c1[C];if(q)return typeof q==="function"?q({label:""}).trim():q;let Q=$.error||$.code||$.type;return Q?`${C} [${Q}]`:C}function F6($){try{return JSON.parse(Buffer.from($.split(".")[1],"base64").toString()).exp*1000<Date.now()}catch{return!0}}async function P6(){let $=X$();if(!$?.refreshToken)return null;let C=`${U$("auth")}/refresh-token`,Q=await(await fetch(C,{method:"POST",headers:{"X-ORION-REFRESH":$.refreshToken}})).json();if(!Q.token)return null;if(l$()?.canPersistCredentials!==!1)dC({...$,token:Q.token});return Q.token}async function sC(){let $=X$();if(!$?.token)return;if(!F6($.token))return $.token;return await P6()??void 0}async function p0($="application/json"){let C=await sC(),q={"Content-Type":$,"X-ORION-DEVICEID":Y6(),"X-ORION-PLATFORM":"web"};if(C)q["x-orion-jwt"]=C;return q}class t$ extends Error{code;constructor($,C){super($);this.code=C}}async function h($){let C=`${U$($.service)}/graphql`,q=await p0(),Q;try{Q=await fetch(C,{method:"POST",headers:q,body:JSON.stringify({query:$.query,variables:$.variables}),signal:AbortSignal.timeout($.timeoutMs||15000)})}catch(j){if(j instanceof Error&&j.name==="TimeoutError")throw new t$("La solicitud tardó demasiado. Intenta de nuevo.","clientTimeout");throw new t$("No pude conectarme con el servidor de Justo. Revisa tu conexión (o la VPN) e intenta de nuevo.","networkError")}let J=await Q.json();if(J.errors?.length){let j=J.errors[0];throw new t$(w6(j),j.error??j.extensions?.code)}if(!J.data)throw Error("No data returned from server");return J.data}function M6($){return $.replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,"")}function K6($){return $.includes(".")||$.startsWith("http://")||$.startsWith("https://")}async function l0($){if(K6($)){let C=M6($),q=await fetch(`${U$("main")}/website-id/${C}`,{signal:AbortSignal.timeout(1e4)});if(!q.ok)throw Error(`No se encontro el sitio "${C}"`);let Q=await q.json();if(!Q.websiteId)throw Error(`No se pudo resolver el websiteId para "${C}"`);return{input:$,websiteId:Q.websiteId,targetType:"domain"}}return{input:$,websiteId:$,targetType:"websiteId"}}async function v1($){let C=await h({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 o=[],a={},t={};for(let m=0;m<c.length;m++)if(c[m].startsWith(
|
|
|
13
13
|
timezone
|
|
14
14
|
defaultMenuId
|
|
15
15
|
}
|
|
16
|
-
}`,variables:{websiteId
|
|
16
|
+
}`,variables:{websiteId:$}});if(!C.website)throw Error(`No se encontro el website "${$}"`);return C.website}function A6(){if(!X$())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 b1($){if(A6(),!$)throw Error("Uso: team-cli admin <websiteId|domain> show");let C=await l0($),q=await v1(C.websiteId);return{context:C,website:q}}function nC(){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 h1=`
|
|
39
39
|
availableAtPeriods
|
|
40
40
|
closedDays
|
|
41
41
|
closedUntilDate
|
|
@@ -51,7 +51,7 @@ Modulos:
|
|
|
51
51
|
fromMinute
|
|
52
52
|
toMinute
|
|
53
53
|
}
|
|
54
|
-
`,
|
|
54
|
+
`,aC=`
|
|
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
|
+
${h1}
|
|
90
90
|
}
|
|
91
91
|
scheduleAtUse {
|
|
92
|
-
${
|
|
92
|
+
${h1}
|
|
93
93
|
}
|
|
94
94
|
codesCode
|
|
95
|
-
`,
|
|
95
|
+
`,p1=`
|
|
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 mq(){if(!X$())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 f0($,C){let q=$[C];if(!q)throw Error(`--${C} es requerido.`);try{return JSON.parse(q)}catch{throw Error(`--${C} debe ser un JSON válido.`)}}function i$($,C){let q=$[C];if(!q)return;let Q=Number.parseInt(q,10);if(Number.isNaN(Q))throw Error(`--${C} debe ser un número entero.`);return Q}function l1($,C){let q=$[C];if(!q)return;if(q==="true")return!0;if(q==="false")return!1;throw Error(`--${C} debe ser true o false.`)}async function f$($){if(mq(),!$)throw Error("Debes indicar <websiteId|domain>.");return l0($)}async function j0($,C){let q=await h({service:"main",query:`query ($couponId: ID) {
|
|
105
105
|
coupon(couponId: $couponId) {
|
|
106
106
|
_id
|
|
107
107
|
websiteId
|
|
108
108
|
}
|
|
109
|
-
}`,variables:{couponId
|
|
109
|
+
}`,variables:{couponId:$}});if(!q.coupon)throw Error(`No se encontró el cupón "${$}"`);if(q.coupon.websiteId!==C)throw Error(`El cupón "${$}" no pertenece al website seleccionado.`);return q.coupon}function U6($){if(!Array.isArray($))throw Error("--input debe ser un arreglo JSON.");return $.map((C)=>{if(!C||typeof C!=="object"||typeof C.code!=="string")throw Error('Cada item de --input debe tener al menos { "code": "..." }.');if(C.userEmail!=null&&typeof C.userEmail!=="string")throw Error("userEmail debe ser string cuando viene informado.");return{code:C.code,userEmail:C.userEmail}})}function R6($){if(!Array.isArray($)||$.some((C)=>typeof C!=="string"))throw Error("--ids debe ser un arreglo JSON de strings.");return $}async function f1($,C,q){let Q=await f$($);await j0(C,Q.websiteId);let J=i$(q,"limit"),j=i$(q,"page"),G=q.filter,W=await h({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
|
+
${p1}
|
|
113
113
|
}
|
|
114
114
|
totalCount
|
|
115
115
|
totalPages
|
|
116
116
|
hasNextPage
|
|
117
117
|
hasPreviousPage
|
|
118
118
|
}
|
|
119
|
-
}`,variables:{couponId:
|
|
119
|
+
}`,variables:{couponId:C,filter:G,limit:J,page:j}});return{context:Q,couponId:C,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:j??1,limit:J??null}}}async function u1($,C,q){let Q=await f$($);await j0(C,Q.websiteId);let J=U6(f0(q,"input")),j=J.some((W)=>W.userEmail),G=await h({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:C,codesWithEmail:J,useCodeWithEmail:j}});return{context:Q,couponId:C,requestedCount:J.length,result:G.createCouponCodes}}async function d1($,C,q){let Q=await f$($);await j0(C,Q.websiteId);let J=i$(q,"quantity");if(!J)throw Error("--quantity es requerido.");let j=await h({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:C,couponQuantity:J,couponCodePrefix:q.prefix}});return{context:Q,couponId:C,quantity:J,prefix:q.prefix??null,result:j.createRandomCouponCodes}}async function s1($,C,q){let Q=await f$($);await j0(C,Q.websiteId);let J=R6(f0(q,"ids")),j=await h({service:"main",query:`mutation ($couponId: ID, $couponCodesIds: [ID]) {
|
|
124
124
|
deleteCouponCodes(couponId: $couponId, couponCodesIds: $couponCodesIds, globalCoupon: false)
|
|
125
|
-
}`,variables:{couponId:
|
|
125
|
+
}`,variables:{couponId:C,couponCodesIds:J}});return{context:Q,couponId:C,deleted:j.deleteCouponCodes,couponCodesIds:J}}function n1(){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 a1={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 z6($){let C=Object.entries($).filter(([,j])=>j!==void 0),q=C.map(([j])=>j).filter((j)=>!a1[j]);if(q.length)throw Error(`Campos no soportados para create: ${q.join(", ")}`);let Q=C.map(([j])=>`$${j}: ${a1[j]}`).join(", "),J=C.map(([j])=>`${j}: $${j}`).join(", ");return`mutation (${Q}) {
|
|
149
|
+
createCoupon(${J}) {
|
|
150
|
+
${aC}
|
|
151
151
|
}
|
|
152
|
-
}`}async function
|
|
152
|
+
}`}async function o1($,C){let q=await f$($),Q=i$(C,"limit"),J=i$(C,"page"),j=C.filter,G=await h({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:q.websiteId,filter:j,limit:Q,page:J}});return{context:q,coupons:G.coupons.items??[],pagination:{totalCount:G.coupons.totalCount??0,totalPages:G.coupons.totalPages??0,hasNextPage:Boolean(G.coupons.hasNextPage),hasPreviousPage:Boolean(G.coupons.hasPreviousPage),page:J??1,limit:Q??null}}}async function r1($,C){let q=await f$($);await j0(C,q.websiteId);let Q=await h({service:"main",query:`query ($couponId: ID) {
|
|
173
173
|
coupon(couponId: $couponId) {
|
|
174
|
-
${
|
|
174
|
+
${aC}
|
|
175
175
|
}
|
|
176
|
-
}`,variables:{couponId:
|
|
176
|
+
}`,variables:{couponId:C}});return{context:q,coupon:Q.coupon}}async function t1($,C){let q=await f$($),Q=f0(C,"input");if(Q.websiteId&&Q.websiteId!==q.websiteId)throw Error("El websiteId del input no coincide con el website seleccionado.");let J={...Q,websiteId:q.websiteId},j=z6(J),G=await h({service:"main",query:j,variables:J});return{context:q,coupon:G.createCoupon}}async function i1($,C,q){let Q=await f$($);await j0(C,Q.websiteId);let J=f0(q,"input"),j=await h({service:"main",query:`mutation ($couponId: ID, $coupon: UpdateCouponInput) {
|
|
177
177
|
updateCoupon(couponId: $couponId, coupon: $coupon) {
|
|
178
|
-
${
|
|
178
|
+
${aC}
|
|
179
179
|
}
|
|
180
|
-
}`,variables:{couponId:
|
|
180
|
+
}`,variables:{couponId:C,coupon:J}});return{context:Q,coupon:j.updateCoupon}}async function e1($,C){let q=await f$($);await j0(C,q.websiteId);let Q=await h({service:"main",query:`mutation ($couponsIds: [ID]) {
|
|
181
181
|
deleteCoupons(couponsIds: $couponsIds, globalCoupon: false)
|
|
182
|
-
}`,variables:{couponsIds:[
|
|
182
|
+
}`,variables:{couponsIds:[C]}});return{context:q,couponId:C,deleted:Q.deleteCoupons}}function FC(){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 $Q(){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 CQ(){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 Iq($){return(await h({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:$})).websites}async function qQ($,C){mq();let q=$[2]??C.filter;if(!q)throw Error("Debes indicar un término de búsqueda. Uso: team-cli admin search <texto>");let Q=i$(C,"limit"),J=i$(C,"page"),j=l1(C,"only-active"),G=await Iq({filter:q,limit:Q,page:J,onlyActiveWebsites:j});return{searchTerm:q,websites:G.items??[],pagination:{totalCount:G.totalCount??0,totalPages:G.totalPages??0,hasNextPage:Boolean(G.hasNextPage),hasPreviousPage:Boolean(G.hasPreviousPage),page:J??1,limit:Q??null}}}function QQ(){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 _6(){if(!X$())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 V6($){let C=[$.address?.streetAddress,$.address?.extendedAddress,$.address?.locality].filter(Boolean);if(!C.length)return null;return C.join(", ")}async function JQ($){if(_6(),!$)throw Error("Uso: team-cli admin <websiteId|domain> stores list");let C=await l0($),Q=((await h({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:C.websiteId}})).stores.items??[]).map((J)=>({_id:J._id,name:J.name,address:V6(J)})).sort((J,j)=>J.name.localeCompare(j.name,"es",{sensitivity:"base"}));return{context:C,stores:Q,totalCount:Q.length}}import{createInterface as m6}from"node:readline";function u0($){if(process.env.JUSTO_TEAM_CLI_INTERACTIVE==="false")throw Error("Este entorno no soporta prompts interactivos.");if(l$()?.interactive===!1)throw Error("Este entorno no soporta prompts interactivos.");let C=m6({input:process.stdin,output:process.stderr});return new Promise((q)=>{C.question($,(Q)=>{C.close(),q(Q.trim())})})}async function jQ($){return(await h({service:"auth",query:`mutation ($email: String!) {
|
|
370
370
|
requestLoginCode(email: $email)
|
|
371
|
-
}`,variables:{email
|
|
371
|
+
}`,variables:{email:$}})).requestLoginCode}async function WQ($,C,q){let Q=await h({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
|
|
377
|
-
`);let
|
|
378
|
-
`);let
|
|
379
|
-
`);let
|
|
376
|
+
}`,variables:{email:$,token:C,code:q.toUpperCase()}});dC({email:$,token:Q.loginWithCode.token,refreshToken:Q.loginWithCode.refreshToken}),await I6()}async function I6(){if(!(await h({service:"main",query:"query { me { roles } }"})).me?.roles?.length)throw Vq(),Error("Solo miembros del equipo Justo pueden usar esta herramienta.")}async function GQ(){let $=await u0("Email: ");T$(`Enviando codigo de verificacion...
|
|
377
|
+
`);let C=await jQ($);T$(`Codigo enviado a tu email.
|
|
378
|
+
`);let q=await u0("Codigo: ");return await WQ($,C,q),{ok:!0,authenticated:!0,email:$}}async function ZQ($){let C=ZC($,"email"),q=ZC($,"token"),Q=ZC($,"code");return await WQ(C,q,Q),{ok:!0,authenticated:!0,email:C}}async function XQ($){let C=ZC($,"email");T$(`Enviando codigo de verificacion...
|
|
379
|
+
`);let q=await jQ(C);return{ok:!0,email:C,token:q,nextCommand:`npx @getjusto/team-cli auth login-with-token --email ${C} --token ${q} --code <CODIGO>`}}async function YQ(){return Vq(),{ok:!0,authenticated:!1}}async function HQ(){let $=X$();if(!$)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:$.email}}function Dq(){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 O6}from"node:fs";import{mkdtempSync as D6,readFileSync as E6,rmSync as T6,writeFileSync as L6}from"node:fs";import{tmpdir as N6}from"node:os";import{join as wQ}from"node:path";import{spawnSync as g6}from"node:child_process";function k6($){return`'${$.replaceAll("'",`'"'"'`)}'`}function FQ($,C){if($==null)return;if(!Array.isArray($)||$.some((q)=>typeof q!=="string"))throw Error(`${C} debe ser un arreglo de strings.`);return $}function S6($){if(!Array.isArray($))throw Error("variables debe ser un arreglo.");return $.map((C,q)=>{if(!C||typeof C!=="object"||Array.isArray(C))throw Error(`variables[${q}] debe ser un objeto.`);let Q=C;if(typeof Q.key!=="string"||!Q.key)throw Error(`variables[${q}].key debe ser un string no vacío.`);if(typeof Q.fieldType!=="string"||!Q.fieldType)throw Error(`variables[${q}].fieldType debe ser un string no vacío.`);if(Q.fieldParams!=null&&typeof Q.fieldParams!=="string")throw Error(`variables[${q}].fieldParams debe ser un string.`);return{key:Q.key,fieldType:Q.fieldType,fieldParams:typeof Q.fieldParams==="string"?Q.fieldParams:void 0}})}function B6($){if(!$||typeof $!=="object"||Array.isArray($))throw Error("El archivo editado debe contener un objeto JSON.");let C=$;if(typeof C.name!=="string"||!C.name.trim())throw Error("name debe ser un string no vacío.");if(C.description!=null&&typeof C.description!=="string")throw Error("description debe ser un string.");if(typeof C.collection!=="string"||!C.collection.trim())throw Error("collection debe ser un string no vacío.");if(typeof C.pipeline!=="string")throw Error("pipeline debe ser un string.");return{name:C.name.trim(),description:C.description?.trim()||void 0,collection:C.collection.trim(),allowedUsersIds:FQ(C.allowedUsersIds,"allowedUsersIds")??[],tags:FQ(C.tags,"tags")??[],pipeline:C.pipeline,variables:S6(C.variables)}}function PQ($){let C=process.env.VISUAL||process.env.EDITOR||"vi",q=D6(wQ(N6(),"team-cli-query-")),Q=wQ(q,"aggregation-query.json");L6(Q,`${JSON.stringify($,null,2)}
|
|
406
|
+
`);let J=`${C} ${k6(Q)}`,j=g6(J,{shell:!0,stdio:"inherit"});if(j.error)throw Error(`No se pudo abrir el editor "${C}": ${j.error.message}`);if(j.status!==0)throw Error(`El editor terminó con código ${j.status}.`);try{let G=E6(Q,"utf-8");if(!G.trim())throw Error("El archivo quedó vacío.");let W;try{W=JSON.parse(G)}catch{throw Error("El archivo editado no contiene JSON válido.")}return B6(W)}finally{T6(q,{recursive:!0,force:!0})}}function Y$(){if(!X$())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 W0($,C){let q=$[3];if(!q)throw Error(`Uso: ${C}`);return q}function d0($){if(!$.params)return{};try{return JSON.parse($.params)}catch{throw Error("--params debe ser un JSON válido.")}}function Eq($){let C=$.limit;if(!C)throw Error("--limit es requerido. Ejemplo: --limit 1000");let q=Number(C);if(!Number.isInteger(q)||q<=0)throw Error("--limit debe ser un entero positivo.");return q}function MQ($){let C=$.emails;if(!C)throw Error("--emails es requerido. Ejemplo: --emails ana@justo.com,bob@justo.com");let q=C.split(",").map((J)=>J.trim().toLowerCase()).filter(Boolean);if(!q.length)throw Error("--emails debe contener al menos un email.");let Q=q.find((J)=>!J.includes("@"));if(Q)throw Error(`Email inválido: ${Q}`);return[...new Set(q)]}function Tq($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return{value:$}}}async function s0($){return(await h({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
|
|
422
|
+
}`,variables:{aggregationQueryId:$}})).aggregationQuery}async function KQ($){return await Promise.all($.map(async(q)=>{let J=(await h({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:q,limit:10}})).justoUsers?.items?.find((j)=>j.email?.toLowerCase()===q);if(!J?._id)throw Error(`No encontramos un usuario de Justo para ${q}`);return J}))}function AQ($){return{name:$.name,description:$.description,collection:$.collection,allowedUsersIds:$.allowedUsersIds??[],tags:$.tags??[],pipeline:$.pipeline,variables:$.variables??[]}}async function Lq($,C){let q=await h({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
|
|
431
431
|
testAggregationQuery(aggregationQueryId: $aggregationQueryId, params: $params)
|
|
432
|
-
}`,variables:{aggregationQueryId
|
|
433
|
-
`);while(
|
|
434
|
-
`)}}let
|
|
432
|
+
}`,variables:{aggregationQueryId:$,params:C}});return Tq(q.testAggregationQuery)}async function UQ($){let C=await fetch(`${U$("data")}/execute-pipeline`,{method:"POST",headers:await p0(),body:JSON.stringify({collection:$.collection,pipeline:$.pipeline,params:$.queryParams,limit:$.limit}),signal:AbortSignal.timeout(75000)});if(!C.ok){let q=await C.text();throw Error(RQ(q)||"No se pudo ejecutar el pipeline.")}return await C.json()}function RQ($){try{return JSON.parse($).error||$}catch{return $}}async function zQ($,C,q){let Q=await fetch(`${U$("data")}/aggregation-queries/${$}/run`,{method:"POST",headers:await p0(),body:JSON.stringify({params:C,limit:q}),signal:AbortSignal.timeout(315000)});if(!Q.ok){let X=await Q.text();throw Error(RQ(X)||"No se pudo ejecutar el query.")}if(!Q.body)throw Error("El servidor no devolvió un stream de datos.");let J=Q.body.getReader(),j=new TextDecoder,G="",W=0;while(!0){let{done:X,value:Y}=await J.read();if(X)break;let H=j.decode(Y,{stream:!0});process.stdout.write(H),G+=H;let F=G.indexOf(`
|
|
433
|
+
`);while(F>=0){if(G.slice(0,F).trim())W++;G=G.slice(F+1),F=G.indexOf(`
|
|
434
|
+
`)}}let Z=j.decode();if(Z)process.stdout.write(Z),G+=Z;if(G.trim())W++;return{ok:!0,queryId:$,limit:q,rows:W}}async function Nq($,C){await gq($,{name:C.name,description:C.description,collection:C.collection,allowedUsersIds:C.allowedUsersIds,tags:C.tags}),await h({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
|
|
443
|
+
}`,variables:{aggregationQueryId:$,pipeline:C.pipeline,variables:C.variables}})}async function gq($,C){await h({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
|
|
456
|
+
}`,variables:{aggregationQueryId:$,aggregationQuery:{name:C.name,description:C.description,collection:C.collection,allowedUsersIds:C.allowedUsersIds,tags:C.tags}}})}async function _Q(){return(await h({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 y6($){if(!Array.isArray($))throw Error("El preview del query debe devolver un arreglo para usar AI edit.");return $}async function x6($){let C=await h({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
|
|
498
|
+
}`,variables:$});if(!C.generateAdminQuery?.pipeline||!C.generateAdminQuery.fullCollectionName)throw Error("La IA no devolvió una versión válida del query.");return C.generateAdminQuery}async function c6($){let C=await h({service:"messenger",timeoutMs:120000,query:`mutation explainAdminQuery($prompt: String) {
|
|
499
499
|
explainAdminQuery(prompt: $prompt) {
|
|
500
500
|
responseText
|
|
501
501
|
}
|
|
502
|
-
}`,variables:{prompt
|
|
503
|
-
`);try{let
|
|
504
|
-
`);let
|
|
505
|
-
`);let
|
|
502
|
+
}`,variables:{prompt:$}});if(!C.explainAdminQuery?.responseText)throw Error("La IA no devolvió una explicación válida.");return C.explainAdminQuery}async function VQ(){return Y$(),await _Q()}async function mQ($){Y$();let C=$.prompt||await u0("Explica qué query quieres investigar o construir: ");if(!C)throw Error("Debes indicar un prompt para explain.");return(await c6(C)).responseText}async function IQ($){if(Y$(),!$.collection)throw Error("Debes indicar --collection con formato db.collection. Ejemplo: --collection justo.users");if(!$.pipeline)throw Error("Debes indicar --pipeline. Ejemplo: --pipeline '[{$limit: 5}]'");let C=$.limit?Eq($):void 0;return await UQ({collection:$.collection,pipeline:$.pipeline,queryParams:d0($),limit:C})}async function DQ($){Y$();let C=W0($,"team-cli data queries edit <queryId>"),q=await s0(C),Q=PQ(AQ(q));return await Nq(C,Q),{ok:!0,queryId:C,name:Q.name,collection:Q.collection}}async function EQ($,C){Y$();let q=W0($,"team-cli data queries ai-edit <queryId> --prompt '<texto>' [--params '<json>']"),Q=await s0(q),J=C.prompt||await u0("Describe los cambios para la IA: ");if(!J)throw Error("Debes indicar un prompt para AI edit.");let j=d0(C),G;if(C.params){T$(`Obteniendo preview del query actual...
|
|
503
|
+
`);try{let Z=await Lq(q,j);G=y6(Z)}catch(Z){let X=Z instanceof Error?Z.message:String(Z);throw Error(`No se pudo obtener el preview para AI edit: ${X}`)}}T$(`Generando propuesta con IA...
|
|
504
|
+
`);let W=await x6({prompt:J,fullCollectionName:Q.collection,pipeline:Q.pipeline,preview:G,description:Q.description,name:Q.name,variables:Q.variables});return await Nq(q,{name:Q.name==="Nuevo query"?W.aggregationName||Q.name:Q.name,description:Q.description||W.aggregationDescription,collection:W.fullCollectionName,allowedUsersIds:Q.allowedUsersIds??[],tags:Q.tags??[],pipeline:W.pipeline,variables:W.variables??[]}),{ok:!0,queryId:q,responseText:W.responseText,collection:W.fullCollectionName,name:W.aggregationName,description:W.aggregationDescription}}async function TQ($){Y$();let C=W0($,"team-cli data queries view <queryId>");return await s0(C)}async function LQ($){Y$();let C=W0($,"team-cli data queries view-pipeline <queryId>"),q=await s0(C);return{queryId:C,pipeline:q.pipeline}}async function NQ($,C){Y$();let q=W0($,"team-cli data queries preview <queryId> --params '<json>'"),Q=d0(C),J=await Lq(q,Q);return Tq(J)}async function gQ($,C){Y$();let q=W0($,"team-cli data queries run <queryId> --limit <n> --params '<json>'"),Q=d0(C),J=Eq(C);return await zQ(q,Q,J),{__streamHandled:!0}}async function kQ($,C){Y$();let q=W0($,"team-cli data queries add-viewers <queryId> --emails 'ana@justo.com,bob@justo.com'"),Q=MQ(C),J=await s0(q),j=await KQ(Q),G=[...new Set([...J.allowedUsersIds??[],...j.map((W)=>W._id)])];return await gq(q,{name:J.name,description:J.description,collection:J.collection,allowedUsersIds:G,tags:J.tags??[]}),{ok:!0,queryId:q,addedViewers:j.map((W)=>({_id:W._id,email:W.email,fullName:W.fullName})),allowedUsersIds:G}}function v6($){return new Promise((C)=>setTimeout(C,$))}async function SQ($,C){Y$();let q=W0($,"team-cli data queries download <queryId> --params '<json>'"),Q=d0(C);if(!C.path)throw Error("--path es requerido. Ejemplo: --path resultado.xlsx");T$(`Iniciando descarga...
|
|
505
|
+
`);let j=(await h({service:"data",query:`mutation ($aggregationQueryId: String, $params: JSON) {
|
|
506
506
|
downloadAggregationQueryData(aggregationQueryId: $aggregationQueryId, params: $params)
|
|
507
|
-
}`,variables:{aggregationQueryId:
|
|
508
|
-
`);let
|
|
507
|
+
}`,variables:{aggregationQueryId:q,params:Q}})).downloadAggregationQueryData;T$(`Reporte en proceso (${j})...
|
|
508
|
+
`);let G=null;while(!G){await v6(1000);let X=await h({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:j}}),Y=X.getAsyncReport,H=X.getAsyncReportRecordsCount;if(Y.status==="error")throw Error("El reporte falló al generarse.");if(Y.fileUrl)G=Y.fileUrl;else{let F=Y.estimatedRecordsCount?` (~${Y.estimatedRecordsCount} registros)`:"",M=H!=null?` ${H} procesados`:"";T$(`\rGenerando...${F}${M}`)}}T$(`
|
|
517
517
|
Descargando archivo...
|
|
518
|
-
`);let
|
|
518
|
+
`);let W=await fetch(G);if(!W.ok)throw Error(`Error descargando archivo: ${W.status}`);let Z=Buffer.from(await W.arrayBuffer());return O6(C.path,Z),{ok:!0,queryId:q,asyncReportId:j,outputPath:C.path,fileUrl:G}}function kq(){return`team-cli data
|
|
519
519
|
|
|
520
520
|
Comandos de datos y reportes.
|
|
521
521
|
|
|
@@ -615,26 +615,26 @@ 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'`}function
|
|
619
|
-
`,
|
|
618
|
+
team-cli data queries add-viewers abc123 --emails 'ana@justo.com,bob@justo.com'`}function BQ($,C){let q=C;while(q<$.length){let Q=$[q];if(/\s/.test(Q)){q+=1;continue}if(Q==="#"){let J=$.indexOf(`
|
|
619
|
+
`,q);if(J===-1)return $.length;q=J+1;continue}return q}return q}function OQ($,C){let q=/^[_A-Za-z][_0-9A-Za-z]*/.exec($.slice(C));if(!q)return null;return{name:q[0],end:C+q[0].length}}function yQ($){let C=$.replace(/^\uFEFF/,""),q=BQ(C,0);if(q>=C.length)return{type:"unknown"};if(C[q]==="{")return{type:"query"};let Q=OQ(C,q);if(!Q)return{type:"unknown"};if(!["query","mutation","subscription"].includes(Q.name))return{type:"unknown"};q=BQ(C,Q.end);let j=OQ(C,q)?.name;return{type:Q.name,name:j}}import{spawnSync as cQ}from"node:child_process";import{stdin as b6,stdout as xQ}from"node:process";import{createInterface as h6}from"node:readline/promises";function p6($){if(!$)return"{}";return JSON.stringify($,null,2)}function l6($,C){if($.length<=C)return $;return`${$.slice(0,C)}
|
|
620
620
|
|
|
621
|
-
[Contenido truncado en esta ventana]`}function
|
|
622
|
-
`)}function
|
|
623
|
-
`)}function
|
|
621
|
+
[Contenido truncado en esta ventana]`}function vQ($){return["Esta operación puede modificar datos.","",`Servicio: ${$.service}`,`Ambiente: ${$.environment}`,`Operación: ${$.operationName??"mutation"}`,`Endpoint: ${$.endpoint}`].join(`
|
|
622
|
+
`)}function Sq($){return["Query:",$.query,"","Variables:",p6($.variables)].join(`
|
|
623
|
+
`)}function f6($){let C=l6(`${vQ($)}
|
|
624
624
|
|
|
625
|
-
${
|
|
625
|
+
${Sq($)}`,7000),q=`
|
|
626
626
|
on run argv
|
|
627
627
|
set dialogMessage to item 1 of argv
|
|
628
628
|
display dialog dialogMessage buttons {"Cancelar", "Ejecutar"} default button "Cancelar" cancel button "Cancelar" with title "Confirmar mutation GraphQL" with icon caution
|
|
629
629
|
return button returned of result
|
|
630
630
|
end run
|
|
631
|
-
`,
|
|
631
|
+
`,Q=cQ("osascript",["-e",`
|
|
632
632
|
on run argv
|
|
633
633
|
set dialogMessage to item 1 of argv
|
|
634
634
|
display dialog dialogMessage buttons {"Cancelar", "Ejecutar"} default button "Cancelar" cancel button "Cancelar" with title "Confirmar mutation GraphQL" with icon caution
|
|
635
635
|
return button returned of result
|
|
636
636
|
end run
|
|
637
|
-
`,
|
|
637
|
+
`,C],{encoding:"utf8"});if(Q.error)return null;return Q.status===0&&Q.stdout.trim()==="Ejecutar"}function u6($){let q={service:$.service,environment:$.environment,operationName:$.operationName??"mutation",endpoint:$.endpoint,details:Sq($)},Q=cQ("powershell.exe",["-STA","-NoProfile","-Command",`
|
|
638
638
|
Add-Type -AssemblyName System.Windows.Forms
|
|
639
639
|
Add-Type -AssemblyName System.Drawing
|
|
640
640
|
|
|
@@ -723,11 +723,11 @@ $form.CancelButton = $cancelButton
|
|
|
723
723
|
$result = $form.ShowDialog()
|
|
724
724
|
if ($result -eq [System.Windows.Forms.DialogResult]::OK) { exit 0 }
|
|
725
725
|
exit 2
|
|
726
|
-
`],{input:JSON.stringify(
|
|
726
|
+
`],{input:JSON.stringify(q),encoding:"utf8"});if(Q.error)return null;if(Q.status===0)return!0;if(Q.status===2)return!1;return null}async function d6($){if(!process.stdin.isTTY||!process.stdout.isTTY)return null;xQ.write(`${vQ($)}
|
|
727
727
|
|
|
728
|
-
${
|
|
728
|
+
${Sq($)}
|
|
729
729
|
|
|
730
|
-
`);let
|
|
730
|
+
`);let C=h6({input:b6,output:xQ});try{return(await C.question('Ejecutar mutation? Escribe "si" para confirmar: ')).trim().toLowerCase()==="si"}finally{C.close()}}async function bQ($){let C={...$,environment:J0(),endpoint:`${U$($.service)}/graphql`},q=null;if(process.platform==="darwin")q=f6(C);if(process.platform==="win32")q=u6(C);if(q===null)q=await d6(C);if(q===null)throw Error("No se pudo abrir una confirmación para ejecutar el mutation.");if(!q)throw Error("Mutation rechazada por el usuario. No se ejecutó ninguna llamada.")}var hQ=["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"],pQ=`
|
|
731
731
|
query ResolverInfo($name: ID!, $mutation: Boolean!) {
|
|
732
732
|
params(name: $name, mutation: $mutation) {
|
|
733
733
|
name
|
|
@@ -736,8 +736,8 @@ ${io(c)}
|
|
|
736
736
|
basicResultQuery
|
|
737
737
|
}
|
|
738
738
|
}
|
|
739
|
-
`;function
|
|
740
|
-
`)}function
|
|
739
|
+
`;function s6($){if(!$)throw Error("Uso: team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]");if(!hQ.includes($))throw Error(`Servicio "${$}" no válido. Servicios disponibles: ${hQ.join(", ")}`)}async function n6($,C){let q;try{let Q=await h({service:$,query:pQ,variables:{name:C,mutation:!1}});return{service:$,operationName:C,operationType:"query",info:Q.params}}catch(Q){q=Q}try{let Q=await h({service:$,query:pQ,variables:{name:C,mutation:!0}});return{service:$,operationName:C,operationType:"mutation",info:Q.params}}catch(Q){let J=q instanceof Error?q.message:"",j=Q instanceof Error?Q.message:"";if(J.includes('Cannot query field "params"')||j.includes('Cannot query field "params"'))throw Error(`El servicio "${$}" no expone metadata de resolvers por GraphQL.`);throw q instanceof Error?q:Q}}async function lQ($,C){let q=$[1],Q=$[2],J=$[2];if(!X$())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(s6(q),Q==="info"){let Z=$[3];if(!Z)throw Error("Uso: team-cli graphql <servicio> info <queryName|mutationName> [--format toon|json]");return await n6(q,Z)}if(!J)throw Error("Uso: team-cli graphql <servicio> '<query>' [--variables '<json>'] [--format toon|json]");let j;if(C.variables)try{j=JSON.parse(C.variables)}catch{throw Error("Las variables deben ser un JSON válido.")}let G=yQ(J);if(G.type==="mutation"&&J0()!=="local")await bQ({service:q,query:J,variables:j,operationName:G.name});return await h({service:q,query:J,variables:j})}function fQ(){return Object.keys(fC)}function a6(){return fQ().map(($)=>{let C=fC[$].prod;return`- \`${$}\`: \`${C}/graphql\``}).join(`
|
|
740
|
+
`)}function uQ(){let C=fQ().join(", "),q=a6();return`team-cli graphql
|
|
741
741
|
|
|
742
742
|
Ejecutar queries y mutations GraphQL.
|
|
743
743
|
|
|
@@ -755,7 +755,7 @@ Formato:
|
|
|
755
755
|
|
|
756
756
|
|
|
757
757
|
|
|
758
|
-
Servicios disponibles: ${
|
|
758
|
+
Servicios disponibles: ${C}.
|
|
759
759
|
|
|
760
760
|
Ejemplos:
|
|
761
761
|
\`\`\`bash
|
|
@@ -788,13 +788,13 @@ npx @getjusto/team-cli graphql auth info requestLoginCode --format json
|
|
|
788
788
|
|
|
789
789
|
Usa esto para mapear una URL GraphQL al valor correcto de \`team-cli graphql <service>\`.
|
|
790
790
|
|
|
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)
|
|
793
|
-
`:" "}${
|
|
794
|
-
`:""}${
|
|
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
|
-
${
|
|
797
|
-
${
|
|
791
|
+
${q}`}var PC={medido:"27 nov 2026",fuente:"1.521 marcas de KAM y Partner Experience, historia mensual de noviembre de 2024 a octubre de 2026. Cuatro análisis independientes, cada uno replicado desde cero y revisado por un escéptico de método (posventa-360/analisis/activacion).",requisitos:{appPropia:{pedidosMes:27,texto:"9 de cada 10 marcas que la usan venden 27 pedidos online al mes o más (la mitad, más de 380)"},commander:{pedidosMes:34,texto:"9 de cada 10 marcas que lo usan venden 34 pedidos online al mes o más"},instagramOrderFood:{pedidosMes:22,texto:"9 de cada 10 marcas que lo usan venden 22 pedidos online al mes o más"},sac:{pedidosMes:298,texto:"lo usan 15 marcas, todas con unos 300 pedidos online al mes o más"},adelantoDePagos:{pedidosMes:12,texto:"9 de cada 10 marcas que lo usan venden 12 pedidos online al mes o más"},loyalty:{texto:"no tiene piso: lo usan marcas de todos los tamaños, incluso las que venden casi solo en el local"},email:{texto:"no tiene piso de tamaño, pero una campaña trae pedidos según los clientes activos (ver tamaño)"},justoApp:{texto:"no tiene piso: 9 de cada 10 marcas que la usan venden 6 pedidos online al mes o más"}},efecto:{loyalty:{nivel:"señal",texto:"las marcas que activaron puntos tuvieron en los 3 meses siguientes unos 4 a 5% más pedidos por comprador que marcas parecidas (de 1,31 a 1,37 en 90 días; 54 marcas), sin diferencia antes de activar. Es lo más sólido de todos los productos, pero es una asociación, no prueba que los puntos lo causen; en la recompra a 90 días no se ve cambio"},email:{nivel:"pedidos por campaña",texto:"no se ve que mueva la frecuencia ni la recompra de la marca; lo que trae son pedidos atribuidos a cada campaña"},alianzas:{nivel:"depende de Justo",texto:"las marcas que entran suben pedidos y clientes nuevos más que sus pares, pero Justo elige las marcas y financia el cupón, así que no es una palanca de la marca; su ticket es más bajo"},justoApp:{nivel:"sin evidencia",texto:"en las marcas que la usan pesa cerca de 5% de los pedidos; no hay evidencia de que haga crecer a la marca"},appPropia:{nivel:"reemplaza",texto:"pasa a ser cerca de 15% de los pedidos, pero en marcas que ya vendían online buena parte reemplaza pedidos web: el total no sube (27 casos)"},pdv:{nivel:"tipo de marca",texto:"las marcas con PDV de Justo tienen unos 2 puntos más de recompra online, pero ya la tenían antes de usarlo: describe al tipo de marca, no es un efecto"},delivery:{nivel:"sin evidencia",texto:"se activa junto con la venta online; no hay casos suficientes de marcas establecidas para medirlo"},reservas:{nivel:"sin evidencia",texto:"muy pocos casos para medir; las marcas con reservas tienen ticket más alto (restaurantes de mesa)"},inventario:{nivel:"sin efecto medible",texto:"no se asocia con cambios en pedidos ni en venta"},terminalDePago:{nivel:"sin efecto medible",texto:"no se asocia con más pedidos online; desde abril de 2026 casi ninguna marca registra su cobro"},commander:{nivel:"sin evidencia",texto:"muy pocos casos para medir"},instagramOrderFood:{nivel:"sin evidencia",texto:"muy pocos casos para medir; el producto volvió a registrarse en julio de 2026"},adelantoDePagos:{nivel:"sin evidencia",texto:"muy pocos casos para medir"},sac:{nivel:"sin evidencia",texto:"muy pocos casos para medir"},ecommerce:{nivel:"base",texto:"es la base de todos los productos digitales"},loyaltyCanje:{nivel:"sin medición",texto:"no se midió qué pasa al subir el canje; las marcas con más canje tienen más recompra y frecuencia, pero en buena parte es mecánico (quien compra seguido junta puntos para canjear). Usa el canje como indicador de que el programa funciona, no como promesa"}},correo:{pedidosPor100Activos:1.42,pedidosPor100ActivosP25:0.86,pedidosPor100ActivosP75:2.38,aperturaMediana:0.23,pedidosPorMilEnviados:0.88,campanasPorMesMediana:1.67,pedidosPorCampanaPorTier:{A:91,B:19,C:5,D:1,E:0},nota:"pedidos atribuidos a la campaña, no necesariamente adicionales; la apertura está inflada por aperturas automáticas"},puntos:{canjeMediana:0.073,canjeP25:0.026,canjeP75:0.144}};var E0=["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic"],o6=["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"];function v($){let C=Math.floor($),q=$-C;if(q>0.5)return C+1;if(q<0.5)return C;return C%2===0?C:C+1}function z$($,C){let q=Math.abs($).toFixed(100),Q=q.indexOf("."),J=q.slice(Q+1+C);if(!/^50*$/.test(J))return $.toFixed(C);let j=q.slice(0,Q)+q.slice(Q+1,Q+1+C),G=BigInt(j);if(G%2n===1n)G+=1n;let W=G.toString().padStart(C+1,"0"),Z=C?`${W.slice(0,-C)}.${W.slice(-C)}`:W;return $<0?`-${Z}`:Z}function m($){let[C,q]=String(Math.abs($)).split("."),Q=C.replace(/\B(?=(\d{3})+(?!\d))/g,",");return(($<0?"-":"")+Q+(q!==void 0?`.${q}`:"")).replaceAll(",",".")}function B($,C=!1){if($===null||$===void 0)return"s/d";let q=v($);return`${C?q>0?"+":q<0?"−":"":q<0?"−":""}US$${m(Math.abs(q))}`}function oC($,C){if($===null||$===void 0||C===null||C===void 0)return null;return v($)-v(C)}function L$($,C=!0){if($===null||$===void 0)return"s/d";let q=v($*100);return`${C&&q>0?"+":q<0?"−":""}${Math.abs(q)}%`}function T0($){if($===null||$===void 0)return"s/d";return $>10?"más de 1.000%":`${z$($*100,1)}%`.replace(".",",")}function N($,C=0){if($===null||$===void 0)return"s/d";return`${z$($*100,C)}%`.replace(".",",")}function n($,C){if($===null||$===void 0)return"s/d";if(C==="pct")return`${z$($*100,1)}%`.replace(".",",");if(C==="usd2")return`US$${z$($,2).replace(".",",")}`;if(C==="usd0")return B($);return z$($,2).replace(".",",")}function u($,C,q){return C!=null&&Object.hasOwn($,C)?$[C]:q}function O($){if($===null||$===void 0)return"None";if($===!0)return"True";if($===!1)return"False";return String($)}function C$($){return[...($||"").normalize("NFKD")].filter((q)=>q.charCodeAt(0)<128).join("").toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}function r6($,C){let q=new Date(Date.UTC($,0,4)),Q=q.getUTCDay()||7;return new Date(q.getTime()+((C-1)*7-(Q-1))*86400000)}function MC($){let C=new Date($.getTime()+(4-($.getUTCDay()||7))*86400000),q=C.getUTCFullYear(),Q=Math.ceil(((C.getTime()-Date.UTC(q,0,1))/86400000+1)/7);return`${q}-W${String(Q).padStart(2,"0")}`}function KC($){let C=r6(Number($.slice(0,4)),Number($.slice(6)));return[C,new Date(C.getTime()+518400000)]}function AC($,C){return new Date($.getTime()+C*86400000)}function q$($){return String(Number($.slice(6)))}function UC($){let[C,q]=KC($);return`semana ${q$($)} (${C.getUTCDate()} ${E0[C.getUTCMonth()]} al ${q.getUTCDate()} ${E0[q.getUTCMonth()]})`}function rC($){let C=$&&typeof $==="object"&&"$date"in $?$.$date:$;if(!C)return null;return new Date(String(C))}function dQ(){let $=new Date,C=new Date(Date.UTC($.getFullYear(),$.getMonth(),$.getDate()));return MC(AC(C,-7))}function sQ(){let $=new Date,C=String($.getMonth()+1).padStart(2,"0"),q=String($.getDate()).padStart(2,"0");return`${$.getFullYear()}-${C}-${q}`}function H$($){return $?o6[Number($.slice(5,7))-1]:"s/d"}function nQ($){let C=Number($.slice(0,4)),q=Number($.slice(5,7));return q===1?`${C-1}-12`:`${C}-${String(q-1).padStart(2,"0")}`}function n0($){return $?$[0].toUpperCase()+$.slice(1).toLowerCase():$}function J$($,C="",q="s"){return $===1?C:q}import{existsSync as pW,mkdirSync as lW,readdirSync as fW}from"node:fs";import{resolve as Gj}from"node:path";import{randomBytes as t6}from"crypto";var i6=(()=>{let $=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag).get;return(C)=>$.call(C)})();function GJ($){return i6($)==="Uint8Array"}function e6($){return typeof $==="object"&&$!=null&&Symbol.toStringTag in $&&($[Symbol.toStringTag]==="ArrayBuffer"||$[Symbol.toStringTag]==="SharedArrayBuffer")}function $8($){return $ instanceof RegExp||Object.prototype.toString.call($)==="[object RegExp]"}function ZJ($){return typeof $==="object"&&$!=null&&Symbol.toStringTag in $&&$[Symbol.toStringTag]==="Map"}function C8($){return $ instanceof Date||Object.prototype.toString.call($)==="[object Date]"}function g$($,C){return JSON.stringify($,(q,Q)=>{if(typeof Q==="bigint")return{$numberLong:`${Q}`};else if(ZJ(Q))return Object.fromEntries(Q);return Q})}function q8($){if($!=null&&typeof $==="object"&&"stylize"in $&&typeof $.stylize==="function")return $.stylize}var bq=6,XJ=Symbol.for("@@mdb.bson.version"),hq=2147483647,pq=-2147483648,YJ=Math.pow(2,63)-1,HJ=-Math.pow(2,63),Q8=Math.pow(2,53),J8=-Math.pow(2,53);var wJ=4,_Z=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 g extends Error{get bsonError(){return!0}get name(){return"BSONError"}constructor($,C){super($,C)}static isBSONError($){return $!=null&&typeof $==="object"&&"bsonError"in $&&$.bsonError===!0&&"name"in $&&"message"in $&&"stack"in $}}class FJ extends g{get name(){return"BSONVersionError"}constructor(){super(`Unsupported BSON version, bson types must be from bson ${bq}.x.x`)}}class vq extends g{get name(){return"BSONRuntimeError"}constructor($){super($)}}class G0 extends g{get name(){return"BSONOffsetError"}constructor($,C,q){super(`${$}. offset: ${C}`,q);this.offset=C}}var aQ,oQ;function PJ($,C,q,Q){if(Q){aQ??=new TextDecoder("utf8",{fatal:!0});try{return aQ.decode($.subarray(C,q))}catch(J){throw new g("Invalid UTF-8 string in BSON document",{cause:J})}}return oQ??=new TextDecoder("utf8",{fatal:!1}),oQ.decode($.subarray(C,q))}function MJ($,C,q){if($.length===0)return"";let Q=q-C;if(Q===0)return"";if(Q>20)return null;if(Q===1&&$[C]<128)return String.fromCharCode($[C]);if(Q===2&&$[C]<128&&$[C+1]<128)return String.fromCharCode($[C])+String.fromCharCode($[C+1]);if(Q===3&&$[C]<128&&$[C+1]<128&&$[C+2]<128)return String.fromCharCode($[C])+String.fromCharCode($[C+1])+String.fromCharCode($[C+2]);let J=[];for(let j=C;j<q;j++){let G=$[j];if(G>127)return null;J.push(G)}return String.fromCharCode(...J)}function j8($,C,q){if(C.length===0)return 0;if(C.length>25)return null;if($.length-q<C.length)return null;for(let Q=0,J=q;Q<C.length;Q++,J++){let j=C.charCodeAt(Q);if(j>127)return null;$[J]=j}return C.length}var U0={toLocalBufferType($){if(Buffer.isBuffer($))return $;if(ArrayBuffer.isView($))return Buffer.from($.buffer,$.byteOffset,$.byteLength);let C=$?.[Symbol.toStringTag]??Object.prototype.toString.call($);if(C==="ArrayBuffer"||C==="SharedArrayBuffer"||C==="[object ArrayBuffer]"||C==="[object SharedArrayBuffer]")return Buffer.from($);throw new g("Cannot create Buffer from the passed potentialBuffer.")},allocate($){return Buffer.alloc($)},allocateUnsafe($){return Buffer.allocUnsafe($)},equals($,C){return U0.toLocalBufferType($).equals(C)},fromNumberArray($){return Buffer.from($)},fromBase64($){return Buffer.from($,"base64")},toBase64($){return U0.toLocalBufferType($).toString("base64")},fromISO88591($){return Buffer.from($,"binary")},toISO88591($){return U0.toLocalBufferType($).toString("binary")},fromHex($){return Buffer.from($,"hex")},toHex($){return U0.toLocalBufferType($).toString("hex")},toUTF8($,C,q,Q){let J=q-C<=20?MJ($,C,q):null;if(J!=null)return J;let j=U0.toLocalBufferType($).toString("utf8",C,q);if(Q){for(let G=0;G<j.length;G++)if(j.charCodeAt(G)===65533){PJ($,C,q,!0);break}}return j},utf8ByteLength($){return Buffer.byteLength($,"utf8")},encodeUTF8Into($,C,q){let Q=j8($,C,q);if(Q!=null)return Q;return U0.toLocalBufferType($).write(C,q,void 0,"utf8")},randomBytes:t6,swap32($){return U0.toLocalBufferType($).swap32()}};function W8(){let{navigator:$}=globalThis;return typeof $==="object"&&$.product==="ReactNative"}function G8($){if($<0)throw RangeError(`The argument 'byteLength' is invalid. Received ${$}`);return _C.fromNumberArray(Array.from({length:$},()=>Math.floor(Math.random()*256)))}var Z8=(()=>{let{crypto:$}=globalThis;if($!=null&&typeof $.getRandomValues==="function")return(C)=>{return $.getRandomValues(_C.allocate(C))};else{if(W8()){let{console:C}=globalThis;C?.warn?.("BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.")}return G8}})(),rQ=/(\d|[a-f])/i,_C={toLocalBufferType($){let C=$?.[Symbol.toStringTag]??Object.prototype.toString.call($);if(C==="Uint8Array")return $;if(ArrayBuffer.isView($))return new Uint8Array($.buffer.slice($.byteOffset,$.byteOffset+$.byteLength));if(C==="ArrayBuffer"||C==="SharedArrayBuffer"||C==="[object ArrayBuffer]"||C==="[object SharedArrayBuffer]")return new Uint8Array($);throw new g("Cannot make a Uint8Array from passed potentialBuffer.")},allocate($){if(typeof $!=="number")throw TypeError(`The "size" argument must be of type number. Received ${String($)}`);return new Uint8Array($)},allocateUnsafe($){return _C.allocate($)},equals($,C){if($.byteLength!==C.byteLength)return!1;for(let q=0;q<$.byteLength;q++)if($[q]!==C[q])return!1;return!0},fromNumberArray($){return Uint8Array.from($)},fromBase64($){return Uint8Array.from(atob($),(C)=>C.charCodeAt(0))},toBase64($){return btoa(_C.toISO88591($))},fromISO88591($){return Uint8Array.from($,(C)=>C.charCodeAt(0)&255)},toISO88591($){return Array.from(Uint16Array.from($),(C)=>String.fromCharCode(C)).join("")},fromHex($){let C=$.length%2===0?$:$.slice(0,$.length-1),q=[];for(let Q=0;Q<C.length;Q+=2){let J=C[Q],j=C[Q+1];if(!rQ.test(J))break;if(!rQ.test(j))break;let G=Number.parseInt(`${J}${j}`,16);q.push(G)}return Uint8Array.from(q)},toHex($){return Array.from($,(C)=>C.toString(16).padStart(2,"0")).join("")},toUTF8($,C,q,Q){let J=q-C<=20?MJ($,C,q):null;if(J!=null)return J;return PJ($,C,q,Q)},utf8ByteLength($){return new TextEncoder().encode($).byteLength},encodeUTF8Into($,C,q){let Q=new TextEncoder().encode(C);return $.set(Q,q),Q.byteLength},randomBytes:Z8,swap32($){if($.length%4!==0)throw RangeError("Buffer size must be a multiple of 32-bits");for(let C=0;C<$.length;C+=4){let q=$[C],Q=$[C+1],J=$[C+2],j=$[C+3];$[C]=j,$[C+1]=J,$[C+2]=Q,$[C+3]=q}return $}},X8=typeof Buffer==="function"&&Buffer.prototype?._isBuffer!==!0,b=X8?U0:_C;class k${get[XJ](){return bq}[Symbol.for("nodejs.util.inspect.custom")]($,C,q){return this.inspect($,C,q)}}var o0=new Float64Array(1),t=new Uint8Array(o0.buffer,0,8);o0[0]=-1;var Bq=t[7]===0,N0={isBigEndian:Bq,getNonnegativeInt32LE($,C){if($[C+3]>127)throw RangeError(`Size cannot be negative at offset: ${C}`);return $[C]|$[C+1]<<8|$[C+2]<<16|$[C+3]<<24},getInt32LE($,C){return $[C]|$[C+1]<<8|$[C+2]<<16|$[C+3]<<24},getUint32LE($,C){return $[C]+$[C+1]*256+$[C+2]*65536+$[C+3]*16777216},getUint32BE($,C){return $[C+3]+$[C+2]*256+$[C+1]*65536+$[C]*16777216},getBigInt64LE($,C){let q=BigInt($[C+4]+$[C+5]*256+$[C+6]*65536+($[C+7]<<24)),Q=BigInt($[C]+$[C+1]*256+$[C+2]*65536+$[C+3]*16777216);return(q<<BigInt(32))+Q},getFloat64LE:Bq?($,C)=>{return t[7]=$[C],t[6]=$[C+1],t[5]=$[C+2],t[4]=$[C+3],t[3]=$[C+4],t[2]=$[C+5],t[1]=$[C+6],t[0]=$[C+7],o0[0]}:($,C)=>{return t[0]=$[C],t[1]=$[C+1],t[2]=$[C+2],t[3]=$[C+3],t[4]=$[C+4],t[5]=$[C+5],t[6]=$[C+6],t[7]=$[C+7],o0[0]},setInt32BE($,C,q){return $[C+3]=q,q>>>=8,$[C+2]=q,q>>>=8,$[C+1]=q,q>>>=8,$[C]=q,4},setInt32LE($,C,q){return $[C]=q,q>>>=8,$[C+1]=q,q>>>=8,$[C+2]=q,q>>>=8,$[C+3]=q,4},setBigInt64LE($,C,q){let Q=BigInt(4294967295),J=Number(q&Q);$[C]=J,J>>=8,$[C+1]=J,J>>=8,$[C+2]=J,J>>=8,$[C+3]=J;let j=Number(q>>BigInt(32)&Q);return $[C+4]=j,j>>=8,$[C+5]=j,j>>=8,$[C+6]=j,j>>=8,$[C+7]=j,8},setFloat64LE:Bq?($,C,q)=>{return o0[0]=q,$[C]=t[7],$[C+1]=t[6],$[C+2]=t[5],$[C+3]=t[4],$[C+4]=t[3],$[C+5]=t[2],$[C+6]=t[1],$[C+7]=t[0],8}:($,C,q)=>{return o0[0]=q,$[C]=t[0],$[C+1]=t[1],$[C+2]=t[2],$[C+3]=t[3],$[C+4]=t[4],$[C+5]=t[5],$[C+6]=t[6],$[C+7]=t[7],8}};class f extends k${get _bsontype(){return"Binary"}constructor($,C){super();if($!=null&&typeof $==="string"&&!ArrayBuffer.isView($)&&!e6($)&&!Array.isArray($))throw new g("Binary can only be constructed from Uint8Array or number[]");if(this.sub_type=C??f.BSON_BINARY_SUBTYPE_DEFAULT,$==null)this.buffer=b.allocate(f.BUFFER_SIZE),this.position=0;else this.buffer=Array.isArray($)?b.fromNumberArray($):b.toLocalBufferType($),this.position=this.buffer.byteLength}put($){if(typeof $==="string"&&$.length!==1)throw new g("only accepts single character String");else if(typeof $!=="number"&&$.length!==1)throw new g("only accepts single character Uint8Array or Array");let C;if(typeof $==="string")C=$.charCodeAt(0);else if(typeof $==="number")C=$;else C=$[0];if(C<0||C>255)throw new g("only accepts number in a valid unsigned byte range 0-255");if(this.buffer.byteLength>this.position)this.buffer[this.position++]=C;else{let q=b.allocate(f.BUFFER_SIZE+this.buffer.length);q.set(this.buffer,0),this.buffer=q,this.buffer[this.position++]=C}}write($,C){if(C=typeof C==="number"?C:this.position,this.buffer.byteLength<C+$.length){let q=b.allocate(this.buffer.byteLength+$.length);q.set(this.buffer,0),this.buffer=q}if(ArrayBuffer.isView($))this.buffer.set(b.toLocalBufferType($),C),this.position=C+$.byteLength>this.position?C+$.length:this.position;else if(typeof $==="string")throw new g("input cannot be string")}read($,C){C=C&&C>0?C:this.position;let q=$+C;return this.buffer.subarray($,q>this.position?this.position:q)}value(){return this.buffer.length===this.position?this.buffer:this.buffer.subarray(0,this.position)}length(){return this.position}toJSON(){return b.toBase64(this.buffer.subarray(0,this.position))}toString($){if($==="hex")return b.toHex(this.buffer.subarray(0,this.position));if($==="base64")return b.toBase64(this.buffer.subarray(0,this.position));if($==="utf8"||$==="utf-8")return b.toUTF8(this.buffer,0,this.position,!1);return b.toUTF8(this.buffer,0,this.position,!1)}toExtendedJSON($){if($=$||{},this.sub_type===f.SUBTYPE_VECTOR)A0(this);let C=b.toBase64(this.buffer),q=Number(this.sub_type).toString(16);if($.legacy)return{$binary:C,$type:q.length===1?"0"+q:q};return{$binary:{base64:C,subType:q.length===1?"0"+q:q}}}toUUID(){if(this.sub_type===f.SUBTYPE_UUID)return new I$(this.buffer.subarray(0,this.position));throw new g(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${f.SUBTYPE_UUID}" is currently supported.`)}static createFromHexString($,C){return new f(b.fromHex($),C)}static createFromBase64($,C){return new f(b.fromBase64($),C)}static fromExtendedJSON($,C){C=C||{};let q,Q;if("$binary"in $){if(C.legacy&&typeof $.$binary==="string"&&"$type"in $)Q=$.$type?parseInt($.$type,16):0,q=b.fromBase64($.$binary);else if(typeof $.$binary!=="string")Q=$.$binary.subType?parseInt($.$binary.subType,16):0,q=b.fromBase64($.$binary.base64)}else if("$uuid"in $)Q=4,q=I$.bytesFromString($.$uuid);if(!q)throw new g(`Unexpected Binary Extended JSON format ${JSON.stringify($)}`);return Q===wJ?new I$(q):new f(q,Q)}inspect($,C,q){q??=g$;let Q=b.toBase64(this.buffer.subarray(0,this.position)),J=q(Q,C),j=q(this.sub_type,C);return`Binary.createFromBase64(${J}, ${j})`}toInt8Array(){if(this.sub_type!==f.SUBTYPE_VECTOR)throw new g("Binary sub_type is not Vector");if(this.buffer[0]!==f.VECTOR_TYPE.Int8)throw new g("Binary datatype field is not Int8");return A0(this),new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toFloat32Array(){if(this.sub_type!==f.SUBTYPE_VECTOR)throw new g("Binary sub_type is not Vector");if(this.buffer[0]!==f.VECTOR_TYPE.Float32)throw new g("Binary datatype field is not Float32");A0(this);let $=new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position));if(N0.isBigEndian)b.swap32($);return new Float32Array($.buffer)}toPackedBits(){if(this.sub_type!==f.SUBTYPE_VECTOR)throw new g("Binary sub_type is not Vector");if(this.buffer[0]!==f.VECTOR_TYPE.PackedBit)throw new g("Binary datatype field is not packed bit");return A0(this),new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toBits(){if(this.sub_type!==f.SUBTYPE_VECTOR)throw new g("Binary sub_type is not Vector");if(this.buffer[0]!==f.VECTOR_TYPE.PackedBit)throw new g("Binary datatype field is not packed bit");A0(this);let C=(this.length()-2)*8-this.buffer[1],q=new Int8Array(C);for(let Q=0;Q<q.length;Q++){let J=Q/8|0,j=this.buffer[J+2],G=7-Q%8,W=j>>G&1;q[Q]=W}return q}static fromInt8Array($){let C=b.allocate($.byteLength+2);C[0]=f.VECTOR_TYPE.Int8,C[1]=0;let q=new Uint8Array($.buffer,$.byteOffset,$.byteLength);C.set(q,2);let Q=new this(C,this.SUBTYPE_VECTOR);return A0(Q),Q}static fromFloat32Array($){let C=b.allocate($.byteLength+2);C[0]=f.VECTOR_TYPE.Float32,C[1]=0;let q=new Uint8Array($.buffer,$.byteOffset,$.byteLength);if(C.set(q,2),N0.isBigEndian)b.swap32(new Uint8Array(C.buffer,2));let Q=new this(C,this.SUBTYPE_VECTOR);return A0(Q),Q}static fromPackedBits($,C=0){let q=b.allocate($.byteLength+2);q[0]=f.VECTOR_TYPE.PackedBit,q[1]=C,q.set($,2);let Q=new this(q,this.SUBTYPE_VECTOR);return A0(Q),Q}static fromBits($){let C=$.length+7>>>3,q=new Uint8Array(C+2);q[0]=f.VECTOR_TYPE.PackedBit;let Q=$.length%8;q[1]=Q===0?0:8-Q;for(let J=0;J<$.length;J++){let j=J>>>3,G=$[J];if(G!==0&&G!==1)throw new g(`Invalid bit value at ${J}: must be 0 or 1, found ${$[J]}`);if(G===0)continue;let W=7-J%8;q[j+2]|=G<<W}return new this(q,f.SUBTYPE_VECTOR)}}f.BSON_BINARY_SUBTYPE_DEFAULT=0;f.BUFFER_SIZE=256;f.SUBTYPE_DEFAULT=0;f.SUBTYPE_FUNCTION=1;f.SUBTYPE_BYTE_ARRAY=2;f.SUBTYPE_UUID_OLD=3;f.SUBTYPE_UUID=4;f.SUBTYPE_MD5=5;f.SUBTYPE_ENCRYPTED=6;f.SUBTYPE_COLUMN=7;f.SUBTYPE_SENSITIVE=8;f.SUBTYPE_VECTOR=9;f.SUBTYPE_USER_DEFINED=128;f.VECTOR_TYPE=Object.freeze({Int8:3,Float32:39,PackedBit:16});function A0($){if($.sub_type!==f.SUBTYPE_VECTOR)return;let C=$.position,q=$.buffer[0],Q=$.buffer[1];if((q===f.VECTOR_TYPE.Float32||q===f.VECTOR_TYPE.Int8)&&Q!==0)throw new g("Invalid Vector: padding must be zero for int8 and float32 vectors");if(q===f.VECTOR_TYPE.Float32){if(C!==0&&C-2!==0&&(C-2)%4!==0)throw new g("Invalid Vector: Float32 vector must contain a multiple of 4 bytes")}if(q===f.VECTOR_TYPE.PackedBit&&Q!==0&&C===2)throw new g("Invalid Vector: padding must be zero for packed bit vectors that are empty");if(q===f.VECTOR_TYPE.PackedBit&&Q>7)throw new g(`Invalid Vector: padding must be a value between 0 and 7. found: ${Q}`)}var Oq=16,Y8=/^[0-9A-F]{32}$/i,H8=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;class I$ extends f{constructor($){let C;if($==null)C=I$.generate();else if($ instanceof I$)C=b.toLocalBufferType(new Uint8Array($.buffer));else if(ArrayBuffer.isView($)&&$.byteLength===Oq)C=b.toLocalBufferType($);else if(typeof $==="string")C=I$.bytesFromString($);else throw new g("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(C,wJ)}get id(){return this.buffer}set id($){this.buffer=$}toHexString($=!0){if($)return[b.toHex(this.buffer.subarray(0,4)),b.toHex(this.buffer.subarray(4,6)),b.toHex(this.buffer.subarray(6,8)),b.toHex(this.buffer.subarray(8,10)),b.toHex(this.buffer.subarray(10,16))].join("-");return b.toHex(this.buffer)}toString($){if($==="hex")return b.toHex(this.id);if($==="base64")return b.toBase64(this.id);return this.toHexString()}toJSON(){return this.toHexString()}equals($){if(!$)return!1;if($ instanceof I$)return b.equals($.id,this.id);try{return b.equals(new I$($).id,this.id)}catch{return!1}}toBinary(){return new f(this.id,f.SUBTYPE_UUID)}static generate(){let $=b.randomBytes(Oq);return $[6]=$[6]&15|64,$[8]=$[8]&63|128,$}static isValid($){if(!$)return!1;if(typeof $==="string")return I$.isValidUUIDString($);if(GJ($))return $.byteLength===Oq;return $._bsontype==="Binary"&&$.sub_type===this.SUBTYPE_UUID&&$.buffer.byteLength===16}static createFromHexString($){let C=I$.bytesFromString($);return new I$(C)}static createFromBase64($){return new I$(b.fromBase64($))}static bytesFromString($){if(!I$.isValidUUIDString($))throw new g("UUID string representation must be 32 hex digits or canonical hyphenated representation");return b.fromHex($.replace(/-/g,""))}static isValidUUIDString($){return Y8.test($)||H8.test($)}inspect($,C,q){return q??=g$,`new UUID(${q(this.toHexString(),C)})`}}class VC extends k${get _bsontype(){return"Code"}constructor($,C){super();this.code=$.toString(),this.scope=C??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($){return new VC($.$code,$.$scope)}inspect($,C,q){q??=g$;let Q=q(this.code,C),J=Q.includes(`
|
|
792
|
+
`);if(this.scope!=null)Q+=`,${J?`
|
|
793
|
+
`:" "}${q(this.scope,C)}`;let j=J&&this.scope===null;return`new Code(${J?`
|
|
794
|
+
`:""}${Q}${j?`
|
|
795
|
+
`:""})`}}function w8($){return $!=null&&typeof $==="object"&&"$id"in $&&$.$id!=null&&"$ref"in $&&typeof $.$ref==="string"&&(!("$db"in $)||("$db"in $)&&typeof $.$db==="string")}class t0 extends k${get _bsontype(){return"DBRef"}constructor($,C,q,Q){super();let J=$.split(".");if(J.length===2)q=J.shift(),$=J.shift();this.collection=$,this.oid=C,this.db=q,this.fields=Q||{}}get namespace(){return this.collection}set namespace($){this.collection=$}toJSON(){let $=Object.assign({$ref:this.collection,$id:this.oid},this.fields);if(this.db!=null)$.$db=this.db;return $}toExtendedJSON($){$=$||{};let C={$ref:this.collection,$id:this.oid};if($.legacy)return C;if(this.db)C.$db=this.db;return C=Object.assign(C,this.fields),C}static fromExtendedJSON($){let C=Object.assign({},$);return delete C.$ref,delete C.$id,delete C.$db,new t0($.$ref,$.$id,$.$db,C)}inspect($,C,q){q??=g$;let Q=[q(this.namespace,C),q(this.oid,C),...this.db?[q(this.db,C)]:[],...Object.keys(this.fields).length>0?[q(this.fields,C)]:[]];return Q[1]=q===g$?`new ObjectId(${Q[1]})`:Q[1],`new DBRef(${Q.join(", ")})`}}function KJ($){if($==="")return $;let C=0,q=$[C]==="-",Q=$[C]==="+";if(Q||q)C+=1;let J=!1;for(;C<$.length&&$[C]==="0";++C)J=!0;if(!J)return Q?$.slice(1):$;return`${q?"-":""}${$.length===C?"0":$.slice(C)}`}function F8($,C){C=C??10;let q="0123456789abcdefghijklmnopqrstuvwxyz".slice(0,C);return new RegExp(`[^-+${q}]`,"i").test($)?!1:$}var x$=void 0;try{x$=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 tQ=65536,P8=16777216,r0=tQ*tQ,AJ=r0*r0,M8=AJ/2,iQ={},eQ={},K8=20,A8=/^(\+?0|(\+|-)?[1-9][0-9]*)$/;class P extends k${get _bsontype(){return"Long"}get __isLong__(){return!0}constructor($=0,C,q){super();let Q=typeof C==="boolean"?C:Boolean(q),J=typeof C==="number"?C:0,j=typeof $==="string"?P.fromString($,Q):typeof $==="bigint"?P.fromBigInt($,Q):{low:$|0,high:J|0,unsigned:Q};this.low=j.low,this.high=j.high,this.unsigned=j.unsigned}static fromBits($,C,q){return new P($,C,q)}static fromInt($,C){let q,Q,J;if(C){if($>>>=0,J=0<=$&&$<256){if(Q=eQ[$],Q)return Q}if(q=P.fromBits($,($|0)<0?-1:0,!0),J)eQ[$]=q;return q}else{if($|=0,J=-128<=$&&$<128){if(Q=iQ[$],Q)return Q}if(q=P.fromBits($,$<0?-1:0,!1),J)iQ[$]=q;return q}}static fromNumber($,C){if(isNaN($))return C?P.UZERO:P.ZERO;if(C){if($<0)return P.UZERO;if($>=AJ)return P.MAX_UNSIGNED_VALUE}else{if($<=-9223372036854776000)return P.MIN_VALUE;if($+1>=M8)return P.MAX_VALUE}if($<0)return P.fromNumber(-$,C).neg();return P.fromBits($%r0|0,$/r0|0,C)}static fromBigInt($,C){let q=BigInt(4294967295),Q=BigInt(32);return new P(Number($&q),Number($>>Q&q),C)}static _fromString($,C,q){if($.length===0)throw new g("empty string");if(q<2||36<q)throw new g("radix");let Q;if((Q=$.indexOf("-"))>0)throw new g("interior hyphen");else if(Q===0)return P._fromString($.substring(1),C,q).neg();let J=P.fromNumber(Math.pow(q,8)),j=P.ZERO;for(let G=0;G<$.length;G+=8){let W=Math.min(8,$.length-G),Z=parseInt($.substring(G,G+W),q);if(W<8){let X=P.fromNumber(Math.pow(q,W));j=j.mul(X).add(P.fromNumber(Z))}else j=j.mul(J),j=j.add(P.fromNumber(Z))}return j.unsigned=C,j}static fromStringStrict($,C,q){let Q=!1;if(typeof C==="number")q=C,C=!1;else Q=!!C;if(q??=10,$.trim()!==$)throw new g(`Input: '${$}' contains leading and/or trailing whitespace`);if(!F8($,q))throw new g(`Input: '${$}' contains invalid characters for radix: ${q}`);let J=KJ($),j=P._fromString(J,Q,q);if(j.toString(q).toLowerCase()!==J.toLowerCase())throw new g(`Input: ${$} is not representable as ${j.unsigned?"an unsigned":"a signed"} 64-bit Long ${q!=null?`with radix: ${q}`:""}`);return j}static fromString($,C,q){let Q=!1;if(typeof C==="number")q=C,C=!1;else Q=!!C;if(q??=10,$==="NaN"&&q<24)return P.ZERO;else if(($==="Infinity"||$==="+Infinity"||$==="-Infinity")&&q<35)return P.ZERO;return P._fromString($,Q,q)}static fromBytes($,C,q){return q?P.fromBytesLE($,C):P.fromBytesBE($,C)}static fromBytesLE($,C){return new P($[0]|$[1]<<8|$[2]<<16|$[3]<<24,$[4]|$[5]<<8|$[6]<<16|$[7]<<24,C)}static fromBytesBE($,C){return new P($[4]<<24|$[5]<<16|$[6]<<8|$[7],$[0]<<24|$[1]<<16|$[2]<<8|$[3],C)}static isLong($){return $!=null&&typeof $==="object"&&"__isLong__"in $&&$.__isLong__===!0}static fromValue($,C){if(typeof $==="number")return P.fromNumber($,C);if(typeof $==="string")return P.fromString($,C);return P.fromBits($.low,$.high,typeof C==="boolean"?C:$.unsigned)}add($){if(!P.isLong($))$=P.fromValue($);let C=this.high>>>16,q=this.high&65535,Q=this.low>>>16,J=this.low&65535,j=$.high>>>16,G=$.high&65535,W=$.low>>>16,Z=$.low&65535,X=0,Y=0,H=0,F=0;return F+=J+Z,H+=F>>>16,F&=65535,H+=Q+W,Y+=H>>>16,H&=65535,Y+=q+G,X+=Y>>>16,Y&=65535,X+=C+j,X&=65535,P.fromBits(H<<16|F,X<<16|Y,this.unsigned)}and($){if(!P.isLong($))$=P.fromValue($);return P.fromBits(this.low&$.low,this.high&$.high,this.unsigned)}compare($){if(!P.isLong($))$=P.fromValue($);if(this.eq($))return 0;let C=this.isNegative(),q=$.isNegative();if(C&&!q)return-1;if(!C&&q)return 1;if(!this.unsigned)return this.sub($).isNegative()?-1:1;return $.high>>>0>this.high>>>0||$.high===this.high&&$.low>>>0>this.low>>>0?-1:1}comp($){return this.compare($)}divide($){if(!P.isLong($))$=P.fromValue($);if($.isZero())throw new g("division by zero");if(x$){if(!this.unsigned&&this.high===-2147483648&&$.low===-1&&$.high===-1)return this;let J=(this.unsigned?x$.div_u:x$.div_s)(this.low,this.high,$.low,$.high);return P.fromBits(J,x$.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?P.UZERO:P.ZERO;let C,q,Q;if(!this.unsigned){if(this.eq(P.MIN_VALUE))if($.eq(P.ONE)||$.eq(P.NEG_ONE))return P.MIN_VALUE;else if($.eq(P.MIN_VALUE))return P.ONE;else if(C=this.shr(1).div($).shl(1),C.eq(P.ZERO))return $.isNegative()?P.ONE:P.NEG_ONE;else return q=this.sub($.mul(C)),Q=C.add(q.div($)),Q;else if($.eq(P.MIN_VALUE))return this.unsigned?P.UZERO:P.ZERO;if(this.isNegative()){if($.isNegative())return this.neg().div($.neg());return this.neg().div($).neg()}else if($.isNegative())return this.div($.neg()).neg();Q=P.ZERO}else{if(!$.unsigned)$=$.toUnsigned();if($.gt(this))return P.UZERO;if($.gt(this.shru(1)))return P.UONE;Q=P.UZERO}q=this;while(q.gte($)){C=Math.max(1,Math.floor(q.toNumber()/$.toNumber()));let J=Math.ceil(Math.log(C)/Math.LN2),j=J<=48?1:Math.pow(2,J-48),G=P.fromNumber(C),W=G.mul($);while(W.isNegative()||W.gt(q))C-=j,G=P.fromNumber(C,this.unsigned),W=G.mul($);if(G.isZero())G=P.ONE;Q=Q.add(G),q=q.sub(W)}return Q}div($){return this.divide($)}equals($){if(!P.isLong($))$=P.fromValue($);if(this.unsigned!==$.unsigned&&this.high>>>31===1&&$.high>>>31===1)return!1;return this.high===$.high&&this.low===$.low}eq($){return this.equals($)}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 $=this.high!==0?this.high:this.low,C;for(C=31;C>0;C--)if(($&1<<C)!==0)break;return this.high!==0?C+33:C+1}greaterThan($){return this.comp($)>0}gt($){return this.greaterThan($)}greaterThanOrEqual($){return this.comp($)>=0}gte($){return this.greaterThanOrEqual($)}ge($){return this.greaterThanOrEqual($)}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($){return this.comp($)<0}lt($){return this.lessThan($)}lessThanOrEqual($){return this.comp($)<=0}lte($){return this.lessThanOrEqual($)}modulo($){if(!P.isLong($))$=P.fromValue($);if(x$){let C=(this.unsigned?x$.rem_u:x$.rem_s)(this.low,this.high,$.low,$.high);return P.fromBits(C,x$.get_high(),this.unsigned)}return this.sub(this.div($).mul($))}mod($){return this.modulo($)}rem($){return this.modulo($)}multiply($){if(this.isZero())return P.ZERO;if(!P.isLong($))$=P.fromValue($);if(x$){let M=x$.mul(this.low,this.high,$.low,$.high);return P.fromBits(M,x$.get_high(),this.unsigned)}if($.isZero())return P.ZERO;if(this.eq(P.MIN_VALUE))return $.isOdd()?P.MIN_VALUE:P.ZERO;if($.eq(P.MIN_VALUE))return this.isOdd()?P.MIN_VALUE:P.ZERO;if(this.isNegative())if($.isNegative())return this.neg().mul($.neg());else return this.neg().mul($).neg();else if($.isNegative())return this.mul($.neg()).neg();if(this.lt(P.TWO_PWR_24)&&$.lt(P.TWO_PWR_24))return P.fromNumber(this.toNumber()*$.toNumber(),this.unsigned);let C=this.high>>>16,q=this.high&65535,Q=this.low>>>16,J=this.low&65535,j=$.high>>>16,G=$.high&65535,W=$.low>>>16,Z=$.low&65535,X=0,Y=0,H=0,F=0;return F+=J*Z,H+=F>>>16,F&=65535,H+=Q*Z,Y+=H>>>16,H&=65535,H+=J*W,Y+=H>>>16,H&=65535,Y+=q*Z,X+=Y>>>16,Y&=65535,Y+=Q*W,X+=Y>>>16,Y&=65535,Y+=J*G,X+=Y>>>16,Y&=65535,X+=C*Z+q*W+Q*G+J*j,X&=65535,P.fromBits(H<<16|F,X<<16|Y,this.unsigned)}mul($){return this.multiply($)}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($){return!this.equals($)}neq($){return this.notEquals($)}ne($){return this.notEquals($)}or($){if(!P.isLong($))$=P.fromValue($);return P.fromBits(this.low|$.low,this.high|$.high,this.unsigned)}shiftLeft($){if(P.isLong($))$=$.toInt();if(($&=63)===0)return this;else if($<32)return P.fromBits(this.low<<$,this.high<<$|this.low>>>32-$,this.unsigned);else return P.fromBits(0,this.low<<$-32,this.unsigned)}shl($){return this.shiftLeft($)}shiftRight($){if(P.isLong($))$=$.toInt();if(($&=63)===0)return this;else if($<32)return P.fromBits(this.low>>>$|this.high<<32-$,this.high>>$,this.unsigned);else return P.fromBits(this.high>>$-32,this.high>=0?0:-1,this.unsigned)}shr($){return this.shiftRight($)}shiftRightUnsigned($){if(P.isLong($))$=$.toInt();if($&=63,$===0)return this;else{let C=this.high;if($<32){let q=this.low;return P.fromBits(q>>>$|C<<32-$,C>>>$,this.unsigned)}else if($===32)return P.fromBits(C,0,this.unsigned);else return P.fromBits(C>>>$-32,0,this.unsigned)}}shr_u($){return this.shiftRightUnsigned($)}shru($){return this.shiftRightUnsigned($)}subtract($){if(!P.isLong($))$=P.fromValue($);return this.add($.neg())}sub($){return this.subtract($)}toInt(){return this.unsigned?this.low>>>0:this.low}toNumber(){if(this.unsigned)return(this.high>>>0)*r0+(this.low>>>0);return this.high*r0+(this.low>>>0)}toBigInt(){return BigInt(this.toString())}toBytes($){return $?this.toBytesLE():this.toBytesBE()}toBytesLE(){let $=this.high,C=this.low;return[C&255,C>>>8&255,C>>>16&255,C>>>24,$&255,$>>>8&255,$>>>16&255,$>>>24]}toBytesBE(){let $=this.high,C=this.low;return[$>>>24,$>>>16&255,$>>>8&255,$&255,C>>>24,C>>>16&255,C>>>8&255,C&255]}toSigned(){if(!this.unsigned)return this;return P.fromBits(this.low,this.high,!1)}toString($){if($=$||10,$<2||36<$)throw new g("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(P.MIN_VALUE)){let J=P.fromNumber($),j=this.div(J),G=j.mul(J).sub(this);return j.toString($)+G.toInt().toString($)}else return"-"+this.neg().toString($);let C=P.fromNumber(Math.pow($,6),this.unsigned),q=this,Q="";while(!0){let J=q.div(C),G=(q.sub(J.mul(C)).toInt()>>>0).toString($);if(q=J,q.isZero())return G+Q;else{while(G.length<6)G="0"+G;Q=""+G+Q}}}toUnsigned(){if(this.unsigned)return this;return P.fromBits(this.low,this.high,!0)}xor($){if(!P.isLong($))$=P.fromValue($);return P.fromBits(this.low^$.low,this.high^$.high,this.unsigned)}eqz(){return this.isZero()}le($){return this.lessThanOrEqual($)}toExtendedJSON($){if($&&$.relaxed)return this.toNumber();return{$numberLong:this.toString()}}static fromExtendedJSON($,C){let{useBigInt64:q=!1,relaxed:Q=!0}={...C};if($.$numberLong.length>K8)throw new g("$numberLong string is too long");if(!A8.test($.$numberLong))throw new g(`$numberLong string "${$.$numberLong}" is in an invalid format`);if(q){let j=BigInt($.$numberLong);return BigInt.asIntN(64,j)}let J=P.fromString($.$numberLong);if(Q)return J.toNumber();return J}inspect($,C,q){q??=g$;let Q=q(this.toString(),C),J=this.unsigned?`, ${q(this.unsigned,C)}`:"";return`new Long(${Q}${J})`}}P.TWO_PWR_24=P.fromInt(P8);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 U8=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/,R8=/^(\+|-)?(Infinity|inf)$/i,z8=/^(\+|-)?NaN$/i,a0=6111,RC=-6176,$J=6176,CJ=34,yq=b.fromNumberArray([124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),qJ=b.fromNumberArray([248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),QJ=b.fromNumberArray([120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),_8=/^([-+])?(\d+)?$/,V8=31,JJ=16383,m8=30,I8=31;function jJ($){return!isNaN(parseInt($,10))}function D8($){let C=P.fromNumber(1e9),q=P.fromNumber(0);if(!$.parts[0]&&!$.parts[1]&&!$.parts[2]&&!$.parts[3])return{quotient:$,rem:q};for(let Q=0;Q<=3;Q++)q=q.shiftLeft(32),q=q.add(new P($.parts[Q],0)),$.parts[Q]=q.div(C).low,q=q.modulo(C);return{quotient:$,rem:q}}function E8($,C){if(!$&&!C)return{high:P.fromNumber(0),low:P.fromNumber(0)};let q=$.shiftRightUnsigned(32),Q=new P($.getLowBits(),0),J=C.shiftRightUnsigned(32),j=new P(C.getLowBits(),0),G=q.multiply(J),W=q.multiply(j),Z=Q.multiply(J),X=Q.multiply(j);return G=G.add(W.shiftRightUnsigned(32)),W=new P(W.getLowBits(),0).add(Z).add(X.shiftRightUnsigned(32)),G=G.add(W.shiftRightUnsigned(32)),X=W.shiftLeft(32).add(new P(X.getLowBits(),0)),{high:G,low:X}}function T8($,C){let q=$.high>>>0,Q=C.high>>>0;if(q<Q)return!0;else if(q===Q){let J=$.low>>>0,j=C.low>>>0;if(J<j)return!0}return!1}function u$($,C){throw new g(`"${$}" is not a valid Decimal128 string - ${C}`)}class N$ extends k${get _bsontype(){return"Decimal128"}constructor($){super();if(typeof $==="string")this.bytes=N$.fromString($).bytes;else if($ instanceof Uint8Array||GJ($)){if($.byteLength!==16)throw new g("Decimal128 must take a Buffer of 16 bytes");this.bytes=$}else throw new g("Decimal128 must take a Buffer or string")}static fromString($){return N$._fromString($,{allowRounding:!1})}static fromStringWithRounding($){return N$._fromString($,{allowRounding:!0})}static _fromString($,C){let q=!1,Q=!1,J=!1,j=!1,G=0,W=0,Z=0,X=0,Y=0,H=[0],F=0,M=0,U=0,R=0,E=new P(0,0),V=new P(0,0),I=0,A=0;if($.length>=7000)throw new g(""+$+" not a valid Decimal128 string");let x=$.match(U8),r=$.match(R8),W$=$.match(z8);if(!x&&!r&&!W$||$.length===0)throw new g(""+$+" not a valid Decimal128 string");if(x){let p=x[2],K=x[4],S=x[5],s=x[6];if(K&&s===void 0)u$($,"missing exponent power");if(K&&p===void 0)u$($,"missing exponent base");if(K===void 0&&(S||s))u$($,"missing e before exponent")}if($[A]==="+"||$[A]==="-")Q=!0,q=$[A++]==="-";if(!jJ($[A])&&$[A]!=="."){if($[A]==="i"||$[A]==="I")return new N$(q?qJ:QJ);else if($[A]==="N")return new N$(yq)}while(jJ($[A])||$[A]==="."){if($[A]==="."){if(J)u$($,"contains multiple periods");J=!0,A=A+1;continue}if(F<CJ){if($[A]!=="0"||j){if(!j)Y=W;j=!0,H[M++]=parseInt($[A],10),F=F+1}}if(j)Z=Z+1;if(J)X=X+1;W=W+1,A=A+1}if(J&&!W)throw new g(""+$+" not a valid Decimal128 string");if($[A]==="e"||$[A]==="E"){let p=$.substr(++A).match(_8);if(!p||!p[2])return new N$(yq);R=parseInt(p[0],10),A=A+p[0].length}if($[A])return new N$(yq);if(!F)H[0]=0,Z=1,F=1,G=0;else if(U=F-1,G=Z,G!==1)while($[Y+G-1+Number(Q)+Number(J)]==="0")G=G-1;if(R<=X&&X>R+16384)R=RC;else R=R-X;while(R>a0){if(U=U+1,U>=CJ){if(G===0){R=a0;break}u$($,"overflow")}R=R-1}if(C.allowRounding){while(R<RC||F<Z){if(U===0&&G<F){R=RC,G=0;break}if(F<Z)Z=Z-1;else U=U-1;if(R<a0)R=R+1;else{if(H.join("").match(/^0+$/)){R=a0;break}u$($,"overflow")}}if(U+1<G){let p=W;if(J)Y=Y+1,p=p+1;if(Q)Y=Y+1,p=p+1;let K=parseInt($[Y+U+1],10),S=0;if(K>=5){if(S=1,K===5){S=H[U]%2===1?1:0;for(let s=Y+U+2;s<p;s++)if(parseInt($[s],10)){S=1;break}}}if(S){let s=U;for(;s>=0;s--)if(++H[s]>9){if(H[s]=0,s===0)if(R<a0)R=R+1,H[s]=1;else return new N$(q?qJ:QJ)}else break}}}else{while(R<RC||F<Z){if(U===0){if(G===0){R=RC;break}u$($,"exponent underflow")}if(F<Z){if($[Z-1+Number(Q)+Number(J)]!=="0"&&G!==0)u$($,"inexact rounding");Z=Z-1}else{if(H[U]!==0)u$($,"inexact rounding");U=U-1}if(R<a0)R=R+1;else u$($,"overflow")}if(U+1<G){if(J)Y=Y+1;if(Q)Y=Y+1;if(parseInt($[Y+U+1],10)!==0)u$($,"inexact rounding")}}if(E=P.fromNumber(0),V=P.fromNumber(0),G===0)E=P.fromNumber(0),V=P.fromNumber(0);else if(U<17){let p=0;V=P.fromNumber(H[p++]),E=new P(0,0);for(;p<=U;p++)V=V.multiply(P.fromNumber(10)),V=V.add(P.fromNumber(H[p]))}else{let p=0;E=P.fromNumber(H[p++]);for(;p<=U-17;p++)E=E.multiply(P.fromNumber(10)),E=E.add(P.fromNumber(H[p]));V=P.fromNumber(H[p++]);for(;p<=U;p++)V=V.multiply(P.fromNumber(10)),V=V.add(P.fromNumber(H[p]))}let o=E8(E,P.fromString("100000000000000000"));if(o.low=o.low.add(V),T8(o.low,V))o.high=o.high.add(P.fromNumber(1));I=R+$J;let z={low:P.fromNumber(0),high:P.fromNumber(0)};if(o.high.shiftRightUnsigned(49).and(P.fromNumber(1)).equals(P.fromNumber(1)))z.high=z.high.or(P.fromNumber(3).shiftLeft(61)),z.high=z.high.or(P.fromNumber(I).and(P.fromNumber(16383).shiftLeft(47))),z.high=z.high.or(o.high.and(P.fromNumber(140737488355327)));else z.high=z.high.or(P.fromNumber(I&16383).shiftLeft(49)),z.high=z.high.or(o.high.and(P.fromNumber(562949953421311)));if(z.low=o.low,q)z.high=z.high.or(P.fromString("9223372036854775808"));let d=b.allocateUnsafe(16);return A=0,d[A++]=z.low.low&255,d[A++]=z.low.low>>8&255,d[A++]=z.low.low>>16&255,d[A++]=z.low.low>>24&255,d[A++]=z.low.high&255,d[A++]=z.low.high>>8&255,d[A++]=z.low.high>>16&255,d[A++]=z.low.high>>24&255,d[A++]=z.high.low&255,d[A++]=z.high.low>>8&255,d[A++]=z.high.low>>16&255,d[A++]=z.high.low>>24&255,d[A++]=z.high.high&255,d[A++]=z.high.high>>8&255,d[A++]=z.high.high>>16&255,d[A++]=z.high.high>>24&255,new N$(d)}toString(){let $,C=0,q=Array(36);for(let A=0;A<q.length;A++)q[A]=0;let Q=0,J=!1,j,G={parts:[0,0,0,0]},W,Z,X=[];Q=0;let Y=this.bytes,H=Y[Q++]|Y[Q++]<<8|Y[Q++]<<16|Y[Q++]<<24,F=Y[Q++]|Y[Q++]<<8|Y[Q++]<<16|Y[Q++]<<24,M=Y[Q++]|Y[Q++]<<8|Y[Q++]<<16|Y[Q++]<<24,U=Y[Q++]|Y[Q++]<<8|Y[Q++]<<16|Y[Q++]<<24;if(Q=0,{low:new P(H,F),high:new P(M,U)}.high.lessThan(P.ZERO))X.push("-");let E=U>>26&V8;if(E>>3===3)if(E===m8)return X.join("")+"Infinity";else if(E===I8)return"NaN";else $=U>>15&JJ,j=8+(U>>14&1);else j=U>>14&7,$=U>>17&JJ;let V=$-$J;if(G.parts[0]=(U&16383)+((j&15)<<14),G.parts[1]=M,G.parts[2]=F,G.parts[3]=H,G.parts[0]===0&&G.parts[1]===0&&G.parts[2]===0&&G.parts[3]===0)J=!0;else for(Z=3;Z>=0;Z--){let A=0,x=D8(G);if(G=x.quotient,A=x.rem.low,!A)continue;for(W=8;W>=0;W--)q[Z*9+W]=A%10,A=Math.floor(A/10)}if(J)C=1,q[Q]=0;else{C=36;while(!q[Q])C=C-1,Q=Q+1}let I=C-1+V;if(I>=34||I<=-7||V>0){if(C>34){if(X.push("0"),V>0)X.push(`E+${V}`);else if(V<0)X.push(`E${V}`);return X.join("")}if(X.push(`${q[Q++]}`),C=C-1,C)X.push(".");for(let A=0;A<C;A++)X.push(`${q[Q++]}`);if(X.push("E"),I>0)X.push(`+${I}`);else X.push(`${I}`)}else if(V>=0)for(let A=0;A<C;A++)X.push(`${q[Q++]}`);else{let A=C+V;if(A>0)for(let x=0;x<A;x++)X.push(`${q[Q++]}`);else X.push("0");X.push(".");while(A++<0)X.push("0");for(let x=0;x<C-Math.max(A-1,0);x++)X.push(`${q[Q++]}`)}return X.join("")}toJSON(){return{$numberDecimal:this.toString()}}toExtendedJSON(){return{$numberDecimal:this.toString()}}static fromExtendedJSON($){return N$.fromString($.$numberDecimal)}inspect($,C,q){return q??=g$,`new Decimal128(${q(this.toString(),C)})`}}class X0 extends k${get _bsontype(){return"Double"}constructor($){super();if($ instanceof Number)$=$.valueOf();this.value=+$}static fromString($){let C=Number($);if($==="NaN")return new X0(NaN);if($==="Infinity")return new X0(1/0);if($==="-Infinity")return new X0(-1/0);if(!Number.isFinite(C))throw new g(`Input: ${$} is not representable as a Double`);if($.trim()!==$)throw new g(`Input: '${$}' contains whitespace`);if($==="")throw new g("Input is an empty string");if(/[^-0-9.+eE]/.test($))throw new g(`Input: '${$}' is not in decimal or exponential notation`);return new X0(C)}valueOf(){return this.value}toJSON(){return this.value}toString($){return this.value.toString($)}toExtendedJSON($){if($&&($.legacy||$.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){let q=parseFloat($.$numberDouble);return C&&C.relaxed?q:new X0(q)}inspect($,C,q){return q??=g$,`new Double(${q(this.value,C)})`}}class i0 extends k${get _bsontype(){return"Int32"}constructor($){super();if($ instanceof Number)$=$.valueOf();this.value=+$|0}static fromString($){let C=KJ($),q=Number($);if(hq<q)throw new g(`Input: '${$}' is larger than the maximum value for Int32`);else if(pq>q)throw new g(`Input: '${$}' is smaller than the minimum value for Int32`);else if(!Number.isSafeInteger(q))throw new g(`Input: '${$}' is not a safe integer`);else if(q.toString()!==C)throw new g(`Input: '${$}' is not a valid Int32 string`);return new i0(q)}valueOf(){return this.value}toString($){return this.value.toString($)}toJSON(){return this.value}toExtendedJSON($){if($&&($.relaxed||$.legacy))return this.value;return{$numberInt:this.value.toString()}}static fromExtendedJSON($,C){return C&&C.relaxed?parseInt($.$numberInt,10):new i0($.$numberInt)}inspect($,C,q){return q??=g$,`new Int32(${q(this.value,C)})`}}class tC extends k${get _bsontype(){return"MaxKey"}toExtendedJSON(){return{$maxKey:1}}static fromExtendedJSON(){return new tC}inspect(){return"new MaxKey()"}}class iC extends k${get _bsontype(){return"MinKey"}toExtendedJSON(){return{$minKey:1}}static fromExtendedJSON(){return new iC}inspect(){return"new MinKey()"}}var L0=null,zC=new WeakMap;class G$ extends k${get _bsontype(){return"ObjectId"}constructor($){super();let C;if(typeof $==="object"&&$&&"id"in $){if(typeof $.id!=="string"&&!ArrayBuffer.isView($.id))throw new g("Argument passed in must have an id that is of type string or Buffer");if("toHexString"in $&&typeof $.toHexString==="function")C=b.fromHex($.toHexString());else C=$.id}else C=$;if(C==null||typeof C==="number")this.buffer=G$.generate(typeof C==="number"?C:void 0);else if(ArrayBuffer.isView(C)&&C.byteLength===12)this.buffer=b.toLocalBufferType(C);else if(typeof C==="string")if(G$.validateHexString(C)){if(this.buffer=b.fromHex(C),G$.cacheHexString)zC.set(this,C)}else throw new g("input must be a 24 character hex string, 12 byte Uint8Array, or an integer");else throw new g("Argument passed in does not match the accepted types")}get id(){return this.buffer}set id($){if(this.buffer=$,G$.cacheHexString)zC.set(this,b.toHex($))}static validateHexString($){if($?.length!==24)return!1;for(let C=0;C<24;C++){let q=$.charCodeAt(C);if(q>=48&&q<=57||q>=97&&q<=102||q>=65&&q<=70)continue;return!1}return!0}toHexString(){if(G$.cacheHexString){let C=zC.get(this);if(C)return C}let $=b.toHex(this.id);if(G$.cacheHexString)zC.set(this,$);return $}static getInc(){return G$.index=(G$.index+1)%16777215}static generate($){if(typeof $!=="number")$=Math.floor(Date.now()/1000);let C=G$.getInc(),q=b.allocateUnsafe(12);if(N0.setInt32BE(q,0,$),L0===null)L0=b.randomBytes(5);return q[4]=L0[0],q[5]=L0[1],q[6]=L0[2],q[7]=L0[3],q[8]=L0[4],q[11]=C&255,q[10]=C>>8&255,q[9]=C>>16&255,q}toString($){if($==="base64")return b.toBase64(this.id);if($==="hex")return this.toHexString();return this.toHexString()}toJSON(){return this.toHexString()}static is($){return $!=null&&typeof $==="object"&&"_bsontype"in $&&$._bsontype==="ObjectId"}equals($){if($===void 0||$===null)return!1;if(G$.is($))return this.buffer[11]===$.buffer[11]&&b.equals(this.buffer,$.buffer);if(typeof $==="string")return $.toLowerCase()===this.toHexString();if(typeof $==="object"&&typeof $.toHexString==="function"){let C=$.toHexString(),q=this.toHexString();return typeof C==="string"&&C.toLowerCase()===q}return!1}getTimestamp(){let $=new Date,C=N0.getUint32BE(this.buffer,0);return $.setTime(Math.floor(C)*1000),$}static createPk(){return new G$}serializeInto($,C){return $[C]=this.buffer[0],$[C+1]=this.buffer[1],$[C+2]=this.buffer[2],$[C+3]=this.buffer[3],$[C+4]=this.buffer[4],$[C+5]=this.buffer[5],$[C+6]=this.buffer[6],$[C+7]=this.buffer[7],$[C+8]=this.buffer[8],$[C+9]=this.buffer[9],$[C+10]=this.buffer[10],$[C+11]=this.buffer[11],12}static createFromTime($){let C=b.allocate(12);for(let q=11;q>=4;q--)C[q]=0;return N0.setInt32BE(C,0,$),new G$(C)}static createFromHexString($){if($?.length!==24)throw new g("hex string must be 24 characters");return new G$(b.fromHex($))}static createFromBase64($){if($?.length!==16)throw new g("base64 string must be 16 characters");return new G$(b.fromBase64($))}static isValid($){if($==null)return!1;if(typeof $==="string")return G$.validateHexString($);try{return new G$($),!0}catch{return!1}}toExtendedJSON(){if(this.toHexString)return{$oid:this.toHexString()};return{$oid:this.toString("hex")}}static fromExtendedJSON($){return new G$($.$oid)}isCached(){return G$.cacheHexString&&zC.has(this)}inspect($,C,q){return q??=g$,`new ObjectId(${q(this.toHexString(),C)})`}}G$.index=Math.floor(Math.random()*16777215);function L8($){return $.split("").sort().join("")}class H0 extends k${get _bsontype(){return"BSONRegExp"}constructor($,C){super();if(this.pattern=$,this.options=L8(C??""),this.pattern.indexOf("\x00")!==-1)throw new g(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`);if(this.options.indexOf("\x00")!==-1)throw new g(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`);for(let q=0;q<this.options.length;q++)if(!(this.options[q]==="i"||this.options[q]==="m"||this.options[q]==="x"||this.options[q]==="l"||this.options[q]==="s"||this.options[q]==="u"))throw new g(`The regular expression option [${this.options[q]}] is not supported`)}static parseOptions($){return $?$.split("").sort().join(""):""}toExtendedJSON($){if($=$||{},$.legacy)return{$regex:this.pattern,$options:this.options};return{$regularExpression:{pattern:this.pattern,options:this.options}}}static fromExtendedJSON($){if("$regex"in $)if(typeof $.$regex!=="string"){if($.$regex._bsontype==="BSONRegExp")return $}else return new H0($.$regex,H0.parseOptions($.$options));if("$regularExpression"in $)return new H0($.$regularExpression.pattern,H0.parseOptions($.$regularExpression.options));throw new g(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify($)}`)}inspect($,C,q){let Q=q8(C)??((G)=>G);q??=g$;let J=Q(q(this.pattern),"regexp"),j=Q(q(this.options),"regexp");return`new BSONRegExp(${J}, ${j})`}}class eC extends k${get _bsontype(){return"BSONSymbol"}constructor($){super();this.value=$}valueOf(){return this.value}toString(){return this.value}toJSON(){return this.value}toExtendedJSON(){return{$symbol:this.value}}static fromExtendedJSON($){return new eC($.$symbol)}inspect($,C,q){return q??=g$,`new BSONSymbol(${q(this.value,C)})`}}var N8=P;class Y0 extends N8{get _bsontype(){return"Timestamp"}get i(){return this.low>>>0}get t(){return this.high>>>0}constructor($){if($==null)super(0,0,!0);else if(typeof $==="bigint")super($,!0);else if(P.isLong($))super($.low,$.high,!0);else if(typeof $==="object"&&"t"in $&&"i"in $){if(typeof $.t!=="number"&&(typeof $.t!=="object"||$.t._bsontype!=="Int32"))throw new g("Timestamp constructed from { t, i } must provide t as a number");if(typeof $.i!=="number"&&(typeof $.i!=="object"||$.i._bsontype!=="Int32"))throw new g("Timestamp constructed from { t, i } must provide i as a number");let C=Number($.t),q=Number($.i);if(C<0||Number.isNaN(C))throw new g("Timestamp constructed from { t, i } must provide a positive t");if(q<0||Number.isNaN(q))throw new g("Timestamp constructed from { t, i } must provide a positive i");if(C>4294967295)throw new g("Timestamp constructed from { t, i } must provide t equal or less than uint32 max");if(q>4294967295)throw new g("Timestamp constructed from { t, i } must provide i equal or less than uint32 max");super(q,C,!0)}else throw new g("A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }")}toJSON(){return{$timestamp:this.toString()}}static fromInt($){return new Y0(P.fromInt($,!0))}static fromNumber($){return new Y0(P.fromNumber($,!0))}static fromBits($,C){return new Y0({i:$,t:C})}static fromString($,C){return new Y0(P.fromString($,!0,C))}toExtendedJSON(){return{$timestamp:{t:this.t,i:this.i}}}static fromExtendedJSON($){let C=P.isLong($.$timestamp.i)?$.$timestamp.i.getLowBitsUnsigned():$.$timestamp.i,q=P.isLong($.$timestamp.t)?$.$timestamp.t.getLowBitsUnsigned():$.$timestamp.t;return new Y0({t:q,i:C})}inspect($,C,q){q??=g$;let Q=q(this.t,C),J=q(this.i,C);return`new Timestamp({ t: ${Q}, i: ${J} })`}}Y0.MAX_VALUE=P.MAX_UNSIGNED_VALUE;var VZ=P.fromNumber(Q8),mZ=P.fromNumber(J8);function g8($){return $!=null&&typeof $==="object"&&"_bsontype"in $&&typeof $._bsontype==="string"}var k8={$oid:G$,$binary:f,$uuid:f,$symbol:eC,$numberInt:i0,$numberDecimal:N$,$numberDouble:X0,$numberLong:P,$minKey:iC,$maxKey:tC,$regex:H0,$regularExpression:H0,$timestamp:Y0};function UJ($,C={}){if(typeof $==="number"){let Q=$<=hq&&$>=pq,J=$<=YJ&&$>=HJ;if(C.relaxed||C.legacy)return $;if(Number.isInteger($)&&!Object.is($,-0)){if(Q)return new i0($);if(J){if(C.useBigInt64)return BigInt($);return P.fromNumber($)}}return new X0($)}if($==null||typeof $!=="object")return $;if($.$undefined)return null;let q=Object.keys($).filter((Q)=>Q.startsWith("$")&&$[Q]!=null);for(let Q=0;Q<q.length;Q++){let J=k8[q[Q]];if(J)return J.fromExtendedJSON($,C)}if($.$date!=null){let Q=$.$date,J=new Date;if(C.legacy)if(typeof Q==="number")J.setTime(Q);else if(typeof Q==="string")J.setTime(Date.parse(Q));else if(typeof Q==="bigint")J.setTime(Number(Q));else throw new vq(`Unrecognized type for EJSON date: ${typeof Q}`);else if(typeof Q==="string")J.setTime(Date.parse(Q));else if(P.isLong(Q))J.setTime(Q.toNumber());else if(typeof Q==="number"&&C.relaxed)J.setTime(Q);else if(typeof Q==="bigint")J.setTime(Number(Q));else throw new vq(`Unrecognized type for EJSON date: ${typeof Q}`);return J}if($.$code!=null){let Q=Object.assign({},$);if($.$scope)Q.$scope=UJ($.$scope);return VC.fromExtendedJSON($)}if(w8($)||$.$dbPointer){let Q=$.$ref?$:$.$dbPointer;if(Q instanceof t0)return Q;let J=Object.keys(Q).filter((G)=>G.startsWith("$")),j=!0;if(J.forEach((G)=>{if(["$ref","$id","$db"].indexOf(G)===-1)j=!1}),j)return t0.fromExtendedJSON(Q)}return $}function S8($,C){return $.map((q,Q)=>{C.seenObjects.push({propertyName:`index ${Q}`,obj:null});try{return Z0(q,C)}finally{C.seenObjects.pop()}})}function WJ($){let C=$.toISOString();return $.getUTCMilliseconds()!==0?C:C.slice(0,-5)+"Z"}function Z0($,C){if($ instanceof Map||ZJ($)){let q=Object.create(null);for(let[Q,J]of $){if(typeof Q!=="string")throw new g("Can only serialize maps with string keys");q[Q]=J}return Z0(q,C)}if((typeof $==="object"||typeof $==="function")&&$!==null){let q=C.seenObjects.findIndex((Q)=>Q.obj===$);if(q!==-1){let Q=C.seenObjects.map((Y)=>Y.propertyName),J=Q.slice(0,q).map((Y)=>`${Y} -> `).join(""),j=Q[q],G=" -> "+Q.slice(q+1,Q.length-1).map((Y)=>`${Y} -> `).join(""),W=Q[Q.length-1],Z=" ".repeat(J.length+j.length/2),X="-".repeat(G.length+(j.length+W.length)/2-1);throw new g(`Converting circular structure to EJSON:
|
|
796
|
+
${J}${j}${G}${W}
|
|
797
|
+
${Z}\\${X}/`)}C.seenObjects[C.seenObjects.length-1].obj=$}if(Array.isArray($))return S8($,C);if($===void 0)return null;if($ instanceof Date||C8($)){let q=$.getTime(),Q=q>-1&&q<253402318800000;if(C.legacy)return C.relaxed&&Q?{$date:$.getTime()}:{$date:WJ($)};return C.relaxed&&Q?{$date:WJ($)}:{$date:{$numberLong:$.getTime().toString()}}}if(typeof $==="number"&&(!C.relaxed||!isFinite($))){if(Number.isInteger($)&&!Object.is($,-0)){if($>=pq&&$<=hq)return{$numberInt:$.toString()};if($>=HJ&&$<=YJ)return{$numberLong:$.toString()}}return{$numberDouble:Object.is($,-0)?"-0.0":$.toString()}}if(typeof $==="bigint"){if(!C.relaxed)return{$numberLong:BigInt.asIntN(64,$).toString()};return Number(BigInt.asIntN(64,$))}if($ instanceof RegExp||$8($)){let q=$.flags;if(q===void 0){let J=$.toString().match(/[gimuy]*$/);if(J)q=J[0]}return new H0($.source,q).toExtendedJSON(C)}if($!=null&&typeof $==="object")return O8($,C);return $}var B8={Binary:($)=>new f($.value(),$.sub_type),Code:($)=>new VC($.code,$.scope),DBRef:($)=>new t0($.collection||$.namespace,$.oid,$.db,$.fields),Decimal128:($)=>new N$($.bytes),Double:($)=>new X0($.value),Int32:($)=>new i0($.value),Long:($)=>P.fromBits($.low!=null?$.low:$.low_,$.low!=null?$.high:$.high_,$.low!=null?$.unsigned:$.unsigned_),MaxKey:()=>new tC,MinKey:()=>new iC,ObjectId:($)=>new G$($),BSONRegExp:($)=>new H0($.pattern,$.options),BSONSymbol:($)=>new eC($.value),Timestamp:($)=>Y0.fromBits($.low,$.high)};function O8($,C){if($==null||typeof $!=="object")throw new g("not an object instance");let q=$._bsontype;if(typeof q>"u"){let Q={};for(let J of Object.keys($)){C.seenObjects.push({propertyName:J,obj:null});try{let j=Z0($[J],C);if(J==="__proto__")Object.defineProperty(Q,J,{value:j,writable:!0,enumerable:!0,configurable:!0});else Q[J]=j}finally{C.seenObjects.pop()}}return Q}else if($!=null&&typeof $==="object"&&typeof $._bsontype==="string"&&$[XJ]!==bq)throw new FJ;else if(g8($)){let Q=$;if(typeof Q.toExtendedJSON!=="function"){let J=B8[$._bsontype];if(!J)throw new g("Unrecognized or invalid _bsontype: "+$._bsontype);Q=J(Q)}if(q==="Code"&&Q.scope)Q=new VC(Q.code,Z0(Q.scope,C));else if(q==="DBRef"&&Q.oid)Q=new t0(Z0(Q.collection,C),Z0(Q.oid,C),Z0(Q.db,C),Z0(Q.fields,C));return Q.toExtendedJSON(C)}else throw new g("_bsontype must be a string, but was: "+typeof q)}function RJ($,C){let q={useBigInt64:C?.useBigInt64??!1,relaxed:C?.relaxed??!0,legacy:C?.legacy??!1};return JSON.parse($,(Q,J)=>{if(Q.indexOf("\x00")!==-1)throw new g(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(Q)}`);return UJ(J,q)})}function zJ($,C,q,Q){if(q!=null&&typeof q==="object")Q=q,q=0;if(C!=null&&typeof C==="object"&&!Array.isArray(C))Q=C,C=void 0,q=0;let J=Object.assign({relaxed:!0,legacy:!1},Q,{seenObjects:[{propertyName:"(root)",obj:null}]}),j=Z0($,J);return JSON.stringify(j,C,q)}function y8($,C){return C=C||{},JSON.parse(zJ($,C))}function x8($,C){return C=C||{},RJ(JSON.stringify($),C)}var R0=Object.create(null);R0.parse=RJ;R0.stringify=zJ;R0.serialize=y8;R0.deserialize=x8;Object.freeze(R0);var j$={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 xq($,C){try{return N0.getNonnegativeInt32LE($,C)}catch(q){throw new G0("BSON size cannot be negative",C,{cause:q})}}function cq($,C){let q=C;for(;$[q]!==0;q++);if(q===$.length-1)throw new G0("Null terminator not found",C);return q}function c8($,C=0){if(C??=0,$.length<5)throw new G0(`Input must be at least 5 bytes, got ${$.length} bytes`,C);let q=xq($,C);if(q>$.length-C)throw new G0(`Parsed documentSize (${q} bytes) does not match input length (${$.length} bytes)`,C);if($[C+q-1]!==0)throw new G0("BSON documents must end in 0x00",C+q);let Q=[],J=C+4;while(J<=q+C){let j=$[J];if(J+=1,j===0){if(J-C!==q)throw new G0("Invalid 0x00 type byte",J);break}let G=J,W=cq($,J)-G;J+=W+1;let Z;if(j===j$.double||j===j$.long||j===j$.date||j===j$.timestamp)Z=8;else if(j===j$.int)Z=4;else if(j===j$.objectId)Z=12;else if(j===j$.decimal)Z=16;else if(j===j$.bool)Z=1;else if(j===j$.null||j===j$.undefined||j===j$.maxKey||j===j$.minKey)Z=0;else if(j===j$.regex)Z=cq($,cq($,J)+1)+1-J;else if(j===j$.object||j===j$.array||j===j$.javascriptWithScope)Z=xq($,J);else if(j===j$.string||j===j$.binData||j===j$.dbPointer||j===j$.javascript||j===j$.symbol){if(Z=xq($,J)+4,j===j$.binData)Z+=1;if(j===j$.dbPointer)Z+=12}else throw new G0(`Invalid 0x${j.toString(16).padStart(2,"0")} type byte`,J);if(Z>q)throw new G0("value reports length larger than document",J);Q.push([j,G,W,J,Z]),J+=Z}return Q}var $q=Object.create(null);$q.parseToElements=c8;$q.ByteUtils=b;$q.NumberUtils=N0;Object.freeze($q);var v8=17825792,IZ=b.allocate(v8);import{execFileSync as b8}from"node:child_process";import{existsSync as qq,mkdirSync as h8,readdirSync as p8,readFileSync as Qq,rmSync as fq,writeFileSync as e$}from"node:fs";import{basename as TJ,dirname as LJ,join as _$,resolve as NJ}from"node:path";var lq=".justo-space.json";function _J(){return{template:"react-vite-shadcn",version:2,collections:{}}}function Cq(){return process.execPath}function g0($){if(process.platform==="win32")return`${$}.cmd`;return $}function VJ(){return`import {useState, type FormEvent} from 'react'
|
|
798
798
|
import {Badge} from '@/components/ui/badge'
|
|
799
799
|
import {Button} from '@/components/ui/button'
|
|
800
800
|
import {Card, CardContent, CardDescription, CardHeader, CardTitle} from '@/components/ui/card'
|
|
@@ -804,16 +804,14 @@ import {Input} from '@/components/ui/input'
|
|
|
804
804
|
import {Separator} from '@/components/ui/separator'
|
|
805
805
|
import {Textarea} from '@/components/ui/textarea'
|
|
806
806
|
import {Toaster} from '@/components/ui/sonner'
|
|
807
|
-
import {MapContainer,
|
|
807
|
+
import {MapContainer, CircleMarker, Popup} from 'react-leaflet'
|
|
808
|
+
import {BaseMapLayer} from '@/components/BaseMapLayer'
|
|
808
809
|
import {Bar, BarChart, CartesianGrid, XAxis} from 'recharts'
|
|
809
810
|
import {toast} from 'sonner'
|
|
810
811
|
import {justoCli} from '@/lib/justo'
|
|
811
812
|
|
|
812
813
|
const defaultCommand = 'auth status'
|
|
813
814
|
const queryExample = "data queries preview <queryId> --params '{\\"limit\\":10}'"
|
|
814
|
-
const mapTilerToken =
|
|
815
|
-
(import.meta.env as {${Sc}?: string}).${Sc} ||
|
|
816
|
-
'${no}'
|
|
817
815
|
const chartData = [
|
|
818
816
|
{day: 'Lun', sessions: 12},
|
|
819
817
|
{day: 'Mar', sessions: 18},
|
|
@@ -982,7 +980,7 @@ export function App() {
|
|
|
982
980
|
<CardHeader>
|
|
983
981
|
<CardTitle>Mapa con OpenStreetMap</CardTitle>
|
|
984
982
|
<CardDescription className="text-stone-600">
|
|
985
|
-
Usa el
|
|
983
|
+
Usa el mapa base propio de Justo (tiles.getjusto.com), con datos de
|
|
986
984
|
OpenStreetMap.
|
|
987
985
|
</CardDescription>
|
|
988
986
|
</CardHeader>
|
|
@@ -994,12 +992,7 @@ export function App() {
|
|
|
994
992
|
scrollWheelZoom={false}
|
|
995
993
|
zoom={12}
|
|
996
994
|
>
|
|
997
|
-
<
|
|
998
|
-
attribution='© <a href="https://www.maptiler.com/copyright/" target="_blank">MapTiler</a> <a href="https://www.openstreetmap.org/copyright" target="_blank">© OpenStreetMap contributors</a>'
|
|
999
|
-
tileSize={512}
|
|
1000
|
-
url={\`https://api.maptiler.com/maps/streets/{z}/{x}/{y}@2x.png?key=\${mapTilerToken}\`}
|
|
1001
|
-
zoomOffset={-1}
|
|
1002
|
-
/>
|
|
995
|
+
<BaseMapLayer />
|
|
1003
996
|
<CircleMarker
|
|
1004
997
|
center={[-33.4372, -70.6506]}
|
|
1005
998
|
pathOptions={{color: '#44403c', fillColor: '#44403c', fillOpacity: 0.9}}
|
|
@@ -1010,8 +1003,8 @@ export function App() {
|
|
|
1010
1003
|
</MapContainer>
|
|
1011
1004
|
</div>
|
|
1012
1005
|
<p className="text-sm text-stone-600">
|
|
1013
|
-
No necesitas configurar
|
|
1014
|
-
|
|
1006
|
+
No necesitas configurar ninguna key: usa \`<BaseMapLayer />\` dentro de cualquier
|
|
1007
|
+
\`MapContainer\`.
|
|
1015
1008
|
</p>
|
|
1016
1009
|
</CardContent>
|
|
1017
1010
|
</Card>
|
|
@@ -1024,7 +1017,38 @@ export function App() {
|
|
|
1024
1017
|
}
|
|
1025
1018
|
|
|
1026
1019
|
export default App
|
|
1027
|
-
`}function
|
|
1020
|
+
`}function mJ(){return`import {leafletLayer} from 'protomaps-leaflet'
|
|
1021
|
+
import {useEffect} from 'react'
|
|
1022
|
+
import {useMap} from 'react-leaflet'
|
|
1023
|
+
|
|
1024
|
+
// Self-hosted Justo basemap (vector tiles served from S3 + CloudFront, no key needed)
|
|
1025
|
+
const MAP_TILES_URL = 'https://tiles.getjusto.com/latam.pmtiles'
|
|
1026
|
+
// OpenStreetMap credit is the only one its license (ODbL) requires
|
|
1027
|
+
const MAP_ATTRIBUTION =
|
|
1028
|
+
'<a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noreferrer">© OpenStreetMap</a>'
|
|
1029
|
+
|
|
1030
|
+
/** Background map for any react-leaflet MapContainer */
|
|
1031
|
+
export function BaseMapLayer({dark = false}: {dark?: boolean}) {
|
|
1032
|
+
const map = useMap()
|
|
1033
|
+
|
|
1034
|
+
useEffect(() => {
|
|
1035
|
+
// Credits show only "© OpenStreetMap", without Leaflet's own prefix
|
|
1036
|
+
map.attributionControl?.setPrefix(false)
|
|
1037
|
+
const layer = leafletLayer({
|
|
1038
|
+
url: MAP_TILES_URL,
|
|
1039
|
+
flavor: dark ? 'dark' : 'light',
|
|
1040
|
+
lang: 'es',
|
|
1041
|
+
attribution: MAP_ATTRIBUTION,
|
|
1042
|
+
})
|
|
1043
|
+
layer.addTo(map)
|
|
1044
|
+
return () => {
|
|
1045
|
+
layer.remove()
|
|
1046
|
+
}
|
|
1047
|
+
}, [map, dark])
|
|
1048
|
+
|
|
1049
|
+
return null
|
|
1050
|
+
}
|
|
1051
|
+
`}function IJ(){return`type JustoCliFunction = <T = unknown>(command: string) => Promise<T>
|
|
1028
1052
|
type JustoStreamFunction = <T = unknown>(
|
|
1029
1053
|
command: string,
|
|
1030
1054
|
onRow: (row: T) => Promise<void> | void,
|
|
@@ -1166,7 +1190,7 @@ export async function justoStream<T = unknown>(
|
|
|
1166
1190
|
}
|
|
1167
1191
|
|
|
1168
1192
|
ensurePreviewWindowJusto()
|
|
1169
|
-
`}function
|
|
1193
|
+
`}function DJ($){return`# ${$}
|
|
1170
1194
|
|
|
1171
1195
|
Starter de Justo Spaces generado por \`team-cli spaces init\`.
|
|
1172
1196
|
|
|
@@ -1175,7 +1199,7 @@ Incluye:
|
|
|
1175
1199
|
- Tailwind
|
|
1176
1200
|
- todos los componentes shadcn
|
|
1177
1201
|
- chart wrapper de shadcn + recharts
|
|
1178
|
-
- mapas con \`react-leaflet\` +
|
|
1202
|
+
- mapas con \`react-leaflet\` + \`<BaseMapLayer />\` (mapa base propio de Justo)
|
|
1179
1203
|
- helper \`justoCli(...)\` para llamar \`window.justo.cli(...)\`
|
|
1180
1204
|
- helper \`justoStream(...)\` para consumir NDJSON desde el CLI
|
|
1181
1205
|
- un repo git nuevo e independiente para versionar el space
|
|
@@ -1202,7 +1226,7 @@ Tip:
|
|
|
1202
1226
|
- después de \`spaces init\`, haz un initial commit para fijar el scaffold base
|
|
1203
1227
|
- después de cada publish, haz commit para que el repo refleje exactamente lo que quedó publicado
|
|
1204
1228
|
- 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'\`
|
|
1205
|
-
`}function
|
|
1229
|
+
`}function EJ(){return`import {StrictMode} from 'react'
|
|
1206
1230
|
import {createRoot} from 'react-dom/client'
|
|
1207
1231
|
import App from './App.tsx'
|
|
1208
1232
|
import './index.css'
|
|
@@ -1213,13 +1237,13 @@ createRoot(document.getElementById('root')!).render(
|
|
|
1213
1237
|
<App />
|
|
1214
1238
|
</StrictMode>,
|
|
1215
1239
|
)
|
|
1216
|
-
`}function
|
|
1217
|
-
base: './',`);
|
|
1218
|
-
`)}function
|
|
1219
|
-
${
|
|
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((
|
|
1222
|
-
`);let
|
|
1240
|
+
`}function mC($,C,q){b8($,C,{cwd:q,stdio:"inherit",env:{...process.env,CI:"1"}})}function l8($){if(!$)throw Error("Falta --path. Ejemplo: team-cli spaces init --path ./mi-space-app");let C=NJ($);if(qq(C)){if(p8(C).length>0)throw Error(`La carpeta ya existe y no está vacía: ${C}`);fq(C,{recursive:!0,force:!0})}return h8(LJ(C),{recursive:!0}),C}function f8($){let C=_$($,"vite.config.ts"),q=Qq(C,"utf-8");if(q.includes("base: './'"))return;let Q=q.replace("export default defineConfig({",`export default defineConfig({
|
|
1241
|
+
base: './',`);e$(C,Q)}function u8($){let C=_$($,"tsconfig.app.json"),Q=Qq(C,"utf-8").replace('"noUnusedLocals": true,','"noUnusedLocals": false,').replace('"noUnusedParameters": true,','"noUnusedParameters": false,');e$(C,Q)}function d8($){let C=_$($,"package.json"),q=JSON.parse(Qq(C,"utf-8"));q.dependencies=q.dependencies||{},q.devDependencies=q.devDependencies||{},q.dependencies.leaflet="^1.9.4",q.dependencies["react-leaflet"]="^5.0.0",q.dependencies["protomaps-leaflet"]="5.1.0",q.devDependencies["@types/leaflet"]="^1.9.20",q.justoSpaceApp=!0,e$(C,`${JSON.stringify(q,null,2)}
|
|
1242
|
+
`)}function s8($){let C=_$($,"src","index.css"),q=Qq(C,"utf-8");if(q.includes("leaflet/dist/leaflet.css"))return;e$(C,`@import "leaflet/dist/leaflet.css";
|
|
1243
|
+
${q}`)}function n8($){let C=TJ($);e$(_$($,"README.md"),DJ(C)),e$(_$($,"src","App.tsx"),VJ()),e$(_$($,"src","main.tsx"),EJ()),e$(_$($,"src","lib","justo.ts"),IJ()),e$(_$($,"src","components","BaseMapLayer.tsx"),mJ()),e$(_$($,lq),`${JSON.stringify(_J(),null,2)}
|
|
1244
|
+
`),fq(_$($,".git"),{recursive:!0,force:!0})}function a8($){mC("git",["init"],$)}function o8($){fq(_$($,"package-lock.json"),{force:!0})}function uq($){let C=NJ($);if(!qq(C))throw Error(`No existe la app del space: ${C}`);if(!qq(_$(C,lq)))throw Error("Este publish solo acepta apps creadas con team-cli spaces init. Debes apuntar al root de esa app.");return C}function gJ($){let C=uq($);mC(g0("yarn"),["build"],C);let q=_$(C,"dist");if(!qq(_$(q,"index.html")))throw Error("El build no generó dist/index.html");return q}function kJ($){let C=l8($),q=LJ(C),Q=TJ(C);return mC(g0("npx"),["shadcn@latest","init","-t","vite","-d","-y","-n",Q],q),mC(g0("npx"),["shadcn@latest","add","-a","-y"],C),o8(C),d8(C),mC(g0("yarn"),["install"],C),f8(C),u8(C),s8(C),n8(C),a8(C),{path:C,nextSteps:[`cd ${C}`,'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 yJ,readFileSync as xJ,statSync as cJ}from"node:fs";import{gzipSync as JW}from"node:zlib";import{join as vJ,relative as bJ,resolve as BJ}from"node:path";import{existsSync as r8,readFileSync as t8}from"node:fs";import{join as i8}from"node:path";var e8=[".git","node_modules","dist",".justo-space-preview",".DS_Store"];function $W($){return $.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}function CW($){let C="";for(let q=0;q<$.length;q++){let Q=$[q],J=$[q+1];if(Q==="*"){if(J==="*"){C+=".*",q+=1;continue}C+="[^/]*";continue}if(Q==="?"){C+="[^/]";continue}C+=$W(Q)}return C}function qW($){let C=$.trim();if(!C||C.startsWith("#"))return null;let q=C.startsWith("!"),Q=q?C.slice(1).trim():C;if(!Q)return null;let J=Q.endsWith("/"),j=Q.replace(/^\/+/,"").replace(/\/+$/,"");if(!j)return null;let G=j.includes("/"),W=CW(j),Z=G?`^${W}${J?"(?:/.*)?":""}$`:`(?:^|/)${W}${J?"(?:/.*)?":"(?:$|/)"}`;return{negate:q,directoryOnly:J,regex:new RegExp(Z)}}function QW($){let C=i8($,".gitignore"),q=[...e8];if(r8(C))q.push(...t8(C,"utf-8").split(/\r?\n/));return q.map(qW).filter((Q)=>Boolean(Q))}function SJ($){let C=QW($);return(q,Q)=>{let J=q.replaceAll("\\","/").replace(/^\/+/,""),j=!1;for(let G of C){if(!G.regex.test(J))continue;j=!G.negate}return j}}var Jq=512,jW=2,WW="repo",GW="dist";function ZW($){let C=$.replaceAll("\\","/");if(C.startsWith("/")||C.includes("../"))throw Error(`Ruta inválida en el space: ${$}`);return C}function XW($){let C=ZW($);if(Buffer.from(C).length<=100)return{name:C,prefix:""};let Q=C.lastIndexOf("/");if(Q<=0)throw Error(`La ruta es demasiado larga para el paquete del space: ${$}`);let J=C.slice(0,Q),j=C.slice(Q+1);if(Buffer.from(J).length>155||Buffer.from(j).length>100)throw Error(`La ruta es demasiado larga para el paquete del space: ${$}`);return{name:j,prefix:J}}function k0($,C,q,Q){let J=Buffer.from(Q);J.copy($,C,0,Math.min(J.length,q))}function IC($,C,q,Q){let J=Math.max(0,Math.trunc(Q)).toString(8).padStart(q-1,"0");k0($,C,q,`${J}\x00`)}function YW($){let C=Buffer.alloc(Jq,0),{name:q,prefix:Q}=XW($.path);k0(C,0,100,q),IC(C,100,8,$.mode),IC(C,108,8,0),IC(C,116,8,0),IC(C,124,12,$.content.length),IC(C,136,12,$.mtime),C.fill(32,148,156),k0(C,156,1,"0"),k0(C,257,6,"ustar"),k0(C,263,2,"00"),k0(C,345,155,Q);let J=0;for(let G of C)J+=G;let j=`${J.toString(8).padStart(6,"0")}\x00 `;return k0(C,148,8,j),C}function HW($){let C=$%Jq;return C===0?0:Jq-C}function hJ($,C=$){return yJ(C,{withFileTypes:!0}).sort((Q,J)=>Q.name.localeCompare(J.name)).flatMap((Q)=>{let J=vJ(C,Q.name);if(Q.isDirectory())return hJ($,J);if(!Q.isFile())return[];let j=bJ($,J),G=cJ(J);return[{path:j,content:xJ(J),mode:G.mode&511,mtime:Math.floor(G.mtimeMs/1000)}]})}function OJ($,C){return $.map((q)=>({...q,path:`${C}/${q.path.replaceAll("\\","/")}`}))}function pJ($,C=$){let q=SJ($);return yJ(C,{withFileTypes:!0}).sort((J,j)=>J.name.localeCompare(j.name)).flatMap((J)=>{let j=vJ(C,J.name),G=bJ($,j).replaceAll("\\","/");if(q(G,J.isDirectory()))return[];if(J.isDirectory())return pJ($,j);if(!J.isFile())return[];let W=cJ(j);return[{path:G,content:xJ(j),mode:W.mode&511,mtime:Math.floor(W.mtimeMs/1000)}]})}function lJ($,C){let q=BJ($),Q=BJ(C),J=[...OJ(pJ(q),WW),...OJ(hJ(Q),GW)];if(!J.length)throw Error("El build del space no contiene archivos para publicar");let j=[];for(let G of J){j.push(YW(G)),j.push(G.content);let W=HW(G.content.length);if(W>0)j.push(Buffer.alloc(W,0))}return j.push(Buffer.alloc(Jq*jW,0)),JW(Buffer.concat(j))}import{mkdirSync as fJ,writeFileSync as wW}from"node:fs";import{dirname as FW,join as PW,normalize as MW,sep as uJ}from"node:path";import{gunzipSync as KW}from"node:zlib";var DC=512;function jq($,C,q){let Q=$.subarray(C,C+q),J=Q.indexOf(0);return(J>=0?Q.subarray(0,J):Q).toString("utf-8").trim()}function AW($,C,q){let Q=jq($,C,q).replaceAll("\x00","").trim();if(!Q)return 0;return Number.parseInt(Q,8)}function UW($){let C=$%DC;return C===0?0:DC-C}function RW($){let C=jq($,0,100),q=jq($,345,155);return q?`${q}/${C}`:C}function zW($){let C=MW($);if(!$||$.startsWith("/")||C.startsWith("..")||C.includes(`${uJ}..${uJ}`)||C==="..")throw Error("El paquete del space contiene rutas inválidas")}function dJ($,C,q){let Q=KW($),J=C.replaceAll("\\","/").replace(/^\/+|\/+$/g,""),j=`${J}/`,G=0,W=0;while(G+DC<=Q.length){let Z=Q.subarray(G,G+DC),X=Z.every((E)=>E===0);if(G+=DC,X)break;let Y=RW(Z),H=jq(Z,156,1)||"0",F=AW(Z,124,12),M=Q.subarray(G,G+F);if(G+=F+UW(F),!Y.startsWith(j))continue;let U=Y.slice(j.length);if(!U)continue;zW(U);let R=PW(q,...U.split("/"));if(H==="5"){fJ(R,{recursive:!0});continue}if(H!=="0")continue;fJ(FW(R),{recursive:!0}),wW(R,M),W+=1}if(!W)throw Error(`El paquete del space no contiene la carpeta ${J}/`);return W}import{spawn as Gq}from"node:child_process";import{existsSync as _W,mkdirSync as VW,openSync as mW,readFileSync as IW,rmSync as DW,writeFileSync as EW}from"node:fs";import{createServer as eJ,request as TW}from"node:http";import{request as LW}from"node:https";import{dirname as NW,join as Zq,resolve as $j}from"node:path";function sJ($){let C=[],q="",Q=null,J=!1;for(let j of $){if(J){q+=j,J=!1;continue}if(j==="\\"){J=!0;continue}if(Q){if(j===Q)Q=null;else q+=j;continue}if(j==='"'||j==="'"){Q=j;continue}if(/\s/.test(j)){if(q)C.push(q),q="";continue}q+=j}if(Q)throw Error("Comando inválido: falta cerrar una comilla");if(q)C.push(q);return C}var gW=".justo-space-preview",kW="preview.json",SW=30000;function Xq($){return Zq($,gW)}function Cj($){return Zq(Xq($),kW)}function nJ($){return Zq(Xq($),"bridge.log")}function aJ($){return Zq(Xq($),"vite.log")}function qj($){VW(Xq($),{recursive:!0})}function Wq($){if(!$)return;try{process.kill($,"SIGTERM")}catch{return}}function BW($){if(process.platform==="darwin")return{command:"open",args:[$]};if(process.platform==="win32")return{command:"cmd",args:["/c","start","",$]};return{command:"xdg-open",args:[$]}}async function OW($,C){if(!C)return{attempted:!1,opened:!1};let q=BW($);return await new Promise((Q)=>{let J=Gq(q.command,q.args,{stdio:"ignore",detached:!0});J.once("error",()=>{Q({attempted:!0,opened:!1,message:"No se pudo abrir el navegador por defecto automáticamente. Abre la URL manualmente."})}),J.once("spawn",()=>{J.unref(),Q({attempted:!0,opened:!0})})})}function yW($){let C=Cj($);if(!_W(C))return;try{let q=JSON.parse(IW(C,"utf-8"));Wq(q.appPid),Wq(q.bridgePid)}catch{}DW(C,{force:!0})}function oJ(){return new Promise(($,C)=>{let q=eJ();q.listen(0,"127.0.0.1",()=>{let Q=q.address();if(!Q||typeof Q==="string"){q.close(),C(Error("No se pudo obtener un puerto libre"));return}let{port:J}=Q;q.close((j)=>{if(j){C(j);return}$(J)})}),q.on("error",C)})}function rJ($){return new Promise((C)=>setTimeout(C,$))}function xW($){return new Promise((C,q)=>{let j=(new URL($).protocol==="https:"?LW:TW)($,{method:"GET"},(G)=>{C(G.statusCode||0),G.resume()});j.on("error",q),j.end()})}async function tJ($,C=SW){let q=Date.now();while(Date.now()-q<C){try{if(await xW($)>0)return}catch{await rJ(500);continue}await rJ(500)}throw Error(`Timeout esperando que el preview responda en ${$}`)}function cW($){return qj(NW($)),mW($,"a")}function iJ($,C,q,Q,J){let j=cW(Q),G=Gq($,C,{cwd:q,detached:!0,stdio:["ignore",j,j],env:{...process.env,...J}});if(!G.pid)throw Error(`No se pudo iniciar el proceso ${$}`);return G.unref(),G.pid}function Qj(){let $=B1("prod");if(!$)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 $}async function vW($){let C=[];for await(let q of $)C.push(Buffer.isBuffer(q)?q:Buffer.from(q));return Buffer.concat(C).toString("utf-8")}function EC($,C,q){$.writeHead(C,{"Content-Type":"application/json; charset=utf-8","Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"Content-Type","Access-Control-Allow-Methods":"POST,OPTIONS,GET"}),$.end(JSON.stringify(q))}function dq($){let C=$.trim(),q=new Set([0]);for(let J=0;J<C.length;J++)if(C[J]==="{"||C[J]==="[")q.add(J);let Q=[...q].sort((J,j)=>j-J);for(let J of Q)try{return JSON.parse(C.slice(J))}catch{}return C}function Jj($){return{...process.env,NODE_OPTIONS:"",__JUSTO_REPL_PORT:"",JUSTO_TEAM_CLI_EMAIL:$.email,JUSTO_TEAM_CLI_TOKEN:$.token,JUSTO_TEAM_CLI_REFRESH_TOKEN:$.refreshToken,JUSTO_TEAM_CLI_INTERACTIVE:"false",JUSTO_TEAM_CLI_DEVICE_ID:"spaces-preview"}}function bW($,C){return{VITE_JUSTO_CLI_ENDPOINT:$,VITE_JUSTO_STREAM_ENDPOINT:C,VITE_JUSTO_CLI_MODE:"preview"}}function hW($,C,q,Q){return new Promise((J,j)=>{let G=Gq(Cq(),[C,"--env","prod",...Q,"--format","json"],{cwd:process.cwd(),env:Jj(q),stdio:["ignore","pipe","pipe"]}),W="";G.stdout.on("data",(Z)=>{if(!$.headersSent)$.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"});$.write(Z)}),G.stderr.on("data",(Z)=>{W+=Buffer.from(Z).toString("utf-8")}),G.on("error",j),G.on("close",(Z)=>{if(!Z){if(!$.headersSent)$.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"});$.end(),J();return}let X=dq(W.trim());j(Error(X.error||W.trim()||"justoStream failed"))})})}async function jj($){let C=Number($.port);if(!C)throw Error("Falta --port para el bridge interno de preview");let q=Qj(),Q=$j($["cli-path"]||process.argv[1]||""),J=eJ(async(j,G)=>{if(j.method==="OPTIONS"){EC(G,200,{ok:!0});return}if(j.method==="GET"&&j.url==="/__justo/health"){EC(G,200,{ok:!0});return}if(j.method!=="POST"||j.url!=="/__justo/cli"&&j.url!=="/__justo/stream"){EC(G,404,{ok:!1,error:"Not found"});return}try{let W=await vW(j),X=JSON.parse(W||"{}").command;if(!X)throw Error("Debes indicar un comando");let Y=Array.isArray(X)?X:sJ(X);if(j.url==="/__justo/stream"){await hW(G,Q,q,Y);return}let H=await new Promise((F,M)=>{let U=Gq(Cq(),[Q,"--env","prod",...Y,"--format","json"],{cwd:process.cwd(),env:Jj(q),stdio:["ignore","pipe","pipe"]}),R=[],E=[];U.stdout.on("data",(V)=>R.push(Buffer.from(V))),U.stderr.on("data",(V)=>E.push(Buffer.from(V))),U.on("error",M),U.on("close",(V)=>{let I=Buffer.concat(R).toString("utf-8")||Buffer.concat(E).toString("utf-8");if(V&&V!==0){let A=dq(I);M(Error(A.error||I||"justoCli failed"));return}F(dq(I))})});EC(G,200,{result:H})}catch(W){let Z=W instanceof Error?W.message:"Unexpected error";EC(G,400,{error:Z})}});await new Promise((j,G)=>{J.listen(C,"127.0.0.1",()=>j()),J.on("error",G)}),T$(`Space preview bridge listening on http://127.0.0.1:${C}
|
|
1245
|
+
`),await new Promise((j,G)=>{J.on("close",()=>j()),J.on("error",G)})}async function Wj($){let C=$.path;if(!C)throw Error("Falta --path. Ejemplo: team-cli spaces preview --path ./mi-space-app");let q=uq(C);Qj(),qj(q),yW(q);let Q=Number($.port)||await oJ(),J=Number($["bridge-port"])||await oJ(),j=$.open==="true",G=`http://127.0.0.1:${Q}`,W=`http://127.0.0.1:${J}/__justo/cli`,Z=`http://127.0.0.1:${J}/__justo/stream`,X=$j(process.argv[1]||""),Y=iJ(Cq(),[X,"__spaces-preview-bridge","--port",String(J),"--cli-path",X],process.cwd(),nJ(q),{}),H=iJ(g0("yarn"),["dev","--host","127.0.0.1","--port",String(Q)],q,aJ(q),bW(W,Z));try{await tJ(`http://127.0.0.1:${J}/__justo/health`),await tJ(G)}catch(U){throw Wq(H),Wq(Y),U}let F={appPid:H,bridgePid:Y,previewUrl:G,bridgeUrl:W,streamUrl:Z,cliEnv:"prod"};EW(Cj(q),`${JSON.stringify(F,null,2)}
|
|
1246
|
+
`);let M=await OW(G,j);return{ok:!0,path:q,previewUrl:G,bridgeUrl:W,streamUrl:Z,cliEnv:"prod",appPid:H,bridgePid:Y,logs:{app:aJ(q),bridge:nJ(q)},open:M}}function uW($){try{return R0.parse($)}catch{throw Error("El valor de --operation debe ser JSON/EJSON válido")}}function TC(){if(!X$())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 z0($,C,q){let Q=$[C];if(!Q)throw Error(`Falta --${C}. Ejemplo: ${q}`);return Q}function Zj($,C){let q=$[2];if(!q)throw Error(`Uso: ${C}`);return q}function sq(){let $=J0();if($==="local")return"http://intra.localhost:5173";if($==="develop")return"https://intra.bejusto.com";return"https://intra.getjusto.com"}function dW(){return`Configuración de collections en \`.justo-space.json\`:
|
|
1223
1247
|
- \`spaces publish\` lee \`repo/.justo-space.json\`, valida \`collections\` y sincroniza índices
|
|
1224
1248
|
- cada collection lógica debe existir en \`collections\`
|
|
1225
1249
|
- los nombres válidos usan solo letras, números y guion bajo
|
|
@@ -1258,7 +1282,7 @@ Reglas de índices:
|
|
|
1258
1282
|
- cada índice debe tener \`name\` y \`key\`
|
|
1259
1283
|
- puedes usar opciones comunes de Mongo como \`unique\`, \`sparse\`, \`expireAfterSeconds\` y \`partialFilterExpression\`
|
|
1260
1284
|
- en cada publish, los índices declarados se recrean en modo estricto para esa collection
|
|
1261
|
-
`}function
|
|
1285
|
+
`}function sW(){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 nW($,C){let q=await sC(),Q=await fetch(`${U$("spaces")}/spaces/publish/${$}`,{method:"POST",headers:{"Content-Type":"application/gzip",...q?{"X-ORION-JWT":q}:{}},body:C}),J=await Q.json();if(!Q.ok||J.error)throw Error(J.error||"No se pudo publicar el space.");return J}async function aW($){let C=await sC(),q=await fetch(`${U$("spaces")}/spaces/fork/${$}`,{method:"GET",headers:C?{"X-ORION-JWT":C}:{}});if(!q.ok){let Q=await q.json().catch(()=>({}));throw Error(Q.error||"No se pudo descargar el repo del space.")}return Buffer.from(await q.arrayBuffer())}function oW($){let C=Gj($);if(pW(C)&&fW(C).length>0)throw Error(`La carpeta ya existe y no está vacía: ${C}`);return lW(C,{recursive:!0}),C}function nq(){return`team-cli spaces
|
|
1262
1286
|
|
|
1263
1287
|
Spaces son aplicaciones internas en React, pensadas para que las construyan agentes.
|
|
1264
1288
|
El flujo oficial parte con \`spaces init\` y \`spaces publish\` solo acepta apps creadas así.
|
|
@@ -1284,9 +1308,9 @@ Cada space:
|
|
|
1284
1308
|
- el archivo \`.justo-space.json\` puede declarar \`collections\` para que el publish sincronice índices en Mongo
|
|
1285
1309
|
- esas collections se exponen con \`team-cli spaces db\` usando el prefijo físico \`spaces.<slug_sanitized>.<collection>\`
|
|
1286
1310
|
|
|
1287
|
-
${
|
|
1311
|
+
${dW()}
|
|
1288
1312
|
|
|
1289
|
-
${
|
|
1313
|
+
${sW()}
|
|
1290
1314
|
|
|
1291
1315
|
Flujo sugerido para agentes:
|
|
1292
1316
|
1. \`team-cli spaces init --path ./mi-space-app\`
|
|
@@ -1296,7 +1320,7 @@ Flujo sugerido para agentes:
|
|
|
1296
1320
|
5. desarrollar la app React dentro de esa carpeta
|
|
1297
1321
|
6. \`team-cli spaces publish <spaceId> --path ./mi-space-app\`
|
|
1298
1322
|
7. hacer commit del repo después de publicar
|
|
1299
|
-
8. abrir \`${
|
|
1323
|
+
8. abrir \`${sq()}/spaces/<slug>\`
|
|
1300
1324
|
9. si necesitas retomarlo en otra carpeta: \`team-cli spaces fork <slug> --path ./mi-space-app\`
|
|
1301
1325
|
|
|
1302
1326
|
Slugs:
|
|
@@ -1310,7 +1334,7 @@ Qué crea \`spaces init\`:
|
|
|
1310
1334
|
- Tailwind listo para usar
|
|
1311
1335
|
- todos los componentes shadcn disponibles en \`src/components/ui\`
|
|
1312
1336
|
- charts listos con el wrapper de shadcn + \`recharts\`
|
|
1313
|
-
- mapas listos con \`react-leaflet\` +
|
|
1337
|
+
- mapas listos con \`react-leaflet\` + \`<BaseMapLayer />\` (mapa base propio de Justo)
|
|
1314
1338
|
- helper \`justoCli(...)\` en \`src/lib/justo.ts\`
|
|
1315
1339
|
- helper \`justoStream(...)\` en \`src/lib/justo.ts\`
|
|
1316
1340
|
- ejemplo inicial en \`src/App.tsx\`
|
|
@@ -1323,8 +1347,8 @@ Compartir dashboards:
|
|
|
1323
1347
|
- comparte todas las queries usadas por el dashboard, no solo el space
|
|
1324
1348
|
|
|
1325
1349
|
Mapas:
|
|
1326
|
-
-
|
|
1327
|
-
- no necesitas configurar
|
|
1350
|
+
- usa \`<BaseMapLayer />\` de \`src/components/BaseMapLayer.tsx\` dentro de cualquier \`MapContainer\` (tiles propios en tiles.getjusto.com)
|
|
1351
|
+
- no necesitas configurar ninguna key ni usar proveedores externos de tiles
|
|
1328
1352
|
|
|
1329
1353
|
Reglas de diseño para agentes:
|
|
1330
1354
|
- preferir siempre componentes shadcn antes que UI custom
|
|
@@ -1370,7 +1394,7 @@ Comandos:
|
|
|
1370
1394
|
- \`spaces fork <slug> --path ./mi-space-app\`
|
|
1371
1395
|
- \`spaces archive <spaceId>\`
|
|
1372
1396
|
- \`spaces db --slug <slug> --collection events --operation '{"type":"find","filter":{}}'\`
|
|
1373
|
-
`}async function
|
|
1397
|
+
`}async function Xj($){let C=z0($,"path","team-cli spaces init --path ./mi-space-app");return kJ(C)}async function Yj($){return await Wj($)}async function Hj($){TC();let C=z0($,"name","team-cli spaces create --name 'Mi space' --description '...' --slug dashboard-1234"),q=z0($,"description","team-cli spaces create --name 'Mi space' --description 'Sitio interno' --slug dashboard-1234"),Q=z0($,"slug","team-cli spaces create --name 'Mi space' --description '...' --slug dashboard-1234"),J=await h({service:"spaces",query:`mutation ($name: String, $description: String, $slug: String) {
|
|
1374
1398
|
createSpace(name: $name, description: $description, slug: $slug) {
|
|
1375
1399
|
_id
|
|
1376
1400
|
name
|
|
@@ -1381,7 +1405,7 @@ Comandos:
|
|
|
1381
1405
|
createdByEmail
|
|
1382
1406
|
createdById
|
|
1383
1407
|
}
|
|
1384
|
-
}`,variables:{name:
|
|
1408
|
+
}`,variables:{name:C,description:q,slug:Q}});return{...J.createSpace,intraUrl:`${sq()}/spaces/${J.createSpace.slug}`,serveUrl:`${U$("spaces")}/spaces/${J.createSpace.slug}`}}async function wj($,C){TC();let q=Zj($,"team-cli spaces publish <spaceId> --path ./mi-space-app"),Q=z0(C,"path","team-cli spaces publish <spaceId> --path ./mi-space-app"),J=gJ(Q),j=lJ(Q,J),G=await nW(q,j);return{...G,intraUrl:G.slug?`${sq()}/spaces/${G.slug}`:void 0,serveUrl:G.slug?`${U$("spaces")}/spaces/${G.slug}`:void 0,builtFrom:Gj(Q)}}async function Fj($,C){TC();let q=$[2];if(!q)throw Error("Uso: team-cli spaces fork <slug> --path ./mi-space-app");let Q=oW(C.path||`./${q}`),J=await aW(q),j=dJ(J,"repo",Q);return{ok:!0,slug:q,path:Q,extractedFiles:j,nextSteps:[`cd ${Q}`,"yarn install","team-cli spaces preview --path . --open"]}}async function Pj($){TC();let C=Zj($,"team-cli spaces archive <spaceId>");return(await h({service:"spaces",query:`mutation ($spaceId: String) {
|
|
1385
1409
|
archiveSpace(spaceId: $spaceId) {
|
|
1386
1410
|
_id
|
|
1387
1411
|
name
|
|
@@ -1393,11 +1417,231 @@ Comandos:
|
|
|
1393
1417
|
createdById
|
|
1394
1418
|
archivedAt
|
|
1395
1419
|
}
|
|
1396
|
-
}`,variables:{spaceId:
|
|
1420
|
+
}`,variables:{spaceId:C}})).archiveSpace}async function Mj($){TC();let C=z0($,"slug",`team-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{"type":"find","filter":{}}'`),q=z0($,"collection",`team-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{"type":"find","filter":{}}'`),Q=z0($,"operation",`team-cli spaces db --slug usuario:dashboard-1234 --collection events --operation '{"type":"find","filter":{}}'`);return await e0(C,q,uW(Q))}async function e0($,C,q){let Q=await fetch(`${U$("spaces")}/spaces/${encodeURIComponent($)}/db`,{method:"POST",headers:await p0(),body:JSON.stringify({collection:C,operation:R0.serialize(q)})}),J=await Q.json().catch(()=>({}));if(!Q.ok||J.error)throw Error(J.error||"No se pudo ejecutar spaces db");return J.result}var Yq="jorge:posventa-360";async function d$($,C){return await e0(Yq,$,{type:"findOne",...C})??null}async function M$($,C){return await e0(Yq,$,{type:"find",...C})??[]}async function V$(){let $=await d$("meta",{filter:{metaId:"carga"}});if(!$)throw Error("El space no tiene una carga registrada todavía.");return $}function S$($,C=!1){let q=$.semana,Q=rC($.calculadoEl),J=`Datos de la ${UC(q)}, calculados el ${Q?.getUTCDate()} ${E0[Q?.getUTCMonth()??0]} ${Q?.getUTCFullYear()}.`;if(C)J+=` En total: ${m($.marcas||0)} marcas asignadas a KAM o a Partner Experience.`;let j=dQ();if(q<j)J+=`
|
|
1421
|
+
ATENCIÓN: datos atrasados. Ya cerró la ${UC(j)} y el cálculo central todavía no corre. Dilo al entregar el resultado.`;return J}var rW="https://intra.getjusto.com/data/new-bi/website-bi-list",tW="https://intra.getjusto.com/data/segmentos",c$={PX:{team:"Partner Experience",title:"Partner Experience completo (TOP, Longtail y Lanzamiento)"},KAM:{team:"KAM",title:"todas las carteras de KAM"},TODAS:{team:null,title:"KAM y Partner Experience"}},Kj={px:"PX","partner experience":"PX",kam:"KAM",kams:"KAM",todas:"TODAS",todo:"TODAS"};function Aj($){return Object.entries($.paises||{}).sort((C,q)=>q[1]-C[1]).map(([C,q])=>`${C} ${m(q)}`).join(", ")}async function Uj(){let $=X$()?.email||null;try{let q=(await h({service:"main",query:"query { me { profile { firstName lastName } } }"})).me?.profile||{},Q=[q.firstName,q.lastName].map((J)=>J?.trim()).filter(Boolean).join(" ");return{email:$,name:Q||null}}catch{return{email:$,name:null}}}function Rj($,C){let q=(C.carteras||[]).filter((G)=>G.equipo==="KAM"),Q=new Set(C$($.name).split(" ").filter(Boolean)),J=(G,W)=>[...G].every((Z)=>W.has(Z)),j=[];if(Q.size>=2)j=q.filter((G)=>{let W=new Set(C$(G.asignacion).split(" ").filter(Boolean));return W.size>=2&&(J(W,Q)||J(Q,W))});if(!j.length&&$.email){let G=C$($.email.split("@")[0]).split(" ").filter(Boolean);if(G.length>=2)j=q.filter((W)=>G.every((Z)=>C$(W.asignacion).replaceAll(" ","").includes(Z)))}return j}async function $C($,C){let q=C.carteras||[];if($){let G=C$($);if(Object.hasOwn(Kj,G))return{portfolio:Kj[G],origin:null};let W=G.split(" ").filter(Boolean),Z=q.filter((F)=>G===C$(F.cartera)||G===C$(F.asignacion)),X=Z.length?Z:q.filter((F)=>{let M=C$(F.asignacion).split(" ");return W.every((U)=>M.includes(U))});if(X.length===1)return{portfolio:X[0].cartera,origin:null};let Y=q.map((F)=>F.cartera).join(", "),H=X.length?`"${$}" calza con varias carteras: ${X.map((F)=>F.cartera).join(", ")}`:`No hay una cartera "${$}" en la planilla de asignación`;throw Error(`${H}. Carteras: ${Y}, o PX, KAM, TODAS.`)}let Q=await Uj(),J=Rj(Q,C),j=Q.email||"sin correo";if(J.length===1)return{portfolio:J[0].cartera,origin:`SESIÓN ${j}: en la planilla de asignación del intra figuras como KAM ("${J[0].asignacion}"), así que este es el radar de tu cartera.`};if(J.length>1)throw Error(`Tu nombre calza con más de una asignación de la planilla (${J.map((G)=>G.asignacion).join(", ")}). Indica cuál con --cartera.`);return{portfolio:"PX",origin:`SESIÓN ${j}: tu nombre no es una asignación de la planilla del intra, así que te corresponde Partner Experience. `+"Este radar es de Partner Experience completo; para una cartera usa --cartera TOP, Longtail o Lanzamiento, y --pais para el país."}}function S0($,C){if(Object.hasOwn(c$,$))return c$[$].title;return(C.carteras||[]).find((Q)=>Q.cartera===$)?.equipo==="KAM"?`${$} (KAM)`:`${$} (Partner Experience)`}function iW($){let C=$.ejecucion?.canales||{};if(!Object.keys(C).length)return[];return[`
|
|
1422
|
+
CANALES DE EJECUCIÓN (salen solo de la asignación: una cartera de KAM va por ejecutivo directo y cada cartera de Partner Experience tiene el suyo; el segmento no los cambia):`,...Object.entries(C).map(([q,Q])=>` ${q}: ${Q.nombre} — ${Q.como}; tareas: ${Q.tareas}`)]}async function zj(){let $=await V$(),C=[S$($,!0)],q=await Uj(),Q=Rj(q,$);if(C.push(`
|
|
1423
|
+
SESIÓN de team-cli: ${q.email||"sin correo"}${q.name?` · ${q.name}`:""}`),Q.length===1){let J=Q[0];C.push(`TU CARTERA: la de KAM "${J.asignacion}" en la planilla de asignación del intra: ${m(J.marcas)} marcas (${Aj(J)}). El radar sin --cartera usa esta.`)}else if(Q.length>1)C.push(`TU CARTERA: tu nombre calza con más de una asignación de la planilla (${Q.map((J)=>J.asignacion).join(", ")}). Indica cuál con --cartera.`);else C.push("TU CARTERA: tu nombre no es una asignación de la planilla del intra, así que te corresponde Partner Experience. "+"El radar sin --cartera muestra Partner Experience completo; elige con --cartera TOP, Longtail o Lanzamiento, y el país con --pais.");C.push(`
|
|
1424
|
+
CARTERAS (planilla de asignación del intra: ${rW})`);for(let J of["Partner Experience","KAM"]){let j=($.carteras||[]).filter((G)=>G.equipo===J);if(!j.length)continue;C.push(` ${J}: ${j.map((G)=>`${G.cartera} ${m(G.marcas)} (${Aj(G)})`).join("; ")}`)}return C.push(' Otra cartera: --cartera "<nombre del KAM>", o PX (todo Partner Experience), KAM (todas las de KAM), TODAS.'),C.push(`
|
|
1425
|
+
SEGMENTO (reporte de segmentos del intra: ${tW}): rubro, tier por venta online y modo por recompra. `+"Describe a la marca y va en paralelo a la asignación: en un mismo segmento hay marcas de KAM y de Partner Experience. Se filtra con --tier y --modo."),C.push(...iW($)),C.join(`
|
|
1426
|
+
`)}var oq={lanzamiento:"Lanzamiento",crecimiento:"Crecimiento",madura:"Madura",sin_fecha:"Sin fecha de activación"},s$={diagnostico_caida:"Diagnosticar la caída",recuperar_uso:"Recuperar el uso de un producto",aprovechar_impulso:"Aprovechar el impulso (activar productos)",rescate:"Rescate (preChurn o dejó de vender online)",lanzamiento:"Acompañar el lanzamiento",plan_activacion:"Plan de activación de productos",auditoria_web:"Auditoría web y siguiente producto",ajuste_fino:"Ajuste fino de web y app",lote:"Tratamiento en lote",dormida:"Sin actividad"},eW={bloqueada_por_deuda:"la marca está bloqueada por deuda",sitio_caido:"su sitio de pedidos no carga o ya no apunta a Justo",sin_ventas_en_la_semana:"no registró ventas online en la semana",locales_sin_ventas:"hay locales que dejaron de vender",mercado:"cayó todo su rubro en el país",menos_ordenes:"tuvo menos órdenes",ticket_menor:"bajó el ticket promedio",menor_cobro_por_orden:"Justo cobró menos por cada orden (comisión, mezcla de delivery o medio de pago)",sin_causa_clara:"sin causa clara en los datos"},rq={ecommerce:"venta online",delivery:"delivery Justo",pdv:"PDV",pdvConnectedToJusto:"PDV conectado a la venta online",justoApp:"Justo App",loyalty:"programa de puntos",alianzas:"alianzas y campañas",email:"email marketing",deliveryEspecial:"delivery especial",inventario:"inventario",reservas:"reservas",reservasMarketplace:"reservas marketplace",appPropia:"app propia",adelantoDePagos:"adelanto de pagos",instagramOrderFood:"pedidos desde Instagram",commander:"Commander",commanderManejado:"Commander manejado",terminalDePago:"terminal de pago",sac:"SAC"},w0=["ecommerce","delivery","pdv","justoApp","loyalty","email","alianzas","reservas","appPropia","commander","adelantoDePagos","inventario","sac","terminalDePago","instagramOrderFood"],_0={localDishes:"comida local",burgersSandwiches:"hamburguesas y sándwiches",sushiAsian:"sushi y asiática",coffeeBakery:"café y pastelería",pizzaItalian:"pizza e italiana",dessertsIceCream:"postres y helados",chicken:"pollo",healthy:"saludable",store:"tienda",none:"sin rubro"},a$={adq:"adquisición",hib:"híbrido",lea:"lealtad"},B0={adq:"venta por visita",hib:"recompra a 90 días",lea:"frecuencia de compra"},O0={city:"en su ciudad",zone:"en su zona del país",country:"en su país",rubro:"en todos los países"},$5=[["conversion","Conversión (pedidos por visita)","pct"],["ventaPorVisita","Venta por visita","usd2"],["ticket","Ticket","usd0"],["recompra30","Recompra a 30 días","pct"],["recompra90","Recompra a 90 días","pct"],["frecuencia","Pedidos por comprador en 90 días","num"]],Hq={A:"A (top)",B:"B (grande)",C:"C (mediano)",D:"D (chico)",E:"E (micro)",F:"F (sin venta online)"},C5={caida:"CAÍDA",subida:"SUBIDA",uso:"PRODUCTO SIN USO",estable:"estable",sin_actividad:"sin actividad en el período",nueva:"recién activada, sin semanas para comparar"},q5={no_compra:"su menú online está vacío o no se pudo leer",conversion:"recibe visitas y convierte bajo sus pares",app:"vende sobre todo por su app propia"},Q5={1:"impide comprar",2:"traba antes de comprar",3:"lo primero que ve el cliente",4:"calidad del menú",5:"confianza",6:"app propia"},tq=[1,2,3,6],J5={"lo ajusta el equipo, con el OK de la marca":"Tofu, con el OK de la marca","necesita material o una decisión de la marca":"la marca","va a Soporte":"Soporte"};function a($){if(Array.isArray($))return $.length>0;if($&&typeof $==="object")return Object.keys($).length>0;return Boolean($)}function n$($){return a($)?$.map((C)=>u(rq,C,C)).join(", "):"ninguno"}function LC($){if(!$)return"";if($.startsWith("linea_"))return`cayó la línea de ${$.slice(6)} (no depende de las órdenes)`;return u(eW,$,$)}function j5($){let C=$.ndr||{},q=C.abierto,Q=C.cerrado;if(!a(q)&&!a(Q))return null;let J="";if(q&&a(q))J=q.comparable?`NDR de ${H$(q.mes)} según el tablero (proyección a mes completo): ${T0(q.pct)} · ${(q.movimiento||"").toLowerCase()} · `+`${B(q.impactoUSD,!0)} contra ${H$(nQ(q.mes))} (${B(q.nrAnteriorUSD)} → ${B(q.nrMesUSD)} de net revenue total).`:`NDR de ${H$(q.mes)}: sin base comparable en el tablero (no tuvo net revenue el mes anterior).`;if(Q&&a(Q)&&Q.comparable)J+=` ${n0(H$(Q.mes))} cerró en ${T0(Q.pct)}.`;return J.trim()}function F0($){return`${H$($.desde)} a ${H$($.hasta)} de ${$.hasta.slice(0,4)}`}function W5($){let C=$.segmento?.modo,q=$.potencial||{};if(!C)return"Potencial: el reporte no lo calcula para esta marca (todavía no tiene modo: necesita 30 clientes nuevos en la cohorte de recompra).";if((q.justoUSD||0)>0||(q.ventaUSD||0)>0)return`Potencial según el reporte: ${B(q.ventaUSD,!0)} de venta online al mes (${B(q.justoUSD,!0)} para Justo) si llegara a la mediana de sus pares en ${B0[C]}, que es la palanca de su modo. Es una estimación teórica, no un pronóstico.`;return`Potencial: ninguno por esta vía; ya está en la mediana de sus pares o sobre ella en ${B0[C]}.`}function G5($){let C=$.benchmark;if(!C||!a(C))return["BENCHMARK: la marca no aparece en el reporte de segmentos (sin actividad en sus últimos 3 meses cerrados)."];let{segmento:q,mensual:Q,tresMeses:J}=C,j=[`BENCHMARK (reporte de segmentos del intra; ${F0(C.periodo)}, solo venta online)`],G=`tier ${O(q.tier)}`+(q.tierHaceUnAno&&q.tierHaceUnAno!==q.tier?` (hace un año ${q.tierHaceUnAno})`:"");j.push(`Segmento: ${q.rubro||"sin rubro"} · ${G} · modo ${u(a$,q.modo,"sin asignar")} · ${q.ciudad||"s/d"}`),j.push(`Promedio mensual: ${B(Q.ventaUSD)} de venta online (${B(Q.ventaHaceUnAnoUSD)} hace un año), ${v(Q.ordenes||0)} pedidos, ${B(Q.margenUSD)} de margen para Justo. En los 3 meses: ${m(J.visitas||0)} visitas al sitio y ${m(J.compradores||0)} compradores.`);let W=$5.filter(([Y])=>a(C.metricas[Y])).map(([Y,H,F])=>[H,C.metricas[Y],F]);if(W.length){j.push(`${"".padEnd(34)}${"marca".padStart(9)} ${"cuartil bajo".padStart(12)} ${"mediana".padStart(9)} ${"cuartil alto".padStart(12)} posición entre sus pares`);for(let[Y,H,F]of W){let M=H.pares?`${H.posicion||"sin dato propio"} (${H.pares} marcas de su rubro ${u(O0,H.alcance,"")})`:"sin pares suficientes";j.push(`${Y.padEnd(34)}${n(H.valor,F).padStart(9)} ${n(H.p25,F).padStart(12)} ${n(H.p50,F).padStart(9)} ${n(H.p75,F).padStart(12)} ${M}`)}}j.push(W5(C));let Z=Object.entries(C.canales||{}).sort((Y,H)=>H[1]-Y[1]),X=[];if(Z.length)X.push(`Pedidos por canal: ${Z.filter(([,Y])=>Y>=0.005).map(([Y,H])=>`${Y} ${v(H*100)}%`).join(", ")}`);if(C.cancelacion!==null&&C.cancelacion!==void 0)X.push(`cancelación ${n(C.cancelacion,"pct")}`);if(X.length)j.push(`${X.join(" · ")}.`);return j}function _j($,C){let q=$.ejecucion?.canal,Q=q?C?.ejecucion?.canales?.[q]:void 0,J=Q&&"nombre"in Q?O(Q.nombre):q||"sin definir";return{channel:Q,name:J}}function wq($,C){return _j($,C).name}function NC($,C){let{channel:q,name:Q}=_j($,C);return Q+(q?.como?` (${q.como}; tareas: ${O(q.tareas)})`:"")}function y0($){return`tier ${u(Hq,$.tier,"sin dato")}, modo ${u(a$,$.modo,"sin etapa")}`}function v$($){let C=$.asignacion||$.cartera;return $.equipo==="KAM"?`${C} (KAM)`:C}function CC($){let C=($||"").slice(0,10).split("-"),q=(Q)=>/^\s*[+-]?\d+\s*$/.test(Q);if(C.length===3&&C.every(q)){let Q=Number(C[1])-1;if(Q>=-12&&Q<12)return`${Number(C[2])} ${E0.at(Q)}`}return $||"s/f"}function Z5($){let C=[...$];if(C.length<=260)return $;let q=C.slice(0,257).join(""),Q=q.lastIndexOf(" ");return`${Q===-1?q:q.slice(0,Q)}…`}function x0($,C=!1){let q=$.perfil;if(!q||!a(q))return[];let Q=[`Perfil de onboarding (bitácora del intra, lectura del ${CC(q.fecha)}): ${O(q.tipo)}`],J=(q.estrategia||"").trim();if(J)Q.push(`Estrategia de relacionamiento registrada: ${C?Z5(J):J}`);if(C)return Q;if(q.justificacion)Q.push(`Por qué ese perfil (uso interno, no va en mensajes a la marca): ${q.justificacion}`);if(q.asistencia)Q.push(`Asistencia a reuniones: ${q.asistencia}`);return Q}async function gC($){return(await d$("resumenes",{filter:{key:`TODAS|TODOS|${$}`},projection:{sitio:1}}))?.sitio||{}}function iq($,C){if(!$||!a($))return[];let q=[],Q=$.opciones||{},J=$.menu,j=C.porcentajes||{};if(Q.preciosOcultosHastaElegirLocal)q.push(["precios_ocultos",`no muestra precios hasta que el cliente elige local (lo tiene así el ${N(j.preciosOcultosHastaElegirLocal)} de las marcas)`]);if(Q.menuVersion&&Q.menuVersion!=="v2")q.push(["menu_version_anterior",`usa la versión anterior del menú (el ${N(j.menuVersionActual)} de las marcas ya está en la actual)`]);if(Q.pideTelefonoVerificado)q.push(["telefono_verificado",`pide verificar el teléfono antes de comprar (lo pide el ${N(j.pideTelefonoVerificado)} de las marcas)`]);if(!J||!a(J))q.push(["menu_no_leido","no se pudo leer su menú online"]);else{let{fotoPct:W,descripcionPct:Z}=C;if(J.productos&&W&&a(W)&&J.fotoPct!=null&&J.fotoPct<W.p25)q.push(["pocas_fotos",`${N(J.fotoPct)} de sus productos tiene foto (cuartil bajo de la cartera: ${N(W.p25)}; mediana ${N(W.p50)})`]);if(J.productos&&Z&&a(Z)&&J.descripcionPct!=null&&J.descripcionPct<Z.p25)q.push(["pocas_descripciones",`${N(J.descripcionPct)} de sus productos tiene descripción (cuartil bajo: ${N(Z.p25)}; mediana ${N(Z.p50)})`]);if(J.conFoto&&(J.fotoChica??0)/J.conFoto>=0.2)q.push(["fotos_chicas",`${O(J.fotoChica)} de sus ${J.conFoto} fotos miden menos de 600 px de ancho`]);if(J.productos===0)q.push(["menu_vacio","su menú online no tiene productos disponibles"])}let G=$.portada||{};if(a(G.componentes)&&!a(G.vitrina)&&!a(G.redirigeAlMenu))q.push(["portada_sin_vitrina",`la portada no muestra productos ni categorías (los muestra el ${N(j.vitrinaEnPortada)} de las marcas)`]);if($.app?.quitadaTemporalmente)q.push(["app_quitada","su app propia figura quitada temporalmente de las tiendas"]);return q}function eq($){if(!tq.includes($.nivel))return!1;let C=$.texto.match(/Hacen? (\d+)% de las unidades/);return!(C&&Number(C[1])<5)}function X5($,C=260){if($.length<=C)return $;let q=$.slice(0,C),Q=Math.max(q.lastIndexOf("; "),q.lastIndexOf(", "));if(Q>Math.floor(C/2))q=q.slice(0,Q);return`${q.replace(/[ ,;]+$/,"")} … (lista completa en auditoria-web).`}function kC($,C=3){let q=$.auditoria;if(!q||!a(q))return[];let Q=q.brecha||{},J=`SITIO DE PEDIDOS (auditado el ${O(q.leidoEl)}, porque ${O(u(q5,q.motivo,O(q.motivo)))})`;if(Q.valor!=null&&q.motivo!=="app"){let X=v(Q.pedidosMes??0);J+=`: convierte ${n(Q.valor,"pct")} de ${m(v(Q.visitasMes||0))} visitas al mes contra ${n(Q.p50,"pct")} de mediana de sus pares`+((Q.pedidosMes||0)>=1?`; le faltan ${m(X)} pedido${X===1?"":"s"} al mes, ${B(Q.ventaUSD)} de venta (estimación)`:"")}else if(q.motivo==="app")J+=`: ${N(q.appPct)} de sus pedidos digitales entra por la app, así que la conversión del sitio web no mide su vitrina`;let j=[`${J}.`];if(q.error)return[...j,`No se pudo auditar el lunes (${q.error.slice(0,80)}). Para verla: skill auditoria-web.`];let G=(q.puntos||[]).filter(eq),W=G.slice(0,C),Z=G.length-W.length;for(let X of W)j.push(`· [${Q5[X.nivel]} → ${u(J5,X.quien,X.quien)}] ${X5(X.texto)}`);if(!W.length)j.push("La revisión no encontró nada que impida comprar ni que esté a la vista del cliente. Lo que queda es la revisión visual (skill auditoria-web).");else if(Z>0)j.push(`Y ${Z} punto${Z===1?"":"s"} más en la auditoría completa (skill auditoria-web).`);return j}function Y5($,C){let q=$.sitio;if(!q||!a(q))return[];let Q=q.menu,J=[];if(Q?.productos){let G=C.fotoPct&&a(C.fotoPct)?` (mediana de la cartera: ${N(C.fotoPct.p50)} y ${N(C.descripcionPct?.p50)})`:"";J.push(`SITIO DE PEDIDOS (leído el lunes): menú online con ${Q.productos} productos en ${O(Q.categorias)} categorías; `+`${N(Q.fotoPct)} con foto y ${N(Q.descripcionPct)} con descripción`+G+(a(q.app)?"; tiene app propia":"")+".")}if(a($.auditoria))return[...J,...kC($)];let j=iq(q,C).map(([,G])=>G);if(j.length)J.push(`Fuera de lo habitual en su sitio: ${j.join("; ")}. Para auditarlo: skill auditoria-web.`);return J}function aq($){let C=$.base||{};if(!C.desde||!C.hasta)return"";return C.desde!==C.hasta?`semanas ${q$(C.desde)} a ${q$(C.hasta)}`:`semana ${q$(C.desde)}`}function H5($){let C=$.senal?.nivelPrevioUSD,q=$.actual?.nrOp;return C==null||q==null?null:oC(q,C)}function $1($){let C=$.senal,q=C.nivelPrevioUSD;if(q==null)return`NR operativo ${B($.actual.nrOp)}`;return`NR operativo ${B($.actual.nrOp)}; su nivel previo era ${B(q)} (${B(H5($),!0)}, ${L$(C.variacionPct)})`}function Vj($){return`Sitio ${$.url||""}: ${$.detalle} (revisado el ${"revisado"in $?O($.revisado):"s/d"}).`}function C1($,C=!1){let q=$.base||{},Q=$.senal.evidencia,J=[];if(!Q||!a(Q))return J;let j=Q.ordenes||{};if(j.base!=null&&(j.base||j.actual)){let Z=`Contra el promedio de las ${aq($)}: órdenes online ${z$(j.base,0)} → ${z$(j.actual??0,0)} por semana (${L$(Q.ordenesPct)})`;if("ticketPct"in Q)Z+=`, ticket ${L$(Q.ticketPct)}, cobro por orden ${L$(Q.cobroPorOrdenPct)}`;J.push(`${Z}.`)}if("efectoOrdenesUSD"in Q&&!C)J.push(`Esa diferencia (${B(Q.diferenciaUSD,!0)} contra ${B(q.nrOp)}) se reparte en: órdenes ${B(Q.efectoOrdenesUSD,!0)}, ticket ${B(Q.efectoTicketUSD,!0)}, cobro por orden ${B(Q.efectoCobroPorOrdenUSD,!0)}.`);let G=(Q.lineas||[]).slice(0,4).map((Z)=>`${Z.linea} ${B(Z.variacionUSD,!0)}`);if(G.length)J.push(`Por línea de cobro: ${G.join(", ")}.`);let W=Q.localesConVentas||{};if(W.total&&(W.base||W.actual)&&(W.total>1||W.actual===0)){let Z=z$(W.base??0,1).replace(".",",").replaceAll(",0","");J.push(`Locales con ventas online: ${Z} en la referencia, ${O(W.actual)} esta semana, de ${W.total} en total.`)}if(Q.sitio&&a(Q.sitio))J.push(Vj(Q.sitio));return J}function q1($){let C=$.senal,q=$.pares||{},Q=$.actual,J=$.base||{},j=[];if(q.medianaPct!=null)j.push(`Pares esta semana (${O(q.marcas)} marcas, mismo ${O(q.referencia)}): mediana ${L$(q.medianaPct)} contra sus 4 semanas previas; la marca ${L$(q.marcaPct)}.`);if(a(C.productosSinUso))j.push(`Usó las 4 semanas previas y esta no: ${n$(C.productosSinUso)}.`);if(a(C.productosNuevos))j.push(`Primer uso esta semana: ${n$(C.productosNuevos)}.`);if((Q.nrPun||0)>=1||(J.nrPun||0)>=1)j.push(`Marketing (cobros por campaña, fuera de la señal): ${B(Q.nrPun)} esta semana; ${B(J.nrPun)} por semana en la referencia.`);if($.bloqueadaPorDeuda)j.push("La marca figura bloqueada o desactivada por deuda.");let G=j5($);if(G)j.push(G);return j}function Q1($){let C=$.sinVentaOnline;if(!C||!a(C))return null;let q=C.pedidosSemanaAntes||0,Q=C.nrOpSemanaAntes||0,J=`Dejó de vender online: ${C.semanas} semanas sin pedidos online, desde la semana ${q$(C.desde)}; antes vendía `+(q<1?"menos de 1 pedido por semana":`unos ${v(q)} pedidos por semana`)+` (${Q>0&&Q<0.5?"menos de US$1":B(Q)} de net revenue operativo por semana).`;if(C.sitio&&a(C.sitio))J+=` ${Vj(C.sitio)}`;return J}async function w5($,C){try{let q=await Iq({filter:$,limit:10,onlyActiveWebsites:!0}),Q=C$($);return(q.items??[]).filter((J)=>!C.has(J._id)&&C$(J.name).startsWith(Q)).slice(0,5)}catch{return null}}async function SC($){let C=await d$("fichas",{filter:{websiteId:$}});if(C)return[C];let q=await M$("fichas",{filter:{},projection:{websiteId:1,marca:1,pais:1,cartera:1,url:1,_id:0},limit:5000}),Q=C$($),J=q.filter((Z)=>C$(Z.marca)===Q),j=J.length?J:q.filter((Z)=>Q&&(C$(Z.marca).includes(Q)||C$(Z.url).replaceAll(" ","").includes(Q.replaceAll(" ",""))));if(j.length!==1)return j;let[G,W]=await Promise.all([d$("fichas",{filter:{websiteId:j[0].websiteId}}),w5($,new Set(q.map((Z)=>Z.websiteId)))]);if(!G)return[];return G._homonimas=W,[G]}function F5($,C,q,Q,J){let j=$.senal,G=$.base||{},W=[];if(W.push(`MARCA: ${$.marca} · ${$.pais} · estado ${$.estado} · plan ${$.plan||"s/d"}`),W.push(`websiteId ${$.websiteId} · ${$.url||"sin dominio"}`),W.push(`ASIGNACIÓN (planilla de asignación del intra): ${v$($)} · canal de ejecución: ${NC($,Q)}`),W.push(`SEGMENTO (reporte de segmentos del intra; describe a la marca, no cambia quién la trabaja): rubro ${u(_0,$.rubro,$.rubro||"s/d")}, ${y0($)}`),W.push(...x0($)),$._homonimas===null)W.push("OJO: no pude revisar si hay otras marcas con este nombre fuera de las carteras; confirma con la persona que es la marca que busca.");if($._homonimas?.length){let R=$._homonimas.map((E)=>`${E.name} (${O(E.countryCode)}, ${O(E.baseURL)})`).join("; ");W.push(`OJO: con ese nombre también existen marcas fuera de las carteras de KAM y Partner Experience: ${R}. Esta ficha es de ${$.marca} de ${$.pais}; confirma con la persona que es la marca que busca.`)}W.push(S$(Q)),W.push(`
|
|
1427
|
+
ÁRBOL`);let{fase:Z,peso:X}=$,Y=u(oq,Z.codigo,Z.codigo);if(Z.dias!=null){let R=Z.dias<730?`${Z.dias} días`:`${z$(Z.dias/365,1)} años`.replace(".",","),E=Z.fuente==="fecha de activación"?"":`; sin fecha de activación, se usó el ${O(Z.fuente)}`;W.push(`1. Fase: ${Y} (${R} activa, desde ${O(Z.desde)}${E})`)}else W.push(`1. Fase: ${Y}`);W.push(`2. Peso: ${X.codigo==="360"?"revisión 360":"lote"} (net revenue total por semana: ${B(X.nr4USD)} en las 4 semanas previas y ${B(X.nr8USD)} en las 8 previas; entra a revisión con US$25 en cualquiera de las dos)`),W.push(`3. Señal de la semana: ${C5[j.tipo]} · ${$1($)}`);let H=Q1($);if(H)W.push(` ${H} Por eso la ruta es rescate, aunque su venta fuera chica.`);if(j.tipo==="caida"){if((j.racha??1)>1)W.push(` Lleva ${j.racha} semanas seguidas en caída, desde la semana ${q$(j.inicio??"")}. El nivel previo es el de las ${aq($)}, antes de que empezara a caer.`);if(j.causa)W.push(` Causa principal según los datos: ${LC(j.causa)}.`)}if(j.nivelPrevioUSD!=null&&G.nrOp&&Math.abs(G.nrOp-j.nivelPrevioUSD)>Math.max(2,0.05*G.nrOp)&&(j.tipo==="caida"||j.tipo==="subida"))W.push(` El nivel previo (${B(j.nivelPrevioUSD)}) no es el promedio de las ${aq($)} (${B(G.nrOp)}): una semana fuera de lo normal lo distorsionaba y se usó su nivel típico de las 8 semanas previas.`);for(let R of[...C1($),...q1($)])W.push(` ${R}`);W.push(`4. Productos con uso en las últimas 4 semanas (${$.productos.n}): ${n$($.productos.activos)}`),W.push(` Del catálogo, sin uso: ${n$(w0.filter((R)=>!$.productos.activos.includes(R)))}`);let F=$.ruta;W.push(`
|
|
1428
|
+
RUTA: ${u(s$,F.codigo,F.codigo)} — ${F.motivo}.`+(F.skill?` Skill que la trabaja: ${F.skill}.`:"")+` Posición ${F.orden} en esa ruta dentro de ${$.cartera} ${$.pais}.`),W.push(""),W.push(...G5($)),W.push(...Y5($,J));let M=($.semanas||[]).slice(-13);W.push(`
|
|
1429
|
+
ÚLTIMAS ${M.length} SEMANAS (USD; la última fila es la semana analizada)`),W.push("semana NR operativo marketing recurrente órdenes venta online locales con venta");for(let R of M)W.push(`${q$(R.s).padStart(6)} ${m(v(R.nrOp)).padStart(12)} ${m(v(R.nrPun||0)).padStart(9)} ${m(v(R.nrRec)).padStart(10)} ${O(R.ord).padStart(7)} ${m(v(R.gmv)).padStart(12)} ${O(R.locV).padStart(17)}`);let U=C.filter((R)=>R.semana!==$.semana);if(U.length){W.push(`
|
|
1430
|
+
SEMANAS ANTERIORES EN EL RADAR`);for(let R of U.slice(0,8))W.push(`semana ${q$(R.semana)}: ${u(s$,R.ruta,R.ruta)}`+(R.causa?` · ${LC(R.causa)}`:"")+(R.enJuegoUSD?` · ${B(R.enJuegoUSD)} en juego`:""))}if(q.length){W.push(`
|
|
1431
|
+
DECISIONES REGISTRADAS`);for(let R of q.slice(0,6)){let E=rC(R.fecha);W.push(`semana ${q$(R.semana)}: ${R.tipo==="auditoria"?"auditoría web · ":""}${R.decision} — ${R.nota||"sin nota"} (${R.por||"s/d"}, ${E?.getUTCDate()} ${E0[E?.getUTCMonth()??0]})`)}}return W.join(`
|
|
1432
|
+
`)}async function mj($,C){let q=await SC($);if(!q.length)return[`No encontré "${$}" entre las marcas asignadas a un KAM o a Partner Experience (TOP, Longtail, Lanzamiento) en la planilla del intra, en estados active/new/preChurned.`,'Puede ser una marca de Última Milla, de inDrive, sin asignación, churned o demo. Para ubicarla: npx @getjusto/team-cli admin search "<texto>"'].join(`
|
|
1433
|
+
`);if(q.length>1)return[`Hay ${q.length} marcas que calzan con "${$}". Pregunta cuál es y vuelve a correr con el websiteId:`,...q.slice(0,15).map((Z)=>` ${Z.websiteId} ${O(Z.marca)} · ${O(Z.pais)} · ${O(Z.cartera)} · ${Z.url||""}`)].join(`
|
|
1434
|
+
`);let Q=q[0],[J,j,G]=await Promise.all([M$("historial",{filter:{websiteId:Q.websiteId},sort:{semana:-1},limit:12}),M$("acciones",{filter:{websiteId:Q.websiteId},sort:{semana:-1},limit:6}),C?null:V$()]);if(C||!G){let{_id:Z,...X}=Q;return JSON.stringify({ficha:X,historial:J,acciones:j},null,1)}let W=a(Q.sitio)?await gC(G.semana):{};return F5(Q,J,j,G,W)}var Ij=["CL","CO","PE","MX","EC","TODOS"],P5={web:"sitio web",app:"app propia",justoApp:"Justo App",commander:"Commander (los carga el local)",embedded:"apps aliadas",pide:"Pide",orderingAPI:"API de pedidos",messenger:"Messenger","order-food":"Instagram",phone:"teléfono",tabs:"PDV"},M5=["delivery","email","loyalty","alianzas","justoApp","appPropia","reservas","pdv","commander","terminalDePago","inventario","adelantoDePagos","sac","instagramOrderFood"],K5={abandonedCart:"carro abandonado",secondPurchaseThanks:"gracias por la segunda compra",backInStock:"producto de vuelta",registeredUser:"bienvenida al registrarse",birthday:"cumpleaños",inactiveUser:"cliente inactivo",firstPurchaseThanks:"gracias por la primera compra",orderReview:"pedir reseña (de servicio)",blank:"en blanco",product:"recomendación de producto"},Tj={adq:"ventaPorVisita",hib:"recompra90",lea:"frecuencia"},Lj={adq:"usd2",hib:"pct",lea:"num"},A5=86400000,Dj={productsByMonth:"productos por mes",segmentMonths:"recompra y frecuencia por mes",charges:"net revenue por producto",channelOrders:"pedidos por canal",emailCampaigns:"email marketing",deliveryTypes:"tipos de entrega del sitio",customApplication:"app propia",stores:"locales",instagram:"Instagram",menu:"lo que vende su menú"};function P0($,C=1){return z$($,C).replace(".",",")}function Nj($){return($||"").replace(/\s+/g," ").replace(/^[ .]+|[ .]+$/g,"")}function qC($){return u(rq,$,$)}function m$($,C){return[...$].sort((q,Q)=>{let J=C(q),j=C(Q);for(let G=0;G<J.length;G++){if(J[G]<j[G])return-1;if(J[G]>j[G])return 1}return 0})}function R$($){let C=0;for(let q of $)C+=q;return C}function J1($,C){return`${$>=C?"+":"−"}${Math.abs(v(100*($-C)/C))}%`}function U5($){let C=($||"").toLowerCase();if(["platformfee","paymentfee","servefee"].includes(C))return"ecommerce";if(C==="marketing")return"email";if(["marketingservices","externalmarketing"].includes(C))return"servicios de marketing";let q=[[/reservation/,"reservas"],[/tabs/,"pdv"],[/commander/,"commander"],[/presentpayment/,"terminalDePago"],[/advancepayout|loan|lending/,"adelantoDePagos"],[/messenger|clientsupport/,"sac"],[/ownapp|appextra/,"appPropia"],[/indrive/,"inDrive"],[/delivery/,"delivery"]];for(let[Q,J]of q)if(Q.test(C))return J;if(/subscription|setupfee|monthly|plan/.test(C))return"suscripción del plan";return"otros"}function R5($,C){let q=$.tier,Q=C.filter((W)=>W.websiteId!==$.websiteId&&W.tier===q&&W.pais===$.pais),J=`tier ${O(q)} de ${$.pais}`;if(Q.length<15)Q=C.filter((W)=>W.websiteId!==$.websiteId&&W.tier===q),J=`tier ${O(q)} de todos los países`;let j={};for(let W of w0){let Z=Q.filter((X)=>(X.productos?.activos||[]).includes(W)).length;j[W]=Q.length?Z/Q.length:null}let G=Q.map((W)=>W.productos?.n??0).sort((W,Z)=>W-Z);return{n:Q.length,alcance:J,uso:j,productosMediana:Q.length?G[Math.floor(Q.length/2)]:null}}function gj($){let C=($.semanas||[]).map((j)=>j.ord||0),q=0;for(let j of[...C].reverse()){if(j)break;q++}let Q=q?C.slice(0,-q):C,J=R$(Q)>=10&&Q.filter((j)=>j).length>=4;return q>=2&&J?q:0}function z5($){let C=($.semanas||[]).map((J)=>J.ord||0);if(C.length<16)return null;let q=R$(C.slice(-8)),Q=R$(C.slice(-16,-8));return Q>=40?(q-Q)/Q:null}function _5($){let C=new Map;for(let q of $){let Q=new Set(q.productos?.activos||[]);for(let J of[`${O(q.tier)}|${q.pais}`,`${O(q.tier)}|`]){let j=C.get(J);if(!j)j={n:0,uso:Object.fromEntries(w0.map((G)=>[G,0]))},C.set(J,j);j.n++;for(let G of Q)if(G in j.uso)j.uso[G]++}}return C}function Ej($,C){let q=new Set($.productos?.activos||[]),Q=`${O($.tier)}|${$.pais}`,J=`tier ${O($.tier)} de ${$.pais}`;if((C.get(Q)?.n??0)-1<15)Q=`${O($.tier)}|`,J=`tier ${O($.tier)} de todos los países`;let j=C.get(Q)??{n:1,uso:{}},G=j.n-1,W={};for(let X of w0)W[X]=G>0?((j.uso[X]??0)-(q.has(X)?1:0))/G:null;let Z=m$(M5.filter((X)=>!q.has(X)&&(W[X]||0)>=0.25).map((X)=>[X,W[X]]),([,X])=>[-X]);return[{n:G,alcance:J,uso:W},Z]}function V5($,C){let q=$.ejecucion?.canal,Q=q?C.ejecucion?.canales?.[q]:void 0;return Q&&"nombre"in Q?O(Q.nombre):q||"sin definir"}var m5={_id:0,websiteId:1,marca:1,pais:1,cartera:1,equipo:1,asignacion:1,tier:1,modo:1,ruta:1,peso:1,productos:1,"senal.tipo":1,"senal.enJuegoUSD":1,"benchmark.potencial":1,"benchmark.segmento":1,"benchmark.metricas.recompra90":1,"benchmark.metricas.frecuencia":1,"benchmark.metricas.conversion":1,"benchmark.metricas.ventaPorVisita":1,"benchmark.tresMeses":1,ejecucion:1,"semanas.ord":1,estado:1,"benchmark.mensual":1};function kj($){let C=($.pais||"TODOS").toUpperCase();if(!Ij.includes(C))throw Error(`--pais debe ser uno de: ${Ij.join(", ")}.`);let q=$.top?Number($.top):10;if(!Number.isInteger(q)||q<1)throw Error("--top debe ser un entero mayor que 0.");return{cartera:$.cartera,pais:C,top:q,json:$.json==="true"}}async function Sj($){let C=await V$(),{portfolio:q,origin:Q}=await $C($.cartera,C),J=await M$("fichas",{filter:{},projection:m5,limit:5000}),j=c$[q],G=j?J.filter((K)=>!j.team||K.equipo===j.team):J.filter((K)=>K.cartera===q);if($.pais!=="TODOS")G=G.filter((K)=>K.pais===$.pais);let W=G.length,Z=_5(J),X=(K)=>[-(K.peso.nrSemanalUSD||0),K.marca||""],Y=(K)=>(K.productos?.activos||[]).includes("ecommerce"),H=(K)=>{let S=K.benchmark?.mensual||{},s=S.ventaUSD,D=S.ventaHaceUnAnoUSD;return s!=null&&D&&D>=300?s/D-1:null},F=(K)=>{let S=K.benchmark?.metricas?.conversion||{};return(K.benchmark?.tresMeses?.visitas||0)>=300&&S.valor!=null&&Boolean(S.p50)&&(S.posicion==="cuartil inferior"||S.valor<0.6*S.p50)},M=(K)=>{let S=H(K);return K._tend!=null&&K._tend<=-0.15||S!==null&&S<=-0.3};for(let K of G)K._sinVenta=gj(K),K._tend=z5(K);let U=m$(G.filter((K)=>(K._sinVenta??0)>=3&&!["rescate","diagnostico_caida","dormida"].includes(K.ruta.codigo)&&K.estado!=="preChurned"&&K.peso.codigo==="360"),X),R=new Set(U.map((K)=>K.websiteId));G=G.filter((K)=>!R.has(K.websiteId));let E=m$(G.filter((K)=>!Y(K)&&["plan_activacion","aprovechar_impulso","lanzamiento"].includes(K.ruta.codigo)&&K.peso.codigo==="360"),X),V=new Set(E.map((K)=>K.websiteId)),I=G.filter((K)=>K.ruta.codigo==="aprovechar_impulso"&&!V.has(K.websiteId)),A=m$(I.filter((K)=>!M(K)),(K)=>[-(K.senal.enJuegoUSD||0),K.marca||""]),x=m$(I.filter((K)=>M(K)),X),r=m$(G.filter((K)=>K.ruta.codigo==="plan_activacion"&&!V.has(K.websiteId)),X),W$=new Set([...[...A,...x,...r].map((K)=>K.websiteId),...V]),o=m$(G.filter((K)=>!["rescate","diagnostico_caida","lote","dormida","recuperar_uso"].includes(K.ruta.codigo)&&["hib","lea"].includes(K.benchmark?.segmento?.modo||"")&&(K.benchmark?.potencial?.justoUSD||0)>0&&!W$.has(K.websiteId)),(K)=>[-K.benchmark?.potencial?.justoUSD,K.marca||""]);if($.json){let K=(S)=>S.slice(0,$.top).map((s)=>({...s,faltan:Ej(s,Z)[1]}));return JSON.stringify({semana:C.semana,cartera:q,origenDeLaCartera:Q,marcas:W,dejaronDeVender:K(U),sinVentaOnline:K(E),impulso:K(A),subieronPeroVienenCayendo:K(x),pocosProductos:K(r),potencial:K(o)},null,1)}let z=[];if(z.push(`COLA DE ACTIVACIÓN DE PRODUCTOS · cartera ${S0(q,C)} · país ${$.pais}`),Q)z.push(Q);z.push(S$(C)),z.push(`${m(W)} marcas en la cartera. La cola solo lee lo que dejó la carga del lunes; los clientes, el correo, los puntos y el menú se ven al correr \`posventa activacion marca\`.`),z.push('Marcas de su tamaño = mismo tier y mismo país (si son menos de 15, mismo tier en todos los países), sin contar a la marca. "Usa" = con uso en las últimas 4 semanas: '+"un producto que la marca usa a ratos puede aparecer como no usado. El producto de cada línea es tentativo: se confirma con `posventa activacion marca`."),z.push(`Evidencia de qué pasa al activar cada producto: medida el ${PC.medido} (references/criterios.md, sección 3).`);let d=(K,S)=>{let[s,D]=Ej(S,Z),c=S.benchmark,_=c?.segmento||{},k=c?.metricas||{},T=S.productos.n,l=[`${K}. ${S.marca} [${S.websiteId}] · ${S.pais} · ${v$(S)} · canal ${V5(S,C).toLowerCase()} · `+`${B(S.peso.nrSemanalUSD)} de net revenue por semana · usa ${T} producto${T===1?"":"s"}: ${n$(S.productos.activos)}`],i=_.modo,e=i?k[Tj[i]]||{}:{};if(i&&e.valor!=null){let $$=Lj[i],y$=c?.potencial||{};l.push(`Etapa: ${a$[i]}; su palanca es ${B0[i]}: ${n(e.valor,$$)} contra ${n(e.p50,$$)} de mediana de sus pares de rubro`+(e.posicion?` (${e.posicion})`:"")+((y$.justoUSD||0)>0?`. Potencial del reporte de segmentos: ${B(y$.ventaUSD,!0)} de venta al mes, ${B(y$.justoUSD,!0)} para Justo.`:"."))}if(F(S)){let $$=k.conversion||{};l.push(`Su sitio convierte ${n($$.valor,"pct")} contra ${n($$.p50,"pct")} de sus pares de rubro (${O($$.posicion)}): lo primero es la auditoría web, no un producto nuevo.`)}let F$=[];if(S._tend!=null&&Math.abs(S._tend)>=0.15)F$.push(`pedidos online de las últimas 8 semanas ${S._tend>0?"+":"−"}${Math.abs(v(100*S._tend))}% contra las 8 anteriores`);let K$=H(S);if(K$!==null&&Math.abs(K$)>=0.3)F$.push(`venta online de agosto a octubre ${K$>0?"+":"−"}${Math.abs(v(100*K$))}% contra hace un año`);if(F$.length)l.push(`Tendencia: ${F$.join("; ")}.`);if(!Y(S))l.push("No vende online: usa Justo solo en el local. El producto a conversar es la venta online.");else if(D.length)l.push(`Lo usan las marcas de su tamaño (${s.n}, ${s.alcance}) y ella no: `+D.slice(0,5).map(([$$,y$])=>`${qC($$)} ${N(y$)}`).join(", ")+".");else l.push(`No hay producto que use 1 de cada 4 marcas de su tamaño (${s.n}, ${s.alcance}) y ella no.`);return l[0]+l.slice(1).map(($$)=>`
|
|
1435
|
+
${$$}`).join("")},p=(K,S)=>{z.push(`
|
|
1436
|
+
${K} — ${S.length} marca${S.length===1?"":"s"}`+(S.length>$.top?`; se detallan ${$.top}`:""));for(let[s,D]of S.slice(0,$.top).entries())z.push(d(s+1,D));if(S.length>$.top)z.push(` Fuera del detalle (${S.length-$.top}; para verlas usa --top ${S.length}): `+S.slice($.top,$.top+40).map((s)=>s.marca).join("; "))};if(U.length){if(z.push(`
|
|
1437
|
+
ANTES QUE TODO: DEJARON DE VENDER ONLINE — ${U.length} marca${U.length===1?"":"s"} con 3 semanas o más sin pedidos online, que antes vendían `+"y que el radar no tiene en caída ni en rescate. No es momento de ofrecerles un producto: hay que saber por qué dejaron de vender."),U.slice(0,$.top).forEach((K,S)=>{z.push(`${S+1}. ${K.marca} [${K.websiteId}] · ${K.pais} · ${v$(K)} · ${K._sinVenta} semanas sin pedidos online · `+`${B(K.peso.nrSemanalUSD)} de net revenue por semana (incluye su plan)`)}),U.length>$.top)z.push(` Fuera del detalle (${U.length-$.top}): `+U.slice($.top,$.top+40).map((K)=>K.marca).join("; "))}if(p("PRIMERO: CON IMPULSO (subieron sobre su nivel previo esta semana y no vienen cayendo: buen momento para proponer)",A),x.length){z.push(`
|
|
1438
|
+
SUBIERON ESTA SEMANA PERO VIENEN CAYENDO — ${x.length} marca${x.length===1?"":"s"}: sus pedidos online de las últimas 8 semanas están 15% o más bajo las 8 anteriores, `+"o su venta online está 30% o más bajo la de hace un año. Una semana buena no es impulso: mira primero por qué vienen cayendo.");for(let[K,S]of x.slice(0,$.top).entries())z.push(d(K+1,S))}if(p("POCOS PRODUCTOS (estables, venden online, usan 2 productos o menos y dejan US$25 o más por semana)",r),E.length)p("NO VENDEN ONLINE (usan Justo solo en el local; el producto a conversar es la venta online)",E);return p("MAYOR POTENCIAL EN RECOMPRA O FRECUENCIA (según el reporte de segmentos; las de etapa adquisición van a auditoría web)",o),z.push(`
|
|
1439
|
+
Las marcas en caída, en rescate o con un producto que dejó de usar se atienden primero con radar-semanal; las de tratamiento en lote, por canal masivo.`),z.join(`
|
|
1440
|
+
`)}async function I5($,C){return(await h({service:"data",timeoutMs:55000,query:`query ($websiteId: String, $countryCode: PosventaCountry) {
|
|
1441
|
+
posventaBrandActivation(websiteId: $websiteId, countryCode: $countryCode) {
|
|
1442
|
+
months
|
|
1443
|
+
missingParts
|
|
1444
|
+
productsByMonth { month products }
|
|
1445
|
+
segmentMonths { month r90Cohort r90Returned buyers90 orders90 newCustomers30 gmvUSD }
|
|
1446
|
+
charges { month chargeType amountUSD }
|
|
1447
|
+
channelOrders { month source orders }
|
|
1448
|
+
customers { registered buyers repeatBuyers active90 dormant dormantWithEmail withEmail withAppNotifications }
|
|
1449
|
+
emailCampaigns { createdAt subject sendType automatedEmailType isMarketing sent opened orders }
|
|
1450
|
+
loyaltyPoints { movementType transactions customers }
|
|
1451
|
+
deliveryTypes
|
|
1452
|
+
customApplication { iosURL androidURL downloads downloadsSyncedAt }
|
|
1453
|
+
stores { total withTable withPickup withDelivery }
|
|
1454
|
+
instagram
|
|
1455
|
+
menu { from currentFrom to products { week productId productName units sales } }
|
|
1456
|
+
}
|
|
1457
|
+
}`,variables:{websiteId:$,countryCode:C}})).posventaBrandActivation}function D5($,C){let q=$.emailCampaigns||[],Q=q.filter((W)=>W.sendType==="date"&&W.isMarketing!==!1),J=Q.filter((W)=>(W.createdAt||"")>=C&&W.sent>0),j=[...new Set(q.filter((W)=>W.sendType==="automation"&&W.isMarketing&&W.sent>0).map((W)=>W.automatedEmailType).filter((W)=>Boolean(W)))].sort(),G=Q.filter((W)=>W.sent>0).map((W)=>W.createdAt).filter((W)=>Boolean(W));return{campanas180:J.length,enviados180:R$(J.map((W)=>W.sent)),abiertos180:R$(J.map((W)=>W.opened)),pedidos180:R$(J.map((W)=>W.orders)),automatizaciones:j,ultimaCampana:G.length?G.reduce((W,Z)=>Z>W?Z:W):null,ultimas:J.slice(0,6).map((W)=>({fecha:(W.createdAt||"").slice(0,10),asunto:Nj(W.subject),enviados:W.sent,abiertos:W.opened,pedidos:W.orders})),leido:!$.missingParts.includes("emailCampaigns")}}function E5($){let C=new Map,q=new Map;for(let Y of $.products){let H=Y.week<4?C:q,F=C$(Y.productName)||O(Y.productId),M=H.get(F);if(!M)M={nombre:Nj(Y.productName)||O(Y.productId),u:0,v:0},H.set(F,M);M.u+=Y.units||0,M.v+=Y.sales||0}let Q=(Y,H)=>Y.get(H)?.u??0,J=R$([...q.values()].map((Y)=>Y.u)),j=R$([...C.values()].map((Y)=>Y.u)),G=m$([...q.values()],(Y)=>[-Y.u,-Y.v,C$(Y.nombre)]).slice(0,10).map((Y)=>({...Y,antes:Q(C,C$(Y.nombre)),share:J?Y.u/J:null})),W=m$([...q.entries()].filter(([Y,H])=>H.u>=10&&H.u>=1.3*Math.max(Q(C,Y),1)&&Q(C,Y)>=1).map(([Y,H])=>({...H,antes:Q(C,Y)})),(Y)=>[-(Y.u-Y.antes),C$(Y.nombre)]).slice(0,8),Z=m$([...q.entries()].filter(([Y,H])=>H.u>=5&&!Q(C,Y)).map(([,Y])=>Y),(Y)=>[-Y.u,C$(Y.nombre)]).slice(0,6),X=m$([...C.entries()].filter(([Y,H])=>H.u>=10&&Q(q,Y)<=0.6*H.u).map(([Y,H])=>({...H,ahora:Q(q,Y)})),(Y)=>[-(Y.u-Y.ahora),C$(Y.nombre)]).slice(0,6);return{top:G,alza:W,nuevos:Z,baja:X,unidades:J,unidadesAntes:j,desde:$.currentFrom.slice(0,10),hasta:$.to.slice(0,10)}}function T5($,C,q){let Q=C.months,J=Q.slice(-6),j=new Map((C.productsByMonth||[]).map((I)=>[I.month,new Set(I.products)])),G={};for(let I of w0)G[I]=Q.map((A)=>j.get(A)?.has(I)??!1);let W=new Map;for(let I of C.charges||[]){if(!J.includes(I.month))continue;let A=U5(I.chargeType);if(!W.has(A))W.set(A,new Map(J.map((r)=>[r,0])));let x=W.get(A);x.set(I.month,(x.get(I.month)??0)+(I.amountUSD||0))}let Z=new Map;for(let I of C.channelOrders||[]){if(!J.includes(I.month))continue;let A=I.source||"sin dato";if(!Z.has(A))Z.set(A,new Map(J.map((r)=>[r,0])));let x=Z.get(A);x.set(I.month,(x.get(I.month)??0)+I.orders)}let X=new Map((C.segmentMonths||[]).map((I)=>[I.month,I])),Y=Q.map((I)=>{let A=X.get(I);return{m:I,r90:(A?.r90Cohort||0)>=30?A?.r90Returned/A?.r90Cohort:null,frec:(A?.buyers90||0)>=30?A?.orders90/A?.buyers90:null,compradores90:A?.buyers90,nuevos30:A?.newCustomers30,gmv:A?.gmvUSD}}),H=C.customers,F=H?{registrados:H.registered,compradores:H.buyers,recurrentes:H.repeatBuyers,activos90:H.active90,dormidos:H.dormant,dormidosCorreo:H.dormantWithEmail,correo:H.withEmail,push:H.withAppNotifications}:null,M=Math.floor(Date.now()/3600000)*60*60*1000,U=new Date(M-180*A5).toISOString(),R=C.loyaltyPoints?Object.fromEntries(C.loyaltyPoints.map((I)=>[I.movementType||"sin tipo",{n:I.transactions,usuarios:I.customers}])):null,E=C.customApplication,V=C.stores;return{sinVentaSemanas:gj($),meses:Q,usoMes:G,activos:[...new Set($.productos?.activos||[])].sort(),lineas:W,canales:Z,m6:J,evolucion:Y,clientes:F,correo:D5(C,U),puntos:R,menu:C.menu?E5(C.menu):null,pares:R5($,q),web:{tipos:C.deliveryTypes||[]},app:E?{ios:E.iosURL,android:E.androidURL,descargas:E.downloads||null,descargasLeidas:(E.downloadsSyncedAt||"").slice(0,10)||null}:null,locales:V?{total:V.total,conMesa:V.withTable,conRetiro:V.withPickup,conDelivery:V.withDelivery}:null,instagram:C.instagram||null,faltan:C.missingParts}}function L5($,C){let q=$.benchmark,Q=q?.metricas||{},J=q?.segmento?.modo,j=C.pares,G=new Set([...C.activos,...w0.filter((K)=>C.usoMes[K].slice(-6).some(Boolean))]),W=C.clientes,Z=C.correo,X=C.puntos||{},Y=(K)=>Q[K]?.posicion||"",H=q?.mensual?.ordenes||0,F=q?.mensual?.ticketUSD,{requisitos:M,efecto:U,correo:R,puntos:E}=PC,V=[],I=(K,S,s,D,c=null,_)=>{let k=M[K],T=k?.pedidosMes!==void 0?H>=k.pedidosMes:null,l=D;if(T===!1&&l<4)l=4;if(l===3&&(j.uso[K]||0)<0.1&&K!=="email")l=4;V.push({producto:K,estado:S,porque:s,prioridad:l,pares:j.uso[K]??null,requisito:k?.texto,cumpleRequisito:T,evidencia:_??U[K],dimension:c})};if(!G.has("ecommerce"))if(C.sinVentaSemanas)I("ecommerce","dejó de vender online",`lleva ${C.sinVentaSemanas} semanas sin pedidos online y antes vendía: es un rescate, no una activación`,0);else I("ecommerce","no vende online","usa Justo solo en el local; sin venta online no aplica ningún producto digital",0);let A=W?.activos90||0,x=null,r=0;if(A&&R.pedidosPor100Activos){r=A*R.pedidosPor100Activos/100;let K=A*R.pedidosPor100ActivosP25/100,S=A*R.pedidosPor100ActivosP75/100;x=`una campaña a su base traería del orden de ${m(v(r))} pedidos atribuidos (entre ${m(v(K))} y ${m(v(S))}), `+`según la respuesta de la cartera: ${P0(R.pedidosPor100Activos)} pedidos por cada 100 clientes activos`+(F?`; unos ${B(r*F)} de venta atribuida por campaña (no necesariamente adicional)`:"")}let W$=X.accumulation?.usuarios||0,o=W$?(X.redemption?.usuarios||0)/W$:null;if(!G.has("loyalty")&&!W$){let K=Q.frecuencia||{};if(K.valor!=null&&Boolean(K.p50)&&(Y("frecuencia")==="cuartil inferior"||K.valor<=0.95*K.p50))I("loyalty","no lo usa",`sus clientes compran menos seguido que sus pares de rubro (${n(K.valor,"num")} contra ${n(K.p50,"num")} `+"pedidos por comprador en 90 días), y es lo que se asocia con los puntos",1);else if(J==="hib"||J==="lea")I("loyalty","no lo usa","su etapa depende de que los clientes vuelvan y compren seguido; los puntos se asocian con algo más de frecuencia, no con más recompra",1);else if(["sobre la mediana","cuartil superior","bajo la mediana"].includes(Y("frecuencia")))I("loyalty","no lo usa",`sus clientes compran casi tan seguido como sus pares de rubro (${n(K.valor,"num")} contra ${n(K.p50,"num")}): los puntos no apuntan a una brecha clara`,J==="hib"||J==="lea"?2:3);else I("loyalty","no lo usa","trabaja sobre los clientes que ya compraron",2)}else if(o!==null&&W$>=30&&E.canjeP25!=null&&o<E.canjeP25)I("loyalty","lo usa poco",`${m(X.redemption?.usuarios||0)} de los ${m(W$)} clientes que acumularon puntos en 90 días los canjearon `+`(${N(o,1)}; la mediana de la cartera es ${N(E.canjeMediana,1)} y el cuartil bajo ${N(E.canjeP25,1)})`,2,null,U.loyaltyCanje);let z=Z.campanas180/6;if(Z.leido&&z<1){let K=Z.campanas180?"lo usa poco":"no lo usa",S=Z.campanas180?`${Z.campanas180} campaña${Z.campanas180===1?"":"s"} en 6 meses; las marcas que envían mandan una mediana de `+`${P0(R.campanasPorMesMediana)} al mes`:"tiene clientes con correo y no les escribe";if(W&&W.correo>=200){let s=r>=3?1:3;I("email",K,S+(s===1?"":"; con sus clientes activos, una campaña trae pocos pedidos"),s,x)}}if(Z.leido&&!Z.automatizaciones.includes("abandonedCart")&&G.has("ecommerce"))I("email","falta el correo automático de carro abandonado","cuesta poco y no requiere campañas; no se ve diferencia medible entre marcas que lo tienen y no lo tienen",3);if(G.has("ecommerce")){if(!G.has("justoApp"))I("justoApp","no lo usa","suma un canal de clientes nuevos",J==="adq"?2:3);if(!G.has("alianzas"))I("alianzas","no participa","las campañas con cupón que financia Justo traen pedidos y clientes nuevos; la decisión de incluirla es de Justo",3);if(!G.has("instagramOrderFood")&&C.instagram)I("instagramOrderFood","no lo usa","tiene Instagram enlazado y no recibe pedidos desde ahí",3);if(!G.has("appPropia"))I("appPropia","no la tiene","canal propio para clientes que compran seguido; en marcas que ya venden online reemplaza en buena parte pedidos web",J==="lea"?3:4);if(!G.has("delivery")&&C.web.tipos.includes("delivery"))I("delivery","no lo usa","reparte con flota propia o no reparte",3)}let d=C.locales;if(!G.has("reservas")&&d?.conMesa)I("reservas","no lo usa",`tiene ${d.conMesa} local${d.conMesa===1?"":"es"} con atención en mesa`,3);if(!G.has("pdv")&&d?.total)I("pdv","no lo usa","vende en el local con otro sistema",4);let p={commander:"pedidos por teléfono o WhatsApp cargados por el local",terminalDePago:"cobro con tarjeta en el local",inventario:"control de stock",sac:"atención de clientes hecha por Justo",adelantoDePagos:"recibir antes el dinero de sus ventas"};for(let[K,S]of Object.entries(p))if(!G.has(K)&&(j.uso[K]||0)>=0.25)I(K,"no lo usa",S,4);return m$(V,(K)=>[K.prioridad,-(K.pares||0),K.producto])}function $0($,C){return $.faltan.includes(C)?` ${Dj[C][0].toUpperCase()}${Dj[C].slice(1)}: la consulta tardó demasiado (marca muy grande); sin dato.`:null}function N5($,C,q){let Q=$.benchmark,J=Q?.metricas||{},j=Q?.segmento?.modo;if(q.push(`
|
|
1458
|
+
1. DÓNDE ESTÁ LA MARCA`),j){let H=J[Tj[j]]||{},F=Lj[j];q.push(` Etapa: ${a$[j]}. Su palanca es ${B0[j]}: ${n(H.valor,F)} contra ${n(H.p50,F)} de mediana de sus pares de rubro`+(H.posicion?` (${H.posicion}; ${O(H.pares)} marcas de su rubro ${u(O0,H.alcance,"")}).`:"."))}else q.push(" Etapa: sin dato (el reporte de segmentos necesita 30 clientes nuevos en la cohorte de recompra para asignarla).");let G=[["recompra90","recompra a 90 días","pct"],["frecuencia","pedidos por comprador en 90 días","num"],["ticket","ticket","usd0"],["conversion","conversión del sitio","pct"]].map(([H,F,M])=>[J[H]||{},F,M]).filter(([H])=>H.valor!=null&&H.p50!=null).map(([H,F,M])=>`${F} ${n(H.valor,M)} contra ${n(H.p50,M)} (${O(H.posicion)}; ${O(H.pares)} marcas)`);if(G.length&&Q)q.push(` Contra sus pares de rubro (${F0(Q.periodo)}; la recompra a 90 días mide a los clientes que compraron por primera vez 3 a 5 meses antes): ${G.join("; ")}.`);let W=J.conversion||{};if(W.valor!=null&&W.p50&&(W.valor>=0.2||W.valor>=3*W.p50))q.push(` OJO: su conversión (${n(W.valor,"pct")} contra ${n(W.p50,"pct")} de sus pares de rubro) es poco creíble: probablemente faltan visitas registradas. No la uses ni para descartar ni para justificar nada.`);let Z=Q?.potencial||{};if((Z.justoUSD||0)>0)q.push(` Potencial según el reporte de segmentos: ${B(Z.ventaUSD,!0)} de venta al mes (${B(Z.justoUSD,!0)} para Justo) si llegara a la mediana de sus pares en su palanca. Es una estimación teórica.`);let X=$0(C,"segmentMonths");if(X)q.push(X);let Y=C.evolucion.filter((H)=>H.r90!==null||H.frec!==null);if(Y.length>=4)q.push(" Últimos meses (recompra a 90 días · pedidos por comprador · clientes nuevos en el mes): "+Y.slice(-6).map((H)=>`${H$(H.m)} ${H.r90!==null?N(H.r90):"s/d"} · ${H.frec!==null?P0(H.frec,2):"s/d"} · ${m(H.nuevos30||0)}`).join("; ")+".")}function g5($,C){C.push(`
|
|
1459
|
+
2. PRODUCTOS DE JUSTO QUE USA`),C.push(` Con uso en las últimas 4 semanas (${$.activos.length}): ${n$($.activos)}.`);let q=$0($,"productsByMonth");if(q)C.push(q);let Q=w0.filter((Z)=>$.usoMes[Z].some(Boolean));C.push(" Meses con uso en los últimos 12 (del más antiguo al más reciente; ■ con uso, · sin uso):");for(let Z of Q){let X=$.usoMes[Z];C.push(` ${qC(Z).padEnd(32)} ${X.map((Y)=>Y?"■":"·").join("")} ${X.filter(Boolean).length} de 12`)}let J=Q.filter((Z)=>$.usoMes[Z].slice(0,9).some(Boolean)&&!$.usoMes[Z].slice(-3).some(Boolean));if(J.length){let Z=(X)=>$.usoMes[X].lastIndexOf(!0);C.push(" Sin uso en los últimos 3 meses, con su último mes de uso: "+J.map((X)=>`${qC(X)} (${H$($.meses[Z(X)])})`).join(", ")+".")}let j=$.m6,G=$0($,"charges");if(G)C.push(G);if($.lineas.size){C.push(` Net revenue de Justo por producto, en USD por mes (${H$(j[0])} a ${H$(j[j.length-1])}), y cambio de los 3 últimos meses contra los 3 anteriores:`);let Z=m$([...$.lineas.entries()],([,X])=>[-R$(X.values())]);for(let[X,Y]of Z){let H=j.map((R)=>Y.get(R)??0);if(Math.abs(R$(H))<6)continue;let F=R$(H.slice(3)),M=R$(H.slice(0,3)),U=M>0?M>=15?J1(F,M):"monto chico":F>0?"nuevo":"s/d";C.push(` ${qC(X).padEnd(32)} ${H.map((R)=>m(v(R)).padStart(6)).join(" ")} ${U}`)}}let W=$0($,"channelOrders");if(W)C.push(W);if($.canales.size){C.push(` Pedidos con pago aprobado por canal, por mes (${H$(j[0])} a ${H$(j[j.length-1])}):`);let Z=m$([...$.canales.entries()],([,X])=>[-R$(X.values())]);for(let[X,Y]of Z){let H=j.map((R)=>Y.get(R)??0),F=R$(H.slice(3)),M=R$(H.slice(0,3)),U=M>0?M>=20?J1(F,M):"pocos pedidos":F>0?"nuevo":"s/d";C.push(` ${u(P5,X,X).padEnd(32)} ${H.map((R)=>m(R).padStart(6)).join(" ")} ${U}`)}}}function k5($,C,q){C.push(`
|
|
1460
|
+
3. BASE DE CLIENTES Y CANALES PROPIOS`);let Q=$.clientes;if(Q===null)C.push(" Base de clientes: la consulta tardó demasiado (marca muy grande). Sin este dato no se puede dimensionar correo ni puntos: dilo.");else C.push(` Clientes: ${m(Q.compradores)} han comprado alguna vez; ${m(Q.recurrentes)} más de una vez; ${m(Q.activos90)} compraron en los últimos 90 días; `+`${m(Q.dormidos)} compraron 2 veces o más y llevan 90 días sin volver (${m(Q.dormidosCorreo)} de ellos contactables por correo). Contactables por correo (compradores con correo y sin bloqueo de marketing): ${m(Q.correo)}.`+(Q.push?` Con notificaciones de la app activadas: ${m(Q.push)}.`:""));let J=$.correo,j=PC.correo,G=$0($,"emailCampaigns");if(G)C.push(G);else if(J.campanas180){let U=J.enviados180?J.abiertos180/J.enviados180:null,R=J.enviados180?1000*J.pedidos180/J.enviados180:null;C.push(` Email marketing, últimos 180 días: ${J.campanas180} campañas, ${m(J.enviados180)} correos enviados, apertura ${N(U)} (inflada por aperturas automáticas: no la uses como argumento), `+`${R!==null?P0(R):"s/d"} pedidos por cada 1.000 enviados (en la cartera: apertura mediana ${N(j.aperturaMediana)}, ${P0(j.pedidosPorMilEnviados)} pedidos por cada 1.000).`);for(let E of J.ultimas.slice(0,q?6:3))C.push(` ${E.fecha} · ${[...E.asunto].slice(0,70).join("")} · ${m(E.enviados)} enviados · ${m(E.abiertos)} abiertos · ${m(E.pedidos)} pedidos`)}else C.push(" Email marketing: ninguna campaña con envíos en los últimos 180 días"+(J.ultimaCampana?` (la última fue el ${CC(J.ultimaCampana)} de ${J.ultimaCampana.slice(0,4)})`:"")+".");if(C.push(` Referencia de la cartera para el correo: una campaña trae una mediana de ${P0(j.pedidosPor100Activos)} pedidos atribuidos por cada 100 clientes activos (la mitad de las marcas entre ${P0(j.pedidosPor100ActivosP25)} y ${P0(j.pedidosPor100ActivosP75)}); ${P0(j.pedidosPorMilEnviados,2)} pedidos por cada 1.000 correos enviados.`),!G)C.push(` Correos automáticos de marketing con envíos: ${J.automatizaciones.map((U)=>u(K5,U,U)).join(", ")||"ninguno"}.`);let W=$.puntos,Z=PC.puntos;if(W===null)C.push(" Programa de puntos: la consulta tardó demasiado; sin dato.");else if(W.accumulation?.usuarios){let U=W.accumulation.usuarios,R=W.redemption?.usuarios||0;C.push(` Programa de puntos, últimos 90 días: ${m(U)} clientes acumularon`+(Q?.activos90?` (${N(U/Q.activos90)} de sus ${m(Q.activos90)} clientes activos)`:"")+` y ${m(R)} canjearon (${N(R/U,1)} de los que acumulan; en la cartera, mediana ${N(Z.canjeMediana,1)} y cuartil bajo ${N(Z.canjeP25,1)}).`)}else C.push(" Programa de puntos: sin movimientos en los últimos 90 días.");let X=$0($,"customApplication");if(X)C.push(X);let Y=$.app;if(Y){let U=R$($.canales.get("app")?.values()??[]);C.push(` App propia: activa (${Y.ios||"sin enlace App Store"} · ${Y.android||"sin enlace Google Play"}); ${m(U)} pedidos en 6 meses`+(Y.descargas?`; ${m(Y.descargas)} descargas registradas (dato del ${O(Y.descargasLeidas)})`:"")+".")}let H=$0($,"instagram");C.push(H??` Instagram enlazado en su sitio: ${$.instagram||"ninguno"}. No hay dato de seguidores: si importa para el plan, pídelo a la persona o mira el perfil.`);let F=$.locales;C.push(F?` Locales: ${F.total}; con atención en mesa ${F.conMesa}, con retiro ${F.conRetiro}, con delivery ${F.conDelivery}.`:$0($,"stores"));let M=$0($,"deliveryTypes");if(M)C.push(M)}function S5($,C){C.push(`
|
|
1461
|
+
4. LO QUE VENDE SU MENÚ (pedidos con pago aprobado de todos los canales; unidades)`);let q=$.menu;if(!q){C.push($0($,"menu"));return}if(!q.unidades){C.push(" Sin ventas en los últimos 28 días.");return}let Q=q.unidadesAntes?J1(q.unidades,q.unidadesAntes):"s/d";if(C.push(` ${m(v(q.unidades))} unidades en los últimos 28 días (${q.desde} a ${q.hasta}), ${Q} contra los 28 anteriores.`),C.push(" Más vendidos (unidades ahora · antes · % de las unidades): "+q.top.map((J)=>`${J.nombre} ${m(v(J.u))} · ${m(v(J.antes??0))} · ${N(J.share)}`).join("; ")+"."),q.alza.length)C.push(" En alza (10 unidades o más y 30% o más que antes): "+q.alza.map((J)=>`${J.nombre} ${m(v(J.antes??0))} → ${m(v(J.u))}`).join("; ")+".");if(q.nuevos.length)C.push(" Nuevos (sin ventas en los 28 días anteriores): "+q.nuevos.map((J)=>`${J.nombre} ${m(v(J.u))}`).join("; ")+".");if(q.baja.length)C.push(" En baja (cayeron 40% o más): "+q.baja.map((J)=>`${J.nombre} ${m(v(J.u))} → ${m(v(J.ahora??0))}`).join("; ")+".");C.push(" Sirve para elegir con qué productos del menú se arma cada activación (el plato del correo, el premio de los puntos, la portada de la app).")}function B5($,C){C.push(`
|
|
1462
|
+
5. QUÉ USAN LAS MARCAS DE SU TAMAÑO`);let q=$.pares;C.push(` ${q.n} marcas de su tamaño (${q.alcance}); usan una mediana de ${O(q.productosMediana)} productos y esta marca usa ${$.activos.length}. `+"Ojo con Justo App: basta un pedido para contar como uso, así que su porcentaje sale alto.");let Q=m$(w0.filter((J)=>J!=="ecommerce").map((J)=>[J,q.uso[J]]),([,J])=>[-(J||0)]);C.push(" % que usa cada producto (✓ = esta marca lo usa): "+Q.filter(([,J])=>(J||0)>=0.03).map(([J,j])=>`${qC(J)} ${N(j)}${$.activos.includes(J)?" ✓":""}`).join("; ")+".")}function O5($,C){if(C.push(`
|
|
1463
|
+
6. CANDIDATOS — ${$.length} producto${$.length===1?"":"s"} ordenados por reglas fijas (references/criterios.md, sección 2). No son la recomendación: son la materia prima.`),$.forEach((q,Q)=>{let J=q.evidencia,j=[`${q.estado}: ${q.porque}`];if(q.pares!==null)j.push(`lo usa ${N(q.pares)} de las marcas de su tamaño`);if(q.requisito)j.push(`requisito: ${q.requisito}`+(q.cumpleRequisito===null?"":q.cumpleRequisito?" (lo cumple)":" (NO lo cumple)"));if(J?.texto)j.push(`evidencia (${J.nivel||"s/d"}): ${J.texto}`);if(q.dimension)j.push(`tamaño: ${q.dimension}`);C.push(` ${Q+1}. [Prioridad ${q.prioridad}] ${qC(q.producto)} — ${j.join("; ")}.`)}),!$.length)C.push(" Ninguna regla marcó un producto por proponer: la marca ya usa lo que usan sus pares. Dilo así.")}async function Bj($,C){let q=await SC($);if(!q.length)return`No encontré "${$}" entre las marcas asignadas a un KAM o a Partner Experience en la planilla del intra.`;if(q.length>1)return[`Hay ${q.length} marcas que calzan con "${$}". Pregunta cuál es y vuelve a correr con el websiteId:`,...q.slice(0,15).map((M)=>` ${M.websiteId} ${O(M.marca)} · ${O(M.pais)} · ${O(M.cartera)} · ${M.url||""}`)].join(`
|
|
1464
|
+
`);let Q=q[0],J=["CL","CO","PE","EC","MX"].includes(Q.pais)?Q.pais:"CL",[j,G,W,Z]=await Promise.all([V$(),M$("fichas",{filter:{},projection:{_id:0,websiteId:1,pais:1,tier:1,productos:1},limit:5000}),M$("acciones",{filter:{websiteId:Q.websiteId,tipo:"activacion"},sort:{semana:-1},limit:3}),I5(Q.websiteId,J).then((M)=>({result:M}),(M)=>({error:M}))]);if("error"in Z){let M=Z.error,U=M instanceof t$?M.code:void 0,R=U==="clientTimeout"?"la consulta tardó demasiado y se cortó":M instanceof Error?M.message:String(M),E=[`No pude consultar en vivo ${Q.marca}: ${R}`];if(U==="PermissionsError")E.push(`El plan de activación necesita el rol "kam" en team-cli. Sin ese rol solo queda la ficha: npx @getjusto/team-cli posventa ficha ${Q.websiteId}. Dilo en el resultado.`);return E.join(`
|
|
1465
|
+
`)}let X=T5(Q,Z.result,G),Y=L5(Q,X);if(C.json){let{_id:M,...U}=Q;return JSON.stringify({marca:Q.marca,websiteId:Q.websiteId,asignacion:Q.asignacion,perfil:Q.perfil,benchmark:U.benchmark,hechos:{...X,lineas:Object.fromEntries([...X.lineas].map(([R,E])=>[R,Object.fromEntries(E)])),canales:Object.fromEntries([...X.canales].map(([R,E])=>[R,Object.fromEntries(E)]))},candidatos:Y,activacionesAnteriores:W},null,1)}let H=[];if(H.push(`PLAN DE ACTIVACIÓN · ${Q.marca} [${Q.websiteId}] · ${Q.pais} · ${Q.url||"sin dominio"}`),H.push(`ASIGNACIÓN (planilla de asignación del intra): ${v$(Q)} · canal de ejecución: ${NC(Q,j)}`),H.push(`SEGMENTO (reporte de segmentos del intra): rubro ${u(_0,Q.rubro,Q.rubro||"s/d")}, ${y0(Q)}`),H.push(`RUTA DEL ÁRBOL: ${u(s$,Q.ruta.codigo,Q.ruta.codigo)} — ${Q.ruta.motivo}.`),["diagnostico_caida","recuperar_uso","rescate"].includes(Q.ruta.codigo)){let M=Q.ruta.codigo==="recuperar_uso"?` (dejó de usar: ${n$(Q.senal?.productosSinUso||[])})`:"";H.push(`OJO: esta semana la marca tiene una señal del radar${M}. Atiéndela primero con radar-semanal; el plan de activación va después, salvo que la señal ya esté resuelta.`)}let F=x0(Q,!0);H.push(...F.length?F:["Perfil de onboarding: no tiene uno registrado."]);for(let M of W)H.push(`ACTIVACIÓN ANTERIOR (semana ${q$(M.semana)}, ${M.por||"s/d"}): ${M.decision} — ${M.nota||"sin nota"}.`);if(!W.length)H.push("Activación anterior: no hay ninguna registrada.");if(H.push(S$(j)),H.push(`Leído en vivo hoy. Productos por mes: ${H$(X.meses[0])} de ${X.meses[0].slice(0,4)} a ${H$(X.meses[X.meses.length-1])} de ${X.meses[X.meses.length-1].slice(0,4)}. `+"Cobros y pedidos por canal: últimos 6 meses cerrados. Clientes: foto de hoy. Correo: últimos 180 días. Puntos: últimos 90 días. Menú: últimos 28 días contra los 28 anteriores."),X.sinVentaSemanas)H.push(`
|
|
1466
|
+
ATENCIÓN: la marca lleva ${X.sinVentaSemanas} semanas sin pedidos online y antes vendía. Esto no es una activación: es un rescate. `+`Revisa primero por qué dejó de vender (\`npx @getjusto/team-cli posventa detalle ${Q.websiteId} --que sitio,locales,canales\`) y no le propongas un producto nuevo hasta resolverlo.`);return N5(Q,X,H),g5(X,H),k5(X,H,C.completo),S5(X,H),B5(X,H),O5(Y,H),H.push(`
|
|
1467
|
+
Lo que este listado no ve: seguidores en redes, si la marca ya conversó estos productos con su ejecutivo, precios y condiciones de cada producto, `+"y el consentimiento explícito de cada cliente (solo se sabe quién bloqueó el marketing)."),H.join(`
|
|
1468
|
+
`)}var OC=300,BC=0.4,y5=["lanzamiento","auditoria_web","ajuste_fino"],x5=1.3,Oj=["CL","CO","PE","MX","EC","TODOS"],c5={precios_ocultos:"No muestran precios hasta elegir local",menu_version_anterior:"Menú en la versión anterior",telefono_verificado:"Piden verificar el teléfono antes de comprar",pocas_fotos:"Pocas fotos en el menú",pocas_descripciones:"Pocas descripciones en el menú",fotos_chicas:"Fotos de baja resolución",portada_sin_vitrina:"Portada sin productos ni categorías",app_quitada:"App propia quitada temporalmente",menu_vacio:"Menú online sin productos disponibles",menu_no_leido:"Menú online que no se pudo leer"},v5=["menu_vacio","menu_no_leido"];function b5($,C){for(let q=0;q<Math.min($.length,C.length);q++){if($[q]<C[q])return-1;if($[q]>C[q])return 1}return $.length-C.length}function w$($,C){return $.map((q)=>({item:q,key:C(q)})).sort((q,Q)=>b5(q.key,Q.key)).map(({item:q})=>q)}function W1($,C){let q=$.benchmark,Q=q?.metricas?.conversion||{},J=q?.tresMeses?.visitas||0;if(Q.valor==null||Q.p50==null||J<OC||(Q.pares||0)<8)return null;let j=C??$.sitio?.web3m?.pagados,G=v(Q.valor*J),W=Boolean(j&&j>=20&&j>=x5*Math.max(G,1)),Z=W?j/J:Q.valor,X=Math.max(0,J/3*(Q.p50-Z));return{pedidosMes:X,ventaUSD:X*(q?.mensual?.ticketUSD||0),visitasMes:J/3,valor:Z,p50:Q.p50,posicion:Q.posicion,pares:Q.pares,alcance:Q.alcance,ventaActualUSD:q?.mensual?.ventaUSD,corregida:W,valorReporte:Q.valor,pedidosReporte:G,pedidosBase:j}}function G1($){return`OJO: en ese período el reporte de segmentos cuenta cerca de ${m($.pedidosReporte)} pedidos y la base registra ${m($.pedidosBase??0)} pedidos web pagados. `+`El reporte subestima a esta marca: su conversión según el reporte es ${n($.valorReporte,"pct")} y con los pedidos de la base es ${n($.valor,"pct")}. `+"La brecha está calculada con la de la base."}function Z1($){let{fotoPct:C,descripcionPct:q,productos:Q,categorias:J}=$;if(!C||!q||!Q||!J)return"REFERENCIA: la carga del lunes no trae la referencia del sitio (falta el bloque de sitio en esta carga). Dilo al entregar.";return`REFERENCIA (las ${m($.marcas??0)} marcas de KAM y Partner Experience con venta online en las 4 semanas previas, leída el lunes): `+`productos con foto, mediana ${N(C.p50)} y cuartil bajo ${N(C.p25)}; con descripción, mediana `+`${N(q.p50)} y cuartil bajo ${N(q.p25)}; productos en el menú, mediana `+`${v(Q.p50)} (cuartil alto ${v(Q.p75)}); categorías, mediana ${v(J.p50)}.`}function yj($){let C=$.pais??"TODOS";if(!Oj.includes(C))throw Error(`--pais debe ser uno de: ${Oj.join(", ")}.`);let q=$.top===void 0?10:Number($.top);if(!Number.isInteger(q))throw Error("--top debe ser un número entero.");let Q=$.rutas??"web";if(Q!=="web"&&Q!=="todas")throw Error("--rutas debe ser web o todas.");return{cartera:$.cartera==="true"?void 0:$.cartera,pais:C,top:q,rutas:Q,json:$.json==="true"}}var Fq=($)=>[-($.ficha.peso.nrSemanalUSD||0),$.ficha.marca||""];function xj($,C){let{ficha:q,gap:Q}=C,J=[`${$}. ${q.marca} [${q.websiteId}] · ${q.pais} · ${v$(q)} · ${u(s$,q.ruta.codigo,q.ruta.codigo)} · `+`${B(q.peso.nrSemanalUSD)} de net revenue por semana`];if(Q){let j=u(O0,Q.alcance,""),G=Q.corregida?`(${O(Q.pares)} marcas de su rubro ${j}).`:`(${O(Q.posicion)}; ${O(Q.pares)} marcas de su rubro ${j}).`,W=Q.pedidosMes>=1?` Le faltan ${m(v(Q.pedidosMes))} pedidos al mes para la mediana: ${B(Q.ventaUSD)} de venta`+(Q.ventaActualUSD!=null?` (hoy vende ${B(Q.ventaActualUSD)} al mes online).`:"."):"";if(J.push(`Convierte ${n(Q.valor,"pct")} de ${m(v(Q.visitasMes))} visitas al mes; la mediana de sus pares es ${n(Q.p50,"pct")} ${G}${W}`),Q.corregida)J.push(G1(Q))}else J.push("Sin conversión comparable contra pares.");if(C.appShare>=0.1)J.push(`Pedidos por la app propia: ${N(C.appShare)} de sus pedidos digitales de 28 días.`+(C.appShare>=BC?" La conversión de arriba mide solo el sitio web, que no es su vitrina principal: no leas la brecha como venta perdida.":""));if(C.flags.length)J.push(`Configuración: ${C.flags.map(([,j])=>j).join("; ")}.`);return J[0]+J.slice(1).map((j)=>`
|
|
1469
|
+
${j}`).join("")}function j1($,C,q,Q=(J)=>J.ficha.marca){let J=[`
|
|
1470
|
+
${$} — ${C.length} marca${J$(C.length)}`+(C.length>q?`; se detallan ${q}`:"")];if(C.slice(0,q).forEach((j,G)=>{J.push(xj(G+1,j))}),C.length>q)J.push(` Fuera del detalle (${C.length-q}; para verlas usa --top ${C.length}): `+C.slice(q,q+40).map((j)=>Q(j)).join("; "));return J}function Pq($){let{sitio:C,...q}=$.ficha;return{...q,_brecha:$.gap,_flags:$.flags,_app:$.appShare}}async function cj($){let C=await V$(),q=C.semana,{portfolio:Q,origin:J}=await $C($.cartera,C),j={};if(Object.hasOwn(c$,Q)){let z=c$[Q].team;if(z)j.equipo=z}else j.cartera=Q;if($.pais!=="TODOS")j.pais=$.pais;let G={_id:0,websiteId:1,marca:1,pais:1,cartera:1,equipo:1,asignacion:1,"ruta.codigo":1,peso:1,"fase.codigo":1,"productos.n":1,ejecucion:1,tier:1,modo:1,sitio:1,"benchmark.metricas.conversion":1,"benchmark.tresMeses":1,"benchmark.mensual.ticketUSD":1,"benchmark.mensual.ventaUSD":1,"benchmark.periodo":1,url:1},[W,Z]=await Promise.all([M$("fichas",{filter:j,projection:G,limit:5000}),gC(q)]),X=W.map((z)=>({ficha:z,gap:W1(z),flags:iq(z.sitio,Z),appShare:z.sitio?.compra?.appPct||0})),Y=(z)=>z.ficha.peso.codigo==="360",H=w$(X.filter((z)=>Y(z)&&z.flags.some(([d])=>v5.includes(d))),Fq),F=new Set(H.map((z)=>z.ficha.websiteId)),M=X.filter((z)=>($.rutas==="todas"||y5.includes(z.ficha.ruta.codigo))&&!F.has(z.ficha.websiteId)),U=w$(M.filter((z)=>z.appShare>=BC),Fq),R=new Set(U.map((z)=>z.ficha.websiteId)),E=w$(M.filter((z)=>!R.has(z.ficha.websiteId)&&z.gap&&z.gap.pedidosMes>=1),(z)=>[-z.gap.ventaUSD,z.ficha.marca||""]),V=new Set([...E.map((z)=>z.ficha.websiteId),...R]),I=w$(M.filter((z)=>z.flags.length&&!V.has(z.ficha.websiteId)&&Y(z)),(z)=>[-z.flags.length,...Fq(z)]);if($.json)return JSON.stringify({semana:q,cartera:Q,origenDeLaCartera:J,referencia:Z,noSePuedeComprar:H.map(Pq),conversion:E.slice(0,$.top).map(Pq),appFuerte:U.slice(0,$.top).map(Pq),configuracion:I.slice(0,$.top).map(Pq)},null,1);let A=[`COLA DE AUDITORÍA WEB · cartera ${S0(Q,C)} · país ${$.pais}`];if(J)A.push(J);if(A.push(S$(C)),A.push(`${m(W.length)} marcas en la cartera; ${m(M.length)} `+($.rutas==="todas"?"en total":"en las rutas que el árbol manda a auditoría web (lanzamiento, auditoría web y ajuste fino; ver references/arbol.md, sección 3)")+"."),A.push(Z1(Z)),A.push("Cómo leer la brecha: visitas al mes × (conversión mediana de sus pares − la suya) = pedidos que faltan al mes; por su ticket = venta. "+"Son cifras del reporte de segmentos (3 últimos meses cerrados, solo sitio web directo). Es una estimación para ordenar, no un pronóstico; "+"cuando supera la venta online actual de la marca, léela como orden de magnitud."),A.push("La cola solo ve lo que se leyó el lunes (conversión, pedidos por canal y configuración). Las ventas por producto, los agotados y el orden del menú se ven recién al auditar la marca."),H.length)A.push(`
|
|
1471
|
+
ANTES QUE TODO: NO SE PUEDE COMPRAR O NO SE PUDO LEER EL MENÚ — ${H.length} marca${J$(H.length)}, de cualquier ruta. `+"Puede ser el sitio caído o el menú vacío: confírmalo con `posventa auditoria marca` antes de cualquier otra cosa."),H.forEach((z,d)=>{A.push(xj(d+1,z))});if(A.push(...j1("PRIMERO: LLEGAN VISITAS Y CONVIERTEN BAJO SUS PARES (ordenadas por la venta que falta)",E,$.top,(z)=>`${z.ficha.marca} (${B(z.gap?.ventaUSD)})`)),U.length)A.push(...j1(`CON APP PROPIA FUERTE: ${N(BC)} o más de sus pedidos digitales entra por la app (ordenadas por net revenue; lo que hay que auditar es la app)`,U,$.top));A.push(...j1("DESPUÉS: CONFIGURACIÓN FUERA DE LO HABITUAL (marcas de US$25 o más por semana que convierten como sus pares o no tienen dato; ordenadas por cantidad de puntos y después por net revenue)",I,$.top));let x=new Map;for(let z of X)for(let[d]of z.flags)x.set(d,[...x.get(d)??[],z]);if(x.size){A.push(`
|
|
1472
|
+
POR SITUACIÓN — toda la cartera (${m(W.length)} marcas, incluidas las de tratamiento en lote). Sirve para aplicar el mismo arreglo a varias marcas; `+"en canal masivo, además, para un solo envío por situación");for(let[z,d]of w$([...x],([p,K])=>[-K.length,p])){let p=w$(d,Fq);A.push(` ${u(c5,z,z)}: ${p.length} marca${J$(p.length)} — `+p.slice(0,20).map((K)=>`${K.ficha.marca} [${K.ficha.websiteId}]`).join(", ")+(p.length>20?` y ${p.length-20} más`:""))}}let r=new Set([...V,...I.map((z)=>z.ficha.websiteId)]),W$=M.filter((z)=>!r.has(z.ficha.websiteId)),o=M.filter((z)=>!z.gap).length;return A.push(`
|
|
1473
|
+
Fuera de las listas: ${W$.length} de ${M.length} marcas, sin nada marcado en lo que la cola alcanza a ver (o de menos de US$25 por semana).`),A.push(`Sin dato de conversión comparable: ${o} de ${M.length} marcas (menos de ${OC} visitas en 3 meses, sin benchmark o sin pares suficientes). `+"No significa que estén bien: no hay cómo medirlas contra pares."),A.join(`
|
|
1474
|
+
`)}import{execFile as h5}from"node:child_process";import{mkdtemp as p5,readFile as l5,rm as f5}from"node:fs/promises";import{tmpdir as u5}from"node:os";import{join as vj}from"node:path";var X1={60:"el certificado de seguridad está vencido o es inválido",35:"falla la conexión segura",51:"el certificado no corresponde al dominio",6:"el dominio no existe o no resuelve",7:"el servidor no responde",28:"el sitio no respondió a tiempo"},bj="Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1",hj=20,pj=900000;async function Mq($,C){let q=await p5(vj(u5(),"posventa-sitio-")),Q=vj(q,"body.html");try{let{exitCode:J,stdout:j}=await new Promise((W,Z)=>{h5("curl",["-sS","-L",...C.extraArgs??[],"--max-time",String(C.timeoutSeconds),"-o",Q,"-w",C.writeOut,"--proto","=http,https","--proto-redir","=http,https","--",$],{timeout:(C.timeoutSeconds+10)*1000},(X,Y)=>{if(!X)return W({exitCode:0,stdout:Y});if(typeof X.code==="number"&&!X.killed)return W({exitCode:X.code,stdout:Y});Z(X)})}),G=J===0?(await l5(Q,"utf-8")).slice(0,C.maxBodyChars):"";return{exitCode:J,stdout:j,body:G}}finally{await f5(q,{recursive:!0,force:!0})}}function Y1($){return $?.code==="ENOENT"}var d5={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",aacute:"á",eacute:"é",iacute:"í",oacute:"ó",uacute:"ú",Aacute:"Á",Eacute:"É",Iacute:"Í",Oacute:"Ó",Uacute:"Ú",ntilde:"ñ",Ntilde:"Ñ",uuml:"ü",Uuml:"Ü",iexcl:"¡",iquest:"¿",ordf:"ª",ordm:"º",deg:"°",copy:"©",reg:"®",trade:"™",middot:"·",bull:"•",hellip:"…",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",laquo:"«",raquo:"»",euro:"€"};function s5($){return $.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi,(C,q)=>{if(q[0]==="#"){let Q=q[1]==="x"||q[1]==="X"?Number.parseInt(q.slice(2),16):Number(q.slice(1));return Number.isFinite(Q)&&Q>0&&Q<=1114111?String.fromCodePoint(Q):C}return d5[q]??C})}function yC($,C){let q=$.match(C);if(!q)return null;return s5(q[1].replace(/\s+/g," ").trim())}async function lj($){if(!$)return{ok:null,detalle:"la marca no tiene dominio registrado"};let C;try{C=await Mq($,{timeoutSeconds:hj,writeOut:"%{http_code} %{time_starttransfer} %{time_total} %{size_download}",extraArgs:["-A",bj],maxBodyChars:pj})}catch(X){return{ok:null,detalle:Y1(X)?"no se pudo revisar (falta curl en este equipo)":"no se pudo revisar el sitio"}}if(C.exitCode!==0)return await n5($,C.exitCode);let q=C.stdout.trim().split(/\s+/),Q=q[0]??"",J=C.body,j={ok:Q==="200"&&J.includes("getjusto.com"),url:$,http:Q,detalle:""},[G,W,Z]=q.slice(1,4).map(Number);if([G,W,Z].every(Number.isFinite)&&q.length>=4)j.primerByte=G,j.total=W,j.kb=v(Z/1024);if(Q!=="200")return{...j,detalle:`responde con error ${Q}`};if(!J.includes("getjusto.com"))return{...j,detalle:"carga, pero no es la página de Justo: el dominio apunta a otro servicio"};return{...j,detalle:"carga y es la página de Justo",titulo:yC(J,/<title[^>]*>(.*?)<\/title>/is),descripcion:yC(J,/<meta[^>]+name=["']description["'][^>]+content=["'](.*?)["']/is)||yC(J,/<meta[^>]+content=["'](.*?)["'][^>]+name=["']description["']/is),imagenCompartir:yC(J,/<meta[^>]+property=["']og:image["'][^>]+content=["'](.*?)["']/is)||yC(J,/<meta[^>]+content=["'](.*?)["'][^>]+property=["']og:image["']/is)}}async function n5($,C){let q=X1[C]??`error de conexión (curl ${C})`,Q={ok:!1,url:$,detalle:`no carga: ${q}`};if(C!==60&&C!==51)return Q;try{let J=await Mq($,{timeoutSeconds:hj,writeOut:"%{http_code} %{url_effective}",extraArgs:["-k","-A",bj],maxBodyChars:pj});if(J.exitCode===0){let j=J.stdout.trim().split(/\s+/).at(-1);Q.detalle+=`; saltándose la advertencia, el dominio lleva a ${j}, que `+(J.body.includes("getjusto.com")?"es una página de Justo":"no es una página de Justo")}}catch{}return Q}var xC=["sitio","locales","canales","pagos","cobros","soporte"],H1=["CL","CO","PE","EC","MX"],fj=26,a5={web:"Sitio web",app:"App propia",justoApp:"Justo App",commander:"Commander",commanderManaged:"Commander manejado",pide:"Pide",orderingAPI:"API de pedidos",messenger:"Messenger"},o5={inDrivePEApp:"inDrive",inDriveTracking:"inDrive",nequiCoWeb:"Nequi",nequiCoApp:"Nequi",daleCoApp:"Dale!",daleCoWeb:"Dale!",claroCoApp:"Claro",claroCoWeb:"Claro",yapeApp:"Yape"},F1={delivery:"delivery",go:"retiro en local",serve:"en mesa"},r5={open:"abierto",closed:"cerrado"},t5=15,i5=600000;async function e5($){if(!$)return{detalle:"la marca no tiene dominio registrado",revisado:null};let C=sQ();try{let{exitCode:q,stdout:Q,body:J}=await Mq($,{timeoutSeconds:t5,writeOut:"%{http_code}",maxBodyChars:i5});if(q!==0)return{detalle:`no carga: ${X1[q]??`error de conexión (curl ${q})`}`,revisado:C};let j=Q.trim().slice(-3);if(j!=="200")return{detalle:`responde con error ${j}`,revisado:C};if(!J.includes("getjusto.com"))return{detalle:"carga, pero no es la página de Justo: el dominio apunta a otro servicio",revisado:C};return{detalle:"carga y es la página de Justo",revisado:C}}catch(q){return{detalle:Y1(q)?"no se pudo revisar (falta curl en este equipo)":"no se pudo revisar el sitio",revisado:null}}}function $4($,C){let[q]=KC($);return Array.from({length:C},(Q,J)=>MC(AC(q,-7*(C-1-J))))}async function C4($){return(await h({service:"data",timeoutMs:55000,query:`query ($websiteId: String, $countryCode: PosventaCountry, $lastWeek: String, $weeks: BigInt, $tables: [PosventaDetailTable]) {
|
|
1475
|
+
posventaBrandDetail(websiteId: $websiteId, countryCode: $countryCode, lastWeek: $lastWeek, weeks: $weeks, tables: $tables) {
|
|
1476
|
+
weeks
|
|
1477
|
+
lastPaidOrderDate
|
|
1478
|
+
storeOrders { storeId storeName week orders }
|
|
1479
|
+
storesWithoutOrders
|
|
1480
|
+
channelOrders { source embeddedVendor deliveryType week orders totalPrice }
|
|
1481
|
+
paymentAttempts { paymentStatus orderStatus week attempts }
|
|
1482
|
+
charges { chargeType week amount }
|
|
1483
|
+
supportTickets { week tickets }
|
|
1484
|
+
recentSupportCases { date priority status idSuffix }
|
|
1485
|
+
}
|
|
1486
|
+
}`,variables:$})).posventaBrandDetail}function QC($,C,q,Q){let J=new Map;for(let j of $??[]){if(!C.includes(j.week))continue;let G=q(j),W=J.get(G)??new Map;W.set(j.week,(W.get(j.week)??0)+(Q(j)||0)),J.set(G,W)}return J}function w1($,C=!1){let q=0;for(let Q of $.values())q+=C?Math.abs(Q):Q;return q}function dj($,C=!1){let q=new Map([...$].map(([Q,J])=>[Q,w1(J,C)]));return[...$.keys()].sort((Q,J)=>{let j=(q.get(J)??0)-(q.get(Q)??0);if(j)return j;return Q<J?-1:Q>J?1:0})}function JC($,C,q,Q={}){let J=Q.format??((W)=>m(v(W))),j=[`
|
|
1487
|
+
${$}`];if(!C.size)return[...j," sin registros"];j.push(` ${" ".repeat(40)}${q.map((W)=>`s${q$(W)}`.padStart(8)).join("")}`);let G=Q.order?.length?Q.order:dj(C,!0);for(let W of G){let Z=C.get(W),X=q.map((H)=>(Z.has(H)?J(Z.get(H)):"·").padStart(8)),Y=[...W].slice(0,40);j.push(` ${Y.join("")}${" ".repeat(40-Y.length)}${X.join("")}`)}if(Q.note)j.push(` ${Q.note}`);return j}function uj($){let{source:C,embeddedVendor:q,deliveryType:Q}=$,J=C==="embedded"?u(o5,q,q||"app aliada"):u(a5,C,C||"sin dato"),j=u(F1,Q,Q||"s/d");return`${J} · ${j}`}function q4($,C){let q=QC($.storeOrders,C,(j)=>j.storeName??j.storeId??"sin local",(j)=>j.orders),Q=JC("ÓRDENES ONLINE POR LOCAL (con pago aprobado, sin canceladas)",q,C),J=$.storesWithoutOrders??[];if(J.length)Q.push(` Locales sin ninguna orden online en el período: ${J.slice(0,20).join(", ")}. (No se puede ver desde aquí si están apagados en el admin.)`);return Q}function Q4($,C){let q=QC($.channelOrders,C,uj,(j)=>j.orders),Q=QC($.channelOrders,C,uj,(j)=>j.totalPrice),J=new Map;for(let[j,G]of q){let W=new Map;for(let[Z,X]of G)if(X)W.set(Z,(Q.get(j)?.get(Z)??0)/X);J.set(j,W)}return[...JC("ÓRDENES ONLINE POR CANAL Y TIPO DE ENTREGA",q,C),...JC("TICKET PROMEDIO POR CANAL (moneda local)",J,C,{order:dj(q)})]}function J4($,C){let q=QC($.paymentAttempts,C,(j)=>`pago ${j.paymentStatus} · orden ${j.orderStatus}`,(j)=>j.attempts),Q=JC("INTENTOS DE COMPRA POR ESTADO",q,C);if(!q.size)return Q;let J=C.map((j)=>{let G=0,W=0;for(let[Z,X]of q){let Y=X.get(j)??0;if(G+=Y,Z.startsWith("pago done"))W+=Y}return(G?`${v(100*W/G)}%`:"·").padStart(8)});return Q.push(` ${"% de intentos con pago aprobado".padEnd(40)}${J.join("")}`),Q.push(' Lectura: "pago done" = pago aprobado; "pago pending" = el pago no se completó; "pago error" = rechazado; "blocked" = bloqueado.'),Q.push(" Compara cada semana con las anteriores de la misma marca: lo que importa es si el porcentaje aprobado cambió."),Q}function j4($,C,q){let Q=q.familias||{},J=new RegExp(q.recurrente_regex||"subscription|plan","i"),j=new Set(q.tipos_puntuales||[]),G=(F)=>{let M=F||"sin tipo";if(J.test(M))return`[recurrente] ${M}`;if(j.has(M))return`[marketing] ${M}`;return`${u(Q,M,"otros")} · ${M}`},W=QC($.charges,C,(F)=>G(F.chargeType),(F)=>F.amount),Z=[...W.keys()].filter((F)=>!F.startsWith("[")),X="= NR OPERATIVO (lo que mide la señal)";if(Z.length)W.set("= NR OPERATIVO (lo que mide la señal)",new Map(C.map((F)=>[F,Z.reduce((M,U)=>M+(W.get(U)?.get(F)??0),0)])));let H=[...[...Z].sort((F,M)=>{let U=F.split(" · ")[0],R=M.split(" · ")[0];if(U!==R)return U<R?-1:1;return w1(W.get(M))-w1(W.get(F))}),...[...W.keys()].filter((F)=>F.startsWith("=")),...[...W.keys()].filter((F)=>F.startsWith("[")).sort()];return JC("NET REVENUE POR TIPO DE COBRO (USD, sin anulados)",W,C,{order:H,note:'Cada fila es "línea · tipo de cobro". Las filas [marketing] y [recurrente] no entran en la señal de la semana.'})}function W4($,C){let q=QC($.supportTickets,C,()=>"tickets abiertos",(j)=>j.tickets),Q=JC("TICKETS DE SOPORTE POR SEMANA (sin los avisos automáticos que Justo le manda al local)",q,C),J=$.recentSupportCases??[];if(J.length){Q.push(" Los 20 más recientes del período (fecha · prioridad · estado · id; sin el título, que puede traer datos de clientes):");for(let j of J){let G=j.status?u(r5,j.status,j.status):"s/d";Q.push(` ${j.date} · ${j.priority||"s/d"} · ${G} · ${j.idSuffix}`)}Q.push(" No hay una vara de cuántos tickets son normales: compara las semanas de la misma marca entre sí.")}return Q}async function G4($,C,q){let Q=await d$("fichas",{filter:{websiteId:$},projection:{marca:1,pais:1,semana:1,url:1}}),J=Q?.pais||C.country||"CL",j=Q?.semana||q.semana,G=$4(j,C.weeks),W=new Set(C.tables),Z=[`
|
|
1488
|
+
${"=".repeat(78)}
|
|
1489
|
+
DETALLE EN VIVO · ${Q?.marca||$} [${$}] · semanas ${q$(G[0])} a ${q$(G[G.length-1])} (hora de ${J}; la última es la semana analizada)`],[X,Y]=await Promise.all([W.has("sitio")?e5(Q?.url):null,C4({websiteId:$,countryCode:H1.includes(J)?J:"CL",lastWeek:j,weeks:C.weeks,tables:C.tables.filter((H)=>H!=="sitio")})]);if(X)Z.push(`
|
|
1490
|
+
SITIO DE PEDIDOS: ${Q?.url||"sin dominio"} → ${X.detalle}${X.revisado?` (revisado el ${X.revisado})`:""}`);if(Z.push(`
|
|
1491
|
+
ÚLTIMA ORDEN ONLINE CON PAGO APROBADO: ${Y.lastPaidOrderDate||"ninguna registrada"}`),W.has("locales"))Z.push(...q4(Y,G));if(W.has("canales"))Z.push(...Q4(Y,G));if(W.has("pagos"))Z.push(...J4(Y,G));if(W.has("cobros"))Z.push(...j4(Y,G,q));if(W.has("soporte"))Z.push(...W4(Y,G));return Z}function sj($){let C=($.que||xC.join(",")).split(",").map((j)=>j.trim()).filter(Boolean),q=C.filter((j)=>!xC.includes(j));if(q.length)throw Error(`No existe la tabla ${q.join(", ")}. Tablas válidas: ${xC.join(", ")}. (Los cupones se ven con: npx @getjusto/team-cli admin <websiteId> coupons list)`);let Q=$.semanas?Number($.semanas):9;if(!Number.isInteger(Q)||Q<1||Q>fj)throw Error(`--semanas debe ser un entero entre 1 y ${fj}.`);let J=$.pais?.toUpperCase();if(J&&!H1.includes(J))throw Error(`--pais debe ser uno de: ${H1.join(", ")}.`);return{tables:C,weeks:Q,country:J}}async function nj($,C){let q=await V$(),Q=[];for(let J of $.split(",").map((j)=>j.trim()).filter(Boolean))try{Q.push(...await G4(J,C,q))}catch(j){let G=j instanceof t$?j.code:void 0;if(G==="posventaDetailTimeout"||G==="clientTimeout"){Q.push(`
|
|
1492
|
+
No pude consultar en vivo ${J}: la consulta tardó demasiado y se cortó. Vuelve a pedirla con menos semanas (por ejemplo --semanas ${Math.max(1,Math.floor(C.weeks/2))}) o menos tablas (--que).`);continue}let W=j instanceof Error?j.message:String(j);if(Q.push(`
|
|
1493
|
+
No pude consultar en vivo ${J}: ${W}`),G!=="PermissionsError")continue;Q.push('Las consultas en vivo necesitan el rol "kam" en team-cli. Sin ese rol, trabaja con la evidencia que ya traen el radar y la ficha, y dilo en el resultado.');break}return Q.join(`
|
|
1494
|
+
`)}var Kq=["web","app","justoApp"],P1={web:"sitio web",app:"app propia",justoApp:"Justo App",commander:"Commander",commanderManaged:"Commander manejado",embedded:"apps aliadas",pide:"Pide",orderingAPI:"API de pedidos",messenger:"Messenger"},D$=28,Z4=new Set(["productShowcase","featuredCategories","categoriesImageBar","searchProduct"]),X4={startOrdering:"imagen con botón de pedir",productShowcase:"vitrina de productos",featuredCategories:"categorías destacadas",slider:"carrusel de imágenes",hero:"imagen principal",gallery:"galería",justAnImage:"imagen",popup:"ventana emergente",fullImageWithMessage:"imagen con mensaje",imageWithMessage:"imagen con mensaje",redirect:"envío directo al menú",ai:"bloque generado con IA",custom:"bloque a medida",whiteSpace:"espacio en blanco",stores:"locales",deliveryZone:"zona de reparto",contactForm:"formulario de contacto",searchProduct:"buscador de productos",categoriesImageBar:"barra de categorías con imagen",multiImageWithMessage:"imágenes con mensaje",htmlMcp:"página a medida",links:"enlaces",faq:"preguntas frecuentes",storeLocator:"buscador de locales"},Y4={1:"No se puede comprar",2:"Trabas antes de comprar",3:"Lo primero que ve el cliente",4:"Calidad del menú",5:"Confianza y hallazgo",6:"App propia"},b$="lo ajusta el equipo, con el OK de la marca",B$="necesita material o una decisión de la marca",cC="va a Soporte";async function H4($,C){return(await h({service:"data",timeoutMs:55000,query:`query ($websiteId: String, $benchmarkFromMonth: String, $benchmarkToMonth: String) {
|
|
1495
|
+
posventaBrandAudit(websiteId: $websiteId, benchmarkFromMonth: $benchmarkFromMonth, benchmarkToMonth: $benchmarkToMonth) {
|
|
1496
|
+
periodFrom
|
|
1497
|
+
periodTo
|
|
1498
|
+
website {
|
|
1499
|
+
menuLayout checkoutLayout dontShowPricesUntilStoreSelected hideNotAvailableProducts
|
|
1500
|
+
minimumOrderPrice hasFeaturedCoupon requestVerifiedPhoneToCreateOrders deliveryTypes
|
|
1501
|
+
extraPaymentTypes loyaltyActive description defaultMenuId reviewCount reviewRating
|
|
1502
|
+
reviewDeliveryRating
|
|
1503
|
+
}
|
|
1504
|
+
seoTitle
|
|
1505
|
+
seoDescription
|
|
1506
|
+
footerSocialNetworks
|
|
1507
|
+
menus { _id name channels openPeriods { daysOfWeek fromMinute toMinute } }
|
|
1508
|
+
orderGroups { source paymentStatus cancelled menuId mobile orders }
|
|
1509
|
+
paidOrdersByStore { storeId orders }
|
|
1510
|
+
weeklyAttempts { source approved weekIndex orders }
|
|
1511
|
+
products {
|
|
1512
|
+
_id name categoriesIds mandatoryModifiers descriptionLength photos firstPhotoWidth
|
|
1513
|
+
availability { menuId basePrice available discountPrice }
|
|
1514
|
+
}
|
|
1515
|
+
productSales { productId menuId units sales nameAtPurchase }
|
|
1516
|
+
categories { _id name index parentId }
|
|
1517
|
+
outOfStock { productId storeIds since }
|
|
1518
|
+
homeComponents { componentTypeId productsIds }
|
|
1519
|
+
stores {
|
|
1520
|
+
_id name openPeriods { daysOfWeek fromMinute toMinute } acceptDelivery acceptGo
|
|
1521
|
+
acceptSchedulingOrders disableNowOrders currentPreparationDuration
|
|
1522
|
+
}
|
|
1523
|
+
app { appCode iosURL androidURL iosDownloads androidDownloads downloadsReadAt temporarilyRemoved }
|
|
1524
|
+
webThreeMonths { attempts approved }
|
|
1525
|
+
}
|
|
1526
|
+
}`,variables:{websiteId:$,benchmarkFromMonth:C?.desde??null,benchmarkToMonth:C?.hasta??null}})).posventaBrandAudit}function jC($){return($||"").replace(/\s+/g," ").replace(/^[ .]+|[ .]+$/g,"")}var h$=($)=>C$($);function M1($,C){return Number(z$($,C))}function aj($){if(!$.length)return null;let C=$.reduce((q,Q)=>q+(Q.daysOfWeek?.length||0)*Math.max(0,(Q.toMinute||0)-(Q.fromMinute||0)),0);return M1(C/60,1)}function C0($,C){return $.reduce((q,Q)=>q+C(Q),0)}function w4($,C){let q=$[0];for(let Q of $.slice(1)){let J=C(Q),j=C(q),G=J.findIndex((W,Z)=>W!==j[Z]);if(G>=0&&J[G]>j[G])q=Q}return q}function F4($,C){let{website:q,orderGroups:Q}=$,J=Q.filter((w)=>w.paymentStatus==="done"&&!w.cancelled),j={};for(let w of J){let L=w.source||"sin dato";j[L]=(j[L]??0)+w.orders}let G={};for(let w of Q){let L=w.source;if(!Kq.includes(L))continue;let y=G[L]??{intentos:0,aprobados:0};y.intentos+=w.orders,y.aprobados+=w.paymentStatus==="done"?w.orders:0,G[L]=y}let W=J.filter((w)=>w.source==="web"),Z=J.filter((w)=>Kq.includes(w.source)),X=C0(Z,(w)=>w.orders),Y=new Map;for(let w of $.weeklyAttempts){let L=Math.trunc(w.weekIndex||0);if(L<0||L>=8)continue;let y=Y.get(w.source)??Array.from({length:8},()=>[0,0]);y[L][0]+=w.orders,y[L][1]+=w.approved?w.orders:0,Y.set(w.source,y)}let H=new Map($.menus.map((w)=>[w._id,w])),F=new Map;for(let w of Z)if(w.menuId)F.set(w.menuId,(F.get(w.menuId)??0)+w.orders);let M=w$([...F].filter(([w,L])=>L>=0.05*X&&H.has(w)),([w,L])=>[-L,H.get(w)?.name||"",w]).map(([w])=>w),U=`el menú con que entraron sus pedidos de los últimos ${D$} días`;if(!M.length&&q?.defaultMenuId&&H.has(q.defaultMenuId))M=[q.defaultMenuId],U="el menú por defecto del sitio (no tuvo pedidos en el período)";if(!M.length)M=w$([...H.values()].filter((w)=>w.channels.some((L)=>L==="web-delivery"||L==="web-go")),(w)=>[w.name||"",w._id]).map((w)=>w._id),U="los menús que declaran canal web";let R=new Map,E=(w,L)=>JSON.stringify([w??null,L??null]),V=new Map;for(let w of $.productSales){let L=E(w.productId,w.menuId);R.set(L,(R.get(L)??0)+(w.units||0));let y=w.productId??null,P$=V.get(y)??{u:0,v:0,nom:w.nameAtPurchase??null};P$.u+=w.units||0,P$.v+=w.sales||0,V.set(y,P$)}let I=(w,L)=>R.get(E(w,L))??0,A=new Map;for(let w of w$($.products,(L)=>[L._id])){let L=new Map;for(let Q$ of w.availability)if(Q$.menuId&&M.includes(Q$.menuId))L.set(Q$.menuId,Q$);if(!L.size)continue;let y=M.filter((Q$)=>L.get(Q$)?.available),P$=[...L].filter(([Q$,Z$])=>(y.includes(Q$)||!y.length)&&Z$.basePrice!=null).map(([,Q$])=>Q$.discountPrice??Q$.basePrice);A.set(w._id,{id:w._id,nombre:jC(w.name),cats:w.categoriesIds,desc:w.descriptionLength||0,fotos:w.photos||0,ancho:w.firstPhotoWidth||0,menus:M.filter((Q$)=>L.has(Q$)),dispEn:y,disponible:y.length>0,precio:P$.length?Math.min(...P$):null,descuento:y.some((Q$)=>L.get(Q$)?.discountPrice!=null),obligatorios:w.mandatoryModifiers||0,u:V.get(w._id)?.u??0})}let x=[...A.values()].filter((w)=>w.disponible),r=new Map,W$=new Set([...A.keys(),...V.keys()]);for(let w of w$([...W$],(L)=>[O(L)])){let L=w===null?void 0:A.get(w),y=V.get(w),P$=L?.nombre||jC(y?.nom)||O(w),Q$=h$(P$),Z$=r.get(Q$)??{nombre:P$,ids:[],u:0,v:0,enMenu:!1,disponible:!1,p:null};Z$.ids.push(w),Z$.u+=y?.u??0,Z$.v+=y?.v??0,r.set(Q$,Z$)}for(let w of r.values()){let L=w$(w.ids.flatMap((y)=>y!==null&&A.has(y)?[A.get(y)]:[]),(y)=>[!y.disponible,-y.u,y.id]);if(w.enMenu=L.length>0,w.disponible=L.some((y)=>y.disponible),w.p=L[0]??null,w.p)w.nombre=w.p.nombre}let o=w$([...r.values()].filter((w)=>w.u>0),(w)=>[-w.u,-w.v,h$(w.nombre)]),z=C0(o,(w)=>w.u),d=o.slice(0,10),p=o.length>=5?o[4].u:o.length?o.at(-1).u:0,K=new Set(o.filter((w)=>w.u>=p).map((w)=>h$(w.nombre))),S=(w)=>r.get(h$(w))?.u??0,s=new Map($.paidOrdersByStore.map((w)=>[w.storeId??null,w.orders])),D=w$($.stores.filter((w)=>w.acceptDelivery||w.acceptGo).map((w)=>({id:w._id,nombre:jC(w.name),horas:aj(w.openPeriods),delivery:w.acceptDelivery,retiro:w.acceptGo,programados:w.acceptSchedulingOrders,sinPedidosInmediatos:w.disableNowOrders,preparacion:w.currentPreparationDuration??null,pedidos:s.get(w._id)??0})),(w)=>[-w.pedidos,w.nombre]),c=new Map(D.map((w)=>[w.id,w.nombre])),_=new Map($.outOfStock.map((w)=>[w.productId??null,{locales:w.storeIds.filter((L)=>c.has(L)).map((L)=>c.get(L)).sort(),desde:(w.since||"").slice(0,10)}])),k=new Map($.categories.map((w)=>[w._id,w])),T=w$([...k.values()],(w)=>[((w.parentId?k.get(w.parentId):void 0)??w).index||0,w.parentId?1:0,w.index||0,w._id]),l=[],i=new Map;for(let w of M){let L=x.filter((Z$)=>Z$.dispEn.includes(w)),y=C0(L,(Z$)=>I(Z$.id,w)),P$=[];for(let Z$ of T){let A$=L.filter((v0)=>v0.cats.includes(Z$._id));if(!A$.length)continue;let GC=C0(A$,(v0)=>I(v0.id,w));P$.push({id:Z$._id,nombre:jC(Z$.name),productos:A$.length,u:GC,sub:Boolean(Z$.parentId),pos:P$.length+1,share:y?GC/y:null})}for(let Z$ of P$)i.set(JSON.stringify([w,Z$.id]),Z$);let Q$=H.get(w);l.push({id:w,nombre:jC(Q$?.name)||"sin nombre",pedidos:F.get(w)??0,pedidosPct:X?(F.get(w)??0)/X:null,horas:aj(Q$?.openPeriods??[]),productos:L.length,unidades:y,categorias:P$})}let e=d.map((w)=>{let L=w.p,y=null;if(L){let A$=L.dispEn.length?L.dispEn:L.menus,GC=w4(A$,(m0)=>[I(L.id,m0),-M.indexOf(m0)]),v0=L.cats.flatMap((m0)=>{let I0=i.get(JSON.stringify([GC,m0]));return I0?[I0]:[]});if(v0.length){let m0=v0.reduce((I0,U1)=>U1.pos<I0.pos?U1:I0);y={nombre:m0.nombre,pos:m0.pos,menu:l.find((I0)=>I0.id===GC).nombre}}}let P$=[...new Set(w.ids.flatMap((A$)=>_.get(A$)?.locales??[]))].sort(),Q$=w.ids.map((A$)=>_.get(A$)?.desde).filter((A$)=>Boolean(A$)).sort()[0],Z$=w.ids.flatMap((A$)=>A$!==null&&A.get(A$)?.disponible?[A.get(A$)]:[]);return{nombre:w.nombre,u:w.u,share:z?w.u/z:null,cargas:Z$.length,menusDistintos:new Set(Z$.flatMap((A$)=>A$.dispEn)).size,enMenu:w.enMenu,disponible:w.disponible,foto:Boolean(L?.fotos),ancho:L?L.ancho:null,desc:L?.desc??0,precio:L?.precio??null,categoria:y,obligatorios:L?.obligatorios??0,agotadoEn:P$,agotadoDesde:P$.length?Q$||null:null}}),F$=[];for(let w of $.homeComponents){if(w.componentTypeId!=="productShowcase")continue;for(let L of w.productsIds){let y=A.get(L);F$.push({nombre:y?y.nombre:null,disponible:Boolean(y?.disponible),entreLos5:Boolean(y&&K.has(h$(y.nombre))),u:y?S(y.nombre):0})}}let K$=(w)=>{let L=new Map;for(let y of w)if(!L.has(h$(y.nombre)))L.set(h$(y.nombre),y.nombre);return w$([...L.values()].map((y)=>({nombre:y,u:S(y)})),(y)=>[-y.u,h$(y.nombre)])},$$=x.filter((w)=>w.fotos),y$=x.filter((w)=>w.desc>=15),M0=$.app;return{periodo:{desde:$.periodFrom.slice(0,10),hasta:$.periodTo.slice(0,10),dias:D$},sitio:C,opciones:{menuVersion:q?.menuLayout??null,checkoutVersion:q?.checkoutLayout??null,preciosOcultosHastaElegirLocal:Boolean(q?.dontShowPricesUntilStoreSelected),ocultaNoDisponibles:Boolean(q?.hideNotAvailableProducts),pedidoMinimo:q?.minimumOrderPrice||0,cuponDestacado:Boolean(q?.hasFeaturedCoupon),pideTelefonoVerificado:Boolean(q?.requestVerifiedPhoneToCreateOrders),entregas:q?.deliveryTypes??[],pagosExtra:q?.extraPaymentTypes??[],puntosActivo:Boolean(q?.loyaltyActive)},identidad:{descripcion:(q?.description||"").trim()||null,resenas:q?.reviewCount||0,nota:q?.reviewRating??null,notaDelivery:q?.reviewDeliveryRating??null,redes:$.footerSocialNetworks,seoTituloAdmin:$.seoTitle??null,seoDescripcionAdmin:$.seoDescription??null},portada:{componentes:$.homeComponents.map((w)=>w.componentTypeId??null),vitrina:F$.length?F$:null,de5EnVitrina:F$.length?new Set(F$.filter((w)=>w.entreLos5).map((w)=>h$(w.nombre))).size:null,empatadosEn5:K.size},pedidos:{porFuente:j,digitales:X,intentos:G,webMovil:C0(W.filter((w)=>w.mobile),(w)=>w.orders),webTotal:C0(W,(w)=>w.orders),appPct:X?(j.app??0)/X:0,aprobacionPorTramo:Object.fromEntries([...Y].map(([w,L])=>[w,L.map(([y,P$])=>[y?M1(P$/y,4):null,y])])),webTresMeses:$.webThreeMonths?{intentos:$.webThreeMonths.attempts,aprobados:$.webThreeMonths.approved}:null},menu:{origen:U,menus:l,productos:x.length,enMenu:A.size,noDisponibles:K$([...A.values()].filter((w)=>!w.disponible&&!r.get(h$(w.nombre))?.disponible)),conFoto:$$.length,conDescripcion:y$.length,conDescuento:x.filter((w)=>w.descuento).length,fotoPct:x.length?$$.length/x.length:null,descripcionPct:x.length?y$.length/x.length:null,categorias:new Set(x.flatMap((w)=>w.cats.filter((L)=>k.has(L)))).size,unidades:z,productosVendidos:o.length,nombresDistintos:new Set(x.map((w)=>h$(w.nombre))).size,sinVentas:w$([...r.values()].filter((w)=>w.disponible&&!w.u).map((w)=>{let L=w.p.cats.find((y)=>k.has(y));return{nombre:w.nombre,categoria:L?jC(k.get(L)?.name):null}}),(w)=>[w.categoria||"zz",h$(w.nombre)]),sinFoto:K$(x.filter((w)=>!w.fotos)),fotoChica:K$(x.filter((w)=>w.fotos&&w.ancho<600)),sinDescripcion:K$(x.filter((w)=>w.desc<15)),vendidosNoDisponibles:o.filter((w)=>!w.disponible).map((w)=>({nombre:w.nombre,u:w.u,enMenu:w.enMenu})),top10Share:z?C0(d,(w)=>w.u)/z:null},masVendidos:e,locales:D,app:M0?{codigo:M0.appCode??null,ios:M0.iosURL??null,android:M0.androidURL??null,descargasIos:M0.iosDownloads??null,descargasAndroid:M0.androidDownloads??null,descargasLeidas:M0.downloadsReadAt||null,quitadaTemporalmente:M0.temporarilyRemoved}:null}}function o$($,C=2){return z$($,C).replace(".",",")}function oj($){return $==null?"s/d":m(v($))}function P4($,C,q){let Q=[],J=(D,c,_,k=0)=>{Q.push({nivel:D,texto:c,quien:_,peso:M1(k||0,4)})},{sitio:j,opciones:G,menu:W,pedidos:Z,masVendidos:X}=C,Y=q.porcentajes||{},H=C.locales.length||1,F=(D)=>C0(D,(c)=>c.share||0);if(j.ok===!1)J(1,`El sitio no está operativo: ${j.detalle}.`,cC,1);if(W.productos===0)J(1,"El menú online no tiene productos disponibles.",B$,1);let M=X.filter((D)=>!D.disponible);if(M.length){let D=M.length;J(1,`${D} de sus 10 más vendidos de los últimos ${D$} días hoy no se puede${J$(D,"","n")} pedir en el menú online: `+`${M.map((c)=>c.nombre).join(", ")}. Hace${J$(D,"","n")} ${N(F(M))} de las unidades. Suele ser una promoción que terminó: mira el nombre.`,B$,F(M))}let U=X.filter((D)=>D.disponible&&D.agotadoEn.length&&(H<=3||D.agotadoEn.length/H>=0.25));if(U.length)J(1,"Más vendidos marcados como agotados en este momento: "+U.map((D)=>`${D.nombre} en ${D.agotadoEn.length} de ${H} locales (${D.agotadoEn.slice(0,4).join(", ")}${D.agotadoEn.length>4?"…":""}`+(D.agotadoDesde?`; marcado desde el ${CC(D.agotadoDesde)}`:"")+")").join("; ")+".",B$,F(U));let R=C.locales.filter((D)=>D.sinPedidosInmediatos);if(R.length){let D=R.length;J(1,`${D} local${J$(D,"","es")} no acepta${J$(D,"","n")} pedidos para ahora, solo programados: ${R.slice(0,8).map((c)=>c.nombre).join(", ")}.`,B$)}if(j.total&&j.total>=3)J(2,`La portada tardó ${o$(j.total,1)} segundos en responder en esta medición (una sola medición; repite antes de afirmarlo).`,cC);if(G.preciosOcultosHastaElegirLocal)J(2,`No muestra precios hasta que el cliente elige local. Lo tiene así el ${N(Y.preciosOcultosHastaElegirLocal)} de las marcas.`,b$);if(G.pideTelefonoVerificado)J(2,`Pide verificar el teléfono antes de comprar. Lo pide el ${N(Y.pideTelefonoVerificado)} de las marcas.`,B$);let E=q.aprobacionPct;for(let D of Kq){let c=Z.intentos[D];if(c&&E&&c.intentos>=30&&c.aprobados/c.intentos<E.p25)J(2,`En ${P1[D]}, ${N(c.aprobados/c.intentos)} de los ${m(c.intentos)} intentos de compra de ${D$} días terminó con pago aprobado. `+`El cuartil bajo de la cartera es ${N(E.p25)} y la mediana ${N(E.p50)}. La serie por tramos del bloque de embudo dice si es de siempre o un cambio.`,cC)}let V=X.filter((D)=>D.obligatorios>=4);if(V.length)J(2,`Más vendidos con 4 o más elecciones obligatorias antes de agregar al carro: ${V.map((D)=>`${D.nombre} (${D.obligatorios})`).join(", ")}.`,B$,F(V));let I=C.portada,A=I.componentes,x=A.includes("redirect");if(A.length&&!A.some((D)=>D&&Z4.has(D))&&!x)J(3,`La portada no muestra productos ni categorías. Los muestra el ${N(Y.vitrinaEnPortada)} de las marcas.`,b$);if(I.vitrina&&!x){let D=I.vitrina.filter((c)=>!c.disponible);if(D.length){let c=D.flatMap((T)=>T.nombre?[T.nombre]:[]),_=D.length-c.length,k=c.slice(0,6).join(", ")+(_?`${c.length?" y ":""}${_} que ya no existe${J$(_,"","n")} en el menú online`:"");J(3,`La vitrina de la portada tiene ${D.length} de ${I.vitrina.length} productos que hoy no se pueden pedir: ${k}.`,b$)}if(X.length&&W.unidades>=30&&(I.de5EnVitrina??0)<=1){let c=I.de5EnVitrina??0;J(3,`De sus 5 productos más vendidos, ${c} está${J$(c,"","n")} en la vitrina de la portada`+(I.empatadosEn5>5?` (hay empate en el quinto lugar, así que se miraron los ${I.empatadosEn5} primeros)`:"")+".",b$)}}if(W.unidades>=50)for(let D of W.menus){let c=D.categorias.filter((T)=>!T.sub);if(!c.length||D.unidades<50||(D.pedidosPct||0)<0.2)continue;let _=W.menus.length>1?` del menú ${D.nombre}`:"",k=w$(c.filter((T)=>T.pos>3&&(T.share||0)>=0.2),(T)=>[-T.u,T.pos]).slice(0,2);for(let T of k)J(3,`La categoría ${T.nombre}${_} hace ${N(T.share)} de las unidades de ese menú y está en la posición ${T.pos} de ${D.categorias.length}.`,b$,T.share??0);if((c[0].share||0)<0.05&&c.length>=4)J(3,`La primera categoría${_}, ${c[0].nombre}, hace ${N(c[0].share,1)} de las unidades de ese menú.`,b$)}let r=X.filter((D)=>D.enMenu&&!D.foto);if(r.length){let D=r.length;J(3,`${D} de sus 10 más vendidos no tiene${J$(D,"","n")} foto: ${r.map((c)=>c.nombre).join(", ")}. Hace${J$(D,"","n")} ${N(F(r))} de las unidades.`,B$,F(r))}let W$=X.filter((D)=>D.foto&&(D.ancho||0)<600);if(W$.length){let D=W$.length;J(3,`${D} de sus 10 más vendidos tiene${J$(D,"","n")} una foto de menos de 600 px de ancho: ${W$.map((c)=>c.nombre).join(", ")}.`,B$,F(W$))}let o=X.filter((D)=>D.enMenu&&D.desc<15);if(o.length){let D=o.length;J(3,`${D} de sus 10 más vendidos no tiene${J$(D,"","n")} descripción: ${o.map((c)=>c.nombre).join(", ")}. Hace${J$(D,"","n")} ${N(F(o))} de las unidades.`,b$,F(o))}let{fotoPct:z,descripcionPct:d,productos:p}=q;if(W.productos&&z&&W.fotoPct<z.p25)J(4,`${N(W.fotoPct)} de sus productos tiene foto (${W.productos-W.conFoto} sin foto). El cuartil bajo de la cartera es ${N(z.p25)} y la mediana ${N(z.p50)}.`,B$);if(W.productos&&d&&W.descripcionPct<d.p25)J(4,`${N(W.descripcionPct)} de sus productos tiene descripción (${W.productos-W.conDescripcion} sin descripción). El cuartil bajo de la cartera es ${N(d.p25)} y la mediana ${N(d.p50)}.`,b$);if(W.conFoto&&W.fotoChica.length/W.conFoto>=0.2)J(4,`${W.fotoChica.length} de sus ${W.conFoto} fotos miden menos de 600 px de ancho.`,B$);if(W.nombresDistintos>=15&&W.unidades>=50&&W.sinVentas.length/W.nombresDistintos>=0.4)J(4,`${W.sinVentas.length} de sus ${W.nombresDistintos} productos disponibles (${N(W.sinVentas.length/W.nombresDistintos)}) no vendieron ninguna unidad en ${D$} días por sus canales digitales.`+(p&&W.productos>p.p75?` Su menú tiene ${W.productos} productos; el cuartil alto de la cartera es ${v(p.p75)}.`:""),B$);let K=C.identidad,S=q.nota;if(K.resenas>=30&&K.nota!=null&&S&&K.nota<S.p25)J(5,`Nota ${o$(K.nota)} de 5`+(K.resenas>=100?" en sus últimas 100 reseñas":` en ${K.resenas} reseñas`)+`. La mediana de la cartera es ${o$(S.p50)} y el cuartil bajo ${o$(S.p25)}.`,B$);if(j.ok&&!j.descripcion)J(5,"La portada no entrega una descripción para buscadores.",b$);if(j.ok&&!j.imagenCompartir)J(5,"Al compartir el enlace del sitio no aparece una imagen.",b$);if(!K.redes.includes("instagram"))J(5,`El pie del sitio no enlaza a su Instagram. Lo enlaza el ${N(Y.instagram)} de las marcas.`,b$);if(G.menuVersion&&G.menuVersion!=="v2")J(5,`Usa la versión anterior del menú. El ${N(Y.menuVersionActual)} de las marcas ya está en la actual.`,b$);let s=C.app;if(s){if(s.quitadaTemporalmente)J(6,"La app figura quitada temporalmente de las tiendas.",cC);else if(Z.digitales>=30&&(Z.porFuente.app??0)===0)J(6,`Tiene app propia publicada y no registró pedidos por la app en ${D$} días.`,B$)}else if(($.productos?.activos||[]).includes("appPropia"))J(6,"La ficha la muestra usando app propia, pero no hay una app activa registrada.",cC);return w$(Q,(D)=>[D.nivel,-D.peso])}function c0($,C,q,Q){if(q||$.length<=C)return $.map(Q).join(", ");return`${$.slice(0,C).map(Q).join(", ")} y ${$.length-C} más (lista entera con --completo)`}function M4($,C,q,Q,J){let j=[`AUDITORÍA WEB · ${$.marca} [${$.websiteId}] · ${$.pais} · ${$.url||"sin dominio"}`,`ASIGNACIÓN (planilla de asignación del intra): ${v$($)} · canal de ejecución: ${NC($,C)}`,`SEGMENTO (reporte de segmentos del intra): rubro ${u(_0,$.rubro,$.rubro||"s/d")}, ${y0($)}`,`RUTA DEL ÁRBOL: ${u(s$,$.ruta.codigo,$.ruta.codigo)} — ${$.ruta.motivo}.`],G=x0($,!0);if(j.push(...G.length?G:["Perfil de onboarding: no tiene uno registrado."]),J.length)for(let W of J){let Z=W.lineaBase||{},X=[Z.conversion!=null?`conversión ${n(Z.conversion,"pct")}`:null,Z.fotoPct!=null?`${N(Z.fotoPct)} de productos con foto`:null,Z.descripcionPct!=null?`${N(Z.descripcionPct)} con descripción`:null,Z.nrSemanalUSD!=null?`${B(Z.nrSemanalUSD)} de net revenue por semana`:null].filter(Boolean).join(", ");j.push(`AUDITORÍA ANTERIOR (semana ${q$(W.semana)}, ${W.por||"s/d"}): ${W.decision} — ${W.nota||"sin nota"}.`+(X?` Entonces: ${X}.`:""))}else j.push("Auditoría anterior: no hay ninguna registrada.");return j.push(S$(C)),j.push("Menú, configuración y ventas leídos en vivo hoy; se mueven durante el día, así que dos corridas separadas pueden diferir en unas pocas unidades. "+`Ventas: últimos ${D$} días (${Q.periodo.desde} a ${Q.periodo.hasta}), pedidos con pago aprobado y sin cancelar, por sitio web, app propia y Justo App.`),j.push(Z1(q)),j}function K4($,C,q,Q){let J=C.pedidos,j=$.benchmark,G=J.appPct>=BC,W=C0(Object.values(J.porFuente),(F)=>F),Z=[`
|
|
1527
|
+
1. EMBUDO`];if(W)Z.push(` Pedidos de los últimos ${D$} días por canal: `+w$(Object.entries(J.porFuente),([F,M])=>[-M,F]).map(([F,M])=>`${u(P1,F,F)} ${m(M)} (${N(M/W)})`).join(", ")+".");else Z.push(` No registró pedidos con pago aprobado en los últimos ${D$} días.`);if(G)Z.push(` OJO: ${N(J.appPct)} de sus pedidos digitales entra por la app propia. Su vitrina principal es la app. La conversión de abajo mide solo el sitio web: `+"sale baja porque sus clientes compran en la app, y la brecha no se debe leer como venta perdida.");else if(W&&J.digitales/W<0.3)Z.push(` OJO: solo ${N(J.digitales/W)} de sus pedidos entra por canales digitales propios. La pregunta de fondo no es qué arreglar del sitio, sino por qué sus clientes no piden por ahí.`);if(j&&a(j)){let F=j.metricas?.conversion||{},M=j.tresMeses?.visitas||0,U=F.valor!=null&&F.p50!=null;if(Z.push(` Reporte de segmentos, ${F0(j.periodo)}, solo sitio web directo: ${m(M)} visitas en los 3 meses (${m(v(M/3))} al mes)`+(U?`; convierte ${n(F.valor,"pct")} contra ${n(F.p50,"pct")} de mediana de sus pares (${O(F.posicion)}; ${O(F.pares)} marcas de su rubro ${u(O0,F.alcance,"")}`+(F.alcance==="city"&&j.segmento?.ciudad?`, ${j.segmento.ciudad}`:"")+`; rubro del reporte: ${j.segmento?.rubro||"s/d"}).`:"; sin conversión comparable.")),Q?.corregida)Z.push(` ${G1(Q)}`);if(Q&&Q.pedidosMes>=1)Z.push(` Brecha: le faltan ${m(v(Q.pedidosMes))} pedidos al mes para convertir como la mediana de sus pares, ${B(Q.ventaUSD)} de venta`+(Q.ventaActualUSD!=null?` (hoy vende ${B(Q.ventaActualUSD)} al mes online)`:"")+". Es una estimación, no un pronóstico."+(G?" Con app propia fuerte, no la uses.":""));else if(Q)Z.push(" Brecha: ninguna; convierte igual o mejor que la mediana de sus pares.");else Z.push(` Brecha: no se puede estimar (menos de ${OC} visitas en 3 meses, o sin pares suficientes).`);let R=[["recompra90","recompra a 90 días","pct"],["ticket","ticket","usd0"]].flatMap(([E,V,I])=>{let A=j.metricas?.[E]||{};return A.valor!=null&&A.p50!=null?[`${V} ${n(A.valor,I)} contra ${n(A.p50,I)} de mediana (${O(A.posicion)})`]:[]});if(R.length)Z.push(` También contra sus pares: ${R.join("; ")}. No son del sitio: quedan para el plan de activación.`)}else Z.push(" La marca no aparece en el reporte de segmentos: no hay visitas ni conversión contra pares.");let X=q.aprobacionPct;for(let F of Kq){let M=J.intentos[F];if(!M?.intentos)continue;let U=(J.aprobacionPorTramo[F]||[]).filter(([,E])=>E),R=U.map(([,E])=>E);Z.push(` Intentos de compra en ${P1[F]}: ${m(M.intentos)}; con pago aprobado ${m(M.aprobados)} (${N(M.aprobados/M.intentos)})`+(X&&F==="web"?`; en la cartera, mediana ${N(X.p50)} y cuartil bajo ${N(X.p25)}`:"")+"."+(U.length>=4&&M.intentos>=30?` Por tramos de 7 días, del más antiguo al más reciente: ${U.map(([E])=>N(E)).join(", ")} (intentos por tramo: ${Math.min(...R)} a ${Math.max(...R)}).`:""))}let Y=J.webTresMeses,H=j?.tresMeses?.visitas||0;if(j&&a(j)&&Y?.intentos&&H>=OC&&!G)Z.push(` Dónde se pierde (${F0(j.periodo)}, el mismo período de la conversión): de cada 100 visitas al sitio, cerca de ${o$(100*Y.intentos/H,1)} llegaron a intentar comprar y ${o$(100*Y.aprobados/H,1)} terminaron pagando (${m(Y.intentos)} intentos, ${m(Y.aprobados)} pagados). Lo que pasa entre la visita y el intento de compra no tiene datos: solo se ve mirando el sitio.`);if(J.webTotal)Z.push(` Pedidos del sitio web hechos desde un teléfono: ${N(J.webMovil/J.webTotal)} de ${m(J.webTotal)}.`);return Z}function A4($,C,q){let{sitio:Q,opciones:J}=C,j=[`
|
|
1528
|
+
2. SITIO Y COMPRA`],G=Q.total!=null?` · respondió en ${o$(Q.total,1)} s, pedida como un teléfono`:"";if(j.push(` Sitio: ${Q.url||$.url||"sin dominio"} → ${Q.detalle}${G}.`),Q.ok)j.push(` Lo que ve un buscador o quien recibe el enlace · título: ${Q.titulo||"ninguno"} · descripción: ${Q.descripcion||"ninguna"} · imagen: ${Q.imagenCompartir?"sí":"no"}`);let W=C.identidad,Z=` · redes en el pie del sitio: ${W.redes.join(", ")||"ninguna"}`;if(W.resenas)j.push(` Reseñas: nota ${W.nota!=null?o$(W.nota):"s/d"} de 5`+(W.notaDelivery!=null?` (la entrega, ${o$(W.notaDelivery)})`:"")+(W.resenas>=100?" en sus últimas 100 reseñas":` en ${W.resenas} reseñas`)+(q.nota?`; en la cartera, mediana ${o$(q.nota.p50)} y cuartil bajo ${o$(q.nota.p25)}`:"")+Z);else j.push(` Reseñas: todavía no tiene${Z}`);let X=C.portada.componentes,Y=X.includes("redirect");j.push(" Portada, bloques en orden: "+(X.length?X.map((F)=>u(X4,F,O(F))).join(" → "):"sin bloques propios")+"."+(Y?' Con "envío directo al menú", quien entra al sitio cae en el menú y no ve los otros bloques.':""));let H=C.portada.vitrina;if(H)j.push(` Vitrina de la portada (${H.length} productos; entre paréntesis, unidades vendidas en ${D$} días): `+H.map((F)=>`${F.nombre||"producto que ya no existe"} (${m(v(F.u))}${F.disponible?"":", hoy no se puede pedir"})`).join(", ")+`. Incluye ${O(C.portada.de5EnVitrina)} de sus 5 más vendidos.`+(Y?" Como el sitio envía directo al menú, esta vitrina no la ve quien entra por la portada: no se marca.":""));return j.push(` Opciones de compra: menú en la versión ${J.menuVersion==="v2"?"actual":"anterior"}; precios ${J.preciosOcultosHastaElegirLocal?"ocultos hasta elegir local":"visibles desde el inicio"}; `+`pedido mínimo ${J.pedidoMinimo?`${oj(J.pedidoMinimo)} (moneda local)`:"no tiene"}; verificación de teléfono ${J.pideTelefonoVerificado?"sí":"no"}; entregas ${J.entregas.map((F)=>u(F1,F,F)).join(", ")||"s/d"}; los productos apagados ${J.ocultaNoDisponibles?"se ocultan":"quedan a la vista como no disponibles"}.`),j}function U4($,C){let q=$.menu,Q=q.menus.length>1,J=[`
|
|
1529
|
+
3. MENÚ ONLINE`];if(J.push(` Menú auditado (${q.origen}): `+(q.menus.map((W)=>W.nombre+(Q&&W.pedidosPct!=null?` (${N(W.pedidosPct)} de los pedidos)`:"")).join("; ")||"no se identificó")+(Q?". Como son varios menús, las categorías y sus posiciones van por separado para cada uno.":".")),q.productos){let W=q.noDisponibles.length;J.push(` ${q.productos} productos disponibles`+(q.nombresDistintos<q.productos?` (${q.nombresDistintos} nombres distintos: hay productos cargados en más de un menú)`:"")+` en ${q.categorias} categorías. Con foto ${q.conFoto} (${N(q.fotoPct)}); con descripción ${q.conDescripcion} (${N(q.descripcionPct)}); fotos de menos de 600 px ${q.fotoChica.length}; con descuento ${q.conDescuento}. Aparte, ${W} producto${J$(W)} apagado${J$(W)} en el menú.`),J.push(` Ventas: ${m(v(q.unidades))} unidades de ${q.productosVendidos} productos`+(q.top10Share!=null?`; los 10 más vendidos hacen ${N(q.top10Share)} de las unidades`:"")+`; ${q.sinVentas.length} disponible${J$(q.sinVentas.length)} sin ninguna venta en el período.`)}if($.masVendidos.length&&q.unidades<30)J.push(` Con ${m(v(q.unidades))} unidades en ${D$} días por canales digitales, el orden de los más vendidos no dice mucho: mira el menú por lo completo que está, no por lo que vende.`);if($.masVendidos.length)J.push(" Los 10 más vendidos (unidades · % de las unidades · categoría y su posición · foto · descripción · precio en moneda local · elecciones obligatorias). "+"Un producto cargado más de una vez se suma por nombre; los empates se ordenan por venta y después por nombre:"),$.masVendidos.forEach((W,Z)=>{let X=W.disponible?"":W.enMenu?" · HOY NO SE PUEDE PEDIR":" · YA NO ESTÁ EN EL MENÚ ONLINE",Y=!W.foto?"sin foto":(W.ancho||0)<600?`foto chica (${O(W.ancho)} px)`:"con foto",H=W.desc<15?"sin descripción":`descripción de ${W.desc} caracteres`,F=W.categoria?`${W.categoria.nombre} (posición ${W.categoria.pos}${Q?` en ${W.categoria.menu}`:""})`:"sin categoría visible",M=W.agotadoEn.length?` · agotado en ${W.agotadoEn.length} de ${$.locales.length} locales`+(W.agotadoDesde?` desde el ${CC(W.agotadoDesde)}`:""):"",U=W.cargas<=1?"":W.menusDistintos>=W.cargas?` (en ${W.menusDistintos} menús)`:` (cargado ${W.cargas} veces)`;J.push(` ${String(Z+1).padStart(2)}. ${W.nombre}${U} · ${m(v(W.u))} · ${N(W.share)} · ${F} · ${Y} · ${H} · `+`${W.precio?oj(W.precio):"precio según opciones"} · ${W.obligatorios} obligatoria${J$(W.obligatorios)}${M}${X}`)});for(let W of q.menus){if(!W.categorias.length)continue;J.push(` Categorías${Q?` del menú ${W.nombre}`:""}, en el orden del sitio (${W.productos} productos, ${m(v(W.unidades))} unidades). `+`Cada fila: productos disponibles · % de las unidades${Q?" de este menú":""} (un producto en dos categorías cuenta en ambas):`);for(let Z of C?W.categorias:W.categorias.slice(0,20)){let X=Z.u&&(Z.share||0)<0.005?"menos de 1%":N(Z.share);J.push(` ${String(Z.pos).padStart(2)}. ${Z.sub?" ":""}${Z.nombre} · ${Z.productos} · ${X}`)}if(!C&&W.categorias.length>20)J.push(` … y ${W.categorias.length-20} categorías más (todas con --completo).`)}let j=(W)=>`${W.nombre} (${m(v(W.u))})`;if(q.sinFoto.length)J.push(` Sin foto (${q.sinFoto.length}), por unidades vendidas: ${c0(q.sinFoto,15,C,j)}.`);if(q.fotoChica.length)J.push(` Con foto de menos de 600 px (${q.fotoChica.length}), por unidades vendidas: ${c0(q.fotoChica,15,C,j)}.`);if(q.sinDescripcion.length)J.push(` Sin descripción (${q.sinDescripcion.length}), por unidades vendidas: ${c0(q.sinDescripcion,15,C,j)}.`);if(q.sinVentas.length)J.push(` Disponibles sin ventas en ${D$} días (${q.sinVentas.length}), con su categoría: `+c0(q.sinVentas,25,C,(W)=>W.nombre+(W.categoria?` [${W.categoria}]`:""))+".");if(q.noDisponibles.length)J.push(` Apagados en el menú (${q.noDisponibles.length}), por unidades vendidas en el período: ${c0(q.noDisponibles,15,C,j)}.`);let G=q.vendidosNoDisponibles.filter((W)=>W.u>=1);if(G.length)J.push(` Vendidos en el período que hoy no se pueden pedir (${G.length}): ${c0(G,12,C,j)}.`);return J}function R4($,C){let q=$.locales,Q=[`
|
|
1530
|
+
4. LOCALES`];if(!q.length)return Q.push(" No se encontraron locales habilitados para vender online."),Q;let J=(M)=>String(M).replace(".",","),j=q.flatMap((M)=>M.horas!=null?[M.horas]:[]).sort((M,U)=>M-U),G=q.filter((M)=>M.horas==null).length,W=q.flatMap((M)=>M.preparacion?[M.preparacion]:[]).sort((M,U)=>M-U),Z=q.filter((M)=>M.pedidos),X=q.filter((M)=>!M.pedidos),Y=q.length;Q.push(` ${Y} local${J$(Y,"","es")} habilitado${J$(Y)} para vender online; ${Z.length} con pedidos digitales en ${D$} días`+(X.length?`. Sin pedidos: ${c0(X.map((M)=>M.nombre),10,C,(M)=>M)}`:"")+".");let H=j[0],F=j.at(-1);return Q.push(" Contexto, sin referencia de cartera: horas abiertas a la semana "+(j.length?H===F?J(H):`de ${J(H)} a ${J(F)}`:"sin dato")+(G&&j.length?` (${G} sin horario cargado)`:"")+(W.length?W[0]===W.at(-1)?`; preparación declarada ${W[0]} minutos`:`; preparación declarada de ${W[0]} a ${W.at(-1)} minutos`:"")+`; aceptan pedidos programados ${q.filter((M)=>M.programados).length} de ${Y}; con delivery ${q.filter((M)=>M.delivery).length}, con retiro ${q.filter((M)=>M.retiro).length}.`),Q.push(" No se ve desde aquí si un local está apagado en este momento, ni sus zonas y costos de reparto."),Q}function z4($){let C=$.app,q=[`
|
|
1531
|
+
5. APP PROPIA`];if(!C)return q.push(" La marca no tiene app propia activa. Proponerla es materia del plan de activación, no de esta auditoría."),q;let Q=$.pedidos.porFuente.app??0,J=C0(Object.values($.pedidos.porFuente),(j)=>j);return q.push(` Activa. App Store: ${C.ios||"sin enlace"} · Google Play: ${C.android||"sin enlace"}`),q.push(` Pedidos por la app en ${D$} días: ${m(Q)}`+(J?` (${N(Q/J)} del total)`:"")+". Descargas registradas: "+(C.descargasIos!=null||C.descargasAndroid!=null?`iPhone ${m(C.descargasIos||0)}, Android ${m(C.descargasAndroid||0)} (dato del ${O(C.descargasLeidas)}; puede estar desactualizado).`:"sin dato.")),q.push(" No existe dato de versión publicada, valoración en las tiendas ni usuarios activos. Eso se mira en las fichas de App Store y Google Play (enlaces de arriba). "+"La app por dentro no se puede auditar desde aquí."),q}function _4($){let C=[`
|
|
1532
|
+
6. PARA REVISAR — ${$.length} punto${J$($.length)} que salen de reglas fijas, ordenados por nivel de importancia (references/criterios.md, sección 2)`];if($.forEach((q,Q)=>{C.push(` ${Q+1}. [Nivel ${q.nivel} · ${Y4[q.nivel]}] ${q.texto} → ${q.quien}.`)}),!$.length)C.push(" Ninguna regla marcó algo fuera de lo habitual.");return C.push(`
|
|
1533
|
+
Lo que este listado no ve: cómo se ve el sitio (orden visual, calidad de las fotos, textos), los pasos hasta el carro, zonas y costo de reparto, `+"y lo que pasa entre la visita y el intento de compra. Eso es la revisión visual de la skill."),C}function V4($,C){let q=C instanceof t$?C.code:void 0,Q=`No pude consultar en vivo ${$.marca}: `;if(q==="posventaAuditTimeout"||q==="clientTimeout")return`${Q}la consulta tardó demasiado y se cortó. Vuelve a intentarlo en unos minutos; si se repite, dilo en el resultado.`;let J=C instanceof Error?C.message:String(C);if(q!=="PermissionsError")return`${Q}${J}`;return[`${Q}${J}`,'La auditoría necesita el rol "kam" en team-cli para leer el menú y las ventas. Sin ese rol solo queda lo que trae la ficha: npx @getjusto/team-cli posventa ficha '+`${$.websiteId}. Dilo en el resultado.`].join(`
|
|
1534
|
+
`)}async function rj($,C){let q=await SC($);if(!q.length)return`No encontré "${$}" entre las marcas asignadas a un KAM o a Partner Experience en la planilla del intra.`;if(q.length>1)return[`Hay ${q.length} marcas que calzan con "${$}". Pregunta cuál es y vuelve a correr con el websiteId:`,...q.slice(0,15).map((F)=>` ${F.websiteId} ${O(F.marca)} · ${O(F.pais)} · ${O(F.cartera)} · ${F.url||""}`)].join(`
|
|
1535
|
+
`);let Q=q[0],J=await V$(),[j,G,W,Z]=await Promise.all([gC(J.semana),M$("acciones",{filter:{websiteId:Q.websiteId,tipo:"auditoria"},sort:{semana:-1},limit:3}),lj(Q.url),H4(Q.websiteId,Q.benchmark?.periodo).catch((F)=>F)]);if(Z instanceof Error||!Z)return V4(Q,Z);let X=F4(Z,W),Y=P4(Q,X,j),H=W1(Q,X.pedidos.webTresMeses?.aprobados);if(C.json)return JSON.stringify({marca:Q.marca,websiteId:Q.websiteId,asignacion:Q.asignacion,perfil:Q.perfil,brecha:H,referencia:j,hechos:X,paraRevisar:Y,auditoriasAnteriores:G},null,1);return[...M4(Q,J,j,X,G),...K4(Q,X,j,H),...A4(Q,X,j),...U4(X,C.completo),...R4(X,C.completo),...z4(X),..._4(Y)].join(`
|
|
1536
|
+
`)}var tj=["CL","CO","PE","MX","EC","TODOS"],V0=[["diagnostico_caida","CAÍDAS A ATENDER","ordenadas por dólares en juego por semana contra su nivel previo"],["recuperar_uso","USO QUE SE APAGÓ","usaban el producto las 4 semanas previas y esta no"],["aprovechar_impulso","CON IMPULSO","subieron sobre su nivel previo: buen momento para proponer otro producto"],["rescate","RESCATE","marcas en preChurn o que dejaron de vender online, ordenadas por lo que facturan"]],m4=["diagnostico_caida","recuperar_uso","rescate"],I4=["lanzamiento","plan_activacion","auditoria_web","ajuste_fino","lote","dormida"],D4={adq:["ventaPorVisita","usd2"],hib:["recompra90","pct"],lea:["frecuencia","num"]};function WC($,C){let q=$[C];if(q==="true")throw Error(`--${C} necesita un valor.`);return q}function $2($){let C=(WC($,"pais")||"TODOS").toUpperCase();if(!tj.includes(C))throw Error(`--pais debe ser uno de: ${tj.join(", ")}.`);let q=WC($,"top"),Q=q?Number(q):10;if(!Number.isInteger(Q)||Q<1)throw Error("--top debe ser un entero mayor que 0.");return{portfolio:WC($,"cartera"),country:C,executionChannel:WC($,"ejecucion"),tiers:WC($,"tier"),modes:WC($,"modo"),top:Q,json:$.json==="true"}}function E4($){let C=$.benchmark;if(!C||!a(C))return null;let q=[["conversion","conversión","pct"],["recompra90","recompra a 90 días","pct"],["ticket","ticket","usd0"]],Q=[];for(let[W,Z,X]of q){let Y=C.metricas[W];if(Y&&a(Y)&&Y.valor!=null&&Y.p50!=null)Q.push(`${Z} ${n(Y.valor,X)} contra ${n(Y.p50,X)} de mediana (${O(Y.posicion)})`)}if(!Q.length)return null;let J=C.segmento,j=C.potencial||{},G=(j.ventaUSD||0)>0?`; potencial ${B(j.ventaUSD,!0)} de venta al mes`:"";return`Contra sus pares (${F0(C.periodo)}; tier ${O(J.tier)}, modo ${u(a$,J.modo,"sin asignar")}): ${Q.join("; ")}${G}.`}function T4($){return[...$].sort((q,Q)=>q-Q).slice(3,5).reduce((q,Q)=>q+Q,0)/2}function L4($){let C=$.ruta?.codigo,q=$.senal||{},Q=$.semana,J=$.actual?.nrOp,j=($.semanas||[]).filter((W)=>!Q||W.s<Q),G=j.map((W)=>W.nrOp||0).slice(-12);if(J==null||G.length<12)return null;if(C==="diagnostico_caida"&&(q.racha||1)<2){let W=T4(G.slice(0,8)),Z=G.slice(-4).filter((Y)=>Y>1.2*W).length;if(W>0&&J>=0.8*W&&Z>=2)return`volvió a su nivel: venía de semanas altas y esta semana (${B(J)}) se parece a lo que hacía hace 2 o 3 meses (${B(W)} de mediana)`;let X=$.pares||{};if(X.medianaPct!=null&&X.marcaPct!=null&&X.medianaPct<0&&X.marcaPct-X.medianaPct>=-0.1)return`es mercado: cayó ${L$(X.marcaPct)} y su rubro ${L$(X.medianaPct)}`}if(C==="aprovechar_impulso"&&(q.nivelPrevioUSD||0)>0){let W=q.evidencia?.ordenesPct,Z=j.map((H)=>H.ord||0).slice(-4),X=$.actual?.ord||0;if(X>0&&X<10)return`son muy pocos pedidos para hablar de impulso (${X} en la semana)`;if(X&&Z.length===4&&Z.includes(0)&&[...Z].sort((H,F)=>H-F)[2]>0)return"su nivel previo incluye una semana sin pedidos, así que la subida es en buena parte la vuelta a lo normal";if(W!=null&&W<0.1)return`la subida no viene de más pedidos: las órdenes online variaron ${L$(W)}`;let Y=Math.max(...G);if(J<=Y)return`está dentro de lo que ya hizo: en las 12 semanas previas llegó a ${B(Y)}`}return null}function N4($,C,q,Q,J){let{senal:j,productos:G}=C,W=[`${$}. ${C.marca} [${C.websiteId}] · ${u(oq,C.fase.codigo,"")} · ${G.n} producto${G.n===1?"":"s"}: ${n$(G.activos)}`,`Asignación: ${v$(C)} · canal de ejecución: ${wq(C,J)}`,`Segmento: rubro ${u(_0,C.rubro,C.rubro||"s/d")}, ${y0(C)}`];W.push(...x0(C,!0));let Z=Q1(C);if(Z)W.push(Z);else if(C.ruta.codigo==="rescate")W.push(`Rescate: ${C.ruta.motivo}.`);let X=$1(C);if((j.racha??1)>1)X+=` · ${j.racha} semanas seguidas en caída, desde la semana ${q$(j.inicio??"")}`;if(j.causa)X+=` · causa: ${LC(j.causa)}`;if(!(a(C.sinVentaOnline)&&C.ruta.codigo==="rescate"&&!C.actual?.nrOp))W.push(X);W.push(...C1(C,!0),...q1(C));let H=E4(C);if(H)W.push(H);let F=(C.semanas||[]).slice(-13);if(F.length)W.push(`NR operativo, semanas ${q$(F[0].s)} a ${q$(F[F.length-1].s)}: ${F.map((U)=>m(v(U.nrOp))).join(", ")}`);W.push(...kC(C));let M=L4(C);if(M)W.push(`Lectura automática (por esto el aviso del lunes no la nombró): ${M}. Descártala salvo que el detalle muestre otra cosa.`);if(q>1)W.push(`Lleva ${q} semanas seguidas en el radar.`);if(Q)W.push(`Última decisión (semana ${q$(Q.semana)}): ${Q.tipo==="auditoria"?"auditoría web · ":""}${Q.decision} — ${Q.nota||"sin nota"}`);return W[0]+W.slice(1).map((U)=>`
|
|
1537
|
+
${U}`).join("")}function g4($,C){let q=new Set($.filter((j)=>m4.includes(j.ruta)).map((j)=>j.semana)),Q=0,J=KC(C)[0];while(q.has(MC(J)))Q+=1,J=AC(J,-7);return Q}function k4($){let C=$.ndr;if(!C||!a(C))return["NDR: no disponible en esta carga (no se pudo leer el tablero NDR por cartera). Dilo en el plan."];let{abierto:q,cerrado:Q}=C,J=[`NDR (leído del ${C.fuente}; net revenue total del mes contra el mes anterior, marcas con net revenue el mes anterior):`,` ${n0(H$(Q.mes))}, mes cerrado: ${T0(Q.pct)} con ${m(Q.comparables||0)} marcas comparables.`],j=` ${n0(H$(q.mes))}, proyección: ${T0(q.pct)} con ${m(q.comparables||0)} marcas comparables`;if(q.dias){if(j+=`; lleva ${q.dias} de ${q.diasMes||30} días y se proyecta al ritmo actual. Es proyección, no NDR oficial`,q.dias<10)j+=", y con tan pocos días es poco confiable"}J.push(`${j}.`);let G=(W)=>`${W.marca} (${T0(W.pct)}, ${B(W.impactoUSD,!0)}${W.estado==="churned"?", ya en churn":""})`;if(C.riesgos?.length)J.push(` Las que más restan al NDR de ${H$(q.mes)}: ${C.riesgos.map(G).join("; ")}.`);if(C.oportunidades?.length)J.push(` Las que más suman: ${C.oportunidades.map(G).join("; ")}.`);return J}function ij($){return($.auditoria?.puntos||[]).filter(eq).slice(0,3)}var ej=($,C)=>$<C?-1:$>C?1:0;async function C2($){let C=await V$(),q=C.semana,{portfolio:Q,origin:J}=await $C($.portfolio,C),j={};if(Object.hasOwn(c$,Q)){let _=c$[Q].team;if(_)j.equipo=_}else j.cartera=Q;if($.country!=="TODOS")j.pais=$.country;let G=C.ejecucion?.canales||{},W=[];if($.executionChannel){if(!Object.hasOwn(G,$.executionChannel))throw Error(`No existe el canal de ejecución "${$.executionChannel}". Canales: ${Object.keys(G).join(", ")||"ninguno cargado"}.`);j["ejecucion.canal"]=$.executionChannel,W.push(`canal de ejecución ${G[$.executionChannel].nombre}`)}if($.tiers){let _=$.tiers.split(",").map((T)=>T.trim().toUpperCase()).filter(Boolean),k=_.filter((T)=>!Object.hasOwn(Hq,T));if(k.length)throw Error(`Tier no válido: ${k.join(", ")}. Tiers: A, B, C, D, E, F.`);j.tier={$in:_},W.push(`tier ${_.join(", ")}`)}if($.modes){let _=$.modes.split(",").map((T)=>T.trim().toLowerCase()).filter(Boolean),k=_.filter((T)=>!Object.hasOwn(a$,T));if(k.length)throw Error(`Modo no válido: ${k.join(", ")}. Modos: adq, hib, lea.`);j.modo={$in:_},W.push(`modo ${_.map((T)=>a$[T]).join(", ")}`)}let Z=await d$("resumenes",{filter:{key:`${Q}|${$.country}|${q}`}});if(!Z)return[...J?[J]:[],`No hay marcas en la cartera ${S0(Q,C)} de ${$.country} para la ${UC(q)}.`].join(`
|
|
1538
|
+
`);let X=new Map,Y=await Promise.all(V0.map(([_])=>M$("fichas",{filter:{...j,"ruta.codigo":_},projection:{_id:0},limit:2000})));V0.forEach(([_],k)=>{let T=(l)=>_==="diagnostico_caida"||_==="aprovechar_impulso"?l.senal?.enJuegoUSD||0:l.peso?.nrSemanalUSD||0;X.set(_,[...Y[k]].sort((l,i)=>T(i)-T(l)||ej(l.marca,i.marca)))});let H=$.top,F=V0.flatMap(([_])=>(X.get(_)||[]).slice(0,H).map((k)=>k.websiteId)),[M,U]=F.length?await Promise.all([M$("historial",{filter:{websiteId:{$in:F}},projection:{websiteId:1,semana:1,ruta:1,_id:0},limit:5000}),M$("acciones",{filter:{websiteId:{$in:F}},sort:{semana:-1},limit:2000})]):[[],[]],R=new Map;for(let _ of M){let k=R.get(_.websiteId??"")||[];k.push(_),R.set(_.websiteId??"",k)}let E=new Map;for(let _ of U)if(!E.has(_.websiteId??""))E.set(_.websiteId??"",_);if($.json){let{_id:_,...k}=Z;return JSON.stringify({semana:q,cartera:Q,origenDeLaCartera:J,filtro:W,canalesDeEjecucion:G,resumen:k,secciones:Object.fromEntries(V0.map(([T])=>[T,(X.get(T)||[]).slice(0,H)]))},null,1)}let V=[];if(V.push(`RADAR · cartera ${S0(Q,C)} · país ${$.country}${W.length?` · solo ${W.join(" · ")}`:""}`),J)V.push(J);if(V.push(S$(C)),W.length)V.push(`FILTRO: las listas de abajo traen solo las marcas de ${W.join(" y ")}. El resumen, el NDR y el benchmark de cabecera son de la cartera completa.`);let I=oC(Z.nrOpActualUSD,Z.nrOpPreviasUSD);V.push(`
|
|
1539
|
+
RESUMEN: ${m(Z.marcas)} marcas. NR operativo ${B(Z.nrOpActualUSD)} contra ${B(Z.nrOpPreviasUSD)} de promedio en las 4 semanas previas (${B(I,!0)}, ${L$(I!=null&&Z.nrOpPreviasUSD?I/Z.nrOpPreviasUSD:null)}).`),V.push(`Aparte, fuera de la señal: ${B(Z.nrPunActualUSD)} de marketing (cobros por campaña) y ${B(Z.nrRecActualUSD)} recurrente (suscripciones; se mueve por calendario).`);let A=X.get("diagnostico_caida")||[],x=A.slice(0,H).reduce((_,k)=>_+(k.senal.enJuegoUSD||0),0);if(V.push(`${Z.marcasEnCaida} marca${Z.marcasEnCaida===1?"":"s"} en caída: ${B(Z.caidaUSD)} por semana en juego`+(A.length>H?`; las ${H} primeras concentran ${B(x)}`:"")+`. Con impulso: ${Z.marcasEnSubida??0}, que suman ${B(Z.subidaUSD)} sobre su nivel previo.`),Object.hasOwn(c$,Q)){let _=c$[Q].team,k=(C.carteras||[]).filter((T)=>(_===null||_===T.equipo)&&($.country==="TODOS"||T.paises[$.country]));V.push(`ASIGNACIÓN (planilla de asignación del intra): ${k.map((T)=>`${T.cartera} ${m($.country!=="TODOS"?T.paises[$.country]||0:T.marcas)}`).join("; ")}.`)}let r=Z.segmento;if(r&&a(r)){let _=[...Object.keys(Hq),"sin dato"].filter((T)=>r.tier[T]).map((T)=>`${T} ${m(r.tier[T])}`).join(", "),k=Object.entries(r.modo).sort((T,l)=>Number(T[0]==="sin dato")-Number(l[0]==="sin dato")||l[1]-T[1]).map(([T,l])=>`${u(a$,T,"sin etapa")} ${m(l)}`).join(", ");V.push(`SEGMENTO (reporte de segmentos del intra; describe a las marcas y va en paralelo a la asignación): por tier ${_} · por modo ${k}.`)}let W$=Z.ejecucion||{};if(a(W$)&&a(G)){V.push("CANALES DE EJECUCIÓN (salen de la asignación de cada marca, no de su segmento):");let _=V0.flatMap(([k])=>X.get(k)||[]);for(let[k,T]of Object.entries(G)){if(!Object.hasOwn(W$,k))continue;let l=_.filter((i)=>i.ejecucion?.canal===k).length;V.push(` ${T.nombre}: ${m(W$[k].marcas)} marcas de la cartera, ${l} en las listas de abajo · ${T.como} · tareas: ${T.tareas}`)}}let o=Z.perfiles||{};if(a(o))V.push("PERFIL DE ONBOARDING (lo registra el equipo en la bitácora del intra; solo marcas en puesta en marcha): "+Object.entries(o).sort((_,k)=>k[1]-_[1]).map(([_,k])=>`${_.toLowerCase()} ${k}`).join(", ")+". El perfil y la estrategia de relacionamiento de cada marca vienen en su ficha.");V.push(...k4(Z));let z=Z.benchmark;if(z&&a(z)){let _=z.conversion||{};V.push(`BENCHMARK (leído del ${z.fuente}; ${F0(z.periodo)}): ${z.marcasConPotencial} marcas con potencial suman ${B(z.potencialVentaUSD)} de venta online al mes, ${B(z.potencialJustoUSD)} para Justo, si llegaran a la mediana de sus pares. `+`En conversión, ${_.cuartilInferior??0} de ${_.conDato??0} marcas con dato están en el cuartil inferior de sus pares.`)}else V.push("BENCHMARK: no disponible en esta carga (no se pudo leer el reporte de segmentos). Dilo en el plan.");let d=Object.entries(Z.mercado||{}).sort((_,k)=>_[1].medianaPct-k[1].medianaPct);if(d.length)V.push(`Mercado esta semana (mediana de variación de cada rubro en el país, contra sus 4 semanas previas): ${d.map(([_,k])=>`${u(_0,_,_)} ${L$(k.medianaPct)}`).join(", ")}.`);for(let[_,k,T]of V0){let l=X.get(_)||[];if(V.push(`
|
|
1540
|
+
${k} — ${l.length} marca${l.length===1?"":"s"} (${T})${l.length>H?`; se detallan ${H}`:""}`),l.slice(0,H).forEach((i,e)=>{V.push(N4(e+1,i,g4(R.get(i.websiteId)||[],q),E.get(i.websiteId),C))}),l.length>H){let i=l.slice(H).map((e)=>`${e.marca} (${B(e.senal.variacionUSD,!0)}${(e.senal.racha??1)>1?`, ${e.senal.racha} semanas`:""})`);V.push(` Fuera del detalle (${i.length}; para verlas usa --top ${l.length}): ${i.slice(0,40).join("; ")}`)}}let[p,K]=await Promise.all([M$("fichas",{filter:{...j,"benchmark.potencial.justoUSD":{$gt:0}},projection:{_id:0,semanas:0},sort:{"benchmark.potencial.justoUSD":-1},limit:H}),M$("fichas",{filter:{...j,"auditoria.puntos.nivel":{$in:tq}},projection:{_id:0,semanas:0},limit:2000})]);if(p.length)V.push(`
|
|
1541
|
+
MAYOR POTENCIAL — según el reporte de segmentos (venta que sumarían al mes si llegaran a la mediana de sus pares; estimación teórica)`),p.forEach((_,k)=>{let T=_.benchmark,l=T.segmento.modo,[i,e]=l&&D4[l]||[void 0,"num"],F$=i&&T.metricas[i]||{},K$=T.potencial||{};V.push(`${k+1}. ${_.marca} [${_.websiteId}] · tier ${O(T.segmento.tier)} · modo ${u(a$,l,"s/d")} · canal de ejecución: ${wq(_,C)} · hoy en ruta: ${u(s$,_.ruta.codigo,_.ruta.codigo)}`),V.push(` ${B(K$.ventaUSD,!0)} de venta online al mes (${B(K$.justoUSD,!0)} para Justo) · palanca: ${u(B0,l,"s/d")}, ${n(F$.valor,e)} contra ${n(F$.p50,e)} de mediana de sus pares · ${m(T.tresMeses.visitas||0)} visitas en 3 meses`);let $$=T.metricas.conversion||{};if($$.valor!=null&&$$.p50!=null)V.push(` Conversión ${n($$.valor,"pct")} contra ${n($$.p50,"pct")} de mediana (${O($$.posicion)}).`);for(let y$ of kC(_))V.push(` ${y$}`)});let S=new Set([...V0.flatMap(([_])=>(X.get(_)||[]).map((k)=>k.websiteId)),...p.map((_)=>_.websiteId)]),s=(_)=>_.auditoria?.brecha?.ventaUSD||0,D=(_)=>Math.min(...ij(_).map((k)=>k.nivel))>1,c=K.filter((_)=>!S.has(_.websiteId)&&ij(_).length).sort((_,k)=>Number(D(_))-Number(D(k))||s(k)-s(_)||ej(_.marca,k.marca));if(c.length){if(V.push(`
|
|
1542
|
+
SITIO QUE FRENA LA VENTA — ${c.length} marca${c.length===1?"":"s"} (auditoría del sitio de los lunes; primero las que tienen algo que impide comprar, `+`después por la venta que les falta contra sus pares)${c.length>H?`; se detallan ${H}`:""}`),c.slice(0,H).forEach((_,k)=>{V.push(`${k+1}. ${_.marca} [${_.websiteId}] · ${_.pais} · ${v$(_)} · canal de ejecución: ${wq(_,C)} · `+`${B(_.peso?.nrSemanalUSD)} de net revenue por semana`);for(let T of kC(_))V.push(` ${T}`)}),c.length>H)V.push(` Fuera del detalle (${c.length-H}; para verlas usa --top ${c.length}): ${c.slice(H,H+40).map((_)=>_.marca).join("; ")}`)}for(let[_,k]of Object.entries(G)){if(!k.agrupa)continue;let T=new Map;for(let[l,i]of V0)for(let e of X.get(l)||[]){if(e.ejecucion?.canal!==_)continue;let F$=l==="diagnostico_caida"?LC(e.senal.causa)||"sin causa clara":l==="recuperar_uso"?`dejó de usar ${n$(e.senal.productosSinUso||[])}`:"",K$=`${i}\x00${F$}`,$$=T.get(K$)||{title:i,sub:F$,fichas:[]};$$.fichas.push(e),T.set(K$,$$)}if(!T.size)continue;V.push(`
|
|
1543
|
+
GRUPOS PARA EL CANAL ${k.nombre.toUpperCase()} — ${k.como}; una tarea por grupo, no por marca`);for(let{title:l,sub:i,fichas:e}of T.values()){let F$=e.reduce(($$,y$)=>$$+(y$.senal.enJuegoUSD||0),0),K$=e.slice(0,25).map(($$)=>`${$$.marca} [${$$.websiteId}]`).join(", ")+(e.length>25?` y ${e.length-25} más`:"");V.push(` ${n0(l)}${i?` · ${i}`:""}: ${e.length} marca${e.length===1?"":"s"}`+(F$?`, ${B(F$)} por semana`:"")+` — ${K$}`)}}V.push(`
|
|
1544
|
+
EL RESTO DE LA CARTERA (sin urgencia esta semana)`);for(let _ of I4)if(Z.rutas[_])V.push(` ${String(Z.rutas[_]).padStart(4)} · ${s$[_]}`);return V.join(`
|
|
1545
|
+
`)}var q2=["atender","descartar","resuelto"],Q2=["radar","auditoria","activacion"],S4={auditoria:"auditoría web · ",activacion:"plan de activación · "},B4='Uso: team-cli posventa registrar <websiteId> --decision atender|descartar|resuelto --nota "..." [--tipo radar|auditoria|activacion]';function J2($,C){let q=$[2],Q=(G)=>Boolean(C[G])&&C[G]!=="true",J=[q?null:"<websiteId>",Q("decision")?null:"--decision",Q("nota")?null:"--nota"].filter(Boolean);if(J.length)throw Error(`Falta ${J.join(", ")}. ${B4}`);if(!q2.includes(C.decision))throw Error(`--decision debe ser una de: ${q2.join(", ")}.`);let j=C.tipo||"radar";if(!Q2.includes(j))throw Error(`--tipo debe ser uno de: ${Q2.join(", ")}.`);return{websiteId:q,decision:C.decision,note:C.nota,type:j}}async function O4(){try{return(await h({service:"main",query:"query { me { email } }"})).me?.email??null}catch{return null}}async function j2($){let C=await d$("fichas",{filter:{websiteId:$.websiteId},projection:{marca:1,semana:1,cartera:1,pais:1,ruta:1,"peso.nrSemanalUSD":1,"sitio.menu":1,"benchmark.metricas.conversion.valor":1,"benchmark.tresMeses.visitas":1,"benchmark.periodo":1}});if(!C)throw Error(`No existe la marca ${$.websiteId} en las fichas.`);let q=new Date;q.setUTCMilliseconds(0);let Q=`${$.websiteId}|${C.semana}${$.type==="radar"?"":`|${$.type}`}`,J={key:Q,websiteId:$.websiteId,marca:C.marca,semana:C.semana,cartera:C.cartera,pais:C.pais,ruta:C.ruta.codigo,tipo:$.type,decision:$.decision,nota:$.note,por:await O4(),fecha:q};if($.type==="auditoria"){let j=C.benchmark||{},G=C.sitio?.menu||{};J.lineaBase={conversion:j.metricas?.conversion?.valor??null,visitas3m:j.tresMeses?.visitas??null,periodo:j.periodo??null,fotoPct:G.fotoPct??null,descripcionPct:G.descripcionPct??null,productos:G.productos??null,nrSemanalUSD:C.peso?.nrSemanalUSD??null}}return await e0(Yq,"acciones",{type:"updateOne",filter:{key:Q},upsert:!0,update:{$set:J}}),`Registrado: ${C.marca} · semana ${q$(C.semana)} · ${S4[$.type]??""}${$.decision} — ${$.note}`}async function W2(){return Y$(),await zj()}async function G2($){return Y$(),await C2($2($))}async function Z2($,C){return Y$(),await j2(J2($,C))}async function X2($,C){Y$();let q=$.slice(2).join(" ").trim();if(!q)throw Error('Uso: team-cli posventa ficha "<nombre, dominio o websiteId>"');return await mj(q,C.json==="true")}async function Y2($,C){Y$();let q=$[2];if(!q)throw Error("Uso: team-cli posventa detalle <websiteId>[,<websiteId>...] [--que <tablas>]");return await nj(q,sj(C))}async function H2($,C){Y$();let q=$[2];if(q==="cola")return await Sj(kj(C));if(q==="marca"){let Q=$.slice(3).join(" ").trim();if(!Q)throw Error('Uso: team-cli posventa activacion marca "<nombre, dominio o websiteId>" [--completo] [--json]');return await Bj(Q,{completo:C.completo==="true",json:C.json==="true"})}return vC()}async function w2($,C){Y$();let q=$[2];if(q==="cola")return await cj(yj(C));if(q==="marca"){let J=[...[C.completo,C.json].filter((j)=>j&&j!=="true"),...$.slice(3)].join(" ").trim();if(!J)throw Error('Uso: team-cli posventa auditoria marca "<nombre, dominio o websiteId>" [--completo] [--json]');return await rj(J,{completo:C.completo!==void 0,json:C.json!==void 0})}return vC()}function vC(){return`team-cli posventa
|
|
1546
|
+
|
|
1547
|
+
Datos de posventa (KAM y Partner Experience) para las skills marca-360, radar-semanal,
|
|
1548
|
+
plan-activacion y auditoria-web. No piden confirmación; solo registrar escribe, y solo en
|
|
1549
|
+
la colección acciones del space jorge:posventa-360.
|
|
1550
|
+
|
|
1551
|
+
Uso:
|
|
1552
|
+
team-cli posventa estado
|
|
1553
|
+
Qué semana está cargada y si está al día, quién tiene la sesión de team-cli y qué
|
|
1554
|
+
cartera le corresponde según la planilla de asignación del intra.
|
|
1555
|
+
|
|
1556
|
+
team-cli posventa radar [--cartera <cartera>] [--pais CL] [--tier A,B] [--modo adq,hib]
|
|
1557
|
+
[--ejecucion <canal>] [--top 10] [--json]
|
|
1558
|
+
Movimientos de la semana en una cartera: caídas, uso que se apagó, impulso, rescate,
|
|
1559
|
+
mayor potencial y sitio que frena la venta.
|
|
1560
|
+
--cartera TOP, Longtail, Lanzamiento, PX, KAM, TODAS o el nombre de un KAM. Sin
|
|
1561
|
+
este argumento: la cartera de quien tiene la sesión de team-cli
|
|
1562
|
+
--pais CL, CO, PE, MX, EC o TODOS (por defecto TODOS)
|
|
1563
|
+
--tier solo estos tiers del segmento, separados por coma (A a F)
|
|
1564
|
+
--modo solo estos modos del segmento, separados por coma (adq, hib, lea)
|
|
1565
|
+
--ejecucion solo las marcas de un canal de ejecución del space (hoy directo, masivo,
|
|
1566
|
+
lanzamiento; si no existe, el error lista los cargados)
|
|
1567
|
+
--top cuántas marcas detallar por lista (por defecto 10)
|
|
1568
|
+
--json datos crudos
|
|
1569
|
+
|
|
1570
|
+
team-cli posventa ficha "<nombre, dominio o websiteId>" [--json]
|
|
1571
|
+
Ficha 360 de una marca, leída del space jorge:posventa-360 que el cálculo central
|
|
1572
|
+
actualiza cada semana. Si varias marcas calzan, las lista para elegir por websiteId.
|
|
1573
|
+
Con --json entrega los datos crudos.
|
|
1574
|
+
|
|
1575
|
+
team-cli posventa detalle <websiteId>[,<websiteId>...] [--que <tablas>] [--semanas 9] [--pais CL]
|
|
1576
|
+
Consultas en vivo de una o varias marcas, en una sola llamada al servicio data.
|
|
1577
|
+
Tablas (por defecto todas): ${xC.join(", ")}.
|
|
1578
|
+
sitio si el sitio de pedidos carga y es el de Justo (lo revisa este equipo con curl)
|
|
1579
|
+
locales órdenes online por local y semana
|
|
1580
|
+
canales órdenes y ticket por canal y tipo de entrega
|
|
1581
|
+
pagos intentos de compra por estado de pago y de orden
|
|
1582
|
+
cobros net revenue por tipo de cobro (USD)
|
|
1583
|
+
soporte tickets de soporte por semana y los 20 más recientes, sin títulos
|
|
1584
|
+
Siempre muestra la fecha de la última orden online con pago aprobado.
|
|
1585
|
+
--semanas cuántas semanas mirar hacia atrás, de 1 a 26 (por defecto 9)
|
|
1586
|
+
--pais CL, CO, PE, EC o MX; solo si la marca no está en el space (define la hora de las semanas)
|
|
1587
|
+
|
|
1588
|
+
team-cli posventa registrar <websiteId> --decision atender|descartar|resuelto --nota "..."
|
|
1589
|
+
[--tipo radar|auditoria|activacion]
|
|
1590
|
+
Anota la decisión tomada con una marca en la semana cargada. Una decisión por marca,
|
|
1591
|
+
semana y tipo: registrar de nuevo la reemplaza.
|
|
1592
|
+
--tipo radar = decisión del plan semanal (por defecto); auditoria = lo acordado tras
|
|
1593
|
+
una auditoría web; activacion = el producto acordado en un plan de activación
|
|
1594
|
+
|
|
1595
|
+
team-cli posventa activacion cola [--cartera <cartera>] [--pais CL] [--top 10] [--json]
|
|
1596
|
+
A qué marcas de la cartera conviene proponerles un producto esta semana. Solo lee la carga
|
|
1597
|
+
semanal del space. Sin --cartera usa la de quien tiene la sesión (KAM: su cartera; si no,
|
|
1598
|
+
Partner Experience). --cartera acepta TOP, Longtail, Lanzamiento, PX, KAM, TODAS o el
|
|
1599
|
+
nombre de un KAM; --pais CL, CO, PE, MX, EC o TODOS.
|
|
1600
|
+
|
|
1601
|
+
team-cli posventa activacion marca "<nombre, dominio o websiteId>" [--completo] [--json]
|
|
1602
|
+
Hechos de una marca para armar su plan de activación: productos que usa mes a mes, net
|
|
1603
|
+
revenue por producto, pedidos por canal, clientes, correo, puntos, menú, lo que usan sus
|
|
1604
|
+
marcas parecidas y los productos candidatos ordenados por reglas. Una sola llamada al
|
|
1605
|
+
servicio data (menos de 45 s); si una parte no alcanza, lo dice y entrega el resto.
|
|
1606
|
+
|
|
1607
|
+
team-cli posventa auditoria cola [--cartera <cartera>] [--pais TODOS] [--top 10] [--rutas web] [--json]
|
|
1608
|
+
A qué marcas de la cartera conviene auditar primero el sitio, ordenadas por la venta que
|
|
1609
|
+
les falta para convertir como sus pares. Sin --cartera usa la de quien tiene la sesión.
|
|
1610
|
+
--cartera TOP, Longtail, Lanzamiento, PX, KAM, TODAS o el nombre de un KAM
|
|
1611
|
+
--pais CL, CO, PE, MX, EC o TODOS
|
|
1612
|
+
--rutas web (solo las que el árbol manda a auditoría web) o todas
|
|
1613
|
+
|
|
1614
|
+
team-cli posventa auditoria marca "<nombre, dominio o websiteId>" [--completo] [--json]
|
|
1615
|
+
Hechos de una marca para auditar su sitio, menú y app: embudo, sitio (lo revisa este
|
|
1616
|
+
equipo con curl), menú online y más vendidos, locales, app y los puntos para revisar.
|
|
1617
|
+
Lee menú y ventas en vivo en una sola llamada al servicio data (hasta ~45 s).
|
|
1618
|
+
--completo imprime las listas enteras; --json entrega los datos crudos.
|
|
1619
|
+
|
|
1620
|
+
Permisos: rol kam (o admin) y acceso al space jorge:posventa-360. No necesita el rol queries.
|
|
1621
|
+
|
|
1622
|
+
Ejemplos:
|
|
1623
|
+
team-cli posventa estado
|
|
1624
|
+
team-cli posventa radar --cartera Longtail --pais CL
|
|
1625
|
+
team-cli posventa registrar vS9R7SZe57sdp7Lht --decision atender --nota "Llamar al dueño"
|
|
1626
|
+
team-cli posventa ficha "La Casa de Toño"
|
|
1627
|
+
team-cli posventa detalle vS9R7SZe57sdp7Lht --que sitio,canales
|
|
1628
|
+
team-cli posventa detalle id1,id2 --que canales,soporte --semanas 12
|
|
1629
|
+
team-cli posventa activacion cola --cartera TOP --pais CL
|
|
1630
|
+
team-cli posventa activacion marca "La Casa de Toño"
|
|
1631
|
+
team-cli posventa auditoria cola --cartera TOP --pais CL
|
|
1632
|
+
team-cli posventa auditoria marca "La Casa de Toño"`}import{existsSync as A2,mkdirSync as U2,readdirSync as F2,readFileSync as y4,renameSync as x4,rmSync as bC,writeFileSync as K1}from"node:fs";import{homedir as P2}from"node:os";import{join as O$,resolve as c4}from"node:path";var M2=["posventa","partnerExperience"],R2=".team-cli-skill.json",v4=/^[a-z0-9][a-z0-9-]{0,63}$/,b4=/^[a-z0-9][a-z0-9_-]{0,59}\.md$/,z2=".team-cli-staging-";function _2($){let C=$||"posventa";if(!M2.includes(C))throw Error(`Área inválida: ${C}. Usa ${M2.join(" o ")}.`);return C}function h4($){if($.dir)return[c4($.dir)];return[O$(P2(),".claude","skills"),O$(P2(),".agents","skills")]}async function V2($){return(await h({service:"messenger",query:`query AgentSkillsForSync($area: AgentSkillArea!) {
|
|
1633
|
+
agentSkillsForSync(area: $area) {
|
|
1634
|
+
slug area name version content
|
|
1635
|
+
references { fileName content }
|
|
1636
|
+
}
|
|
1637
|
+
}`,variables:{area:$},timeoutMs:30000})).agentSkillsForSync}function K2($){let C=O$($,R2);if(!A2(C))return null;try{return JSON.parse(y4(C,"utf8"))}catch{return null}}function p4($){for(let C of $){if(!v4.test(C.slug))throw Error(`Slug inválido: ${C.slug}`);for(let q of C.references)if(!b4.test(q.fileName))throw Error(`Nombre de archivo inválido en la skill ${C.slug}: ${q.fileName}`)}}function l4($,C){let q=O$($,`${z2}${C.slug}`);bC(q,{recursive:!0,force:!0});try{U2(O$(q,"references"),{recursive:!0}),K1(O$(q,"SKILL.md"),`${C.content.trimEnd()}
|
|
1638
|
+
`);for(let j of C.references)K1(O$(q,"references",j.fileName),`${j.content.trimEnd()}
|
|
1639
|
+
`);let Q={slug:C.slug,area:C.area,version:C.version,syncedAt:new Date().toISOString()};K1(O$(q,R2),`${JSON.stringify(Q,null,2)}
|
|
1640
|
+
`);let J=O$($,C.slug);bC(J,{recursive:!0,force:!0}),x4(q,J)}catch(Q){throw bC(q,{recursive:!0,force:!0}),Q}}async function m2($){let C=_2($.area),q=await V2(C);p4(q);let Q=new Set(q.map((j)=>j.slug)),J=[];for(let j of h4($)){U2(j,{recursive:!0});for(let X of F2(j))if(X.startsWith(z2))bC(O$(j,X),{recursive:!0,force:!0});let G=[],W=[],Z=[];for(let X of q){let Y=O$(j,X.slug);if(A2(Y)&&!K2(Y)){W.push(`${X.slug} (ya existe una skill tuya con ese nombre)`);continue}l4(j,X),G.push(`${X.slug} v${X.version}`)}for(let X of F2(j,{withFileTypes:!0})){if(!X.isDirectory()||Q.has(X.name))continue;if(K2(O$(j,X.name))?.area!==C)continue;bC(O$(j,X.name),{recursive:!0,force:!0}),Z.push(X.name)}J.push({dir:j,installed:G,skipped:W,removed:Z})}return{area:C,skills:q.length,results:J}}async function I2($){let C=_2($.area);return(await V2(C)).map((Q)=>({slug:Q.slug,name:Q.name,version:Q.version,references:Q.references.map((J)=>J.fileName).join(", ")}))}function A1(){return"team-cli skills\n\nSkills de los agentes de posventa y partner experience. Se editan en intra y se guardan en messenger.\n\n## Comandos\n\n- `skills list [--area posventa|partnerExperience]` — Lista las skills activas del área\n- `skills sync [--area posventa|partnerExperience] [--dir <carpeta>]` — Instala las skills activas del área\n\nSin `--dir`, `sync` instala en `~/.claude/skills` (Claude Code) y `~/.agents/skills` (Codex).\nCada skill queda en `<slug>/SKILL.md` con sus archivos en `<slug>/references/`.\nLas skills que se desactivan o borran en intra se quitan en el siguiente `sync`.\nNunca toca carpetas que no instaló team-cli: si ya tienes una skill con el mismo nombre, la salta.\n\nRequiere el rol `kam` o ser editor de skills.\n"}function D2($){return`team-cli
|
|
1397
1641
|
|
|
1398
1642
|
Herramienta CLI para el equipo Justo.
|
|
1399
1643
|
|
|
1400
|
-
${
|
|
1644
|
+
${$}
|
|
1401
1645
|
|
|
1402
1646
|
Si necesitas obtener data y no existe un query listo, usa create + ai-edit.
|
|
1403
1647
|
Flujo sugerido: create -> ai-edit -> preview -> run o download.
|
|
@@ -1425,6 +1669,8 @@ Cada grupo de comandos tiene su propia ayuda. Usa \`--help\` para ver los comand
|
|
|
1425
1669
|
- \`graphql\` — Ejecutar queries y mutations GraphQL
|
|
1426
1670
|
- \`admin\` — Comandos administrativos con contexto de website
|
|
1427
1671
|
- \`data\` — Datos y reportes. Puede obtener data de todas las bases de datos de Justo
|
|
1672
|
+
- \`posventa\` — Datos de las skills de posventa: estado de la carga, radar de una cartera, ficha 360, detalle en vivo, registro de decisiones, plan de activación y auditoría web (\`posventa estado|radar|ficha|detalle|registrar|activacion|auditoria\`). Pide rol kam.
|
|
1673
|
+
- \`skills\` — Instala las skills de posventa y partner experience que se editan en intra (\`skills sync\`)
|
|
1428
1674
|
- \`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.
|
|
1429
1675
|
|
|
1430
1676
|
## Tips
|
|
@@ -1454,4 +1700,4 @@ Si todavía no sabes bien dónde vive la data, primero usa \`data explain\` para
|
|
|
1454
1700
|
Cuando ya tengas claro un pipeline y solo quieras probarlo una vez, usa \`data execute\`.
|
|
1455
1701
|
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\`.
|
|
1456
1702
|
|
|
1457
|
-
`}function
|
|
1703
|
+
`}function E2(){let $=X$(),C=$?`Sesión: ${$.email}`:"Sesión: no iniciada";return D2(C)}async function T2($){let{positional:C,flags:q}=hC($);if(q.env)N1(q.env);let Q=C[0],J=C[1];if(Q==="__spaces-preview-bridge")return await jj(q);if(q.version)return{version:"0.0.16"};if(q.help&&!Q)return E2();if(Q==="auth"){if(J==="--help"||q.help)return Dq();if(J==="login")return await GQ();if(J==="login-with-token")return await ZQ(q);if(J==="request-code")return await XQ(q);if(J==="logout")return await YQ();if(J==="status")return await HQ();return Dq()}if(Q==="admin"){let j=C[1],G=C[2],W=C[3],Z=C[4];if(!j||j==="--help")return nC();if(j==="search"&&q.help)return QQ();if(j==="search")return await qQ(C,q);if(!G||G==="--help")return nC();if(G==="show")return await b1(j);if(G==="stores"&&W==="list")return await JQ(j);if(G==="coupons"&&(!W||W==="--help"))return FC();if(G==="coupons"&&W==="create"&&q.help)return $Q();if(G==="coupons"&&W==="update"&&q.help)return CQ();if(G==="coupons"&&W==="codes"&&C[4]==="create"&&q.help)return n1();if(G==="coupons"&&q.help)return FC();if(G==="coupons"&&W==="list")return await o1(j,q);if(G==="coupons"&&W==="show"){if(!Z)throw Error("Uso: team-cli admin <web> coupons show <couponId>");return await r1(j,Z)}if(G==="coupons"&&W==="create")return await t1(j,q);if(G==="coupons"&&W==="update"){if(!Z)throw Error("Uso: team-cli admin <web> coupons update <couponId> --input '<json>'");return await i1(j,Z,q)}if(G==="coupons"&&W==="delete"){if(!Z)throw Error("Uso: team-cli admin <web> coupons delete <couponId>");return await e1(j,Z)}if(G==="coupons"&&W==="codes"){let X=C[4],Y=C[5];if(!X||X==="--help")return FC();if(X==="list"){if(!Y)throw Error("Uso: team-cli admin <web> coupons codes list <couponId>");return await f1(j,Y,q)}if(X==="create"){if(!Y)throw Error("Uso: team-cli admin <web> coupons codes create <couponId> --input '<json>'");return await u1(j,Y,q)}if(X==="create-random"){if(!Y)throw Error("Uso: team-cli admin <web> coupons codes create-random <couponId> --quantity <n>");return await d1(j,Y,q)}if(X==="delete"){if(!Y)throw Error(`Uso: team-cli admin <web> coupons codes delete <couponId> --ids '["id1"]'`);return await s1(j,Y,q)}return FC()}return nC()}if(Q==="graphql"){if(J==="--help"||q.help)return uQ();return await lQ(C,q)}if(Q==="data"){let j=C[1],G=C[2];if(q.help||J==="--help")return kq();if(j==="explain")return await mQ(q);if(j==="execute")return await IQ(q);if(j==="queries"&&G==="create")return await VQ();if(j==="queries"&&G==="edit")return await DQ(C);if(j==="queries"&&G==="ai-edit")return await EQ(C,q);if(j==="queries"&&G==="view")return await TQ(C);if(j==="queries"&&G==="view-pipeline")return await LQ(C);if(j==="queries"&&G==="preview")return await NQ(C,q);if(j==="queries"&&G==="run")return await gQ(C,q);if(j==="queries"&&G==="add-viewers")return await kQ(C,q);if(j==="queries"&&G==="download")return await SQ(C,q);return kq()}if(Q==="posventa"){if(!J||J==="--help"||q.help)return vC();if(J==="ficha")return await X2(C,q);if(J==="detalle")return await Y2(C,q);if(J==="estado")return await W2();if(J==="radar")return await G2(q);if(J==="registrar")return await Z2(C,q);if(J==="activacion")return await H2(C,q);if(J==="auditoria")return await w2(C,q);return vC()}if(Q==="skills"){if(!J||J==="--help"||q.help)return A1();if(J==="sync")return await m2(q);if(J==="list")return await I2(q);return A1()}if(Q==="spaces"){let j=C[1];if(!j||j==="--help"||q.help)return nq();if(j==="init")return await Xj(q);if(j==="create")return await Hj(q);if(j==="preview")return await Yj(q);if(j==="publish")return await wj(C,q);if(j==="fork")return await Fj(C,q);if(j==="archive")return await Pj(C);if(j==="db")return await Mj(q);return nq()}return E2()}var{flags:L2}=hC(process.argv.slice(2));async function f4(){try{let $=await T2(process.argv.slice(2));if($&&typeof $==="object"&&"__streamHandled"in $&&$.__streamHandled)return;if(typeof $==="string"){E1($);return}D1($,L2)}catch($){T1($,L2),process.exit(1)}}f4();
|