@customyai/cli 0.10.1 → 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';
@@ -153,6 +153,8 @@ var CONNECTABLE_PRODUCT_MANIFESTS = [
153
153
  product("customy-data", [{ kind: "external_source", keys: ["analytics-source"], operations: { allowed: ["submit"], mode: "exact" } }]),
154
154
  // Experiments: las apps conectadas lo referencian para evaluar flags con su clave publicable; sin enlaces propios todavía (F5).
155
155
  product("customy-experiments"),
156
+ // Paywalls: las apps conectadas lo consumen por `decide` con su clave publicable; sin enlaces propios todavía (F2 trae el SDK).
157
+ product("customy-paywalls"),
156
158
  product("customy-analytics"),
157
159
  product("customy-campaigns", [{ kind: "external_communication", keys: ["weekly-brief"], operations: { allowed: ["read"], mode: "exact" } }]),
158
160
  product("customy-engagement", [{ kind: "external_communication", keys: ["notification-delivery", "operator-approval"], operations: { allowed: ["deliver_notification", "request_operator_approval"], mode: "subset" } }]),
@@ -283,11 +285,11 @@ function appManifestProblems(input, manifests = CONNECTABLE_PRODUCT_MANIFESTS) {
283
285
  if (!parsed.success) return parsed.error.issues.map((issue) => ({ path: issue.path.join("."), code: "SCHEMA_INVALID" }));
284
286
  const app = parsed.data;
285
287
  const problems = [];
286
- const unique = (items, key2, path6) => {
288
+ const unique = (items, key2, path7) => {
287
289
  const seen = /* @__PURE__ */ new Set();
288
290
  items.forEach((item, index) => {
289
291
  const k = key2(item);
290
- if (seen.has(k)) problems.push({ path: `${path6}.${index}`, code: "DUPLICATE" });
292
+ if (seen.has(k)) problems.push({ path: `${path7}.${index}`, code: "DUPLICATE" });
291
293
  seen.add(k);
292
294
  });
293
295
  };
@@ -364,33 +366,43 @@ function validateManifest(input) {
364
366
  return problems.length ? { ok: false, problems } : { ok: true, manifest: AppManifestSchema.parse(input) };
365
367
  }
366
368
  var SyncError = class extends Error {
367
- constructor(code, status2) {
368
- super(`${code} (${status2})`);
369
+ constructor(code, status2, hint) {
370
+ super(`${code} (${status2})${hint ? ` \u2014 ${hint}` : ""}`);
369
371
  this.code = code;
370
372
  this.status = status2;
373
+ this.hint = hint;
371
374
  }
372
375
  code;
373
376
  status;
377
+ hint;
374
378
  };
379
+ function rejectedCredentialHint(sent) {
380
+ return sent === "bearer" ? "Access rechaz\xF3 el Bearer (CUSTOMY_ACCESS_TOKEN). Access de producci\xF3n espera el secreto de administrador en la cabecera x-admin-secret: define CUSTOMY_ADMIN_SECRET" : "Access rechaz\xF3 x-admin-secret (CUSTOMY_ADMIN_SECRET). Comprueba el secreto de ese entorno o usa un token de administrador del Workspace en CUSTOMY_ACCESS_TOKEN (Bearer)";
381
+ }
375
382
  async function syncApp(options) {
376
383
  const base = options.accessUrl.replace(/\/$/, "");
377
384
  if (!/^https:\/\//.test(base) && !/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(base)) throw new SyncError("ACCESS_URL_INSECURE", 0);
378
- const call = async (method, path6, body) => {
379
- const response = await (options.fetch ?? fetch)(`${base}${path6}`, {
385
+ const sent = options.adminSecret ? "x-admin-secret" : "bearer";
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
+ 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, path7, body) => {
389
+ const response = await (options.fetch ?? fetch)(`${base}${path7}`, {
380
390
  method,
381
- headers: { authorization: `Bearer ${options.token}`, "content-type": "application/json", "idempotency-key": crypto.randomUUID() },
391
+ headers: { ...credential, "content-type": "application/json", "idempotency-key": crypto.randomUUID() },
382
392
  body: JSON.stringify(body)
383
393
  });
384
394
  const json = await response.json().catch(() => ({}));
385
- if (!response.ok) throw new SyncError(String(json.code ?? json.error ?? "ACCESS_REQUEST_FAILED"), response.status);
395
+ if (!response.ok) throw new SyncError(String(json.code ?? json.error ?? "ACCESS_REQUEST_FAILED"), response.status, response.status === 401 ? rejectedCredentialHint(sent) : void 0);
386
396
  return json;
387
397
  };
388
398
  const env = encodeURIComponent(options.workspaceEnvironmentId);
389
399
  const installed = await call("POST", `/api/admin/env/${env}/connected-applications/install`, { manifest: options.manifest, reason: options.reason });
390
400
  const connection = installed.connection;
401
+ const key2 = installed.publishableKey ?? connection.publishableKey;
402
+ const publishableKey = typeof key2 === "string" && key2 ? key2 : null;
391
403
  const reconciliation = (value) => value && typeof value === "object" ? value : {};
392
404
  if (!installed.replayed) {
393
- return { action: "installed", applicationId: connection.applicationId, environmentId: connection.environmentId, revision: connection.revision, reconciliation: reconciliation(installed.reconciliation) };
405
+ return { action: "installed", applicationId: connection.applicationId, environmentId: connection.environmentId, revision: connection.revision, publishableKey, reconciliation: reconciliation(installed.reconciliation) };
394
406
  }
395
407
  const updated = await call("PUT", `/api/admin/env/${encodeURIComponent(connection.environmentId)}/connected-application/manifest`, {
396
408
  expectedRevision: connection.revision,
@@ -398,7 +410,7 @@ async function syncApp(options) {
398
410
  reason: options.reason
399
411
  });
400
412
  const revision = Number(updated.revision ?? connection.revision);
401
- return { action: updated.unchanged ? "unchanged" : "updated", applicationId: connection.applicationId, environmentId: connection.environmentId, revision, reconciliation: reconciliation(updated.reconciliation) };
413
+ return { action: updated.unchanged ? "unchanged" : "updated", applicationId: connection.applicationId, environmentId: connection.environmentId, revision, publishableKey, reconciliation: reconciliation(updated.reconciliation) };
402
414
  }
403
415
  var EXIT = { ok: 0, failure: 1, unsupported: 2, auth: 3, confirmation: 4 };
404
416
  var PROVISIONING_GROUPS = ["users", "audit", "policy", "whoami", "login"];
@@ -734,7 +746,7 @@ async function audit(args, io) {
734
746
  const text = await liveClient(ctx).audit.export({ format, ...pick(flags) });
735
747
  const out = str(flags, "out");
736
748
  if (out) {
737
- const target = path3.resolve(io.cwd, out);
749
+ const target = path4.resolve(io.cwd, out);
738
750
  await writeFile(target, text, { mode: 384 });
739
751
  await chmod(target, 384).catch(() => void 0);
740
752
  emit(ctx, { out, bytes: text.length, format }, [`wrote ${text.length} characters of ${format} to ${out}`]);
@@ -867,7 +879,7 @@ async function readBody(flags, io) {
867
879
  if (typeof file !== "string") throw new UsageError2("falta --file con el JSON de la petici\xF3n");
868
880
  let parsed;
869
881
  try {
870
- parsed = JSON.parse(await readFile(path3.resolve(io.cwd, file), "utf8"));
882
+ parsed = JSON.parse(await readFile(path4.resolve(io.cwd, file), "utf8"));
871
883
  } catch (error) {
872
884
  throw new UsageError2(`no se pudo leer ${file}: ${error instanceof Error ? error.message : String(error)}`);
873
885
  }
@@ -1017,10 +1029,379 @@ async function runExperimentsCli(group, args, io) {
1017
1029
  return EXPERIMENTS_EXIT.failure;
1018
1030
  }
1019
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
1020
1400
  var EXPERIENCE_GROUPS = ["experience"];
1021
1401
  var EXPERIENCE_EXIT = { ok: 0, invalid: 1, usage: 2, auth: 3, conflict: 4, failure: 5 };
1022
1402
  var EXPERIENCE_HELP = [
1023
- "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):",
1024
1405
  " customy experience pull [--dir catalogs] [--namespace a,b] [--locale es,en] [--draft] download catalog@1 files (sorted by key) + a lock file",
1025
1406
  ' customy experience push [file.json ...] [--dir catalogs] [--create] [--rebase] [--publish] [--note "..."]',
1026
1407
  " [--ack-remove k1,k2] [--ack-placeholders k3] [--plan free|pro|enterprise] [--dry-run]",
@@ -1036,11 +1417,15 @@ var EXPERIENCE_HELP = [
1036
1417
  ' customy experience scope show | rotate --reason "..." | retire [--force] delivery scope (rotate/retire: experience.scope.rotate)',
1037
1418
  " customy experience signing plan [--retire id,id] [--threshold n] [--compromised id,id] READ-ONLY key rotation plan",
1038
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",
1039
1423
  " customy experience reconcile <channel> after a database restore (storage ahead of database)",
1424
+ ...INTEGRATOR_HELP,
1040
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."
1041
1426
  ];
1042
1427
  var LOCK_FILE = ".customy-experience.lock.json";
1043
- 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"]);
1044
1429
  var UsageError3 = class extends Error {
1045
1430
  };
1046
1431
  var ExitError = class extends Error {
@@ -1096,32 +1481,58 @@ function serializeCatalog(doc) {
1096
1481
  return `${JSON.stringify({ version: doc.version, namespace: doc.namespace, locale: doc.locale, syntax: doc.syntax, messages: messages2 }, null, 2)}
1097
1482
  `;
1098
1483
  }
1099
- 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) {
1100
1497
  const base = (typeof flags["base-url"] === "string" ? flags["base-url"] : io.env.CUSTOMY_EXPERIENCE_URL)?.replace(/\/+$/, "");
1101
1498
  if (!base) throw new UsageError3("falta el origen: --base-url o CUSTOMY_EXPERIENCE_URL");
1102
1499
  if (!/^https:\/\//i.test(base) && !/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?(\/|$)/i.test(base)) {
1103
1500
  throw new UsageError3("el origen de Experience debe ser https:// (http:// solo hacia localhost): el token viajar\xEDa en claro");
1104
1501
  }
1105
- const token = io.env.CUSTOMY_EXPERIENCE_TOKEN;
1106
- 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)");
1107
1504
  const timeout = typeof flags.timeout === "string" ? Number(flags.timeout) : 3e4;
1108
1505
  if (!Number.isFinite(timeout) || timeout < 1) throw new UsageError3("--timeout debe ser un n\xFAmero de milisegundos");
1109
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;
1110
1510
  return {
1111
1511
  origin: base,
1512
+ api,
1112
1513
  async request(method, route, options = {}) {
1113
- 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)}` : "";
1114
1516
  let response;
1115
- try {
1116
- response = await doFetch(`${base}/api/experience${route}${query}`, {
1117
- method,
1118
- headers: { authorization: `Bearer ${token}`, accept: "application/json", "user-agent": "customy-cli", ...options.body !== void 0 ? { "content-type": "application/json" } : {} },
1119
- ...options.body !== void 0 ? { body: JSON.stringify(options.body) } : {},
1120
- signal: AbortSignal.timeout(timeout)
1121
- });
1122
- } catch (error) {
1123
- 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;
1124
1534
  }
1535
+ if (!response) throw new ExitError(EXPERIENCE_EXIT.failure, `no se pudo conectar con ${base}`);
1125
1536
  const text = await response.text();
1126
1537
  let data;
1127
1538
  try {
@@ -1147,7 +1558,8 @@ function exitFor(error) {
1147
1558
  }
1148
1559
  function explain(error, what) {
1149
1560
  const details = isRec(error.details) ? error.details : {};
1150
- 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.`;
1151
1563
  if (error.status === 403) return `${what}: sin permiso (403). ${error.message}`;
1152
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.`;
1153
1565
  if (error.status === 402) return `${what}: tope del plan agotado (402). ${error.message}`;
@@ -1159,6 +1571,8 @@ function explain(error, what) {
1159
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.`;
1160
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" : ""}.`;
1161
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}`;
1162
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).`;
1163
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.`;
1164
1578
  if (error.name === "fallback_invalid" || error.name === "fallback_revoked") return `${what}: ${error.message} (canales: ${channelNames(details.channels)})`;
@@ -1176,7 +1590,7 @@ var lockKey = (namespace, locale) => `${namespace}/${locale}`;
1176
1590
  var fileName = (namespace, locale) => `${namespace}.${locale}.json`;
1177
1591
  async function readLock(dir) {
1178
1592
  try {
1179
- 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"));
1180
1594
  return isRec(parsed) && isRec(parsed.artifacts) ? parsed : null;
1181
1595
  } catch {
1182
1596
  return null;
@@ -1189,12 +1603,12 @@ async function catalogFilesIn(dir) {
1189
1603
  } catch {
1190
1604
  throw new UsageError3(`no se pudo leer el directorio ${dir}`);
1191
1605
  }
1192
- 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));
1193
1607
  }
1194
1608
  async function loadFiles(files, io) {
1195
1609
  const out = [];
1196
1610
  for (const file of files) {
1197
- const display = path3.relative(io.cwd, file) || file;
1611
+ const display = path4.relative(io.cwd, file) || file;
1198
1612
  try {
1199
1613
  out.push({ file, display, raw: JSON.parse(await readFile(file, "utf8")), parseError: null });
1200
1614
  } catch (error) {
@@ -1241,7 +1655,7 @@ async function readArtifactDoc(client, id, draft) {
1241
1655
  }
1242
1656
  async function pull(flags, io) {
1243
1657
  const client = makeClient(flags, io);
1244
- 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");
1245
1659
  const namespaces = list(flags.namespace);
1246
1660
  const locales = list(flags.locale);
1247
1661
  const artifacts = (await listCatalogArtifacts(client)).filter((a) => (!namespaces.length || namespaces.includes(str2(a.name))) && (!locales.length || locales.includes(str2(a.locale))));
@@ -1262,29 +1676,29 @@ async function pull(flags, io) {
1262
1676
  continue;
1263
1677
  }
1264
1678
  const { doc: checkedDoc, revision, contentHash, draftVersion } = read2;
1265
- const file = path3.join(dir, fileName(name, locale));
1679
+ const file = path4.join(dir, fileName(name, locale));
1266
1680
  const content = serializeCatalog(checkedDoc);
1267
1681
  let existing = null;
1268
1682
  try {
1269
1683
  existing = await readFile(file, "utf8");
1270
1684
  } catch {
1271
1685
  }
1272
- if (existing === content) unchanged.push(path3.relative(io.cwd, file));
1686
+ if (existing === content) unchanged.push(path4.relative(io.cwd, file));
1273
1687
  else {
1274
1688
  await writeFile(file, content);
1275
- written.push(path3.relative(io.cwd, file));
1689
+ written.push(path4.relative(io.cwd, file));
1276
1690
  }
1277
1691
  lock.artifacts[lockKey(name, locale)] = { artifactId: id, revision, contentHash, draftVersion };
1278
1692
  }
1279
- 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)}
1280
1694
  `);
1281
1695
  const lines = [
1282
1696
  ...written.map((f) => `\u2713 ${f}`),
1283
1697
  ...unchanged.map((f) => `= ${f} (sin cambios)`),
1284
1698
  ...skipped.map((s) => `- ${s.name}/${s.locale}: ${s.reason}`),
1285
- `${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))})`
1286
1700
  ];
1287
- 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)) } };
1288
1702
  }
1289
1703
  function checkAckFlags(flags) {
1290
1704
  const ackRemove = list(flags["ack-remove"]);
@@ -1294,8 +1708,8 @@ function checkAckFlags(flags) {
1294
1708
  }
1295
1709
  async function push(positional, flags, io) {
1296
1710
  const limits = limitsOf(flags);
1297
- const dir = path3.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
1298
- 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);
1299
1713
  if (!files.length) throw new UsageError3("no hay ficheros que subir: pasa archivos o --dir con catalog@1");
1300
1714
  checkAckFlags(flags);
1301
1715
  const loaded = await loadFiles(files, io);
@@ -1316,38 +1730,38 @@ async function push(positional, flags, io) {
1316
1730
  if (flags["dry-run"]) {
1317
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 })) } };
1318
1732
  }
1319
- 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);
1320
1734
  }
1321
1735
  async function uploadDocs(docs, flags, io, lockDir) {
1322
1736
  const ackRemove = list(flags["ack-remove"]);
1323
1737
  const ackPlaceholders = list(flags["ack-placeholders"]);
1324
1738
  const client = makeClient(flags, io);
1325
1739
  const lock = await readLock(lockDir);
1326
- 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`);
1327
1741
  const lockFile = { version: 1, origin: client.origin, artifacts: { ...lock?.artifacts ?? {} } };
1328
1742
  const known = await listCatalogArtifacts(client);
1329
1743
  const results = [];
1330
1744
  const lines = [];
1331
1745
  const saveLock = async () => {
1332
1746
  await mkdir(lockDir, { recursive: true }).catch(() => void 0);
1333
- 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)}
1334
1748
  `).catch(() => void 0);
1335
1749
  };
1336
1750
  for (const { display, doc } of docs) {
1337
1751
  const key2 = lockKey(doc.namespace, doc.locale);
1338
- const label = `${display} (${key2})`;
1752
+ const label2 = `${display} (${key2})`;
1339
1753
  try {
1340
1754
  let artifact = known.find((a) => a.name === doc.namespace && a.locale === doc.locale);
1341
1755
  let created = false;
1342
1756
  if (!artifact) {
1343
- 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`);
1344
1758
  artifact = await client.request("POST", "/artifacts", { body: { kind: "catalog", name: doc.namespace, locale: doc.locale } });
1345
1759
  created = true;
1346
1760
  }
1347
1761
  const id = str2(artifact.id);
1348
1762
  let entry = lockFile.artifacts[key2];
1349
1763
  if (!created && (!entry || entry.artifactId !== id)) {
1350
- 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.`);
1351
1765
  const detail = await client.request("GET", `/artifacts/${encodeURIComponent(id)}`);
1352
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 };
1353
1767
  }
@@ -1358,7 +1772,7 @@ async function uploadDocs(docs, flags, io, lockDir) {
1358
1772
  const draftVersion = isRec(saved) && typeof saved.version === "number" ? saved.version : base.draftVersion + 1;
1359
1773
  lockFile.artifacts[key2] = { ...base, draftVersion };
1360
1774
  const outcome = { file: display, namespace: doc.namespace, locale: doc.locale, artifactId: id, artifactCreated: created, revisionBase: base.revision, draftVersion, published: null };
1361
- 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" : ""}`);
1362
1776
  if (flags.publish) {
1363
1777
  const body = { ...typeof flags.note === "string" ? { note: flags.note } : {}, ...ackRemove.length || ackPlaceholders.length ? { acknowledge: { ...ackRemove.length ? { removeKeys: ackRemove } : {}, ...ackPlaceholders.length ? { placeholderKeys: ackPlaceholders } : {} } } : {} };
1364
1778
  const published = await client.request("POST", `/artifacts/${encodeURIComponent(id)}/revisions`, { body, query: catalogHint });
@@ -1367,12 +1781,12 @@ async function uploadDocs(docs, flags, io, lockDir) {
1367
1781
  const n = typeof rev.n === "number" ? rev.n : base.revision;
1368
1782
  outcome.published = { created: wasCreated, revision: n, contentHash: typeof rev.contentHash === "string" ? rev.contentHash : null, warnings: isRec(published) && Array.isArray(published.warnings) ? published.warnings : [] };
1369
1783
  lockFile.artifacts[key2] = { artifactId: id, revision: n, contentHash: typeof rev.contentHash === "string" ? rev.contentHash : null, draftVersion };
1370
- 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`);
1371
1785
  }
1372
1786
  results.push(outcome);
1373
1787
  } catch (error) {
1374
1788
  await saveLock();
1375
- 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"));
1376
1790
  if (error instanceof ExitError) throw new ExitError(error.code, [...lines, `\u2717 ${error.message}`].join("\n"));
1377
1791
  throw error;
1378
1792
  }
@@ -1380,7 +1794,118 @@ async function uploadDocs(docs, flags, io, lockDir) {
1380
1794
  await saveLock();
1381
1795
  return { lines, result: { files: results } };
1382
1796
  }
1383
- 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;
1384
1909
  var opt = (v) => typeof v === "string" ? v : void 0;
1385
1910
  function scopeFrom(data) {
1386
1911
  if (!isRec(data)) return null;
@@ -1395,7 +1920,7 @@ function scopeFrom(data) {
1395
1920
  successor: typeof scope.successor === "string" ? scope.successor : null,
1396
1921
  drainsUntil: typeof scope.drainsUntil === "string" ? scope.drainsUntil : null,
1397
1922
  draining: view(data.draining),
1398
- 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) },
1399
1924
  delivery: {
1400
1925
  base: typeof delivery.base === "string" ? delivery.base : null,
1401
1926
  channels: (Array.isArray(delivery.channels) ? delivery.channels.filter(isRec) : []).map((c) => ({ channel: str2(c.channel), timestampUrl: typeof c.timestampUrl === "string" ? c.timestampUrl : null })),
@@ -1420,6 +1945,7 @@ function scopeLines(info) {
1420
1945
  ];
1421
1946
  }
1422
1947
  async function status(flags, io) {
1948
+ if (typeof flags.app === "string") return { ...await statusApp(flags, io), code: 0 };
1423
1949
  const client = makeClient(flags, io);
1424
1950
  const explicitWarn = typeof flags["warn-hours"] === "string" ? Number(flags["warn-hours"]) : null;
1425
1951
  if (explicitWarn !== null && (!Number.isFinite(explicitWarn) || explicitWarn < 0)) throw new UsageError3("--warn-hours debe ser un n\xFAmero de horas");
@@ -1470,12 +1996,12 @@ async function usedKeys(root) {
1470
1996
  if (depth > 12) return;
1471
1997
  for (const entry of (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name < b.name ? -1 : 1)) {
1472
1998
  if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "dist" || entry.name === "build") continue;
1473
- const full = path3.join(dir, entry.name);
1999
+ const full = path4.join(dir, entry.name);
1474
2000
  if (entry.isDirectory()) {
1475
2001
  await walk(full, depth + 1);
1476
2002
  continue;
1477
2003
  }
1478
- if (!entry.isFile() || !SRC_EXT.has(path3.extname(entry.name))) continue;
2004
+ if (!entry.isFile() || !SRC_EXT.has(path4.extname(entry.name))) continue;
1479
2005
  if ((await stat(full)).size > 1e6) continue;
1480
2006
  const text = await readFile(full, "utf8");
1481
2007
  for (const pattern of USAGE_PATTERNS) for (const match of text.matchAll(pattern)) if (!found.has(match[1])) found.set(match[1], full);
@@ -1486,9 +2012,9 @@ async function usedKeys(root) {
1486
2012
  }
1487
2013
  async function check(flags, io) {
1488
2014
  const limits = limitsOf(flags);
1489
- 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");
1490
2016
  const loaded = (await loadFiles(await catalogFilesIn(dir), io)).filter((item) => item.parseError || isCatalogLike(item.raw));
1491
- 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) || "."}`);
1492
2018
  const failures = [];
1493
2019
  const invalid = [];
1494
2020
  const byNamespace = /* @__PURE__ */ new Map();
@@ -1524,7 +2050,7 @@ async function check(flags, io) {
1524
2050
  const glossary = await loadGlossary(flags, io);
1525
2051
  const strict = flags.strict === true;
1526
2052
  const mismatched = new Set(parity.flatMap((p) => p.placeholderMismatch.map((m) => `${String(p.namespace)}\0${m.locale}\0${m.key}`)));
1527
- const { checkCatalog } = await import('./quality-ILK6IA5O.mjs');
2053
+ const { checkCatalog } = await import('./quality-UALNP7GO.mjs');
1528
2054
  const findings2 = [];
1529
2055
  const warnings = [];
1530
2056
  for (const p of parity) {
@@ -1546,7 +2072,7 @@ async function check(flags, io) {
1546
2072
  }
1547
2073
  let usage = null;
1548
2074
  if (typeof flags.src === "string") {
1549
- const src = path3.resolve(io.cwd, flags.src);
2075
+ const src = path4.resolve(io.cwd, flags.src);
1550
2076
  let used;
1551
2077
  try {
1552
2078
  used = await usedKeys(src);
@@ -1557,8 +2083,8 @@ async function check(flags, io) {
1557
2083
  for (const p of parity) for (const key2 of Object.keys((byNamespace.get(String(p.namespace)) ?? {})[String(p.base)] ?? {})) defined.add(key2);
1558
2084
  const missing = [...used.keys()].filter((key2) => !defined.has(key2)).sort();
1559
2085
  const unused = [...defined].filter((key2) => !used.has(key2)).sort();
1560
- 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 };
1561
- 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`);
1562
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`);
1563
2089
  }
1564
2090
  const ok = failures.length === 0;
@@ -1575,7 +2101,7 @@ async function loadGlossary(flags, io) {
1575
2101
  if (typeof flags.glossary !== "string") throw new UsageError3("--glossary necesita un fichero");
1576
2102
  let raw;
1577
2103
  try {
1578
- 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"));
1579
2105
  } catch (error) {
1580
2106
  throw new UsageError3(`--glossary: no se pudo leer ${flags.glossary} como JSON (${error instanceof Error ? error.message : String(error)})`);
1581
2107
  }
@@ -1625,9 +2151,9 @@ function formatFlag(flags, allowAuto) {
1625
2151
  }
1626
2152
  function outputPath(out, io, fallbackDir, name, single) {
1627
2153
  if (out !== void 0 && typeof out !== "string") throw new UsageError3("--out necesita una ruta");
1628
- if (out === void 0) return path3.resolve(io.cwd, fallbackDir, name);
1629
- const resolved = path3.resolve(io.cwd, out);
1630
- 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);
1631
2157
  }
1632
2158
  async function exportCmd(flags, io) {
1633
2159
  const format = formatFlag(flags, false);
@@ -1642,9 +2168,9 @@ async function exportCmd(flags, io) {
1642
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`);
1643
2169
  if (!byNamespace.size) throw new ExitError(EXPERIENCE_EXIT.invalid, "no hay cat\xE1logos en el servidor que exportar");
1644
2170
  const tools = {
1645
- xliff: format === "xliff" ? await import('./xliff-DEJHB2SY.mjs') : null,
1646
- po: format === "po" ? await import('./po-AKWHAYBL.mjs') : null,
1647
- 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
1648
2174
  };
1649
2175
  const exported = [];
1650
2176
  const skipped = [];
@@ -1694,9 +2220,9 @@ async function exportCmd(flags, io) {
1694
2220
  const lines = [];
1695
2221
  for (const job of jobs) {
1696
2222
  const file = outputPath(flags.out, io, "translations", job.name, jobs.length === 1);
1697
- await mkdir(path3.dirname(file), { recursive: true });
2223
+ await mkdir(path4.dirname(file), { recursive: true });
1698
2224
  await writeFile(file, job.content);
1699
- const shown = path3.relative(io.cwd, file) || file;
2225
+ const shown = path4.relative(io.cwd, file) || file;
1700
2226
  exported.push({ namespace: job.namespace, locale: job.locale, format, file: shown, keys: job.keys, source: draft ? "draft" : "published", from: job.from });
1701
2227
  lines.push(`\u2713 ${shown} (${job.namespace}/${job.locale}, ${job.keys} claves, ${job.from})`);
1702
2228
  }
@@ -1706,7 +2232,7 @@ async function exportCmd(flags, io) {
1706
2232
  }
1707
2233
  function detectFormat(flag, file, text) {
1708
2234
  if (flag !== "auto") return flag;
1709
- const ext = path3.extname(file).toLowerCase();
2235
+ const ext = path4.extname(file).toLowerCase();
1710
2236
  if (ext === ".xlf" || ext === ".xliff") return "xliff";
1711
2237
  if (ext === ".po" || ext === ".pot") return "po";
1712
2238
  if (ext === ".json") return "json";
@@ -1731,9 +2257,9 @@ async function importCmd(positional, flags, io) {
1731
2257
  const localeFlag = singleLocale(flags, "locale");
1732
2258
  const sourceLocaleFlag = singleLocale(flags, "source-locale");
1733
2259
  const glossary = await loadGlossary(flags, io);
1734
- const dir = path3.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
1735
- const file = path3.resolve(io.cwd, positional[0]);
1736
- 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;
1737
2263
  let size;
1738
2264
  try {
1739
2265
  const info = await stat(file);
@@ -1755,10 +2281,10 @@ async function importCmd(positional, flags, io) {
1755
2281
  let target;
1756
2282
  try {
1757
2283
  if (format === "xliff") {
1758
- const t = await import('./xliff-DEJHB2SY.mjs');
2284
+ const t = await import('./xliff-IAIUQGY4.mjs');
1759
2285
  ({ source, target } = t.xliffToCatalogs(t.importXliff(bytes, namespaceFlag ? { namespace: namespaceFlag } : {})));
1760
2286
  } else if (format === "po") {
1761
- const t = await import('./po-AKWHAYBL.mjs');
2287
+ const t = await import('./po-AD6IPL4F.mjs');
1762
2288
  ({ source, target } = t.poToCatalogs(t.parsePo(text), { ...namespaceFlag ? { namespace: namespaceFlag } : {}, ...sourceLocaleFlag ? { sourceLocale: sourceLocaleFlag } : {}, ...localeFlag ? { targetLocale: localeFlag } : {} }));
1763
2289
  } else {
1764
2290
  let parsed;
@@ -1773,9 +2299,9 @@ async function importCmd(positional, flags, io) {
1773
2299
  source = null;
1774
2300
  target = checked2.doc;
1775
2301
  } else {
1776
- const t = await import('./json-NETFQXLJ.mjs');
2302
+ const t = await import('./json-37BBZACO.mjs');
1777
2303
  const flat = t.parseFlatJson(text);
1778
- 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$/);
1779
2305
  const namespace = namespaceFlag ?? named?.[1];
1780
2306
  const locale = localeFlag ?? named?.[2];
1781
2307
  if (!namespace || !locale) throw new UsageError3("un JSON plano necesita --namespace y --locale (o un nombre \xAB<espacio>.<idioma>.json\xBB)");
@@ -1798,7 +2324,7 @@ async function importCmd(positional, flags, io) {
1798
2324
  }
1799
2325
  const doc = checked.doc;
1800
2326
  if (!source && format === "json") {
1801
- const localSource = path3.join(dir, fileName(doc.namespace, sourceLocaleFlag ?? "en"));
2327
+ const localSource = path4.join(dir, fileName(doc.namespace, sourceLocaleFlag ?? "en"));
1802
2328
  try {
1803
2329
  const candidate = validateCatalog(JSON.parse(await readFile(localSource, "utf8")), { limits: TRANSLATION_PLAN_LIMITS.enterprise });
1804
2330
  if (candidate.ok && candidate.doc && candidate.doc.locale !== doc.locale) source = candidate.doc;
@@ -1808,7 +2334,7 @@ async function importCmd(positional, flags, io) {
1808
2334
  const findings2 = [];
1809
2335
  const noteLines = [];
1810
2336
  if (source) {
1811
- const { checkCatalog } = await import('./quality-ILK6IA5O.mjs');
2337
+ const { checkCatalog } = await import('./quality-UALNP7GO.mjs');
1812
2338
  for (const f of checkCatalog(source, doc, { glossary, severities: QUALITY_SEVERITIES })) findings2.push(qualityRow(doc.namespace, f));
1813
2339
  const strictFail = flags.strict === true;
1814
2340
  const failing = (row) => row.severity === "error" || strictFail && row.severity === "warning";
@@ -1837,8 +2363,8 @@ async function pseudoCmd(positional, flags, io) {
1837
2363
  if (locale === sourceLocale) throw new UsageError3("--locale no puede ser el idioma de origen");
1838
2364
  const limits = limitsOf(flags);
1839
2365
  const namespaces = list(flags.namespace);
1840
- const dir = path3.resolve(io.cwd, typeof flags.dir === "string" ? flags.dir : "catalogs");
1841
- 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);
1842
2368
  const loaded = (await loadFiles(files, io)).filter((item) => positional.length || item.parseError || isCatalogLike(item.raw));
1843
2369
  const sources = [];
1844
2370
  const problems = [];
@@ -1859,7 +2385,7 @@ async function pseudoCmd(positional, flags, io) {
1859
2385
  if (!namespaces.length || namespaces.includes(checked.doc.namespace)) sources.push({ display: item.display, doc: checked.doc });
1860
2386
  }
1861
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"));
1862
- 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) || "."}`);
1863
2389
  const { pseudoLocalizeMessages } = await import('./pseudo-CKYMJJBX.mjs');
1864
2390
  const outputs = [];
1865
2391
  for (const { display, doc } of sources) {
@@ -1876,14 +2402,14 @@ async function pseudoCmd(positional, flags, io) {
1876
2402
  outputs.push({ doc: checked.doc, from: display });
1877
2403
  }
1878
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"));
1879
- const fallbackDir = positional.length ? path3.dirname(files[0]) : dir;
2405
+ const fallbackDir = positional.length ? path4.dirname(files[0]) : dir;
1880
2406
  const written = [];
1881
2407
  const lines = [];
1882
2408
  for (const { doc, from } of outputs) {
1883
- const target = outputPath(flags.out, io, path3.relative(io.cwd, fallbackDir) || ".", fileName(doc.namespace, locale), outputs.length === 1);
1884
- 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 });
1885
2411
  await writeFile(target, serializeCatalog(doc));
1886
- const shown = path3.relative(io.cwd, target) || target;
2412
+ const shown = path4.relative(io.cwd, target) || target;
1887
2413
  written.push({ namespace: doc.namespace, locale, strategy: flags.rtl ? "rtl" : "accented", file: shown, from, keys: Object.keys(doc.messages).length });
1888
2414
  lines.push(`\u2713 ${shown} (${doc.namespace}/${locale}, ${Object.keys(doc.messages).length} claves, desde ${from})`);
1889
2415
  }
@@ -1926,8 +2452,8 @@ var rolesOf = (key2) => Array.isArray(key2.roles) ? key2.roles.filter((r) => typ
1926
2452
  async function initCmd(flags, io) {
1927
2453
  const client = makeClient(flags, io);
1928
2454
  const channel = channelFlag(flags, "production");
1929
- const out = path3.resolve(io.cwd, typeof flags.out === "string" ? flags.out : CONFIG_FILE);
1930
- 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;
1931
2457
  if (!flags.force) {
1932
2458
  let exists = true;
1933
2459
  try {
@@ -1951,7 +2477,7 @@ async function initCmd(flags, io) {
1951
2477
  const tenant = isRec(context3) && isRec(context3.tenant) ? context3.tenant : {};
1952
2478
  const environmentId = typeof tenant.environmentId === "string" ? tenant.environmentId : null;
1953
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 };
1954
- await mkdir(path3.dirname(out), { recursive: true });
2480
+ await mkdir(path4.dirname(out), { recursive: true });
1955
2481
  await writeFile(out, `${JSON.stringify(config, null, 2)}
1956
2482
  `);
1957
2483
  const lines = [
@@ -1970,14 +2496,14 @@ async function revokeCmd(positional, flags, io) {
1970
2496
  const target = await resolveRelease(client, positional[0]);
1971
2497
  const fallback = typeof flags.fallback === "string" ? await resolveRelease(client, flags.fallback) : null;
1972
2498
  if (fallback && fallback.id === target.id) throw new UsageError3("--fallback no puede ser el release que se revoca");
1973
- const label = `release ${target.number !== null ? `#${target.number} ` : ""}${target.id}`;
1974
- 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 } };
1975
2501
  const result = await client.request("POST", `/releases/${encodeURIComponent(target.id)}/revoke`, { body: { reason, ...fallback ? { fallbackReleaseId: fallback.id } : {} } });
1976
2502
  const rec = isRec(result) ? result : {};
1977
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 }));
1978
2504
  const already = rec.alreadyRevoked === true;
1979
2505
  const lines = [
1980
- already ? `= ${label}: ya estaba revocado` : `\u2713 ${label}: revocado`,
2506
+ already ? `= ${label2}: ya estaba revocado` : `\u2713 ${label2}: revocado`,
1981
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)`),
1982
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)."] : []
1983
2509
  ];
@@ -2056,12 +2582,12 @@ async function reconcileCmd(positional, flags, io) {
2056
2582
  const rec = await client.request("POST", `/channels/${encodeURIComponent(channel)}/reconcile`, { body: {} });
2057
2583
  const data = isRec(rec) ? rec : {};
2058
2584
  const republished = isRec(data.republished) ? data.republished : null;
2059
- const num2 = (value) => typeof value === "number" ? value : null;
2585
+ const num3 = (value) => typeof value === "number" ? value : null;
2060
2586
  const lines = [
2061
- `\u2713 canal ${channel} reconciliado: contador ${num2(data.previousSequence) ?? "?"} \u2192 ${num2(data.sequence) ?? "?"} (el almac\xE9n anunci\xF3 hasta ${num2(data.storedSequence) ?? "?"})`,
2062
- 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"
2063
2589
  ];
2064
- 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 } };
2065
2591
  }
2066
2592
  async function runExperienceCli(args, io) {
2067
2593
  const asJson = args.includes("--json");
@@ -2110,8 +2636,26 @@ async function runExperienceCli(args, io) {
2110
2636
  case "reconcile":
2111
2637
  outcome = await reconcileCmd(positional, flags, io);
2112
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;
2113
2657
  default:
2114
- 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)`);
2115
2659
  }
2116
2660
  const code = outcome.code ?? EXPERIENCE_EXIT.ok;
2117
2661
  if (asJson) io.out(JSON.stringify({ ok: code === 0, command: command2, exitCode: code, ...isRec(outcome.result) ? outcome.result : { result: outcome.result } }, null, 2));
@@ -2236,7 +2780,7 @@ function table2(rows) {
2236
2780
  }
2237
2781
  async function readJsonFile(io, file) {
2238
2782
  try {
2239
- return JSON.parse(await readFile(path3.resolve(io.cwd, file), "utf8"));
2783
+ return JSON.parse(await readFile(path4.resolve(io.cwd, file), "utf8"));
2240
2784
  } catch (error) {
2241
2785
  throw new UsageError4(`no se pudo leer ${file}: ${error instanceof Error ? error.message : String(error)}`);
2242
2786
  }
@@ -2542,10 +3086,10 @@ async function tail(args, io) {
2542
3086
  }
2543
3087
  return WHATSAPP_EXIT.ok;
2544
3088
  }
2545
- function dryRun(ctx, method, path6, body) {
2546
- 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 } }, [
2547
3091
  "DRY RUN (no se cambia nada)",
2548
- `${method} ${path6}`,
3092
+ `${method} ${path7}`,
2549
3093
  ...body === void 0 ? [] : [JSON.stringify(body, null, 2)]
2550
3094
  ]);
2551
3095
  return WHATSAPP_EXIT.ok;
@@ -2665,7 +3209,7 @@ async function recipientsFromFile(io, file) {
2665
3209
  return parsed;
2666
3210
  }
2667
3211
  try {
2668
- 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);
2669
3213
  } catch (error) {
2670
3214
  throw new UsageError4(`no se pudo leer ${file}: ${error instanceof Error ? error.message : String(error)}`);
2671
3215
  }
@@ -2868,7 +3412,7 @@ async function webhookBody(flags, io) {
2868
3412
  if (file === void 0 === (inline === void 0)) throw new UsageError4("indica exactamente uno: --body-file o --body (el cuerpo CRUDO, sin re-serializar)");
2869
3413
  if (inline !== void 0) return inline;
2870
3414
  try {
2871
- return await readFile(path3.resolve(io.cwd, file), "utf8");
3415
+ return await readFile(path4.resolve(io.cwd, file), "utf8");
2872
3416
  } catch (error) {
2873
3417
  throw new UsageError4(`no se pudo leer ${file}: ${error instanceof Error ? error.message : String(error)}`);
2874
3418
  }
@@ -3165,12 +3709,12 @@ function option(args, name) {
3165
3709
  return index >= 0 ? args[index + 1] : void 0;
3166
3710
  }
3167
3711
  async function loadManifest(args, io) {
3168
- 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");
3169
3713
  let raw;
3170
3714
  try {
3171
3715
  raw = JSON.parse(await readFile(file, "utf8"));
3172
3716
  } catch (error) {
3173
- 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}`);
3174
3718
  return null;
3175
3719
  }
3176
3720
  const result = validateManifest(raw);
@@ -3202,17 +3746,18 @@ async function runCli(argv, io) {
3202
3746
  return 0;
3203
3747
  }
3204
3748
  if (command2 === "codegen") {
3205
- const out = path3.resolve(io.cwd, option(args, "out") ?? "customy.generated.ts");
3206
- 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 });
3207
3751
  await writeFile(out, generateAppTypes(manifest));
3208
- 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)}`);
3209
3753
  return 0;
3210
3754
  }
3211
3755
  const workspaceEnvironmentId = option(args, "workspace-env");
3212
3756
  const accessUrl = io.env.CUSTOMY_ACCESS_URL;
3213
3757
  const token = io.env.CUSTOMY_ACCESS_TOKEN;
3214
- if (!workspaceEnvironmentId || !accessUrl || !token) {
3215
- io.err("sync necesita --workspace-env y las variables CUSTOMY_ACCESS_URL y CUSTOMY_ACCESS_TOKEN");
3758
+ const adminSecret = io.env.CUSTOMY_ADMIN_SECRET;
3759
+ if (!workspaceEnvironmentId || !accessUrl || !token && !adminSecret) {
3760
+ io.err("sync necesita --workspace-env, CUSTOMY_ACCESS_URL y una credencial: CUSTOMY_ADMIN_SECRET (x-admin-secret, producci\xF3n) o CUSTOMY_ACCESS_TOKEN (Bearer)");
3216
3761
  return 2;
3217
3762
  }
3218
3763
  try {
@@ -3220,12 +3765,19 @@ async function runCli(argv, io) {
3220
3765
  manifest,
3221
3766
  accessUrl,
3222
3767
  token,
3768
+ adminSecret,
3769
+ actor: io.env.CUSTOMY_ADMIN_ACTOR,
3223
3770
  workspaceEnvironmentId,
3224
3771
  reason: option(args, "reason") ?? `customy apps sync ${manifest.key}`,
3225
3772
  fetch: io.fetch
3226
3773
  });
3227
3774
  const verb = { installed: "instalada", updated: "actualizada", unchanged: "sin cambios" }[result.action];
3228
3775
  io.out(`\u2713 ${manifest.key} ${verb}: aplicaci\xF3n ${result.applicationId}, entorno ${result.environmentId}, revisi\xF3n ${result.revision} (${authorizationSummary(manifest)})`);
3776
+ if (result.publishableKey) {
3777
+ io.out("Para el .env de la app (la clave p\xFAblica no es secreta):");
3778
+ io.out(`CUSTOMY_PUBLISHABLE_KEY=${result.publishableKey}`);
3779
+ }
3780
+ io.out(`CUSTOMY_ENVIRONMENT_ID=${result.environmentId}`);
3229
3781
  let failed = false;
3230
3782
  for (const [product2, outcome] of Object.entries(result.reconciliation)) {
3231
3783
  if (outcome.status === "failed") {