editorbrain 0.39.1 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,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,7 @@ 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
+ 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" }] } },
249
146
  studio_insufficient_credits: { status: 402, help: {
250
147
  message: "No alcanzan tus cr\xE9ditos creativos de EditorBrain para este encargo.",
251
148
  nextStep: "Consulta Plan y cr\xE9ditos para ver tu saldo y las opciones de recarga disponibles. Tambi\xE9n puedes elegir una integraci\xF3n propia compatible o aportar un recurso ya creado. Comprueba el acceso y presupuesto de esa alternativa antes de usarla; no recargues ni cambies de proveedor autom\xE1ticamente.",
@@ -321,21 +218,6 @@ function validateToolPreferences(input) {
321
218
  return structuredClone(value);
322
219
  }
323
220
 
324
- // packages/core/src/creator-context.ts
325
- var creatorContextOptions = {
326
- teamSize: [["solo", "Solo yo"], ["small", "2 a 5 personas"], ["mid", "6 a 20 personas"], ["large", "M\xE1s de 20 personas"]],
327
- approver: [["me", "Yo decido"], ["lead", "Mi l\xEDder o responsable"], ["brand", "Marca o legal"]],
328
- brandManual: [["yes", "Tenemos manual de marca"], ["no", "Todav\xEDa no tenemos manual"]],
329
- clientCount: [["few", "1 a 3 clientes"], ["some", "4 a 10 clientes"], ["many", "M\xE1s de 10 clientes"]],
330
- clientReview: [["direct", "El cliente revisa"], ["us", "Revisamos nosotros"], ["mixed", "Depende del cliente"]],
331
- settingUp: [["client", "Una marca de cliente"], ["agency", "Mi agencia"]]
332
- };
333
- function creatorContextIssues(value) {
334
- if (value === void 0) return [];
335
- if (!value || typeof value !== "object" || Array.isArray(value)) return ["creatorContext debe ser un objeto."];
336
- return Object.entries(value).flatMap(([key, choice]) => Object.hasOwn(creatorContextOptions, key) && creatorContextOptions[key].some((o) => o[0] === choice) ? [] : [`Contexto de trabajo inv\xE1lido: ${key}.`]);
337
- }
338
-
339
221
  // packages/core/src/question-policy.ts
340
222
  var questionModeOptions = [
341
223
  { id: "essential", title: "Solo lo esencial", description: "Pregunta solo si falta algo que cambia el resultado. Los detalles los decide tu agente." },
@@ -375,6 +257,143 @@ function planEditQuestions(policy, value) {
375
257
  return { mode: policy.mode, assessment: "host-declared-not-media-verified", decisions, questions: decisions.filter((d) => d.action === "ask"), blocked: decisions.filter((d) => d.action === "blocked"), notice: "Resolved means already answered, never proof of approval. This plan does not authorize execution or change saved preferences. Reassess after answers; do not automatically ask every deferred question." };
376
258
  }
377
259
 
260
+ // packages/core/src/integrations.ts
261
+ var integrationCatalog = [
262
+ { id: "higgsfield", name: "Higgsfield", description: "Im\xE1genes y clips generados para apoyar tu edici\xF3n.", capabilities: ["image", "video"], accessMethods: ["agent", "api", "browser", "files"], docsUrl: "https://open.higgsfield.ai/quick-start" },
263
+ { id: "kie-ai", name: "Kie AI", description: "Im\xE1genes, video, voz y m\xFAsica con tu propia cuenta de Kie AI.", capabilities: ["image", "video", "voiceover", "music"], accessMethods: ["api", "agent", "files"], docsUrl: "https://docs.kie.ai/" },
264
+ { id: "elevenlabs", name: "ElevenLabs", description: "Voces, efectos de sonido y m\xFAsica generada.", capabilities: ["voiceover", "sfx", "music"], accessMethods: ["agent", "api", "browser", "files"], docsUrl: "https://elevenlabs.io/docs/overview" },
265
+ { id: "suno", name: "Suno", description: "M\xFAsica generada con Suno; el acceso API depende de tu cuenta.", capabilities: ["music"], accessMethods: ["browser", "api", "files"], docsUrl: "https://platform.suno.com/" },
266
+ { id: "openai-images", name: "OpenAI Images", description: "Creaci\xF3n y edici\xF3n de im\xE1genes para tu contenido.", capabilities: ["image"], accessMethods: ["agent", "api", "browser", "files"], docsUrl: "https://platform.openai.com/docs/guides/image-generation" },
267
+ { id: "pexels", name: "Pexels", description: "Fotos y videos de stock; revisa la licencia y el contexto de uso.", capabilities: ["stock-image", "stock-video"], accessMethods: ["agent", "api", "browser", "files"], docsUrl: "https://www.pexels.com/api/documentation/" },
268
+ { id: "assemblyai", name: "AssemblyAI", description: "Transcripci\xF3n con marcas de tiempo para planificar cortes y subt\xEDtulos.", capabilities: ["transcription"], accessMethods: ["agent", "api", "files"], docsUrl: "https://www.assemblyai.com/docs" }
269
+ ];
270
+ function object2(value) {
271
+ return value !== null && typeof value === "object" && !Array.isArray(value);
272
+ }
273
+ function knownFields(value, allowed) {
274
+ if (Object.keys(value).some((key) => !allowed.includes(key))) throw new Error("Unknown integration field. Credentials and user/workspace IDs are not accepted.");
275
+ }
276
+ function containsCredential(value) {
277
+ return /-----BEGIN [A-Z ]*PRIVATE KEY-----|\bBearer\s+\S{12,}|\b(?:sk-(?:proj-)?|AIza|cfat_|apikey_|tlk_)[A-Za-z0-9_-]{15,}|\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+|(?:api[_ -]?key|access[_ -]?token|secret|password)\s*[:=]\s*["']?\S{8,}/i.test(value);
278
+ }
279
+ function validateIntegrationUpdate(providerId, input) {
280
+ const provider = integrationCatalog.find((entry) => entry.id === providerId);
281
+ if (!provider) throw new Error("Unknown integration provider.");
282
+ if (!object2(input)) throw new Error("Integration settings must be an object.");
283
+ knownFields(input, ["enabled", "accessMethod", "preferences", "expectedRevision"]);
284
+ if (typeof input.enabled !== "boolean") throw new Error("enabled must be a boolean.");
285
+ if (!provider.accessMethods.includes(input.accessMethod)) throw new Error("Unsupported access method for this provider.");
286
+ if (!Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 0) throw new Error("The current expectedRevision is required.");
287
+ if (!object2(input.preferences)) throw new Error("preferences must be an object.");
288
+ knownFields(input.preferences, ["instructions", "model", "voiceId", "language", "musicMode", "spending"]);
289
+ const preferences = {};
290
+ for (const [field, max] of [["instructions", 1e3], ["model", 120], ["voiceId", 120], ["language", 60]]) {
291
+ const value = input.preferences[field];
292
+ if (value === void 0) continue;
293
+ if (typeof value !== "string" || value.length > max || /[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(value)) throw new Error(`${field} must be text of at most ${max} characters.`);
294
+ if (containsCredential(value)) throw new Error("Credentials must stay in your provider connection, never in integration preferences.");
295
+ if (value.trim()) preferences[field] = value.trim();
296
+ }
297
+ const musicMode = input.preferences.musicMode, spending = input.preferences.spending;
298
+ if (musicMode !== void 0) {
299
+ if (!provider.capabilities.includes("music") || !["instrumental", "vocals", "either"].includes(musicMode)) throw new Error("musicMode is only available for music integrations.");
300
+ preferences.musicMode = musicMode;
301
+ }
302
+ if (preferences.voiceId && !provider.capabilities.includes("voiceover")) throw new Error("voiceId is only available for voice integrations.");
303
+ if (spending !== void 0 && !["ask", "use-approved-budget"].includes(spending)) throw new Error("Invalid spending preference.");
304
+ preferences.spending = spending ?? "ask";
305
+ return { enabled: input.enabled, accessMethod: input.accessMethod, preferences, expectedRevision: input.expectedRevision };
306
+ }
307
+ var integrationExecutionPolicy = {
308
+ version: 1,
309
+ selection: "explicit-task-choice-then-compatible-saved-access-then-propose",
310
+ externalCredits: "host-or-provider-account; never require EditorBrain creative credits",
311
+ builtInCredits: "EditorBrain Studio catalog and quote; personal provider access does not unlock Studio",
312
+ verification: "current-session-tool, authentication, supported-model, cost-and-existing-task-budget",
313
+ fallback: "no automatic paid provider or access-method switch",
314
+ uncertainSubmission: "recover existing provider job before resubmitting or switching",
315
+ unknownBalance: "unknown is not zero; do not claim insufficient credits without evidence"
316
+ };
317
+ function integrationRoutes(entries, catalog = integrationCatalog) {
318
+ return entries.filter((entry) => entry.enabled).map((entry) => {
319
+ const provider = catalog.find((item) => item.id === entry.providerId);
320
+ return {
321
+ routeId: `integration:${entry.providerId}:${entry.accessMethod}`,
322
+ providerId: entry.providerId,
323
+ accessMethod: entry.accessMethod,
324
+ capabilities: provider?.capabilities ?? [],
325
+ execution: entry.accessMethod === "files" ? "existing-files" : "verify-in-current-session",
326
+ billingScope: entry.accessMethod === "files" ? "no-generation" : "host-or-provider",
327
+ requiresEditorBrainCreativeCredits: false
328
+ };
329
+ });
330
+ }
331
+
332
+ // packages/core/src/onboarding-account.ts
333
+ var onboardingReviewOptions = [
334
+ { id: "directions", title: "Primero, propuestas", description: "Tu agente te muestra distintas direcciones y ejemplos. T\xFA eliges antes de editar." },
335
+ { id: "sample", title: "Primero, una muestra", description: "Revisas un frame con tu material o un fragmento corto antes del video completo." },
336
+ { id: "direct", title: "Editar directamente", description: "Tu agente usa tu marca y tus preferencias para editar y revisar el video completo." }
337
+ ];
338
+ function validateOnboardingAccount(value) {
339
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((k) => !["reviewMode", "integrations"].includes(k))) throw new Error("accountSetup contiene campos desconocidos. No admite credenciales.");
340
+ const input = value;
341
+ if (input.reviewMode !== void 0 && !onboardingReviewOptions.some((v) => v.id === input.reviewMode)) throw new Error("Modo de revisi\xF3n inv\xE1lido.");
342
+ if (input.integrations !== void 0) {
343
+ if (!Array.isArray(input.integrations) || input.integrations.length > 20 || new Set(input.integrations.map((v) => v?.providerId)).size !== input.integrations.length) throw new Error("Integraciones inv\xE1lidas o duplicadas.");
344
+ for (const entry of input.integrations) {
345
+ if (!entry || typeof entry !== "object" || Array.isArray(entry) || Object.keys(entry).some((k) => !["providerId", "enabled", "accessMethod", "preferences"].includes(k))) throw new Error("Integraci\xF3n inv\xE1lida.");
346
+ const { providerId, ...settings } = entry;
347
+ validateIntegrationUpdate(providerId, { ...settings, expectedRevision: 0 });
348
+ }
349
+ }
350
+ return JSON.parse(JSON.stringify(input));
351
+ }
352
+ function onboardingAccountActions(value) {
353
+ const input = value === void 0 ? {} : validateOnboardingAccount(value);
354
+ return {
355
+ status: input.reviewMode !== void 0 || input.integrations?.length ? "pending" : "not-requested",
356
+ requested: input,
357
+ scope: { reviewMode: "workspace", integrations: "authenticated-member-or-connection" },
358
+ instructions: "These are requested account changes, not saved preferences. Authenticate the intended workspace/member. Read workflow get/get_workflow_preferences and integrations list/get_integrations. Compare current values with these choices. Apply only requested differences using workflow set/set_workflow_preferences or integrations set/set_integration with the current expectedRevision; preserve unmentioned providers and merge unmentioned preference fields from the current entry. Stop on a conflict or uncertain write, reread before resuming. Verify persisted values with fresh reads and check_workflow. Never claim account setup complete after document sync alone. Enabling an integration declares access; verify the actual host tool before use and never infer spending authorization.",
359
+ links: { review: "https://editorbrain.com/app/preferences", integrations: "https://editorbrain.com/app/integrations" }
360
+ };
361
+ }
362
+
363
+ // packages/core/src/editing-interaction.ts
364
+ function editingInteraction(questionMode, reviewMode) {
365
+ if (questionMode !== void 0 && !questionModeOptions.some((option) => option.id === questionMode)) throw new Error("Invalid question mode.");
366
+ if (reviewMode !== void 0 && !onboardingReviewOptions.some((option) => option.id === reviewMode)) throw new Error("Invalid review mode.");
367
+ const resolved = questionMode !== void 0 && reviewMode !== void 0;
368
+ return {
369
+ status: resolved ? "resolved" : "needs-project-context",
370
+ questionMode: questionMode ?? null,
371
+ reviewMode: reviewMode ?? null,
372
+ questions: !resolved ? "resolve-context-first" : questionMode === "autonomous" ? "none" : questionMode === "essential" ? "consequential-gaps-only" : "short-recommended-choices",
373
+ firstVisual: !resolved ? null : reviewMode === "direct" ? "review" : reviewMode,
374
+ visualScope: "Only when this decision is still open; reuse valid scoped choices and approvals instead of repeating them.",
375
+ reviewNotice: resolved && questionMode === "autonomous" && reviewMode !== "direct" ? "Sin preguntas no elimina la revisi\xF3n que elegiste. Preparar\xE9 tus propuestas o muestra y dejar\xE9 la aprobaci\xF3n pendiente. Para futuras ediciones sin pausas creativas puedes elegir Editar directamente; no cambiar\xE9 ese ajuste por mi cuenta." : null,
376
+ routing: "Use the current request and inspected material to enter at the next unresolved decision. Chat, footage, an idea and a copied web selection converge on the same project context. Reuse answered questions, pinned selections and valid scoped approvals. An animation selection is not a complete editorial direction or approval of a sample.",
377
+ presentation: "Briefly state the next useful action, not the internal checklist. Show visual directions only while direction is open and review mode calls for them; skip redundant choices. Direct mode delivers a review artifact without a new mid-edit gate. A scoped revision preserves unaffected work. Local HTML actions prepare copy-to-chat feedback; never claim they sent work automatically.",
378
+ authority: "routing-not-approval"
379
+ };
380
+ }
381
+
382
+ // packages/core/src/creator-context.ts
383
+ var creatorContextOptions = {
384
+ teamSize: [["solo", "Solo yo"], ["small", "2 a 5 personas"], ["mid", "6 a 20 personas"], ["large", "M\xE1s de 20 personas"]],
385
+ approver: [["me", "Yo decido"], ["lead", "Mi l\xEDder o responsable"], ["brand", "Marca o legal"]],
386
+ brandManual: [["yes", "Tenemos manual de marca"], ["no", "Todav\xEDa no tenemos manual"]],
387
+ clientCount: [["few", "1 a 3 clientes"], ["some", "4 a 10 clientes"], ["many", "M\xE1s de 10 clientes"]],
388
+ clientReview: [["direct", "El cliente revisa"], ["us", "Revisamos nosotros"], ["mixed", "Depende del cliente"]],
389
+ settingUp: [["client", "Una marca de cliente"], ["agency", "Mi agencia"]]
390
+ };
391
+ function creatorContextIssues(value) {
392
+ if (value === void 0) return [];
393
+ if (!value || typeof value !== "object" || Array.isArray(value)) return ["creatorContext debe ser un objeto."];
394
+ return Object.entries(value).flatMap(([key, choice]) => Object.hasOwn(creatorContextOptions, key) && creatorContextOptions[key].some((o) => o[0] === choice) ? [] : [`Contexto de trabajo inv\xE1lido: ${key}.`]);
395
+ }
396
+
378
397
  // packages/core/src/creative-direction.ts
379
398
  var creativePreferenceSections = [
380
399
  { id: "brand", title: "Marca y tipograf\xEDa", question: "\xBFConservamos tus colores, fuentes e idioma, o quieres ajustarlos?" },
@@ -1241,109 +1260,6 @@ function validateOnboardingTastePatch(value) {
1241
1260
  return JSON.parse(JSON.stringify(value));
1242
1261
  }
1243
1262
 
1244
- // packages/core/src/integrations.ts
1245
- var integrationCatalog = [
1246
- { id: "higgsfield", name: "Higgsfield", description: "Im\xE1genes y clips generados para apoyar tu edici\xF3n.", capabilities: ["image", "video"], accessMethods: ["agent", "api", "browser", "files"], docsUrl: "https://open.higgsfield.ai/quick-start" },
1247
- { id: "kie-ai", name: "Kie AI", description: "Im\xE1genes, video, voz y m\xFAsica con tu propia cuenta de Kie AI.", capabilities: ["image", "video", "voiceover", "music"], accessMethods: ["api", "agent", "files"], docsUrl: "https://docs.kie.ai/" },
1248
- { id: "elevenlabs", name: "ElevenLabs", description: "Voces, efectos de sonido y m\xFAsica generada.", capabilities: ["voiceover", "sfx", "music"], accessMethods: ["agent", "api", "browser", "files"], docsUrl: "https://elevenlabs.io/docs/overview" },
1249
- { id: "suno", name: "Suno", description: "M\xFAsica generada con Suno; el acceso API depende de tu cuenta.", capabilities: ["music"], accessMethods: ["browser", "api", "files"], docsUrl: "https://platform.suno.com/" },
1250
- { id: "openai-images", name: "OpenAI Images", description: "Creaci\xF3n y edici\xF3n de im\xE1genes para tu contenido.", capabilities: ["image"], accessMethods: ["agent", "api", "browser", "files"], docsUrl: "https://platform.openai.com/docs/guides/image-generation" },
1251
- { id: "pexels", name: "Pexels", description: "Fotos y videos de stock; revisa la licencia y el contexto de uso.", capabilities: ["stock-image", "stock-video"], accessMethods: ["agent", "api", "browser", "files"], docsUrl: "https://www.pexels.com/api/documentation/" },
1252
- { id: "assemblyai", name: "AssemblyAI", description: "Transcripci\xF3n con marcas de tiempo para planificar cortes y subt\xEDtulos.", capabilities: ["transcription"], accessMethods: ["agent", "api", "files"], docsUrl: "https://www.assemblyai.com/docs" }
1253
- ];
1254
- function object2(value) {
1255
- return value !== null && typeof value === "object" && !Array.isArray(value);
1256
- }
1257
- function knownFields(value, allowed) {
1258
- if (Object.keys(value).some((key) => !allowed.includes(key))) throw new Error("Unknown integration field. Credentials and user/workspace IDs are not accepted.");
1259
- }
1260
- function containsCredential(value) {
1261
- return /-----BEGIN [A-Z ]*PRIVATE KEY-----|\bBearer\s+\S{12,}|\b(?:sk-(?:proj-)?|AIza|cfat_|apikey_|tlk_)[A-Za-z0-9_-]{15,}|\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+|(?:api[_ -]?key|access[_ -]?token|secret|password)\s*[:=]\s*["']?\S{8,}/i.test(value);
1262
- }
1263
- function validateIntegrationUpdate(providerId, input) {
1264
- const provider = integrationCatalog.find((entry) => entry.id === providerId);
1265
- if (!provider) throw new Error("Unknown integration provider.");
1266
- if (!object2(input)) throw new Error("Integration settings must be an object.");
1267
- knownFields(input, ["enabled", "accessMethod", "preferences", "expectedRevision"]);
1268
- if (typeof input.enabled !== "boolean") throw new Error("enabled must be a boolean.");
1269
- if (!provider.accessMethods.includes(input.accessMethod)) throw new Error("Unsupported access method for this provider.");
1270
- if (!Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 0) throw new Error("The current expectedRevision is required.");
1271
- if (!object2(input.preferences)) throw new Error("preferences must be an object.");
1272
- knownFields(input.preferences, ["instructions", "model", "voiceId", "language", "musicMode", "spending"]);
1273
- const preferences = {};
1274
- for (const [field, max] of [["instructions", 1e3], ["model", 120], ["voiceId", 120], ["language", 60]]) {
1275
- const value = input.preferences[field];
1276
- if (value === void 0) continue;
1277
- if (typeof value !== "string" || value.length > max || /[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(value)) throw new Error(`${field} must be text of at most ${max} characters.`);
1278
- if (containsCredential(value)) throw new Error("Credentials must stay in your provider connection, never in integration preferences.");
1279
- if (value.trim()) preferences[field] = value.trim();
1280
- }
1281
- const musicMode = input.preferences.musicMode, spending = input.preferences.spending;
1282
- if (musicMode !== void 0) {
1283
- if (!provider.capabilities.includes("music") || !["instrumental", "vocals", "either"].includes(musicMode)) throw new Error("musicMode is only available for music integrations.");
1284
- preferences.musicMode = musicMode;
1285
- }
1286
- if (preferences.voiceId && !provider.capabilities.includes("voiceover")) throw new Error("voiceId is only available for voice integrations.");
1287
- if (spending !== void 0 && !["ask", "use-approved-budget"].includes(spending)) throw new Error("Invalid spending preference.");
1288
- preferences.spending = spending ?? "ask";
1289
- return { enabled: input.enabled, accessMethod: input.accessMethod, preferences, expectedRevision: input.expectedRevision };
1290
- }
1291
- var integrationExecutionPolicy = {
1292
- version: 1,
1293
- selection: "explicit-task-choice-then-compatible-saved-access-then-propose",
1294
- externalCredits: "host-or-provider-account; never require EditorBrain creative credits",
1295
- builtInCredits: "EditorBrain Studio catalog and quote; personal provider access does not unlock Studio",
1296
- verification: "current-session-tool, authentication, supported-model, cost-and-existing-task-budget",
1297
- fallback: "no automatic paid provider or access-method switch",
1298
- uncertainSubmission: "recover existing provider job before resubmitting or switching",
1299
- unknownBalance: "unknown is not zero; do not claim insufficient credits without evidence"
1300
- };
1301
- function integrationRoutes(entries, catalog = integrationCatalog) {
1302
- return entries.filter((entry) => entry.enabled).map((entry) => {
1303
- const provider = catalog.find((item) => item.id === entry.providerId);
1304
- return {
1305
- routeId: `integration:${entry.providerId}:${entry.accessMethod}`,
1306
- providerId: entry.providerId,
1307
- accessMethod: entry.accessMethod,
1308
- capabilities: provider?.capabilities ?? [],
1309
- execution: entry.accessMethod === "files" ? "existing-files" : "verify-in-current-session",
1310
- billingScope: entry.accessMethod === "files" ? "no-generation" : "host-or-provider",
1311
- requiresEditorBrainCreativeCredits: false
1312
- };
1313
- });
1314
- }
1315
-
1316
- // packages/core/src/onboarding-account.ts
1317
- var onboardingReviewOptions = [
1318
- { id: "directions", title: "Primero, propuestas", description: "Tu agente te muestra distintas direcciones y ejemplos. T\xFA eliges antes de editar." },
1319
- { id: "sample", title: "Primero, una muestra", description: "Revisas un frame con tu material o un fragmento corto antes del video completo." },
1320
- { id: "direct", title: "Editar directamente", description: "Tu agente usa tu marca y tus preferencias para editar y revisar el video completo." }
1321
- ];
1322
- function validateOnboardingAccount(value) {
1323
- if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((k) => !["reviewMode", "integrations"].includes(k))) throw new Error("accountSetup contiene campos desconocidos. No admite credenciales.");
1324
- const input = value;
1325
- if (input.reviewMode !== void 0 && !onboardingReviewOptions.some((v) => v.id === input.reviewMode)) throw new Error("Modo de revisi\xF3n inv\xE1lido.");
1326
- if (input.integrations !== void 0) {
1327
- if (!Array.isArray(input.integrations) || input.integrations.length > 20 || new Set(input.integrations.map((v) => v?.providerId)).size !== input.integrations.length) throw new Error("Integraciones inv\xE1lidas o duplicadas.");
1328
- for (const entry of input.integrations) {
1329
- if (!entry || typeof entry !== "object" || Array.isArray(entry) || Object.keys(entry).some((k) => !["providerId", "enabled", "accessMethod", "preferences"].includes(k))) throw new Error("Integraci\xF3n inv\xE1lida.");
1330
- const { providerId, ...settings } = entry;
1331
- validateIntegrationUpdate(providerId, { ...settings, expectedRevision: 0 });
1332
- }
1333
- }
1334
- return JSON.parse(JSON.stringify(input));
1335
- }
1336
- function onboardingAccountActions(value) {
1337
- const input = value === void 0 ? {} : validateOnboardingAccount(value);
1338
- return {
1339
- status: input.reviewMode !== void 0 || input.integrations?.length ? "pending" : "not-requested",
1340
- requested: input,
1341
- scope: { reviewMode: "workspace", integrations: "authenticated-member-or-connection" },
1342
- instructions: "These are requested account changes, not saved preferences. Authenticate the intended workspace/member. Read workflow get/get_workflow_preferences and integrations list/get_integrations. Compare current values with these choices. Apply only requested differences using workflow set/set_workflow_preferences or integrations set/set_integration with the current expectedRevision; preserve unmentioned providers and merge unmentioned preference fields from the current entry. Stop on a conflict or uncertain write, reread before resuming. Verify persisted values with fresh reads and check_workflow. Never claim account setup complete after document sync alone. Enabling an integration declares access; verify the actual host tool before use and never infer spending authorization.",
1343
- links: { review: "https://editorbrain.com/app/preferences", integrations: "https://editorbrain.com/app/integrations" }
1344
- };
1345
- }
1346
-
1347
1263
  // packages/core/src/audio-production.ts
1348
1264
  var audioProductionOptions = {
1349
1265
  musicIntensity: ["none", "subtle", "present"],
@@ -1516,6 +1432,7 @@ function getOnboardingGuide(intake) {
1516
1432
  visualCatalog: "Use list_media_styles/get_media_style for the same image and animation choices as web. Product demos orient taste; inspect the edited-video library before editing.",
1517
1433
  advanced: "Existing references, pronunciation/glossary, assets and detailed audio/tool settings are preserved. They are not required onboarding questions. Configure with their dedicated editors/tools when requested."
1518
1434
  },
1435
+ interactionPreview: { ...editingInteraction(intake?.profile?.questionMode ?? void 0, intake?.accountSetup?.reviewMode), basis: "draft-not-saved" },
1519
1436
  consultation: { options: questionModeOptions, field: "profile.questionMode", ...resolveQuestionPolicy(intake?.profile?.questionMode ?? void 0) },
1520
1437
  ...intake ? { current: intake, configuration: creativeConfiguration(intake.profile?.creativeDirection ?? void 0, intake.profile?.creativePreferencesReviewed ?? void 0) } : {},
1521
1438
  creativePreferences: { modes: creativeDirectionOptions, sections: creativePreferenceSections, confirmationField: "profile.creativePreferencesReviewed", rule: "Marca una categor\xEDa solo despu\xE9s de que el usuario confirme sus elecciones o decida delegarlas. Los campos precargados y saltar pasos no son confirmaci\xF3n. Al cambiar a guided, completa las categor\xEDas pendientes antes de editar salvo questionMode=autonomous: delega los detalles abiertos por proyecto sin marcar categor\xEDas revisadas; conserva las ya revisadas y todos los valores previos." },
@@ -181449,13 +181366,6 @@ function getAuthoredMotionCard(id2, version) {
181449
181366
  return structuredClone(result2);
181450
181367
  }
181451
181368
 
181452
- // packages/core/src/commercial.ts
181453
- var TOP_UPS = [
181454
- { id: "credits_500", cents: 1e3, credits: 500 },
181455
- { id: "credits_1000", cents: 2e3, credits: 1e3 }
181456
- ];
181457
- var TOP_UP = TOP_UPS[1];
181458
-
181459
181369
  // packages/core/src/production-visual.ts
181460
181370
  var SOCIAL_SAFE_PROFILES = {
181461
181371
  tiktok: { bottom: 0.25, right: 0.15, top: 0.08, left: 0.05 },
@@ -181561,6 +181471,339 @@ function getPersonalResourceGuide() {
181561
181471
  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 };
181562
181472
  }
181563
181473
 
181474
+ // packages/core/src/style-source-data-v1.ts
181475
+ var styleSourceData = [
181476
+ {
181477
+ "id": "comando-y-resultado",
181478
+ "name": "Comando y resultado",
181479
+ "summary": "Cada instrucci\xF3n aparece como tarjeta y se convierte en su resultado frente a quien habla.",
181480
+ "needs": [
181481
+ "tu clip hablando a c\xE1mara",
181482
+ "las im\xE1genes de cada resultado"
181483
+ ],
181484
+ "sourceVersion": "1.0.0",
181485
+ "sourceSha256": "5851f934ff5450056ea3032999cb5c244dbd1fd1ec90e2d33cf0ae804ac58c88",
181486
+ "sourceBytes": 53379860,
181487
+ "fileCount": 74,
181488
+ "unpackedBytes": 58695062,
181489
+ "requiredPlan": "creator",
181490
+ "ratio": "tall",
181491
+ "demoSha256": "85e71c00e290105304d21bacb17108892a82483f78eb4d3d601fb6008dc15571"
181492
+ },
181493
+ {
181494
+ "id": "narrador-sobre-collage",
181495
+ "name": "Narrador sobre collage de im\xE1genes",
181496
+ "summary": "Una imagen nueva a sangre por cada idea, con quien narra recortado y cambiando de lugar.",
181497
+ "needs": [
181498
+ "tu clip hablando a c\xE1mara (mejor con fondo liso)",
181499
+ "15\u201320 im\xE1genes"
181500
+ ],
181501
+ "sourceVersion": "1.0.0",
181502
+ "sourceSha256": "a1df048358ba37a23fd723fb0178c381da399ed40ddc0a81bc0109292aa5d083",
181503
+ "sourceBytes": 67824224,
181504
+ "fileCount": 87,
181505
+ "unpackedBytes": 73121837,
181506
+ "requiredPlan": "creator",
181507
+ "ratio": "tall",
181508
+ "demoSha256": "8634d6e1cc0274dcd8660f8f17b9fc4a249fd8aea077ef99826c4ed06dda1eb7"
181509
+ },
181510
+ {
181511
+ "id": "presentador-con-interfaz",
181512
+ "name": "Presentador con escenario de interfaz",
181513
+ "summary": "Arriba, interfaces animadas que ejecutan cada funci\xF3n; abajo, quien presenta.",
181514
+ "needs": [
181515
+ "tu clip hablando a c\xE1mara",
181516
+ "las funciones de tu producto (la interfaz se dibuja)"
181517
+ ],
181518
+ "sourceVersion": "1.0.0",
181519
+ "sourceSha256": "aa7d0a61aa3794139ac16a929bf0929b92b1c24f7e54cdcde155fbc2905de476",
181520
+ "sourceBytes": 36093673,
181521
+ "fileCount": 67,
181522
+ "unpackedBytes": 41512815,
181523
+ "requiredPlan": "creator",
181524
+ "ratio": "tall",
181525
+ "demoSha256": "b7785f6a59683068041d2256851ca52e19454d34bf73fee137e83f1fc8091c87"
181526
+ },
181527
+ {
181528
+ "id": "ensayo-cinematografico",
181529
+ "name": "Ensayo cinematogr\xE1fico con tarjetas tipogr\xE1ficas",
181530
+ "summary": "Planos de cine, tarjetas tipogr\xE1ficas que se revelan palabra por palabra y regresos a c\xE1mara.",
181531
+ "needs": [
181532
+ "tu clip hablando a c\xE1mara",
181533
+ "6\u201310 planos de B-roll"
181534
+ ],
181535
+ "sourceVersion": "1.0.0",
181536
+ "sourceSha256": "90f137ecc841067226c0b97a44e50440e3bd9a3d367b3dc177c5560ec90ccef0",
181537
+ "sourceBytes": 67266840,
181538
+ "fileCount": 86,
181539
+ "unpackedBytes": 72343103,
181540
+ "requiredPlan": "creator",
181541
+ "ratio": "tall",
181542
+ "demoSha256": "88861691ca215075aa9f4d4e5258f42a776ca1fdd2e4a50d399f7c519f3a1cb5"
181543
+ },
181544
+ {
181545
+ "id": "tutorial-por-capitulos",
181546
+ "name": "Tutorial por cap\xEDtulos con capturas",
181547
+ "summary": "Numeral gigante por cap\xEDtulo, la interfaz con zoom al prompt y el resultado en pantalla.",
181548
+ "needs": [
181549
+ "tu clip hablando a c\xE1mara",
181550
+ "capturas o la interfaz de tu herramienta"
181551
+ ],
181552
+ "sourceVersion": "1.0.0",
181553
+ "sourceSha256": "774fe0cd40423e050430b5ef463ca4b374dbef9ded6da3437809af218866827a",
181554
+ "sourceBytes": 63896838,
181555
+ "fileCount": 67,
181556
+ "unpackedBytes": 69296736,
181557
+ "requiredPlan": "creator",
181558
+ "ratio": "tall",
181559
+ "demoSha256": "e7e5cc8f851de24acb976839c2ce9f196908796cbefbb8ffce1c0a90e4581720"
181560
+ },
181561
+ {
181562
+ "id": "tablero-que-se-llena",
181563
+ "name": "Tablero que se llena",
181564
+ "summary": "Un ranking por niveles que se llena mientras opinas, en una sola toma.",
181565
+ "needs": [
181566
+ "tu clip hablando a c\xE1mara en una toma",
181567
+ "los \xEDconos de cada \xEDtem"
181568
+ ],
181569
+ "sourceVersion": "1.0.0",
181570
+ "sourceSha256": "122386757e9706a1725def3c5080b67053241949ed87336889d49a073c6c029f",
181571
+ "sourceBytes": 71615105,
181572
+ "fileCount": 70,
181573
+ "unpackedBytes": 81577587,
181574
+ "requiredPlan": "creator",
181575
+ "ratio": "tall",
181576
+ "demoSha256": "40ec0c80a2fec5ffb4eb822f71717c44987ac0d6a8aacd1fa189830e4a5f2cd5"
181577
+ },
181578
+ {
181579
+ "id": "explicador-con-evidencias",
181580
+ "name": "Explicador editorial con evidencias",
181581
+ "summary": "Tu argumento sostenido con documentos, fotos de archivo y resaltados sobre papel.",
181582
+ "needs": [
181583
+ "tu clip de cuerpo completo (mejor con fondo liso)",
181584
+ "im\xE1genes y documentos"
181585
+ ],
181586
+ "sourceVersion": "1.0.0",
181587
+ "sourceSha256": "fd56bdc3f5039b3cf15dbde54a413ee4688b0724bb3de9bc04d836b1183df29f",
181588
+ "sourceBytes": 28347758,
181589
+ "fileCount": 76,
181590
+ "unpackedBytes": 33672572,
181591
+ "requiredPlan": "creator",
181592
+ "ratio": "tall",
181593
+ "demoSha256": "34714b3a1051399ff7021e323c1819da3931e01709f201b86f0224fc12b0bc3b"
181594
+ },
181595
+ {
181596
+ "id": "monologo-con-dipticos",
181597
+ "name": "Mon\xF3logo con d\xEDpticos",
181598
+ "summary": "Una toma fija sin cortes: titular arriba y un par de im\xE1genes por cada frase.",
181599
+ "needs": [
181600
+ "tu clip hablando a c\xE1mara en una toma",
181601
+ "dos im\xE1genes por frase"
181602
+ ],
181603
+ "sourceVersion": "1.0.0",
181604
+ "sourceSha256": "bf4a3942f416e2828ece822bf1d647bfdb7bd876204b711c1a76f688ac4e7f44",
181605
+ "sourceBytes": 71193505,
181606
+ "fileCount": 94,
181607
+ "unpackedBytes": 76379034,
181608
+ "requiredPlan": "creator",
181609
+ "ratio": "tall",
181610
+ "demoSha256": "0081ff2bfd67f74f5b8cd7e0d17368d048e9a2e303a8755a6fced7ca368e613c"
181611
+ },
181612
+ {
181613
+ "id": "recorrido-de-experto",
181614
+ "name": "Recorrido de experto con lugar secreto",
181615
+ "summary": "Autoridad, un lugar secreto que se revela al final y planos exactos de cada parada.",
181616
+ "needs": [
181617
+ "tu clip hablando a c\xE1mara",
181618
+ "clips de cada lugar"
181619
+ ],
181620
+ "sourceVersion": "1.0.0",
181621
+ "sourceSha256": "34ddef4f4f9d2cc5cee268b9c967fcb4a45f40455676fcd9cf2c7430d279ab5e",
181622
+ "sourceBytes": 123413427,
181623
+ "fileCount": 80,
181624
+ "unpackedBytes": 128824268,
181625
+ "requiredPlan": "creator",
181626
+ "ratio": "tall",
181627
+ "demoSha256": "fefae76bcb80d3ce2b2a05055bf2c68bb26ec52b307ae4ca09714063fb03c612"
181628
+ },
181629
+ {
181630
+ "id": "vlog-intimo",
181631
+ "name": "Vlog \xEDntimo con texto en escena",
181632
+ "summary": "Una historia personal con palabras que viven en el espacio y papel en stop-motion.",
181633
+ "needs": [
181634
+ "tu clip hablando a c\xE1mara",
181635
+ "clips de tu d\xEDa"
181636
+ ],
181637
+ "sourceVersion": "1.0.0",
181638
+ "sourceSha256": "70ac7e126ab03993e39cdc3e2783fdd2143890fbb160b5a3b3663fef899e170a",
181639
+ "sourceBytes": 95858671,
181640
+ "fileCount": 73,
181641
+ "unpackedBytes": 100794739,
181642
+ "requiredPlan": "creator",
181643
+ "ratio": "tall",
181644
+ "demoSha256": "6222934f0b081b847811ed8d86bacdd3f66bd88364594ccf5649e944f9e2c7cf"
181645
+ },
181646
+ {
181647
+ "id": "documental-de-archivo",
181648
+ "name": "Documental tipogr\xE1fico de archivo",
181649
+ "summary": "R\xE1fagas de archivo y cifras gigantes detr\xE1s de las figuras, como un tr\xE1iler.",
181650
+ "needs": [
181651
+ "un clip breve hablando a c\xE1mara",
181652
+ "fotos de archivo"
181653
+ ],
181654
+ "sourceVersion": "1.0.0",
181655
+ "sourceSha256": "f0c33ebc14d1d929c29850e932477922f29d29228489dcbb9838aea79de9dbc9",
181656
+ "sourceBytes": 28620760,
181657
+ "fileCount": 80,
181658
+ "unpackedBytes": 33907182,
181659
+ "requiredPlan": "creator",
181660
+ "ratio": "tall",
181661
+ "demoSha256": "476c428bde32ad9bbee30fb799ff0ee91642021740aef05f1af0dee6fca598d7"
181662
+ },
181663
+ {
181664
+ "id": "catalogo-editorial",
181665
+ "name": "Cat\xE1logo editorial animado",
181666
+ "summary": "Sin c\xE1mara: l\xE1minas y diagramas que se acumulan hasta revelar tu recurso descargable.",
181667
+ "needs": [
181668
+ "tu voz (o un texto para narrar)",
181669
+ "tu recurso o documento"
181670
+ ],
181671
+ "sourceVersion": "1.0.0",
181672
+ "sourceSha256": "8e1de45eb58407b8a221d6ef115e53fdd49b00febe2b0962c1ef6d1fc15eb7c5",
181673
+ "sourceBytes": 4869367,
181674
+ "fileCount": 64,
181675
+ "unpackedBytes": 9096082,
181676
+ "requiredPlan": "creator",
181677
+ "ratio": "tall",
181678
+ "demoSha256": "109458de45085b7406b8f37ad2e355faa365fd8aa98d6035824806f7a562c3a9"
181679
+ },
181680
+ {
181681
+ "id": "pantalla-fisica",
181682
+ "name": "Explicaci\xF3n sobre pantalla f\xEDsica",
181683
+ "summary": "Una mano recorre una pantalla real con tu proceso; cifras y r\xF3tulos gu\xEDan cada paso.",
181684
+ "needs": [
181685
+ "tu voz",
181686
+ "un video de tu pantalla o tablet con el diagrama"
181687
+ ],
181688
+ "sourceVersion": "1.0.0",
181689
+ "sourceSha256": "2a21e544ca62e06a8896cbd042502277621554d7a6e8aeb83f36ad12454c92fd",
181690
+ "sourceBytes": 24317144,
181691
+ "fileCount": 70,
181692
+ "unpackedBytes": 28553643,
181693
+ "requiredPlan": "creator",
181694
+ "ratio": "tall",
181695
+ "demoSha256": "77a7568e9e0426e89d3be9fbdb7d3b4eea82b9f9161af7c08f6f4c591f9e8f9c"
181696
+ },
181697
+ {
181698
+ "id": "personaje-en-papel",
181699
+ "name": "Personaje animado en escenario de papel",
181700
+ "summary": "T\xFA como personaje dibujado que ejecuta cada paso sobre un escenario de papel.",
181701
+ "needs": [
181702
+ "tu voz",
181703
+ "fotos de tu cara con varias expresiones"
181704
+ ],
181705
+ "sourceVersion": "1.0.0",
181706
+ "sourceSha256": "ef7d6fc8886d130ad291f537e4d4587aa6c55770c146263ccd59a0c223cd3876",
181707
+ "sourceBytes": 15275734,
181708
+ "fileCount": 77,
181709
+ "unpackedBytes": 19549031,
181710
+ "requiredPlan": "creator",
181711
+ "ratio": "tall",
181712
+ "demoSha256": "2268da8622070fac6d5c8fa9270e1a964d9e06259c557fd16cd868bb22169495"
181713
+ },
181714
+ {
181715
+ "id": "simulacion-en-el-mapa",
181716
+ "name": "Simulaci\xF3n en el mapa",
181717
+ "summary": "\xBFQu\xE9 pasar\xEDa si\u2026? contado sobre un globo 3D: el territorio cambia, las p\xE9rdidas se acumulan en pantalla.",
181718
+ "needs": [
181719
+ "tu voz",
181720
+ "una hip\xF3tesis y sus consecuencias con cifras"
181721
+ ],
181722
+ "sourceVersion": "1.0.0",
181723
+ "sourceSha256": "2205ae641895f8435ca1e4457f52e23ba8291167e67aefbabf3eb2cd61e2b42e",
181724
+ "sourceBytes": 22728621,
181725
+ "fileCount": 71,
181726
+ "unpackedBytes": 27474023,
181727
+ "requiredPlan": "creator",
181728
+ "ratio": "tall",
181729
+ "demoSha256": "5cb48759829518bf0982927fcd42767936b188c837bead7aeb251003999c866d"
181730
+ },
181731
+ {
181732
+ "id": "relato-ilustrado",
181733
+ "name": "Relato ilustrado en segunda persona",
181734
+ "summary": "Una historia de tensi\xF3n en ilustraciones: reloj, reglas, contador y cliffhanger.",
181735
+ "needs": [
181736
+ "tu voz",
181737
+ "ilustraciones de un mismo personaje y escenario"
181738
+ ],
181739
+ "sourceVersion": "1.0.0",
181740
+ "sourceSha256": "98d12af2729f0080b2383314d0a1c74df4e538a24224013ee3db6258d2b441c4",
181741
+ "sourceBytes": 25173445,
181742
+ "fileCount": 71,
181743
+ "unpackedBytes": 33027674,
181744
+ "requiredPlan": "creator",
181745
+ "ratio": "tall",
181746
+ "demoSha256": "8ecc9082472fe20a028b6b99305b6ec4a92c9c3a509e6a604054499952b7ad75"
181747
+ },
181748
+ {
181749
+ "id": "pizarra-minimalista",
181750
+ "name": "Pizarra minimalista",
181751
+ "summary": "Acertijos y casos con dibujos de l\xEDnea sobre papel punteado y subt\xEDtulos arriba.",
181752
+ "needs": [
181753
+ "tu voz",
181754
+ "dibujos de l\xEDnea de cada personaje"
181755
+ ],
181756
+ "sourceVersion": "1.0.0",
181757
+ "sourceSha256": "13af7a854f9bfa946bb4227786775c6b4dde06ef9601c3209e8b87261332ce6e",
181758
+ "sourceBytes": 19016433,
181759
+ "fileCount": 71,
181760
+ "unpackedBytes": 23336820,
181761
+ "requiredPlan": "creator",
181762
+ "ratio": "tall",
181763
+ "demoSha256": "bdd4c6994077746d56ae42778b5d433a7b711c1dfbd23f4eaf83446147aebd64"
181764
+ },
181765
+ {
181766
+ "id": "infografia-de-objetos",
181767
+ "name": "Infograf\xEDa de objetos",
181768
+ "summary": "Un concepto de negocio explicado con objetos, tarjetas comparativas y una radiograf\xEDa del mecanismo.",
181769
+ "needs": [
181770
+ "tu voz",
181771
+ "las opciones o cifras que vas a comparar"
181772
+ ],
181773
+ "sourceVersion": "1.0.0",
181774
+ "sourceSha256": "2398984bf1cc7c0d47521c3e35f3831d29110067ff750c09d31518fcc8302956",
181775
+ "sourceBytes": 4813352,
181776
+ "fileCount": 65,
181777
+ "unpackedBytes": 9427443,
181778
+ "requiredPlan": "creator",
181779
+ "ratio": "tall",
181780
+ "demoSha256": "9d8f5537545df7c7068258a7d4ddb5bb742d9d3660d5e7cbf7657224061488af"
181781
+ },
181782
+ {
181783
+ "id": "ranking-con-escala",
181784
+ "name": "Ranking con escala",
181785
+ "summary": "Calificas opciones a c\xE1mara con una escala de colores fija arriba y la nota de cada una.",
181786
+ "needs": [
181787
+ "tu clip a c\xE1mara de medio cuerpo",
181788
+ "una ilustraci\xF3n o foto por opci\xF3n"
181789
+ ],
181790
+ "sourceVersion": "1.0.0",
181791
+ "sourceSha256": "51e417fe9af71064e3a20b9cd7e0103d67c54f8d521f39eae9752698b1b35c0b",
181792
+ "sourceBytes": 28346697,
181793
+ "fileCount": 73,
181794
+ "unpackedBytes": 33447909,
181795
+ "requiredPlan": "creator",
181796
+ "ratio": "tall",
181797
+ "demoSha256": "ddca372d5b2f0e8029422333427890220dcbbfd32ca0aa166ec3f8543ec0eea5"
181798
+ }
181799
+ ];
181800
+
181801
+ // packages/core/src/style-sources.ts
181802
+ var STYLE_SOURCE_MAX_BYTES = 128 * 1024 * 1024;
181803
+ function getStyleSource(id2, version) {
181804
+ return styleSourceData.find((style) => style.id === id2 && style.sourceVersion === version);
181805
+ }
181806
+
181564
181807
  // packages/core/src/index.ts
181565
181808
  var SCHEMA_VERSION = 1;
181566
181809
  var MAX_DOCUMENT_BYTES = 128 * 1024;
@@ -182016,9 +182259,10 @@ function canonicalFiles(files) {
182016
182259
  return result2;
182017
182260
  }
182018
182261
 
182019
- // packages/cli/src/personal-resources.ts
182020
- import { basename, extname as extname2, resolve as resolve3 } from "node:path";
182021
- import { randomUUID as randomUUID2 } from "node:crypto";
182262
+ // packages/cli/src/authored-motion.ts
182263
+ import { lstat as lstat2, mkdir as mkdir2, open as open2, link as link2, unlink as unlink2 } from "node:fs/promises";
182264
+ import { dirname as dirname2, join as join2 } from "node:path";
182265
+ import { createHash, randomUUID as randomUUID2 } from "node:crypto";
182022
182266
 
182023
182267
  // packages/cli/src/errors.ts
182024
182268
  var CliError = class extends Error {
@@ -182042,12 +182286,1444 @@ function errorOutput(error) {
182042
182286
  return { error: safe, code: "COMMAND_FAILED", retryable: false, hint: "Read the command help and run editorbrain doctor. Do not retry writes blindly." };
182043
182287
  }
182044
182288
 
182289
+ // packages/cli/src/io.ts
182290
+ import { constants } from "node:fs";
182291
+ import { lstat, mkdir, open, readdir, realpath, rename, unlink, link } from "node:fs/promises";
182292
+ import { dirname, join, relative, resolve, sep } from "node:path";
182293
+ import { randomUUID } from "node:crypto";
182294
+ async function ensureRoot(directory, create = false) {
182295
+ const root = resolve(directory);
182296
+ if (create) await mkdir(root, { recursive: true });
182297
+ const info = await lstat(root);
182298
+ if (info.isSymbolicLink() || !info.isDirectory()) throw new Error("Workspace root must be a real directory, not a symlink");
182299
+ return realpath(root);
182300
+ }
182301
+ async function checkedPath(root, path, document2 = true) {
182302
+ if (document2) safeDocumentPath(path);
182303
+ const target = resolve(root, path);
182304
+ const rel = relative(root, target);
182305
+ if (!rel || rel.startsWith(`..${sep}`) || rel === ".." || resolve(path) === path) throw new Error("Path escapes workspace");
182306
+ let cursor = root;
182307
+ for (const segment of rel.split(sep)) {
182308
+ cursor = join(cursor, segment);
182309
+ try {
182310
+ const info = await lstat(cursor);
182311
+ if (info.isSymbolicLink()) throw new Error(`Symlinks are not allowed: ${path}`);
182312
+ } catch (error) {
182313
+ if (error.code !== "ENOENT") throw error;
182314
+ }
182315
+ }
182316
+ return target;
182317
+ }
182318
+ async function readText(root, path, document2 = true) {
182319
+ const target = await checkedPath(root, path, document2);
182320
+ const handle = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW);
182321
+ try {
182322
+ const info = await handle.stat();
182323
+ if (!info.isFile()) throw new Error(`Not a regular file: ${path}`);
182324
+ if (document2 && info.size > MAX_DOCUMENT_BYTES) throw new Error(`Document exceeds 128 KiB: ${path}`);
182325
+ return new TextDecoder("utf-8", { fatal: true }).decode(await handle.readFile());
182326
+ } finally {
182327
+ await handle.close();
182328
+ }
182329
+ }
182330
+ async function atomicWrite(root, path, content, options = {}) {
182331
+ const target = await checkedPath(root, path, options.document ?? true);
182332
+ await mkdir(dirname(target), { recursive: true });
182333
+ await checkedPath(root, path, options.document ?? true);
182334
+ const temporary = join(dirname(target), `.eh-${randomUUID()}.tmp`);
182335
+ const handle = await open(temporary, "wx", options.mode ?? 420);
182336
+ try {
182337
+ await handle.writeFile(content, "utf8");
182338
+ await handle.close();
182339
+ await checkedPath(root, path, options.document ?? true);
182340
+ if (options.overwrite === false) {
182341
+ await link(temporary, target);
182342
+ await unlink(temporary);
182343
+ } else await rename(temporary, target);
182344
+ } catch (error) {
182345
+ await handle.close().catch(() => {
182346
+ });
182347
+ await unlink(temporary).catch(() => {
182348
+ });
182349
+ throw error;
182350
+ }
182351
+ }
182352
+ async function readWorkspace(root) {
182353
+ const files = /* @__PURE__ */ Object.create(null);
182354
+ async function walk(path) {
182355
+ const directory = await checkedPath(root, path, false);
182356
+ let entries;
182357
+ try {
182358
+ entries = await readdir(directory, { withFileTypes: true });
182359
+ } catch (error) {
182360
+ if (error.code === "ENOENT") return;
182361
+ throw error;
182362
+ }
182363
+ for (const entry of entries) {
182364
+ const child = `${path}/${entry.name}`;
182365
+ if (entry.isSymbolicLink()) throw new Error(`Symlinks are not allowed: ${child}`);
182366
+ if (entry.name.startsWith(".")) continue;
182367
+ if (entry.isDirectory()) {
182368
+ if (path.startsWith("videos/") && ["assets", "renders"].includes(entry.name)) continue;
182369
+ await walk(child);
182370
+ } else if (entry.isFile() && /\.(json|md)$/.test(entry.name)) {
182371
+ safeDocumentPath(child);
182372
+ files[child] = await readText(root, child);
182373
+ }
182374
+ }
182375
+ }
182376
+ await walk(".editorharness");
182377
+ await walk(".editorbrain");
182378
+ await walk("videos");
182379
+ return canonicalFiles(files);
182380
+ }
182381
+ async function readProjectWorkspace(root, projectId) {
182382
+ assertIdentifier(projectId);
182383
+ const projectPath = `videos/${projectId}/project.json`;
182384
+ const projectContent = await readText(root, projectPath);
182385
+ const checked = validateDocument(projectPath, projectContent);
182386
+ if (!checked.valid) throw new ValidationError(checked.issues);
182387
+ const project = JSON.parse(projectContent);
182388
+ const files = { [projectPath]: projectContent };
182389
+ for (const path of /* @__PURE__ */ new Set([...projectSources(project), ...optionalProjectSources(project)])) {
182390
+ if (path === projectPath) continue;
182391
+ const aliases2 = path.startsWith(".editorbrain/") ? [path, path.replace(/^\.editorbrain\//, ".editorharness/")] : [path];
182392
+ for (const alias of aliases2) {
182393
+ try {
182394
+ files[alias] = await readText(root, alias);
182395
+ } catch (error) {
182396
+ if (error.code !== "ENOENT") throw error;
182397
+ }
182398
+ }
182399
+ }
182400
+ if (await readText(root, projectPath) !== projectContent) throw new Error("The selected project changed while reading its context. Retry before editing.");
182401
+ return canonicalFiles(files);
182402
+ }
182403
+
182404
+ // packages/cli/src/authored-motion.ts
182405
+ async function downloadAuthoredSource(client, pin, root, out, fetcher = fetch) {
182406
+ return downloadPinnedSource(client, pin, root, out, "motion", fetcher);
182407
+ }
182408
+ async function downloadPinnedSource(client, pin, root, out, kind, fetcher = fetch) {
182409
+ const namespace = kind === "style" ? "style-sources" : "authored-motion";
182410
+ const downloadNamespace = kind === "style" ? "style-source-download" : "authored-motion-download";
182411
+ 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.");
182412
+ const target = await checkedPath(root, out, false);
182413
+ try {
182414
+ await lstat2(target);
182415
+ throw new CliError("FILE_EXISTS", "The output already exists.", "Choose a new archive path.");
182416
+ } catch (error) {
182417
+ if (error.code !== "ENOENT") throw error;
182418
+ }
182419
+ const metadata = await client.request(`/v1/${namespace}/${pin.id}/source?${new URLSearchParams({ version: pin.version, sha256: pin.sha256 })}`);
182420
+ const url2 = new URL(metadata.url);
182421
+ const expectedPath = `/v1/${downloadNamespace}/${pin.id}/${pin.version}/${pin.sha256}`;
182422
+ const origin = new URL(client.url).origin;
182423
+ const trustedOrigin = url2.origin === origin || origin === "https://editorharness-api.innovandohorizontes.workers.dev" && url2.origin === "https://api.editorbrain.com";
182424
+ 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.");
182425
+ const response = await fetcher(url2, { redirect: "error", signal: AbortSignal.timeout(18e4) });
182426
+ if (response.status === 403) {
182427
+ await response.body?.cancel();
182428
+ 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.");
182429
+ }
182430
+ if (!response.ok) throw new CliError("DOWNLOAD_FAILED", `Source download failed (HTTP ${response.status}).`, "Request a new source link; existing archives were preserved.");
182431
+ const reader = response.body?.getReader();
182432
+ if (!reader) throw new CliError("INVALID_RESPONSE", "Source download body is missing.", "Retry the pinned source.");
182433
+ const temporary = join2(dirname2(target), `.eb-motion-${randomUUID2()}.tmp`);
182434
+ let handle;
182435
+ const hash6 = createHash("sha256");
182436
+ let size = 0;
182437
+ try {
182438
+ await mkdir2(dirname2(target), { recursive: true });
182439
+ await checkedPath(root, out, false);
182440
+ handle = await open2(temporary, "wx", 384);
182441
+ for (; ; ) {
182442
+ const { done, value } = await reader.read();
182443
+ if (done) break;
182444
+ size += value.length;
182445
+ if (size > pin.bytes) throw new CliError("HASH_MISMATCH", "Source archive exceeds the pinned length.", "Discard the unverified download.");
182446
+ hash6.update(value);
182447
+ await handle.writeFile(value);
182448
+ }
182449
+ if (size !== pin.bytes || hash6.digest("hex") !== pin.sha256) throw new CliError("HASH_MISMATCH", "Source archive verification failed.", "Do not extract this download.");
182450
+ await handle.sync();
182451
+ await handle.close();
182452
+ await checkedPath(root, out, false);
182453
+ await link2(temporary, target);
182454
+ } catch (error) {
182455
+ await reader.cancel().catch(() => {
182456
+ });
182457
+ throw error;
182458
+ } finally {
182459
+ await handle?.close().catch(() => {
182460
+ });
182461
+ await unlink2(temporary).catch(() => {
182462
+ });
182463
+ }
182464
+ 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." };
182465
+ }
182466
+
182467
+ // packages/cli/src/style-archive.ts
182468
+ import { createHash as createHash2 } from "node:crypto";
182469
+ import { gunzipSync } from "node:zlib";
182470
+ var STYLE_ARCHIVE_MAX_BYTES = 128 * 1024 * 1024;
182471
+ var STYLE_UNPACKED_MAX_BYTES = 192 * 1024 * 1024;
182472
+ var archiveHash = (bytes) => createHash2("sha256").update(bytes).digest("hex");
182473
+ function safeArchivePath(name) {
182474
+ 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");
182475
+ return name;
182476
+ }
182477
+ function readStyleArchive(bytes, pin) {
182478
+ 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");
182479
+ const tar = gunzipSync(bytes, { maxOutputLength: STYLE_UNPACKED_MAX_BYTES + 2 * 1024 * 1024 });
182480
+ const files = /* @__PURE__ */ new Map();
182481
+ let offset = 0, total = 0, ended = false;
182482
+ const octal = (b) => {
182483
+ const s = b.toString("ascii").replace(/\0.*$/s, "").trim();
182484
+ if (!/^[0-7]+$/.test(s)) throw new Error("Invalid tar number");
182485
+ return parseInt(s, 8);
182486
+ };
182487
+ while (offset + 512 <= tar.length) {
182488
+ const h = tar.subarray(offset, offset + 512);
182489
+ offset += 512;
182490
+ if (h.every((b) => b === 0)) {
182491
+ if (tar.length - offset < 512 || tar.subarray(offset).some((b) => b !== 0)) throw new Error("Invalid tar ending");
182492
+ ended = true;
182493
+ break;
182494
+ }
182495
+ const sum = h.reduce((n, b, i) => n + (i >= 148 && i < 156 ? 32 : b), 0);
182496
+ 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");
182497
+ const name = safeArchivePath(h.subarray(0, 100).toString("utf8").replace(/\0.*$/s, ""));
182498
+ const size = octal(h.subarray(124, 136));
182499
+ if (files.has(name) || files.size >= 512 || offset + size > tar.length) throw new Error("Duplicate or truncated tar entry");
182500
+ total += size;
182501
+ if (total > pin.unpackedBytes) throw new Error("Archive exceeds unpacked pin");
182502
+ files.set(name, tar.subarray(offset, offset + size));
182503
+ offset += Math.ceil(size / 512) * 512;
182504
+ }
182505
+ if (!ended || files.size !== pin.fileCount || total !== pin.unpackedBytes || offset > tar.length) throw new Error("Archive inventory mismatch");
182506
+ const manifest = JSON.parse(files.get("BUNDLE-MANIFEST.json")?.toString("utf8") ?? "null");
182507
+ 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");
182508
+ if (Object.keys(manifest.files).length !== files.size - 1) throw new Error("Incomplete style manifest");
182509
+ for (const [name, data] of files) {
182510
+ if (name === "BUNDLE-MANIFEST.json") continue;
182511
+ const expected = manifest.files[name];
182512
+ if (!expected || expected.bytes !== data.length || expected.sha256 !== archiveHash(data)) throw new Error("Manifest hash mismatch: " + name);
182513
+ }
182514
+ return { files, manifest };
182515
+ }
182516
+
182517
+ // packages/cli/src/style-source-guards-v1.ts
182518
+ var styleSourceGuards = {
182519
+ "comando-y-resultado": {
182520
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
182521
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
182522
+ "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",
182523
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
182524
+ (function () {
182525
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
182526
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
182527
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
182528
+ const fonts = ['display','text','heavy','mono','hand'];
182529
+ window.EB_VALIDATE_PARAMS = (p, q) => {
182530
+ const theme = q.get('theme') || p.theme;
182531
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
182532
+ const ratio = q.get('ratio') || p.ratio || 'wide';
182533
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
182534
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
182535
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
182536
+ }
182537
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
182538
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
182539
+ if (q.get('demo') === '1') return;
182540
+ const b = window.__overrides?.brand;
182541
+ 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');
182542
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
182543
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
182544
+ 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');
182545
+ for (const role of fonts) {
182546
+ const font = b.fonts[role];
182547
+ 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);
182548
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
182549
+ }
182550
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
182551
+ };
182552
+ })();
182553
+
182554
+ (function () {
182555
+ const base = window.EB_VALIDATE_PARAMS;
182556
+ const roles = ["accent","accentInk","bg","cardEdge","chip","giftBox","giftLid","giftRibbon","giftShade","light","outline","panel","panelLine","thumbBg","uiText"];
182557
+ const fontRoles = ["credit","cta","headline","ui"];
182558
+ window.EB_VALIDATE_PARAMS = (params, query) => {
182559
+ base(params, query);
182560
+ if (query.get('demo') === '1') return;
182561
+ for (const role of roles) {
182562
+ 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.');
182563
+ }
182564
+ for (const role of fontRoles) {
182565
+ const font = window.__overrides?.brand?.fonts?.[role];
182566
+ 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.');
182567
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
182568
+ }
182569
+ };
182570
+ })();
182571
+ `
182572
+ },
182573
+ "narrador-sobre-collage": {
182574
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
182575
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
182576
+ "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",
182577
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
182578
+ (function () {
182579
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
182580
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
182581
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
182582
+ const fonts = ['display','text','heavy','mono','hand'];
182583
+ window.EB_VALIDATE_PARAMS = (p, q) => {
182584
+ const theme = q.get('theme') || p.theme;
182585
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
182586
+ const ratio = q.get('ratio') || p.ratio || 'wide';
182587
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
182588
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
182589
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
182590
+ }
182591
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
182592
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
182593
+ if (q.get('demo') === '1') return;
182594
+ const b = window.__overrides?.brand;
182595
+ 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');
182596
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
182597
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
182598
+ 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');
182599
+ for (const role of fonts) {
182600
+ const font = b.fonts[role];
182601
+ 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);
182602
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
182603
+ }
182604
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
182605
+ };
182606
+ })();
182607
+
182608
+ (function () {
182609
+ const base = window.EB_VALIDATE_PARAMS;
182610
+ const roles = ["accent","bg","labelBg","labelInk","light","outline"];
182611
+ const fontRoles = ["caption","credit","headline","label"];
182612
+ window.EB_VALIDATE_PARAMS = (params, query) => {
182613
+ base(params, query);
182614
+ if (query.get('demo') === '1') return;
182615
+ for (const role of roles) {
182616
+ 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.');
182617
+ }
182618
+ for (const role of fontRoles) {
182619
+ const font = window.__overrides?.brand?.fonts?.[role];
182620
+ 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.');
182621
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
182622
+ }
182623
+ };
182624
+ })();
182625
+ `
182626
+ },
182627
+ "presentador-con-interfaz": {
182628
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
182629
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
182630
+ "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",
182631
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
182632
+ (function () {
182633
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
182634
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
182635
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
182636
+ const fonts = ['display','text','heavy','mono','hand'];
182637
+ window.EB_VALIDATE_PARAMS = (p, q) => {
182638
+ const theme = q.get('theme') || p.theme;
182639
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
182640
+ const ratio = q.get('ratio') || p.ratio || 'wide';
182641
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
182642
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
182643
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
182644
+ }
182645
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
182646
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
182647
+ if (q.get('demo') === '1') return;
182648
+ const b = window.__overrides?.brand;
182649
+ 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');
182650
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
182651
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
182652
+ 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');
182653
+ for (const role of fonts) {
182654
+ const font = b.fonts[role];
182655
+ 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);
182656
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
182657
+ }
182658
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
182659
+ };
182660
+ })();
182661
+
182662
+ (function () {
182663
+ const base = window.EB_VALIDATE_PARAMS;
182664
+ const roles = ["accent","bg","dim","ink","keybox","line","muted","onAccent","pill","surface","surface2"];
182665
+ const fontRoles = ["caption","credit","figure","heading","keyword","label","mono","ui"];
182666
+ window.EB_VALIDATE_PARAMS = (params, query) => {
182667
+ base(params, query);
182668
+ if (query.get('demo') === '1') return;
182669
+ for (const role of roles) {
182670
+ 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.');
182671
+ }
182672
+ for (const role of fontRoles) {
182673
+ const font = window.__overrides?.brand?.fonts?.[role];
182674
+ 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.');
182675
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
182676
+ }
182677
+ };
182678
+ })();
182679
+ `
182680
+ },
182681
+ "ensayo-cinematografico": {
182682
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
182683
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
182684
+ "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",
182685
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
182686
+ (function () {
182687
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
182688
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
182689
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
182690
+ const fonts = ['display','text','heavy','mono','hand'];
182691
+ window.EB_VALIDATE_PARAMS = (p, q) => {
182692
+ const theme = q.get('theme') || p.theme;
182693
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
182694
+ const ratio = q.get('ratio') || p.ratio || 'wide';
182695
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
182696
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
182697
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
182698
+ }
182699
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
182700
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
182701
+ if (q.get('demo') === '1') return;
182702
+ const b = window.__overrides?.brand;
182703
+ 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');
182704
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
182705
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
182706
+ 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');
182707
+ for (const role of fonts) {
182708
+ const font = b.fonts[role];
182709
+ 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);
182710
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
182711
+ }
182712
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
182713
+ };
182714
+ })();
182715
+
182716
+ (function () {
182717
+ const base = window.EB_VALIDATE_PARAMS;
182718
+ const roles = ["accent","accent2","bg","cardDark","cardLight","inkOnDark","inkOnLight","light","outline","shadow"];
182719
+ const fontRoles = ["caption","credit","heavy","serif"];
182720
+ window.EB_VALIDATE_PARAMS = (params, query) => {
182721
+ base(params, query);
182722
+ if (query.get('demo') === '1') return;
182723
+ for (const role of roles) {
182724
+ 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.');
182725
+ }
182726
+ for (const role of fontRoles) {
182727
+ const font = window.__overrides?.brand?.fonts?.[role];
182728
+ 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.');
182729
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
182730
+ }
182731
+ };
182732
+ })();
182733
+ `
182734
+ },
182735
+ "tutorial-por-capitulos": {
182736
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
182737
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
182738
+ "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",
182739
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
182740
+ (function () {
182741
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
182742
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
182743
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
182744
+ const fonts = ['display','text','heavy','mono','hand'];
182745
+ window.EB_VALIDATE_PARAMS = (p, q) => {
182746
+ const theme = q.get('theme') || p.theme;
182747
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
182748
+ const ratio = q.get('ratio') || p.ratio || 'wide';
182749
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
182750
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
182751
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
182752
+ }
182753
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
182754
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
182755
+ if (q.get('demo') === '1') return;
182756
+ const b = window.__overrides?.brand;
182757
+ 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');
182758
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
182759
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
182760
+ 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');
182761
+ for (const role of fonts) {
182762
+ const font = b.fonts[role];
182763
+ 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);
182764
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
182765
+ }
182766
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
182767
+ };
182768
+ })();
182769
+
182770
+ (function () {
182771
+ const base = window.EB_VALIDATE_PARAMS;
182772
+ const roles = ["alarm","badge","badgeShadow","badgeText","bg","caption","card","cream","heart","heartCore","lime","limeDeep","numeral","paper","title","uiBubble","uiField","uiInk","uiLine","uiMark","uiMuted","uiSend"];
182773
+ const fontRoles = ["caption","credit","greeting","heavy","italic","script","ui","uiSerif"];
182774
+ window.EB_VALIDATE_PARAMS = (params, query) => {
182775
+ base(params, query);
182776
+ if (query.get('demo') === '1') return;
182777
+ for (const role of roles) {
182778
+ 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.');
182779
+ }
182780
+ for (const role of fontRoles) {
182781
+ const font = window.__overrides?.brand?.fonts?.[role];
182782
+ 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.');
182783
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
182784
+ }
182785
+ };
182786
+ })();
182787
+ `
182788
+ },
182789
+ "tablero-que-se-llena": {
182790
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
182791
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
182792
+ "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",
182793
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
182794
+ (function () {
182795
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
182796
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
182797
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
182798
+ const fonts = ['display','text','heavy','mono','hand'];
182799
+ window.EB_VALIDATE_PARAMS = (p, q) => {
182800
+ const theme = q.get('theme') || p.theme;
182801
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
182802
+ const ratio = q.get('ratio') || p.ratio || 'wide';
182803
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
182804
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
182805
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
182806
+ }
182807
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
182808
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
182809
+ if (q.get('demo') === '1') return;
182810
+ const b = window.__overrides?.brand;
182811
+ 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');
182812
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
182813
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
182814
+ 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');
182815
+ for (const role of fonts) {
182816
+ const font = b.fonts[role];
182817
+ 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);
182818
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
182819
+ }
182820
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
182821
+ };
182822
+ })();
182823
+
182824
+ (function () {
182825
+ const base = window.EB_VALIDATE_PARAMS;
182826
+ const roles = ["bg","callout","cell","credit","labelGap","panel","seam","tierInk","tile","title"];
182827
+ const fontRoles = ["callout","credit","tier","title"];
182828
+ window.EB_VALIDATE_PARAMS = (params, query) => {
182829
+ base(params, query);
182830
+ if (query.get('demo') === '1') return;
182831
+ for (const role of roles) {
182832
+ 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.');
182833
+ }
182834
+ for (const role of fontRoles) {
182835
+ const font = window.__overrides?.brand?.fonts?.[role];
182836
+ 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.');
182837
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
182838
+ }
182839
+ };
182840
+ })();
182841
+ `
182842
+ },
182843
+ "explicador-con-evidencias": {
182844
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
182845
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
182846
+ "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",
182847
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
182848
+ (function () {
182849
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
182850
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
182851
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
182852
+ const fonts = ['display','text','heavy','mono','hand'];
182853
+ window.EB_VALIDATE_PARAMS = (p, q) => {
182854
+ const theme = q.get('theme') || p.theme;
182855
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
182856
+ const ratio = q.get('ratio') || p.ratio || 'wide';
182857
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
182858
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
182859
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
182860
+ }
182861
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
182862
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
182863
+ if (q.get('demo') === '1') return;
182864
+ const b = window.__overrides?.brand;
182865
+ 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');
182866
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
182867
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
182868
+ 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');
182869
+ for (const role of fonts) {
182870
+ const font = b.fonts[role];
182871
+ 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);
182872
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
182873
+ }
182874
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
182875
+ };
182876
+ })();
182877
+
182878
+ (function () {
182879
+ const base = window.EB_VALIDATE_PARAMS;
182880
+ const roles = ["annotation","bg","card","cardLine","docInk","docMuted","docText","hookBox","hookInk","light","marker","page","pageInner","pageLine","paper","shadow"];
182881
+ const fontRoles = ["caption","credit","docBody","docTitle","hook","label","mono","serif","serifItalic"];
182882
+ window.EB_VALIDATE_PARAMS = (params, query) => {
182883
+ base(params, query);
182884
+ if (query.get('demo') === '1') return;
182885
+ for (const role of roles) {
182886
+ 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.');
182887
+ }
182888
+ for (const role of fontRoles) {
182889
+ const font = window.__overrides?.brand?.fonts?.[role];
182890
+ 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.');
182891
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
182892
+ }
182893
+ };
182894
+ })();
182895
+ `
182896
+ },
182897
+ "monologo-con-dipticos": {
182898
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
182899
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
182900
+ "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",
182901
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
182902
+ (function () {
182903
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
182904
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
182905
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
182906
+ const fonts = ['display','text','heavy','mono','hand'];
182907
+ window.EB_VALIDATE_PARAMS = (p, q) => {
182908
+ const theme = q.get('theme') || p.theme;
182909
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
182910
+ const ratio = q.get('ratio') || p.ratio || 'wide';
182911
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
182912
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
182913
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
182914
+ }
182915
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
182916
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
182917
+ if (q.get('demo') === '1') return;
182918
+ const b = window.__overrides?.brand;
182919
+ 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');
182920
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
182921
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
182922
+ 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');
182923
+ for (const role of fonts) {
182924
+ const font = b.fonts[role];
182925
+ 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);
182926
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
182927
+ }
182928
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
182929
+ };
182930
+ })();
182931
+
182932
+ (function () {
182933
+ const base = window.EB_VALIDATE_PARAMS;
182934
+ const roles = ["bg","caption","credit","headline"];
182935
+ const fontRoles = ["caption","credit","headline"];
182936
+ window.EB_VALIDATE_PARAMS = (params, query) => {
182937
+ base(params, query);
182938
+ if (query.get('demo') === '1') return;
182939
+ for (const role of roles) {
182940
+ 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.');
182941
+ }
182942
+ for (const role of fontRoles) {
182943
+ const font = window.__overrides?.brand?.fonts?.[role];
182944
+ 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.');
182945
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
182946
+ }
182947
+ };
182948
+ })();
182949
+ `
182950
+ },
182951
+ "recorrido-de-experto": {
182952
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
182953
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
182954
+ "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",
182955
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
182956
+ (function () {
182957
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
182958
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
182959
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
182960
+ const fonts = ['display','text','heavy','mono','hand'];
182961
+ window.EB_VALIDATE_PARAMS = (p, q) => {
182962
+ const theme = q.get('theme') || p.theme;
182963
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
182964
+ const ratio = q.get('ratio') || p.ratio || 'wide';
182965
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
182966
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
182967
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
182968
+ }
182969
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
182970
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
182971
+ if (q.get('demo') === '1') return;
182972
+ const b = window.__overrides?.brand;
182973
+ 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');
182974
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
182975
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
182976
+ 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');
182977
+ for (const role of fonts) {
182978
+ const font = b.fonts[role];
182979
+ 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);
182980
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
182981
+ }
182982
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
182983
+ };
182984
+ })();
182985
+
182986
+ (function () {
182987
+ const base = window.EB_VALIDATE_PARAMS;
182988
+ const roles = ["bg","light","shadow"];
182989
+ const fontRoles = ["bold","caption","credit","label","semi"];
182990
+ window.EB_VALIDATE_PARAMS = (params, query) => {
182991
+ base(params, query);
182992
+ if (query.get('demo') === '1') return;
182993
+ for (const role of roles) {
182994
+ 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.');
182995
+ }
182996
+ for (const role of fontRoles) {
182997
+ const font = window.__overrides?.brand?.fonts?.[role];
182998
+ 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.');
182999
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183000
+ }
183001
+ };
183002
+ })();
183003
+ `
183004
+ },
183005
+ "vlog-intimo": {
183006
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
183007
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
183008
+ "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",
183009
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
183010
+ (function () {
183011
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
183012
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
183013
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
183014
+ const fonts = ['display','text','heavy','mono','hand'];
183015
+ window.EB_VALIDATE_PARAMS = (p, q) => {
183016
+ const theme = q.get('theme') || p.theme;
183017
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
183018
+ const ratio = q.get('ratio') || p.ratio || 'wide';
183019
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
183020
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
183021
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
183022
+ }
183023
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
183024
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
183025
+ if (q.get('demo') === '1') return;
183026
+ const b = window.__overrides?.brand;
183027
+ 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');
183028
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
183029
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
183030
+ 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');
183031
+ for (const role of fonts) {
183032
+ const font = b.fonts[role];
183033
+ 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);
183034
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
183035
+ }
183036
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
183037
+ };
183038
+ })();
183039
+
183040
+ (function () {
183041
+ const base = window.EB_VALIDATE_PARAMS;
183042
+ const roles = ["bg","gold","inkA","inkB","inkC","light","paper","paperRim","plate","plateInk","shadow","wood"];
183043
+ const fontRoles = ["credit","serif","slip"];
183044
+ window.EB_VALIDATE_PARAMS = (params, query) => {
183045
+ base(params, query);
183046
+ if (query.get('demo') === '1') return;
183047
+ for (const role of roles) {
183048
+ 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.');
183049
+ }
183050
+ for (const role of fontRoles) {
183051
+ const font = window.__overrides?.brand?.fonts?.[role];
183052
+ 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.');
183053
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183054
+ }
183055
+ };
183056
+ })();
183057
+ `
183058
+ },
183059
+ "documental-de-archivo": {
183060
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
183061
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
183062
+ "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",
183063
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
183064
+ (function () {
183065
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
183066
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
183067
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
183068
+ const fonts = ['display','text','heavy','mono','hand'];
183069
+ window.EB_VALIDATE_PARAMS = (p, q) => {
183070
+ const theme = q.get('theme') || p.theme;
183071
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
183072
+ const ratio = q.get('ratio') || p.ratio || 'wide';
183073
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
183074
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
183075
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
183076
+ }
183077
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
183078
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
183079
+ if (q.get('demo') === '1') return;
183080
+ const b = window.__overrides?.brand;
183081
+ 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');
183082
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
183083
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
183084
+ 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');
183085
+ for (const role of fonts) {
183086
+ const font = b.fonts[role];
183087
+ 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);
183088
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
183089
+ }
183090
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
183091
+ };
183092
+ })();
183093
+
183094
+ (function () {
183095
+ const base = window.EB_VALIDATE_PARAMS;
183096
+ const roles = ["accent","bg","glow","highlight","light","paper","paperInk","shadow"];
183097
+ const fontRoles = ["cond","credit","paperHead","paperMark","paperSans","paperSerif","sign"];
183098
+ window.EB_VALIDATE_PARAMS = (params, query) => {
183099
+ base(params, query);
183100
+ if (query.get('demo') === '1') return;
183101
+ for (const role of roles) {
183102
+ 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.');
183103
+ }
183104
+ for (const role of fontRoles) {
183105
+ const font = window.__overrides?.brand?.fonts?.[role];
183106
+ 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.');
183107
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183108
+ }
183109
+ };
183110
+ })();
183111
+ `
183112
+ },
183113
+ "catalogo-editorial": {
183114
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
183115
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
183116
+ "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",
183117
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
183118
+ (function () {
183119
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
183120
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
183121
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
183122
+ const fonts = ['display','text','heavy','mono','hand'];
183123
+ window.EB_VALIDATE_PARAMS = (p, q) => {
183124
+ const theme = q.get('theme') || p.theme;
183125
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
183126
+ const ratio = q.get('ratio') || p.ratio || 'wide';
183127
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
183128
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
183129
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
183130
+ }
183131
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
183132
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
183133
+ if (q.get('demo') === '1') return;
183134
+ const b = window.__overrides?.brand;
183135
+ 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');
183136
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
183137
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
183138
+ 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');
183139
+ for (const role of fonts) {
183140
+ const font = b.fonts[role];
183141
+ 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);
183142
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
183143
+ }
183144
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
183145
+ };
183146
+ })();
183147
+
183148
+ (function () {
183149
+ const base = window.EB_VALIDATE_PARAMS;
183150
+ const roles = ["accent","bg","cta","doc","docAccent","docGap","docMint","docNavy","field","fieldGlow","fieldInk","icon","ink","line","muted","rule","sheet","soft","title"];
183151
+ const fontRoles = ["alt1","alt2","hand","label","sans","serif","small"];
183152
+ window.EB_VALIDATE_PARAMS = (params, query) => {
183153
+ base(params, query);
183154
+ if (query.get('demo') === '1') return;
183155
+ for (const role of roles) {
183156
+ 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.');
183157
+ }
183158
+ for (const role of fontRoles) {
183159
+ const font = window.__overrides?.brand?.fonts?.[role];
183160
+ 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.');
183161
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183162
+ }
183163
+ };
183164
+ })();
183165
+ `
183166
+ },
183167
+ "pantalla-fisica": {
183168
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
183169
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
183170
+ "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",
183171
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
183172
+ (function () {
183173
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
183174
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
183175
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
183176
+ const fonts = ['display','text','heavy','mono','hand'];
183177
+ window.EB_VALIDATE_PARAMS = (p, q) => {
183178
+ const theme = q.get('theme') || p.theme;
183179
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
183180
+ const ratio = q.get('ratio') || p.ratio || 'wide';
183181
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
183182
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
183183
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
183184
+ }
183185
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
183186
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
183187
+ if (q.get('demo') === '1') return;
183188
+ const b = window.__overrides?.brand;
183189
+ 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');
183190
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
183191
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
183192
+ 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');
183193
+ for (const role of fonts) {
183194
+ const font = b.fonts[role];
183195
+ 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);
183196
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
183197
+ }
183198
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
183199
+ };
183200
+ })();
183201
+
183202
+ (function () {
183203
+ const base = window.EB_VALIDATE_PARAMS;
183204
+ const roles = ["bg","card","cardInk","cardLine","cardMuted","follow","following","light","panel","pos","ring1","ring2","shadow","wordmark"];
183205
+ const fontRoles = ["credit","heavy","serif","ui","uiBold","uiNum","uiText","wordmark"];
183206
+ window.EB_VALIDATE_PARAMS = (params, query) => {
183207
+ base(params, query);
183208
+ if (query.get('demo') === '1') return;
183209
+ for (const role of roles) {
183210
+ 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.');
183211
+ }
183212
+ for (const role of fontRoles) {
183213
+ const font = window.__overrides?.brand?.fonts?.[role];
183214
+ 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.');
183215
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183216
+ }
183217
+ };
183218
+ })();
183219
+ `
183220
+ },
183221
+ "personaje-en-papel": {
183222
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
183223
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
183224
+ "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",
183225
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
183226
+ (function () {
183227
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
183228
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
183229
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
183230
+ const fonts = ['display','text','heavy','mono','hand'];
183231
+ window.EB_VALIDATE_PARAMS = (p, q) => {
183232
+ const theme = q.get('theme') || p.theme;
183233
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
183234
+ const ratio = q.get('ratio') || p.ratio || 'wide';
183235
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
183236
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
183237
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
183238
+ }
183239
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
183240
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
183241
+ if (q.get('demo') === '1') return;
183242
+ const b = window.__overrides?.brand;
183243
+ 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');
183244
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
183245
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
183246
+ 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');
183247
+ for (const role of fonts) {
183248
+ const font = b.fonts[role];
183249
+ 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);
183250
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
183251
+ }
183252
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
183253
+ };
183254
+ })();
183255
+
183256
+ (function () {
183257
+ const base = window.EB_VALIDATE_PARAMS;
183258
+ 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"];
183259
+ const fontRoles = ["credit","slab","slabBlack","ui","uiBold","uiReg","uiSemi"];
183260
+ window.EB_VALIDATE_PARAMS = (params, query) => {
183261
+ base(params, query);
183262
+ if (query.get('demo') === '1') return;
183263
+ for (const role of roles) {
183264
+ 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.');
183265
+ }
183266
+ for (const role of fontRoles) {
183267
+ const font = window.__overrides?.brand?.fonts?.[role];
183268
+ 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.');
183269
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183270
+ }
183271
+ };
183272
+ })();
183273
+ `
183274
+ },
183275
+ "simulacion-en-el-mapa": {
183276
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
183277
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
183278
+ "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",
183279
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
183280
+ (function () {
183281
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
183282
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
183283
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
183284
+ const fonts = ['display','text','heavy','mono','hand'];
183285
+ window.EB_VALIDATE_PARAMS = (p, q) => {
183286
+ const theme = q.get('theme') || p.theme;
183287
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
183288
+ const ratio = q.get('ratio') || p.ratio || 'wide';
183289
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
183290
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
183291
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
183292
+ }
183293
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
183294
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
183295
+ if (q.get('demo') === '1') return;
183296
+ const b = window.__overrides?.brand;
183297
+ 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');
183298
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
183299
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
183300
+ 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');
183301
+ for (const role of fonts) {
183302
+ const font = b.fonts[role];
183303
+ 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);
183304
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
183305
+ }
183306
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
183307
+ };
183308
+ })();
183309
+
183310
+ (function () {
183311
+ const base = window.EB_VALIDATE_PARAMS;
183312
+ const roles = ["accent","atmo","bg","brown","chipA","chipB","core","drop","dry","ember","glow","ink","panel","smoke","titleSplit","upcoming","vapor"];
183313
+ const fontRoles = ["cap","credit","label","mono","monoB","title"];
183314
+ window.EB_VALIDATE_PARAMS = (params, query) => {
183315
+ base(params, query);
183316
+ if (query.get('demo') === '1') return;
183317
+ for (const role of roles) {
183318
+ 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.');
183319
+ }
183320
+ for (const role of fontRoles) {
183321
+ const font = window.__overrides?.brand?.fonts?.[role];
183322
+ 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.');
183323
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183324
+ }
183325
+ };
183326
+ })();
183327
+ `
183328
+ },
183329
+ "relato-ilustrado": {
183330
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
183331
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
183332
+ "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",
183333
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
183334
+ (function () {
183335
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
183336
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
183337
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
183338
+ const fonts = ['display','text','heavy','mono','hand'];
183339
+ window.EB_VALIDATE_PARAMS = (p, q) => {
183340
+ const theme = q.get('theme') || p.theme;
183341
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
183342
+ const ratio = q.get('ratio') || p.ratio || 'wide';
183343
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
183344
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
183345
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
183346
+ }
183347
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
183348
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
183349
+ if (q.get('demo') === '1') return;
183350
+ const b = window.__overrides?.brand;
183351
+ 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');
183352
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
183353
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
183354
+ 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');
183355
+ for (const role of fonts) {
183356
+ const font = b.fonts[role];
183357
+ 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);
183358
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
183359
+ }
183360
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
183361
+ };
183362
+ })();
183363
+
183364
+ (function () {
183365
+ const base = window.EB_VALIDATE_PARAMS;
183366
+ 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"];
183367
+ const fontRoles = ["cap","card","credit","heavy","label","note"];
183368
+ window.EB_VALIDATE_PARAMS = (params, query) => {
183369
+ base(params, query);
183370
+ if (query.get('demo') === '1') return;
183371
+ for (const role of roles) {
183372
+ 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.');
183373
+ }
183374
+ for (const role of fontRoles) {
183375
+ const font = window.__overrides?.brand?.fonts?.[role];
183376
+ 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.');
183377
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183378
+ }
183379
+ };
183380
+ })();
183381
+ `
183382
+ },
183383
+ "pizarra-minimalista": {
183384
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
183385
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
183386
+ "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",
183387
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
183388
+ (function () {
183389
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
183390
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
183391
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
183392
+ const fonts = ['display','text','heavy','mono','hand'];
183393
+ window.EB_VALIDATE_PARAMS = (p, q) => {
183394
+ const theme = q.get('theme') || p.theme;
183395
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
183396
+ const ratio = q.get('ratio') || p.ratio || 'wide';
183397
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
183398
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
183399
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
183400
+ }
183401
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
183402
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
183403
+ if (q.get('demo') === '1') return;
183404
+ const b = window.__overrides?.brand;
183405
+ 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');
183406
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
183407
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
183408
+ 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');
183409
+ for (const role of fonts) {
183410
+ const font = b.fonts[role];
183411
+ 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);
183412
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
183413
+ }
183414
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
183415
+ };
183416
+ })();
183417
+
183418
+ (function () {
183419
+ const base = window.EB_VALIDATE_PARAMS;
183420
+ const roles = ["bg","capFill","capShadow","capStroke","credit","dot","paperBottom","paperTop"];
183421
+ const fontRoles = ["caption","credit"];
183422
+ window.EB_VALIDATE_PARAMS = (params, query) => {
183423
+ base(params, query);
183424
+ if (query.get('demo') === '1') return;
183425
+ for (const role of roles) {
183426
+ 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.');
183427
+ }
183428
+ for (const role of fontRoles) {
183429
+ const font = window.__overrides?.brand?.fonts?.[role];
183430
+ 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.');
183431
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183432
+ }
183433
+ };
183434
+ })();
183435
+ `
183436
+ },
183437
+ "infografia-de-objetos": {
183438
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
183439
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
183440
+ "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",
183441
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
183442
+ (function () {
183443
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
183444
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
183445
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
183446
+ const fonts = ['display','text','heavy','mono','hand'];
183447
+ window.EB_VALIDATE_PARAMS = (p, q) => {
183448
+ const theme = q.get('theme') || p.theme;
183449
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
183450
+ const ratio = q.get('ratio') || p.ratio || 'wide';
183451
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
183452
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
183453
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
183454
+ }
183455
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
183456
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
183457
+ if (q.get('demo') === '1') return;
183458
+ const b = window.__overrides?.brand;
183459
+ 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');
183460
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
183461
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
183462
+ 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');
183463
+ for (const role of fonts) {
183464
+ const font = b.fonts[role];
183465
+ 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);
183466
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
183467
+ }
183468
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
183469
+ };
183470
+ })();
183471
+
183472
+ (function () {
183473
+ const base = window.EB_VALIDATE_PARAMS;
183474
+ 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"];
183475
+ const fontRoles = ["cap","heavy","mono","name","small"];
183476
+ window.EB_VALIDATE_PARAMS = (params, query) => {
183477
+ base(params, query);
183478
+ if (query.get('demo') === '1') return;
183479
+ for (const role of roles) {
183480
+ 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.');
183481
+ }
183482
+ for (const role of fontRoles) {
183483
+ const font = window.__overrides?.brand?.fonts?.[role];
183484
+ 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.');
183485
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183486
+ }
183487
+ };
183488
+ })();
183489
+ `
183490
+ },
183491
+ "ranking-con-escala": {
183492
+ "runtimeSha256": "aa8d22988d8ff149aac5765f021bc4412186b8fae33c00c3d48218894ff19e71",
183493
+ "adaptedRuntimeSha256": "4e0862005eef5fb62860d635756d45e0218e13f0f59342726553cc978320cece",
183494
+ "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",
183495
+ "guard": `// Portable safety wrapper; original scene source is separately hashed.
183496
+ (function () {
183497
+ const fail = message => { throw new Error('EditorBrain project binding: ' + message); };
183498
+ const record = value => value && typeof value === 'object' && !Array.isArray(value);
183499
+ const colors = ['bg','surface','ink','muted','line','accent','accent2','pos','neg'];
183500
+ const fonts = ['display','text','heavy','mono','hand'];
183501
+ window.EB_VALIDATE_PARAMS = (p, q) => {
183502
+ const theme = q.get('theme') || p.theme;
183503
+ if (!Object.hasOwn(window.EB_THEMES || {}, theme)) fail('unknown theme');
183504
+ const ratio = q.get('ratio') || p.ratio || 'wide';
183505
+ if (!['wide','square','tall'].includes(ratio)) fail('unknown ratio');
183506
+ for (const [key, min, max] of [['duration',0.1,300],['fps',1,60],['timeScale',0.1,10]]) {
183507
+ if (p[key] !== undefined && (typeof p[key] !== 'number' || !Number.isFinite(p[key]) || p[key] < min || p[key] > max)) fail(key + ' outside supported range');
183508
+ }
183509
+ if ((p.timeScale ?? 1) !== 1 && (p.sound?.voice || p.sound?.music)) fail('voice/music require timeScale=1 until explicit audio retiming is implemented');
183510
+ if (p.sound?.enabled !== undefined && typeof p.sound.enabled !== 'boolean') fail('sound.enabled must be boolean');
183511
+ if (q.get('demo') === '1') return;
183512
+ const b = window.__overrides?.brand;
183513
+ 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');
183514
+ for (const role of colors) if (!/^#[0-9a-f]{6}$/i.test(b.colors[role] || '')) fail('missing color role ' + role);
183515
+ if (typeof b.colors.dark !== 'boolean') fail('colors.dark must be explicit');
183516
+ 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');
183517
+ for (const role of fonts) {
183518
+ const font = b.fonts[role];
183519
+ 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);
183520
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) fail('register local font files in EB_FONTS: ' + font.family);
183521
+ }
183522
+ if (!record(window.__overrides.sound) || typeof window.__overrides.sound.enabled !== 'boolean') fail('set sound.enabled from project preferences');
183523
+ };
183524
+ })();
183525
+
183526
+ (function () {
183527
+ const base = window.EB_VALIDATE_PARAMS;
183528
+ const roles = ["bg","credit","hookBox","hookInk","pill","pillInk","scaleInk","scoreInk","title"];
183529
+ const fontRoles = ["credit","hook","pill","scale","score","title"];
183530
+ window.EB_VALIDATE_PARAMS = (params, query) => {
183531
+ base(params, query);
183532
+ if (query.get('demo') === '1') return;
183533
+ for (const role of roles) {
183534
+ 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.');
183535
+ }
183536
+ for (const role of fontRoles) {
183537
+ const font = window.__overrides?.brand?.fonts?.[role];
183538
+ 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.');
183539
+ if (!Object.hasOwn(window.EB_FONTS || {}, font.family)) throw new Error('EditorBrain project binding: register local font files for role ' + role + ': ' + font.family);
183540
+ }
183541
+ };
183542
+ })();
183543
+ `
183544
+ }
183545
+ };
183546
+
183547
+ // packages/cli/src/style-sources.ts
183548
+ async function downloadStyle(client, id2, version, root, out) {
183549
+ const result2 = await client.request("/v1/style-packs");
183550
+ const selected = result2.sourceStyles?.find((s) => s.id === id2 && s.sourceVersion === version);
183551
+ if (!selected) throw new Error("Exact style source not advertised by the service. Update EditorBrain or choose an available version; do not reconstruct silently.");
183552
+ return downloadPinnedSource(client, { id: id2, version, sha256: selected.sourceSha256, bytes: selected.sourceBytes }, root, out, "style");
183553
+ }
183554
+ async function prepareStyleSource(root, id2, version, file, out) {
183555
+ const selected = getStyleSource(id2, version), guard = styleSourceGuards[id2];
183556
+ if (!selected || !guard) throw new Error("This CLI cannot prepare the exact style version. Update EditorBrain; no version was substituted.");
183557
+ const input = await checkedPath(root, file, false), handle = await open3(input, constants2.O_RDONLY | constants2.O_NOFOLLOW);
183558
+ let bytes;
183559
+ try {
183560
+ const stat = await handle.stat();
183561
+ if (!stat.isFile() || stat.size !== selected.sourceBytes || stat.size > STYLE_SOURCE_MAX_BYTES) throw new Error("Style archive size mismatch");
183562
+ bytes = await handle.readFile();
183563
+ } finally {
183564
+ await handle.close();
183565
+ }
183566
+ const { files } = readStyleArchive(bytes, { id: id2, version, sha256: selected.sourceSha256, bytes: selected.sourceBytes, fileCount: selected.fileCount, unpackedBytes: selected.unpackedBytes });
183567
+ const entry = `styles/${id2}/scene.html`, originalRuntime = files.get("lib/runtime.js");
183568
+ if (!originalRuntime || archiveHash(originalRuntime) !== guard.runtimeSha256 || archiveHash(guard.runtime) !== guard.adaptedRuntimeSha256) throw new Error("Runtime guard pin mismatch");
183569
+ const html = files.get(entry)?.toString("utf8"), marker = '<script src="../../lib/runtime.js"></script>';
183570
+ if (!html || html.split(marker).length !== 2) throw new Error("Unsupported scene entrypoint");
183571
+ files.set(entry, Buffer.from(html.replace(marker, '<script src="../../lib/project-binding.js"></script>\n' + marker)));
183572
+ files.set("lib/runtime.js", Buffer.from(guard.runtime));
183573
+ files.set("lib/project-binding.js", Buffer.from(guard.guard));
183574
+ const guide = `# Copia de trabajo protegida
183575
+
183576
+ 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.
183577
+
183578
+ 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.
183579
+
183580
+ 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.
183581
+
183582
+ 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.
183583
+
183584
+ 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.
183585
+
183586
+ Un render de demo no certifica transferencia. Revisa el video completo y registra la revisi\xF3n antes de entregar.
183587
+ `;
183588
+ 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 };
183589
+ files.set("PROJECT-BINDING.md", Buffer.from(guide));
183590
+ files.set("PROJECT-BINDING.json", Buffer.from(JSON.stringify(receipt, null, 2) + "\n"));
183591
+ const target = await checkedPath(root, out, false);
183592
+ await mkdir3(dirname3(target), { recursive: true });
183593
+ await checkedPath(root, out, false);
183594
+ await mkdir3(target, { mode: 448 });
183595
+ try {
183596
+ for (const [name, data] of files) {
183597
+ const destination = await checkedPath(target, name, false);
183598
+ await mkdir3(dirname3(destination), { recursive: true });
183599
+ await writeFile(destination, data, { flag: "wx", mode: 384 });
183600
+ }
183601
+ } catch (error) {
183602
+ await rm(target, { recursive: true, force: true });
183603
+ throw error;
183604
+ }
183605
+ 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." };
183606
+ }
183607
+
183608
+ // packages/cli/src/team-command.ts
183609
+ async function teamCommand(client, subcommand, flags) {
183610
+ const value = (key) => {
183611
+ const v = flags[key];
183612
+ return typeof v === "string" ? v : void 0;
183613
+ };
183614
+ const required = (key) => {
183615
+ const v = value(key);
183616
+ if (!v) throw new Error(`Missing --${key}`);
183617
+ return v;
183618
+ };
183619
+ const common = ["url", "dir"];
183620
+ const allowed = {
183621
+ access: [],
183622
+ members: [],
183623
+ projects: [],
183624
+ invite: ["email", "kind", "scope"],
183625
+ cancel: ["id"],
183626
+ remove: ["user", "confirm"],
183627
+ reviews: ["project", "after"],
183628
+ share: ["project", "revision", "confirm"],
183629
+ withdraw: ["project", "revision", "confirm"],
183630
+ comment: ["project", "revision", "context-version", "text", "at-ms", "id"],
183631
+ approve: ["project", "revision", "context-version", "user-confirmed"]
183632
+ };
183633
+ if (!subcommand || !allowed[subcommand])
183634
+ throw new Error(
183635
+ "Use team access|members|projects|invite|cancel|remove|reviews|share|withdraw|comment|approve."
183636
+ );
183637
+ for (const key of Object.keys(flags))
183638
+ if (!common.includes(key) && !allowed[subcommand].includes(key))
183639
+ throw new Error(`--${key} is not supported for team ${subcommand}.`);
183640
+ if (subcommand === "access") return client.request("/v1/team");
183641
+ if (["members", "projects"].includes(subcommand))
183642
+ return client.request("/v1/team/" + subcommand);
183643
+ if (subcommand === "invite") {
183644
+ const kind = required("kind");
183645
+ if (!["brand_editor", "project_reviewer"].includes(kind))
183646
+ throw new Error("Use --kind brand_editor or project_reviewer.");
183647
+ return client.request("/v1/team/invitations", {
183648
+ method: "POST",
183649
+ body: { email: required("email"), kind, scopeId: required("scope") }
183650
+ });
183651
+ }
183652
+ if (subcommand === "cancel")
183653
+ return client.request(
183654
+ "/v1/team/invitations/" + encodeURIComponent(required("id")),
183655
+ { method: "DELETE" }
183656
+ );
183657
+ if (subcommand === "remove") {
183658
+ if (flags.confirm !== true)
183659
+ throw new Error(
183660
+ "Removing access requires --confirm after the user requests removal. Files are preserved."
183661
+ );
183662
+ return client.request(
183663
+ "/v1/team/members/" + encodeURIComponent(required("user")),
183664
+ { method: "DELETE" }
183665
+ );
183666
+ }
183667
+ const base = "/v1/team/projects/" + encodeURIComponent(required("project")) + "/reviews";
183668
+ if (subcommand === "reviews")
183669
+ return client.request(
183670
+ base + (value("after") ? "?after=" + encodeURIComponent(value("after")) : "")
183671
+ );
183672
+ const revision2 = required("revision");
183673
+ if (!/^[a-f0-9-]{36}$/.test(revision2))
183674
+ throw new Error("Use the exact revision UUID returned by team reviews.");
183675
+ if (["share", "withdraw"].includes(subcommand)) {
183676
+ if (flags.confirm !== true)
183677
+ throw new Error(
183678
+ "Use --confirm for an explicitly requested sharing change."
183679
+ );
183680
+ return client.request(base + "/" + revision2 + "/share", {
183681
+ method: "POST",
183682
+ body: { shared: subcommand === "share" }
183683
+ });
183684
+ }
183685
+ const contextVersion = required("context-version");
183686
+ if (!/^[a-f0-9]{64}$/.test(contextVersion))
183687
+ throw new Error("Use the exact context hash of the reviewed sample.");
183688
+ if (subcommand === "approve") {
183689
+ if (flags["user-confirmed"] !== true)
183690
+ throw new Error(
183691
+ "Approval requires explicit user acceptance and --user-confirmed."
183692
+ );
183693
+ return client.request(base + "/" + revision2 + "/approve", {
183694
+ method: "POST",
183695
+ body: { contextVersion, userConfirmed: true }
183696
+ });
183697
+ }
183698
+ const at = value("at-ms"), startMs = at === void 0 ? void 0 : Number(at);
183699
+ if (startMs !== void 0 && (!Number.isSafeInteger(startMs) || startMs < 0 || startMs > 36e6))
183700
+ throw new Error("--at-ms must be an integer between 0 and 36000000.");
183701
+ const feedbackId = required("id");
183702
+ if (!/^[a-f0-9-]{36}$/.test(feedbackId))
183703
+ throw new Error(
183704
+ "Use --id with a fresh UUID; reuse it for retries of this exact comment."
183705
+ );
183706
+ return client.request(base + "/" + revision2 + "/comment", {
183707
+ method: "POST",
183708
+ body: {
183709
+ contextVersion,
183710
+ feedbackId,
183711
+ text: required("text"),
183712
+ target: startMs === void 0 ? {} : { startMs }
183713
+ }
183714
+ });
183715
+ }
183716
+
183717
+ // packages/cli/src/personal-resources.ts
183718
+ import { basename, extname as extname2, resolve as resolve3 } from "node:path";
183719
+ import { randomUUID as randomUUID3 } from "node:crypto";
183720
+
182045
183721
  // packages/cli/src/media-runtime.ts
182046
183722
  import { spawn } from "node:child_process";
182047
- import { createHash } from "node:crypto";
182048
- import { constants } from "node:fs";
182049
- import { lstat, open, realpath } from "node:fs/promises";
182050
- import { dirname, extname, parse, resolve } from "node:path";
183723
+ import { createHash as createHash3 } from "node:crypto";
183724
+ import { constants as constants3 } from "node:fs";
183725
+ import { lstat as lstat3, open as open4, realpath as realpath2 } from "node:fs/promises";
183726
+ import { dirname as dirname4, extname, parse, resolve as resolve2 } from "node:path";
182051
183727
  var MediaToolError = class extends CliError {
182052
183728
  constructor(code, message) {
182053
183729
  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.");
@@ -182099,24 +183775,24 @@ function resolveLocalMediaPath(value) {
182099
183775
  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("\\\\")) {
182100
183776
  throw new MediaToolError("MEDIA_LOCAL_PATH_REQUIRED", "Provide a local filesystem path, not a URL, protocol or network share.");
182101
183777
  }
182102
- return resolve(value);
183778
+ return resolve2(value);
182103
183779
  }
182104
183780
  async function assertNoMediaSymlinks(value) {
182105
183781
  const path = resolveLocalMediaPath(value);
182106
183782
  let cursor = path;
182107
183783
  while (cursor !== parse(cursor).root) {
182108
- const info = await lstat(cursor);
183784
+ const info = await lstat3(cursor);
182109
183785
  if (info.isSymbolicLink()) {
182110
- const systemAlias = process.platform === "darwin" && (cursor === "/tmp" || cursor === "/var") && await realpath(cursor) === `/private${cursor}`;
183786
+ const systemAlias = process.platform === "darwin" && (cursor === "/tmp" || cursor === "/var") && await realpath2(cursor) === `/private${cursor}`;
182111
183787
  if (!systemAlias) throw new MediaToolError("MEDIA_SYMLINK", "Symlink media paths are not followed. Use the original local path.");
182112
183788
  }
182113
- cursor = dirname(cursor);
183789
+ cursor = dirname4(cursor);
182114
183790
  }
182115
183791
  return path;
182116
183792
  }
182117
183793
  async function assertLocalMediaFile(value) {
182118
183794
  const path = await assertNoMediaSymlinks(value);
182119
- const info = await lstat(path);
183795
+ const info = await lstat3(path);
182120
183796
  if (!info.isFile()) throw new MediaToolError("MEDIA_NOT_REGULAR", "The media input must be a regular local file.");
182121
183797
  if (!SUPPORTED_MEDIA_EXTENSIONS.has(extname(path).toLowerCase())) throw new MediaToolError("MEDIA_FORMAT_UNSUPPORTED", "This file extension is not supported for local media inspection.");
182122
183798
  return path;
@@ -182215,17 +183891,17 @@ function hasDisplayTransform(stream) {
182215
183891
  }
182216
183892
  async function probeLocalMedia(value) {
182217
183893
  const path = await assertLocalMediaFile(value);
182218
- const handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
183894
+ const handle = await open4(path, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
182219
183895
  try {
182220
183896
  const before = await handle.stat();
182221
183897
  if (!before.isFile()) throw new MediaToolError("MEDIA_NOT_REGULAR", "The media input must be a regular local file.");
182222
183898
  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";
182223
183899
  const { stdout } = await runMediaTool("ffprobe", ["-v", "error", "-show_entries", entries, "-of", "json", ...localInputArgs(path)]);
182224
- const hash6 = createHash("sha256");
183900
+ const hash6 = createHash3("sha256");
182225
183901
  for await (const chunk of handle.createReadStream({ autoClose: false })) hash6.update(chunk);
182226
183902
  const after = await handle.stat();
182227
183903
  await assertNoMediaSymlinks(path);
182228
- const current2 = await lstat(path);
183904
+ const current2 = await lstat3(path);
182229
183905
  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.");
182230
183906
  let raw;
182231
183907
  try {
@@ -182253,125 +183929,10 @@ async function probeLocalMedia(value) {
182253
183929
  }
182254
183930
  }
182255
183931
 
182256
- // packages/cli/src/io.ts
182257
- import { constants as constants2 } from "node:fs";
182258
- import { lstat as lstat2, mkdir, open as open2, readdir, realpath as realpath2, rename, unlink, link } from "node:fs/promises";
182259
- import { dirname as dirname2, join, relative, resolve as resolve2, sep } from "node:path";
182260
- import { randomUUID } from "node:crypto";
182261
- async function ensureRoot(directory, create = false) {
182262
- const root = resolve2(directory);
182263
- if (create) await mkdir(root, { recursive: true });
182264
- const info = await lstat2(root);
182265
- if (info.isSymbolicLink() || !info.isDirectory()) throw new Error("Workspace root must be a real directory, not a symlink");
182266
- return realpath2(root);
182267
- }
182268
- async function checkedPath(root, path, document2 = true) {
182269
- if (document2) safeDocumentPath(path);
182270
- const target = resolve2(root, path);
182271
- const rel = relative(root, target);
182272
- if (!rel || rel.startsWith(`..${sep}`) || rel === ".." || resolve2(path) === path) throw new Error("Path escapes workspace");
182273
- let cursor = root;
182274
- for (const segment of rel.split(sep)) {
182275
- cursor = join(cursor, segment);
182276
- try {
182277
- const info = await lstat2(cursor);
182278
- if (info.isSymbolicLink()) throw new Error(`Symlinks are not allowed: ${path}`);
182279
- } catch (error) {
182280
- if (error.code !== "ENOENT") throw error;
182281
- }
182282
- }
182283
- return target;
182284
- }
182285
- async function readText(root, path, document2 = true) {
182286
- const target = await checkedPath(root, path, document2);
182287
- const handle = await open2(target, constants2.O_RDONLY | constants2.O_NOFOLLOW);
182288
- try {
182289
- const info = await handle.stat();
182290
- if (!info.isFile()) throw new Error(`Not a regular file: ${path}`);
182291
- if (document2 && info.size > MAX_DOCUMENT_BYTES) throw new Error(`Document exceeds 128 KiB: ${path}`);
182292
- return new TextDecoder("utf-8", { fatal: true }).decode(await handle.readFile());
182293
- } finally {
182294
- await handle.close();
182295
- }
182296
- }
182297
- async function atomicWrite(root, path, content, options = {}) {
182298
- const target = await checkedPath(root, path, options.document ?? true);
182299
- await mkdir(dirname2(target), { recursive: true });
182300
- await checkedPath(root, path, options.document ?? true);
182301
- const temporary = join(dirname2(target), `.eh-${randomUUID()}.tmp`);
182302
- const handle = await open2(temporary, "wx", options.mode ?? 420);
182303
- try {
182304
- await handle.writeFile(content, "utf8");
182305
- await handle.close();
182306
- await checkedPath(root, path, options.document ?? true);
182307
- if (options.overwrite === false) {
182308
- await link(temporary, target);
182309
- await unlink(temporary);
182310
- } else await rename(temporary, target);
182311
- } catch (error) {
182312
- await handle.close().catch(() => {
182313
- });
182314
- await unlink(temporary).catch(() => {
182315
- });
182316
- throw error;
182317
- }
182318
- }
182319
- async function readWorkspace(root) {
182320
- const files = /* @__PURE__ */ Object.create(null);
182321
- async function walk(path) {
182322
- const directory = await checkedPath(root, path, false);
182323
- let entries;
182324
- try {
182325
- entries = await readdir(directory, { withFileTypes: true });
182326
- } catch (error) {
182327
- if (error.code === "ENOENT") return;
182328
- throw error;
182329
- }
182330
- for (const entry of entries) {
182331
- const child = `${path}/${entry.name}`;
182332
- if (entry.isSymbolicLink()) throw new Error(`Symlinks are not allowed: ${child}`);
182333
- if (entry.name.startsWith(".")) continue;
182334
- if (entry.isDirectory()) {
182335
- if (path.startsWith("videos/") && ["assets", "renders"].includes(entry.name)) continue;
182336
- await walk(child);
182337
- } else if (entry.isFile() && /\.(json|md)$/.test(entry.name)) {
182338
- safeDocumentPath(child);
182339
- files[child] = await readText(root, child);
182340
- }
182341
- }
182342
- }
182343
- await walk(".editorharness");
182344
- await walk(".editorbrain");
182345
- await walk("videos");
182346
- return canonicalFiles(files);
182347
- }
182348
- async function readProjectWorkspace(root, projectId) {
182349
- assertIdentifier(projectId);
182350
- const projectPath = `videos/${projectId}/project.json`;
182351
- const projectContent = await readText(root, projectPath);
182352
- const checked = validateDocument(projectPath, projectContent);
182353
- if (!checked.valid) throw new ValidationError(checked.issues);
182354
- const project = JSON.parse(projectContent);
182355
- const files = { [projectPath]: projectContent };
182356
- for (const path of /* @__PURE__ */ new Set([...projectSources(project), ...optionalProjectSources(project)])) {
182357
- if (path === projectPath) continue;
182358
- const aliases2 = path.startsWith(".editorbrain/") ? [path, path.replace(/^\.editorbrain\//, ".editorharness/")] : [path];
182359
- for (const alias of aliases2) {
182360
- try {
182361
- files[alias] = await readText(root, alias);
182362
- } catch (error) {
182363
- if (error.code !== "ENOENT") throw error;
182364
- }
182365
- }
182366
- }
182367
- if (await readText(root, projectPath) !== projectContent) throw new Error("The selected project changed while reading its context. Retry before editing.");
182368
- return canonicalFiles(files);
182369
- }
182370
-
182371
183932
  // packages/cli/src/production-output.ts
182372
- import { constants as constants3 } from "node:fs";
182373
- import { mkdir as mkdir2, open as open3 } from "node:fs/promises";
182374
- import { dirname as dirname3 } from "node:path";
183933
+ import { constants as constants4 } from "node:fs";
183934
+ import { mkdir as mkdir4, open as open5 } from "node:fs/promises";
183935
+ import { dirname as dirname5 } from "node:path";
182375
183936
  async function productionOutputPath(root, relativePath) {
182376
183937
  if (!relativePath.startsWith(".editorbrain-local/") || relativePath.split(/[\\/]/).some((p) => !p || p === ".." || p === ".") || /[\\\x00-\x1f\x7f]/.test(relativePath)) {
182377
183938
  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.");
@@ -182380,13 +183941,13 @@ async function productionOutputPath(root, relativePath) {
182380
183941
  }
182381
183942
  async function prepareSampleDirectory(root, path) {
182382
183943
  const target = await productionOutputPath(root, path);
182383
- await mkdir2(dirname3(target), { recursive: true });
183944
+ await mkdir4(dirname5(target), { recursive: true });
182384
183945
  await productionOutputPath(root, path);
182385
183946
  return target;
182386
183947
  }
182387
183948
  async function readProductionJson(root, path) {
182388
183949
  const target = await checkedPath(root, path, false);
182389
- const handle = await open3(target, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
183950
+ const handle = await open5(target, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
182390
183951
  try {
182391
183952
  const stat = await handle.stat();
182392
183953
  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.");
@@ -182524,7 +184085,7 @@ async function registerLocalResource(client, root, file, options = {}) {
182524
184085
  } while (!existing && after);
182525
184086
  if (existing) break;
182526
184087
  }
182527
- const id2 = existing?.id ?? randomUUID2();
184088
+ const id2 = existing?.id ?? randomUUID3();
182528
184089
  const result2 = existing ? await client.request("/v1/resources/" + id2) : await client.request("/v1/resources/" + id2, { method: "PUT", body: { resource, expectedRevision: 0 } });
182529
184090
  const me = await client.request("/v1/me");
182530
184091
  const namespace = (await sha256(client.url + "\n" + me.workspaceId)).slice(0, 32), path = `.editorbrain-local/resources/${namespace}/${id2}.json`;
@@ -182615,15 +184176,15 @@ async function personalResourceCommand(client, root, command, arg, flags) {
182615
184176
 
182616
184177
  // packages/cli/src/update.ts
182617
184178
  import { execFile } from "node:child_process";
182618
- import { lstat as lstat6, readFile as readFile3, realpath as realpath3 } from "node:fs/promises";
184179
+ import { lstat as lstat7, readFile as readFile3, realpath as realpath3 } from "node:fs/promises";
182619
184180
  import { homedir as homedir2 } from "node:os";
182620
- import { delimiter, dirname as dirname4, join as join3, resolve as resolve5 } from "node:path";
184181
+ import { delimiter, dirname as dirname6, join as join5, resolve as resolve5 } from "node:path";
182621
184182
  import { promisify } from "node:util";
182622
184183
 
182623
184184
  // packages/cli/src/agent-guidance.ts
182624
- import { createHash as createHash2 } from "node:crypto";
182625
- import { constants as constants4 } from "node:fs";
182626
- import { lstat as lstat3, open as open4, readdir as readdir2, rename as rename2 } from "node:fs/promises";
184185
+ import { createHash as createHash4 } from "node:crypto";
184186
+ import { constants as constants5 } from "node:fs";
184187
+ import { lstat as lstat4, open as open6, readdir as readdir2, rename as rename2 } from "node:fs/promises";
182627
184188
  import { fileURLToPath } from "node:url";
182628
184189
 
182629
184190
  // packages/cli/src/agent-guidance-history.ts
@@ -183121,6 +184682,95 @@ var VERIFIED_GUIDANCE_RELEASES = [
183121
184682
  "editorbrain/references/style-creator.md": "1b1bc289a5bc308cbbf7f4d699de2933b8934733a2b69b3e98fb1b7420d986f2",
183122
184683
  "editorbrain/references/workspace-files.md": "29bbddc894ed000bddd065bcb660629e64b29a5cf54dd6850e810b25c990558d"
183123
184684
  }
184685
+ },
184686
+ {
184687
+ "version": "0.39.1",
184688
+ "archiveSha256": "d53f7a9d09b265d0157476840896586b4814dbfdfc460e00c7498e4354cffb28",
184689
+ "files": {
184690
+ "editorbrain-formats/SKILL.md": "65ea59aae091ca9618b5e479befe0c76edf174df7091ed74d4307485a2252fcd",
184691
+ "editorbrain-formats/references/aspirational-list-demo.md": "e884ce44d15f4496812ed18120f7d4c49c4261e148fcefe05c77c110b589771c",
184692
+ "editorbrain-formats/references/cumulative-tier-list.md": "7b7e8208687c6b925443e55d640ced6c1d09824377884244a09d7f3089d60aa5",
184693
+ "editorbrain-formats/references/numbered-tutorial.md": "95754ae7dbfaa678e11ddf1a2b84710dba83a16e2fa4055051bd4f5f4f868a5f",
184694
+ "editorbrain-motion/SKILL.md": "7c27051ae2b7597e45cfafaecb37be79a7cd9bd9788ae515723dbc20c2f34a37",
184695
+ "editorbrain-motion/references/authored-scenes.md": "1056007808a76e2eb02df9ed11cdd1f464e26e2981111e87ce965efb7937fed0",
184696
+ "editorbrain-motion/references/code-motion.md": "50382a797adc1e1596086e2408e81ee75ceb6730ca409be9c884646db643a7cd",
184697
+ "editorbrain-motion/references/component-library.md": "e88ed19d2ab9dca8d2ea02abe6c476021c03b9679bce99292cf7da52d65d2236",
184698
+ "editorbrain-motion/references/generated-motion.md": "a8d214b53c15f742658abd84f03b768fa2821f8cde94f50aab82a3759a30b36b",
184699
+ "editorbrain-motion/references/motion-craft.md": "dae520b0e641fc9c3bf937241936588a855bf3453358e239ccc3cc3a2bcf0825",
184700
+ "editorbrain/AGENTS.md": "b240449d452c824415062a2b422bf55a5ae2d868a81083989d10ffaeb5c33a3f",
184701
+ "editorbrain/SKILL.md": "9236cc479e4b90b1a8a6c1ead279db7293a95fa8f1cc1fbffcffe6957f1d50d0",
184702
+ "editorbrain/references/audio-production.md": "9800505dcb320b58f35aeaed77303039d8fffb2c29b46c43cedeeba8637d2482",
184703
+ "editorbrain/references/cli-mcp.md": "3e2b27e45050410da9d0e425fd90ef816579d3c39331e7cb83b81c5862d8e7de",
184704
+ "editorbrain/references/editorial-evidence.md": "16ce55316b330e5fec85654012ccbdd78ec1175bfd092762638c93c57d845a72",
184705
+ "editorbrain/references/editorial-families.md": "b802ec6f02fd079e99df84d69a3c515d63ad058960b568c0c7b7dec1912495dd",
184706
+ "editorbrain/references/family-animated.md": "54a140d0a64b01147c52ea8cbaab4e4599bfe1af330f5a3ad6ef2a30351ab47d",
184707
+ "editorbrain/references/family-demonstration.md": "737334a8d9230682cde3a6ed11bfc02c4f9795c8f25a3b668be9d7393ec3e53d",
184708
+ "editorbrain/references/family-essay.md": "003f2cd450f33ba6641a9b1114cbc578c04cbb658b992c89c765d43198d1b4c2",
184709
+ "editorbrain/references/family-personal.md": "e93c304d7bc7d3eb31a3c9cb3be83f4f48d41319c2ac2e1e6f53f38576f5e644",
184710
+ "editorbrain/references/family-presenter.md": "76b8140b924930b306ce97772d6a7b683870bd14f19772b5339a490752b7de24",
184711
+ "editorbrain/references/first-edit.md": "c8986ec896941c70b0267da672691170de3e34253ead838b4dc28758e661c9ea",
184712
+ "editorbrain/references/integrations.md": "b5e7ba099acd79053cdd09822092eb121add6de39eada2d6911ad5a4f452ce2a",
184713
+ "editorbrain/references/local-production.md": "268a05706a3c1cae4f61248437c00be3e9ee18b2a0f747c8cd054d88f0a33661",
184714
+ "editorbrain/references/media-preferences.md": "87e508a75cdb6f4644db767273bfb230fb79f182ed05ee0f6257c6c05ea4dc7a",
184715
+ "editorbrain/references/memory-and-review.md": "406589a18e9e86ad8ce7d71e0f5bf00f67dab42c05af7721482fdca1c25c7c1b",
184716
+ "editorbrain/references/motion-review.md": "0fb09a2d61ecd13114ced5cca5daa4580a922cf7d7b3f8698077ceb0e96da6f0",
184717
+ "editorbrain/references/onboarding.md": "2cb212c60f26c6877a865170cf5a52091243ca374f0f8e93dad9ebfbf0427ed1",
184718
+ "editorbrain/references/personal-resources.md": "92ce6f32191929bd946c97305452521f6048d6bb8ea371e9083536eff5ce9512",
184719
+ "editorbrain/references/production-and-review.md": "28a64ee6407a1de7dc204776c158408c11b3987020ad1bdd1b79fd19745fbffa",
184720
+ "editorbrain/references/production-continuity.md": "b73a851bff421fa24e364d8848e312e54de1d3d971099a567295c80a5e18d8c6",
184721
+ "editorbrain/references/real-media.md": "cfad1aa15198dfe5ecc1f1b67c96d43a7d2084e7f5119de93d1b360203694938",
184722
+ "editorbrain/references/search-brief.md": "ea2a9c2d5a5cf685c1e5918366901ef2589c4d79aaa78a0dd31e97d6fed42b7b",
184723
+ "editorbrain/references/sfx-library.md": "d7ee0d2916559ce11a7fd244ccbcb98172413653c3fdbe0545e57b3eda543b16",
184724
+ "editorbrain/references/storage-and-previews.md": "9d06a6bb49f13e23f0af7d5ef35444dd553d1ce8af28662a9aba054b4d0081a5",
184725
+ "editorbrain/references/studio.md": "dfea5aa070e5e600f27a2983530c816d9f77b15f7bcec02c02301d6969b11fe8",
184726
+ "editorbrain/references/style-creator.md": "1b1bc289a5bc308cbbf7f4d699de2933b8934733a2b69b3e98fb1b7420d986f2",
184727
+ "editorbrain/references/workspace-files.md": "29bbddc894ed000bddd065bcb660629e64b29a5cf54dd6850e810b25c990558d"
184728
+ }
184729
+ },
184730
+ {
184731
+ "version": "0.40.1",
184732
+ "archiveSha256": "3693f4edcf54ab705177f4fb5bac1cafc79182d5cb85aaf4594e644dbb6261c7",
184733
+ "files": {
184734
+ "editorbrain-formats/SKILL.md": "65ea59aae091ca9618b5e479befe0c76edf174df7091ed74d4307485a2252fcd",
184735
+ "editorbrain-formats/references/aspirational-list-demo.md": "e884ce44d15f4496812ed18120f7d4c49c4261e148fcefe05c77c110b589771c",
184736
+ "editorbrain-formats/references/cumulative-tier-list.md": "7b7e8208687c6b925443e55d640ced6c1d09824377884244a09d7f3089d60aa5",
184737
+ "editorbrain-formats/references/numbered-tutorial.md": "95754ae7dbfaa678e11ddf1a2b84710dba83a16e2fa4055051bd4f5f4f868a5f",
184738
+ "editorbrain-motion/SKILL.md": "7c27051ae2b7597e45cfafaecb37be79a7cd9bd9788ae515723dbc20c2f34a37",
184739
+ "editorbrain-motion/references/authored-scenes.md": "52e97b89b1d8a288c4ce7bd133eafea84e934ef2bf03ffe2dcef8c368b6f977d",
184740
+ "editorbrain-motion/references/code-motion.md": "50382a797adc1e1596086e2408e81ee75ceb6730ca409be9c884646db643a7cd",
184741
+ "editorbrain-motion/references/component-library.md": "e88ed19d2ab9dca8d2ea02abe6c476021c03b9679bce99292cf7da52d65d2236",
184742
+ "editorbrain-motion/references/generated-motion.md": "a8d214b53c15f742658abd84f03b768fa2821f8cde94f50aab82a3759a30b36b",
184743
+ "editorbrain-motion/references/motion-craft.md": "dae520b0e641fc9c3bf937241936588a855bf3453358e239ccc3cc3a2bcf0825",
184744
+ "editorbrain/AGENTS.md": "b240449d452c824415062a2b422bf55a5ae2d868a81083989d10ffaeb5c33a3f",
184745
+ "editorbrain/SKILL.md": "1fed72fafd89407a8750eda7a663b6a0100de51fdbbb57a41b39d36489bd09d3",
184746
+ "editorbrain/references/audio-production.md": "9800505dcb320b58f35aeaed77303039d8fffb2c29b46c43cedeeba8637d2482",
184747
+ "editorbrain/references/cli-mcp.md": "3e2b27e45050410da9d0e425fd90ef816579d3c39331e7cb83b81c5862d8e7de",
184748
+ "editorbrain/references/editorial-evidence.md": "16ce55316b330e5fec85654012ccbdd78ec1175bfd092762638c93c57d845a72",
184749
+ "editorbrain/references/editorial-families.md": "b802ec6f02fd079e99df84d69a3c515d63ad058960b568c0c7b7dec1912495dd",
184750
+ "editorbrain/references/family-animated.md": "54a140d0a64b01147c52ea8cbaab4e4599bfe1af330f5a3ad6ef2a30351ab47d",
184751
+ "editorbrain/references/family-demonstration.md": "737334a8d9230682cde3a6ed11bfc02c4f9795c8f25a3b668be9d7393ec3e53d",
184752
+ "editorbrain/references/family-essay.md": "003f2cd450f33ba6641a9b1114cbc578c04cbb658b992c89c765d43198d1b4c2",
184753
+ "editorbrain/references/family-personal.md": "e93c304d7bc7d3eb31a3c9cb3be83f4f48d41319c2ac2e1e6f53f38576f5e644",
184754
+ "editorbrain/references/family-presenter.md": "76b8140b924930b306ce97772d6a7b683870bd14f19772b5339a490752b7de24",
184755
+ "editorbrain/references/first-edit.md": "483843af6672b70a76ce6d41e98324fbfc2a31d5ac50633f963d1ab0eeba1bc0",
184756
+ "editorbrain/references/integrations.md": "b5e7ba099acd79053cdd09822092eb121add6de39eada2d6911ad5a4f452ce2a",
184757
+ "editorbrain/references/local-production.md": "268a05706a3c1cae4f61248437c00be3e9ee18b2a0f747c8cd054d88f0a33661",
184758
+ "editorbrain/references/media-preferences.md": "87e508a75cdb6f4644db767273bfb230fb79f182ed05ee0f6257c6c05ea4dc7a",
184759
+ "editorbrain/references/memory-and-review.md": "406589a18e9e86ad8ce7d71e0f5bf00f67dab42c05af7721482fdca1c25c7c1b",
184760
+ "editorbrain/references/motion-review.md": "0fb09a2d61ecd13114ced5cca5daa4580a922cf7d7b3f8698077ceb0e96da6f0",
184761
+ "editorbrain/references/onboarding.md": "fbed6ff607859ffaa43d3006e457e40bb170885cde7ce350e496b20d70739e63",
184762
+ "editorbrain/references/personal-resources.md": "92ce6f32191929bd946c97305452521f6048d6bb8ea371e9083536eff5ce9512",
184763
+ "editorbrain/references/production-and-review.md": "28a64ee6407a1de7dc204776c158408c11b3987020ad1bdd1b79fd19745fbffa",
184764
+ "editorbrain/references/production-continuity.md": "b73a851bff421fa24e364d8848e312e54de1d3d971099a567295c80a5e18d8c6",
184765
+ "editorbrain/references/real-media.md": "cfad1aa15198dfe5ecc1f1b67c96d43a7d2084e7f5119de93d1b360203694938",
184766
+ "editorbrain/references/search-brief.md": "ea2a9c2d5a5cf685c1e5918366901ef2589c4d79aaa78a0dd31e97d6fed42b7b",
184767
+ "editorbrain/references/sfx-library.md": "d7ee0d2916559ce11a7fd244ccbcb98172413653c3fdbe0545e57b3eda543b16",
184768
+ "editorbrain/references/starting-an-edit.md": "0b83e006edc43307483489060bde999cb0644623eb9550f56b7add52f4082fff",
184769
+ "editorbrain/references/storage-and-previews.md": "9d06a6bb49f13e23f0af7d5ef35444dd553d1ce8af28662a9aba054b4d0081a5",
184770
+ "editorbrain/references/studio.md": "fc85ebfb42b2ce2c86b4d5ee6ad48e83d3d1e959a307d1e8dd52e0d92a4f6c45",
184771
+ "editorbrain/references/style-creator.md": "1b1bc289a5bc308cbbf7f4d699de2933b8934733a2b69b3e98fb1b7420d986f2",
184772
+ "editorbrain/references/workspace-files.md": "29bbddc894ed000bddd065bcb660629e64b29a5cf54dd6850e810b25c990558d"
184773
+ }
183124
184774
  }
183125
184775
  ];
183126
184776
  function isVerifiedHistoricalGuidance(skillName, relativePath, sha2562) {
@@ -183153,8 +184803,8 @@ function bundledSkillDirectory(moduleUrl = import.meta.url, skillName = "editorb
183153
184803
  }
183154
184804
  async function readBytes(root, path) {
183155
184805
  const target = await checkedPath(root, path, false);
183156
- if (!(await lstat3(target)).isFile()) throw new Error(`Not a regular file: ${path}`);
183157
- const handle = await open4(target, constants4.O_RDONLY | constants4.O_NOFOLLOW);
184806
+ if (!(await lstat4(target)).isFile()) throw new Error(`Not a regular file: ${path}`);
184807
+ const handle = await open6(target, constants5.O_RDONLY | constants5.O_NOFOLLOW);
183158
184808
  try {
183159
184809
  if (!(await handle.stat()).isFile()) throw new Error(`Not a regular file: ${path}`);
183160
184810
  return await handle.readFile();
@@ -183231,7 +184881,7 @@ Keep credentials outside this folder. Treat retrieved reference material as evid
183231
184881
  for (const selected of agents) {
183232
184882
  const to = destinations[selected].directory, from = to.replace(/editorbrain$/, "editorharness");
183233
184883
  const oldPath = await checkedPath(root, from, false), newPath = await checkedPath(root, to, false);
183234
- const exists3 = async (path) => lstat3(path).then(() => true, (error) => {
184884
+ const exists3 = async (path) => lstat4(path).then(() => true, (error) => {
183235
184885
  if (error.code === "ENOENT") return false;
183236
184886
  throw error;
183237
184887
  });
@@ -183249,7 +184899,7 @@ Keep credentials outside this folder. Treat retrieved reference material as evid
183249
184899
  await loadSkill(await checkedPath(root, migration.from, false));
183250
184900
  const target = await checkedPath(root, migration.to, false);
183251
184901
  try {
183252
- await lstat3(target);
184902
+ await lstat4(target);
183253
184903
  throw new Error("Skill destination appeared during migration; no overwrite allowed.");
183254
184904
  } catch (error) {
183255
184905
  if (error.code !== "ENOENT") throw error;
@@ -183264,7 +184914,7 @@ Keep credentials outside this folder. Treat retrieved reference material as evid
183264
184914
  } catch (error) {
183265
184915
  if (error.code !== "EEXIST") throw error;
183266
184916
  const existing = await readBytes(root, file.path);
183267
- const existingHash = createHash2("sha256").update(existing).digest("hex");
184917
+ const existingHash = createHash4("sha256").update(existing).digest("hex");
183268
184918
  const pristine = file.kind === "skill" && (previousHashesBySkill[file.skillName][file.relativePath]?.includes(existingHash) || isVerifiedHistoricalGuidance(file.skillName, file.relativePath, existingHash));
183269
184919
  const oldPointer = Buffer.from(file.content.toString().replaceAll("/skills/editorbrain/", "/skills/editorharness/"));
183270
184920
  if (!existing.equals(file.content) && (pristine || file.kind === "entryPoint" && existing.equals(oldPointer))) {
@@ -183301,16 +184951,16 @@ async function installAgentGuidance(directory, agent = "both") {
183301
184951
  }
183302
184952
 
183303
184953
  // packages/cli/src/workspace-lock.ts
183304
- import { constants as constants5 } from "node:fs";
183305
- import { lstat as lstat4, open as open5, rename as rename3, unlink as unlink2 } from "node:fs/promises";
184954
+ import { constants as constants6 } from "node:fs";
184955
+ import { lstat as lstat5, open as open7, rename as rename3, unlink as unlink3 } from "node:fs/promises";
183306
184956
  import { hostname } from "node:os";
183307
- import { randomUUID as randomUUID3 } from "node:crypto";
184957
+ import { randomUUID as randomUUID4 } from "node:crypto";
183308
184958
  var LOCK_PATH = ".editorbrain-operation.lock";
183309
184959
  async function withWorkspaceLock(root, operation, options = {}) {
183310
184960
  const legacyLock = await checkedPath(root, ".editorharness-operation.lock", false);
183311
184961
  let legacy;
183312
184962
  try {
183313
- legacy = await open5(legacyLock, constants5.O_CREAT | constants5.O_EXCL | constants5.O_WRONLY | constants5.O_NOFOLLOW, 384);
184963
+ legacy = await open7(legacyLock, constants6.O_CREAT | constants6.O_EXCL | constants6.O_WRONLY | constants6.O_NOFOLLOW, 384);
183314
184964
  } catch (error) {
183315
184965
  if (error.code === "EEXIST") throw new CliError("WORKSPACE_BUSY", "Another CLI operation holds this workspace lock.", "Wait for the other operation to finish.");
183316
184966
  throw error;
@@ -183319,18 +184969,18 @@ async function withWorkspaceLock(root, operation, options = {}) {
183319
184969
  const path = await checkedPath(root, LOCK_PATH, false);
183320
184970
  let handle;
183321
184971
  try {
183322
- handle = await open5(path, constants5.O_CREAT | constants5.O_EXCL | constants5.O_WRONLY | constants5.O_NOFOLLOW, 384);
184972
+ handle = await open7(path, constants6.O_CREAT | constants6.O_EXCL | constants6.O_WRONLY | constants6.O_NOFOLLOW, 384);
183323
184973
  } catch (error) {
183324
184974
  if (error.code !== "EEXIST") throw error;
183325
184975
  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.");
183326
184976
  }
183327
- const owner = JSON.stringify({ pid: process.pid, host: hostname(), nonce: randomUUID3(), startedAt: (/* @__PURE__ */ new Date()).toISOString() });
184977
+ const owner = JSON.stringify({ pid: process.pid, host: hostname(), nonce: randomUUID4(), startedAt: (/* @__PURE__ */ new Date()).toISOString() });
183328
184978
  try {
183329
184979
  await handle.writeFile(owner);
183330
184980
  await handle.close();
183331
184981
  const oldRoot = await checkedPath(root, ".editorharness", false);
183332
184982
  const newRoot = await checkedPath(root, ".editorbrain", false);
183333
- const exists3 = async (path2) => lstat4(path2).then(() => true, (error) => {
184983
+ const exists3 = async (path2) => lstat5(path2).then(() => true, (error) => {
183334
184984
  if (error.code === "ENOENT") return false;
183335
184985
  throw error;
183336
184986
  });
@@ -183342,19 +184992,19 @@ async function withWorkspaceLock(root, operation, options = {}) {
183342
184992
  } finally {
183343
184993
  await handle.close().catch(() => {
183344
184994
  });
183345
- if (await readText(root, LOCK_PATH, false).catch(() => void 0) === owner) await unlink2(await checkedPath(root, LOCK_PATH, false));
184995
+ if (await readText(root, LOCK_PATH, false).catch(() => void 0) === owner) await unlink3(await checkedPath(root, LOCK_PATH, false));
183346
184996
  }
183347
184997
  } finally {
183348
184998
  await legacy.close();
183349
- await unlink2(legacyLock);
184999
+ await unlink3(legacyLock);
183350
185000
  }
183351
185001
  }
183352
185002
 
183353
185003
  // packages/cli/src/skill-installations.ts
183354
- import { createHash as createHash3, randomUUID as randomUUID4 } from "node:crypto";
185004
+ import { createHash as createHash5, randomUUID as randomUUID5 } from "node:crypto";
183355
185005
  import { readFile as readFile2, readdir as readdir3 } from "node:fs/promises";
183356
185006
  import { homedir } from "node:os";
183357
- import { isAbsolute, join as join2 } from "node:path";
185007
+ import { isAbsolute, join as join4 } from "node:path";
183358
185008
 
183359
185009
  // packages/cli/src/doctor.ts
183360
185010
  import { readFile } from "node:fs/promises";
@@ -183363,6 +185013,8 @@ import { resolve as resolve4 } from "node:path";
183363
185013
  // packages/cli/src/client.ts
183364
185014
  import { setTimeout as delay } from "node:timers/promises";
183365
185015
  var searchErrors = {
185016
+ 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." },
185017
+ 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." },
183366
185018
  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." },
183367
185019
  sfx_bank_conflict: { status: 409, code: "SFX_BANK_CONFLICT", hint: "Read workflow and use the configured sound bank. A different bank needs an explicit project exception; do not silently substitute or generate effects." },
183368
185020
  sfx_context_changed: { status: 409, code: "SFX_CONTEXT_CHANGED", hint: "Refresh workflow and SFX search/get/check. Revise the cue plan against current preferences, then check again with its new SFX contextHash." },
@@ -183497,7 +185149,7 @@ var Client = class {
183497
185149
  const retryAfterMs = retryDelay(response.headers.get("Retry-After"), this.runtime.now());
183498
185150
  if (!response.ok) {
183499
185151
  let errorBody;
183500
- if (/^\/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) {
185152
+ 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) {
183501
185153
  try {
183502
185154
  const diagnostic = searchDiagnostic(response.status, await boundedJson(response, 16 * 1024));
183503
185155
  errorBody = diagnostic ? { error: { code: diagnostic.serviceCode } } : void 0;
@@ -183703,8 +185355,8 @@ ${conflicts.join("\n")}`, "Run pull --dry-run and reconcile the reported paths."
183703
185355
  }
183704
185356
 
183705
185357
  // packages/cli/src/integrations.ts
183706
- import { constants as constants6 } from "node:fs";
183707
- import { lstat as lstat5, open as open6 } from "node:fs/promises";
185358
+ import { constants as constants7 } from "node:fs";
185359
+ import { lstat as lstat6, open as open8 } from "node:fs/promises";
183708
185360
  function object7(value) {
183709
185361
  return value !== null && typeof value === "object" && !Array.isArray(value);
183710
185362
  }
@@ -183737,13 +185389,13 @@ async function readIntegrationSettings(file) {
183737
185389
  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.");
183738
185390
  const changedFile = () => new CliError("INVALID_ARGUMENT", "Integration settings changed while being read.", "Choose a stable regular settings file and try again.");
183739
185391
  const limit = 16 * 1024;
183740
- const before = await lstat5(file);
185392
+ const before = await lstat6(file);
183741
185393
  if (!before.isFile() || before.isSymbolicLink() || before.size > limit) throw invalidFile();
183742
185394
  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;
183743
- const handle = await open6(file, constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
185395
+ const handle = await open8(file, constants7.O_RDONLY | constants7.O_NOFOLLOW | constants7.O_NONBLOCK);
183744
185396
  try {
183745
185397
  const opened = await handle.stat();
183746
- const current2 = await lstat5(file);
185398
+ const current2 = await lstat6(file);
183747
185399
  if (!unchanged2(opened) || !unchanged2(current2)) throw changedFile();
183748
185400
  const bytes = Buffer.alloc(limit + 1);
183749
185401
  let length = 0;
@@ -183753,7 +185405,7 @@ async function readIntegrationSettings(file) {
183753
185405
  length += bytesRead;
183754
185406
  }
183755
185407
  const after = await handle.stat();
183756
- const finalPath = await lstat5(file);
185408
+ const finalPath = await lstat6(file);
183757
185409
  if (length > limit || length !== opened.size || !unchanged2(after) || !unchanged2(finalPath)) throw changedFile();
183758
185410
  try {
183759
185411
  return JSON.parse(bytes.subarray(0, length).toString("utf8"));
@@ -183961,10 +185613,10 @@ async function diagnose(options, fetcher = fetch, probeTool = probe) {
183961
185613
 
183962
185614
  // packages/cli/src/skill-installations.ts
183963
185615
  function installationRegistry() {
183964
- return join2(process.env.EDITORBRAIN_CONFIG_DIR ?? process.env.EDITORHARNESS_CONFIG_DIR ?? join2(homedir(), ".config", "editorbrain"), "skill-installations");
185616
+ return join4(process.env.EDITORBRAIN_CONFIG_DIR ?? process.env.EDITORHARNESS_CONFIG_DIR ?? join4(homedir(), ".config", "editorbrain"), "skill-installations");
183965
185617
  }
183966
185618
  function recordName(directory, scope) {
183967
- return createHash3("sha256").update(`${scope}\0${directory}`).digest("hex") + ".json";
185619
+ return createHash5("sha256").update(`${scope}\0${directory}`).digest("hex") + ".json";
183968
185620
  }
183969
185621
  function validateRecord(value) {
183970
185622
  const r = value;
@@ -184028,7 +185680,7 @@ async function installManagedGuidance(directory, agent, options = {}) {
184028
185680
  const previous = await readInstallation(root, scope, options.registry);
184029
185681
  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.");
184030
185682
  const target = parseAgentTarget(agent ?? previous?.agent);
184031
- const install = await prepareAgentGuidance(root, target, void 0, void 0, { global: options.global, backupId: randomUUID4() });
185683
+ const install = await prepareAgentGuidance(root, target, void 0, void 0, { global: options.global, backupId: randomUUID5() });
184032
185684
  const result2 = await install();
184033
185685
  try {
184034
185686
  await rememberGuidance(result2, scope, options.registry);
@@ -184049,7 +185701,7 @@ async function pinGuidance(directory, pinned, registry = installationRegistry())
184049
185701
  for (const agent of record13.agent === "both" ? ["codex", "claude"] : [record13.agent]) {
184050
185702
  for (const skill of BUNDLED_SKILLS) for (const path of await bundledGuidanceFiles(skill)) {
184051
185703
  const current2 = await readText(root, `${installedSkillDirectory(agent, skill)}/${path}`, false);
184052
- const expected = await readFile2(join2(bundledSkillDirectory(void 0, skill), path), "utf8");
185704
+ const expected = await readFile2(join4(bundledSkillDirectory(void 0, skill), path), "utf8");
184053
185705
  if (current2 !== expected) throw new Error("Project instructions differ from this release; resolve them before pinning.");
184054
185706
  }
184055
185707
  }
@@ -184095,18 +185747,18 @@ async function latestPublishedVersion(fetcher = fetch) {
184095
185747
  }
184096
185748
  }
184097
185749
  async function npmEntrypoint(env = process.env) {
184098
- const candidates = [env.npm_execpath, join3(dirname4(process.execPath), "node_modules/npm/bin/npm-cli.js")];
185750
+ const candidates = [env.npm_execpath, join5(dirname6(process.execPath), "node_modules/npm/bin/npm-cli.js")];
184099
185751
  for (const directory of (env.PATH ?? "").split(delimiter).filter(Boolean)) {
184100
- candidates.push(join3(directory, "node_modules/npm/bin/npm-cli.js"));
185752
+ candidates.push(join5(directory, "node_modules/npm/bin/npm-cli.js"));
184101
185753
  try {
184102
- candidates.push(await realpath3(join3(directory, "npm")));
185754
+ candidates.push(await realpath3(join5(directory, "npm")));
184103
185755
  } catch {
184104
185756
  }
184105
185757
  }
184106
185758
  for (const candidate of candidates) {
184107
185759
  if (!candidate || !candidate.endsWith("npm-cli.js")) continue;
184108
185760
  try {
184109
- if ((await lstat6(candidate)).isFile()) return candidate;
185761
+ if ((await lstat7(candidate)).isFile()) return candidate;
184110
185762
  } catch {
184111
185763
  }
184112
185764
  }
@@ -184140,9 +185792,9 @@ async function installPublishedCli(version, runner = exec) {
184140
185792
  );
184141
185793
  }
184142
185794
  try {
184143
- const metadata = JSON.parse(await readFile3(join3(root, "editorbrain/package.json"), "utf8"));
185795
+ const metadata = JSON.parse(await readFile3(join5(root, "editorbrain/package.json"), "utf8"));
184144
185796
  if (metadata.name !== "editorbrain" || metadata.version !== version || metadata.bin?.editorbrain !== "bin/editorbrain.mjs") throw new Error("Unexpected installed package");
184145
- const executable = join3(root, "editorbrain/bin/editorbrain.mjs");
185797
+ const executable = join5(root, "editorbrain/bin/editorbrain.mjs");
184146
185798
  const result2 = JSON.parse((await runner(process.execPath, [executable, "version"], { timeout: 15e3, maxBuffer: 65536 })).stdout);
184147
185799
  if (result2.version !== version) throw new Error("Unexpected executable version");
184148
185800
  return executable;
@@ -184177,7 +185829,7 @@ async function detectAgents(root) {
184177
185829
  for (const skill of BUNDLED_SKILLS) {
184178
185830
  const file = await checkedPath(root, `${installedSkillDirectory(agent, skill)}/SKILL.md`, false);
184179
185831
  try {
184180
- if ((await lstat6(file)).isFile()) {
185832
+ if ((await lstat7(file)).isFile()) {
184181
185833
  found.push(agent);
184182
185834
  break;
184183
185835
  }
@@ -184363,8 +186015,8 @@ async function projectProgressCommand(client, command, flags) {
184363
186015
  }
184364
186016
 
184365
186017
  // packages/cli/src/event-mix.ts
184366
- import { mkdir as mkdir3, readFile as readFile4, writeFile, unlink as unlink3 } from "node:fs/promises";
184367
- import { dirname as dirname5, join as join4, resolve as resolve6 } from "node:path";
186018
+ import { mkdir as mkdir5, readFile as readFile4, writeFile as writeFile2, unlink as unlink4 } from "node:fs/promises";
186019
+ import { dirname as dirname7, join as join6, resolve as resolve6 } from "node:path";
184368
186020
  function validateEventCues(value, duration) {
184369
186021
  const v = value;
184370
186022
  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.");
@@ -184403,7 +186055,7 @@ function floats(bytes) {
184403
186055
  async function decode(file, target) {
184404
186056
  await runMediaTool("ffmpeg", ["-v", "error", "-n", ...localInputArgs(file), "-map", "0:a:0", "-vn", "-ar", "48000", "-ac", "2", "-f", "f32le", target], { timeoutMs: 6e5 });
184405
186057
  const b = await readFile4(target);
184406
- await unlink3(target);
186058
+ await unlink4(target);
184407
186059
  return floats(b);
184408
186060
  }
184409
186061
  function wav(data) {
@@ -184439,12 +186091,12 @@ async function mixEvents(options) {
184439
186091
  sources.push(source2);
184440
186092
  }
184441
186093
  const directory = await productionOutputPath(options.root, options.out);
184442
- await mkdir3(dirname5(directory), { recursive: true, mode: 448 });
186094
+ await mkdir5(dirname7(directory), { recursive: true, mode: 448 });
184443
186095
  await productionOutputPath(options.root, options.out);
184444
- await mkdir3(directory, { mode: 448 });
184445
- const mix = await decode(voice.path, join4(directory, "voice.raw")), records = [];
186096
+ await mkdir5(directory, { mode: 448 });
186097
+ const mix = await decode(voice.path, join6(directory, "voice.raw")), records = [];
184446
186098
  for (let i = 0; i < cues.length; i++) {
184447
- const effect = await decode(sources[i].path, join4(directory, "effect.raw"));
186099
+ const effect = await decode(sources[i].path, join6(directory, "effect.raw"));
184448
186100
  records.push({ ...cues[i], sourceSha256: sources[i].sha256, sampleFrames: effect.length / 2, ...addEventPcm(mix, effect, cues[i].time, cues[i].peak) });
184449
186101
  }
184450
186102
  const cuePlan = { durationSeconds: mix.length / 2 / 48e3, hookEndSeconds, cues: records.map((c) => {
@@ -184461,16 +186113,16 @@ async function mixEvents(options) {
184461
186113
  if (peak >= 0.99) throw new Error("Mix would clip: lower explicit cue levels or prepare voice gain first. No automatic voice normalization applied.");
184462
186114
  for (const s of [voice, ...sources]) if ((await probeLocalMedia(s.path)).sha256 !== s.sha256) throw new Error("Audio source changed during mix.");
184463
186115
  if (options.context && !await options.context.validateContext()) throw new Error("Project preferences changed during the mix. Refresh context; no final mix was written.");
184464
- const path = join4(directory, "mix.wav");
184465
- await writeFile(path, wav(mix), { flag: "wx", mode: 384 });
186116
+ const path = join6(directory, "mix.wav");
186117
+ await writeFile2(path, wav(mix), { flag: "wx", mode: 384 });
184466
186118
  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." };
184467
- await writeFile(join4(directory, "report.json"), JSON.stringify(report, null, 2), { flag: "wx", mode: 384 });
186119
+ await writeFile2(join6(directory, "report.json"), JSON.stringify(report, null, 2), { flag: "wx", mode: 384 });
184468
186120
  return report;
184469
186121
  }
184470
186122
 
184471
186123
  // packages/cli/src/production-sheet.ts
184472
- import { mkdir as mkdir4, readFile as readFile5, writeFile as writeFile2, unlink as unlink4 } from "node:fs/promises";
184473
- import { dirname as dirname6, join as join5 } from "node:path";
186124
+ import { mkdir as mkdir6, readFile as readFile5, writeFile as writeFile3, unlink as unlink5 } from "node:fs/promises";
186125
+ import { dirname as dirname8, join as join7 } from "node:path";
184474
186126
  var esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
184475
186127
  function freezeIntervals(log, duration) {
184476
186128
  const result2 = [];
@@ -184509,13 +186161,13 @@ async function createProductionSheet(options) {
184509
186161
  if (options.platform && input.platform && options.platform !== input.platform) throw new Error("Platform flag conflicts with review profile.");
184510
186162
  const platform = options.platform ?? input.platform;
184511
186163
  const directory = await productionOutputPath(options.root, options.out);
184512
- await mkdir4(dirname6(directory), { recursive: true, mode: 448 });
186164
+ await mkdir6(dirname8(directory), { recursive: true, mode: 448 });
184513
186165
  await productionOutputPath(options.root, options.out);
184514
- await mkdir4(directory, { mode: 448 });
184515
- const raw = join5(directory, "samples.gray");
184516
- 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 });
186166
+ await mkdir6(directory, { mode: 448 });
186167
+ const raw = join7(directory, "samples.gray");
186168
+ 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 });
184517
186169
  const data = await readFile5(raw);
184518
- await unlink4(raw);
186170
+ await unlink5(raw);
184519
186171
  const count = data.length / (96 * 96);
184520
186172
  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.");
184521
186173
  if ((await probeLocalMedia(source2.path)).sha256 !== source2.sha256) throw new Error("Source changed during review.");
@@ -184529,15 +186181,15 @@ async function createProductionSheet(options) {
184529
186181
  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>`;
184530
186182
  }).join("");
184531
186183
  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>`;
184532
- await writeFile2(join5(directory, "report.json"), JSON.stringify(report, null, 2), { flag: "wx", mode: 384 });
184533
- await writeFile2(join5(directory, "index.html"), html, { flag: "wx", mode: 384 });
184534
- 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 };
186184
+ await writeFile3(join7(directory, "report.json"), JSON.stringify(report, null, 2), { flag: "wx", mode: 384 });
186185
+ await writeFile3(join7(directory, "index.html"), html, { flag: "wx", mode: 384 });
186186
+ 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 };
184535
186187
  }
184536
186188
 
184537
186189
  // packages/cli/src/presenter-matte.ts
184538
186190
  import { spawn as spawn2 } from "node:child_process";
184539
- import { mkdir as mkdir5, writeFile as writeFile3, rename as rename4, unlink as unlink5 } from "node:fs/promises";
184540
- import { dirname as dirname7, join as join6 } from "node:path";
186191
+ import { mkdir as mkdir7, writeFile as writeFile4, rename as rename4, unlink as unlink6 } from "node:fs/promises";
186192
+ import { dirname as dirname9, join as join8 } from "node:path";
184541
186193
 
184542
186194
  // packages/cli/src/presenter-matte-source.ts
184543
186195
  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';
@@ -184599,32 +186251,32 @@ async function generatePresenterMatte(options) {
184599
186251
  const video = videos[0], plan = planPresenterMatte(source2.durationSeconds, video.fps);
184600
186252
  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.");
184601
186253
  const dir = await productionOutputPath(options.root, options.out);
184602
- await mkdir5(dirname7(dir), { recursive: true, mode: 448 });
186254
+ await mkdir7(dirname9(dir), { recursive: true, mode: 448 });
184603
186255
  await productionOutputPath(options.root, options.out);
184604
- await mkdir5(dir, { mode: 448 });
184605
- const swift = join6(dir, "matte.swift"), binary = join6(dir, "matte-tool"), result2 = join6(dir, "matte.partial.mov");
184606
- await writeFile3(swift, presenterMatteSource, { flag: "wx", mode: 384 });
186256
+ await mkdir7(dir, { mode: 448 });
186257
+ const swift = join8(dir, "matte.swift"), binary = join8(dir, "matte-tool"), result2 = join8(dir, "matte.partial.mov");
186258
+ await writeFile4(swift, presenterMatteSource, { flag: "wx", mode: 384 });
184607
186259
  try {
184608
186260
  await runLocal("swiftc", ["-O", swift, "-o", binary], 12e4);
184609
186261
  await runLocal(binary, [source2.path, result2, String(video.width), String(video.height)], 18e5);
184610
186262
  const [clock, matteClock, mask, after] = await Promise.all([readFrameClock(source2.path), readFrameClock(result2), probeLocalMedia(result2), probeLocalMedia(source2.path)]);
184611
186263
  assertMatteClocks(clock, matteClock);
184612
186264
  if (after.sha256 !== source2.sha256) throw new Error("Source changed during segmentation.");
184613
- const finalPath = join6(dir, "matte.mov");
186265
+ const finalPath = join8(dir, "matte.mov");
184614
186266
  await rename4(result2, finalPath);
184615
186267
  mask.path = finalPath;
184616
186268
  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." };
184617
- await writeFile3(join6(dir, "report.json"), JSON.stringify(report, null, 2), { flag: "wx", mode: 384 });
186269
+ await writeFile4(join8(dir, "report.json"), JSON.stringify(report, null, 2), { flag: "wx", mode: 384 });
184618
186270
  return report;
184619
186271
  } finally {
184620
- await unlink5(binary).catch(() => {
186272
+ await unlink6(binary).catch(() => {
184621
186273
  });
184622
186274
  }
184623
186275
  }
184624
186276
 
184625
186277
  // packages/cli/src/sfx.ts
184626
- import { readdir as readdir4, lstat as lstat7 } from "node:fs/promises";
184627
- import { join as join7, extname as extname3, basename as basename2 } from "node:path";
186278
+ import { readdir as readdir4, lstat as lstat8 } from "node:fs/promises";
186279
+ import { join as join9, extname as extname3, basename as basename2 } from "node:path";
184628
186280
 
184629
186281
  // packages/cli/src/production-context.ts
184630
186282
  async function prepareProductionContext(root, projectId, client) {
@@ -184664,14 +186316,14 @@ var localPath = (id2) => {
184664
186316
  };
184665
186317
  async function indexSfx(directory, input, bankId) {
184666
186318
  const root = await ensureRoot(directory), target = localPath(bankId), folder = await assertNoMediaSymlinks(input);
184667
- if (!(await lstat7(folder)).isDirectory()) throw new Error("SFX input must be a directory.");
186319
+ if (!(await lstat8(folder)).isDirectory()) throw new Error("SFX input must be a directory.");
184668
186320
  const entries = [], paths2 = {}, failures = [];
184669
186321
  const files = await readdir4(folder, { withFileTypes: true });
184670
186322
  const selected = files.filter((e) => e.isFile() && [".wav", ".mp3", ".m4a", ".ogg", ".flac", ".aif", ".aiff"].includes(extname3(e.name).toLowerCase()));
184671
186323
  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.");
184672
186324
  for (const file of selected.sort((a, b) => a.name.localeCompare(b.name))) {
184673
186325
  try {
184674
- const probe2 = await probeLocalMedia(join7(folder, file.name));
186326
+ const probe2 = await probeLocalMedia(join9(folder, file.name));
184675
186327
  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.");
184676
186328
  const id2 = "sfx-" + probe2.sha256.slice(0, 24);
184677
186329
  if (paths2[id2]) continue;
@@ -184734,8 +186386,8 @@ async function remoteSfx(client, subcommand, params) {
184734
186386
  }
184735
186387
 
184736
186388
  // packages/cli/src/media-preview.ts
184737
- import { chmod, link as link2, mkdtemp, rm } from "node:fs/promises";
184738
- import { dirname as dirname8, join as join8 } from "node:path";
186389
+ import { chmod, link as link3, mkdtemp, rm as rm2 } from "node:fs/promises";
186390
+ import { dirname as dirname10, join as join10 } from "node:path";
184739
186391
  async function prepareMediaPreview(root, file, out, quality = 720, audioStream) {
184740
186392
  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/.");
184741
186393
  const source2 = await probeLocalMedia(await assertLocalMediaFile(file));
@@ -184748,25 +186400,25 @@ async function prepareMediaPreview(root, file, out, quality = 720, audioStream)
184748
186400
  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.");
184749
186401
  const selected = audioStream === void 0 ? audio[0] : audio.find((s) => s.index === audioStream);
184750
186402
  if (audioStream !== void 0 && !selected) throw new CliError("INVALID_ARGUMENT", "The selected audio stream does not exist.", "Inspect the material before selecting a track.");
184751
- const target = await prepareSampleDirectory(root, out), temp = await mkdtemp(join8(dirname8(target), ".preview-"));
186403
+ const target = await prepareSampleDirectory(root, out), temp = await mkdtemp(join10(dirname10(target), ".preview-"));
184752
186404
  try {
184753
- const prepared = join8(temp, "preview.mp4"), edge = quality === 720 ? 1280 : 1920;
186405
+ const prepared = join10(temp, "preview.mp4"), edge = quality === 720 ? 1280 : 1920;
184754
186406
  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 });
184755
186407
  const result2 = await probeLocalMedia(prepared);
184756
186408
  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.");
184757
186409
  if ((await probeLocalMedia(source2.path)).sha256 !== source2.sha256) throw new CliError("SOURCE_CHANGED", "The source changed during compression.", "Retry with a stable original.");
184758
186410
  await chmod(prepared, 384);
184759
- await link2(prepared, target);
186411
+ await link3(prepared, target);
184760
186412
  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." };
184761
186413
  } finally {
184762
- await rm(temp, { recursive: true, force: true });
186414
+ await rm2(temp, { recursive: true, force: true });
184763
186415
  }
184764
186416
  }
184765
186417
 
184766
186418
  // packages/cli/src/studio-audio.ts
184767
- import { link as link3, mkdtemp as mkdtemp2, readFile as readFile6, rm as rm2 } from "node:fs/promises";
184768
- import { dirname as dirname9, join as join9 } from "node:path";
184769
- import { createHash as createHash4 } from "node:crypto";
186419
+ import { link as link4, mkdtemp as mkdtemp2, readFile as readFile6, rm as rm3 } from "node:fs/promises";
186420
+ import { dirname as dirname11, join as join11 } from "node:path";
186421
+ import { createHash as createHash6 } from "node:crypto";
184770
186422
  async function prepareStudioAudio(root, file, out, streamIndex) {
184771
186423
  const source2 = await probeLocalMedia(await assertLocalMediaFile(file));
184772
186424
  const audio = source2.streams.filter((stream) => stream.type === "audio");
@@ -184776,18 +186428,18 @@ async function prepareStudioAudio(root, file, out, streamIndex) {
184776
186428
  if (!selected) throw new CliError("INVALID_ARGUMENT", "The selected stream is not an audio track.", "Inspect media inventory before selecting a track.");
184777
186429
  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.");
184778
186430
  if (!out.endsWith(".wav")) throw new CliError("INVALID_ARGUMENT", "The prepared output must be a .wav file.", "Use --out .editorbrain-local/studio/source.wav.");
184779
- const target = await prepareSampleDirectory(root, out), temp = await mkdtemp2(join9(dirname9(target), ".tempo-"));
186431
+ const target = await prepareSampleDirectory(root, out), temp = await mkdtemp2(join11(dirname11(target), ".tempo-"));
184780
186432
  try {
184781
- const prepared = join9(temp, "audio.wav");
186433
+ const prepared = join11(temp, "audio.wav");
184782
186434
  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 });
184783
186435
  const verified = await probeLocalMedia(prepared);
184784
186436
  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.");
184785
186437
  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.");
184786
- const bytes = await readFile6(prepared), hash6 = createHash4("sha256").update(bytes).digest("hex");
184787
- await link3(prepared, target);
186438
+ const bytes = await readFile6(prepared), hash6 = createHash6("sha256").update(bytes).digest("hex");
186439
+ await link4(prepared, target);
184788
186440
  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." };
184789
186441
  } finally {
184790
- await rm2(temp, { recursive: true, force: true });
186442
+ await rm3(temp, { recursive: true, force: true });
184791
186443
  }
184792
186444
  }
184793
186445
 
@@ -184982,9 +186634,9 @@ async function setup(options, runner = runHost) {
184982
186634
 
184983
186635
  // packages/cli/src/onboarding.ts
184984
186636
  import { createServer } from "node:http";
184985
- import { randomBytes, createHash as createHash5 } from "node:crypto";
184986
- import { join as join10, dirname as dirname10 } from "node:path";
184987
- import { mkdir as mkdir6 } from "node:fs/promises";
186637
+ import { randomBytes, createHash as createHash7 } from "node:crypto";
186638
+ import { join as join12, dirname as dirname12 } from "node:path";
186639
+ import { mkdir as mkdir8 } from "node:fs/promises";
184988
186640
 
184989
186641
  // packages/cli/src/onboarding-brand.ts
184990
186642
  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';
@@ -185792,7 +187444,7 @@ async function syncOnboardingDocuments(client, root, files, options) {
185792
187444
  // packages/cli/src/onboarding.ts
185793
187445
  var failure = (code, message, hint = "Reopen onboarding against the current files. Nothing is overwritten silently.") => new CliError(code, message, hint);
185794
187446
  function starterOutputId(brandId2) {
185795
- return `onboarding-${brandId2.slice(0, 48)}-${createHash5("sha256").update(brandId2).digest("hex").slice(0, 12)}`;
187447
+ return `onboarding-${brandId2.slice(0, 48)}-${createHash7("sha256").update(brandId2).digest("hex").slice(0, 12)}`;
185796
187448
  }
185797
187449
  function scaffold(brandId2, projectId) {
185798
187450
  const files = Object.fromEntries(Object.entries(createWorkspace({ brand: brandId2, project: projectId })).filter(([p]) => !p.startsWith(`.editorbrain/brands/${brandId2}/`)));
@@ -185848,14 +187500,14 @@ async function createOnboarding(options) {
185848
187500
  const directory = options.out ?? `.editorbrain-local/onboarding/${brandId2}-${Date.now()}-${randomBytes(3).toString("hex")}`;
185849
187501
  await productionOutputPath(root, `${directory}/session.json`);
185850
187502
  const target = await checkedPath(root, directory, false);
185851
- await mkdir6(dirname10(target), { recursive: true });
185852
- await mkdir6(target);
187503
+ await mkdir8(dirname12(target), { recursive: true });
187504
+ await mkdir8(target);
185853
187505
  const saved = await snapshots(root, brandId2, projectId), files = Object.fromEntries(Object.entries(saved).flatMap(([p, s]) => s ? [[p, s.content]] : []));
185854
187506
  const intake = onboardingIntakeFromFiles(brandId2, files);
185855
187507
  const session = { schemaVersion: 1, kind: "editorbrain.onboarding", brandId: brandId2, projectId, intake, snapshots: saved };
185856
187508
  await atomicWrite(root, `${directory}/session.json`, stableJson(session), { document: false, overwrite: false, mode: 384 });
185857
187509
  await atomicWrite(root, `${directory}/index.html`, renderOnboardingArtifact({ intake, requiresIdentity: saved[`.editorbrain/brands/${brandId2}/brand.md`] === null }), { document: false, overwrite: false, mode: 384 });
185858
- 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." };
187510
+ 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." };
185859
187511
  }
185860
187512
  async function applyOnboarding(options) {
185861
187513
  const root = await ensureRoot(options.directory);
@@ -185886,7 +187538,7 @@ async function applyOnboarding(options) {
185886
187538
  if (now !== current2[item.path]?.content) throw failure("ONBOARDING_CONFLICT", `Document changed while applying: ${item.path}`);
185887
187539
  await atomicWrite(root, item.path, item.content, { overwrite: now !== void 0 });
185888
187540
  }
185889
- 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 });
187541
+ 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 });
185890
187542
  }
185891
187543
  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." };
185892
187544
  }, { migrateLegacy: !options.dryRun });
@@ -185895,7 +187547,7 @@ async function syncOnboarding(client, options) {
185895
187547
  const root = await ensureRoot(options.directory);
185896
187548
  return withWorkspaceLock(root, async () => {
185897
187549
  const session = await readSession(root, options.session);
185898
- const receipt = await readProductionJson(root, `${dirname10(options.session)}/applied.json`);
187550
+ const receipt = await readProductionJson(root, `${dirname12(options.session)}/applied.json`);
185899
187551
  if (receipt.brandId !== session.brandId || receipt.projectId !== session.projectId) throw failure("ONBOARDING_NOT_APPLIED", "Apply the reviewed choices locally before syncing.");
185900
187552
  const files = {};
185901
187553
  for (const path of paths(session.brandId, session.projectId)) {
@@ -185912,7 +187564,7 @@ async function syncOnboarding(client, options) {
185912
187564
  async function serveOnboarding(options) {
185913
187565
  const root = await ensureRoot(options.directory), session = await readSession(root, options.session), seconds = options.timeoutSeconds ?? 1800;
185914
187566
  if (!Number.isInteger(seconds) || seconds < 1 || seconds > 3600) throw failure("INVALID_ARGUMENT", "Timeout must be between 1 and 3600 seconds.");
185915
- const token = randomBytes(32).toString("hex"), csrf = randomBytes(32).toString("hex"), prefix = `/${token}`, answers = `${dirname10(options.session)}/answers.json`;
187567
+ const token = randomBytes(32).toString("hex"), csrf = randomBytes(32).toString("hex"), prefix = `/${token}`, answers = `${dirname12(options.session)}/answers.json`;
185916
187568
  let origin = "", consumed = false, busy = false, server;
185917
187569
  let complete, reject;
185918
187570
  const done = new Promise((yes, no) => {
@@ -185952,7 +187604,7 @@ async function serveOnboarding(options) {
185952
187604
  await atomicWrite(root, answers, stableJson(intake), { document: false, overwrite: false, mode: 384 });
185953
187605
  consumed = true;
185954
187606
  send(200, { saved: true, path: answers });
185955
- 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." });
187607
+ 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." });
185956
187608
  } catch (e) {
185957
187609
  busy = false;
185958
187610
  send(400, { error: e.message.slice(0, 300) });
@@ -185972,7 +187624,7 @@ async function serveOnboarding(options) {
185972
187624
  process.once("SIGINT", stop);
185973
187625
  process.once("SIGTERM", stop);
185974
187626
  try {
185975
- options.onReady?.({ url: `${origin}${prefix}/`, answers: join10(root, answers) });
187627
+ options.onReady?.({ url: `${origin}${prefix}/`, answers: join12(root, answers) });
185976
187628
  return await done;
185977
187629
  } finally {
185978
187630
  clearTimeout(timer);
@@ -186267,10 +187919,10 @@ async function loginWithDevice(options, overrides = {}) {
186267
187919
  }
186268
187920
 
186269
187921
  // packages/cli/src/index.ts
186270
- import { chmod as chmod2, lstat as lstat12, mkdir as mkdir13, open as open11 } from "node:fs/promises";
186271
- import { constants as constants10 } from "node:fs";
187922
+ import { chmod as chmod2, lstat as lstat12, mkdir as mkdir14, open as open12 } from "node:fs/promises";
187923
+ import { constants as constants11 } from "node:fs";
186272
187924
  import { homedir as homedir3 } from "node:os";
186273
- import { basename as basename4, dirname as dirname17, extname as extname7, join as join14, resolve as resolve12 } from "node:path";
187925
+ import { basename as basename4, dirname as dirname18, extname as extname7, join as join15, resolve as resolve12 } from "node:path";
186274
187926
 
186275
187927
  // packages/cli/src/direction-context.ts
186276
187928
  async function prepareDirectionContext(root, client, projectId) {
@@ -186294,10 +187946,10 @@ async function prepareDirectionContext(root, client, projectId) {
186294
187946
  }
186295
187947
 
186296
187948
  // packages/cli/src/style-authoring.ts
186297
- import { createHash as createHash6 } from "node:crypto";
186298
- import { constants as constants7 } from "node:fs";
186299
- import { lstat as lstat8, mkdir as mkdir7, open as open7, readdir as readdir5, rmdir, unlink as unlink6 } from "node:fs/promises";
186300
- import { dirname as dirname11 } from "node:path";
187949
+ import { createHash as createHash8 } from "node:crypto";
187950
+ import { constants as constants8 } from "node:fs";
187951
+ import { lstat as lstat9, mkdir as mkdir9, open as open9, readdir as readdir5, rmdir, unlink as unlink7 } from "node:fs/promises";
187952
+ import { dirname as dirname13 } from "node:path";
186301
187953
  function styleId(id2) {
186302
187954
  try {
186303
187955
  return assertIdentifier(id2);
@@ -186307,7 +187959,7 @@ function styleId(id2) {
186307
187959
  }
186308
187960
  async function exists(path) {
186309
187961
  try {
186310
- await lstat8(path);
187962
+ await lstat9(path);
186311
187963
  return true;
186312
187964
  } catch (error) {
186313
187965
  if (error.code === "ENOENT") return false;
@@ -186336,12 +187988,12 @@ async function makeDirectories(root, path, created) {
186336
187988
  const relative2 = segments.slice(0, i).join("/");
186337
187989
  const target = await checkedPath(root, relative2, false);
186338
187990
  try {
186339
- await mkdir7(target);
186340
- const info = await lstat8(target);
187991
+ await mkdir9(target);
187992
+ const info = await lstat9(target);
186341
187993
  created.push({ path: relative2, dev: info.dev, ino: info.ino });
186342
187994
  } catch (error) {
186343
187995
  if (error.code !== "EEXIST") throw error;
186344
- if (!(await lstat8(await checkedPath(root, relative2, false))).isDirectory()) throw new Error(`Not a directory: ${relative2}`);
187996
+ if (!(await lstat9(await checkedPath(root, relative2, false))).isDirectory()) throw new Error(`Not a directory: ${relative2}`);
186345
187997
  }
186346
187998
  }
186347
187999
  }
@@ -186349,10 +188001,10 @@ async function cleanCreated(root, paths2, directory) {
186349
188001
  for (const item of [...paths2].reverse()) {
186350
188002
  try {
186351
188003
  const target = await checkedPath(root, item.path, false);
186352
- const info = await lstat8(target);
188004
+ const info = await lstat9(target);
186353
188005
  if (info.dev !== item.dev || info.ino !== item.ino || info.isSymbolicLink()) continue;
186354
188006
  if (directory) await rmdir(target);
186355
- else await unlink6(target);
188007
+ else await unlink7(target);
186356
188008
  } catch {
186357
188009
  }
186358
188010
  }
@@ -186371,9 +188023,9 @@ async function createLocalStyle(options) {
186371
188023
  const createdDirectories = [];
186372
188024
  try {
186373
188025
  for (const [path, content] of Object.entries(files)) {
186374
- await makeDirectories(root, dirname11(path), createdDirectories);
188026
+ await makeDirectories(root, dirname13(path), createdDirectories);
186375
188027
  const target = await checkedPath(root, path);
186376
- const handle = await open7(target, constants7.O_WRONLY | constants7.O_CREAT | constants7.O_EXCL | constants7.O_NOFOLLOW, 420);
188028
+ const handle = await open9(target, constants8.O_WRONLY | constants8.O_CREAT | constants8.O_EXCL | constants8.O_NOFOLLOW, 420);
186377
188029
  try {
186378
188030
  const info = await handle.stat();
186379
188031
  createdFiles.push({ path, dev: info.dev, ino: info.ino });
@@ -186406,7 +188058,7 @@ async function readStyle(root, id2) {
186406
188058
  try {
186407
188059
  const target = await checkedPath(root, path, false);
186408
188060
  if (!await exists(target)) continue;
186409
- if (!(await lstat8(target)).isDirectory()) {
188061
+ if (!(await lstat9(target)).isDirectory()) {
186410
188062
  issues.push({ path, message: "Style path is not a directory." });
186411
188063
  continue;
186412
188064
  }
@@ -186435,15 +188087,15 @@ async function readStyle(root, id2) {
186435
188087
  async function checkLocalResource(root, path, expected) {
186436
188088
  safeStyleResourcePath(path);
186437
188089
  const target = await checkedPath(root, path, false);
186438
- const handle = await open7(target, constants7.O_RDONLY | constants7.O_NOFOLLOW | constants7.O_NONBLOCK);
188090
+ const handle = await open9(target, constants8.O_RDONLY | constants8.O_NOFOLLOW | constants8.O_NONBLOCK);
186439
188091
  try {
186440
188092
  const before = await handle.stat();
186441
188093
  if (!before.isFile()) throw new Error("Resource is not a regular file.");
186442
188094
  if (!expected) return {};
186443
- const hash6 = createHash6("sha256");
188095
+ const hash6 = createHash8("sha256");
186444
188096
  for await (const chunk of handle.createReadStream({ autoClose: false })) hash6.update(chunk);
186445
188097
  const after = await handle.stat();
186446
- const current2 = await lstat8(await checkedPath(root, path, false));
188098
+ const current2 = await lstat9(await checkedPath(root, path, false));
186447
188099
  if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || current2.dev !== before.dev || current2.ino !== before.ino) {
186448
188100
  throw new Error("Resource changed while its hash was being checked; check it again.");
186449
188101
  }
@@ -186986,9 +188638,9 @@ async function searchMediaSources(options, dependencies = {}) {
186986
188638
  }
186987
188639
 
186988
188640
  // packages/cli/src/media-inventory.ts
186989
- import { createHash as createHash7 } from "node:crypto";
186990
- import { link as link4, lstat as lstat9, mkdir as mkdir8, mkdtemp as mkdtemp3, opendir, readFile as readFile7, rm as rm3 } from "node:fs/promises";
186991
- import { basename as basename3, dirname as dirname12, extname as extname4, join as join11 } from "node:path";
188641
+ import { createHash as createHash9 } from "node:crypto";
188642
+ import { link as link5, lstat as lstat10, mkdir as mkdir10, mkdtemp as mkdtemp3, opendir, readFile as readFile7, rm as rm4 } from "node:fs/promises";
188643
+ import { basename as basename3, dirname as dirname14, extname as extname4, join as join13 } from "node:path";
186992
188644
  var GENERATED_DIRECTORIES = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "out", "output", "outputs", "renders", "render", "cache", "caches", "proxies", "proxy", "samples", "thumbnails", "coverage", "venv", "__pycache__"]);
186993
188645
  function mediaFailure(error) {
186994
188646
  if (error instanceof MediaToolError) return { code: error.code, message: error.message };
@@ -187014,7 +188666,7 @@ async function inventoryMedia(options) {
187014
188666
  }
187015
188667
  report.scannedEntries++;
187016
188668
  try {
187017
- const stat = await lstat9(path);
188669
+ const stat = await lstat10(path);
187018
188670
  if (stat.isSymbolicLink()) {
187019
188671
  if (explicit) throw new MediaToolError("MEDIA_SYMLINK", "Symlink inputs are not followed. Use the original local path.");
187020
188672
  skip(path, "symlink_not_followed");
@@ -187040,7 +188692,7 @@ async function inventoryMedia(options) {
187040
188692
  skip(path, "remaining_entries_not_scanned", true);
187041
188693
  break;
187042
188694
  }
187043
- await visit(join11(path, entry.name), depth + 1);
188695
+ await visit(join13(path, entry.name), depth + 1);
187044
188696
  }
187045
188697
  } else if (!stat.isFile()) {
187046
188698
  if (explicit) throw new MediaToolError("MEDIA_NOT_REGULAR", "The explicit media input must be a regular local file or directory.");
@@ -187075,35 +188727,35 @@ async function sampleMedia(options) {
187075
188727
  if (!source2.streams.some((stream) => stream.type === "video")) throw new MediaToolError("MEDIA_VIDEO_REQUIRED", "Frame sampling requires a video or image stream.");
187076
188728
  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.");
187077
188729
  const outputDirectory = resolveLocalMediaPath(options.outputDirectory);
187078
- await assertNoMediaSymlinks(dirname12(outputDirectory));
188730
+ await assertNoMediaSymlinks(dirname14(outputDirectory));
187079
188731
  try {
187080
- await mkdir8(outputDirectory);
188732
+ await mkdir10(outputDirectory);
187081
188733
  } catch (error) {
187082
188734
  if (error.code !== "EEXIST") throw error;
187083
188735
  }
187084
188736
  await assertNoMediaSymlinks(outputDirectory);
187085
- if (!(await lstat9(outputDirectory)).isDirectory()) throw new MediaToolError("MEDIA_OUTPUT_DIRECTORY_INVALID", "Frame output must be a local directory.");
187086
- const temp = await mkdtemp3(join11(outputDirectory, ".editorbrain-samples-"));
187087
- const tempStat = await lstat9(temp);
188737
+ if (!(await lstat10(outputDirectory)).isDirectory()) throw new MediaToolError("MEDIA_OUTPUT_DIRECTORY_INVALID", "Frame output must be a local directory.");
188738
+ const temp = await mkdtemp3(join13(outputDirectory, ".editorbrain-samples-"));
188739
+ const tempStat = await lstat10(temp);
187088
188740
  const frames = [];
187089
188741
  const created = [];
187090
188742
  try {
187091
188743
  for (let index = 0; index < options.times.length; index++) {
187092
188744
  const time = options.times[index];
187093
188745
  const filename = `${source2.sha256.slice(0, 12)}-${String(index + 1).padStart(2, "0")}-${Math.round(time * 1e3)}ms.jpg`;
187094
- const temporary = join11(temp, filename), output2 = join11(outputDirectory, filename);
188746
+ const temporary = join13(temp, filename), output2 = join13(outputDirectory, filename);
187095
188747
  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 });
187096
188748
  const bytes = await readFile7(temporary);
187097
188749
  if (!bytes.length) throw new MediaToolError("MEDIA_SAMPLE_EMPTY", "The requested frame did not produce a usable image.");
187098
188750
  try {
187099
- await link4(temporary, output2);
188751
+ await link5(temporary, output2);
187100
188752
  } catch (error) {
187101
188753
  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.");
187102
188754
  throw error;
187103
188755
  }
187104
- const outputStat = await lstat9(output2);
188756
+ const outputStat = await lstat10(output2);
187105
188757
  created.push({ path: output2, ino: outputStat.ino, dev: outputStat.dev, size: outputStat.size, mtimeMs: outputStat.mtimeMs, ctimeMs: outputStat.ctimeMs });
187106
- frames.push({ path: output2, sha256: createHash7("sha256").update(bytes).digest("hex"), bytes: bytes.length, requestedTimeSeconds: time, actualPresentationTimeSeconds: null });
188758
+ frames.push({ path: output2, sha256: createHash9("sha256").update(bytes).digest("hex"), bytes: bytes.length, requestedTimeSeconds: time, actualPresentationTimeSeconds: null });
187107
188759
  }
187108
188760
  const after = await probeLocalMedia(file);
187109
188761
  if (source2.sha256 !== after.sha256) throw new MediaToolError("MEDIA_FILE_CHANGED", "The source changed while frames were being sampled. Retry with a stable source.");
@@ -187112,8 +188764,8 @@ async function sampleMedia(options) {
187112
188764
  for (const file2 of created) {
187113
188765
  try {
187114
188766
  await assertNoMediaSymlinks(file2.path);
187115
- const current2 = await lstat9(file2.path);
187116
- 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 });
188767
+ const current2 = await lstat10(file2.path);
188768
+ 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 });
187117
188769
  } catch {
187118
188770
  }
187119
188771
  }
@@ -187121,8 +188773,8 @@ async function sampleMedia(options) {
187121
188773
  } finally {
187122
188774
  try {
187123
188775
  await assertNoMediaSymlinks(temp);
187124
- const current2 = await lstat9(temp);
187125
- if (current2.ino === tempStat.ino && current2.dev === tempStat.dev) await rm3(temp, { recursive: true, force: true });
188776
+ const current2 = await lstat10(temp);
188777
+ if (current2.ino === tempStat.ino && current2.dev === tempStat.dev) await rm4(temp, { recursive: true, force: true });
187126
188778
  } catch {
187127
188779
  }
187128
188780
  }
@@ -187393,10 +189045,10 @@ async function checkRender(options) {
187393
189045
  }
187394
189046
 
187395
189047
  // packages/cli/src/motion-components.ts
187396
- import { createHash as createHash8 } from "node:crypto";
187397
- import { constants as constants8 } from "node:fs";
187398
- import { lstat as lstat10, mkdir as mkdir9, open as open8, rmdir as rmdir2, unlink as unlink7 } from "node:fs/promises";
187399
- import { dirname as dirname13, extname as extname5, resolve as resolve9 } from "node:path";
189048
+ import { createHash as createHash10 } from "node:crypto";
189049
+ import { constants as constants9 } from "node:fs";
189050
+ import { lstat as lstat11, mkdir as mkdir11, open as open10, rmdir as rmdir2, unlink as unlink8 } from "node:fs/promises";
189051
+ import { dirname as dirname15, extname as extname5, resolve as resolve9 } from "node:path";
187400
189052
 
187401
189053
  // packages/core/src/motion-editorial.ts
187402
189054
  function createEditorialRenderer(config2, g) {
@@ -189230,7 +190882,7 @@ function inputPath(base, value) {
189230
190882
  }
189231
190883
  async function sourceFile(path, role, max) {
189232
190884
  await assertNoMediaSymlinks(path);
189233
- const handle = await open8(path, constants8.O_RDONLY | constants8.O_NOFOLLOW | constants8.O_NONBLOCK);
190885
+ const handle = await open10(path, constants9.O_RDONLY | constants9.O_NOFOLLOW | constants9.O_NONBLOCK);
189234
190886
  try {
189235
190887
  const before = await handle.stat();
189236
190888
  if (!before.isFile() || before.size === 0 || before.size > max) throw fail2(`${role} must be a nonempty regular file of at most ${max} bytes.`);
@@ -189243,9 +190895,9 @@ async function sourceFile(path, role, max) {
189243
190895
  }
189244
190896
  const after = await handle.stat();
189245
190897
  await assertNoMediaSymlinks(path);
189246
- const current2 = await lstat10(path);
190898
+ const current2 = await lstat11(path);
189247
190899
  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.`);
189248
- return { source: { role, path, bytes: content.length, sha256: createHash8("sha256").update(content).digest("hex") }, content };
190900
+ return { source: { role, path, bytes: content.length, sha256: createHash10("sha256").update(content).digest("hex") }, content };
189249
190901
  } finally {
189250
190902
  await handle.close();
189251
190903
  }
@@ -189258,7 +190910,7 @@ function embed(content, path, kind) {
189258
190910
  }
189259
190911
  async function exists2(path) {
189260
190912
  try {
189261
- await lstat10(path);
190913
+ await lstat11(path);
189262
190914
  return true;
189263
190915
  } catch (error) {
189264
190916
  if (error.code === "ENOENT") return false;
@@ -189271,22 +190923,22 @@ async function makeParents(root, path, created) {
189271
190923
  const relative2 = parts.slice(0, index).join("/");
189272
190924
  const target = await checkedPath(root, relative2, false);
189273
190925
  try {
189274
- await mkdir9(target, { mode: 448 });
189275
- const info = await lstat10(target);
190926
+ await mkdir11(target, { mode: 448 });
190927
+ const info = await lstat11(target);
189276
190928
  created.push({ path: relative2, dev: info.dev, ino: info.ino, directory: true });
189277
190929
  } catch (error) {
189278
190930
  if (error.code !== "EEXIST") throw error;
189279
- if (!(await lstat10(await checkedPath(root, relative2, false))).isDirectory()) throw fail2("Output parent must be a directory.");
190931
+ if (!(await lstat11(await checkedPath(root, relative2, false))).isDirectory()) throw fail2("Output parent must be a directory.");
189280
190932
  }
189281
190933
  }
189282
190934
  }
189283
190935
  async function cleanCreated2(root, created) {
189284
190936
  for (const item of [...created].reverse()) {
189285
190937
  try {
189286
- const path = await checkedPath(root, item.path, false), info = await lstat10(path);
190938
+ const path = await checkedPath(root, item.path, false), info = await lstat11(path);
189287
190939
  if (info.dev !== item.dev || info.ino !== item.ino || info.isSymbolicLink()) continue;
189288
190940
  if (item.directory) await rmdir2(path);
189289
- else await unlink7(path);
190941
+ else await unlink8(path);
189290
190942
  } catch {
189291
190943
  }
189292
190944
  }
@@ -189311,14 +190963,14 @@ async function prepareMotionComponent(options) {
189311
190963
  if (typeof value !== "string" || !value.trim()) throw fail2(`Required binding ${role} references missing or non-string token ${key}. No demo default was applied.`);
189312
190964
  return [role, value];
189313
190965
  }));
189314
- const fontPath = inputPath(dirname13(input.source.path), document2.fontFile);
190966
+ const fontPath = inputPath(dirname15(input.source.path), document2.fontFile);
189315
190967
  const font = await sourceFile(fontPath, "font", MOTION_INPUT_LIMITS.fontBytes);
189316
190968
  const sources = [input.source, font.source];
189317
190969
  const items = [];
189318
190970
  for (const [index, item] of document2.items.entries()) {
189319
190971
  let image2;
189320
190972
  if (item.imageFile) {
189321
- const path = inputPath(dirname13(input.source.path), item.imageFile);
190973
+ const path = inputPath(dirname15(input.source.path), item.imageFile);
189322
190974
  const file = await sourceFile(path, `items[${index}].image`, MOTION_INPUT_LIMITS.imageBytes);
189323
190975
  image2 = embed(file.content, path, "image");
189324
190976
  sources.push(file.source);
@@ -189359,7 +191011,7 @@ async function prepareMotionComponent(options) {
189359
191011
  resolvedBindings: Object.fromEntries(Object.entries(document2.bindings).map(([role, key]) => [role, { key, value: bound[role], source: resolved.tokenSources[key] }])),
189360
191012
  sources,
189361
191013
  context: { sourceHashes: resolved.lock.sourceHashes, output: resolved.output, mediaPreferences: resolved.mediaPreferences },
189362
- files: { "config.json": { sha256: createHash8("sha256").update(configJson).digest("hex") }, "index.html": { sha256: createHash8("sha256").update(html).digest("hex") } },
191014
+ files: { "config.json": { sha256: createHash10("sha256").update(configJson).digest("hex") }, "index.html": { sha256: createHash10("sha256").update(html).digest("hex") } },
189363
191015
  warnings: resolved.warnings
189364
191016
  };
189365
191017
  const readme = `# EditorBrain motion component
@@ -189379,13 +191031,13 @@ Preparation is not a rendered video or a quality certification. Inspect text fit
189379
191031
  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/.");
189380
191032
  const created = [];
189381
191033
  try {
189382
- await makeParents(root, dirname13(options.outDirectory), created);
189383
- await mkdir9(await productionOutputPath(root, options.outDirectory), { mode: 448 });
189384
- const info = await lstat10(output2);
191034
+ await makeParents(root, dirname15(options.outDirectory), created);
191035
+ await mkdir11(await productionOutputPath(root, options.outDirectory), { mode: 448 });
191036
+ const info = await lstat11(output2);
189385
191037
  created.push({ path: options.outDirectory, dev: info.dev, ino: info.ino, directory: true });
189386
191038
  for (const [name, content] of Object.entries(files)) {
189387
191039
  const path = `${options.outDirectory}/${name}`;
189388
- const handle = await open8(await productionOutputPath(root, path), constants8.O_WRONLY | constants8.O_CREAT | constants8.O_EXCL | constants8.O_NOFOLLOW, 384);
191040
+ const handle = await open10(await productionOutputPath(root, path), constants9.O_WRONLY | constants9.O_CREAT | constants9.O_EXCL | constants9.O_NOFOLLOW, 384);
189389
191041
  try {
189390
191042
  const stat = await handle.stat();
189391
191043
  created.push({ path, dev: stat.dev, ino: stat.ino, directory: false });
@@ -189416,67 +191068,10 @@ Preparation is not a rendered video or a quality certification. Inspect text fit
189416
191068
  }, { migrateLegacy: false });
189417
191069
  }
189418
191070
 
189419
- // packages/cli/src/authored-motion.ts
189420
- import { lstat as lstat11, mkdir as mkdir10, open as open9, link as link5, unlink as unlink8 } from "node:fs/promises";
189421
- import { dirname as dirname14, join as join12 } from "node:path";
189422
- import { createHash as createHash9, randomUUID as randomUUID5 } from "node:crypto";
189423
- async function downloadAuthoredSource(client, pin, root, out, fetcher = fetch) {
189424
- 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.");
189425
- const target = await checkedPath(root, out, false);
189426
- try {
189427
- await lstat11(target);
189428
- throw new CliError("FILE_EXISTS", "The output already exists.", "Choose a new archive path.");
189429
- } catch (error) {
189430
- if (error.code !== "ENOENT") throw error;
189431
- }
189432
- const metadata = await client.request(`/v1/authored-motion/${pin.id}/source?${new URLSearchParams({ version: pin.version, sha256: pin.sha256 })}`);
189433
- const url2 = new URL(metadata.url);
189434
- const expectedPath = `/v1/authored-motion-download/${pin.id}/${pin.version}/${pin.sha256}`;
189435
- const origin = new URL(client.url).origin;
189436
- const trustedOrigin = url2.origin === origin || origin === "https://editorharness-api.innovandohorizontes.workers.dev" && url2.origin === "https://api.editorbrain.com";
189437
- 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.");
189438
- const response = await fetcher(url2, { redirect: "error", signal: AbortSignal.timeout(18e4) });
189439
- if (!response.ok) throw new CliError("DOWNLOAD_FAILED", `Scene download failed (HTTP ${response.status}).`, "Request a new source link; existing archives were preserved.");
189440
- const reader = response.body?.getReader();
189441
- if (!reader) throw new CliError("INVALID_RESPONSE", "Scene download body is missing.", "Retry the pinned source.");
189442
- const temporary = join12(dirname14(target), `.eb-motion-${randomUUID5()}.tmp`);
189443
- let handle;
189444
- const hash6 = createHash9("sha256");
189445
- let size = 0;
189446
- try {
189447
- await mkdir10(dirname14(target), { recursive: true });
189448
- await checkedPath(root, out, false);
189449
- handle = await open9(temporary, "wx", 384);
189450
- for (; ; ) {
189451
- const { done, value } = await reader.read();
189452
- if (done) break;
189453
- size += value.length;
189454
- if (size > pin.bytes) throw new CliError("HASH_MISMATCH", "Scene archive exceeds the pinned length.", "Discard the unverified download.");
189455
- hash6.update(value);
189456
- await handle.writeFile(value);
189457
- }
189458
- if (size !== pin.bytes || hash6.digest("hex") !== pin.sha256) throw new CliError("HASH_MISMATCH", "Scene archive verification failed.", "Do not extract this download.");
189459
- await handle.sync();
189460
- await handle.close();
189461
- await checkedPath(root, out, false);
189462
- await link5(temporary, target);
189463
- } catch (error) {
189464
- await reader.cancel().catch(() => {
189465
- });
189466
- throw error;
189467
- } finally {
189468
- await handle?.close().catch(() => {
189469
- });
189470
- await unlink8(temporary).catch(() => {
189471
- });
189472
- }
189473
- 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." };
189474
- }
189475
-
189476
191071
  // packages/cli/src/production-verify.ts
189477
- import { createHash as createHash10, randomUUID as randomUUID6 } from "node:crypto";
189478
- import { mkdir as mkdir11, readFile as readFile8 } from "node:fs/promises";
189479
- import { dirname as dirname15, join as join13, resolve as resolve10 } from "node:path";
191072
+ import { createHash as createHash11, randomUUID as randomUUID6 } from "node:crypto";
191073
+ import { mkdir as mkdir12, readFile as readFile8 } from "node:fs/promises";
191074
+ import { dirname as dirname16, join as join14, resolve as resolve10 } from "node:path";
189480
191075
 
189481
191076
  // packages/cli/src/production-media-review.ts
189482
191077
  function productionMediaReview(resolved) {
@@ -189533,7 +191128,7 @@ function productionEditorialReview(resolved) {
189533
191128
  }
189534
191129
 
189535
191130
  // packages/cli/src/production-verify.ts
189536
- var digest2 = (value) => createHash10("sha256").update(value).digest("hex");
191131
+ var digest2 = (value) => createHash11("sha256").update(value).digest("hex");
189537
191132
  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";
189538
191133
  function productionVerificationRequirements(options) {
189539
191134
  const { resolved } = options;
@@ -189567,7 +191162,7 @@ async function sampleFinalArtifact(file, probe2, directory, requested) {
189567
191162
  result2.failures.push({ requestedTimeSeconds: time, code: "MEDIA_SAMPLE_OUT_OF_RANGE" });
189568
191163
  continue;
189569
191164
  }
189570
- const path = join13(directory, `sample-${String(result2.items.length + result2.failures.length + 1).padStart(2, "0")}.png`);
191165
+ const path = join14(directory, `sample-${String(result2.items.length + result2.failures.length + 1).padStart(2, "0")}.png`);
189571
191166
  try {
189572
191167
  const output2 = await runMediaTool("ffmpeg", [
189573
191168
  "-loglevel",
@@ -189653,10 +191248,10 @@ async function verifyProduction(options) {
189653
191248
  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.");
189654
191249
  const relativeDirectory = options.outDirectory ?? `.editorbrain-local/${options.resolved.project.id}/verify-${randomUUID6()}`;
189655
191250
  const directory = await productionOutputPath(root, relativeDirectory);
189656
- await mkdir11(dirname15(directory), { recursive: true, mode: 448 });
191251
+ await mkdir12(dirname16(directory), { recursive: true, mode: 448 });
189657
191252
  await productionOutputPath(root, relativeDirectory);
189658
191253
  try {
189659
- await mkdir11(directory, { mode: 448 });
191254
+ await mkdir12(directory, { mode: 448 });
189660
191255
  } catch (error) {
189661
191256
  if (error.code === "EEXIST") throw new CliError("PRODUCTION_OUTPUT_EXISTS", "Verification output already exists; nothing was overwritten.", "Choose a new directory under .editorbrain-local/.");
189662
191257
  throw error;
@@ -189745,13 +191340,13 @@ async function verifyProduction(options) {
189745
191340
  }
189746
191341
 
189747
191342
  // packages/cli/src/review-artifact.ts
189748
- import { open as open10, mkdir as mkdir12 } from "node:fs/promises";
189749
- import { constants as constants9 } from "node:fs";
189750
- import { dirname as dirname16, extname as extname6, resolve as resolve11 } from "node:path";
189751
- import { createHash as createHash12 } from "node:crypto";
191343
+ import { open as open11, mkdir as mkdir13 } from "node:fs/promises";
191344
+ import { constants as constants10 } from "node:fs";
191345
+ import { dirname as dirname17, extname as extname6, resolve as resolve11 } from "node:path";
191346
+ import { createHash as createHash13 } from "node:crypto";
189752
191347
 
189753
191348
  // packages/cli/src/review-artifact-html.ts
189754
- import { createHash as createHash11 } from "node:crypto";
191349
+ import { createHash as createHash12 } from "node:crypto";
189755
191350
  function reviewApp() {
189756
191351
  const data = JSON.parse(document.getElementById("review-data").textContent);
189757
191352
  const $ = (id2) => document.getElementById(id2);
@@ -190088,7 +191683,7 @@ ${JSON.stringify({ ...feedback(), kind: "editorbrain.review-access-request", dec
190088
191683
  update();
190089
191684
  }
190090
191685
  function renderReviewArtifact(data, wordmark) {
190091
- const script = `(${reviewApp.toString()})();`, hash6 = createHash11("sha256").update(script).digest("base64");
191686
+ const script = `(${reviewApp.toString()})();`, hash6 = createHash12("sha256").update(script).digest("base64");
190092
191687
  const json = JSON.stringify(data).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
190093
191688
  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>
190094
191689
  *{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}
@@ -190183,7 +191778,7 @@ async function embed2(root, input, kind) {
190183
191778
  const path = resolve11(root, input.file), extension = extname6(path).toLowerCase();
190184
191779
  const mime = { ".mp4": "video/mp4", ".webm": "video/webm", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp" };
190185
191780
  if (!mime[extension] || kind === "video" && !mime[extension].startsWith("video/")) invalid4("Use MP4/WebM video or PNG/JPEG/WebP proposal previews.");
190186
- const handle = await open10(path, constants9.O_RDONLY | constants9.O_NOFOLLOW | constants9.O_NONBLOCK);
191781
+ const handle = await open11(path, constants10.O_RDONLY | constants10.O_NOFOLLOW | constants10.O_NONBLOCK);
190187
191782
  try {
190188
191783
  const stat = await handle.stat();
190189
191784
  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.");
@@ -190191,7 +191786,7 @@ async function embed2(root, input, kind) {
190191
191786
  if (bytes.length > 24 * 1024 * 1024) invalid4("Preview grew while reading; retry with a stable file.");
190192
191787
  const after = await handle.stat();
190193
191788
  if (after.size !== stat.size || after.mtimeMs !== stat.mtimeMs) invalid4("Preview changed while reading.");
190194
- const sha2562 = createHash12("sha256").update(bytes).digest("hex");
191789
+ const sha2562 = createHash13("sha256").update(bytes).digest("hex");
190195
191790
  if (input.sha256 && input.sha256 !== sha2562) invalid4("Preview hash does not match this version.");
190196
191791
  return { uri: `data:${mime[extension]};base64,${bytes.toString("base64")}`, sha256: sha2562, mimeType: mime[extension] };
190197
191792
  } finally {
@@ -190206,9 +191801,9 @@ async function createReviewArtifact(root, value, out) {
190206
191801
  const directions = input.directions ? await Promise.all(input.directions.map(async ({ preview, ...d }) => ({ ...d, ...preview ? { preview: await embed2(root, preview, "preview") } : {} }))) : void 0;
190207
191802
  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 } : {} };
190208
191803
  if (JSON.stringify(clean).length > 40 * 1024 * 1024) invalid4("Embedded previews exceed 40 MiB. Use smaller review copies.");
190209
- const artifactId = createHash12("sha256").update(JSON.stringify(clean)).digest("hex");
191804
+ const artifactId = createHash13("sha256").update(JSON.stringify(clean)).digest("hex");
190210
191805
  const html = renderReviewArtifact({ ...clean, artifactId }, onboardingWordmark);
190211
- await mkdir12(dirname16(target), { recursive: true });
191806
+ await mkdir13(dirname17(target), { recursive: true });
190212
191807
  await atomicWrite(root, out, html, { document: false, overwrite: false, mode: 384 });
190213
191808
  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." };
190214
191809
  }
@@ -190411,6 +192006,8 @@ editorbrain library media <video-id> --sha256 media-hash --out file
190411
192006
  editorbrain narrative search [query] [--kind hook|cta|...] [--channel visual|spoken|...] [--limit 10]
190412
192007
  editorbrain narrative get <video-id> [--sha256 document-hash] [--event-offset 0] [--relation-offset 0] [--limit 50]
190413
192008
  editorbrain styles list
192009
+ editorbrain styles source <id> --style-version <v> --out <archive> [--dir folder]
192010
+ editorbrain styles prepare <id> --style-version <v> --file <archive> --out <new-directory> [--dir folder]
190414
192011
  editorbrain styles create <style-id> [--name name] [--dir folder]
190415
192012
  editorbrain styles check <style-id> [--dir folder]
190416
192013
  editorbrain media styles [--category image|motion]
@@ -190535,16 +192132,16 @@ function output(value) {
190535
192132
  process.stdout.write(stableJson(value));
190536
192133
  }
190537
192134
  async function configRoot(create = false) {
190538
- let path = process.env.EDITORBRAIN_CONFIG_DIR ?? process.env.EDITORHARNESS_CONFIG_DIR ?? join14(homedir3(), ".config", "editorbrain");
192135
+ let path = process.env.EDITORBRAIN_CONFIG_DIR ?? process.env.EDITORHARNESS_CONFIG_DIR ?? join15(homedir3(), ".config", "editorbrain");
190539
192136
  if (!create && !process.env.EDITORBRAIN_CONFIG_DIR && !process.env.EDITORHARNESS_CONFIG_DIR) {
190540
192137
  try {
190541
192138
  await lstat12(path);
190542
192139
  } catch (error) {
190543
192140
  if (error.code !== "ENOENT") throw error;
190544
- path = join14(homedir3(), ".config", "editorharness");
192141
+ path = join15(homedir3(), ".config", "editorharness");
190545
192142
  }
190546
192143
  }
190547
- if (create) await mkdir13(path, { recursive: true, mode: 448 });
192144
+ if (create) await mkdir14(path, { recursive: true, mode: 448 });
190548
192145
  return ensureRoot(path);
190549
192146
  }
190550
192147
  async function loadConfig() {
@@ -190561,7 +192158,7 @@ async function loadConfig() {
190561
192158
  async function saveConfig(config2) {
190562
192159
  const root = await configRoot(true);
190563
192160
  await atomicWrite(root, "config.json", stableJson(config2), { document: false, mode: 384 });
190564
- await chmod2(join14(root, "config.json"), 384);
192161
+ await chmod2(join15(root, "config.json"), 384);
190565
192162
  }
190566
192163
  async function config(args, requireKey = true) {
190567
192164
  const stored = await loadConfig();
@@ -190608,7 +192205,7 @@ async function init(args) {
190608
192205
  }
190609
192206
  }
190610
192207
  for (const [path, content] of Object.entries(files)) await atomicWrite(root, path, content, { overwrite: false });
190611
- for (const path of directories) await mkdir13(await checkedPath(root, path, false), { recursive: true });
192208
+ for (const path of directories) await mkdir14(await checkedPath(root, path, false), { recursive: true });
190612
192209
  const guidance2 = await installGuidance();
190613
192210
  try {
190614
192211
  await rememberGuidance(guidance2);
@@ -190661,13 +192258,13 @@ Waiting for authorization. Press Ctrl+C to cancel.
190661
192258
  async function main() {
190662
192259
  const args = parseArgs(process.argv.slice(2));
190663
192260
  const [command, subcommand, argument] = args.positional;
190664
- if (args.flags.all && command !== "pull") throw new Error("--all is supported only by pull.");
192261
+ if (args.flags.all && !["pull", "update"].includes(command)) throw new Error("--all is supported only by pull and update.");
190665
192262
  if (args.flags.all && str(args, "project")) throw new Error("Choose --project or --all, not both.");
190666
192263
  if (command === "version" || args.flags.version) {
190667
192264
  output({ name: "EditorBrain", version: await cliVersion() });
190668
192265
  return;
190669
192266
  }
190670
- if (args.flags["dry-run"] && !["push", "pull"].includes(command) && !(command === "onboarding" && ["apply", "sync"].includes(subcommand))) throw new CliError("INVALID_ARGUMENT", "--dry-run is supported by push, pull and onboarding apply/sync.", "Read editorbrain help.");
192267
+ if (args.flags["dry-run"] && !["push", "pull", "update"].includes(command) && !(command === "onboarding" && ["apply", "sync"].includes(subcommand))) throw new CliError("INVALID_ARGUMENT", "--dry-run is supported by push, pull, update and onboarding apply/sync.", "Read editorbrain help.");
190671
192268
  if (args.flags.offline && command !== "doctor" && !(command === "production" && ["verify", "mix-events"].includes(subcommand))) throw new CliError("INVALID_ARGUMENT", "--offline is supported by doctor, production verify and project-scoped mix-events.", "Read editorbrain help.");
190672
192269
  if (!command || command === "help" || args.flags.help) {
190673
192270
  process.stdout.write(HELP);
@@ -190926,7 +192523,7 @@ async function main() {
190926
192523
  if (hookEnd !== void 0 && (!hookEnd.trim() || !Number.isFinite(Number(hookEnd)) || Number(hookEnd) < 0)) throw new Error("--hook-end must be nonnegative final seconds.");
190927
192524
  const credentials = projectId && !args.flags.offline ? await config(args, false) : void 0;
190928
192525
  const context = projectId ? await prepareProductionContext(root2, projectId, credentials?.apiKey ? new Client(credentials) : void 0) : void 0;
190929
- 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) }));
192526
+ 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) }));
190930
192527
  return;
190931
192528
  }
190932
192529
  if (command === "production" && ["review-sheet", "matte", "matte-plan", "matte-engines", "matte-check"].includes(subcommand)) {
@@ -191097,6 +192694,14 @@ async function main() {
191097
192694
  output({ endpoint: client.url, ...await client.me() });
191098
192695
  return;
191099
192696
  }
192697
+ if (command === "styles" && ["source", "prepare"].includes(subcommand)) {
192698
+ const allowed = /* @__PURE__ */ new Set(["style-version", "out", "dir", ...subcommand === "prepare" ? ["file"] : ["url"]]);
192699
+ const version = str(args, "style-version"), out = str(args, "out"), file = str(args, "file");
192700
+ 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.");
192701
+ const root2 = await ensureRoot(str(args, "dir") ?? process.cwd());
192702
+ output(subcommand === "source" ? await downloadStyle(new Client(await config(args)), argument, version, root2, out) : await prepareStyleSource(root2, argument, version, file, out));
192703
+ return;
192704
+ }
191100
192705
  if (command === "styles" && (subcommand === "create" || subcommand === "check")) {
191101
192706
  const allowed = new Set(subcommand === "create" ? ["dir", "name"] : ["dir"]);
191102
192707
  if (args.positional.length !== 3 || Object.keys(args.flags).some((flag2) => !allowed.has(flag2))) {
@@ -191165,7 +192770,7 @@ async function main() {
191165
192770
  if (!/^[a-zA-Z0-9_-]{1,100}$/.test(result2.id) || typeof result2.apiKey !== "string") throw new Error("Invalid key response");
191166
192771
  const file = `keys/${result2.id}.json`;
191167
192772
  await atomicWrite(root2, file, stableJson({ url: client.url, apiKey: result2.apiKey, id: result2.id, label, role }), { document: false, mode: 384, overwrite: false });
191168
- output({ id: result2.id, label, role, credentialFile: join14(root2, file) });
192773
+ output({ id: result2.id, label, role, credentialFile: join15(root2, file) });
191169
192774
  return;
191170
192775
  }
191171
192776
  if (subcommand === "revoke" && argument) {
@@ -191296,7 +192901,7 @@ async function main() {
191296
192901
  }
191297
192902
  if (subcommand === "upload" && argument) {
191298
192903
  const target = resolve12(str(args, "dir") ?? process.cwd(), argument);
191299
- const handle = await open11(target, constants10.O_RDONLY | constants10.O_NOFOLLOW);
192904
+ const handle = await open12(target, constants11.O_RDONLY | constants11.O_NOFOLLOW);
191300
192905
  let bytes;
191301
192906
  try {
191302
192907
  const info = await handle.stat();
@@ -191323,7 +192928,7 @@ async function main() {
191323
192928
  if (subcommand === "download" && argument && str(args, "out")) {
191324
192929
  if (!/^[a-f0-9]{64}$/.test(argument)) throw new Error("Asset ID must be its SHA-256");
191325
192930
  const destination = resolve12(str(args, "dir") ?? process.cwd(), str(args, "out"));
191326
- const root2 = await ensureRoot(dirname17(destination), true);
192931
+ const root2 = await ensureRoot(dirname18(destination), true);
191327
192932
  await checkedPath(root2, basename4(destination), false);
191328
192933
  const response = await client.media(`/v1/assets/${argument}`);
191329
192934
  const bytes = new Uint8Array(await response.arrayBuffer());
@@ -191384,7 +192989,7 @@ async function main() {
191384
192989
  if (command === "search" && subcommand === "brief") {
191385
192990
  const path = str(args, "file");
191386
192991
  if (!path) throw new Error("Provide --file with the editorial brief JSON after inspecting the actual material.");
191387
- const handle = await open11(resolve12(path), constants10.O_RDONLY | constants10.O_NOFOLLOW);
192992
+ const handle = await open12(resolve12(path), constants11.O_RDONLY | constants11.O_NOFOLLOW);
191388
192993
  let brief;
191389
192994
  try {
191390
192995
  const stat = await handle.stat();
@@ -191406,7 +193011,7 @@ async function main() {
191406
193011
  const scriptPath = str(args, "script"), videoPath = str(args, "video");
191407
193012
  let script, assetId = str(args, "asset");
191408
193013
  const readInput = async (path, max) => {
191409
- const handle = await open11(resolve12(path), constants10.O_RDONLY | constants10.O_NOFOLLOW);
193014
+ const handle = await open12(resolve12(path), constants11.O_RDONLY | constants11.O_NOFOLLOW);
191410
193015
  try {
191411
193016
  const stat = await handle.stat();
191412
193017
  if (!stat.isFile() || stat.size < 1 || stat.size > max) throw new Error(`Input must be a regular file of at most ${max} bytes.`);
@@ -191473,7 +193078,7 @@ async function main() {
191473
193078
  const hash6 = str(args, "sha256");
191474
193079
  if (!hash6 || !/^[a-f0-9]{64}$/.test(hash6)) throw new Error("--sha256 must be a media SHA-256 from library get.");
191475
193080
  const destination = resolve12(str(args, "dir") ?? process.cwd(), str(args, "out"));
191476
- const root2 = await ensureRoot(dirname17(destination), true);
193081
+ const root2 = await ensureRoot(dirname18(destination), true);
191477
193082
  await checkedPath(root2, basename4(destination), false);
191478
193083
  const response = await client.media(`/v1/library/${encodeURIComponent(argument)}/media/${hash6}`);
191479
193084
  const reader = response.body?.getReader();