editorbrain 0.40.1 → 0.41.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.
@@ -1,113 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // packages/cli/src/team-command.ts
4
- async function teamCommand(client, subcommand, flags) {
5
- const value = (key) => {
6
- const v = flags[key];
7
- return typeof v === "string" ? v : void 0;
8
- };
9
- const required = (key) => {
10
- const v = value(key);
11
- if (!v) throw new Error(`Missing --${key}`);
12
- return v;
13
- };
14
- const common = ["url", "dir"];
15
- const allowed = {
16
- access: [],
17
- members: [],
18
- projects: [],
19
- invite: ["email", "kind", "scope"],
20
- cancel: ["id"],
21
- remove: ["user", "confirm"],
22
- reviews: ["project", "after"],
23
- share: ["project", "revision", "confirm"],
24
- withdraw: ["project", "revision", "confirm"],
25
- comment: ["project", "revision", "context-version", "text", "at-ms", "id"],
26
- approve: ["project", "revision", "context-version", "user-confirmed"]
27
- };
28
- if (!subcommand || !allowed[subcommand])
29
- throw new Error(
30
- "Use team access|members|projects|invite|cancel|remove|reviews|share|withdraw|comment|approve."
31
- );
32
- for (const key of Object.keys(flags))
33
- if (!common.includes(key) && !allowed[subcommand].includes(key))
34
- throw new Error(`--${key} is not supported for team ${subcommand}.`);
35
- if (subcommand === "access") return client.request("/v1/team");
36
- if (["members", "projects"].includes(subcommand))
37
- return client.request("/v1/team/" + subcommand);
38
- if (subcommand === "invite") {
39
- const kind = required("kind");
40
- if (!["brand_editor", "project_reviewer"].includes(kind))
41
- throw new Error("Use --kind brand_editor or project_reviewer.");
42
- return client.request("/v1/team/invitations", {
43
- method: "POST",
44
- body: { email: required("email"), kind, scopeId: required("scope") }
45
- });
46
- }
47
- if (subcommand === "cancel")
48
- return client.request(
49
- "/v1/team/invitations/" + encodeURIComponent(required("id")),
50
- { method: "DELETE" }
51
- );
52
- if (subcommand === "remove") {
53
- if (flags.confirm !== true)
54
- throw new Error(
55
- "Removing access requires --confirm after the user requests removal. Files are preserved."
56
- );
57
- return client.request(
58
- "/v1/team/members/" + encodeURIComponent(required("user")),
59
- { method: "DELETE" }
60
- );
61
- }
62
- const base = "/v1/team/projects/" + encodeURIComponent(required("project")) + "/reviews";
63
- if (subcommand === "reviews")
64
- return client.request(
65
- base + (value("after") ? "?after=" + encodeURIComponent(value("after")) : "")
66
- );
67
- const revision2 = required("revision");
68
- if (!/^[a-f0-9-]{36}$/.test(revision2))
69
- throw new Error("Use the exact revision UUID returned by team reviews.");
70
- if (["share", "withdraw"].includes(subcommand)) {
71
- if (flags.confirm !== true)
72
- throw new Error(
73
- "Use --confirm for an explicitly requested sharing change."
74
- );
75
- return client.request(base + "/" + revision2 + "/share", {
76
- method: "POST",
77
- body: { shared: subcommand === "share" }
78
- });
79
- }
80
- const contextVersion = required("context-version");
81
- if (!/^[a-f0-9]{64}$/.test(contextVersion))
82
- throw new Error("Use the exact context hash of the reviewed sample.");
83
- if (subcommand === "approve") {
84
- if (flags["user-confirmed"] !== true)
85
- throw new Error(
86
- "Approval requires explicit user acceptance and --user-confirmed."
87
- );
88
- return client.request(base + "/" + revision2 + "/approve", {
89
- method: "POST",
90
- body: { contextVersion, userConfirmed: true }
91
- });
92
- }
93
- const at = value("at-ms"), startMs = at === void 0 ? void 0 : Number(at);
94
- if (startMs !== void 0 && (!Number.isSafeInteger(startMs) || startMs < 0 || startMs > 36e6))
95
- throw new Error("--at-ms must be an integer between 0 and 36000000.");
96
- const feedbackId = required("id");
97
- if (!/^[a-f0-9-]{36}$/.test(feedbackId))
98
- throw new Error(
99
- "Use --id with a fresh UUID; reuse it for retries of this exact comment."
100
- );
101
- return client.request(base + "/" + revision2 + "/comment", {
102
- method: "POST",
103
- body: {
104
- contextVersion,
105
- feedbackId,
106
- text: required("text"),
107
- target: startMs === void 0 ? {} : { startMs }
108
- }
109
- });
110
- }
3
+ // packages/cli/src/style-sources.ts
4
+ import { constants as constants2 } from "node:fs";
5
+ import { open as open3, mkdir as mkdir3, writeFile, rm } from "node:fs/promises";
6
+ import { dirname as dirname3 } from "node:path";
111
7
 
112
8
  // packages/core/src/editorial-learning.ts
113
9
  var learningCategories = ["captions", "cuts", "layout", "motion", "media", "sound", "color", "story", "other"];
@@ -246,6 +142,21 @@ var billing = { label: "Ver plan y cr\xE9ditos", url: "https://editorbrain.com/a
246
142
  var integrations = { label: "Ver mis integraciones", url: "https://editorbrain.com/app/integrations" };
247
143
  var support = { label: "Contactar soporte", url: "mailto:soporte@editorbrain.com" };
248
144
  var guidance = {
145
+ email_verification_required: { status: 403, help: {
146
+ message: "Verifica tu correo para usar las funciones de IA de EditorBrain.",
147
+ nextStep: "Abre la verificaci\xF3n de correo y solicita un enlace si lo necesitas. Completa ese paso antes de repetir la b\xFAsqueda. Mientras tanto puedes trabajar con tu material y los recursos ya disponibles. No hace falta comprar cr\xE9ditos ni cambiar de cuenta para evitar esta comprobaci\xF3n.",
148
+ actions: [{ label: "Verificar mi correo", url: "https://editorbrain.com/verify-email" }]
149
+ } },
150
+ invalid_authored_query: { status: 400, help: {
151
+ message: "La consulta o su cursor de animaciones no es v\xE1lido.",
152
+ nextStep: "Comprueba los par\xE1metros y l\xEDmites de list_authored_scenes. Si cambiaste la consulta, los filtros o la versi\xF3n, descarta after y comienza en la primera p\xE1gina. Para continuar, utiliza nextCursor tal como se recibi\xF3 con los mismos par\xE1metros; no lo construyas ni lo modifiques. No repitas indefinidamente la petici\xF3n que fall\xF3.",
153
+ actions: []
154
+ } },
155
+ sfx_unavailable: { status: 404, help: {
156
+ message: "Este banco o sonido no est\xE1 disponible para esta selecci\xF3n.",
157
+ nextStep: "Consulta search_sfx con el proyecto actual y respeta su banco configurado. Si no hay bancos disponibles, informa de esa limitaci\xF3n y contin\xFAa las partes independientes del montaje. Puedes solicitar un audio propio con permiso de uso o contactar soporte; no inventes un ID, cambies de banco ni generes sonidos de pago autom\xE1ticamente. Recargar cr\xE9ditos no activa esta biblioteca.",
158
+ actions: [support]
159
+ } },
249
160
  resource_plan_required: { status: 403, help: { message: "Este recurso requiere Creator o Studio.", nextStep: "Puedes ver su preview o proponer un recurso con access.canUse=true que encaje con la escena. Una recarga de cr\xE9ditos no desbloquea recursos premium. No sustituyas la elecci\xF3n expl\xEDcita del usuario ni cambies de plan autom\xE1ticamente.", actions: [billing, { label: "Explorar animaciones", url: "https://editorbrain.com/app/animations" }] } },
250
161
  studio_insufficient_credits: { status: 402, help: {
251
162
  message: "No alcanzan tus cr\xE9ditos creativos de EditorBrain para este encargo.",
@@ -181351,7 +181262,72 @@ var stopwords = new Set("a al algo como con cual de del donde el ella en entre e
181351
181262
  function stems(text11) {
181352
181263
  return new Set((normalized(text11).match(/[a-z0-9]+/g) ?? []).filter((word) => word.length > 2 && !stopwords.has(word)).map((word) => word.slice(0, 5)));
181353
181264
  }
181354
- var buildSearchIndex = (scenes) => scenes.map((scene) => ({ scene, fields: [
181265
+ var discoveryWords = {
181266
+ animated: "",
181267
+ animation: "",
181268
+ animations: "",
181269
+ show: "",
181270
+ showing: "",
181271
+ with: "",
181272
+ the: "",
181273
+ and: "",
181274
+ for: "",
181275
+ of: "",
181276
+ a: "",
181277
+ an: "",
181278
+ number: "numero",
181279
+ numbers: "numeros",
181280
+ counter: "contador",
181281
+ counters: "contadores",
181282
+ money: "dinero",
181283
+ underline: "subrayar",
181284
+ underlined: "subrayado",
181285
+ word: "palabra",
181286
+ words: "palabras",
181287
+ before: "antes",
181288
+ after: "despues",
181289
+ comparison: "comparacion",
181290
+ compare: "comparar",
181291
+ reveal: "revelar",
181292
+ brand: "marca",
181293
+ end: "final",
181294
+ title: "titulo",
181295
+ name: "nombre",
181296
+ job: "cargo",
181297
+ map: "mapa",
181298
+ route: "ruta",
181299
+ journey: "recorrido",
181300
+ steps: "pasos",
181301
+ list: "lista",
181302
+ chart: "grafica",
181303
+ graph: "grafica",
181304
+ bars: "barras",
181305
+ ranking: "ranking",
181306
+ timeline: "cronologia",
181307
+ photo: "foto",
181308
+ photos: "fotos",
181309
+ image: "imagen",
181310
+ images: "imagenes",
181311
+ testimonial: "testimonio",
181312
+ product: "producto",
181313
+ price: "precio",
181314
+ pricing: "precios",
181315
+ discount: "descuento",
181316
+ typewriter: "maquina escribir",
181317
+ handwriting: "escritura mano",
181318
+ handwritten: "escrito mano"
181319
+ };
181320
+ function discoveryTerms(search) {
181321
+ const translated = search.replace(/\blower third\b/g, "nombre cargo").replace(/\bcount up\b/g, "contador").replace(/\b[a-z0-9]+\b/g, (word) => Object.hasOwn(discoveryWords, word) ? discoveryWords[word] : word);
181322
+ const terms = stems(translated);
181323
+ if (/\bcontador(?:es)?\b/.test(translated)) {
181324
+ terms.delete("conta");
181325
+ terms.add("contador");
181326
+ }
181327
+ return terms;
181328
+ }
181329
+ var mechanismTerms = /* @__PURE__ */ new Set([...stems("subrayar odometro"), "contador"]);
181330
+ var buildSearchIndex = (scenes, precise = false) => scenes.map((scene) => ({ scene, fields: [
181355
181331
  [scene.title, 3],
181356
181332
  [scene.universalMechanism ?? "", 3],
181357
181333
  [scene.intent, 2.5],
@@ -181359,21 +181335,28 @@ var buildSearchIndex = (scenes) => scenes.map((scene) => ({ scene, fields: [
181359
181335
  [(scene.crossNicheUses ?? []).join(" "), 2.5],
181360
181336
  [(scene.presets ?? []).map((preset) => `${preset.name.replace(/-/g, " ")} ${preset.summary}`).join(" "), 2],
181361
181337
  [scene.useFor ?? "", 1.5]
181362
- ].map(([text11, weight]) => ({ terms: stems(text11), weight })) }));
181338
+ ].map(([text11, weight]) => {
181339
+ const terms = stems(text11);
181340
+ if (precise && /\bcontador(?:es)?\b/.test(normalized(text11))) terms.add("contador");
181341
+ return { terms, weight };
181342
+ }) }));
181363
181343
  var searchIndexes = { "1.1.0": buildSearchIndex(catalogs["1.1.0"]), "1.2.0": buildSearchIndex(catalogs["1.2.0"]), "1.3.0": buildSearchIndex(catalogs["1.3.0"]), "1.4.0": buildSearchIndex(catalogs["1.4.0"]) };
181364
- var v14TermWeights = (() => {
181365
- const index = searchIndexes["1.4.0"], frequencies = /* @__PURE__ */ new Map();
181344
+ var bilingualIndex = buildSearchIndex(catalogs["1.4.0"], true);
181345
+ function termWeights(index) {
181346
+ const frequencies = /* @__PURE__ */ new Map();
181366
181347
  for (const { fields } of index) for (const term of new Set(fields.flatMap((field) => [...field.terms]))) {
181367
181348
  frequencies.set(term, (frequencies.get(term) ?? 0) + 1);
181368
181349
  }
181369
181350
  return new Map([...frequencies].map(([term, count]) => [term, 1 + Math.log((index.length + 1) / (count + 1))]));
181370
- })();
181371
- function rankedCandidates(search, version) {
181372
- const scenes = catalogs[version], searchIndex = searchIndexes[version];
181351
+ }
181352
+ var v14TermWeights = termWeights(searchIndexes["1.4.0"]);
181353
+ var bilingualTermWeights = termWeights(bilingualIndex);
181354
+ function rankedCandidates(search, version, bilingual = false) {
181355
+ const scenes = catalogs[version], searchIndex = bilingual ? bilingualIndex : searchIndexes[version];
181373
181356
  if (!search) return scenes;
181374
181357
  const exact = scenes.find((scene) => scene.id === search);
181375
181358
  if (exact) return [exact];
181376
- const queryTerms = stems(search);
181359
+ const queryTerms = bilingual ? discoveryTerms(search) : stems(search);
181377
181360
  if (version === "1.4.0") queryTerms.delete("quien");
181378
181361
  return searchIndex.map(({ scene, fields }) => {
181379
181362
  if (version === "1.4.0") {
@@ -181381,8 +181364,9 @@ function rankedCandidates(search, version) {
181381
181364
  for (const term of queryTerms) {
181382
181365
  const fieldWeight = fields.reduce((sum, field) => sum + (field.terms.has(term) ? field.weight : 0), 0);
181383
181366
  if (!fieldWeight) continue;
181384
- const rarity = v14TermWeights.get(term);
181385
- score += rarity * Math.sqrt(fieldWeight);
181367
+ const rarity = (bilingual ? bilingualTermWeights : v14TermWeights).get(term);
181368
+ const mechanismBoost = bilingual && mechanismTerms.has(term) && fields.slice(0, 2).some((field) => field.terms.has(term)) ? 3 : 1;
181369
+ score += rarity * Math.sqrt(fieldWeight) * mechanismBoost;
181386
181370
  coverage += rarity;
181387
181371
  }
181388
181372
  return { scene, score: score * Math.sqrt(coverage) };
@@ -181426,13 +181410,16 @@ function listAuthoredMotionScenes(options = {}) {
181426
181410
  let version = options.version ?? AUTHORED_MOTION_CATALOG_VERSION;
181427
181411
  if (!isAuthoredMotionVersion(version)) throw Error("Unknown authored motion version");
181428
181412
  let cursorId;
181413
+ let bilingual = version === "1.4.0" && Boolean(search);
181429
181414
  if (after !== void 0) {
181430
- const [cursorVersion, encoded, id2, encodedFilters, ...extra] = after.split("|");
181431
- if (!isAuthoredMotionVersion(cursorVersion) || options.version !== void 0 && options.version !== cursorVersion || encoded !== encodeURIComponent(search) || !id2 || encodedFilters !== cursorFilters || extra.length) throw new Error("Cursor does not match this authored motion query, version or filters.");
181415
+ const [cursorVersion, encoded, id2, encodedFilters, ranker, ...extra] = after.split("|");
181416
+ const q2 = ranker === "q2" && cursorVersion === "1.4.0" && Boolean(search);
181417
+ if (!isAuthoredMotionVersion(cursorVersion) || options.version !== void 0 && options.version !== cursorVersion || encoded !== encodeURIComponent(search) || !id2 || (q2 ? encodedFilters !== (cursorFilters ?? "") : encodedFilters !== cursorFilters) || ranker !== void 0 && !q2 || extra.length) throw new Error("Cursor does not match this authored motion query, version or filters.");
181432
181418
  version = cursorVersion;
181433
181419
  cursorId = id2;
181420
+ bilingual = q2;
181434
181421
  }
181435
- const queryCandidates = version === "1.0.0" ? legacyCandidates(search) : rankedCandidates(search, version);
181422
+ const queryCandidates = version === "1.0.0" ? legacyCandidates(search) : rankedCandidates(search, version, bilingual);
181436
181423
  const candidates = queryCandidates.filter((scene) => matchesAuthoredMotionFilters(scene.facets, filters));
181437
181424
  if (!search && filters.funcion) candidates.sort((a, b) => Number(filters.funcion.includes(b.facets.funciones[0])) - Number(filters.funcion.includes(a.facets.funciones[0])));
181438
181425
  let start3 = 0;
@@ -181444,7 +181431,7 @@ function listAuthoredMotionScenes(options = {}) {
181444
181431
  return {
181445
181432
  version,
181446
181433
  items: page.map(summary),
181447
- nextCursor: start3 + page.length < candidates.length ? `${version}|${encodeURIComponent(search)}|${page[page.length - 1].id}${cursorFilters ? `|${cursorFilters}` : ""}` : null,
181434
+ nextCursor: start3 + page.length < candidates.length ? `${version}|${encodeURIComponent(search)}|${page[page.length - 1].id}${bilingual ? `|${cursorFilters ?? ""}|q2` : cursorFilters ? `|${cursorFilters}` : ""}` : null,
181448
181435
  total: candidates.length,
181449
181436
  facetCounts: countAuthoredMotionFacets(queryCandidates, filters),
181450
181437
  availableFacetCounts: structuredClone(availableFacetCounts[version]),
@@ -181575,6 +181562,339 @@ function getPersonalResourceGuide() {
181575
181562
  return { schemaVersion: 1, optional: true, createsResources: false, notice: "Suggestions are not uploaded assets or confirmed customer preferences. Select only relevant examples, then use real customer files and editable usage guidance. Do not require every slot or upload.", starters: resourceStarters };
181576
181563
  }
181577
181564
 
181565
+ // packages/core/src/style-source-data-v1.ts
181566
+ var styleSourceData = [
181567
+ {
181568
+ "id": "comando-y-resultado",
181569
+ "name": "Comando y resultado",
181570
+ "summary": "Cada instrucci\xF3n aparece como tarjeta y se convierte en su resultado frente a quien habla.",
181571
+ "needs": [
181572
+ "tu clip hablando a c\xE1mara",
181573
+ "las im\xE1genes de cada resultado"
181574
+ ],
181575
+ "sourceVersion": "1.0.0",
181576
+ "sourceSha256": "5851f934ff5450056ea3032999cb5c244dbd1fd1ec90e2d33cf0ae804ac58c88",
181577
+ "sourceBytes": 53379860,
181578
+ "fileCount": 74,
181579
+ "unpackedBytes": 58695062,
181580
+ "requiredPlan": "creator",
181581
+ "ratio": "tall",
181582
+ "demoSha256": "85e71c00e290105304d21bacb17108892a82483f78eb4d3d601fb6008dc15571"
181583
+ },
181584
+ {
181585
+ "id": "narrador-sobre-collage",
181586
+ "name": "Narrador sobre collage de im\xE1genes",
181587
+ "summary": "Una imagen nueva a sangre por cada idea, con quien narra recortado y cambiando de lugar.",
181588
+ "needs": [
181589
+ "tu clip hablando a c\xE1mara (mejor con fondo liso)",
181590
+ "15\u201320 im\xE1genes"
181591
+ ],
181592
+ "sourceVersion": "1.0.0",
181593
+ "sourceSha256": "a1df048358ba37a23fd723fb0178c381da399ed40ddc0a81bc0109292aa5d083",
181594
+ "sourceBytes": 67824224,
181595
+ "fileCount": 87,
181596
+ "unpackedBytes": 73121837,
181597
+ "requiredPlan": "creator",
181598
+ "ratio": "tall",
181599
+ "demoSha256": "8634d6e1cc0274dcd8660f8f17b9fc4a249fd8aea077ef99826c4ed06dda1eb7"
181600
+ },
181601
+ {
181602
+ "id": "presentador-con-interfaz",
181603
+ "name": "Presentador con escenario de interfaz",
181604
+ "summary": "Arriba, interfaces animadas que ejecutan cada funci\xF3n; abajo, quien presenta.",
181605
+ "needs": [
181606
+ "tu clip hablando a c\xE1mara",
181607
+ "las funciones de tu producto (la interfaz se dibuja)"
181608
+ ],
181609
+ "sourceVersion": "1.0.0",
181610
+ "sourceSha256": "aa7d0a61aa3794139ac16a929bf0929b92b1c24f7e54cdcde155fbc2905de476",
181611
+ "sourceBytes": 36093673,
181612
+ "fileCount": 67,
181613
+ "unpackedBytes": 41512815,
181614
+ "requiredPlan": "creator",
181615
+ "ratio": "tall",
181616
+ "demoSha256": "b7785f6a59683068041d2256851ca52e19454d34bf73fee137e83f1fc8091c87"
181617
+ },
181618
+ {
181619
+ "id": "ensayo-cinematografico",
181620
+ "name": "Ensayo cinematogr\xE1fico con tarjetas tipogr\xE1ficas",
181621
+ "summary": "Planos de cine, tarjetas tipogr\xE1ficas que se revelan palabra por palabra y regresos a c\xE1mara.",
181622
+ "needs": [
181623
+ "tu clip hablando a c\xE1mara",
181624
+ "6\u201310 planos de B-roll"
181625
+ ],
181626
+ "sourceVersion": "1.0.0",
181627
+ "sourceSha256": "90f137ecc841067226c0b97a44e50440e3bd9a3d367b3dc177c5560ec90ccef0",
181628
+ "sourceBytes": 67266840,
181629
+ "fileCount": 86,
181630
+ "unpackedBytes": 72343103,
181631
+ "requiredPlan": "creator",
181632
+ "ratio": "tall",
181633
+ "demoSha256": "88861691ca215075aa9f4d4e5258f42a776ca1fdd2e4a50d399f7c519f3a1cb5"
181634
+ },
181635
+ {
181636
+ "id": "tutorial-por-capitulos",
181637
+ "name": "Tutorial por cap\xEDtulos con capturas",
181638
+ "summary": "Numeral gigante por cap\xEDtulo, la interfaz con zoom al prompt y el resultado en pantalla.",
181639
+ "needs": [
181640
+ "tu clip hablando a c\xE1mara",
181641
+ "capturas o la interfaz de tu herramienta"
181642
+ ],
181643
+ "sourceVersion": "1.0.0",
181644
+ "sourceSha256": "774fe0cd40423e050430b5ef463ca4b374dbef9ded6da3437809af218866827a",
181645
+ "sourceBytes": 63896838,
181646
+ "fileCount": 67,
181647
+ "unpackedBytes": 69296736,
181648
+ "requiredPlan": "creator",
181649
+ "ratio": "tall",
181650
+ "demoSha256": "e7e5cc8f851de24acb976839c2ce9f196908796cbefbb8ffce1c0a90e4581720"
181651
+ },
181652
+ {
181653
+ "id": "tablero-que-se-llena",
181654
+ "name": "Tablero que se llena",
181655
+ "summary": "Un ranking por niveles que se llena mientras opinas, en una sola toma.",
181656
+ "needs": [
181657
+ "tu clip hablando a c\xE1mara en una toma",
181658
+ "los \xEDconos de cada \xEDtem"
181659
+ ],
181660
+ "sourceVersion": "1.0.0",
181661
+ "sourceSha256": "122386757e9706a1725def3c5080b67053241949ed87336889d49a073c6c029f",
181662
+ "sourceBytes": 71615105,
181663
+ "fileCount": 70,
181664
+ "unpackedBytes": 81577587,
181665
+ "requiredPlan": "creator",
181666
+ "ratio": "tall",
181667
+ "demoSha256": "40ec0c80a2fec5ffb4eb822f71717c44987ac0d6a8aacd1fa189830e4a5f2cd5"
181668
+ },
181669
+ {
181670
+ "id": "explicador-con-evidencias",
181671
+ "name": "Explicador editorial con evidencias",
181672
+ "summary": "Tu argumento sostenido con documentos, fotos de archivo y resaltados sobre papel.",
181673
+ "needs": [
181674
+ "tu clip de cuerpo completo (mejor con fondo liso)",
181675
+ "im\xE1genes y documentos"
181676
+ ],
181677
+ "sourceVersion": "1.0.0",
181678
+ "sourceSha256": "fd56bdc3f5039b3cf15dbde54a413ee4688b0724bb3de9bc04d836b1183df29f",
181679
+ "sourceBytes": 28347758,
181680
+ "fileCount": 76,
181681
+ "unpackedBytes": 33672572,
181682
+ "requiredPlan": "creator",
181683
+ "ratio": "tall",
181684
+ "demoSha256": "34714b3a1051399ff7021e323c1819da3931e01709f201b86f0224fc12b0bc3b"
181685
+ },
181686
+ {
181687
+ "id": "monologo-con-dipticos",
181688
+ "name": "Mon\xF3logo con d\xEDpticos",
181689
+ "summary": "Una toma fija sin cortes: titular arriba y un par de im\xE1genes por cada frase.",
181690
+ "needs": [
181691
+ "tu clip hablando a c\xE1mara en una toma",
181692
+ "dos im\xE1genes por frase"
181693
+ ],
181694
+ "sourceVersion": "1.0.0",
181695
+ "sourceSha256": "bf4a3942f416e2828ece822bf1d647bfdb7bd876204b711c1a76f688ac4e7f44",
181696
+ "sourceBytes": 71193505,
181697
+ "fileCount": 94,
181698
+ "unpackedBytes": 76379034,
181699
+ "requiredPlan": "creator",
181700
+ "ratio": "tall",
181701
+ "demoSha256": "0081ff2bfd67f74f5b8cd7e0d17368d048e9a2e303a8755a6fced7ca368e613c"
181702
+ },
181703
+ {
181704
+ "id": "recorrido-de-experto",
181705
+ "name": "Recorrido de experto con lugar secreto",
181706
+ "summary": "Autoridad, un lugar secreto que se revela al final y planos exactos de cada parada.",
181707
+ "needs": [
181708
+ "tu clip hablando a c\xE1mara",
181709
+ "clips de cada lugar"
181710
+ ],
181711
+ "sourceVersion": "1.0.0",
181712
+ "sourceSha256": "34ddef4f4f9d2cc5cee268b9c967fcb4a45f40455676fcd9cf2c7430d279ab5e",
181713
+ "sourceBytes": 123413427,
181714
+ "fileCount": 80,
181715
+ "unpackedBytes": 128824268,
181716
+ "requiredPlan": "creator",
181717
+ "ratio": "tall",
181718
+ "demoSha256": "fefae76bcb80d3ce2b2a05055bf2c68bb26ec52b307ae4ca09714063fb03c612"
181719
+ },
181720
+ {
181721
+ "id": "vlog-intimo",
181722
+ "name": "Vlog \xEDntimo con texto en escena",
181723
+ "summary": "Una historia personal con palabras que viven en el espacio y papel en stop-motion.",
181724
+ "needs": [
181725
+ "tu clip hablando a c\xE1mara",
181726
+ "clips de tu d\xEDa"
181727
+ ],
181728
+ "sourceVersion": "1.0.0",
181729
+ "sourceSha256": "70ac7e126ab03993e39cdc3e2783fdd2143890fbb160b5a3b3663fef899e170a",
181730
+ "sourceBytes": 95858671,
181731
+ "fileCount": 73,
181732
+ "unpackedBytes": 100794739,
181733
+ "requiredPlan": "creator",
181734
+ "ratio": "tall",
181735
+ "demoSha256": "6222934f0b081b847811ed8d86bacdd3f66bd88364594ccf5649e944f9e2c7cf"
181736
+ },
181737
+ {
181738
+ "id": "documental-de-archivo",
181739
+ "name": "Documental tipogr\xE1fico de archivo",
181740
+ "summary": "R\xE1fagas de archivo y cifras gigantes detr\xE1s de las figuras, como un tr\xE1iler.",
181741
+ "needs": [
181742
+ "un clip breve hablando a c\xE1mara",
181743
+ "fotos de archivo"
181744
+ ],
181745
+ "sourceVersion": "1.0.0",
181746
+ "sourceSha256": "f0c33ebc14d1d929c29850e932477922f29d29228489dcbb9838aea79de9dbc9",
181747
+ "sourceBytes": 28620760,
181748
+ "fileCount": 80,
181749
+ "unpackedBytes": 33907182,
181750
+ "requiredPlan": "creator",
181751
+ "ratio": "tall",
181752
+ "demoSha256": "476c428bde32ad9bbee30fb799ff0ee91642021740aef05f1af0dee6fca598d7"
181753
+ },
181754
+ {
181755
+ "id": "catalogo-editorial",
181756
+ "name": "Cat\xE1logo editorial animado",
181757
+ "summary": "Sin c\xE1mara: l\xE1minas y diagramas que se acumulan hasta revelar tu recurso descargable.",
181758
+ "needs": [
181759
+ "tu voz (o un texto para narrar)",
181760
+ "tu recurso o documento"
181761
+ ],
181762
+ "sourceVersion": "1.0.0",
181763
+ "sourceSha256": "8e1de45eb58407b8a221d6ef115e53fdd49b00febe2b0962c1ef6d1fc15eb7c5",
181764
+ "sourceBytes": 4869367,
181765
+ "fileCount": 64,
181766
+ "unpackedBytes": 9096082,
181767
+ "requiredPlan": "creator",
181768
+ "ratio": "tall",
181769
+ "demoSha256": "109458de45085b7406b8f37ad2e355faa365fd8aa98d6035824806f7a562c3a9"
181770
+ },
181771
+ {
181772
+ "id": "pantalla-fisica",
181773
+ "name": "Explicaci\xF3n sobre pantalla f\xEDsica",
181774
+ "summary": "Una mano recorre una pantalla real con tu proceso; cifras y r\xF3tulos gu\xEDan cada paso.",
181775
+ "needs": [
181776
+ "tu voz",
181777
+ "un video de tu pantalla o tablet con el diagrama"
181778
+ ],
181779
+ "sourceVersion": "1.0.0",
181780
+ "sourceSha256": "2a21e544ca62e06a8896cbd042502277621554d7a6e8aeb83f36ad12454c92fd",
181781
+ "sourceBytes": 24317144,
181782
+ "fileCount": 70,
181783
+ "unpackedBytes": 28553643,
181784
+ "requiredPlan": "creator",
181785
+ "ratio": "tall",
181786
+ "demoSha256": "77a7568e9e0426e89d3be9fbdb7d3b4eea82b9f9161af7c08f6f4c591f9e8f9c"
181787
+ },
181788
+ {
181789
+ "id": "personaje-en-papel",
181790
+ "name": "Personaje animado en escenario de papel",
181791
+ "summary": "T\xFA como personaje dibujado que ejecuta cada paso sobre un escenario de papel.",
181792
+ "needs": [
181793
+ "tu voz",
181794
+ "fotos de tu cara con varias expresiones"
181795
+ ],
181796
+ "sourceVersion": "1.0.0",
181797
+ "sourceSha256": "ef7d6fc8886d130ad291f537e4d4587aa6c55770c146263ccd59a0c223cd3876",
181798
+ "sourceBytes": 15275734,
181799
+ "fileCount": 77,
181800
+ "unpackedBytes": 19549031,
181801
+ "requiredPlan": "creator",
181802
+ "ratio": "tall",
181803
+ "demoSha256": "2268da8622070fac6d5c8fa9270e1a964d9e06259c557fd16cd868bb22169495"
181804
+ },
181805
+ {
181806
+ "id": "simulacion-en-el-mapa",
181807
+ "name": "Simulaci\xF3n en el mapa",
181808
+ "summary": "\xBFQu\xE9 pasar\xEDa si\u2026? contado sobre un globo 3D: el territorio cambia, las p\xE9rdidas se acumulan en pantalla.",
181809
+ "needs": [
181810
+ "tu voz",
181811
+ "una hip\xF3tesis y sus consecuencias con cifras"
181812
+ ],
181813
+ "sourceVersion": "1.0.0",
181814
+ "sourceSha256": "2205ae641895f8435ca1e4457f52e23ba8291167e67aefbabf3eb2cd61e2b42e",
181815
+ "sourceBytes": 22728621,
181816
+ "fileCount": 71,
181817
+ "unpackedBytes": 27474023,
181818
+ "requiredPlan": "creator",
181819
+ "ratio": "tall",
181820
+ "demoSha256": "5cb48759829518bf0982927fcd42767936b188c837bead7aeb251003999c866d"
181821
+ },
181822
+ {
181823
+ "id": "relato-ilustrado",
181824
+ "name": "Relato ilustrado en segunda persona",
181825
+ "summary": "Una historia de tensi\xF3n en ilustraciones: reloj, reglas, contador y cliffhanger.",
181826
+ "needs": [
181827
+ "tu voz",
181828
+ "ilustraciones de un mismo personaje y escenario"
181829
+ ],
181830
+ "sourceVersion": "1.0.0",
181831
+ "sourceSha256": "98d12af2729f0080b2383314d0a1c74df4e538a24224013ee3db6258d2b441c4",
181832
+ "sourceBytes": 25173445,
181833
+ "fileCount": 71,
181834
+ "unpackedBytes": 33027674,
181835
+ "requiredPlan": "creator",
181836
+ "ratio": "tall",
181837
+ "demoSha256": "8ecc9082472fe20a028b6b99305b6ec4a92c9c3a509e6a604054499952b7ad75"
181838
+ },
181839
+ {
181840
+ "id": "pizarra-minimalista",
181841
+ "name": "Pizarra minimalista",
181842
+ "summary": "Acertijos y casos con dibujos de l\xEDnea sobre papel punteado y subt\xEDtulos arriba.",
181843
+ "needs": [
181844
+ "tu voz",
181845
+ "dibujos de l\xEDnea de cada personaje"
181846
+ ],
181847
+ "sourceVersion": "1.0.0",
181848
+ "sourceSha256": "13af7a854f9bfa946bb4227786775c6b4dde06ef9601c3209e8b87261332ce6e",
181849
+ "sourceBytes": 19016433,
181850
+ "fileCount": 71,
181851
+ "unpackedBytes": 23336820,
181852
+ "requiredPlan": "creator",
181853
+ "ratio": "tall",
181854
+ "demoSha256": "bdd4c6994077746d56ae42778b5d433a7b711c1dfbd23f4eaf83446147aebd64"
181855
+ },
181856
+ {
181857
+ "id": "infografia-de-objetos",
181858
+ "name": "Infograf\xEDa de objetos",
181859
+ "summary": "Un concepto de negocio explicado con objetos, tarjetas comparativas y una radiograf\xEDa del mecanismo.",
181860
+ "needs": [
181861
+ "tu voz",
181862
+ "las opciones o cifras que vas a comparar"
181863
+ ],
181864
+ "sourceVersion": "1.0.0",
181865
+ "sourceSha256": "2398984bf1cc7c0d47521c3e35f3831d29110067ff750c09d31518fcc8302956",
181866
+ "sourceBytes": 4813352,
181867
+ "fileCount": 65,
181868
+ "unpackedBytes": 9427443,
181869
+ "requiredPlan": "creator",
181870
+ "ratio": "tall",
181871
+ "demoSha256": "9d8f5537545df7c7068258a7d4ddb5bb742d9d3660d5e7cbf7657224061488af"
181872
+ },
181873
+ {
181874
+ "id": "ranking-con-escala",
181875
+ "name": "Ranking con escala",
181876
+ "summary": "Calificas opciones a c\xE1mara con una escala de colores fija arriba y la nota de cada una.",
181877
+ "needs": [
181878
+ "tu clip a c\xE1mara de medio cuerpo",
181879
+ "una ilustraci\xF3n o foto por opci\xF3n"
181880
+ ],
181881
+ "sourceVersion": "1.0.0",
181882
+ "sourceSha256": "51e417fe9af71064e3a20b9cd7e0103d67c54f8d521f39eae9752698b1b35c0b",
181883
+ "sourceBytes": 28346697,
181884
+ "fileCount": 73,
181885
+ "unpackedBytes": 33447909,
181886
+ "requiredPlan": "creator",
181887
+ "ratio": "tall",
181888
+ "demoSha256": "ddca372d5b2f0e8029422333427890220dcbbfd32ca0aa166ec3f8543ec0eea5"
181889
+ }
181890
+ ];
181891
+
181892
+ // packages/core/src/style-sources.ts
181893
+ var STYLE_SOURCE_MAX_BYTES = 128 * 1024 * 1024;
181894
+ function getStyleSource(id2, version) {
181895
+ return styleSourceData.find((style) => style.id === id2 && style.sourceVersion === version);
181896
+ }
181897
+
181578
181898
  // packages/core/src/index.ts
181579
181899
  var SCHEMA_VERSION = 1;
181580
181900
  var MAX_DOCUMENT_BYTES = 128 * 1024;
@@ -182030,9 +182350,10 @@ function canonicalFiles(files) {
182030
182350
  return result2;
182031
182351
  }
182032
182352
 
182033
- // packages/cli/src/personal-resources.ts
182034
- import { basename, extname as extname2, resolve as resolve3 } from "node:path";
182035
- import { randomUUID as randomUUID2 } from "node:crypto";
182353
+ // packages/cli/src/authored-motion.ts
182354
+ import { lstat as lstat2, mkdir as mkdir2, open as open2, link as link2, unlink as unlink2 } from "node:fs/promises";
182355
+ import { dirname as dirname2, join as join2 } from "node:path";
182356
+ import { createHash, randomUUID as randomUUID2 } from "node:crypto";
182036
182357
 
182037
182358
  // packages/cli/src/errors.ts
182038
182359
  var CliError = class extends Error {
@@ -182056,239 +182377,28 @@ function errorOutput(error) {
182056
182377
  return { error: safe, code: "COMMAND_FAILED", retryable: false, hint: "Read the command help and run editorbrain doctor. Do not retry writes blindly." };
182057
182378
  }
182058
182379
 
182059
- // packages/cli/src/media-runtime.ts
182060
- import { spawn } from "node:child_process";
182061
- import { createHash } from "node:crypto";
182062
- import { constants } from "node:fs";
182063
- import { lstat, open, realpath } from "node:fs/promises";
182064
- import { dirname, extname, parse, resolve } from "node:path";
182065
- var MediaToolError = class extends CliError {
182066
- constructor(code, message) {
182067
- super(code, message, code === "MEDIA_TOOL_NOT_FOUND" ? "Install FFmpeg/FFprobe separately and make them available on PATH; no account or model is needed." : "Review the local input and reported limit. An incomplete check does not validate the media.");
182068
- this.name = "MediaToolError";
182069
- }
182070
- };
182071
- var SUPPORTED_MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
182072
- ".mp4",
182073
- ".mov",
182074
- ".m4v",
182075
- ".mkv",
182076
- ".webm",
182077
- ".avi",
182078
- ".mpg",
182079
- ".mpeg",
182080
- ".mts",
182081
- ".m2ts",
182082
- ".ts",
182083
- ".ogv",
182084
- ".wmv",
182085
- ".wav",
182086
- ".mp3",
182087
- ".m4a",
182088
- ".aac",
182089
- ".flac",
182090
- ".ogg",
182091
- ".opus",
182092
- ".aif",
182093
- ".aiff",
182094
- ".ac3",
182095
- ".eac3",
182096
- ".jpg",
182097
- ".jpeg",
182098
- ".png",
182099
- ".webp",
182100
- ".bmp",
182101
- ".tif",
182102
- ".tiff",
182103
- ".gif",
182104
- ".avif",
182105
- ".heic",
182106
- ".heif"
182107
- ]);
182108
- var PROTOCOLS = "file,pipe";
182109
- var FORMATS = "mov,matroska,webm,avi,mpeg,mpegts,ogg,wav,flac,mp3,aac,aiff,ac3,eac3,asf,jpeg_pipe,png_pipe,webp_pipe,bmp_pipe,tiff_pipe,gif,heif,avif";
182110
- var DEFAULT_TIMEOUT = 3e4;
182111
- var DEFAULT_OUTPUT_LIMIT = 2 * 1024 * 1024;
182112
- function resolveLocalMediaPath(value) {
182113
- if (!value || value.includes("\0") || /[\r\n]/.test(value) || /^[a-z][a-z\d+.-]*:/i.test(value) && !(process.platform === "win32" && /^[a-z]:[\\/]/i.test(value)) || value.startsWith("\\\\")) {
182114
- throw new MediaToolError("MEDIA_LOCAL_PATH_REQUIRED", "Provide a local filesystem path, not a URL, protocol or network share.");
182115
- }
182116
- return resolve(value);
182117
- }
182118
- async function assertNoMediaSymlinks(value) {
182119
- const path = resolveLocalMediaPath(value);
182120
- let cursor = path;
182121
- while (cursor !== parse(cursor).root) {
182122
- const info = await lstat(cursor);
182123
- if (info.isSymbolicLink()) {
182124
- const systemAlias = process.platform === "darwin" && (cursor === "/tmp" || cursor === "/var") && await realpath(cursor) === `/private${cursor}`;
182125
- if (!systemAlias) throw new MediaToolError("MEDIA_SYMLINK", "Symlink media paths are not followed. Use the original local path.");
182126
- }
182127
- cursor = dirname(cursor);
182128
- }
182129
- return path;
182130
- }
182131
- async function assertLocalMediaFile(value) {
182132
- const path = await assertNoMediaSymlinks(value);
182133
- const info = await lstat(path);
182134
- if (!info.isFile()) throw new MediaToolError("MEDIA_NOT_REGULAR", "The media input must be a regular local file.");
182135
- if (!SUPPORTED_MEDIA_EXTENSIONS.has(extname(path).toLowerCase())) throw new MediaToolError("MEDIA_FORMAT_UNSUPPORTED", "This file extension is not supported for local media inspection.");
182136
- return path;
182137
- }
182138
- function localInputArgs(path) {
182139
- return ["-protocol_whitelist", PROTOCOLS, "-format_whitelist", FORMATS, "-i", resolveLocalMediaPath(path)];
182140
- }
182141
- async function runMediaTool(tool, args, options = {}) {
182142
- if (tool !== "ffmpeg" && tool !== "ffprobe") throw new MediaToolError("MEDIA_TOOL_INVALID", "Unsupported media executable.");
182143
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT;
182144
- const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_OUTPUT_LIMIT;
182145
- if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 10 * 6e4 || !Number.isInteger(maxOutputBytes) || maxOutputBytes < 1 || maxOutputBytes > 16 * 1024 * 1024) {
182146
- throw new MediaToolError("MEDIA_TOOL_LIMITS_INVALID", "Media runtime limits are outside the supported range.");
182147
- }
182148
- if (!Array.isArray(args) || args.length > 200 || args.some((arg) => typeof arg !== "string" || arg.length > 8192 || arg.includes("\0"))) {
182149
- throw new MediaToolError("MEDIA_TOOL_ARGUMENTS_INVALID", "Invalid media tool arguments.");
182150
- }
182151
- for (let i = 0; i < args.length; i++) {
182152
- const arg = args[i];
182153
- if (/(?:^|[=,;\s])(?:https?|ftp|sftp|tcp|udp|rtsp|rtmp|smb|data|concat|subfile|crypto):/i.test(arg) || arg === "-safe" && args[i + 1] === "0" || arg === "-enable_drefs" && args[i + 1] !== "0") {
182154
- throw new MediaToolError("MEDIA_REMOTE_INPUT_FORBIDDEN", "Only self-contained local media inputs are allowed.");
182155
- }
182156
- if (arg === "-protocol_whitelist" && args[i + 1] !== PROTOCOLS || arg === "-format_whitelist" && args[i + 1] !== FORMATS) {
182157
- throw new MediaToolError("MEDIA_TOOL_ARGUMENTS_INVALID", "The local media allowlists cannot be widened.");
182158
- }
182159
- if (arg === "-i") {
182160
- await assertLocalMediaFile(args[i + 1] ?? "");
182161
- if (args[i - 4] !== "-protocol_whitelist" || args[i - 3] !== PROTOCOLS || args[i - 2] !== "-format_whitelist" || args[i - 1] !== FORMATS) {
182162
- throw new MediaToolError("MEDIA_TOOL_ARGUMENTS_INVALID", "Every media input must use localInputArgs.");
182163
- }
182164
- }
182165
- }
182166
- return new Promise((resolveResult, reject) => {
182167
- const stdout = [], stderr = [];
182168
- let size = 0, done = false;
182169
- const child = spawn(tool, ["-hide_banner", ...tool === "ffmpeg" ? ["-nostdin"] : [], ...args], { shell: false, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
182170
- const fail3 = (error) => {
182171
- if (done) return;
182172
- done = true;
182173
- clearTimeout(timer);
182174
- child.kill("SIGKILL");
182175
- reject(error);
182176
- };
182177
- const timer = setTimeout(() => fail3(new MediaToolError("MEDIA_TOOL_TIMEOUT", "The local media check exceeded its time limit. No complete result is available.")), timeoutMs);
182178
- const collect = (target) => (chunk) => {
182179
- if (done) return;
182180
- size += chunk.length;
182181
- if (size > maxOutputBytes) return fail3(new MediaToolError("MEDIA_TOOL_OUTPUT_LIMIT", "The local media check exceeded its output limit. No complete result is available."));
182182
- target.push(chunk);
182183
- };
182184
- child.stdout.on("data", collect(stdout));
182185
- child.stderr.on("data", collect(stderr));
182186
- child.on("error", (error) => fail3(new MediaToolError(error.code === "ENOENT" ? "MEDIA_TOOL_NOT_FOUND" : "MEDIA_TOOL_FAILED", error.code === "ENOENT" ? `${tool} is not installed or available on PATH. Install it separately to use local media checks.` : "The local media executable could not run.")));
182187
- child.on("close", (code) => {
182188
- if (done) return;
182189
- done = true;
182190
- clearTimeout(timer);
182191
- if (code !== 0) return reject(new MediaToolError("MEDIA_TOOL_FAILED", "The local media tool could not inspect or decode this input. No complete result is available."));
182192
- resolveResult({ stdout: Buffer.concat(stdout).toString("utf8"), stderr: Buffer.concat(stderr).toString("utf8") });
182193
- });
182194
- });
182195
- }
182196
- var finite2 = (value) => {
182197
- if (typeof value !== "number" && typeof value !== "string" || value === "") return null;
182198
- const n = Number(value);
182199
- return Number.isFinite(n) ? n : null;
182200
- };
182201
- var nonnegative2 = (value) => {
182202
- const n = finite2(value);
182203
- return n !== null && n >= 0 ? n : null;
182204
- };
182205
- var positiveInteger = (value) => {
182206
- const n = finite2(value);
182207
- return n !== null && Number.isInteger(n) && n > 0 ? n : void 0;
182208
- };
182209
- var rate2 = (value) => {
182210
- if (typeof value !== "string" || !/^\d+(?:\/\d+)?$/.test(value)) return null;
182211
- const [n, d = "1"] = value.split("/");
182212
- const result2 = Number(n) / Number(d);
182213
- return Number.isFinite(result2) && result2 > 0 ? result2 : null;
182214
- };
182215
- var sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs;
182216
- function hasDisplayTransform(stream) {
182217
- const rotate = stream.tags?.rotate;
182218
- if (rotate !== void 0 && (!Number.isFinite(Number(rotate)) || Number(rotate) % 360 !== 0)) return true;
182219
- const sideData = Array.isArray(stream.side_data_list) ? stream.side_data_list : [];
182220
- return sideData.some((data) => {
182221
- if (!data || typeof data !== "object") return false;
182222
- if (data.rotation !== void 0 && (!Number.isFinite(Number(data.rotation)) || Number(data.rotation) % 360 !== 0)) return true;
182223
- if (data.displaymatrix === void 0) return data.side_data_type === "Display Matrix";
182224
- if (typeof data.displaymatrix !== "string") return true;
182225
- const values = data.displaymatrix.trim().split("\n").flatMap((line) => line.replace(/^[^:]*:/, "").trim().split(/\s+/).map(Number));
182226
- const identity = [65536, 0, 0, 0, 65536, 0, 0, 0, 1073741824];
182227
- return values.length !== 9 || values.some((value, index) => value !== identity[index]);
182228
- });
182229
- }
182230
- async function probeLocalMedia(value) {
182231
- const path = await assertLocalMediaFile(value);
182232
- const handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
182233
- try {
182234
- const before = await handle.stat();
182235
- if (!before.isFile()) throw new MediaToolError("MEDIA_NOT_REGULAR", "The media input must be a regular local file.");
182236
- const entries = "format=duration,start_time:stream=index,codec_type,codec_name,width,height,avg_frame_rate,sample_rate,channels,duration,color_transfer,sample_aspect_ratio,pix_fmt:stream_disposition=attached_pic:stream_side_data=side_data_type,rotation,displaymatrix:stream_tags=rotate";
182237
- const { stdout } = await runMediaTool("ffprobe", ["-v", "error", "-show_entries", entries, "-of", "json", ...localInputArgs(path)]);
182238
- const hash6 = createHash("sha256");
182239
- for await (const chunk of handle.createReadStream({ autoClose: false })) hash6.update(chunk);
182240
- const after = await handle.stat();
182241
- await assertNoMediaSymlinks(path);
182242
- const current2 = await lstat(path);
182243
- if (!sameFile(before, after) || !sameFile(after, current2)) throw new MediaToolError("MEDIA_FILE_CHANGED", "The media file changed while it was being inspected. Retry with a stable source.");
182244
- let raw;
182245
- try {
182246
- raw = JSON.parse(stdout);
182247
- } catch {
182248
- throw new MediaToolError("MEDIA_PROBE_INVALID", "The media probe returned invalid metadata.");
182249
- }
182250
- if (!raw || !Array.isArray(raw.streams) || raw.streams.length > 256 || raw.streams.some((stream) => !stream || typeof stream !== "object" || Array.isArray(stream))) throw new MediaToolError("MEDIA_PROBE_INVALID", "The media probe returned invalid or excessive stream metadata.");
182251
- const streams = raw.streams.map((stream, offset) => {
182252
- const type = typeof stream.codec_type === "string" && /^(video|audio|subtitle|data|attachment|unknown)$/.test(stream.codec_type) ? stream.codec_type : "unknown";
182253
- const codec = typeof stream.codec_name === "string" && /^[a-zA-Z0-9_]{1,64}$/.test(stream.codec_name) ? stream.codec_name : null;
182254
- const index = finite2(stream.index);
182255
- return {
182256
- index: index !== null && Number.isInteger(index) && index >= 0 ? index : offset,
182257
- type,
182258
- codec,
182259
- durationSeconds: nonnegative2(stream.duration),
182260
- ...type === "video" ? { displayTransformed: hasDisplayTransform(stream), width: positiveInteger(stream.width), height: positiveInteger(stream.height), fps: rate2(stream.avg_frame_rate), ...typeof stream.sample_aspect_ratio === "string" ? { sampleAspectRatio: stream.sample_aspect_ratio } : {}, ...typeof stream.pix_fmt === "string" ? { pixelFormat: stream.pix_fmt } : {}, ...typeof stream.color_transfer === "string" ? { colorTransfer: stream.color_transfer } : {}, attachedPicture: stream.disposition?.attached_pic === 1 } : {},
182261
- ...type === "audio" ? { sampleRate: nonnegative2(stream.sample_rate), channels: positiveInteger(stream.channels) ?? null } : {}
182262
- };
182263
- });
182264
- return { path, sha256: hash6.digest("hex"), bytes: after.size, durationSeconds: nonnegative2(raw.format?.duration), startTimeSeconds: finite2(raw.format?.start_time), streams };
182265
- } finally {
182266
- await handle.close();
182267
- }
182268
- }
182269
-
182270
182380
  // packages/cli/src/io.ts
182271
- import { constants as constants2 } from "node:fs";
182272
- import { lstat as lstat2, mkdir, open as open2, readdir, realpath as realpath2, rename, unlink, link } from "node:fs/promises";
182273
- import { dirname as dirname2, join, relative, resolve as resolve2, sep } from "node:path";
182381
+ import { constants } from "node:fs";
182382
+ import { lstat, mkdir, open, readdir, realpath, rename, unlink, link } from "node:fs/promises";
182383
+ import { dirname, join, relative, resolve, sep } from "node:path";
182274
182384
  import { randomUUID } from "node:crypto";
182275
182385
  async function ensureRoot(directory, create = false) {
182276
- const root = resolve2(directory);
182386
+ const root = resolve(directory);
182277
182387
  if (create) await mkdir(root, { recursive: true });
182278
- const info = await lstat2(root);
182388
+ const info = await lstat(root);
182279
182389
  if (info.isSymbolicLink() || !info.isDirectory()) throw new Error("Workspace root must be a real directory, not a symlink");
182280
- return realpath2(root);
182390
+ return realpath(root);
182281
182391
  }
182282
182392
  async function checkedPath(root, path, document2 = true) {
182283
182393
  if (document2) safeDocumentPath(path);
182284
- const target = resolve2(root, path);
182394
+ const target = resolve(root, path);
182285
182395
  const rel = relative(root, target);
182286
- if (!rel || rel.startsWith(`..${sep}`) || rel === ".." || resolve2(path) === path) throw new Error("Path escapes workspace");
182396
+ if (!rel || rel.startsWith(`..${sep}`) || rel === ".." || resolve(path) === path) throw new Error("Path escapes workspace");
182287
182397
  let cursor = root;
182288
182398
  for (const segment of rel.split(sep)) {
182289
182399
  cursor = join(cursor, segment);
182290
182400
  try {
182291
- const info = await lstat2(cursor);
182401
+ const info = await lstat(cursor);
182292
182402
  if (info.isSymbolicLink()) throw new Error(`Symlinks are not allowed: ${path}`);
182293
182403
  } catch (error) {
182294
182404
  if (error.code !== "ENOENT") throw error;
@@ -182298,7 +182408,7 @@ async function checkedPath(root, path, document2 = true) {
182298
182408
  }
182299
182409
  async function readText(root, path, document2 = true) {
182300
182410
  const target = await checkedPath(root, path, document2);
182301
- const handle = await open2(target, constants2.O_RDONLY | constants2.O_NOFOLLOW);
182411
+ const handle = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW);
182302
182412
  try {
182303
182413
  const info = await handle.stat();
182304
182414
  if (!info.isFile()) throw new Error(`Not a regular file: ${path}`);
@@ -182310,10 +182420,10 @@ async function readText(root, path, document2 = true) {
182310
182420
  }
182311
182421
  async function atomicWrite(root, path, content, options = {}) {
182312
182422
  const target = await checkedPath(root, path, options.document ?? true);
182313
- await mkdir(dirname2(target), { recursive: true });
182423
+ await mkdir(dirname(target), { recursive: true });
182314
182424
  await checkedPath(root, path, options.document ?? true);
182315
- const temporary = join(dirname2(target), `.eh-${randomUUID()}.tmp`);
182316
- const handle = await open2(temporary, "wx", options.mode ?? 420);
182425
+ const temporary = join(dirname(target), `.eh-${randomUUID()}.tmp`);
182426
+ const handle = await open(temporary, "wx", options.mode ?? 420);
182317
182427
  try {
182318
182428
  await handle.writeFile(content, "utf8");
182319
182429
  await handle.close();
@@ -182382,10 +182492,1538 @@ async function readProjectWorkspace(root, projectId) {
182382
182492
  return canonicalFiles(files);
182383
182493
  }
182384
182494
 
182385
- // packages/cli/src/production-output.ts
182495
+ // packages/cli/src/authored-motion.ts
182496
+ async function downloadAuthoredSource(client, pin, root, out, fetcher = fetch) {
182497
+ return downloadPinnedSource(client, pin, root, out, "motion", fetcher);
182498
+ }
182499
+ async function downloadPinnedSource(client, pin, root, out, kind, fetcher = fetch) {
182500
+ const namespace = kind === "style" ? "style-sources" : "authored-motion";
182501
+ const downloadNamespace = kind === "style" ? "style-source-download" : "authored-motion-download";
182502
+ if (!/^[a-z0-9][a-z0-9-]{0,79}$/.test(pin.id) || !/^\d+\.\d+\.\d+$/.test(pin.version) || !/^[a-f0-9]{64}$/.test(pin.sha256) || !Number.isSafeInteger(pin.bytes) || pin.bytes < 1 || pin.bytes > (kind === "style" ? 128 : pin.version === "1.4.0" ? 96 : 16) * 1024 * 1024) throw new CliError("INVALID_ARGUMENT", "Invalid pinned source bundle.", "Retrieve one authored scene from the catalog.");
182503
+ const target = await checkedPath(root, out, false);
182504
+ try {
182505
+ await lstat2(target);
182506
+ throw new CliError("FILE_EXISTS", "The output already exists.", "Choose a new archive path.");
182507
+ } catch (error) {
182508
+ if (error.code !== "ENOENT") throw error;
182509
+ }
182510
+ const metadata = await client.request(`/v1/${namespace}/${pin.id}/source?${new URLSearchParams({ version: pin.version, sha256: pin.sha256 })}`);
182511
+ const url2 = new URL(metadata.url);
182512
+ const expectedPath = `/v1/${downloadNamespace}/${pin.id}/${pin.version}/${pin.sha256}`;
182513
+ const origin = new URL(client.url).origin;
182514
+ const trustedOrigin = url2.origin === origin || origin === "https://editorharness-api.innovandohorizontes.workers.dev" && url2.origin === "https://api.editorbrain.com";
182515
+ if (metadata.sha256 !== pin.sha256 || metadata.bytes !== pin.bytes || !trustedOrigin || url2.pathname !== expectedPath || url2.username || url2.password || url2.hash) throw new CliError("INVALID_RESPONSE", "Source bundle metadata differs from the selected version.", "Do not use this source. Retrieve the pinned catalog entry again.");
182516
+ const response = await fetcher(url2, { redirect: "error", signal: AbortSignal.timeout(18e4) });
182517
+ if (response.status === 403) {
182518
+ await response.body?.cancel();
182519
+ throw new CliError("RESOURCE_ACCESS_CHANGED", "Source access was denied at download time.", "Check current workspace permissions and membership at https://editorbrain.com/app/billing. Do not retry old versions or buy credits to unlock premium resources; existing archives were preserved.");
182520
+ }
182521
+ if (!response.ok) throw new CliError("DOWNLOAD_FAILED", `Source download failed (HTTP ${response.status}).`, "Request a new source link; existing archives were preserved.");
182522
+ const reader = response.body?.getReader();
182523
+ if (!reader) throw new CliError("INVALID_RESPONSE", "Source download body is missing.", "Retry the pinned source.");
182524
+ const temporary = join2(dirname2(target), `.eb-motion-${randomUUID2()}.tmp`);
182525
+ let handle;
182526
+ const hash6 = createHash("sha256");
182527
+ let size = 0;
182528
+ try {
182529
+ await mkdir2(dirname2(target), { recursive: true });
182530
+ await checkedPath(root, out, false);
182531
+ handle = await open2(temporary, "wx", 384);
182532
+ for (; ; ) {
182533
+ const { done, value } = await reader.read();
182534
+ if (done) break;
182535
+ size += value.length;
182536
+ if (size > pin.bytes) throw new CliError("HASH_MISMATCH", "Source archive exceeds the pinned length.", "Discard the unverified download.");
182537
+ hash6.update(value);
182538
+ await handle.writeFile(value);
182539
+ }
182540
+ if (size !== pin.bytes || hash6.digest("hex") !== pin.sha256) throw new CliError("HASH_MISMATCH", "Source archive verification failed.", "Do not extract this download.");
182541
+ await handle.sync();
182542
+ await handle.close();
182543
+ await checkedPath(root, out, false);
182544
+ await link2(temporary, target);
182545
+ } catch (error) {
182546
+ await reader.cancel().catch(() => {
182547
+ });
182548
+ throw error;
182549
+ } finally {
182550
+ await handle?.close().catch(() => {
182551
+ });
182552
+ await unlink2(temporary).catch(() => {
182553
+ });
182554
+ }
182555
+ return { ...kind === "style" ? { documents: metadata.documents } : {}, id: pin.id, version: pin.version, path: target, sha256: pin.sha256, bytes: size, extracted: false, executed: false, rendered: false, next: kind === "style" ? "Use editorbrain styles prepare with this exact version and archive to create a guarded local copy. Nothing has been extracted or executed." : "Inspect bundle README and selected card; extract into a new local directory. Bind current project colors, fonts, language, content, timing and sound before rendering. The demo is not your finished edit." };
182556
+ }
182557
+
182558
+ // packages/cli/src/style-archive.ts
182559
+ import { createHash as createHash2 } from "node:crypto";
182560
+ import { gunzipSync } from "node:zlib";
182561
+ var STYLE_ARCHIVE_MAX_BYTES = 128 * 1024 * 1024;
182562
+ var STYLE_UNPACKED_MAX_BYTES = 192 * 1024 * 1024;
182563
+ var archiveHash = (bytes) => createHash2("sha256").update(bytes).digest("hex");
182564
+ function safeArchivePath(name) {
182565
+ if (!name || name.length > 240 || !/^[a-zA-Z0-9_. /-]+$/.test(name) || name.startsWith("/") || name.split("/").some((p) => !p || p === "." || p === "..")) throw new Error("Unsafe archive path");
182566
+ return name;
182567
+ }
182568
+ function readStyleArchive(bytes, pin) {
182569
+ if (pin.bytes > STYLE_ARCHIVE_MAX_BYTES || pin.unpackedBytes > STYLE_UNPACKED_MAX_BYTES || bytes.length !== pin.bytes || archiveHash(bytes) !== pin.sha256) throw new Error("Style archive pin mismatch");
182570
+ const tar = gunzipSync(bytes, { maxOutputLength: STYLE_UNPACKED_MAX_BYTES + 2 * 1024 * 1024 });
182571
+ const files = /* @__PURE__ */ new Map();
182572
+ let offset = 0, total = 0, ended = false;
182573
+ const octal = (b) => {
182574
+ const s = b.toString("ascii").replace(/\0.*$/s, "").trim();
182575
+ if (!/^[0-7]+$/.test(s)) throw new Error("Invalid tar number");
182576
+ return parseInt(s, 8);
182577
+ };
182578
+ while (offset + 512 <= tar.length) {
182579
+ const h = tar.subarray(offset, offset + 512);
182580
+ offset += 512;
182581
+ if (h.every((b) => b === 0)) {
182582
+ if (tar.length - offset < 512 || tar.subarray(offset).some((b) => b !== 0)) throw new Error("Invalid tar ending");
182583
+ ended = true;
182584
+ break;
182585
+ }
182586
+ const sum = h.reduce((n, b, i) => n + (i >= 148 && i < 156 ? 32 : b), 0);
182587
+ if (sum !== octal(h.subarray(148, 156)) || h[156] !== 48 || h.subarray(157, 257).some((b) => b !== 0) || h.subarray(345, 500).some((b) => b !== 0)) throw new Error("Unsupported or corrupt tar entry");
182588
+ const name = safeArchivePath(h.subarray(0, 100).toString("utf8").replace(/\0.*$/s, ""));
182589
+ const size = octal(h.subarray(124, 136));
182590
+ if (files.has(name) || files.size >= 512 || offset + size > tar.length) throw new Error("Duplicate or truncated tar entry");
182591
+ total += size;
182592
+ if (total > pin.unpackedBytes) throw new Error("Archive exceeds unpacked pin");
182593
+ files.set(name, tar.subarray(offset, offset + size));
182594
+ offset += Math.ceil(size / 512) * 512;
182595
+ }
182596
+ if (!ended || files.size !== pin.fileCount || total !== pin.unpackedBytes || offset > tar.length) throw new Error("Archive inventory mismatch");
182597
+ const manifest = JSON.parse(files.get("BUNDLE-MANIFEST.json")?.toString("utf8") ?? "null");
182598
+ if (!manifest || manifest.style !== pin.id || manifest.version !== pin.version || manifest.entry !== `styles/${pin.id}/scene.html` || !manifest.files || Array.isArray(manifest.files)) throw new Error("Invalid style manifest");
182599
+ if (Object.keys(manifest.files).length !== files.size - 1) throw new Error("Incomplete style manifest");
182600
+ for (const [name, data] of files) {
182601
+ if (name === "BUNDLE-MANIFEST.json") continue;
182602
+ const expected = manifest.files[name];
182603
+ if (!expected || expected.bytes !== data.length || expected.sha256 !== archiveHash(data)) throw new Error("Manifest hash mismatch: " + name);
182604
+ }
182605
+ return { files, manifest };
182606
+ }
182607
+
182608
+ // packages/cli/src/style-source-guards-v1.ts
182609
+ var styleSourceGuards = {
182610
+ "comando-y-resultado": {
182611
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
182612
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
182613
+ "runtime": "// EditorBrain authored motion \xB7 scene runtime.\n// One canvas, explicit time: window.renderAt(seconds) draws the exact state for that time.\n// URL: ?ratio=wide|square|tall &theme=<kit> &t=<sec> &capture=1 &autoplay=1 &controls=0\n(function () {\n const RATIOS = { wide: [1920, 1080], square: [1080, 1080], tall: [1080, 1920] };\n const LIB_BASE = new URL('..', document.currentScript.src).href; // library root\n const q = new URLSearchParams(location.search);\n const capture = q.get('capture') === '1';\n\n const isObj = v => v && typeof v === 'object' && !Array.isArray(v);\n const merge = (a, b) => {\n if (!isObj(b)) return b === undefined ? a : b;\n const out = { ...(isObj(a) ? a : {}) };\n for (const k of Object.keys(b)) out[k] = merge(out[k], b[k]);\n return out;\n };\n\n function readParams() {\n const el = document.getElementById('params');\n let p = el ? JSON.parse(el.textContent) : {};\n if (window.__overrides) p = merge(p, window.__overrides);\n const enc = q.get('params');\n if (enc) { const supplied = JSON.parse(decodeURIComponent(escape(atob(enc)))); window.__overrides = merge(window.__overrides || {}, supplied); p = merge(p, supplied); }\n window.EB_VALIDATE_PARAMS(p, q);\n return p;\n }\n\n async function loadFonts(F, warn) {\n const families = new Set(Object.values(F).map(f => f.family));\n const status = {};\n for (const fam of families) {\n const defs = (window.EB_FONTS || {})[fam];\n if (!defs) {\n status[fam] = 'not-registered';\n warn(`font family not registered: ${fam}`);\n continue;\n }\n const results = await Promise.all(defs.map(async d => {\n const src = d.local ? d.local.map(n => `local(\"${n}\")`).join(', ') : `url(\"${new URL(d.src, LIB_BASE).href}\")`;\n const desc = {};\n if (d.weight) desc.weight = d.weight;\n if (d.style) desc.style = d.style;\n if (d.stretch) desc.stretch = d.stretch;\n try {\n const face = new FontFace(fam, src, desc);\n await face.load();\n document.fonts.add(face);\n return true;\n } catch (e) {\n return false;\n }\n }));\n const ok = results.filter(Boolean).length;\n status[fam] = ok === defs.length ? 'loaded' : ok ? `partial ${ok}/${defs.length}` : 'missing';\n if (!ok) warn(`font unavailable, renderer would fall back: ${fam}`);\n }\n return status;\n }\n\n function loadImage(src) {\n return new Promise((res, rej) => {\n const img = new Image();\n img.onload = () => res(img);\n img.onerror = () => rej(new Error('image failed: ' + src));\n img.src = src;\n });\n }\n\n function resolveTheme(params) {\n const kits = window.EB_THEMES || {};\n const id = q.get('theme') || params.theme || Object.keys(kits)[0];\n const kit = kits[id] || kits[Object.keys(kits)[0]];\n const brand = params.brand || {};\n const C = { ...kit.colors, ...(brand.colors || {}) };\n C.series = brand.series || kit.series;\n const F = {};\n for (const role of new Set(['display', 'text', 'heavy', 'mono', 'hand', ...Object.keys(brand.fonts || {})])) F[role] = { ...(kit.fonts[role] || kit.fonts.text), ...((brand.fonts || {})[role] || {}) };\n return { id, kit, C, F };\n }\n\n window.EB = {\n RATIOS,\n scene(def) {\n const warnings = new Set();\n const warn = m => { warnings.add(m); if (q.get(\"demo\") !== \"1\") throw new Error(m); };\n try {\n void boot(def, warn, warnings).catch(e => { window.__motionError = String(e && e.stack || e); console.error(window.__motionError); });\n } catch (e) {\n window.__motionError = String(e && e.stack || e);\n throw e;\n }\n },\n };\n\n async function boot(def, warn, warnings) {\n const P = readParams();\n const ratio = q.get('ratio') || P.ratio || 'wide';\n const [W, H] = RATIOS[ratio] || RATIOS.wide;\n const { id: themeId, C, F } = resolveTheme(P);\n const timeScale = P.timeScale || 1;\n const duration = (P.duration || def.duration || 10) * timeScale;\n const fps = P.fps || 30;\n\n document.documentElement.style.background = capture ? C.bg : '#0b0b0a';\n document.body.style.margin = '0';\n const canvas = document.createElement('canvas');\n canvas.id = 'stage';\n canvas.width = W;\n canvas.height = H;\n const ctx = canvas.getContext('2d');\n\n const S = {\n W, H, ratio, P, C, F, themeId, fps, duration, timeScale,\n u: Math.min(W, H) / 1080, // 1 unit = 1px at 1080 short side\n wide: ratio === 'wide', square: ratio === 'square', tall: ratio === 'tall',\n warn, lib: LIB_BASE, frame: 0, images: {}, beats: P.beats || {},\n };\n S.pick = (wide, square, tall) => (S.tall ? tall : S.square ? square : wide);\n\n const fontStatus = await loadFonts(F, warn);\n if (Object.values(fontStatus).some(value => value !== \"loaded\")) throw new Error(\"All registered font faces must load; fallback is not permitted.\");\n for (const [k, rel] of Object.entries(P.media || {})) {\n try { S.images[k] = await loadImage(new URL(rel, location.href).href); } catch (e) { warn(String(e.message)); }\n }\n if (def.setup) await def.setup(S, ctx);\n\n // Scenes with external frames (video clips) define `prepare(t, S)`; renderAt then returns a\n // promise that resolves after those frames are decoded, so captures stay frame-exact.\n function renderAt(t) {\n t = Math.max(0, Math.min(duration, t));\n if (def.prepare) {\n const token = (S._token = (S._token || 0) + 1);\n return Promise.resolve(def.prepare(t / timeScale, S)).then(() => (token === S._token ? paint(t) : false));\n }\n return paint(t);\n }\n function paint(t) {\n S.frame = Math.round(t * fps);\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.globalAlpha = 1;\n ctx.globalCompositeOperation = 'source-over';\n ctx.fillStyle = C.bg;\n ctx.fillRect(0, 0, W, H);\n def.draw(ctx, t / timeScale, S);\n return true;\n }\n\n const beatTime = v => (typeof v === 'number' ? v : (S.beats[v] ?? 0));\n // cues from params plus cues the scene derives from its own data (def.cues)\n const rawCues = P.sound?.enabled === false ? [] : [...((P.sound && P.sound.cues) || []), ...(def.cues ? def.cues(S) : [])];\n const cues = rawCues.map(c => ({\n t: +((beatTime(c.at) + (c.offset || 0)) * timeScale).toFixed(4),\n sfx: c.sfx, file: c.file, dur: c.dur, trim: c.trim, gain: c.gain ?? (c.file ? 0.3 : 1),\n })).sort((a, b) => a.t - b.t);\n\n window.renderAt = renderAt;\n window.__sceneMeta = { id: def.id, W, H, ratio, fps, duration, frames: Math.round(duration * fps), theme: themeId, cues, timeScale, music: P.sound?.enabled === false ? null : P.sound?.music || null, voice: P.sound?.enabled === false ? null : P.sound?.voice || null, loudness: P.sound?.enabled === false ? null : P.sound?.loudness || null };\n window.getDiagnostics = () => ({ fonts: fontStatus, warnings: [...warnings], meta: window.__sceneMeta });\n\n document.body.appendChild(canvas);\n if (capture) {\n canvas.style.cssText = 'display:block';\n await renderAt(+(q.get('t') || 0));\n window.__ready = true;\n return;\n }\n preview(canvas, renderAt, S, cues);\n window.__ready = true;\n }\n\n // ---------- interactive preview (never used for rendering) ----------\n function preview(canvas, renderAt, S, cues) {\n const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;\n const showControls = q.get('controls') !== '0';\n const style = document.createElement('style');\n style.textContent = `\n body{height:100vh;display:flex;flex-direction:column;font:13px/1.3 -apple-system,system-ui,sans-serif;color:#e9e4da;background:#0b0b0a}\n #wrap{flex:1;display:flex;align-items:center;justify-content:center;min-height:0;padding:${showControls ? '12px' : '0'}}\n #stage{max-width:100%;max-height:100%;width:auto;height:auto;box-shadow:0 10px 40px rgba(0,0,0,.45)}\n #bar{display:flex;gap:10px;align-items:center;padding:10px 14px;background:#151412;border-top:1px solid #2a2824;flex-wrap:wrap}\n #bar button,#bar select{background:#24221f;color:#e9e4da;border:1px solid #3a3732;border-radius:6px;padding:5px 9px;font:inherit;cursor:pointer}\n #bar button.on{background:#E89A4A;color:#1b1a18;border-color:#E89A4A}\n #bar input[type=range]{flex:1;min-width:160px;accent-color:#E89A4A}\n #tm{font-variant-numeric:tabular-nums;min-width:92px}`;\n document.head.appendChild(style);\n const wrap = document.createElement('div');\n wrap.id = 'wrap';\n document.body.appendChild(wrap);\n wrap.appendChild(canvas);\n\n let t = q.has('t') ? +q.get('t') : reduced ? (S.P.reducedHold ?? S.duration * 0.9) : 0;\n let playing = !reduced && q.get('autoplay') === '1';\n let last = null;\n let sound = q.get('sound') === '1';\n const audio = audioEngine(cues, S);\n\n let range, tm, playBtn, soundBtn;\n if (showControls) {\n const bar = document.createElement('div');\n bar.id = 'bar';\n bar.innerHTML = `<button id=\"pp\"></button><input id=\"rg\" type=\"range\" min=\"0\" max=\"${S.duration}\" step=\"${1 / S.fps}\"><span id=\"tm\"></span>\n <span>${['wide', 'square', 'tall'].map(r => `<button data-r=\"${r}\" class=\"${r === S.ratio ? 'on' : ''}\">${{ wide: '16:9', square: '1:1', tall: '9:16' }[r]}</button>`).join(' ')}</span>\n <select id=\"th\">${Object.entries(window.EB_THEMES).map(([k, v]) => `<option value=\"${k}\" ${k === S.themeId ? 'selected' : ''}>${v.label}</option>`).join('')}</select>\n <button id=\"snd\"></button>`;\n document.body.appendChild(bar);\n range = bar.querySelector('#rg');\n tm = bar.querySelector('#tm');\n playBtn = bar.querySelector('#pp');\n soundBtn = bar.querySelector('#snd');\n const go = (k, v) => { const u = new URL(location.href); u.searchParams.set(k, v); u.searchParams.delete('t'); location.href = u.href; };\n bar.querySelectorAll('[data-r]').forEach(b => b.onclick = () => go('ratio', b.dataset.r));\n bar.querySelector('#th').onchange = e => go('theme', e.target.value);\n playBtn.onclick = toggle;\n soundBtn.onclick = () => { sound = !sound; audio.stop(); if (sound && playing) audio.start(t); sync(); };\n range.oninput = () => { t = +range.value; audio.stop(); if (playing && sound) audio.start(t); draw(); };\n }\n addEventListener('keydown', e => { if (e.code === 'Space') { e.preventDefault(); toggle(); } });\n canvas.onclick = toggle;\n function toggle() {\n playing = !playing;\n if (playing && t >= S.duration - 0.01) t = 0;\n last = null;\n audio.stop();\n if (playing && sound) audio.start(t);\n sync();\n }\n function sync() {\n if (!showControls) return;\n playBtn.textContent = playing ? 'Pausa' : 'Reproducir';\n soundBtn.textContent = sound ? 'Sonido: s\xED' : 'Sonido: no';\n soundBtn.className = sound ? 'on' : '';\n soundBtn.disabled = !cues.length;\n if (!cues.length) soundBtn.textContent = 'Sin sonido';\n }\n function draw() {\n renderAt(t);\n if (showControls) {\n range.value = t;\n tm.textContent = `${t.toFixed(2)} / ${S.duration.toFixed(1)} s`;\n }\n }\n // Pause off-screen / hidden tabs.\n let visible = true;\n new IntersectionObserver(es => { visible = es[0].isIntersecting; }).observe(canvas);\n function loop(now) {\n if (playing && visible && !document.hidden) {\n if (last !== null) t += (now - last) / 1000;\n if (t >= S.duration) {\n t = q.get('loop') === '0' ? S.duration : 0;\n if (q.get('loop') === '0') playing = false;\n audio.stop();\n if (playing && sound) audio.start(t);\n }\n draw();\n }\n last = playing ? now : null;\n requestAnimationFrame(loop);\n }\n sync();\n draw();\n requestAnimationFrame(loop);\n }\n\n // Preview-only audio: schedules the scene's cues from the synthesized SFX bank.\n function audioEngine(cues, S) {\n let ac = null, nodes = [];\n const buffers = {};\n async function buf(name) {\n if (!buffers[name]) {\n const r = await fetch(new URL(`sfx/${name}.wav`, S.lib));\n buffers[name] = await ac.decodeAudioData(await r.arrayBuffer());\n }\n return buffers[name];\n }\n return {\n async start(from) {\n if (!cues.length) return;\n ac = ac || new AudioContext();\n const t0 = ac.currentTime + 0.05;\n for (const c of cues) {\n if (c.t < from - 0.02) continue;\n const b = await buf(c.sfx);\n const src = ac.createBufferSource(), g = ac.createGain();\n src.buffer = b;\n g.gain.value = c.gain;\n src.connect(g).connect(ac.destination);\n src.start(t0 + (c.t - from));\n nodes.push(src);\n }\n },\n stop() { nodes.forEach(n => { try { n.stop(); } catch (e) {} }); nodes = []; },\n };\n }\n})();\n",
182614
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
182615
+ (function () {
182616
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
182617
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
182618
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
182619
+ const fonts = ['display','text','heavy','mono','hand'];
182620
+ window.EB_VALIDATE_PARAMS = (p, q) => {
182621
+ const theme = q.get('theme') || p.theme;
182622
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
182623
+ const ratio = q.get('ratio') || p.ratio || 'wide';
182624
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
182625
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
182626
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
182627
+ }
182628
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
182629
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
182630
+ if (q.get('demo') === '1') return;
182631
+ const b = window.__overrides?.brand;
182632
+ if (!record(b) || !record(b.colors) || !record(b.fonts)) fail('provide complete window.__overrides.brand from the selected project; demo themes are not customer defaults');
182633
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
182634
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
182635
+ if (!Array.isArray(b.series) || b.series.length < 6 || b.series.some(c => !/^#[0-9a-f]{6}$/i.test(c))) fail('provide at least six explicit series hex colors; roles may repeat project colors but never inherit demo colors');
182636
+ for (const role of fonts) {
182637
+ const font = b.fonts[role];
182638
+ if (!record(font) || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) fail('provide explicit family, weight and style for font role ' + role);
182639
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
182640
+ }
182641
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
182642
+ };
182643
+ })();
182644
+
182645
+ (function () {
182646
+ const base = window.EB_VALIDATE_PARAMS;
182647
+ const roles = ["accent","accentInk","bg","cardEdge","chip","giftBox","giftLid","giftRibbon","giftShade","light","outline","panel","panelLine","thumbBg","uiText"];
182648
+ const fontRoles = ["credit","cta","headline","ui"];
182649
+ window.EB_VALIDATE_PARAMS = (params, query) => {
182650
+ base(params, query);
182651
+ if (query.get('demo') === '1') return;
182652
+ for (const role of roles) {
182653
+ if (!/^#[0-9a-f]{6}$/i.test(window.__overrides?.brand?.colors?.[role] || '')) throw new Error('EditorBrain project binding: provide scene-specific color role ' + role + '; never inherit demo/preset brand colors.');
182654
+ }
182655
+ for (const role of fontRoles) {
182656
+ const font = window.__overrides?.brand?.fonts?.[role];
182657
+ if (!font || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) throw new Error('EditorBrain project binding: provide complete scene-specific font role ' + role + '; never inherit demo/preset typography.');
182658
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
182659
+ }
182660
+ };
182661
+ })();
182662
+ `
182663
+ },
182664
+ "narrador-sobre-collage": {
182665
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
182666
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
182667
+ "runtime": "// EditorBrain authored motion \xB7 scene runtime.\n// One canvas, explicit time: window.renderAt(seconds) draws the exact state for that time.\n// URL: ?ratio=wide|square|tall &theme=<kit> &t=<sec> &capture=1 &autoplay=1 &controls=0\n(function () {\n const RATIOS = { wide: [1920, 1080], square: [1080, 1080], tall: [1080, 1920] };\n const LIB_BASE = new URL('..', document.currentScript.src).href; // library root\n const q = new URLSearchParams(location.search);\n const capture = q.get('capture') === '1';\n\n const isObj = v => v && typeof v === 'object' && !Array.isArray(v);\n const merge = (a, b) => {\n if (!isObj(b)) return b === undefined ? a : b;\n const out = { ...(isObj(a) ? a : {}) };\n for (const k of Object.keys(b)) out[k] = merge(out[k], b[k]);\n return out;\n };\n\n function readParams() {\n const el = document.getElementById('params');\n let p = el ? JSON.parse(el.textContent) : {};\n if (window.__overrides) p = merge(p, window.__overrides);\n const enc = q.get('params');\n if (enc) { const supplied = JSON.parse(decodeURIComponent(escape(atob(enc)))); window.__overrides = merge(window.__overrides || {}, supplied); p = merge(p, supplied); }\n window.EB_VALIDATE_PARAMS(p, q);\n return p;\n }\n\n async function loadFonts(F, warn) {\n const families = new Set(Object.values(F).map(f => f.family));\n const status = {};\n for (const fam of families) {\n const defs = (window.EB_FONTS || {})[fam];\n if (!defs) {\n status[fam] = 'not-registered';\n warn(`font family not registered: ${fam}`);\n continue;\n }\n const results = await Promise.all(defs.map(async d => {\n const src = d.local ? d.local.map(n => `local(\"${n}\")`).join(', ') : `url(\"${new URL(d.src, LIB_BASE).href}\")`;\n const desc = {};\n if (d.weight) desc.weight = d.weight;\n if (d.style) desc.style = d.style;\n if (d.stretch) desc.stretch = d.stretch;\n try {\n const face = new FontFace(fam, src, desc);\n await face.load();\n document.fonts.add(face);\n return true;\n } catch (e) {\n return false;\n }\n }));\n const ok = results.filter(Boolean).length;\n status[fam] = ok === defs.length ? 'loaded' : ok ? `partial ${ok}/${defs.length}` : 'missing';\n if (!ok) warn(`font unavailable, renderer would fall back: ${fam}`);\n }\n return status;\n }\n\n function loadImage(src) {\n return new Promise((res, rej) => {\n const img = new Image();\n img.onload = () => res(img);\n img.onerror = () => rej(new Error('image failed: ' + src));\n img.src = src;\n });\n }\n\n function resolveTheme(params) {\n const kits = window.EB_THEMES || {};\n const id = q.get('theme') || params.theme || Object.keys(kits)[0];\n const kit = kits[id] || kits[Object.keys(kits)[0]];\n const brand = params.brand || {};\n const C = { ...kit.colors, ...(brand.colors || {}) };\n C.series = brand.series || kit.series;\n const F = {};\n for (const role of new Set(['display', 'text', 'heavy', 'mono', 'hand', ...Object.keys(brand.fonts || {})])) F[role] = { ...(kit.fonts[role] || kit.fonts.text), ...((brand.fonts || {})[role] || {}) };\n return { id, kit, C, F };\n }\n\n window.EB = {\n RATIOS,\n scene(def) {\n const warnings = new Set();\n const warn = m => { warnings.add(m); if (q.get(\"demo\") !== \"1\") throw new Error(m); };\n try {\n void boot(def, warn, warnings).catch(e => { window.__motionError = String(e && e.stack || e); console.error(window.__motionError); });\n } catch (e) {\n window.__motionError = String(e && e.stack || e);\n throw e;\n }\n },\n };\n\n async function boot(def, warn, warnings) {\n const P = readParams();\n const ratio = q.get('ratio') || P.ratio || 'wide';\n const [W, H] = RATIOS[ratio] || RATIOS.wide;\n const { id: themeId, C, F } = resolveTheme(P);\n const timeScale = P.timeScale || 1;\n const duration = (P.duration || def.duration || 10) * timeScale;\n const fps = P.fps || 30;\n\n document.documentElement.style.background = capture ? C.bg : '#0b0b0a';\n document.body.style.margin = '0';\n const canvas = document.createElement('canvas');\n canvas.id = 'stage';\n canvas.width = W;\n canvas.height = H;\n const ctx = canvas.getContext('2d');\n\n const S = {\n W, H, ratio, P, C, F, themeId, fps, duration, timeScale,\n u: Math.min(W, H) / 1080, // 1 unit = 1px at 1080 short side\n wide: ratio === 'wide', square: ratio === 'square', tall: ratio === 'tall',\n warn, lib: LIB_BASE, frame: 0, images: {}, beats: P.beats || {},\n };\n S.pick = (wide, square, tall) => (S.tall ? tall : S.square ? square : wide);\n\n const fontStatus = await loadFonts(F, warn);\n if (Object.values(fontStatus).some(value => value !== \"loaded\")) throw new Error(\"All registered font faces must load; fallback is not permitted.\");\n for (const [k, rel] of Object.entries(P.media || {})) {\n try { S.images[k] = await loadImage(new URL(rel, location.href).href); } catch (e) { warn(String(e.message)); }\n }\n if (def.setup) await def.setup(S, ctx);\n\n // Scenes with external frames (video clips) define `prepare(t, S)`; renderAt then returns a\n // promise that resolves after those frames are decoded, so captures stay frame-exact.\n function renderAt(t) {\n t = Math.max(0, Math.min(duration, t));\n if (def.prepare) {\n const token = (S._token = (S._token || 0) + 1);\n return Promise.resolve(def.prepare(t / timeScale, S)).then(() => (token === S._token ? paint(t) : false));\n }\n return paint(t);\n }\n function paint(t) {\n S.frame = Math.round(t * fps);\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.globalAlpha = 1;\n ctx.globalCompositeOperation = 'source-over';\n ctx.fillStyle = C.bg;\n ctx.fillRect(0, 0, W, H);\n def.draw(ctx, t / timeScale, S);\n return true;\n }\n\n const beatTime = v => (typeof v === 'number' ? v : (S.beats[v] ?? 0));\n // cues from params plus cues the scene derives from its own data (def.cues)\n const rawCues = P.sound?.enabled === false ? [] : [...((P.sound && P.sound.cues) || []), ...(def.cues ? def.cues(S) : [])];\n const cues = rawCues.map(c => ({\n t: +((beatTime(c.at) + (c.offset || 0)) * timeScale).toFixed(4),\n sfx: c.sfx, file: c.file, dur: c.dur, trim: c.trim, gain: c.gain ?? (c.file ? 0.3 : 1),\n })).sort((a, b) => a.t - b.t);\n\n window.renderAt = renderAt;\n window.__sceneMeta = { id: def.id, W, H, ratio, fps, duration, frames: Math.round(duration * fps), theme: themeId, cues, timeScale, music: P.sound?.enabled === false ? null : P.sound?.music || null, voice: P.sound?.enabled === false ? null : P.sound?.voice || null, loudness: P.sound?.enabled === false ? null : P.sound?.loudness || null };\n window.getDiagnostics = () => ({ fonts: fontStatus, warnings: [...warnings], meta: window.__sceneMeta });\n\n document.body.appendChild(canvas);\n if (capture) {\n canvas.style.cssText = 'display:block';\n await renderAt(+(q.get('t') || 0));\n window.__ready = true;\n return;\n }\n preview(canvas, renderAt, S, cues);\n window.__ready = true;\n }\n\n // ---------- interactive preview (never used for rendering) ----------\n function preview(canvas, renderAt, S, cues) {\n const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;\n const showControls = q.get('controls') !== '0';\n const style = document.createElement('style');\n style.textContent = `\n body{height:100vh;display:flex;flex-direction:column;font:13px/1.3 -apple-system,system-ui,sans-serif;color:#e9e4da;background:#0b0b0a}\n #wrap{flex:1;display:flex;align-items:center;justify-content:center;min-height:0;padding:${showControls ? '12px' : '0'}}\n #stage{max-width:100%;max-height:100%;width:auto;height:auto;box-shadow:0 10px 40px rgba(0,0,0,.45)}\n #bar{display:flex;gap:10px;align-items:center;padding:10px 14px;background:#151412;border-top:1px solid #2a2824;flex-wrap:wrap}\n #bar button,#bar select{background:#24221f;color:#e9e4da;border:1px solid #3a3732;border-radius:6px;padding:5px 9px;font:inherit;cursor:pointer}\n #bar button.on{background:#E89A4A;color:#1b1a18;border-color:#E89A4A}\n #bar input[type=range]{flex:1;min-width:160px;accent-color:#E89A4A}\n #tm{font-variant-numeric:tabular-nums;min-width:92px}`;\n document.head.appendChild(style);\n const wrap = document.createElement('div');\n wrap.id = 'wrap';\n document.body.appendChild(wrap);\n wrap.appendChild(canvas);\n\n let t = q.has('t') ? +q.get('t') : reduced ? (S.P.reducedHold ?? S.duration * 0.9) : 0;\n let playing = !reduced && q.get('autoplay') === '1';\n let last = null;\n let sound = q.get('sound') === '1';\n const audio = audioEngine(cues, S);\n\n let range, tm, playBtn, soundBtn;\n if (showControls) {\n const bar = document.createElement('div');\n bar.id = 'bar';\n bar.innerHTML = `<button id=\"pp\"></button><input id=\"rg\" type=\"range\" min=\"0\" max=\"${S.duration}\" step=\"${1 / S.fps}\"><span id=\"tm\"></span>\n <span>${['wide', 'square', 'tall'].map(r => `<button data-r=\"${r}\" class=\"${r === S.ratio ? 'on' : ''}\">${{ wide: '16:9', square: '1:1', tall: '9:16' }[r]}</button>`).join(' ')}</span>\n <select id=\"th\">${Object.entries(window.EB_THEMES).map(([k, v]) => `<option value=\"${k}\" ${k === S.themeId ? 'selected' : ''}>${v.label}</option>`).join('')}</select>\n <button id=\"snd\"></button>`;\n document.body.appendChild(bar);\n range = bar.querySelector('#rg');\n tm = bar.querySelector('#tm');\n playBtn = bar.querySelector('#pp');\n soundBtn = bar.querySelector('#snd');\n const go = (k, v) => { const u = new URL(location.href); u.searchParams.set(k, v); u.searchParams.delete('t'); location.href = u.href; };\n bar.querySelectorAll('[data-r]').forEach(b => b.onclick = () => go('ratio', b.dataset.r));\n bar.querySelector('#th').onchange = e => go('theme', e.target.value);\n playBtn.onclick = toggle;\n soundBtn.onclick = () => { sound = !sound; audio.stop(); if (sound && playing) audio.start(t); sync(); };\n range.oninput = () => { t = +range.value; audio.stop(); if (playing && sound) audio.start(t); draw(); };\n }\n addEventListener('keydown', e => { if (e.code === 'Space') { e.preventDefault(); toggle(); } });\n canvas.onclick = toggle;\n function toggle() {\n playing = !playing;\n if (playing && t >= S.duration - 0.01) t = 0;\n last = null;\n audio.stop();\n if (playing && sound) audio.start(t);\n sync();\n }\n function sync() {\n if (!showControls) return;\n playBtn.textContent = playing ? 'Pausa' : 'Reproducir';\n soundBtn.textContent = sound ? 'Sonido: s\xED' : 'Sonido: no';\n soundBtn.className = sound ? 'on' : '';\n soundBtn.disabled = !cues.length;\n if (!cues.length) soundBtn.textContent = 'Sin sonido';\n }\n function draw() {\n renderAt(t);\n if (showControls) {\n range.value = t;\n tm.textContent = `${t.toFixed(2)} / ${S.duration.toFixed(1)} s`;\n }\n }\n // Pause off-screen / hidden tabs.\n let visible = true;\n new IntersectionObserver(es => { visible = es[0].isIntersecting; }).observe(canvas);\n function loop(now) {\n if (playing && visible && !document.hidden) {\n if (last !== null) t += (now - last) / 1000;\n if (t >= S.duration) {\n t = q.get('loop') === '0' ? S.duration : 0;\n if (q.get('loop') === '0') playing = false;\n audio.stop();\n if (playing && sound) audio.start(t);\n }\n draw();\n }\n last = playing ? now : null;\n requestAnimationFrame(loop);\n }\n sync();\n draw();\n requestAnimationFrame(loop);\n }\n\n // Preview-only audio: schedules the scene's cues from the synthesized SFX bank.\n function audioEngine(cues, S) {\n let ac = null, nodes = [];\n const buffers = {};\n async function buf(name) {\n if (!buffers[name]) {\n const r = await fetch(new URL(`sfx/${name}.wav`, S.lib));\n buffers[name] = await ac.decodeAudioData(await r.arrayBuffer());\n }\n return buffers[name];\n }\n return {\n async start(from) {\n if (!cues.length) return;\n ac = ac || new AudioContext();\n const t0 = ac.currentTime + 0.05;\n for (const c of cues) {\n if (c.t < from - 0.02) continue;\n const b = await buf(c.sfx);\n const src = ac.createBufferSource(), g = ac.createGain();\n src.buffer = b;\n g.gain.value = c.gain;\n src.connect(g).connect(ac.destination);\n src.start(t0 + (c.t - from));\n nodes.push(src);\n }\n },\n stop() { nodes.forEach(n => { try { n.stop(); } catch (e) {} }); nodes = []; },\n };\n }\n})();\n",
182668
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
182669
+ (function () {
182670
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
182671
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
182672
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
182673
+ const fonts = ['display','text','heavy','mono','hand'];
182674
+ window.EB_VALIDATE_PARAMS = (p, q) => {
182675
+ const theme = q.get('theme') || p.theme;
182676
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
182677
+ const ratio = q.get('ratio') || p.ratio || 'wide';
182678
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
182679
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
182680
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
182681
+ }
182682
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
182683
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
182684
+ if (q.get('demo') === '1') return;
182685
+ const b = window.__overrides?.brand;
182686
+ if (!record(b) || !record(b.colors) || !record(b.fonts)) fail('provide complete window.__overrides.brand from the selected project; demo themes are not customer defaults');
182687
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
182688
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
182689
+ if (!Array.isArray(b.series) || b.series.length < 6 || b.series.some(c => !/^#[0-9a-f]{6}$/i.test(c))) fail('provide at least six explicit series hex colors; roles may repeat project colors but never inherit demo colors');
182690
+ for (const role of fonts) {
182691
+ const font = b.fonts[role];
182692
+ if (!record(font) || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) fail('provide explicit family, weight and style for font role ' + role);
182693
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
182694
+ }
182695
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
182696
+ };
182697
+ })();
182698
+
182699
+ (function () {
182700
+ const base = window.EB_VALIDATE_PARAMS;
182701
+ const roles = ["accent","bg","labelBg","labelInk","light","outline"];
182702
+ const fontRoles = ["caption","credit","headline","label"];
182703
+ window.EB_VALIDATE_PARAMS = (params, query) => {
182704
+ base(params, query);
182705
+ if (query.get('demo') === '1') return;
182706
+ for (const role of roles) {
182707
+ if (!/^#[0-9a-f]{6}$/i.test(window.__overrides?.brand?.colors?.[role] || '')) throw new Error('EditorBrain project binding: provide scene-specific color role ' + role + '; never inherit demo/preset brand colors.');
182708
+ }
182709
+ for (const role of fontRoles) {
182710
+ const font = window.__overrides?.brand?.fonts?.[role];
182711
+ if (!font || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) throw new Error('EditorBrain project binding: provide complete scene-specific font role ' + role + '; never inherit demo/preset typography.');
182712
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
182713
+ }
182714
+ };
182715
+ })();
182716
+ `
182717
+ },
182718
+ "presentador-con-interfaz": {
182719
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
182720
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
182721
+ "runtime": "// EditorBrain authored motion \xB7 scene runtime.\n// One canvas, explicit time: window.renderAt(seconds) draws the exact state for that time.\n// URL: ?ratio=wide|square|tall &theme=<kit> &t=<sec> &capture=1 &autoplay=1 &controls=0\n(function () {\n const RATIOS = { wide: [1920, 1080], square: [1080, 1080], tall: [1080, 1920] };\n const LIB_BASE = new URL('..', document.currentScript.src).href; // library root\n const q = new URLSearchParams(location.search);\n const capture = q.get('capture') === '1';\n\n const isObj = v => v && typeof v === 'object' && !Array.isArray(v);\n const merge = (a, b) => {\n if (!isObj(b)) return b === undefined ? a : b;\n const out = { ...(isObj(a) ? a : {}) };\n for (const k of Object.keys(b)) out[k] = merge(out[k], b[k]);\n return out;\n };\n\n function readParams() {\n const el = document.getElementById('params');\n let p = el ? JSON.parse(el.textContent) : {};\n if (window.__overrides) p = merge(p, window.__overrides);\n const enc = q.get('params');\n if (enc) { const supplied = JSON.parse(decodeURIComponent(escape(atob(enc)))); window.__overrides = merge(window.__overrides || {}, supplied); p = merge(p, supplied); }\n window.EB_VALIDATE_PARAMS(p, q);\n return p;\n }\n\n async function loadFonts(F, warn) {\n const families = new Set(Object.values(F).map(f => f.family));\n const status = {};\n for (const fam of families) {\n const defs = (window.EB_FONTS || {})[fam];\n if (!defs) {\n status[fam] = 'not-registered';\n warn(`font family not registered: ${fam}`);\n continue;\n }\n const results = await Promise.all(defs.map(async d => {\n const src = d.local ? d.local.map(n => `local(\"${n}\")`).join(', ') : `url(\"${new URL(d.src, LIB_BASE).href}\")`;\n const desc = {};\n if (d.weight) desc.weight = d.weight;\n if (d.style) desc.style = d.style;\n if (d.stretch) desc.stretch = d.stretch;\n try {\n const face = new FontFace(fam, src, desc);\n await face.load();\n document.fonts.add(face);\n return true;\n } catch (e) {\n return false;\n }\n }));\n const ok = results.filter(Boolean).length;\n status[fam] = ok === defs.length ? 'loaded' : ok ? `partial ${ok}/${defs.length}` : 'missing';\n if (!ok) warn(`font unavailable, renderer would fall back: ${fam}`);\n }\n return status;\n }\n\n function loadImage(src) {\n return new Promise((res, rej) => {\n const img = new Image();\n img.onload = () => res(img);\n img.onerror = () => rej(new Error('image failed: ' + src));\n img.src = src;\n });\n }\n\n function resolveTheme(params) {\n const kits = window.EB_THEMES || {};\n const id = q.get('theme') || params.theme || Object.keys(kits)[0];\n const kit = kits[id] || kits[Object.keys(kits)[0]];\n const brand = params.brand || {};\n const C = { ...kit.colors, ...(brand.colors || {}) };\n C.series = brand.series || kit.series;\n const F = {};\n for (const role of new Set(['display', 'text', 'heavy', 'mono', 'hand', ...Object.keys(brand.fonts || {})])) F[role] = { ...(kit.fonts[role] || kit.fonts.text), ...((brand.fonts || {})[role] || {}) };\n return { id, kit, C, F };\n }\n\n window.EB = {\n RATIOS,\n scene(def) {\n const warnings = new Set();\n const warn = m => { warnings.add(m); if (q.get(\"demo\") !== \"1\") throw new Error(m); };\n try {\n void boot(def, warn, warnings).catch(e => { window.__motionError = String(e && e.stack || e); console.error(window.__motionError); });\n } catch (e) {\n window.__motionError = String(e && e.stack || e);\n throw e;\n }\n },\n };\n\n async function boot(def, warn, warnings) {\n const P = readParams();\n const ratio = q.get('ratio') || P.ratio || 'wide';\n const [W, H] = RATIOS[ratio] || RATIOS.wide;\n const { id: themeId, C, F } = resolveTheme(P);\n const timeScale = P.timeScale || 1;\n const duration = (P.duration || def.duration || 10) * timeScale;\n const fps = P.fps || 30;\n\n document.documentElement.style.background = capture ? C.bg : '#0b0b0a';\n document.body.style.margin = '0';\n const canvas = document.createElement('canvas');\n canvas.id = 'stage';\n canvas.width = W;\n canvas.height = H;\n const ctx = canvas.getContext('2d');\n\n const S = {\n W, H, ratio, P, C, F, themeId, fps, duration, timeScale,\n u: Math.min(W, H) / 1080, // 1 unit = 1px at 1080 short side\n wide: ratio === 'wide', square: ratio === 'square', tall: ratio === 'tall',\n warn, lib: LIB_BASE, frame: 0, images: {}, beats: P.beats || {},\n };\n S.pick = (wide, square, tall) => (S.tall ? tall : S.square ? square : wide);\n\n const fontStatus = await loadFonts(F, warn);\n if (Object.values(fontStatus).some(value => value !== \"loaded\")) throw new Error(\"All registered font faces must load; fallback is not permitted.\");\n for (const [k, rel] of Object.entries(P.media || {})) {\n try { S.images[k] = await loadImage(new URL(rel, location.href).href); } catch (e) { warn(String(e.message)); }\n }\n if (def.setup) await def.setup(S, ctx);\n\n // Scenes with external frames (video clips) define `prepare(t, S)`; renderAt then returns a\n // promise that resolves after those frames are decoded, so captures stay frame-exact.\n function renderAt(t) {\n t = Math.max(0, Math.min(duration, t));\n if (def.prepare) {\n const token = (S._token = (S._token || 0) + 1);\n return Promise.resolve(def.prepare(t / timeScale, S)).then(() => (token === S._token ? paint(t) : false));\n }\n return paint(t);\n }\n function paint(t) {\n S.frame = Math.round(t * fps);\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.globalAlpha = 1;\n ctx.globalCompositeOperation = 'source-over';\n ctx.fillStyle = C.bg;\n ctx.fillRect(0, 0, W, H);\n def.draw(ctx, t / timeScale, S);\n return true;\n }\n\n const beatTime = v => (typeof v === 'number' ? v : (S.beats[v] ?? 0));\n // cues from params plus cues the scene derives from its own data (def.cues)\n const rawCues = P.sound?.enabled === false ? [] : [...((P.sound && P.sound.cues) || []), ...(def.cues ? def.cues(S) : [])];\n const cues = rawCues.map(c => ({\n t: +((beatTime(c.at) + (c.offset || 0)) * timeScale).toFixed(4),\n sfx: c.sfx, file: c.file, dur: c.dur, trim: c.trim, gain: c.gain ?? (c.file ? 0.3 : 1),\n })).sort((a, b) => a.t - b.t);\n\n window.renderAt = renderAt;\n window.__sceneMeta = { id: def.id, W, H, ratio, fps, duration, frames: Math.round(duration * fps), theme: themeId, cues, timeScale, music: P.sound?.enabled === false ? null : P.sound?.music || null, voice: P.sound?.enabled === false ? null : P.sound?.voice || null, loudness: P.sound?.enabled === false ? null : P.sound?.loudness || null };\n window.getDiagnostics = () => ({ fonts: fontStatus, warnings: [...warnings], meta: window.__sceneMeta });\n\n document.body.appendChild(canvas);\n if (capture) {\n canvas.style.cssText = 'display:block';\n await renderAt(+(q.get('t') || 0));\n window.__ready = true;\n return;\n }\n preview(canvas, renderAt, S, cues);\n window.__ready = true;\n }\n\n // ---------- interactive preview (never used for rendering) ----------\n function preview(canvas, renderAt, S, cues) {\n const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;\n const showControls = q.get('controls') !== '0';\n const style = document.createElement('style');\n style.textContent = `\n body{height:100vh;display:flex;flex-direction:column;font:13px/1.3 -apple-system,system-ui,sans-serif;color:#e9e4da;background:#0b0b0a}\n #wrap{flex:1;display:flex;align-items:center;justify-content:center;min-height:0;padding:${showControls ? '12px' : '0'}}\n #stage{max-width:100%;max-height:100%;width:auto;height:auto;box-shadow:0 10px 40px rgba(0,0,0,.45)}\n #bar{display:flex;gap:10px;align-items:center;padding:10px 14px;background:#151412;border-top:1px solid #2a2824;flex-wrap:wrap}\n #bar button,#bar select{background:#24221f;color:#e9e4da;border:1px solid #3a3732;border-radius:6px;padding:5px 9px;font:inherit;cursor:pointer}\n #bar button.on{background:#E89A4A;color:#1b1a18;border-color:#E89A4A}\n #bar input[type=range]{flex:1;min-width:160px;accent-color:#E89A4A}\n #tm{font-variant-numeric:tabular-nums;min-width:92px}`;\n document.head.appendChild(style);\n const wrap = document.createElement('div');\n wrap.id = 'wrap';\n document.body.appendChild(wrap);\n wrap.appendChild(canvas);\n\n let t = q.has('t') ? +q.get('t') : reduced ? (S.P.reducedHold ?? S.duration * 0.9) : 0;\n let playing = !reduced && q.get('autoplay') === '1';\n let last = null;\n let sound = q.get('sound') === '1';\n const audio = audioEngine(cues, S);\n\n let range, tm, playBtn, soundBtn;\n if (showControls) {\n const bar = document.createElement('div');\n bar.id = 'bar';\n bar.innerHTML = `<button id=\"pp\"></button><input id=\"rg\" type=\"range\" min=\"0\" max=\"${S.duration}\" step=\"${1 / S.fps}\"><span id=\"tm\"></span>\n <span>${['wide', 'square', 'tall'].map(r => `<button data-r=\"${r}\" class=\"${r === S.ratio ? 'on' : ''}\">${{ wide: '16:9', square: '1:1', tall: '9:16' }[r]}</button>`).join(' ')}</span>\n <select id=\"th\">${Object.entries(window.EB_THEMES).map(([k, v]) => `<option value=\"${k}\" ${k === S.themeId ? 'selected' : ''}>${v.label}</option>`).join('')}</select>\n <button id=\"snd\"></button>`;\n document.body.appendChild(bar);\n range = bar.querySelector('#rg');\n tm = bar.querySelector('#tm');\n playBtn = bar.querySelector('#pp');\n soundBtn = bar.querySelector('#snd');\n const go = (k, v) => { const u = new URL(location.href); u.searchParams.set(k, v); u.searchParams.delete('t'); location.href = u.href; };\n bar.querySelectorAll('[data-r]').forEach(b => b.onclick = () => go('ratio', b.dataset.r));\n bar.querySelector('#th').onchange = e => go('theme', e.target.value);\n playBtn.onclick = toggle;\n soundBtn.onclick = () => { sound = !sound; audio.stop(); if (sound && playing) audio.start(t); sync(); };\n range.oninput = () => { t = +range.value; audio.stop(); if (playing && sound) audio.start(t); draw(); };\n }\n addEventListener('keydown', e => { if (e.code === 'Space') { e.preventDefault(); toggle(); } });\n canvas.onclick = toggle;\n function toggle() {\n playing = !playing;\n if (playing && t >= S.duration - 0.01) t = 0;\n last = null;\n audio.stop();\n if (playing && sound) audio.start(t);\n sync();\n }\n function sync() {\n if (!showControls) return;\n playBtn.textContent = playing ? 'Pausa' : 'Reproducir';\n soundBtn.textContent = sound ? 'Sonido: s\xED' : 'Sonido: no';\n soundBtn.className = sound ? 'on' : '';\n soundBtn.disabled = !cues.length;\n if (!cues.length) soundBtn.textContent = 'Sin sonido';\n }\n function draw() {\n renderAt(t);\n if (showControls) {\n range.value = t;\n tm.textContent = `${t.toFixed(2)} / ${S.duration.toFixed(1)} s`;\n }\n }\n // Pause off-screen / hidden tabs.\n let visible = true;\n new IntersectionObserver(es => { visible = es[0].isIntersecting; }).observe(canvas);\n function loop(now) {\n if (playing && visible && !document.hidden) {\n if (last !== null) t += (now - last) / 1000;\n if (t >= S.duration) {\n t = q.get('loop') === '0' ? S.duration : 0;\n if (q.get('loop') === '0') playing = false;\n audio.stop();\n if (playing && sound) audio.start(t);\n }\n draw();\n }\n last = playing ? now : null;\n requestAnimationFrame(loop);\n }\n sync();\n draw();\n requestAnimationFrame(loop);\n }\n\n // Preview-only audio: schedules the scene's cues from the synthesized SFX bank.\n function audioEngine(cues, S) {\n let ac = null, nodes = [];\n const buffers = {};\n async function buf(name) {\n if (!buffers[name]) {\n const r = await fetch(new URL(`sfx/${name}.wav`, S.lib));\n buffers[name] = await ac.decodeAudioData(await r.arrayBuffer());\n }\n return buffers[name];\n }\n return {\n async start(from) {\n if (!cues.length) return;\n ac = ac || new AudioContext();\n const t0 = ac.currentTime + 0.05;\n for (const c of cues) {\n if (c.t < from - 0.02) continue;\n const b = await buf(c.sfx);\n const src = ac.createBufferSource(), g = ac.createGain();\n src.buffer = b;\n g.gain.value = c.gain;\n src.connect(g).connect(ac.destination);\n src.start(t0 + (c.t - from));\n nodes.push(src);\n }\n },\n stop() { nodes.forEach(n => { try { n.stop(); } catch (e) {} }); nodes = []; },\n };\n }\n})();\n",
182722
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
182723
+ (function () {
182724
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
182725
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
182726
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
182727
+ const fonts = ['display','text','heavy','mono','hand'];
182728
+ window.EB_VALIDATE_PARAMS = (p, q) => {
182729
+ const theme = q.get('theme') || p.theme;
182730
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
182731
+ const ratio = q.get('ratio') || p.ratio || 'wide';
182732
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
182733
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
182734
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
182735
+ }
182736
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
182737
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
182738
+ if (q.get('demo') === '1') return;
182739
+ const b = window.__overrides?.brand;
182740
+ if (!record(b) || !record(b.colors) || !record(b.fonts)) fail('provide complete window.__overrides.brand from the selected project; demo themes are not customer defaults');
182741
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
182742
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
182743
+ if (!Array.isArray(b.series) || b.series.length < 6 || b.series.some(c => !/^#[0-9a-f]{6}$/i.test(c))) fail('provide at least six explicit series hex colors; roles may repeat project colors but never inherit demo colors');
182744
+ for (const role of fonts) {
182745
+ const font = b.fonts[role];
182746
+ if (!record(font) || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) fail('provide explicit family, weight and style for font role ' + role);
182747
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
182748
+ }
182749
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
182750
+ };
182751
+ })();
182752
+
182753
+ (function () {
182754
+ const base = window.EB_VALIDATE_PARAMS;
182755
+ const roles = ["accent","bg","dim","ink","keybox","line","muted","onAccent","pill","surface","surface2"];
182756
+ const fontRoles = ["caption","credit","figure","heading","keyword","label","mono","ui"];
182757
+ window.EB_VALIDATE_PARAMS = (params, query) => {
182758
+ base(params, query);
182759
+ if (query.get('demo') === '1') return;
182760
+ for (const role of roles) {
182761
+ if (!/^#[0-9a-f]{6}$/i.test(window.__overrides?.brand?.colors?.[role] || '')) throw new Error('EditorBrain project binding: provide scene-specific color role ' + role + '; never inherit demo/preset brand colors.');
182762
+ }
182763
+ for (const role of fontRoles) {
182764
+ const font = window.__overrides?.brand?.fonts?.[role];
182765
+ if (!font || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) throw new Error('EditorBrain project binding: provide complete scene-specific font role ' + role + '; never inherit demo/preset typography.');
182766
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
182767
+ }
182768
+ };
182769
+ })();
182770
+ `
182771
+ },
182772
+ "ensayo-cinematografico": {
182773
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
182774
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
182775
+ "runtime": "// EditorBrain authored motion \xB7 scene runtime.\n// One canvas, explicit time: window.renderAt(seconds) draws the exact state for that time.\n// URL: ?ratio=wide|square|tall &theme=<kit> &t=<sec> &capture=1 &autoplay=1 &controls=0\n(function () {\n const RATIOS = { wide: [1920, 1080], square: [1080, 1080], tall: [1080, 1920] };\n const LIB_BASE = new URL('..', document.currentScript.src).href; // library root\n const q = new URLSearchParams(location.search);\n const capture = q.get('capture') === '1';\n\n const isObj = v => v && typeof v === 'object' && !Array.isArray(v);\n const merge = (a, b) => {\n if (!isObj(b)) return b === undefined ? a : b;\n const out = { ...(isObj(a) ? a : {}) };\n for (const k of Object.keys(b)) out[k] = merge(out[k], b[k]);\n return out;\n };\n\n function readParams() {\n const el = document.getElementById('params');\n let p = el ? JSON.parse(el.textContent) : {};\n if (window.__overrides) p = merge(p, window.__overrides);\n const enc = q.get('params');\n if (enc) { const supplied = JSON.parse(decodeURIComponent(escape(atob(enc)))); window.__overrides = merge(window.__overrides || {}, supplied); p = merge(p, supplied); }\n window.EB_VALIDATE_PARAMS(p, q);\n return p;\n }\n\n async function loadFonts(F, warn) {\n const families = new Set(Object.values(F).map(f => f.family));\n const status = {};\n for (const fam of families) {\n const defs = (window.EB_FONTS || {})[fam];\n if (!defs) {\n status[fam] = 'not-registered';\n warn(`font family not registered: ${fam}`);\n continue;\n }\n const results = await Promise.all(defs.map(async d => {\n const src = d.local ? d.local.map(n => `local(\"${n}\")`).join(', ') : `url(\"${new URL(d.src, LIB_BASE).href}\")`;\n const desc = {};\n if (d.weight) desc.weight = d.weight;\n if (d.style) desc.style = d.style;\n if (d.stretch) desc.stretch = d.stretch;\n try {\n const face = new FontFace(fam, src, desc);\n await face.load();\n document.fonts.add(face);\n return true;\n } catch (e) {\n return false;\n }\n }));\n const ok = results.filter(Boolean).length;\n status[fam] = ok === defs.length ? 'loaded' : ok ? `partial ${ok}/${defs.length}` : 'missing';\n if (!ok) warn(`font unavailable, renderer would fall back: ${fam}`);\n }\n return status;\n }\n\n function loadImage(src) {\n return new Promise((res, rej) => {\n const img = new Image();\n img.onload = () => res(img);\n img.onerror = () => rej(new Error('image failed: ' + src));\n img.src = src;\n });\n }\n\n function resolveTheme(params) {\n const kits = window.EB_THEMES || {};\n const id = q.get('theme') || params.theme || Object.keys(kits)[0];\n const kit = kits[id] || kits[Object.keys(kits)[0]];\n const brand = params.brand || {};\n const C = { ...kit.colors, ...(brand.colors || {}) };\n C.series = brand.series || kit.series;\n const F = {};\n for (const role of new Set(['display', 'text', 'heavy', 'mono', 'hand', ...Object.keys(brand.fonts || {})])) F[role] = { ...(kit.fonts[role] || kit.fonts.text), ...((brand.fonts || {})[role] || {}) };\n return { id, kit, C, F };\n }\n\n window.EB = {\n RATIOS,\n scene(def) {\n const warnings = new Set();\n const warn = m => { warnings.add(m); if (q.get(\"demo\") !== \"1\") throw new Error(m); };\n try {\n void boot(def, warn, warnings).catch(e => { window.__motionError = String(e && e.stack || e); console.error(window.__motionError); });\n } catch (e) {\n window.__motionError = String(e && e.stack || e);\n throw e;\n }\n },\n };\n\n async function boot(def, warn, warnings) {\n const P = readParams();\n const ratio = q.get('ratio') || P.ratio || 'wide';\n const [W, H] = RATIOS[ratio] || RATIOS.wide;\n const { id: themeId, C, F } = resolveTheme(P);\n const timeScale = P.timeScale || 1;\n const duration = (P.duration || def.duration || 10) * timeScale;\n const fps = P.fps || 30;\n\n document.documentElement.style.background = capture ? C.bg : '#0b0b0a';\n document.body.style.margin = '0';\n const canvas = document.createElement('canvas');\n canvas.id = 'stage';\n canvas.width = W;\n canvas.height = H;\n const ctx = canvas.getContext('2d');\n\n const S = {\n W, H, ratio, P, C, F, themeId, fps, duration, timeScale,\n u: Math.min(W, H) / 1080, // 1 unit = 1px at 1080 short side\n wide: ratio === 'wide', square: ratio === 'square', tall: ratio === 'tall',\n warn, lib: LIB_BASE, frame: 0, images: {}, beats: P.beats || {},\n };\n S.pick = (wide, square, tall) => (S.tall ? tall : S.square ? square : wide);\n\n const fontStatus = await loadFonts(F, warn);\n if (Object.values(fontStatus).some(value => value !== \"loaded\")) throw new Error(\"All registered font faces must load; fallback is not permitted.\");\n for (const [k, rel] of Object.entries(P.media || {})) {\n try { S.images[k] = await loadImage(new URL(rel, location.href).href); } catch (e) { warn(String(e.message)); }\n }\n if (def.setup) await def.setup(S, ctx);\n\n // Scenes with external frames (video clips) define `prepare(t, S)`; renderAt then returns a\n // promise that resolves after those frames are decoded, so captures stay frame-exact.\n function renderAt(t) {\n t = Math.max(0, Math.min(duration, t));\n if (def.prepare) {\n const token = (S._token = (S._token || 0) + 1);\n return Promise.resolve(def.prepare(t / timeScale, S)).then(() => (token === S._token ? paint(t) : false));\n }\n return paint(t);\n }\n function paint(t) {\n S.frame = Math.round(t * fps);\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.globalAlpha = 1;\n ctx.globalCompositeOperation = 'source-over';\n ctx.fillStyle = C.bg;\n ctx.fillRect(0, 0, W, H);\n def.draw(ctx, t / timeScale, S);\n return true;\n }\n\n const beatTime = v => (typeof v === 'number' ? v : (S.beats[v] ?? 0));\n // cues from params plus cues the scene derives from its own data (def.cues)\n const rawCues = P.sound?.enabled === false ? [] : [...((P.sound && P.sound.cues) || []), ...(def.cues ? def.cues(S) : [])];\n const cues = rawCues.map(c => ({\n t: +((beatTime(c.at) + (c.offset || 0)) * timeScale).toFixed(4),\n sfx: c.sfx, file: c.file, dur: c.dur, trim: c.trim, gain: c.gain ?? (c.file ? 0.3 : 1),\n })).sort((a, b) => a.t - b.t);\n\n window.renderAt = renderAt;\n window.__sceneMeta = { id: def.id, W, H, ratio, fps, duration, frames: Math.round(duration * fps), theme: themeId, cues, timeScale, music: P.sound?.enabled === false ? null : P.sound?.music || null, voice: P.sound?.enabled === false ? null : P.sound?.voice || null, loudness: P.sound?.enabled === false ? null : P.sound?.loudness || null };\n window.getDiagnostics = () => ({ fonts: fontStatus, warnings: [...warnings], meta: window.__sceneMeta });\n\n document.body.appendChild(canvas);\n if (capture) {\n canvas.style.cssText = 'display:block';\n await renderAt(+(q.get('t') || 0));\n window.__ready = true;\n return;\n }\n preview(canvas, renderAt, S, cues);\n window.__ready = true;\n }\n\n // ---------- interactive preview (never used for rendering) ----------\n function preview(canvas, renderAt, S, cues) {\n const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;\n const showControls = q.get('controls') !== '0';\n const style = document.createElement('style');\n style.textContent = `\n body{height:100vh;display:flex;flex-direction:column;font:13px/1.3 -apple-system,system-ui,sans-serif;color:#e9e4da;background:#0b0b0a}\n #wrap{flex:1;display:flex;align-items:center;justify-content:center;min-height:0;padding:${showControls ? '12px' : '0'}}\n #stage{max-width:100%;max-height:100%;width:auto;height:auto;box-shadow:0 10px 40px rgba(0,0,0,.45)}\n #bar{display:flex;gap:10px;align-items:center;padding:10px 14px;background:#151412;border-top:1px solid #2a2824;flex-wrap:wrap}\n #bar button,#bar select{background:#24221f;color:#e9e4da;border:1px solid #3a3732;border-radius:6px;padding:5px 9px;font:inherit;cursor:pointer}\n #bar button.on{background:#E89A4A;color:#1b1a18;border-color:#E89A4A}\n #bar input[type=range]{flex:1;min-width:160px;accent-color:#E89A4A}\n #tm{font-variant-numeric:tabular-nums;min-width:92px}`;\n document.head.appendChild(style);\n const wrap = document.createElement('div');\n wrap.id = 'wrap';\n document.body.appendChild(wrap);\n wrap.appendChild(canvas);\n\n let t = q.has('t') ? +q.get('t') : reduced ? (S.P.reducedHold ?? S.duration * 0.9) : 0;\n let playing = !reduced && q.get('autoplay') === '1';\n let last = null;\n let sound = q.get('sound') === '1';\n const audio = audioEngine(cues, S);\n\n let range, tm, playBtn, soundBtn;\n if (showControls) {\n const bar = document.createElement('div');\n bar.id = 'bar';\n bar.innerHTML = `<button id=\"pp\"></button><input id=\"rg\" type=\"range\" min=\"0\" max=\"${S.duration}\" step=\"${1 / S.fps}\"><span id=\"tm\"></span>\n <span>${['wide', 'square', 'tall'].map(r => `<button data-r=\"${r}\" class=\"${r === S.ratio ? 'on' : ''}\">${{ wide: '16:9', square: '1:1', tall: '9:16' }[r]}</button>`).join(' ')}</span>\n <select id=\"th\">${Object.entries(window.EB_THEMES).map(([k, v]) => `<option value=\"${k}\" ${k === S.themeId ? 'selected' : ''}>${v.label}</option>`).join('')}</select>\n <button id=\"snd\"></button>`;\n document.body.appendChild(bar);\n range = bar.querySelector('#rg');\n tm = bar.querySelector('#tm');\n playBtn = bar.querySelector('#pp');\n soundBtn = bar.querySelector('#snd');\n const go = (k, v) => { const u = new URL(location.href); u.searchParams.set(k, v); u.searchParams.delete('t'); location.href = u.href; };\n bar.querySelectorAll('[data-r]').forEach(b => b.onclick = () => go('ratio', b.dataset.r));\n bar.querySelector('#th').onchange = e => go('theme', e.target.value);\n playBtn.onclick = toggle;\n soundBtn.onclick = () => { sound = !sound; audio.stop(); if (sound && playing) audio.start(t); sync(); };\n range.oninput = () => { t = +range.value; audio.stop(); if (playing && sound) audio.start(t); draw(); };\n }\n addEventListener('keydown', e => { if (e.code === 'Space') { e.preventDefault(); toggle(); } });\n canvas.onclick = toggle;\n function toggle() {\n playing = !playing;\n if (playing && t >= S.duration - 0.01) t = 0;\n last = null;\n audio.stop();\n if (playing && sound) audio.start(t);\n sync();\n }\n function sync() {\n if (!showControls) return;\n playBtn.textContent = playing ? 'Pausa' : 'Reproducir';\n soundBtn.textContent = sound ? 'Sonido: s\xED' : 'Sonido: no';\n soundBtn.className = sound ? 'on' : '';\n soundBtn.disabled = !cues.length;\n if (!cues.length) soundBtn.textContent = 'Sin sonido';\n }\n function draw() {\n renderAt(t);\n if (showControls) {\n range.value = t;\n tm.textContent = `${t.toFixed(2)} / ${S.duration.toFixed(1)} s`;\n }\n }\n // Pause off-screen / hidden tabs.\n let visible = true;\n new IntersectionObserver(es => { visible = es[0].isIntersecting; }).observe(canvas);\n function loop(now) {\n if (playing && visible && !document.hidden) {\n if (last !== null) t += (now - last) / 1000;\n if (t >= S.duration) {\n t = q.get('loop') === '0' ? S.duration : 0;\n if (q.get('loop') === '0') playing = false;\n audio.stop();\n if (playing && sound) audio.start(t);\n }\n draw();\n }\n last = playing ? now : null;\n requestAnimationFrame(loop);\n }\n sync();\n draw();\n requestAnimationFrame(loop);\n }\n\n // Preview-only audio: schedules the scene's cues from the synthesized SFX bank.\n function audioEngine(cues, S) {\n let ac = null, nodes = [];\n const buffers = {};\n async function buf(name) {\n if (!buffers[name]) {\n const r = await fetch(new URL(`sfx/${name}.wav`, S.lib));\n buffers[name] = await ac.decodeAudioData(await r.arrayBuffer());\n }\n return buffers[name];\n }\n return {\n async start(from) {\n if (!cues.length) return;\n ac = ac || new AudioContext();\n const t0 = ac.currentTime + 0.05;\n for (const c of cues) {\n if (c.t < from - 0.02) continue;\n const b = await buf(c.sfx);\n const src = ac.createBufferSource(), g = ac.createGain();\n src.buffer = b;\n g.gain.value = c.gain;\n src.connect(g).connect(ac.destination);\n src.start(t0 + (c.t - from));\n nodes.push(src);\n }\n },\n stop() { nodes.forEach(n => { try { n.stop(); } catch (e) {} }); nodes = []; },\n };\n }\n})();\n",
182776
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
182777
+ (function () {
182778
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
182779
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
182780
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
182781
+ const fonts = ['display','text','heavy','mono','hand'];
182782
+ window.EB_VALIDATE_PARAMS = (p, q) => {
182783
+ const theme = q.get('theme') || p.theme;
182784
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
182785
+ const ratio = q.get('ratio') || p.ratio || 'wide';
182786
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
182787
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
182788
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
182789
+ }
182790
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
182791
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
182792
+ if (q.get('demo') === '1') return;
182793
+ const b = window.__overrides?.brand;
182794
+ if (!record(b) || !record(b.colors) || !record(b.fonts)) fail('provide complete window.__overrides.brand from the selected project; demo themes are not customer defaults');
182795
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
182796
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
182797
+ if (!Array.isArray(b.series) || b.series.length < 6 || b.series.some(c => !/^#[0-9a-f]{6}$/i.test(c))) fail('provide at least six explicit series hex colors; roles may repeat project colors but never inherit demo colors');
182798
+ for (const role of fonts) {
182799
+ const font = b.fonts[role];
182800
+ if (!record(font) || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) fail('provide explicit family, weight and style for font role ' + role);
182801
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
182802
+ }
182803
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
182804
+ };
182805
+ })();
182806
+
182807
+ (function () {
182808
+ const base = window.EB_VALIDATE_PARAMS;
182809
+ const roles = ["accent","accent2","bg","cardDark","cardLight","inkOnDark","inkOnLight","light","outline","shadow"];
182810
+ const fontRoles = ["caption","credit","heavy","serif"];
182811
+ window.EB_VALIDATE_PARAMS = (params, query) => {
182812
+ base(params, query);
182813
+ if (query.get('demo') === '1') return;
182814
+ for (const role of roles) {
182815
+ if (!/^#[0-9a-f]{6}$/i.test(window.__overrides?.brand?.colors?.[role] || '')) throw new Error('EditorBrain project binding: provide scene-specific color role ' + role + '; never inherit demo/preset brand colors.');
182816
+ }
182817
+ for (const role of fontRoles) {
182818
+ const font = window.__overrides?.brand?.fonts?.[role];
182819
+ if (!font || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) throw new Error('EditorBrain project binding: provide complete scene-specific font role ' + role + '; never inherit demo/preset typography.');
182820
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
182821
+ }
182822
+ };
182823
+ })();
182824
+ `
182825
+ },
182826
+ "tutorial-por-capitulos": {
182827
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
182828
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
182829
+ "runtime": "// EditorBrain authored motion \xB7 scene runtime.\n// One canvas, explicit time: window.renderAt(seconds) draws the exact state for that time.\n// URL: ?ratio=wide|square|tall &theme=<kit> &t=<sec> &capture=1 &autoplay=1 &controls=0\n(function () {\n const RATIOS = { wide: [1920, 1080], square: [1080, 1080], tall: [1080, 1920] };\n const LIB_BASE = new URL('..', document.currentScript.src).href; // library root\n const q = new URLSearchParams(location.search);\n const capture = q.get('capture') === '1';\n\n const isObj = v => v && typeof v === 'object' && !Array.isArray(v);\n const merge = (a, b) => {\n if (!isObj(b)) return b === undefined ? a : b;\n const out = { ...(isObj(a) ? a : {}) };\n for (const k of Object.keys(b)) out[k] = merge(out[k], b[k]);\n return out;\n };\n\n function readParams() {\n const el = document.getElementById('params');\n let p = el ? JSON.parse(el.textContent) : {};\n if (window.__overrides) p = merge(p, window.__overrides);\n const enc = q.get('params');\n if (enc) { const supplied = JSON.parse(decodeURIComponent(escape(atob(enc)))); window.__overrides = merge(window.__overrides || {}, supplied); p = merge(p, supplied); }\n window.EB_VALIDATE_PARAMS(p, q);\n return p;\n }\n\n async function loadFonts(F, warn) {\n const families = new Set(Object.values(F).map(f => f.family));\n const status = {};\n for (const fam of families) {\n const defs = (window.EB_FONTS || {})[fam];\n if (!defs) {\n status[fam] = 'not-registered';\n warn(`font family not registered: ${fam}`);\n continue;\n }\n const results = await Promise.all(defs.map(async d => {\n const src = d.local ? d.local.map(n => `local(\"${n}\")`).join(', ') : `url(\"${new URL(d.src, LIB_BASE).href}\")`;\n const desc = {};\n if (d.weight) desc.weight = d.weight;\n if (d.style) desc.style = d.style;\n if (d.stretch) desc.stretch = d.stretch;\n try {\n const face = new FontFace(fam, src, desc);\n await face.load();\n document.fonts.add(face);\n return true;\n } catch (e) {\n return false;\n }\n }));\n const ok = results.filter(Boolean).length;\n status[fam] = ok === defs.length ? 'loaded' : ok ? `partial ${ok}/${defs.length}` : 'missing';\n if (!ok) warn(`font unavailable, renderer would fall back: ${fam}`);\n }\n return status;\n }\n\n function loadImage(src) {\n return new Promise((res, rej) => {\n const img = new Image();\n img.onload = () => res(img);\n img.onerror = () => rej(new Error('image failed: ' + src));\n img.src = src;\n });\n }\n\n function resolveTheme(params) {\n const kits = window.EB_THEMES || {};\n const id = q.get('theme') || params.theme || Object.keys(kits)[0];\n const kit = kits[id] || kits[Object.keys(kits)[0]];\n const brand = params.brand || {};\n const C = { ...kit.colors, ...(brand.colors || {}) };\n C.series = brand.series || kit.series;\n const F = {};\n for (const role of new Set(['display', 'text', 'heavy', 'mono', 'hand', ...Object.keys(brand.fonts || {})])) F[role] = { ...(kit.fonts[role] || kit.fonts.text), ...((brand.fonts || {})[role] || {}) };\n return { id, kit, C, F };\n }\n\n window.EB = {\n RATIOS,\n scene(def) {\n const warnings = new Set();\n const warn = m => { warnings.add(m); if (q.get(\"demo\") !== \"1\") throw new Error(m); };\n try {\n void boot(def, warn, warnings).catch(e => { window.__motionError = String(e && e.stack || e); console.error(window.__motionError); });\n } catch (e) {\n window.__motionError = String(e && e.stack || e);\n throw e;\n }\n },\n };\n\n async function boot(def, warn, warnings) {\n const P = readParams();\n const ratio = q.get('ratio') || P.ratio || 'wide';\n const [W, H] = RATIOS[ratio] || RATIOS.wide;\n const { id: themeId, C, F } = resolveTheme(P);\n const timeScale = P.timeScale || 1;\n const duration = (P.duration || def.duration || 10) * timeScale;\n const fps = P.fps || 30;\n\n document.documentElement.style.background = capture ? C.bg : '#0b0b0a';\n document.body.style.margin = '0';\n const canvas = document.createElement('canvas');\n canvas.id = 'stage';\n canvas.width = W;\n canvas.height = H;\n const ctx = canvas.getContext('2d');\n\n const S = {\n W, H, ratio, P, C, F, themeId, fps, duration, timeScale,\n u: Math.min(W, H) / 1080, // 1 unit = 1px at 1080 short side\n wide: ratio === 'wide', square: ratio === 'square', tall: ratio === 'tall',\n warn, lib: LIB_BASE, frame: 0, images: {}, beats: P.beats || {},\n };\n S.pick = (wide, square, tall) => (S.tall ? tall : S.square ? square : wide);\n\n const fontStatus = await loadFonts(F, warn);\n if (Object.values(fontStatus).some(value => value !== \"loaded\")) throw new Error(\"All registered font faces must load; fallback is not permitted.\");\n for (const [k, rel] of Object.entries(P.media || {})) {\n try { S.images[k] = await loadImage(new URL(rel, location.href).href); } catch (e) { warn(String(e.message)); }\n }\n if (def.setup) await def.setup(S, ctx);\n\n // Scenes with external frames (video clips) define `prepare(t, S)`; renderAt then returns a\n // promise that resolves after those frames are decoded, so captures stay frame-exact.\n function renderAt(t) {\n t = Math.max(0, Math.min(duration, t));\n if (def.prepare) {\n const token = (S._token = (S._token || 0) + 1);\n return Promise.resolve(def.prepare(t / timeScale, S)).then(() => (token === S._token ? paint(t) : false));\n }\n return paint(t);\n }\n function paint(t) {\n S.frame = Math.round(t * fps);\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.globalAlpha = 1;\n ctx.globalCompositeOperation = 'source-over';\n ctx.fillStyle = C.bg;\n ctx.fillRect(0, 0, W, H);\n def.draw(ctx, t / timeScale, S);\n return true;\n }\n\n const beatTime = v => (typeof v === 'number' ? v : (S.beats[v] ?? 0));\n // cues from params plus cues the scene derives from its own data (def.cues)\n const rawCues = P.sound?.enabled === false ? [] : [...((P.sound && P.sound.cues) || []), ...(def.cues ? def.cues(S) : [])];\n const cues = rawCues.map(c => ({\n t: +((beatTime(c.at) + (c.offset || 0)) * timeScale).toFixed(4),\n sfx: c.sfx, file: c.file, dur: c.dur, trim: c.trim, gain: c.gain ?? (c.file ? 0.3 : 1),\n })).sort((a, b) => a.t - b.t);\n\n window.renderAt = renderAt;\n window.__sceneMeta = { id: def.id, W, H, ratio, fps, duration, frames: Math.round(duration * fps), theme: themeId, cues, timeScale, music: P.sound?.enabled === false ? null : P.sound?.music || null, voice: P.sound?.enabled === false ? null : P.sound?.voice || null, loudness: P.sound?.enabled === false ? null : P.sound?.loudness || null };\n window.getDiagnostics = () => ({ fonts: fontStatus, warnings: [...warnings], meta: window.__sceneMeta });\n\n document.body.appendChild(canvas);\n if (capture) {\n canvas.style.cssText = 'display:block';\n await renderAt(+(q.get('t') || 0));\n window.__ready = true;\n return;\n }\n preview(canvas, renderAt, S, cues);\n window.__ready = true;\n }\n\n // ---------- interactive preview (never used for rendering) ----------\n function preview(canvas, renderAt, S, cues) {\n const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;\n const showControls = q.get('controls') !== '0';\n const style = document.createElement('style');\n style.textContent = `\n body{height:100vh;display:flex;flex-direction:column;font:13px/1.3 -apple-system,system-ui,sans-serif;color:#e9e4da;background:#0b0b0a}\n #wrap{flex:1;display:flex;align-items:center;justify-content:center;min-height:0;padding:${showControls ? '12px' : '0'}}\n #stage{max-width:100%;max-height:100%;width:auto;height:auto;box-shadow:0 10px 40px rgba(0,0,0,.45)}\n #bar{display:flex;gap:10px;align-items:center;padding:10px 14px;background:#151412;border-top:1px solid #2a2824;flex-wrap:wrap}\n #bar button,#bar select{background:#24221f;color:#e9e4da;border:1px solid #3a3732;border-radius:6px;padding:5px 9px;font:inherit;cursor:pointer}\n #bar button.on{background:#E89A4A;color:#1b1a18;border-color:#E89A4A}\n #bar input[type=range]{flex:1;min-width:160px;accent-color:#E89A4A}\n #tm{font-variant-numeric:tabular-nums;min-width:92px}`;\n document.head.appendChild(style);\n const wrap = document.createElement('div');\n wrap.id = 'wrap';\n document.body.appendChild(wrap);\n wrap.appendChild(canvas);\n\n let t = q.has('t') ? +q.get('t') : reduced ? (S.P.reducedHold ?? S.duration * 0.9) : 0;\n let playing = !reduced && q.get('autoplay') === '1';\n let last = null;\n let sound = q.get('sound') === '1';\n const audio = audioEngine(cues, S);\n\n let range, tm, playBtn, soundBtn;\n if (showControls) {\n const bar = document.createElement('div');\n bar.id = 'bar';\n bar.innerHTML = `<button id=\"pp\"></button><input id=\"rg\" type=\"range\" min=\"0\" max=\"${S.duration}\" step=\"${1 / S.fps}\"><span id=\"tm\"></span>\n <span>${['wide', 'square', 'tall'].map(r => `<button data-r=\"${r}\" class=\"${r === S.ratio ? 'on' : ''}\">${{ wide: '16:9', square: '1:1', tall: '9:16' }[r]}</button>`).join(' ')}</span>\n <select id=\"th\">${Object.entries(window.EB_THEMES).map(([k, v]) => `<option value=\"${k}\" ${k === S.themeId ? 'selected' : ''}>${v.label}</option>`).join('')}</select>\n <button id=\"snd\"></button>`;\n document.body.appendChild(bar);\n range = bar.querySelector('#rg');\n tm = bar.querySelector('#tm');\n playBtn = bar.querySelector('#pp');\n soundBtn = bar.querySelector('#snd');\n const go = (k, v) => { const u = new URL(location.href); u.searchParams.set(k, v); u.searchParams.delete('t'); location.href = u.href; };\n bar.querySelectorAll('[data-r]').forEach(b => b.onclick = () => go('ratio', b.dataset.r));\n bar.querySelector('#th').onchange = e => go('theme', e.target.value);\n playBtn.onclick = toggle;\n soundBtn.onclick = () => { sound = !sound; audio.stop(); if (sound && playing) audio.start(t); sync(); };\n range.oninput = () => { t = +range.value; audio.stop(); if (playing && sound) audio.start(t); draw(); };\n }\n addEventListener('keydown', e => { if (e.code === 'Space') { e.preventDefault(); toggle(); } });\n canvas.onclick = toggle;\n function toggle() {\n playing = !playing;\n if (playing && t >= S.duration - 0.01) t = 0;\n last = null;\n audio.stop();\n if (playing && sound) audio.start(t);\n sync();\n }\n function sync() {\n if (!showControls) return;\n playBtn.textContent = playing ? 'Pausa' : 'Reproducir';\n soundBtn.textContent = sound ? 'Sonido: s\xED' : 'Sonido: no';\n soundBtn.className = sound ? 'on' : '';\n soundBtn.disabled = !cues.length;\n if (!cues.length) soundBtn.textContent = 'Sin sonido';\n }\n function draw() {\n renderAt(t);\n if (showControls) {\n range.value = t;\n tm.textContent = `${t.toFixed(2)} / ${S.duration.toFixed(1)} s`;\n }\n }\n // Pause off-screen / hidden tabs.\n let visible = true;\n new IntersectionObserver(es => { visible = es[0].isIntersecting; }).observe(canvas);\n function loop(now) {\n if (playing && visible && !document.hidden) {\n if (last !== null) t += (now - last) / 1000;\n if (t >= S.duration) {\n t = q.get('loop') === '0' ? S.duration : 0;\n if (q.get('loop') === '0') playing = false;\n audio.stop();\n if (playing && sound) audio.start(t);\n }\n draw();\n }\n last = playing ? now : null;\n requestAnimationFrame(loop);\n }\n sync();\n draw();\n requestAnimationFrame(loop);\n }\n\n // Preview-only audio: schedules the scene's cues from the synthesized SFX bank.\n function audioEngine(cues, S) {\n let ac = null, nodes = [];\n const buffers = {};\n async function buf(name) {\n if (!buffers[name]) {\n const r = await fetch(new URL(`sfx/${name}.wav`, S.lib));\n buffers[name] = await ac.decodeAudioData(await r.arrayBuffer());\n }\n return buffers[name];\n }\n return {\n async start(from) {\n if (!cues.length) return;\n ac = ac || new AudioContext();\n const t0 = ac.currentTime + 0.05;\n for (const c of cues) {\n if (c.t < from - 0.02) continue;\n const b = await buf(c.sfx);\n const src = ac.createBufferSource(), g = ac.createGain();\n src.buffer = b;\n g.gain.value = c.gain;\n src.connect(g).connect(ac.destination);\n src.start(t0 + (c.t - from));\n nodes.push(src);\n }\n },\n stop() { nodes.forEach(n => { try { n.stop(); } catch (e) {} }); nodes = []; },\n };\n }\n})();\n",
182830
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
182831
+ (function () {
182832
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
182833
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
182834
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
182835
+ const fonts = ['display','text','heavy','mono','hand'];
182836
+ window.EB_VALIDATE_PARAMS = (p, q) => {
182837
+ const theme = q.get('theme') || p.theme;
182838
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
182839
+ const ratio = q.get('ratio') || p.ratio || 'wide';
182840
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
182841
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
182842
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
182843
+ }
182844
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
182845
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
182846
+ if (q.get('demo') === '1') return;
182847
+ const b = window.__overrides?.brand;
182848
+ if (!record(b) || !record(b.colors) || !record(b.fonts)) fail('provide complete window.__overrides.brand from the selected project; demo themes are not customer defaults');
182849
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
182850
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
182851
+ if (!Array.isArray(b.series) || b.series.length < 6 || b.series.some(c => !/^#[0-9a-f]{6}$/i.test(c))) fail('provide at least six explicit series hex colors; roles may repeat project colors but never inherit demo colors');
182852
+ for (const role of fonts) {
182853
+ const font = b.fonts[role];
182854
+ if (!record(font) || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) fail('provide explicit family, weight and style for font role ' + role);
182855
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
182856
+ }
182857
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
182858
+ };
182859
+ })();
182860
+
182861
+ (function () {
182862
+ const base = window.EB_VALIDATE_PARAMS;
182863
+ const roles = ["alarm","badge","badgeShadow","badgeText","bg","caption","card","cream","heart","heartCore","lime","limeDeep","numeral","paper","title","uiBubble","uiField","uiInk","uiLine","uiMark","uiMuted","uiSend"];
182864
+ const fontRoles = ["caption","credit","greeting","heavy","italic","script","ui","uiSerif"];
182865
+ window.EB_VALIDATE_PARAMS = (params, query) => {
182866
+ base(params, query);
182867
+ if (query.get('demo') === '1') return;
182868
+ for (const role of roles) {
182869
+ if (!/^#[0-9a-f]{6}$/i.test(window.__overrides?.brand?.colors?.[role] || '')) throw new Error('EditorBrain project binding: provide scene-specific color role ' + role + '; never inherit demo/preset brand colors.');
182870
+ }
182871
+ for (const role of fontRoles) {
182872
+ const font = window.__overrides?.brand?.fonts?.[role];
182873
+ if (!font || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) throw new Error('EditorBrain project binding: provide complete scene-specific font role ' + role + '; never inherit demo/preset typography.');
182874
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
182875
+ }
182876
+ };
182877
+ })();
182878
+ `
182879
+ },
182880
+ "tablero-que-se-llena": {
182881
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
182882
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
182883
+ "runtime": "// EditorBrain authored motion \xB7 scene runtime.\n// One canvas, explicit time: window.renderAt(seconds) draws the exact state for that time.\n// URL: ?ratio=wide|square|tall &theme=<kit> &t=<sec> &capture=1 &autoplay=1 &controls=0\n(function () {\n const RATIOS = { wide: [1920, 1080], square: [1080, 1080], tall: [1080, 1920] };\n const LIB_BASE = new URL('..', document.currentScript.src).href; // library root\n const q = new URLSearchParams(location.search);\n const capture = q.get('capture') === '1';\n\n const isObj = v => v && typeof v === 'object' && !Array.isArray(v);\n const merge = (a, b) => {\n if (!isObj(b)) return b === undefined ? a : b;\n const out = { ...(isObj(a) ? a : {}) };\n for (const k of Object.keys(b)) out[k] = merge(out[k], b[k]);\n return out;\n };\n\n function readParams() {\n const el = document.getElementById('params');\n let p = el ? JSON.parse(el.textContent) : {};\n if (window.__overrides) p = merge(p, window.__overrides);\n const enc = q.get('params');\n if (enc) { const supplied = JSON.parse(decodeURIComponent(escape(atob(enc)))); window.__overrides = merge(window.__overrides || {}, supplied); p = merge(p, supplied); }\n window.EB_VALIDATE_PARAMS(p, q);\n return p;\n }\n\n async function loadFonts(F, warn) {\n const families = new Set(Object.values(F).map(f => f.family));\n const status = {};\n for (const fam of families) {\n const defs = (window.EB_FONTS || {})[fam];\n if (!defs) {\n status[fam] = 'not-registered';\n warn(`font family not registered: ${fam}`);\n continue;\n }\n const results = await Promise.all(defs.map(async d => {\n const src = d.local ? d.local.map(n => `local(\"${n}\")`).join(', ') : `url(\"${new URL(d.src, LIB_BASE).href}\")`;\n const desc = {};\n if (d.weight) desc.weight = d.weight;\n if (d.style) desc.style = d.style;\n if (d.stretch) desc.stretch = d.stretch;\n try {\n const face = new FontFace(fam, src, desc);\n await face.load();\n document.fonts.add(face);\n return true;\n } catch (e) {\n return false;\n }\n }));\n const ok = results.filter(Boolean).length;\n status[fam] = ok === defs.length ? 'loaded' : ok ? `partial ${ok}/${defs.length}` : 'missing';\n if (!ok) warn(`font unavailable, renderer would fall back: ${fam}`);\n }\n return status;\n }\n\n function loadImage(src) {\n return new Promise((res, rej) => {\n const img = new Image();\n img.onload = () => res(img);\n img.onerror = () => rej(new Error('image failed: ' + src));\n img.src = src;\n });\n }\n\n function resolveTheme(params) {\n const kits = window.EB_THEMES || {};\n const id = q.get('theme') || params.theme || Object.keys(kits)[0];\n const kit = kits[id] || kits[Object.keys(kits)[0]];\n const brand = params.brand || {};\n const C = { ...kit.colors, ...(brand.colors || {}) };\n C.series = brand.series || kit.series;\n const F = {};\n for (const role of new Set(['display', 'text', 'heavy', 'mono', 'hand', ...Object.keys(brand.fonts || {})])) F[role] = { ...(kit.fonts[role] || kit.fonts.text), ...((brand.fonts || {})[role] || {}) };\n return { id, kit, C, F };\n }\n\n window.EB = {\n RATIOS,\n scene(def) {\n const warnings = new Set();\n const warn = m => { warnings.add(m); if (q.get(\"demo\") !== \"1\") throw new Error(m); };\n try {\n void boot(def, warn, warnings).catch(e => { window.__motionError = String(e && e.stack || e); console.error(window.__motionError); });\n } catch (e) {\n window.__motionError = String(e && e.stack || e);\n throw e;\n }\n },\n };\n\n async function boot(def, warn, warnings) {\n const P = readParams();\n const ratio = q.get('ratio') || P.ratio || 'wide';\n const [W, H] = RATIOS[ratio] || RATIOS.wide;\n const { id: themeId, C, F } = resolveTheme(P);\n const timeScale = P.timeScale || 1;\n const duration = (P.duration || def.duration || 10) * timeScale;\n const fps = P.fps || 30;\n\n document.documentElement.style.background = capture ? C.bg : '#0b0b0a';\n document.body.style.margin = '0';\n const canvas = document.createElement('canvas');\n canvas.id = 'stage';\n canvas.width = W;\n canvas.height = H;\n const ctx = canvas.getContext('2d');\n\n const S = {\n W, H, ratio, P, C, F, themeId, fps, duration, timeScale,\n u: Math.min(W, H) / 1080, // 1 unit = 1px at 1080 short side\n wide: ratio === 'wide', square: ratio === 'square', tall: ratio === 'tall',\n warn, lib: LIB_BASE, frame: 0, images: {}, beats: P.beats || {},\n };\n S.pick = (wide, square, tall) => (S.tall ? tall : S.square ? square : wide);\n\n const fontStatus = await loadFonts(F, warn);\n if (Object.values(fontStatus).some(value => value !== \"loaded\")) throw new Error(\"All registered font faces must load; fallback is not permitted.\");\n for (const [k, rel] of Object.entries(P.media || {})) {\n try { S.images[k] = await loadImage(new URL(rel, location.href).href); } catch (e) { warn(String(e.message)); }\n }\n if (def.setup) await def.setup(S, ctx);\n\n // Scenes with external frames (video clips) define `prepare(t, S)`; renderAt then returns a\n // promise that resolves after those frames are decoded, so captures stay frame-exact.\n function renderAt(t) {\n t = Math.max(0, Math.min(duration, t));\n if (def.prepare) {\n const token = (S._token = (S._token || 0) + 1);\n return Promise.resolve(def.prepare(t / timeScale, S)).then(() => (token === S._token ? paint(t) : false));\n }\n return paint(t);\n }\n function paint(t) {\n S.frame = Math.round(t * fps);\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.globalAlpha = 1;\n ctx.globalCompositeOperation = 'source-over';\n ctx.fillStyle = C.bg;\n ctx.fillRect(0, 0, W, H);\n def.draw(ctx, t / timeScale, S);\n return true;\n }\n\n const beatTime = v => (typeof v === 'number' ? v : (S.beats[v] ?? 0));\n // cues from params plus cues the scene derives from its own data (def.cues)\n const rawCues = P.sound?.enabled === false ? [] : [...((P.sound && P.sound.cues) || []), ...(def.cues ? def.cues(S) : [])];\n const cues = rawCues.map(c => ({\n t: +((beatTime(c.at) + (c.offset || 0)) * timeScale).toFixed(4),\n sfx: c.sfx, file: c.file, dur: c.dur, trim: c.trim, gain: c.gain ?? (c.file ? 0.3 : 1),\n })).sort((a, b) => a.t - b.t);\n\n window.renderAt = renderAt;\n window.__sceneMeta = { id: def.id, W, H, ratio, fps, duration, frames: Math.round(duration * fps), theme: themeId, cues, timeScale, music: P.sound?.enabled === false ? null : P.sound?.music || null, voice: P.sound?.enabled === false ? null : P.sound?.voice || null, loudness: P.sound?.enabled === false ? null : P.sound?.loudness || null };\n window.getDiagnostics = () => ({ fonts: fontStatus, warnings: [...warnings], meta: window.__sceneMeta });\n\n document.body.appendChild(canvas);\n if (capture) {\n canvas.style.cssText = 'display:block';\n await renderAt(+(q.get('t') || 0));\n window.__ready = true;\n return;\n }\n preview(canvas, renderAt, S, cues);\n window.__ready = true;\n }\n\n // ---------- interactive preview (never used for rendering) ----------\n function preview(canvas, renderAt, S, cues) {\n const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;\n const showControls = q.get('controls') !== '0';\n const style = document.createElement('style');\n style.textContent = `\n body{height:100vh;display:flex;flex-direction:column;font:13px/1.3 -apple-system,system-ui,sans-serif;color:#e9e4da;background:#0b0b0a}\n #wrap{flex:1;display:flex;align-items:center;justify-content:center;min-height:0;padding:${showControls ? '12px' : '0'}}\n #stage{max-width:100%;max-height:100%;width:auto;height:auto;box-shadow:0 10px 40px rgba(0,0,0,.45)}\n #bar{display:flex;gap:10px;align-items:center;padding:10px 14px;background:#151412;border-top:1px solid #2a2824;flex-wrap:wrap}\n #bar button,#bar select{background:#24221f;color:#e9e4da;border:1px solid #3a3732;border-radius:6px;padding:5px 9px;font:inherit;cursor:pointer}\n #bar button.on{background:#E89A4A;color:#1b1a18;border-color:#E89A4A}\n #bar input[type=range]{flex:1;min-width:160px;accent-color:#E89A4A}\n #tm{font-variant-numeric:tabular-nums;min-width:92px}`;\n document.head.appendChild(style);\n const wrap = document.createElement('div');\n wrap.id = 'wrap';\n document.body.appendChild(wrap);\n wrap.appendChild(canvas);\n\n let t = q.has('t') ? +q.get('t') : reduced ? (S.P.reducedHold ?? S.duration * 0.9) : 0;\n let playing = !reduced && q.get('autoplay') === '1';\n let last = null;\n let sound = q.get('sound') === '1';\n const audio = audioEngine(cues, S);\n\n let range, tm, playBtn, soundBtn;\n if (showControls) {\n const bar = document.createElement('div');\n bar.id = 'bar';\n bar.innerHTML = `<button id=\"pp\"></button><input id=\"rg\" type=\"range\" min=\"0\" max=\"${S.duration}\" step=\"${1 / S.fps}\"><span id=\"tm\"></span>\n <span>${['wide', 'square', 'tall'].map(r => `<button data-r=\"${r}\" class=\"${r === S.ratio ? 'on' : ''}\">${{ wide: '16:9', square: '1:1', tall: '9:16' }[r]}</button>`).join(' ')}</span>\n <select id=\"th\">${Object.entries(window.EB_THEMES).map(([k, v]) => `<option value=\"${k}\" ${k === S.themeId ? 'selected' : ''}>${v.label}</option>`).join('')}</select>\n <button id=\"snd\"></button>`;\n document.body.appendChild(bar);\n range = bar.querySelector('#rg');\n tm = bar.querySelector('#tm');\n playBtn = bar.querySelector('#pp');\n soundBtn = bar.querySelector('#snd');\n const go = (k, v) => { const u = new URL(location.href); u.searchParams.set(k, v); u.searchParams.delete('t'); location.href = u.href; };\n bar.querySelectorAll('[data-r]').forEach(b => b.onclick = () => go('ratio', b.dataset.r));\n bar.querySelector('#th').onchange = e => go('theme', e.target.value);\n playBtn.onclick = toggle;\n soundBtn.onclick = () => { sound = !sound; audio.stop(); if (sound && playing) audio.start(t); sync(); };\n range.oninput = () => { t = +range.value; audio.stop(); if (playing && sound) audio.start(t); draw(); };\n }\n addEventListener('keydown', e => { if (e.code === 'Space') { e.preventDefault(); toggle(); } });\n canvas.onclick = toggle;\n function toggle() {\n playing = !playing;\n if (playing && t >= S.duration - 0.01) t = 0;\n last = null;\n audio.stop();\n if (playing && sound) audio.start(t);\n sync();\n }\n function sync() {\n if (!showControls) return;\n playBtn.textContent = playing ? 'Pausa' : 'Reproducir';\n soundBtn.textContent = sound ? 'Sonido: s\xED' : 'Sonido: no';\n soundBtn.className = sound ? 'on' : '';\n soundBtn.disabled = !cues.length;\n if (!cues.length) soundBtn.textContent = 'Sin sonido';\n }\n function draw() {\n renderAt(t);\n if (showControls) {\n range.value = t;\n tm.textContent = `${t.toFixed(2)} / ${S.duration.toFixed(1)} s`;\n }\n }\n // Pause off-screen / hidden tabs.\n let visible = true;\n new IntersectionObserver(es => { visible = es[0].isIntersecting; }).observe(canvas);\n function loop(now) {\n if (playing && visible && !document.hidden) {\n if (last !== null) t += (now - last) / 1000;\n if (t >= S.duration) {\n t = q.get('loop') === '0' ? S.duration : 0;\n if (q.get('loop') === '0') playing = false;\n audio.stop();\n if (playing && sound) audio.start(t);\n }\n draw();\n }\n last = playing ? now : null;\n requestAnimationFrame(loop);\n }\n sync();\n draw();\n requestAnimationFrame(loop);\n }\n\n // Preview-only audio: schedules the scene's cues from the synthesized SFX bank.\n function audioEngine(cues, S) {\n let ac = null, nodes = [];\n const buffers = {};\n async function buf(name) {\n if (!buffers[name]) {\n const r = await fetch(new URL(`sfx/${name}.wav`, S.lib));\n buffers[name] = await ac.decodeAudioData(await r.arrayBuffer());\n }\n return buffers[name];\n }\n return {\n async start(from) {\n if (!cues.length) return;\n ac = ac || new AudioContext();\n const t0 = ac.currentTime + 0.05;\n for (const c of cues) {\n if (c.t < from - 0.02) continue;\n const b = await buf(c.sfx);\n const src = ac.createBufferSource(), g = ac.createGain();\n src.buffer = b;\n g.gain.value = c.gain;\n src.connect(g).connect(ac.destination);\n src.start(t0 + (c.t - from));\n nodes.push(src);\n }\n },\n stop() { nodes.forEach(n => { try { n.stop(); } catch (e) {} }); nodes = []; },\n };\n }\n})();\n",
182884
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
182885
+ (function () {
182886
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
182887
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
182888
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
182889
+ const fonts = ['display','text','heavy','mono','hand'];
182890
+ window.EB_VALIDATE_PARAMS = (p, q) => {
182891
+ const theme = q.get('theme') || p.theme;
182892
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
182893
+ const ratio = q.get('ratio') || p.ratio || 'wide';
182894
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
182895
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
182896
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
182897
+ }
182898
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
182899
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
182900
+ if (q.get('demo') === '1') return;
182901
+ const b = window.__overrides?.brand;
182902
+ if (!record(b) || !record(b.colors) || !record(b.fonts)) fail('provide complete window.__overrides.brand from the selected project; demo themes are not customer defaults');
182903
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
182904
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
182905
+ if (!Array.isArray(b.series) || b.series.length < 6 || b.series.some(c => !/^#[0-9a-f]{6}$/i.test(c))) fail('provide at least six explicit series hex colors; roles may repeat project colors but never inherit demo colors');
182906
+ for (const role of fonts) {
182907
+ const font = b.fonts[role];
182908
+ if (!record(font) || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) fail('provide explicit family, weight and style for font role ' + role);
182909
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
182910
+ }
182911
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
182912
+ };
182913
+ })();
182914
+
182915
+ (function () {
182916
+ const base = window.EB_VALIDATE_PARAMS;
182917
+ const roles = ["bg","callout","cell","credit","labelGap","panel","seam","tierInk","tile","title"];
182918
+ const fontRoles = ["callout","credit","tier","title"];
182919
+ window.EB_VALIDATE_PARAMS = (params, query) => {
182920
+ base(params, query);
182921
+ if (query.get('demo') === '1') return;
182922
+ for (const role of roles) {
182923
+ if (!/^#[0-9a-f]{6}$/i.test(window.__overrides?.brand?.colors?.[role] || '')) throw new Error('EditorBrain project binding: provide scene-specific color role ' + role + '; never inherit demo/preset brand colors.');
182924
+ }
182925
+ for (const role of fontRoles) {
182926
+ const font = window.__overrides?.brand?.fonts?.[role];
182927
+ if (!font || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) throw new Error('EditorBrain project binding: provide complete scene-specific font role ' + role + '; never inherit demo/preset typography.');
182928
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
182929
+ }
182930
+ };
182931
+ })();
182932
+ `
182933
+ },
182934
+ "explicador-con-evidencias": {
182935
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
182936
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
182937
+ "runtime": "// EditorBrain authored motion \xB7 scene runtime.\n// One canvas, explicit time: window.renderAt(seconds) draws the exact state for that time.\n// URL: ?ratio=wide|square|tall &theme=<kit> &t=<sec> &capture=1 &autoplay=1 &controls=0\n(function () {\n const RATIOS = { wide: [1920, 1080], square: [1080, 1080], tall: [1080, 1920] };\n const LIB_BASE = new URL('..', document.currentScript.src).href; // library root\n const q = new URLSearchParams(location.search);\n const capture = q.get('capture') === '1';\n\n const isObj = v => v && typeof v === 'object' && !Array.isArray(v);\n const merge = (a, b) => {\n if (!isObj(b)) return b === undefined ? a : b;\n const out = { ...(isObj(a) ? a : {}) };\n for (const k of Object.keys(b)) out[k] = merge(out[k], b[k]);\n return out;\n };\n\n function readParams() {\n const el = document.getElementById('params');\n let p = el ? JSON.parse(el.textContent) : {};\n if (window.__overrides) p = merge(p, window.__overrides);\n const enc = q.get('params');\n if (enc) { const supplied = JSON.parse(decodeURIComponent(escape(atob(enc)))); window.__overrides = merge(window.__overrides || {}, supplied); p = merge(p, supplied); }\n window.EB_VALIDATE_PARAMS(p, q);\n return p;\n }\n\n async function loadFonts(F, warn) {\n const families = new Set(Object.values(F).map(f => f.family));\n const status = {};\n for (const fam of families) {\n const defs = (window.EB_FONTS || {})[fam];\n if (!defs) {\n status[fam] = 'not-registered';\n warn(`font family not registered: ${fam}`);\n continue;\n }\n const results = await Promise.all(defs.map(async d => {\n const src = d.local ? d.local.map(n => `local(\"${n}\")`).join(', ') : `url(\"${new URL(d.src, LIB_BASE).href}\")`;\n const desc = {};\n if (d.weight) desc.weight = d.weight;\n if (d.style) desc.style = d.style;\n if (d.stretch) desc.stretch = d.stretch;\n try {\n const face = new FontFace(fam, src, desc);\n await face.load();\n document.fonts.add(face);\n return true;\n } catch (e) {\n return false;\n }\n }));\n const ok = results.filter(Boolean).length;\n status[fam] = ok === defs.length ? 'loaded' : ok ? `partial ${ok}/${defs.length}` : 'missing';\n if (!ok) warn(`font unavailable, renderer would fall back: ${fam}`);\n }\n return status;\n }\n\n function loadImage(src) {\n return new Promise((res, rej) => {\n const img = new Image();\n img.onload = () => res(img);\n img.onerror = () => rej(new Error('image failed: ' + src));\n img.src = src;\n });\n }\n\n function resolveTheme(params) {\n const kits = window.EB_THEMES || {};\n const id = q.get('theme') || params.theme || Object.keys(kits)[0];\n const kit = kits[id] || kits[Object.keys(kits)[0]];\n const brand = params.brand || {};\n const C = { ...kit.colors, ...(brand.colors || {}) };\n C.series = brand.series || kit.series;\n const F = {};\n for (const role of new Set(['display', 'text', 'heavy', 'mono', 'hand', ...Object.keys(brand.fonts || {})])) F[role] = { ...(kit.fonts[role] || kit.fonts.text), ...((brand.fonts || {})[role] || {}) };\n return { id, kit, C, F };\n }\n\n window.EB = {\n RATIOS,\n scene(def) {\n const warnings = new Set();\n const warn = m => { warnings.add(m); if (q.get(\"demo\") !== \"1\") throw new Error(m); };\n try {\n void boot(def, warn, warnings).catch(e => { window.__motionError = String(e && e.stack || e); console.error(window.__motionError); });\n } catch (e) {\n window.__motionError = String(e && e.stack || e);\n throw e;\n }\n },\n };\n\n async function boot(def, warn, warnings) {\n const P = readParams();\n const ratio = q.get('ratio') || P.ratio || 'wide';\n const [W, H] = RATIOS[ratio] || RATIOS.wide;\n const { id: themeId, C, F } = resolveTheme(P);\n const timeScale = P.timeScale || 1;\n const duration = (P.duration || def.duration || 10) * timeScale;\n const fps = P.fps || 30;\n\n document.documentElement.style.background = capture ? C.bg : '#0b0b0a';\n document.body.style.margin = '0';\n const canvas = document.createElement('canvas');\n canvas.id = 'stage';\n canvas.width = W;\n canvas.height = H;\n const ctx = canvas.getContext('2d');\n\n const S = {\n W, H, ratio, P, C, F, themeId, fps, duration, timeScale,\n u: Math.min(W, H) / 1080, // 1 unit = 1px at 1080 short side\n wide: ratio === 'wide', square: ratio === 'square', tall: ratio === 'tall',\n warn, lib: LIB_BASE, frame: 0, images: {}, beats: P.beats || {},\n };\n S.pick = (wide, square, tall) => (S.tall ? tall : S.square ? square : wide);\n\n const fontStatus = await loadFonts(F, warn);\n if (Object.values(fontStatus).some(value => value !== \"loaded\")) throw new Error(\"All registered font faces must load; fallback is not permitted.\");\n for (const [k, rel] of Object.entries(P.media || {})) {\n try { S.images[k] = await loadImage(new URL(rel, location.href).href); } catch (e) { warn(String(e.message)); }\n }\n if (def.setup) await def.setup(S, ctx);\n\n // Scenes with external frames (video clips) define `prepare(t, S)`; renderAt then returns a\n // promise that resolves after those frames are decoded, so captures stay frame-exact.\n function renderAt(t) {\n t = Math.max(0, Math.min(duration, t));\n if (def.prepare) {\n const token = (S._token = (S._token || 0) + 1);\n return Promise.resolve(def.prepare(t / timeScale, S)).then(() => (token === S._token ? paint(t) : false));\n }\n return paint(t);\n }\n function paint(t) {\n S.frame = Math.round(t * fps);\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.globalAlpha = 1;\n ctx.globalCompositeOperation = 'source-over';\n ctx.fillStyle = C.bg;\n ctx.fillRect(0, 0, W, H);\n def.draw(ctx, t / timeScale, S);\n return true;\n }\n\n const beatTime = v => (typeof v === 'number' ? v : (S.beats[v] ?? 0));\n // cues from params plus cues the scene derives from its own data (def.cues)\n const rawCues = P.sound?.enabled === false ? [] : [...((P.sound && P.sound.cues) || []), ...(def.cues ? def.cues(S) : [])];\n const cues = rawCues.map(c => ({\n t: +((beatTime(c.at) + (c.offset || 0)) * timeScale).toFixed(4),\n sfx: c.sfx, file: c.file, dur: c.dur, trim: c.trim, gain: c.gain ?? (c.file ? 0.3 : 1),\n })).sort((a, b) => a.t - b.t);\n\n window.renderAt = renderAt;\n window.__sceneMeta = { id: def.id, W, H, ratio, fps, duration, frames: Math.round(duration * fps), theme: themeId, cues, timeScale, music: P.sound?.enabled === false ? null : P.sound?.music || null, voice: P.sound?.enabled === false ? null : P.sound?.voice || null, loudness: P.sound?.enabled === false ? null : P.sound?.loudness || null };\n window.getDiagnostics = () => ({ fonts: fontStatus, warnings: [...warnings], meta: window.__sceneMeta });\n\n document.body.appendChild(canvas);\n if (capture) {\n canvas.style.cssText = 'display:block';\n await renderAt(+(q.get('t') || 0));\n window.__ready = true;\n return;\n }\n preview(canvas, renderAt, S, cues);\n window.__ready = true;\n }\n\n // ---------- interactive preview (never used for rendering) ----------\n function preview(canvas, renderAt, S, cues) {\n const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;\n const showControls = q.get('controls') !== '0';\n const style = document.createElement('style');\n style.textContent = `\n body{height:100vh;display:flex;flex-direction:column;font:13px/1.3 -apple-system,system-ui,sans-serif;color:#e9e4da;background:#0b0b0a}\n #wrap{flex:1;display:flex;align-items:center;justify-content:center;min-height:0;padding:${showControls ? '12px' : '0'}}\n #stage{max-width:100%;max-height:100%;width:auto;height:auto;box-shadow:0 10px 40px rgba(0,0,0,.45)}\n #bar{display:flex;gap:10px;align-items:center;padding:10px 14px;background:#151412;border-top:1px solid #2a2824;flex-wrap:wrap}\n #bar button,#bar select{background:#24221f;color:#e9e4da;border:1px solid #3a3732;border-radius:6px;padding:5px 9px;font:inherit;cursor:pointer}\n #bar button.on{background:#E89A4A;color:#1b1a18;border-color:#E89A4A}\n #bar input[type=range]{flex:1;min-width:160px;accent-color:#E89A4A}\n #tm{font-variant-numeric:tabular-nums;min-width:92px}`;\n document.head.appendChild(style);\n const wrap = document.createElement('div');\n wrap.id = 'wrap';\n document.body.appendChild(wrap);\n wrap.appendChild(canvas);\n\n let t = q.has('t') ? +q.get('t') : reduced ? (S.P.reducedHold ?? S.duration * 0.9) : 0;\n let playing = !reduced && q.get('autoplay') === '1';\n let last = null;\n let sound = q.get('sound') === '1';\n const audio = audioEngine(cues, S);\n\n let range, tm, playBtn, soundBtn;\n if (showControls) {\n const bar = document.createElement('div');\n bar.id = 'bar';\n bar.innerHTML = `<button id=\"pp\"></button><input id=\"rg\" type=\"range\" min=\"0\" max=\"${S.duration}\" step=\"${1 / S.fps}\"><span id=\"tm\"></span>\n <span>${['wide', 'square', 'tall'].map(r => `<button data-r=\"${r}\" class=\"${r === S.ratio ? 'on' : ''}\">${{ wide: '16:9', square: '1:1', tall: '9:16' }[r]}</button>`).join(' ')}</span>\n <select id=\"th\">${Object.entries(window.EB_THEMES).map(([k, v]) => `<option value=\"${k}\" ${k === S.themeId ? 'selected' : ''}>${v.label}</option>`).join('')}</select>\n <button id=\"snd\"></button>`;\n document.body.appendChild(bar);\n range = bar.querySelector('#rg');\n tm = bar.querySelector('#tm');\n playBtn = bar.querySelector('#pp');\n soundBtn = bar.querySelector('#snd');\n const go = (k, v) => { const u = new URL(location.href); u.searchParams.set(k, v); u.searchParams.delete('t'); location.href = u.href; };\n bar.querySelectorAll('[data-r]').forEach(b => b.onclick = () => go('ratio', b.dataset.r));\n bar.querySelector('#th').onchange = e => go('theme', e.target.value);\n playBtn.onclick = toggle;\n soundBtn.onclick = () => { sound = !sound; audio.stop(); if (sound && playing) audio.start(t); sync(); };\n range.oninput = () => { t = +range.value; audio.stop(); if (playing && sound) audio.start(t); draw(); };\n }\n addEventListener('keydown', e => { if (e.code === 'Space') { e.preventDefault(); toggle(); } });\n canvas.onclick = toggle;\n function toggle() {\n playing = !playing;\n if (playing && t >= S.duration - 0.01) t = 0;\n last = null;\n audio.stop();\n if (playing && sound) audio.start(t);\n sync();\n }\n function sync() {\n if (!showControls) return;\n playBtn.textContent = playing ? 'Pausa' : 'Reproducir';\n soundBtn.textContent = sound ? 'Sonido: s\xED' : 'Sonido: no';\n soundBtn.className = sound ? 'on' : '';\n soundBtn.disabled = !cues.length;\n if (!cues.length) soundBtn.textContent = 'Sin sonido';\n }\n function draw() {\n renderAt(t);\n if (showControls) {\n range.value = t;\n tm.textContent = `${t.toFixed(2)} / ${S.duration.toFixed(1)} s`;\n }\n }\n // Pause off-screen / hidden tabs.\n let visible = true;\n new IntersectionObserver(es => { visible = es[0].isIntersecting; }).observe(canvas);\n function loop(now) {\n if (playing && visible && !document.hidden) {\n if (last !== null) t += (now - last) / 1000;\n if (t >= S.duration) {\n t = q.get('loop') === '0' ? S.duration : 0;\n if (q.get('loop') === '0') playing = false;\n audio.stop();\n if (playing && sound) audio.start(t);\n }\n draw();\n }\n last = playing ? now : null;\n requestAnimationFrame(loop);\n }\n sync();\n draw();\n requestAnimationFrame(loop);\n }\n\n // Preview-only audio: schedules the scene's cues from the synthesized SFX bank.\n function audioEngine(cues, S) {\n let ac = null, nodes = [];\n const buffers = {};\n async function buf(name) {\n if (!buffers[name]) {\n const r = await fetch(new URL(`sfx/${name}.wav`, S.lib));\n buffers[name] = await ac.decodeAudioData(await r.arrayBuffer());\n }\n return buffers[name];\n }\n return {\n async start(from) {\n if (!cues.length) return;\n ac = ac || new AudioContext();\n const t0 = ac.currentTime + 0.05;\n for (const c of cues) {\n if (c.t < from - 0.02) continue;\n const b = await buf(c.sfx);\n const src = ac.createBufferSource(), g = ac.createGain();\n src.buffer = b;\n g.gain.value = c.gain;\n src.connect(g).connect(ac.destination);\n src.start(t0 + (c.t - from));\n nodes.push(src);\n }\n },\n stop() { nodes.forEach(n => { try { n.stop(); } catch (e) {} }); nodes = []; },\n };\n }\n})();\n",
182938
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
182939
+ (function () {
182940
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
182941
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
182942
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
182943
+ const fonts = ['display','text','heavy','mono','hand'];
182944
+ window.EB_VALIDATE_PARAMS = (p, q) => {
182945
+ const theme = q.get('theme') || p.theme;
182946
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
182947
+ const ratio = q.get('ratio') || p.ratio || 'wide';
182948
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
182949
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
182950
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
182951
+ }
182952
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
182953
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
182954
+ if (q.get('demo') === '1') return;
182955
+ const b = window.__overrides?.brand;
182956
+ if (!record(b) || !record(b.colors) || !record(b.fonts)) fail('provide complete window.__overrides.brand from the selected project; demo themes are not customer defaults');
182957
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
182958
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
182959
+ if (!Array.isArray(b.series) || b.series.length < 6 || b.series.some(c => !/^#[0-9a-f]{6}$/i.test(c))) fail('provide at least six explicit series hex colors; roles may repeat project colors but never inherit demo colors');
182960
+ for (const role of fonts) {
182961
+ const font = b.fonts[role];
182962
+ if (!record(font) || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) fail('provide explicit family, weight and style for font role ' + role);
182963
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
182964
+ }
182965
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
182966
+ };
182967
+ })();
182968
+
182969
+ (function () {
182970
+ const base = window.EB_VALIDATE_PARAMS;
182971
+ const roles = ["annotation","bg","card","cardLine","docInk","docMuted","docText","hookBox","hookInk","light","marker","page","pageInner","pageLine","paper","shadow"];
182972
+ const fontRoles = ["caption","credit","docBody","docTitle","hook","label","mono","serif","serifItalic"];
182973
+ window.EB_VALIDATE_PARAMS = (params, query) => {
182974
+ base(params, query);
182975
+ if (query.get('demo') === '1') return;
182976
+ for (const role of roles) {
182977
+ if (!/^#[0-9a-f]{6}$/i.test(window.__overrides?.brand?.colors?.[role] || '')) throw new Error('EditorBrain project binding: provide scene-specific color role ' + role + '; never inherit demo/preset brand colors.');
182978
+ }
182979
+ for (const role of fontRoles) {
182980
+ const font = window.__overrides?.brand?.fonts?.[role];
182981
+ if (!font || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) throw new Error('EditorBrain project binding: provide complete scene-specific font role ' + role + '; never inherit demo/preset typography.');
182982
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
182983
+ }
182984
+ };
182985
+ })();
182986
+ `
182987
+ },
182988
+ "monologo-con-dipticos": {
182989
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
182990
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
182991
+ "runtime": "// EditorBrain authored motion \xB7 scene runtime.\n// One canvas, explicit time: window.renderAt(seconds) draws the exact state for that time.\n// URL: ?ratio=wide|square|tall &theme=<kit> &t=<sec> &capture=1 &autoplay=1 &controls=0\n(function () {\n const RATIOS = { wide: [1920, 1080], square: [1080, 1080], tall: [1080, 1920] };\n const LIB_BASE = new URL('..', document.currentScript.src).href; // library root\n const q = new URLSearchParams(location.search);\n const capture = q.get('capture') === '1';\n\n const isObj = v => v && typeof v === 'object' && !Array.isArray(v);\n const merge = (a, b) => {\n if (!isObj(b)) return b === undefined ? a : b;\n const out = { ...(isObj(a) ? a : {}) };\n for (const k of Object.keys(b)) out[k] = merge(out[k], b[k]);\n return out;\n };\n\n function readParams() {\n const el = document.getElementById('params');\n let p = el ? JSON.parse(el.textContent) : {};\n if (window.__overrides) p = merge(p, window.__overrides);\n const enc = q.get('params');\n if (enc) { const supplied = JSON.parse(decodeURIComponent(escape(atob(enc)))); window.__overrides = merge(window.__overrides || {}, supplied); p = merge(p, supplied); }\n window.EB_VALIDATE_PARAMS(p, q);\n return p;\n }\n\n async function loadFonts(F, warn) {\n const families = new Set(Object.values(F).map(f => f.family));\n const status = {};\n for (const fam of families) {\n const defs = (window.EB_FONTS || {})[fam];\n if (!defs) {\n status[fam] = 'not-registered';\n warn(`font family not registered: ${fam}`);\n continue;\n }\n const results = await Promise.all(defs.map(async d => {\n const src = d.local ? d.local.map(n => `local(\"${n}\")`).join(', ') : `url(\"${new URL(d.src, LIB_BASE).href}\")`;\n const desc = {};\n if (d.weight) desc.weight = d.weight;\n if (d.style) desc.style = d.style;\n if (d.stretch) desc.stretch = d.stretch;\n try {\n const face = new FontFace(fam, src, desc);\n await face.load();\n document.fonts.add(face);\n return true;\n } catch (e) {\n return false;\n }\n }));\n const ok = results.filter(Boolean).length;\n status[fam] = ok === defs.length ? 'loaded' : ok ? `partial ${ok}/${defs.length}` : 'missing';\n if (!ok) warn(`font unavailable, renderer would fall back: ${fam}`);\n }\n return status;\n }\n\n function loadImage(src) {\n return new Promise((res, rej) => {\n const img = new Image();\n img.onload = () => res(img);\n img.onerror = () => rej(new Error('image failed: ' + src));\n img.src = src;\n });\n }\n\n function resolveTheme(params) {\n const kits = window.EB_THEMES || {};\n const id = q.get('theme') || params.theme || Object.keys(kits)[0];\n const kit = kits[id] || kits[Object.keys(kits)[0]];\n const brand = params.brand || {};\n const C = { ...kit.colors, ...(brand.colors || {}) };\n C.series = brand.series || kit.series;\n const F = {};\n for (const role of new Set(['display', 'text', 'heavy', 'mono', 'hand', ...Object.keys(brand.fonts || {})])) F[role] = { ...(kit.fonts[role] || kit.fonts.text), ...((brand.fonts || {})[role] || {}) };\n return { id, kit, C, F };\n }\n\n window.EB = {\n RATIOS,\n scene(def) {\n const warnings = new Set();\n const warn = m => { warnings.add(m); if (q.get(\"demo\") !== \"1\") throw new Error(m); };\n try {\n void boot(def, warn, warnings).catch(e => { window.__motionError = String(e && e.stack || e); console.error(window.__motionError); });\n } catch (e) {\n window.__motionError = String(e && e.stack || e);\n throw e;\n }\n },\n };\n\n async function boot(def, warn, warnings) {\n const P = readParams();\n const ratio = q.get('ratio') || P.ratio || 'wide';\n const [W, H] = RATIOS[ratio] || RATIOS.wide;\n const { id: themeId, C, F } = resolveTheme(P);\n const timeScale = P.timeScale || 1;\n const duration = (P.duration || def.duration || 10) * timeScale;\n const fps = P.fps || 30;\n\n document.documentElement.style.background = capture ? C.bg : '#0b0b0a';\n document.body.style.margin = '0';\n const canvas = document.createElement('canvas');\n canvas.id = 'stage';\n canvas.width = W;\n canvas.height = H;\n const ctx = canvas.getContext('2d');\n\n const S = {\n W, H, ratio, P, C, F, themeId, fps, duration, timeScale,\n u: Math.min(W, H) / 1080, // 1 unit = 1px at 1080 short side\n wide: ratio === 'wide', square: ratio === 'square', tall: ratio === 'tall',\n warn, lib: LIB_BASE, frame: 0, images: {}, beats: P.beats || {},\n };\n S.pick = (wide, square, tall) => (S.tall ? tall : S.square ? square : wide);\n\n const fontStatus = await loadFonts(F, warn);\n if (Object.values(fontStatus).some(value => value !== \"loaded\")) throw new Error(\"All registered font faces must load; fallback is not permitted.\");\n for (const [k, rel] of Object.entries(P.media || {})) {\n try { S.images[k] = await loadImage(new URL(rel, location.href).href); } catch (e) { warn(String(e.message)); }\n }\n if (def.setup) await def.setup(S, ctx);\n\n // Scenes with external frames (video clips) define `prepare(t, S)`; renderAt then returns a\n // promise that resolves after those frames are decoded, so captures stay frame-exact.\n function renderAt(t) {\n t = Math.max(0, Math.min(duration, t));\n if (def.prepare) {\n const token = (S._token = (S._token || 0) + 1);\n return Promise.resolve(def.prepare(t / timeScale, S)).then(() => (token === S._token ? paint(t) : false));\n }\n return paint(t);\n }\n function paint(t) {\n S.frame = Math.round(t * fps);\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.globalAlpha = 1;\n ctx.globalCompositeOperation = 'source-over';\n ctx.fillStyle = C.bg;\n ctx.fillRect(0, 0, W, H);\n def.draw(ctx, t / timeScale, S);\n return true;\n }\n\n const beatTime = v => (typeof v === 'number' ? v : (S.beats[v] ?? 0));\n // cues from params plus cues the scene derives from its own data (def.cues)\n const rawCues = P.sound?.enabled === false ? [] : [...((P.sound && P.sound.cues) || []), ...(def.cues ? def.cues(S) : [])];\n const cues = rawCues.map(c => ({\n t: +((beatTime(c.at) + (c.offset || 0)) * timeScale).toFixed(4),\n sfx: c.sfx, file: c.file, dur: c.dur, trim: c.trim, gain: c.gain ?? (c.file ? 0.3 : 1),\n })).sort((a, b) => a.t - b.t);\n\n window.renderAt = renderAt;\n window.__sceneMeta = { id: def.id, W, H, ratio, fps, duration, frames: Math.round(duration * fps), theme: themeId, cues, timeScale, music: P.sound?.enabled === false ? null : P.sound?.music || null, voice: P.sound?.enabled === false ? null : P.sound?.voice || null, loudness: P.sound?.enabled === false ? null : P.sound?.loudness || null };\n window.getDiagnostics = () => ({ fonts: fontStatus, warnings: [...warnings], meta: window.__sceneMeta });\n\n document.body.appendChild(canvas);\n if (capture) {\n canvas.style.cssText = 'display:block';\n await renderAt(+(q.get('t') || 0));\n window.__ready = true;\n return;\n }\n preview(canvas, renderAt, S, cues);\n window.__ready = true;\n }\n\n // ---------- interactive preview (never used for rendering) ----------\n function preview(canvas, renderAt, S, cues) {\n const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;\n const showControls = q.get('controls') !== '0';\n const style = document.createElement('style');\n style.textContent = `\n body{height:100vh;display:flex;flex-direction:column;font:13px/1.3 -apple-system,system-ui,sans-serif;color:#e9e4da;background:#0b0b0a}\n #wrap{flex:1;display:flex;align-items:center;justify-content:center;min-height:0;padding:${showControls ? '12px' : '0'}}\n #stage{max-width:100%;max-height:100%;width:auto;height:auto;box-shadow:0 10px 40px rgba(0,0,0,.45)}\n #bar{display:flex;gap:10px;align-items:center;padding:10px 14px;background:#151412;border-top:1px solid #2a2824;flex-wrap:wrap}\n #bar button,#bar select{background:#24221f;color:#e9e4da;border:1px solid #3a3732;border-radius:6px;padding:5px 9px;font:inherit;cursor:pointer}\n #bar button.on{background:#E89A4A;color:#1b1a18;border-color:#E89A4A}\n #bar input[type=range]{flex:1;min-width:160px;accent-color:#E89A4A}\n #tm{font-variant-numeric:tabular-nums;min-width:92px}`;\n document.head.appendChild(style);\n const wrap = document.createElement('div');\n wrap.id = 'wrap';\n document.body.appendChild(wrap);\n wrap.appendChild(canvas);\n\n let t = q.has('t') ? +q.get('t') : reduced ? (S.P.reducedHold ?? S.duration * 0.9) : 0;\n let playing = !reduced && q.get('autoplay') === '1';\n let last = null;\n let sound = q.get('sound') === '1';\n const audio = audioEngine(cues, S);\n\n let range, tm, playBtn, soundBtn;\n if (showControls) {\n const bar = document.createElement('div');\n bar.id = 'bar';\n bar.innerHTML = `<button id=\"pp\"></button><input id=\"rg\" type=\"range\" min=\"0\" max=\"${S.duration}\" step=\"${1 / S.fps}\"><span id=\"tm\"></span>\n <span>${['wide', 'square', 'tall'].map(r => `<button data-r=\"${r}\" class=\"${r === S.ratio ? 'on' : ''}\">${{ wide: '16:9', square: '1:1', tall: '9:16' }[r]}</button>`).join(' ')}</span>\n <select id=\"th\">${Object.entries(window.EB_THEMES).map(([k, v]) => `<option value=\"${k}\" ${k === S.themeId ? 'selected' : ''}>${v.label}</option>`).join('')}</select>\n <button id=\"snd\"></button>`;\n document.body.appendChild(bar);\n range = bar.querySelector('#rg');\n tm = bar.querySelector('#tm');\n playBtn = bar.querySelector('#pp');\n soundBtn = bar.querySelector('#snd');\n const go = (k, v) => { const u = new URL(location.href); u.searchParams.set(k, v); u.searchParams.delete('t'); location.href = u.href; };\n bar.querySelectorAll('[data-r]').forEach(b => b.onclick = () => go('ratio', b.dataset.r));\n bar.querySelector('#th').onchange = e => go('theme', e.target.value);\n playBtn.onclick = toggle;\n soundBtn.onclick = () => { sound = !sound; audio.stop(); if (sound && playing) audio.start(t); sync(); };\n range.oninput = () => { t = +range.value; audio.stop(); if (playing && sound) audio.start(t); draw(); };\n }\n addEventListener('keydown', e => { if (e.code === 'Space') { e.preventDefault(); toggle(); } });\n canvas.onclick = toggle;\n function toggle() {\n playing = !playing;\n if (playing && t >= S.duration - 0.01) t = 0;\n last = null;\n audio.stop();\n if (playing && sound) audio.start(t);\n sync();\n }\n function sync() {\n if (!showControls) return;\n playBtn.textContent = playing ? 'Pausa' : 'Reproducir';\n soundBtn.textContent = sound ? 'Sonido: s\xED' : 'Sonido: no';\n soundBtn.className = sound ? 'on' : '';\n soundBtn.disabled = !cues.length;\n if (!cues.length) soundBtn.textContent = 'Sin sonido';\n }\n function draw() {\n renderAt(t);\n if (showControls) {\n range.value = t;\n tm.textContent = `${t.toFixed(2)} / ${S.duration.toFixed(1)} s`;\n }\n }\n // Pause off-screen / hidden tabs.\n let visible = true;\n new IntersectionObserver(es => { visible = es[0].isIntersecting; }).observe(canvas);\n function loop(now) {\n if (playing && visible && !document.hidden) {\n if (last !== null) t += (now - last) / 1000;\n if (t >= S.duration) {\n t = q.get('loop') === '0' ? S.duration : 0;\n if (q.get('loop') === '0') playing = false;\n audio.stop();\n if (playing && sound) audio.start(t);\n }\n draw();\n }\n last = playing ? now : null;\n requestAnimationFrame(loop);\n }\n sync();\n draw();\n requestAnimationFrame(loop);\n }\n\n // Preview-only audio: schedules the scene's cues from the synthesized SFX bank.\n function audioEngine(cues, S) {\n let ac = null, nodes = [];\n const buffers = {};\n async function buf(name) {\n if (!buffers[name]) {\n const r = await fetch(new URL(`sfx/${name}.wav`, S.lib));\n buffers[name] = await ac.decodeAudioData(await r.arrayBuffer());\n }\n return buffers[name];\n }\n return {\n async start(from) {\n if (!cues.length) return;\n ac = ac || new AudioContext();\n const t0 = ac.currentTime + 0.05;\n for (const c of cues) {\n if (c.t < from - 0.02) continue;\n const b = await buf(c.sfx);\n const src = ac.createBufferSource(), g = ac.createGain();\n src.buffer = b;\n g.gain.value = c.gain;\n src.connect(g).connect(ac.destination);\n src.start(t0 + (c.t - from));\n nodes.push(src);\n }\n },\n stop() { nodes.forEach(n => { try { n.stop(); } catch (e) {} }); nodes = []; },\n };\n }\n})();\n",
182992
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
182993
+ (function () {
182994
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
182995
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
182996
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
182997
+ const fonts = ['display','text','heavy','mono','hand'];
182998
+ window.EB_VALIDATE_PARAMS = (p, q) => {
182999
+ const theme = q.get('theme') || p.theme;
183000
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
183001
+ const ratio = q.get('ratio') || p.ratio || 'wide';
183002
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
183003
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
183004
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
183005
+ }
183006
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
183007
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
183008
+ if (q.get('demo') === '1') return;
183009
+ const b = window.__overrides?.brand;
183010
+ if (!record(b) || !record(b.colors) || !record(b.fonts)) fail('provide complete window.__overrides.brand from the selected project; demo themes are not customer defaults');
183011
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
183012
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
183013
+ if (!Array.isArray(b.series) || b.series.length < 6 || b.series.some(c => !/^#[0-9a-f]{6}$/i.test(c))) fail('provide at least six explicit series hex colors; roles may repeat project colors but never inherit demo colors');
183014
+ for (const role of fonts) {
183015
+ const font = b.fonts[role];
183016
+ if (!record(font) || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) fail('provide explicit family, weight and style for font role ' + role);
183017
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
183018
+ }
183019
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
183020
+ };
183021
+ })();
183022
+
183023
+ (function () {
183024
+ const base = window.EB_VALIDATE_PARAMS;
183025
+ const roles = ["bg","caption","credit","headline"];
183026
+ const fontRoles = ["caption","credit","headline"];
183027
+ window.EB_VALIDATE_PARAMS = (params, query) => {
183028
+ base(params, query);
183029
+ if (query.get('demo') === '1') return;
183030
+ for (const role of roles) {
183031
+ if (!/^#[0-9a-f]{6}$/i.test(window.__overrides?.brand?.colors?.[role] || '')) throw new Error('EditorBrain project binding: provide scene-specific color role ' + role + '; never inherit demo/preset brand colors.');
183032
+ }
183033
+ for (const role of fontRoles) {
183034
+ const font = window.__overrides?.brand?.fonts?.[role];
183035
+ if (!font || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) throw new Error('EditorBrain project binding: provide complete scene-specific font role ' + role + '; never inherit demo/preset typography.');
183036
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183037
+ }
183038
+ };
183039
+ })();
183040
+ `
183041
+ },
183042
+ "recorrido-de-experto": {
183043
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
183044
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
183045
+ "runtime": "// EditorBrain authored motion \xB7 scene runtime.\n// One canvas, explicit time: window.renderAt(seconds) draws the exact state for that time.\n// URL: ?ratio=wide|square|tall &theme=<kit> &t=<sec> &capture=1 &autoplay=1 &controls=0\n(function () {\n const RATIOS = { wide: [1920, 1080], square: [1080, 1080], tall: [1080, 1920] };\n const LIB_BASE = new URL('..', document.currentScript.src).href; // library root\n const q = new URLSearchParams(location.search);\n const capture = q.get('capture') === '1';\n\n const isObj = v => v && typeof v === 'object' && !Array.isArray(v);\n const merge = (a, b) => {\n if (!isObj(b)) return b === undefined ? a : b;\n const out = { ...(isObj(a) ? a : {}) };\n for (const k of Object.keys(b)) out[k] = merge(out[k], b[k]);\n return out;\n };\n\n function readParams() {\n const el = document.getElementById('params');\n let p = el ? JSON.parse(el.textContent) : {};\n if (window.__overrides) p = merge(p, window.__overrides);\n const enc = q.get('params');\n if (enc) { const supplied = JSON.parse(decodeURIComponent(escape(atob(enc)))); window.__overrides = merge(window.__overrides || {}, supplied); p = merge(p, supplied); }\n window.EB_VALIDATE_PARAMS(p, q);\n return p;\n }\n\n async function loadFonts(F, warn) {\n const families = new Set(Object.values(F).map(f => f.family));\n const status = {};\n for (const fam of families) {\n const defs = (window.EB_FONTS || {})[fam];\n if (!defs) {\n status[fam] = 'not-registered';\n warn(`font family not registered: ${fam}`);\n continue;\n }\n const results = await Promise.all(defs.map(async d => {\n const src = d.local ? d.local.map(n => `local(\"${n}\")`).join(', ') : `url(\"${new URL(d.src, LIB_BASE).href}\")`;\n const desc = {};\n if (d.weight) desc.weight = d.weight;\n if (d.style) desc.style = d.style;\n if (d.stretch) desc.stretch = d.stretch;\n try {\n const face = new FontFace(fam, src, desc);\n await face.load();\n document.fonts.add(face);\n return true;\n } catch (e) {\n return false;\n }\n }));\n const ok = results.filter(Boolean).length;\n status[fam] = ok === defs.length ? 'loaded' : ok ? `partial ${ok}/${defs.length}` : 'missing';\n if (!ok) warn(`font unavailable, renderer would fall back: ${fam}`);\n }\n return status;\n }\n\n function loadImage(src) {\n return new Promise((res, rej) => {\n const img = new Image();\n img.onload = () => res(img);\n img.onerror = () => rej(new Error('image failed: ' + src));\n img.src = src;\n });\n }\n\n function resolveTheme(params) {\n const kits = window.EB_THEMES || {};\n const id = q.get('theme') || params.theme || Object.keys(kits)[0];\n const kit = kits[id] || kits[Object.keys(kits)[0]];\n const brand = params.brand || {};\n const C = { ...kit.colors, ...(brand.colors || {}) };\n C.series = brand.series || kit.series;\n const F = {};\n for (const role of new Set(['display', 'text', 'heavy', 'mono', 'hand', ...Object.keys(brand.fonts || {})])) F[role] = { ...(kit.fonts[role] || kit.fonts.text), ...((brand.fonts || {})[role] || {}) };\n return { id, kit, C, F };\n }\n\n window.EB = {\n RATIOS,\n scene(def) {\n const warnings = new Set();\n const warn = m => { warnings.add(m); if (q.get(\"demo\") !== \"1\") throw new Error(m); };\n try {\n void boot(def, warn, warnings).catch(e => { window.__motionError = String(e && e.stack || e); console.error(window.__motionError); });\n } catch (e) {\n window.__motionError = String(e && e.stack || e);\n throw e;\n }\n },\n };\n\n async function boot(def, warn, warnings) {\n const P = readParams();\n const ratio = q.get('ratio') || P.ratio || 'wide';\n const [W, H] = RATIOS[ratio] || RATIOS.wide;\n const { id: themeId, C, F } = resolveTheme(P);\n const timeScale = P.timeScale || 1;\n const duration = (P.duration || def.duration || 10) * timeScale;\n const fps = P.fps || 30;\n\n document.documentElement.style.background = capture ? C.bg : '#0b0b0a';\n document.body.style.margin = '0';\n const canvas = document.createElement('canvas');\n canvas.id = 'stage';\n canvas.width = W;\n canvas.height = H;\n const ctx = canvas.getContext('2d');\n\n const S = {\n W, H, ratio, P, C, F, themeId, fps, duration, timeScale,\n u: Math.min(W, H) / 1080, // 1 unit = 1px at 1080 short side\n wide: ratio === 'wide', square: ratio === 'square', tall: ratio === 'tall',\n warn, lib: LIB_BASE, frame: 0, images: {}, beats: P.beats || {},\n };\n S.pick = (wide, square, tall) => (S.tall ? tall : S.square ? square : wide);\n\n const fontStatus = await loadFonts(F, warn);\n if (Object.values(fontStatus).some(value => value !== \"loaded\")) throw new Error(\"All registered font faces must load; fallback is not permitted.\");\n for (const [k, rel] of Object.entries(P.media || {})) {\n try { S.images[k] = await loadImage(new URL(rel, location.href).href); } catch (e) { warn(String(e.message)); }\n }\n if (def.setup) await def.setup(S, ctx);\n\n // Scenes with external frames (video clips) define `prepare(t, S)`; renderAt then returns a\n // promise that resolves after those frames are decoded, so captures stay frame-exact.\n function renderAt(t) {\n t = Math.max(0, Math.min(duration, t));\n if (def.prepare) {\n const token = (S._token = (S._token || 0) + 1);\n return Promise.resolve(def.prepare(t / timeScale, S)).then(() => (token === S._token ? paint(t) : false));\n }\n return paint(t);\n }\n function paint(t) {\n S.frame = Math.round(t * fps);\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.globalAlpha = 1;\n ctx.globalCompositeOperation = 'source-over';\n ctx.fillStyle = C.bg;\n ctx.fillRect(0, 0, W, H);\n def.draw(ctx, t / timeScale, S);\n return true;\n }\n\n const beatTime = v => (typeof v === 'number' ? v : (S.beats[v] ?? 0));\n // cues from params plus cues the scene derives from its own data (def.cues)\n const rawCues = P.sound?.enabled === false ? [] : [...((P.sound && P.sound.cues) || []), ...(def.cues ? def.cues(S) : [])];\n const cues = rawCues.map(c => ({\n t: +((beatTime(c.at) + (c.offset || 0)) * timeScale).toFixed(4),\n sfx: c.sfx, file: c.file, dur: c.dur, trim: c.trim, gain: c.gain ?? (c.file ? 0.3 : 1),\n })).sort((a, b) => a.t - b.t);\n\n window.renderAt = renderAt;\n window.__sceneMeta = { id: def.id, W, H, ratio, fps, duration, frames: Math.round(duration * fps), theme: themeId, cues, timeScale, music: P.sound?.enabled === false ? null : P.sound?.music || null, voice: P.sound?.enabled === false ? null : P.sound?.voice || null, loudness: P.sound?.enabled === false ? null : P.sound?.loudness || null };\n window.getDiagnostics = () => ({ fonts: fontStatus, warnings: [...warnings], meta: window.__sceneMeta });\n\n document.body.appendChild(canvas);\n if (capture) {\n canvas.style.cssText = 'display:block';\n await renderAt(+(q.get('t') || 0));\n window.__ready = true;\n return;\n }\n preview(canvas, renderAt, S, cues);\n window.__ready = true;\n }\n\n // ---------- interactive preview (never used for rendering) ----------\n function preview(canvas, renderAt, S, cues) {\n const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;\n const showControls = q.get('controls') !== '0';\n const style = document.createElement('style');\n style.textContent = `\n body{height:100vh;display:flex;flex-direction:column;font:13px/1.3 -apple-system,system-ui,sans-serif;color:#e9e4da;background:#0b0b0a}\n #wrap{flex:1;display:flex;align-items:center;justify-content:center;min-height:0;padding:${showControls ? '12px' : '0'}}\n #stage{max-width:100%;max-height:100%;width:auto;height:auto;box-shadow:0 10px 40px rgba(0,0,0,.45)}\n #bar{display:flex;gap:10px;align-items:center;padding:10px 14px;background:#151412;border-top:1px solid #2a2824;flex-wrap:wrap}\n #bar button,#bar select{background:#24221f;color:#e9e4da;border:1px solid #3a3732;border-radius:6px;padding:5px 9px;font:inherit;cursor:pointer}\n #bar button.on{background:#E89A4A;color:#1b1a18;border-color:#E89A4A}\n #bar input[type=range]{flex:1;min-width:160px;accent-color:#E89A4A}\n #tm{font-variant-numeric:tabular-nums;min-width:92px}`;\n document.head.appendChild(style);\n const wrap = document.createElement('div');\n wrap.id = 'wrap';\n document.body.appendChild(wrap);\n wrap.appendChild(canvas);\n\n let t = q.has('t') ? +q.get('t') : reduced ? (S.P.reducedHold ?? S.duration * 0.9) : 0;\n let playing = !reduced && q.get('autoplay') === '1';\n let last = null;\n let sound = q.get('sound') === '1';\n const audio = audioEngine(cues, S);\n\n let range, tm, playBtn, soundBtn;\n if (showControls) {\n const bar = document.createElement('div');\n bar.id = 'bar';\n bar.innerHTML = `<button id=\"pp\"></button><input id=\"rg\" type=\"range\" min=\"0\" max=\"${S.duration}\" step=\"${1 / S.fps}\"><span id=\"tm\"></span>\n <span>${['wide', 'square', 'tall'].map(r => `<button data-r=\"${r}\" class=\"${r === S.ratio ? 'on' : ''}\">${{ wide: '16:9', square: '1:1', tall: '9:16' }[r]}</button>`).join(' ')}</span>\n <select id=\"th\">${Object.entries(window.EB_THEMES).map(([k, v]) => `<option value=\"${k}\" ${k === S.themeId ? 'selected' : ''}>${v.label}</option>`).join('')}</select>\n <button id=\"snd\"></button>`;\n document.body.appendChild(bar);\n range = bar.querySelector('#rg');\n tm = bar.querySelector('#tm');\n playBtn = bar.querySelector('#pp');\n soundBtn = bar.querySelector('#snd');\n const go = (k, v) => { const u = new URL(location.href); u.searchParams.set(k, v); u.searchParams.delete('t'); location.href = u.href; };\n bar.querySelectorAll('[data-r]').forEach(b => b.onclick = () => go('ratio', b.dataset.r));\n bar.querySelector('#th').onchange = e => go('theme', e.target.value);\n playBtn.onclick = toggle;\n soundBtn.onclick = () => { sound = !sound; audio.stop(); if (sound && playing) audio.start(t); sync(); };\n range.oninput = () => { t = +range.value; audio.stop(); if (playing && sound) audio.start(t); draw(); };\n }\n addEventListener('keydown', e => { if (e.code === 'Space') { e.preventDefault(); toggle(); } });\n canvas.onclick = toggle;\n function toggle() {\n playing = !playing;\n if (playing && t >= S.duration - 0.01) t = 0;\n last = null;\n audio.stop();\n if (playing && sound) audio.start(t);\n sync();\n }\n function sync() {\n if (!showControls) return;\n playBtn.textContent = playing ? 'Pausa' : 'Reproducir';\n soundBtn.textContent = sound ? 'Sonido: s\xED' : 'Sonido: no';\n soundBtn.className = sound ? 'on' : '';\n soundBtn.disabled = !cues.length;\n if (!cues.length) soundBtn.textContent = 'Sin sonido';\n }\n function draw() {\n renderAt(t);\n if (showControls) {\n range.value = t;\n tm.textContent = `${t.toFixed(2)} / ${S.duration.toFixed(1)} s`;\n }\n }\n // Pause off-screen / hidden tabs.\n let visible = true;\n new IntersectionObserver(es => { visible = es[0].isIntersecting; }).observe(canvas);\n function loop(now) {\n if (playing && visible && !document.hidden) {\n if (last !== null) t += (now - last) / 1000;\n if (t >= S.duration) {\n t = q.get('loop') === '0' ? S.duration : 0;\n if (q.get('loop') === '0') playing = false;\n audio.stop();\n if (playing && sound) audio.start(t);\n }\n draw();\n }\n last = playing ? now : null;\n requestAnimationFrame(loop);\n }\n sync();\n draw();\n requestAnimationFrame(loop);\n }\n\n // Preview-only audio: schedules the scene's cues from the synthesized SFX bank.\n function audioEngine(cues, S) {\n let ac = null, nodes = [];\n const buffers = {};\n async function buf(name) {\n if (!buffers[name]) {\n const r = await fetch(new URL(`sfx/${name}.wav`, S.lib));\n buffers[name] = await ac.decodeAudioData(await r.arrayBuffer());\n }\n return buffers[name];\n }\n return {\n async start(from) {\n if (!cues.length) return;\n ac = ac || new AudioContext();\n const t0 = ac.currentTime + 0.05;\n for (const c of cues) {\n if (c.t < from - 0.02) continue;\n const b = await buf(c.sfx);\n const src = ac.createBufferSource(), g = ac.createGain();\n src.buffer = b;\n g.gain.value = c.gain;\n src.connect(g).connect(ac.destination);\n src.start(t0 + (c.t - from));\n nodes.push(src);\n }\n },\n stop() { nodes.forEach(n => { try { n.stop(); } catch (e) {} }); nodes = []; },\n };\n }\n})();\n",
183046
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
183047
+ (function () {
183048
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
183049
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
183050
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
183051
+ const fonts = ['display','text','heavy','mono','hand'];
183052
+ window.EB_VALIDATE_PARAMS = (p, q) => {
183053
+ const theme = q.get('theme') || p.theme;
183054
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
183055
+ const ratio = q.get('ratio') || p.ratio || 'wide';
183056
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
183057
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
183058
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
183059
+ }
183060
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
183061
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
183062
+ if (q.get('demo') === '1') return;
183063
+ const b = window.__overrides?.brand;
183064
+ if (!record(b) || !record(b.colors) || !record(b.fonts)) fail('provide complete window.__overrides.brand from the selected project; demo themes are not customer defaults');
183065
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
183066
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
183067
+ if (!Array.isArray(b.series) || b.series.length < 6 || b.series.some(c => !/^#[0-9a-f]{6}$/i.test(c))) fail('provide at least six explicit series hex colors; roles may repeat project colors but never inherit demo colors');
183068
+ for (const role of fonts) {
183069
+ const font = b.fonts[role];
183070
+ if (!record(font) || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) fail('provide explicit family, weight and style for font role ' + role);
183071
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
183072
+ }
183073
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
183074
+ };
183075
+ })();
183076
+
183077
+ (function () {
183078
+ const base = window.EB_VALIDATE_PARAMS;
183079
+ const roles = ["bg","light","shadow"];
183080
+ const fontRoles = ["bold","caption","credit","label","semi"];
183081
+ window.EB_VALIDATE_PARAMS = (params, query) => {
183082
+ base(params, query);
183083
+ if (query.get('demo') === '1') return;
183084
+ for (const role of roles) {
183085
+ if (!/^#[0-9a-f]{6}$/i.test(window.__overrides?.brand?.colors?.[role] || '')) throw new Error('EditorBrain project binding: provide scene-specific color role ' + role + '; never inherit demo/preset brand colors.');
183086
+ }
183087
+ for (const role of fontRoles) {
183088
+ const font = window.__overrides?.brand?.fonts?.[role];
183089
+ if (!font || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) throw new Error('EditorBrain project binding: provide complete scene-specific font role ' + role + '; never inherit demo/preset typography.');
183090
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183091
+ }
183092
+ };
183093
+ })();
183094
+ `
183095
+ },
183096
+ "vlog-intimo": {
183097
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
183098
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
183099
+ "runtime": "// EditorBrain authored motion \xB7 scene runtime.\n// One canvas, explicit time: window.renderAt(seconds) draws the exact state for that time.\n// URL: ?ratio=wide|square|tall &theme=<kit> &t=<sec> &capture=1 &autoplay=1 &controls=0\n(function () {\n const RATIOS = { wide: [1920, 1080], square: [1080, 1080], tall: [1080, 1920] };\n const LIB_BASE = new URL('..', document.currentScript.src).href; // library root\n const q = new URLSearchParams(location.search);\n const capture = q.get('capture') === '1';\n\n const isObj = v => v && typeof v === 'object' && !Array.isArray(v);\n const merge = (a, b) => {\n if (!isObj(b)) return b === undefined ? a : b;\n const out = { ...(isObj(a) ? a : {}) };\n for (const k of Object.keys(b)) out[k] = merge(out[k], b[k]);\n return out;\n };\n\n function readParams() {\n const el = document.getElementById('params');\n let p = el ? JSON.parse(el.textContent) : {};\n if (window.__overrides) p = merge(p, window.__overrides);\n const enc = q.get('params');\n if (enc) { const supplied = JSON.parse(decodeURIComponent(escape(atob(enc)))); window.__overrides = merge(window.__overrides || {}, supplied); p = merge(p, supplied); }\n window.EB_VALIDATE_PARAMS(p, q);\n return p;\n }\n\n async function loadFonts(F, warn) {\n const families = new Set(Object.values(F).map(f => f.family));\n const status = {};\n for (const fam of families) {\n const defs = (window.EB_FONTS || {})[fam];\n if (!defs) {\n status[fam] = 'not-registered';\n warn(`font family not registered: ${fam}`);\n continue;\n }\n const results = await Promise.all(defs.map(async d => {\n const src = d.local ? d.local.map(n => `local(\"${n}\")`).join(', ') : `url(\"${new URL(d.src, LIB_BASE).href}\")`;\n const desc = {};\n if (d.weight) desc.weight = d.weight;\n if (d.style) desc.style = d.style;\n if (d.stretch) desc.stretch = d.stretch;\n try {\n const face = new FontFace(fam, src, desc);\n await face.load();\n document.fonts.add(face);\n return true;\n } catch (e) {\n return false;\n }\n }));\n const ok = results.filter(Boolean).length;\n status[fam] = ok === defs.length ? 'loaded' : ok ? `partial ${ok}/${defs.length}` : 'missing';\n if (!ok) warn(`font unavailable, renderer would fall back: ${fam}`);\n }\n return status;\n }\n\n function loadImage(src) {\n return new Promise((res, rej) => {\n const img = new Image();\n img.onload = () => res(img);\n img.onerror = () => rej(new Error('image failed: ' + src));\n img.src = src;\n });\n }\n\n function resolveTheme(params) {\n const kits = window.EB_THEMES || {};\n const id = q.get('theme') || params.theme || Object.keys(kits)[0];\n const kit = kits[id] || kits[Object.keys(kits)[0]];\n const brand = params.brand || {};\n const C = { ...kit.colors, ...(brand.colors || {}) };\n C.series = brand.series || kit.series;\n const F = {};\n for (const role of new Set(['display', 'text', 'heavy', 'mono', 'hand', ...Object.keys(brand.fonts || {})])) F[role] = { ...(kit.fonts[role] || kit.fonts.text), ...((brand.fonts || {})[role] || {}) };\n return { id, kit, C, F };\n }\n\n window.EB = {\n RATIOS,\n scene(def) {\n const warnings = new Set();\n const warn = m => { warnings.add(m); if (q.get(\"demo\") !== \"1\") throw new Error(m); };\n try {\n void boot(def, warn, warnings).catch(e => { window.__motionError = String(e && e.stack || e); console.error(window.__motionError); });\n } catch (e) {\n window.__motionError = String(e && e.stack || e);\n throw e;\n }\n },\n };\n\n async function boot(def, warn, warnings) {\n const P = readParams();\n const ratio = q.get('ratio') || P.ratio || 'wide';\n const [W, H] = RATIOS[ratio] || RATIOS.wide;\n const { id: themeId, C, F } = resolveTheme(P);\n const timeScale = P.timeScale || 1;\n const duration = (P.duration || def.duration || 10) * timeScale;\n const fps = P.fps || 30;\n\n document.documentElement.style.background = capture ? C.bg : '#0b0b0a';\n document.body.style.margin = '0';\n const canvas = document.createElement('canvas');\n canvas.id = 'stage';\n canvas.width = W;\n canvas.height = H;\n const ctx = canvas.getContext('2d');\n\n const S = {\n W, H, ratio, P, C, F, themeId, fps, duration, timeScale,\n u: Math.min(W, H) / 1080, // 1 unit = 1px at 1080 short side\n wide: ratio === 'wide', square: ratio === 'square', tall: ratio === 'tall',\n warn, lib: LIB_BASE, frame: 0, images: {}, beats: P.beats || {},\n };\n S.pick = (wide, square, tall) => (S.tall ? tall : S.square ? square : wide);\n\n const fontStatus = await loadFonts(F, warn);\n if (Object.values(fontStatus).some(value => value !== \"loaded\")) throw new Error(\"All registered font faces must load; fallback is not permitted.\");\n for (const [k, rel] of Object.entries(P.media || {})) {\n try { S.images[k] = await loadImage(new URL(rel, location.href).href); } catch (e) { warn(String(e.message)); }\n }\n if (def.setup) await def.setup(S, ctx);\n\n // Scenes with external frames (video clips) define `prepare(t, S)`; renderAt then returns a\n // promise that resolves after those frames are decoded, so captures stay frame-exact.\n function renderAt(t) {\n t = Math.max(0, Math.min(duration, t));\n if (def.prepare) {\n const token = (S._token = (S._token || 0) + 1);\n return Promise.resolve(def.prepare(t / timeScale, S)).then(() => (token === S._token ? paint(t) : false));\n }\n return paint(t);\n }\n function paint(t) {\n S.frame = Math.round(t * fps);\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.globalAlpha = 1;\n ctx.globalCompositeOperation = 'source-over';\n ctx.fillStyle = C.bg;\n ctx.fillRect(0, 0, W, H);\n def.draw(ctx, t / timeScale, S);\n return true;\n }\n\n const beatTime = v => (typeof v === 'number' ? v : (S.beats[v] ?? 0));\n // cues from params plus cues the scene derives from its own data (def.cues)\n const rawCues = P.sound?.enabled === false ? [] : [...((P.sound && P.sound.cues) || []), ...(def.cues ? def.cues(S) : [])];\n const cues = rawCues.map(c => ({\n t: +((beatTime(c.at) + (c.offset || 0)) * timeScale).toFixed(4),\n sfx: c.sfx, file: c.file, dur: c.dur, trim: c.trim, gain: c.gain ?? (c.file ? 0.3 : 1),\n })).sort((a, b) => a.t - b.t);\n\n window.renderAt = renderAt;\n window.__sceneMeta = { id: def.id, W, H, ratio, fps, duration, frames: Math.round(duration * fps), theme: themeId, cues, timeScale, music: P.sound?.enabled === false ? null : P.sound?.music || null, voice: P.sound?.enabled === false ? null : P.sound?.voice || null, loudness: P.sound?.enabled === false ? null : P.sound?.loudness || null };\n window.getDiagnostics = () => ({ fonts: fontStatus, warnings: [...warnings], meta: window.__sceneMeta });\n\n document.body.appendChild(canvas);\n if (capture) {\n canvas.style.cssText = 'display:block';\n await renderAt(+(q.get('t') || 0));\n window.__ready = true;\n return;\n }\n preview(canvas, renderAt, S, cues);\n window.__ready = true;\n }\n\n // ---------- interactive preview (never used for rendering) ----------\n function preview(canvas, renderAt, S, cues) {\n const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;\n const showControls = q.get('controls') !== '0';\n const style = document.createElement('style');\n style.textContent = `\n body{height:100vh;display:flex;flex-direction:column;font:13px/1.3 -apple-system,system-ui,sans-serif;color:#e9e4da;background:#0b0b0a}\n #wrap{flex:1;display:flex;align-items:center;justify-content:center;min-height:0;padding:${showControls ? '12px' : '0'}}\n #stage{max-width:100%;max-height:100%;width:auto;height:auto;box-shadow:0 10px 40px rgba(0,0,0,.45)}\n #bar{display:flex;gap:10px;align-items:center;padding:10px 14px;background:#151412;border-top:1px solid #2a2824;flex-wrap:wrap}\n #bar button,#bar select{background:#24221f;color:#e9e4da;border:1px solid #3a3732;border-radius:6px;padding:5px 9px;font:inherit;cursor:pointer}\n #bar button.on{background:#E89A4A;color:#1b1a18;border-color:#E89A4A}\n #bar input[type=range]{flex:1;min-width:160px;accent-color:#E89A4A}\n #tm{font-variant-numeric:tabular-nums;min-width:92px}`;\n document.head.appendChild(style);\n const wrap = document.createElement('div');\n wrap.id = 'wrap';\n document.body.appendChild(wrap);\n wrap.appendChild(canvas);\n\n let t = q.has('t') ? +q.get('t') : reduced ? (S.P.reducedHold ?? S.duration * 0.9) : 0;\n let playing = !reduced && q.get('autoplay') === '1';\n let last = null;\n let sound = q.get('sound') === '1';\n const audio = audioEngine(cues, S);\n\n let range, tm, playBtn, soundBtn;\n if (showControls) {\n const bar = document.createElement('div');\n bar.id = 'bar';\n bar.innerHTML = `<button id=\"pp\"></button><input id=\"rg\" type=\"range\" min=\"0\" max=\"${S.duration}\" step=\"${1 / S.fps}\"><span id=\"tm\"></span>\n <span>${['wide', 'square', 'tall'].map(r => `<button data-r=\"${r}\" class=\"${r === S.ratio ? 'on' : ''}\">${{ wide: '16:9', square: '1:1', tall: '9:16' }[r]}</button>`).join(' ')}</span>\n <select id=\"th\">${Object.entries(window.EB_THEMES).map(([k, v]) => `<option value=\"${k}\" ${k === S.themeId ? 'selected' : ''}>${v.label}</option>`).join('')}</select>\n <button id=\"snd\"></button>`;\n document.body.appendChild(bar);\n range = bar.querySelector('#rg');\n tm = bar.querySelector('#tm');\n playBtn = bar.querySelector('#pp');\n soundBtn = bar.querySelector('#snd');\n const go = (k, v) => { const u = new URL(location.href); u.searchParams.set(k, v); u.searchParams.delete('t'); location.href = u.href; };\n bar.querySelectorAll('[data-r]').forEach(b => b.onclick = () => go('ratio', b.dataset.r));\n bar.querySelector('#th').onchange = e => go('theme', e.target.value);\n playBtn.onclick = toggle;\n soundBtn.onclick = () => { sound = !sound; audio.stop(); if (sound && playing) audio.start(t); sync(); };\n range.oninput = () => { t = +range.value; audio.stop(); if (playing && sound) audio.start(t); draw(); };\n }\n addEventListener('keydown', e => { if (e.code === 'Space') { e.preventDefault(); toggle(); } });\n canvas.onclick = toggle;\n function toggle() {\n playing = !playing;\n if (playing && t >= S.duration - 0.01) t = 0;\n last = null;\n audio.stop();\n if (playing && sound) audio.start(t);\n sync();\n }\n function sync() {\n if (!showControls) return;\n playBtn.textContent = playing ? 'Pausa' : 'Reproducir';\n soundBtn.textContent = sound ? 'Sonido: s\xED' : 'Sonido: no';\n soundBtn.className = sound ? 'on' : '';\n soundBtn.disabled = !cues.length;\n if (!cues.length) soundBtn.textContent = 'Sin sonido';\n }\n function draw() {\n renderAt(t);\n if (showControls) {\n range.value = t;\n tm.textContent = `${t.toFixed(2)} / ${S.duration.toFixed(1)} s`;\n }\n }\n // Pause off-screen / hidden tabs.\n let visible = true;\n new IntersectionObserver(es => { visible = es[0].isIntersecting; }).observe(canvas);\n function loop(now) {\n if (playing && visible && !document.hidden) {\n if (last !== null) t += (now - last) / 1000;\n if (t >= S.duration) {\n t = q.get('loop') === '0' ? S.duration : 0;\n if (q.get('loop') === '0') playing = false;\n audio.stop();\n if (playing && sound) audio.start(t);\n }\n draw();\n }\n last = playing ? now : null;\n requestAnimationFrame(loop);\n }\n sync();\n draw();\n requestAnimationFrame(loop);\n }\n\n // Preview-only audio: schedules the scene's cues from the synthesized SFX bank.\n function audioEngine(cues, S) {\n let ac = null, nodes = [];\n const buffers = {};\n async function buf(name) {\n if (!buffers[name]) {\n const r = await fetch(new URL(`sfx/${name}.wav`, S.lib));\n buffers[name] = await ac.decodeAudioData(await r.arrayBuffer());\n }\n return buffers[name];\n }\n return {\n async start(from) {\n if (!cues.length) return;\n ac = ac || new AudioContext();\n const t0 = ac.currentTime + 0.05;\n for (const c of cues) {\n if (c.t < from - 0.02) continue;\n const b = await buf(c.sfx);\n const src = ac.createBufferSource(), g = ac.createGain();\n src.buffer = b;\n g.gain.value = c.gain;\n src.connect(g).connect(ac.destination);\n src.start(t0 + (c.t - from));\n nodes.push(src);\n }\n },\n stop() { nodes.forEach(n => { try { n.stop(); } catch (e) {} }); nodes = []; },\n };\n }\n})();\n",
183100
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
183101
+ (function () {
183102
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
183103
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
183104
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
183105
+ const fonts = ['display','text','heavy','mono','hand'];
183106
+ window.EB_VALIDATE_PARAMS = (p, q) => {
183107
+ const theme = q.get('theme') || p.theme;
183108
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
183109
+ const ratio = q.get('ratio') || p.ratio || 'wide';
183110
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
183111
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
183112
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
183113
+ }
183114
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
183115
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
183116
+ if (q.get('demo') === '1') return;
183117
+ const b = window.__overrides?.brand;
183118
+ if (!record(b) || !record(b.colors) || !record(b.fonts)) fail('provide complete window.__overrides.brand from the selected project; demo themes are not customer defaults');
183119
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
183120
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
183121
+ if (!Array.isArray(b.series) || b.series.length < 6 || b.series.some(c => !/^#[0-9a-f]{6}$/i.test(c))) fail('provide at least six explicit series hex colors; roles may repeat project colors but never inherit demo colors');
183122
+ for (const role of fonts) {
183123
+ const font = b.fonts[role];
183124
+ if (!record(font) || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) fail('provide explicit family, weight and style for font role ' + role);
183125
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
183126
+ }
183127
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
183128
+ };
183129
+ })();
183130
+
183131
+ (function () {
183132
+ const base = window.EB_VALIDATE_PARAMS;
183133
+ const roles = ["bg","gold","inkA","inkB","inkC","light","paper","paperRim","plate","plateInk","shadow","wood"];
183134
+ const fontRoles = ["credit","serif","slip"];
183135
+ window.EB_VALIDATE_PARAMS = (params, query) => {
183136
+ base(params, query);
183137
+ if (query.get('demo') === '1') return;
183138
+ for (const role of roles) {
183139
+ if (!/^#[0-9a-f]{6}$/i.test(window.__overrides?.brand?.colors?.[role] || '')) throw new Error('EditorBrain project binding: provide scene-specific color role ' + role + '; never inherit demo/preset brand colors.');
183140
+ }
183141
+ for (const role of fontRoles) {
183142
+ const font = window.__overrides?.brand?.fonts?.[role];
183143
+ if (!font || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) throw new Error('EditorBrain project binding: provide complete scene-specific font role ' + role + '; never inherit demo/preset typography.');
183144
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183145
+ }
183146
+ };
183147
+ })();
183148
+ `
183149
+ },
183150
+ "documental-de-archivo": {
183151
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
183152
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
183153
+ "runtime": "// EditorBrain authored motion \xB7 scene runtime.\n// One canvas, explicit time: window.renderAt(seconds) draws the exact state for that time.\n// URL: ?ratio=wide|square|tall &theme=<kit> &t=<sec> &capture=1 &autoplay=1 &controls=0\n(function () {\n const RATIOS = { wide: [1920, 1080], square: [1080, 1080], tall: [1080, 1920] };\n const LIB_BASE = new URL('..', document.currentScript.src).href; // library root\n const q = new URLSearchParams(location.search);\n const capture = q.get('capture') === '1';\n\n const isObj = v => v && typeof v === 'object' && !Array.isArray(v);\n const merge = (a, b) => {\n if (!isObj(b)) return b === undefined ? a : b;\n const out = { ...(isObj(a) ? a : {}) };\n for (const k of Object.keys(b)) out[k] = merge(out[k], b[k]);\n return out;\n };\n\n function readParams() {\n const el = document.getElementById('params');\n let p = el ? JSON.parse(el.textContent) : {};\n if (window.__overrides) p = merge(p, window.__overrides);\n const enc = q.get('params');\n if (enc) { const supplied = JSON.parse(decodeURIComponent(escape(atob(enc)))); window.__overrides = merge(window.__overrides || {}, supplied); p = merge(p, supplied); }\n window.EB_VALIDATE_PARAMS(p, q);\n return p;\n }\n\n async function loadFonts(F, warn) {\n const families = new Set(Object.values(F).map(f => f.family));\n const status = {};\n for (const fam of families) {\n const defs = (window.EB_FONTS || {})[fam];\n if (!defs) {\n status[fam] = 'not-registered';\n warn(`font family not registered: ${fam}`);\n continue;\n }\n const results = await Promise.all(defs.map(async d => {\n const src = d.local ? d.local.map(n => `local(\"${n}\")`).join(', ') : `url(\"${new URL(d.src, LIB_BASE).href}\")`;\n const desc = {};\n if (d.weight) desc.weight = d.weight;\n if (d.style) desc.style = d.style;\n if (d.stretch) desc.stretch = d.stretch;\n try {\n const face = new FontFace(fam, src, desc);\n await face.load();\n document.fonts.add(face);\n return true;\n } catch (e) {\n return false;\n }\n }));\n const ok = results.filter(Boolean).length;\n status[fam] = ok === defs.length ? 'loaded' : ok ? `partial ${ok}/${defs.length}` : 'missing';\n if (!ok) warn(`font unavailable, renderer would fall back: ${fam}`);\n }\n return status;\n }\n\n function loadImage(src) {\n return new Promise((res, rej) => {\n const img = new Image();\n img.onload = () => res(img);\n img.onerror = () => rej(new Error('image failed: ' + src));\n img.src = src;\n });\n }\n\n function resolveTheme(params) {\n const kits = window.EB_THEMES || {};\n const id = q.get('theme') || params.theme || Object.keys(kits)[0];\n const kit = kits[id] || kits[Object.keys(kits)[0]];\n const brand = params.brand || {};\n const C = { ...kit.colors, ...(brand.colors || {}) };\n C.series = brand.series || kit.series;\n const F = {};\n for (const role of new Set(['display', 'text', 'heavy', 'mono', 'hand', ...Object.keys(brand.fonts || {})])) F[role] = { ...(kit.fonts[role] || kit.fonts.text), ...((brand.fonts || {})[role] || {}) };\n return { id, kit, C, F };\n }\n\n window.EB = {\n RATIOS,\n scene(def) {\n const warnings = new Set();\n const warn = m => { warnings.add(m); if (q.get(\"demo\") !== \"1\") throw new Error(m); };\n try {\n void boot(def, warn, warnings).catch(e => { window.__motionError = String(e && e.stack || e); console.error(window.__motionError); });\n } catch (e) {\n window.__motionError = String(e && e.stack || e);\n throw e;\n }\n },\n };\n\n async function boot(def, warn, warnings) {\n const P = readParams();\n const ratio = q.get('ratio') || P.ratio || 'wide';\n const [W, H] = RATIOS[ratio] || RATIOS.wide;\n const { id: themeId, C, F } = resolveTheme(P);\n const timeScale = P.timeScale || 1;\n const duration = (P.duration || def.duration || 10) * timeScale;\n const fps = P.fps || 30;\n\n document.documentElement.style.background = capture ? C.bg : '#0b0b0a';\n document.body.style.margin = '0';\n const canvas = document.createElement('canvas');\n canvas.id = 'stage';\n canvas.width = W;\n canvas.height = H;\n const ctx = canvas.getContext('2d');\n\n const S = {\n W, H, ratio, P, C, F, themeId, fps, duration, timeScale,\n u: Math.min(W, H) / 1080, // 1 unit = 1px at 1080 short side\n wide: ratio === 'wide', square: ratio === 'square', tall: ratio === 'tall',\n warn, lib: LIB_BASE, frame: 0, images: {}, beats: P.beats || {},\n };\n S.pick = (wide, square, tall) => (S.tall ? tall : S.square ? square : wide);\n\n const fontStatus = await loadFonts(F, warn);\n if (Object.values(fontStatus).some(value => value !== \"loaded\")) throw new Error(\"All registered font faces must load; fallback is not permitted.\");\n for (const [k, rel] of Object.entries(P.media || {})) {\n try { S.images[k] = await loadImage(new URL(rel, location.href).href); } catch (e) { warn(String(e.message)); }\n }\n if (def.setup) await def.setup(S, ctx);\n\n // Scenes with external frames (video clips) define `prepare(t, S)`; renderAt then returns a\n // promise that resolves after those frames are decoded, so captures stay frame-exact.\n function renderAt(t) {\n t = Math.max(0, Math.min(duration, t));\n if (def.prepare) {\n const token = (S._token = (S._token || 0) + 1);\n return Promise.resolve(def.prepare(t / timeScale, S)).then(() => (token === S._token ? paint(t) : false));\n }\n return paint(t);\n }\n function paint(t) {\n S.frame = Math.round(t * fps);\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.globalAlpha = 1;\n ctx.globalCompositeOperation = 'source-over';\n ctx.fillStyle = C.bg;\n ctx.fillRect(0, 0, W, H);\n def.draw(ctx, t / timeScale, S);\n return true;\n }\n\n const beatTime = v => (typeof v === 'number' ? v : (S.beats[v] ?? 0));\n // cues from params plus cues the scene derives from its own data (def.cues)\n const rawCues = P.sound?.enabled === false ? [] : [...((P.sound && P.sound.cues) || []), ...(def.cues ? def.cues(S) : [])];\n const cues = rawCues.map(c => ({\n t: +((beatTime(c.at) + (c.offset || 0)) * timeScale).toFixed(4),\n sfx: c.sfx, file: c.file, dur: c.dur, trim: c.trim, gain: c.gain ?? (c.file ? 0.3 : 1),\n })).sort((a, b) => a.t - b.t);\n\n window.renderAt = renderAt;\n window.__sceneMeta = { id: def.id, W, H, ratio, fps, duration, frames: Math.round(duration * fps), theme: themeId, cues, timeScale, music: P.sound?.enabled === false ? null : P.sound?.music || null, voice: P.sound?.enabled === false ? null : P.sound?.voice || null, loudness: P.sound?.enabled === false ? null : P.sound?.loudness || null };\n window.getDiagnostics = () => ({ fonts: fontStatus, warnings: [...warnings], meta: window.__sceneMeta });\n\n document.body.appendChild(canvas);\n if (capture) {\n canvas.style.cssText = 'display:block';\n await renderAt(+(q.get('t') || 0));\n window.__ready = true;\n return;\n }\n preview(canvas, renderAt, S, cues);\n window.__ready = true;\n }\n\n // ---------- interactive preview (never used for rendering) ----------\n function preview(canvas, renderAt, S, cues) {\n const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;\n const showControls = q.get('controls') !== '0';\n const style = document.createElement('style');\n style.textContent = `\n body{height:100vh;display:flex;flex-direction:column;font:13px/1.3 -apple-system,system-ui,sans-serif;color:#e9e4da;background:#0b0b0a}\n #wrap{flex:1;display:flex;align-items:center;justify-content:center;min-height:0;padding:${showControls ? '12px' : '0'}}\n #stage{max-width:100%;max-height:100%;width:auto;height:auto;box-shadow:0 10px 40px rgba(0,0,0,.45)}\n #bar{display:flex;gap:10px;align-items:center;padding:10px 14px;background:#151412;border-top:1px solid #2a2824;flex-wrap:wrap}\n #bar button,#bar select{background:#24221f;color:#e9e4da;border:1px solid #3a3732;border-radius:6px;padding:5px 9px;font:inherit;cursor:pointer}\n #bar button.on{background:#E89A4A;color:#1b1a18;border-color:#E89A4A}\n #bar input[type=range]{flex:1;min-width:160px;accent-color:#E89A4A}\n #tm{font-variant-numeric:tabular-nums;min-width:92px}`;\n document.head.appendChild(style);\n const wrap = document.createElement('div');\n wrap.id = 'wrap';\n document.body.appendChild(wrap);\n wrap.appendChild(canvas);\n\n let t = q.has('t') ? +q.get('t') : reduced ? (S.P.reducedHold ?? S.duration * 0.9) : 0;\n let playing = !reduced && q.get('autoplay') === '1';\n let last = null;\n let sound = q.get('sound') === '1';\n const audio = audioEngine(cues, S);\n\n let range, tm, playBtn, soundBtn;\n if (showControls) {\n const bar = document.createElement('div');\n bar.id = 'bar';\n bar.innerHTML = `<button id=\"pp\"></button><input id=\"rg\" type=\"range\" min=\"0\" max=\"${S.duration}\" step=\"${1 / S.fps}\"><span id=\"tm\"></span>\n <span>${['wide', 'square', 'tall'].map(r => `<button data-r=\"${r}\" class=\"${r === S.ratio ? 'on' : ''}\">${{ wide: '16:9', square: '1:1', tall: '9:16' }[r]}</button>`).join(' ')}</span>\n <select id=\"th\">${Object.entries(window.EB_THEMES).map(([k, v]) => `<option value=\"${k}\" ${k === S.themeId ? 'selected' : ''}>${v.label}</option>`).join('')}</select>\n <button id=\"snd\"></button>`;\n document.body.appendChild(bar);\n range = bar.querySelector('#rg');\n tm = bar.querySelector('#tm');\n playBtn = bar.querySelector('#pp');\n soundBtn = bar.querySelector('#snd');\n const go = (k, v) => { const u = new URL(location.href); u.searchParams.set(k, v); u.searchParams.delete('t'); location.href = u.href; };\n bar.querySelectorAll('[data-r]').forEach(b => b.onclick = () => go('ratio', b.dataset.r));\n bar.querySelector('#th').onchange = e => go('theme', e.target.value);\n playBtn.onclick = toggle;\n soundBtn.onclick = () => { sound = !sound; audio.stop(); if (sound && playing) audio.start(t); sync(); };\n range.oninput = () => { t = +range.value; audio.stop(); if (playing && sound) audio.start(t); draw(); };\n }\n addEventListener('keydown', e => { if (e.code === 'Space') { e.preventDefault(); toggle(); } });\n canvas.onclick = toggle;\n function toggle() {\n playing = !playing;\n if (playing && t >= S.duration - 0.01) t = 0;\n last = null;\n audio.stop();\n if (playing && sound) audio.start(t);\n sync();\n }\n function sync() {\n if (!showControls) return;\n playBtn.textContent = playing ? 'Pausa' : 'Reproducir';\n soundBtn.textContent = sound ? 'Sonido: s\xED' : 'Sonido: no';\n soundBtn.className = sound ? 'on' : '';\n soundBtn.disabled = !cues.length;\n if (!cues.length) soundBtn.textContent = 'Sin sonido';\n }\n function draw() {\n renderAt(t);\n if (showControls) {\n range.value = t;\n tm.textContent = `${t.toFixed(2)} / ${S.duration.toFixed(1)} s`;\n }\n }\n // Pause off-screen / hidden tabs.\n let visible = true;\n new IntersectionObserver(es => { visible = es[0].isIntersecting; }).observe(canvas);\n function loop(now) {\n if (playing && visible && !document.hidden) {\n if (last !== null) t += (now - last) / 1000;\n if (t >= S.duration) {\n t = q.get('loop') === '0' ? S.duration : 0;\n if (q.get('loop') === '0') playing = false;\n audio.stop();\n if (playing && sound) audio.start(t);\n }\n draw();\n }\n last = playing ? now : null;\n requestAnimationFrame(loop);\n }\n sync();\n draw();\n requestAnimationFrame(loop);\n }\n\n // Preview-only audio: schedules the scene's cues from the synthesized SFX bank.\n function audioEngine(cues, S) {\n let ac = null, nodes = [];\n const buffers = {};\n async function buf(name) {\n if (!buffers[name]) {\n const r = await fetch(new URL(`sfx/${name}.wav`, S.lib));\n buffers[name] = await ac.decodeAudioData(await r.arrayBuffer());\n }\n return buffers[name];\n }\n return {\n async start(from) {\n if (!cues.length) return;\n ac = ac || new AudioContext();\n const t0 = ac.currentTime + 0.05;\n for (const c of cues) {\n if (c.t < from - 0.02) continue;\n const b = await buf(c.sfx);\n const src = ac.createBufferSource(), g = ac.createGain();\n src.buffer = b;\n g.gain.value = c.gain;\n src.connect(g).connect(ac.destination);\n src.start(t0 + (c.t - from));\n nodes.push(src);\n }\n },\n stop() { nodes.forEach(n => { try { n.stop(); } catch (e) {} }); nodes = []; },\n };\n }\n})();\n",
183154
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
183155
+ (function () {
183156
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
183157
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
183158
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
183159
+ const fonts = ['display','text','heavy','mono','hand'];
183160
+ window.EB_VALIDATE_PARAMS = (p, q) => {
183161
+ const theme = q.get('theme') || p.theme;
183162
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
183163
+ const ratio = q.get('ratio') || p.ratio || 'wide';
183164
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
183165
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
183166
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
183167
+ }
183168
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
183169
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
183170
+ if (q.get('demo') === '1') return;
183171
+ const b = window.__overrides?.brand;
183172
+ if (!record(b) || !record(b.colors) || !record(b.fonts)) fail('provide complete window.__overrides.brand from the selected project; demo themes are not customer defaults');
183173
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
183174
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
183175
+ if (!Array.isArray(b.series) || b.series.length < 6 || b.series.some(c => !/^#[0-9a-f]{6}$/i.test(c))) fail('provide at least six explicit series hex colors; roles may repeat project colors but never inherit demo colors');
183176
+ for (const role of fonts) {
183177
+ const font = b.fonts[role];
183178
+ if (!record(font) || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) fail('provide explicit family, weight and style for font role ' + role);
183179
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
183180
+ }
183181
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
183182
+ };
183183
+ })();
183184
+
183185
+ (function () {
183186
+ const base = window.EB_VALIDATE_PARAMS;
183187
+ const roles = ["accent","bg","glow","highlight","light","paper","paperInk","shadow"];
183188
+ const fontRoles = ["cond","credit","paperHead","paperMark","paperSans","paperSerif","sign"];
183189
+ window.EB_VALIDATE_PARAMS = (params, query) => {
183190
+ base(params, query);
183191
+ if (query.get('demo') === '1') return;
183192
+ for (const role of roles) {
183193
+ if (!/^#[0-9a-f]{6}$/i.test(window.__overrides?.brand?.colors?.[role] || '')) throw new Error('EditorBrain project binding: provide scene-specific color role ' + role + '; never inherit demo/preset brand colors.');
183194
+ }
183195
+ for (const role of fontRoles) {
183196
+ const font = window.__overrides?.brand?.fonts?.[role];
183197
+ if (!font || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) throw new Error('EditorBrain project binding: provide complete scene-specific font role ' + role + '; never inherit demo/preset typography.');
183198
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183199
+ }
183200
+ };
183201
+ })();
183202
+ `
183203
+ },
183204
+ "catalogo-editorial": {
183205
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
183206
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
183207
+ "runtime": "// EditorBrain authored motion \xB7 scene runtime.\n// One canvas, explicit time: window.renderAt(seconds) draws the exact state for that time.\n// URL: ?ratio=wide|square|tall &theme=<kit> &t=<sec> &capture=1 &autoplay=1 &controls=0\n(function () {\n const RATIOS = { wide: [1920, 1080], square: [1080, 1080], tall: [1080, 1920] };\n const LIB_BASE = new URL('..', document.currentScript.src).href; // library root\n const q = new URLSearchParams(location.search);\n const capture = q.get('capture') === '1';\n\n const isObj = v => v && typeof v === 'object' && !Array.isArray(v);\n const merge = (a, b) => {\n if (!isObj(b)) return b === undefined ? a : b;\n const out = { ...(isObj(a) ? a : {}) };\n for (const k of Object.keys(b)) out[k] = merge(out[k], b[k]);\n return out;\n };\n\n function readParams() {\n const el = document.getElementById('params');\n let p = el ? JSON.parse(el.textContent) : {};\n if (window.__overrides) p = merge(p, window.__overrides);\n const enc = q.get('params');\n if (enc) { const supplied = JSON.parse(decodeURIComponent(escape(atob(enc)))); window.__overrides = merge(window.__overrides || {}, supplied); p = merge(p, supplied); }\n window.EB_VALIDATE_PARAMS(p, q);\n return p;\n }\n\n async function loadFonts(F, warn) {\n const families = new Set(Object.values(F).map(f => f.family));\n const status = {};\n for (const fam of families) {\n const defs = (window.EB_FONTS || {})[fam];\n if (!defs) {\n status[fam] = 'not-registered';\n warn(`font family not registered: ${fam}`);\n continue;\n }\n const results = await Promise.all(defs.map(async d => {\n const src = d.local ? d.local.map(n => `local(\"${n}\")`).join(', ') : `url(\"${new URL(d.src, LIB_BASE).href}\")`;\n const desc = {};\n if (d.weight) desc.weight = d.weight;\n if (d.style) desc.style = d.style;\n if (d.stretch) desc.stretch = d.stretch;\n try {\n const face = new FontFace(fam, src, desc);\n await face.load();\n document.fonts.add(face);\n return true;\n } catch (e) {\n return false;\n }\n }));\n const ok = results.filter(Boolean).length;\n status[fam] = ok === defs.length ? 'loaded' : ok ? `partial ${ok}/${defs.length}` : 'missing';\n if (!ok) warn(`font unavailable, renderer would fall back: ${fam}`);\n }\n return status;\n }\n\n function loadImage(src) {\n return new Promise((res, rej) => {\n const img = new Image();\n img.onload = () => res(img);\n img.onerror = () => rej(new Error('image failed: ' + src));\n img.src = src;\n });\n }\n\n function resolveTheme(params) {\n const kits = window.EB_THEMES || {};\n const id = q.get('theme') || params.theme || Object.keys(kits)[0];\n const kit = kits[id] || kits[Object.keys(kits)[0]];\n const brand = params.brand || {};\n const C = { ...kit.colors, ...(brand.colors || {}) };\n C.series = brand.series || kit.series;\n const F = {};\n for (const role of new Set(['display', 'text', 'heavy', 'mono', 'hand', ...Object.keys(brand.fonts || {})])) F[role] = { ...(kit.fonts[role] || kit.fonts.text), ...((brand.fonts || {})[role] || {}) };\n return { id, kit, C, F };\n }\n\n window.EB = {\n RATIOS,\n scene(def) {\n const warnings = new Set();\n const warn = m => { warnings.add(m); if (q.get(\"demo\") !== \"1\") throw new Error(m); };\n try {\n void boot(def, warn, warnings).catch(e => { window.__motionError = String(e && e.stack || e); console.error(window.__motionError); });\n } catch (e) {\n window.__motionError = String(e && e.stack || e);\n throw e;\n }\n },\n };\n\n async function boot(def, warn, warnings) {\n const P = readParams();\n const ratio = q.get('ratio') || P.ratio || 'wide';\n const [W, H] = RATIOS[ratio] || RATIOS.wide;\n const { id: themeId, C, F } = resolveTheme(P);\n const timeScale = P.timeScale || 1;\n const duration = (P.duration || def.duration || 10) * timeScale;\n const fps = P.fps || 30;\n\n document.documentElement.style.background = capture ? C.bg : '#0b0b0a';\n document.body.style.margin = '0';\n const canvas = document.createElement('canvas');\n canvas.id = 'stage';\n canvas.width = W;\n canvas.height = H;\n const ctx = canvas.getContext('2d');\n\n const S = {\n W, H, ratio, P, C, F, themeId, fps, duration, timeScale,\n u: Math.min(W, H) / 1080, // 1 unit = 1px at 1080 short side\n wide: ratio === 'wide', square: ratio === 'square', tall: ratio === 'tall',\n warn, lib: LIB_BASE, frame: 0, images: {}, beats: P.beats || {},\n };\n S.pick = (wide, square, tall) => (S.tall ? tall : S.square ? square : wide);\n\n const fontStatus = await loadFonts(F, warn);\n if (Object.values(fontStatus).some(value => value !== \"loaded\")) throw new Error(\"All registered font faces must load; fallback is not permitted.\");\n for (const [k, rel] of Object.entries(P.media || {})) {\n try { S.images[k] = await loadImage(new URL(rel, location.href).href); } catch (e) { warn(String(e.message)); }\n }\n if (def.setup) await def.setup(S, ctx);\n\n // Scenes with external frames (video clips) define `prepare(t, S)`; renderAt then returns a\n // promise that resolves after those frames are decoded, so captures stay frame-exact.\n function renderAt(t) {\n t = Math.max(0, Math.min(duration, t));\n if (def.prepare) {\n const token = (S._token = (S._token || 0) + 1);\n return Promise.resolve(def.prepare(t / timeScale, S)).then(() => (token === S._token ? paint(t) : false));\n }\n return paint(t);\n }\n function paint(t) {\n S.frame = Math.round(t * fps);\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.globalAlpha = 1;\n ctx.globalCompositeOperation = 'source-over';\n ctx.fillStyle = C.bg;\n ctx.fillRect(0, 0, W, H);\n def.draw(ctx, t / timeScale, S);\n return true;\n }\n\n const beatTime = v => (typeof v === 'number' ? v : (S.beats[v] ?? 0));\n // cues from params plus cues the scene derives from its own data (def.cues)\n const rawCues = P.sound?.enabled === false ? [] : [...((P.sound && P.sound.cues) || []), ...(def.cues ? def.cues(S) : [])];\n const cues = rawCues.map(c => ({\n t: +((beatTime(c.at) + (c.offset || 0)) * timeScale).toFixed(4),\n sfx: c.sfx, file: c.file, dur: c.dur, trim: c.trim, gain: c.gain ?? (c.file ? 0.3 : 1),\n })).sort((a, b) => a.t - b.t);\n\n window.renderAt = renderAt;\n window.__sceneMeta = { id: def.id, W, H, ratio, fps, duration, frames: Math.round(duration * fps), theme: themeId, cues, timeScale, music: P.sound?.enabled === false ? null : P.sound?.music || null, voice: P.sound?.enabled === false ? null : P.sound?.voice || null, loudness: P.sound?.enabled === false ? null : P.sound?.loudness || null };\n window.getDiagnostics = () => ({ fonts: fontStatus, warnings: [...warnings], meta: window.__sceneMeta });\n\n document.body.appendChild(canvas);\n if (capture) {\n canvas.style.cssText = 'display:block';\n await renderAt(+(q.get('t') || 0));\n window.__ready = true;\n return;\n }\n preview(canvas, renderAt, S, cues);\n window.__ready = true;\n }\n\n // ---------- interactive preview (never used for rendering) ----------\n function preview(canvas, renderAt, S, cues) {\n const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;\n const showControls = q.get('controls') !== '0';\n const style = document.createElement('style');\n style.textContent = `\n body{height:100vh;display:flex;flex-direction:column;font:13px/1.3 -apple-system,system-ui,sans-serif;color:#e9e4da;background:#0b0b0a}\n #wrap{flex:1;display:flex;align-items:center;justify-content:center;min-height:0;padding:${showControls ? '12px' : '0'}}\n #stage{max-width:100%;max-height:100%;width:auto;height:auto;box-shadow:0 10px 40px rgba(0,0,0,.45)}\n #bar{display:flex;gap:10px;align-items:center;padding:10px 14px;background:#151412;border-top:1px solid #2a2824;flex-wrap:wrap}\n #bar button,#bar select{background:#24221f;color:#e9e4da;border:1px solid #3a3732;border-radius:6px;padding:5px 9px;font:inherit;cursor:pointer}\n #bar button.on{background:#E89A4A;color:#1b1a18;border-color:#E89A4A}\n #bar input[type=range]{flex:1;min-width:160px;accent-color:#E89A4A}\n #tm{font-variant-numeric:tabular-nums;min-width:92px}`;\n document.head.appendChild(style);\n const wrap = document.createElement('div');\n wrap.id = 'wrap';\n document.body.appendChild(wrap);\n wrap.appendChild(canvas);\n\n let t = q.has('t') ? +q.get('t') : reduced ? (S.P.reducedHold ?? S.duration * 0.9) : 0;\n let playing = !reduced && q.get('autoplay') === '1';\n let last = null;\n let sound = q.get('sound') === '1';\n const audio = audioEngine(cues, S);\n\n let range, tm, playBtn, soundBtn;\n if (showControls) {\n const bar = document.createElement('div');\n bar.id = 'bar';\n bar.innerHTML = `<button id=\"pp\"></button><input id=\"rg\" type=\"range\" min=\"0\" max=\"${S.duration}\" step=\"${1 / S.fps}\"><span id=\"tm\"></span>\n <span>${['wide', 'square', 'tall'].map(r => `<button data-r=\"${r}\" class=\"${r === S.ratio ? 'on' : ''}\">${{ wide: '16:9', square: '1:1', tall: '9:16' }[r]}</button>`).join(' ')}</span>\n <select id=\"th\">${Object.entries(window.EB_THEMES).map(([k, v]) => `<option value=\"${k}\" ${k === S.themeId ? 'selected' : ''}>${v.label}</option>`).join('')}</select>\n <button id=\"snd\"></button>`;\n document.body.appendChild(bar);\n range = bar.querySelector('#rg');\n tm = bar.querySelector('#tm');\n playBtn = bar.querySelector('#pp');\n soundBtn = bar.querySelector('#snd');\n const go = (k, v) => { const u = new URL(location.href); u.searchParams.set(k, v); u.searchParams.delete('t'); location.href = u.href; };\n bar.querySelectorAll('[data-r]').forEach(b => b.onclick = () => go('ratio', b.dataset.r));\n bar.querySelector('#th').onchange = e => go('theme', e.target.value);\n playBtn.onclick = toggle;\n soundBtn.onclick = () => { sound = !sound; audio.stop(); if (sound && playing) audio.start(t); sync(); };\n range.oninput = () => { t = +range.value; audio.stop(); if (playing && sound) audio.start(t); draw(); };\n }\n addEventListener('keydown', e => { if (e.code === 'Space') { e.preventDefault(); toggle(); } });\n canvas.onclick = toggle;\n function toggle() {\n playing = !playing;\n if (playing && t >= S.duration - 0.01) t = 0;\n last = null;\n audio.stop();\n if (playing && sound) audio.start(t);\n sync();\n }\n function sync() {\n if (!showControls) return;\n playBtn.textContent = playing ? 'Pausa' : 'Reproducir';\n soundBtn.textContent = sound ? 'Sonido: s\xED' : 'Sonido: no';\n soundBtn.className = sound ? 'on' : '';\n soundBtn.disabled = !cues.length;\n if (!cues.length) soundBtn.textContent = 'Sin sonido';\n }\n function draw() {\n renderAt(t);\n if (showControls) {\n range.value = t;\n tm.textContent = `${t.toFixed(2)} / ${S.duration.toFixed(1)} s`;\n }\n }\n // Pause off-screen / hidden tabs.\n let visible = true;\n new IntersectionObserver(es => { visible = es[0].isIntersecting; }).observe(canvas);\n function loop(now) {\n if (playing && visible && !document.hidden) {\n if (last !== null) t += (now - last) / 1000;\n if (t >= S.duration) {\n t = q.get('loop') === '0' ? S.duration : 0;\n if (q.get('loop') === '0') playing = false;\n audio.stop();\n if (playing && sound) audio.start(t);\n }\n draw();\n }\n last = playing ? now : null;\n requestAnimationFrame(loop);\n }\n sync();\n draw();\n requestAnimationFrame(loop);\n }\n\n // Preview-only audio: schedules the scene's cues from the synthesized SFX bank.\n function audioEngine(cues, S) {\n let ac = null, nodes = [];\n const buffers = {};\n async function buf(name) {\n if (!buffers[name]) {\n const r = await fetch(new URL(`sfx/${name}.wav`, S.lib));\n buffers[name] = await ac.decodeAudioData(await r.arrayBuffer());\n }\n return buffers[name];\n }\n return {\n async start(from) {\n if (!cues.length) return;\n ac = ac || new AudioContext();\n const t0 = ac.currentTime + 0.05;\n for (const c of cues) {\n if (c.t < from - 0.02) continue;\n const b = await buf(c.sfx);\n const src = ac.createBufferSource(), g = ac.createGain();\n src.buffer = b;\n g.gain.value = c.gain;\n src.connect(g).connect(ac.destination);\n src.start(t0 + (c.t - from));\n nodes.push(src);\n }\n },\n stop() { nodes.forEach(n => { try { n.stop(); } catch (e) {} }); nodes = []; },\n };\n }\n})();\n",
183208
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
183209
+ (function () {
183210
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
183211
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
183212
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
183213
+ const fonts = ['display','text','heavy','mono','hand'];
183214
+ window.EB_VALIDATE_PARAMS = (p, q) => {
183215
+ const theme = q.get('theme') || p.theme;
183216
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
183217
+ const ratio = q.get('ratio') || p.ratio || 'wide';
183218
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
183219
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
183220
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
183221
+ }
183222
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
183223
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
183224
+ if (q.get('demo') === '1') return;
183225
+ const b = window.__overrides?.brand;
183226
+ if (!record(b) || !record(b.colors) || !record(b.fonts)) fail('provide complete window.__overrides.brand from the selected project; demo themes are not customer defaults');
183227
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
183228
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
183229
+ if (!Array.isArray(b.series) || b.series.length < 6 || b.series.some(c => !/^#[0-9a-f]{6}$/i.test(c))) fail('provide at least six explicit series hex colors; roles may repeat project colors but never inherit demo colors');
183230
+ for (const role of fonts) {
183231
+ const font = b.fonts[role];
183232
+ if (!record(font) || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) fail('provide explicit family, weight and style for font role ' + role);
183233
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
183234
+ }
183235
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
183236
+ };
183237
+ })();
183238
+
183239
+ (function () {
183240
+ const base = window.EB_VALIDATE_PARAMS;
183241
+ const roles = ["accent","bg","cta","doc","docAccent","docGap","docMint","docNavy","field","fieldGlow","fieldInk","icon","ink","line","muted","rule","sheet","soft","title"];
183242
+ const fontRoles = ["alt1","alt2","hand","label","sans","serif","small"];
183243
+ window.EB_VALIDATE_PARAMS = (params, query) => {
183244
+ base(params, query);
183245
+ if (query.get('demo') === '1') return;
183246
+ for (const role of roles) {
183247
+ if (!/^#[0-9a-f]{6}$/i.test(window.__overrides?.brand?.colors?.[role] || '')) throw new Error('EditorBrain project binding: provide scene-specific color role ' + role + '; never inherit demo/preset brand colors.');
183248
+ }
183249
+ for (const role of fontRoles) {
183250
+ const font = window.__overrides?.brand?.fonts?.[role];
183251
+ if (!font || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) throw new Error('EditorBrain project binding: provide complete scene-specific font role ' + role + '; never inherit demo/preset typography.');
183252
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183253
+ }
183254
+ };
183255
+ })();
183256
+ `
183257
+ },
183258
+ "pantalla-fisica": {
183259
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
183260
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
183261
+ "runtime": "// EditorBrain authored motion \xB7 scene runtime.\n// One canvas, explicit time: window.renderAt(seconds) draws the exact state for that time.\n// URL: ?ratio=wide|square|tall &theme=<kit> &t=<sec> &capture=1 &autoplay=1 &controls=0\n(function () {\n const RATIOS = { wide: [1920, 1080], square: [1080, 1080], tall: [1080, 1920] };\n const LIB_BASE = new URL('..', document.currentScript.src).href; // library root\n const q = new URLSearchParams(location.search);\n const capture = q.get('capture') === '1';\n\n const isObj = v => v && typeof v === 'object' && !Array.isArray(v);\n const merge = (a, b) => {\n if (!isObj(b)) return b === undefined ? a : b;\n const out = { ...(isObj(a) ? a : {}) };\n for (const k of Object.keys(b)) out[k] = merge(out[k], b[k]);\n return out;\n };\n\n function readParams() {\n const el = document.getElementById('params');\n let p = el ? JSON.parse(el.textContent) : {};\n if (window.__overrides) p = merge(p, window.__overrides);\n const enc = q.get('params');\n if (enc) { const supplied = JSON.parse(decodeURIComponent(escape(atob(enc)))); window.__overrides = merge(window.__overrides || {}, supplied); p = merge(p, supplied); }\n window.EB_VALIDATE_PARAMS(p, q);\n return p;\n }\n\n async function loadFonts(F, warn) {\n const families = new Set(Object.values(F).map(f => f.family));\n const status = {};\n for (const fam of families) {\n const defs = (window.EB_FONTS || {})[fam];\n if (!defs) {\n status[fam] = 'not-registered';\n warn(`font family not registered: ${fam}`);\n continue;\n }\n const results = await Promise.all(defs.map(async d => {\n const src = d.local ? d.local.map(n => `local(\"${n}\")`).join(', ') : `url(\"${new URL(d.src, LIB_BASE).href}\")`;\n const desc = {};\n if (d.weight) desc.weight = d.weight;\n if (d.style) desc.style = d.style;\n if (d.stretch) desc.stretch = d.stretch;\n try {\n const face = new FontFace(fam, src, desc);\n await face.load();\n document.fonts.add(face);\n return true;\n } catch (e) {\n return false;\n }\n }));\n const ok = results.filter(Boolean).length;\n status[fam] = ok === defs.length ? 'loaded' : ok ? `partial ${ok}/${defs.length}` : 'missing';\n if (!ok) warn(`font unavailable, renderer would fall back: ${fam}`);\n }\n return status;\n }\n\n function loadImage(src) {\n return new Promise((res, rej) => {\n const img = new Image();\n img.onload = () => res(img);\n img.onerror = () => rej(new Error('image failed: ' + src));\n img.src = src;\n });\n }\n\n function resolveTheme(params) {\n const kits = window.EB_THEMES || {};\n const id = q.get('theme') || params.theme || Object.keys(kits)[0];\n const kit = kits[id] || kits[Object.keys(kits)[0]];\n const brand = params.brand || {};\n const C = { ...kit.colors, ...(brand.colors || {}) };\n C.series = brand.series || kit.series;\n const F = {};\n for (const role of new Set(['display', 'text', 'heavy', 'mono', 'hand', ...Object.keys(brand.fonts || {})])) F[role] = { ...(kit.fonts[role] || kit.fonts.text), ...((brand.fonts || {})[role] || {}) };\n return { id, kit, C, F };\n }\n\n window.EB = {\n RATIOS,\n scene(def) {\n const warnings = new Set();\n const warn = m => { warnings.add(m); if (q.get(\"demo\") !== \"1\") throw new Error(m); };\n try {\n void boot(def, warn, warnings).catch(e => { window.__motionError = String(e && e.stack || e); console.error(window.__motionError); });\n } catch (e) {\n window.__motionError = String(e && e.stack || e);\n throw e;\n }\n },\n };\n\n async function boot(def, warn, warnings) {\n const P = readParams();\n const ratio = q.get('ratio') || P.ratio || 'wide';\n const [W, H] = RATIOS[ratio] || RATIOS.wide;\n const { id: themeId, C, F } = resolveTheme(P);\n const timeScale = P.timeScale || 1;\n const duration = (P.duration || def.duration || 10) * timeScale;\n const fps = P.fps || 30;\n\n document.documentElement.style.background = capture ? C.bg : '#0b0b0a';\n document.body.style.margin = '0';\n const canvas = document.createElement('canvas');\n canvas.id = 'stage';\n canvas.width = W;\n canvas.height = H;\n const ctx = canvas.getContext('2d');\n\n const S = {\n W, H, ratio, P, C, F, themeId, fps, duration, timeScale,\n u: Math.min(W, H) / 1080, // 1 unit = 1px at 1080 short side\n wide: ratio === 'wide', square: ratio === 'square', tall: ratio === 'tall',\n warn, lib: LIB_BASE, frame: 0, images: {}, beats: P.beats || {},\n };\n S.pick = (wide, square, tall) => (S.tall ? tall : S.square ? square : wide);\n\n const fontStatus = await loadFonts(F, warn);\n if (Object.values(fontStatus).some(value => value !== \"loaded\")) throw new Error(\"All registered font faces must load; fallback is not permitted.\");\n for (const [k, rel] of Object.entries(P.media || {})) {\n try { S.images[k] = await loadImage(new URL(rel, location.href).href); } catch (e) { warn(String(e.message)); }\n }\n if (def.setup) await def.setup(S, ctx);\n\n // Scenes with external frames (video clips) define `prepare(t, S)`; renderAt then returns a\n // promise that resolves after those frames are decoded, so captures stay frame-exact.\n function renderAt(t) {\n t = Math.max(0, Math.min(duration, t));\n if (def.prepare) {\n const token = (S._token = (S._token || 0) + 1);\n return Promise.resolve(def.prepare(t / timeScale, S)).then(() => (token === S._token ? paint(t) : false));\n }\n return paint(t);\n }\n function paint(t) {\n S.frame = Math.round(t * fps);\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.globalAlpha = 1;\n ctx.globalCompositeOperation = 'source-over';\n ctx.fillStyle = C.bg;\n ctx.fillRect(0, 0, W, H);\n def.draw(ctx, t / timeScale, S);\n return true;\n }\n\n const beatTime = v => (typeof v === 'number' ? v : (S.beats[v] ?? 0));\n // cues from params plus cues the scene derives from its own data (def.cues)\n const rawCues = P.sound?.enabled === false ? [] : [...((P.sound && P.sound.cues) || []), ...(def.cues ? def.cues(S) : [])];\n const cues = rawCues.map(c => ({\n t: +((beatTime(c.at) + (c.offset || 0)) * timeScale).toFixed(4),\n sfx: c.sfx, file: c.file, dur: c.dur, trim: c.trim, gain: c.gain ?? (c.file ? 0.3 : 1),\n })).sort((a, b) => a.t - b.t);\n\n window.renderAt = renderAt;\n window.__sceneMeta = { id: def.id, W, H, ratio, fps, duration, frames: Math.round(duration * fps), theme: themeId, cues, timeScale, music: P.sound?.enabled === false ? null : P.sound?.music || null, voice: P.sound?.enabled === false ? null : P.sound?.voice || null, loudness: P.sound?.enabled === false ? null : P.sound?.loudness || null };\n window.getDiagnostics = () => ({ fonts: fontStatus, warnings: [...warnings], meta: window.__sceneMeta });\n\n document.body.appendChild(canvas);\n if (capture) {\n canvas.style.cssText = 'display:block';\n await renderAt(+(q.get('t') || 0));\n window.__ready = true;\n return;\n }\n preview(canvas, renderAt, S, cues);\n window.__ready = true;\n }\n\n // ---------- interactive preview (never used for rendering) ----------\n function preview(canvas, renderAt, S, cues) {\n const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;\n const showControls = q.get('controls') !== '0';\n const style = document.createElement('style');\n style.textContent = `\n body{height:100vh;display:flex;flex-direction:column;font:13px/1.3 -apple-system,system-ui,sans-serif;color:#e9e4da;background:#0b0b0a}\n #wrap{flex:1;display:flex;align-items:center;justify-content:center;min-height:0;padding:${showControls ? '12px' : '0'}}\n #stage{max-width:100%;max-height:100%;width:auto;height:auto;box-shadow:0 10px 40px rgba(0,0,0,.45)}\n #bar{display:flex;gap:10px;align-items:center;padding:10px 14px;background:#151412;border-top:1px solid #2a2824;flex-wrap:wrap}\n #bar button,#bar select{background:#24221f;color:#e9e4da;border:1px solid #3a3732;border-radius:6px;padding:5px 9px;font:inherit;cursor:pointer}\n #bar button.on{background:#E89A4A;color:#1b1a18;border-color:#E89A4A}\n #bar input[type=range]{flex:1;min-width:160px;accent-color:#E89A4A}\n #tm{font-variant-numeric:tabular-nums;min-width:92px}`;\n document.head.appendChild(style);\n const wrap = document.createElement('div');\n wrap.id = 'wrap';\n document.body.appendChild(wrap);\n wrap.appendChild(canvas);\n\n let t = q.has('t') ? +q.get('t') : reduced ? (S.P.reducedHold ?? S.duration * 0.9) : 0;\n let playing = !reduced && q.get('autoplay') === '1';\n let last = null;\n let sound = q.get('sound') === '1';\n const audio = audioEngine(cues, S);\n\n let range, tm, playBtn, soundBtn;\n if (showControls) {\n const bar = document.createElement('div');\n bar.id = 'bar';\n bar.innerHTML = `<button id=\"pp\"></button><input id=\"rg\" type=\"range\" min=\"0\" max=\"${S.duration}\" step=\"${1 / S.fps}\"><span id=\"tm\"></span>\n <span>${['wide', 'square', 'tall'].map(r => `<button data-r=\"${r}\" class=\"${r === S.ratio ? 'on' : ''}\">${{ wide: '16:9', square: '1:1', tall: '9:16' }[r]}</button>`).join(' ')}</span>\n <select id=\"th\">${Object.entries(window.EB_THEMES).map(([k, v]) => `<option value=\"${k}\" ${k === S.themeId ? 'selected' : ''}>${v.label}</option>`).join('')}</select>\n <button id=\"snd\"></button>`;\n document.body.appendChild(bar);\n range = bar.querySelector('#rg');\n tm = bar.querySelector('#tm');\n playBtn = bar.querySelector('#pp');\n soundBtn = bar.querySelector('#snd');\n const go = (k, v) => { const u = new URL(location.href); u.searchParams.set(k, v); u.searchParams.delete('t'); location.href = u.href; };\n bar.querySelectorAll('[data-r]').forEach(b => b.onclick = () => go('ratio', b.dataset.r));\n bar.querySelector('#th').onchange = e => go('theme', e.target.value);\n playBtn.onclick = toggle;\n soundBtn.onclick = () => { sound = !sound; audio.stop(); if (sound && playing) audio.start(t); sync(); };\n range.oninput = () => { t = +range.value; audio.stop(); if (playing && sound) audio.start(t); draw(); };\n }\n addEventListener('keydown', e => { if (e.code === 'Space') { e.preventDefault(); toggle(); } });\n canvas.onclick = toggle;\n function toggle() {\n playing = !playing;\n if (playing && t >= S.duration - 0.01) t = 0;\n last = null;\n audio.stop();\n if (playing && sound) audio.start(t);\n sync();\n }\n function sync() {\n if (!showControls) return;\n playBtn.textContent = playing ? 'Pausa' : 'Reproducir';\n soundBtn.textContent = sound ? 'Sonido: s\xED' : 'Sonido: no';\n soundBtn.className = sound ? 'on' : '';\n soundBtn.disabled = !cues.length;\n if (!cues.length) soundBtn.textContent = 'Sin sonido';\n }\n function draw() {\n renderAt(t);\n if (showControls) {\n range.value = t;\n tm.textContent = `${t.toFixed(2)} / ${S.duration.toFixed(1)} s`;\n }\n }\n // Pause off-screen / hidden tabs.\n let visible = true;\n new IntersectionObserver(es => { visible = es[0].isIntersecting; }).observe(canvas);\n function loop(now) {\n if (playing && visible && !document.hidden) {\n if (last !== null) t += (now - last) / 1000;\n if (t >= S.duration) {\n t = q.get('loop') === '0' ? S.duration : 0;\n if (q.get('loop') === '0') playing = false;\n audio.stop();\n if (playing && sound) audio.start(t);\n }\n draw();\n }\n last = playing ? now : null;\n requestAnimationFrame(loop);\n }\n sync();\n draw();\n requestAnimationFrame(loop);\n }\n\n // Preview-only audio: schedules the scene's cues from the synthesized SFX bank.\n function audioEngine(cues, S) {\n let ac = null, nodes = [];\n const buffers = {};\n async function buf(name) {\n if (!buffers[name]) {\n const r = await fetch(new URL(`sfx/${name}.wav`, S.lib));\n buffers[name] = await ac.decodeAudioData(await r.arrayBuffer());\n }\n return buffers[name];\n }\n return {\n async start(from) {\n if (!cues.length) return;\n ac = ac || new AudioContext();\n const t0 = ac.currentTime + 0.05;\n for (const c of cues) {\n if (c.t < from - 0.02) continue;\n const b = await buf(c.sfx);\n const src = ac.createBufferSource(), g = ac.createGain();\n src.buffer = b;\n g.gain.value = c.gain;\n src.connect(g).connect(ac.destination);\n src.start(t0 + (c.t - from));\n nodes.push(src);\n }\n },\n stop() { nodes.forEach(n => { try { n.stop(); } catch (e) {} }); nodes = []; },\n };\n }\n})();\n",
183262
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
183263
+ (function () {
183264
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
183265
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
183266
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
183267
+ const fonts = ['display','text','heavy','mono','hand'];
183268
+ window.EB_VALIDATE_PARAMS = (p, q) => {
183269
+ const theme = q.get('theme') || p.theme;
183270
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
183271
+ const ratio = q.get('ratio') || p.ratio || 'wide';
183272
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
183273
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
183274
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
183275
+ }
183276
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
183277
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
183278
+ if (q.get('demo') === '1') return;
183279
+ const b = window.__overrides?.brand;
183280
+ if (!record(b) || !record(b.colors) || !record(b.fonts)) fail('provide complete window.__overrides.brand from the selected project; demo themes are not customer defaults');
183281
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
183282
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
183283
+ if (!Array.isArray(b.series) || b.series.length < 6 || b.series.some(c => !/^#[0-9a-f]{6}$/i.test(c))) fail('provide at least six explicit series hex colors; roles may repeat project colors but never inherit demo colors');
183284
+ for (const role of fonts) {
183285
+ const font = b.fonts[role];
183286
+ if (!record(font) || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) fail('provide explicit family, weight and style for font role ' + role);
183287
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
183288
+ }
183289
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
183290
+ };
183291
+ })();
183292
+
183293
+ (function () {
183294
+ const base = window.EB_VALIDATE_PARAMS;
183295
+ const roles = ["bg","card","cardInk","cardLine","cardMuted","follow","following","light","panel","pos","ring1","ring2","shadow","wordmark"];
183296
+ const fontRoles = ["credit","heavy","serif","ui","uiBold","uiNum","uiText","wordmark"];
183297
+ window.EB_VALIDATE_PARAMS = (params, query) => {
183298
+ base(params, query);
183299
+ if (query.get('demo') === '1') return;
183300
+ for (const role of roles) {
183301
+ if (!/^#[0-9a-f]{6}$/i.test(window.__overrides?.brand?.colors?.[role] || '')) throw new Error('EditorBrain project binding: provide scene-specific color role ' + role + '; never inherit demo/preset brand colors.');
183302
+ }
183303
+ for (const role of fontRoles) {
183304
+ const font = window.__overrides?.brand?.fonts?.[role];
183305
+ if (!font || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) throw new Error('EditorBrain project binding: provide complete scene-specific font role ' + role + '; never inherit demo/preset typography.');
183306
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183307
+ }
183308
+ };
183309
+ })();
183310
+ `
183311
+ },
183312
+ "personaje-en-papel": {
183313
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
183314
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
183315
+ "runtime": "// EditorBrain authored motion \xB7 scene runtime.\n// One canvas, explicit time: window.renderAt(seconds) draws the exact state for that time.\n// URL: ?ratio=wide|square|tall &theme=<kit> &t=<sec> &capture=1 &autoplay=1 &controls=0\n(function () {\n const RATIOS = { wide: [1920, 1080], square: [1080, 1080], tall: [1080, 1920] };\n const LIB_BASE = new URL('..', document.currentScript.src).href; // library root\n const q = new URLSearchParams(location.search);\n const capture = q.get('capture') === '1';\n\n const isObj = v => v && typeof v === 'object' && !Array.isArray(v);\n const merge = (a, b) => {\n if (!isObj(b)) return b === undefined ? a : b;\n const out = { ...(isObj(a) ? a : {}) };\n for (const k of Object.keys(b)) out[k] = merge(out[k], b[k]);\n return out;\n };\n\n function readParams() {\n const el = document.getElementById('params');\n let p = el ? JSON.parse(el.textContent) : {};\n if (window.__overrides) p = merge(p, window.__overrides);\n const enc = q.get('params');\n if (enc) { const supplied = JSON.parse(decodeURIComponent(escape(atob(enc)))); window.__overrides = merge(window.__overrides || {}, supplied); p = merge(p, supplied); }\n window.EB_VALIDATE_PARAMS(p, q);\n return p;\n }\n\n async function loadFonts(F, warn) {\n const families = new Set(Object.values(F).map(f => f.family));\n const status = {};\n for (const fam of families) {\n const defs = (window.EB_FONTS || {})[fam];\n if (!defs) {\n status[fam] = 'not-registered';\n warn(`font family not registered: ${fam}`);\n continue;\n }\n const results = await Promise.all(defs.map(async d => {\n const src = d.local ? d.local.map(n => `local(\"${n}\")`).join(', ') : `url(\"${new URL(d.src, LIB_BASE).href}\")`;\n const desc = {};\n if (d.weight) desc.weight = d.weight;\n if (d.style) desc.style = d.style;\n if (d.stretch) desc.stretch = d.stretch;\n try {\n const face = new FontFace(fam, src, desc);\n await face.load();\n document.fonts.add(face);\n return true;\n } catch (e) {\n return false;\n }\n }));\n const ok = results.filter(Boolean).length;\n status[fam] = ok === defs.length ? 'loaded' : ok ? `partial ${ok}/${defs.length}` : 'missing';\n if (!ok) warn(`font unavailable, renderer would fall back: ${fam}`);\n }\n return status;\n }\n\n function loadImage(src) {\n return new Promise((res, rej) => {\n const img = new Image();\n img.onload = () => res(img);\n img.onerror = () => rej(new Error('image failed: ' + src));\n img.src = src;\n });\n }\n\n function resolveTheme(params) {\n const kits = window.EB_THEMES || {};\n const id = q.get('theme') || params.theme || Object.keys(kits)[0];\n const kit = kits[id] || kits[Object.keys(kits)[0]];\n const brand = params.brand || {};\n const C = { ...kit.colors, ...(brand.colors || {}) };\n C.series = brand.series || kit.series;\n const F = {};\n for (const role of new Set(['display', 'text', 'heavy', 'mono', 'hand', ...Object.keys(brand.fonts || {})])) F[role] = { ...(kit.fonts[role] || kit.fonts.text), ...((brand.fonts || {})[role] || {}) };\n return { id, kit, C, F };\n }\n\n window.EB = {\n RATIOS,\n scene(def) {\n const warnings = new Set();\n const warn = m => { warnings.add(m); if (q.get(\"demo\") !== \"1\") throw new Error(m); };\n try {\n void boot(def, warn, warnings).catch(e => { window.__motionError = String(e && e.stack || e); console.error(window.__motionError); });\n } catch (e) {\n window.__motionError = String(e && e.stack || e);\n throw e;\n }\n },\n };\n\n async function boot(def, warn, warnings) {\n const P = readParams();\n const ratio = q.get('ratio') || P.ratio || 'wide';\n const [W, H] = RATIOS[ratio] || RATIOS.wide;\n const { id: themeId, C, F } = resolveTheme(P);\n const timeScale = P.timeScale || 1;\n const duration = (P.duration || def.duration || 10) * timeScale;\n const fps = P.fps || 30;\n\n document.documentElement.style.background = capture ? C.bg : '#0b0b0a';\n document.body.style.margin = '0';\n const canvas = document.createElement('canvas');\n canvas.id = 'stage';\n canvas.width = W;\n canvas.height = H;\n const ctx = canvas.getContext('2d');\n\n const S = {\n W, H, ratio, P, C, F, themeId, fps, duration, timeScale,\n u: Math.min(W, H) / 1080, // 1 unit = 1px at 1080 short side\n wide: ratio === 'wide', square: ratio === 'square', tall: ratio === 'tall',\n warn, lib: LIB_BASE, frame: 0, images: {}, beats: P.beats || {},\n };\n S.pick = (wide, square, tall) => (S.tall ? tall : S.square ? square : wide);\n\n const fontStatus = await loadFonts(F, warn);\n if (Object.values(fontStatus).some(value => value !== \"loaded\")) throw new Error(\"All registered font faces must load; fallback is not permitted.\");\n for (const [k, rel] of Object.entries(P.media || {})) {\n try { S.images[k] = await loadImage(new URL(rel, location.href).href); } catch (e) { warn(String(e.message)); }\n }\n if (def.setup) await def.setup(S, ctx);\n\n // Scenes with external frames (video clips) define `prepare(t, S)`; renderAt then returns a\n // promise that resolves after those frames are decoded, so captures stay frame-exact.\n function renderAt(t) {\n t = Math.max(0, Math.min(duration, t));\n if (def.prepare) {\n const token = (S._token = (S._token || 0) + 1);\n return Promise.resolve(def.prepare(t / timeScale, S)).then(() => (token === S._token ? paint(t) : false));\n }\n return paint(t);\n }\n function paint(t) {\n S.frame = Math.round(t * fps);\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.globalAlpha = 1;\n ctx.globalCompositeOperation = 'source-over';\n ctx.fillStyle = C.bg;\n ctx.fillRect(0, 0, W, H);\n def.draw(ctx, t / timeScale, S);\n return true;\n }\n\n const beatTime = v => (typeof v === 'number' ? v : (S.beats[v] ?? 0));\n // cues from params plus cues the scene derives from its own data (def.cues)\n const rawCues = P.sound?.enabled === false ? [] : [...((P.sound && P.sound.cues) || []), ...(def.cues ? def.cues(S) : [])];\n const cues = rawCues.map(c => ({\n t: +((beatTime(c.at) + (c.offset || 0)) * timeScale).toFixed(4),\n sfx: c.sfx, file: c.file, dur: c.dur, trim: c.trim, gain: c.gain ?? (c.file ? 0.3 : 1),\n })).sort((a, b) => a.t - b.t);\n\n window.renderAt = renderAt;\n window.__sceneMeta = { id: def.id, W, H, ratio, fps, duration, frames: Math.round(duration * fps), theme: themeId, cues, timeScale, music: P.sound?.enabled === false ? null : P.sound?.music || null, voice: P.sound?.enabled === false ? null : P.sound?.voice || null, loudness: P.sound?.enabled === false ? null : P.sound?.loudness || null };\n window.getDiagnostics = () => ({ fonts: fontStatus, warnings: [...warnings], meta: window.__sceneMeta });\n\n document.body.appendChild(canvas);\n if (capture) {\n canvas.style.cssText = 'display:block';\n await renderAt(+(q.get('t') || 0));\n window.__ready = true;\n return;\n }\n preview(canvas, renderAt, S, cues);\n window.__ready = true;\n }\n\n // ---------- interactive preview (never used for rendering) ----------\n function preview(canvas, renderAt, S, cues) {\n const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;\n const showControls = q.get('controls') !== '0';\n const style = document.createElement('style');\n style.textContent = `\n body{height:100vh;display:flex;flex-direction:column;font:13px/1.3 -apple-system,system-ui,sans-serif;color:#e9e4da;background:#0b0b0a}\n #wrap{flex:1;display:flex;align-items:center;justify-content:center;min-height:0;padding:${showControls ? '12px' : '0'}}\n #stage{max-width:100%;max-height:100%;width:auto;height:auto;box-shadow:0 10px 40px rgba(0,0,0,.45)}\n #bar{display:flex;gap:10px;align-items:center;padding:10px 14px;background:#151412;border-top:1px solid #2a2824;flex-wrap:wrap}\n #bar button,#bar select{background:#24221f;color:#e9e4da;border:1px solid #3a3732;border-radius:6px;padding:5px 9px;font:inherit;cursor:pointer}\n #bar button.on{background:#E89A4A;color:#1b1a18;border-color:#E89A4A}\n #bar input[type=range]{flex:1;min-width:160px;accent-color:#E89A4A}\n #tm{font-variant-numeric:tabular-nums;min-width:92px}`;\n document.head.appendChild(style);\n const wrap = document.createElement('div');\n wrap.id = 'wrap';\n document.body.appendChild(wrap);\n wrap.appendChild(canvas);\n\n let t = q.has('t') ? +q.get('t') : reduced ? (S.P.reducedHold ?? S.duration * 0.9) : 0;\n let playing = !reduced && q.get('autoplay') === '1';\n let last = null;\n let sound = q.get('sound') === '1';\n const audio = audioEngine(cues, S);\n\n let range, tm, playBtn, soundBtn;\n if (showControls) {\n const bar = document.createElement('div');\n bar.id = 'bar';\n bar.innerHTML = `<button id=\"pp\"></button><input id=\"rg\" type=\"range\" min=\"0\" max=\"${S.duration}\" step=\"${1 / S.fps}\"><span id=\"tm\"></span>\n <span>${['wide', 'square', 'tall'].map(r => `<button data-r=\"${r}\" class=\"${r === S.ratio ? 'on' : ''}\">${{ wide: '16:9', square: '1:1', tall: '9:16' }[r]}</button>`).join(' ')}</span>\n <select id=\"th\">${Object.entries(window.EB_THEMES).map(([k, v]) => `<option value=\"${k}\" ${k === S.themeId ? 'selected' : ''}>${v.label}</option>`).join('')}</select>\n <button id=\"snd\"></button>`;\n document.body.appendChild(bar);\n range = bar.querySelector('#rg');\n tm = bar.querySelector('#tm');\n playBtn = bar.querySelector('#pp');\n soundBtn = bar.querySelector('#snd');\n const go = (k, v) => { const u = new URL(location.href); u.searchParams.set(k, v); u.searchParams.delete('t'); location.href = u.href; };\n bar.querySelectorAll('[data-r]').forEach(b => b.onclick = () => go('ratio', b.dataset.r));\n bar.querySelector('#th').onchange = e => go('theme', e.target.value);\n playBtn.onclick = toggle;\n soundBtn.onclick = () => { sound = !sound; audio.stop(); if (sound && playing) audio.start(t); sync(); };\n range.oninput = () => { t = +range.value; audio.stop(); if (playing && sound) audio.start(t); draw(); };\n }\n addEventListener('keydown', e => { if (e.code === 'Space') { e.preventDefault(); toggle(); } });\n canvas.onclick = toggle;\n function toggle() {\n playing = !playing;\n if (playing && t >= S.duration - 0.01) t = 0;\n last = null;\n audio.stop();\n if (playing && sound) audio.start(t);\n sync();\n }\n function sync() {\n if (!showControls) return;\n playBtn.textContent = playing ? 'Pausa' : 'Reproducir';\n soundBtn.textContent = sound ? 'Sonido: s\xED' : 'Sonido: no';\n soundBtn.className = sound ? 'on' : '';\n soundBtn.disabled = !cues.length;\n if (!cues.length) soundBtn.textContent = 'Sin sonido';\n }\n function draw() {\n renderAt(t);\n if (showControls) {\n range.value = t;\n tm.textContent = `${t.toFixed(2)} / ${S.duration.toFixed(1)} s`;\n }\n }\n // Pause off-screen / hidden tabs.\n let visible = true;\n new IntersectionObserver(es => { visible = es[0].isIntersecting; }).observe(canvas);\n function loop(now) {\n if (playing && visible && !document.hidden) {\n if (last !== null) t += (now - last) / 1000;\n if (t >= S.duration) {\n t = q.get('loop') === '0' ? S.duration : 0;\n if (q.get('loop') === '0') playing = false;\n audio.stop();\n if (playing && sound) audio.start(t);\n }\n draw();\n }\n last = playing ? now : null;\n requestAnimationFrame(loop);\n }\n sync();\n draw();\n requestAnimationFrame(loop);\n }\n\n // Preview-only audio: schedules the scene's cues from the synthesized SFX bank.\n function audioEngine(cues, S) {\n let ac = null, nodes = [];\n const buffers = {};\n async function buf(name) {\n if (!buffers[name]) {\n const r = await fetch(new URL(`sfx/${name}.wav`, S.lib));\n buffers[name] = await ac.decodeAudioData(await r.arrayBuffer());\n }\n return buffers[name];\n }\n return {\n async start(from) {\n if (!cues.length) return;\n ac = ac || new AudioContext();\n const t0 = ac.currentTime + 0.05;\n for (const c of cues) {\n if (c.t < from - 0.02) continue;\n const b = await buf(c.sfx);\n const src = ac.createBufferSource(), g = ac.createGain();\n src.buffer = b;\n g.gain.value = c.gain;\n src.connect(g).connect(ac.destination);\n src.start(t0 + (c.t - from));\n nodes.push(src);\n }\n },\n stop() { nodes.forEach(n => { try { n.stop(); } catch (e) {} }); nodes = []; },\n };\n }\n})();\n",
183316
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
183317
+ (function () {
183318
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
183319
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
183320
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
183321
+ const fonts = ['display','text','heavy','mono','hand'];
183322
+ window.EB_VALIDATE_PARAMS = (p, q) => {
183323
+ const theme = q.get('theme') || p.theme;
183324
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
183325
+ const ratio = q.get('ratio') || p.ratio || 'wide';
183326
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
183327
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
183328
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
183329
+ }
183330
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
183331
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
183332
+ if (q.get('demo') === '1') return;
183333
+ const b = window.__overrides?.brand;
183334
+ if (!record(b) || !record(b.colors) || !record(b.fonts)) fail('provide complete window.__overrides.brand from the selected project; demo themes are not customer defaults');
183335
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
183336
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
183337
+ if (!Array.isArray(b.series) || b.series.length < 6 || b.series.some(c => !/^#[0-9a-f]{6}$/i.test(c))) fail('provide at least six explicit series hex colors; roles may repeat project colors but never inherit demo colors');
183338
+ for (const role of fonts) {
183339
+ const font = b.fonts[role];
183340
+ if (!record(font) || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) fail('provide explicit family, weight and style for font role ' + role);
183341
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
183342
+ }
183343
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
183344
+ };
183345
+ })();
183346
+
183347
+ (function () {
183348
+ const base = window.EB_VALIDATE_PARAMS;
183349
+ const roles = ["avatar","bg","card","chip","chipEdge","chipText","edge","glow","glowCore","gray","ground","groundInk","ink","mapBg","mapBlock","mapHwy","mapPark","mapRoad","mapWater","ok","okSoft","paper","pick","pickLine","pill","pin","red","route","shutter","skip","stampShade","star","tick","tile1","tile2","tile3","tile4","uiAccent","uiBubble","uiChat","uiInk","uiLine","uiMuted","uiPanel"];
183350
+ const fontRoles = ["credit","slab","slabBlack","ui","uiBold","uiReg","uiSemi"];
183351
+ window.EB_VALIDATE_PARAMS = (params, query) => {
183352
+ base(params, query);
183353
+ if (query.get('demo') === '1') return;
183354
+ for (const role of roles) {
183355
+ if (!/^#[0-9a-f]{6}$/i.test(window.__overrides?.brand?.colors?.[role] || '')) throw new Error('EditorBrain project binding: provide scene-specific color role ' + role + '; never inherit demo/preset brand colors.');
183356
+ }
183357
+ for (const role of fontRoles) {
183358
+ const font = window.__overrides?.brand?.fonts?.[role];
183359
+ if (!font || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) throw new Error('EditorBrain project binding: provide complete scene-specific font role ' + role + '; never inherit demo/preset typography.');
183360
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183361
+ }
183362
+ };
183363
+ })();
183364
+ `
183365
+ },
183366
+ "simulacion-en-el-mapa": {
183367
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
183368
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
183369
+ "runtime": "// EditorBrain authored motion \xB7 scene runtime.\n// One canvas, explicit time: window.renderAt(seconds) draws the exact state for that time.\n// URL: ?ratio=wide|square|tall &theme=<kit> &t=<sec> &capture=1 &autoplay=1 &controls=0\n(function () {\n const RATIOS = { wide: [1920, 1080], square: [1080, 1080], tall: [1080, 1920] };\n const LIB_BASE = new URL('..', document.currentScript.src).href; // library root\n const q = new URLSearchParams(location.search);\n const capture = q.get('capture') === '1';\n\n const isObj = v => v && typeof v === 'object' && !Array.isArray(v);\n const merge = (a, b) => {\n if (!isObj(b)) return b === undefined ? a : b;\n const out = { ...(isObj(a) ? a : {}) };\n for (const k of Object.keys(b)) out[k] = merge(out[k], b[k]);\n return out;\n };\n\n function readParams() {\n const el = document.getElementById('params');\n let p = el ? JSON.parse(el.textContent) : {};\n if (window.__overrides) p = merge(p, window.__overrides);\n const enc = q.get('params');\n if (enc) { const supplied = JSON.parse(decodeURIComponent(escape(atob(enc)))); window.__overrides = merge(window.__overrides || {}, supplied); p = merge(p, supplied); }\n window.EB_VALIDATE_PARAMS(p, q);\n return p;\n }\n\n async function loadFonts(F, warn) {\n const families = new Set(Object.values(F).map(f => f.family));\n const status = {};\n for (const fam of families) {\n const defs = (window.EB_FONTS || {})[fam];\n if (!defs) {\n status[fam] = 'not-registered';\n warn(`font family not registered: ${fam}`);\n continue;\n }\n const results = await Promise.all(defs.map(async d => {\n const src = d.local ? d.local.map(n => `local(\"${n}\")`).join(', ') : `url(\"${new URL(d.src, LIB_BASE).href}\")`;\n const desc = {};\n if (d.weight) desc.weight = d.weight;\n if (d.style) desc.style = d.style;\n if (d.stretch) desc.stretch = d.stretch;\n try {\n const face = new FontFace(fam, src, desc);\n await face.load();\n document.fonts.add(face);\n return true;\n } catch (e) {\n return false;\n }\n }));\n const ok = results.filter(Boolean).length;\n status[fam] = ok === defs.length ? 'loaded' : ok ? `partial ${ok}/${defs.length}` : 'missing';\n if (!ok) warn(`font unavailable, renderer would fall back: ${fam}`);\n }\n return status;\n }\n\n function loadImage(src) {\n return new Promise((res, rej) => {\n const img = new Image();\n img.onload = () => res(img);\n img.onerror = () => rej(new Error('image failed: ' + src));\n img.src = src;\n });\n }\n\n function resolveTheme(params) {\n const kits = window.EB_THEMES || {};\n const id = q.get('theme') || params.theme || Object.keys(kits)[0];\n const kit = kits[id] || kits[Object.keys(kits)[0]];\n const brand = params.brand || {};\n const C = { ...kit.colors, ...(brand.colors || {}) };\n C.series = brand.series || kit.series;\n const F = {};\n for (const role of new Set(['display', 'text', 'heavy', 'mono', 'hand', ...Object.keys(brand.fonts || {})])) F[role] = { ...(kit.fonts[role] || kit.fonts.text), ...((brand.fonts || {})[role] || {}) };\n return { id, kit, C, F };\n }\n\n window.EB = {\n RATIOS,\n scene(def) {\n const warnings = new Set();\n const warn = m => { warnings.add(m); if (q.get(\"demo\") !== \"1\") throw new Error(m); };\n try {\n void boot(def, warn, warnings).catch(e => { window.__motionError = String(e && e.stack || e); console.error(window.__motionError); });\n } catch (e) {\n window.__motionError = String(e && e.stack || e);\n throw e;\n }\n },\n };\n\n async function boot(def, warn, warnings) {\n const P = readParams();\n const ratio = q.get('ratio') || P.ratio || 'wide';\n const [W, H] = RATIOS[ratio] || RATIOS.wide;\n const { id: themeId, C, F } = resolveTheme(P);\n const timeScale = P.timeScale || 1;\n const duration = (P.duration || def.duration || 10) * timeScale;\n const fps = P.fps || 30;\n\n document.documentElement.style.background = capture ? C.bg : '#0b0b0a';\n document.body.style.margin = '0';\n const canvas = document.createElement('canvas');\n canvas.id = 'stage';\n canvas.width = W;\n canvas.height = H;\n const ctx = canvas.getContext('2d');\n\n const S = {\n W, H, ratio, P, C, F, themeId, fps, duration, timeScale,\n u: Math.min(W, H) / 1080, // 1 unit = 1px at 1080 short side\n wide: ratio === 'wide', square: ratio === 'square', tall: ratio === 'tall',\n warn, lib: LIB_BASE, frame: 0, images: {}, beats: P.beats || {},\n };\n S.pick = (wide, square, tall) => (S.tall ? tall : S.square ? square : wide);\n\n const fontStatus = await loadFonts(F, warn);\n if (Object.values(fontStatus).some(value => value !== \"loaded\")) throw new Error(\"All registered font faces must load; fallback is not permitted.\");\n for (const [k, rel] of Object.entries(P.media || {})) {\n try { S.images[k] = await loadImage(new URL(rel, location.href).href); } catch (e) { warn(String(e.message)); }\n }\n if (def.setup) await def.setup(S, ctx);\n\n // Scenes with external frames (video clips) define `prepare(t, S)`; renderAt then returns a\n // promise that resolves after those frames are decoded, so captures stay frame-exact.\n function renderAt(t) {\n t = Math.max(0, Math.min(duration, t));\n if (def.prepare) {\n const token = (S._token = (S._token || 0) + 1);\n return Promise.resolve(def.prepare(t / timeScale, S)).then(() => (token === S._token ? paint(t) : false));\n }\n return paint(t);\n }\n function paint(t) {\n S.frame = Math.round(t * fps);\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.globalAlpha = 1;\n ctx.globalCompositeOperation = 'source-over';\n ctx.fillStyle = C.bg;\n ctx.fillRect(0, 0, W, H);\n def.draw(ctx, t / timeScale, S);\n return true;\n }\n\n const beatTime = v => (typeof v === 'number' ? v : (S.beats[v] ?? 0));\n // cues from params plus cues the scene derives from its own data (def.cues)\n const rawCues = P.sound?.enabled === false ? [] : [...((P.sound && P.sound.cues) || []), ...(def.cues ? def.cues(S) : [])];\n const cues = rawCues.map(c => ({\n t: +((beatTime(c.at) + (c.offset || 0)) * timeScale).toFixed(4),\n sfx: c.sfx, file: c.file, dur: c.dur, trim: c.trim, gain: c.gain ?? (c.file ? 0.3 : 1),\n })).sort((a, b) => a.t - b.t);\n\n window.renderAt = renderAt;\n window.__sceneMeta = { id: def.id, W, H, ratio, fps, duration, frames: Math.round(duration * fps), theme: themeId, cues, timeScale, music: P.sound?.enabled === false ? null : P.sound?.music || null, voice: P.sound?.enabled === false ? null : P.sound?.voice || null, loudness: P.sound?.enabled === false ? null : P.sound?.loudness || null };\n window.getDiagnostics = () => ({ fonts: fontStatus, warnings: [...warnings], meta: window.__sceneMeta });\n\n document.body.appendChild(canvas);\n if (capture) {\n canvas.style.cssText = 'display:block';\n await renderAt(+(q.get('t') || 0));\n window.__ready = true;\n return;\n }\n preview(canvas, renderAt, S, cues);\n window.__ready = true;\n }\n\n // ---------- interactive preview (never used for rendering) ----------\n function preview(canvas, renderAt, S, cues) {\n const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;\n const showControls = q.get('controls') !== '0';\n const style = document.createElement('style');\n style.textContent = `\n body{height:100vh;display:flex;flex-direction:column;font:13px/1.3 -apple-system,system-ui,sans-serif;color:#e9e4da;background:#0b0b0a}\n #wrap{flex:1;display:flex;align-items:center;justify-content:center;min-height:0;padding:${showControls ? '12px' : '0'}}\n #stage{max-width:100%;max-height:100%;width:auto;height:auto;box-shadow:0 10px 40px rgba(0,0,0,.45)}\n #bar{display:flex;gap:10px;align-items:center;padding:10px 14px;background:#151412;border-top:1px solid #2a2824;flex-wrap:wrap}\n #bar button,#bar select{background:#24221f;color:#e9e4da;border:1px solid #3a3732;border-radius:6px;padding:5px 9px;font:inherit;cursor:pointer}\n #bar button.on{background:#E89A4A;color:#1b1a18;border-color:#E89A4A}\n #bar input[type=range]{flex:1;min-width:160px;accent-color:#E89A4A}\n #tm{font-variant-numeric:tabular-nums;min-width:92px}`;\n document.head.appendChild(style);\n const wrap = document.createElement('div');\n wrap.id = 'wrap';\n document.body.appendChild(wrap);\n wrap.appendChild(canvas);\n\n let t = q.has('t') ? +q.get('t') : reduced ? (S.P.reducedHold ?? S.duration * 0.9) : 0;\n let playing = !reduced && q.get('autoplay') === '1';\n let last = null;\n let sound = q.get('sound') === '1';\n const audio = audioEngine(cues, S);\n\n let range, tm, playBtn, soundBtn;\n if (showControls) {\n const bar = document.createElement('div');\n bar.id = 'bar';\n bar.innerHTML = `<button id=\"pp\"></button><input id=\"rg\" type=\"range\" min=\"0\" max=\"${S.duration}\" step=\"${1 / S.fps}\"><span id=\"tm\"></span>\n <span>${['wide', 'square', 'tall'].map(r => `<button data-r=\"${r}\" class=\"${r === S.ratio ? 'on' : ''}\">${{ wide: '16:9', square: '1:1', tall: '9:16' }[r]}</button>`).join(' ')}</span>\n <select id=\"th\">${Object.entries(window.EB_THEMES).map(([k, v]) => `<option value=\"${k}\" ${k === S.themeId ? 'selected' : ''}>${v.label}</option>`).join('')}</select>\n <button id=\"snd\"></button>`;\n document.body.appendChild(bar);\n range = bar.querySelector('#rg');\n tm = bar.querySelector('#tm');\n playBtn = bar.querySelector('#pp');\n soundBtn = bar.querySelector('#snd');\n const go = (k, v) => { const u = new URL(location.href); u.searchParams.set(k, v); u.searchParams.delete('t'); location.href = u.href; };\n bar.querySelectorAll('[data-r]').forEach(b => b.onclick = () => go('ratio', b.dataset.r));\n bar.querySelector('#th').onchange = e => go('theme', e.target.value);\n playBtn.onclick = toggle;\n soundBtn.onclick = () => { sound = !sound; audio.stop(); if (sound && playing) audio.start(t); sync(); };\n range.oninput = () => { t = +range.value; audio.stop(); if (playing && sound) audio.start(t); draw(); };\n }\n addEventListener('keydown', e => { if (e.code === 'Space') { e.preventDefault(); toggle(); } });\n canvas.onclick = toggle;\n function toggle() {\n playing = !playing;\n if (playing && t >= S.duration - 0.01) t = 0;\n last = null;\n audio.stop();\n if (playing && sound) audio.start(t);\n sync();\n }\n function sync() {\n if (!showControls) return;\n playBtn.textContent = playing ? 'Pausa' : 'Reproducir';\n soundBtn.textContent = sound ? 'Sonido: s\xED' : 'Sonido: no';\n soundBtn.className = sound ? 'on' : '';\n soundBtn.disabled = !cues.length;\n if (!cues.length) soundBtn.textContent = 'Sin sonido';\n }\n function draw() {\n renderAt(t);\n if (showControls) {\n range.value = t;\n tm.textContent = `${t.toFixed(2)} / ${S.duration.toFixed(1)} s`;\n }\n }\n // Pause off-screen / hidden tabs.\n let visible = true;\n new IntersectionObserver(es => { visible = es[0].isIntersecting; }).observe(canvas);\n function loop(now) {\n if (playing && visible && !document.hidden) {\n if (last !== null) t += (now - last) / 1000;\n if (t >= S.duration) {\n t = q.get('loop') === '0' ? S.duration : 0;\n if (q.get('loop') === '0') playing = false;\n audio.stop();\n if (playing && sound) audio.start(t);\n }\n draw();\n }\n last = playing ? now : null;\n requestAnimationFrame(loop);\n }\n sync();\n draw();\n requestAnimationFrame(loop);\n }\n\n // Preview-only audio: schedules the scene's cues from the synthesized SFX bank.\n function audioEngine(cues, S) {\n let ac = null, nodes = [];\n const buffers = {};\n async function buf(name) {\n if (!buffers[name]) {\n const r = await fetch(new URL(`sfx/${name}.wav`, S.lib));\n buffers[name] = await ac.decodeAudioData(await r.arrayBuffer());\n }\n return buffers[name];\n }\n return {\n async start(from) {\n if (!cues.length) return;\n ac = ac || new AudioContext();\n const t0 = ac.currentTime + 0.05;\n for (const c of cues) {\n if (c.t < from - 0.02) continue;\n const b = await buf(c.sfx);\n const src = ac.createBufferSource(), g = ac.createGain();\n src.buffer = b;\n g.gain.value = c.gain;\n src.connect(g).connect(ac.destination);\n src.start(t0 + (c.t - from));\n nodes.push(src);\n }\n },\n stop() { nodes.forEach(n => { try { n.stop(); } catch (e) {} }); nodes = []; },\n };\n }\n})();\n",
183370
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
183371
+ (function () {
183372
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
183373
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
183374
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
183375
+ const fonts = ['display','text','heavy','mono','hand'];
183376
+ window.EB_VALIDATE_PARAMS = (p, q) => {
183377
+ const theme = q.get('theme') || p.theme;
183378
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
183379
+ const ratio = q.get('ratio') || p.ratio || 'wide';
183380
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
183381
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
183382
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
183383
+ }
183384
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
183385
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
183386
+ if (q.get('demo') === '1') return;
183387
+ const b = window.__overrides?.brand;
183388
+ if (!record(b) || !record(b.colors) || !record(b.fonts)) fail('provide complete window.__overrides.brand from the selected project; demo themes are not customer defaults');
183389
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
183390
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
183391
+ if (!Array.isArray(b.series) || b.series.length < 6 || b.series.some(c => !/^#[0-9a-f]{6}$/i.test(c))) fail('provide at least six explicit series hex colors; roles may repeat project colors but never inherit demo colors');
183392
+ for (const role of fonts) {
183393
+ const font = b.fonts[role];
183394
+ if (!record(font) || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) fail('provide explicit family, weight and style for font role ' + role);
183395
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
183396
+ }
183397
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
183398
+ };
183399
+ })();
183400
+
183401
+ (function () {
183402
+ const base = window.EB_VALIDATE_PARAMS;
183403
+ const roles = ["accent","atmo","bg","brown","chipA","chipB","core","drop","dry","ember","glow","ink","panel","smoke","titleSplit","upcoming","vapor"];
183404
+ const fontRoles = ["cap","credit","label","mono","monoB","title"];
183405
+ window.EB_VALIDATE_PARAMS = (params, query) => {
183406
+ base(params, query);
183407
+ if (query.get('demo') === '1') return;
183408
+ for (const role of roles) {
183409
+ if (!/^#[0-9a-f]{6}$/i.test(window.__overrides?.brand?.colors?.[role] || '')) throw new Error('EditorBrain project binding: provide scene-specific color role ' + role + '; never inherit demo/preset brand colors.');
183410
+ }
183411
+ for (const role of fontRoles) {
183412
+ const font = window.__overrides?.brand?.fonts?.[role];
183413
+ if (!font || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) throw new Error('EditorBrain project binding: provide complete scene-specific font role ' + role + '; never inherit demo/preset typography.');
183414
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183415
+ }
183416
+ };
183417
+ })();
183418
+ `
183419
+ },
183420
+ "relato-ilustrado": {
183421
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
183422
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
183423
+ "runtime": "// EditorBrain authored motion \xB7 scene runtime.\n// One canvas, explicit time: window.renderAt(seconds) draws the exact state for that time.\n// URL: ?ratio=wide|square|tall &theme=<kit> &t=<sec> &capture=1 &autoplay=1 &controls=0\n(function () {\n const RATIOS = { wide: [1920, 1080], square: [1080, 1080], tall: [1080, 1920] };\n const LIB_BASE = new URL('..', document.currentScript.src).href; // library root\n const q = new URLSearchParams(location.search);\n const capture = q.get('capture') === '1';\n\n const isObj = v => v && typeof v === 'object' && !Array.isArray(v);\n const merge = (a, b) => {\n if (!isObj(b)) return b === undefined ? a : b;\n const out = { ...(isObj(a) ? a : {}) };\n for (const k of Object.keys(b)) out[k] = merge(out[k], b[k]);\n return out;\n };\n\n function readParams() {\n const el = document.getElementById('params');\n let p = el ? JSON.parse(el.textContent) : {};\n if (window.__overrides) p = merge(p, window.__overrides);\n const enc = q.get('params');\n if (enc) { const supplied = JSON.parse(decodeURIComponent(escape(atob(enc)))); window.__overrides = merge(window.__overrides || {}, supplied); p = merge(p, supplied); }\n window.EB_VALIDATE_PARAMS(p, q);\n return p;\n }\n\n async function loadFonts(F, warn) {\n const families = new Set(Object.values(F).map(f => f.family));\n const status = {};\n for (const fam of families) {\n const defs = (window.EB_FONTS || {})[fam];\n if (!defs) {\n status[fam] = 'not-registered';\n warn(`font family not registered: ${fam}`);\n continue;\n }\n const results = await Promise.all(defs.map(async d => {\n const src = d.local ? d.local.map(n => `local(\"${n}\")`).join(', ') : `url(\"${new URL(d.src, LIB_BASE).href}\")`;\n const desc = {};\n if (d.weight) desc.weight = d.weight;\n if (d.style) desc.style = d.style;\n if (d.stretch) desc.stretch = d.stretch;\n try {\n const face = new FontFace(fam, src, desc);\n await face.load();\n document.fonts.add(face);\n return true;\n } catch (e) {\n return false;\n }\n }));\n const ok = results.filter(Boolean).length;\n status[fam] = ok === defs.length ? 'loaded' : ok ? `partial ${ok}/${defs.length}` : 'missing';\n if (!ok) warn(`font unavailable, renderer would fall back: ${fam}`);\n }\n return status;\n }\n\n function loadImage(src) {\n return new Promise((res, rej) => {\n const img = new Image();\n img.onload = () => res(img);\n img.onerror = () => rej(new Error('image failed: ' + src));\n img.src = src;\n });\n }\n\n function resolveTheme(params) {\n const kits = window.EB_THEMES || {};\n const id = q.get('theme') || params.theme || Object.keys(kits)[0];\n const kit = kits[id] || kits[Object.keys(kits)[0]];\n const brand = params.brand || {};\n const C = { ...kit.colors, ...(brand.colors || {}) };\n C.series = brand.series || kit.series;\n const F = {};\n for (const role of new Set(['display', 'text', 'heavy', 'mono', 'hand', ...Object.keys(brand.fonts || {})])) F[role] = { ...(kit.fonts[role] || kit.fonts.text), ...((brand.fonts || {})[role] || {}) };\n return { id, kit, C, F };\n }\n\n window.EB = {\n RATIOS,\n scene(def) {\n const warnings = new Set();\n const warn = m => { warnings.add(m); if (q.get(\"demo\") !== \"1\") throw new Error(m); };\n try {\n void boot(def, warn, warnings).catch(e => { window.__motionError = String(e && e.stack || e); console.error(window.__motionError); });\n } catch (e) {\n window.__motionError = String(e && e.stack || e);\n throw e;\n }\n },\n };\n\n async function boot(def, warn, warnings) {\n const P = readParams();\n const ratio = q.get('ratio') || P.ratio || 'wide';\n const [W, H] = RATIOS[ratio] || RATIOS.wide;\n const { id: themeId, C, F } = resolveTheme(P);\n const timeScale = P.timeScale || 1;\n const duration = (P.duration || def.duration || 10) * timeScale;\n const fps = P.fps || 30;\n\n document.documentElement.style.background = capture ? C.bg : '#0b0b0a';\n document.body.style.margin = '0';\n const canvas = document.createElement('canvas');\n canvas.id = 'stage';\n canvas.width = W;\n canvas.height = H;\n const ctx = canvas.getContext('2d');\n\n const S = {\n W, H, ratio, P, C, F, themeId, fps, duration, timeScale,\n u: Math.min(W, H) / 1080, // 1 unit = 1px at 1080 short side\n wide: ratio === 'wide', square: ratio === 'square', tall: ratio === 'tall',\n warn, lib: LIB_BASE, frame: 0, images: {}, beats: P.beats || {},\n };\n S.pick = (wide, square, tall) => (S.tall ? tall : S.square ? square : wide);\n\n const fontStatus = await loadFonts(F, warn);\n if (Object.values(fontStatus).some(value => value !== \"loaded\")) throw new Error(\"All registered font faces must load; fallback is not permitted.\");\n for (const [k, rel] of Object.entries(P.media || {})) {\n try { S.images[k] = await loadImage(new URL(rel, location.href).href); } catch (e) { warn(String(e.message)); }\n }\n if (def.setup) await def.setup(S, ctx);\n\n // Scenes with external frames (video clips) define `prepare(t, S)`; renderAt then returns a\n // promise that resolves after those frames are decoded, so captures stay frame-exact.\n function renderAt(t) {\n t = Math.max(0, Math.min(duration, t));\n if (def.prepare) {\n const token = (S._token = (S._token || 0) + 1);\n return Promise.resolve(def.prepare(t / timeScale, S)).then(() => (token === S._token ? paint(t) : false));\n }\n return paint(t);\n }\n function paint(t) {\n S.frame = Math.round(t * fps);\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.globalAlpha = 1;\n ctx.globalCompositeOperation = 'source-over';\n ctx.fillStyle = C.bg;\n ctx.fillRect(0, 0, W, H);\n def.draw(ctx, t / timeScale, S);\n return true;\n }\n\n const beatTime = v => (typeof v === 'number' ? v : (S.beats[v] ?? 0));\n // cues from params plus cues the scene derives from its own data (def.cues)\n const rawCues = P.sound?.enabled === false ? [] : [...((P.sound && P.sound.cues) || []), ...(def.cues ? def.cues(S) : [])];\n const cues = rawCues.map(c => ({\n t: +((beatTime(c.at) + (c.offset || 0)) * timeScale).toFixed(4),\n sfx: c.sfx, file: c.file, dur: c.dur, trim: c.trim, gain: c.gain ?? (c.file ? 0.3 : 1),\n })).sort((a, b) => a.t - b.t);\n\n window.renderAt = renderAt;\n window.__sceneMeta = { id: def.id, W, H, ratio, fps, duration, frames: Math.round(duration * fps), theme: themeId, cues, timeScale, music: P.sound?.enabled === false ? null : P.sound?.music || null, voice: P.sound?.enabled === false ? null : P.sound?.voice || null, loudness: P.sound?.enabled === false ? null : P.sound?.loudness || null };\n window.getDiagnostics = () => ({ fonts: fontStatus, warnings: [...warnings], meta: window.__sceneMeta });\n\n document.body.appendChild(canvas);\n if (capture) {\n canvas.style.cssText = 'display:block';\n await renderAt(+(q.get('t') || 0));\n window.__ready = true;\n return;\n }\n preview(canvas, renderAt, S, cues);\n window.__ready = true;\n }\n\n // ---------- interactive preview (never used for rendering) ----------\n function preview(canvas, renderAt, S, cues) {\n const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;\n const showControls = q.get('controls') !== '0';\n const style = document.createElement('style');\n style.textContent = `\n body{height:100vh;display:flex;flex-direction:column;font:13px/1.3 -apple-system,system-ui,sans-serif;color:#e9e4da;background:#0b0b0a}\n #wrap{flex:1;display:flex;align-items:center;justify-content:center;min-height:0;padding:${showControls ? '12px' : '0'}}\n #stage{max-width:100%;max-height:100%;width:auto;height:auto;box-shadow:0 10px 40px rgba(0,0,0,.45)}\n #bar{display:flex;gap:10px;align-items:center;padding:10px 14px;background:#151412;border-top:1px solid #2a2824;flex-wrap:wrap}\n #bar button,#bar select{background:#24221f;color:#e9e4da;border:1px solid #3a3732;border-radius:6px;padding:5px 9px;font:inherit;cursor:pointer}\n #bar button.on{background:#E89A4A;color:#1b1a18;border-color:#E89A4A}\n #bar input[type=range]{flex:1;min-width:160px;accent-color:#E89A4A}\n #tm{font-variant-numeric:tabular-nums;min-width:92px}`;\n document.head.appendChild(style);\n const wrap = document.createElement('div');\n wrap.id = 'wrap';\n document.body.appendChild(wrap);\n wrap.appendChild(canvas);\n\n let t = q.has('t') ? +q.get('t') : reduced ? (S.P.reducedHold ?? S.duration * 0.9) : 0;\n let playing = !reduced && q.get('autoplay') === '1';\n let last = null;\n let sound = q.get('sound') === '1';\n const audio = audioEngine(cues, S);\n\n let range, tm, playBtn, soundBtn;\n if (showControls) {\n const bar = document.createElement('div');\n bar.id = 'bar';\n bar.innerHTML = `<button id=\"pp\"></button><input id=\"rg\" type=\"range\" min=\"0\" max=\"${S.duration}\" step=\"${1 / S.fps}\"><span id=\"tm\"></span>\n <span>${['wide', 'square', 'tall'].map(r => `<button data-r=\"${r}\" class=\"${r === S.ratio ? 'on' : ''}\">${{ wide: '16:9', square: '1:1', tall: '9:16' }[r]}</button>`).join(' ')}</span>\n <select id=\"th\">${Object.entries(window.EB_THEMES).map(([k, v]) => `<option value=\"${k}\" ${k === S.themeId ? 'selected' : ''}>${v.label}</option>`).join('')}</select>\n <button id=\"snd\"></button>`;\n document.body.appendChild(bar);\n range = bar.querySelector('#rg');\n tm = bar.querySelector('#tm');\n playBtn = bar.querySelector('#pp');\n soundBtn = bar.querySelector('#snd');\n const go = (k, v) => { const u = new URL(location.href); u.searchParams.set(k, v); u.searchParams.delete('t'); location.href = u.href; };\n bar.querySelectorAll('[data-r]').forEach(b => b.onclick = () => go('ratio', b.dataset.r));\n bar.querySelector('#th').onchange = e => go('theme', e.target.value);\n playBtn.onclick = toggle;\n soundBtn.onclick = () => { sound = !sound; audio.stop(); if (sound && playing) audio.start(t); sync(); };\n range.oninput = () => { t = +range.value; audio.stop(); if (playing && sound) audio.start(t); draw(); };\n }\n addEventListener('keydown', e => { if (e.code === 'Space') { e.preventDefault(); toggle(); } });\n canvas.onclick = toggle;\n function toggle() {\n playing = !playing;\n if (playing && t >= S.duration - 0.01) t = 0;\n last = null;\n audio.stop();\n if (playing && sound) audio.start(t);\n sync();\n }\n function sync() {\n if (!showControls) return;\n playBtn.textContent = playing ? 'Pausa' : 'Reproducir';\n soundBtn.textContent = sound ? 'Sonido: s\xED' : 'Sonido: no';\n soundBtn.className = sound ? 'on' : '';\n soundBtn.disabled = !cues.length;\n if (!cues.length) soundBtn.textContent = 'Sin sonido';\n }\n function draw() {\n renderAt(t);\n if (showControls) {\n range.value = t;\n tm.textContent = `${t.toFixed(2)} / ${S.duration.toFixed(1)} s`;\n }\n }\n // Pause off-screen / hidden tabs.\n let visible = true;\n new IntersectionObserver(es => { visible = es[0].isIntersecting; }).observe(canvas);\n function loop(now) {\n if (playing && visible && !document.hidden) {\n if (last !== null) t += (now - last) / 1000;\n if (t >= S.duration) {\n t = q.get('loop') === '0' ? S.duration : 0;\n if (q.get('loop') === '0') playing = false;\n audio.stop();\n if (playing && sound) audio.start(t);\n }\n draw();\n }\n last = playing ? now : null;\n requestAnimationFrame(loop);\n }\n sync();\n draw();\n requestAnimationFrame(loop);\n }\n\n // Preview-only audio: schedules the scene's cues from the synthesized SFX bank.\n function audioEngine(cues, S) {\n let ac = null, nodes = [];\n const buffers = {};\n async function buf(name) {\n if (!buffers[name]) {\n const r = await fetch(new URL(`sfx/${name}.wav`, S.lib));\n buffers[name] = await ac.decodeAudioData(await r.arrayBuffer());\n }\n return buffers[name];\n }\n return {\n async start(from) {\n if (!cues.length) return;\n ac = ac || new AudioContext();\n const t0 = ac.currentTime + 0.05;\n for (const c of cues) {\n if (c.t < from - 0.02) continue;\n const b = await buf(c.sfx);\n const src = ac.createBufferSource(), g = ac.createGain();\n src.buffer = b;\n g.gain.value = c.gain;\n src.connect(g).connect(ac.destination);\n src.start(t0 + (c.t - from));\n nodes.push(src);\n }\n },\n stop() { nodes.forEach(n => { try { n.stop(); } catch (e) {} }); nodes = []; },\n };\n }\n})();\n",
183424
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
183425
+ (function () {
183426
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
183427
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
183428
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
183429
+ const fonts = ['display','text','heavy','mono','hand'];
183430
+ window.EB_VALIDATE_PARAMS = (p, q) => {
183431
+ const theme = q.get('theme') || p.theme;
183432
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
183433
+ const ratio = q.get('ratio') || p.ratio || 'wide';
183434
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
183435
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
183436
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
183437
+ }
183438
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
183439
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
183440
+ if (q.get('demo') === '1') return;
183441
+ const b = window.__overrides?.brand;
183442
+ if (!record(b) || !record(b.colors) || !record(b.fonts)) fail('provide complete window.__overrides.brand from the selected project; demo themes are not customer defaults');
183443
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
183444
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
183445
+ if (!Array.isArray(b.series) || b.series.length < 6 || b.series.some(c => !/^#[0-9a-f]{6}$/i.test(c))) fail('provide at least six explicit series hex colors; roles may repeat project colors but never inherit demo colors');
183446
+ for (const role of fonts) {
183447
+ const font = b.fonts[role];
183448
+ if (!record(font) || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) fail('provide explicit family, weight and style for font role ' + role);
183449
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
183450
+ }
183451
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
183452
+ };
183453
+ })();
183454
+
183455
+ (function () {
183456
+ const base = window.EB_VALIDATE_PARAMS;
183457
+ const roles = ["badgeInk","badgeRed","badgeYellow","bg","card","cardInk","cardMuted","cardRed","chip","chipDone","chipDoneInk","chipInk","chipThreat","endBg","endGlow","led","ledBox","ledEdge","ledOff","line","metal","metalDark","note","paper","paperEdge","pill","pillInk","red","shadow","shaft","slab","white","yellow"];
183458
+ const fontRoles = ["cap","card","credit","heavy","label","note"];
183459
+ window.EB_VALIDATE_PARAMS = (params, query) => {
183460
+ base(params, query);
183461
+ if (query.get('demo') === '1') return;
183462
+ for (const role of roles) {
183463
+ if (!/^#[0-9a-f]{6}$/i.test(window.__overrides?.brand?.colors?.[role] || '')) throw new Error('EditorBrain project binding: provide scene-specific color role ' + role + '; never inherit demo/preset brand colors.');
183464
+ }
183465
+ for (const role of fontRoles) {
183466
+ const font = window.__overrides?.brand?.fonts?.[role];
183467
+ if (!font || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) throw new Error('EditorBrain project binding: provide complete scene-specific font role ' + role + '; never inherit demo/preset typography.');
183468
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183469
+ }
183470
+ };
183471
+ })();
183472
+ `
183473
+ },
183474
+ "pizarra-minimalista": {
183475
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
183476
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
183477
+ "runtime": "// EditorBrain authored motion \xB7 scene runtime.\n// One canvas, explicit time: window.renderAt(seconds) draws the exact state for that time.\n// URL: ?ratio=wide|square|tall &theme=<kit> &t=<sec> &capture=1 &autoplay=1 &controls=0\n(function () {\n const RATIOS = { wide: [1920, 1080], square: [1080, 1080], tall: [1080, 1920] };\n const LIB_BASE = new URL('..', document.currentScript.src).href; // library root\n const q = new URLSearchParams(location.search);\n const capture = q.get('capture') === '1';\n\n const isObj = v => v && typeof v === 'object' && !Array.isArray(v);\n const merge = (a, b) => {\n if (!isObj(b)) return b === undefined ? a : b;\n const out = { ...(isObj(a) ? a : {}) };\n for (const k of Object.keys(b)) out[k] = merge(out[k], b[k]);\n return out;\n };\n\n function readParams() {\n const el = document.getElementById('params');\n let p = el ? JSON.parse(el.textContent) : {};\n if (window.__overrides) p = merge(p, window.__overrides);\n const enc = q.get('params');\n if (enc) { const supplied = JSON.parse(decodeURIComponent(escape(atob(enc)))); window.__overrides = merge(window.__overrides || {}, supplied); p = merge(p, supplied); }\n window.EB_VALIDATE_PARAMS(p, q);\n return p;\n }\n\n async function loadFonts(F, warn) {\n const families = new Set(Object.values(F).map(f => f.family));\n const status = {};\n for (const fam of families) {\n const defs = (window.EB_FONTS || {})[fam];\n if (!defs) {\n status[fam] = 'not-registered';\n warn(`font family not registered: ${fam}`);\n continue;\n }\n const results = await Promise.all(defs.map(async d => {\n const src = d.local ? d.local.map(n => `local(\"${n}\")`).join(', ') : `url(\"${new URL(d.src, LIB_BASE).href}\")`;\n const desc = {};\n if (d.weight) desc.weight = d.weight;\n if (d.style) desc.style = d.style;\n if (d.stretch) desc.stretch = d.stretch;\n try {\n const face = new FontFace(fam, src, desc);\n await face.load();\n document.fonts.add(face);\n return true;\n } catch (e) {\n return false;\n }\n }));\n const ok = results.filter(Boolean).length;\n status[fam] = ok === defs.length ? 'loaded' : ok ? `partial ${ok}/${defs.length}` : 'missing';\n if (!ok) warn(`font unavailable, renderer would fall back: ${fam}`);\n }\n return status;\n }\n\n function loadImage(src) {\n return new Promise((res, rej) => {\n const img = new Image();\n img.onload = () => res(img);\n img.onerror = () => rej(new Error('image failed: ' + src));\n img.src = src;\n });\n }\n\n function resolveTheme(params) {\n const kits = window.EB_THEMES || {};\n const id = q.get('theme') || params.theme || Object.keys(kits)[0];\n const kit = kits[id] || kits[Object.keys(kits)[0]];\n const brand = params.brand || {};\n const C = { ...kit.colors, ...(brand.colors || {}) };\n C.series = brand.series || kit.series;\n const F = {};\n for (const role of new Set(['display', 'text', 'heavy', 'mono', 'hand', ...Object.keys(brand.fonts || {})])) F[role] = { ...(kit.fonts[role] || kit.fonts.text), ...((brand.fonts || {})[role] || {}) };\n return { id, kit, C, F };\n }\n\n window.EB = {\n RATIOS,\n scene(def) {\n const warnings = new Set();\n const warn = m => { warnings.add(m); if (q.get(\"demo\") !== \"1\") throw new Error(m); };\n try {\n void boot(def, warn, warnings).catch(e => { window.__motionError = String(e && e.stack || e); console.error(window.__motionError); });\n } catch (e) {\n window.__motionError = String(e && e.stack || e);\n throw e;\n }\n },\n };\n\n async function boot(def, warn, warnings) {\n const P = readParams();\n const ratio = q.get('ratio') || P.ratio || 'wide';\n const [W, H] = RATIOS[ratio] || RATIOS.wide;\n const { id: themeId, C, F } = resolveTheme(P);\n const timeScale = P.timeScale || 1;\n const duration = (P.duration || def.duration || 10) * timeScale;\n const fps = P.fps || 30;\n\n document.documentElement.style.background = capture ? C.bg : '#0b0b0a';\n document.body.style.margin = '0';\n const canvas = document.createElement('canvas');\n canvas.id = 'stage';\n canvas.width = W;\n canvas.height = H;\n const ctx = canvas.getContext('2d');\n\n const S = {\n W, H, ratio, P, C, F, themeId, fps, duration, timeScale,\n u: Math.min(W, H) / 1080, // 1 unit = 1px at 1080 short side\n wide: ratio === 'wide', square: ratio === 'square', tall: ratio === 'tall',\n warn, lib: LIB_BASE, frame: 0, images: {}, beats: P.beats || {},\n };\n S.pick = (wide, square, tall) => (S.tall ? tall : S.square ? square : wide);\n\n const fontStatus = await loadFonts(F, warn);\n if (Object.values(fontStatus).some(value => value !== \"loaded\")) throw new Error(\"All registered font faces must load; fallback is not permitted.\");\n for (const [k, rel] of Object.entries(P.media || {})) {\n try { S.images[k] = await loadImage(new URL(rel, location.href).href); } catch (e) { warn(String(e.message)); }\n }\n if (def.setup) await def.setup(S, ctx);\n\n // Scenes with external frames (video clips) define `prepare(t, S)`; renderAt then returns a\n // promise that resolves after those frames are decoded, so captures stay frame-exact.\n function renderAt(t) {\n t = Math.max(0, Math.min(duration, t));\n if (def.prepare) {\n const token = (S._token = (S._token || 0) + 1);\n return Promise.resolve(def.prepare(t / timeScale, S)).then(() => (token === S._token ? paint(t) : false));\n }\n return paint(t);\n }\n function paint(t) {\n S.frame = Math.round(t * fps);\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.globalAlpha = 1;\n ctx.globalCompositeOperation = 'source-over';\n ctx.fillStyle = C.bg;\n ctx.fillRect(0, 0, W, H);\n def.draw(ctx, t / timeScale, S);\n return true;\n }\n\n const beatTime = v => (typeof v === 'number' ? v : (S.beats[v] ?? 0));\n // cues from params plus cues the scene derives from its own data (def.cues)\n const rawCues = P.sound?.enabled === false ? [] : [...((P.sound && P.sound.cues) || []), ...(def.cues ? def.cues(S) : [])];\n const cues = rawCues.map(c => ({\n t: +((beatTime(c.at) + (c.offset || 0)) * timeScale).toFixed(4),\n sfx: c.sfx, file: c.file, dur: c.dur, trim: c.trim, gain: c.gain ?? (c.file ? 0.3 : 1),\n })).sort((a, b) => a.t - b.t);\n\n window.renderAt = renderAt;\n window.__sceneMeta = { id: def.id, W, H, ratio, fps, duration, frames: Math.round(duration * fps), theme: themeId, cues, timeScale, music: P.sound?.enabled === false ? null : P.sound?.music || null, voice: P.sound?.enabled === false ? null : P.sound?.voice || null, loudness: P.sound?.enabled === false ? null : P.sound?.loudness || null };\n window.getDiagnostics = () => ({ fonts: fontStatus, warnings: [...warnings], meta: window.__sceneMeta });\n\n document.body.appendChild(canvas);\n if (capture) {\n canvas.style.cssText = 'display:block';\n await renderAt(+(q.get('t') || 0));\n window.__ready = true;\n return;\n }\n preview(canvas, renderAt, S, cues);\n window.__ready = true;\n }\n\n // ---------- interactive preview (never used for rendering) ----------\n function preview(canvas, renderAt, S, cues) {\n const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;\n const showControls = q.get('controls') !== '0';\n const style = document.createElement('style');\n style.textContent = `\n body{height:100vh;display:flex;flex-direction:column;font:13px/1.3 -apple-system,system-ui,sans-serif;color:#e9e4da;background:#0b0b0a}\n #wrap{flex:1;display:flex;align-items:center;justify-content:center;min-height:0;padding:${showControls ? '12px' : '0'}}\n #stage{max-width:100%;max-height:100%;width:auto;height:auto;box-shadow:0 10px 40px rgba(0,0,0,.45)}\n #bar{display:flex;gap:10px;align-items:center;padding:10px 14px;background:#151412;border-top:1px solid #2a2824;flex-wrap:wrap}\n #bar button,#bar select{background:#24221f;color:#e9e4da;border:1px solid #3a3732;border-radius:6px;padding:5px 9px;font:inherit;cursor:pointer}\n #bar button.on{background:#E89A4A;color:#1b1a18;border-color:#E89A4A}\n #bar input[type=range]{flex:1;min-width:160px;accent-color:#E89A4A}\n #tm{font-variant-numeric:tabular-nums;min-width:92px}`;\n document.head.appendChild(style);\n const wrap = document.createElement('div');\n wrap.id = 'wrap';\n document.body.appendChild(wrap);\n wrap.appendChild(canvas);\n\n let t = q.has('t') ? +q.get('t') : reduced ? (S.P.reducedHold ?? S.duration * 0.9) : 0;\n let playing = !reduced && q.get('autoplay') === '1';\n let last = null;\n let sound = q.get('sound') === '1';\n const audio = audioEngine(cues, S);\n\n let range, tm, playBtn, soundBtn;\n if (showControls) {\n const bar = document.createElement('div');\n bar.id = 'bar';\n bar.innerHTML = `<button id=\"pp\"></button><input id=\"rg\" type=\"range\" min=\"0\" max=\"${S.duration}\" step=\"${1 / S.fps}\"><span id=\"tm\"></span>\n <span>${['wide', 'square', 'tall'].map(r => `<button data-r=\"${r}\" class=\"${r === S.ratio ? 'on' : ''}\">${{ wide: '16:9', square: '1:1', tall: '9:16' }[r]}</button>`).join(' ')}</span>\n <select id=\"th\">${Object.entries(window.EB_THEMES).map(([k, v]) => `<option value=\"${k}\" ${k === S.themeId ? 'selected' : ''}>${v.label}</option>`).join('')}</select>\n <button id=\"snd\"></button>`;\n document.body.appendChild(bar);\n range = bar.querySelector('#rg');\n tm = bar.querySelector('#tm');\n playBtn = bar.querySelector('#pp');\n soundBtn = bar.querySelector('#snd');\n const go = (k, v) => { const u = new URL(location.href); u.searchParams.set(k, v); u.searchParams.delete('t'); location.href = u.href; };\n bar.querySelectorAll('[data-r]').forEach(b => b.onclick = () => go('ratio', b.dataset.r));\n bar.querySelector('#th').onchange = e => go('theme', e.target.value);\n playBtn.onclick = toggle;\n soundBtn.onclick = () => { sound = !sound; audio.stop(); if (sound && playing) audio.start(t); sync(); };\n range.oninput = () => { t = +range.value; audio.stop(); if (playing && sound) audio.start(t); draw(); };\n }\n addEventListener('keydown', e => { if (e.code === 'Space') { e.preventDefault(); toggle(); } });\n canvas.onclick = toggle;\n function toggle() {\n playing = !playing;\n if (playing && t >= S.duration - 0.01) t = 0;\n last = null;\n audio.stop();\n if (playing && sound) audio.start(t);\n sync();\n }\n function sync() {\n if (!showControls) return;\n playBtn.textContent = playing ? 'Pausa' : 'Reproducir';\n soundBtn.textContent = sound ? 'Sonido: s\xED' : 'Sonido: no';\n soundBtn.className = sound ? 'on' : '';\n soundBtn.disabled = !cues.length;\n if (!cues.length) soundBtn.textContent = 'Sin sonido';\n }\n function draw() {\n renderAt(t);\n if (showControls) {\n range.value = t;\n tm.textContent = `${t.toFixed(2)} / ${S.duration.toFixed(1)} s`;\n }\n }\n // Pause off-screen / hidden tabs.\n let visible = true;\n new IntersectionObserver(es => { visible = es[0].isIntersecting; }).observe(canvas);\n function loop(now) {\n if (playing && visible && !document.hidden) {\n if (last !== null) t += (now - last) / 1000;\n if (t >= S.duration) {\n t = q.get('loop') === '0' ? S.duration : 0;\n if (q.get('loop') === '0') playing = false;\n audio.stop();\n if (playing && sound) audio.start(t);\n }\n draw();\n }\n last = playing ? now : null;\n requestAnimationFrame(loop);\n }\n sync();\n draw();\n requestAnimationFrame(loop);\n }\n\n // Preview-only audio: schedules the scene's cues from the synthesized SFX bank.\n function audioEngine(cues, S) {\n let ac = null, nodes = [];\n const buffers = {};\n async function buf(name) {\n if (!buffers[name]) {\n const r = await fetch(new URL(`sfx/${name}.wav`, S.lib));\n buffers[name] = await ac.decodeAudioData(await r.arrayBuffer());\n }\n return buffers[name];\n }\n return {\n async start(from) {\n if (!cues.length) return;\n ac = ac || new AudioContext();\n const t0 = ac.currentTime + 0.05;\n for (const c of cues) {\n if (c.t < from - 0.02) continue;\n const b = await buf(c.sfx);\n const src = ac.createBufferSource(), g = ac.createGain();\n src.buffer = b;\n g.gain.value = c.gain;\n src.connect(g).connect(ac.destination);\n src.start(t0 + (c.t - from));\n nodes.push(src);\n }\n },\n stop() { nodes.forEach(n => { try { n.stop(); } catch (e) {} }); nodes = []; },\n };\n }\n})();\n",
183478
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
183479
+ (function () {
183480
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
183481
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
183482
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
183483
+ const fonts = ['display','text','heavy','mono','hand'];
183484
+ window.EB_VALIDATE_PARAMS = (p, q) => {
183485
+ const theme = q.get('theme') || p.theme;
183486
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
183487
+ const ratio = q.get('ratio') || p.ratio || 'wide';
183488
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
183489
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
183490
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
183491
+ }
183492
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
183493
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
183494
+ if (q.get('demo') === '1') return;
183495
+ const b = window.__overrides?.brand;
183496
+ if (!record(b) || !record(b.colors) || !record(b.fonts)) fail('provide complete window.__overrides.brand from the selected project; demo themes are not customer defaults');
183497
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
183498
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
183499
+ if (!Array.isArray(b.series) || b.series.length < 6 || b.series.some(c => !/^#[0-9a-f]{6}$/i.test(c))) fail('provide at least six explicit series hex colors; roles may repeat project colors but never inherit demo colors');
183500
+ for (const role of fonts) {
183501
+ const font = b.fonts[role];
183502
+ if (!record(font) || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) fail('provide explicit family, weight and style for font role ' + role);
183503
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
183504
+ }
183505
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
183506
+ };
183507
+ })();
183508
+
183509
+ (function () {
183510
+ const base = window.EB_VALIDATE_PARAMS;
183511
+ const roles = ["bg","capFill","capShadow","capStroke","credit","dot","paperBottom","paperTop"];
183512
+ const fontRoles = ["caption","credit"];
183513
+ window.EB_VALIDATE_PARAMS = (params, query) => {
183514
+ base(params, query);
183515
+ if (query.get('demo') === '1') return;
183516
+ for (const role of roles) {
183517
+ if (!/^#[0-9a-f]{6}$/i.test(window.__overrides?.brand?.colors?.[role] || '')) throw new Error('EditorBrain project binding: provide scene-specific color role ' + role + '; never inherit demo/preset brand colors.');
183518
+ }
183519
+ for (const role of fontRoles) {
183520
+ const font = window.__overrides?.brand?.fonts?.[role];
183521
+ if (!font || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) throw new Error('EditorBrain project binding: provide complete scene-specific font role ' + role + '; never inherit demo/preset typography.');
183522
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183523
+ }
183524
+ };
183525
+ })();
183526
+ `
183527
+ },
183528
+ "infografia-de-objetos": {
183529
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
183530
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
183531
+ "runtime": "// EditorBrain authored motion \xB7 scene runtime.\n// One canvas, explicit time: window.renderAt(seconds) draws the exact state for that time.\n// URL: ?ratio=wide|square|tall &theme=<kit> &t=<sec> &capture=1 &autoplay=1 &controls=0\n(function () {\n const RATIOS = { wide: [1920, 1080], square: [1080, 1080], tall: [1080, 1920] };\n const LIB_BASE = new URL('..', document.currentScript.src).href; // library root\n const q = new URLSearchParams(location.search);\n const capture = q.get('capture') === '1';\n\n const isObj = v => v && typeof v === 'object' && !Array.isArray(v);\n const merge = (a, b) => {\n if (!isObj(b)) return b === undefined ? a : b;\n const out = { ...(isObj(a) ? a : {}) };\n for (const k of Object.keys(b)) out[k] = merge(out[k], b[k]);\n return out;\n };\n\n function readParams() {\n const el = document.getElementById('params');\n let p = el ? JSON.parse(el.textContent) : {};\n if (window.__overrides) p = merge(p, window.__overrides);\n const enc = q.get('params');\n if (enc) { const supplied = JSON.parse(decodeURIComponent(escape(atob(enc)))); window.__overrides = merge(window.__overrides || {}, supplied); p = merge(p, supplied); }\n window.EB_VALIDATE_PARAMS(p, q);\n return p;\n }\n\n async function loadFonts(F, warn) {\n const families = new Set(Object.values(F).map(f => f.family));\n const status = {};\n for (const fam of families) {\n const defs = (window.EB_FONTS || {})[fam];\n if (!defs) {\n status[fam] = 'not-registered';\n warn(`font family not registered: ${fam}`);\n continue;\n }\n const results = await Promise.all(defs.map(async d => {\n const src = d.local ? d.local.map(n => `local(\"${n}\")`).join(', ') : `url(\"${new URL(d.src, LIB_BASE).href}\")`;\n const desc = {};\n if (d.weight) desc.weight = d.weight;\n if (d.style) desc.style = d.style;\n if (d.stretch) desc.stretch = d.stretch;\n try {\n const face = new FontFace(fam, src, desc);\n await face.load();\n document.fonts.add(face);\n return true;\n } catch (e) {\n return false;\n }\n }));\n const ok = results.filter(Boolean).length;\n status[fam] = ok === defs.length ? 'loaded' : ok ? `partial ${ok}/${defs.length}` : 'missing';\n if (!ok) warn(`font unavailable, renderer would fall back: ${fam}`);\n }\n return status;\n }\n\n function loadImage(src) {\n return new Promise((res, rej) => {\n const img = new Image();\n img.onload = () => res(img);\n img.onerror = () => rej(new Error('image failed: ' + src));\n img.src = src;\n });\n }\n\n function resolveTheme(params) {\n const kits = window.EB_THEMES || {};\n const id = q.get('theme') || params.theme || Object.keys(kits)[0];\n const kit = kits[id] || kits[Object.keys(kits)[0]];\n const brand = params.brand || {};\n const C = { ...kit.colors, ...(brand.colors || {}) };\n C.series = brand.series || kit.series;\n const F = {};\n for (const role of new Set(['display', 'text', 'heavy', 'mono', 'hand', ...Object.keys(brand.fonts || {})])) F[role] = { ...(kit.fonts[role] || kit.fonts.text), ...((brand.fonts || {})[role] || {}) };\n return { id, kit, C, F };\n }\n\n window.EB = {\n RATIOS,\n scene(def) {\n const warnings = new Set();\n const warn = m => { warnings.add(m); if (q.get(\"demo\") !== \"1\") throw new Error(m); };\n try {\n void boot(def, warn, warnings).catch(e => { window.__motionError = String(e && e.stack || e); console.error(window.__motionError); });\n } catch (e) {\n window.__motionError = String(e && e.stack || e);\n throw e;\n }\n },\n };\n\n async function boot(def, warn, warnings) {\n const P = readParams();\n const ratio = q.get('ratio') || P.ratio || 'wide';\n const [W, H] = RATIOS[ratio] || RATIOS.wide;\n const { id: themeId, C, F } = resolveTheme(P);\n const timeScale = P.timeScale || 1;\n const duration = (P.duration || def.duration || 10) * timeScale;\n const fps = P.fps || 30;\n\n document.documentElement.style.background = capture ? C.bg : '#0b0b0a';\n document.body.style.margin = '0';\n const canvas = document.createElement('canvas');\n canvas.id = 'stage';\n canvas.width = W;\n canvas.height = H;\n const ctx = canvas.getContext('2d');\n\n const S = {\n W, H, ratio, P, C, F, themeId, fps, duration, timeScale,\n u: Math.min(W, H) / 1080, // 1 unit = 1px at 1080 short side\n wide: ratio === 'wide', square: ratio === 'square', tall: ratio === 'tall',\n warn, lib: LIB_BASE, frame: 0, images: {}, beats: P.beats || {},\n };\n S.pick = (wide, square, tall) => (S.tall ? tall : S.square ? square : wide);\n\n const fontStatus = await loadFonts(F, warn);\n if (Object.values(fontStatus).some(value => value !== \"loaded\")) throw new Error(\"All registered font faces must load; fallback is not permitted.\");\n for (const [k, rel] of Object.entries(P.media || {})) {\n try { S.images[k] = await loadImage(new URL(rel, location.href).href); } catch (e) { warn(String(e.message)); }\n }\n if (def.setup) await def.setup(S, ctx);\n\n // Scenes with external frames (video clips) define `prepare(t, S)`; renderAt then returns a\n // promise that resolves after those frames are decoded, so captures stay frame-exact.\n function renderAt(t) {\n t = Math.max(0, Math.min(duration, t));\n if (def.prepare) {\n const token = (S._token = (S._token || 0) + 1);\n return Promise.resolve(def.prepare(t / timeScale, S)).then(() => (token === S._token ? paint(t) : false));\n }\n return paint(t);\n }\n function paint(t) {\n S.frame = Math.round(t * fps);\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.globalAlpha = 1;\n ctx.globalCompositeOperation = 'source-over';\n ctx.fillStyle = C.bg;\n ctx.fillRect(0, 0, W, H);\n def.draw(ctx, t / timeScale, S);\n return true;\n }\n\n const beatTime = v => (typeof v === 'number' ? v : (S.beats[v] ?? 0));\n // cues from params plus cues the scene derives from its own data (def.cues)\n const rawCues = P.sound?.enabled === false ? [] : [...((P.sound && P.sound.cues) || []), ...(def.cues ? def.cues(S) : [])];\n const cues = rawCues.map(c => ({\n t: +((beatTime(c.at) + (c.offset || 0)) * timeScale).toFixed(4),\n sfx: c.sfx, file: c.file, dur: c.dur, trim: c.trim, gain: c.gain ?? (c.file ? 0.3 : 1),\n })).sort((a, b) => a.t - b.t);\n\n window.renderAt = renderAt;\n window.__sceneMeta = { id: def.id, W, H, ratio, fps, duration, frames: Math.round(duration * fps), theme: themeId, cues, timeScale, music: P.sound?.enabled === false ? null : P.sound?.music || null, voice: P.sound?.enabled === false ? null : P.sound?.voice || null, loudness: P.sound?.enabled === false ? null : P.sound?.loudness || null };\n window.getDiagnostics = () => ({ fonts: fontStatus, warnings: [...warnings], meta: window.__sceneMeta });\n\n document.body.appendChild(canvas);\n if (capture) {\n canvas.style.cssText = 'display:block';\n await renderAt(+(q.get('t') || 0));\n window.__ready = true;\n return;\n }\n preview(canvas, renderAt, S, cues);\n window.__ready = true;\n }\n\n // ---------- interactive preview (never used for rendering) ----------\n function preview(canvas, renderAt, S, cues) {\n const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;\n const showControls = q.get('controls') !== '0';\n const style = document.createElement('style');\n style.textContent = `\n body{height:100vh;display:flex;flex-direction:column;font:13px/1.3 -apple-system,system-ui,sans-serif;color:#e9e4da;background:#0b0b0a}\n #wrap{flex:1;display:flex;align-items:center;justify-content:center;min-height:0;padding:${showControls ? '12px' : '0'}}\n #stage{max-width:100%;max-height:100%;width:auto;height:auto;box-shadow:0 10px 40px rgba(0,0,0,.45)}\n #bar{display:flex;gap:10px;align-items:center;padding:10px 14px;background:#151412;border-top:1px solid #2a2824;flex-wrap:wrap}\n #bar button,#bar select{background:#24221f;color:#e9e4da;border:1px solid #3a3732;border-radius:6px;padding:5px 9px;font:inherit;cursor:pointer}\n #bar button.on{background:#E89A4A;color:#1b1a18;border-color:#E89A4A}\n #bar input[type=range]{flex:1;min-width:160px;accent-color:#E89A4A}\n #tm{font-variant-numeric:tabular-nums;min-width:92px}`;\n document.head.appendChild(style);\n const wrap = document.createElement('div');\n wrap.id = 'wrap';\n document.body.appendChild(wrap);\n wrap.appendChild(canvas);\n\n let t = q.has('t') ? +q.get('t') : reduced ? (S.P.reducedHold ?? S.duration * 0.9) : 0;\n let playing = !reduced && q.get('autoplay') === '1';\n let last = null;\n let sound = q.get('sound') === '1';\n const audio = audioEngine(cues, S);\n\n let range, tm, playBtn, soundBtn;\n if (showControls) {\n const bar = document.createElement('div');\n bar.id = 'bar';\n bar.innerHTML = `<button id=\"pp\"></button><input id=\"rg\" type=\"range\" min=\"0\" max=\"${S.duration}\" step=\"${1 / S.fps}\"><span id=\"tm\"></span>\n <span>${['wide', 'square', 'tall'].map(r => `<button data-r=\"${r}\" class=\"${r === S.ratio ? 'on' : ''}\">${{ wide: '16:9', square: '1:1', tall: '9:16' }[r]}</button>`).join(' ')}</span>\n <select id=\"th\">${Object.entries(window.EB_THEMES).map(([k, v]) => `<option value=\"${k}\" ${k === S.themeId ? 'selected' : ''}>${v.label}</option>`).join('')}</select>\n <button id=\"snd\"></button>`;\n document.body.appendChild(bar);\n range = bar.querySelector('#rg');\n tm = bar.querySelector('#tm');\n playBtn = bar.querySelector('#pp');\n soundBtn = bar.querySelector('#snd');\n const go = (k, v) => { const u = new URL(location.href); u.searchParams.set(k, v); u.searchParams.delete('t'); location.href = u.href; };\n bar.querySelectorAll('[data-r]').forEach(b => b.onclick = () => go('ratio', b.dataset.r));\n bar.querySelector('#th').onchange = e => go('theme', e.target.value);\n playBtn.onclick = toggle;\n soundBtn.onclick = () => { sound = !sound; audio.stop(); if (sound && playing) audio.start(t); sync(); };\n range.oninput = () => { t = +range.value; audio.stop(); if (playing && sound) audio.start(t); draw(); };\n }\n addEventListener('keydown', e => { if (e.code === 'Space') { e.preventDefault(); toggle(); } });\n canvas.onclick = toggle;\n function toggle() {\n playing = !playing;\n if (playing && t >= S.duration - 0.01) t = 0;\n last = null;\n audio.stop();\n if (playing && sound) audio.start(t);\n sync();\n }\n function sync() {\n if (!showControls) return;\n playBtn.textContent = playing ? 'Pausa' : 'Reproducir';\n soundBtn.textContent = sound ? 'Sonido: s\xED' : 'Sonido: no';\n soundBtn.className = sound ? 'on' : '';\n soundBtn.disabled = !cues.length;\n if (!cues.length) soundBtn.textContent = 'Sin sonido';\n }\n function draw() {\n renderAt(t);\n if (showControls) {\n range.value = t;\n tm.textContent = `${t.toFixed(2)} / ${S.duration.toFixed(1)} s`;\n }\n }\n // Pause off-screen / hidden tabs.\n let visible = true;\n new IntersectionObserver(es => { visible = es[0].isIntersecting; }).observe(canvas);\n function loop(now) {\n if (playing && visible && !document.hidden) {\n if (last !== null) t += (now - last) / 1000;\n if (t >= S.duration) {\n t = q.get('loop') === '0' ? S.duration : 0;\n if (q.get('loop') === '0') playing = false;\n audio.stop();\n if (playing && sound) audio.start(t);\n }\n draw();\n }\n last = playing ? now : null;\n requestAnimationFrame(loop);\n }\n sync();\n draw();\n requestAnimationFrame(loop);\n }\n\n // Preview-only audio: schedules the scene's cues from the synthesized SFX bank.\n function audioEngine(cues, S) {\n let ac = null, nodes = [];\n const buffers = {};\n async function buf(name) {\n if (!buffers[name]) {\n const r = await fetch(new URL(`sfx/${name}.wav`, S.lib));\n buffers[name] = await ac.decodeAudioData(await r.arrayBuffer());\n }\n return buffers[name];\n }\n return {\n async start(from) {\n if (!cues.length) return;\n ac = ac || new AudioContext();\n const t0 = ac.currentTime + 0.05;\n for (const c of cues) {\n if (c.t < from - 0.02) continue;\n const b = await buf(c.sfx);\n const src = ac.createBufferSource(), g = ac.createGain();\n src.buffer = b;\n g.gain.value = c.gain;\n src.connect(g).connect(ac.destination);\n src.start(t0 + (c.t - from));\n nodes.push(src);\n }\n },\n stop() { nodes.forEach(n => { try { n.stop(); } catch (e) {} }); nodes = []; },\n };\n }\n})();\n",
183532
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
183533
+ (function () {
183534
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
183535
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
183536
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
183537
+ const fonts = ['display','text','heavy','mono','hand'];
183538
+ window.EB_VALIDATE_PARAMS = (p, q) => {
183539
+ const theme = q.get('theme') || p.theme;
183540
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
183541
+ const ratio = q.get('ratio') || p.ratio || 'wide';
183542
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
183543
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
183544
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
183545
+ }
183546
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
183547
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
183548
+ if (q.get('demo') === '1') return;
183549
+ const b = window.__overrides?.brand;
183550
+ if (!record(b) || !record(b.colors) || !record(b.fonts)) fail('provide complete window.__overrides.brand from the selected project; demo themes are not customer defaults');
183551
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
183552
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
183553
+ if (!Array.isArray(b.series) || b.series.length < 6 || b.series.some(c => !/^#[0-9a-f]{6}$/i.test(c))) fail('provide at least six explicit series hex colors; roles may repeat project colors but never inherit demo colors');
183554
+ for (const role of fonts) {
183555
+ const font = b.fonts[role];
183556
+ if (!record(font) || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) fail('provide explicit family, weight and style for font role ' + role);
183557
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
183558
+ }
183559
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
183560
+ };
183561
+ })();
183562
+
183563
+ (function () {
183564
+ const base = window.EB_VALIDATE_PARAMS;
183565
+ const roles = ["accent","afterHead","beforeHead","bp","bpEdge","bpFill","bpLine","bpRed","bpSoft","card","chipDark","green","grid","ice","ink","ink2","muted","paper","paperCorner","paperEdge","pill","pillDim","pillText","red","slot","titleBottom","titleTop","yellow"];
183566
+ const fontRoles = ["cap","heavy","mono","name","small"];
183567
+ window.EB_VALIDATE_PARAMS = (params, query) => {
183568
+ base(params, query);
183569
+ if (query.get('demo') === '1') return;
183570
+ for (const role of roles) {
183571
+ if (!/^#[0-9a-f]{6}$/i.test(window.__overrides?.brand?.colors?.[role] || '')) throw new Error('EditorBrain project binding: provide scene-specific color role ' + role + '; never inherit demo/preset brand colors.');
183572
+ }
183573
+ for (const role of fontRoles) {
183574
+ const font = window.__overrides?.brand?.fonts?.[role];
183575
+ if (!font || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) throw new Error('EditorBrain project binding: provide complete scene-specific font role ' + role + '; never inherit demo/preset typography.');
183576
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183577
+ }
183578
+ };
183579
+ })();
183580
+ `
183581
+ },
183582
+ "ranking-con-escala": {
183583
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
183584
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
183585
+ "runtime": "// EditorBrain authored motion \xB7 scene runtime.\n// One canvas, explicit time: window.renderAt(seconds) draws the exact state for that time.\n// URL: ?ratio=wide|square|tall &theme=<kit> &t=<sec> &capture=1 &autoplay=1 &controls=0\n(function () {\n const RATIOS = { wide: [1920, 1080], square: [1080, 1080], tall: [1080, 1920] };\n const LIB_BASE = new URL('..', document.currentScript.src).href; // library root\n const q = new URLSearchParams(location.search);\n const capture = q.get('capture') === '1';\n\n const isObj = v => v && typeof v === 'object' && !Array.isArray(v);\n const merge = (a, b) => {\n if (!isObj(b)) return b === undefined ? a : b;\n const out = { ...(isObj(a) ? a : {}) };\n for (const k of Object.keys(b)) out[k] = merge(out[k], b[k]);\n return out;\n };\n\n function readParams() {\n const el = document.getElementById('params');\n let p = el ? JSON.parse(el.textContent) : {};\n if (window.__overrides) p = merge(p, window.__overrides);\n const enc = q.get('params');\n if (enc) { const supplied = JSON.parse(decodeURIComponent(escape(atob(enc)))); window.__overrides = merge(window.__overrides || {}, supplied); p = merge(p, supplied); }\n window.EB_VALIDATE_PARAMS(p, q);\n return p;\n }\n\n async function loadFonts(F, warn) {\n const families = new Set(Object.values(F).map(f => f.family));\n const status = {};\n for (const fam of families) {\n const defs = (window.EB_FONTS || {})[fam];\n if (!defs) {\n status[fam] = 'not-registered';\n warn(`font family not registered: ${fam}`);\n continue;\n }\n const results = await Promise.all(defs.map(async d => {\n const src = d.local ? d.local.map(n => `local(\"${n}\")`).join(', ') : `url(\"${new URL(d.src, LIB_BASE).href}\")`;\n const desc = {};\n if (d.weight) desc.weight = d.weight;\n if (d.style) desc.style = d.style;\n if (d.stretch) desc.stretch = d.stretch;\n try {\n const face = new FontFace(fam, src, desc);\n await face.load();\n document.fonts.add(face);\n return true;\n } catch (e) {\n return false;\n }\n }));\n const ok = results.filter(Boolean).length;\n status[fam] = ok === defs.length ? 'loaded' : ok ? `partial ${ok}/${defs.length}` : 'missing';\n if (!ok) warn(`font unavailable, renderer would fall back: ${fam}`);\n }\n return status;\n }\n\n function loadImage(src) {\n return new Promise((res, rej) => {\n const img = new Image();\n img.onload = () => res(img);\n img.onerror = () => rej(new Error('image failed: ' + src));\n img.src = src;\n });\n }\n\n function resolveTheme(params) {\n const kits = window.EB_THEMES || {};\n const id = q.get('theme') || params.theme || Object.keys(kits)[0];\n const kit = kits[id] || kits[Object.keys(kits)[0]];\n const brand = params.brand || {};\n const C = { ...kit.colors, ...(brand.colors || {}) };\n C.series = brand.series || kit.series;\n const F = {};\n for (const role of new Set(['display', 'text', 'heavy', 'mono', 'hand', ...Object.keys(brand.fonts || {})])) F[role] = { ...(kit.fonts[role] || kit.fonts.text), ...((brand.fonts || {})[role] || {}) };\n return { id, kit, C, F };\n }\n\n window.EB = {\n RATIOS,\n scene(def) {\n const warnings = new Set();\n const warn = m => { warnings.add(m); if (q.get(\"demo\") !== \"1\") throw new Error(m); };\n try {\n void boot(def, warn, warnings).catch(e => { window.__motionError = String(e && e.stack || e); console.error(window.__motionError); });\n } catch (e) {\n window.__motionError = String(e && e.stack || e);\n throw e;\n }\n },\n };\n\n async function boot(def, warn, warnings) {\n const P = readParams();\n const ratio = q.get('ratio') || P.ratio || 'wide';\n const [W, H] = RATIOS[ratio] || RATIOS.wide;\n const { id: themeId, C, F } = resolveTheme(P);\n const timeScale = P.timeScale || 1;\n const duration = (P.duration || def.duration || 10) * timeScale;\n const fps = P.fps || 30;\n\n document.documentElement.style.background = capture ? C.bg : '#0b0b0a';\n document.body.style.margin = '0';\n const canvas = document.createElement('canvas');\n canvas.id = 'stage';\n canvas.width = W;\n canvas.height = H;\n const ctx = canvas.getContext('2d');\n\n const S = {\n W, H, ratio, P, C, F, themeId, fps, duration, timeScale,\n u: Math.min(W, H) / 1080, // 1 unit = 1px at 1080 short side\n wide: ratio === 'wide', square: ratio === 'square', tall: ratio === 'tall',\n warn, lib: LIB_BASE, frame: 0, images: {}, beats: P.beats || {},\n };\n S.pick = (wide, square, tall) => (S.tall ? tall : S.square ? square : wide);\n\n const fontStatus = await loadFonts(F, warn);\n if (Object.values(fontStatus).some(value => value !== \"loaded\")) throw new Error(\"All registered font faces must load; fallback is not permitted.\");\n for (const [k, rel] of Object.entries(P.media || {})) {\n try { S.images[k] = await loadImage(new URL(rel, location.href).href); } catch (e) { warn(String(e.message)); }\n }\n if (def.setup) await def.setup(S, ctx);\n\n // Scenes with external frames (video clips) define `prepare(t, S)`; renderAt then returns a\n // promise that resolves after those frames are decoded, so captures stay frame-exact.\n function renderAt(t) {\n t = Math.max(0, Math.min(duration, t));\n if (def.prepare) {\n const token = (S._token = (S._token || 0) + 1);\n return Promise.resolve(def.prepare(t / timeScale, S)).then(() => (token === S._token ? paint(t) : false));\n }\n return paint(t);\n }\n function paint(t) {\n S.frame = Math.round(t * fps);\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.globalAlpha = 1;\n ctx.globalCompositeOperation = 'source-over';\n ctx.fillStyle = C.bg;\n ctx.fillRect(0, 0, W, H);\n def.draw(ctx, t / timeScale, S);\n return true;\n }\n\n const beatTime = v => (typeof v === 'number' ? v : (S.beats[v] ?? 0));\n // cues from params plus cues the scene derives from its own data (def.cues)\n const rawCues = P.sound?.enabled === false ? [] : [...((P.sound && P.sound.cues) || []), ...(def.cues ? def.cues(S) : [])];\n const cues = rawCues.map(c => ({\n t: +((beatTime(c.at) + (c.offset || 0)) * timeScale).toFixed(4),\n sfx: c.sfx, file: c.file, dur: c.dur, trim: c.trim, gain: c.gain ?? (c.file ? 0.3 : 1),\n })).sort((a, b) => a.t - b.t);\n\n window.renderAt = renderAt;\n window.__sceneMeta = { id: def.id, W, H, ratio, fps, duration, frames: Math.round(duration * fps), theme: themeId, cues, timeScale, music: P.sound?.enabled === false ? null : P.sound?.music || null, voice: P.sound?.enabled === false ? null : P.sound?.voice || null, loudness: P.sound?.enabled === false ? null : P.sound?.loudness || null };\n window.getDiagnostics = () => ({ fonts: fontStatus, warnings: [...warnings], meta: window.__sceneMeta });\n\n document.body.appendChild(canvas);\n if (capture) {\n canvas.style.cssText = 'display:block';\n await renderAt(+(q.get('t') || 0));\n window.__ready = true;\n return;\n }\n preview(canvas, renderAt, S, cues);\n window.__ready = true;\n }\n\n // ---------- interactive preview (never used for rendering) ----------\n function preview(canvas, renderAt, S, cues) {\n const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;\n const showControls = q.get('controls') !== '0';\n const style = document.createElement('style');\n style.textContent = `\n body{height:100vh;display:flex;flex-direction:column;font:13px/1.3 -apple-system,system-ui,sans-serif;color:#e9e4da;background:#0b0b0a}\n #wrap{flex:1;display:flex;align-items:center;justify-content:center;min-height:0;padding:${showControls ? '12px' : '0'}}\n #stage{max-width:100%;max-height:100%;width:auto;height:auto;box-shadow:0 10px 40px rgba(0,0,0,.45)}\n #bar{display:flex;gap:10px;align-items:center;padding:10px 14px;background:#151412;border-top:1px solid #2a2824;flex-wrap:wrap}\n #bar button,#bar select{background:#24221f;color:#e9e4da;border:1px solid #3a3732;border-radius:6px;padding:5px 9px;font:inherit;cursor:pointer}\n #bar button.on{background:#E89A4A;color:#1b1a18;border-color:#E89A4A}\n #bar input[type=range]{flex:1;min-width:160px;accent-color:#E89A4A}\n #tm{font-variant-numeric:tabular-nums;min-width:92px}`;\n document.head.appendChild(style);\n const wrap = document.createElement('div');\n wrap.id = 'wrap';\n document.body.appendChild(wrap);\n wrap.appendChild(canvas);\n\n let t = q.has('t') ? +q.get('t') : reduced ? (S.P.reducedHold ?? S.duration * 0.9) : 0;\n let playing = !reduced && q.get('autoplay') === '1';\n let last = null;\n let sound = q.get('sound') === '1';\n const audio = audioEngine(cues, S);\n\n let range, tm, playBtn, soundBtn;\n if (showControls) {\n const bar = document.createElement('div');\n bar.id = 'bar';\n bar.innerHTML = `<button id=\"pp\"></button><input id=\"rg\" type=\"range\" min=\"0\" max=\"${S.duration}\" step=\"${1 / S.fps}\"><span id=\"tm\"></span>\n <span>${['wide', 'square', 'tall'].map(r => `<button data-r=\"${r}\" class=\"${r === S.ratio ? 'on' : ''}\">${{ wide: '16:9', square: '1:1', tall: '9:16' }[r]}</button>`).join(' ')}</span>\n <select id=\"th\">${Object.entries(window.EB_THEMES).map(([k, v]) => `<option value=\"${k}\" ${k === S.themeId ? 'selected' : ''}>${v.label}</option>`).join('')}</select>\n <button id=\"snd\"></button>`;\n document.body.appendChild(bar);\n range = bar.querySelector('#rg');\n tm = bar.querySelector('#tm');\n playBtn = bar.querySelector('#pp');\n soundBtn = bar.querySelector('#snd');\n const go = (k, v) => { const u = new URL(location.href); u.searchParams.set(k, v); u.searchParams.delete('t'); location.href = u.href; };\n bar.querySelectorAll('[data-r]').forEach(b => b.onclick = () => go('ratio', b.dataset.r));\n bar.querySelector('#th').onchange = e => go('theme', e.target.value);\n playBtn.onclick = toggle;\n soundBtn.onclick = () => { sound = !sound; audio.stop(); if (sound && playing) audio.start(t); sync(); };\n range.oninput = () => { t = +range.value; audio.stop(); if (playing && sound) audio.start(t); draw(); };\n }\n addEventListener('keydown', e => { if (e.code === 'Space') { e.preventDefault(); toggle(); } });\n canvas.onclick = toggle;\n function toggle() {\n playing = !playing;\n if (playing && t >= S.duration - 0.01) t = 0;\n last = null;\n audio.stop();\n if (playing && sound) audio.start(t);\n sync();\n }\n function sync() {\n if (!showControls) return;\n playBtn.textContent = playing ? 'Pausa' : 'Reproducir';\n soundBtn.textContent = sound ? 'Sonido: s\xED' : 'Sonido: no';\n soundBtn.className = sound ? 'on' : '';\n soundBtn.disabled = !cues.length;\n if (!cues.length) soundBtn.textContent = 'Sin sonido';\n }\n function draw() {\n renderAt(t);\n if (showControls) {\n range.value = t;\n tm.textContent = `${t.toFixed(2)} / ${S.duration.toFixed(1)} s`;\n }\n }\n // Pause off-screen / hidden tabs.\n let visible = true;\n new IntersectionObserver(es => { visible = es[0].isIntersecting; }).observe(canvas);\n function loop(now) {\n if (playing && visible && !document.hidden) {\n if (last !== null) t += (now - last) / 1000;\n if (t >= S.duration) {\n t = q.get('loop') === '0' ? S.duration : 0;\n if (q.get('loop') === '0') playing = false;\n audio.stop();\n if (playing && sound) audio.start(t);\n }\n draw();\n }\n last = playing ? now : null;\n requestAnimationFrame(loop);\n }\n sync();\n draw();\n requestAnimationFrame(loop);\n }\n\n // Preview-only audio: schedules the scene's cues from the synthesized SFX bank.\n function audioEngine(cues, S) {\n let ac = null, nodes = [];\n const buffers = {};\n async function buf(name) {\n if (!buffers[name]) {\n const r = await fetch(new URL(`sfx/${name}.wav`, S.lib));\n buffers[name] = await ac.decodeAudioData(await r.arrayBuffer());\n }\n return buffers[name];\n }\n return {\n async start(from) {\n if (!cues.length) return;\n ac = ac || new AudioContext();\n const t0 = ac.currentTime + 0.05;\n for (const c of cues) {\n if (c.t < from - 0.02) continue;\n const b = await buf(c.sfx);\n const src = ac.createBufferSource(), g = ac.createGain();\n src.buffer = b;\n g.gain.value = c.gain;\n src.connect(g).connect(ac.destination);\n src.start(t0 + (c.t - from));\n nodes.push(src);\n }\n },\n stop() { nodes.forEach(n => { try { n.stop(); } catch (e) {} }); nodes = []; },\n };\n }\n})();\n",
183586
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
183587
+ (function () {
183588
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
183589
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
183590
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
183591
+ const fonts = ['display','text','heavy','mono','hand'];
183592
+ window.EB_VALIDATE_PARAMS = (p, q) => {
183593
+ const theme = q.get('theme') || p.theme;
183594
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
183595
+ const ratio = q.get('ratio') || p.ratio || 'wide';
183596
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
183597
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
183598
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
183599
+ }
183600
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
183601
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
183602
+ if (q.get('demo') === '1') return;
183603
+ const b = window.__overrides?.brand;
183604
+ if (!record(b) || !record(b.colors) || !record(b.fonts)) fail('provide complete window.__overrides.brand from the selected project; demo themes are not customer defaults');
183605
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
183606
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
183607
+ if (!Array.isArray(b.series) || b.series.length < 6 || b.series.some(c => !/^#[0-9a-f]{6}$/i.test(c))) fail('provide at least six explicit series hex colors; roles may repeat project colors but never inherit demo colors');
183608
+ for (const role of fonts) {
183609
+ const font = b.fonts[role];
183610
+ if (!record(font) || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) fail('provide explicit family, weight and style for font role ' + role);
183611
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
183612
+ }
183613
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
183614
+ };
183615
+ })();
183616
+
183617
+ (function () {
183618
+ const base = window.EB_VALIDATE_PARAMS;
183619
+ const roles = ["bg","credit","hookBox","hookInk","pill","pillInk","scaleInk","scoreInk","title"];
183620
+ const fontRoles = ["credit","hook","pill","scale","score","title"];
183621
+ window.EB_VALIDATE_PARAMS = (params, query) => {
183622
+ base(params, query);
183623
+ if (query.get('demo') === '1') return;
183624
+ for (const role of roles) {
183625
+ if (!/^#[0-9a-f]{6}$/i.test(window.__overrides?.brand?.colors?.[role] || '')) throw new Error('EditorBrain project binding: provide scene-specific color role ' + role + '; never inherit demo/preset brand colors.');
183626
+ }
183627
+ for (const role of fontRoles) {
183628
+ const font = window.__overrides?.brand?.fonts?.[role];
183629
+ if (!font || typeof font.family !== 'string' || !font.family.trim() || !Number.isFinite(font.weight) || font.weight < 100 || font.weight > 1000 || !['normal','italic','oblique'].includes(font.style)) throw new Error('EditorBrain project binding: provide complete scene-specific font role ' + role + '; never inherit demo/preset typography.');
183630
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183631
+ }
183632
+ };
183633
+ })();
183634
+ `
183635
+ }
183636
+ };
183637
+
183638
+ // packages/cli/src/style-sources.ts
183639
+ async function downloadStyle(client, id2, version, root, out) {
183640
+ const result2 = await client.request("/v1/style-packs");
183641
+ const selected = result2.sourceStyles?.find((s) => s.id === id2 && s.sourceVersion === version);
183642
+ if (!selected) throw new Error("Exact style source not advertised by the service. Update EditorBrain or choose an available version; do not reconstruct silently.");
183643
+ return downloadPinnedSource(client, { id: id2, version, sha256: selected.sourceSha256, bytes: selected.sourceBytes }, root, out, "style");
183644
+ }
183645
+ async function prepareStyleSource(root, id2, version, file, out) {
183646
+ const selected = getStyleSource(id2, version), guard = styleSourceGuards[id2];
183647
+ if (!selected || !guard) throw new Error("This CLI cannot prepare the exact style version. Update EditorBrain; no version was substituted.");
183648
+ const input = await checkedPath(root, file, false), handle = await open3(input, constants2.O_RDONLY | constants2.O_NOFOLLOW);
183649
+ let bytes;
183650
+ try {
183651
+ const stat = await handle.stat();
183652
+ if (!stat.isFile() || stat.size !== selected.sourceBytes || stat.size > STYLE_SOURCE_MAX_BYTES) throw new Error("Style archive size mismatch");
183653
+ bytes = await handle.readFile();
183654
+ } finally {
183655
+ await handle.close();
183656
+ }
183657
+ const { files } = readStyleArchive(bytes, { id: id2, version, sha256: selected.sourceSha256, bytes: selected.sourceBytes, fileCount: selected.fileCount, unpackedBytes: selected.unpackedBytes });
183658
+ const entry = `styles/${id2}/scene.html`, originalRuntime = files.get("lib/runtime.js");
183659
+ if (!originalRuntime || archiveHash(originalRuntime) !== guard.runtimeSha256 || archiveHash(guard.runtime) !== guard.adaptedRuntimeSha256) throw new Error("Runtime guard pin mismatch");
183660
+ const html = files.get(entry)?.toString("utf8"), marker = '<script src="../../lib/runtime.js"></script>';
183661
+ if (!html || html.split(marker).length !== 2) throw new Error("Unsupported scene entrypoint");
183662
+ files.set(entry, Buffer.from(html.replace(marker, '<script src="../../lib/project-binding.js"></script>\n' + marker)));
183663
+ files.set("lib/runtime.js", Buffer.from(guard.runtime));
183664
+ files.set("lib/project-binding.js", Buffer.from(guard.guard));
183665
+ const guide = `# Copia de trabajo protegida
183666
+
183667
+ Original: ${id2} ${version}, SHA-256 ${selected.sourceSha256}. BUNDLE-MANIFEST.json describe el archivo original; PROJECT-BINDING.json describe esta adaptaci\xF3n de seguridad. No afirmes que el runtime modificado es id\xE9ntico al original.
183668
+
183669
+ Lee las gu\xEDas guardadas en .editorbrain/styles/${id2}/style.md (package/style.md del README original se refiere a esas gu\xEDas, no a una carpeta incluida). Conserva la coreograf\xEDa del estilo y adapta la historia, duraci\xF3n y contenido.
183670
+
183671
+ Antes de runtime.js, define window.__overrides (o usa --params con el renderizador incluido): marca completa del proyecto, colores base y espec\xEDficos de esta escena, fuentes registradas con todos los roles, e indica sound.enabled expl\xEDcitamente. Nunca heredes colores, palabras, avatar, voz, cifras ni medios ficticios de la demo para un cliente. El campo sound.enabled=false silencia tambi\xE9n la voz: respeta el contrato del mezclador y revisa la pista final; no lo confundas con solo desactivar SFX.
183672
+
183673
+ Para inspecci\xF3n del original sirve la copia local y abre ${entry}?demo=1&ratio=tall. Este bypass es solo inspecci\xF3n; no usarlo para producir al cliente. La descarga no ejecut\xF3 c\xF3digo ni instal\xF3 herramientas. Revisa README.md, LICENSES.md, package.json y tools/ antes de ejecutar deliberadamente. Usa una carpeta nueva para cada adaptaci\xF3n y conserva el original.
183674
+
183675
+ El renderer admite --params; valida __ready/__motionError, fuentes, tiempos y audio. Solo 9:16 est\xE1 compuesto aqu\xED. talking_head_prep.py/track.swift usan Apple Vision en macOS; en Linux/Windows usa presenter matte con un motor compatible disponible y aporta clip.mp4, person.webm con alfa, track.json, voice.wav y words.json con el mismo contrato. No ejecutes Swift ni inventes una instalaci\xF3n autom\xE1tica. La transcripci\xF3n/generaci\xF3n debe respetar las integraciones y presupuesto del cliente.
183676
+
183677
+ Un render de demo no certifica transferencia. Revisa el video completo y registra la revisi\xF3n antes de entregar.
183678
+ `;
183679
+ const receipt = { schemaVersion: 1, id: id2, version, sourceSha256: selected.sourceSha256, originalRuntimeSha256: guard.runtimeSha256, adaptedRuntimeSha256: guard.adaptedRuntimeSha256, guardSha256: archiveHash(guard.guard), entrySha256: archiveHash(files.get(entry)), brandBound: false, executed: false, rendered: false };
183680
+ files.set("PROJECT-BINDING.md", Buffer.from(guide));
183681
+ files.set("PROJECT-BINDING.json", Buffer.from(JSON.stringify(receipt, null, 2) + "\n"));
183682
+ const target = await checkedPath(root, out, false);
183683
+ await mkdir3(dirname3(target), { recursive: true });
183684
+ await checkedPath(root, out, false);
183685
+ await mkdir3(target, { mode: 448 });
183686
+ try {
183687
+ for (const [name, data] of files) {
183688
+ const destination = await checkedPath(target, name, false);
183689
+ await mkdir3(dirname3(destination), { recursive: true });
183690
+ await writeFile(destination, data, { flag: "wx", mode: 384 });
183691
+ }
183692
+ } catch (error) {
183693
+ await rm(target, { recursive: true, force: true });
183694
+ throw error;
183695
+ }
183696
+ return { ...receipt, path: target, extracted: true, next: "Read PROJECT-BINDING.md and the selected style guides. Bind current project preferences and replace demo media before explicitly rendering. No dependencies installed." };
183697
+ }
183698
+
183699
+ // packages/cli/src/team-command.ts
183700
+ async function teamCommand(client, subcommand, flags) {
183701
+ const value = (key) => {
183702
+ const v = flags[key];
183703
+ return typeof v === "string" ? v : void 0;
183704
+ };
183705
+ const required = (key) => {
183706
+ const v = value(key);
183707
+ if (!v) throw new Error(`Missing --${key}`);
183708
+ return v;
183709
+ };
183710
+ const common = ["url", "dir"];
183711
+ const allowed = {
183712
+ access: [],
183713
+ members: [],
183714
+ projects: [],
183715
+ invite: ["email", "kind", "scope"],
183716
+ cancel: ["id"],
183717
+ remove: ["user", "confirm"],
183718
+ reviews: ["project", "after"],
183719
+ share: ["project", "revision", "confirm"],
183720
+ withdraw: ["project", "revision", "confirm"],
183721
+ comment: ["project", "revision", "context-version", "text", "at-ms", "id"],
183722
+ approve: ["project", "revision", "context-version", "user-confirmed"]
183723
+ };
183724
+ if (!subcommand || !allowed[subcommand])
183725
+ throw new Error(
183726
+ "Use team access|members|projects|invite|cancel|remove|reviews|share|withdraw|comment|approve."
183727
+ );
183728
+ for (const key of Object.keys(flags))
183729
+ if (!common.includes(key) && !allowed[subcommand].includes(key))
183730
+ throw new Error(`--${key} is not supported for team ${subcommand}.`);
183731
+ if (subcommand === "access") return client.request("/v1/team");
183732
+ if (["members", "projects"].includes(subcommand))
183733
+ return client.request("/v1/team/" + subcommand);
183734
+ if (subcommand === "invite") {
183735
+ const kind = required("kind");
183736
+ if (!["brand_editor", "project_reviewer"].includes(kind))
183737
+ throw new Error("Use --kind brand_editor or project_reviewer.");
183738
+ return client.request("/v1/team/invitations", {
183739
+ method: "POST",
183740
+ body: { email: required("email"), kind, scopeId: required("scope") }
183741
+ });
183742
+ }
183743
+ if (subcommand === "cancel")
183744
+ return client.request(
183745
+ "/v1/team/invitations/" + encodeURIComponent(required("id")),
183746
+ { method: "DELETE" }
183747
+ );
183748
+ if (subcommand === "remove") {
183749
+ if (flags.confirm !== true)
183750
+ throw new Error(
183751
+ "Removing access requires --confirm after the user requests removal. Files are preserved."
183752
+ );
183753
+ return client.request(
183754
+ "/v1/team/members/" + encodeURIComponent(required("user")),
183755
+ { method: "DELETE" }
183756
+ );
183757
+ }
183758
+ const base = "/v1/team/projects/" + encodeURIComponent(required("project")) + "/reviews";
183759
+ if (subcommand === "reviews")
183760
+ return client.request(
183761
+ base + (value("after") ? "?after=" + encodeURIComponent(value("after")) : "")
183762
+ );
183763
+ const revision2 = required("revision");
183764
+ if (!/^[a-f0-9-]{36}$/.test(revision2))
183765
+ throw new Error("Use the exact revision UUID returned by team reviews.");
183766
+ if (["share", "withdraw"].includes(subcommand)) {
183767
+ if (flags.confirm !== true)
183768
+ throw new Error(
183769
+ "Use --confirm for an explicitly requested sharing change."
183770
+ );
183771
+ return client.request(base + "/" + revision2 + "/share", {
183772
+ method: "POST",
183773
+ body: { shared: subcommand === "share" }
183774
+ });
183775
+ }
183776
+ const contextVersion = required("context-version");
183777
+ if (!/^[a-f0-9]{64}$/.test(contextVersion))
183778
+ throw new Error("Use the exact context hash of the reviewed sample.");
183779
+ if (subcommand === "approve") {
183780
+ if (flags["user-confirmed"] !== true)
183781
+ throw new Error(
183782
+ "Approval requires explicit user acceptance and --user-confirmed."
183783
+ );
183784
+ return client.request(base + "/" + revision2 + "/approve", {
183785
+ method: "POST",
183786
+ body: { contextVersion, userConfirmed: true }
183787
+ });
183788
+ }
183789
+ const at = value("at-ms"), startMs = at === void 0 ? void 0 : Number(at);
183790
+ if (startMs !== void 0 && (!Number.isSafeInteger(startMs) || startMs < 0 || startMs > 36e6))
183791
+ throw new Error("--at-ms must be an integer between 0 and 36000000.");
183792
+ const feedbackId = required("id");
183793
+ if (!/^[a-f0-9-]{36}$/.test(feedbackId))
183794
+ throw new Error(
183795
+ "Use --id with a fresh UUID; reuse it for retries of this exact comment."
183796
+ );
183797
+ return client.request(base + "/" + revision2 + "/comment", {
183798
+ method: "POST",
183799
+ body: {
183800
+ contextVersion,
183801
+ feedbackId,
183802
+ text: required("text"),
183803
+ target: startMs === void 0 ? {} : { startMs }
183804
+ }
183805
+ });
183806
+ }
183807
+
183808
+ // packages/cli/src/personal-resources.ts
183809
+ import { basename, extname as extname2, resolve as resolve3 } from "node:path";
183810
+ import { randomUUID as randomUUID3 } from "node:crypto";
183811
+
183812
+ // packages/cli/src/media-runtime.ts
183813
+ import { spawn } from "node:child_process";
183814
+ import { createHash as createHash3 } from "node:crypto";
182386
183815
  import { constants as constants3 } from "node:fs";
182387
- import { mkdir as mkdir2, open as open3 } from "node:fs/promises";
182388
- import { dirname as dirname3 } from "node:path";
183816
+ import { lstat as lstat3, open as open4, realpath as realpath2 } from "node:fs/promises";
183817
+ import { dirname as dirname4, extname, parse, resolve as resolve2 } from "node:path";
183818
+ var MediaToolError = class extends CliError {
183819
+ constructor(code, message) {
183820
+ super(code, message, code === "MEDIA_TOOL_NOT_FOUND" ? "Install FFmpeg/FFprobe separately and make them available on PATH; no account or model is needed." : "Review the local input and reported limit. An incomplete check does not validate the media.");
183821
+ this.name = "MediaToolError";
183822
+ }
183823
+ };
183824
+ var SUPPORTED_MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
183825
+ ".mp4",
183826
+ ".mov",
183827
+ ".m4v",
183828
+ ".mkv",
183829
+ ".webm",
183830
+ ".avi",
183831
+ ".mpg",
183832
+ ".mpeg",
183833
+ ".mts",
183834
+ ".m2ts",
183835
+ ".ts",
183836
+ ".ogv",
183837
+ ".wmv",
183838
+ ".wav",
183839
+ ".mp3",
183840
+ ".m4a",
183841
+ ".aac",
183842
+ ".flac",
183843
+ ".ogg",
183844
+ ".opus",
183845
+ ".aif",
183846
+ ".aiff",
183847
+ ".ac3",
183848
+ ".eac3",
183849
+ ".jpg",
183850
+ ".jpeg",
183851
+ ".png",
183852
+ ".webp",
183853
+ ".bmp",
183854
+ ".tif",
183855
+ ".tiff",
183856
+ ".gif",
183857
+ ".avif",
183858
+ ".heic",
183859
+ ".heif"
183860
+ ]);
183861
+ var PROTOCOLS = "file,pipe";
183862
+ var FORMATS = "mov,matroska,webm,avi,mpeg,mpegts,ogg,wav,flac,mp3,aac,aiff,ac3,eac3,asf,jpeg_pipe,png_pipe,webp_pipe,bmp_pipe,tiff_pipe,gif,heif,avif";
183863
+ var DEFAULT_TIMEOUT = 3e4;
183864
+ var DEFAULT_OUTPUT_LIMIT = 2 * 1024 * 1024;
183865
+ function resolveLocalMediaPath(value) {
183866
+ if (!value || value.includes("\0") || /[\r\n]/.test(value) || /^[a-z][a-z\d+.-]*:/i.test(value) && !(process.platform === "win32" && /^[a-z]:[\\/]/i.test(value)) || value.startsWith("\\\\")) {
183867
+ throw new MediaToolError("MEDIA_LOCAL_PATH_REQUIRED", "Provide a local filesystem path, not a URL, protocol or network share.");
183868
+ }
183869
+ return resolve2(value);
183870
+ }
183871
+ async function assertNoMediaSymlinks(value) {
183872
+ const path = resolveLocalMediaPath(value);
183873
+ let cursor = path;
183874
+ while (cursor !== parse(cursor).root) {
183875
+ const info = await lstat3(cursor);
183876
+ if (info.isSymbolicLink()) {
183877
+ const systemAlias = process.platform === "darwin" && (cursor === "/tmp" || cursor === "/var") && await realpath2(cursor) === `/private${cursor}`;
183878
+ if (!systemAlias) throw new MediaToolError("MEDIA_SYMLINK", "Symlink media paths are not followed. Use the original local path.");
183879
+ }
183880
+ cursor = dirname4(cursor);
183881
+ }
183882
+ return path;
183883
+ }
183884
+ async function assertLocalMediaFile(value) {
183885
+ const path = await assertNoMediaSymlinks(value);
183886
+ const info = await lstat3(path);
183887
+ if (!info.isFile()) throw new MediaToolError("MEDIA_NOT_REGULAR", "The media input must be a regular local file.");
183888
+ if (!SUPPORTED_MEDIA_EXTENSIONS.has(extname(path).toLowerCase())) throw new MediaToolError("MEDIA_FORMAT_UNSUPPORTED", "This file extension is not supported for local media inspection.");
183889
+ return path;
183890
+ }
183891
+ function localInputArgs(path) {
183892
+ return ["-protocol_whitelist", PROTOCOLS, "-format_whitelist", FORMATS, "-i", resolveLocalMediaPath(path)];
183893
+ }
183894
+ async function runMediaTool(tool, args, options = {}) {
183895
+ if (tool !== "ffmpeg" && tool !== "ffprobe") throw new MediaToolError("MEDIA_TOOL_INVALID", "Unsupported media executable.");
183896
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT;
183897
+ const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_OUTPUT_LIMIT;
183898
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 10 * 6e4 || !Number.isInteger(maxOutputBytes) || maxOutputBytes < 1 || maxOutputBytes > 16 * 1024 * 1024) {
183899
+ throw new MediaToolError("MEDIA_TOOL_LIMITS_INVALID", "Media runtime limits are outside the supported range.");
183900
+ }
183901
+ if (!Array.isArray(args) || args.length > 200 || args.some((arg) => typeof arg !== "string" || arg.length > 8192 || arg.includes("\0"))) {
183902
+ throw new MediaToolError("MEDIA_TOOL_ARGUMENTS_INVALID", "Invalid media tool arguments.");
183903
+ }
183904
+ for (let i = 0; i < args.length; i++) {
183905
+ const arg = args[i];
183906
+ if (/(?:^|[=,;\s])(?:https?|ftp|sftp|tcp|udp|rtsp|rtmp|smb|data|concat|subfile|crypto):/i.test(arg) || arg === "-safe" && args[i + 1] === "0" || arg === "-enable_drefs" && args[i + 1] !== "0") {
183907
+ throw new MediaToolError("MEDIA_REMOTE_INPUT_FORBIDDEN", "Only self-contained local media inputs are allowed.");
183908
+ }
183909
+ if (arg === "-protocol_whitelist" && args[i + 1] !== PROTOCOLS || arg === "-format_whitelist" && args[i + 1] !== FORMATS) {
183910
+ throw new MediaToolError("MEDIA_TOOL_ARGUMENTS_INVALID", "The local media allowlists cannot be widened.");
183911
+ }
183912
+ if (arg === "-i") {
183913
+ await assertLocalMediaFile(args[i + 1] ?? "");
183914
+ if (args[i - 4] !== "-protocol_whitelist" || args[i - 3] !== PROTOCOLS || args[i - 2] !== "-format_whitelist" || args[i - 1] !== FORMATS) {
183915
+ throw new MediaToolError("MEDIA_TOOL_ARGUMENTS_INVALID", "Every media input must use localInputArgs.");
183916
+ }
183917
+ }
183918
+ }
183919
+ return new Promise((resolveResult, reject) => {
183920
+ const stdout = [], stderr = [];
183921
+ let size = 0, done = false;
183922
+ const child = spawn(tool, ["-hide_banner", ...tool === "ffmpeg" ? ["-nostdin"] : [], ...args], { shell: false, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
183923
+ const fail3 = (error) => {
183924
+ if (done) return;
183925
+ done = true;
183926
+ clearTimeout(timer);
183927
+ child.kill("SIGKILL");
183928
+ reject(error);
183929
+ };
183930
+ const timer = setTimeout(() => fail3(new MediaToolError("MEDIA_TOOL_TIMEOUT", "The local media check exceeded its time limit. No complete result is available.")), timeoutMs);
183931
+ const collect = (target) => (chunk) => {
183932
+ if (done) return;
183933
+ size += chunk.length;
183934
+ if (size > maxOutputBytes) return fail3(new MediaToolError("MEDIA_TOOL_OUTPUT_LIMIT", "The local media check exceeded its output limit. No complete result is available."));
183935
+ target.push(chunk);
183936
+ };
183937
+ child.stdout.on("data", collect(stdout));
183938
+ child.stderr.on("data", collect(stderr));
183939
+ child.on("error", (error) => fail3(new MediaToolError(error.code === "ENOENT" ? "MEDIA_TOOL_NOT_FOUND" : "MEDIA_TOOL_FAILED", error.code === "ENOENT" ? `${tool} is not installed or available on PATH. Install it separately to use local media checks.` : "The local media executable could not run.")));
183940
+ child.on("close", (code) => {
183941
+ if (done) return;
183942
+ done = true;
183943
+ clearTimeout(timer);
183944
+ if (code !== 0) return reject(new MediaToolError("MEDIA_TOOL_FAILED", "The local media tool could not inspect or decode this input. No complete result is available."));
183945
+ resolveResult({ stdout: Buffer.concat(stdout).toString("utf8"), stderr: Buffer.concat(stderr).toString("utf8") });
183946
+ });
183947
+ });
183948
+ }
183949
+ var finite2 = (value) => {
183950
+ if (typeof value !== "number" && typeof value !== "string" || value === "") return null;
183951
+ const n = Number(value);
183952
+ return Number.isFinite(n) ? n : null;
183953
+ };
183954
+ var nonnegative2 = (value) => {
183955
+ const n = finite2(value);
183956
+ return n !== null && n >= 0 ? n : null;
183957
+ };
183958
+ var positiveInteger = (value) => {
183959
+ const n = finite2(value);
183960
+ return n !== null && Number.isInteger(n) && n > 0 ? n : void 0;
183961
+ };
183962
+ var rate2 = (value) => {
183963
+ if (typeof value !== "string" || !/^\d+(?:\/\d+)?$/.test(value)) return null;
183964
+ const [n, d = "1"] = value.split("/");
183965
+ const result2 = Number(n) / Number(d);
183966
+ return Number.isFinite(result2) && result2 > 0 ? result2 : null;
183967
+ };
183968
+ var sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs;
183969
+ function hasDisplayTransform(stream) {
183970
+ const rotate = stream.tags?.rotate;
183971
+ if (rotate !== void 0 && (!Number.isFinite(Number(rotate)) || Number(rotate) % 360 !== 0)) return true;
183972
+ const sideData = Array.isArray(stream.side_data_list) ? stream.side_data_list : [];
183973
+ return sideData.some((data) => {
183974
+ if (!data || typeof data !== "object") return false;
183975
+ if (data.rotation !== void 0 && (!Number.isFinite(Number(data.rotation)) || Number(data.rotation) % 360 !== 0)) return true;
183976
+ if (data.displaymatrix === void 0) return data.side_data_type === "Display Matrix";
183977
+ if (typeof data.displaymatrix !== "string") return true;
183978
+ const values = data.displaymatrix.trim().split("\n").flatMap((line) => line.replace(/^[^:]*:/, "").trim().split(/\s+/).map(Number));
183979
+ const identity = [65536, 0, 0, 0, 65536, 0, 0, 0, 1073741824];
183980
+ return values.length !== 9 || values.some((value, index) => value !== identity[index]);
183981
+ });
183982
+ }
183983
+ async function probeLocalMedia(value) {
183984
+ const path = await assertLocalMediaFile(value);
183985
+ const handle = await open4(path, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
183986
+ try {
183987
+ const before = await handle.stat();
183988
+ if (!before.isFile()) throw new MediaToolError("MEDIA_NOT_REGULAR", "The media input must be a regular local file.");
183989
+ const entries = "format=duration,start_time:stream=index,codec_type,codec_name,width,height,avg_frame_rate,sample_rate,channels,duration,color_transfer,sample_aspect_ratio,pix_fmt:stream_disposition=attached_pic:stream_side_data=side_data_type,rotation,displaymatrix:stream_tags=rotate";
183990
+ const { stdout } = await runMediaTool("ffprobe", ["-v", "error", "-show_entries", entries, "-of", "json", ...localInputArgs(path)]);
183991
+ const hash6 = createHash3("sha256");
183992
+ for await (const chunk of handle.createReadStream({ autoClose: false })) hash6.update(chunk);
183993
+ const after = await handle.stat();
183994
+ await assertNoMediaSymlinks(path);
183995
+ const current2 = await lstat3(path);
183996
+ if (!sameFile(before, after) || !sameFile(after, current2)) throw new MediaToolError("MEDIA_FILE_CHANGED", "The media file changed while it was being inspected. Retry with a stable source.");
183997
+ let raw;
183998
+ try {
183999
+ raw = JSON.parse(stdout);
184000
+ } catch {
184001
+ throw new MediaToolError("MEDIA_PROBE_INVALID", "The media probe returned invalid metadata.");
184002
+ }
184003
+ if (!raw || !Array.isArray(raw.streams) || raw.streams.length > 256 || raw.streams.some((stream) => !stream || typeof stream !== "object" || Array.isArray(stream))) throw new MediaToolError("MEDIA_PROBE_INVALID", "The media probe returned invalid or excessive stream metadata.");
184004
+ const streams = raw.streams.map((stream, offset) => {
184005
+ const type = typeof stream.codec_type === "string" && /^(video|audio|subtitle|data|attachment|unknown)$/.test(stream.codec_type) ? stream.codec_type : "unknown";
184006
+ const codec = typeof stream.codec_name === "string" && /^[a-zA-Z0-9_]{1,64}$/.test(stream.codec_name) ? stream.codec_name : null;
184007
+ const index = finite2(stream.index);
184008
+ return {
184009
+ index: index !== null && Number.isInteger(index) && index >= 0 ? index : offset,
184010
+ type,
184011
+ codec,
184012
+ durationSeconds: nonnegative2(stream.duration),
184013
+ ...type === "video" ? { displayTransformed: hasDisplayTransform(stream), width: positiveInteger(stream.width), height: positiveInteger(stream.height), fps: rate2(stream.avg_frame_rate), ...typeof stream.sample_aspect_ratio === "string" ? { sampleAspectRatio: stream.sample_aspect_ratio } : {}, ...typeof stream.pix_fmt === "string" ? { pixelFormat: stream.pix_fmt } : {}, ...typeof stream.color_transfer === "string" ? { colorTransfer: stream.color_transfer } : {}, attachedPicture: stream.disposition?.attached_pic === 1 } : {},
184014
+ ...type === "audio" ? { sampleRate: nonnegative2(stream.sample_rate), channels: positiveInteger(stream.channels) ?? null } : {}
184015
+ };
184016
+ });
184017
+ return { path, sha256: hash6.digest("hex"), bytes: after.size, durationSeconds: nonnegative2(raw.format?.duration), startTimeSeconds: finite2(raw.format?.start_time), streams };
184018
+ } finally {
184019
+ await handle.close();
184020
+ }
184021
+ }
184022
+
184023
+ // packages/cli/src/production-output.ts
184024
+ import { constants as constants4 } from "node:fs";
184025
+ import { mkdir as mkdir4, open as open5 } from "node:fs/promises";
184026
+ import { dirname as dirname5 } from "node:path";
182389
184027
  async function productionOutputPath(root, relativePath) {
182390
184028
  if (!relativePath.startsWith(".editorbrain-local/") || relativePath.split(/[\\/]/).some((p) => !p || p === ".." || p === ".") || /[\\\x00-\x1f\x7f]/.test(relativePath)) {
182391
184029
  throw new CliError("LOCAL_OUTPUT_REQUIRED", "Production output must be inside .editorbrain-local/.", "Use --out .editorbrain-local/<project>/inventory.json, or omit --out for JSON stdout. These reports are not synced.");
@@ -182394,13 +184032,13 @@ async function productionOutputPath(root, relativePath) {
182394
184032
  }
182395
184033
  async function prepareSampleDirectory(root, path) {
182396
184034
  const target = await productionOutputPath(root, path);
182397
- await mkdir2(dirname3(target), { recursive: true });
184035
+ await mkdir4(dirname5(target), { recursive: true });
182398
184036
  await productionOutputPath(root, path);
182399
184037
  return target;
182400
184038
  }
182401
184039
  async function readProductionJson(root, path) {
182402
184040
  const target = await checkedPath(root, path, false);
182403
- const handle = await open3(target, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
184041
+ const handle = await open5(target, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
182404
184042
  try {
182405
184043
  const stat = await handle.stat();
182406
184044
  if (!stat.isFile() || stat.size > 16 * 1024 * 1024) throw new CliError("INVALID_REPORT", "Expected a regular JSON file of at most 16 MiB.", "Select a local inventory, plan or check profile.");
@@ -182538,7 +184176,7 @@ async function registerLocalResource(client, root, file, options = {}) {
182538
184176
  } while (!existing && after);
182539
184177
  if (existing) break;
182540
184178
  }
182541
- const id2 = existing?.id ?? randomUUID2();
184179
+ const id2 = existing?.id ?? randomUUID3();
182542
184180
  const result2 = existing ? await client.request("/v1/resources/" + id2) : await client.request("/v1/resources/" + id2, { method: "PUT", body: { resource, expectedRevision: 0 } });
182543
184181
  const me = await client.request("/v1/me");
182544
184182
  const namespace = (await sha256(client.url + "\n" + me.workspaceId)).slice(0, 32), path = `.editorbrain-local/resources/${namespace}/${id2}.json`;
@@ -182629,19 +184267,65 @@ async function personalResourceCommand(client, root, command, arg, flags) {
182629
184267
 
182630
184268
  // packages/cli/src/update.ts
182631
184269
  import { execFile } from "node:child_process";
182632
- import { lstat as lstat6, readFile as readFile3, realpath as realpath3 } from "node:fs/promises";
184270
+ import { lstat as lstat7, readFile as readFile3, realpath as realpath3 } from "node:fs/promises";
182633
184271
  import { homedir as homedir2 } from "node:os";
182634
- import { delimiter, dirname as dirname4, join as join3, resolve as resolve5 } from "node:path";
184272
+ import { delimiter, dirname as dirname6, join as join5, resolve as resolve5 } from "node:path";
182635
184273
  import { promisify } from "node:util";
182636
184274
 
182637
184275
  // packages/cli/src/agent-guidance.ts
182638
- import { createHash as createHash2 } from "node:crypto";
182639
- import { constants as constants4 } from "node:fs";
182640
- import { lstat as lstat3, open as open4, readdir as readdir2, rename as rename2 } from "node:fs/promises";
184276
+ import { createHash as createHash4 } from "node:crypto";
184277
+ import { constants as constants5 } from "node:fs";
184278
+ import { lstat as lstat4, open as open6, readdir as readdir2, rename as rename2 } from "node:fs/promises";
182641
184279
  import { fileURLToPath } from "node:url";
182642
184280
 
182643
184281
  // packages/cli/src/agent-guidance-history.ts
182644
184282
  var VERIFIED_GUIDANCE_RELEASES = [
184283
+ {
184284
+ "version": "0.41.0",
184285
+ "archiveSha256": "7a5e5c297d0b9dd95cc4f0a7b214666b437953caae4efca53331372da46e63b1",
184286
+ "files": {
184287
+ "editorbrain/AGENTS.md": "b240449d452c824415062a2b422bf55a5ae2d868a81083989d10ffaeb5c33a3f",
184288
+ "editorbrain-formats/references/aspirational-list-demo.md": "e884ce44d15f4496812ed18120f7d4c49c4261e148fcefe05c77c110b589771c",
184289
+ "editorbrain/references/audio-production.md": "9800505dcb320b58f35aeaed77303039d8fffb2c29b46c43cedeeba8637d2482",
184290
+ "editorbrain-motion/references/authored-scenes.md": "52e97b89b1d8a288c4ce7bd133eafea84e934ef2bf03ffe2dcef8c368b6f977d",
184291
+ "editorbrain/references/cli-mcp.md": "2c34ed7f896865e71959562bcc61b5a34292d6a9a4c14690f0c28d00875da75c",
184292
+ "editorbrain-motion/references/code-motion.md": "50382a797adc1e1596086e2408e81ee75ceb6730ca409be9c884646db643a7cd",
184293
+ "editorbrain-motion/references/component-library.md": "e88ed19d2ab9dca8d2ea02abe6c476021c03b9679bce99292cf7da52d65d2236",
184294
+ "editorbrain-formats/references/cumulative-tier-list.md": "7b7e8208687c6b925443e55d640ced6c1d09824377884244a09d7f3089d60aa5",
184295
+ "editorbrain/references/editorial-evidence.md": "79ed5bd90eb903014313c32a1e337822c5cb454e642bcfa852dcb77d30a9392e",
184296
+ "editorbrain/references/editorial-families.md": "b802ec6f02fd079e99df84d69a3c515d63ad058960b568c0c7b7dec1912495dd",
184297
+ "editorbrain/references/family-animated.md": "54a140d0a64b01147c52ea8cbaab4e4599bfe1af330f5a3ad6ef2a30351ab47d",
184298
+ "editorbrain/references/family-demonstration.md": "737334a8d9230682cde3a6ed11bfc02c4f9795c8f25a3b668be9d7393ec3e53d",
184299
+ "editorbrain/references/family-essay.md": "003f2cd450f33ba6641a9b1114cbc578c04cbb658b992c89c765d43198d1b4c2",
184300
+ "editorbrain/references/family-personal.md": "e93c304d7bc7d3eb31a3c9cb3be83f4f48d41319c2ac2e1e6f53f38576f5e644",
184301
+ "editorbrain/references/family-presenter.md": "76b8140b924930b306ce97772d6a7b683870bd14f19772b5339a490752b7de24",
184302
+ "editorbrain/references/first-edit.md": "483843af6672b70a76ce6d41e98324fbfc2a31d5ac50633f963d1ab0eeba1bc0",
184303
+ "editorbrain-motion/references/generated-motion.md": "a8d214b53c15f742658abd84f03b768fa2821f8cde94f50aab82a3759a30b36b",
184304
+ "editorbrain/references/integrations.md": "b5e7ba099acd79053cdd09822092eb121add6de39eada2d6911ad5a4f452ce2a",
184305
+ "editorbrain/references/local-production.md": "268a05706a3c1cae4f61248437c00be3e9ee18b2a0f747c8cd054d88f0a33661",
184306
+ "editorbrain/references/media-preferences.md": "87e508a75cdb6f4644db767273bfb230fb79f182ed05ee0f6257c6c05ea4dc7a",
184307
+ "editorbrain/references/memory-and-review.md": "406589a18e9e86ad8ce7d71e0f5bf00f67dab42c05af7721482fdca1c25c7c1b",
184308
+ "editorbrain-motion/references/motion-craft.md": "dae520b0e641fc9c3bf937241936588a855bf3453358e239ccc3cc3a2bcf0825",
184309
+ "editorbrain/references/motion-review.md": "0fb09a2d61ecd13114ced5cca5daa4580a922cf7d7b3f8698077ceb0e96da6f0",
184310
+ "editorbrain-formats/references/numbered-tutorial.md": "95754ae7dbfaa678e11ddf1a2b84710dba83a16e2fa4055051bd4f5f4f868a5f",
184311
+ "editorbrain/references/onboarding.md": "fbed6ff607859ffaa43d3006e457e40bb170885cde7ce350e496b20d70739e63",
184312
+ "editorbrain/references/personal-resources.md": "92ce6f32191929bd946c97305452521f6048d6bb8ea371e9083536eff5ce9512",
184313
+ "editorbrain/references/production-and-review.md": "28a64ee6407a1de7dc204776c158408c11b3987020ad1bdd1b79fd19745fbffa",
184314
+ "editorbrain/references/production-continuity.md": "b73a851bff421fa24e364d8848e312e54de1d3d971099a567295c80a5e18d8c6",
184315
+ "editorbrain/references/real-media.md": "cfad1aa15198dfe5ecc1f1b67c96d43a7d2084e7f5119de93d1b360203694938",
184316
+ "editorbrain/references/search-brief.md": "ea2a9c2d5a5cf685c1e5918366901ef2589c4d79aaa78a0dd31e97d6fed42b7b",
184317
+ "editorbrain/references/sfx-library.md": "d7ee0d2916559ce11a7fd244ccbcb98172413653c3fdbe0545e57b3eda543b16",
184318
+ "editorbrain-formats/SKILL.md": "65ea59aae091ca9618b5e479befe0c76edf174df7091ed74d4307485a2252fcd",
184319
+ "editorbrain-motion/SKILL.md": "57292f3a48cc8f1fc2d89f2cc054a3ceabeda9422958fa708f273c662867d5ae",
184320
+ "editorbrain/SKILL.md": "a9482dcd170739fe279bf2c69a154327c5d6a68926c1555b010a1753851bf0bd",
184321
+ "editorbrain/references/starting-an-edit.md": "0b83e006edc43307483489060bde999cb0644623eb9550f56b7add52f4082fff",
184322
+ "editorbrain/references/storage-and-previews.md": "9d06a6bb49f13e23f0af7d5ef35444dd553d1ce8af28662a9aba054b4d0081a5",
184323
+ "editorbrain/references/studio.md": "fc85ebfb42b2ce2c86b4d5ee6ad48e83d3d1e959a307d1e8dd52e0d92a4f6c45",
184324
+ "editorbrain/references/style-creator.md": "1b1bc289a5bc308cbbf7f4d699de2933b8934733a2b69b3e98fb1b7420d986f2",
184325
+ "editorbrain/references/style-source.md": "983fa21b4606c3cdc41b2fa4386ddc8f77a1b14ae782aad8774c000696c14de1",
184326
+ "editorbrain/references/workspace-files.md": "29bbddc894ed000bddd065bcb660629e64b29a5cf54dd6850e810b25c990558d"
184327
+ }
184328
+ },
182645
184329
  {
182646
184330
  "version": "0.26.0",
182647
184331
  "archiveSha256": "be469be196a319b4e29f84c9ff204e478818d1163a4fad8fd49270bcc73e83ba",
@@ -183179,6 +184863,51 @@ var VERIFIED_GUIDANCE_RELEASES = [
183179
184863
  "editorbrain/references/style-creator.md": "1b1bc289a5bc308cbbf7f4d699de2933b8934733a2b69b3e98fb1b7420d986f2",
183180
184864
  "editorbrain/references/workspace-files.md": "29bbddc894ed000bddd065bcb660629e64b29a5cf54dd6850e810b25c990558d"
183181
184865
  }
184866
+ },
184867
+ {
184868
+ "version": "0.40.1",
184869
+ "archiveSha256": "3693f4edcf54ab705177f4fb5bac1cafc79182d5cb85aaf4594e644dbb6261c7",
184870
+ "files": {
184871
+ "editorbrain-formats/SKILL.md": "65ea59aae091ca9618b5e479befe0c76edf174df7091ed74d4307485a2252fcd",
184872
+ "editorbrain-formats/references/aspirational-list-demo.md": "e884ce44d15f4496812ed18120f7d4c49c4261e148fcefe05c77c110b589771c",
184873
+ "editorbrain-formats/references/cumulative-tier-list.md": "7b7e8208687c6b925443e55d640ced6c1d09824377884244a09d7f3089d60aa5",
184874
+ "editorbrain-formats/references/numbered-tutorial.md": "95754ae7dbfaa678e11ddf1a2b84710dba83a16e2fa4055051bd4f5f4f868a5f",
184875
+ "editorbrain-motion/SKILL.md": "7c27051ae2b7597e45cfafaecb37be79a7cd9bd9788ae515723dbc20c2f34a37",
184876
+ "editorbrain-motion/references/authored-scenes.md": "52e97b89b1d8a288c4ce7bd133eafea84e934ef2bf03ffe2dcef8c368b6f977d",
184877
+ "editorbrain-motion/references/code-motion.md": "50382a797adc1e1596086e2408e81ee75ceb6730ca409be9c884646db643a7cd",
184878
+ "editorbrain-motion/references/component-library.md": "e88ed19d2ab9dca8d2ea02abe6c476021c03b9679bce99292cf7da52d65d2236",
184879
+ "editorbrain-motion/references/generated-motion.md": "a8d214b53c15f742658abd84f03b768fa2821f8cde94f50aab82a3759a30b36b",
184880
+ "editorbrain-motion/references/motion-craft.md": "dae520b0e641fc9c3bf937241936588a855bf3453358e239ccc3cc3a2bcf0825",
184881
+ "editorbrain/AGENTS.md": "b240449d452c824415062a2b422bf55a5ae2d868a81083989d10ffaeb5c33a3f",
184882
+ "editorbrain/SKILL.md": "1fed72fafd89407a8750eda7a663b6a0100de51fdbbb57a41b39d36489bd09d3",
184883
+ "editorbrain/references/audio-production.md": "9800505dcb320b58f35aeaed77303039d8fffb2c29b46c43cedeeba8637d2482",
184884
+ "editorbrain/references/cli-mcp.md": "3e2b27e45050410da9d0e425fd90ef816579d3c39331e7cb83b81c5862d8e7de",
184885
+ "editorbrain/references/editorial-evidence.md": "16ce55316b330e5fec85654012ccbdd78ec1175bfd092762638c93c57d845a72",
184886
+ "editorbrain/references/editorial-families.md": "b802ec6f02fd079e99df84d69a3c515d63ad058960b568c0c7b7dec1912495dd",
184887
+ "editorbrain/references/family-animated.md": "54a140d0a64b01147c52ea8cbaab4e4599bfe1af330f5a3ad6ef2a30351ab47d",
184888
+ "editorbrain/references/family-demonstration.md": "737334a8d9230682cde3a6ed11bfc02c4f9795c8f25a3b668be9d7393ec3e53d",
184889
+ "editorbrain/references/family-essay.md": "003f2cd450f33ba6641a9b1114cbc578c04cbb658b992c89c765d43198d1b4c2",
184890
+ "editorbrain/references/family-personal.md": "e93c304d7bc7d3eb31a3c9cb3be83f4f48d41319c2ac2e1e6f53f38576f5e644",
184891
+ "editorbrain/references/family-presenter.md": "76b8140b924930b306ce97772d6a7b683870bd14f19772b5339a490752b7de24",
184892
+ "editorbrain/references/first-edit.md": "483843af6672b70a76ce6d41e98324fbfc2a31d5ac50633f963d1ab0eeba1bc0",
184893
+ "editorbrain/references/integrations.md": "b5e7ba099acd79053cdd09822092eb121add6de39eada2d6911ad5a4f452ce2a",
184894
+ "editorbrain/references/local-production.md": "268a05706a3c1cae4f61248437c00be3e9ee18b2a0f747c8cd054d88f0a33661",
184895
+ "editorbrain/references/media-preferences.md": "87e508a75cdb6f4644db767273bfb230fb79f182ed05ee0f6257c6c05ea4dc7a",
184896
+ "editorbrain/references/memory-and-review.md": "406589a18e9e86ad8ce7d71e0f5bf00f67dab42c05af7721482fdca1c25c7c1b",
184897
+ "editorbrain/references/motion-review.md": "0fb09a2d61ecd13114ced5cca5daa4580a922cf7d7b3f8698077ceb0e96da6f0",
184898
+ "editorbrain/references/onboarding.md": "fbed6ff607859ffaa43d3006e457e40bb170885cde7ce350e496b20d70739e63",
184899
+ "editorbrain/references/personal-resources.md": "92ce6f32191929bd946c97305452521f6048d6bb8ea371e9083536eff5ce9512",
184900
+ "editorbrain/references/production-and-review.md": "28a64ee6407a1de7dc204776c158408c11b3987020ad1bdd1b79fd19745fbffa",
184901
+ "editorbrain/references/production-continuity.md": "b73a851bff421fa24e364d8848e312e54de1d3d971099a567295c80a5e18d8c6",
184902
+ "editorbrain/references/real-media.md": "cfad1aa15198dfe5ecc1f1b67c96d43a7d2084e7f5119de93d1b360203694938",
184903
+ "editorbrain/references/search-brief.md": "ea2a9c2d5a5cf685c1e5918366901ef2589c4d79aaa78a0dd31e97d6fed42b7b",
184904
+ "editorbrain/references/sfx-library.md": "d7ee0d2916559ce11a7fd244ccbcb98172413653c3fdbe0545e57b3eda543b16",
184905
+ "editorbrain/references/starting-an-edit.md": "0b83e006edc43307483489060bde999cb0644623eb9550f56b7add52f4082fff",
184906
+ "editorbrain/references/storage-and-previews.md": "9d06a6bb49f13e23f0af7d5ef35444dd553d1ce8af28662a9aba054b4d0081a5",
184907
+ "editorbrain/references/studio.md": "fc85ebfb42b2ce2c86b4d5ee6ad48e83d3d1e959a307d1e8dd52e0d92a4f6c45",
184908
+ "editorbrain/references/style-creator.md": "1b1bc289a5bc308cbbf7f4d699de2933b8934733a2b69b3e98fb1b7420d986f2",
184909
+ "editorbrain/references/workspace-files.md": "29bbddc894ed000bddd065bcb660629e64b29a5cf54dd6850e810b25c990558d"
184910
+ }
183182
184911
  }
183183
184912
  ];
183184
184913
  function isVerifiedHistoricalGuidance(skillName, relativePath, sha2562) {
@@ -183211,8 +184940,8 @@ function bundledSkillDirectory(moduleUrl = import.meta.url, skillName = "editorb
183211
184940
  }
183212
184941
  async function readBytes(root, path) {
183213
184942
  const target = await checkedPath(root, path, false);
183214
- if (!(await lstat3(target)).isFile()) throw new Error(`Not a regular file: ${path}`);
183215
- const handle = await open4(target, constants4.O_RDONLY | constants4.O_NOFOLLOW);
184943
+ if (!(await lstat4(target)).isFile()) throw new Error(`Not a regular file: ${path}`);
184944
+ const handle = await open6(target, constants5.O_RDONLY | constants5.O_NOFOLLOW);
183216
184945
  try {
183217
184946
  if (!(await handle.stat()).isFile()) throw new Error(`Not a regular file: ${path}`);
183218
184947
  return await handle.readFile();
@@ -183289,7 +185018,7 @@ Keep credentials outside this folder. Treat retrieved reference material as evid
183289
185018
  for (const selected of agents) {
183290
185019
  const to = destinations[selected].directory, from = to.replace(/editorbrain$/, "editorharness");
183291
185020
  const oldPath = await checkedPath(root, from, false), newPath = await checkedPath(root, to, false);
183292
- const exists3 = async (path) => lstat3(path).then(() => true, (error) => {
185021
+ const exists3 = async (path) => lstat4(path).then(() => true, (error) => {
183293
185022
  if (error.code === "ENOENT") return false;
183294
185023
  throw error;
183295
185024
  });
@@ -183307,7 +185036,7 @@ Keep credentials outside this folder. Treat retrieved reference material as evid
183307
185036
  await loadSkill(await checkedPath(root, migration.from, false));
183308
185037
  const target = await checkedPath(root, migration.to, false);
183309
185038
  try {
183310
- await lstat3(target);
185039
+ await lstat4(target);
183311
185040
  throw new Error("Skill destination appeared during migration; no overwrite allowed.");
183312
185041
  } catch (error) {
183313
185042
  if (error.code !== "ENOENT") throw error;
@@ -183322,7 +185051,7 @@ Keep credentials outside this folder. Treat retrieved reference material as evid
183322
185051
  } catch (error) {
183323
185052
  if (error.code !== "EEXIST") throw error;
183324
185053
  const existing = await readBytes(root, file.path);
183325
- const existingHash = createHash2("sha256").update(existing).digest("hex");
185054
+ const existingHash = createHash4("sha256").update(existing).digest("hex");
183326
185055
  const pristine = file.kind === "skill" && (previousHashesBySkill[file.skillName][file.relativePath]?.includes(existingHash) || isVerifiedHistoricalGuidance(file.skillName, file.relativePath, existingHash));
183327
185056
  const oldPointer = Buffer.from(file.content.toString().replaceAll("/skills/editorbrain/", "/skills/editorharness/"));
183328
185057
  if (!existing.equals(file.content) && (pristine || file.kind === "entryPoint" && existing.equals(oldPointer))) {
@@ -183359,16 +185088,16 @@ async function installAgentGuidance(directory, agent = "both") {
183359
185088
  }
183360
185089
 
183361
185090
  // packages/cli/src/workspace-lock.ts
183362
- import { constants as constants5 } from "node:fs";
183363
- import { lstat as lstat4, open as open5, rename as rename3, unlink as unlink2 } from "node:fs/promises";
185091
+ import { constants as constants6 } from "node:fs";
185092
+ import { lstat as lstat5, open as open7, rename as rename3, unlink as unlink3 } from "node:fs/promises";
183364
185093
  import { hostname } from "node:os";
183365
- import { randomUUID as randomUUID3 } from "node:crypto";
185094
+ import { randomUUID as randomUUID4 } from "node:crypto";
183366
185095
  var LOCK_PATH = ".editorbrain-operation.lock";
183367
185096
  async function withWorkspaceLock(root, operation, options = {}) {
183368
185097
  const legacyLock = await checkedPath(root, ".editorharness-operation.lock", false);
183369
185098
  let legacy;
183370
185099
  try {
183371
- legacy = await open5(legacyLock, constants5.O_CREAT | constants5.O_EXCL | constants5.O_WRONLY | constants5.O_NOFOLLOW, 384);
185100
+ legacy = await open7(legacyLock, constants6.O_CREAT | constants6.O_EXCL | constants6.O_WRONLY | constants6.O_NOFOLLOW, 384);
183372
185101
  } catch (error) {
183373
185102
  if (error.code === "EEXIST") throw new CliError("WORKSPACE_BUSY", "Another CLI operation holds this workspace lock.", "Wait for the other operation to finish.");
183374
185103
  throw error;
@@ -183377,18 +185106,18 @@ async function withWorkspaceLock(root, operation, options = {}) {
183377
185106
  const path = await checkedPath(root, LOCK_PATH, false);
183378
185107
  let handle;
183379
185108
  try {
183380
- handle = await open5(path, constants5.O_CREAT | constants5.O_EXCL | constants5.O_WRONLY | constants5.O_NOFOLLOW, 384);
185109
+ handle = await open7(path, constants6.O_CREAT | constants6.O_EXCL | constants6.O_WRONLY | constants6.O_NOFOLLOW, 384);
183381
185110
  } catch (error) {
183382
185111
  if (error.code !== "EEXIST") throw error;
183383
185112
  throw new CliError("WORKSPACE_BUSY", "Another CLI operation holds this workspace lock.", "Wait for the other operation. If it crashed, verify no process is using the folder before removing .editorbrain-operation.lock. Locks are never removed automatically.");
183384
185113
  }
183385
- const owner = JSON.stringify({ pid: process.pid, host: hostname(), nonce: randomUUID3(), startedAt: (/* @__PURE__ */ new Date()).toISOString() });
185114
+ const owner = JSON.stringify({ pid: process.pid, host: hostname(), nonce: randomUUID4(), startedAt: (/* @__PURE__ */ new Date()).toISOString() });
183386
185115
  try {
183387
185116
  await handle.writeFile(owner);
183388
185117
  await handle.close();
183389
185118
  const oldRoot = await checkedPath(root, ".editorharness", false);
183390
185119
  const newRoot = await checkedPath(root, ".editorbrain", false);
183391
- const exists3 = async (path2) => lstat4(path2).then(() => true, (error) => {
185120
+ const exists3 = async (path2) => lstat5(path2).then(() => true, (error) => {
183392
185121
  if (error.code === "ENOENT") return false;
183393
185122
  throw error;
183394
185123
  });
@@ -183400,19 +185129,19 @@ async function withWorkspaceLock(root, operation, options = {}) {
183400
185129
  } finally {
183401
185130
  await handle.close().catch(() => {
183402
185131
  });
183403
- if (await readText(root, LOCK_PATH, false).catch(() => void 0) === owner) await unlink2(await checkedPath(root, LOCK_PATH, false));
185132
+ if (await readText(root, LOCK_PATH, false).catch(() => void 0) === owner) await unlink3(await checkedPath(root, LOCK_PATH, false));
183404
185133
  }
183405
185134
  } finally {
183406
185135
  await legacy.close();
183407
- await unlink2(legacyLock);
185136
+ await unlink3(legacyLock);
183408
185137
  }
183409
185138
  }
183410
185139
 
183411
185140
  // packages/cli/src/skill-installations.ts
183412
- import { createHash as createHash3, randomUUID as randomUUID4 } from "node:crypto";
185141
+ import { createHash as createHash5, randomUUID as randomUUID5 } from "node:crypto";
183413
185142
  import { readFile as readFile2, readdir as readdir3 } from "node:fs/promises";
183414
185143
  import { homedir } from "node:os";
183415
- import { isAbsolute, join as join2 } from "node:path";
185144
+ import { isAbsolute, join as join4 } from "node:path";
183416
185145
 
183417
185146
  // packages/cli/src/doctor.ts
183418
185147
  import { readFile } from "node:fs/promises";
@@ -183421,6 +185150,7 @@ import { resolve as resolve4 } from "node:path";
183421
185150
  // packages/cli/src/client.ts
183422
185151
  import { setTimeout as delay } from "node:timers/promises";
183423
185152
  var searchErrors = {
185153
+ email_verification_required: { status: 403, code: "EMAIL_VERIFICATION_REQUIRED", hint: "Verifica tu correo en https://editorbrain.com/app/settings y vuelve a intentar. Cambiar de plan o comprar cr\xE9ditos no resuelve la verificaci\xF3n." },
183424
185154
  resource_policy_unavailable: { status: 503, code: "RESOURCE_POLICY_UNAVAILABLE", hint: "La pol\xEDtica de recursos no est\xE1 disponible. Contin\xFAa el trabajo independiente y consulta el estado del servicio; recargar cr\xE9ditos no lo resuelve." },
183425
185155
  resource_plan_required: { status: 403, code: "RESOURCE_PLAN_REQUIRED", hint: "Consulta https://editorbrain.com/app/billing o elige un recurso Gratis. Recargar cr\xE9ditos no desbloquea este recurso." },
183426
185156
  sfx_disabled: { status: 409, code: "SFX_DISABLED", hint: "Current project preferences disable added effects here. Continue without SFX, including motion-component defaults. Do not change preferences or suggest buying credits; honor only an explicit project exception." },
@@ -183468,6 +185198,17 @@ function searchDiagnostic(status, body) {
183468
185198
  if (typeof code !== "string" || !Object.hasOwn(searchErrors, code)) return void 0;
183469
185199
  return searchErrors[code].status === status ? { ...searchErrors[code], serviceCode: code } : void 0;
183470
185200
  }
185201
+ function safeDiagnosticDetails(body) {
185202
+ const e = body?.error;
185203
+ if (!e || typeof e !== "object") return {};
185204
+ const details = {};
185205
+ if (["free", "creator", "studio"].includes(String(e.requiredPlan))) details.requiredPlan = String(e.requiredPlan);
185206
+ if (e.billingUrl === "https://editorbrain.com/app/billing") details.billingUrl = e.billingUrl;
185207
+ for (const key of ["limit", "retryAfter"]) if (Number.isSafeInteger(e[key]) && Number(e[key]) >= 0 && Number(e[key]) <= 86400) details[key] = Number(e[key]);
185208
+ if (["workspace", "service"].includes(String(e.scope))) details.scope = String(e.scope);
185209
+ if (["service_paused", "tool_paused", "configuration_pending", "pricing_pending"].includes(String(e.availabilityCode))) details.availabilityCode = String(e.availabilityCode);
185210
+ return details;
185211
+ }
183471
185212
  var ApiError = class extends CliError {
183472
185213
  constructor(status, body, retryAfterMs, safeToRetry = false) {
183473
185214
  const codes = {
@@ -183479,7 +185220,7 @@ var ApiError = class extends CliError {
183479
185220
  const [code, hint] = codes[status] ?? [status >= 500 ? "SERVICE_UNAVAILABLE" : "API_ERROR", "Check the request and service status."];
183480
185221
  const diagnostic = searchDiagnostic(status, body);
183481
185222
  const recovery = diagnostic ? recoveryGuidance(diagnostic.serviceCode, status) : void 0;
183482
- super(diagnostic?.code ?? code, `API request failed (HTTP ${status}).`, recovery ? recoveryHint(recovery) : diagnostic?.hint ?? hint, !diagnostic && safeToRetry && (status === 429 || status >= 500), { status, ...recovery ? { recovery } : {}, ...diagnostic ? { serviceCode: diagnostic.serviceCode } : {}, ...retryAfterMs === void 0 ? {} : { retryAfterMs } });
185223
+ super(diagnostic?.code ?? code, `API request failed (HTTP ${status}).`, recovery ? recoveryHint(recovery) : diagnostic?.hint ?? hint, !diagnostic && safeToRetry && (status === 429 || status >= 500), { status, ...recovery ? { recovery } : {}, ...diagnostic ? { serviceCode: diagnostic.serviceCode, ...safeDiagnosticDetails(body) } : {}, ...retryAfterMs === void 0 ? {} : { retryAfterMs } });
183483
185224
  this.status = status;
183484
185225
  this.body = body;
183485
185226
  }
@@ -183557,10 +185298,11 @@ var Client = class {
183557
185298
  const retryAfterMs = retryDelay(response.headers.get("Retry-After"), this.runtime.now());
183558
185299
  if (!response.ok) {
183559
185300
  let errorBody;
183560
- if (/^\/v1\/authored-motion(?:\/|\?|$)/.test(path) || /^\/v1\/sfx\//.test(path) || /^\/v1\/team(?:\/|$)/.test(path) || path.startsWith("/v1/studio/") || path.startsWith("/v1/batches") && response.status === 409 || path === "/v1/search/brief" && [400, 422, 503].includes(response.status) || /^\/v1\/projects\/[^/]+\/progress$/.test(path) && response.status === 409) {
185301
+ if ((/^\/v1\/(?:authored-motion|style-sources|sfx|team|studio|batches)(?:\/|\?|$)/.test(path) || path === "/v1/search/brief" || /^\/v1\/projects\/[^/]+\/progress$/.test(path)) && [400, 402, 403, 404, 409, 422, 429, 503].includes(response.status)) {
183561
185302
  try {
183562
- const diagnostic = searchDiagnostic(response.status, await boundedJson(response, 16 * 1024));
183563
- errorBody = diagnostic ? { error: { code: diagnostic.serviceCode } } : void 0;
185303
+ const parsed = await boundedJson(response, 16 * 1024);
185304
+ const diagnostic = searchDiagnostic(response.status, parsed);
185305
+ errorBody = diagnostic ? { error: { code: diagnostic.serviceCode, ...safeDiagnosticDetails(parsed) } } : void 0;
183564
185306
  } catch {
183565
185307
  }
183566
185308
  } else await response.body?.cancel();
@@ -183638,7 +185380,11 @@ async function loadSyncState(root, endpoint2, workspaceId) {
183638
185380
  const state = JSON.parse(raw);
183639
185381
  if (state.projectId !== void 0) assertIdentifier(state.projectId);
183640
185382
  if (state.schemaVersion !== 1 || typeof state.documents !== "object") throw new Error("Invalid local sync state");
183641
- if (state.endpoint !== endpoint2 || state.workspaceId !== workspaceId) throw new CliError("WORKSPACE_MISMATCH", "This folder is bound to a different endpoint/workspace.", "Use a separate folder; never merge private documents across spaces.");
185383
+ if (state.endpoint !== endpoint2 || state.workspaceId !== workspaceId) {
185384
+ assertIdentifier(state.workspaceId);
185385
+ normalizeUrl(state.endpoint);
185386
+ throw new CliError("WORKSPACE_MISMATCH", `This folder is bound to a different endpoint/workspace. Bound workspace: ${state.workspaceId}; active workspace: ${workspaceId}.`, "Run editorbrain status to inspect the active connection. Run editorbrain login and authorize the workspace shown as boundWorkspaceId, then retry in this folder. For the current workspace, use a separate folder. Do not delete or edit .sync.json to bypass isolation.", false, { boundWorkspaceId: state.workspaceId, currentWorkspaceId: workspaceId, boundEndpoint: state.endpoint });
185387
+ }
183642
185388
  for (const [path, item] of Object.entries(state.documents)) {
183643
185389
  safeDocumentPath(path);
183644
185390
  if (!Number.isInteger(item.revision) || item.revision < 1 || !/^[a-f0-9]{64}$/.test(item.sha256)) throw new Error("Invalid local revision");
@@ -183763,8 +185509,8 @@ ${conflicts.join("\n")}`, "Run pull --dry-run and reconcile the reported paths."
183763
185509
  }
183764
185510
 
183765
185511
  // packages/cli/src/integrations.ts
183766
- import { constants as constants6 } from "node:fs";
183767
- import { lstat as lstat5, open as open6 } from "node:fs/promises";
185512
+ import { constants as constants7 } from "node:fs";
185513
+ import { lstat as lstat6, open as open8 } from "node:fs/promises";
183768
185514
  function object7(value) {
183769
185515
  return value !== null && typeof value === "object" && !Array.isArray(value);
183770
185516
  }
@@ -183797,13 +185543,13 @@ async function readIntegrationSettings(file) {
183797
185543
  const invalidFile = () => new CliError("INVALID_ARGUMENT", "Choose a regular integration settings JSON file under 16 KiB.", "Store provider credentials in the provider connection, not this file.");
183798
185544
  const changedFile = () => new CliError("INVALID_ARGUMENT", "Integration settings changed while being read.", "Choose a stable regular settings file and try again.");
183799
185545
  const limit = 16 * 1024;
183800
- const before = await lstat5(file);
185546
+ const before = await lstat6(file);
183801
185547
  if (!before.isFile() || before.isSymbolicLink() || before.size > limit) throw invalidFile();
183802
185548
  const unchanged2 = (info) => info.isFile() && !info.isSymbolicLink() && info.dev === before.dev && info.ino === before.ino && info.size === before.size && info.mtimeMs === before.mtimeMs && info.ctimeMs === before.ctimeMs;
183803
- const handle = await open6(file, constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
185549
+ const handle = await open8(file, constants7.O_RDONLY | constants7.O_NOFOLLOW | constants7.O_NONBLOCK);
183804
185550
  try {
183805
185551
  const opened = await handle.stat();
183806
- const current2 = await lstat5(file);
185552
+ const current2 = await lstat6(file);
183807
185553
  if (!unchanged2(opened) || !unchanged2(current2)) throw changedFile();
183808
185554
  const bytes = Buffer.alloc(limit + 1);
183809
185555
  let length = 0;
@@ -183813,7 +185559,7 @@ async function readIntegrationSettings(file) {
183813
185559
  length += bytesRead;
183814
185560
  }
183815
185561
  const after = await handle.stat();
183816
- const finalPath = await lstat5(file);
185562
+ const finalPath = await lstat6(file);
183817
185563
  if (length > limit || length !== opened.size || !unchanged2(after) || !unchanged2(finalPath)) throw changedFile();
183818
185564
  try {
183819
185565
  return JSON.parse(bytes.subarray(0, length).toString("utf8"));
@@ -184021,10 +185767,10 @@ async function diagnose(options, fetcher = fetch, probeTool = probe) {
184021
185767
 
184022
185768
  // packages/cli/src/skill-installations.ts
184023
185769
  function installationRegistry() {
184024
- return join2(process.env.EDITORBRAIN_CONFIG_DIR ?? process.env.EDITORHARNESS_CONFIG_DIR ?? join2(homedir(), ".config", "editorbrain"), "skill-installations");
185770
+ return join4(process.env.EDITORBRAIN_CONFIG_DIR ?? process.env.EDITORHARNESS_CONFIG_DIR ?? join4(homedir(), ".config", "editorbrain"), "skill-installations");
184025
185771
  }
184026
185772
  function recordName(directory, scope) {
184027
- return createHash3("sha256").update(`${scope}\0${directory}`).digest("hex") + ".json";
185773
+ return createHash5("sha256").update(`${scope}\0${directory}`).digest("hex") + ".json";
184028
185774
  }
184029
185775
  function validateRecord(value) {
184030
185776
  const r = value;
@@ -184088,7 +185834,7 @@ async function installManagedGuidance(directory, agent, options = {}) {
184088
185834
  const previous = await readInstallation(root, scope, options.registry);
184089
185835
  if (previous?.pinned) throw new CliError("SKILLS_PINNED", "Las instrucciones de este proyecto est\xE1n fijadas.", "Usa skill unpin en esta carpeta cuando termines la edici\xF3n.");
184090
185836
  const target = parseAgentTarget(agent ?? previous?.agent);
184091
- const install = await prepareAgentGuidance(root, target, void 0, void 0, { global: options.global, backupId: randomUUID4() });
185837
+ const install = await prepareAgentGuidance(root, target, void 0, void 0, { global: options.global, backupId: randomUUID5() });
184092
185838
  const result2 = await install();
184093
185839
  try {
184094
185840
  await rememberGuidance(result2, scope, options.registry);
@@ -184109,7 +185855,7 @@ async function pinGuidance(directory, pinned, registry = installationRegistry())
184109
185855
  for (const agent of record13.agent === "both" ? ["codex", "claude"] : [record13.agent]) {
184110
185856
  for (const skill of BUNDLED_SKILLS) for (const path of await bundledGuidanceFiles(skill)) {
184111
185857
  const current2 = await readText(root, `${installedSkillDirectory(agent, skill)}/${path}`, false);
184112
- const expected = await readFile2(join2(bundledSkillDirectory(void 0, skill), path), "utf8");
185858
+ const expected = await readFile2(join4(bundledSkillDirectory(void 0, skill), path), "utf8");
184113
185859
  if (current2 !== expected) throw new Error("Project instructions differ from this release; resolve them before pinning.");
184114
185860
  }
184115
185861
  }
@@ -184155,18 +185901,18 @@ async function latestPublishedVersion(fetcher = fetch) {
184155
185901
  }
184156
185902
  }
184157
185903
  async function npmEntrypoint(env = process.env) {
184158
- const candidates = [env.npm_execpath, join3(dirname4(process.execPath), "node_modules/npm/bin/npm-cli.js")];
185904
+ const candidates = [env.npm_execpath, join5(dirname6(process.execPath), "node_modules/npm/bin/npm-cli.js")];
184159
185905
  for (const directory of (env.PATH ?? "").split(delimiter).filter(Boolean)) {
184160
- candidates.push(join3(directory, "node_modules/npm/bin/npm-cli.js"));
185906
+ candidates.push(join5(directory, "node_modules/npm/bin/npm-cli.js"));
184161
185907
  try {
184162
- candidates.push(await realpath3(join3(directory, "npm")));
185908
+ candidates.push(await realpath3(join5(directory, "npm")));
184163
185909
  } catch {
184164
185910
  }
184165
185911
  }
184166
185912
  for (const candidate of candidates) {
184167
185913
  if (!candidate || !candidate.endsWith("npm-cli.js")) continue;
184168
185914
  try {
184169
- if ((await lstat6(candidate)).isFile()) return candidate;
185915
+ if ((await lstat7(candidate)).isFile()) return candidate;
184170
185916
  } catch {
184171
185917
  }
184172
185918
  }
@@ -184200,9 +185946,9 @@ async function installPublishedCli(version, runner = exec) {
184200
185946
  );
184201
185947
  }
184202
185948
  try {
184203
- const metadata = JSON.parse(await readFile3(join3(root, "editorbrain/package.json"), "utf8"));
185949
+ const metadata = JSON.parse(await readFile3(join5(root, "editorbrain/package.json"), "utf8"));
184204
185950
  if (metadata.name !== "editorbrain" || metadata.version !== version || metadata.bin?.editorbrain !== "bin/editorbrain.mjs") throw new Error("Unexpected installed package");
184205
- const executable = join3(root, "editorbrain/bin/editorbrain.mjs");
185951
+ const executable = join5(root, "editorbrain/bin/editorbrain.mjs");
184206
185952
  const result2 = JSON.parse((await runner(process.execPath, [executable, "version"], { timeout: 15e3, maxBuffer: 65536 })).stdout);
184207
185953
  if (result2.version !== version) throw new Error("Unexpected executable version");
184208
185954
  return executable;
@@ -184237,7 +185983,7 @@ async function detectAgents(root) {
184237
185983
  for (const skill of BUNDLED_SKILLS) {
184238
185984
  const file = await checkedPath(root, `${installedSkillDirectory(agent, skill)}/SKILL.md`, false);
184239
185985
  try {
184240
- if ((await lstat6(file)).isFile()) {
185986
+ if ((await lstat7(file)).isFile()) {
184241
185987
  found.push(agent);
184242
185988
  break;
184243
185989
  }
@@ -184423,8 +186169,8 @@ async function projectProgressCommand(client, command, flags) {
184423
186169
  }
184424
186170
 
184425
186171
  // packages/cli/src/event-mix.ts
184426
- import { mkdir as mkdir3, readFile as readFile4, writeFile, unlink as unlink3 } from "node:fs/promises";
184427
- import { dirname as dirname5, join as join4, resolve as resolve6 } from "node:path";
186172
+ import { mkdir as mkdir5, readFile as readFile4, writeFile as writeFile2, unlink as unlink4 } from "node:fs/promises";
186173
+ import { dirname as dirname7, join as join6, resolve as resolve6 } from "node:path";
184428
186174
  function validateEventCues(value, duration) {
184429
186175
  const v = value;
184430
186176
  if (!v || v.schemaVersion !== 1 || v.clock !== "output_seconds" || !Array.isArray(v.cues) || v.cues.length > 300 || Object.keys(v).some((k) => !["schemaVersion", "clock", "cues"].includes(k))) throw new Error("Use schemaVersion 1, clock output_seconds and up to 300 explicit cues.");
@@ -184463,7 +186209,7 @@ function floats(bytes) {
184463
186209
  async function decode(file, target) {
184464
186210
  await runMediaTool("ffmpeg", ["-v", "error", "-n", ...localInputArgs(file), "-map", "0:a:0", "-vn", "-ar", "48000", "-ac", "2", "-f", "f32le", target], { timeoutMs: 6e5 });
184465
186211
  const b = await readFile4(target);
184466
- await unlink3(target);
186212
+ await unlink4(target);
184467
186213
  return floats(b);
184468
186214
  }
184469
186215
  function wav(data) {
@@ -184499,12 +186245,12 @@ async function mixEvents(options) {
184499
186245
  sources.push(source2);
184500
186246
  }
184501
186247
  const directory = await productionOutputPath(options.root, options.out);
184502
- await mkdir3(dirname5(directory), { recursive: true, mode: 448 });
186248
+ await mkdir5(dirname7(directory), { recursive: true, mode: 448 });
184503
186249
  await productionOutputPath(options.root, options.out);
184504
- await mkdir3(directory, { mode: 448 });
184505
- const mix = await decode(voice.path, join4(directory, "voice.raw")), records = [];
186250
+ await mkdir5(directory, { mode: 448 });
186251
+ const mix = await decode(voice.path, join6(directory, "voice.raw")), records = [];
184506
186252
  for (let i = 0; i < cues.length; i++) {
184507
- const effect = await decode(sources[i].path, join4(directory, "effect.raw"));
186253
+ const effect = await decode(sources[i].path, join6(directory, "effect.raw"));
184508
186254
  records.push({ ...cues[i], sourceSha256: sources[i].sha256, sampleFrames: effect.length / 2, ...addEventPcm(mix, effect, cues[i].time, cues[i].peak) });
184509
186255
  }
184510
186256
  const cuePlan = { durationSeconds: mix.length / 2 / 48e3, hookEndSeconds, cues: records.map((c) => {
@@ -184521,16 +186267,16 @@ async function mixEvents(options) {
184521
186267
  if (peak >= 0.99) throw new Error("Mix would clip: lower explicit cue levels or prepare voice gain first. No automatic voice normalization applied.");
184522
186268
  for (const s of [voice, ...sources]) if ((await probeLocalMedia(s.path)).sha256 !== s.sha256) throw new Error("Audio source changed during mix.");
184523
186269
  if (options.context && !await options.context.validateContext()) throw new Error("Project preferences changed during the mix. Refresh context; no final mix was written.");
184524
- const path = join4(directory, "mix.wav");
184525
- await writeFile(path, wav(mix), { flag: "wx", mode: 384 });
186270
+ const path = join6(directory, "mix.wav");
186271
+ await writeFile2(path, wav(mix), { flag: "wx", mode: 384 });
184526
186272
  const report = { schemaVersion: 1, kind: "editorbrain.event-mix", voiceSha256: voice.sha256, path, clock: "output_seconds", musicAdded: false, voiceGain: 1, cues: records, peak, mediaUploaded: false, listening: "not_assessed", preferenceCheck, contextScope: options.context?.contextScope ?? "not_checked", contextHash: options.context?.contextVersion ?? null, note: "The SFX maximum peak is aligned to the event, not its file start. Inspect audible attack and sync; those can differ from the peak. Without --project, preferences are not checked; do not claim compliance." };
184527
- await writeFile(join4(directory, "report.json"), JSON.stringify(report, null, 2), { flag: "wx", mode: 384 });
186273
+ await writeFile2(join6(directory, "report.json"), JSON.stringify(report, null, 2), { flag: "wx", mode: 384 });
184528
186274
  return report;
184529
186275
  }
184530
186276
 
184531
186277
  // packages/cli/src/production-sheet.ts
184532
- import { mkdir as mkdir4, readFile as readFile5, writeFile as writeFile2, unlink as unlink4 } from "node:fs/promises";
184533
- import { dirname as dirname6, join as join5 } from "node:path";
186278
+ import { mkdir as mkdir6, readFile as readFile5, writeFile as writeFile3, unlink as unlink5 } from "node:fs/promises";
186279
+ import { dirname as dirname8, join as join7 } from "node:path";
184534
186280
  var esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
184535
186281
  function freezeIntervals(log, duration) {
184536
186282
  const result2 = [];
@@ -184569,13 +186315,13 @@ async function createProductionSheet(options) {
184569
186315
  if (options.platform && input.platform && options.platform !== input.platform) throw new Error("Platform flag conflicts with review profile.");
184570
186316
  const platform = options.platform ?? input.platform;
184571
186317
  const directory = await productionOutputPath(options.root, options.out);
184572
- await mkdir4(dirname6(directory), { recursive: true, mode: 448 });
186318
+ await mkdir6(dirname8(directory), { recursive: true, mode: 448 });
184573
186319
  await productionOutputPath(options.root, options.out);
184574
- await mkdir4(directory, { mode: 448 });
184575
- const raw = join5(directory, "samples.gray");
184576
- const result2 = await runMediaTool("ffmpeg", ["-v", "info", "-nostats", "-n", "-copyts", "-start_at_zero", ...localInputArgs(source2.path), "-filter_complex", `[0:${video[0].index}]split=2[a][b];[a]freezedetect=n=0.003:d=1,fps=fps=1:start_time=0:round=up,scale=240:240:force_original_aspect_ratio=decrease,setsar=1[thumb];[b]fps=fps=1:start_time=0:round=up,scale=96:96,format=gray[gray]`, "-map", "[thumb]", "-an", "-fps_mode", "passthrough", "-q:v", "3", join5(directory, "frame-%05d.jpg"), "-map", "[gray]", "-an", "-f", "rawvideo", raw], { timeoutMs: 6e5, maxOutputBytes: 8 * 1024 * 1024 });
186320
+ await mkdir6(directory, { mode: 448 });
186321
+ const raw = join7(directory, "samples.gray");
186322
+ const result2 = await runMediaTool("ffmpeg", ["-v", "info", "-nostats", "-n", "-copyts", "-start_at_zero", ...localInputArgs(source2.path), "-filter_complex", `[0:${video[0].index}]split=2[a][b];[a]freezedetect=n=0.003:d=1,fps=fps=1:start_time=0:round=up,scale=240:240:force_original_aspect_ratio=decrease,setsar=1[thumb];[b]fps=fps=1:start_time=0:round=up,scale=96:96,format=gray[gray]`, "-map", "[thumb]", "-an", "-fps_mode", "passthrough", "-q:v", "3", join7(directory, "frame-%05d.jpg"), "-map", "[gray]", "-an", "-f", "rawvideo", raw], { timeoutMs: 6e5, maxOutputBytes: 8 * 1024 * 1024 });
184577
186323
  const data = await readFile5(raw);
184578
- await unlink4(raw);
186324
+ await unlink5(raw);
184579
186325
  const count = data.length / (96 * 96);
184580
186326
  if (!Number.isInteger(count) || count < 1 || count > 1801 || count < Math.ceil(duration - 1e-6)) throw new Error("Incomplete frame sampling; no complete review was accepted.");
184581
186327
  if ((await probeLocalMedia(source2.path)).sha256 !== source2.sha256) throw new Error("Source changed during review.");
@@ -184589,15 +186335,15 @@ async function createProductionSheet(options) {
184589
186335
  return `<figure><div class="frame"><img loading="lazy" src="frame-${String(i + 1).padStart(5, "0")}.jpg" alt="${i} segundos">${p ? `<i class="bottom"></i><i class="right"></i>` : ""}</div><figcaption>${i}s ${esc(warnings.join(" \xB7 "))}</figcaption></figure>`;
184590
186336
  }).join("");
184591
186337
  const html = `<!doctype html><html lang="es"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src 'self' file:; style-src 'unsafe-inline'"><title>EditorBrain \xB7 revisi\xF3n completa</title><style>body{background:#171717;color:#eee;font:15px system-ui;margin:28px}main{display:grid;grid-template-columns:repeat(auto-fill,minmax(170px,1fr));gap:15px}figure{margin:0}.frame{position:relative;display:table}img{display:block;max-width:100%;height:auto}i{position:absolute;background:#f4474760;pointer-events:none}.bottom{bottom:0;left:0;width:100%;height:${(p?.bottom ?? 0) * 100}%}.right{top:0;right:0;height:100%;width:${(p?.right ?? 0) * 100}%}figcaption{padding:8px 0;min-height:40px;color:#ffd280}p{max-width:850px}</style><h1>Revisi\xF3n del video completo</h1><p>${count} cuadros \xB7 1 por segundo. ${esc(platform ?? "Sin perfil social")} \xB7 rojo: riesgo de interfaz aproximado. Las pausas planeadas se excluyen de avisos de congelaci\xF3n. Geometr\xEDa: ${esc(report.geometryStatus)}. Esto no aprueba la edici\xF3n.</p><p>Sin OCR ni detecci\xF3n autom\xE1tica de logos. Revisa la reproducci\xF3n y los cuadros adyacentes a cada aviso. Informe: report.json.</p><main>${cards}</main></html>`;
184592
- await writeFile2(join5(directory, "report.json"), JSON.stringify(report, null, 2), { flag: "wx", mode: 384 });
184593
- await writeFile2(join5(directory, "index.html"), html, { flag: "wx", mode: 384 });
184594
- return { kind: report.kind, complete: true, path: join5(directory, "index.html"), reportPath: join5(directory, "report.json"), sourceSha256: source2.sha256, frames: count, candidates: { freezes: freezes.length, nearlyEmpty: flat.length, geometry: report.candidates.geometry.length }, geometryStatus: report.geometryStatus, creativeQuality: "not_assessed", mediaUploaded: false };
186338
+ await writeFile3(join7(directory, "report.json"), JSON.stringify(report, null, 2), { flag: "wx", mode: 384 });
186339
+ await writeFile3(join7(directory, "index.html"), html, { flag: "wx", mode: 384 });
186340
+ return { kind: report.kind, complete: true, path: join7(directory, "index.html"), reportPath: join7(directory, "report.json"), sourceSha256: source2.sha256, frames: count, candidates: { freezes: freezes.length, nearlyEmpty: flat.length, geometry: report.candidates.geometry.length }, geometryStatus: report.geometryStatus, creativeQuality: "not_assessed", mediaUploaded: false };
184595
186341
  }
184596
186342
 
184597
186343
  // packages/cli/src/presenter-matte.ts
184598
186344
  import { spawn as spawn2 } from "node:child_process";
184599
- import { mkdir as mkdir5, writeFile as writeFile3, rename as rename4, unlink as unlink5 } from "node:fs/promises";
184600
- import { dirname as dirname7, join as join6 } from "node:path";
186345
+ import { mkdir as mkdir7, writeFile as writeFile4, rename as rename4, unlink as unlink6 } from "node:fs/promises";
186346
+ import { dirname as dirname9, join as join8 } from "node:path";
184601
186347
 
184602
186348
  // packages/cli/src/presenter-matte-source.ts
184603
186349
  var presenterMatteSource = 'import Foundation\nimport AVFoundation\nimport Vision\nimport CoreImage\nfunc fail(_ message: String) -> Never { fputs(message + "\\n", stderr); exit(1) }\nlet a = CommandLine.arguments\nif a.count != 5 { fail("Expected source, new output, width and height") }\nlet src = URL(fileURLWithPath:a[1]), dst = URL(fileURLWithPath:a[2])\nguard let w = Int(a[3]), let h = Int(a[4]), w > 0, h > 0 else { fail("Invalid dimensions") }\nif FileManager.default.fileExists(atPath:dst.path) { fail("Output already exists") }\nlet asset = AVURLAsset(url:src)\nguard let track = asset.tracks(withMediaType:.video).first else { fail("No video") }\nlet tr = track.preferredTransform\nif abs(tr.b) > 0.001 || abs(tr.c) > 0.001 || tr.a < 0 || tr.d < 0 { fail("Normalize orientation before segmentation") }\nlet reader = try AVAssetReader(asset:asset)\nlet output = AVAssetReaderTrackOutput(track:track,outputSettings:[kCVPixelBufferPixelFormatTypeKey as String:kCVPixelFormatType_32BGRA])\nreader.add(output)\nlet writer = try AVAssetWriter(outputURL:dst,fileType:.mov)\nlet input = AVAssetWriterInput(mediaType:.video,outputSettings:[AVVideoCodecKey:AVVideoCodecType.h264,AVVideoWidthKey:w,AVVideoHeightKey:h,AVVideoCompressionPropertiesKey:[AVVideoAverageBitRateKey:4000000]])\nlet adapter = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput:input,sourcePixelBufferAttributes:[kCVPixelBufferPixelFormatTypeKey as String:kCVPixelFormatType_32BGRA,kCVPixelBufferWidthKey as String:w,kCVPixelBufferHeightKey as String:h,kCVPixelBufferIOSurfacePropertiesKey as String:[:]])\nwriter.add(input)\nif !writer.startWriting() || !reader.startReading() { fail("Cannot start media processing") }\nlet request = VNGeneratePersonSegmentationRequest()\nrequest.qualityLevel = .accurate\nrequest.outputPixelFormat = kCVPixelFormatType_OneComponent8\nlet context = CIContext(options:[.cacheIntermediates:false])\nvar count = 0\nvar origin: CMTime? = nil\nwhile let sb = output.copyNextSampleBuffer() {\n autoreleasepool {\n let sourcePTS = CMSampleBufferGetPresentationTimeStamp(sb)\n if origin == nil { origin = sourcePTS; writer.startSession(atSourceTime:.zero) }\n let pts = CMTimeSubtract(sourcePTS,origin!)\n guard let pb = CMSampleBufferGetImageBuffer(sb) else { fail("Missing input frame") }\n do { try VNImageRequestHandler(cvPixelBuffer:pb,orientation:.up).perform([request]) }\n catch { fail("Segmentation failed; no placeholder was inserted") }\n guard let mask = request.results?.first?.pixelBuffer else { fail("No segmentation result; no placeholder was inserted") }\n let ci = CIImage(cvPixelBuffer:mask)\n let scaled = ci.transformed(by:CGAffineTransform(scaleX:CGFloat(w)/ci.extent.width,y:CGFloat(h)/ci.extent.height))\n let deadline = Date().addingTimeInterval(30)\n while !input.isReadyForMoreMediaData {\n if writer.status == .failed || Date() > deadline { fail("Writer stalled") }\n Thread.sleep(forTimeInterval:0.002)\n }\n guard let pool = adapter.pixelBufferPool else { fail("No pixel buffer pool") }\n var buf:CVPixelBuffer?\n if CVPixelBufferPoolCreatePixelBuffer(nil,pool,&buf) != kCVReturnSuccess || buf == nil { fail("Cannot allocate output frame") }\n context.render(scaled,to:buf!)\n if !adapter.append(buf!,withPresentationTime:pts) { fail("Cannot append output frame") }\n count += 1\n }\n}\nif reader.status != .completed || count == 0 { fail("Incomplete source decode") }\ninput.markAsFinished()\nlet group = DispatchGroup(); group.enter(); writer.finishWriting { group.leave() }\nif group.wait(timeout:.now()+60) != .success || writer.status != .completed { fail("Incomplete output") }\nprint("{\\"frames\\":\\(count),\\"fullMontage\\":true}")\n';
@@ -184659,32 +186405,32 @@ async function generatePresenterMatte(options) {
184659
186405
  const video = videos[0], plan = planPresenterMatte(source2.durationSeconds, video.fps);
184660
186406
  if (video.width > 2160 || video.height > 2160 || video.width % 2 || video.height % 2) throw new Error("Normalize montage dimensions: even width and height up to 2160.");
184661
186407
  const dir = await productionOutputPath(options.root, options.out);
184662
- await mkdir5(dirname7(dir), { recursive: true, mode: 448 });
186408
+ await mkdir7(dirname9(dir), { recursive: true, mode: 448 });
184663
186409
  await productionOutputPath(options.root, options.out);
184664
- await mkdir5(dir, { mode: 448 });
184665
- const swift = join6(dir, "matte.swift"), binary = join6(dir, "matte-tool"), result2 = join6(dir, "matte.partial.mov");
184666
- await writeFile3(swift, presenterMatteSource, { flag: "wx", mode: 384 });
186410
+ await mkdir7(dir, { mode: 448 });
186411
+ const swift = join8(dir, "matte.swift"), binary = join8(dir, "matte-tool"), result2 = join8(dir, "matte.partial.mov");
186412
+ await writeFile4(swift, presenterMatteSource, { flag: "wx", mode: 384 });
184667
186413
  try {
184668
186414
  await runLocal("swiftc", ["-O", swift, "-o", binary], 12e4);
184669
186415
  await runLocal(binary, [source2.path, result2, String(video.width), String(video.height)], 18e5);
184670
186416
  const [clock, matteClock, mask, after] = await Promise.all([readFrameClock(source2.path), readFrameClock(result2), probeLocalMedia(result2), probeLocalMedia(source2.path)]);
184671
186417
  assertMatteClocks(clock, matteClock);
184672
186418
  if (after.sha256 !== source2.sha256) throw new Error("Source changed during segmentation.");
184673
- const finalPath = join6(dir, "matte.mov");
186419
+ const finalPath = join8(dir, "matte.mov");
184674
186420
  await rename4(result2, finalPath);
184675
186421
  mask.path = finalPath;
184676
186422
  const report = { ...plan, generated: true, engine: "apple-vision-local", source: source2, matte: mask, frames: clock.length, frameClockVerified: true, placeholderFramesInserted: 0, silhouetteQuality: "not_assessed", mediaUploaded: false, modelDownloads: false, note: "Run review-sheet --matte on the result and inspect silhouette edges in motion. A blank mask can mean no person or a missed detection." };
184677
- await writeFile3(join6(dir, "report.json"), JSON.stringify(report, null, 2), { flag: "wx", mode: 384 });
186423
+ await writeFile4(join8(dir, "report.json"), JSON.stringify(report, null, 2), { flag: "wx", mode: 384 });
184678
186424
  return report;
184679
186425
  } finally {
184680
- await unlink5(binary).catch(() => {
186426
+ await unlink6(binary).catch(() => {
184681
186427
  });
184682
186428
  }
184683
186429
  }
184684
186430
 
184685
186431
  // packages/cli/src/sfx.ts
184686
- import { readdir as readdir4, lstat as lstat7 } from "node:fs/promises";
184687
- import { join as join7, extname as extname3, basename as basename2 } from "node:path";
186432
+ import { readdir as readdir4, lstat as lstat8 } from "node:fs/promises";
186433
+ import { join as join9, extname as extname3, basename as basename2 } from "node:path";
184688
186434
 
184689
186435
  // packages/cli/src/production-context.ts
184690
186436
  async function prepareProductionContext(root, projectId, client) {
@@ -184724,14 +186470,14 @@ var localPath = (id2) => {
184724
186470
  };
184725
186471
  async function indexSfx(directory, input, bankId) {
184726
186472
  const root = await ensureRoot(directory), target = localPath(bankId), folder = await assertNoMediaSymlinks(input);
184727
- if (!(await lstat7(folder)).isDirectory()) throw new Error("SFX input must be a directory.");
186473
+ if (!(await lstat8(folder)).isDirectory()) throw new Error("SFX input must be a directory.");
184728
186474
  const entries = [], paths2 = {}, failures = [];
184729
186475
  const files = await readdir4(folder, { withFileTypes: true });
184730
186476
  const selected = files.filter((e) => e.isFile() && [".wav", ".mp3", ".m4a", ".ogg", ".flac", ".aif", ".aiff"].includes(extname3(e.name).toLowerCase()));
184731
186477
  if (selected.length > 100) throw new Error("Choose a folder with up to 100 audio files; split larger banks by purpose. No files were changed.");
184732
186478
  for (const file of selected.sort((a, b) => a.name.localeCompare(b.name))) {
184733
186479
  try {
184734
- const probe2 = await probeLocalMedia(join7(folder, file.name));
186480
+ const probe2 = await probeLocalMedia(join9(folder, file.name));
184735
186481
  if (!probe2.durationSeconds || probe2.durationSeconds > 600 || !probe2.streams.some((s) => s.type === "audio") || probe2.streams.some((s) => s.type === "video" && !s.attachedPicture)) throw new Error("Expected a measured audio effect up to 600 seconds.");
184736
186482
  const id2 = "sfx-" + probe2.sha256.slice(0, 24);
184737
186483
  if (paths2[id2]) continue;
@@ -184794,8 +186540,8 @@ async function remoteSfx(client, subcommand, params) {
184794
186540
  }
184795
186541
 
184796
186542
  // packages/cli/src/media-preview.ts
184797
- import { chmod, link as link2, mkdtemp, rm } from "node:fs/promises";
184798
- import { dirname as dirname8, join as join8 } from "node:path";
186543
+ import { chmod, link as link3, mkdtemp, rm as rm2 } from "node:fs/promises";
186544
+ import { dirname as dirname10, join as join10 } from "node:path";
184799
186545
  async function prepareMediaPreview(root, file, out, quality = 720, audioStream) {
184800
186546
  if (![720, 1080].includes(quality) || !out.endsWith(".mp4")) throw new CliError("INVALID_ARGUMENT", "Use --quality 720 or 1080 and a new .mp4 output.", "Previews belong under .editorbrain-local/.");
184801
186547
  const source2 = await probeLocalMedia(await assertLocalMediaFile(file));
@@ -184808,25 +186554,25 @@ async function prepareMediaPreview(root, file, out, quality = 720, audioStream)
184808
186554
  if (/^(yuva|gbrap|rgba|bgra|argb|abgr|ya)/.test(videos[0].pixelFormat ?? "")) throw new CliError("PREVIEW_ALPHA", "Transparent media needs an explicit background for review.", "Keep the alpha master and export a composited review copy first.");
184809
186555
  const selected = audioStream === void 0 ? audio[0] : audio.find((s) => s.index === audioStream);
184810
186556
  if (audioStream !== void 0 && !selected) throw new CliError("INVALID_ARGUMENT", "The selected audio stream does not exist.", "Inspect the material before selecting a track.");
184811
- const target = await prepareSampleDirectory(root, out), temp = await mkdtemp(join8(dirname8(target), ".preview-"));
186557
+ const target = await prepareSampleDirectory(root, out), temp = await mkdtemp(join10(dirname10(target), ".preview-"));
184812
186558
  try {
184813
- const prepared = join8(temp, "preview.mp4"), edge = quality === 720 ? 1280 : 1920;
186559
+ const prepared = join10(temp, "preview.mp4"), edge = quality === 720 ? 1280 : 1920;
184814
186560
  await runMediaTool("ffmpeg", ["-v", "error", "-n", "-copyts", "-start_at_zero", ...localInputArgs(source2.path), "-map", `0:${videos[0].index}`, ...selected ? ["-map", `0:${selected.index}`, "-c:a", "aac", "-b:a", "128k"] : ["-an"], "-sn", "-dn", "-map_metadata", "-1", "-vf", `scale=w='min(iw,${edge})':h='min(ih,${edge})':force_original_aspect_ratio=decrease:force_divisible_by=2,setsar=1`, "-c:v", "libx264", "-preset", "fast", "-crf", "23", "-pix_fmt", "yuv420p", "-movflags", "+faststart", prepared], { timeoutMs: 6e5 });
184815
186561
  const result2 = await probeLocalMedia(prepared);
184816
186562
  if (result2.durationSeconds === null || Math.abs(result2.durationSeconds - source2.durationSeconds) > 0.25 || result2.streams.some((s) => s.type === "audio") !== !!selected) throw new CliError("PREVIEW_VERIFICATION", "Preview duration or audio does not match the source.", "No output was accepted. Inspect source timing in your editor.");
184817
186563
  if ((await probeLocalMedia(source2.path)).sha256 !== source2.sha256) throw new CliError("SOURCE_CHANGED", "The source changed during compression.", "Retry with a stable original.");
184818
186564
  await chmod(prepared, 384);
184819
- await link2(prepared, target);
186565
+ await link3(prepared, target);
184820
186566
  return { kind: "editorbrain.review-preview", path: target, sha256: result2.sha256, sourceSha256: source2.sha256, sourceBytes: source2.bytes, bytes: result2.bytes, durationSeconds: result2.durationSeconds, quality, originalPreserved: true, uploaded: false, uploadEligible: result2.bytes <= 90 * 1024 * 1024, savedPercent: Math.round((1 - result2.bytes / source2.bytes) * 100), purpose: "preview", note: "Review copy, not an export master. Inspect text, color and audio before sharing. Small sources may become larger; originals remain untouched." };
184821
186567
  } finally {
184822
- await rm(temp, { recursive: true, force: true });
186568
+ await rm2(temp, { recursive: true, force: true });
184823
186569
  }
184824
186570
  }
184825
186571
 
184826
186572
  // packages/cli/src/studio-audio.ts
184827
- import { link as link3, mkdtemp as mkdtemp2, readFile as readFile6, rm as rm2 } from "node:fs/promises";
184828
- import { dirname as dirname9, join as join9 } from "node:path";
184829
- import { createHash as createHash4 } from "node:crypto";
186573
+ import { link as link4, mkdtemp as mkdtemp2, readFile as readFile6, rm as rm3 } from "node:fs/promises";
186574
+ import { dirname as dirname11, join as join11 } from "node:path";
186575
+ import { createHash as createHash6 } from "node:crypto";
184830
186576
  async function prepareStudioAudio(root, file, out, streamIndex) {
184831
186577
  const source2 = await probeLocalMedia(await assertLocalMediaFile(file));
184832
186578
  const audio = source2.streams.filter((stream) => stream.type === "audio");
@@ -184836,18 +186582,18 @@ async function prepareStudioAudio(root, file, out, streamIndex) {
184836
186582
  if (!selected) throw new CliError("INVALID_ARGUMENT", "The selected stream is not an audio track.", "Inspect media inventory before selecting a track.");
184837
186583
  if (source2.durationSeconds === null || source2.durationSeconds > 1800) throw new CliError("AUDIO_DURATION_LIMIT", "Tempo preparation requires a known source duration up to 30 minutes.", "Split long recordings explicitly and preserve each segment offset; never silently truncate.");
184838
186584
  if (!out.endsWith(".wav")) throw new CliError("INVALID_ARGUMENT", "The prepared output must be a .wav file.", "Use --out .editorbrain-local/studio/source.wav.");
184839
- const target = await prepareSampleDirectory(root, out), temp = await mkdtemp2(join9(dirname9(target), ".tempo-"));
186585
+ const target = await prepareSampleDirectory(root, out), temp = await mkdtemp2(join11(dirname11(target), ".tempo-"));
184840
186586
  try {
184841
- const prepared = join9(temp, "audio.wav");
186587
+ const prepared = join11(temp, "audio.wav");
184842
186588
  await runMediaTool("ffmpeg", ["-v", "error", "-n", "-copyts", "-start_at_zero", ...localInputArgs(source2.path), "-map", `0:${selected.index}`, "-vn", "-sn", "-dn", "-map_metadata", "-1", "-af", "aresample=16000:async=1:first_pts=0", "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", "-t", "1801", prepared], { timeoutMs: 6e5 });
184843
186589
  const verified = await probeLocalMedia(prepared);
184844
186590
  if (verified.durationSeconds === null || verified.durationSeconds > 1800 || verified.bytes > 90 * 1024 * 1024) throw new CliError("AUDIO_DURATION_LIMIT", "The decoded audio exceeds the supported duration.", "Inspect source timestamps; no file was uploaded.");
184845
186591
  if ((await probeLocalMedia(source2.path)).sha256 !== source2.sha256) throw new CliError("SOURCE_CHANGED", "The source changed during extraction.", "Retry only after the source is stable.");
184846
- const bytes = await readFile6(prepared), hash6 = createHash4("sha256").update(bytes).digest("hex");
184847
- await link3(prepared, target);
186592
+ const bytes = await readFile6(prepared), hash6 = createHash6("sha256").update(bytes).digest("hex");
186593
+ await link4(prepared, target);
184848
186594
  return { kind: "editorbrain.scribe-input", name: "Tempo", path: target, sha256: hash6, bytes: bytes.length, durationMs: Math.round(verified.durationSeconds * 1e3), mimeType: "audio/wav", sourceSha256: source2.sha256, sourcePath: source2.path, audioStream: selected.index, sourceStartTimeSeconds: source2.startTimeSeconds, timestampBasis: "milliseconds_from_container_start", silenceRemoved: false, uploaded: false, next: "Upload this WAV using assets upload, then quote Tempo with its assetId. Keep this source mapping locally; returned word times refer to this prepared audio." };
184849
186595
  } finally {
184850
- await rm2(temp, { recursive: true, force: true });
186596
+ await rm3(temp, { recursive: true, force: true });
184851
186597
  }
184852
186598
  }
184853
186599
 
@@ -185042,9 +186788,9 @@ async function setup(options, runner = runHost) {
185042
186788
 
185043
186789
  // packages/cli/src/onboarding.ts
185044
186790
  import { createServer } from "node:http";
185045
- import { randomBytes, createHash as createHash5 } from "node:crypto";
185046
- import { join as join10, dirname as dirname10 } from "node:path";
185047
- import { mkdir as mkdir6 } from "node:fs/promises";
186791
+ import { randomBytes, createHash as createHash7 } from "node:crypto";
186792
+ import { join as join12, dirname as dirname12 } from "node:path";
186793
+ import { mkdir as mkdir8 } from "node:fs/promises";
185048
186794
 
185049
186795
  // packages/cli/src/onboarding-brand.ts
185050
186796
  var onboardingWordmark = '<svg xmlns="http://www.w3.org/2000/svg"\n width="873" height="131" viewBox="0 0 873.000000 131.000000"\n preserveAspectRatio="xMidYMid meet">\n<!-- Traced from approved Thought Loop lettering, excluding residual background. -->\n<g transform="translate(0.000000,131.000000) scale(0.100000,-0.100000)"\nfill="#f3ede3" stroke="none">\n<path d="M2116 1290 c-41 -13 -63 -36 -82 -87 -14 -36 -15 -50 -6 -81 31 -102\n157 -139 231 -68 50 48 58 116 23 183 -25 46 -107 72 -166 53z"/>\n<path d="M7491 1282 c-69 -34 -97 -113 -68 -185 30 -71 133 -101 204 -57 94\n57 80 202 -24 246 -43 19 -71 18 -112 -4z"/>\n<path d="M4771 1268 c-37 -13 -41 -39 -41 -314 0 -502 11 -894 27 -910 10 -10\n39 -14 97 -14 87 0 116 13 116 53 0 22 12 21 43 -3 75 -60 226 -86 338 -60\n129 30 250 123 302 233 31 66 57 171 57 230 -1 171 -105 339 -257 414 -67 33\n-85 38 -169 41 -113 5 -170 -7 -246 -53 -31 -19 -60 -35 -65 -35 -4 0 -6 84\n-5 188 5 230 5 229 -105 234 -40 2 -81 0 -92 -4z m552 -578 c59 -29 83 -51\n112 -105 32 -61 35 -157 6 -213 -25 -48 -77 -97 -123 -116 -51 -22 -153 -20\n-203 3 -145 66 -185 260 -77 375 67 72 198 97 285 56z"/>\n<path d="M1699 1243 c-11 -13 -13 -56 -11 -205 2 -114 0 -188 -6 -188 -5 0\n-35 15 -67 34 -87 53 -175 67 -285 46 -210 -40 -360 -232 -360 -461 0 -256\n193 -459 436 -459 77 0 155 25 227 74 l52 34 6 -29 c11 -52 24 -59 113 -59 44\n0 86 4 92 8 33 22 36 52 29 330 -3 152 -7 412 -10 576 -3 233 -7 301 -17 307\n-7 5 -52 9 -99 9 -69 0 -89 -3 -100 -17z m-133 -569 c137 -84 153 -274 33\n-377 -121 -104 -299 -65 -377 83 -21 38 -17 151 6 197 65 124 221 170 338 97z"/>\n<path d="M2543 1168 c-4 -7 -10 -65 -13 -128 l-5 -115 -60 -3 c-32 -2 -65 -8\n-72 -14 -9 -7 -13 -38 -13 -94 0 -103 8 -114 90 -114 l58 0 4 -232 c3 -261 9\n-284 82 -366 101 -111 320 -117 422 -11 l29 30 -35 65 c-47 89 -62 99 -111 73\n-49 -24 -80 -24 -112 1 -39 31 -47 77 -47 267 l0 171 98 4 c128 4 132 7 132\n110 0 106 -3 108 -129 108 l-101 0 0 114 c0 146 0 146 -120 146 -60 0 -91 -4\n-97 -12z"/>\n<path d="M4515 941 c-49 -12 -108 -47 -144 -85 -43 -44 -51 -45 -51 -5 0 62\n-11 69 -108 69 -55 0 -95 -5 -105 -12 -16 -12 -17 -46 -15 -431 3 -489 -8\n-447 123 -447 118 0 113 -12 117 260 3 189 6 231 21 265 39 87 122 144 212\n145 75 0 78 5 83 113 5 119 -3 137 -61 136 -23 -1 -55 -4 -72 -8z"/>\n<path d="M6218 940 c-47 -14 -135 -69 -152 -95 -23 -36 -36 -31 -36 13 0 21\n-5 43 -12 50 -16 16 -180 16 -196 0 -9 -9 -12 -119 -12 -435 0 -489 -12 -443\n118 -443 116 0 112 -8 112 241 0 238 9 286 68 351 48 53 102 78 173 78 30 0\n60 5 67 12 8 8 12 48 12 113 0 65 -4 105 -12 113 -13 13 -89 15 -130 2z"/>\n<path d="M8259 940 c-54 -9 -133 -48 -172 -84 -33 -30 -47 -26 -47 13 0 15 -5\n32 -12 39 -14 14 -166 16 -188 2 -13 -8 -15 -67 -15 -428 0 -337 3 -423 14\n-436 10 -12 32 -16 97 -16 129 0 124 -11 124 273 0 129 5 249 10 269 43 154\n261 187 343 53 l27 -46 0 -253 c0 -309 -5 -296 125 -296 135 0 127 -21 123\n343 -3 290 -4 304 -26 352 -34 74 -68 118 -115 152 -75 54 -192 80 -288 63z"/>\n<path d="M350 926 c-102 -29 -192 -95 -249 -184 -97 -153 -97 -381 0 -534 89\n-139 233 -206 422 -195 76 4 99 10 163 41 72 36 174 124 174 151 0 16 -47 57\n-107 91 l-45 27 -26 -22 c-90 -72 -101 -76 -193 -76 -81 0 -90 2 -131 30 -43\n31 -88 95 -88 128 0 16 22 17 314 17 314 0 315 0 330 22 41 58 -8 274 -79 350\n-14 15 -25 30 -25 34 0 20 -128 100 -190 118 -64 19 -205 20 -270 2z m239\n-215 c44 -23 86 -72 96 -113 l7 -28 -211 0 c-171 0 -211 3 -211 14 0 17 45 84\n73 107 58 50 170 58 246 20z"/>\n<path d="M3401 924 c-244 -65 -390 -320 -326 -567 88 -338 502 -461 774 -230\n98 84 151 205 151 348 0 50 -7 111 -15 138 -46 153 -170 271 -328 313 -66 18\n-187 17 -256 -2z m239 -242 c62 -32 115 -100 125 -163 33 -194 -166 -341 -343\n-253 -51 26 -79 55 -115 123 -22 43 -16 134 13 190 60 117 205 164 320 103z"/>\n<path d="M6723 930 c-47 -10 -146 -55 -175 -79 -11 -9 -28 -23 -37 -31 -10 -8\n-38 -45 -63 -81 -61 -90 -82 -168 -76 -296 3 -88 7 -106 41 -176 77 -164 225\n-257 407 -257 64 0 167 33 218 70 51 37 62 37 62 4 0 -42 25 -53 117 -54 73 0\n83 2 97 22 14 19 16 76 16 418 0 298 -3 401 -13 420 -12 23 -18 25 -101 28\n-95 3 -116 -5 -116 -43 0 -35 -11 -37 -48 -9 -75 58 -223 87 -329 64z m243\n-256 c73 -45 107 -100 112 -180 6 -85 -16 -141 -73 -192 -109 -95 -276 -79\n-358 36 -27 37 -32 54 -35 116 -3 48 1 84 10 106 57 136 221 190 344 114z"/>\n<path d="M2065 896 c-14 -20 -15 -76 -13 -431 3 -476 -8 -435 125 -435 123 0\n115 -32 112 447 -1 331 -4 402 -17 420 -13 21 -22 23 -103 23 -82 0 -90 -2\n-104 -24z"/>\n<path d="M7459 903 c-11 -13 -14 -94 -14 -430 0 -483 -10 -443 115 -443 119 0\n110 -35 110 447 0 482 10 443 -117 443 -63 0 -84 -4 -94 -17z"/>\n</g>\n</svg>\n';
@@ -185425,7 +187171,11 @@ var artifactScript = String.raw`
185425
187171
  field(fontFields, 'Fuente de títulos', tokenValue('typography.heading'), v => setToken('typography.heading', v), { placeholder: 'Ej. Manrope', maxLength: 100 });
185426
187172
  field(fontFields, 'Fuente de texto', tokenValue('typography.body'), v => setToken('typography.body', v), { placeholder: 'Ej. Inter', maxLength: 100 });
185427
187173
  strengthControl(fontFields, 'Aplicar estas fuentes', ['typography.heading', 'typography.body']);
185428
- type.append(details('Escribir mis fuentes', fontFields));
187174
+ const customFonts = !!(tokenValue('typography.heading') || tokenValue('typography.body')) && !fonts.some(([, heading, body]) => tokenValue('typography.heading') === heading && tokenValue('typography.body') === body);
187175
+ const fontDetails = details('Escribir mis fuentes', fontFields, customFonts ? 'Tus fuentes seleccionadas' : undefined);
187176
+ fontDetails.open = customFonts;
187177
+ fontDetails.dataset.selected = String(customFonts);
187178
+ type.append(fontDetails);
185429
187179
  panel.append(type);
185430
187180
  const freedom = section('¿Cuánto puede explorar tu agente?', 'Los tokens obligatorios de marca se respetan en ambos casos.', decide(!p().freedom, () => updateProfile('freedom', '')));
185431
187181
  choices(freedom, [[options.freedom[0], 'Una identidad reconocible', 'Mantener criterios visuales; adaptar cada escena.'], [options.freedom[1], 'Explorar composiciones nuevas', 'Variar recursos y animaciones según el video.']], p().freedom, v => updateProfile('freedom', v), { columns: 2 });
@@ -185852,7 +187602,7 @@ async function syncOnboardingDocuments(client, root, files, options) {
185852
187602
  // packages/cli/src/onboarding.ts
185853
187603
  var failure = (code, message, hint = "Reopen onboarding against the current files. Nothing is overwritten silently.") => new CliError(code, message, hint);
185854
187604
  function starterOutputId(brandId2) {
185855
- return `onboarding-${brandId2.slice(0, 48)}-${createHash5("sha256").update(brandId2).digest("hex").slice(0, 12)}`;
187605
+ return `onboarding-${brandId2.slice(0, 48)}-${createHash7("sha256").update(brandId2).digest("hex").slice(0, 12)}`;
185856
187606
  }
185857
187607
  function scaffold(brandId2, projectId) {
185858
187608
  const files = Object.fromEntries(Object.entries(createWorkspace({ brand: brandId2, project: projectId })).filter(([p]) => !p.startsWith(`.editorbrain/brands/${brandId2}/`)));
@@ -185908,14 +187658,14 @@ async function createOnboarding(options) {
185908
187658
  const directory = options.out ?? `.editorbrain-local/onboarding/${brandId2}-${Date.now()}-${randomBytes(3).toString("hex")}`;
185909
187659
  await productionOutputPath(root, `${directory}/session.json`);
185910
187660
  const target = await checkedPath(root, directory, false);
185911
- await mkdir6(dirname10(target), { recursive: true });
185912
- await mkdir6(target);
187661
+ await mkdir8(dirname12(target), { recursive: true });
187662
+ await mkdir8(target);
185913
187663
  const saved = await snapshots(root, brandId2, projectId), files = Object.fromEntries(Object.entries(saved).flatMap(([p, s]) => s ? [[p, s.content]] : []));
185914
187664
  const intake = onboardingIntakeFromFiles(brandId2, files);
185915
187665
  const session = { schemaVersion: 1, kind: "editorbrain.onboarding", brandId: brandId2, projectId, intake, snapshots: saved };
185916
187666
  await atomicWrite(root, `${directory}/session.json`, stableJson(session), { document: false, overwrite: false, mode: 384 });
185917
187667
  await atomicWrite(root, `${directory}/index.html`, renderOnboardingArtifact({ intake, requiresIdentity: saved[`.editorbrain/brands/${brandId2}/brand.md`] === null }), { document: false, overwrite: false, mode: 384 });
185918
- return { schemaVersion: 1, brandId: brandId2, projectId, configuration: creativeConfiguration(intake.profile?.creativeDirection ?? void 0, intake.profile?.creativePreferencesReviewed ?? void 0), artifact: join10(root, directory, "index.html"), session: `${directory}/session.json`, answers: `${directory}/answers.json`, savedToBrain: false, next: "Show the HTML artifact, or run onboarding serve --session <session>. Static artifacts download answers: put them in this workspace and run onboarding apply --session <session> --file <answers>. Never fill choices on the user\u2019s behalf." };
187668
+ return { schemaVersion: 1, brandId: brandId2, projectId, configuration: creativeConfiguration(intake.profile?.creativeDirection ?? void 0, intake.profile?.creativePreferencesReviewed ?? void 0), artifact: join12(root, directory, "index.html"), session: `${directory}/session.json`, answers: `${directory}/answers.json`, savedToBrain: false, next: "Show the HTML artifact, or run onboarding serve --session <session>. Static artifacts download answers: put them in this workspace and run onboarding apply --session <session> --file <answers>. Never fill choices on the user\u2019s behalf." };
185919
187669
  }
185920
187670
  async function applyOnboarding(options) {
185921
187671
  const root = await ensureRoot(options.directory);
@@ -185946,7 +187696,7 @@ async function applyOnboarding(options) {
185946
187696
  if (now !== current2[item.path]?.content) throw failure("ONBOARDING_CONFLICT", `Document changed while applying: ${item.path}`);
185947
187697
  await atomicWrite(root, item.path, item.content, { overwrite: now !== void 0 });
185948
187698
  }
185949
- await atomicWrite(root, `${dirname10(options.session)}/applied.json`, stableJson({ schemaVersion: 1, brandId: session.brandId, projectId: session.projectId, appliedAt: (/* @__PURE__ */ new Date()).toISOString(), accountSetup: intake.accountSetup, paths: Object.keys(merged) }), { document: false, mode: 384 });
187699
+ await atomicWrite(root, `${dirname12(options.session)}/applied.json`, stableJson({ schemaVersion: 1, brandId: session.brandId, projectId: session.projectId, appliedAt: (/* @__PURE__ */ new Date()).toISOString(), accountSetup: intake.accountSetup, paths: Object.keys(merged) }), { document: false, mode: 384 });
185950
187700
  }
185951
187701
  return { schemaVersion: 1, brandId: session.brandId, projectId: session.projectId, dryRun: !!options.dryRun, changed: pending.map((w) => w.path), documents: Object.keys(merged).length, brainGenerated: !options.dryRun, accountActions: plan.accountActions, aiAnalyzed: false, cloudSynced: false, next: "Local documents are ready after apply. Install the skill if needed, authenticate, use onboarding sync for this session, then complete and verify requested accountActions. Only if requested, use brain prepare and review before brain accept. A brain is editorial context, not a rendered video." };
185952
187702
  }, { migrateLegacy: !options.dryRun });
@@ -185955,7 +187705,7 @@ async function syncOnboarding(client, options) {
185955
187705
  const root = await ensureRoot(options.directory);
185956
187706
  return withWorkspaceLock(root, async () => {
185957
187707
  const session = await readSession(root, options.session);
185958
- const receipt = await readProductionJson(root, `${dirname10(options.session)}/applied.json`);
187708
+ const receipt = await readProductionJson(root, `${dirname12(options.session)}/applied.json`);
185959
187709
  if (receipt.brandId !== session.brandId || receipt.projectId !== session.projectId) throw failure("ONBOARDING_NOT_APPLIED", "Apply the reviewed choices locally before syncing.");
185960
187710
  const files = {};
185961
187711
  for (const path of paths(session.brandId, session.projectId)) {
@@ -185972,7 +187722,7 @@ async function syncOnboarding(client, options) {
185972
187722
  async function serveOnboarding(options) {
185973
187723
  const root = await ensureRoot(options.directory), session = await readSession(root, options.session), seconds = options.timeoutSeconds ?? 1800;
185974
187724
  if (!Number.isInteger(seconds) || seconds < 1 || seconds > 3600) throw failure("INVALID_ARGUMENT", "Timeout must be between 1 and 3600 seconds.");
185975
- const token = randomBytes(32).toString("hex"), csrf = randomBytes(32).toString("hex"), prefix = `/${token}`, answers = `${dirname10(options.session)}/answers.json`;
187725
+ const token = randomBytes(32).toString("hex"), csrf = randomBytes(32).toString("hex"), prefix = `/${token}`, answers = `${dirname12(options.session)}/answers.json`;
185976
187726
  let origin = "", consumed = false, busy = false, server;
185977
187727
  let complete, reject;
185978
187728
  const done = new Promise((yes, no) => {
@@ -186012,7 +187762,7 @@ async function serveOnboarding(options) {
186012
187762
  await atomicWrite(root, answers, stableJson(intake), { document: false, overwrite: false, mode: 384 });
186013
187763
  consumed = true;
186014
187764
  send(200, { saved: true, path: answers });
186015
- complete({ schemaVersion: 1, saved: true, answers: join10(root, answers), session: options.session, applied: false, next: "Review saved choices and run onboarding apply with this session and answers file." });
187765
+ complete({ schemaVersion: 1, saved: true, answers: join12(root, answers), session: options.session, applied: false, next: "Review saved choices and run onboarding apply with this session and answers file." });
186016
187766
  } catch (e) {
186017
187767
  busy = false;
186018
187768
  send(400, { error: e.message.slice(0, 300) });
@@ -186032,7 +187782,7 @@ async function serveOnboarding(options) {
186032
187782
  process.once("SIGINT", stop);
186033
187783
  process.once("SIGTERM", stop);
186034
187784
  try {
186035
- options.onReady?.({ url: `${origin}${prefix}/`, answers: join10(root, answers) });
187785
+ options.onReady?.({ url: `${origin}${prefix}/`, answers: join12(root, answers) });
186036
187786
  return await done;
186037
187787
  } finally {
186038
187788
  clearTimeout(timer);
@@ -186327,10 +188077,10 @@ async function loginWithDevice(options, overrides = {}) {
186327
188077
  }
186328
188078
 
186329
188079
  // packages/cli/src/index.ts
186330
- import { chmod as chmod2, lstat as lstat12, mkdir as mkdir13, open as open11 } from "node:fs/promises";
186331
- import { constants as constants10 } from "node:fs";
188080
+ import { chmod as chmod2, lstat as lstat12, mkdir as mkdir14, open as open12 } from "node:fs/promises";
188081
+ import { constants as constants11 } from "node:fs";
186332
188082
  import { homedir as homedir3 } from "node:os";
186333
- import { basename as basename4, dirname as dirname17, extname as extname7, join as join14, resolve as resolve12 } from "node:path";
188083
+ import { basename as basename4, dirname as dirname18, extname as extname7, join as join15, resolve as resolve12 } from "node:path";
186334
188084
 
186335
188085
  // packages/cli/src/direction-context.ts
186336
188086
  async function prepareDirectionContext(root, client, projectId) {
@@ -186354,10 +188104,10 @@ async function prepareDirectionContext(root, client, projectId) {
186354
188104
  }
186355
188105
 
186356
188106
  // packages/cli/src/style-authoring.ts
186357
- import { createHash as createHash6 } from "node:crypto";
186358
- import { constants as constants7 } from "node:fs";
186359
- import { lstat as lstat8, mkdir as mkdir7, open as open7, readdir as readdir5, rmdir, unlink as unlink6 } from "node:fs/promises";
186360
- import { dirname as dirname11 } from "node:path";
188107
+ import { createHash as createHash8 } from "node:crypto";
188108
+ import { constants as constants8 } from "node:fs";
188109
+ import { lstat as lstat9, mkdir as mkdir9, open as open9, readdir as readdir5, rmdir, unlink as unlink7 } from "node:fs/promises";
188110
+ import { dirname as dirname13 } from "node:path";
186361
188111
  function styleId(id2) {
186362
188112
  try {
186363
188113
  return assertIdentifier(id2);
@@ -186367,7 +188117,7 @@ function styleId(id2) {
186367
188117
  }
186368
188118
  async function exists(path) {
186369
188119
  try {
186370
- await lstat8(path);
188120
+ await lstat9(path);
186371
188121
  return true;
186372
188122
  } catch (error) {
186373
188123
  if (error.code === "ENOENT") return false;
@@ -186396,12 +188146,12 @@ async function makeDirectories(root, path, created) {
186396
188146
  const relative2 = segments.slice(0, i).join("/");
186397
188147
  const target = await checkedPath(root, relative2, false);
186398
188148
  try {
186399
- await mkdir7(target);
186400
- const info = await lstat8(target);
188149
+ await mkdir9(target);
188150
+ const info = await lstat9(target);
186401
188151
  created.push({ path: relative2, dev: info.dev, ino: info.ino });
186402
188152
  } catch (error) {
186403
188153
  if (error.code !== "EEXIST") throw error;
186404
- if (!(await lstat8(await checkedPath(root, relative2, false))).isDirectory()) throw new Error(`Not a directory: ${relative2}`);
188154
+ if (!(await lstat9(await checkedPath(root, relative2, false))).isDirectory()) throw new Error(`Not a directory: ${relative2}`);
186405
188155
  }
186406
188156
  }
186407
188157
  }
@@ -186409,10 +188159,10 @@ async function cleanCreated(root, paths2, directory) {
186409
188159
  for (const item of [...paths2].reverse()) {
186410
188160
  try {
186411
188161
  const target = await checkedPath(root, item.path, false);
186412
- const info = await lstat8(target);
188162
+ const info = await lstat9(target);
186413
188163
  if (info.dev !== item.dev || info.ino !== item.ino || info.isSymbolicLink()) continue;
186414
188164
  if (directory) await rmdir(target);
186415
- else await unlink6(target);
188165
+ else await unlink7(target);
186416
188166
  } catch {
186417
188167
  }
186418
188168
  }
@@ -186431,9 +188181,9 @@ async function createLocalStyle(options) {
186431
188181
  const createdDirectories = [];
186432
188182
  try {
186433
188183
  for (const [path, content] of Object.entries(files)) {
186434
- await makeDirectories(root, dirname11(path), createdDirectories);
188184
+ await makeDirectories(root, dirname13(path), createdDirectories);
186435
188185
  const target = await checkedPath(root, path);
186436
- const handle = await open7(target, constants7.O_WRONLY | constants7.O_CREAT | constants7.O_EXCL | constants7.O_NOFOLLOW, 420);
188186
+ const handle = await open9(target, constants8.O_WRONLY | constants8.O_CREAT | constants8.O_EXCL | constants8.O_NOFOLLOW, 420);
186437
188187
  try {
186438
188188
  const info = await handle.stat();
186439
188189
  createdFiles.push({ path, dev: info.dev, ino: info.ino });
@@ -186466,7 +188216,7 @@ async function readStyle(root, id2) {
186466
188216
  try {
186467
188217
  const target = await checkedPath(root, path, false);
186468
188218
  if (!await exists(target)) continue;
186469
- if (!(await lstat8(target)).isDirectory()) {
188219
+ if (!(await lstat9(target)).isDirectory()) {
186470
188220
  issues.push({ path, message: "Style path is not a directory." });
186471
188221
  continue;
186472
188222
  }
@@ -186495,15 +188245,15 @@ async function readStyle(root, id2) {
186495
188245
  async function checkLocalResource(root, path, expected) {
186496
188246
  safeStyleResourcePath(path);
186497
188247
  const target = await checkedPath(root, path, false);
186498
- const handle = await open7(target, constants7.O_RDONLY | constants7.O_NOFOLLOW | constants7.O_NONBLOCK);
188248
+ const handle = await open9(target, constants8.O_RDONLY | constants8.O_NOFOLLOW | constants8.O_NONBLOCK);
186499
188249
  try {
186500
188250
  const before = await handle.stat();
186501
188251
  if (!before.isFile()) throw new Error("Resource is not a regular file.");
186502
188252
  if (!expected) return {};
186503
- const hash6 = createHash6("sha256");
188253
+ const hash6 = createHash8("sha256");
186504
188254
  for await (const chunk of handle.createReadStream({ autoClose: false })) hash6.update(chunk);
186505
188255
  const after = await handle.stat();
186506
- const current2 = await lstat8(await checkedPath(root, path, false));
188256
+ const current2 = await lstat9(await checkedPath(root, path, false));
186507
188257
  if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || current2.dev !== before.dev || current2.ino !== before.ino) {
186508
188258
  throw new Error("Resource changed while its hash was being checked; check it again.");
186509
188259
  }
@@ -187046,9 +188796,9 @@ async function searchMediaSources(options, dependencies = {}) {
187046
188796
  }
187047
188797
 
187048
188798
  // packages/cli/src/media-inventory.ts
187049
- import { createHash as createHash7 } from "node:crypto";
187050
- import { link as link4, lstat as lstat9, mkdir as mkdir8, mkdtemp as mkdtemp3, opendir, readFile as readFile7, rm as rm3 } from "node:fs/promises";
187051
- import { basename as basename3, dirname as dirname12, extname as extname4, join as join11 } from "node:path";
188799
+ import { createHash as createHash9 } from "node:crypto";
188800
+ import { link as link5, lstat as lstat10, mkdir as mkdir10, mkdtemp as mkdtemp3, opendir, readFile as readFile7, rm as rm4 } from "node:fs/promises";
188801
+ import { basename as basename3, dirname as dirname14, extname as extname4, join as join13 } from "node:path";
187052
188802
  var GENERATED_DIRECTORIES = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "out", "output", "outputs", "renders", "render", "cache", "caches", "proxies", "proxy", "samples", "thumbnails", "coverage", "venv", "__pycache__"]);
187053
188803
  function mediaFailure(error) {
187054
188804
  if (error instanceof MediaToolError) return { code: error.code, message: error.message };
@@ -187074,7 +188824,7 @@ async function inventoryMedia(options) {
187074
188824
  }
187075
188825
  report.scannedEntries++;
187076
188826
  try {
187077
- const stat = await lstat9(path);
188827
+ const stat = await lstat10(path);
187078
188828
  if (stat.isSymbolicLink()) {
187079
188829
  if (explicit) throw new MediaToolError("MEDIA_SYMLINK", "Symlink inputs are not followed. Use the original local path.");
187080
188830
  skip(path, "symlink_not_followed");
@@ -187100,7 +188850,7 @@ async function inventoryMedia(options) {
187100
188850
  skip(path, "remaining_entries_not_scanned", true);
187101
188851
  break;
187102
188852
  }
187103
- await visit(join11(path, entry.name), depth + 1);
188853
+ await visit(join13(path, entry.name), depth + 1);
187104
188854
  }
187105
188855
  } else if (!stat.isFile()) {
187106
188856
  if (explicit) throw new MediaToolError("MEDIA_NOT_REGULAR", "The explicit media input must be a regular local file or directory.");
@@ -187135,35 +188885,35 @@ async function sampleMedia(options) {
187135
188885
  if (!source2.streams.some((stream) => stream.type === "video")) throw new MediaToolError("MEDIA_VIDEO_REQUIRED", "Frame sampling requires a video or image stream.");
187136
188886
  if (source2.durationSeconds !== null && options.times.some((time) => time >= source2.durationSeconds)) throw new MediaToolError("MEDIA_SAMPLE_OUT_OF_RANGE", "A requested sample is outside the known media duration.");
187137
188887
  const outputDirectory = resolveLocalMediaPath(options.outputDirectory);
187138
- await assertNoMediaSymlinks(dirname12(outputDirectory));
188888
+ await assertNoMediaSymlinks(dirname14(outputDirectory));
187139
188889
  try {
187140
- await mkdir8(outputDirectory);
188890
+ await mkdir10(outputDirectory);
187141
188891
  } catch (error) {
187142
188892
  if (error.code !== "EEXIST") throw error;
187143
188893
  }
187144
188894
  await assertNoMediaSymlinks(outputDirectory);
187145
- if (!(await lstat9(outputDirectory)).isDirectory()) throw new MediaToolError("MEDIA_OUTPUT_DIRECTORY_INVALID", "Frame output must be a local directory.");
187146
- const temp = await mkdtemp3(join11(outputDirectory, ".editorbrain-samples-"));
187147
- const tempStat = await lstat9(temp);
188895
+ if (!(await lstat10(outputDirectory)).isDirectory()) throw new MediaToolError("MEDIA_OUTPUT_DIRECTORY_INVALID", "Frame output must be a local directory.");
188896
+ const temp = await mkdtemp3(join13(outputDirectory, ".editorbrain-samples-"));
188897
+ const tempStat = await lstat10(temp);
187148
188898
  const frames = [];
187149
188899
  const created = [];
187150
188900
  try {
187151
188901
  for (let index = 0; index < options.times.length; index++) {
187152
188902
  const time = options.times[index];
187153
188903
  const filename = `${source2.sha256.slice(0, 12)}-${String(index + 1).padStart(2, "0")}-${Math.round(time * 1e3)}ms.jpg`;
187154
- const temporary = join11(temp, filename), output2 = join11(outputDirectory, filename);
188904
+ const temporary = join13(temp, filename), output2 = join13(outputDirectory, filename);
187155
188905
  await runMediaTool("ffmpeg", ["-v", "error", "-n", "-ss", String(time), ...localInputArgs(file), "-map", "0:v:0", "-frames:v", "1", "-an", "-sn", "-dn", "-vf", "scale=960:960:force_original_aspect_ratio=decrease", "-q:v", "3", "-update", "1", temporary], { timeoutMs: 6e4 });
187156
188906
  const bytes = await readFile7(temporary);
187157
188907
  if (!bytes.length) throw new MediaToolError("MEDIA_SAMPLE_EMPTY", "The requested frame did not produce a usable image.");
187158
188908
  try {
187159
- await link4(temporary, output2);
188909
+ await link5(temporary, output2);
187160
188910
  } catch (error) {
187161
188911
  if (error.code === "EEXIST") throw new MediaToolError("MEDIA_OUTPUT_EXISTS", "A sample output already exists. Choose a new output directory; existing files are never overwritten.");
187162
188912
  throw error;
187163
188913
  }
187164
- const outputStat = await lstat9(output2);
188914
+ const outputStat = await lstat10(output2);
187165
188915
  created.push({ path: output2, ino: outputStat.ino, dev: outputStat.dev, size: outputStat.size, mtimeMs: outputStat.mtimeMs, ctimeMs: outputStat.ctimeMs });
187166
- frames.push({ path: output2, sha256: createHash7("sha256").update(bytes).digest("hex"), bytes: bytes.length, requestedTimeSeconds: time, actualPresentationTimeSeconds: null });
188916
+ frames.push({ path: output2, sha256: createHash9("sha256").update(bytes).digest("hex"), bytes: bytes.length, requestedTimeSeconds: time, actualPresentationTimeSeconds: null });
187167
188917
  }
187168
188918
  const after = await probeLocalMedia(file);
187169
188919
  if (source2.sha256 !== after.sha256) throw new MediaToolError("MEDIA_FILE_CHANGED", "The source changed while frames were being sampled. Retry with a stable source.");
@@ -187172,8 +188922,8 @@ async function sampleMedia(options) {
187172
188922
  for (const file2 of created) {
187173
188923
  try {
187174
188924
  await assertNoMediaSymlinks(file2.path);
187175
- const current2 = await lstat9(file2.path);
187176
- if (current2.ino === file2.ino && current2.dev === file2.dev && current2.size === file2.size && current2.mtimeMs === file2.mtimeMs && current2.ctimeMs === file2.ctimeMs) await rm3(file2.path, { force: true });
188925
+ const current2 = await lstat10(file2.path);
188926
+ if (current2.ino === file2.ino && current2.dev === file2.dev && current2.size === file2.size && current2.mtimeMs === file2.mtimeMs && current2.ctimeMs === file2.ctimeMs) await rm4(file2.path, { force: true });
187177
188927
  } catch {
187178
188928
  }
187179
188929
  }
@@ -187181,8 +188931,8 @@ async function sampleMedia(options) {
187181
188931
  } finally {
187182
188932
  try {
187183
188933
  await assertNoMediaSymlinks(temp);
187184
- const current2 = await lstat9(temp);
187185
- if (current2.ino === tempStat.ino && current2.dev === tempStat.dev) await rm3(temp, { recursive: true, force: true });
188934
+ const current2 = await lstat10(temp);
188935
+ if (current2.ino === tempStat.ino && current2.dev === tempStat.dev) await rm4(temp, { recursive: true, force: true });
187186
188936
  } catch {
187187
188937
  }
187188
188938
  }
@@ -187453,10 +189203,10 @@ async function checkRender(options) {
187453
189203
  }
187454
189204
 
187455
189205
  // packages/cli/src/motion-components.ts
187456
- import { createHash as createHash8 } from "node:crypto";
187457
- import { constants as constants8 } from "node:fs";
187458
- import { lstat as lstat10, mkdir as mkdir9, open as open8, rmdir as rmdir2, unlink as unlink7 } from "node:fs/promises";
187459
- import { dirname as dirname13, extname as extname5, resolve as resolve9 } from "node:path";
189206
+ import { createHash as createHash10 } from "node:crypto";
189207
+ import { constants as constants9 } from "node:fs";
189208
+ import { lstat as lstat11, mkdir as mkdir11, open as open10, rmdir as rmdir2, unlink as unlink8 } from "node:fs/promises";
189209
+ import { dirname as dirname15, extname as extname5, resolve as resolve9 } from "node:path";
187460
189210
 
187461
189211
  // packages/core/src/motion-editorial.ts
187462
189212
  function createEditorialRenderer(config2, g) {
@@ -189290,7 +191040,7 @@ function inputPath(base, value) {
189290
191040
  }
189291
191041
  async function sourceFile(path, role, max) {
189292
191042
  await assertNoMediaSymlinks(path);
189293
- const handle = await open8(path, constants8.O_RDONLY | constants8.O_NOFOLLOW | constants8.O_NONBLOCK);
191043
+ const handle = await open10(path, constants9.O_RDONLY | constants9.O_NOFOLLOW | constants9.O_NONBLOCK);
189294
191044
  try {
189295
191045
  const before = await handle.stat();
189296
191046
  if (!before.isFile() || before.size === 0 || before.size > max) throw fail2(`${role} must be a nonempty regular file of at most ${max} bytes.`);
@@ -189303,9 +191053,9 @@ async function sourceFile(path, role, max) {
189303
191053
  }
189304
191054
  const after = await handle.stat();
189305
191055
  await assertNoMediaSymlinks(path);
189306
- const current2 = await lstat10(path);
191056
+ const current2 = await lstat11(path);
189307
191057
  if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || current2.dev !== before.dev || current2.ino !== before.ino || current2.size !== after.size || current2.mtimeMs !== after.mtimeMs) throw fail2(`${role} changed during reading.`);
189308
- return { source: { role, path, bytes: content.length, sha256: createHash8("sha256").update(content).digest("hex") }, content };
191058
+ return { source: { role, path, bytes: content.length, sha256: createHash10("sha256").update(content).digest("hex") }, content };
189309
191059
  } finally {
189310
191060
  await handle.close();
189311
191061
  }
@@ -189318,7 +191068,7 @@ function embed(content, path, kind) {
189318
191068
  }
189319
191069
  async function exists2(path) {
189320
191070
  try {
189321
- await lstat10(path);
191071
+ await lstat11(path);
189322
191072
  return true;
189323
191073
  } catch (error) {
189324
191074
  if (error.code === "ENOENT") return false;
@@ -189331,22 +191081,22 @@ async function makeParents(root, path, created) {
189331
191081
  const relative2 = parts.slice(0, index).join("/");
189332
191082
  const target = await checkedPath(root, relative2, false);
189333
191083
  try {
189334
- await mkdir9(target, { mode: 448 });
189335
- const info = await lstat10(target);
191084
+ await mkdir11(target, { mode: 448 });
191085
+ const info = await lstat11(target);
189336
191086
  created.push({ path: relative2, dev: info.dev, ino: info.ino, directory: true });
189337
191087
  } catch (error) {
189338
191088
  if (error.code !== "EEXIST") throw error;
189339
- if (!(await lstat10(await checkedPath(root, relative2, false))).isDirectory()) throw fail2("Output parent must be a directory.");
191089
+ if (!(await lstat11(await checkedPath(root, relative2, false))).isDirectory()) throw fail2("Output parent must be a directory.");
189340
191090
  }
189341
191091
  }
189342
191092
  }
189343
191093
  async function cleanCreated2(root, created) {
189344
191094
  for (const item of [...created].reverse()) {
189345
191095
  try {
189346
- const path = await checkedPath(root, item.path, false), info = await lstat10(path);
191096
+ const path = await checkedPath(root, item.path, false), info = await lstat11(path);
189347
191097
  if (info.dev !== item.dev || info.ino !== item.ino || info.isSymbolicLink()) continue;
189348
191098
  if (item.directory) await rmdir2(path);
189349
- else await unlink7(path);
191099
+ else await unlink8(path);
189350
191100
  } catch {
189351
191101
  }
189352
191102
  }
@@ -189371,14 +191121,14 @@ async function prepareMotionComponent(options) {
189371
191121
  if (typeof value !== "string" || !value.trim()) throw fail2(`Required binding ${role} references missing or non-string token ${key}. No demo default was applied.`);
189372
191122
  return [role, value];
189373
191123
  }));
189374
- const fontPath = inputPath(dirname13(input.source.path), document2.fontFile);
191124
+ const fontPath = inputPath(dirname15(input.source.path), document2.fontFile);
189375
191125
  const font = await sourceFile(fontPath, "font", MOTION_INPUT_LIMITS.fontBytes);
189376
191126
  const sources = [input.source, font.source];
189377
191127
  const items = [];
189378
191128
  for (const [index, item] of document2.items.entries()) {
189379
191129
  let image2;
189380
191130
  if (item.imageFile) {
189381
- const path = inputPath(dirname13(input.source.path), item.imageFile);
191131
+ const path = inputPath(dirname15(input.source.path), item.imageFile);
189382
191132
  const file = await sourceFile(path, `items[${index}].image`, MOTION_INPUT_LIMITS.imageBytes);
189383
191133
  image2 = embed(file.content, path, "image");
189384
191134
  sources.push(file.source);
@@ -189419,7 +191169,7 @@ async function prepareMotionComponent(options) {
189419
191169
  resolvedBindings: Object.fromEntries(Object.entries(document2.bindings).map(([role, key]) => [role, { key, value: bound[role], source: resolved.tokenSources[key] }])),
189420
191170
  sources,
189421
191171
  context: { sourceHashes: resolved.lock.sourceHashes, output: resolved.output, mediaPreferences: resolved.mediaPreferences },
189422
- files: { "config.json": { sha256: createHash8("sha256").update(configJson).digest("hex") }, "index.html": { sha256: createHash8("sha256").update(html).digest("hex") } },
191172
+ files: { "config.json": { sha256: createHash10("sha256").update(configJson).digest("hex") }, "index.html": { sha256: createHash10("sha256").update(html).digest("hex") } },
189423
191173
  warnings: resolved.warnings
189424
191174
  };
189425
191175
  const readme = `# EditorBrain motion component
@@ -189439,13 +191189,13 @@ Preparation is not a rendered video or a quality certification. Inspect text fit
189439
191189
  if (await exists2(await productionOutputPath(root, options.outDirectory))) throw new CliError("MOTION_OUTPUT_EXISTS", "The output directory already exists; nothing was overwritten.", "Choose a new directory under .editorbrain-local/.");
189440
191190
  const created = [];
189441
191191
  try {
189442
- await makeParents(root, dirname13(options.outDirectory), created);
189443
- await mkdir9(await productionOutputPath(root, options.outDirectory), { mode: 448 });
189444
- const info = await lstat10(output2);
191192
+ await makeParents(root, dirname15(options.outDirectory), created);
191193
+ await mkdir11(await productionOutputPath(root, options.outDirectory), { mode: 448 });
191194
+ const info = await lstat11(output2);
189445
191195
  created.push({ path: options.outDirectory, dev: info.dev, ino: info.ino, directory: true });
189446
191196
  for (const [name, content] of Object.entries(files)) {
189447
191197
  const path = `${options.outDirectory}/${name}`;
189448
- const handle = await open8(await productionOutputPath(root, path), constants8.O_WRONLY | constants8.O_CREAT | constants8.O_EXCL | constants8.O_NOFOLLOW, 384);
191198
+ const handle = await open10(await productionOutputPath(root, path), constants9.O_WRONLY | constants9.O_CREAT | constants9.O_EXCL | constants9.O_NOFOLLOW, 384);
189449
191199
  try {
189450
191200
  const stat = await handle.stat();
189451
191201
  created.push({ path, dev: stat.dev, ino: stat.ino, directory: false });
@@ -189476,71 +191226,10 @@ Preparation is not a rendered video or a quality certification. Inspect text fit
189476
191226
  }, { migrateLegacy: false });
189477
191227
  }
189478
191228
 
189479
- // packages/cli/src/authored-motion.ts
189480
- import { lstat as lstat11, mkdir as mkdir10, open as open9, link as link5, unlink as unlink8 } from "node:fs/promises";
189481
- import { dirname as dirname14, join as join12 } from "node:path";
189482
- import { createHash as createHash9, randomUUID as randomUUID5 } from "node:crypto";
189483
- async function downloadAuthoredSource(client, pin, root, out, fetcher = fetch) {
189484
- if (!/^[a-z0-9][a-z0-9-]{0,79}$/.test(pin.id) || !/^\d+\.\d+\.\d+$/.test(pin.version) || !/^[a-f0-9]{64}$/.test(pin.sha256) || !Number.isSafeInteger(pin.bytes) || pin.bytes < 1 || pin.bytes > (pin.version === "1.4.0" ? 96 : 16) * 1024 * 1024) throw new CliError("INVALID_ARGUMENT", "Invalid pinned scene bundle.", "Retrieve one authored scene from the catalog.");
189485
- const target = await checkedPath(root, out, false);
189486
- try {
189487
- await lstat11(target);
189488
- throw new CliError("FILE_EXISTS", "The output already exists.", "Choose a new archive path.");
189489
- } catch (error) {
189490
- if (error.code !== "ENOENT") throw error;
189491
- }
189492
- const metadata = await client.request(`/v1/authored-motion/${pin.id}/source?${new URLSearchParams({ version: pin.version, sha256: pin.sha256 })}`);
189493
- const url2 = new URL(metadata.url);
189494
- const expectedPath = `/v1/authored-motion-download/${pin.id}/${pin.version}/${pin.sha256}`;
189495
- const origin = new URL(client.url).origin;
189496
- const trustedOrigin = url2.origin === origin || origin === "https://editorharness-api.innovandohorizontes.workers.dev" && url2.origin === "https://api.editorbrain.com";
189497
- if (metadata.sha256 !== pin.sha256 || metadata.bytes !== pin.bytes || !trustedOrigin || url2.pathname !== expectedPath || url2.username || url2.password || url2.hash) throw new CliError("INVALID_RESPONSE", "Scene bundle metadata differs from the selected version.", "Do not use this source. Retrieve the pinned catalog entry again.");
189498
- const response = await fetcher(url2, { redirect: "error", signal: AbortSignal.timeout(18e4) });
189499
- if (response.status === 403) {
189500
- await response.body?.cancel();
189501
- throw new CliError("RESOURCE_ACCESS_CHANGED", "Source access was denied at download time.", "Check current workspace permissions and membership at https://editorbrain.com/app/billing. Do not retry old versions or buy credits to unlock premium resources; existing archives were preserved.");
189502
- }
189503
- if (!response.ok) throw new CliError("DOWNLOAD_FAILED", `Scene download failed (HTTP ${response.status}).`, "Request a new source link; existing archives were preserved.");
189504
- const reader = response.body?.getReader();
189505
- if (!reader) throw new CliError("INVALID_RESPONSE", "Scene download body is missing.", "Retry the pinned source.");
189506
- const temporary = join12(dirname14(target), `.eb-motion-${randomUUID5()}.tmp`);
189507
- let handle;
189508
- const hash6 = createHash9("sha256");
189509
- let size = 0;
189510
- try {
189511
- await mkdir10(dirname14(target), { recursive: true });
189512
- await checkedPath(root, out, false);
189513
- handle = await open9(temporary, "wx", 384);
189514
- for (; ; ) {
189515
- const { done, value } = await reader.read();
189516
- if (done) break;
189517
- size += value.length;
189518
- if (size > pin.bytes) throw new CliError("HASH_MISMATCH", "Scene archive exceeds the pinned length.", "Discard the unverified download.");
189519
- hash6.update(value);
189520
- await handle.writeFile(value);
189521
- }
189522
- if (size !== pin.bytes || hash6.digest("hex") !== pin.sha256) throw new CliError("HASH_MISMATCH", "Scene archive verification failed.", "Do not extract this download.");
189523
- await handle.sync();
189524
- await handle.close();
189525
- await checkedPath(root, out, false);
189526
- await link5(temporary, target);
189527
- } catch (error) {
189528
- await reader.cancel().catch(() => {
189529
- });
189530
- throw error;
189531
- } finally {
189532
- await handle?.close().catch(() => {
189533
- });
189534
- await unlink8(temporary).catch(() => {
189535
- });
189536
- }
189537
- return { id: pin.id, version: pin.version, path: target, sha256: pin.sha256, bytes: size, extracted: false, executed: false, rendered: false, next: "Inspect bundle README and selected card; extract into a new local directory. Bind current project colors, fonts, language, content, timing and sound before rendering. The demo is not your finished edit." };
189538
- }
189539
-
189540
191229
  // packages/cli/src/production-verify.ts
189541
- import { createHash as createHash10, randomUUID as randomUUID6 } from "node:crypto";
189542
- import { mkdir as mkdir11, readFile as readFile8 } from "node:fs/promises";
189543
- import { dirname as dirname15, join as join13, resolve as resolve10 } from "node:path";
191230
+ import { createHash as createHash11, randomUUID as randomUUID6 } from "node:crypto";
191231
+ import { mkdir as mkdir12, readFile as readFile8 } from "node:fs/promises";
191232
+ import { dirname as dirname16, join as join14, resolve as resolve10 } from "node:path";
189544
191233
 
189545
191234
  // packages/cli/src/production-media-review.ts
189546
191235
  function productionMediaReview(resolved) {
@@ -189597,7 +191286,7 @@ function productionEditorialReview(resolved) {
189597
191286
  }
189598
191287
 
189599
191288
  // packages/cli/src/production-verify.ts
189600
- var digest2 = (value) => createHash10("sha256").update(value).digest("hex");
191289
+ var digest2 = (value) => createHash11("sha256").update(value).digest("hex");
189601
191290
  var errorCode2 = (error) => error && typeof error === "object" && "code" in error && typeof error.code === "string" && /^[A-Z0-9_]+$/.test(error.code) ? error.code : "PRODUCTION_VERIFY_FAILED";
189602
191291
  function productionVerificationRequirements(options) {
189603
191292
  const { resolved } = options;
@@ -189631,7 +191320,7 @@ async function sampleFinalArtifact(file, probe2, directory, requested) {
189631
191320
  result2.failures.push({ requestedTimeSeconds: time, code: "MEDIA_SAMPLE_OUT_OF_RANGE" });
189632
191321
  continue;
189633
191322
  }
189634
- const path = join13(directory, `sample-${String(result2.items.length + result2.failures.length + 1).padStart(2, "0")}.png`);
191323
+ const path = join14(directory, `sample-${String(result2.items.length + result2.failures.length + 1).padStart(2, "0")}.png`);
189635
191324
  try {
189636
191325
  const output2 = await runMediaTool("ffmpeg", [
189637
191326
  "-loglevel",
@@ -189717,10 +191406,10 @@ async function verifyProduction(options) {
189717
191406
  if (options.sampleTimesSeconds !== void 0 && (!Array.isArray(options.sampleTimesSeconds) || options.sampleTimesSeconds.length < 1 || options.sampleTimesSeconds.length > 6 || Array.from(options.sampleTimesSeconds).some((time) => typeof time !== "number" || !Number.isFinite(time) || time < 0 || time > 86400))) throw new CliError("INVALID_SAMPLE_TIMES", "Provide one to six finite sample times between 0 and 86400 seconds.", "Select a few timestamps that answer a review question.");
189718
191407
  const relativeDirectory = options.outDirectory ?? `.editorbrain-local/${options.resolved.project.id}/verify-${randomUUID6()}`;
189719
191408
  const directory = await productionOutputPath(root, relativeDirectory);
189720
- await mkdir11(dirname15(directory), { recursive: true, mode: 448 });
191409
+ await mkdir12(dirname16(directory), { recursive: true, mode: 448 });
189721
191410
  await productionOutputPath(root, relativeDirectory);
189722
191411
  try {
189723
- await mkdir11(directory, { mode: 448 });
191412
+ await mkdir12(directory, { mode: 448 });
189724
191413
  } catch (error) {
189725
191414
  if (error.code === "EEXIST") throw new CliError("PRODUCTION_OUTPUT_EXISTS", "Verification output already exists; nothing was overwritten.", "Choose a new directory under .editorbrain-local/.");
189726
191415
  throw error;
@@ -189809,13 +191498,13 @@ async function verifyProduction(options) {
189809
191498
  }
189810
191499
 
189811
191500
  // packages/cli/src/review-artifact.ts
189812
- import { open as open10, mkdir as mkdir12 } from "node:fs/promises";
189813
- import { constants as constants9 } from "node:fs";
189814
- import { dirname as dirname16, extname as extname6, resolve as resolve11 } from "node:path";
189815
- import { createHash as createHash12 } from "node:crypto";
191501
+ import { open as open11, mkdir as mkdir13 } from "node:fs/promises";
191502
+ import { constants as constants10 } from "node:fs";
191503
+ import { dirname as dirname17, extname as extname6, resolve as resolve11 } from "node:path";
191504
+ import { createHash as createHash13 } from "node:crypto";
189816
191505
 
189817
191506
  // packages/cli/src/review-artifact-html.ts
189818
- import { createHash as createHash11 } from "node:crypto";
191507
+ import { createHash as createHash12 } from "node:crypto";
189819
191508
  function reviewApp() {
189820
191509
  const data = JSON.parse(document.getElementById("review-data").textContent);
189821
191510
  const $ = (id2) => document.getElementById(id2);
@@ -190152,7 +191841,7 @@ ${JSON.stringify({ ...feedback(), kind: "editorbrain.review-access-request", dec
190152
191841
  update();
190153
191842
  }
190154
191843
  function renderReviewArtifact(data, wordmark) {
190155
- const script = `(${reviewApp.toString()})();`, hash6 = createHash11("sha256").update(script).digest("base64");
191844
+ const script = `(${reviewApp.toString()})();`, hash6 = createHash12("sha256").update(script).digest("base64");
190156
191845
  const json = JSON.stringify(data).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
190157
191846
  return `<!doctype html><html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-${hash6}'; style-src 'unsafe-inline'; img-src data:; media-src data: blob:; connect-src 'none'; font-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'"><title>EditorBrain \xB7 Tu edici\xF3n</title><style>
190158
191847
  *{box-sizing:border-box} [hidden]{display:none!important} :root{color-scheme:dark;font-family:Inter,ui-sans-serif,system-ui,-apple-system,sans-serif;color:#f6f6f6;background:#090909}body{margin:0;background:radial-gradient(ellipse at 15% 0%,#252525 0,transparent 50%),#090909}main{max-width:1220px;margin:auto;padding:28px clamp(18px,4vw,50px) 44px}header{display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #ffffff20;padding-bottom:22px;gap:20px}header svg{width:146px;height:auto;display:block}header span{color:#aaa;font-size:12px}h1{font-size:clamp(28px,4vw,48px);font-weight:550;letter-spacing:-.045em;margin:14px 0}h2{font-size:20px;letter-spacing:-.025em;margin:0 0 12px}.eyebrow{font-size:10px;letter-spacing:.18em;color:#aaa;margin:30px 0 0}.intro{color:#aaa;font-size:15px;line-height:1.6;margin-bottom:24px}button,a{touch-action:manipulation}button{border:1px solid #ffffff30;border-radius:12px;background:#ffffff08;color:#fff;padding:11px 15px;font:inherit;font-size:13px;cursor:pointer}button:hover{background:#ffffff16}button:disabled{opacity:.38;cursor:default}.primary{background:#f5f5f5;color:#111;font-weight:650;border-color:#fff}.primary:hover{background:#ddd}.secondary{background:transparent}button:focus-visible,textarea:focus-visible,summary:focus-visible,a:focus-visible{outline:2px solid #fff;outline-offset:4px}p{line-height:1.6}.workspace{display:grid;grid-template-columns:minmax(0,1.25fr) minmax(280px,1fr);gap:30px;align-items:start}.preview{position:sticky;top:20px;min-width:0}.screen{border:1px solid #ffffff22;border-radius:20px;overflow:hidden;background:radial-gradient(ellipse,#242424,#050505);display:flex;justify-content:center;min-height:260px}.screen video{width:100%;max-height:590px;display:block}.controls{display:flex;justify-content:center;align-items:center;gap:16px;margin:12px 0;font-size:12px;color:#aaa;font-variant-numeric:tabular-nums}.controls button{padding:8px 12px}aside{background:linear-gradient(140deg,#ffffff07,#ffffff02);border:1px solid #ffffff19;border-radius:20px;padding:24px}aside>p{color:#aaa;font-size:13px}label{display:block;font-size:12px;color:#bbb}select{max-width:100%;padding:10px;background:#181818;color:#fff;border:1px solid #ffffff40;border-radius:8px}#learning-options article{padding:16px 0;border-top:1px solid #ffffff20}textarea{width:100%;background:#090909;border:1px solid #ffffff30;border-radius:12px;padding:14px;color:#fff;font:inherit;font-size:14px;line-height:1.5;min-height:108px;resize:vertical;margin:12px 0}textarea::placeholder{color:#818181}.target{display:flex;align-items:center;gap:10px;margin:16px 0 0;font-size:12px;color:#bbb;flex-wrap:wrap}.target button{padding:6px 10px}.save{width:100%;margin-bottom:16px}.muted{color:#aaa;font-size:12px}details{border-top:1px solid #ffffff20;padding-top:16px;margin-top:16px}summary{cursor:pointer;font-size:13px;line-height:1.6}#phrases{max-height:300px;overflow-y:auto;margin:12px 0}#phrases article{padding:12px;margin-bottom:8px;border-radius:10px;background:#ffffff04;border-left:2px solid transparent}#phrases .speaking{background:#ffffff12;border-left-color:#fff}#phrases article>button:first-child{border:0;background:none;text-align:left;padding:0;line-height:1.7;width:100%;margin-bottom:8px}#phrases article>button:last-child{font-size:11px;padding:6px 8px}#phrases .removed{opacity:.7}#show-cuts-label{margin:12px 0}#approve{width:100%;margin-top:18px}#pending{padding:12px 16px;border-left:2px solid #eee;background:#ffffff08;font-size:13px;margin-bottom:20px}#notes{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,240px),1fr));gap:12px}#notes article{border:1px solid #ffffff22;border-radius:12px;padding:15px;font-size:13px;overflow-wrap:anywhere}#notes p{margin-bottom:0}.note-head{display:flex;align-items:center;justify-content:space-between;gap:10px}.note-head button{font-size:11px;padding:5px 8px}#markers{display:flex;gap:8px;flex-wrap:wrap}#markers button{font-size:11px;padding:7px 10px}.handoff{margin-top:24px;padding:22px;border:1px solid #ffffff30;border-radius:18px;background:#ffffff05}.handoff-head{display:flex;align-items:center;justify-content:space-between;gap:20px}.handoff p{color:#aaa;font-size:13px;margin:6px 0}.handoff .actions{display:flex;gap:8px;flex-shrink:0;flex-wrap:wrap}#status{color:#fff;margin:14px 0;font-size:13px}#request{font-family:ui-monospace,monospace;font-size:12px;min-height:200px}footer{margin-top:22px;display:flex;justify-content:space-between;gap:16px;color:#888;font-size:11px}#direction-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,250px),1fr));gap:18px}.direction{padding:16px;border:1px solid #ffffff22;border-radius:18px;background:#ffffff05}.direction.chosen{border-color:#fff;box-shadow:0 0 0 1px #fff}.direction img,.direction video{width:100%;height:220px;object-fit:contain;border-radius:10px;background:#030303;margin-bottom:18px}.direction p{color:#bbb;font-size:14px}.direction button{width:100%}.direction details a{display:block;color:#fff;font-size:12px;margin:8px 0}.no-preview{height:160px;display:grid;place-items:center;background:#222;color:#aaa;margin-bottom:16px;border-radius:10px}#future{background:none;border:0;color:#aaa;padding:0;font-size:12px;text-align:left}#future-details{color:#aaa;font-size:13px}#future-details summary{color:#eee}.future-note{max-width:660px}#undo{margin-top:12px}input[type=checkbox]{accent-color:#fff}#intro{max-width:680px}
@@ -190247,7 +191936,7 @@ async function embed2(root, input, kind) {
190247
191936
  const path = resolve11(root, input.file), extension = extname6(path).toLowerCase();
190248
191937
  const mime = { ".mp4": "video/mp4", ".webm": "video/webm", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp" };
190249
191938
  if (!mime[extension] || kind === "video" && !mime[extension].startsWith("video/")) invalid4("Use MP4/WebM video or PNG/JPEG/WebP proposal previews.");
190250
- const handle = await open10(path, constants9.O_RDONLY | constants9.O_NOFOLLOW | constants9.O_NONBLOCK);
191939
+ const handle = await open11(path, constants10.O_RDONLY | constants10.O_NOFOLLOW | constants10.O_NONBLOCK);
190251
191940
  try {
190252
191941
  const stat = await handle.stat();
190253
191942
  if (!stat.isFile() || stat.size > 24 * 1024 * 1024 || !stat.size) invalid4("Each review preview must be a regular local file under 24 MiB. Make a lightweight review copy; keep your master.");
@@ -190255,7 +191944,7 @@ async function embed2(root, input, kind) {
190255
191944
  if (bytes.length > 24 * 1024 * 1024) invalid4("Preview grew while reading; retry with a stable file.");
190256
191945
  const after = await handle.stat();
190257
191946
  if (after.size !== stat.size || after.mtimeMs !== stat.mtimeMs) invalid4("Preview changed while reading.");
190258
- const sha2562 = createHash12("sha256").update(bytes).digest("hex");
191947
+ const sha2562 = createHash13("sha256").update(bytes).digest("hex");
190259
191948
  if (input.sha256 && input.sha256 !== sha2562) invalid4("Preview hash does not match this version.");
190260
191949
  return { uri: `data:${mime[extension]};base64,${bytes.toString("base64")}`, sha256: sha2562, mimeType: mime[extension] };
190261
191950
  } finally {
@@ -190270,9 +191959,9 @@ async function createReviewArtifact(root, value, out) {
190270
191959
  const directions = input.directions ? await Promise.all(input.directions.map(async ({ preview, ...d }) => ({ ...d, ...preview ? { preview: await embed2(root, preview, "preview") } : {} }))) : void 0;
190271
191960
  const clean = { schemaVersion: 1, projectId: input.projectId, title: input.title, version: input.version, stage: input.stage, ...input.contextVersion ? { contextVersion: input.contextVersion } : {}, ...video ? { video } : {}, ...directions ? { directions } : {}, ...input.transcript ? { transcript: input.transcript } : {}, ...input.learnings ? { learnings: input.learnings } : {}, ...input.learningContext ? { learningContext: input.learningContext } : {} };
190272
191961
  if (JSON.stringify(clean).length > 40 * 1024 * 1024) invalid4("Embedded previews exceed 40 MiB. Use smaller review copies.");
190273
- const artifactId = createHash12("sha256").update(JSON.stringify(clean)).digest("hex");
191962
+ const artifactId = createHash13("sha256").update(JSON.stringify(clean)).digest("hex");
190274
191963
  const html = renderReviewArtifact({ ...clean, artifactId }, onboardingWordmark);
190275
- await mkdir12(dirname16(target), { recursive: true });
191964
+ await mkdir13(dirname17(target), { recursive: true });
190276
191965
  await atomicWrite(root, out, html, { document: false, overwrite: false, mode: 384 });
190277
191966
  return { kind: "editorbrain.review-artifact", path: target, artifactId, projectId: input.projectId, stage: input.stage, videoSha256: video?.sha256 ?? null, mediaEmbedded: true, mediaUploaded: false, agentTriggered: false, reviewSurface: "computer", cloudStorageBytes: 0, next: "Default: review on the computer. Open/display this HTML with the host artifact tool. If inline HTML/video is unsupported, offer the downloadable HTML opened in a browser. The user copies the prepared request or attaches downloaded feedback JSON to this chat. Phone review is opt-in: the collapsed action prepares a request, not an upload or approval. Never claim a click started the agent." };
190278
191967
  }
@@ -190475,6 +192164,8 @@ editorbrain library media <video-id> --sha256 media-hash --out file
190475
192164
  editorbrain narrative search [query] [--kind hook|cta|...] [--channel visual|spoken|...] [--limit 10]
190476
192165
  editorbrain narrative get <video-id> [--sha256 document-hash] [--event-offset 0] [--relation-offset 0] [--limit 50]
190477
192166
  editorbrain styles list
192167
+ editorbrain styles source <id> --style-version <v> --out <archive> [--dir folder]
192168
+ editorbrain styles prepare <id> --style-version <v> --file <archive> --out <new-directory> [--dir folder]
190478
192169
  editorbrain styles create <style-id> [--name name] [--dir folder]
190479
192170
  editorbrain styles check <style-id> [--dir folder]
190480
192171
  editorbrain media styles [--category image|motion]
@@ -190599,16 +192290,16 @@ function output(value) {
190599
192290
  process.stdout.write(stableJson(value));
190600
192291
  }
190601
192292
  async function configRoot(create = false) {
190602
- let path = process.env.EDITORBRAIN_CONFIG_DIR ?? process.env.EDITORHARNESS_CONFIG_DIR ?? join14(homedir3(), ".config", "editorbrain");
192293
+ let path = process.env.EDITORBRAIN_CONFIG_DIR ?? process.env.EDITORHARNESS_CONFIG_DIR ?? join15(homedir3(), ".config", "editorbrain");
190603
192294
  if (!create && !process.env.EDITORBRAIN_CONFIG_DIR && !process.env.EDITORHARNESS_CONFIG_DIR) {
190604
192295
  try {
190605
192296
  await lstat12(path);
190606
192297
  } catch (error) {
190607
192298
  if (error.code !== "ENOENT") throw error;
190608
- path = join14(homedir3(), ".config", "editorharness");
192299
+ path = join15(homedir3(), ".config", "editorharness");
190609
192300
  }
190610
192301
  }
190611
- if (create) await mkdir13(path, { recursive: true, mode: 448 });
192302
+ if (create) await mkdir14(path, { recursive: true, mode: 448 });
190612
192303
  return ensureRoot(path);
190613
192304
  }
190614
192305
  async function loadConfig() {
@@ -190625,7 +192316,7 @@ async function loadConfig() {
190625
192316
  async function saveConfig(config2) {
190626
192317
  const root = await configRoot(true);
190627
192318
  await atomicWrite(root, "config.json", stableJson(config2), { document: false, mode: 384 });
190628
- await chmod2(join14(root, "config.json"), 384);
192319
+ await chmod2(join15(root, "config.json"), 384);
190629
192320
  }
190630
192321
  async function config(args, requireKey = true) {
190631
192322
  const stored = await loadConfig();
@@ -190672,7 +192363,7 @@ async function init(args) {
190672
192363
  }
190673
192364
  }
190674
192365
  for (const [path, content] of Object.entries(files)) await atomicWrite(root, path, content, { overwrite: false });
190675
- for (const path of directories) await mkdir13(await checkedPath(root, path, false), { recursive: true });
192366
+ for (const path of directories) await mkdir14(await checkedPath(root, path, false), { recursive: true });
190676
192367
  const guidance2 = await installGuidance();
190677
192368
  try {
190678
192369
  await rememberGuidance(guidance2);
@@ -190990,7 +192681,7 @@ async function main() {
190990
192681
  if (hookEnd !== void 0 && (!hookEnd.trim() || !Number.isFinite(Number(hookEnd)) || Number(hookEnd) < 0)) throw new Error("--hook-end must be nonnegative final seconds.");
190991
192682
  const credentials = projectId && !args.flags.offline ? await config(args, false) : void 0;
190992
192683
  const context = projectId ? await prepareProductionContext(root2, projectId, credentials?.apiKey ? new Client(credentials) : void 0) : void 0;
190993
- output(await mixEvents({ root: root2, voice: resolve12(root2, voice), manifest: await readProductionJson(root2, cues), manifestDirectory: dirname17(resolve12(root2, cues)), out, context, hookEndSeconds: hookEnd === void 0 ? void 0 : Number(hookEnd) }));
192684
+ output(await mixEvents({ root: root2, voice: resolve12(root2, voice), manifest: await readProductionJson(root2, cues), manifestDirectory: dirname18(resolve12(root2, cues)), out, context, hookEndSeconds: hookEnd === void 0 ? void 0 : Number(hookEnd) }));
190994
192685
  return;
190995
192686
  }
190996
192687
  if (command === "production" && ["review-sheet", "matte", "matte-plan", "matte-engines", "matte-check"].includes(subcommand)) {
@@ -191161,6 +192852,14 @@ async function main() {
191161
192852
  output({ endpoint: client.url, ...await client.me() });
191162
192853
  return;
191163
192854
  }
192855
+ if (command === "styles" && ["source", "prepare"].includes(subcommand)) {
192856
+ const allowed = /* @__PURE__ */ new Set(["style-version", "out", "dir", ...subcommand === "prepare" ? ["file"] : ["url"]]);
192857
+ const version = str(args, "style-version"), out = str(args, "out"), file = str(args, "file");
192858
+ if (args.positional.length !== 3 || !version || !out || subcommand === "prepare" && !file || Object.keys(args.flags).some((f) => !allowed.has(f))) throw new CliError("INVALID_ARGUMENT", "Use styles source/prepare <id> --style-version <v> --out <new-path>; prepare also requires --file <archive>.", "Run editorbrain help.");
192859
+ const root2 = await ensureRoot(str(args, "dir") ?? process.cwd());
192860
+ output(subcommand === "source" ? await downloadStyle(new Client(await config(args)), argument, version, root2, out) : await prepareStyleSource(root2, argument, version, file, out));
192861
+ return;
192862
+ }
191164
192863
  if (command === "styles" && (subcommand === "create" || subcommand === "check")) {
191165
192864
  const allowed = new Set(subcommand === "create" ? ["dir", "name"] : ["dir"]);
191166
192865
  if (args.positional.length !== 3 || Object.keys(args.flags).some((flag2) => !allowed.has(flag2))) {
@@ -191229,7 +192928,7 @@ async function main() {
191229
192928
  if (!/^[a-zA-Z0-9_-]{1,100}$/.test(result2.id) || typeof result2.apiKey !== "string") throw new Error("Invalid key response");
191230
192929
  const file = `keys/${result2.id}.json`;
191231
192930
  await atomicWrite(root2, file, stableJson({ url: client.url, apiKey: result2.apiKey, id: result2.id, label, role }), { document: false, mode: 384, overwrite: false });
191232
- output({ id: result2.id, label, role, credentialFile: join14(root2, file) });
192931
+ output({ id: result2.id, label, role, credentialFile: join15(root2, file) });
191233
192932
  return;
191234
192933
  }
191235
192934
  if (subcommand === "revoke" && argument) {
@@ -191360,7 +193059,7 @@ async function main() {
191360
193059
  }
191361
193060
  if (subcommand === "upload" && argument) {
191362
193061
  const target = resolve12(str(args, "dir") ?? process.cwd(), argument);
191363
- const handle = await open11(target, constants10.O_RDONLY | constants10.O_NOFOLLOW);
193062
+ const handle = await open12(target, constants11.O_RDONLY | constants11.O_NOFOLLOW);
191364
193063
  let bytes;
191365
193064
  try {
191366
193065
  const info = await handle.stat();
@@ -191387,7 +193086,7 @@ async function main() {
191387
193086
  if (subcommand === "download" && argument && str(args, "out")) {
191388
193087
  if (!/^[a-f0-9]{64}$/.test(argument)) throw new Error("Asset ID must be its SHA-256");
191389
193088
  const destination = resolve12(str(args, "dir") ?? process.cwd(), str(args, "out"));
191390
- const root2 = await ensureRoot(dirname17(destination), true);
193089
+ const root2 = await ensureRoot(dirname18(destination), true);
191391
193090
  await checkedPath(root2, basename4(destination), false);
191392
193091
  const response = await client.media(`/v1/assets/${argument}`);
191393
193092
  const bytes = new Uint8Array(await response.arrayBuffer());
@@ -191448,7 +193147,7 @@ async function main() {
191448
193147
  if (command === "search" && subcommand === "brief") {
191449
193148
  const path = str(args, "file");
191450
193149
  if (!path) throw new Error("Provide --file with the editorial brief JSON after inspecting the actual material.");
191451
- const handle = await open11(resolve12(path), constants10.O_RDONLY | constants10.O_NOFOLLOW);
193150
+ const handle = await open12(resolve12(path), constants11.O_RDONLY | constants11.O_NOFOLLOW);
191452
193151
  let brief;
191453
193152
  try {
191454
193153
  const stat = await handle.stat();
@@ -191470,7 +193169,7 @@ async function main() {
191470
193169
  const scriptPath = str(args, "script"), videoPath = str(args, "video");
191471
193170
  let script, assetId = str(args, "asset");
191472
193171
  const readInput = async (path, max) => {
191473
- const handle = await open11(resolve12(path), constants10.O_RDONLY | constants10.O_NOFOLLOW);
193172
+ const handle = await open12(resolve12(path), constants11.O_RDONLY | constants11.O_NOFOLLOW);
191474
193173
  try {
191475
193174
  const stat = await handle.stat();
191476
193175
  if (!stat.isFile() || stat.size < 1 || stat.size > max) throw new Error(`Input must be a regular file of at most ${max} bytes.`);
@@ -191514,7 +193213,7 @@ async function main() {
191514
193213
  const params = new URLSearchParams({ query: args.positional.slice(2).join(" ") });
191515
193214
  const limit = str(args, "limit"), after = str(args, "after");
191516
193215
  if (limit !== void 0) {
191517
- if (!/^\d+$/.test(limit) || Number(limit) < 1 || Number(limit) > 20) throw new Error("--limit must be 1 through 20");
193216
+ if (!/^\d+$/.test(limit) || Number(limit) < 1 || Number(limit) > 20) throw new Error("--limit must be 1 through 20. Use --limit 20, then --after <nextCursor> from the previous page with the same query.");
191518
193217
  params.set("limit", limit);
191519
193218
  }
191520
193219
  if (after !== void 0) {
@@ -191537,7 +193236,7 @@ async function main() {
191537
193236
  const hash6 = str(args, "sha256");
191538
193237
  if (!hash6 || !/^[a-f0-9]{64}$/.test(hash6)) throw new Error("--sha256 must be a media SHA-256 from library get.");
191539
193238
  const destination = resolve12(str(args, "dir") ?? process.cwd(), str(args, "out"));
191540
- const root2 = await ensureRoot(dirname17(destination), true);
193239
+ const root2 = await ensureRoot(dirname18(destination), true);
191541
193240
  await checkedPath(root2, basename4(destination), false);
191542
193241
  const response = await client.media(`/v1/library/${encodeURIComponent(argument)}/media/${hash6}`);
191543
193242
  const reader = response.body?.getReader();