@customyai/cli 0.11.0 → 0.14.0

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.
@@ -1,7 +1,7 @@
1
- import { validateCatalog, TRANSLATION_PLAN_LIMITS, parityReport } from './chunk-QKIF4C5R.mjs';
1
+ import { validateCatalog, TRANSLATION_PLAN_LIMITS, parityReport } from './chunk-CCF7M44T.mjs';
2
2
  import { z } from 'zod';
3
- import { mkdir, writeFile, chmod, stat, readFile, readdir } from 'fs/promises';
4
- import path3 from 'path';
3
+ import { mkdir, writeFile, chmod, readFile, stat, readdir } from 'fs/promises';
4
+ import path4 from 'path';
5
5
  import { CustomyProvisioningError, CustomyScopeError, CustomyEnvironmentMismatchError, CustomyConflictError, CustomyRateLimitError, CustomyAuthError, createProvisioning } from '@customyai/provisioning';
6
6
  import { createMachineTokens, discoverPlatform } from '@customyai/core';
7
7
  import { verifyMetaSignature, verifyWebhook, WebhookVerificationError, signMetaPayload, signPayload, CustomyWhatsAppError, WHATSAPP_AUDIENCE, createWhatsApp, WHATSAPP_WEBHOOK_EVENTS } from '@customyai/whatsapp';
@@ -285,11 +285,11 @@ function appManifestProblems(input, manifests = CONNECTABLE_PRODUCT_MANIFESTS) {
285
285
  if (!parsed.success) return parsed.error.issues.map((issue) => ({ path: issue.path.join("."), code: "SCHEMA_INVALID" }));
286
286
  const app = parsed.data;
287
287
  const problems = [];
288
- const unique = (items, key2, path6) => {
288
+ const unique = (items, key2, path7) => {
289
289
  const seen = /* @__PURE__ */ new Set();
290
290
  items.forEach((item, index) => {
291
291
  const k = key2(item);
292
- if (seen.has(k)) problems.push({ path: `${path6}.${index}`, code: "DUPLICATE" });
292
+ if (seen.has(k)) problems.push({ path: `${path7}.${index}`, code: "DUPLICATE" });
293
293
  seen.add(k);
294
294
  });
295
295
  };
@@ -385,8 +385,8 @@ async function syncApp(options) {
385
385
  const sent = options.adminSecret ? "x-admin-secret" : "bearer";
386
386
  if (!options.adminSecret && !options.token) throw new SyncError("ACCESS_CREDENTIAL_MISSING", 0, "define CUSTOMY_ADMIN_SECRET (x-admin-secret) o CUSTOMY_ACCESS_TOKEN (Bearer)");
387
387
  const credential = options.adminSecret ? { "x-admin-secret": options.adminSecret, "x-reason": options.reason.slice(0, 256), ...options.actor ? { "x-actor": options.actor } : {} } : { authorization: `Bearer ${options.token}` };
388
- const call = async (method, path6, body) => {
389
- const response = await (options.fetch ?? fetch)(`${base}${path6}`, {
388
+ const call = async (method, path7, body) => {
389
+ const response = await (options.fetch ?? fetch)(`${base}${path7}`, {
390
390
  method,
391
391
  headers: { ...credential, "content-type": "application/json", "idempotency-key": crypto.randomUUID() },
392
392
  body: JSON.stringify(body)
@@ -746,7 +746,7 @@ async function audit(args, io) {
746
746
  const text = await liveClient(ctx).audit.export({ format, ...pick(flags) });
747
747
  const out = str(flags, "out");
748
748
  if (out) {
749
- const target = path3.resolve(io.cwd, out);
749
+ const target = path4.resolve(io.cwd, out);
750
750
  await writeFile(target, text, { mode: 384 });
751
751
  await chmod(target, 384).catch(() => void 0);
752
752
  emit(ctx, { out, bytes: text.length, format }, [`wrote ${text.length} characters of ${format} to ${out}`]);
@@ -879,7 +879,7 @@ async function readBody(flags, io) {
879
879
  if (typeof file !== "string") throw new UsageError2("falta --file con el JSON de la petici\xF3n");
880
880
  let parsed;
881
881
  try {
882
- parsed = JSON.parse(await readFile(path3.resolve(io.cwd, file), "utf8"));
882
+ parsed = JSON.parse(await readFile(path4.resolve(io.cwd, file), "utf8"));
883
883
  } catch (error) {
884
884
  throw new UsageError2(`no se pudo leer ${file}: ${error instanceof Error ? error.message : String(error)}`);
885
885
  }
@@ -1029,10 +1029,379 @@ async function runExperimentsCli(group, args, io) {
1029
1029
  return EXPERIMENTS_EXIT.failure;
1030
1030
  }
1031
1031
  }
1032
+ var INTEGRATOR_HELP = [
1033
+ " customy experience add [component:|tokens:|catalog:]<name> [--kind component|tokens|catalog] [--dir customy] [--revision n] [--force] [--dry-run]",
1034
+ " bring one artifact from the backend into your project (JSON + a typed .ts module + a lock); --list shows what exists",
1035
+ " customy experience diff <releaseA> [<releaseB>] [--html changes.html] [--fail-on removed,contrast] what changes between two releases, per type",
1036
+ ' customy experience pin <app> <release> --reason "..." [--dry-run] | pin <app> --clear --reason "..." declare which release an app should use (write key)',
1037
+ " customy experience status --app <app> [--channel production] which release and source that app sees",
1038
+ " Read commands use CUSTOMY_EXPERIENCE_READ_KEY (falls back to CUSTOMY_EXPERIENCE_TOKEN); `pin` needs CUSTOMY_EXPERIENCE_TOKEN (write)."
1039
+ ];
1040
+ var readClient = (flags, io) => makeClient(flags, io, {
1041
+ token: io.env.CUSTOMY_EXPERIENCE_READ_KEY || io.env.CUSTOMY_EXPERIENCE_TOKEN,
1042
+ missing: "falta una credencial de lectura: CUSTOMY_EXPERIENCE_READ_KEY (o CUSTOMY_EXPERIENCE_TOKEN) en el entorno, nunca por la l\xEDnea de comandos"
1043
+ });
1044
+ var writeClient = (flags, io) => makeClient(flags, io, {
1045
+ token: io.env.CUSTOMY_EXPERIENCE_TOKEN,
1046
+ missing: io.env.CUSTOMY_EXPERIENCE_READ_KEY ? "`pin` escribe y una clave de solo lectura no puede: define CUSTOMY_EXPERIENCE_TOKEN (credencial de escritura con experience.release.publish)" : "falta CUSTOMY_EXPERIENCE_TOKEN en el entorno (credencial de escritura con experience.release.publish; nunca por la l\xEDnea de comandos)"
1047
+ });
1048
+ var APP_NAME = /^[a-z][a-z0-9-]{0,39}$/;
1049
+ var num = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
1050
+ var KIND_ALIASES = { component: "component", componente: "component", tokens: "tokens", token: "tokens", catalog: "catalog", text: "catalog", texto: "catalog", textos: "catalog" };
1051
+ var KIND_DIR = { component: "components", tokens: "tokens", catalog: "text" };
1052
+ function kindOf(raw) {
1053
+ if (raw === void 0) return null;
1054
+ const kind = typeof raw === "string" ? KIND_ALIASES[raw.toLowerCase()] : void 0;
1055
+ if (!kind) throw new UsageError3("--kind debe ser component|componente, tokens|token o catalog|texto");
1056
+ return kind;
1057
+ }
1058
+ var fileSafe = (name) => name.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^[-.]+|[-.]+$/g, "") || "artifact";
1059
+ var pascal = (name) => name.split(/[^A-Za-z0-9]+/).filter(Boolean).map((p) => p[0].toUpperCase() + p.slice(1)).join("") || "Artifact";
1060
+ var camel = (name) => {
1061
+ const p = pascal(name);
1062
+ return p[0].toLowerCase() + p.slice(1);
1063
+ };
1064
+ var sortedJson = (value) => {
1065
+ if (Array.isArray(value)) return value.map(sortedJson);
1066
+ if (isRec(value)) return Object.fromEntries(Object.keys(value).sort().map((k) => [k, sortedJson(value[k])]));
1067
+ return value;
1068
+ };
1069
+ var pretty = (value) => `${JSON.stringify(sortedJson(value), null, 2)}
1070
+ `;
1071
+ async function listArtifacts(client, kind) {
1072
+ const all = [];
1073
+ let after;
1074
+ for (let page = 0; page < 50; page += 1) {
1075
+ const result = await client.request("GET", "/artifacts", { query: { kind, limit: "200", ...after ? { after } : {} } });
1076
+ const data = isRec(result) && Array.isArray(result.data) ? result.data.filter(isRec) : [];
1077
+ all.push(...data);
1078
+ const next = isRec(result) ? result.next : null;
1079
+ if (typeof next !== "string" || !data.length) break;
1080
+ after = next;
1081
+ }
1082
+ return all.filter((a) => !a.archivedAt);
1083
+ }
1084
+ var LOCK = "customy.add.lock.json";
1085
+ async function readAddLock(dir) {
1086
+ try {
1087
+ const parsed = JSON.parse(await readFile(path4.join(dir, LOCK), "utf8"));
1088
+ if (isRec(parsed) && isRec(parsed.items)) return parsed;
1089
+ } catch {
1090
+ }
1091
+ return { version: 1, origin: "", items: {} };
1092
+ }
1093
+ function planFiles(kind, name, locale, document, root) {
1094
+ const base = `${root}/${KIND_DIR[kind]}`;
1095
+ const stem = fileSafe(locale ? `${name}.${locale}` : name);
1096
+ if (kind === "catalog") {
1097
+ const checked = validateCatalog(document, { limits: TRANSLATION_PLAN_LIMITS.enterprise });
1098
+ if (!checked.ok || !checked.doc) throw new ExitError(EXPERIENCE_EXIT.invalid, `el servidor devolvi\xF3 \xAB${name}\xBB sin ser un catalog@1 v\xE1lido: ${checked.issues[0]?.message ?? "?"}`);
1099
+ const keys = Object.keys(checked.doc.messages).sort();
1100
+ const type = `${pascal(name)}Key`;
1101
+ return [
1102
+ { file: `${base}/${stem}.json`, content: serializeCatalog(checked.doc) },
1103
+ { file: `${base}/${stem}.ts`, content: `// Generado por \xABcustomy experience add\xBB. No lo edites: vuelve a ejecutar el comando.
1104
+ export type ${type} = ${keys.length ? keys.map((k) => JSON.stringify(k)).join(" | ") : "never"};
1105
+ export const ${camel(name)}Keys: readonly ${type}[] = ${JSON.stringify(keys)};
1106
+ ` }
1107
+ ];
1108
+ }
1109
+ const doc = isRec(document) ? document : {};
1110
+ const body = `${JSON.stringify(sortedJson(document), null, 2)}`;
1111
+ if (kind === "tokens") {
1112
+ const tokens = isRec(doc.tokens) ? doc.tokens : doc;
1113
+ const names = Object.keys(tokens).sort();
1114
+ return [
1115
+ { file: `${base}/${stem}.json`, content: pretty(document) },
1116
+ { file: `${base}/${stem}.ts`, content: `// Generado por \xABcustomy experience add\xBB. No lo edites: vuelve a ejecutar el comando.
1117
+ export const ${camel(name)} = ${body} as const;
1118
+ export type ${pascal(name)} = typeof ${camel(name)};
1119
+ export type ${pascal(name)}Token = ${names.length ? names.map((k) => JSON.stringify(k)).join(" | ") : "never"};
1120
+ ` }
1121
+ ];
1122
+ }
1123
+ return [
1124
+ { file: `${base}/${stem}.json`, content: pretty(document) },
1125
+ { file: `${base}/${stem}.ts`, content: `// Generado por \xABcustomy experience add\xBB. No lo edites: vuelve a ejecutar el comando.
1126
+ export const ${camel(name)} = ${body} as const;
1127
+ export type ${pascal(name)} = typeof ${camel(name)};
1128
+ ` }
1129
+ ];
1130
+ }
1131
+ async function addCmd(positional, flags, io) {
1132
+ const client = readClient(flags, io);
1133
+ let kind = kindOf(flags.kind);
1134
+ if (flags.list) {
1135
+ const kinds2 = kind ? [kind] : ["component", "tokens", "catalog"];
1136
+ const items = [];
1137
+ for (const k of kinds2) for (const a of await listArtifacts(client, k)) items.push({ kind: k, name: str2(a.name), locale: str2(a.locale) || null, artifactId: str2(a.id) });
1138
+ items.sort((a, b) => a.kind.localeCompare(b.kind) || a.name.localeCompare(b.name) || (a.locale ?? "").localeCompare(b.locale ?? ""));
1139
+ return { lines: items.length ? items.map((i) => ` ${i.kind}:${i.name}${i.locale ? ` (${i.locale})` : ""}`) : [" (nada publicado para esos tipos)"], result: { items } };
1140
+ }
1141
+ if (positional.length !== 1) throw new UsageError3("uso: customy experience add [component:|tokens:|catalog:]<nombre> [--kind \u2026] [--dir customy] [--revision n] [--force] [--dry-run] (o --list)");
1142
+ let name = positional[0];
1143
+ const prefixed = name.match(/^([A-Za-z]+):(.+)$/);
1144
+ if (prefixed) {
1145
+ const fromPrefix = KIND_ALIASES[prefixed[1].toLowerCase()];
1146
+ if (!fromPrefix) throw new UsageError3(`tipo desconocido \xAB${prefixed[1]}\xBB: usa component, tokens o catalog (tambi\xE9n componente, token, texto)`);
1147
+ if (kind && kind !== fromPrefix) throw new UsageError3("el prefijo del nombre y --kind no coinciden");
1148
+ kind = fromPrefix;
1149
+ name = prefixed[2];
1150
+ }
1151
+ const wantedRevision = typeof flags.revision === "string" ? Number(flags.revision) : null;
1152
+ if (wantedRevision !== null && (!Number.isInteger(wantedRevision) || wantedRevision < 1)) throw new UsageError3("--revision debe ser un entero positivo");
1153
+ const kinds = kind ? [kind] : ["component", "tokens", "catalog"];
1154
+ const matches = [];
1155
+ for (const k of kinds) for (const art of await listArtifacts(client, k)) if (str2(art.name) === name) matches.push({ kind: k, art });
1156
+ if (!matches.length) throw new ExitError(EXPERIENCE_EXIT.auth, `no hay ning\xFAn artefacto \xAB${name}\xBB${kind ? ` de tipo ${kind}` : ""} (o no tienes permiso para verlo). Mira lo disponible con \xABcustomy experience add --list\xBB.`);
1157
+ const kindsFound = [...new Set(matches.map((m) => m.kind))];
1158
+ if (kindsFound.length > 1) throw new UsageError3(`\xAB${name}\xBB existe como ${kindsFound.join(" y ")}: indica cu\xE1l con el prefijo (p. ej. ${kindsFound[0]}:${name}) o --kind`);
1159
+ const found = matches[0].kind;
1160
+ const root = typeof flags.dir === "string" ? flags.dir : "customy";
1161
+ const abs = path4.resolve(io.cwd, root);
1162
+ const planned = [];
1163
+ const lockItems = [];
1164
+ for (const { art } of matches) {
1165
+ const id = str2(art.id);
1166
+ const detail = await client.request("GET", `/artifacts/${encodeURIComponent(id)}`);
1167
+ const latest = isRec(detail) ? num(detail.latestRevision) ?? 0 : 0;
1168
+ const revision = wantedRevision ?? latest;
1169
+ if (revision < 1) throw new ExitError(EXPERIENCE_EXIT.conflict, `\xAB${name}\xBB no tiene ninguna revisi\xF3n publicada: un borrador no se trae. Pide a quien lo edita que lo publique.`);
1170
+ const rev = await client.request("GET", `/artifacts/${encodeURIComponent(id)}/revisions/${revision}`);
1171
+ if (!isRec(rev) || rev.document === void 0) throw new ExitError(EXPERIENCE_EXIT.failure, `el servicio no devolvi\xF3 el documento de \xAB${name}\xBB r${revision}`);
1172
+ const locale = str2(art.locale) || void 0;
1173
+ const files = planFiles(found, name, locale, rev.document, root);
1174
+ planned.push(...files);
1175
+ lockItems.push([`${found}:${name}${locale ? `/${locale}` : ""}`, { kind: found, name, ...locale ? { locale } : {}, artifactId: id, revision, contentHash: typeof rev.contentHash === "string" ? rev.contentHash : null, files: files.map((f) => f.file) }]);
1176
+ }
1177
+ const states = [];
1178
+ for (const f of planned) {
1179
+ let current = null;
1180
+ try {
1181
+ current = await readFile(path4.resolve(io.cwd, f.file), "utf8");
1182
+ } catch {
1183
+ current = null;
1184
+ }
1185
+ states.push({ file: f.file, action: current === null ? "create" : current === f.content ? "unchanged" : "update" });
1186
+ }
1187
+ const blocked = states.filter((s) => s.action === "update" && !flags.force).map((s) => s.file);
1188
+ if (blocked.length && !flags["dry-run"]) throw new ExitError(EXPERIENCE_EXIT.conflict, `ya existen y difieren (\xBFeditados a mano o de otra revisi\xF3n?): ${blocked.join(", ")}. Revisa con git diff y repite con --force para sobrescribir.`);
1189
+ const summary = lockItems.map(([, e]) => `${e.kind}:${e.name}${e.locale ? `/${e.locale}` : ""} r${e.revision}`).join(", ");
1190
+ const fileLines = states.map((s) => ` ${s.action === "create" ? "+" : s.action === "update" ? "~" : "="} ${s.file}${s.action === "update" && !flags.force ? " (difiere: --force)" : ""}`);
1191
+ if (flags["dry-run"]) return { lines: [`dry-run: se traer\xEDa ${summary}; no se escribi\xF3 nada`, ...fileLines], result: { dryRun: true, kind: found, name, files: states, blocked } };
1192
+ for (const f of planned) {
1193
+ const target = path4.resolve(io.cwd, f.file);
1194
+ await mkdir(path4.dirname(target), { recursive: true });
1195
+ await writeFile(target, f.content);
1196
+ }
1197
+ const lock = await readAddLock(abs);
1198
+ lock.origin = client.origin;
1199
+ for (const [key2, entry] of lockItems) lock.items[key2] = entry;
1200
+ const sortedItems = Object.fromEntries(Object.keys(lock.items).sort().map((k) => [k, lock.items[k]]));
1201
+ await mkdir(abs, { recursive: true });
1202
+ await writeFile(path4.join(abs, LOCK), pretty({ version: 1, origin: lock.origin, items: sortedItems }));
1203
+ return { lines: [`\u2713 ${summary}`, ...fileLines, ` lock: ${root}/${LOCK}`], result: { kind: found, name, files: states, lock: `${root}/${LOCK}` } };
1204
+ }
1205
+ var strList = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
1206
+ function normalizeDiff(data) {
1207
+ const d = isRec(data) ? data : {};
1208
+ const side = (v) => isRec(v) && typeof v.releaseId === "string" && typeof v.number === "number" ? { releaseId: v.releaseId, number: v.number } : null;
1209
+ const to = side(d.to);
1210
+ if (!to) throw new ExitError(EXPERIENCE_EXIT.failure, "el servicio no devolvi\xF3 un diff de release reconocible (\xBFel BFF o el servicio son anteriores a F1?)");
1211
+ const entries = (Array.isArray(d.entries) ? d.entries.filter(isRec) : []).map((e) => {
1212
+ const diff = isRec(e.diff) ? e.diff : null;
1213
+ const colors = diff && isRec(diff.tokens) && Array.isArray(diff.tokens.colors) ? diff.tokens.colors.filter(isRec) : [];
1214
+ const messages2 = diff && isRec(diff.messages) ? { added: strList(diff.messages.added), changed: strList(diff.messages.changed), removed: strList(diff.messages.removed) } : null;
1215
+ const comp = isRec(e.component) ? e.component : diff && isRec(diff.component) ? diff.component : null;
1216
+ return {
1217
+ artifactId: str2(e.artifactId),
1218
+ kind: str2(e.kind),
1219
+ name: str2(e.name),
1220
+ locale: str2(e.locale) || null,
1221
+ change: e.change === "added" || e.change === "removed" ? e.change : "changed",
1222
+ from: isRec(e.from) ? num(e.from.revision) : null,
1223
+ to: isRec(e.to) ? num(e.to.revision) : null,
1224
+ fields: diff && isRec(diff.summary) ? { added: num(diff.summary.added) ?? 0, changed: num(diff.summary.changed) ?? 0, removed: num(diff.summary.removed) ?? 0 } : null,
1225
+ messages: messages2,
1226
+ colors: colors.map((c) => {
1227
+ const cb = isRec(c.contrastBefore) ? c.contrastBefore : null, ca = isRec(c.contrastAfter) ? c.contrastAfter : null;
1228
+ const passesTextAfter = ca && typeof ca.passesText === "boolean" ? ca.passesText : null;
1229
+ return { key: str2(c.key), change: str2(c.change), before: typeof c.before === "string" ? c.before : null, after: typeof c.after === "string" ? c.after : null, contrastBefore: cb ? num(cb.ratio) : null, contrastAfter: ca ? num(ca.ratio) : null, passesTextAfter, regressed: !!(cb && ca && cb.passesText === true && ca.passesText === false) };
1230
+ }),
1231
+ component: comp ? { bump: str2(comp.bump), changes: Array.isArray(comp.changes) ? comp.changes.map((c) => isRec(c) ? `${str2(c.bump)}: ${str2(c.what)}` : String(c)) : [] } : null,
1232
+ changes: diff && Array.isArray(diff.changes) ? diff.changes.filter(isRec).map((c) => ({ path: str2(c.path), change: str2(c.change), before: typeof c.before === "string" ? c.before : null, after: typeof c.after === "string" ? c.after : null })) : []
1233
+ };
1234
+ });
1235
+ const s = isRec(d.summary) ? d.summary : {};
1236
+ return {
1237
+ from: side(d.from),
1238
+ to,
1239
+ summary: { added: num(s.added) ?? 0, changed: num(s.changed) ?? 0, removed: num(s.removed) ?? 0, unchanged: num(s.unchanged) ?? 0 },
1240
+ entries,
1241
+ truncated: d.truncated === true,
1242
+ contrastRegressions: entries.reduce((n, e) => n + e.colors.filter((c) => c.regressed).length, 0)
1243
+ };
1244
+ }
1245
+ var label = (e) => `${e.kind}:${e.name}${e.locale ? `/${e.locale}` : ""}`;
1246
+ var rel = (r) => r ? `#${r.number}` : "(nada: primer release)";
1247
+ function diffLines(d) {
1248
+ const lines = [`Release ${rel(d.from)} \u2192 ${rel(d.to)}: ${d.summary.added} a\xF1adidos, ${d.summary.changed} cambiados, ${d.summary.removed} eliminados, ${d.summary.unchanged} sin cambios`];
1249
+ for (const e of d.entries) {
1250
+ const mark = e.change === "added" ? "+" : e.change === "removed" ? "-" : "~";
1251
+ const revs = e.change === "changed" ? ` r${e.from}\u2192r${e.to}` : e.change === "added" ? ` r${e.to}` : ` r${e.from}`;
1252
+ const detail = [];
1253
+ if (e.messages) detail.push(`textos +${e.messages.added.length} ~${e.messages.changed.length} -${e.messages.removed.length}`);
1254
+ else if (e.fields && e.kind !== "component") detail.push(`campos +${e.fields.added} ~${e.fields.changed} -${e.fields.removed}`);
1255
+ if (e.component) detail.push(`bump ${e.component.bump || "?"}`);
1256
+ lines.push(` ${mark} ${label(e)}${revs}${detail.length ? ` (${detail.join("; ")})` : ""}`);
1257
+ for (const c of e.colors.filter((x) => x.regressed)) lines.push(` ! contraste de ${c.key}: ${c.contrastBefore} \u2192 ${c.contrastAfter} (pierde AA de texto)`);
1258
+ for (const key2 of e.messages?.removed ?? []) lines.push(` ! texto eliminado: ${key2}`);
1259
+ }
1260
+ if (d.truncated) lines.push(" (hay m\xE1s cambios de los que el servicio detalla: el resumen los cuenta todos)");
1261
+ if (d.contrastRegressions) lines.push(`! ${d.contrastRegressions} color(es) pierden el contraste AA de texto`);
1262
+ return lines;
1263
+ }
1264
+ var esc = (value) => String(value ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
1265
+ var CHANGE_LABEL = { added: "A\xF1adido", changed: "Cambiado", removed: "Eliminado" };
1266
+ function renderDiffHtml(d) {
1267
+ const groups = /* @__PURE__ */ new Map();
1268
+ for (const e of d.entries) groups.set(e.kind, [...groups.get(e.kind) ?? [], e]);
1269
+ const entryHtml = (e) => {
1270
+ const parts = [];
1271
+ if (e.colors.length) {
1272
+ parts.push(`<table><thead><tr><th>Color</th><th>Antes</th><th>Despu\xE9s</th><th>Contraste</th></tr></thead><tbody>${e.colors.map((c) => `<tr class="${c.regressed ? "bad" : ""}"><td>${esc(c.key)}</td><td>${c.before ? `<i class="sw" style="background:${/^#[0-9a-fA-F]{3,6}$/.test(c.before) ? esc(c.before) : "transparent"}"></i>${esc(c.before)}` : "\u2014"}</td><td>${c.after ? `<i class="sw" style="background:${/^#[0-9a-fA-F]{3,6}$/.test(c.after) ? esc(c.after) : "transparent"}"></i>${esc(c.after)}` : "\u2014"}</td><td>${c.contrastAfter === null ? "\u2014" : `${c.contrastBefore ?? "\u2014"} \u2192 ${c.contrastAfter}${c.regressed ? " \xB7 pierde AA" : c.passesTextAfter === false ? " \xB7 bajo AA" : ""}`}</td></tr>`).join("")}</tbody></table>`);
1273
+ }
1274
+ if (e.messages) {
1275
+ const list3 = (title, keys) => keys.length ? `<p><b>${title} (${keys.length}):</b> ${keys.slice(0, 40).map((k) => `<code>${esc(k)}</code>`).join(" ")}${keys.length > 40 ? " \u2026" : ""}</p>` : "";
1276
+ parts.push(list3("A\xF1adidos", e.messages.added) + list3("Cambiados", e.messages.changed) + list3("Eliminados", e.messages.removed));
1277
+ }
1278
+ if (e.component) parts.push(`<p><b>Bump exigido:</b> ${esc(e.component.bump)}</p><ul>${e.component.changes.map((c) => `<li>${esc(c)}</li>`).join("")}</ul>`);
1279
+ if (!e.colors.length && !e.messages && !e.component && e.changes.length) {
1280
+ parts.push(`<table><thead><tr><th>Campo</th><th>Antes</th><th>Despu\xE9s</th></tr></thead><tbody>${e.changes.slice(0, 60).map((c) => `<tr><td>${esc(c.path)}</td><td>${esc(c.before ?? "\u2014")}</td><td>${esc(c.after ?? "\u2014")}</td></tr>`).join("")}</tbody></table>`);
1281
+ }
1282
+ const revs = e.change === "changed" ? `r${e.from} \u2192 r${e.to}` : e.change === "added" ? `r${e.to}` : `r${e.from}`;
1283
+ return `<article class="${e.change}"><h3><span class="tag">${CHANGE_LABEL[e.change]}</span> ${esc(e.name)}${e.locale ? ` <small>${esc(e.locale)}</small>` : ""} <small>${esc(revs)}</small></h3>${parts.join("")}</article>`;
1284
+ };
1285
+ return `<!doctype html>
1286
+ <html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
1287
+ <title>Qu\xE9 cambia: release ${esc(rel(d.from))} a ${esc(rel(d.to))}</title>
1288
+ <style>
1289
+ :root{--bg:#fff;--fg:#14171c;--mut:#5b6472;--line:#d9dee6;--add:#0b7a3b;--chg:#8a5a00;--rem:#b3261e;--card:#f6f8fb}
1290
+ @media (prefers-color-scheme:dark){:root{--bg:#10131a;--fg:#e8ebf0;--mut:#9aa4b2;--line:#2a313c;--add:#4cc582;--chg:#e0b050;--rem:#ff8a80;--card:#171c25}}
1291
+ body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 system-ui,sans-serif}main{max-width:62rem;margin:0 auto;padding:1.5rem 1rem 4rem}
1292
+ h1{font-size:1.5rem;margin:0 0 .25rem}h2{margin:2rem 0 .5rem;font-size:1.1rem;border-bottom:1px solid var(--line);padding-bottom:.25rem}h3{font-size:1rem;margin:0 0 .5rem}small{color:var(--mut);font-weight:400}
1293
+ .sum{display:flex;gap:.75rem;flex-wrap:wrap;margin:1rem 0}.sum div{background:var(--card);border:1px solid var(--line);border-radius:8px;padding:.5rem .9rem}.sum b{font-size:1.25rem;display:block}
1294
+ article{background:var(--card);border:1px solid var(--line);border-left:4px solid var(--chg);border-radius:8px;padding:.75rem 1rem;margin:.6rem 0}article.added{border-left-color:var(--add)}article.removed{border-left-color:var(--rem)}
1295
+ .tag{font-size:.75rem;text-transform:uppercase;letter-spacing:.04em;color:var(--mut)}table{border-collapse:collapse;width:100%;margin:.4rem 0;font-size:.9rem}th,td{text-align:left;padding:.25rem .5rem;border-bottom:1px solid var(--line);vertical-align:top;word-break:break-word}
1296
+ tr.bad td{color:var(--rem);font-weight:600}.sw{display:inline-block;width:.9em;height:.9em;border:1px solid var(--line);border-radius:3px;margin-right:.35em;vertical-align:-.1em}code{background:var(--bg);border:1px solid var(--line);border-radius:4px;padding:0 .3em}
1297
+ .warn{border:1px solid var(--rem);color:var(--rem);border-radius:8px;padding:.5rem .9rem;margin:.75rem 0}
1298
+ </style></head><body><main>
1299
+ <h1>Qu\xE9 cambia en este release</h1>
1300
+ <p>Release <b>${esc(rel(d.from))}</b> \u2192 <b>${esc(rel(d.to))}</b> \xB7 generado por <code>customy experience diff</code>. Vista de revisi\xF3n previa: no publica ni fija nada.</p>
1301
+ <div class="sum"><div><b>${d.summary.added}</b>a\xF1adidos</div><div><b>${d.summary.changed}</b>cambiados</div><div><b>${d.summary.removed}</b>eliminados</div><div><b>${d.summary.unchanged}</b>sin cambios</div></div>
1302
+ ${d.contrastRegressions ? `<div class="warn">${d.contrastRegressions} color(es) pierden el contraste AA de texto con este cambio.</div>` : ""}
1303
+ ${d.truncated ? `<p><small>El servicio detalla solo una parte de los cambios; el resumen los cuenta todos.</small></p>` : ""}
1304
+ ${[...groups].map(([kind, list3]) => `<h2>${esc(kind)} (${list3.length})</h2>${list3.map(entryHtml).join("")}`).join("") || "<p>Sin cambios entre estos releases.</p>"}
1305
+ </main></body></html>
1306
+ `;
1307
+ }
1308
+ async function diffCmd(positional, flags, io) {
1309
+ if (positional.length < 1 || positional.length > 2) throw new UsageError3("uso: customy experience diff <releaseA> [<releaseB>] [--html cambios.html] [--fail-on removed,contrast] (un solo release = contra su padre)");
1310
+ const failOn = typeof flags["fail-on"] === "string" ? flags["fail-on"].split(",").map((x) => x.trim()).filter(Boolean) : [];
1311
+ const badFail = failOn.filter((x) => x !== "removed" && x !== "contrast");
1312
+ if (badFail.length) throw new UsageError3(`--fail-on admite removed y contrast (recib\xED: ${badFail.join(", ")})`);
1313
+ if (flags.html !== void 0 && typeof flags.html !== "string") throw new UsageError3("--html necesita un fichero de salida");
1314
+ const client = readClient(flags, io);
1315
+ const [a, b] = positional.length === 2 ? [positional[0], positional[1]] : [null, positional[0]];
1316
+ const target = await resolveRelease(client, b);
1317
+ const base = a ? await resolveRelease(client, a) : null;
1318
+ const data = await client.request("GET", `/releases/${encodeURIComponent(target.id)}/diff`, { query: base ? { against: base.id } : {} });
1319
+ const diff = normalizeDiff(data);
1320
+ const lines = diffLines(diff);
1321
+ let html = null;
1322
+ if (typeof flags.html === "string") {
1323
+ html = path4.relative(io.cwd, path4.resolve(io.cwd, flags.html)) || flags.html;
1324
+ if (flags["dry-run"]) lines.push(`dry-run: no se escribi\xF3 ${html}`);
1325
+ else {
1326
+ const target2 = path4.resolve(io.cwd, flags.html);
1327
+ await mkdir(path4.dirname(target2), { recursive: true });
1328
+ await writeFile(target2, renderDiffHtml(diff));
1329
+ lines.push(`\u2713 vista de revisi\xF3n: ${html}`);
1330
+ }
1331
+ }
1332
+ const tripped = [...failOn.includes("removed") && diff.summary.removed > 0 ? ["removed"] : [], ...failOn.includes("contrast") && diff.contrastRegressions > 0 ? ["contrast"] : []];
1333
+ if (tripped.length) lines.push(`\u2717 --fail-on: ${tripped.join(", ")}`);
1334
+ return { lines, result: { ...diff, html, dryRun: flags["dry-run"] === true, failedOn: tripped }, code: tripped.length ? EXPERIENCE_EXIT.invalid : EXPERIENCE_EXIT.ok };
1335
+ }
1336
+ async function pinCmd(positional, flags, io) {
1337
+ const clear = flags.clear === true;
1338
+ if (positional.length !== (clear ? 1 : 2)) throw new UsageError3('uso: customy experience pin <app> <release|#n\xFAmero> --reason "\u2026" [--dry-run] | pin <app> --clear --reason "\u2026"');
1339
+ const app = positional[0];
1340
+ if (!APP_NAME.test(app)) throw new UsageError3("el nombre de la app debe ser min\xFAsculas, d\xEDgitos y guiones (hasta 40, empezando por letra)");
1341
+ const reason = typeof flags.reason === "string" ? flags.reason.trim() : "";
1342
+ if (reason.length < 3 || reason.length > 500) throw new UsageError3('--reason "\u2026" es obligatorio (3 a 500 caracteres): queda en la auditor\xEDa');
1343
+ const client = writeClient(flags, io);
1344
+ if (clear) {
1345
+ if (flags["dry-run"]) return { lines: [`dry-run: se quitar\xEDa el pin de ${app}; no se envi\xF3 nada`], result: { dryRun: true, app, clear: true } };
1346
+ await client.request("POST", `/pins/${encodeURIComponent(app)}/clear`, { body: { reason } });
1347
+ return { lines: [`\u2713 pin de ${app} retirado: vuelve a seguir su canal`], result: { app, cleared: true } };
1348
+ }
1349
+ const target = await resolveRelease(client, positional[1]);
1350
+ const label2 = `release ${target.number !== null ? `#${target.number} ` : ""}${target.id}`;
1351
+ if (flags["dry-run"]) return { lines: [`dry-run: se fijar\xEDa ${app} al ${label2}; no se envi\xF3 nada`], result: { dryRun: true, app, releaseId: target.id, releaseNumber: target.number } };
1352
+ const result = await client.request("PUT", `/pins/${encodeURIComponent(app)}`, { body: { releaseId: target.id, reason } });
1353
+ const rec = isRec(result) ? result : {};
1354
+ const pin = isRec(rec.pin) ? rec.pin : {};
1355
+ const served = strList(pin.servedByChannels);
1356
+ const already = rec.alreadyPinned === true;
1357
+ const lines = [
1358
+ already ? `= ${app} ya estaba fijada al ${label2}` : `\u2713 ${app} fijada al ${label2}`,
1359
+ ` declarado (no medido): ${num(pin.behindLatest) ? `${pin.behindLatest} release(s) por detr\xE1s del \xFAltimo` : "es el \xFAltimo release"}`,
1360
+ served.length ? ` servido hoy por: ${served.join(", ")}` : " ! ning\xFAn canal sirve hoy ese release: para que la app lo obedezca hay que publicarlo de nuevo con una sequence nueva (el trinquete no admite una menor)"
1361
+ ];
1362
+ return { lines, result: { app, releaseId: str2(pin.releaseId) || target.id, releaseNumber: num(pin.releaseNumber) ?? target.number, alreadyPinned: already, servedByChannels: served, behindLatest: num(pin.behindLatest), delivery: "declared" } };
1363
+ }
1364
+ async function statusApp(flags, io) {
1365
+ const app = flags.app;
1366
+ if (!APP_NAME.test(app)) throw new UsageError3("--app debe ser min\xFAsculas, d\xEDgitos y guiones (hasta 40, empezando por letra)");
1367
+ const channel = typeof flags.channel === "string" ? flags.channel : "production";
1368
+ const client = readClient(flags, io);
1369
+ const usage = await client.request("GET", "/usage");
1370
+ const u = isRec(usage) ? usage : {};
1371
+ const pin = (Array.isArray(u.pins) ? u.pins.filter(isRec) : []).find((p) => p.app === app) ?? null;
1372
+ const row = (Array.isArray(u.channels) ? u.channels.filter(isRec) : []).find((c) => c.channel === channel) ?? null;
1373
+ let timestampUrl = null;
1374
+ let scopeKey = null;
1375
+ try {
1376
+ const scope = await client.request("GET", "/scope");
1377
+ const delivery = isRec(scope) && isRec(scope.delivery) ? scope.delivery : {};
1378
+ scopeKey = isRec(scope) ? str2(scope.key) || null : null;
1379
+ timestampUrl = (Array.isArray(delivery.channels) ? delivery.channels.filter(isRec) : []).find((c) => c.channel === channel)?.timestampUrl ?? null;
1380
+ } catch (error) {
1381
+ if (!(error instanceof ApiError && error.status === 404)) throw error;
1382
+ }
1383
+ const pinned = pin ? { releaseNumber: num(pin.releaseNumber), releaseId: str2(pin.releaseId), reason: str2(pin.reason), since: str2(pin.since) || null, behindLatest: num(pin.behindLatest), servedByChannels: strList(pin.servedByChannels), releaseState: str2(pin.releaseState) } : null;
1384
+ const served = row ? { releaseNumber: num(row.releaseNumber), releaseId: typeof row.releaseId === "string" ? row.releaseId : null, sequence: num(row.sequence), minSequence: num(row.minSequence) } : null;
1385
+ const source = pinned ? "pin" : served?.releaseId ? `canal ${channel}` : "ninguna";
1386
+ const effective = pinned ? pinned.releaseNumber : served?.releaseNumber ?? null;
1387
+ const obeyed = pinned ? pinned.servedByChannels.length > 0 : null;
1388
+ const lines = [
1389
+ `App ${app}: ${effective !== null ? `release #${effective}` : "sin release"} (fuente: ${source})`,
1390
+ pinned ? ` pin \u2192 release #${pinned.releaseNumber}${pinned.behindLatest ? `, ${pinned.behindLatest} por detr\xE1s del \xFAltimo` : ""} \xB7 \xAB${pinned.reason}\xBB \xB7 desde ${pinned.since ?? "?"}` : " sin pin: la app sigue el canal",
1391
+ served ? ` canal ${channel} \u2192 ${served.releaseNumber !== null ? `release #${served.releaseNumber}` : "sin release"} \xB7 seq ${served.sequence ?? "-"} \xB7 minSeq ${served.minSequence ?? "-"}` : ` canal ${channel}: no existe en este entorno`,
1392
+ ...obeyed === false ? [` ! el pin no lo sirve ning\xFAn canal: hay que publicar ese release con una sequence nueva para que la app lo obedezca`] : [],
1393
+ ` puntero que sondea el cliente: ${timestampUrl ?? "(sin base p\xFAblica configurada)"}`,
1394
+ " el pin es una declaraci\xF3n; el consumo real por app no se mide todav\xEDa"
1395
+ ];
1396
+ return { lines, result: { app, source, effectiveReleaseNumber: effective, pin: pinned, channel: { name: channel, ...served ?? {} }, scope: scopeKey, timestampUrl, delivery: { pins: "declared", consumers: "not_measured" } } };
1397
+ }
1398
+
1399
+ // src/experience.ts
1032
1400
  var EXPERIENCE_GROUPS = ["experience"];
1033
1401
  var EXPERIENCE_EXIT = { ok: 0, invalid: 1, usage: 2, auth: 3, conflict: 4, failure: 5 };
1034
1402
  var EXPERIENCE_HELP = [
1035
- "Customy Experience (token: CUSTOMY_EXPERIENCE_TOKEN, origin: --base-url or CUSTOMY_EXPERIENCE_URL; API: <origin>/api/experience/*):",
1403
+ "Customy Experience (token: CUSTOMY_EXPERIENCE_TOKEN, origin: --base-url or CUSTOMY_EXPERIENCE_URL;",
1404
+ " API: <origin>/public/author/v1/* with a machine token cxw_\u2026 (external clients) or <origin>/api/experience/* behind the Workspace BFF; force with --api public|bff):",
1036
1405
  " customy experience pull [--dir catalogs] [--namespace a,b] [--locale es,en] [--draft] download catalog@1 files (sorted by key) + a lock file",
1037
1406
  ' customy experience push [file.json ...] [--dir catalogs] [--create] [--rebase] [--publish] [--note "..."]',
1038
1407
  " [--ack-remove k1,k2] [--ack-placeholders k3] [--plan free|pro|enterprise] [--dry-run]",
@@ -1048,11 +1417,15 @@ var EXPERIENCE_HELP = [
1048
1417
  ' customy experience scope show | rotate --reason "..." | retire [--force] delivery scope (rotate/retire: experience.scope.rotate)',
1049
1418
  " customy experience signing plan [--retire id,id] [--threshold n] [--compromised id,id] READ-ONLY key rotation plan",
1050
1419
  ' customy experience signing rotate --reason "..." [--retire id,id] [--compromised id,id] [--window-elapsed] publishes ONE rotation step',
1420
+ ' customy experience publish [--channel staging] [--note "..."] [--dry-run] create a release from the latest revision of every artifact and move the channel',
1421
+ " customy experience env [--channel staging] [--format env|json] print the NON-secret EXPERIENCE_* values of the environment your token belongs to",
1422
+ " customy experience locale put <bcp47> [<bcp47> ...] [--status translating] [--direction ltr|rtl] [--fallback es,en] open or update languages",
1051
1423
  " customy experience reconcile <channel> after a database restore (storage ahead of database)",
1424
+ ...INTEGRATOR_HELP,
1052
1425
  "Common flags: --json (one JSON document on stdout), --timeout MS (default 30000). Exit codes: 0 ok, 1 invalid/check failed, 2 usage, 3 auth, 4 conflict, 5 network/server."
1053
1426
  ];
1054
1427
  var LOCK_FILE = ".customy-experience.lock.json";
1055
- var VALUE_FLAGS2 = /* @__PURE__ */ new Set(["base-url", "dir", "namespace", "locale", "locales", "base-locale", "src", "note", "ack-remove", "ack-placeholders", "plan", "warn-hours", "timeout", "format", "source-locale", "out", "glossary", "reason", "fallback", "channel", "retire", "threshold", "compromised"]);
1428
+ var VALUE_FLAGS2 = /* @__PURE__ */ new Set(["base-url", "dir", "namespace", "locale", "locales", "base-locale", "src", "note", "ack-remove", "ack-placeholders", "plan", "warn-hours", "timeout", "format", "source-locale", "out", "glossary", "reason", "fallback", "channel", "retire", "threshold", "compromised", "kind", "release", "app", "html", "revision", "fail-on", "api", "status", "direction"]);
1056
1429
  var UsageError3 = class extends Error {
1057
1430
  };
1058
1431
  var ExitError = class extends Error {
@@ -1108,32 +1481,58 @@ function serializeCatalog(doc) {
1108
1481
  return `${JSON.stringify({ version: doc.version, namespace: doc.namespace, locale: doc.locale, syntax: doc.syntax, messages: messages2 }, null, 2)}
1109
1482
  `;
1110
1483
  }
1111
- function makeClient(flags, io) {
1484
+ var PUBLIC_AUTHOR_PREFIX = "/public/author/v1";
1485
+ function apiOf(flags, token) {
1486
+ const forced = flags.api;
1487
+ if (forced !== void 0) {
1488
+ if (forced !== "public" && forced !== "bff") throw new UsageError3("--api debe ser public o bff");
1489
+ return forced;
1490
+ }
1491
+ return token.startsWith("cxw_") ? "public" : "bff";
1492
+ }
1493
+ var sleepMs = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1494
+ var MAX_RATE_RETRIES = 3;
1495
+ var MAX_RATE_WAIT_SECONDS = 30;
1496
+ function makeClient(flags, io, auth) {
1112
1497
  const base = (typeof flags["base-url"] === "string" ? flags["base-url"] : io.env.CUSTOMY_EXPERIENCE_URL)?.replace(/\/+$/, "");
1113
1498
  if (!base) throw new UsageError3("falta el origen: --base-url o CUSTOMY_EXPERIENCE_URL");
1114
1499
  if (!/^https:\/\//i.test(base) && !/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?(\/|$)/i.test(base)) {
1115
1500
  throw new UsageError3("el origen de Experience debe ser https:// (http:// solo hacia localhost): el token viajar\xEDa en claro");
1116
1501
  }
1117
- const token = io.env.CUSTOMY_EXPERIENCE_TOKEN;
1118
- if (!token) throw new UsageError3("falta CUSTOMY_EXPERIENCE_TOKEN en el entorno (nunca por la l\xEDnea de comandos)");
1502
+ const token = auth ? auth.token : io.env.CUSTOMY_EXPERIENCE_TOKEN;
1503
+ if (!token) throw new UsageError3(auth?.missing ?? "falta CUSTOMY_EXPERIENCE_TOKEN en el entorno (nunca por la l\xEDnea de comandos)");
1119
1504
  const timeout = typeof flags.timeout === "string" ? Number(flags.timeout) : 3e4;
1120
1505
  if (!Number.isFinite(timeout) || timeout < 1) throw new UsageError3("--timeout debe ser un n\xFAmero de milisegundos");
1121
1506
  const doFetch = io.fetch ?? fetch;
1507
+ const api = apiOf(flags, token);
1508
+ const prefix = api === "public" ? PUBLIC_AUTHOR_PREFIX : "/api/experience";
1509
+ const sleep = io.sleep ?? sleepMs;
1122
1510
  return {
1123
1511
  origin: base,
1512
+ api,
1124
1513
  async request(method, route, options = {}) {
1125
- const query = options.query && Object.keys(options.query).length ? `?${new URLSearchParams(options.query)}` : "";
1514
+ const queryOptions = api === "public" && method !== "GET" && options.query ? Object.fromEntries(Object.entries(options.query).filter(([k]) => k !== "kind" && k !== "locale" && k !== "action")) : options.query;
1515
+ const query = queryOptions && Object.keys(queryOptions).length ? `?${new URLSearchParams(queryOptions)}` : "";
1126
1516
  let response;
1127
- try {
1128
- response = await doFetch(`${base}/api/experience${route}${query}`, {
1129
- method,
1130
- headers: { authorization: `Bearer ${token}`, accept: "application/json", "user-agent": "customy-cli", ...options.body !== void 0 ? { "content-type": "application/json" } : {} },
1131
- ...options.body !== void 0 ? { body: JSON.stringify(options.body) } : {},
1132
- signal: AbortSignal.timeout(timeout)
1133
- });
1134
- } catch (error) {
1135
- throw new ExitError(EXPERIENCE_EXIT.failure, `no se pudo conectar con ${base}: ${error instanceof Error ? error.message : String(error)}`);
1517
+ for (let attempt = 0; attempt <= MAX_RATE_RETRIES; attempt += 1) {
1518
+ try {
1519
+ response = await doFetch(`${base}${prefix}${route}${query}`, {
1520
+ method,
1521
+ headers: { authorization: `Bearer ${token}`, accept: "application/json", "user-agent": "customy-cli", ...options.body !== void 0 ? { "content-type": "application/json" } : {} },
1522
+ ...options.body !== void 0 ? { body: JSON.stringify(options.body) } : {},
1523
+ signal: AbortSignal.timeout(timeout)
1524
+ });
1525
+ } catch (error) {
1526
+ throw new ExitError(EXPERIENCE_EXIT.failure, `no se pudo conectar con ${base}: ${error instanceof Error ? error.message : String(error)}`);
1527
+ }
1528
+ const wait = Number(response.headers.get("retry-after"));
1529
+ if (response.status === 429 && attempt < MAX_RATE_RETRIES && Number.isFinite(wait) && wait > 0 && wait <= MAX_RATE_WAIT_SECONDS) {
1530
+ await sleep(Math.ceil(wait) * 1e3);
1531
+ continue;
1532
+ }
1533
+ break;
1136
1534
  }
1535
+ if (!response) throw new ExitError(EXPERIENCE_EXIT.failure, `no se pudo conectar con ${base}`);
1137
1536
  const text = await response.text();
1138
1537
  let data;
1139
1538
  try {
@@ -1159,7 +1558,8 @@ function exitFor(error) {
1159
1558
  }
1160
1559
  function explain(error, what) {
1161
1560
  const details = isRec(error.details) ? error.details : {};
1162
- if (error.status === 401) return `${what}: credencial rechazada (401). Revisa CUSTOMY_EXPERIENCE_TOKEN.`;
1561
+ if (error.status === 401) return `${what}: credencial rechazada (401). Revisa CUSTOMY_EXPERIENCE_TOKEN${error.name === "invalid_token" ? ": un token de m\xE1quina vencido, revocado o con el secreto cambiado se ve igual; pide uno nuevo o rota el actual en el panel de Experience (Tokens de m\xE1quina)" : ""}.`;
1562
+ if (error.status === 429) return `${what}: demasiadas peticiones por minuto con este token (429)${details.retryAfterSeconds ? `; reintenta en ${String(details.retryAfterSeconds)} s` : ""}. El CLI ya esper\xF3 y repiti\xF3; baja el ritmo o pide un token con m\xE1s tasa.`;
1163
1563
  if (error.status === 403) return `${what}: sin permiso (403). ${error.message}`;
1164
1564
  if (error.status === 404) return `${what}: sin permiso o inexistente (404). El servicio responde igual en ambos casos; revisa el identificador y que tu token tenga la capacidad exacta.`;
1165
1565
  if (error.status === 402) return `${what}: tope del plan agotado (402). ${error.message}`;
@@ -1171,6 +1571,8 @@ function explain(error, what) {
1171
1571
  if (error.name === "scope_still_draining") return `${what}: el \xE1mbito a\xFAn drena hasta ${String(details.drainsUntil ?? "?")}. Retirarlo antes deja sin migrar a los clientes que no lo hicieron; si lo quieres, repite con --force.`;
1172
1572
  if (error.name === "scope_force_too_early") return `${what}: --force no se admite hasta ${String(details.forceAllowedAt ?? "?")} (${String(details.forceMinDays ?? "?")} d\xEDas tras rotar): los clientes que no sondearon antes no aprender\xEDan el \xE1mbito nuevo. Espera a esa fecha o a ${String(details.drainsUntil ?? "drainsUntil")} y repite${details.drainsUntil ? " sin --force" : ""}.`;
1173
1573
  if (error.name === "scope_rotation_limit") return `${what}: este entorno ya rot\xF3 ${String(details.rotatedThisMonth ?? "?")} veces en ${String(details.month ?? "este mes")} (tope ${String(details.maxRotationsPerMonth ?? "?")}). Cada rotaci\xF3n copia todos los archivos vigentes: espera al mes siguiente o pide a plataforma subir EXPERIENCE_SCOPE_MAX_ROTATIONS_PER_MONTH.`;
1574
+ if (error.name === "machine_token_limit") return `${what}: este entorno ya tiene el m\xE1ximo de tokens de m\xE1quina activos (402). Revoca o deja vencer alguno.`;
1575
+ if (error.name === "production_requires_approval") return `${what}: ${error.message}`;
1174
1576
  if (error.name === "internal_key_route_forbidden") return `${what}: la llave interna del servicio no abre esta ruta (403). Es un fallo de configuraci\xF3n del BFF/despliegue, no de tu token: avisa a plataforma (runbook, \xABLlaves internas por consumidor\xBB).`;
1175
1577
  if (error.name === "fallback_required") return `${what}: hay canales que sirven este release (${channelNames(details.channels)}). Indica --fallback <release no revocado> para volver a publicarlos.`;
1176
1578
  if (error.name === "fallback_invalid" || error.name === "fallback_revoked") return `${what}: ${error.message} (canales: ${channelNames(details.channels)})`;
@@ -1188,7 +1590,7 @@ var lockKey = (namespace, locale) => `${namespace}/${locale}`;
1188
1590
  var fileName = (namespace, locale) => `${namespace}.${locale}.json`;
1189
1591
  async function readLock(dir) {
1190
1592
  try {
1191
- const parsed = JSON.parse(await readFile(path3.join(dir, LOCK_FILE), "utf8"));
1593
+ const parsed = JSON.parse(await readFile(path4.join(dir, LOCK_FILE), "utf8"));
1192
1594
  return isRec(parsed) && isRec(parsed.artifacts) ? parsed : null;
1193
1595
  } catch {
1194
1596
  return null;
@@ -1201,12 +1603,12 @@ async function catalogFilesIn(dir) {
1201
1603
  } catch {
1202
1604
  throw new UsageError3(`no se pudo leer el directorio ${dir}`);
1203
1605
  }
1204
- return names.filter((name) => name.endsWith(".json") && !name.startsWith(".")).sort().map((name) => path3.join(dir, name));
1606
+ return names.filter((name) => name.endsWith(".json") && !name.startsWith(".")).sort().map((name) => path4.join(dir, name));
1205
1607
  }
1206
1608
  async function loadFiles(files, io) {
1207
1609
  const out = [];
1208
1610
  for (const file of files) {
1209
- const display = path3.relative(io.cwd, file) || file;
1611
+ const display = path4.relative(io.cwd, file) || file;
1210
1612
  try {
1211
1613
  out.push({ file, display, raw: JSON.parse(await readFile(file, "utf8")), parseError: null });
1212
1614
  } catch (error) {
@@ -1253,7 +1655,7 @@ async function readArtifactDoc(client, id, draft) {
1253
1655
  }
1254
1656
  async function pull(flags, io) {
1255
1657
  const client = makeClient(flags, io);
1256
- const dir = path3.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
1658
+ const dir = path4.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
1257
1659
  const namespaces = list(flags.namespace);
1258
1660
  const locales = list(flags.locale);
1259
1661
  const artifacts = (await listCatalogArtifacts(client)).filter((a) => (!namespaces.length || namespaces.includes(str2(a.name))) && (!locales.length || locales.includes(str2(a.locale))));
@@ -1274,29 +1676,29 @@ async function pull(flags, io) {
1274
1676
  continue;
1275
1677
  }
1276
1678
  const { doc: checkedDoc, revision, contentHash, draftVersion } = read2;
1277
- const file = path3.join(dir, fileName(name, locale));
1679
+ const file = path4.join(dir, fileName(name, locale));
1278
1680
  const content = serializeCatalog(checkedDoc);
1279
1681
  let existing = null;
1280
1682
  try {
1281
1683
  existing = await readFile(file, "utf8");
1282
1684
  } catch {
1283
1685
  }
1284
- if (existing === content) unchanged.push(path3.relative(io.cwd, file));
1686
+ if (existing === content) unchanged.push(path4.relative(io.cwd, file));
1285
1687
  else {
1286
1688
  await writeFile(file, content);
1287
- written.push(path3.relative(io.cwd, file));
1689
+ written.push(path4.relative(io.cwd, file));
1288
1690
  }
1289
1691
  lock.artifacts[lockKey(name, locale)] = { artifactId: id, revision, contentHash, draftVersion };
1290
1692
  }
1291
- await writeFile(path3.join(dir, LOCK_FILE), `${JSON.stringify({ ...lock, artifacts: Object.fromEntries(sortedKeys(lock.artifacts).map((k) => [k, lock.artifacts[k]])) }, null, 2)}
1693
+ await writeFile(path4.join(dir, LOCK_FILE), `${JSON.stringify({ ...lock, artifacts: Object.fromEntries(sortedKeys(lock.artifacts).map((k) => [k, lock.artifacts[k]])) }, null, 2)}
1292
1694
  `);
1293
1695
  const lines = [
1294
1696
  ...written.map((f) => `\u2713 ${f}`),
1295
1697
  ...unchanged.map((f) => `= ${f} (sin cambios)`),
1296
1698
  ...skipped.map((s) => `- ${s.name}/${s.locale}: ${s.reason}`),
1297
- `${written.length} escritos, ${unchanged.length} sin cambios, ${skipped.length} omitidos (lock: ${path3.relative(io.cwd, path3.join(dir, LOCK_FILE))})`
1699
+ `${written.length} escritos, ${unchanged.length} sin cambios, ${skipped.length} omitidos (lock: ${path4.relative(io.cwd, path4.join(dir, LOCK_FILE))})`
1298
1700
  ];
1299
- return { lines, result: { written, unchanged, skipped, lock: path3.relative(io.cwd, path3.join(dir, LOCK_FILE)) } };
1701
+ return { lines, result: { written, unchanged, skipped, lock: path4.relative(io.cwd, path4.join(dir, LOCK_FILE)) } };
1300
1702
  }
1301
1703
  function checkAckFlags(flags) {
1302
1704
  const ackRemove = list(flags["ack-remove"]);
@@ -1306,8 +1708,8 @@ function checkAckFlags(flags) {
1306
1708
  }
1307
1709
  async function push(positional, flags, io) {
1308
1710
  const limits = limitsOf(flags);
1309
- const dir = path3.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
1310
- const files = positional.length ? positional.map((p) => path3.resolve(io.cwd, p)) : await catalogFilesIn(dir);
1711
+ const dir = path4.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
1712
+ const files = positional.length ? positional.map((p) => path4.resolve(io.cwd, p)) : await catalogFilesIn(dir);
1311
1713
  if (!files.length) throw new UsageError3("no hay ficheros que subir: pasa archivos o --dir con catalog@1");
1312
1714
  checkAckFlags(flags);
1313
1715
  const loaded = await loadFiles(files, io);
@@ -1328,38 +1730,38 @@ async function push(positional, flags, io) {
1328
1730
  if (flags["dry-run"]) {
1329
1731
  return { lines: [...docs.map((d) => `\u2713 ${d.display}: ${d.doc.namespace}/${d.doc.locale}, ${Object.keys(d.doc.messages).length} claves (v\xE1lido)`), "dry-run: no se envi\xF3 nada"], result: { dryRun: true, files: docs.map((d) => ({ file: d.display, namespace: d.doc.namespace, locale: d.doc.locale, keys: Object.keys(d.doc.messages).length })) } };
1330
1732
  }
1331
- return uploadDocs(docs, flags, io, positional.length ? path3.dirname(files[0]) : dir);
1733
+ return uploadDocs(docs, flags, io, positional.length ? path4.dirname(files[0]) : dir);
1332
1734
  }
1333
1735
  async function uploadDocs(docs, flags, io, lockDir) {
1334
1736
  const ackRemove = list(flags["ack-remove"]);
1335
1737
  const ackPlaceholders = list(flags["ack-placeholders"]);
1336
1738
  const client = makeClient(flags, io);
1337
1739
  const lock = await readLock(lockDir);
1338
- if (lock && lock.origin !== client.origin) throw new UsageError3(`el lock de ${path3.relative(io.cwd, lockDir) || "."} es de otro origen (${lock.origin}); haz pull contra este origen`);
1740
+ if (lock && lock.origin !== client.origin) throw new UsageError3(`el lock de ${path4.relative(io.cwd, lockDir) || "."} es de otro origen (${lock.origin}); haz pull contra este origen`);
1339
1741
  const lockFile = { version: 1, origin: client.origin, artifacts: { ...lock?.artifacts ?? {} } };
1340
1742
  const known = await listCatalogArtifacts(client);
1341
1743
  const results = [];
1342
1744
  const lines = [];
1343
1745
  const saveLock = async () => {
1344
1746
  await mkdir(lockDir, { recursive: true }).catch(() => void 0);
1345
- await writeFile(path3.join(lockDir, LOCK_FILE), `${JSON.stringify({ ...lockFile, artifacts: Object.fromEntries(sortedKeys(lockFile.artifacts).map((k) => [k, lockFile.artifacts[k]])) }, null, 2)}
1747
+ await writeFile(path4.join(lockDir, LOCK_FILE), `${JSON.stringify({ ...lockFile, artifacts: Object.fromEntries(sortedKeys(lockFile.artifacts).map((k) => [k, lockFile.artifacts[k]])) }, null, 2)}
1346
1748
  `).catch(() => void 0);
1347
1749
  };
1348
1750
  for (const { display, doc } of docs) {
1349
1751
  const key2 = lockKey(doc.namespace, doc.locale);
1350
- const label = `${display} (${key2})`;
1752
+ const label2 = `${display} (${key2})`;
1351
1753
  try {
1352
1754
  let artifact = known.find((a) => a.name === doc.namespace && a.locale === doc.locale);
1353
1755
  let created = false;
1354
1756
  if (!artifact) {
1355
- if (!flags.create) throw new ExitError(EXPERIENCE_EXIT.invalid, `${label}: no existe ese cat\xE1logo en el servidor; usa --create para crearlo`);
1757
+ if (!flags.create) throw new ExitError(EXPERIENCE_EXIT.invalid, `${label2}: no existe ese cat\xE1logo en el servidor; usa --create para crearlo`);
1356
1758
  artifact = await client.request("POST", "/artifacts", { body: { kind: "catalog", name: doc.namespace, locale: doc.locale } });
1357
1759
  created = true;
1358
1760
  }
1359
1761
  const id = str2(artifact.id);
1360
1762
  let entry = lockFile.artifacts[key2];
1361
1763
  if (!created && (!entry || entry.artifactId !== id)) {
1362
- if (!flags.rebase) throw new ExitError(EXPERIENCE_EXIT.conflict, `${label}: no hay base conocida (sin lock de un pull previo). Ejecuta \xABcustomy experience pull\xBB o usa --rebase para partir de lo \xFAltimo del servidor.`);
1764
+ if (!flags.rebase) throw new ExitError(EXPERIENCE_EXIT.conflict, `${label2}: no hay base conocida (sin lock de un pull previo). Ejecuta \xABcustomy experience pull\xBB o usa --rebase para partir de lo \xFAltimo del servidor.`);
1363
1765
  const detail = await client.request("GET", `/artifacts/${encodeURIComponent(id)}`);
1364
1766
  entry = { artifactId: id, revision: isRec(detail) && typeof detail.latestRevision === "number" ? detail.latestRevision : 0, contentHash: null, draftVersion: isRec(detail) && isRec(detail.draft) && typeof detail.draft.version === "number" ? detail.draft.version : 0 };
1365
1767
  }
@@ -1370,7 +1772,7 @@ async function uploadDocs(docs, flags, io, lockDir) {
1370
1772
  const draftVersion = isRec(saved) && typeof saved.version === "number" ? saved.version : base.draftVersion + 1;
1371
1773
  lockFile.artifacts[key2] = { ...base, draftVersion };
1372
1774
  const outcome = { file: display, namespace: doc.namespace, locale: doc.locale, artifactId: id, artifactCreated: created, revisionBase: base.revision, draftVersion, published: null };
1373
- lines.push(`\u2713 ${label}: borrador guardado (versi\xF3n ${draftVersion}, base r${base.revision})${created ? " \xB7 cat\xE1logo creado" : ""}`);
1775
+ lines.push(`\u2713 ${label2}: borrador guardado (versi\xF3n ${draftVersion}, base r${base.revision})${created ? " \xB7 cat\xE1logo creado" : ""}`);
1374
1776
  if (flags.publish) {
1375
1777
  const body = { ...typeof flags.note === "string" ? { note: flags.note } : {}, ...ackRemove.length || ackPlaceholders.length ? { acknowledge: { ...ackRemove.length ? { removeKeys: ackRemove } : {}, ...ackPlaceholders.length ? { placeholderKeys: ackPlaceholders } : {} } } : {} };
1376
1778
  const published = await client.request("POST", `/artifacts/${encodeURIComponent(id)}/revisions`, { body, query: catalogHint });
@@ -1379,12 +1781,12 @@ async function uploadDocs(docs, flags, io, lockDir) {
1379
1781
  const n = typeof rev.n === "number" ? rev.n : base.revision;
1380
1782
  outcome.published = { created: wasCreated, revision: n, contentHash: typeof rev.contentHash === "string" ? rev.contentHash : null, warnings: isRec(published) && Array.isArray(published.warnings) ? published.warnings : [] };
1381
1783
  lockFile.artifacts[key2] = { artifactId: id, revision: n, contentHash: typeof rev.contentHash === "string" ? rev.contentHash : null, draftVersion };
1382
- lines.push(wasCreated ? `\u2713 ${label}: revisi\xF3n r${n} publicada` : `= ${label}: sin cambios respecto a r${n}, no se cre\xF3 revisi\xF3n`);
1784
+ lines.push(wasCreated ? `\u2713 ${label2}: revisi\xF3n r${n} publicada` : `= ${label2}: sin cambios respecto a r${n}, no se cre\xF3 revisi\xF3n`);
1383
1785
  }
1384
1786
  results.push(outcome);
1385
1787
  } catch (error) {
1386
1788
  await saveLock();
1387
- if (error instanceof ApiError) throw new ExitError(exitFor(error), [...lines, `\u2717 ${explain(error, label)}`].join("\n"));
1789
+ if (error instanceof ApiError) throw new ExitError(exitFor(error), [...lines, `\u2717 ${explain(error, label2)}`].join("\n"));
1388
1790
  if (error instanceof ExitError) throw new ExitError(error.code, [...lines, `\u2717 ${error.message}`].join("\n"));
1389
1791
  throw error;
1390
1792
  }
@@ -1392,7 +1794,118 @@ async function uploadDocs(docs, flags, io, lockDir) {
1392
1794
  await saveLock();
1393
1795
  return { lines, result: { files: results } };
1394
1796
  }
1395
- var num = (v) => typeof v === "number" ? v : void 0;
1797
+ var CHANNEL_RE = /^[a-z][a-z0-9-]{0,23}$/;
1798
+ async function publishCmd(positional, flags, io) {
1799
+ if (positional.length) throw new UsageError3('uso: customy experience publish [--channel staging] [--note "\u2026"] [--dry-run]');
1800
+ const channel = typeof flags.channel === "string" ? flags.channel : "staging";
1801
+ if (!CHANNEL_RE.test(channel)) throw new UsageError3("--channel no es un nombre de canal v\xE1lido (min\xFAsculas, d\xEDgitos y guiones)");
1802
+ if (flags.note !== void 0 && typeof flags.note !== "string") throw new UsageError3("--note necesita un texto");
1803
+ if (flags["dry-run"]) return { lines: [`dry-run: se crear\xEDa un release con la \xFAltima revisi\xF3n de cada artefacto y se mover\xEDa el canal \xAB${channel}\xBB; no se envi\xF3 nada`], result: { dryRun: true, channel } };
1804
+ const client = makeClient(flags, io);
1805
+ let release;
1806
+ try {
1807
+ release = await client.request("POST", "/releases", { body: typeof flags.note === "string" ? { note: flags.note } : {} });
1808
+ } catch (error) {
1809
+ if (error instanceof ApiError) throw new ExitError(exitFor(error), `\u2717 ${explain(error, "crear el release")}`);
1810
+ throw error;
1811
+ }
1812
+ const rel2 = isRec(release) ? release : {};
1813
+ const releaseId = str2(rel2.id);
1814
+ const warnings = Array.isArray(rel2.warnings) ? rel2.warnings : [];
1815
+ if (!releaseId) throw new ExitError(EXPERIENCE_EXIT.failure, "el servicio no devolvi\xF3 el id del release");
1816
+ let moved;
1817
+ try {
1818
+ moved = await client.request("PUT", `/channels/${encodeURIComponent(channel)}`, { body: { releaseId } });
1819
+ } catch (error) {
1820
+ if (error instanceof ApiError) throw new ExitError(exitFor(error), [`\u2713 release #${typeof rel2.number === "number" ? rel2.number : "?"} ${releaseId} creado (el canal NO se movi\xF3)`, `\u2717 ${explain(error, `mover el canal \xAB${channel}\xBB`)}`].join("\n"));
1821
+ throw error;
1822
+ }
1823
+ const move = isRec(moved) ? moved : {};
1824
+ const sequence = typeof move.sequence === "number" ? move.sequence : isRec(move.channel) && typeof move.channel.sequence === "number" ? move.channel.sequence : null;
1825
+ const lines = [
1826
+ `\u2713 release #${typeof rel2.number === "number" ? rel2.number : "?"} ${releaseId}: ${typeof rel2.artifacts === "number" ? `${rel2.artifacts} artefactos` : Array.isArray(rel2.entries) ? `${rel2.entries.length} artefactos` : "creado"}`,
1827
+ `\u2713 canal \xAB${channel}\xBB \u2192 ${releaseId}${sequence !== null ? ` (sequence ${sequence})` : ""}`,
1828
+ ...warnings.filter(isRec).slice(0, 10).map((w) => ` aviso ${str2(w.code)}: ${str2(w.message)}`),
1829
+ " Los clientes ven el cambio cuando su sondeo lea el timestamp firmado del canal (del orden de 1\u20132 min en el borde)."
1830
+ ];
1831
+ return { lines, result: { releaseId, releaseNumber: typeof rel2.number === "number" ? rel2.number : null, channel, sequence, warnings } };
1832
+ }
1833
+ async function artifactNames(client, kind) {
1834
+ const result = await client.request("GET", "/artifacts", { query: { kind, limit: "200" } });
1835
+ const names = (isRec(result) && Array.isArray(result.data) ? result.data.filter(isRec) : []).filter((a) => a.archivedAt === null || a.archivedAt === void 0).map((a) => str2(a.name)).filter(Boolean);
1836
+ return [...new Set(names)].sort();
1837
+ }
1838
+ async function envCmd(positional, flags, io) {
1839
+ if (positional.length) throw new UsageError3("uso: customy experience env [--channel staging] [--format env|json]");
1840
+ const format = typeof flags.format === "string" ? flags.format : "env";
1841
+ if (format !== "env" && format !== "json") throw new UsageError3("--format debe ser env o json");
1842
+ const channel = channelFlag(flags, "production");
1843
+ const client = makeClient(flags, io);
1844
+ const context3 = await client.request("GET", "/context");
1845
+ const info = scopeFrom(context3);
1846
+ if (!info) throw new ExitError(EXPERIENCE_EXIT.failure, "GET /context no devolvi\xF3 el \xE1mbito de entrega (\xBFel servicio es anterior a manifest@2?)");
1847
+ const tenant = isRec(context3) && isRec(context3.tenant) ? context3.tenant : {};
1848
+ const environmentId = str2(tenant.environmentId) || null;
1849
+ const keys = isRec(context3) && Array.isArray(context3.keys) ? context3.keys.filter(isRec) : [];
1850
+ const anchors = keys.map((k) => ({ keyId: k.keyId, alg: k.alg, publicKey: k.publicKey, roles: rolesOf(k) }));
1851
+ const [tokens, catalogs, components] = await Promise.all([artifactNames(client, "tokens"), artifactNames(client, "catalog"), artifactNames(client, "component")]);
1852
+ const brandBases = [...new Set(tokens.map((n) => n.replace(/-(light|dark)$/, "")))].sort();
1853
+ const values = {
1854
+ EXPERIENCE_BASE_URL: info.delivery.base,
1855
+ EXPERIENCE_BRAND_SCOPE: info.key,
1856
+ EXPERIENCE_BRAND_ENVIRONMENT_ID: environmentId,
1857
+ EXPERIENCE_BRAND_CHANNEL: channel,
1858
+ EXPERIENCE_ANCHORED_KEYS: anchors.length ? JSON.stringify(anchors) : null,
1859
+ EXPERIENCE_BRAND_NAME: brandBases.length === 1 ? brandBases[0] : null,
1860
+ EXPERIENCE_NAMESPACE: [...new Set(catalogs)].length === 1 ? catalogs[0] : null
1861
+ };
1862
+ const notes = [];
1863
+ if (!info.delivery.base) notes.push("EXPERIENCE_BASE_URL: el servicio no tiene origen p\xFAblico de entrega configurado (lo configura Customy).");
1864
+ if (!environmentId) notes.push("EXPERIENCE_BRAND_ENVIRONMENT_ID: el contexto no trajo el id del entorno.");
1865
+ if (!anchors.length) notes.push("EXPERIENCE_ANCHORED_KEYS: este token no las ve (solo `experience.release.publish`). P\xEDdelas a quien tenga ese alcance, o ejecuta `customy experience init` con un token que lo lleve.");
1866
+ if (brandBases.length === 0) notes.push("EXPERIENCE_BRAND_NAME: el entorno a\xFAn no tiene marca (artefactos `tokens`): publ\xEDcala o d\xE9jala sin definir.");
1867
+ if (brandBases.length > 1) notes.push(`EXPERIENCE_BRAND_NAME: hay varias marcas (${brandBases.join(", ")}): elige la de TU app.`);
1868
+ if (catalogs.length === 0) notes.push("EXPERIENCE_NAMESPACE: el entorno a\xFAn no tiene cat\xE1logos.");
1869
+ if (new Set(catalogs).size > 1) notes.push(`EXPERIENCE_NAMESPACE: hay varios espacios de textos (${[...new Set(catalogs)].join(", ")}): elige el de TU app.`);
1870
+ notes.push("EXPERIENCE_BRAND_APPEARANCE: opcional; `appearance@2` solo si tu entorno declara esa capacidad (gu\xEDa \xA74.1); no sale de aqu\xED.");
1871
+ notes.push(`Componentes servidos (nombre del documento para ExperienceComponent y EXPERIENCE_SERVED_COMPONENTS): ${components.length ? components.join(", ") : "(ninguno publicado)"}.`);
1872
+ const result = { channel, values, brands: brandBases, namespaces: [...new Set(catalogs)], components, notes };
1873
+ if (format === "json") return { lines: [JSON.stringify(result, null, 2)], result };
1874
+ const lines = [
1875
+ "# Valores NO secretos de tu entorno (gu\xEDa \xA74.1 y \xA711.6). Ning\xFAn secreto: el origen, el \xE1mbito y las anclas son p\xFAblicos.",
1876
+ ...Object.entries(values).map(([name, value]) => value === null ? `# ${name}= (sin valor: ver nota)` : `${name}=${value}`),
1877
+ ...notes.map((n) => `# ${n}`)
1878
+ ];
1879
+ return { lines, result };
1880
+ }
1881
+ var LOCALE_STATUSES = ["planned", "translating", "beta", "live", "disabled"];
1882
+ var LOCALE_RE = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8}){0,2}$/;
1883
+ async function localeCmd(positional, flags, io) {
1884
+ const [sub, ...locales] = positional;
1885
+ if (sub !== "put" || locales.length === 0) throw new UsageError3("uso: customy experience locale put <bcp47> [<bcp47> ...] [--status planned|translating|beta|live|disabled] [--direction ltr|rtl] [--fallback es,en]");
1886
+ const status2 = typeof flags.status === "string" ? flags.status : "translating";
1887
+ if (!LOCALE_STATUSES.includes(status2)) throw new UsageError3(`--status debe ser uno de: ${LOCALE_STATUSES.join(", ")}`);
1888
+ const direction = typeof flags.direction === "string" ? flags.direction : "ltr";
1889
+ if (direction !== "ltr" && direction !== "rtl") throw new UsageError3("--direction debe ser ltr o rtl");
1890
+ const fallback = list(flags.fallback);
1891
+ for (const l of [...locales, ...fallback]) if (!LOCALE_RE.test(l)) throw new UsageError3(`\xAB${l}\xBB no es un idioma BCP 47 v\xE1lido`);
1892
+ const client = makeClient(flags, io);
1893
+ const done = [];
1894
+ const lines = [];
1895
+ for (const locale of locales) {
1896
+ try {
1897
+ const result = await client.request("PUT", `/locales/${encodeURIComponent(locale)}`, { body: { status: status2, direction, fallback } });
1898
+ const rec = isRec(result) ? result : {};
1899
+ done.push({ locale, status: str2(rec.status) || status2 });
1900
+ lines.push(`\u2713 ${locale}: ${str2(rec.status) || status2}`);
1901
+ } catch (error) {
1902
+ if (error instanceof ApiError) throw new ExitError(exitFor(error), [...lines, `\u2717 ${explain(error, `idioma ${locale}`)}`].join("\n"));
1903
+ throw error;
1904
+ }
1905
+ }
1906
+ return { lines, result: { locales: done } };
1907
+ }
1908
+ var num2 = (v) => typeof v === "number" ? v : void 0;
1396
1909
  var opt = (v) => typeof v === "string" ? v : void 0;
1397
1910
  function scopeFrom(data) {
1398
1911
  if (!isRec(data)) return null;
@@ -1407,7 +1920,7 @@ function scopeFrom(data) {
1407
1920
  successor: typeof scope.successor === "string" ? scope.successor : null,
1408
1921
  drainsUntil: typeof scope.drainsUntil === "string" ? scope.drainsUntil : null,
1409
1922
  draining: view(data.draining),
1410
- rot: { n: num(data.rotationsThisMonth), max: num(data.maxRotationsPerMonth), last: opt(data.lastRotatedAt), force: opt(data.forceAllowedAt), stuck: num(data.channelsNotMigrated) },
1923
+ rot: { n: num2(data.rotationsThisMonth), max: num2(data.maxRotationsPerMonth), last: opt(data.lastRotatedAt), force: opt(data.forceAllowedAt), stuck: num2(data.channelsNotMigrated) },
1411
1924
  delivery: {
1412
1925
  base: typeof delivery.base === "string" ? delivery.base : null,
1413
1926
  channels: (Array.isArray(delivery.channels) ? delivery.channels.filter(isRec) : []).map((c) => ({ channel: str2(c.channel), timestampUrl: typeof c.timestampUrl === "string" ? c.timestampUrl : null })),
@@ -1432,6 +1945,7 @@ function scopeLines(info) {
1432
1945
  ];
1433
1946
  }
1434
1947
  async function status(flags, io) {
1948
+ if (typeof flags.app === "string") return { ...await statusApp(flags, io), code: 0 };
1435
1949
  const client = makeClient(flags, io);
1436
1950
  const explicitWarn = typeof flags["warn-hours"] === "string" ? Number(flags["warn-hours"]) : null;
1437
1951
  if (explicitWarn !== null && (!Number.isFinite(explicitWarn) || explicitWarn < 0)) throw new UsageError3("--warn-hours debe ser un n\xFAmero de horas");
@@ -1482,12 +1996,12 @@ async function usedKeys(root) {
1482
1996
  if (depth > 12) return;
1483
1997
  for (const entry of (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name < b.name ? -1 : 1)) {
1484
1998
  if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "dist" || entry.name === "build") continue;
1485
- const full = path3.join(dir, entry.name);
1999
+ const full = path4.join(dir, entry.name);
1486
2000
  if (entry.isDirectory()) {
1487
2001
  await walk(full, depth + 1);
1488
2002
  continue;
1489
2003
  }
1490
- if (!entry.isFile() || !SRC_EXT.has(path3.extname(entry.name))) continue;
2004
+ if (!entry.isFile() || !SRC_EXT.has(path4.extname(entry.name))) continue;
1491
2005
  if ((await stat(full)).size > 1e6) continue;
1492
2006
  const text = await readFile(full, "utf8");
1493
2007
  for (const pattern of USAGE_PATTERNS) for (const match of text.matchAll(pattern)) if (!found.has(match[1])) found.set(match[1], full);
@@ -1498,9 +2012,9 @@ async function usedKeys(root) {
1498
2012
  }
1499
2013
  async function check(flags, io) {
1500
2014
  const limits = limitsOf(flags);
1501
- const dir = path3.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
2015
+ const dir = path4.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
1502
2016
  const loaded = (await loadFiles(await catalogFilesIn(dir), io)).filter((item) => item.parseError || isCatalogLike(item.raw));
1503
- if (!loaded.length) throw new UsageError3(`no hay cat\xE1logos catalog@1 en ${path3.relative(io.cwd, dir) || "."}`);
2017
+ if (!loaded.length) throw new UsageError3(`no hay cat\xE1logos catalog@1 en ${path4.relative(io.cwd, dir) || "."}`);
1504
2018
  const failures = [];
1505
2019
  const invalid = [];
1506
2020
  const byNamespace = /* @__PURE__ */ new Map();
@@ -1536,7 +2050,7 @@ async function check(flags, io) {
1536
2050
  const glossary = await loadGlossary(flags, io);
1537
2051
  const strict = flags.strict === true;
1538
2052
  const mismatched = new Set(parity.flatMap((p) => p.placeholderMismatch.map((m) => `${String(p.namespace)}\0${m.locale}\0${m.key}`)));
1539
- const { checkCatalog } = await import('./quality-ILK6IA5O.mjs');
2053
+ const { checkCatalog } = await import('./quality-UALNP7GO.mjs');
1540
2054
  const findings2 = [];
1541
2055
  const warnings = [];
1542
2056
  for (const p of parity) {
@@ -1558,7 +2072,7 @@ async function check(flags, io) {
1558
2072
  }
1559
2073
  let usage = null;
1560
2074
  if (typeof flags.src === "string") {
1561
- const src = path3.resolve(io.cwd, flags.src);
2075
+ const src = path4.resolve(io.cwd, flags.src);
1562
2076
  let used;
1563
2077
  try {
1564
2078
  used = await usedKeys(src);
@@ -1569,8 +2083,8 @@ async function check(flags, io) {
1569
2083
  for (const p of parity) for (const key2 of Object.keys((byNamespace.get(String(p.namespace)) ?? {})[String(p.base)] ?? {})) defined.add(key2);
1570
2084
  const missing = [...used.keys()].filter((key2) => !defined.has(key2)).sort();
1571
2085
  const unused = [...defined].filter((key2) => !used.has(key2)).sort();
1572
- usage = { src: path3.relative(io.cwd, src) || ".", usedKeys: used.size, missing: missing.map((key2) => ({ key: key2, file: path3.relative(io.cwd, used.get(key2)) })), unused };
1573
- for (const key2 of missing) failures.push(`\u2717 el c\xF3digo usa \xAB${key2}\xBB (${path3.relative(io.cwd, used.get(key2))}) y el cat\xE1logo no la define`);
2086
+ usage = { src: path4.relative(io.cwd, src) || ".", usedKeys: used.size, missing: missing.map((key2) => ({ key: key2, file: path4.relative(io.cwd, used.get(key2)) })), unused };
2087
+ for (const key2 of missing) failures.push(`\u2717 el c\xF3digo usa \xAB${key2}\xBB (${path4.relative(io.cwd, used.get(key2))}) y el cat\xE1logo no la define`);
1574
2088
  if (flags["fail-on-unused"]) for (const key2 of unused) failures.push(`\u2717 \xAB${key2}\xBB est\xE1 en el cat\xE1logo y el c\xF3digo no la usa`);
1575
2089
  }
1576
2090
  const ok = failures.length === 0;
@@ -1587,7 +2101,7 @@ async function loadGlossary(flags, io) {
1587
2101
  if (typeof flags.glossary !== "string") throw new UsageError3("--glossary necesita un fichero");
1588
2102
  let raw;
1589
2103
  try {
1590
- raw = JSON.parse(await readFile(path3.resolve(io.cwd, flags.glossary), "utf8"));
2104
+ raw = JSON.parse(await readFile(path4.resolve(io.cwd, flags.glossary), "utf8"));
1591
2105
  } catch (error) {
1592
2106
  throw new UsageError3(`--glossary: no se pudo leer ${flags.glossary} como JSON (${error instanceof Error ? error.message : String(error)})`);
1593
2107
  }
@@ -1637,9 +2151,9 @@ function formatFlag(flags, allowAuto) {
1637
2151
  }
1638
2152
  function outputPath(out, io, fallbackDir, name, single) {
1639
2153
  if (out !== void 0 && typeof out !== "string") throw new UsageError3("--out necesita una ruta");
1640
- if (out === void 0) return path3.resolve(io.cwd, fallbackDir, name);
1641
- const resolved = path3.resolve(io.cwd, out);
1642
- return single && /\.(xlf|xliff|po|pot|json)$/i.test(out) ? resolved : path3.join(resolved, name);
2154
+ if (out === void 0) return path4.resolve(io.cwd, fallbackDir, name);
2155
+ const resolved = path4.resolve(io.cwd, out);
2156
+ return single && /\.(xlf|xliff|po|pot|json)$/i.test(out) ? resolved : path4.join(resolved, name);
1643
2157
  }
1644
2158
  async function exportCmd(flags, io) {
1645
2159
  const format = formatFlag(flags, false);
@@ -1654,9 +2168,9 @@ async function exportCmd(flags, io) {
1654
2168
  for (const wantedNamespace of namespaces) if (!byNamespace.has(wantedNamespace)) throw new UsageError3(`no existe el espacio de nombres \xAB${wantedNamespace}\xBB en el servidor`);
1655
2169
  if (!byNamespace.size) throw new ExitError(EXPERIENCE_EXIT.invalid, "no hay cat\xE1logos en el servidor que exportar");
1656
2170
  const tools = {
1657
- xliff: format === "xliff" ? await import('./xliff-DEJHB2SY.mjs') : null,
1658
- po: format === "po" ? await import('./po-AKWHAYBL.mjs') : null,
1659
- json: format === "json" ? await import('./json-NETFQXLJ.mjs') : null
2171
+ xliff: format === "xliff" ? await import('./xliff-IAIUQGY4.mjs') : null,
2172
+ po: format === "po" ? await import('./po-AD6IPL4F.mjs') : null,
2173
+ json: format === "json" ? await import('./json-37BBZACO.mjs') : null
1660
2174
  };
1661
2175
  const exported = [];
1662
2176
  const skipped = [];
@@ -1706,9 +2220,9 @@ async function exportCmd(flags, io) {
1706
2220
  const lines = [];
1707
2221
  for (const job of jobs) {
1708
2222
  const file = outputPath(flags.out, io, "translations", job.name, jobs.length === 1);
1709
- await mkdir(path3.dirname(file), { recursive: true });
2223
+ await mkdir(path4.dirname(file), { recursive: true });
1710
2224
  await writeFile(file, job.content);
1711
- const shown = path3.relative(io.cwd, file) || file;
2225
+ const shown = path4.relative(io.cwd, file) || file;
1712
2226
  exported.push({ namespace: job.namespace, locale: job.locale, format, file: shown, keys: job.keys, source: draft ? "draft" : "published", from: job.from });
1713
2227
  lines.push(`\u2713 ${shown} (${job.namespace}/${job.locale}, ${job.keys} claves, ${job.from})`);
1714
2228
  }
@@ -1718,7 +2232,7 @@ async function exportCmd(flags, io) {
1718
2232
  }
1719
2233
  function detectFormat(flag, file, text) {
1720
2234
  if (flag !== "auto") return flag;
1721
- const ext = path3.extname(file).toLowerCase();
2235
+ const ext = path4.extname(file).toLowerCase();
1722
2236
  if (ext === ".xlf" || ext === ".xliff") return "xliff";
1723
2237
  if (ext === ".po" || ext === ".pot") return "po";
1724
2238
  if (ext === ".json") return "json";
@@ -1743,9 +2257,9 @@ async function importCmd(positional, flags, io) {
1743
2257
  const localeFlag = singleLocale(flags, "locale");
1744
2258
  const sourceLocaleFlag = singleLocale(flags, "source-locale");
1745
2259
  const glossary = await loadGlossary(flags, io);
1746
- const dir = path3.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
1747
- const file = path3.resolve(io.cwd, positional[0]);
1748
- const display = path3.relative(io.cwd, file) || file;
2260
+ const dir = path4.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
2261
+ const file = path4.resolve(io.cwd, positional[0]);
2262
+ const display = path4.relative(io.cwd, file) || file;
1749
2263
  let size;
1750
2264
  try {
1751
2265
  const info = await stat(file);
@@ -1767,10 +2281,10 @@ async function importCmd(positional, flags, io) {
1767
2281
  let target;
1768
2282
  try {
1769
2283
  if (format === "xliff") {
1770
- const t = await import('./xliff-DEJHB2SY.mjs');
2284
+ const t = await import('./xliff-IAIUQGY4.mjs');
1771
2285
  ({ source, target } = t.xliffToCatalogs(t.importXliff(bytes, namespaceFlag ? { namespace: namespaceFlag } : {})));
1772
2286
  } else if (format === "po") {
1773
- const t = await import('./po-AKWHAYBL.mjs');
2287
+ const t = await import('./po-AD6IPL4F.mjs');
1774
2288
  ({ source, target } = t.poToCatalogs(t.parsePo(text), { ...namespaceFlag ? { namespace: namespaceFlag } : {}, ...sourceLocaleFlag ? { sourceLocale: sourceLocaleFlag } : {}, ...localeFlag ? { targetLocale: localeFlag } : {} }));
1775
2289
  } else {
1776
2290
  let parsed;
@@ -1785,9 +2299,9 @@ async function importCmd(positional, flags, io) {
1785
2299
  source = null;
1786
2300
  target = checked2.doc;
1787
2301
  } else {
1788
- const t = await import('./json-NETFQXLJ.mjs');
2302
+ const t = await import('./json-37BBZACO.mjs');
1789
2303
  const flat = t.parseFlatJson(text);
1790
- const named = path3.basename(file).match(/^([a-z][a-z0-9-]{1,31})\.([a-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,2})(?:\.flat)?\.json$/);
2304
+ const named = path4.basename(file).match(/^([a-z][a-z0-9-]{1,31})\.([a-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,2})(?:\.flat)?\.json$/);
1791
2305
  const namespace = namespaceFlag ?? named?.[1];
1792
2306
  const locale = localeFlag ?? named?.[2];
1793
2307
  if (!namespace || !locale) throw new UsageError3("un JSON plano necesita --namespace y --locale (o un nombre \xAB<espacio>.<idioma>.json\xBB)");
@@ -1810,7 +2324,7 @@ async function importCmd(positional, flags, io) {
1810
2324
  }
1811
2325
  const doc = checked.doc;
1812
2326
  if (!source && format === "json") {
1813
- const localSource = path3.join(dir, fileName(doc.namespace, sourceLocaleFlag ?? "en"));
2327
+ const localSource = path4.join(dir, fileName(doc.namespace, sourceLocaleFlag ?? "en"));
1814
2328
  try {
1815
2329
  const candidate = validateCatalog(JSON.parse(await readFile(localSource, "utf8")), { limits: TRANSLATION_PLAN_LIMITS.enterprise });
1816
2330
  if (candidate.ok && candidate.doc && candidate.doc.locale !== doc.locale) source = candidate.doc;
@@ -1820,7 +2334,7 @@ async function importCmd(positional, flags, io) {
1820
2334
  const findings2 = [];
1821
2335
  const noteLines = [];
1822
2336
  if (source) {
1823
- const { checkCatalog } = await import('./quality-ILK6IA5O.mjs');
2337
+ const { checkCatalog } = await import('./quality-UALNP7GO.mjs');
1824
2338
  for (const f of checkCatalog(source, doc, { glossary, severities: QUALITY_SEVERITIES })) findings2.push(qualityRow(doc.namespace, f));
1825
2339
  const strictFail = flags.strict === true;
1826
2340
  const failing = (row) => row.severity === "error" || strictFail && row.severity === "warning";
@@ -1849,8 +2363,8 @@ async function pseudoCmd(positional, flags, io) {
1849
2363
  if (locale === sourceLocale) throw new UsageError3("--locale no puede ser el idioma de origen");
1850
2364
  const limits = limitsOf(flags);
1851
2365
  const namespaces = list(flags.namespace);
1852
- const dir = path3.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
1853
- const files = positional.length ? positional.map((p) => path3.resolve(io.cwd, p)) : await catalogFilesIn(dir);
2366
+ const dir = path4.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
2367
+ const files = positional.length ? positional.map((p) => path4.resolve(io.cwd, p)) : await catalogFilesIn(dir);
1854
2368
  const loaded = (await loadFiles(files, io)).filter((item) => positional.length || item.parseError || isCatalogLike(item.raw));
1855
2369
  const sources = [];
1856
2370
  const problems = [];
@@ -1871,7 +2385,7 @@ async function pseudoCmd(positional, flags, io) {
1871
2385
  if (!namespaces.length || namespaces.includes(checked.doc.namespace)) sources.push({ display: item.display, doc: checked.doc });
1872
2386
  }
1873
2387
  if (problems.length) throw new ExitError(EXPERIENCE_EXIT.invalid, ["cat\xE1logo de origen no v\xE1lido; no se escribi\xF3 nada:", ...problems].join("\n"));
1874
- if (!sources.length) throw new UsageError3(`no hay cat\xE1logos de origen \xAB${sourceLocale}\xBB en ${path3.relative(io.cwd, dir) || "."}`);
2388
+ if (!sources.length) throw new UsageError3(`no hay cat\xE1logos de origen \xAB${sourceLocale}\xBB en ${path4.relative(io.cwd, dir) || "."}`);
1875
2389
  const { pseudoLocalizeMessages } = await import('./pseudo-CKYMJJBX.mjs');
1876
2390
  const outputs = [];
1877
2391
  for (const { display, doc } of sources) {
@@ -1888,14 +2402,14 @@ async function pseudoCmd(positional, flags, io) {
1888
2402
  outputs.push({ doc: checked.doc, from: display });
1889
2403
  }
1890
2404
  if (problems.length) throw new ExitError(EXPERIENCE_EXIT.invalid, ["la pseudo-localizaci\xF3n no es un cat\xE1logo v\xE1lido; no se escribi\xF3 nada:", ...problems].join("\n"));
1891
- const fallbackDir = positional.length ? path3.dirname(files[0]) : dir;
2405
+ const fallbackDir = positional.length ? path4.dirname(files[0]) : dir;
1892
2406
  const written = [];
1893
2407
  const lines = [];
1894
2408
  for (const { doc, from } of outputs) {
1895
- const target = outputPath(flags.out, io, path3.relative(io.cwd, fallbackDir) || ".", fileName(doc.namespace, locale), outputs.length === 1);
1896
- await mkdir(path3.dirname(target), { recursive: true });
2409
+ const target = outputPath(flags.out, io, path4.relative(io.cwd, fallbackDir) || ".", fileName(doc.namespace, locale), outputs.length === 1);
2410
+ await mkdir(path4.dirname(target), { recursive: true });
1897
2411
  await writeFile(target, serializeCatalog(doc));
1898
- const shown = path3.relative(io.cwd, target) || target;
2412
+ const shown = path4.relative(io.cwd, target) || target;
1899
2413
  written.push({ namespace: doc.namespace, locale, strategy: flags.rtl ? "rtl" : "accented", file: shown, from, keys: Object.keys(doc.messages).length });
1900
2414
  lines.push(`\u2713 ${shown} (${doc.namespace}/${locale}, ${Object.keys(doc.messages).length} claves, desde ${from})`);
1901
2415
  }
@@ -1938,8 +2452,8 @@ var rolesOf = (key2) => Array.isArray(key2.roles) ? key2.roles.filter((r) => typ
1938
2452
  async function initCmd(flags, io) {
1939
2453
  const client = makeClient(flags, io);
1940
2454
  const channel = channelFlag(flags, "production");
1941
- const out = path3.resolve(io.cwd, typeof flags.out === "string" ? flags.out : CONFIG_FILE);
1942
- const shown = path3.relative(io.cwd, out) || out;
2455
+ const out = path4.resolve(io.cwd, typeof flags.out === "string" ? flags.out : CONFIG_FILE);
2456
+ const shown = path4.relative(io.cwd, out) || out;
1943
2457
  if (!flags.force) {
1944
2458
  let exists = true;
1945
2459
  try {
@@ -1963,7 +2477,7 @@ async function initCmd(flags, io) {
1963
2477
  const tenant = isRec(context3) && isRec(context3.tenant) ? context3.tenant : {};
1964
2478
  const environmentId = typeof tenant.environmentId === "string" ? tenant.environmentId : null;
1965
2479
  const config = { scope: info.key, base: info.delivery.base, ...environmentId ? { environmentId } : {}, channel, anchors: keys.map((k) => ({ keyId: k.keyId, alg: k.alg, publicKey: k.publicKey, roles: rolesOf(k) })), ...floor ? { floor } : {}, strict: false };
1966
- await mkdir(path3.dirname(out), { recursive: true });
2480
+ await mkdir(path4.dirname(out), { recursive: true });
1967
2481
  await writeFile(out, `${JSON.stringify(config, null, 2)}
1968
2482
  `);
1969
2483
  const lines = [
@@ -1982,14 +2496,14 @@ async function revokeCmd(positional, flags, io) {
1982
2496
  const target = await resolveRelease(client, positional[0]);
1983
2497
  const fallback = typeof flags.fallback === "string" ? await resolveRelease(client, flags.fallback) : null;
1984
2498
  if (fallback && fallback.id === target.id) throw new UsageError3("--fallback no puede ser el release que se revoca");
1985
- const label = `release ${target.number !== null ? `#${target.number} ` : ""}${target.id}`;
1986
- if (flags["dry-run"]) return { lines: [`dry-run: se revocar\xEDa el ${label}${fallback ? ` con respaldo ${fallback.id}` : " (sin respaldo: el servicio pedir\xE1 --fallback si alg\xFAn canal lo sirve)"}; no se envi\xF3 nada`], result: { dryRun: true, releaseId: target.id, fallbackReleaseId: fallback?.id ?? null } };
2499
+ const label2 = `release ${target.number !== null ? `#${target.number} ` : ""}${target.id}`;
2500
+ if (flags["dry-run"]) return { lines: [`dry-run: se revocar\xEDa el ${label2}${fallback ? ` con respaldo ${fallback.id}` : " (sin respaldo: el servicio pedir\xE1 --fallback si alg\xFAn canal lo sirve)"}; no se envi\xF3 nada`], result: { dryRun: true, releaseId: target.id, fallbackReleaseId: fallback?.id ?? null } };
1987
2501
  const result = await client.request("POST", `/releases/${encodeURIComponent(target.id)}/revoke`, { body: { reason, ...fallback ? { fallbackReleaseId: fallback.id } : {} } });
1988
2502
  const rec = isRec(result) ? result : {};
1989
2503
  const repointed = (Array.isArray(rec.repointed) ? rec.repointed.filter(isRec) : []).map((r) => ({ channel: str2(r.channel), sequence: typeof r.sequence === "number" ? r.sequence : null, releaseNumber: typeof r.releaseNumber === "number" ? r.releaseNumber : null, minSequence: typeof r.minSequence === "number" ? r.minSequence : null }));
1990
2504
  const already = rec.alreadyRevoked === true;
1991
2505
  const lines = [
1992
- already ? `= ${label}: ya estaba revocado` : `\u2713 ${label}: revocado`,
2506
+ already ? `= ${label2}: ya estaba revocado` : `\u2713 ${label2}: revocado`,
1993
2507
  ...repointed.map((r) => ` ${r.channel}: vuelve a publicar el release #${r.releaseNumber ?? "?"} con sequence ${r.sequence ?? "?"} y minSequence ${r.minSequence ?? "?"} (los clientes descartan lo instalado con sequence menor)`),
1994
2508
  ...repointed.length ? [" Verifica en la CDN: GET <base>/t/<scope>/<canal>/timestamp.json debe traer esa sequence y ese minSequence (mira CF-Cache-Status; el 200 de una purga no prueba nada)."] : []
1995
2509
  ];
@@ -2068,12 +2582,12 @@ async function reconcileCmd(positional, flags, io) {
2068
2582
  const rec = await client.request("POST", `/channels/${encodeURIComponent(channel)}/reconcile`, { body: {} });
2069
2583
  const data = isRec(rec) ? rec : {};
2070
2584
  const republished = isRec(data.republished) ? data.republished : null;
2071
- const num2 = (value) => typeof value === "number" ? value : null;
2585
+ const num3 = (value) => typeof value === "number" ? value : null;
2072
2586
  const lines = [
2073
- `\u2713 canal ${channel} reconciliado: contador ${num2(data.previousSequence) ?? "?"} \u2192 ${num2(data.sequence) ?? "?"} (el almac\xE9n anunci\xF3 hasta ${num2(data.storedSequence) ?? "?"})`,
2074
- republished ? ` release vigente publicado de nuevo con sequence ${num2(republished.sequence) ?? "?"}` : " el canal no ten\xEDa release vigente: no se republic\xF3 nada"
2587
+ `\u2713 canal ${channel} reconciliado: contador ${num3(data.previousSequence) ?? "?"} \u2192 ${num3(data.sequence) ?? "?"} (el almac\xE9n anunci\xF3 hasta ${num3(data.storedSequence) ?? "?"})`,
2588
+ republished ? ` release vigente publicado de nuevo con sequence ${num3(republished.sequence) ?? "?"}` : " el canal no ten\xEDa release vigente: no se republic\xF3 nada"
2075
2589
  ];
2076
- return { lines, result: { channel, previousSequence: num2(data.previousSequence), storedSequence: num2(data.storedSequence), sequence: num2(data.sequence), republished: republished ? { sequence: num2(republished.sequence) } : null } };
2590
+ return { lines, result: { channel, previousSequence: num3(data.previousSequence), storedSequence: num3(data.storedSequence), sequence: num3(data.sequence), republished: republished ? { sequence: num3(republished.sequence) } : null } };
2077
2591
  }
2078
2592
  async function runExperienceCli(args, io) {
2079
2593
  const asJson = args.includes("--json");
@@ -2122,8 +2636,26 @@ async function runExperienceCli(args, io) {
2122
2636
  case "reconcile":
2123
2637
  outcome = await reconcileCmd(positional, flags, io);
2124
2638
  break;
2639
+ case "publish":
2640
+ outcome = await publishCmd(positional, flags, io);
2641
+ break;
2642
+ case "locale":
2643
+ outcome = await localeCmd(positional, flags, io);
2644
+ break;
2645
+ case "env":
2646
+ outcome = await envCmd(positional, flags, io);
2647
+ break;
2648
+ case "add":
2649
+ outcome = await addCmd(positional, flags, io);
2650
+ break;
2651
+ case "diff":
2652
+ outcome = await diffCmd(positional, flags, io);
2653
+ break;
2654
+ case "pin":
2655
+ outcome = await pinCmd(positional, flags, io);
2656
+ break;
2125
2657
  default:
2126
- throw new UsageError3(`comando desconocido: customy experience ${command2} (pull|push|status|check|export|import|pseudo|init|revoke|scope|signing|reconcile)`);
2658
+ throw new UsageError3(`comando desconocido: customy experience ${command2} (pull|push|status|check|export|import|pseudo|init|revoke|scope|signing|reconcile|publish|locale|env|add|diff|pin)`);
2127
2659
  }
2128
2660
  const code = outcome.code ?? EXPERIENCE_EXIT.ok;
2129
2661
  if (asJson) io.out(JSON.stringify({ ok: code === 0, command: command2, exitCode: code, ...isRec(outcome.result) ? outcome.result : { result: outcome.result } }, null, 2));
@@ -2248,7 +2780,7 @@ function table2(rows) {
2248
2780
  }
2249
2781
  async function readJsonFile(io, file) {
2250
2782
  try {
2251
- return JSON.parse(await readFile(path3.resolve(io.cwd, file), "utf8"));
2783
+ return JSON.parse(await readFile(path4.resolve(io.cwd, file), "utf8"));
2252
2784
  } catch (error) {
2253
2785
  throw new UsageError4(`no se pudo leer ${file}: ${error instanceof Error ? error.message : String(error)}`);
2254
2786
  }
@@ -2554,10 +3086,10 @@ async function tail(args, io) {
2554
3086
  }
2555
3087
  return WHATSAPP_EXIT.ok;
2556
3088
  }
2557
- function dryRun(ctx, method, path6, body) {
2558
- emit2(ctx, { dryRun: true, method, path: path6, ...body === void 0 ? {} : { body } }, [
3089
+ function dryRun(ctx, method, path7, body) {
3090
+ emit2(ctx, { dryRun: true, method, path: path7, ...body === void 0 ? {} : { body } }, [
2559
3091
  "DRY RUN (no se cambia nada)",
2560
- `${method} ${path6}`,
3092
+ `${method} ${path7}`,
2561
3093
  ...body === void 0 ? [] : [JSON.stringify(body, null, 2)]
2562
3094
  ]);
2563
3095
  return WHATSAPP_EXIT.ok;
@@ -2677,7 +3209,7 @@ async function recipientsFromFile(io, file) {
2677
3209
  return parsed;
2678
3210
  }
2679
3211
  try {
2680
- return (await readFile(path3.resolve(io.cwd, file), "utf8")).split(/\r?\n/).map((line) => line.split("#")[0].trim()).filter(Boolean);
3212
+ return (await readFile(path4.resolve(io.cwd, file), "utf8")).split(/\r?\n/).map((line) => line.split("#")[0].trim()).filter(Boolean);
2681
3213
  } catch (error) {
2682
3214
  throw new UsageError4(`no se pudo leer ${file}: ${error instanceof Error ? error.message : String(error)}`);
2683
3215
  }
@@ -2880,7 +3412,7 @@ async function webhookBody(flags, io) {
2880
3412
  if (file === void 0 === (inline === void 0)) throw new UsageError4("indica exactamente uno: --body-file o --body (el cuerpo CRUDO, sin re-serializar)");
2881
3413
  if (inline !== void 0) return inline;
2882
3414
  try {
2883
- return await readFile(path3.resolve(io.cwd, file), "utf8");
3415
+ return await readFile(path4.resolve(io.cwd, file), "utf8");
2884
3416
  } catch (error) {
2885
3417
  throw new UsageError4(`no se pudo leer ${file}: ${error instanceof Error ? error.message : String(error)}`);
2886
3418
  }
@@ -3177,12 +3709,12 @@ function option(args, name) {
3177
3709
  return index >= 0 ? args[index + 1] : void 0;
3178
3710
  }
3179
3711
  async function loadManifest(args, io) {
3180
- const file = path3.resolve(io.cwd, option(args, "file") ?? "customy.app.json");
3712
+ const file = path4.resolve(io.cwd, option(args, "file") ?? "customy.app.json");
3181
3713
  let raw;
3182
3714
  try {
3183
3715
  raw = JSON.parse(await readFile(file, "utf8"));
3184
3716
  } catch (error) {
3185
- io.err(`no se pudo leer ${path3.relative(io.cwd, file) || file}: ${error instanceof Error ? error.message : error}`);
3717
+ io.err(`no se pudo leer ${path4.relative(io.cwd, file) || file}: ${error instanceof Error ? error.message : error}`);
3186
3718
  return null;
3187
3719
  }
3188
3720
  const result = validateManifest(raw);
@@ -3214,10 +3746,10 @@ async function runCli(argv, io) {
3214
3746
  return 0;
3215
3747
  }
3216
3748
  if (command2 === "codegen") {
3217
- const out = path3.resolve(io.cwd, option(args, "out") ?? "customy.generated.ts");
3218
- await mkdir(path3.dirname(out), { recursive: true });
3749
+ const out = path4.resolve(io.cwd, option(args, "out") ?? "customy.generated.ts");
3750
+ await mkdir(path4.dirname(out), { recursive: true });
3219
3751
  await writeFile(out, generateAppTypes(manifest));
3220
- io.out(`\u2713 tipos de ${manifest.key} en ${path3.relative(io.cwd, out)}`);
3752
+ io.out(`\u2713 tipos de ${manifest.key} en ${path4.relative(io.cwd, out)}`);
3221
3753
  return 0;
3222
3754
  }
3223
3755
  const workspaceEnvironmentId = option(args, "workspace-env");