@customyai/experience-brand 0.0.0-stage → 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,69 @@
1
- # Temporary Holding Version
1
+ # @customyai/experience-brand
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Marca de Customy Experience (`tokens@1`, `appearance@2` opcional) para apps de Next de terceros. **Apagado por omisión**: sin `BRAND_LOADER=on` el HTML, las peticiones y el bundle son los de siempre. Nunca CSS libre: solo color de acción (`--primary`, `--ring`, `--primary-foreground`) y radio (`--radius`), tras validar firma, huella y contraste AA. Sin marca, con Experience caído o con marca de otro modo (claro/oscuro) la app se ve exactamente como antes.
4
+
5
+ Se genera desde el paquete interno `@customy/experience-brand` del monorepo (`node scripts/build-kit.mjs`); una sola fuente de código.
6
+
7
+ ## Instalación
8
+
9
+ ```bash
10
+ pnpm add @customyai/experience-brand@next @customyai/experience-web@next @customyai/experience-client
11
+ ```
12
+
13
+ Next ≥ 15 y React ≥ 18. En `next.config`: `transpilePackages: ["@customyai/experience-brand"]` (el paquete se entrega como fuente TypeScript).
14
+
15
+ ## Variables (todas públicas; ningún secreto)
16
+
17
+ | Variable | Notas |
18
+ |---|---|
19
+ | `BRAND_LOADER` | `on`/`1`/`true`. Cualquier otra cosa = apagado |
20
+ | `EXPERIENCE_BASE_URL` | https, p. ej. `https://xp.customy.ai` (staging: `https://xp-staging.customy.ai`) |
21
+ | `EXPERIENCE_BRAND_SCOPE` | scope del entorno de ENTREGA de ESTA app |
22
+ | `EXPERIENCE_BRAND_ENVIRONMENT_ID` | entorno de entrega de ESTA app (único por despliegue) |
23
+ | `EXPERIENCE_BRAND_CHANNEL` | `production` por omisión; usa `staging` en staging |
24
+ | `EXPERIENCE_ANCHORED_KEYS` | JSON con ≥ 2 claves públicas ancladas del entorno |
25
+ | `EXPERIENCE_BRAND_NAME` | base del artefacto: `miapp` ⇒ `miapp-light` / `miapp-dark` |
26
+ | `EXPERIENCE_BRAND_APPEARANCE` | `appearance@2` para leer color de acción + radio de la ficha |
27
+
28
+ Incompleta o mal formada, la bandera se queda apagada. Cada despliegue apunta a SU entorno: compartirlo con otra app compartiría su marca.
29
+
30
+ ## Ejemplo mínimo (App Router)
31
+
32
+ ```tsx
33
+ // app/layout.tsx (servidor)
34
+ import { resolveBrand } from "@customyai/experience-brand/server";
35
+ import { BrandScope } from "@customyai/experience-brand/scope";
36
+
37
+ const get = (key: string) => process.env[key];
38
+
39
+ export default async function RootLayout({ children }: { children: React.ReactNode }) {
40
+ const brand = await resolveBrand(get, "light"); // el modo de TU app
41
+ return (
42
+ <html lang="es">
43
+ <body>
44
+ <BrandScope brand={brand} scheme="light" scope="miapp">
45
+ {children}
46
+ </BrandScope>
47
+ </body>
48
+ </html>
49
+ );
50
+ }
51
+ ```
52
+
53
+ CSS: con `varMap="design-system"` (por omisión) el contenedor escribe `--primary`/`--ring`/`--radius` dentro de `data-customy-brand="miapp"` (formato `H S% L%`); tu app debe leer esas variables, con respaldo igual a su valor actual. Si tu app usa otro nombre de variable, pasa `varMap="ap"` y conecta `--ap-action`/`--ap-radius` en tu CSS.
54
+
55
+ CSP: si la fijas, añade el origen de Experience a `connect-src` con `withBrandConnectSrc(csp, brandConnectOrigin(get))` (de `@customyai/experience-brand/config`); con la bandera apagada no cambia nada.
56
+
57
+ ## Prueba mínima
58
+
59
+ 1. Bandera apagada: `renderToString(<BrandScope brand={null} …>hijos</BrandScope>)` es idéntico a `renderToString(hijos)`.
60
+ 2. Encendida en staging con el release de tu entorno: la página trae `data-customy-brand="miapp"` y `data-brand-source` (`initial` o `release`); `--primary` coincide con tu ficha.
61
+ 3. Configuración incompleta o Experience caído: HTML sin variables y sin errores.
62
+
63
+ ## Reversión
64
+
65
+ Quitar `BRAND_LOADER` y reiniciar; o mover el canal del entorno a un release sin `tokens`.
66
+
67
+ ## Requisitos de plataforma (no los crea el paquete)
68
+
69
+ Entorno de entrega con `customy-experience` conectado, llave de consumidor, artefactos `tokens` publicados en el canal y las claves públicas ancladas. Ver `docs/CUSTOMY_EXPERIENCE_BRAND_ENVIRONMENT_MAP.md` §5.
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@customyai/experience-brand",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0-rc.1",
4
+ "description": "Marca de Customy Experience (tokens@1/appearance@2) para apps de Next de terceros: apagada por omisión, sin CSS libre, degrada a lo que la app ya tenía.",
5
+ "type": "module",
6
+ "main": "src/index.ts",
7
+ "types": "src/index.ts",
8
+ "exports": {
9
+ ".": "./src/index.ts",
10
+ "./config": "./src/config.ts",
11
+ "./vars": "./src/vars.ts",
12
+ "./vars-v2": "./src/vars-v2.ts",
13
+ "./scope": "./src/scope.tsx",
14
+ "./server": "./src/server.ts",
15
+ "./scope-on": "./src/scope-on.tsx",
16
+ "./server-on": "./src/server-on.ts",
17
+ "./signin": "./src/signin.ts",
18
+ "./signin-client": "./src/signin-client.tsx",
19
+ "./signin-on": "./src/signin-on.ts"
20
+ },
21
+ "dependencies": {
22
+ "@customyai/experience-client": "^1.5.0",
23
+ "@customyai/experience-web": "^1.4.0-rc.1"
24
+ },
25
+ "peerDependencies": {
26
+ "next": ">=15.0.0",
27
+ "react": ">=18.0.0"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public",
31
+ "tag": "next"
32
+ },
33
+ "files": [
34
+ "src",
35
+ "README.md"
36
+ ],
37
+ "license": "UNLICENSED"
38
+ }
package/src/config.ts ADDED
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Configuración de la marca de Customy Experience (`tokens@1`) para las UIs de producto. PURA y diminuta a propósito: decide si el cargador está encendido y con qué
3
+ * configuración, sin importar nada de `@customyai/experience-web` (con la bandera apagada ese código no se carga ni en el servidor ni en el navegador).
4
+ *
5
+ * Apagado por omisión: hace falta `BRAND_LOADER` = `on` (o `1`/`true`) Y una configuración completa y con forma válida. Cualquier otra cosa devuelve `null` y la UI es la de siempre.
6
+ */
7
+ export interface BrandConfig {
8
+ readonly baseUrl: string;
9
+ readonly scope: string;
10
+ readonly environmentId: string;
11
+ readonly channel: string;
12
+ /** Claves públicas ancladas (JSON de `KeyRecord[]`): el cliente las valida; aquí solo se exige que sea una lista de al menos dos. */
13
+ readonly anchoredKeys: readonly unknown[];
14
+ /** Base del nombre del artefacto `tokens` (`ds` ⇒ `ds-light` / `ds-dark`); sin ella, el único que traiga el release. */
15
+ readonly name?: string;
16
+ /**
17
+ * Capacidad `appearance@2` del ENTORNO (OPT-IN): la declara el entorno con `EXPERIENCE_BRAND_APPEARANCE=appearance@2` (la misma capacidad que su manifiesto de Experience). Ausente o cualquier otro valor ⇒ la UI
18
+ * lee solo `appearance@1`, exactamente como hasta hoy.
19
+ */
20
+ readonly appearance2?: boolean;
21
+ }
22
+
23
+ export type BrandKey = "BRAND_LOADER" | "EXPERIENCE_BASE_URL" | "EXPERIENCE_SCOPE" | "EXPERIENCE_ENVIRONMENT_ID" | "EXPERIENCE_CHANNEL" | "EXPERIENCE_ANCHORED_KEYS" | "EXPERIENCE_BRAND_NAME" | "EXPERIENCE_BRAND_SCOPE" | "EXPERIENCE_BRAND_ENVIRONMENT_ID" | "EXPERIENCE_BRAND_CHANNEL" | "EXPERIENCE_BRAND_APPEARANCE";
24
+
25
+ /** Nombres (sin prefijo) que cada UI añade a la lista blanca de su `definePublicEnv`. */
26
+ export const BRAND_ENV_KEYS: readonly BrandKey[] = ["BRAND_LOADER", "EXPERIENCE_BASE_URL", "EXPERIENCE_SCOPE", "EXPERIENCE_ENVIRONMENT_ID", "EXPERIENCE_CHANNEL", "EXPERIENCE_ANCHORED_KEYS", "EXPERIENCE_BRAND_NAME", "EXPERIENCE_BRAND_SCOPE", "EXPERIENCE_BRAND_ENVIRONMENT_ID", "EXPERIENCE_BRAND_CHANNEL", "EXPERIENCE_BRAND_APPEARANCE"];
27
+
28
+ /**
29
+ * Las claves ancladas viven en DOS formas: `NEXT_PUBLIC_EXPERIENCE_ANCHORED_KEYS` (marca en el navegador, la lee `definePublicEnv`) y `EXPERIENCE_ANCHORED_KEYS` sin prefijo
30
+ * (composiciones en servidor). Si solo una está puesta, el servidor de la UI cae a la otra: se pasa como `serverAliases` de `definePublicEnv`.
31
+ */
32
+ export const BRAND_SERVER_ALIASES = { EXPERIENCE_ANCHORED_KEYS: ["EXPERIENCE_ANCHORED_KEYS"], EXPERIENCE_BASE_URL: ["EXPERIENCE_BASE_URL"], EXPERIENCE_SCOPE: ["EXPERIENCE_SCOPE"] } as const;
33
+
34
+ /** Si el cliente no logra un release (o el que tiene vence), se sigue con el último verificado hasta 7 días; pasado el plazo, el aspecto de siempre. */
35
+ export const BRAND_GRACE_MS = 7 * 24 * 3_600_000;
36
+
37
+ const ON = new Set(["on", "1", "true"]);
38
+ const NAME = /^[a-z][a-z0-9-]{1,47}$/;
39
+
40
+ /** Acepta el JSON de `EXPERIENCE_TRUSTED_KEYS` del servicio (sin `alg`; `roles` opcional) rellenando solo lo que falta; el cliente estricto sigue validando todo. */
41
+ function normalizeAnchoredKeys(keys: readonly unknown[]): readonly unknown[] {
42
+ return keys.map((k) => {
43
+ if (typeof k !== "object" || k === null || Array.isArray(k)) return k;
44
+ const r = k as Record<string, unknown>;
45
+ return { ...r, ...(r.alg === undefined ? { alg: "ed25519" } : {}), ...(r.roles === undefined ? { roles: ["manifest", "timestamp"] } : {}) };
46
+ });
47
+ }
48
+
49
+ /** ¿Está encendida la bandera? No mira nada más (sirve a la CSP, que solo necesita saber si hay que abrir el origen de Experience). */
50
+ export function brandLoaderEnabled(get: (key: BrandKey) => string | undefined): boolean {
51
+ return ON.has((get("BRAND_LOADER") ?? "").trim().toLowerCase());
52
+ }
53
+
54
+ /**
55
+ * La marca tiene variables PROPIAS de scope / entorno / canal (`EXPERIENCE_BRAND_*`) porque `EXPERIENCE_SCOPE` / `_ENVIRONMENT_ID` / `_CHANNEL` ya las usan el catálogo y las cadenas de la UI
56
+ * (otro tenant). Si las propias no están, cae a las compartidas (compatibilidad con lo ya desplegado).
57
+ */
58
+ const brandVar = (get: (key: BrandKey) => string | undefined, own: BrandKey, shared: BrandKey): string => (get(own) ?? "").trim() || (get(shared) ?? "").trim();
59
+
60
+ export function readBrandConfig(get: (key: BrandKey) => string | undefined): BrandConfig | null {
61
+ try {
62
+ if (!brandLoaderEnabled(get)) return null;
63
+ const baseUrl = (get("EXPERIENCE_BASE_URL") ?? "").trim();
64
+ const scope = brandVar(get, "EXPERIENCE_BRAND_SCOPE", "EXPERIENCE_SCOPE");
65
+ const environmentId = brandVar(get, "EXPERIENCE_BRAND_ENVIRONMENT_ID", "EXPERIENCE_ENVIRONMENT_ID");
66
+ if (!baseUrl || !scope || !environmentId || new URL(baseUrl).protocol !== "https:") return null;
67
+ const keys: unknown = JSON.parse(get("EXPERIENCE_ANCHORED_KEYS") ?? "null");
68
+ if (!Array.isArray(keys) || keys.length < 2) return null;
69
+ const channel = brandVar(get, "EXPERIENCE_BRAND_CHANNEL", "EXPERIENCE_CHANNEL") || "production";
70
+ const name = (get("EXPERIENCE_BRAND_NAME") ?? "").trim();
71
+ if (name && !NAME.test(name)) return null;
72
+ const appearance2 = (get("EXPERIENCE_BRAND_APPEARANCE") ?? "").trim().toLowerCase() === "appearance@2";
73
+ return { baseUrl, scope, environmentId, channel, anchoredKeys: normalizeAnchoredKeys(keys), ...(name ? { name } : {}), ...(appearance2 ? { appearance2: true } : {}) };
74
+ } catch {
75
+ return null;
76
+ }
77
+ }
78
+
79
+ /** Origen de Experience que el navegador necesita en `connect-src`, o `null` con la bandera apagada o sin una URL https válida. */
80
+ export function brandConnectOrigin(get: (key: BrandKey) => string | undefined): string | null {
81
+ try {
82
+ if (!brandLoaderEnabled(get)) return null;
83
+ const url = new URL((get("EXPERIENCE_BASE_URL") ?? "").trim());
84
+ return url.protocol === "https:" ? url.origin : null;
85
+ } catch {
86
+ return null;
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Añade el origen de la marca a la directiva `connect-src` de una CSP ya construida (UIs que la fijan en `proxy.ts`/`next.config`). Con `origin` nulo devuelve la CSP intacta;
92
+ * sin `connect-src` en la CSP no inventa una (caería a `default-src`, que sí se ampliaría solo si se pidiera: no es el caso).
93
+ */
94
+ export function withBrandConnectSrc(csp: string, origin: string | null): string {
95
+ if (!origin) return csp;
96
+ return csp
97
+ .split(";")
98
+ .map((directive) => {
99
+ const trimmed = directive.trim();
100
+ return /^connect-src(\s|$)/i.test(trimmed) && !trimmed.split(/\s+/).includes(origin) ? `${trimmed} ${origin}` : directive;
101
+ })
102
+ .join(";");
103
+ }
104
+
105
+ /** Nombre del artefacto para el esquema: `${base}-light` / `${base}-dark`. Sin base no hay variante (se usa el único artefacto del release). */
106
+ export const brandArtifactName = (base: string | undefined, scheme: "light" | "dark"): string | undefined => (base ? `${base}-${scheme}` : undefined);
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./config";
2
+ export * from "./vars";
3
+ export type { BrandPayload } from "./scope";
@@ -0,0 +1,41 @@
1
+ "use client";
2
+
3
+ import * as React from "react";
4
+ import { ExperienceProvider, useExperienceBrand, type InitialBrand } from "@customyai/experience-web";
5
+ import { BRAND_GRACE_MS, brandArtifactName, type BrandConfig } from "./config";
6
+ import { designSystemBrandVarsFor } from "./vars-v2";
7
+
8
+ export type BrandVarMap = "ap" | "design-system";
9
+
10
+ function BrandContainer({ name, scheme, scope, varMap, initial, appearance2, children }: { name: string | undefined; appearance2: boolean; scheme: "light" | "dark"; scope: string; varMap: BrandVarMap; initial: InitialBrand | null; children: React.ReactNode }): React.JSX.Element {
11
+ // Una marca de OTRO modo que el de la UI no se aplica (sus colores no serían legibles): `rejected="mode-mismatch"`. Se prefiere el artefacto del esquema
12
+ // (`<nombre>-light|dark`) y, si el release no lo trae, el de nombre base.
13
+ const variant = useExperienceBrand({ ...(name ? { name: brandArtifactName(name, scheme) } : {}), initial, colorScheme: scheme, appearance2 });
14
+ const base = useExperienceBrand({ ...(name ? { name } : {}), initial, colorScheme: scheme, appearance2 });
15
+ const brand = variant.source !== "none" || variant.rejected ? variant : base;
16
+ const style = React.useMemo<React.CSSProperties>(
17
+ () => (brand.applied ? ({ ...brand.style, ...(varMap === "design-system" ? designSystemBrandVarsFor(brand) : {}), display: "contents" } as React.CSSProperties) : { display: "contents" }),
18
+ [brand, varMap],
19
+ );
20
+ return (
21
+ <div data-customy-brand={scope} data-brand-source={brand.source} {...(brand.rejected ? { "data-brand-rejected": brand.rejected } : {})} style={style}>
22
+ {children}
23
+ </div>
24
+ );
25
+ }
26
+
27
+ /**
28
+ * Lado ENCENDIDO. Solo se carga (import dinámico) con `BRAND_LOADER` encendido. La estructura es SIEMPRE la misma (proveedor + contenedor), tenga o no marca aplicada,
29
+ * para que una marca que llega o se revoca en caliente no remonte la UI. Sin almacén en `localStorage` (regla del repositorio): el cliente guarda en memoria y la marca inicial viene del HTML del servidor.
30
+ */
31
+ export default function BrandScopeOn({ config, initial, scheme, scope, varMap, children }: { config: BrandConfig; initial: InitialBrand | null; scheme: "light" | "dark"; scope: string; varMap: BrandVarMap; children: React.ReactNode }): React.JSX.Element {
32
+ const options = React.useMemo(
33
+ () => ({ baseUrl: config.baseUrl, scope: config.scope, environmentId: config.environmentId, channel: config.channel, anchoredKeys: config.anchoredKeys as never, graceMs: BRAND_GRACE_MS, ...(config.appearance2 ? { appearance2: true } : {}) }),
34
+ [config],
35
+ );
36
+ return (
37
+ <ExperienceProvider locale="es" options={options} refreshIntervalMs={300_000}>
38
+ <BrandContainer name={config.name} scheme={scheme} scope={scope} varMap={varMap} initial={initial} appearance2={config.appearance2 === true}>{children}</BrandContainer>
39
+ </ExperienceProvider>
40
+ );
41
+ }
package/src/scope.tsx ADDED
@@ -0,0 +1,24 @@
1
+ "use client";
2
+
3
+ import * as React from "react";
4
+ import dynamic from "next/dynamic";
5
+ import type { InitialBrand } from "@customyai/experience-web";
6
+ import type { BrandConfig } from "./config";
7
+ import type { BrandVarMap } from "./scope-on";
8
+
9
+ /** Import dinámico: el cargador de marca es código aparte que solo se baja con la bandera encendida. */
10
+ const BrandScopeOn = dynamic(() => import("./scope-on"));
11
+
12
+ /** Lo que el servidor le pasa al cliente: JSON plano (un objeto de prototipo nulo no puede cruzar de Server a Client Component). */
13
+ export type BrandPayload = { config: BrandConfig; initial: InitialBrand | null };
14
+
15
+ /**
16
+ * La marca de Customy Experience puesta sobre una UI. `brand` es `null` con `BRAND_LOADER` apagado (lo normal): devuelve `children` TAL CUAL, mismo árbol, mismo HTML,
17
+ * cero peticiones y cero código nuevo en el navegador. Encendido, envuelve en `<ExperienceProvider>` y en un contenedor `display: contents` con las variables de la marca.
18
+ * `scheme` es el modo de la UI (las de producto son oscuras): una marca del otro modo se rechaza (`data-brand-rejected="mode-mismatch"`) y la UI se queda como está.
19
+ * `varMap`: `ap` deja las `--ap-*` tal cual (Ads las lee en su CSS); `design-system` las traduce a `--primary`/`--ring`/`--radius`.
20
+ */
21
+ export function BrandScope({ brand, scheme, scope, varMap = "design-system", children }: { brand: BrandPayload | null; scheme: "light" | "dark"; scope: string; varMap?: BrandVarMap; children: React.ReactNode }): React.JSX.Element {
22
+ if (!brand) return <>{children}</>;
23
+ return <BrandScopeOn config={brand.config} initial={brand.initial} scheme={scheme} scope={scope} varMap={varMap}>{children}</BrandScopeOn>;
24
+ }
@@ -0,0 +1,73 @@
1
+ import { createNodeExperienceClient } from "@customyai/experience-client/node";
2
+ import type { ExperienceClient } from "@customyai/experience-client";
3
+ import { getInitialBrand, type InitialBrand } from "@customyai/experience-web/brand";
4
+ import { BRAND_GRACE_MS, brandArtifactName, type BrandConfig } from "./config";
5
+
6
+ /**
7
+ * Un cliente por configuración y proceso: el release descargado se comparte entre peticiones. Se vuelve a preguntar como mucho una vez por minuto; las peticiones que
8
+ * coinciden comparten UNA sola consulta. La 1.ª consulta de un proceso (aún sin release) espera hasta `FIRST_TIMEOUT_MS` para que el HTML ya traiga la marca (sin
9
+ * parpadeo en frío); las siguientes, solo `REFRESH_TIMEOUT_MS`, porque ya hay un release que servir.
10
+ */
11
+ const REFRESH_EVERY_MS = 60_000;
12
+ const REFRESH_TIMEOUT_MS = 800;
13
+ /** Mientras el proceso aún no tiene ningún release utilizable, un intento fallido se repite pronto (no a los 60 s): así una consulta que falló al arrancar no deja el HTML sin marca durante un minuto. */
14
+ const RETRY_UNLOADED_MS = 5_000;
15
+ export const FIRST_TIMEOUT_MS = 2_500;
16
+ const CLIENT_LIMIT = 20;
17
+ type Entry = { client: ExperienceClient; refreshedAt: number; loaded: boolean; inflight: Promise<void> | null };
18
+ const clients = new Map<string, Entry>();
19
+
20
+ /** Solo para pruebas. */
21
+ export const clearBrandClients = (): void => clients.clear();
22
+
23
+ function entryFor(config: BrandConfig): Entry {
24
+ const key = JSON.stringify([config.baseUrl, config.scope, config.environmentId, config.channel, config.anchoredKeys, config.appearance2 === true]);
25
+ let entry = clients.get(key);
26
+ if (!entry) {
27
+ entry = {
28
+ client: createNodeExperienceClient({ baseUrl: config.baseUrl, scope: config.scope, environmentId: config.environmentId, channel: config.channel, anchoredKeys: config.anchoredKeys as never, graceMs: BRAND_GRACE_MS, ...(config.appearance2 ? { appearance2: true } : {}) }),
29
+ refreshedAt: 0,
30
+ loaded: false,
31
+ inflight: null,
32
+ };
33
+ clients.set(key, entry);
34
+ while (clients.size > CLIENT_LIMIT) clients.delete(clients.keys().next().value as string);
35
+ }
36
+ return entry;
37
+ }
38
+
39
+ /** Hay un release utilizable (fresco o vencido dentro de la gracia). Un `refresh` que no lanza pero no consiguió nada NO cuenta como cargado. */
40
+ function usable(client: ExperienceClient): boolean {
41
+ try { const state = client.status().state; return state === "fresh" || state === "stale"; } catch { return false; }
42
+ }
43
+
44
+ async function refreshed(entry: Entry): Promise<void> {
45
+ if (!entry.inflight && Date.now() - entry.refreshedAt > (entry.loaded ? REFRESH_EVERY_MS : RETRY_UNLOADED_MS)) {
46
+ entry.refreshedAt = Date.now();
47
+ const run = entry.client.refresh().then(() => { entry.loaded = usable(entry.client); }, () => undefined);
48
+ entry.inflight = run.finally(() => { entry.inflight = null; });
49
+ }
50
+ const pending = entry.inflight;
51
+ if (!pending) return;
52
+ let timer: ReturnType<typeof setTimeout> | undefined;
53
+ await Promise.race([pending, new Promise<void>((resolve) => { timer = setTimeout(resolve, entry.loaded ? REFRESH_TIMEOUT_MS : FIRST_TIMEOUT_MS); })]);
54
+ if (timer) clearTimeout(timer);
55
+ }
56
+
57
+ export async function initialBrandFor(config: BrandConfig, scheme: "light" | "dark" = "dark"): Promise<InitialBrand | null> {
58
+ const entry = entryFor(config);
59
+ await refreshed(entry);
60
+ // Misma preferencia que el contenedor del cliente: el artefacto del esquema (`<nombre>-dark|light`) y, si el release no lo trae, el de nombre base. Sin la variante, el HTML
61
+ // llevaría la marca de `ds` mientras el cliente pide `ds-dark`: no coinciden y el primer pintado sale sin marca.
62
+ const variant = brandArtifactName(config.name, scheme);
63
+ if (variant) {
64
+ const found = await getInitialBrand(entry.client, { name: variant, ...(config.appearance2 ? { appearance2: true } : {}) });
65
+ if (found) return found;
66
+ }
67
+ return getInitialBrand(entry.client, { ...(config.name ? { name: config.name } : {}), ...(config.appearance2 ? { appearance2: true } : {}) });
68
+ }
69
+
70
+ /** Precalentamiento al arrancar el proceso (`instrumentation.ts`): baja el release antes de la 1.ª petición. */
71
+ export async function warmBrandFor(config: BrandConfig): Promise<void> {
72
+ await refreshed(entryFor(config));
73
+ }
package/src/server.ts ADDED
@@ -0,0 +1,56 @@
1
+ import { readBrandConfig, brandLoaderEnabled, type BrandConfig, type BrandKey } from "./config";
2
+ import type { BrandPayload } from "./scope";
3
+ import type { BrandSignIn } from "./signin";
4
+
5
+ /**
6
+ * La marca que el layout debe pintar, o `null` (= la UI de siempre). Con la bandera apagada no importa nada del lado encendido, no abre conexiones. Nunca lanza: si la marca
7
+ * inicial falla, el cliente lo reintenta solo y entretanto la UI se ve como siempre.
8
+ * El resultado se pasa por JSON: `getInitialBrand` puede devolver objetos de prototipo nulo y esos NO cruzan de Server a Client Component (lección del Workspace).
9
+ */
10
+ export async function resolveBrand(get: (key: BrandKey) => string | undefined, scheme: "light" | "dark" = "dark"): Promise<BrandPayload | null> {
11
+ try {
12
+ if (!brandLoaderEnabled(get)) return null;
13
+ const config: BrandConfig | null = readBrandConfig(get);
14
+ if (!config) return null;
15
+ let initial: BrandPayload["initial"] = null;
16
+ try {
17
+ const { initialBrandFor } = await import("./server-on");
18
+ initial = await initialBrandFor(config, scheme);
19
+ } catch {
20
+ initial = null;
21
+ }
22
+ return JSON.parse(JSON.stringify({ config, initial })) as BrandPayload;
23
+ } catch {
24
+ return null;
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Precalienta el cliente de marca al arrancar (`instrumentation.ts` de la UI): con la bandera apagada no hace nada ni importa el lado encendido. Nunca lanza ni retrasa el
30
+ * arranque más de lo que tarda la 1.ª consulta (tope en `server-on`).
31
+ */
32
+ export async function warmBrand(get: (key: BrandKey) => string | undefined): Promise<void> {
33
+ try {
34
+ const config = readBrandConfig(get);
35
+ if (!config) return;
36
+ const { warmBrandFor } = await import("./server-on");
37
+ await warmBrandFor(config);
38
+ } catch {
39
+ // Sin precalentar, la 1.ª petición lo hace.
40
+ }
41
+ }
42
+
43
+ /**
44
+ * La marca de la pantalla de acceso, calculada en el SERVIDOR a partir de la misma marca que `resolveBrand` ya trajo (sin otra consulta): el HTML inicial del login sale con el
45
+ * color de acción y el radio de la marca. Mismo criterio que el contenedor (`mode-mismatch`, lista blanca, `appearance@2` solo con su capacidad). Nunca lanza: sin marca, marca
46
+ * rechazada o cualquier fallo = `null` = la pantalla de siempre.
47
+ */
48
+ export async function resolveSignInBrand(brand: BrandPayload | null, scheme: "light" | "dark" = "dark"): Promise<BrandSignIn | null> {
49
+ try {
50
+ if (!brand?.initial) return null;
51
+ const { initialSignInBrand } = await import("./signin-on");
52
+ return initialSignInBrand(brand.initial, scheme, brand.config.appearance2 === true);
53
+ } catch {
54
+ return null;
55
+ }
56
+ }
@@ -0,0 +1,37 @@
1
+ "use client";
2
+
3
+ import * as React from "react";
4
+ import { readBrandSignIn, type BrandSignIn } from "./signin";
5
+
6
+ /**
7
+ * Envoltura de la pantalla de acceso con marca. `initial` viene del servidor (`resolveSignInBrand`): el PRIMER pintado (HTML del servidor) ya lleva el color de la marca,
8
+ * sin parpadeo. Después de hidratar sigue al contenedor `[data-customy-brand]` (una marca que llega o se revoca en caliente). Solo marca `data-brand-signin` cuando hay marca.
9
+ * Uso: `<BrandSignInHolder initial={...}>{(brand) => <CustomySignIn {...(brand ?? {})} />}</BrandSignInHolder>`.
10
+ */
11
+ export function BrandSignInHolder({ initial, children }: { initial: BrandSignIn | null; children: (brand: BrandSignIn | null) => React.ReactNode }): React.JSX.Element {
12
+ const holder = React.useRef<HTMLDivElement>(null);
13
+ const [brand, setBrand] = React.useState<BrandSignIn | null>(initial);
14
+ React.useEffect(() => {
15
+ const container = holder.current?.closest("[data-customy-brand]");
16
+ // Sin contenedor (bandera apagada) se respeta lo que trajo el servidor, que entonces es `null`.
17
+ if (!container) return;
18
+ const read = () => setBrand((now) => {
19
+ const next = readBrandSignIn(holder.current);
20
+ // Misma marca (el color puede diferir 1 unidad al ir hex → HSL → hex): se conserva la del servidor para no repintar.
21
+ if (now && next && now.tokens.radius === next.tokens.radius && closeHex(now.tokens.primary, next.tokens.primary)) return now;
22
+ return JSON.stringify(next) === JSON.stringify(now) ? now : next;
23
+ });
24
+ read();
25
+ const observer = new MutationObserver(read);
26
+ observer.observe(container, { attributes: true, attributeFilter: ["data-brand-source", "style"] });
27
+ return () => observer.disconnect();
28
+ }, []);
29
+ return <div ref={holder} style={{ display: "contents" }} {...(brand ? { "data-brand-signin": "" } : {})}>{children(brand)}</div>;
30
+ }
31
+
32
+ function closeHex(a: string, b: string): boolean {
33
+ const x = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(a);
34
+ const y = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(b);
35
+ if (!x || !y) return false;
36
+ return [1, 2, 3].every((i) => Math.abs(parseInt(x[i] as string, 16) - parseInt(y[i] as string, 16)) <= 2);
37
+ }
@@ -0,0 +1,10 @@
1
+ import { parseInitialBrand, resolveInitialDoc } from "@customyai/experience-web/brand";
2
+ import { signInBrandFromVars, type BrandSignIn } from "./signin";
3
+
4
+ /** Lado encendido (import dinámico desde `server.ts`): valida la marca inicial con el mismo código del cliente y saca de ella lo que usa la pantalla de acceso. */
5
+ export function initialSignInBrand(initial: unknown, scheme: "light" | "dark", appearance2: boolean): BrandSignIn | null {
6
+ const parsed = parseInitialBrand(initial, { appearance2 });
7
+ if (!parsed) return null;
8
+ const resolved = resolveInitialDoc(parsed.doc, { colorScheme: scheme, appearance2 });
9
+ return resolved ? signInBrandFromVars(resolved.vars) : null;
10
+ }
package/src/signin.ts ADDED
@@ -0,0 +1,50 @@
1
+ /**
2
+ * La marca de Customy Experience en la pantalla de acceso compartida (`CustomySignIn`). El componente trae su propio verde y es claro por omisión; con la marca encendida
3
+ * toma de ella el color de acción y el radio y pasa a oscuro. Sin marca devuelve `null` y la pantalla no cambia.
4
+ * Dos orígenes con el MISMO resultado: el servidor (`signInBrandFromVars`, a partir de las `--ap-*` de la marca inicial: el HTML ya sale con la marca, sin parpadeo) y el
5
+ * navegador (`readBrandSignIn`, a partir del contenedor `[data-customy-brand]`: sigue una marca que llega o se revoca en caliente). Puro y sin dependencias.
6
+ * NO toca `readableOn` del SDK: el texto sobre la acción lo fija la UI con `--primary-foreground` (ver `[data-brand-signin]` en su CSS).
7
+ */
8
+ export type BrandSignIn = { theme: "dark"; tokens: { primary: string; radius?: string } };
9
+
10
+ const HEX = /^#[0-9a-f]{6}$/i;
11
+ const TRIPLET = /^\d{1,3}(?:\.\d+)? \d{1,3}(?:\.\d+)?% \d{1,3}(?:\.\d+)?%$/;
12
+ const PX = /^\d{1,2}px$/;
13
+
14
+ /** «H S% L%» → `#rrggbb`: la pantalla de acceso elige el texto legible solo a partir de un hexadecimal. */
15
+ export function hslTripletToHex(triplet: string): string {
16
+ const [h, s, l] = triplet.split(" ").map((p) => parseFloat(p)) as [number, number, number];
17
+ const sat = s / 100;
18
+ const light = l / 100;
19
+ const a = sat * Math.min(light, 1 - light);
20
+ const channel = (n: number): string => {
21
+ const k = (n + h / 30) % 12;
22
+ return Math.round(255 * (light - a * Math.max(-1, Math.min(k - 3, 9 - k, 1)))).toString(16).padStart(2, "0");
23
+ };
24
+ return `#${channel(0)}${channel(8)}${channel(4)}`;
25
+ }
26
+
27
+ /** Desde las variables `--primary`/`--radius` ya pintadas en el contenedor (navegador). */
28
+ export function brandSignInFrom(read: (name: string) => string, source: string | undefined): BrandSignIn | null {
29
+ if (!source || source === "none") return null;
30
+ const primary = read("--primary").trim();
31
+ if (!TRIPLET.test(primary)) return null;
32
+ const radius = read("--radius").trim();
33
+ return { theme: "dark", tokens: { primary: hslTripletToHex(primary), ...(PX.test(radius) ? { radius } : {}) } };
34
+ }
35
+
36
+ /** Desde las `--ap-*` de una marca resuelta (servidor): `--ap-action` ya es hexadecimal validado. Entrada inválida = `null`. */
37
+ export function signInBrandFromVars(vars: Readonly<Record<string, string>> | null | undefined): BrandSignIn | null {
38
+ const action = vars?.["--ap-action"];
39
+ if (typeof action !== "string" || !HEX.test(action)) return null;
40
+ const radius = vars?.["--ap-radius"];
41
+ return { theme: "dark", tokens: { primary: action.toLowerCase(), ...(typeof radius === "string" && PX.test(radius) ? { radius } : {}) } };
42
+ }
43
+
44
+ /** Lee el contenedor de la marca que envuelve a `from`. Solo en el navegador. */
45
+ export function readBrandSignIn(from: Element | null): BrandSignIn | null {
46
+ const holder = from?.closest("[data-customy-brand]");
47
+ if (!holder) return null;
48
+ const style = getComputedStyle(holder);
49
+ return brandSignInFrom((name) => style.getPropertyValue(name), holder.getAttribute("data-brand-source") ?? undefined);
50
+ }
package/src/vars-v2.ts ADDED
@@ -0,0 +1,12 @@
1
+ import { appearanceLayerVars, type ResolvedBrand } from "@customyai/experience-web";
2
+ import { designSystemBrandVars } from "./vars";
3
+
4
+ /**
5
+ * Variables del design system para una marca ya resuelta: lo de siempre (`designSystemBrandVars`: acción y radio) y, SOLO si la marca es `appearance@2` (capacidad `appearance@2` del entorno),
6
+ * fondo, texto, superficies, borde y estados de shadcn más `--brand-accent` (nunca `--accent`). Con una marca `@1` el resultado es idéntico al de hoy. `font` y `density` nunca se mapean.
7
+ * Vive aparte de `vars.ts` a propósito: importa `@customyai/experience-web`, y con la bandera apagada eso no debe cargarse (solo lo importa `scope-on`).
8
+ */
9
+ export function designSystemBrandVarsFor(brand: { readonly vars: Readonly<Record<string, string>>; readonly appearance2?: ResolvedBrand["appearance2"] }): Record<string, string> {
10
+ const base = designSystemBrandVars(brand.vars);
11
+ return brand.appearance2 ? { ...base, ...appearanceLayerVars(brand as ResolvedBrand, "shadcn") } : base;
12
+ }
package/src/vars.ts ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * De las variables `--ap-*` de una marca verificada (`tokens@1`) a las que las UIs del design system ya consumen (`hsl(var(--primary))`, `--radius`…).
3
+ * Solo el color de acción y el radio: fondo, texto y superficies NO se tocan, para que una marca nunca vuelva ilegible una pantalla.
4
+ * Las entradas ya pasaron la lista blanca de `@customyai/experience-web` (hexadecimal `#rrggbb`, `Npx`); lo que no case aquí simplemente no se mapea.
5
+ */
6
+ const HEX = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i;
7
+ const PX = /^\d{1,2}px$/;
8
+
9
+ /** `#rrggbb` → «H S% L%» (el formato de los tokens de las UIs), o `null`. */
10
+ export function hexToHslTriplet(hex: string | undefined): string | null {
11
+ const match = hex ? HEX.exec(hex) : null;
12
+ if (!match) return null;
13
+ const [r, g, b] = [match[1], match[2], match[3]].map((part) => parseInt(part as string, 16) / 255) as [number, number, number];
14
+ const max = Math.max(r, g, b);
15
+ const min = Math.min(r, g, b);
16
+ const l = (max + min) / 2;
17
+ const d = max - min;
18
+ if (d === 0) return `0 0% ${Math.round(l * 100)}%`;
19
+ const s = d / (1 - Math.abs(2 * l - 1));
20
+ const h = max === r ? ((g - b) / d) % 6 : max === g ? (b - r) / d + 2 : (r - g) / d + 4;
21
+ return `${Math.round(((h * 60) + 360) % 360)} ${Math.round(s * 100)}% ${Math.round(l * 100)}%`;
22
+ }
23
+
24
+ export function designSystemBrandVars(vars: Readonly<Record<string, string>>): Record<string, string> {
25
+ const out: Record<string, string> = {};
26
+ const action = hexToHslTriplet(vars["--ap-action"]);
27
+ const onAction = hexToHslTriplet(vars["--ap-on-action"]);
28
+ if (action) {
29
+ out["--primary"] = action;
30
+ out["--ring"] = action;
31
+ if (onAction) out["--primary-foreground"] = onAction;
32
+ }
33
+ const radius = vars["--ap-radius"];
34
+ if (radius && PX.test(radius)) out["--radius"] = radius;
35
+ return out;
36
+ }